diff --git a/build/org.eclipse.cdt.managedbuilder.core.tests/suite/org/eclipse/cdt/managedbuilder/tests/suite/AllManagedBuildTests.java b/build/org.eclipse.cdt.managedbuilder.core.tests/suite/org/eclipse/cdt/managedbuilder/tests/suite/AllManagedBuildTests.java index 785514bc365..c200c8b178f 100644 --- a/build/org.eclipse.cdt.managedbuilder.core.tests/suite/org/eclipse/cdt/managedbuilder/tests/suite/AllManagedBuildTests.java +++ b/build/org.eclipse.cdt.managedbuilder.core.tests/suite/org/eclipse/cdt/managedbuilder/tests/suite/AllManagedBuildTests.java @@ -35,7 +35,6 @@ import org.eclipse.cdt.managedbuilder.core.tests.ResourceBuildCoreTests; */ public class AllManagedBuildTests { public static void main(String[] args) { - CCorePlugin.getDefault().getCoreModel().getIndexManager().reset(); junit.textui.TestRunner.run(AllManagedBuildTests.suite()); } public static Test suite() { diff --git a/build/org.eclipse.cdt.managedbuilder.core/src/org/eclipse/cdt/managedbuilder/makegen/internal/DefaultIndexerDependencyCalculator.java b/build/org.eclipse.cdt.managedbuilder.core/src/org/eclipse/cdt/managedbuilder/makegen/internal/DefaultIndexerDependencyCalculator.java index be8bd7cd372..8b45a4ba0bb 100644 --- a/build/org.eclipse.cdt.managedbuilder.core/src/org/eclipse/cdt/managedbuilder/makegen/internal/DefaultIndexerDependencyCalculator.java +++ b/build/org.eclipse.cdt.managedbuilder.core/src/org/eclipse/cdt/managedbuilder/makegen/internal/DefaultIndexerDependencyCalculator.java @@ -10,22 +10,10 @@ *******************************************************************************/ package org.eclipse.cdt.managedbuilder.makegen.internal; -import java.util.ArrayList; -import java.util.List; - -import org.eclipse.cdt.core.CCorePlugin; -import org.eclipse.cdt.core.search.ICSearchConstants; -import org.eclipse.cdt.core.search.ICSearchScope; -import org.eclipse.cdt.core.search.SearchEngine; -import org.eclipse.cdt.internal.core.search.PathCollector; -import org.eclipse.cdt.internal.core.search.PatternSearchJob; -import org.eclipse.cdt.internal.core.search.indexing.IndexManager; -import org.eclipse.cdt.internal.core.search.matching.CSearchPattern; import org.eclipse.cdt.managedbuilder.core.IManagedBuildInfo; import org.eclipse.cdt.managedbuilder.makegen.IManagedDependencyGenerator; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; -import org.eclipse.core.resources.IWorkspaceRoot; /** * @since 2.0 @@ -36,37 +24,39 @@ public class DefaultIndexerDependencyCalculator implements IManagedDependencyGen * @see org.eclipse.cdt.managedbuilder.makegen.IManagedBuilderDependencyCalculator#findDependencies(org.eclipse.core.resources.IResource) */ public IResource[] findDependencies(IResource resource, IProject project) { - PathCollector pathCollector = new PathCollector(); - ICSearchScope scope = SearchEngine.createWorkspaceScope(); - CSearchPattern pattern = CSearchPattern.createPattern(resource.getLocation().toOSString(), ICSearchConstants.INCLUDE, ICSearchConstants.REFERENCES, ICSearchConstants.EXACT_MATCH, true); - IndexManager indexManager = CCorePlugin.getDefault().getCoreModel().getIndexManager(); - indexManager.performConcurrentJob( - new PatternSearchJob( - (CSearchPattern) pattern, - scope, - pathCollector, - indexManager), - ICSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, - null, null); - - // We will get back an array of resource names relative to the workspace - String[] deps = pathCollector.getPaths(); - - // Convert them to something useful - List depList = new ArrayList(); - IResource res = null; - IWorkspaceRoot root = null; - if (project != null) { - root = project.getWorkspace().getRoot(); - } - for (int index = 0; index < deps.length; ++index) { - res = root.findMember(deps[index]); - if (res != null) { - depList.add(res); - } - } - - return (IResource[]) depList.toArray(new IResource[depList.size()]); +// PathCollector pathCollector = new PathCollector(); +// ICSearchScope scope = SearchEngine.createWorkspaceScope(); +// CSearchPattern pattern = CSearchPattern.createPattern(resource.getLocation().toOSString(), ICSearchConstants.INCLUDE, ICSearchConstants.REFERENCES, ICSearchConstants.EXACT_MATCH, true); +// IndexManager indexManager = CCorePlugin.getDefault().getCoreModel().getIndexManager(); +// indexManager.performConcurrentJob( +// new PatternSearchJob( +// (CSearchPattern) pattern, +// scope, +// pathCollector, +// indexManager), +// ICSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, +// null, null); +// +// // We will get back an array of resource names relative to the workspace +// String[] deps = pathCollector.getPaths(); +// +// // Convert them to something useful +// List depList = new ArrayList(); +// IResource res = null; +// IWorkspaceRoot root = null; +// if (project != null) { +// root = project.getWorkspace().getRoot(); +// } +// for (int index = 0; index < deps.length; ++index) { +// res = root.findMember(deps[index]); +// if (res != null) { +// depList.add(res); +// } +// } +// +// return (IResource[]) depList.toArray(new IResource[depList.size()]); + // TODO this needs to be redone to fit on the PDOM + return new IResource[0]; } /* (non-Javadoc) diff --git a/build/org.eclipse.cdt.managedbuilder.ui.tests/src/org/eclipse/cdt/managedbuilder/ui/tests/suite/AllManagedBuildUITests.java b/build/org.eclipse.cdt.managedbuilder.ui.tests/src/org/eclipse/cdt/managedbuilder/ui/tests/suite/AllManagedBuildUITests.java index ddf342e7bcc..65cba819d27 100644 --- a/build/org.eclipse.cdt.managedbuilder.ui.tests/src/org/eclipse/cdt/managedbuilder/ui/tests/suite/AllManagedBuildUITests.java +++ b/build/org.eclipse.cdt.managedbuilder.ui.tests/src/org/eclipse/cdt/managedbuilder/ui/tests/suite/AllManagedBuildUITests.java @@ -10,20 +10,17 @@ *******************************************************************************/ package org.eclipse.cdt.managedbuilder.ui.tests.suite; -import org.eclipse.cdt.core.CCorePlugin; -import org.eclipse.cdt.managedbuilder.ui.tests.TestCProjectPlatformPage; -import org.eclipse.cdt.managedbuilder.ui.tests.TestCustomPageManager; - - import junit.framework.Test; import junit.framework.TestSuite; +import org.eclipse.cdt.managedbuilder.ui.tests.TestCProjectPlatformPage; +import org.eclipse.cdt.managedbuilder.ui.tests.TestCustomPageManager; + /** * */ public class AllManagedBuildUITests { public static void main(String[] args) { - CCorePlugin.getDefault().getCoreModel().getIndexManager().reset(); junit.textui.TestRunner.run(AllManagedBuildUITests.suite()); } public static Test suite() { diff --git a/core/org.eclipse.cdt.core.tests/.classpath b/core/org.eclipse.cdt.core.tests/.classpath index 00fb667f64e..74bbb31abbf 100644 --- a/core/org.eclipse.cdt.core.tests/.classpath +++ b/core/org.eclipse.cdt.core.tests/.classpath @@ -5,8 +5,6 @@ - - diff --git a/core/org.eclipse.cdt.core.tests/META-INF/MANIFEST.MF b/core/org.eclipse.cdt.core.tests/META-INF/MANIFEST.MF index 135e710c55a..883d0e71c9e 100644 --- a/core/org.eclipse.cdt.core.tests/META-INF/MANIFEST.MF +++ b/core/org.eclipse.cdt.core.tests/META-INF/MANIFEST.MF @@ -7,7 +7,6 @@ Bundle-ClassPath: cdtcoretests.jar Bundle-Activator: org.eclipse.cdt.core.testplugin.CTestPlugin Bundle-Localization: plugin Export-Package: org.eclipse.cdt.core.cdescriptor.tests, - org.eclipse.cdt.core.indexer.tests, org.eclipse.cdt.core.internal.errorparsers.tests, org.eclipse.cdt.core.model.failedTests, org.eclipse.cdt.core.model.tests, @@ -16,7 +15,6 @@ Export-Package: org.eclipse.cdt.core.cdescriptor.tests, org.eclipse.cdt.core.parser.tests.ast2, org.eclipse.cdt.core.parser.tests.prefix, org.eclipse.cdt.core.parser.tests.scanner2, - org.eclipse.cdt.core.search.tests, org.eclipse.cdt.core.suite, org.eclipse.cdt.core.testplugin, org.eclipse.cdt.core.testplugin.util, diff --git a/core/org.eclipse.cdt.core.tests/indexer/org/eclipse/cdt/core/indexer/tests/DOMSourceIndexerPerfTests.java b/core/org.eclipse.cdt.core.tests/indexer/org/eclipse/cdt/core/indexer/tests/DOMSourceIndexerPerfTests.java deleted file mode 100644 index 6a5e8cd8f2d..00000000000 --- a/core/org.eclipse.cdt.core.tests/indexer/org/eclipse/cdt/core/indexer/tests/DOMSourceIndexerPerfTests.java +++ /dev/null @@ -1,244 +0,0 @@ -/********************************************************************** - * Copyright (c) 2002, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -/* - * Created on Jun 19, 2003 - */ -package org.eclipse.cdt.core.indexer.tests; - -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.zip.ZipEntry; -import java.util.zip.ZipFile; - -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; - -import org.eclipse.cdt.core.CCorePlugin; -import org.eclipse.cdt.core.ICDescriptor; -import org.eclipse.cdt.core.ICDescriptorOperation; -import org.eclipse.cdt.core.index.IIndexChangeListener; -import org.eclipse.cdt.core.index.IIndexDelta; -import org.eclipse.cdt.core.index.IndexChangeEvent; -import org.eclipse.cdt.core.testplugin.CProjectHelper; -import org.eclipse.cdt.core.testplugin.CTestPlugin; -import org.eclipse.cdt.internal.core.index.domsourceindexer.DOMSourceIndexer; -import org.eclipse.cdt.internal.core.search.indexing.IndexManager; -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.NullProgressMonitor; -import org.eclipse.core.runtime.Path; - -/** - * @author bgheorgh - */ -public class DOMSourceIndexerPerfTests extends TestCase { - IProject testProject; - DOMSourceIndexer sourceIndexer; - IndexManager indexManager; - static long timeC = 0; - static long timeCPP = 0; - static int countC = 0; - static int countCPP = 0; - static final int MAXCOUNT = 10; - - /** - * @param name - */ - public DOMSourceIndexerPerfTests(String name) { - super(name); - } - - public void resetIndexer(final String indexerId){ - if ( testProject != null) { - ICDescriptorOperation op = new ICDescriptorOperation() { - - public void execute(ICDescriptor descriptor, IProgressMonitor monitor) throws CoreException { - descriptor.remove(CCorePlugin.INDEXER_UNIQ_ID); - descriptor.create(CCorePlugin.INDEXER_UNIQ_ID,indexerId); - } - }; - try { - CCorePlugin.getDefault().getCDescriptorManager().runDescriptorOperation(testProject, op, new NullProgressMonitor()); - CCorePlugin.getDefault().getCoreModel().getIndexManager().indexerChangeNotification(testProject); - } catch (CoreException e) {} - } - } - - public static void main(String[] args) {} - - /* - * @see TestCase#setUp() - */ - protected void setUp() throws Exception { - super.setUp(); - testProject = CProjectHelper.createCCProject("IndexerTestProject", "bin").getProject(); //$NON-NLS-1$ - assertNotNull("Unable to create project", testProject); //$NON-NLS-1$ - - resetIndexer(CCorePlugin.DEFAULT_INDEXER_UNIQ_ID); - indexManager = CCorePlugin.getDefault().getCoreModel().getIndexManager(); - sourceIndexer = (DOMSourceIndexer) indexManager.getIndexerForProject(testProject); - } - /* - * @see TestCase#tearDown() - */ - protected void tearDown() { - try { - super.tearDown(); - } catch (Exception e1) {} - //Delete project - if (testProject.exists()) { - try { - System.gc(); - System.runFinalization(); - testProject.delete(true, null); - } catch (CoreException e) { - fail(getMessage(e.getStatus())); - } - } - } - - /** - * Makes error message from multistatus - * - * @param status - * @return - */ - private String getMessage(IStatus status) { - StringBuffer message = new StringBuffer("["); //$NON-NLS-1$ - message.append(status.getMessage()); - if (status.isMultiStatus()) { - IStatus children[] = status.getChildren(); - for (int i = 0; i < children.length; i++) { - message.append(getMessage(children[i])); - } - } - message.append("]"); //$NON-NLS-1$ - return message.toString(); - } - - public static Test suite() { - timeC = 0; - timeCPP = 0; - countC = 0; - countCPP = 0; - TestSuite suite = new TestSuite(DOMSourceIndexerPerfTests.class.getName()); - Test t1 = new DOMSourceIndexerPerfTests("testC"); //$NON-NLS-1$ - Test t2 = new DOMSourceIndexerPerfTests("testCPP"); //$NON-NLS-1$ - - for (int i = 0; i < MAXCOUNT; i++) { - suite.addTest(t1); - suite.addTest(t2); - } - return suite; - - } - /** - * Unpack archive contents to project directory - * - * @param name - name of archive file w/o extension - * @param mask - pattern to check file extensions - * @return - list of files which fit to pattern - */ - - private ArrayList unzip(String name, String mask) { - ArrayList lst = new ArrayList(20); - - byte[] buffer = new byte[512]; - String archname = "resources/zips/" + name + ".zip"; - ZipFile zipFile = null; - - try { - zipFile = new ZipFile(CTestPlugin.getDefault().getFileInPlugin(new Path(archname))); - IPath projPath = testProject.getLocation(); - Enumeration entries = zipFile.entries(); - - while (entries.hasMoreElements()) { - ZipEntry entry = (ZipEntry)entries.nextElement(); - if (!entry.isDirectory()) { - IPath entryPath = projPath.append(entry.getName()); - InputStream in = zipFile.getInputStream(entry); - OutputStream out = new FileOutputStream(entryPath.toFile()); - for (int n = in.read(buffer); n >= 0; n = in.read(buffer)) - out.write(buffer, 0, n); - in.close(); - out.close(); - if (entryPath.lastSegment().endsWith(mask)) { - lst.add(entryPath.lastSegment()); - } - } - } - zipFile.close(); - } catch (IOException e) { - fail("Unzip error with " + archname + " : " + e.getLocalizedMessage()); - } - return lst; - } - - /** - * Adds files from list to index and counts indexing time - * - * @param lst - list of file names to be added - * @return - time (in ms) spent for indexing - */ - private long indexFiles(ArrayList lst) { - // wait for finish of other indexing processes, if any - while(indexManager.awaitingJobsCount()>0) { - try { Thread.sleep(20); - } catch (InterruptedException e) {} - } - System.gc(); - long t0 = System.currentTimeMillis(); - for (int i=0; i0) { - try { Thread.sleep(20); - } catch (InterruptedException e) {} - } - return (System.currentTimeMillis() - t0); - } - - /** - * Test C source indexation - * @throws Exception - */ - public void testC() throws Exception { - long t0 = indexFiles(unzip("perf1", ".c")); - timeC += t0; countC++; - System.out.println("Index performance: " + t0 + " ms on C source[" + countC + "]"); - if (countC == MAXCOUNT) { - System.out.println("Average performance on " + MAXCOUNT + " C passes: " + (timeC/MAXCOUNT)); - } - } - - /** - * Test C++ source indexation - * @throws Exception - */ - public void testCPP() throws Exception { - long t0 = indexFiles(unzip("perf2", ".cpp")); - timeCPP += t0; countCPP++; - System.out.println("Index performance: " + t0 + " ms on C++ source[" + countCPP + "]"); - if (countCPP == MAXCOUNT) { - System.out.println("Average performance on " + MAXCOUNT + " C++ passes: " + (timeCPP/MAXCOUNT)); - } - } -} diff --git a/core/org.eclipse.cdt.core.tests/indexer/org/eclipse/cdt/core/indexer/tests/DOMSourceIndexerTests.java b/core/org.eclipse.cdt.core.tests/indexer/org/eclipse/cdt/core/indexer/tests/DOMSourceIndexerTests.java deleted file mode 100644 index 68e7cc57eb7..00000000000 --- a/core/org.eclipse.cdt.core.tests/indexer/org/eclipse/cdt/core/indexer/tests/DOMSourceIndexerTests.java +++ /dev/null @@ -1,876 +0,0 @@ -/********************************************************************** - * Copyright (c) 2002, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -/* - * Created on Jun 19, 2003 - */ -package org.eclipse.cdt.core.indexer.tests; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileWriter; -import java.io.IOException; -import java.nio.ByteBuffer; -import java.nio.channels.FileChannel; -import java.security.MessageDigest; - -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; - -import org.eclipse.cdt.core.CCorePlugin; -import org.eclipse.cdt.core.ICDescriptor; -import org.eclipse.cdt.core.ICDescriptorOperation; -import org.eclipse.cdt.core.index.IIndexChangeListener; -import org.eclipse.cdt.core.index.IIndexDelta; -import org.eclipse.cdt.core.index.IndexChangeEvent; -import org.eclipse.cdt.core.model.ICProject; -import org.eclipse.cdt.core.testplugin.CProjectHelper; -import org.eclipse.cdt.core.testplugin.CTestPlugin; -import org.eclipse.cdt.core.tests.FailingTest; -import org.eclipse.cdt.internal.core.index.IEntryResult; -import org.eclipse.cdt.internal.core.index.IIndex; -import org.eclipse.cdt.internal.core.index.IQueryResult; -import org.eclipse.cdt.internal.core.index.domsourceindexer.DOMSourceIndexer; -import org.eclipse.cdt.internal.core.index.domsourceindexer.DOMSourceIndexerRunner; -import org.eclipse.cdt.internal.core.search.indexing.IndexManager; -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.NullProgressMonitor; -import org.eclipse.core.runtime.Path; - -/** - * @author bgheorgh - */ -public class DOMSourceIndexerTests extends TestCase implements IIndexChangeListener { - IFile file; - IProject testProject; - NullProgressMonitor monitor; - IndexManager indexManager; - DOMSourceIndexer sourceIndexer; - boolean fileIndexed; - - static final String sourceIndexerID = "org.eclipse.cdt.core.originalsourceindexer"; //$NON-NLS-1$ - public static final int TIMEOUT = 50; - /** - * Constructor for IndexManagerTest. - * @param name - */ - public DOMSourceIndexerTests(String name) { - super(name); - } - - public void resetIndexState() { - fileIndexed = false; - } - - public void resetIndexer(final String indexerId){ - if ( testProject != null) { - ICDescriptorOperation op = new ICDescriptorOperation() { - - public void execute(ICDescriptor descriptor, IProgressMonitor monitor) throws CoreException { - descriptor.remove(CCorePlugin.INDEXER_UNIQ_ID); - descriptor.create(CCorePlugin.INDEXER_UNIQ_ID,indexerId); - } - }; - try { - CCorePlugin.getDefault().getCDescriptorManager().runDescriptorOperation(testProject, op, new NullProgressMonitor()); - CCorePlugin.getDefault().getCoreModel().getIndexManager().indexerChangeNotification(testProject); - } catch (CoreException e) {} - } - } - - public void waitForIndex(int maxSec) throws Exception { - int delay = 0; - while (fileIndexed != true && delay < (maxSec * 1000)) - { - Thread.sleep(TIMEOUT); - delay += TIMEOUT; - } - } - - public static void main(String[] args) { - } - - /* - * @see TestCase#setUp() - */ - protected void setUp() throws Exception { - super.setUp(); - - monitor = new NullProgressMonitor(); - - //Create temp project - testProject = createProject("IndexerTestProject"); //$NON-NLS-1$ - IPath pathLoc = CCorePlugin.getDefault().getStateLocation(); - - File indexFile = new File(pathLoc.append("3915980774.index").toOSString()); //$NON-NLS-1$ - if (indexFile.exists()) - indexFile.delete(); - - if (testProject==null) - fail("Unable to create project"); //$NON-NLS-1$ - - resetIndexer(CCorePlugin.DEFAULT_INDEXER_UNIQ_ID); - //The DOM Source Indexer checks to see if a file has any scanner info - //set prior to indexing it in order to increase efficiency. We need to let it know - //that it is running in test mode in order to allow for this scanner info test to be skipped - DOMSourceIndexerRunner.setSkipScannerInfoTest(true); - - - indexManager = CCorePlugin.getDefault().getCoreModel().getIndexManager(); - //indexManager.reset(); - //Get the indexer used for the test project - sourceIndexer = (DOMSourceIndexer) indexManager.getIndexerForProject(testProject); - sourceIndexer.addIndexChangeListener(this); - } - /* - * @see TestCase#tearDown() - */ - protected void tearDown() { - try { - super.tearDown(); - sourceIndexer.removeIndexChangeListener(this); - } catch (Exception e1) { - } - //Delete project - if (testProject.exists()) { - try { - System.gc(); - System.runFinalization(); - testProject.delete(true, monitor); - } catch (CoreException e) { - fail(getMessage(e.getStatus())); - } - } - } - - private String getMessage(IStatus status) { - StringBuffer message = new StringBuffer("["); //$NON-NLS-1$ - message.append(status.getMessage()); - if (status.isMultiStatus()) { - IStatus children[] = status.getChildren(); - for (int i = 0; i < children.length; i++) { - message.append(getMessage(children[i])); - } - } - message.append("]"); //$NON-NLS-1$ - return message.toString(); - } - - public static Test suite() { - TestSuite suite = new TestSuite(DOMSourceIndexerTests.class.getName()); - - suite.addTest(new DOMSourceIndexerTests("testAddNewFileToIndex")); //$NON-NLS-1$ - suite.addTest(new DOMSourceIndexerTests("testForwardDeclarations")); //$NON-NLS-1$ - suite.addTest(new DOMSourceIndexerTests("testIndexAll")); //$NON-NLS-1$ - suite.addTest(new FailingTest(new DOMSourceIndexerTests("testIndexContents"))); //$NON-NLS-1$ - suite.addTest(new DOMSourceIndexerTests("testMacros")); //$NON-NLS-1$ - suite.addTest(new FailingTest(new DOMSourceIndexerTests("testRefs"))); //$NON-NLS-1$ - suite.addTest(new DOMSourceIndexerTests("testExactDeclarations")); //$NON-NLS-1$ - suite.addTest(new FailingTest(new DOMSourceIndexerTests("testRemoveFileFromIndex"))); //$NON-NLS-1$ - suite.addTest(new DOMSourceIndexerTests("testRemoveProjectFromIndex")); //$NON-NLS-1$ - suite.addTest(new DOMSourceIndexerTests("testIndexShutdown")); //$NON-NLS-1$ - - - return suite; - - } - /* - * Utils - */ - private IProject createProject(String projectName) throws CoreException { - ICProject cPrj = CProjectHelper.createCCProject(projectName, "bin"); //$NON-NLS-1$ - return cPrj.getProject(); - } - - private IFile importFile(String fileName, String resourceLocation)throws Exception { - resetIndexState(); - //Obtain file handle - file = testProject.getProject().getFile(fileName); - //Create file input stream - monitor = new NullProgressMonitor(); - if (!file.exists()) { - file.create(new FileInputStream( - CTestPlugin.getDefault().getFileInPlugin(new Path(resourceLocation))), - false, monitor); - } - waitForIndex(20); // only wait 20 seconds max. - return file; - } - - /* - * Start of tests - */ - public void testIndexAll() throws Exception { - - //Add a file to the project - - importFile("mail.cpp","resources/indexer/mail.cpp"); //$NON-NLS-1$ //$NON-NLS-2$ - - IIndex ind = sourceIndexer.getIndex(testProject.getFullPath(),true,true); - assertTrue("Index exists for project",ind != null); //$NON-NLS-1$ - - IQueryResult[] qresults = ind.getPrefix(IIndex.TYPE, IIndex.ANY, IIndex.DEFINITION); - IEntryResult[] eresults = ind.getEntries(IIndex.TYPE, IIndex.ANY, IIndex.DEFINITION); - IEntryResult[] eresultsDecls = ind.getEntries(IIndex.TYPE, IIndex.ANY, IIndex.DECLARATION); - - assertTrue("Query Results exist", qresults != null); //$NON-NLS-1$ - assertTrue("Entry Results exist", eresults != null); //$NON-NLS-1$ - - String [] queryResultModel = {"IndexedFile(1: /IndexerTestProject/mail.cpp)"}; //$NON-NLS-1$ - String [] entryResultModel ={"EntryResult: word=typeDefn/C/Mail, refs={ 1 }, offsets={ [ 294] }", //$NON-NLS-1$ - "EntryResult: word=typeDefn/C/Unknown, refs={ 1 }, offsets={ [ 2738] }", //$NON-NLS-1$ - "EntryResult: word=typeDefn/C/container, refs={ 1 }, offsets={ [ 21084] }", //$NON-NLS-1$ - "EntryResult: word=typeDefn/C/first_class, refs={ 1 }, offsets={ [ 2506] }", //$NON-NLS-1$ - "EntryResult: word=typeDefn/C/postcard, refs={ 1 }, offsets={ [ 2298] }", //$NON-NLS-1$ - }; - - String [] entryResultDeclsModel = { - "EntryResult: word=typeDecl/D/Mail, refs={ 1 }, offsets={ [ 294] }", //$NON-NLS-1$ - "EntryResult: word=typeDecl/D/first_class, refs={ 1 }, offsets={ [ 2506] }", //$NON-NLS-1$ - "EntryResult: word=typeDecl/D/postcard, refs={ 1 }, offsets={ [ 2298] }", //$NON-NLS-1$ - }; - String[] entryResultNameModel = {"Mail","Unknown","container","first_class","postcard"}; - int[] entryResultMetaModel = {IIndex.TYPE}; - int[] entryResultTypeModel = {IIndex.TYPE_CLASS,IIndex.TYPE_CLASS,IIndex.TYPE_CLASS,IIndex.TYPE_CLASS,IIndex.TYPE_CLASS}; - int[] entryResultRefModel = {IIndex.DEFINITION}; - - if (qresults.length != queryResultModel.length) - fail("Query Result length different from model"); //$NON-NLS-1$ - - if (eresults.length != entryResultModel.length) - fail("Entry Result length different from model"); //$NON-NLS-1$ - - if (eresultsDecls.length != entryResultDeclsModel.length) - fail("Entry Result length different from model"); //$NON-NLS-1$ - - for (int i=0; ify/*ref2*/(); \n" ); //$NON-NLS-1$ - writer.write(" fw(); \n" ); //$NON-NLS-1$ - writer.write(" K k; \n" ); //$NON-NLS-1$ - writer.write(" k.fy/*ref3*/(); \n" ); //$NON-NLS-1$ - writer.write(" k.~K/*ref5*/(); \n" ); //$NON-NLS-1$ - writer.write("} \n" ); //$NON-NLS-1$ - String code2 = writer.toString(); - IFile k = importFile( "MethodReference.cpp", code2 ); //$NON-NLS-1$ - ICElement[] list = new ICElement[1]; - list[0]=cproject.findElement(new Path("MethodReference.cpp")); //$NON-NLS-1$ - //vp1 ::, ->, . , inline references - ICSearchPattern pattern=SearchEngine.createSearchPattern("f*", METHOD, REFERENCES, true); //$NON-NLS-1$ - Set matches = search( pattern,list); - //assertEquals( 3, matches.size()); - assertMatch( matches, k, code2.lastIndexOf( "fx/*ref1*/" ) ); //$NON-NLS-1$ - assertMatch( matches, k, code2.indexOf( "fy/*ref2*/" ) ); //$NON-NLS-1$ - assertMatch( matches, k, code2.lastIndexOf( "fy/*ref3*/" ) ); //$NON-NLS-1$ - //vp2 constructor - pattern=SearchEngine.createSearchPattern("*K", METHOD, REFERENCES, true); //$NON-NLS-1$ - matches = search( pattern); - assertEquals( 2, matches.size()); - assertMatch( matches, k, code2.indexOf( "K/*ref4*/" ) ); //$NON-NLS-1$ - assertMatch( matches, k, code2.indexOf( "~K/*ref5*/" ) ); //$NON-NLS-1$ - } - // test SE50, SE100c - public void testMethodReferenceOperator() throws Exception { - Writer writer = new StringWriter(); - writer.write("class K{ \n" ); //$NON-NLS-1$ - writer.write("public: \n" ); //$NON-NLS-1$ - writer.write(" K(); \n" ); //$NON-NLS-1$ - writer.write(" K& operator == (const K &rhs){} \n" ); //$NON-NLS-1$ - writer.write("}; \n" ); //$NON-NLS-1$ - writer.write("void foo(){ \n" ); //$NON-NLS-1$ - writer.write(" K k; \n" ); //$NON-NLS-1$ - writer.write(" K m=k; \n" ); //$NON-NLS-1$ - writer.write(" if (m.operator==/*ref1*/(k)){} \n" ); //$NON-NLS-1$ - writer.write("} \n" ); //$NON-NLS-1$ - String source = writer.toString(); - IFile cpp = importFile( "MethodReferenceOperator.cpp", source ); //$NON-NLS-1$ - //vp1 explicit operator== call - ICSearchPattern pattern=SearchEngine.createSearchPattern("operator ==", METHOD, REFERENCES, true); //$NON-NLS-1$ - Set matches = search( pattern ); - assertEquals( 1, matches.size()); - assertMatch( matches, cpp, source.indexOf( "operator==/*ref1*/" ) ); //$NON-NLS-1$ - } - public void testMethodReferenceImplicitOperator() throws Exception { - Writer writer = new StringWriter(); - writer.write("class K{ \n" ); //$NON-NLS-1$ - writer.write("public: \n" ); //$NON-NLS-1$ - writer.write(" K(); \n" ); //$NON-NLS-1$ - writer.write(" K& operator == (const K &rhs){} \n" ); //$NON-NLS-1$ - writer.write("}; \n" ); //$NON-NLS-1$ - writer.write("void foo(){ \n" ); //$NON-NLS-1$ - writer.write(" K k; \n" ); //$NON-NLS-1$ - writer.write(" K m=k; \n" ); //$NON-NLS-1$ - writer.write(" if (m==/*ref*/k){} \n" ); //$NON-NLS-1$ - writer.write("} \n" ); //$NON-NLS-1$ - String source = writer.toString(); - IFile cpp = importFile( "MethodReferenceImplicitOperator.cpp", source ); //$NON-NLS-1$ - //vp1 implicit operator== call (A==B) - ICSearchPattern pattern=SearchEngine.createSearchPattern("operator ==", METHOD, REFERENCES, true); //$NON-NLS-1$ - Set matches = search( pattern ); - assertEquals( 1, matches.size()); - assertMatch( matches, cpp, source.indexOf( "==/*ref*/" ) ); //$NON-NLS-1$ - } - - //76169 - public void testMethodReferenceInitializer() throws Exception { - Writer writer = new StringWriter(); - writer.write("class Mammal { \n" ); //$NON-NLS-1$ - writer.write(" public: \n" ); //$NON-NLS-1$ - writer.write(" Mammal(int t): num(t){} \n" ); //$NON-NLS-1$ - writer.write(" private: \n" ); //$NON-NLS-1$ - writer.write(" int num; \n" ); //$NON-NLS-1$ - writer.write("}; \n" ); //$NON-NLS-1$ - writer.write("class Bear : Mammal{ \n" ); //$NON-NLS-1$ - writer.write("public: \n" ); //$NON-NLS-1$ - writer.write(" Bear(int t): Mammal(t) {} \n" ); //$NON-NLS-1$ - writer.write("}; \n" ); //$NON-NLS-1$ - String code = writer.toString(); - IFile g = importFile( "MethodReferenceInitializer.cpp", code ); //$NON-NLS-1$ - - ICSearchPattern pattern = SearchEngine.createSearchPattern( "Mammal", METHOD, REFERENCES, true ); //$NON-NLS-1$ - Set matches = search( pattern ); - - assertEquals( 1, matches.size() ); - assertMatch( matches, g, code.indexOf( "Mammal(t)" ) ); //$NON-NLS-1$ - - } - public void testMethodReferenceInline() throws Exception { - - Writer writer = new StringWriter(); - writer.write("class A{ \n" ); //$NON-NLS-1$ - writer.write(" friend class M; \n" ); //$NON-NLS-1$ - writer.write(" void aa(); \n" ); //$NON-NLS-1$ - writer.write("}; \n" ); //$NON-NLS-1$ - writer.write("class M { \n" ); //$NON-NLS-1$ - writer.write("public: \n" ); //$NON-NLS-1$ - writer.write(" M(); \n" ); //$NON-NLS-1$ - writer.write(" void zz(){a->aa();}//ref \n" ); //$NON-NLS-1$ - writer.write(" A *a; \n" ); //$NON-NLS-1$ - writer.write("}; \n" ); //$NON-NLS-1$ - String code = writer.toString(); - IFile gh = importFile( "MethodReferenceInline.cpp", code ); //$NON-NLS-1$ - //ref inside inline defn - ICSearchPattern pattern=SearchEngine.createSearchPattern("aa", METHOD, REFERENCES, true); //$NON-NLS-1$ - Set matches = search(pattern); - assertEquals( 1, matches.size()); - assertMatch( matches, gh, code.indexOf( "aa();}//ref" ) ); //$NON-NLS-1$ - } - public void testMethodReferenceWithCctor() throws Exception { - Writer writer = new StringWriter(); - writer.write("class C{ \n" ); //$NON-NLS-1$ - writer.write(" void cc(){} \n" ); //$NON-NLS-1$ - writer.write("}; \n" ); //$NON-NLS-1$ - writer.write("void g(){ \n" ); //$NON-NLS-1$ - writer.write(" C().cc/*ref*/();\n" ); //$NON-NLS-1$ - writer.write("} \n" ); //$NON-NLS-1$ - String source = writer.toString(); - IFile cpp = importFile( "MethodReferenceWithCctor.cpp", source ); //$NON-NLS-1$ - //vp1 constructor by itself - ICSearchPattern pattern=SearchEngine.createSearchPattern("cc", METHOD, REFERENCES, true); //$NON-NLS-1$ - Set matches = search( pattern ); - assertEquals( 1, matches.size()); - assertMatch( matches, cpp, source.indexOf( "cc/*ref*/" ) ); //$NON-NLS-1$ - - } - public void testConstructorReferenceArg() throws Exception { - Writer writer = new StringWriter(); - writer.write("class C{ \n" ); //$NON-NLS-1$ - writer.write(" C(); \n" ); //$NON-NLS-1$ - writer.write("}; \n" ); //$NON-NLS-1$ - writer.write("void f(C c){} \n" ); //$NON-NLS-1$ - writer.write("void g(){ \n" ); //$NON-NLS-1$ - writer.write(" f(C/*ref*/());; \n" ); //$NON-NLS-1$ - writer.write("} \n" ); //$NON-NLS-1$ - String source = writer.toString(); - IFile cpp = importFile( "ConstructorReferenceArg.cpp", source ); //$NON-NLS-1$ - //vp1 constructor, destructor - ICSearchPattern pattern=SearchEngine.createSearchPattern("C", METHOD, REFERENCES, true); //$NON-NLS-1$ - Set matches = search( pattern ); - assertEquals( 1, matches.size()); - assertMatch( matches, cpp, source.indexOf( "C/*ref*/" ) ); //$NON-NLS-1$ - - } - public void testConstructorReferenceAlone() throws Exception { - Writer writer = new StringWriter(); - writer.write("class C{ \n" ); //$NON-NLS-1$ - writer.write(" C(){} \n" ); //$NON-NLS-1$ - writer.write("}; \n" ); //$NON-NLS-1$ - writer.write("void g(){ \n" ); //$NON-NLS-1$ - writer.write(" C/*ref*/(); \n" ); //$NON-NLS-1$ - writer.write("} \n" ); //$NON-NLS-1$ - String source = writer.toString(); - IFile cpp = importFile( "ConstructorReferenceAlone.cpp", source ); //$NON-NLS-1$ - //vp1 constructor by itself - ICSearchPattern pattern=SearchEngine.createSearchPattern("C", METHOD, REFERENCES, true); //$NON-NLS-1$ - Set matches = search( pattern ); - assertEquals( 1, matches.size()); - assertMatch( matches, cpp, source.indexOf( "C/*ref*/" ) ); //$NON-NLS-1$ - - } - public void testDestructorReference() throws Exception { - - Writer writer = new StringWriter(); - writer.write("class A{ \n" ); //$NON-NLS-1$ - writer.write(" friend class M; \n" ); //$NON-NLS-1$ - writer.write(" ~A(); \n" ); //$NON-NLS-1$ - writer.write("}; \n" ); //$NON-NLS-1$ - writer.write("class M { \n" ); //$NON-NLS-1$ - writer.write("public: \n" ); //$NON-NLS-1$ - writer.write(" M(); \n" ); //$NON-NLS-1$ - writer.write(" ~M(); \n" ); //$NON-NLS-1$ - writer.write(" A *a; \n" ); //$NON-NLS-1$ - writer.write("}; \n" ); //$NON-NLS-1$ - writer.write("M::~M(){a->~A();}//ref \n" ); //$NON-NLS-1$ - writer.write("void f() { \n" ); //$NON-NLS-1$ - writer.write(" M m; \n" ); //$NON-NLS-1$ - writer.write(" m.~M();//ref \n" ); //$NON-NLS-1$ - writer.write("} \n" ); //$NON-NLS-1$ - String source = writer.toString(); - IFile cpp = importFile( "DestructorReference.cpp", source ); //$NON-NLS-1$ - //vp1 arrow ref - ICSearchPattern pattern=SearchEngine.createSearchPattern("~A", METHOD, REFERENCES, true); //$NON-NLS-1$ - Set matches = search(pattern); - assertEquals( 1, matches.size()); - assertMatch( matches, cpp, source.indexOf( "~A();}//ref" ) ); //$NON-NLS-1$ - //vp2 dot ref - pattern=SearchEngine.createSearchPattern("~M", METHOD, REFERENCES, true); //$NON-NLS-1$ - matches = search(pattern); - assertEquals( 1, matches.size()); - assertMatch( matches, cpp, source.indexOf( "~M();//ref" ) ); //$NON-NLS-1$ - } - public void testFunctionDeclaration() throws Exception { - Writer writer = new StringWriter(); - writer.write("namespace N{ \n" ); //$NON-NLS-1$ - writer.write("int f1/*decl*/(){return 0;} \n" ); //$NON-NLS-1$ - writer.write("} \n" ); //$NON-NLS-1$ - writer.write("static int f2/*decl*/(); \n" ); //$NON-NLS-1$ - writer.write("extern int f3/*decl*/(); \n" ); //$NON-NLS-1$ - writer.write("inline void f4/*decl*/(int *a, int *b){int t=*b; *b=*a; *a=t;} \n" ); //$NON-NLS-1$ - String header = writer.toString(); - IFile h = importFile( "FunctionDeclaration.h", header ); //$NON-NLS-1$ - - writer = new StringWriter(); - writer.write("#include \"FunctionDeclaration.h\"\n" ); //$NON-NLS-1$ - writer.write("void f5()/*decl*/{ \n" ); //$NON-NLS-1$ - writer.write(" int i = N::f1(); \n" ); //$NON-NLS-1$ - writer.write(" int j = f3(); \n" ); //$NON-NLS-1$ - writer.write(" f4(&i, &j); \n" ); //$NON-NLS-1$ - writer.write("} \n" ); //$NON-NLS-1$ - String source = writer.toString(); - IFile cpp = importFile( "FunctionDeclaration.cpp", source ); //$NON-NLS-1$ - ICSearchPattern pattern=SearchEngine.createSearchPattern("f*", FUNCTION, DECLARATIONS, true); //$NON-NLS-1$ - ICElement[] list = new ICElement[1]; - list[0]=cproject.getCProject(); - Set matches = search( pattern,list ); - //assertMatch( matches, h, header.indexOf( "f1" ) ); //$NON-NLS-1$ - assertMatch( matches, h, header.indexOf( "f2" ) ); //$NON-NLS-1$ - assertMatch( matches, h, header.indexOf( "f3" ) ); //$NON-NLS-1$ - //assertMatch( matches, h, header.indexOf( "f4" ) ); //$NON-NLS-1$ - //assertMatch( matches, cpp, source.indexOf( "f5" ) ); //$NON-NLS-1$ - assertEquals( 2, matches.size()); - - } - public void testFunctionDefinition() throws Exception { - Writer writer = new StringWriter(); - writer.write("namespace N{ \n" ); //$NON-NLS-1$ - writer.write("int f1/*def*/(){return 0;} \n" ); //$NON-NLS-1$ - writer.write("} \n" ); //$NON-NLS-1$ - writer.write("static int f2(); \n" ); //$NON-NLS-1$ - writer.write("extern int f3/*decl*/(); \n" ); //$NON-NLS-1$ - writer.write("inline void f4/*def*/(int *a, int *b){int t=*b; *b=*a; *a=t;} \n" ); //$NON-NLS-1$ - String header = writer.toString(); - IFile h = importFile( "FunctionDefinition.h", header ); //$NON-NLS-1$ - - writer = new StringWriter(); - writer.write("#include \"FunctionDefinition.h\"\n" ); //$NON-NLS-1$ - writer.write("int f2/*def*/(){return 2;} \n" ); //$NON-NLS-1$ - writer.write("void f5/*def*/(){ \n" ); //$NON-NLS-1$ - writer.write(" int i = N::f1(); \n" ); //$NON-NLS-1$ - writer.write(" int j = f3(); \n" ); //$NON-NLS-1$ - writer.write(" f4(&i, &j); \n" ); //$NON-NLS-1$ - writer.write("} \n" ); //$NON-NLS-1$ - String source = writer.toString(); - IFile cpp = importFile( "FunctionDefinition.cpp", source ); //$NON-NLS-1$ - ICSearchPattern pattern=SearchEngine.createSearchPattern("f*", FUNCTION, DEFINITIONS, true); //$NON-NLS-1$ - ICElement[] list = new ICElement[1]; - list[0]=cproject.getCProject(); - Set matches = search( pattern,list ); - Iterator i = matches.iterator(); - while (i.hasNext()){ - BasicSearchMatch match =(BasicSearchMatch) i.next(); - int x=0; - } - - assertMatch( matches, h, header.indexOf( "f1" ) ); //$NON-NLS-1$ - assertMatch( matches, cpp, source.indexOf( "f2" ) ); //$NON-NLS-1$ - assertMatch( matches, h, header.indexOf( "f4" ) ); //$NON-NLS-1$ - assertMatch( matches, cpp, source.indexOf( "f5" ) ); //$NON-NLS-1$ - assertEquals( 4, matches.size()); - - } - //SE50 working set - public void testFunctionReference() throws Exception { - Writer writer = new StringWriter(); - writer.write("namespace N{ \n" ); //$NON-NLS-1$ - writer.write("int fz(){return 0;} \n" ); //$NON-NLS-1$ - writer.write("} \n" ); //$NON-NLS-1$ - String header = writer.toString(); - importFile( "FunctionReference.h", header ); //$NON-NLS-1$ - - writer = new StringWriter(); - writer.write("#include \"FunctionReference.h\" \n" ); //$NON-NLS-1$ - writer.write("int fw(){return 0;} \n" ); //$NON-NLS-1$ - writer.write("void fg(int i){} \n" ); //$NON-NLS-1$ - writer.write("void f(){ \n" ); //$NON-NLS-1$ - writer.write(" int i = N::fz/*ref1*/(); \n" ); //$NON-NLS-1$ - writer.write(" fg/*ref2*/(fw/*ref3*/()); \n" ); //$NON-NLS-1$ - writer.write("} \n" ); //$NON-NLS-1$ - writer.write("using N::fz/*ref4*/; \n" ); //$NON-NLS-1$ - String source = writer.toString(); - IFile k = importFile( "FunctionReference.cpp", source ); //$NON-NLS-1$ - ICElement[] list = {cproject.findElement(new Path("FunctionReference.cpp"))}; //$NON-NLS-1$ - ICSearchPattern pattern=SearchEngine.createSearchPattern("f*", FUNCTION, REFERENCES, true); //$NON-NLS-1$ - - Set matches = search( pattern,list); - assertMatch( matches, k, source.indexOf( "fz/*ref1*/" ) ); //$NON-NLS-1$ - assertMatch( matches, k, source.lastIndexOf( "fg/*ref2*/" ) ); //$NON-NLS-1$ - assertMatch( matches, k, source.indexOf( "fw/*ref3*/" ) ); //$NON-NLS-1$ - assertMatch( matches, k, source.lastIndexOf( "fz/*ref4*/" ) ); //$NON-NLS-1$ - assertEquals( 4, matches.size()); - - } - // test SE53 // SE60c - public void testFieldDeclaration() throws Exception { - Writer writer = new StringWriter(); - writer.write(" namespace N2 { \n" ); //$NON-NLS-1$ - writer.write(" struct linkedlist1{ \n" ); //$NON-NLS-1$ - writer.write(" long field1_t; \n" ); //$NON-NLS-1$ - writer.write(" struct linkedlist1 *field2; \n" ); //$NON-NLS-1$ - writer.write(" static int sfield; \n" ); //$NON-NLS-1$ - writer.write(" }; \n" ); //$NON-NLS-1$ - writer.write(" class linkedlist2{ \n" ); //$NON-NLS-1$ - writer.write(" unsigned char field3; \n" ); //$NON-NLS-1$ - writer.write(" class linkedlist2 *field4; \n" ); //$NON-NLS-1$ - writer.write(" }; \n" ); //$NON-NLS-1$ - writer.write(" } \n" ); //$NON-NLS-1$ - writer.write(" class C { \n" ); //$NON-NLS-1$ - writer.write(" struct {} field5; \n" ); //$NON-NLS-1$ - writer.write(" class C1 { \n" ); //$NON-NLS-1$ - writer.write(" N2::linkedlist2 *field6; \n" ); //$NON-NLS-1$ - writer.write(" }; \n" ); //$NON-NLS-1$ - writer.write(" }; \n" ); //$NON-NLS-1$ - String code = writer.toString(); - IFile gh = importFile( "FieldDeclaration.h", code ); //$NON-NLS-1$ - - ICSearchPattern pattern = SearchEngine.createSearchPattern("*", FIELD, DEFINITIONS, true); //$NON-NLS-1$ - ICElement[] list = new ICElement[1]; - list[0]=cproject.getCProject(); - Set matches = search( pattern,list); - assertMatch( matches, gh, code.indexOf( "field1" ) ); //$NON-NLS-1$ - assertMatch( matches, gh, code.indexOf( "field2" ) ); //$NON-NLS-1$ - assertMatch( matches, gh, code.indexOf( "field3" ) ); //$NON-NLS-1$ - assertMatch( matches, gh, code.indexOf( "field4" ) ); //$NON-NLS-1$ - assertMatch( matches, gh, code.indexOf( "field5" ) ); //$NON-NLS-1$ - assertMatch( matches, gh, code.indexOf( "field6" ) ); //$NON-NLS-1$ - assertEquals( 6, matches.size()); - - } - public void testBitFieldDeclaration() throws Exception { - Writer writer = new StringWriter(); - writer.write("struct Date { \n" ); //$NON-NLS-1$ - writer.write(" unsigned nWeekDay : 3; // 0..7 (3 bits) \n" ); //$NON-NLS-1$ - writer.write(" unsigned nMonthDay : 6; // 0..31 (6 bits) \n" ); //$NON-NLS-1$ - writer.write(" unsigned : 0; // Force alignment to next boundary.\n" ); //$NON-NLS-1$ - writer.write(" unsigned nMonth : 5; // 0..12 (5 bits) \n" ); //$NON-NLS-1$ - writer.write(" unsigned nYear : 8; // 0..100 (8 bits) \n" ); //$NON-NLS-1$ - writer.write("}; \n" ); //$NON-NLS-1$ - String code = writer.toString(); - IFile cpp = importFile( "BitFieldDeclaration.cpp", code ); //$NON-NLS-1$ - - ICSearchPattern pattern = SearchEngine.createSearchPattern("n*", FIELD, DEFINITIONS, true); //$NON-NLS-1$ - ICElement[] list = new ICElement[1]; - list[0]=cproject.getCProject(); - Set matches = search( pattern,list); - //currently anon bitfields are not found (80166) - assertEquals( 4, matches.size()); - assertMatch( matches, cpp, code.indexOf( "nWeekDay" ) ); //$NON-NLS-1$ - assertMatch( matches, cpp, code.indexOf( "nMonthDay" ) ); //$NON-NLS-1$ - assertMatch( matches, cpp, code.indexOf( "nMonth" ) ); //$NON-NLS-1$ - assertMatch( matches, cpp, code.indexOf( "nYear" ) ); //$NON-NLS-1$ - } - - // test SE63b var field defn - public void testFieldDefinition() throws Exception { - - Writer writer = new StringWriter(); - writer.write(" enum ZooLocs {ZOOANIMAL, BEAR, PANDA};\n" ); //$NON-NLS-1$ - writer.write(" namespace zoo { \n" ); //$NON-NLS-1$ - writer.write(" class ZooAnimal{ \n" ); //$NON-NLS-1$ - writer.write(" public: \n" ); //$NON-NLS-1$ - writer.write(" ZooAnimal(char *s = \"ZooAnimal\"); \n" ); //$NON-NLS-1$ - writer.write(" protected: \n" ); //$NON-NLS-1$ - writer.write(" char *name/*def*/; \n" ); //$NON-NLS-1$ - writer.write(" ZooAnimal *next/*def*/; \n" ); //$NON-NLS-1$ - writer.write(" }; \n" ); //$NON-NLS-1$ - writer.write(" class Mammal{ \n" ); //$NON-NLS-1$ - writer.write(" protected: \n" ); //$NON-NLS-1$ - writer.write(" bool isCarnivore/*def*/; \n" ); //$NON-NLS-1$ - writer.write(" }; \n" ); //$NON-NLS-1$ - writer.write(" class Bear : public ZooAnimal, Mammal{\n" ); //$NON-NLS-1$ - writer.write(" public: static int number; \n" ); //$NON-NLS-1$ - writer.write(" protected: \n" ); //$NON-NLS-1$ - writer.write(" ZooLocs zooArea/*def*/; \n" ); //$NON-NLS-1$ - writer.write(" class Beez{ \n" ); //$NON-NLS-1$ - writer.write(" const double dutch/*def*/; \n" ); //$NON-NLS-1$ - writer.write(" }; \n" ); //$NON-NLS-1$ - writer.write(" }; \n" ); //$NON-NLS-1$ - writer.write(" } \n" ); //$NON-NLS-1$ - writer.write(" int zoo::Bear::number/*def*/=3; \n" ); //$NON-NLS-1$ - String code = writer.toString(); - IFile z = importFile( "FieldDefinition.cpp", code ); //$NON-NLS-1$ - - ICSearchPattern pattern = SearchEngine.createSearchPattern("*", FIELD, DEFINITIONS, true); //$NON-NLS-1$ - ICElement[] list = new ICElement[1]; - list[0]=cproject.getCProject(); - Set matches = search( pattern,list); - assertEquals( 6, matches.size()); - assertMatch( matches, z, code.indexOf( "name/*def*/" ) ); //$NON-NLS-1$ - assertMatch( matches, z, code.indexOf( "next/*def*/" ) ); //$NON-NLS-1$ - assertMatch( matches, z, code.indexOf( "isCarnivore/*def*/" ) ); //$NON-NLS-1$ - assertMatch( matches, z, code.indexOf( "zooArea/*def*/" ) ); //$NON-NLS-1$ - assertMatch( matches, z, code.indexOf( "dutch/*def*/" ) ); //$NON-NLS-1$ - assertMatch( matches, z, code.indexOf( "number/*def*/" ) ); //$NON-NLS-1$ -} - public void testFieldReference() throws Exception { - Writer writer = new StringWriter(); - writer.write("class Mammal {//decl \n" ); //$NON-NLS-1$ - writer.write(" public: \n" ); //$NON-NLS-1$ - writer.write(" Mammal(bool b): isCarnivore/*ref*/(b){} \n" ); //$NON-NLS-1$ - writer.write(" private: \n" ); //$NON-NLS-1$ - writer.write(" bool isCarnivore; \n" ); //$NON-NLS-1$ - writer.write("}; \n" ); //$NON-NLS-1$ - writer.write("class Bear : Mammal{ \n" ); //$NON-NLS-1$ - writer.write("public: \n" ); //$NON-NLS-1$ - writer.write(" Bear(int s,int t): Mammal(true) { \n" ); //$NON-NLS-1$ - writer.write(" biotics.matureYears=s;//ref \n" ); //$NON-NLS-1$ - writer.write(" } \n" ); //$NON-NLS-1$ - writer.write(" struct { \n" ); //$NON-NLS-1$ - writer.write(" int matureYears; \n" ); //$NON-NLS-1$ - writer.write(" } biotics; \n" ); //$NON-NLS-1$ - writer.write("}; \n" ); //$NON-NLS-1$ - writer.write("struct bioticPotential { \n" ); //$NON-NLS-1$ - writer.write(" int litterSize; \n" ); //$NON-NLS-1$ - writer.write(" int matureYears; \n" ); //$NON-NLS-1$ - writer.write("}; \n" ); //$NON-NLS-1$ - writer.write("int main(int argc, char **argv) { \n" ); //$NON-NLS-1$ - writer.write(" bioticPotential brownbear_bt = {1, 3}; \n" ); //$NON-NLS-1$ - writer.write(" Bear *grizzly = new Bear(4,3); \n" ); //$NON-NLS-1$ - writer.write(" brownbear_bt.matureYears = grizzly->biotics.matureYears;//ref\n" ); //$NON-NLS-1$ - writer.write("} \n" ); //$NON-NLS-1$ - String code = writer.toString(); - IFile b = importFile( "FieldReference.cpp", code ); //$NON-NLS-1$ - //vp1 class field ref in constructor initializer list - ICSearchPattern pattern = SearchEngine.createSearchPattern( "isCarnivore", FIELD, REFERENCES, true ); //$NON-NLS-1$ - Set matches = search( pattern ); - assertEquals( 1, matches.size() ); - assertMatch( matches, b, code.indexOf( "isCarnivore/*ref*/" ) ); //$NON-NLS-1$ - //vp2 struct field ref in method to anon struct, ref in function on rhs - pattern = SearchEngine.createSearchPattern( "biotics", FIELD, REFERENCES, true ); //$NON-NLS-1$ - matches = search( pattern ); - assertEquals( 2, matches.size() ); - assertMatch( matches, b, code.indexOf( "biotics.matureYears=s;" ) ); //$NON-NLS-1$ - assertMatch( matches, b, code.indexOf( "biotics.matureYears;//ref" ) ); //$NON-NLS-1$ - - } - //76203 - public void testNestedFieldReference() throws Exception { - Writer writer = new StringWriter(); - writer.write("class Bear { \n" ); //$NON-NLS-1$ - writer.write("public: \n" ); //$NON-NLS-1$ - writer.write(" Bear(int s,int t) { \n" ); //$NON-NLS-1$ - writer.write(" biotics.matureYears=s;//ref \n" ); //$NON-NLS-1$ - writer.write(" biotics.littersPerYear=t; \n" ); //$NON-NLS-1$ - writer.write(" } \n" ); //$NON-NLS-1$ - writer.write(" struct { \n" ); //$NON-NLS-1$ - writer.write(" int matureYears; \n" ); //$NON-NLS-1$ - writer.write(" int littersPerYear; \n" ); //$NON-NLS-1$ - writer.write(" } biotics; \n" ); //$NON-NLS-1$ - writer.write("}; \n" ); //$NON-NLS-1$ - writer.write("struct bioticPotential { \n" ); //$NON-NLS-1$ - writer.write(" int litterSize; \n" ); //$NON-NLS-1$ - writer.write(" int matureYears; \n" ); //$NON-NLS-1$ - writer.write("}; \n" ); //$NON-NLS-1$ - writer.write("int main(int argc, char **argv) { \n" ); //$NON-NLS-1$ - writer.write(" bioticPotential brownbear_bt = {1, 3}; \n" ); //$NON-NLS-1$ - writer.write(" Bear *grizzly = new Bear(4,3); \n" ); //$NON-NLS-1$ - writer.write(" brownbear_bt.matureYears = grizzly->biotics.matureYears;//ref\n" ); //$NON-NLS-1$ - writer.write("} \n" ); //$NON-NLS-1$ - String code = writer.toString(); - IFile b = importFile( "NestedFieldReference.cpp", code ); //$NON-NLS-1$ - - ICSearchPattern pattern = SearchEngine.createSearchPattern( "matureYears", FIELD, REFERENCES, true ); //$NON-NLS-1$ - Set matches = search( pattern ); - assertEquals( 3, matches.size() ); - assertMatch( matches, b, code.indexOf( "matureYears = grizzly" ) ); //$NON-NLS-1$ - assertMatch( matches, b, code.indexOf( "matureYears;//ref" ) ); //$NON-NLS-1$ - assertMatch( matches, b, code.indexOf( "matureYears=s;//ref,ref" ) ); //$NON-NLS-1$ / - - } - public void testVarDeclaration() throws Exception { - Writer writer = new StringWriter(); - writer.write(" namespace N2 { \n" ); //$NON-NLS-1$ - writer.write(" class linkedlist2{ \n" ); //$NON-NLS-1$ - writer.write(" int field3; \n" ); //$NON-NLS-1$ - writer.write(" class linkedlist2 *field4; \n" ); //$NON-NLS-1$ - writer.write(" }; \n" ); //$NON-NLS-1$ - writer.write(" class linkedlist2 var1; \n" ); //$NON-NLS-1$ - writer.write(" } \n" ); //$NON-NLS-1$ - writer.write("extern bool var2; \n" ); //$NON-NLS-1$ - writer.write("unsigned int var3(1024); \n" ); //$NON-NLS-1$ - writer.write("unsigned long long var4=123456, \n" ); //$NON-NLS-1$ - writer.write(" var5=1234567; \n" ); //$NON-NLS-1$ - writer.write("void f(){ \n" ); //$NON-NLS-1$ - writer.write(" volatile unsigned long var6; \n" ); //$NON-NLS-1$ - writer.write(" for (register int var7=0; var7<10000; var7++){} \n" ); //$NON-NLS-1$ - writer.write(" } \n" ); //$NON-NLS-1$ - String code = writer.toString(); - IFile gh = importFile( "VarDeclaration.h", code ); //$NON-NLS-1$ - - ICSearchPattern pattern=SearchEngine.createSearchPattern("*", VAR, DECLARATIONS, true); //$NON-NLS-1$ - ICElement[] list = new ICElement[1]; - list[0]=cproject.getCProject(); - Set matches = search( pattern,list); - assertEquals( 1, matches.size()); - assertMatch( matches, gh, code.indexOf( "var2" ) ); //$NON-NLS-1$ - } - // SE63a var field defn - public void testVarDefinition() throws Exception { - - Writer writer = new StringWriter(); - writer.write("namespace zoo { \n" ); //$NON-NLS-1$ - writer.write(" int var1/*def*/; \n" ); //$NON-NLS-1$ - writer.write("} \n" ); //$NON-NLS-1$ - writer.write("extern int var; \n" ); //$NON-NLS-1$ - writer.write("extern char var2/*def*/=3; \n" ); //$NON-NLS-1$ - writer.write("int& var3/*def*/=zoo::var1; \n" ); //$NON-NLS-1$ - writer.write("long long var4/*def*/; \n" ); //$NON-NLS-1$ - writer.write("void f(){ \n" ); //$NON-NLS-1$ - writer.write(" short var5/*def*/=0xabcd; \n" ); //$NON-NLS-1$ - writer.write(" const float var6/*def*/=1.5;\n" ); //$NON-NLS-1$ - writer.write("} \n" ); //$NON-NLS-1$ - writer.write("class A{ \n" ); //$NON-NLS-1$ - writer.write(" void f(){ \n" ); //$NON-NLS-1$ - writer.write(" long double** var7/*def*/; \n" ); //$NON-NLS-1$ - writer.write(" float var8/*def*/=1.5; \n" ); //$NON-NLS-1$ - writer.write(" } \n" ); //$NON-NLS-1$ - writer.write("}; \n" ); //$NON-NLS-1$ - String code = writer.toString(); - IFile cpp = importFile( "VarDefinition.cpp", code ); //$NON-NLS-1$ - ICSearchPattern pattern = SearchEngine.createSearchPattern("*", VAR, DEFINITIONS, true); //$NON-NLS-1$ - ICElement[] list = new ICElement[1]; - list[0]=cproject.getCProject(); - Set matches = search( pattern,list); - assertEquals( 8, matches.size()); - assertMatch( matches, cpp, code.indexOf( "var1" ) ); //$NON-NLS-1$ - assertMatch( matches, cpp, code.indexOf( "var2" ) ); //$NON-NLS-1$ - assertMatch( matches, cpp, code.indexOf( "var3" ) ); //$NON-NLS-1$ - assertMatch( matches, cpp, code.indexOf( "var4" ) ); //$NON-NLS-1$ - assertMatch( matches, cpp, code.indexOf( "var5" ) ); //$NON-NLS-1$ - assertMatch( matches, cpp, code.indexOf( "var6" ) ); //$NON-NLS-1$ - assertMatch( matches, cpp, code.indexOf( "var7" ) ); //$NON-NLS-1$ - assertMatch( matches, cpp, code.indexOf( "var8" ) ); //$NON-NLS-1$ - } - // test SE60b - public void testVarReference() throws Exception { - Writer writer = new StringWriter(); - writer.write("char * strcpy( char *, const char * ); \n" ); //$NON-NLS-1$ - writer.write("namespace zoo { \n" ); //$NON-NLS-1$ - writer.write(" int sci=1; \n" ); //$NON-NLS-1$ - writer.write(" class ZooAnimal{ \n" ); //$NON-NLS-1$ - writer.write(" public: \n" ); //$NON-NLS-1$ - writer.write(" ZooAnimal(char *s = \"ZooAnimal\"){} \n" ); //$NON-NLS-1$ - writer.write(" protected: \n" ); //$NON-NLS-1$ - writer.write(" char *name; \n" ); //$NON-NLS-1$ - writer.write(" }; \n" ); //$NON-NLS-1$ - writer.write(" class Bear : public ZooAnimal{ \n" ); //$NON-NLS-1$ - writer.write(" public: \n" ); //$NON-NLS-1$ - writer.write(" Bear(char *sci = \"Ursidae\" ); \n" ); //$NON-NLS-1$ - writer.write(" protected: \n" ); //$NON-NLS-1$ - writer.write(" char *sciName; \n" ); //$NON-NLS-1$ - writer.write(" }; \n" ); //$NON-NLS-1$ - writer.write(" Bear::Bear(char *sci) { \n" ); //$NON-NLS-1$ - writer.write(" strcpy (sciName, sci/*ref1*/); \n" ); //$NON-NLS-1$ - writer.write(" int j=zoo::sci/*ref2*/; \n" ); //$NON-NLS-1$ - writer.write(" } \n" ); //$NON-NLS-1$ - writer.write(" } \n" ); //$NON-NLS-1$ - writer.write("void f() { \n" ); //$NON-NLS-1$ - writer.write(" int sci; \n" ); //$NON-NLS-1$ - writer.write(" sci/*ref3*/++; \n" ); //$NON-NLS-1$ - writer.write(" --sci/*ref4*/; \n" ); //$NON-NLS-1$ - writer.write("} \n" ); //$NON-NLS-1$ - String code = writer.toString(); - IFile z = importFile( "VarReference.cpp", code ); //$NON-NLS-1$ - - ICSearchPattern pattern=SearchEngine.createSearchPattern("sci", VAR, REFERENCES, true); //$NON-NLS-1$ - Set matches = search(pattern); - assertEquals( 4, matches.size()); - assertMatch( matches, z, code.indexOf( "sci/*ref1*/" ) ); //$NON-NLS-1$ - assertMatch( matches, z, code.indexOf( "sci/*ref2*/" ) ); //$NON-NLS-1$ - assertMatch( matches, z, code.indexOf( "sci/*ref3*/" ) ); //$NON-NLS-1$ - assertMatch( matches, z, code.indexOf( "sci/*ref4*/" ) ); //$NON-NLS-1$ - - } - // 75901 // test SE60f1 var all - public void testVarDeclarationArgument() throws Exception { - Writer writer = new StringWriter(); - writer.write("namespace zoo { \n" ); //$NON-NLS-1$ - writer.write(" class Bear { \n" ); //$NON-NLS-1$ - writer.write(" public: \n" ); //$NON-NLS-1$ - writer.write(" Bear( char *s/*decl1*/ = \"Bear\" );\n" ); //$NON-NLS-1$ - writer.write(" }; \n" ); //$NON-NLS-1$ - writer.write(" Bear::Bear(char *s/*decl2*/) \n" ); //$NON-NLS-1$ - writer.write(" : ZooAnimal(s) { \n" ); //$NON-NLS-1$ - writer.write(" } \n" ); //$NON-NLS-1$ - writer.write("} \n" ); //$NON-NLS-1$ - String code = writer.toString(); - IFile z = importFile( "VarDeclarationArgument.cpp", code ); //$NON-NLS-1$ - ICSearchPattern pattern=SearchEngine.createSearchPattern("s", VAR, DECLARATIONS, true); //$NON-NLS-1$ - Set matches = search(pattern); - assertMatch( matches, z, code.indexOf( "s/*decl1*/" ) ); //$NON-NLS-1$ - assertMatch( matches, z, code.indexOf( "s/*decl2*/" ) ); //$NON-NLS-1$ - assertEquals( 2, matches.size()); - - } - // 72735 test SE60f2 var all - public void testVarReferenceInitializer() throws Exception{ - Writer writer = new StringWriter(); - writer.write("enum ZooLocs {ZOOANIMAL, BEAR, PANDA}; \n" ); //$NON-NLS-1$ - writer.write("namespace zoo { \n" ); //$NON-NLS-1$ - writer.write(" class ZooAnimal{ \n" ); //$NON-NLS-1$ - writer.write(" public: \n" ); //$NON-NLS-1$ - writer.write(" ZooAnimal(char *s = \"ZooAnimal\"); \n" ); //$NON-NLS-1$ - writer.write(" }; \n" ); //$NON-NLS-1$ - writer.write(" class Bear : public ZooAnimal{ \n" ); //$NON-NLS-1$ - writer.write(" public: \n" ); //$NON-NLS-1$ - writer.write(" Bear( char *s = \"Bear\", ZooLocs loc = \"BEAR\" ); \n" ); //$NON-NLS-1$ - writer.write(" protected: \n" ); //$NON-NLS-1$ - writer.write(" ZooLocs zooArea; \n" ); //$NON-NLS-1$ - writer.write(" }; \n" ); //$NON-NLS-1$ - writer.write(" Bear::Bear(char *s, ZooLocs loc) \n" ); //$NON-NLS-1$ - writer.write(" : ZooAnimal(s), zooArea (loc/*ref*/) {} \n" ); //$NON-NLS-1$ - writer.write(" } \n" ); //$NON-NLS-1$ - writer.write(" } \n" ); //$NON-NLS-1$ - String code = writer.toString(); - IFile z = importFile( "VarReferenceInitializer.cpp", code ); //$NON-NLS-1$ - ICSearchPattern pattern=SearchEngine.createSearchPattern("loc", VAR, REFERENCES, true); //$NON-NLS-1$ - Set matches = search(pattern); - assertEquals( 1, matches.size()); - assertMatch( matches, z, code.indexOf( "loc/*ref*/" ) ); //$NON-NLS-1$ - - } - // 75901 // test SE60f1 var all - public void testVarDefinitionArgument() throws Exception { - Writer writer = new StringWriter(); - writer.write(" class C { \n" ); //$NON-NLS-1$ - writer.write(" public: \n" ); //$NON-NLS-1$ - writer.write(" C( char *s/*def1*/ = \"Bear\" );\n" ); //$NON-NLS-1$ - writer.write(" }; \n" ); //$NON-NLS-1$ - writer.write(" C::C(char *s/*def2*/){} \n" ); //$NON-NLS-1$ - String code = writer.toString(); - IFile z = importFile( "VarDeclarationArgument.cpp", code ); //$NON-NLS-1$ - ICSearchPattern pattern=SearchEngine.createSearchPattern("s", VAR, DEFINITIONS, true); //$NON-NLS-1$ - Set matches = search(pattern); - //Changed to 0 as we no longer encode parameter strings as individual references - assertEquals( 0, matches.size()); - - } - - // test 85a union declaration - public void testUnionDeclaration() throws Exception { - Writer writer = new StringWriter(); - writer.write("enum Tokentype {ID, ICONST}; \n" ); //$NON-NLS-1$ - writer.write("class Token { \n" ); //$NON-NLS-1$ - writer.write(" public: \n" ); //$NON-NLS-1$ - writer.write(" Tokentype tok; \n" ); //$NON-NLS-1$ - writer.write(" union { //anon field \n" ); //$NON-NLS-1$ - writer.write(" char *sval; \n" ); //$NON-NLS-1$ - writer.write(" int ival; \n" ); //$NON-NLS-1$ - writer.write(" double dval; \n" ); //$NON-NLS-1$ - writer.write(" } val1; \n" ); //$NON-NLS-1$ - writer.write("}; \n" ); //$NON-NLS-1$ - writer.write("static union { //anon static \n" ); //$NON-NLS-1$ - writer.write(" char *sval; \n" ); //$NON-NLS-1$ - writer.write(" int ival; \n" ); //$NON-NLS-1$ - writer.write(" double dval; \n" ); //$NON-NLS-1$ - writer.write("}; \n" ); //$NON-NLS-1$ - writer.write("union TokenValue { \n" ); //$NON-NLS-1$ - writer.write("TokenValue (int ix) {ival = ix;} \n" ); //$NON-NLS-1$ - writer.write("TokenValue (char *s) {sval = s;} \n" ); //$NON-NLS-1$ - writer.write("TokenValue () {} \n" ); //$NON-NLS-1$ - writer.write(" char *sval; \n" ); //$NON-NLS-1$ - writer.write(" int ival; \n" ); //$NON-NLS-1$ - writer.write(" double dval; \n" ); //$NON-NLS-1$ - writer.write("}; \n" ); //$NON-NLS-1$ - writer.write("TokenValue val2; \n" ); //$NON-NLS-1$ - String code = writer.toString(); - IFile uh = importFile( "UnionDeclaration.h", code ); //$NON-NLS-1$ - - ICSearchPattern pattern = SearchEngine.createSearchPattern( "*", UNION, DEFINITIONS, true ); //$NON-NLS-1$ - ICElement[] list = new ICElement[1]; - list[0]=cproject.getCProject(); - Set matches = search( pattern,list ); - - assertEquals( 3, matches.size() ); - assertMatch( matches, uh, code.indexOf( "union { //anon field" ) ); //$NON-NLS-1$ - assertMatch( matches, uh, code.indexOf( "union { //anon static" ) ); //$NON-NLS-1$ - assertMatch( matches, uh, code.indexOf( "TokenValue" ) ); //$NON-NLS-1$ - - } - public void testUnionReference() throws Exception { - Writer writer = new StringWriter(); - writer = new StringWriter(); - writer.write("enum Tokentype {ID, ICONST}; \n" ); //$NON-NLS-1$ - writer.write("class Token { \n" ); //$NON-NLS-1$ - writer.write(" public: \n" ); //$NON-NLS-1$ - writer.write(" Tokentype tok; \n" ); //$NON-NLS-1$ - writer.write("union TokenValue { \n" ); //$NON-NLS-1$ - writer.write("TokenValue (int ix) {ival = ix;} \n" ); //$NON-NLS-1$ - writer.write("TokenValue (char *s) {sval = s;} \n" ); //$NON-NLS-1$ - writer.write("TokenValue () {} \n" ); //$NON-NLS-1$ - writer.write(" char *sval; \n" ); //$NON-NLS-1$ - writer.write(" int ival; \n" ); //$NON-NLS-1$ - writer.write(" double dval; \n" ); //$NON-NLS-1$ - writer.write("}; \n" ); //$NON-NLS-1$ - writer.write("TokenValue val2; \n" ); //$NON-NLS-1$ - String header = writer.toString(); - importFile( "UnionReference.h", header ); //$NON-NLS-1$ - writer = new StringWriter(); - writer.write("#include \"UnionReference.h\" \n" ); //$NON-NLS-1$ - writer.write("union Uu{int i; double d;}; \n" ); //$NON-NLS-1$ - writer.write("void f(TokenValue/*ref1*/ t){}; \n" ); //$NON-NLS-1$ - writer.write("void g(){ \n" ); //$NON-NLS-1$ - writer.write(" f(TokenValue/*ref2*/(3)); \n" ); //$NON-NLS-1$ - writer.write(" char *p=\"hello\"; \n" ); //$NON-NLS-1$ - writer.write(" f(p); \n" ); //$NON-NLS-1$ - writer.write(" TokenValue/*ref3*/ t=(TokenValue/*ref4*/) p;\n" ); //$NON-NLS-1$ - writer.write("} \n" ); //$NON-NLS-1$ - writer.write("Uu/*ref5*/ t; \n" ); //$NON-NLS-1$ - String source = writer.toString(); - IFile cpp = importFile( "UnionReference.cpp", source ); //$NON-NLS-1$ - ICElement[] list = {cproject.findElement(new Path("UnionReference.cpp"))}; //$NON-NLS-1$ - ICSearchPattern pattern = SearchEngine.createSearchPattern( "*", UNION, REFERENCES, true ); //$NON-NLS-1$ - Set matches = search( pattern, list ); - - assertEquals( 5, matches.size() ); - assertMatch( matches, cpp, source.indexOf( "TokenValue/*ref1*/" ) ); //$NON-NLS-1$ - assertMatch( matches, cpp, source.indexOf( "TokenValue/*ref2*/" ) ); //$NON-NLS-1$ - assertMatch( matches, cpp, source.indexOf( "TokenValue/*ref3*/" ) ); //$NON-NLS-1$ - assertMatch( matches, cpp, source.indexOf( "TokenValue/*ref4*/" ) ); //$NON-NLS-1$ - assertMatch( matches, cpp, source.indexOf( "Uu/*ref5*/" ) ); //$NON-NLS-1$ - - } - // test SE44 - public void testEnumerationDeclaration() throws Exception { - Writer writer = new StringWriter(); - //next line commented because it affects testEnumeratorDeclarationCase - //writer.write("enum EE/*def1*/ {A0, A1}; \n" ); //$NON-NLS-1$ - writer.write("class B { \n" ); //$NON-NLS-1$ - writer.write(" enum EE/*def2*/ {B0, B1}; \n" ); //$NON-NLS-1$ - writer.write(" B(){ \n" ); //$NON-NLS-1$ - writer.write(" enum EE/*def3*/ {M0, M1}; \n" ); //$NON-NLS-1$ - writer.write(" } \n" ); //$NON-NLS-1$ - writer.write(" void foo(); \n" ); //$NON-NLS-1$ - writer.write("}; \n" ); //$NON-NLS-1$ - String header = writer.toString(); - IFile h = importFile( "EnumerationDeclaration.h", header ); //$NON-NLS-1$ - writer = new StringWriter(); - writer.write("#include \"EnumerationDeclaration.h\" \n" ); //$NON-NLS-1$ - writer.write("void B::foo() { \n" ); //$NON-NLS-1$ - writer.write(" enum EE/*def4*/ {F0, F1}; \n" ); //$NON-NLS-1$ - writer.write(" enum EE ee; \n" ); //$NON-NLS-1$ - writer.write("}; \n" ); //$NON-NLS-1$ - writer.write("void boo() { \n" ); //$NON-NLS-1$ - writer.write(" enum EE/*def5*/ {G0, G1}; \n" ); //$NON-NLS-1$ - writer.write("}; \n" ); //$NON-NLS-1$ - String source = writer.toString(); - IFile cpp = importFile( "EnumerationDeclaration.cpp", source ); //$NON-NLS-1$ - //vp1 global,class,constructor; working set - ICElement[] list = {cproject.findElement(new Path("EnumerationDeclaration.h"))}; //$NON-NLS-1$ - ICSearchPattern pattern = SearchEngine.createSearchPattern( "EE", ENUM, DECLARATIONS, true ); //$NON-NLS-1$ - Set matches = search( pattern, list ); - assertEquals( 2, matches.size() ); - //if including first line in snippet, then include this vp and change 2 to 3 results - //assertMatch( matches, h, header.indexOf( "EE/*def1*/" ) ); //$NON-NLS-1$ - assertMatch( matches, h, header.indexOf( "EE/*def2*/" ) ); //$NON-NLS-1$ - assertMatch( matches, h, header.indexOf( "EE/*def3*/" ) ); //$NON-NLS-1$ - //vp2 method,function; working set - list[0] = cproject.findElement(new Path("EnumerationDeclaration.cpp")); //$NON-NLS-1$ - matches = search( pattern, list ); - assertEquals( 2, matches.size() ); - assertMatch( matches, cpp, source.indexOf( "EE/*def4*/" ) ); //$NON-NLS-1$ - assertMatch( matches, cpp, source.indexOf( "EE/*def5*/" ) ); //$NON-NLS-1$ - } - public void testEnumerationReference() throws Exception { - Writer writer = new StringWriter(); - //next line commented because it affects testEnumeratorDeclarationCase - //writer.write("enum EE {A0, A1}; \n" ); //$NON-NLS-1$ - writer.write("class B { \n" ); //$NON-NLS-1$ - writer.write(" enum EE {B0, B1}; \n" ); //$NON-NLS-1$ - writer.write(" B(){ \n" ); //$NON-NLS-1$ - writer.write(" } \n" ); //$NON-NLS-1$ - writer.write(" EE/*ref8*/ bee; \n" ); //$NON-NLS-1$ - writer.write(" void foo(); \n" ); //$NON-NLS-1$ - writer.write("}; \n" ); //$NON-NLS-1$ - writer.write("B::EE/*ref2*/ eieio; \n" ); //$NON-NLS-1$ - String header = writer.toString(); - IFile h = importFile( "EnumerationReference.h", header ); //$NON-NLS-1$ - writer = new StringWriter(); - writer.write("#include \"EnumerationReference.h\" \n" ); //$NON-NLS-1$ - writer.write("void B::foo() { \n" ); //$NON-NLS-1$ - writer.write(" enum EE {F0, F1}; \n" ); //$NON-NLS-1$ - writer.write(" enum EE/*ref3*/ ib4e; \n" ); //$NON-NLS-1$ - writer.write("} \n" ); //$NON-NLS-1$ - writer.write("void boo(B::EE/*ref4*/ e) { \n" ); //$NON-NLS-1$ - writer.write(" enum EE {G0, G1}; \n" ); //$NON-NLS-1$ - //if including first line in snippet, then include the next line too - //writer.write(" ::EE/*ref5*/ f; \n" ); //$NON-NLS-1$ - writer.write(" EE/*ref6*/ i=(EE/*ref7*/)2; \n" ); //$NON-NLS-1$ - writer.write("} \n" ); //$NON-NLS-1$ - String source = writer.toString(); - IFile cpp = importFile( "EnumerationReference.cpp", source ); //$NON-NLS-1$ - //vp1 global and class reference; working set - ICElement[] list = {cproject.findElement(new Path("EnumerationReference.h"))}; //$NON-NLS-1$ - ICSearchPattern pattern = SearchEngine.createSearchPattern( "EE", ENUM, REFERENCES, true ); //$NON-NLS-1$ - Set matches = search( pattern, list ); - assertEquals( 2, matches.size() ); - assertMatch( matches, h, header.indexOf( "EE/*ref2*/" ) ); //$NON-NLS-1$ - assertMatch( matches, h, header.indexOf( "EE/*ref8*/" ) ); //$NON-NLS-1$ - //vp2 reference in method,function,cast; working set - list[0] = cproject.findElement(new Path("EnumerationReference.cpp")); //$NON-NLS-1$ - matches = search( pattern, list ); - assertEquals( 4, matches.size() ); - //if including first line in snippet, then include this vp and change 4 to 5 results - //assertMatch( matches, cpp, source.indexOf( "EE/*ref5*/" ) ); //$NON-NLS-1$ - assertMatch( matches, cpp, source.indexOf( "EE/*ref3*/" ) ); //$NON-NLS-1$ - assertMatch( matches, cpp, source.indexOf( "EE/*ref4*/" ) ); //$NON-NLS-1$ - assertMatch( matches, cpp, source.indexOf( "EE/*ref6*/" ) ); //$NON-NLS-1$ - assertMatch( matches, cpp, source.indexOf( "EE/*ref7*/" ) ); //$NON-NLS-1$ - //vp3 class-qualified reference in a function argument and class declaration; workspace - pattern = SearchEngine.createSearchPattern( "B::EE", ENUM, REFERENCES, true ); //$NON-NLS-1$ - matches = search( pattern ); - assertEquals( 3, matches.size() ); - assertMatch( matches, h, header.indexOf( "EE/*ref2*/" ) ); //$NON-NLS-1$ - assertMatch( matches, h, header.indexOf( "EE/*ref8*/" ) ); //$NON-NLS-1$ - assertMatch( matches, cpp, source.indexOf( "EE/*ref4*/" ) ); //$NON-NLS-1$ - - } - public void testEnumerationReferenceGlobal() throws Exception { - Writer writer = new StringWriter(); - writer.write("enum E{E0}; \n" ); //$NON-NLS-1$ - writer.write("void f() { \n" ); //$NON-NLS-1$ - writer.write(" enum E{E1}; \n" ); //$NON-NLS-1$ - writer.write(" E e; \n" ); //$NON-NLS-1$ - writer.write("} \n" ); //$NON-NLS-1$ - writer.write("E/*ref*/ f; \n" ); //$NON-NLS-1$ - String source = writer.toString(); - IFile cpp = importFile( "EnumerationReferenceGlobal.cpp", source ); //$NON-NLS-1$ - //vp1 global and class reference; working set - ICSearchPattern pattern = SearchEngine.createSearchPattern( "::E", ENUM, REFERENCES, true ); //$NON-NLS-1$ - Set matches = search( pattern ); - assertEquals( 1, matches.size() ); - assertMatch( matches, cpp, source.indexOf( "E/*ref*/" ) ); //$NON-NLS-1$ - } - public void testEnumeratorDeclaration() throws Exception { - Writer writer = new StringWriter(); - writer.write("enum ZooLocs {ZOOANIMAL, BEAR/*decl1*/}; \n" ); //$NON-NLS-1$ - writer.write("class Bear { \n" ); //$NON-NLS-1$ - writer.write(" public: \n" ); //$NON-NLS-1$ - writer.write(" enum BType{BEAR/*decl2*/, PANDA/*decl3*/}; \n" ); //$NON-NLS-1$ - writer.write(" Bear(ZooLocs loc = ::BEAR ); \n" ); //$NON-NLS-1$ - writer.write("}; \n" ); //$NON-NLS-1$ - String code = writer.toString(); - IFile z = importFile( "EnumeratorDeclaration.cpp", code ); //$NON-NLS-1$ - ICSearchPattern pattern = SearchEngine.createSearchPattern( "BEAR", ENUMTOR, DECLARATIONS, true ); //$NON-NLS-1$ - //vp1 enumtor in global and class scopes - Set matches = search( pattern ); - assertEquals( 2, matches.size() ); - assertMatch( matches, z, code.indexOf( "BEAR/*decl1*/" ) ); //$NON-NLS-1$ - assertMatch( matches, z, code.indexOf( "BEAR/*decl2*/" ) ); //$NON-NLS-1$ - //vp2 global enumtor with fully qualified search pattern - pattern = SearchEngine.createSearchPattern( "::BEAR", ENUMTOR, DECLARATIONS, true ); //$NON-NLS-1$ - matches = search( pattern ); - assertEquals( 1, matches.size() ); - assertMatch( matches, z, code.indexOf( "BEAR/*decl1*/" ) ); //$NON-NLS-1$ - //vp3 class enumtor with fully qualified search pattern - pattern = SearchEngine.createSearchPattern( "Bear::PANDA", ENUMTOR, DECLARATIONS, true ); //$NON-NLS-1$ - matches = search( pattern ); - assertEquals( 1, matches.size() ); - assertMatch( matches, z, code.indexOf( "PANDA" ) ); //$NON-NLS-1$ - - } - public void testEnumeratorReference() throws Exception { - Writer writer = new StringWriter(); - writer.write("enum ZooLocs {ZOOANIMAL, BEAR}; \n" ); //$NON-NLS-1$ - writer.write("class Bear{ \n" ); //$NON-NLS-1$ - writer.write(" public: \n" ); //$NON-NLS-1$ - writer.write(" enum BType {BEAR=2, PANDA}; \n" ); //$NON-NLS-1$ - writer.write(" Bear(ZooLocs loc = ::BEAR/*ref1*/ );\n" ); //$NON-NLS-1$ - writer.write(" protected: \n" ); //$NON-NLS-1$ - writer.write(" ZooLocs zooArea; \n" ); //$NON-NLS-1$ - writer.write("}; \n" ); //$NON-NLS-1$ - writer.write("Bear::Bear(ZooLocs loc){ \n" ); //$NON-NLS-1$ - writer.write(" zooArea=::BEAR/*ref2*/; \n" ); //$NON-NLS-1$ - writer.write(" BEAR/*ref3*/; \n" ); //$NON-NLS-1$ - writer.write("} \n" ); //$NON-NLS-1$ - writer.write("void f(){ \n" ); //$NON-NLS-1$ - writer.write(" Bear::PANDA/*ref5*/; \n" ); //$NON-NLS-1$ - writer.write("} \n" ); //$NON-NLS-1$ - String code = writer.toString(); - IFile z = importFile( "EnumeratorReference.cpp", code ); //$NON-NLS-1$ - //vp1 fully qualified, partially qualified and unqualified reference - ICSearchPattern pattern = SearchEngine.createSearchPattern( "BEAR", ENUMTOR, REFERENCES, true ); //$NON-NLS-1$ - Set matches = search( pattern ); - assertEquals( 3, matches.size() ); - assertMatch( matches, z, code.indexOf( "BEAR/*ref1*/" ) ); //$NON-NLS-1$ - assertMatch( matches, z, code.indexOf( "BEAR/*ref2*/" ) ); //$NON-NLS-1$ - assertMatch( matches, z, code.indexOf( "BEAR/*ref3*/" ) ); //$NON-NLS-1$ - pattern = SearchEngine.createSearchPattern( "Bear::PANDA", ENUMTOR, REFERENCES, true ); //$NON-NLS-1$ - matches = search( pattern ); - assertEquals( 1, matches.size() ); - assertMatch( matches, z, code.indexOf( "PANDA/*ref5*/" ) ); //$NON-NLS-1$ - } - public void testEnumeratorDeclarationCase() throws Exception { - Writer writer = new StringWriter(); - writer.write("enum A {B}; \n" ); //$NON-NLS-1$ - writer.write("class C { \n" ); //$NON-NLS-1$ - writer.write(" enum D {B0}; \n" ); //$NON-NLS-1$ - writer.write("}; \n" ); //$NON-NLS-1$ - String code = writer.toString(); - IFile z = importFile( "EnumeratorDeclarationCase.cpp", code ); //$NON-NLS-1$ - //vp1 case sensitive qualified search on inside enumtor prefixed by outside enumtor - ICSearchPattern pattern = SearchEngine.createSearchPattern( "C::B0", ENUMTOR, DECLARATIONS, true ); //$NON-NLS-1$ - Set matches = search( pattern ); - assertEquals( 1, matches.size() ); - assertMatch( matches, z, code.indexOf( "B0" ) ); //$NON-NLS-1$ - //vp1 case insensitive qualified search on inside enumtor prefixed by outside enumtor - pattern = SearchEngine.createSearchPattern( "C::B0", ENUMTOR, DECLARATIONS, false ); //$NON-NLS-1$ - matches = search( pattern ); - assertEquals( 1, matches.size() ); - assertMatch( matches, z, code.indexOf( "B0" ) ); //$NON-NLS-1$ - } - //typedef is not currently shown in the Search dialog - //but are found when you select all types. - public void testTypedefDeclaration() throws Exception { - Writer writer = new StringWriter(); - writer.write(" class A { \n" ); //$NON-NLS-1$ - writer.write(" typedef struct alpha {} beta/*decl*/; \n" ); //$NON-NLS-1$ - writer.write(" }; \n" ); //$NON-NLS-1$ - - String code = writer.toString(); - IFile f = importFile( "TypedefDeclaration.cpp", code ); //$NON-NLS-1$ - - ICSearchPattern pattern = SearchEngine.createSearchPattern( "beta", TYPEDEF, DECLARATIONS, true ); //$NON-NLS-1$ - Set matches = search( pattern ); - - assertEquals( 1, matches.size() ); - assertMatch( matches, f, code.indexOf( "beta/*decl*/" ) ); //$NON-NLS-1$ - } - public void testMacroDeclaration() throws Exception { - Writer writer = new StringWriter(); - writer.write("#define paster/*decl1*/( n ) printf( \"token\" #n \" = %d\", token##n ) \n" ); //$NON-NLS-1$ - writer.write("#define token9/*decl2*/ 3 \n" ); //$NON-NLS-1$ - writer.write("#define HELLO/*decl3*/ \n" ); //$NON-NLS-1$ - writer.write("#ifdef HELLO \n" ); //$NON-NLS-1$ - writer.write(" #define HI/*decl4*/ \n" ); //$NON-NLS-1$ - writer.write("#endif \n" ); //$NON-NLS-1$ - writer.write("#ifdef GOODBYE \n" ); //$NON-NLS-1$ - writer.write(" #define BYE/*decl5*/ \n" ); //$NON-NLS-1$ - writer.write("#endif \n" ); //$NON-NLS-1$ - String header = writer.toString(); - IFile h = importFile( "MacroDeclaration.cpp", header ); //$NON-NLS-1$ - //vp1 identifier as a function with arguements - ICSearchPattern pattern = SearchEngine.createSearchPattern( "paster", MACRO, DECLARATIONS, true ); //$NON-NLS-1$ - Set matches = search( pattern ); - assertEquals( 1, matches.size() ); - assertMatch( matches, h, header.indexOf( "paster/*decl1*/" ) ); //$NON-NLS-1$ - //vp2 identifier with token-string - pattern = SearchEngine.createSearchPattern( "token9", MACRO, DECLARATIONS, true ); //$NON-NLS-1$ - matches = search( pattern ); - assertEquals( 1, matches.size() ); - assertMatch( matches, h, header.indexOf( "token9/*decl2*/" ) ); //$NON-NLS-1$ - //vp3 identifer without token-string - pattern = SearchEngine.createSearchPattern( "HELLO", MACRO, DECLARATIONS, true ); //$NON-NLS-1$ - matches = search( pattern ); - assertEquals( 1, matches.size() ); - assertMatch( matches, h, header.indexOf( "HELLO/*decl3*/" ) ); //$NON-NLS-1$ - //vp4-identifier inside defined ifdef - pattern = SearchEngine.createSearchPattern( "HI", MACRO, DECLARATIONS, true ); //$NON-NLS-1$ - matches = search( pattern ); - assertEquals( 1, matches.size() ); - assertMatch( matches, h, header.indexOf( "HI/*decl4*" ) ); //$NON-NLS-1$ - //vp5-identifier inside undefined ifdef - pattern = SearchEngine.createSearchPattern( "BYE", MACRO, DECLARATIONS, true ); //$NON-NLS-1$ - matches = search( pattern ); - assertEquals( 0, matches.size() ); - } - public void testMethodFieldReferenceInExpressions() throws Exception { - Writer writer = new StringWriter(); - writer.write("class M { \n" );//$NON-NLS-1$ - writer.write(" public: \n" );//$NON-NLS-1$ - writer.write(" int mm(){return 0;} \n" );//$NON-NLS-1$ - writer.write(" float fm; \n" );//$NON-NLS-1$ - writer.write("}; \n" );//$NON-NLS-1$ - writer.write("class N{ \n" );//$NON-NLS-1$ - writer.write("public: \n" );//$NON-NLS-1$ - writer.write(" double mn(){return 3.2;} \n" );//$NON-NLS-1$ - writer.write(" static const int fn= 12; \n" );//$NON-NLS-1$ - writer.write("}; \n" );//$NON-NLS-1$ - writer.write("void foo() { \n" );//$NON-NLS-1$ - writer.write(" M m; \n" );//$NON-NLS-1$ - writer.write(" N *n; \n" );//$NON-NLS-1$ - writer.write(" double i= ((double)m.mm/*11*/()+n->fn/*21*/-m.fm/*22*/ \n" );//$NON-NLS-1$ - writer.write(" /n->mn/*12*/())*(m.fm/*23*/*n->mn/*13*/()) \n" );//$NON-NLS-1$ - writer.write(" &&m.mm/*14*/()||(int)n->fn/*24*/ \n" );//$NON-NLS-1$ - writer.write(" &(int)n->mn/*15*/()|(int)m.fm/*25*/ \n" );//$NON-NLS-1$ - writer.write(" <<(int)n->fn/*26*/>>m.mm/*16*/(); \n" );//$NON-NLS-1$ - writer.write("} \n" );//$NON-NLS-1$ - String code = writer.toString(); - IFile b = importFile( "MethodFieldReferenceInExpressions.cpp", code ); //$NON-NLS-1$ - //vp1 methods - ICSearchPattern pattern = SearchEngine.createSearchPattern( "m*", METHOD, REFERENCES, true ); //$NON-NLS-1$ - Set matches = search( pattern ); - assertEquals( 6, matches.size() ); - assertMatch( matches, b, code.indexOf( "mm/*11*/" ) ); //$NON-NLS-1$ - assertMatch( matches, b, code.indexOf( "mn/*12*/" ) ); //$NON-NLS-1$ - assertMatch( matches, b, code.indexOf( "mn/*13*/" ) ); //$NON-NLS-1$ - assertMatch( matches, b, code.indexOf( "mm/*14*/" ) ); //$NON-NLS-1$ - assertMatch( matches, b, code.indexOf( "mn/*15*/" ) ); //$NON-NLS-1$ - assertMatch( matches, b, code.indexOf( "mm/*16*/" ) ); //$NON-NLS-1$ - //vp2 fields - pattern = SearchEngine.createSearchPattern( "f*", FIELD, REFERENCES, true ); //$NON-NLS-1$ - matches = search( pattern ); - assertEquals( 6, matches.size() ); - assertMatch( matches, b, code.indexOf( "fn/*21*/" ) ); //$NON-NLS-1$ - assertMatch( matches, b, code.indexOf( "fm/*22*/" ) ); //$NON-NLS-1$ - assertMatch( matches, b, code.indexOf( "fm/*23*/" ) ); //$NON-NLS-1$ - assertMatch( matches, b, code.indexOf( "fn/*24*/" ) ); //$NON-NLS-1$ - assertMatch( matches, b, code.indexOf( "fm/*22*/" ) ); //$NON-NLS-1$ - assertMatch( matches, b, code.indexOf( "fn/*26*/" ) ); //$NON-NLS-1$ - } -} diff --git a/core/org.eclipse.cdt.core.tests/regression/org/eclipse/cdt/core/tests/SelectionRegressionTest.java b/core/org.eclipse.cdt.core.tests/regression/org/eclipse/cdt/core/tests/SelectionRegressionTest.java index dce4b3d4e55..796cfbf8c2a 100644 --- a/core/org.eclipse.cdt.core.tests/regression/org/eclipse/cdt/core/tests/SelectionRegressionTest.java +++ b/core/org.eclipse.cdt.core.tests/regression/org/eclipse/cdt/core/tests/SelectionRegressionTest.java @@ -32,8 +32,6 @@ import org.eclipse.cdt.core.parser.ast.IASTNode; import org.eclipse.cdt.core.parser.ast.IASTOffsetableNamedElement; import org.eclipse.cdt.core.parser.tests.CompleteParseBaseTest.FullParseCallback; import org.eclipse.cdt.core.testplugin.CProjectHelper; -import org.eclipse.cdt.internal.core.browser.cache.TypeCacheManager; -import org.eclipse.cdt.internal.core.index.domsourceindexer.DOMSourceIndexer; import org.eclipse.core.resources.IFile; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.NullProgressMonitor; @@ -103,8 +101,6 @@ public class SelectionRegressionTest extends BaseTestFramework { } } catch ( CoreException e ) { //boo } - TypeCacheManager typeCacheManager = TypeCacheManager.getInstance(); - typeCacheManager.setProcessTypeCacheEvents(false); } protected void tearDown() throws Exception { @@ -112,7 +108,6 @@ public class SelectionRegressionTest extends BaseTestFramework { return; try{ - project.setSessionProperty( DOMSourceIndexer.activationKey, new Boolean( false ) ); project.delete(true,true,new NullProgressMonitor()); project = null; } catch ( CoreException e ) { //boo diff --git a/core/org.eclipse.cdt.core.tests/search/org/eclipse/cdt/core/search/tests/BaseSearchTest.java b/core/org.eclipse.cdt.core.tests/search/org/eclipse/cdt/core/search/tests/BaseSearchTest.java deleted file mode 100644 index 8f1961adad7..00000000000 --- a/core/org.eclipse.cdt.core.tests/search/org/eclipse/cdt/core/search/tests/BaseSearchTest.java +++ /dev/null @@ -1,179 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2003, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corp. - Rational Software - initial implementation - *******************************************************************************/ -/* - * Created on Jul 22, 2003 - */ -package org.eclipse.cdt.core.search.tests; - -import java.io.FileInputStream; - -import junit.framework.TestCase; - -import org.eclipse.cdt.core.CCorePlugin; -import org.eclipse.cdt.core.ICDescriptor; -import org.eclipse.cdt.core.ICDescriptorOperation; -import org.eclipse.cdt.core.model.ICProject; -import org.eclipse.cdt.core.search.BasicSearchResultCollector; -import org.eclipse.cdt.core.search.ICSearchConstants; -import org.eclipse.cdt.core.search.ICSearchPattern; -import org.eclipse.cdt.core.search.ICSearchResultCollector; -import org.eclipse.cdt.core.search.ICSearchScope; -import org.eclipse.cdt.core.search.SearchEngine; -import org.eclipse.cdt.core.testplugin.CProjectHelper; -import org.eclipse.cdt.core.testplugin.CTestPlugin; -import org.eclipse.cdt.core.testplugin.FileManager; -import org.eclipse.cdt.internal.core.index.cindexstorage.Index; -import org.eclipse.cdt.internal.core.index.domsourceindexer.DOMSourceIndexer; -import org.eclipse.cdt.internal.core.index.domsourceindexer.DOMSourceIndexerRunner; -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IWorkspace; -import org.eclipse.core.resources.ResourcesPlugin; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.NullProgressMonitor; -import org.eclipse.core.runtime.Path; - -/** - * @author aniefer - * - * To change the template for this generated type comment go to - * Window>Preferences>Java>Code Generation>Code and Comments - */ -public class BaseSearchTest extends TestCase implements ICSearchConstants { - - static protected ICSearchScope scope; - static protected IFile file; - static protected IProject testProject; - static protected NullProgressMonitor monitor; - static protected IWorkspace workspace; - static protected BasicSearchResultCollector resultCollector; - static protected SearchEngine searchEngine; - static protected FileManager fileManager; - static final String sourceIndexerID = "org.eclipse.cdt.core.originalsourceindexer"; //$NON-NLS-1$ - static protected DOMSourceIndexer sourceIndexer; - { - - //(CCorePlugin.getDefault().getCoreModel().getIndexManager()).reset(); - monitor = new NullProgressMonitor(); - - workspace = ResourcesPlugin.getWorkspace(); - CCorePlugin.getDefault().getPluginPreferences().setValue(CCorePlugin.PREF_INDEXER, CCorePlugin.DEFAULT_INDEXER_UNIQ_ID); - - try { - //Create temp project - testProject = createProject("SearchTestProject"); - resetIndexer(DOMSourceIndexer.ID); - - testProject.setSessionProperty(DOMSourceIndexer.activationKey,new Boolean(true)); - - //Set the id of the source indexer extension point as a session property to allow - //index manager to instantiate it - //testProject.setSessionProperty(IndexManager.indexerIDKey, sourceIndexerID); - sourceIndexer = (DOMSourceIndexer) CCorePlugin.getDefault().getCoreModel().getIndexManager().getIndexerForProject(testProject); - } catch (CoreException e) {} - - resetIndexer(CCorePlugin.DEFAULT_INDEXER_UNIQ_ID); - //The DOM Source Indexer checks to see if a file has any scanner info - //set prior to indexing it in order to increase efficiency. We need to let it know - //that it is running in test mode in order to allow for this scanner info test to be skipped - DOMSourceIndexerRunner.setSkipScannerInfoTest(true); - - - if (testProject == null) - fail("Unable to create project"); - - //Create file manager - fileManager = new FileManager(); - - try { - //Add a file to the project - //importFile("mail.cpp", "resources/indexer/mail.cpp"); - importFile("classDecl.cpp", "resources/search/classDecl.cpp"); - importFile("include.h", "resources/search/include.h"); - } catch (Exception e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); - } - - - scope = SearchEngine.createWorkspaceScope(); - - resultCollector = new BasicSearchResultCollector(); - - searchEngine = new SearchEngine(); - } - - - - public BaseSearchTest(String name) { - super(name); - } - - protected void setUp() throws Exception { - - } - - protected void tearDown() { - } - - private IProject createProject(String projectName) throws CoreException { - ICProject cPrj = CProjectHelper.createCCProject(projectName, "bin"); - return cPrj.getProject(); - } - - private void importFile(String fileName, String resourceLocation) throws Exception{ - //Obtain file handle - file = testProject.getProject().getFile(fileName); - //Create file input stream - - if (!file.exists()){ - file.create(new FileInputStream( - CTestPlugin.getDefault().getFileInPlugin(new Path(resourceLocation))), - false,monitor); - fileManager.addFile(file); - } - - } - - protected char[] getSearchPattern(int meta_kind, int kind, int ref, String name) { - return Index.encodeEntry(meta_kind, kind, ref, name); - } - - public void assertEquals(char [] first, char [] second) { - assertEquals( new String(first), new String(second)); - } - - protected void search(IWorkspace workspace, ICSearchPattern pattern, ICSearchScope scope, ICSearchResultCollector collector) { - try { - searchEngine.search( workspace, pattern, scope, collector, false ); - } catch (InterruptedException e) { - - } - } - - public void resetIndexer(final String indexerId){ - if ( testProject != null) { - ICDescriptorOperation op = new ICDescriptorOperation() { - - public void execute(ICDescriptor descriptor, IProgressMonitor monitor) throws CoreException { - descriptor.remove(CCorePlugin.INDEXER_UNIQ_ID); - descriptor.create(CCorePlugin.INDEXER_UNIQ_ID,indexerId); - } - }; - try { - CCorePlugin.getDefault().getCDescriptorManager().runDescriptorOperation(testProject, op, new NullProgressMonitor()); - CCorePlugin.getDefault().getCoreModel().getIndexManager().indexerChangeNotification(testProject); - } catch (CoreException e) {} - } - } - -} diff --git a/core/org.eclipse.cdt.core.tests/search/org/eclipse/cdt/core/search/tests/ClassDeclarationPatternTests.java b/core/org.eclipse.cdt.core.tests/search/org/eclipse/cdt/core/search/tests/ClassDeclarationPatternTests.java deleted file mode 100644 index 5fadaf07369..00000000000 --- a/core/org.eclipse.cdt.core.tests/search/org/eclipse/cdt/core/search/tests/ClassDeclarationPatternTests.java +++ /dev/null @@ -1,287 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2003, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corp. - Rational Software - initial implementation - *******************************************************************************/ -/* - * Created on Jul 3, 2003 - */ -package org.eclipse.cdt.core.search.tests; - -import java.util.Iterator; -import java.util.Set; - -import org.eclipse.cdt.core.search.ICSearchConstants; -import org.eclipse.cdt.core.search.ICSearchPattern; -import org.eclipse.cdt.core.search.IMatch; -import org.eclipse.cdt.core.search.IOffsetLocatable; -import org.eclipse.cdt.core.search.OrPattern; -import org.eclipse.cdt.core.search.SearchEngine; -import org.eclipse.cdt.internal.core.CharOperation; -import org.eclipse.cdt.internal.core.index.IIndex; -import org.eclipse.cdt.internal.core.search.matching.ClassDeclarationPattern; - - -/** - * @author aniefer - * - * To change the template for this generated type comment go to - * Window>Preferences>Java>Code Generation>Code and Comments - */ -public class ClassDeclarationPatternTests extends BaseSearchTest implements ICSearchConstants { - - public ClassDeclarationPatternTests(String name) { - super(name); - } - - public void testMatchSimpleDeclaration(){ - ICSearchPattern pattern = SearchEngine.createSearchPattern( "A", TYPE, DEFINITIONS, false ); - - assertTrue( pattern instanceof ClassDeclarationPattern ); - - search( workspace, pattern, scope, resultCollector ); - - Set matches = resultCollector.getSearchResults(); - //Changed to 2 since we also return Derived as a Typdecl - assertEquals( 2, matches.size() ); - } - - public void testMatchNamespaceNestedDeclaration(){ - ICSearchPattern pattern = SearchEngine.createSearchPattern( "NS::B", TYPE, DEFINITIONS, true ); - - assertTrue( pattern instanceof ClassDeclarationPattern ); - - ClassDeclarationPattern clsPattern = (ClassDeclarationPattern)pattern; - - assertTrue( CharOperation.equals( new char[] { 'B' }, clsPattern.getName() ) ); - assertTrue( clsPattern.getContainingTypes().length == 1 ); - assertTrue( CharOperation.equals( new char[] { 'N', 'S' }, clsPattern.getContainingTypes()[0] ) ); - - search( workspace, pattern, scope, resultCollector ); - - Set matches = resultCollector.getSearchResults(); - assertEquals( 1, matches.size() ); - } - - public void testBug39652() { - ICSearchPattern pattern = SearchEngine.createSearchPattern( "A::B", TYPE, DEFINITIONS, true ); - - search( workspace, pattern, scope, resultCollector ); - Set matches = resultCollector.getSearchResults(); - - /* Test should find 1 match */ - assertTrue( matches != null ); - assertTrue( matches.size() == 1 ); - - pattern = SearchEngine.createSearchPattern( "NS::NS2::a", TYPE, DEFINITIONS, true ); - search( workspace, pattern, scope, resultCollector ); - - matches = resultCollector.getSearchResults(); - assertTrue( matches != null ); - - pattern = SearchEngine.createSearchPattern( "NS::B::AA", TYPE, DEFINITIONS, true ); //TODO was NS::B::A, changed for bug 41445 - search( workspace, pattern, scope, resultCollector ); - - matches = resultCollector.getSearchResults(); - assertTrue( matches != null ); - } - - public void testMatchStruct(){ - ICSearchPattern pattern = SearchEngine.createSearchPattern( "AA", STRUCT, DEFINITIONS, true ); //TODO was A, changed for bug 41445 - - assertTrue( pattern instanceof ClassDeclarationPattern ); - - search( workspace, pattern, scope, resultCollector ); - - Set matches = resultCollector.getSearchResults(); - assertEquals( matches.size(), 1 ); - - pattern = SearchEngine.createSearchPattern( "NS::B::AA", TYPE, DEFINITIONS, true ); //TODO was 2, changed for bug 41445 - search( workspace, pattern, scope, resultCollector ); - - Set matches2 = resultCollector.getSearchResults(); - assertTrue( matches2 != null ); - assertEquals( matches2.size(), 1 ); - - Iterator iter = matches.iterator(); - Iterator iter2 = matches2.iterator(); - - IMatch match = (IMatch)iter.next(); - IMatch match2 = (IMatch)iter2.next(); - - //assertTrue( match.path.equals( match2.path ) ); - assertEquals( ((IOffsetLocatable) match.getLocatable()).getNameStartOffset(), ((IOffsetLocatable) match2.getLocatable()).getNameStartOffset() ); - assertEquals( ((IOffsetLocatable) match.getLocatable()).getNameEndOffset() , ((IOffsetLocatable) match2.getLocatable()).getNameEndOffset() ); - } - - public void testWildcardQualification() { - ICSearchPattern pattern = SearchEngine.createSearchPattern( "::*::A", TYPE, DEFINITIONS, true ); - search( workspace, pattern, scope, resultCollector ); - - Set matches = resultCollector.getSearchResults(); - assertEquals( matches.size(), 0 ); - - pattern = SearchEngine.createSearchPattern( "NS::*::A", TYPE, DEFINITIONS, false ); - search( workspace, pattern, scope, resultCollector ); - - matches = resultCollector.getSearchResults(); - assertEquals( matches.size(), 1 ); //TODO was 1, changed for bug 41445 - } - - public void testElaboratedType(){ - ICSearchPattern pattern = SearchEngine.createSearchPattern( "struct AA", TYPE, DEFINITIONS, true ); //TODO was 2, changed for bug 41445 - search( workspace, pattern, scope, resultCollector ); - - Set matches = resultCollector.getSearchResults(); - assertEquals( matches.size(), 1 ); - - pattern = SearchEngine.createSearchPattern( "union u", TYPE, DEFINITIONS, true ); - search( workspace, pattern, scope, resultCollector ); - - matches = resultCollector.getSearchResults(); - assertEquals( matches.size(), 2 ); - - pattern = SearchEngine.createSearchPattern( "union ::*::u", TYPE, DEFINITIONS, true ); - search( workspace, pattern, scope, resultCollector ); - - matches = resultCollector.getSearchResults(); - assertEquals( matches.size(), 1 ); - } - - public void testClassIndexPrefix(){ - ICSearchPattern pattern = SearchEngine.createSearchPattern( "struct A::B::*::c", TYPE, DECLARATIONS, true ); - assertTrue( pattern instanceof ClassDeclarationPattern ); - - ClassDeclarationPattern clsPattern = (ClassDeclarationPattern)pattern; - assertEquals( getSearchPattern(IIndex.TYPE, IIndex.TYPE_STRUCT, IIndex.DECLARATION, "c/"), clsPattern.indexEntryPrefix()); - - clsPattern = (ClassDeclarationPattern) SearchEngine.createSearchPattern( "class ::*::A::B::c", TYPE, DECLARATIONS, true ); - assertEquals( getSearchPattern(IIndex.TYPE, IIndex.TYPE_CLASS, IIndex.DECLARATION, "c/B/A/"), clsPattern.indexEntryPrefix()); - - clsPattern = (ClassDeclarationPattern) SearchEngine.createSearchPattern( "enum ::RT*::c", TYPE, REFERENCES, true ); - assertEquals( getSearchPattern(IIndex.TYPE, IIndex.TYPE_ENUM, IIndex.REFERENCE,"c/RT"), clsPattern.indexEntryPrefix()); - - clsPattern = (ClassDeclarationPattern) SearchEngine.createSearchPattern( "union A::B::c", TYPE, REFERENCES, false ); - assertEquals( getSearchPattern(IIndex.TYPE, IIndex.TYPE_UNION, IIndex.REFERENCE, ""), clsPattern.indexEntryPrefix()); - } - - public void testGloballyQualifiedItem(){ - ICSearchPattern pattern = SearchEngine.createSearchPattern( "::A", TYPE, DEFINITIONS, true ); - assertTrue( pattern instanceof ClassDeclarationPattern ); - - search( workspace, pattern, scope, resultCollector ); - - Set matches = resultCollector.getSearchResults(); - assertEquals( matches.size(), 1 ); - - pattern = SearchEngine.createSearchPattern( "::u", TYPE, DEFINITIONS, true ); - assertTrue( pattern instanceof ClassDeclarationPattern ); - - search( workspace, pattern, scope, resultCollector ); - - matches = resultCollector.getSearchResults(); - - assertEquals( matches.size(), 1); - } - - public void testClassReferences(){ - ICSearchPattern pattern = SearchEngine.createSearchPattern( "::A", TYPE, REFERENCES, true ); - - search( workspace, pattern, scope, resultCollector ); - - Set matches = resultCollector.getSearchResults(); - assertEquals( 6, matches.size()); - } - - public void testClassReferenceInFieldType(){ - ICSearchPattern pattern = SearchEngine.createSearchPattern( "::NS::B::AA", TYPE, REFERENCES, true ); //TODO was A, changed for bug 41445 - - search( workspace, pattern, scope, resultCollector ); - - Set matches = resultCollector.getSearchResults(); - assertEquals( matches.size(), 1 ); - } - - public void testTypeReferenceVisibleByUsingDirective(){ - ICSearchPattern pattern = SearchEngine.createSearchPattern( "::NS::NS2::a", STRUCT, REFERENCES, true ); - - search( workspace, pattern, scope, resultCollector ); - Set matches = resultCollector.getSearchResults(); - assertEquals( matches.size(), 1 ); - } - - public void testEnumerationReferenceVisibleByInheritance(){ - ICSearchPattern pattern = SearchEngine.createSearchPattern( "::NS::B::e", ENUM, REFERENCES, true ); - - search( workspace, pattern, scope, resultCollector ); - - Set matches = resultCollector.getSearchResults(); - assertEquals( matches.size(), 1 ); - } - - public void testHeadersVisitedTwice(){ - ICSearchPattern pattern = SearchEngine.createSearchPattern( "Hea*", CLASS, DEFINITIONS, true ); - - search( workspace, pattern, scope, resultCollector ); - - Set matches = resultCollector.getSearchResults(); - - //1 for Heal, 1 for Head - assertEquals( matches.size(), 2 ); - } - - public void testAllOccurences(){ - ICSearchPattern pattern = SearchEngine.createSearchPattern( "A", TYPE, ALL_OCCURRENCES, true ); - assertTrue( pattern instanceof OrPattern ); - - search( workspace, pattern, scope, resultCollector ); - - Set matches = resultCollector.getSearchResults(); - - assertEquals(8, matches.size() ); - } - - public void testReferencesInFunction(){ - ICSearchPattern pattern = SearchEngine.createSearchPattern( "AClassForFoo", CLASS, REFERENCES, true ); - - search( workspace, pattern, scope, resultCollector ); - Set matches = resultCollector.getSearchResults(); - assertEquals( matches.size(), 3 ); - - Iterator iter = matches.iterator(); - - while( iter.hasNext() ){ - IMatch match = (IMatch) iter.next(); - assertTrue( match.getName().equals("AClassForFoo") ); - } - } - - public void testbug42902_TypeDefs(){ - ICSearchPattern pattern = SearchEngine.createSearchPattern("NS_B", TYPEDEF, ALL_OCCURRENCES, true ); - - search( workspace, pattern, scope, resultCollector ); - Set matches = resultCollector.getSearchResults(); - - assertEquals( matches.size(), 2 ); - } - -/* public void testBug54169(){ - ICSearchPattern pattern = SearchEngine.createSearchPattern( "e", TYPE, DECLARATIONS, true ); - search( workspace, pattern, scope, resultCollector ); - Set matches = resultCollector.getSearchResults(); - - assertEquals( matches.size(), 1 ); - - pattern = SearchEngine.createSearchPattern( "NS_B", TYPE, DECLARATIONS, true ); - search( workspace, pattern, scope, resultCollector ); - matches = resultCollector.getSearchResults(); - - assertEquals( matches.size(), 1 ); - }*/ -} - diff --git a/core/org.eclipse.cdt.core.tests/search/org/eclipse/cdt/core/search/tests/FunctionMethodPatternTests.java b/core/org.eclipse.cdt.core.tests/search/org/eclipse/cdt/core/search/tests/FunctionMethodPatternTests.java deleted file mode 100644 index a2c683d8664..00000000000 --- a/core/org.eclipse.cdt.core.tests/search/org/eclipse/cdt/core/search/tests/FunctionMethodPatternTests.java +++ /dev/null @@ -1,256 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2003, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corp. - Rational Software - initial implementation - *******************************************************************************/ -/* - * Created on Jul 23, 2003 - */ -package org.eclipse.cdt.core.search.tests; - -import java.util.Set; - -import org.eclipse.cdt.core.search.ICSearchPattern; -import org.eclipse.cdt.core.search.IMatch; -import org.eclipse.cdt.core.search.IOffsetLocatable; -import org.eclipse.cdt.core.search.SearchEngine; -import org.eclipse.cdt.internal.core.CharOperation; -import org.eclipse.cdt.internal.core.index.IIndex; -import org.eclipse.cdt.internal.core.search.matching.MethodDeclarationPattern; - -/** - * @author aniefer - * - * To change the template for this generated type comment go to - * Window>Preferences>Java>Code Generation>Code and Comments - */ -public class FunctionMethodPatternTests extends BaseSearchTest { - - /** - * @param name - */ - public FunctionMethodPatternTests(String name) { - super(name); - // TODO Auto-generated constructor stub - } - - public void testFunctionIndexPrefix(){ - ICSearchPattern pattern = SearchEngine.createSearchPattern( "c()", FUNCTION, DECLARATIONS, true ); //$NON-NLS-1$ - - MethodDeclarationPattern functionPattern = (MethodDeclarationPattern)pattern; - assertEquals( getSearchPattern(IIndex.FUNCTION, IIndex.ANY, IIndex.DECLARATION, "c"), functionPattern.indexEntryPrefix() ); //$NON-NLS-1$ - - functionPattern = (MethodDeclarationPattern) SearchEngine.createSearchPattern( "rt*()", FUNCTION, DECLARATIONS, true ); //$NON-NLS-1$ - assertEquals( getSearchPattern(IIndex.FUNCTION, IIndex.ANY, IIndex.DECLARATION, "rt"), functionPattern.indexEntryPrefix()); //$NON-NLS-1$ - - functionPattern = (MethodDeclarationPattern) SearchEngine.createSearchPattern( "Ac", FUNCTION, REFERENCES, false ); //$NON-NLS-1$ - assertEquals( getSearchPattern(IIndex.FUNCTION, IIndex.ANY, IIndex.REFERENCE, ""), functionPattern.indexEntryPrefix()); //$NON-NLS-1$ - } - - public void testMethodIndexPrefix(){ - ICSearchPattern pattern = SearchEngine.createSearchPattern( "A::B::c", METHOD, DECLARATIONS, true ); //$NON-NLS-1$ - assertTrue( pattern instanceof MethodDeclarationPattern ); - - MethodDeclarationPattern methodPattern = (MethodDeclarationPattern)pattern; - assertEquals( getSearchPattern(IIndex.METHOD, IIndex.ANY, IIndex.DECLARATION, "c/B/A"), methodPattern.indexEntryPrefix()); //$NON-NLS-1$ - - methodPattern = (MethodDeclarationPattern) SearchEngine.createSearchPattern( "::*::A::B::c", METHOD, DECLARATIONS, true ); //$NON-NLS-1$ - assertEquals( getSearchPattern(IIndex.METHOD, IIndex.ANY, IIndex.DECLARATION, "c/B/A/"), methodPattern.indexEntryPrefix()); //$NON-NLS-1$ - - methodPattern = (MethodDeclarationPattern) SearchEngine.createSearchPattern( "::RT*::c", METHOD, REFERENCES, true ); //$NON-NLS-1$ - assertEquals( getSearchPattern(IIndex.METHOD, IIndex.ANY, IIndex.REFERENCE, "c/RT"), methodPattern.indexEntryPrefix()); //$NON-NLS-1$ - - methodPattern = (MethodDeclarationPattern) SearchEngine.createSearchPattern( "A::B::c", METHOD, REFERENCES, false ); //$NON-NLS-1$ - assertEquals( getSearchPattern(IIndex.METHOD, IIndex.ANY, IIndex.REFERENCE, ""), methodPattern.indexEntryPrefix()); //$NON-NLS-1$ - } - - public void testMethodDeclaration() { - ICSearchPattern pattern = SearchEngine.createSearchPattern( "A::B::f", METHOD, DECLARATIONS, true ); //$NON-NLS-1$ - - search( workspace, pattern, scope, resultCollector ); - - Set matches = resultCollector.getSearchResults(); - - assertEquals( matches.size(), 4 ); - } - - public void testMethodDeclarationWithParams() { - ICSearchPattern pattern = SearchEngine.createSearchPattern( "A::B::f( A )", METHOD, DECLARATIONS, true ); //$NON-NLS-1$ - - search( workspace, pattern, scope, resultCollector ); - - Set matches = resultCollector.getSearchResults(); - - assertEquals( 1, matches.size()); - } - - public void testMethodDeclarationParameterMatching(){ - ICSearchPattern pattern = SearchEngine.createSearchPattern( "f( A & )", METHOD, DECLARATIONS, true ); //$NON-NLS-1$ - - search( workspace, pattern, scope, resultCollector ); - Set matches = resultCollector.getSearchResults(); - assertEquals( 1,matches.size() ); - - pattern = SearchEngine.createSearchPattern( "f( A * )", METHOD, DECLARATIONS, true ); //$NON-NLS-1$ - search( workspace, pattern, scope, resultCollector ); - matches = resultCollector.getSearchResults(); - assertEquals( 1, matches.size()); - - pattern = SearchEngine.createSearchPattern( "f( int &, const char [], A** )", METHOD, DECLARATIONS, true ); //$NON-NLS-1$ - search( workspace, pattern, scope, resultCollector ); - matches = resultCollector.getSearchResults(); - assertEquals( 1, matches.size() ); - } - - public void testMethodWithNoParameters(){ - ICSearchPattern pattern = SearchEngine.createSearchPattern( "turn( )", METHOD, DECLARATIONS, true ); //$NON-NLS-1$ - - search( workspace, pattern, scope, resultCollector ); - Set matches = resultCollector.getSearchResults(); - assertEquals( 2, matches.size()); - - pattern = SearchEngine.createSearchPattern( "turn(void)", METHOD, DECLARATIONS_DEFINITIONS, true ); //$NON-NLS-1$ - - search( workspace, pattern, scope, resultCollector ); - matches = resultCollector.getSearchResults(); - assertEquals( 2, matches.size()); - - pattern = SearchEngine.createSearchPattern( "turnAgain()", METHOD, DECLARATIONS, true ); //$NON-NLS-1$ - - search( workspace, pattern, scope, resultCollector ); - matches = resultCollector.getSearchResults(); - assertEquals( 1, matches.size()); - - } - - public void testOperators_bug43063_bug42979(){ - ICSearchPattern pattern = SearchEngine.createSearchPattern( "operator \\*", METHOD, DECLARATIONS_DEFINITIONS, true ); //$NON-NLS-1$ - - search( workspace, pattern, scope, resultCollector ); - Set matches = resultCollector.getSearchResults(); - assertEquals( matches.size(), 1 ); - IMatch match1 = (IMatch) matches.iterator().next(); - - pattern = SearchEngine.createSearchPattern( "operator \\*", METHOD, DEFINITIONS, true ); //$NON-NLS-1$ - search( workspace, pattern, scope, resultCollector ); - matches = resultCollector.getSearchResults(); - assertEquals( matches.size(), 1 ); - IMatch match2 = (IMatch) matches.iterator().next(); - - assertTrue( ((IOffsetLocatable)match1.getLocatable()).getNameStartOffset() == ((IOffsetLocatable)match2.getLocatable()).getNameStartOffset() ); - - pattern = SearchEngine.createSearchPattern( "operator \\*=", METHOD, DECLARATIONS, true ); //$NON-NLS-1$ - search( workspace, pattern, scope, resultCollector ); - matches = resultCollector.getSearchResults(); - assertEquals( matches.size(), 1 ); - match1 = (IMatch) matches.iterator().next(); - - pattern = SearchEngine.createSearchPattern( "operator \\*=", METHOD, DEFINITIONS, true ); //$NON-NLS-1$ - search( workspace, pattern, scope, resultCollector ); - matches = resultCollector.getSearchResults(); - assertEquals( matches.size(), 1 ); - match2 = (IMatch) matches.iterator().next(); - - assertTrue( ((IOffsetLocatable)match1.getLocatable()).getNameStartOffset() != ((IOffsetLocatable)match2.getLocatable()).getNameStartOffset() ); - - pattern = SearchEngine.createSearchPattern( "operator *", METHOD, DECLARATIONS, true ); //$NON-NLS-1$ - search( workspace, pattern, scope, resultCollector ); - matches = resultCollector.getSearchResults(); - assertEquals( matches.size(), 5 ); - - pattern = SearchEngine.createSearchPattern( "operator *", METHOD, DECLARATIONS_DEFINITIONS, true ); //$NON-NLS-1$ - search( workspace, pattern, scope, resultCollector ); - matches = resultCollector.getSearchResults(); - assertEquals( matches.size(), 8 ); //2 in classDecl.cpp - - pattern = SearchEngine.createSearchPattern( "operator ->\\*", METHOD, DECLARATIONS, true ); //$NON-NLS-1$ - assertTrue( pattern instanceof MethodDeclarationPattern ); - MethodDeclarationPattern methodPattern = (MethodDeclarationPattern) pattern; - char [] string = new char[] {'o','p','e','r','a','t','o','r',' ','-','>','\\','*'}; - assertTrue( CharOperation.equals( string, methodPattern.getSimpleName() ) ); - } - - public void testBug43498(){ - ICSearchPattern pattern = SearchEngine.createSearchPattern( "operator ?elete", METHOD, DECLARATIONS, true ); //$NON-NLS-1$ - - assertTrue( pattern instanceof MethodDeclarationPattern ); - MethodDeclarationPattern methodPattern = (MethodDeclarationPattern) pattern; - - char [] string = new char[] {'o','p','e','r','a','t','o','r',' ','?','e','l','e','t','e'}; - assertTrue( CharOperation.equals( string, methodPattern.getSimpleName() ) ); - - pattern = SearchEngine.createSearchPattern( "operator delete", METHOD, DECLARATIONS, true ); //$NON-NLS-1$ - assertTrue( pattern instanceof MethodDeclarationPattern ); - methodPattern = (MethodDeclarationPattern) pattern; - string = new char[] {'o','p','e','r','a','t','o','r',' ','d','e','l','e','t','e'}; - assertTrue( CharOperation.equals( string, methodPattern.getSimpleName() ) ); - - pattern = SearchEngine.createSearchPattern( "word?word", METHOD, DECLARATIONS, true ); //$NON-NLS-1$ - assertTrue( pattern instanceof MethodDeclarationPattern ); - methodPattern = (MethodDeclarationPattern) pattern; - - string = new char[] {'w','o','r','d','?','w','o','r','d'}; - assertTrue( CharOperation.equals( string, methodPattern.getSimpleName() ) ); - - pattern = SearchEngine.createSearchPattern( "operato? delete", METHOD, DECLARATIONS, true ); //$NON-NLS-1$ - assertTrue( pattern instanceof MethodDeclarationPattern ); - methodPattern = (MethodDeclarationPattern) pattern; - string = new char[] {'o','p','e','r','a','t','o','?',' ','d','e','l','e','t','e'}; - assertTrue( CharOperation.equals( string, methodPattern.getSimpleName() ) ); - } - - public void testBug43062(){ - MethodDeclarationPattern pattern = (MethodDeclarationPattern) SearchEngine.createSearchPattern( "operator const short &", METHOD, DECLARATIONS, true ); //$NON-NLS-1$ - char [] string = new char [] { 'o','p','e','r','a','t','o','r',' ','c','o','n','s','t',' ','s','h','o','r','t',' ','&' }; - assertTrue( CharOperation.equals( string, pattern.getSimpleName() ) ); - - pattern = (MethodDeclarationPattern) SearchEngine.createSearchPattern( "operator short", METHOD, DECLARATIONS, true ); //$NON-NLS-1$ - string = new char [] { 'o','p','e','r','a','t','o','r',' ','s','h','o','r','t' }; - assertTrue( CharOperation.equals( string, pattern.getSimpleName() ) ); - - pattern = (MethodDeclarationPattern) SearchEngine.createSearchPattern( "operator short int", METHOD, DECLARATIONS, true ); //$NON-NLS-1$ - string = new char [] { 'o','p','e','r','a','t','o','r',' ','s','h','o','r','t',' ','i','n','t' }; - assertTrue( CharOperation.equals( string, pattern.getSimpleName() ) ); - } - - public void testConstructorDestructor(){ - ICSearchPattern pattern = SearchEngine.createSearchPattern( "A", METHOD, DECLARATIONS_DEFINITIONS, true ); //$NON-NLS-1$ - search( workspace, pattern, scope, resultCollector ); - - Set matches = resultCollector.getSearchResults(); - assertEquals( matches.size(), 1 ); - - pattern = SearchEngine.createSearchPattern( "~A", METHOD, DECLARATIONS_DEFINITIONS, true ); //$NON-NLS-1$ - search( workspace, pattern, scope, resultCollector ); - - matches = resultCollector.getSearchResults(); - assertEquals( matches.size(), 1 ); - } - - public void testLookupForDefinition(){ - ICSearchPattern pattern = SearchEngine.createSearchPattern( "turn", METHOD, DECLARATIONS_DEFINITIONS, true ); //$NON-NLS-1$ - search( workspace, pattern, scope, resultCollector ); - Set matches = resultCollector.getSearchResults(); - assertEquals( matches.size(), 3 ); - - pattern = SearchEngine.createSearchPattern( "Direction::turn", METHOD, DEFINITIONS, true ); //$NON-NLS-1$ - search( workspace, pattern, scope, resultCollector ); - matches = resultCollector.getSearchResults(); - assertEquals( matches.size(), 0 ); - } - - public void testBug63478(){ - ICSearchPattern pattern = SearchEngine.createSearchPattern( "A::B::f(*)", METHOD, DECLARATIONS, true ); //$NON-NLS-1$ - - search( workspace, pattern, scope, resultCollector ); - - Set matches = resultCollector.getSearchResults(); - - assertEquals( matches.size(), 4 ); - } -} diff --git a/core/org.eclipse.cdt.core.tests/search/org/eclipse/cdt/core/search/tests/OtherPatternTests.java b/core/org.eclipse.cdt.core.tests/search/org/eclipse/cdt/core/search/tests/OtherPatternTests.java deleted file mode 100644 index 0c6ea282bb5..00000000000 --- a/core/org.eclipse.cdt.core.tests/search/org/eclipse/cdt/core/search/tests/OtherPatternTests.java +++ /dev/null @@ -1,368 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2003, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corp. - Rational Software - initial implementation - *******************************************************************************/ -/* - * Created on Jul 23, 2003 - */ -package org.eclipse.cdt.core.search.tests; - - -import java.util.Set; - -import org.eclipse.cdt.core.search.BasicSearchMatch; -import org.eclipse.cdt.core.search.ICSearchPattern; -import org.eclipse.cdt.core.search.IMatch; -import org.eclipse.cdt.core.search.SearchEngine; -import org.eclipse.cdt.core.testplugin.CTestPlugin; -import org.eclipse.cdt.internal.core.index.IIndex; -import org.eclipse.cdt.internal.core.search.matching.FieldDeclarationPattern; -import org.eclipse.cdt.internal.core.search.matching.MatchLocator; -import org.eclipse.cdt.internal.core.search.matching.NamespaceDeclarationPattern; -import org.eclipse.core.runtime.Path; - -/** - * @author aniefer - * - * To change the template for this generated type comment go to - * Window>Preferences>Java>Code Generation>Code and Comments - */ -public class OtherPatternTests extends BaseSearchTest { - - /** - * @param name - */ - public OtherPatternTests(String name) { - super(name); - // TODO Auto-generated constructor stub - } - - public void testNamespaceIndexPrefix(){ - ICSearchPattern pattern = SearchEngine.createSearchPattern( "A::B::c", NAMESPACE, DEFINITIONS, true ); //$NON-NLS-1$ - assertTrue( pattern instanceof NamespaceDeclarationPattern ); - - NamespaceDeclarationPattern nsPattern = (NamespaceDeclarationPattern)pattern; - assertEquals( getSearchPattern(IIndex.NAMESPACE, IIndex.ANY, IIndex.DEFINITION, "c/B/A"), nsPattern.indexEntryPrefix() ); //$NON-NLS-1$ - - nsPattern = (NamespaceDeclarationPattern) SearchEngine.createSearchPattern( "::*::A::B::c", NAMESPACE, DEFINITIONS, true ); //$NON-NLS-1$ - assertEquals( getSearchPattern(IIndex.NAMESPACE, IIndex.ANY, IIndex.DEFINITION, "c/B/A/"), nsPattern.indexEntryPrefix() ); //$NON-NLS-1$ - - nsPattern = (NamespaceDeclarationPattern) SearchEngine.createSearchPattern( "::RT*::c", NAMESPACE, REFERENCES, true ); //$NON-NLS-1$ - assertEquals( getSearchPattern(IIndex.NAMESPACE, IIndex.ANY, IIndex.REFERENCE, "c/RT"), nsPattern.indexEntryPrefix() ); //$NON-NLS-1$ - - nsPattern = (NamespaceDeclarationPattern) SearchEngine.createSearchPattern( "A::B::c", NAMESPACE, REFERENCES, false ); //$NON-NLS-1$ - assertEquals( getSearchPattern(IIndex.NAMESPACE, IIndex.ANY, IIndex.REFERENCE, ""), nsPattern.indexEntryPrefix() ); //$NON-NLS-1$ - } - - public void testVariableIndexPrefix(){ - ICSearchPattern pattern = SearchEngine.createSearchPattern( "c", VAR, DECLARATIONS, true ); //$NON-NLS-1$ - assertTrue( pattern instanceof FieldDeclarationPattern ); - - FieldDeclarationPattern variablePattern = (FieldDeclarationPattern)pattern; - assertEquals( getSearchPattern(IIndex.VAR, IIndex.ANY, IIndex.DECLARATION, "c"), variablePattern.indexEntryPrefix() ); //$NON-NLS-1$ - - variablePattern = (FieldDeclarationPattern) SearchEngine.createSearchPattern( "rt*", VAR, DECLARATIONS, true ); //$NON-NLS-1$ - assertEquals( getSearchPattern(IIndex.VAR, IIndex.ANY, IIndex.DECLARATION, "rt"), variablePattern.indexEntryPrefix() ); //$NON-NLS-1$ - - variablePattern = (FieldDeclarationPattern) SearchEngine.createSearchPattern( "Ac", VAR, REFERENCES, false ); //$NON-NLS-1$ - assertEquals( getSearchPattern(IIndex.VAR, IIndex.ANY, IIndex.REFERENCE, ""), variablePattern.indexEntryPrefix() ); //$NON-NLS-1$ - - variablePattern = (FieldDeclarationPattern) SearchEngine.createSearchPattern( "A?c", VAR, REFERENCES, true ); //$NON-NLS-1$ - assertEquals( getSearchPattern(IIndex.VAR, IIndex.ANY, IIndex.REFERENCE, "A"), variablePattern.indexEntryPrefix() ); //$NON-NLS-1$ - } - - public void testFieldIndexPrefix(){ - ICSearchPattern pattern = SearchEngine.createSearchPattern( "A::B::c", FIELD, DECLARATIONS, true ); //$NON-NLS-1$ - assertTrue( pattern instanceof FieldDeclarationPattern ); - - FieldDeclarationPattern fieldPattern = (FieldDeclarationPattern)pattern; - assertEquals( getSearchPattern(IIndex.FIELD, IIndex.ANY, IIndex.DECLARATION, "c/B/A"), fieldPattern.indexEntryPrefix() ); //$NON-NLS-1$ - - fieldPattern = (FieldDeclarationPattern) SearchEngine.createSearchPattern( "::*::A::B::c", FIELD, DECLARATIONS, true ); //$NON-NLS-1$ - assertEquals( getSearchPattern(IIndex.FIELD, IIndex.ANY, IIndex.DECLARATION, "c/B/A/"), fieldPattern.indexEntryPrefix() ); //$NON-NLS-1$ - - fieldPattern = (FieldDeclarationPattern) SearchEngine.createSearchPattern( "::RT*::c", FIELD, REFERENCES, true ); //$NON-NLS-1$ - assertEquals( getSearchPattern(IIndex.FIELD, IIndex.ANY, IIndex.REFERENCE, "c/RT"), fieldPattern.indexEntryPrefix() ); //$NON-NLS-1$ - - fieldPattern = (FieldDeclarationPattern) SearchEngine.createSearchPattern( "A::B::c", FIELD, REFERENCES, false ); //$NON-NLS-1$ - assertEquals( getSearchPattern(IIndex.FIELD, IIndex.ANY, IIndex.REFERENCE, ""), fieldPattern.indexEntryPrefix() ); //$NON-NLS-1$ - } - - public void testNamespaceDeclaration(){ - ICSearchPattern pattern = SearchEngine.createSearchPattern( "NS*", NAMESPACE, DEFINITIONS, true ); //$NON-NLS-1$ - - search( workspace, pattern, scope, resultCollector ); - - Set matches = resultCollector.getSearchResults(); - - assertEquals( matches.size(), 3 ); - } - - public void testNamespaceReferenceInUsingDirective() { - ICSearchPattern pattern = SearchEngine.createSearchPattern( "::NS::NS2", NAMESPACE, REFERENCES, true ); //$NON-NLS-1$ - - search( workspace, pattern, scope, resultCollector ); - - Set matches = resultCollector.getSearchResults(); - - assertEquals( matches.size(), 1 ); - } - - public void testNamespaceReferenceInClassBaseClause(){ - ICSearchPattern pattern = SearchEngine.createSearchPattern( "::NS", NAMESPACE, REFERENCES, true ); //$NON-NLS-1$ - - search( workspace, pattern, scope, resultCollector ); - - Set matches = resultCollector.getSearchResults(); - assertEquals( matches.size(), 2 ); - } - - public void testFieldDeclaration(){ - ICSearchPattern pattern = SearchEngine.createSearchPattern( "a*Struct", FIELD, DEFINITIONS, true ); //$NON-NLS-1$ - - search( workspace, pattern, scope, resultCollector ); - - Set matches = resultCollector.getSearchResults(); - assertEquals( matches.size(), 1 ); - } - - public void testVariableDeclaration(){ - ICSearchPattern pattern = SearchEngine.createSearchPattern( "b?", VAR, DEFINITIONS, true ); //$NON-NLS-1$ - - search( workspace, pattern, scope, resultCollector ); - - Set matches = resultCollector.getSearchResults(); - assertEquals( matches.size(), 2 ); - - IMatch match = (IMatch) matches.iterator().next(); - assertTrue( match.getParentName().equals( "" ) ); //$NON-NLS-1$ - } - - /*public void testParameterDeclaration(){ - ICSearchPattern pattern = SearchEngine.createSearchPattern( "index", VAR, DECLARATIONS, true ); //$NON-NLS-1$ - - search( workspace, pattern, scope, resultCollector ); - - Set matches = resultCollector.getSearchResults(); - assertEquals( 5, matches.size()); - } - - public void testOrPattern(){ - OrPattern orPattern = new OrPattern(); - orPattern.addPattern( SearchEngine.createSearchPattern( "::NS::B::e", ENUM, REFERENCES, true ) ); //$NON-NLS-1$ - orPattern.addPattern( SearchEngine.createSearchPattern( "Hea*", CLASS, DECLARATIONS, true ) ); //$NON-NLS-1$ - - search( workspace, orPattern, scope, resultCollector ); - - Set matches = resultCollector.getSearchResults(); - - assertEquals( matches.size(), 3 ); - - orPattern = new OrPattern(); - orPattern.addPattern( SearchEngine.createSearchPattern( "b?", VAR, DECLARATIONS, true ) ); //$NON-NLS-1$ - orPattern.addPattern( SearchEngine.createSearchPattern( "a*Struct", FIELD, DECLARATIONS, true ) ); //$NON-NLS-1$ - orPattern.addPattern( SearchEngine.createSearchPattern( "::NS::NS2", NAMESPACE, REFERENCES, true ) ); //$NON-NLS-1$ - orPattern.addPattern( SearchEngine.createSearchPattern( "A::B::f( A )", METHOD, DECLARATIONS, true ) ); //$NON-NLS-1$ - - search( workspace, orPattern, scope, resultCollector ); - matches = resultCollector.getSearchResults(); - assertEquals( 5, matches.size() ); - }*/ - - public void testMacroPattern(){ - ICSearchPattern pattern = SearchEngine.createSearchPattern( "FOO", MACRO, DECLARATIONS, true ); //$NON-NLS-1$ - - search( workspace, pattern, scope, resultCollector ); - - Set matches = resultCollector.getSearchResults(); - assertEquals( matches.size(), 1 ); - - IMatch match = (IMatch) matches.iterator().next(); - assertTrue( match.getName().equals( "FOO" ) ); //$NON-NLS-1$ - assertTrue( match.getParentName().equals( "" )); //$NON-NLS-1$ - - pattern = SearchEngine.createSearchPattern( "FOO", MACRO, ALL_OCCURRENCES, true ); //$NON-NLS-1$ - search( workspace, pattern, scope, resultCollector ); - matches = resultCollector.getSearchResults(); - assertEquals( matches.size(), 1 ); - } - - public void testDerived(){ - ICSearchPattern pattern = SearchEngine.createSearchPattern( "A", DERIVED, DECLARATIONS, true ); //$NON-NLS-1$ - search( workspace, pattern, scope, resultCollector ); - - Set matches = resultCollector.getSearchResults(); - assertEquals( matches.size(), 1 ); - IMatch match = (IMatch) matches.iterator().next(); - assertTrue( match.getName().equals( "A" ) ); //$NON-NLS-1$ - } - - public void testEnumerators(){ - ICSearchPattern pattern = SearchEngine.createSearchPattern( "One", ENUMTOR, DEFINITIONS, true ); //$NON-NLS-1$ - - search( workspace, pattern, scope, resultCollector ); - - Set matches = resultCollector.getSearchResults(); - assertEquals( matches.size(), 1 ); - IMatch match = (IMatch) matches.iterator().next(); - assertTrue( match.getName().equals( "One" ) ); //$NON-NLS-1$ - - pattern = SearchEngine.createSearchPattern( "NS::B::Two", ENUMTOR, DEFINITIONS, true ); //$NON-NLS-1$ - - search( workspace, pattern, scope, resultCollector ); - - matches = resultCollector.getSearchResults(); - assertEquals( matches.size(), 1 ); - match = (IMatch) matches.iterator().next(); - assertTrue( match.getName().equals( "Two" ) ); //$NON-NLS-1$ - } - - public void testEnumeratorReferences(){ - ICSearchPattern pattern = SearchEngine.createSearchPattern( "One", ENUMTOR, REFERENCES, true ); //$NON-NLS-1$ - - search( workspace, pattern, scope, resultCollector ); - - Set matches = resultCollector.getSearchResults(); - assertEquals( matches.size(), 1 ); - - IMatch match = (IMatch) matches.iterator().next(); - assertTrue( match.getName().equals( "One" ) ); //$NON-NLS-1$ - } - - /*public void testParameterReferences(){ - ICSearchPattern pattern = SearchEngine.createSearchPattern( "index", VAR, REFERENCES, true ); //$NON-NLS-1$ - - search( workspace, pattern, scope, resultCollector ); - - Set matches = resultCollector.getSearchResults(); - assertEquals( matches.size(), 3 ); - }*/ - - - /*public void testBug43129(){ - ICSearchPattern pattern = SearchEngine.createSearchPattern( "externalInt", VAR, DECLARATIONS, true ); //$NON-NLS-1$ - search( workspace, pattern, scope, resultCollector ); - Set matches = resultCollector.getSearchResults(); - assertEquals( matches.size(), 1 ); - - pattern = SearchEngine.createSearchPattern( "externalIntWithInitializer", VAR, DEFINITIONS, true ); //$NON-NLS-1$ - search( workspace, pattern, scope, resultCollector ); - matches = resultCollector.getSearchResults(); - assertEquals( matches.size(), 1 ); - - pattern = SearchEngine.createSearchPattern( "externCInt", VAR, DEFINITIONS, true ); //$NON-NLS-1$ - search( workspace, pattern, scope, resultCollector ); - matches = resultCollector.getSearchResults(); - assertEquals( matches.size(), 1 ); - - pattern = SearchEngine.createSearchPattern( "externCIntWithInitializer", VAR, DEFINITIONS, true ); //$NON-NLS-1$ - search( workspace, pattern, scope, resultCollector ); - matches = resultCollector.getSearchResults(); - assertEquals( matches.size(), 1 ); - - pattern = SearchEngine.createSearchPattern( "forwardFunction", FUNCTION, ALL_OCCURRENCES, true ); //$NON-NLS-1$ - search( workspace, pattern, scope, resultCollector ); - matches = resultCollector.getSearchResults(); - assertEquals( matches.size(), 2 ); - - pattern = SearchEngine.createSearchPattern( "normalFunction", FUNCTION, DECLARATIONS, true ); //$NON-NLS-1$ - search( workspace, pattern, scope, resultCollector ); - matches = resultCollector.getSearchResults(); - assertEquals( matches.size(), 1 ); - - pattern = SearchEngine.createSearchPattern( "normalFunction", FUNCTION, DEFINITIONS, true ); //$NON-NLS-1$ - search( workspace, pattern, scope, resultCollector ); - matches = resultCollector.getSearchResults(); - assertEquals( matches.size(), 1 ); - - pattern = SearchEngine.createSearchPattern( "forwardMethod", METHOD, ALL_OCCURRENCES, true ); //$NON-NLS-1$ - search( workspace, pattern, scope, resultCollector ); - matches = resultCollector.getSearchResults(); - assertEquals( matches.size(), 2 ); - - pattern = SearchEngine.createSearchPattern( "staticField", FIELD, ALL_OCCURRENCES, true ); //$NON-NLS-1$ - search( workspace, pattern, scope, resultCollector ); - matches = resultCollector.getSearchResults(); - assertEquals( matches.size(), 2 ); - }*/ - - public void testNoResourceSearching() throws Exception { - String path = CTestPlugin.getDefault().getFileInPlugin(new Path("resources/search/include.h")).getAbsolutePath(); //$NON-NLS-1$ - - ICSearchPattern pattern = SearchEngine.createSearchPattern( "Head", CLASS, REFERENCES, true ); //$NON-NLS-1$ - - resultCollector.aboutToStart(); - - MatchLocator matchLocator = new MatchLocator( pattern, resultCollector, scope); - matchLocator.setProgressMonitor(monitor); - - try { - matchLocator.locateMatches( new String [] { path }, workspace, null ); - } catch (InterruptedException e1) { //boo - } - - resultCollector.done(); - - Set matches = resultCollector.getSearchResults(); - assertEquals( matches.size(), 4 ); - } - - public void testBug42911_43988(){ - BasicSearchMatch match1 = new BasicSearchMatch(); - BasicSearchMatch match2 = new BasicSearchMatch(); - - assertTrue( match1.equals( match2 ) ); - assertTrue( match2.equals( match1 ) ); - - match1.setName( "IWasSaying" ); //$NON-NLS-1$ - match1.setParentName( "boo" ); //$NON-NLS-1$ - match1.setReturnType( "urns" ); //$NON-NLS-1$ - - assertFalse( match1.equals( match2 ) ); - assertFalse( match2.equals( match1 ) ); - - match2.setName( "IWasSaying" ); //$NON-NLS-1$ - match2.setParentName( "boo" ); //$NON-NLS-1$ - match2.setReturnType( "urns" ); //$NON-NLS-1$ - - assertTrue( match1.equals( match2 ) ); - } - - public void testBug68235(){ - ICSearchPattern pattern = SearchEngine.createSearchPattern( "bug68235::xTag", STRUCT, DEFINITIONS, true ); //$NON-NLS-1$ - search( workspace, pattern, scope, resultCollector ); - Set matches = resultCollector.getSearchResults(); - assertEquals( matches.size(), 1 ); - - pattern = SearchEngine.createSearchPattern( "bug68235::yTag", STRUCT, DEFINITIONS, true ); //$NON-NLS-1$ - search( workspace, pattern, scope, resultCollector ); - matches = resultCollector.getSearchResults(); - assertEquals( matches.size(), 1 ); - - pattern = SearchEngine.createSearchPattern( "bug68235::xType", TYPEDEF, DECLARATIONS, true ); //$NON-NLS-1$ - search( workspace, pattern, scope, resultCollector ); - matches = resultCollector.getSearchResults(); - assertEquals( matches.size(), 1 ); - - pattern = SearchEngine.createSearchPattern( "bug68235::yType", TYPEDEF, DECLARATIONS, true ); //$NON-NLS-1$ - search( workspace, pattern, scope, resultCollector ); - matches = resultCollector.getSearchResults(); - assertEquals( matches.size(), 1 ); - - pattern = SearchEngine.createSearchPattern( "bug68235::xType", TYPEDEF, REFERENCES, true ); //$NON-NLS-1$ - search( workspace, pattern, scope, resultCollector ); - matches = resultCollector.getSearchResults(); - assertEquals( matches.size(), 1 ); - - pattern = SearchEngine.createSearchPattern( "bug68235::yType", TYPEDEF, REFERENCES, true ); //$NON-NLS-1$ - search( workspace, pattern, scope, resultCollector ); - matches = resultCollector.getSearchResults(); - assertEquals( matches.size(), 1 ); - } -} diff --git a/core/org.eclipse.cdt.core.tests/search/org/eclipse/cdt/core/search/tests/ParseTestOnSearchFiles.java b/core/org.eclipse.cdt.core.tests/search/org/eclipse/cdt/core/search/tests/ParseTestOnSearchFiles.java deleted file mode 100644 index 8a5a1004e9e..00000000000 --- a/core/org.eclipse.cdt.core.tests/search/org/eclipse/cdt/core/search/tests/ParseTestOnSearchFiles.java +++ /dev/null @@ -1,66 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2002, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.core.search.tests; - -import java.io.File; - -import junit.framework.TestCase; - -import org.eclipse.cdt.core.parser.IParser; -import org.eclipse.cdt.core.parser.IScanner; -import org.eclipse.cdt.core.parser.ISourceElementRequestor; -import org.eclipse.cdt.core.parser.NullLogService; -import org.eclipse.cdt.core.parser.NullSourceElementRequestor; -import org.eclipse.cdt.core.parser.ParserFactory; -import org.eclipse.cdt.core.parser.ParserLanguage; -import org.eclipse.cdt.core.parser.ParserMode; -import org.eclipse.cdt.core.parser.ScannerInfo; -import org.eclipse.cdt.core.testplugin.CTestPlugin; -import org.eclipse.core.runtime.Path; - -/** - * @author jcamelon - * - */ -public class ParseTestOnSearchFiles extends TestCase -{ - private String name; - private String fullPathName; - /** - * - */ - public ParseTestOnSearchFiles() - { - super(); - } - /** - * @param name - */ - public ParseTestOnSearchFiles(String name) - { - super(name); - } - - protected void setUp() throws Exception { - name = "resources/search/classDecl.cpp"; - File f = CTestPlugin.getDefault().getFileInPlugin(new Path(name)); - fullPathName = f.getAbsolutePath(); - } - - public void testParseOfAndrewsFile() throws Exception - { - ISourceElementRequestor requestor = new NullSourceElementRequestor(); - IScanner scanner = ParserFactory.createScanner( fullPathName, new ScannerInfo(), ParserMode.COMPLETE_PARSE, ParserLanguage.CPP, requestor, new NullLogService(), null ); - IParser parser = ParserFactory.createParser( scanner, requestor, ParserMode.COMPLETE_PARSE, ParserLanguage.CPP, null ); - assertTrue( parser.parse() ); - } - -} diff --git a/core/org.eclipse.cdt.core.tests/search/org/eclipse/cdt/core/search/tests/SearchTestSuite.java b/core/org.eclipse.cdt.core.tests/search/org/eclipse/cdt/core/search/tests/SearchTestSuite.java deleted file mode 100644 index fb7ee6e131b..00000000000 --- a/core/org.eclipse.cdt.core.tests/search/org/eclipse/cdt/core/search/tests/SearchTestSuite.java +++ /dev/null @@ -1,34 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2003, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corp. - Rational Software - initial implementation - *******************************************************************************/ - -package org.eclipse.cdt.core.search.tests; - -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; - -/** - * @author aniefer - * - * To change the template for this generated type comment go to - * Window>Preferences>Java>Code Generation>Code and Comments - */ -public class SearchTestSuite extends TestCase { - public static Test suite() { - TestSuite suite= new TestSuite(SearchTestSuite.class.getName()); - - suite.addTestSuite(ClassDeclarationPatternTests.class); - suite.addTestSuite(FunctionMethodPatternTests.class); - suite.addTestSuite(OtherPatternTests.class); - suite.addTestSuite(ParseTestOnSearchFiles.class); - return suite; - } -} diff --git a/core/org.eclipse.cdt.core/.classpath b/core/org.eclipse.cdt.core/.classpath index 9d6202a599d..570015a64be 100644 --- a/core/org.eclipse.cdt.core/.classpath +++ b/core/org.eclipse.cdt.core/.classpath @@ -1,13 +1,9 @@ - - - - diff --git a/core/org.eclipse.cdt.core/META-INF/MANIFEST.MF b/core/org.eclipse.cdt.core/META-INF/MANIFEST.MF index 6c346388e1b..3bb728792f6 100644 --- a/core/org.eclipse.cdt.core/META-INF/MANIFEST.MF +++ b/core/org.eclipse.cdt.core/META-INF/MANIFEST.MF @@ -7,8 +7,6 @@ Bundle-Activator: org.eclipse.cdt.core.CCorePlugin Bundle-Vendor: %providerName Bundle-Localization: plugin Export-Package: org.eclipse.cdt.core, - org.eclipse.cdt.core.browser, - org.eclipse.cdt.core.browser.typehierarchy, org.eclipse.cdt.core.dom, org.eclipse.cdt.core.dom.ast, org.eclipse.cdt.core.dom.ast.c, @@ -17,29 +15,19 @@ Export-Package: org.eclipse.cdt.core, org.eclipse.cdt.core.dom.ast.gnu.c, org.eclipse.cdt.core.dom.ast.gnu.cpp, org.eclipse.cdt.core.formatter, - org.eclipse.cdt.core.index, org.eclipse.cdt.core.model, + org.eclipse.cdt.core.model.util, org.eclipse.cdt.core.parser, org.eclipse.cdt.core.parser.ast, org.eclipse.cdt.core.parser.ast.gcc, org.eclipse.cdt.core.parser.extension, org.eclipse.cdt.core.parser.util, org.eclipse.cdt.core.resources, - org.eclipse.cdt.core.search, org.eclipse.cdt.internal.core, - org.eclipse.cdt.internal.core.browser.cache, - org.eclipse.cdt.internal.core.browser.util, org.eclipse.cdt.internal.core.dom, org.eclipse.cdt.internal.core.dom.parser, org.eclipse.cdt.internal.core.dom.parser.c, org.eclipse.cdt.internal.core.dom.parser.cpp, - org.eclipse.cdt.internal.core.index, - org.eclipse.cdt.internal.core.index.cindexstorage, - org.eclipse.cdt.internal.core.index.cindexstorage.io, - org.eclipse.cdt.internal.core.index.ctagsindexer, - org.eclipse.cdt.internal.core.index.domsourceindexer, - org.eclipse.cdt.internal.core.index.impl, - org.eclipse.cdt.internal.core.index.nullindexer, org.eclipse.cdt.internal.core.model, org.eclipse.cdt.internal.core.parser, org.eclipse.cdt.internal.core.parser.ast, @@ -57,11 +45,6 @@ Export-Package: org.eclipse.cdt.core, org.eclipse.cdt.internal.core.pdom.dom, org.eclipse.cdt.internal.core.pdom.dom.c, org.eclipse.cdt.internal.core.pdom.dom.cpp, - org.eclipse.cdt.internal.core.search, - org.eclipse.cdt.internal.core.search.indexing, - org.eclipse.cdt.internal.core.search.matching, - org.eclipse.cdt.internal.core.search.processing, - org.eclipse.cdt.internal.core.sourcedependency, org.eclipse.cdt.internal.core.util, org.eclipse.cdt.internal.errorparsers, org.eclipse.cdt.internal.formatter, diff --git a/core/org.eclipse.cdt.core/browser/ChangeLog-browser b/core/org.eclipse.cdt.core/browser/ChangeLog-browser deleted file mode 100644 index 076461df5df..00000000000 --- a/core/org.eclipse.cdt.core/browser/ChangeLog-browser +++ /dev/null @@ -1,108 +0,0 @@ -2005-03-29 Chris Wiebe - small change for potential reduction in memory usage - * browser/org/eclipse/cdt/core/browser/QualifiedTypeName.java - -2005-03-29 Chris Wiebe - temporary fix for type parser timeout - * browser/org/eclipse/cdt/core/browser/cache/TypeParser.java - -2005-03-13 Bogdan Gheorghe - Updated references to IndexManager to reflect new multi-indexer framework. - * browser/org/eclipse/cdt/internal/core/browser/cache/IndexerDependencies.java - * browser/org/eclipse/cdt/internal/core/browser/cache/IndexerJob.java - * browser/org/eclipse/cdt/internal/core/browser/cache/IndexerTypesJob.java - * browser/org/eclipse/cdt/internal/core/browser/cache/TypeCache.java - * browser/org/eclipse/cdt/internal/core/browser/cache/TypeCacherJob.java - - Added temporary flag to TypeCacheManager to prevent deadlocks during JUnit runs, pending - changes to Index Storage framework. - * browser/org/eclipse/cdt/internal/core/browser/cache/TypeCacheManager.java - -2005-01-06 Chris Wiebe - added parser timeout to TypeParser - * browser/org/eclipse/cdt/internal/core/browser/cache/TypeParser.java - -2004-11-08 Chris Wiebe - - fix for 68883 - * browser/org/eclipse/cdt/internal/core/browser/cache/TypeCacheManager.java - -2004-09-15 Chris Wiebe - - add getTypes and getAllTypes methods - * browser/org/eclipse/cdt/core/browser/TypeUtil.java - -2004-09-02 Chris Wiebe - - add method to get global namespace - * browser/org/eclipse/cdt/internal/core/browser/AllTypesCache.java - -2004-09-01 Chris Wiebe - - avoid unnecessary deltas - * browser/org/eclipse/cdt/internal/core/browser/cache/TypeCacheManager.java - -2004-08-31 Chris Wiebe - - Fix for 68883 - * browser/org/eclipse/cdt/core/browser/AllTypesCache.java - * browser/org/eclipse/cdt/core/browser/ITypeCacheChangedListener.java - * browser/org/eclipse/cdt/core/browser/ITypeInfo.java - * browser/org/eclipse/cdt/core/browser/TypeInfo.java - * browser/org/eclipse/cdt/core/browser/TypeUtil.java - * browser/org/eclipse/cdt/core/browser/typehierarchy/TypeHierarchy.java - * browser/org/eclipse/cdt/core/browser/cache/ITypeCache.java - * browser/org/eclipse/cdt/core/browser/cache/TypeCache.java - * browser/org/eclipse/cdt/core/browser/cache/TypeCacheManager.java - -2004-08-26 Chris Wiebe - - make QualifiedTypeName immutable class - get rid of unnecessary memory allocations - * browser/org/eclipse/cdt/core/browser/IQualifiedTypeName.java - * browser/org/eclipse/cdt/core/browser/QualifiedTypeName.java - * browser/org/eclipse/cdt/core/browser/TypeInfo.java - * browser/org/eclipse/cdt/internal/core/browser/TypeCache.java - -2004-07-16 Chris Wiebe - - Fixing numerous warnings. - -2004-07-06 Chris Wiebe - - This patch prevents some NPEs from happening in the class browser. I - suggest this should be applied to both HEAD and CDT_2_0 branch. - - * browser/org/eclipse/cdt/core/browser/TypeInfo.java - -2004-06-22 Alain Magloire - Part of PR 68246. - Close the inputstream to release resource handle - when we done with it, we can not rely on the GC to do it for us. - - * browser/org/eclipse/cdt/internal/core/browser/cache/TypeParser.java - -2004-06-21 Chris Wiebe - - - fix for bug #66108 (C++ browser cannot show members of class) - - TypeParser now uses resource to get scanner info - -2004-06-17 Alain Magloire - - Changes from Chris Wiebe to deal - with the memory consumption. - -2004-05-12 Chris Wiebe - Heavy refactoring of type cache to address scalability - concerns. - -2004-05-06 Chris Wiebe - Creating a new Job to handle the changes, instead - of reusing the same job. - -2004-04-20 Chris Wiebe - refactored TypeCacheDeltaListener into standalone class - added option in Work In Progress prefs page to disable background cache - -2004-04-06 Chris Wiebe - initial placement of non-ui code into org.eclipse.cdt.core.browser \ No newline at end of file diff --git a/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/core/browser/AllTypesCache.java b/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/core/browser/AllTypesCache.java deleted file mode 100644 index 1481da5ae08..00000000000 --- a/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/core/browser/AllTypesCache.java +++ /dev/null @@ -1,366 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 QNX Software Systems and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * QNX Software Systems - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.core.browser; - -import java.util.ArrayList; -import java.util.Collection; - -import org.eclipse.cdt.core.CCorePlugin; -import org.eclipse.cdt.core.browser.typehierarchy.ITypeHierarchy; -import org.eclipse.cdt.core.browser.typehierarchy.TypeHierarchyBuilder; -import org.eclipse.cdt.core.model.CModelException; -import org.eclipse.cdt.core.model.CoreModel; -import org.eclipse.cdt.core.model.ElementChangedEvent; -import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.cdt.core.model.IElementChangedListener; -import org.eclipse.cdt.core.model.IWorkingCopy; -import org.eclipse.cdt.core.model.IWorkingCopyProvider; -import org.eclipse.cdt.internal.core.browser.cache.ITypeCache; -import org.eclipse.cdt.internal.core.browser.cache.TypeCacheManager; -import org.eclipse.cdt.internal.core.browser.util.ArrayUtil; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.Preferences; -import org.eclipse.core.runtime.Preferences.IPropertyChangeListener; -import org.eclipse.core.runtime.Preferences.PropertyChangeEvent; -import org.eclipse.core.runtime.jobs.Job; - -/** - * Manages a search cache for types in the workspace. Instead of returning - * objects of type ICElement the methods of this class returns a - * list of the lightweight objects TypeInfo. - *

- * AllTypesCache runs asynchronously using a background job to rebuild the cache - * as needed. If the cache becomes dirty again while the background job is - * running, the job is restarted. - *

- * If getTypes is called in response to a user action, a progress - * dialog is shown. If called before the background job has finished, getTypes - * waits for the completion of the background job. - */ -public class AllTypesCache { - - private static final int INITIAL_DELAY = 5000; - private static IWorkingCopyProvider fgWorkingCopyProvider; - private static TypeHierarchyBuilder fgTypeHierarchyBuilder; - private static IElementChangedListener fgElementChangedListener; - private static IPropertyChangeListener fgPropertyChangeListener; - static boolean fgEnableIndexing = true; - - /** Preference key for enabling background cache */ - public final static String ENABLE_BACKGROUND_TYPE_CACHE = "enableBackgroundTypeCache"; //$NON-NLS-1$ - - /** - * Initializes the AllTypesCache service. - * - * @param provider A working copy provider. - */ - public static void initialize(IWorkingCopyProvider workingCopyProvider) { - fgWorkingCopyProvider = workingCopyProvider; - TypeCacheManager.getInstance().setWorkingCopyProvider(fgWorkingCopyProvider); - fgTypeHierarchyBuilder = new TypeHierarchyBuilder(); - - // load prefs -// Preferences prefs = CCorePlugin.getDefault().getPluginPreferences(); -// if (prefs.contains(ENABLE_BACKGROUND_TYPE_CACHE)) { -// fgEnableIndexing = prefs.getBoolean(ENABLE_BACKGROUND_TYPE_CACHE); -// } else { -// prefs.setDefault(ENABLE_BACKGROUND_TYPE_CACHE, false); -// prefs.setValue(ENABLE_BACKGROUND_TYPE_CACHE, false); -// CCorePlugin.getDefault().savePluginPreferences(); -// fgEnableIndexing = true; -// } - fgEnableIndexing = false; - - // start jobs in background after INITIAL_DELAY - TypeCacheManager.getInstance().reconcile(fgEnableIndexing, Job.BUILD, INITIAL_DELAY); - - // add delta listener - fgElementChangedListener = new IElementChangedListener() { - public void elementChanged(ElementChangedEvent event) { - TypeCacheManager.getInstance().processElementChanged(event, fgEnableIndexing); - } - }; - CoreModel.getDefault().addElementChangedListener(fgElementChangedListener); - -// // add property change listener -// fgPropertyChangeListener = new IPropertyChangeListener() { -// public void propertyChange(PropertyChangeEvent event) { -// String property = event.getProperty(); -// if (property.equals(ENABLE_BACKGROUND_TYPE_CACHE)) { -// String value = (String) event.getNewValue(); -// fgEnableIndexing = Boolean.valueOf(value).booleanValue(); -// if (!fgEnableIndexing) { -// TypeCacheManager.getInstance().cancelJobs(); -// } else { -// TypeCacheManager.getInstance().reconcile(fgEnableIndexing, Job.BUILD, 0); -// } -// } -// } -// }; -// prefs.addPropertyChangeListener(fgPropertyChangeListener); - } - - /** - * Terminates the service provided by AllTypesCache. - */ - public static void terminate() { - // remove delta listener - if (fgElementChangedListener != null) - CoreModel.getDefault().removeElementChangedListener(fgElementChangedListener); - - // remove property change listener - if (fgPropertyChangeListener != null) - CCorePlugin.getDefault().getPluginPreferences().removePropertyChangeListener(fgPropertyChangeListener); - - // terminate all running jobs - if (TypeCacheManager.getInstance() != null) { - TypeCacheManager.getInstance().cancelJobs(); - } - } - - /** - * Returns all types in the workspace. - */ - public static ITypeInfo[] getAllTypes() { - final Collection fAllTypes = new ArrayList(); - TypeSearchScope workspaceScope = new TypeSearchScope(true); - IProject[] projects = workspaceScope.getEnclosingProjects(); - ITypeInfoVisitor visitor = new ITypeInfoVisitor() { - public boolean visit(ITypeInfo info) { - fAllTypes.add(info); - return true; - } - public boolean shouldContinue() { return true; } - }; - for (int i = 0; i < projects.length; ++i) { - TypeCacheManager.getInstance().getCache(projects[i]).accept(visitor); - } - return (ITypeInfo[]) fAllTypes.toArray(new ITypeInfo[fAllTypes.size()]); - } - - /** - * Returns all types in the given scope. - * - * @param scope The search scope - * @param kinds Array containing CElement types: C_NAMESPACE, C_CLASS, - * C_UNION, C_ENUMERATION, C_TYPEDEF - */ - public static ITypeInfo[] getTypes(ITypeSearchScope scope, int[] kinds) { - final Collection fTypesFound = new ArrayList(); - final ITypeSearchScope fScope = scope; - final int[] fKinds = kinds; - IProject[] projects = scope.getEnclosingProjects(); - ITypeInfoVisitor visitor = new ITypeInfoVisitor() { - public boolean visit(ITypeInfo info) { - if (ArrayUtil.contains(fKinds, info.getCElementType()) - && (fScope != null && info.isEnclosed(fScope))) { - fTypesFound.add(info); - } - return true; - } - public boolean shouldContinue() { return true; } - }; - for (int i = 0; i < projects.length; ++i) { - TypeCacheManager.getInstance().getCache(projects[i]).accept(visitor); - } - return (ITypeInfo[]) fTypesFound.toArray(new ITypeInfo[fTypesFound.size()]); - } - - /** - * Returns all types matching name in the given scope. - * - * @param scope The search scope - * @param qualifiedName The qualified type name - * @param kinds Array containing CElement types: C_NAMESPACE, C_CLASS, - * C_UNION, C_ENUMERATION, C_TYPEDEF - * @param matchEnclosed true if enclosed types count as matches (foo::bar == bar) - */ - public static ITypeInfo[] getTypes(ITypeSearchScope scope, IQualifiedTypeName qualifiedName, int[] kinds, boolean matchEnclosed) { - final Collection fTypesFound = new ArrayList(); - final ITypeSearchScope fScope = scope; - final int[] fKinds = kinds; - final IQualifiedTypeName fQualifiedName = qualifiedName; - final boolean fMatchEnclosed = matchEnclosed; - IProject[] projects = scope.getEnclosingProjects(); - ITypeInfoVisitor visitor = new ITypeInfoVisitor() { - public boolean visit(ITypeInfo info) { - if (ArrayUtil.contains(fKinds, info.getCElementType()) - && (fScope != null && info.isEnclosed(fScope))) { - IQualifiedTypeName currName = info.getQualifiedTypeName(); - if (fMatchEnclosed && currName.segmentCount() > fQualifiedName.segmentCount() - && currName.lastSegment().equals(fQualifiedName.lastSegment())) { - currName = currName.removeFirstSegments(currName.segmentCount() - fQualifiedName.segmentCount()); - } - if (currName.equals(fQualifiedName)) { - fTypesFound.add(info); - } - } - return true; - } - public boolean shouldContinue() { return true; } - }; - for (int i = 0; i < projects.length; ++i) { - TypeCacheManager.getInstance().getCache(projects[i]).accept(visitor); - } - return (ITypeInfo[]) fTypesFound.toArray(new ITypeInfo[fTypesFound.size()]); - } - - /** - * Returns all namespaces in the given scope. - * - * @param scope The search scope - * @param includeGlobalNamespace true if the global (default) namespace should be returned - */ - public static ITypeInfo[] getNamespaces(ITypeSearchScope scope, boolean includeGlobalNamespace) { - final Collection fTypesFound = new ArrayList(); - final ITypeSearchScope fScope = scope; - IProject[] projects = scope.getEnclosingProjects(); - ITypeInfoVisitor visitor = new ITypeInfoVisitor() { - public boolean visit(ITypeInfo info) { - if (info.getCElementType() == ICElement.C_NAMESPACE - && (fScope != null && info.isEnclosed(fScope))) { - fTypesFound.add(info); - } - return true; - } - public boolean shouldContinue() { return true; } - }; - for (int i = 0; i < projects.length; ++i) { - ITypeCache cache = TypeCacheManager.getInstance().getCache(projects[i]); - cache.accept(visitor); - if (includeGlobalNamespace) { - fTypesFound.add(cache.getGlobalNamespace()); - } - } - return (ITypeInfo[]) fTypesFound.toArray(new ITypeInfo[fTypesFound.size()]); - } - - /** - * Returns the global (default) namespace for the given project. - * - * @param project the project - */ - public static ITypeInfo getGlobalNamespace(IProject project) { - ITypeCache cache = TypeCacheManager.getInstance().getCache(project); - return cache.getGlobalNamespace(); - } - - /** - * Returns true if the type cache is up to date. - */ - public static boolean isCacheUpToDate(ITypeSearchScope scope) { - forceDeltaComplete(); - - IProject[] projects = scope.getEnclosingProjects(); - for (int i = 0; i < projects.length; ++i) { - IProject project = projects[i]; - if (project.exists() && project.isOpen()) { - if (!TypeCacheManager.getInstance().getCache(project).isUpToDate()) - return false; - } - } - return true; - } - - private static void forceDeltaComplete() { - if (fgWorkingCopyProvider != null) { - IWorkingCopy[] workingCopies = fgWorkingCopyProvider.getWorkingCopies(); - for (int i = 0; i < workingCopies.length; ++i) { - IWorkingCopy wc = workingCopies[i]; - try { - synchronized (wc) { - wc.reconcile(); - } - } catch (CModelException ex) { - } - } - } - } - - /** - * Updates the type cache. - * - * @param monitor the progress monitor - */ - public static void updateCache(ITypeSearchScope scope, IProgressMonitor monitor) { - TypeCacheManager.getInstance().updateCache(scope, monitor); - } - - /** - * Resolves a type location. - * - * @param info the type to search for - * @param monitor the progress monitor - */ - public static ITypeReference resolveTypeLocation(ITypeInfo info, IProgressMonitor monitor) { - return TypeCacheManager.getInstance().resolveTypeLocation(info, monitor, fgEnableIndexing); - } - - /** Returns first type in the cache which matches the given - * type and name. If no type is found, null - * is returned. - * - * @param project the enclosing project - * @param type the ICElement type - * @param qualifiedName the qualified type name to match - * @return the matching type - */ - public static ITypeInfo getType(IProject project, int type, IQualifiedTypeName qualifiedName) { - ITypeCache cache = TypeCacheManager.getInstance().getCache(project); - return cache.getType(type, qualifiedName); - } - - /** - * Returns all types matching name in the given project. - * - * @param project the enclosing project - * @param qualifiedName The qualified type name - * @param matchEnclosed true if enclosed types count as matches (foo::bar == bar) - * @param ignoreCase true if case-insensitive - * @return Array of types - */ - public static ITypeInfo[] getTypes(IProject project, IQualifiedTypeName qualifiedName, boolean matchEnclosed, boolean ignoreCase) { - ITypeCache cache = TypeCacheManager.getInstance().getCache(project); - return cache.getTypes(qualifiedName, matchEnclosed, ignoreCase); - } - - /** - * Creates and returns a type hierarchy for this type containing - * this type and all of its supertypes and subtypes in the workspace. - * - * @param info the given type - * @param monitor the given progress monitor - * @return a type hierarchy for the given type - */ - public static ITypeHierarchy createTypeHierarchy(ICElement type, IProgressMonitor monitor) throws CModelException { - ITypeInfo info = TypeCacheManager.getInstance().getTypeForElement(type, true, true, fgEnableIndexing, monitor); - if (info != null) - return fgTypeHierarchyBuilder.createTypeHierarchy(info, fgEnableIndexing, monitor); - return null; - } - - public static void addTypeCacheChangedListener(ITypeCacheChangedListener listener) { - TypeCacheManager.getInstance().addTypeCacheChangedListener(listener); - } - - public static void removeTypeCacheChangedListener(ITypeCacheChangedListener listener) { - TypeCacheManager.getInstance().removeTypeCacheChangedListener(listener); - } - - public static ITypeInfo getTypeForElement(ICElement element, boolean forceUpdate, boolean forceResolve, IProgressMonitor monitor) { - return TypeCacheManager.getInstance().getTypeForElement(element, forceUpdate, forceResolve, fgEnableIndexing, monitor); - } - - public static ICElement getElementForType(ITypeInfo type, boolean forceUpdate, boolean forceResolve, IProgressMonitor monitor) { - return TypeCacheManager.getInstance().getElementForType(type, forceUpdate, forceResolve, fgEnableIndexing, monitor); - } -} diff --git a/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/core/browser/ITypeCacheChangedListener.java b/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/core/browser/ITypeCacheChangedListener.java deleted file mode 100644 index a7e7bce5d19..00000000000 --- a/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/core/browser/ITypeCacheChangedListener.java +++ /dev/null @@ -1,32 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 QNX Software Systems and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * QNX Software Systems - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.core.browser; - -import org.eclipse.core.resources.IProject; - - -/** - * A listener which gets notified when the type cache changes. - *

- * This interface may be implemented by clients. - *

- */ -public interface ITypeCacheChangedListener { - - /** - * Notifies that the type cache for the given project has changed in some way - * and should be refreshed at some point to make it consistent with the current - * state of the C model. - * - * @param project the given project - */ - void typeCacheChanged(IProject project); -} diff --git a/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/core/browser/ITypeInfo.java b/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/core/browser/ITypeInfo.java deleted file mode 100644 index b985dbf27f6..00000000000 --- a/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/core/browser/ITypeInfo.java +++ /dev/null @@ -1,209 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 QNX Software Systems and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * QNX Software Systems - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.core.browser; - -import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.cdt.core.parser.ast.ASTAccessVisibility; -import org.eclipse.cdt.internal.core.browser.cache.ITypeCache; -import org.eclipse.core.resources.IProject; - -/** - * Type information. - */ -public interface ITypeInfo extends Comparable { - - public static final int KNOWN_TYPES[] = { - ICElement.C_NAMESPACE, - ICElement.C_CLASS, - ICElement.C_STRUCT, - ICElement.C_UNION, - ICElement.C_ENUMERATION, - ICElement.C_TYPEDEF - }; - - /** - * Gets the CElement type. - * @return ICElement.C_NAMESPACE, C_CLASS, C_STRUCT, C_UNION, C_ENUMERATION, or C_TYPEDEF, - * or zero if unknown type. - */ - public int getCElementType(); - - /** - * Sets the CElement type. - */ - public void setCElementType(int type); - - /** - * Gets the type name. - */ - public String getName(); - - /** - * Gets the qualified type name. - */ - public IQualifiedTypeName getQualifiedTypeName(); - - /** - * Returns true if the type exists. - */ - public boolean exists(); - - /** - * Returns true if the element type is unknown. - */ - public boolean isUndefinedType(); - - /** - * Returns true if this type is enclosed by other types, - * i.e. declared an inside another namespace or class. - */ - public boolean isEnclosedType(); - - /** Gets the enclosing type, i.e. the outer class or namespace which contains this type. - * @return the enclosing type, or null if not found. - */ - public ITypeInfo getEnclosingType(); - - /** Gets the enclosing namespace for this type. - * @return the enclosing namespace, or null if none exists. - */ - public ITypeInfo getEnclosingNamespace(boolean includeGlobalNamespace); - - /** Gets the first enclosing type which matches one of the given kinds. - * @param kinds Array containing CElement types: C_NAMESPACE, C_CLASS, C_STRUCT - * @return the enclosing type, or null if not found. - */ - public ITypeInfo getEnclosingType(int[] kinds); - - /** Gets the root namespace, i.e. the outermost namespace - * which contains this type. - * @param includeGlobalNamespace true if the global (default) namespace should be returned - * @return the namespace, or null if not found. - */ - public ITypeInfo getRootNamespace(boolean includeGlobalNamespace); - - /** - * Returns true if this type is capable of enclosing other types, - * i.e. it is a namespace, class, or struct. - */ - public boolean isEnclosingType(); - - /** - * Returns true if this type encloses other types, i.e. contains - * inner classes or namespaces. - */ - public boolean hasEnclosedTypes(); - - /** - * Returns true if this type encloses the given type. - */ - public boolean encloses(ITypeInfo info); - - /** - * Returns true if this type is enclosed by the given type. - */ - public boolean isEnclosed(ITypeInfo info); - - /** Gets the enclosed types, i.e. inner classes or classes inside this namespace. - * @return array of inner types, or empty array if not found. - */ - public ITypeInfo[] getEnclosedTypes(); - - /** Gets the enclosed types, i.e. inner classes or classes inside this namespace. - * @param kinds Array containing CElement types: C_NAMESPACE, C_CLASS, C_STRUCT, - * C_UNION, C_ENUMERATION, C_TYPEDEF - * @return array of inner types, or empty array if not found. - */ - public ITypeInfo[] getEnclosedTypes(int kinds[]); - - /** - * Gets the enclosing project. - */ - public IProject getEnclosingProject(); - - /** - * Returns true if type is enclosed in the given scope. - */ - public boolean isEnclosed(ITypeSearchScope scope); - - /** - * Adds a source reference. - */ - public void addReference(ITypeReference location); - - /** Gets the originating locations where this type was declared. - * @return all known source references, or an empty - * array if none found. - */ - public ITypeReference[] getReferences(); - - /** Gets the real location where type was declared. - * @return the parsed source reference (with offset and length), - * or null if not found. - */ - public ITypeReference getResolvedReference(); - - /** - * Returns true if the type can be substituted. - */ - public boolean canSubstituteFor(ITypeInfo info); - - public ITypeCache getCache(); - public void setCache(ITypeCache typeCache); - - /** - * Returns true if other types extend this type. - */ - public boolean hasSubTypes(); - - /** Gets all types which extend this type. - * @return array of types, or null if none found. - */ - public ITypeInfo[] getSubTypes(); - - /** - * Returns true if this type has base classes. - */ - public boolean hasSuperTypes(); - - /** Gets the base classes. - * @return array of types, or null if none found. - */ - public ITypeInfo[] getSuperTypes(); - - /** - * Gets the base class access visibility (PRIVATE, PROTECTED, PUBLIC) - */ - public ASTAccessVisibility getSuperTypeAccess(ITypeInfo subType); - - /** - * Adds a derived class reference, i.e. this type is used as - * a base class at the given location. - */ - public void addDerivedReference(ITypeReference location); - - /** Gets the originating locations where this type was - * used as a base class. - * @return all known source references, or an empty - * array if none found. - */ - public ITypeReference[] getDerivedReferences(); - - /** - * Returns true if the type is a class or struct. - */ - public boolean isClass(); - - /** - * Returns true if type is referenced in the given scope. - */ - public boolean isReferenced(ITypeSearchScope scope); -} diff --git a/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/core/browser/ITypeInfoVisitor.java b/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/core/browser/ITypeInfoVisitor.java deleted file mode 100644 index 38dcbe93abe..00000000000 --- a/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/core/browser/ITypeInfoVisitor.java +++ /dev/null @@ -1,18 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 QNX Software Systems and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * QNX Software Systems - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.core.browser; - -public interface ITypeInfoVisitor { - - public boolean visit(ITypeInfo info); - - public boolean shouldContinue(); -} diff --git a/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/core/browser/ITypeReference.java b/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/core/browser/ITypeReference.java deleted file mode 100644 index 90d29c4283f..00000000000 --- a/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/core/browser/ITypeReference.java +++ /dev/null @@ -1,91 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 QNX Software Systems and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * QNX Software Systems - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.core.browser; - -import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.cdt.core.model.ITranslationUnit; -import org.eclipse.cdt.core.model.IWorkingCopy; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.runtime.IPath; - -public interface ITypeReference { - - /** - * Returns the full, absolute path of this reference - * relative to the workspace, or null if no path can be - * determined. - */ - public IPath getPath(); - - /** - * Returns the absolute path in the local file system - * to this reference, or null if no path can be - * determined. - */ - public IPath getLocation(); - - /** - * Returns the resource. - */ - public IResource getResource(); - - /** - * Returns the working copy. - */ - public IWorkingCopy getWorkingCopy(); - - /** - * Returns the project. - */ - public IProject getProject(); - - /** - * Returns the offset. - */ - public int getOffset(); - - /** - * Returns the length. - */ - public int getLength(); - - /** - * Returns the CElements located at the stored offset and length, - * or null if not found. - */ - public ICElement[] getCElements(); - - /** - * Returns a translation unit for this location. - */ - public ITranslationUnit getTranslationUnit(); - - /** Gets the path for this location, relative to one of - * the given project's include paths. - * - * @param project the project to use as a reference. - * @return The path to this location, relative to the longest - * matching include path in the given project. - */ - public IPath getRelativeIncludePath(IProject project); - - /** Gets the path for this location, relative to the - * given path. - * - * @param relativeToPath the path to use as a reference. - * @return The path to this location, relative to the - * given path. - */ - public IPath getRelativePath(IPath relativeToPath); - - boolean isLineNumber(); -} diff --git a/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/core/browser/ITypeSearchScope.java b/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/core/browser/ITypeSearchScope.java deleted file mode 100644 index 269d3c9a8f5..00000000000 --- a/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/core/browser/ITypeSearchScope.java +++ /dev/null @@ -1,47 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 QNX Software Systems and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * QNX Software Systems - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.core.browser; - -import java.util.Collection; - -import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.cdt.core.model.IWorkingCopy; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.runtime.IPath; - -public interface ITypeSearchScope { - - public boolean isPathScope(); - public boolean isProjectScope(); - public boolean isWorkspaceScope(); - public boolean isEmpty(); - - public boolean encloses(ITypeSearchScope scope); - public boolean encloses(IProject project); - public boolean encloses(IPath path); - public boolean encloses(String path); - public boolean encloses(ICElement element); - public boolean encloses(IWorkingCopy workingCopy); - - public void add(IWorkingCopy workingCopy); - public void add(IPath path, boolean addSubfolders, IProject enclosingProject); - public void add(IProject project); - public void add(ICElement elem); - public void add(ITypeSearchScope scope); - public void addWorkspace(); - public void clear(); - public IProject[] getEnclosingProjects(); - - public Collection pathSet(); - public Collection containerSet(); - public Collection projectSet(); - public Collection enclosingProjectSet(); -} diff --git a/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/core/browser/TypeInfo.java b/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/core/browser/TypeInfo.java deleted file mode 100644 index 9a10b78da9d..00000000000 --- a/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/core/browser/TypeInfo.java +++ /dev/null @@ -1,330 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 QNX Software Systems and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * QNX Software Systems - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.core.browser; - -import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.cdt.core.parser.ast.ASTAccessVisibility; -import org.eclipse.cdt.internal.core.browser.cache.ITypeCache; -import org.eclipse.cdt.internal.core.browser.util.ArrayUtil; -import org.eclipse.core.resources.IProject; - -public class TypeInfo implements ITypeInfo -{ - protected ITypeCache fTypeCache; - protected int fElementType; - protected IQualifiedTypeName fQualifiedName; - protected ITypeReference[] fSourceRefs = null; - protected int fSourceRefsCount = 0; - protected ITypeReference[] fDerivedSourceRefs = null; - protected int fDerivedSourceRefsCount = 0; - - protected final static int INITIAL_REFS_SIZE = 1; - protected final static int REFS_GROW_BY = 2; - protected final static ITypeInfo[] EMPTY_TYPES = new ITypeInfo[0]; - - public TypeInfo(int elementType, IQualifiedTypeName typeName) { - fElementType = elementType; - fQualifiedName = typeName; - } - - public void addReference(ITypeReference location) { - if (fSourceRefs == null) { - fSourceRefs = new ITypeReference[INITIAL_REFS_SIZE]; - fSourceRefsCount = 0; - } else if (fSourceRefsCount == fSourceRefs.length) { - ITypeReference[] refs = new ITypeReference[fSourceRefs.length + REFS_GROW_BY]; - System.arraycopy(fSourceRefs, 0, refs, 0, fSourceRefsCount); - fSourceRefs = refs; - } - fSourceRefs[fSourceRefsCount] = location; - ++fSourceRefsCount; - } - - public ITypeReference[] getReferences() { - if (fSourceRefs != null) { - ITypeReference[] refs = new ITypeReference[fSourceRefsCount]; - System.arraycopy(fSourceRefs, 0, refs, 0, fSourceRefsCount); - return refs; - } - return null; - } - - public ITypeReference getResolvedReference() { - for (int i = 0; i < fSourceRefsCount; ++i) { - ITypeReference location = fSourceRefs[i]; - if (location.isLineNumber() ) - return location; - if( location.getLength() != 0) { - return location; - } - } - return null; - } - - public boolean isReferenced() { - return (fSourceRefs != null || fDerivedSourceRefs != null); - } - - public boolean isReferenced(ITypeSearchScope scope) { - if (scope == null || scope.isWorkspaceScope()) - return true; - - // check if path is in scope - for (int i = 0; i < fSourceRefsCount; ++i) { - ITypeReference location = fSourceRefs[i]; - if (scope.encloses(location.getPath())) - return true; - } - for (int i = 0; i < fDerivedSourceRefsCount; ++i) { - ITypeReference location = fDerivedSourceRefs[i]; - if (scope.encloses(location.getPath())) - return true; - } - - return false; - } - - public boolean isUndefinedType() { - return fElementType == 0; - } - - public boolean canSubstituteFor(ITypeInfo info) { - return isExactMatch(info); - } - - protected boolean isExactMatch(ITypeInfo info) { - if (hashCode() != info.hashCode()) - return false; - if (fElementType == info.getCElementType() - && fQualifiedName.equals(info.getQualifiedTypeName())) { - IProject project1 = getEnclosingProject(); - IProject project2 = info.getEnclosingProject(); - if (project1 == null && project2 == null) - return true; - if (project1 == null || project2 == null) - return false; - return project1.equals(project2); - } - return false; - } - - public boolean exists() { - return fTypeCache != null; - } - - public int getCElementType() { - return fElementType; - } - - public void setCElementType(int type) { - fElementType = type; - } - - public IQualifiedTypeName getQualifiedTypeName() { - return fQualifiedName; - } - - public String getName() { - return fQualifiedName.getName(); - } - - public boolean isEnclosedType() { - return (fQualifiedName.isQualified()); - } - - public ITypeInfo getEnclosingType(int kinds[]) { - if (fTypeCache != null) { - return fTypeCache.getEnclosingType(this, kinds); - } - return null; - } - - public ITypeInfo getEnclosingType() { - return getEnclosingType(KNOWN_TYPES); - } - - public ITypeInfo getEnclosingNamespace(boolean includeGlobalNamespace) { - if (fTypeCache != null) { - return fTypeCache.getEnclosingNamespace(this, includeGlobalNamespace); - } - return null; - } - - public ITypeInfo getRootNamespace(boolean includeGlobalNamespace) { - if (fTypeCache != null) { - return fTypeCache.getRootNamespace(this, includeGlobalNamespace); - } - return null; - } - - public boolean isEnclosingType() { - return (fElementType == ICElement.C_NAMESPACE - || fElementType == ICElement.C_CLASS - || fElementType == ICElement.C_STRUCT); - } - - public boolean encloses(ITypeInfo info) { - if (isEnclosingType() && fTypeCache == info.getCache()) { - return fQualifiedName.isPrefixOf(info.getQualifiedTypeName()); - } - return false; - } - - public boolean isEnclosed(ITypeInfo info) { - return info.encloses(this); - } - - public boolean hasEnclosedTypes() { - if (isEnclosingType() && fTypeCache != null) { - return fTypeCache.hasEnclosedTypes(this); - } - return false; - } - - public ITypeInfo[] getEnclosedTypes() { - return getEnclosedTypes(KNOWN_TYPES); - } - - public ITypeInfo[] getEnclosedTypes(int kinds[]) { - if (fTypeCache != null) { - return fTypeCache.getEnclosedTypes(this, kinds); - } - return EMPTY_TYPES; - } - - public IProject getEnclosingProject() { - if (fTypeCache != null) { - return fTypeCache.getProject(); - } - return null; - } - - public String toString() { - return fQualifiedName.toString(); - } - - public boolean isEnclosed(ITypeSearchScope scope) { - if (scope == null || scope.isWorkspaceScope()) - return true; - - // check if path is in scope - for (int i = 0; i < fSourceRefsCount; ++i) { - ITypeReference location = fSourceRefs[i]; - if (scope.encloses(location.getPath())) - return true; - } - - return false; - } - - public int hashCode() { - int hashCode = fQualifiedName.hashCode() + fElementType; - IProject project = getEnclosingProject(); - if (project != null) - hashCode += project.hashCode(); - return hashCode; - } - - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - if (!(obj instanceof TypeInfo)) { - return false; - } - return isExactMatch((TypeInfo)obj); - } - - public int compareTo(Object obj) { - if (obj == this) { - return 0; - } - if( !(obj instanceof TypeInfo)) { - throw new ClassCastException(); - } - TypeInfo info= (TypeInfo)obj; - if (fElementType != info.fElementType) - return (fElementType < info.fElementType) ? -1 : 1; - return fQualifiedName.compareTo(info.getQualifiedTypeName()); - } - - public static boolean isValidType(int type) { - return ArrayUtil.contains(KNOWN_TYPES, type); - } - - public ITypeCache getCache() { - return fTypeCache; - } - - public void setCache(ITypeCache typeCache) { - fTypeCache = typeCache; - } - - public void addDerivedReference(ITypeReference location) { - if (fDerivedSourceRefs == null) { - fDerivedSourceRefs = new ITypeReference[INITIAL_REFS_SIZE]; - fDerivedSourceRefsCount = 0; - } else if (fDerivedSourceRefsCount == fDerivedSourceRefs.length) { - ITypeReference[] refs = new ITypeReference[fDerivedSourceRefs.length + REFS_GROW_BY]; - System.arraycopy(fDerivedSourceRefs, 0, refs, 0, fDerivedSourceRefsCount); - fDerivedSourceRefs = refs; - } - fDerivedSourceRefs[fDerivedSourceRefsCount] = location; - ++fDerivedSourceRefsCount; - } - - public ITypeReference[] getDerivedReferences() { - if (fDerivedSourceRefs != null) { - ITypeReference[] refs = new ITypeReference[fDerivedSourceRefsCount]; - System.arraycopy(fDerivedSourceRefs, 0, refs, 0, fDerivedSourceRefsCount); - return refs; - } - return null; - } - - public boolean hasSubTypes() { - return (fDerivedSourceRefs != null); - } - - public ITypeInfo[] getSubTypes() { - if (fTypeCache != null) { - return fTypeCache.getSubtypes(this); - } - return null; - } - - public boolean hasSuperTypes() { - if (fTypeCache != null) { - return (fTypeCache.getSupertypes(this) != null); - } - return false; -// return true; //TODO can't know this until we parse - } - - public ITypeInfo[] getSuperTypes() { - if (fTypeCache != null) { - return fTypeCache.getSupertypes(this); - } - return null; - } - - public ASTAccessVisibility getSuperTypeAccess(ITypeInfo superType) { - if (fTypeCache != null) { - return fTypeCache.getSupertypeAccess(this, superType); - } - return null; - } - - public boolean isClass() { - return (fElementType == ICElement.C_CLASS - || fElementType == ICElement.C_STRUCT); - } -} diff --git a/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/core/browser/TypeReference.java b/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/core/browser/TypeReference.java deleted file mode 100644 index cb91663e812..00000000000 --- a/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/core/browser/TypeReference.java +++ /dev/null @@ -1,245 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 QNX Software Systems and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * QNX Software Systems - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.core.browser; - -import org.eclipse.cdt.core.model.CModelException; -import org.eclipse.cdt.core.model.CoreModel; -import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.cdt.core.model.ICProject; -import org.eclipse.cdt.core.model.ITranslationUnit; -import org.eclipse.cdt.core.model.IWorkingCopy; -import org.eclipse.cdt.utils.PathUtil; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.runtime.IPath; - - -public class TypeReference implements ITypeReference { - private IPath fPath; - private IProject fProject; - private IResource fResource; - private IWorkingCopy fWorkingCopy; - private int fOffset; - private int fLength; - public boolean offsetIsLineNumber = false; - - public TypeReference(IPath path, IProject project, int offset, int length) { - fPath = path; - fProject = project; - fWorkingCopy = null; - fResource = null; - fOffset = offset; - fLength = length; - } - - public TypeReference(IResource resource, IProject project, int offset, int length) { - fPath = null; - fProject = project; - fWorkingCopy = null; - fResource = resource; - fOffset = offset; - fLength = length; - } - - public TypeReference(IWorkingCopy workingCopy, IProject project, int offset, int length) { - fPath = null; - fProject = project; - fWorkingCopy = workingCopy; - fResource = null; - fOffset = offset; - fLength = length; - } - - public TypeReference(IPath path, IProject project) { - this(path, project, 0, 0); - } - - public TypeReference(IResource resource, IProject project) { - this(resource, project, 0, 0); - } - - public TypeReference(IWorkingCopy workingCopy, IProject project) { - this(workingCopy, project, 0, 0); - } - - public IPath getPath() { - if (fWorkingCopy != null) { - return fWorkingCopy.getPath(); - } else if (fResource != null) { - return fResource.getFullPath(); - } else { - return fPath; - } - } - - public IPath getLocation() { - if (fWorkingCopy != null) { - IResource resource = fWorkingCopy.getUnderlyingResource(); - if (resource != null) { - return resource.getLocation(); - } - return null; - } else if (fResource != null) { - return fResource.getLocation(); - } else if (fPath != null) { - return fPath; - } else if (fProject != null) { - return fProject.getLocation(); - } else { - return null; - } - } - - public IResource getResource() { - return fResource; - } - - public IWorkingCopy getWorkingCopy() { - return fWorkingCopy; - } - - public IProject getProject() { - if (fProject != null) { - return fProject; - } - if (fWorkingCopy != null) { - ICProject cProject = fWorkingCopy.getCProject(); - if (cProject != null) { - return cProject.getProject(); - } - return null; - } else if (fResource != null) { - return fResource.getProject(); - } else { - return null; - } - } - - public ITranslationUnit getTranslationUnit() { - ITranslationUnit unit = null; - if (fWorkingCopy != null) { - unit = fWorkingCopy.getTranslationUnit(); - } else if (fResource != null) { - ICElement elem = CoreModel.getDefault().create(fResource); - if (elem instanceof ITranslationUnit) - unit = (ITranslationUnit) elem; - } else { - IPath path = getLocation(); - ICElement elem = CoreModel.getDefault().create(path); - if (elem instanceof ITranslationUnit) - unit = (ITranslationUnit) elem; - } - - if (unit == null) { - IProject project = getProject(); - if (project != null) { - ICProject cProject = findCProject(project); - if (cProject != null) { - IPath path = getLocation(); - ICElement elem = CoreModel.getDefault().createTranslationUnitFrom(cProject, path); - if (elem instanceof ITranslationUnit) - unit = (ITranslationUnit) elem; - } - } - } - return unit; - } - - private ICProject findCProject(IProject project) { - try { - ICProject[] cProjects = CoreModel.getDefault().getCModel().getCProjects(); - if (cProjects != null) { - for (int i = 0; i < cProjects.length; ++i) { - ICProject cProject = cProjects[i]; - if (project.equals(cProjects[i].getProject())) - return cProject; - } - } - } catch (CModelException e) { - } - return null; - } - - public ICElement[] getCElements() { - ITranslationUnit unit = getTranslationUnit(); - if (unit != null) { - try { - if( offsetIsLineNumber ) - { - ICElement [] result = new ICElement[1]; - result[0] = unit.getElementAtLine(fOffset); - return result; - } - return unit.getElementsAtOffset(fOffset); - } catch (CModelException e) { - } - } - return null; - } - - public int getOffset() { - return fOffset; - } - - public int getLength() { - return fLength; - } - - public IPath getRelativeIncludePath(IProject project) { - IPath path = getLocation(); - if (path != null) { - IPath relativePath = PathUtil.makeRelativePathToProjectIncludes(path, project); - if (relativePath != null) - return relativePath; - } - return path; - } - - public IPath getRelativePath(IPath relativeToPath) { - IPath path = getPath(); - if (path != null) { - IPath relativePath = PathUtil.makeRelativePath(path, relativeToPath); - if (relativePath != null) - return relativePath; - } - return path; - } - - public String toString() { - IPath path = getLocation(); - if (path != null) { - if (fLength == 0 && fOffset == 0) { - return path.toString(); - } - return path.toString() + ":" + fOffset + "-" + (fOffset + fLength); //$NON-NLS-1$//$NON-NLS-2$ - } - return ""; //$NON-NLS-1$ - } - - public int hashCode() { - return toString().hashCode(); - } - - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - if (!(obj instanceof ITypeReference)) { - return false; - } - ITypeReference ref = (ITypeReference)obj; - return toString().equals(ref.toString()); - } - - public boolean isLineNumber() { - return offsetIsLineNumber; - } -} diff --git a/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/core/browser/TypeSearchScope.java b/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/core/browser/TypeSearchScope.java deleted file mode 100644 index c29ea790f9a..00000000000 --- a/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/core/browser/TypeSearchScope.java +++ /dev/null @@ -1,419 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 QNX Software Systems and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * QNX Software Systems - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.core.browser; - -import java.util.Collection; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Set; - -import org.eclipse.cdt.core.CCorePlugin; -import org.eclipse.cdt.core.CProjectNature; -import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.cdt.core.model.ICProject; -import org.eclipse.cdt.core.model.IWorkingCopy; -import org.eclipse.cdt.core.parser.IScannerInfo; -import org.eclipse.cdt.core.parser.IScannerInfoProvider; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IProjectDescription; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.Path; - -public class TypeSearchScope implements ITypeSearchScope { - - private Set fPathSet = new HashSet(); - private Set fContainerSet = new HashSet(); - private Set fProjectSet = new HashSet(); - private Set fEnclosingProjectSet = new HashSet(); - private boolean fWorkspaceScope = false; - - // cached arrays - private IProject[] fAllProjects = null; - private IProject[] fProjects = null; - private IPath[] fContainerPaths = null; - - public TypeSearchScope() { - } - - public TypeSearchScope(boolean workspaceScope) { - fWorkspaceScope = workspaceScope; - } - - public TypeSearchScope(ITypeSearchScope scope) { - add(scope); - } - - public TypeSearchScope(IProject project) { - add(project); - } - - public Collection pathSet() { - return fPathSet; - } - public Collection containerSet() { - return fContainerSet; - } - public Collection projectSet() { - return fProjectSet; - } - public Collection enclosingProjectSet() { - return fEnclosingProjectSet; - } - - public boolean encloses(ITypeSearchScope scope) { - if (isWorkspaceScope()) - return true; - - if (!scope.pathSet().isEmpty()) { - // check if this scope encloses the other scope's paths - for (Iterator i = scope.pathSet().iterator(); i.hasNext(); ) { - IPath path = (IPath) i.next(); - if (!encloses(path)) - return false; - } - } - - if (!scope.containerSet().isEmpty()) { - // check if this scope encloses the other scope's containers - for (Iterator i = scope.containerSet().iterator(); i.hasNext(); ) { - IPath path = (IPath) i.next(); - if (!encloses(path)) - return false; - } - } - - if (!scope.projectSet().isEmpty()) { - // check if this scope encloses the other scope's projects - for (Iterator i = scope.projectSet().iterator(); i.hasNext(); ) { - IProject project = (IProject) i.next(); - if (!encloses(project)) - return false; - } - } - - return true; - } - - public boolean encloses(IProject project) { - if (isWorkspaceScope()) - return true; - - // check projects that were explicity added to scope - if (fProjectSet.contains(project)) - return true; - - return false; - } - - public boolean encloses(IPath path) { - if (isWorkspaceScope()) - return true; - - // check files that were explicity added to scope - if (fPathSet.contains(path)) - return true; - - // check containers that were explicity added to scope - // including subdirs - if (fContainerSet.contains(path)) - return true; - if (fContainerPaths == null) { - fContainerPaths = (IPath[]) fContainerSet.toArray(new IPath[fContainerSet.size()]); -// java.util.Arrays.sort(fContainerPaths); - } - for (int i = 0; i < fContainerPaths.length; ++i) { - if (fContainerPaths[i].isPrefixOf(path)) { - return true; - } - } - - // check projects that were explicity added to scope - if (fProjectSet.contains(path)) - return true; - - // check projects that were explicity added to scope - if (fProjects == null) { - fProjects = (IProject[]) fProjectSet.toArray(new IProject[fProjectSet.size()]); - } - // check if one of the projects contains path - for (int i = 0; i < fProjects.length; ++i) { - if (projectContainsPath(fProjects[i], path, false)) { - return true; - } - } - - return false; - } - - public boolean encloses(String path) { - return encloses(new Path(path)); - } - - public boolean encloses(ICElement element) { - return encloses(element.getPath()); - } - - public boolean encloses(IWorkingCopy workingCopy) { - return encloses(workingCopy.getOriginalElement().getPath()); - } - - public IProject[] getEnclosingProjects() { - if (isWorkspaceScope()) { - return getAllProjects(); - } - return (IProject[]) fEnclosingProjectSet.toArray(new IProject[fEnclosingProjectSet.size()]); - } - - private static boolean projectContainsPath(IProject project, IPath path, boolean checkIncludePaths) { - IPath projectPath = project.getFullPath(); - if (projectPath.isPrefixOf(path)) { -// ISourceRoot[] sourceRoots = null; -// try { -// sourceRoots = cProject.getSourceRoots(); -// } catch (CModelException ex) { -// } -// if (sourceRoots != null) { -// for (int j = 0; j < sourceRoots.length; ++j) { -// ISourceRoot root = sourceRoots[j]; -// if (root.isOnSourceEntry(path)) -// return true; -// } -// } - return true; - } - - if (checkIncludePaths) { - //TODO this appears to be very slow -- cache this? - IPath[] includePaths = getIncludePaths(project); - if (includePaths != null) { - for (int i = 0; i < includePaths.length; ++i) { - IPath include = includePaths[i]; - if (include.isPrefixOf(path) || include.equals(path)) - return true; - } - } - } - - return false; - } - - private static IPath[] getIncludePaths(IProject project) { - IScannerInfoProvider provider = CCorePlugin.getDefault().getScannerInfoProvider(project); - if (provider != null) { - IScannerInfo info = provider.getScannerInformation(project); - if (info != null) { - String[] includes = info.getIncludePaths(); - if (includes != null && includes.length > 0) { - IPath[] includePaths = new IPath[includes.length]; - for (int i = 0; i < includes.length; ++i) { - includePaths[i] = new Path(includes[i]); - } -// java.util.Arrays.sort(includePaths); - return includePaths; - } - } - } - return null; - } - - private static IProject[] getAllProjects() { - IProject[] projects = getCProjects(); - if (projects == null) - projects = new IProject[0]; - return projects; - } - - private static IProject[] getCProjects() { - IProject[] allProjects = CCorePlugin.getWorkspace().getRoot().getProjects(); - if (allProjects != null) { - IProject[] cProjects = new IProject[allProjects.length]; - int count = 0; - for (int i = 0; i < allProjects.length; ++i) { - IProject project = allProjects[i]; - if (isCProject(project)) { - cProjects[count++] = project; - } - } - if (count > 0) { - if (count == allProjects.length) { - return cProjects; - } - IProject[] newProjects = new IProject[count]; - System.arraycopy(cProjects, 0, newProjects, 0, count); - return newProjects; - } - } - return null; - } - - private static boolean isCProject(IProject project) { - IProjectDescription projDesc = null; - try { - projDesc = project.getDescription(); - if (projDesc == null) - return false; - } catch (CoreException e) { - return false; - } - String[] natures = projDesc.getNatureIds(); - if (natures != null) { - for (int i = 0; i < natures.length; ++i) { - if (natures[i].equals(CProjectNature.C_NATURE_ID)) { - return true; - } - } - } - return false; - } - - public boolean isPathScope() { - return !fPathSet.isEmpty(); - } - - public boolean isProjectScope() { - return !fProjectSet.isEmpty(); - } - - public boolean isWorkspaceScope() { - return fWorkspaceScope; - } - - public boolean isEmpty() { - return (!isWorkspaceScope() && fPathSet.isEmpty() && fContainerSet.isEmpty() && fProjectSet.isEmpty()); - } - - public void add(IWorkingCopy workingCopy) { - IPath path = workingCopy.getOriginalElement().getPath(); - IProject enclosingProject = null; - ICProject cProject = workingCopy.getCProject(); - if (cProject != null) - enclosingProject = cProject.getProject(); - fPathSet.add(path); - if (enclosingProject != null) - addEnclosingProject(enclosingProject); - } - - public void add(IPath path, boolean addSubfolders, IProject enclosingProject) { - if (addSubfolders) { - fContainerSet.add(path); - fContainerPaths = null; - } else { - fPathSet.add(path); - } - if (enclosingProject != null) { - addEnclosingProject(enclosingProject); - } else { - // check all projects in workspace - if (fAllProjects == null) { - fAllProjects = getAllProjects(); - } - // check if one of the projects contains path - for (int i = 0; i < fAllProjects.length; ++i) { - if (projectContainsPath(fAllProjects[i], path, false)) { - addEnclosingProject(fAllProjects[i]); - break; - } - } - } - } - - public void add(IProject project) { - fProjectSet.add(project); - fProjects = null; - fAllProjects = null; - addEnclosingProject(project); - } - - private void addEnclosingProject(IProject project) { - fEnclosingProjectSet.add(project); - } - - public void addWorkspace() { - fWorkspaceScope = true; - fProjects = null; - fAllProjects = null; - } - - public void add(ICElement elem) { - if (elem == null) - return; - - switch (elem.getElementType()) { - case ICElement.C_MODEL: { - addWorkspace(); - break; - } - - case ICElement.C_PROJECT: { - IProject project = ((ICProject)elem).getProject(); - add(project); - break; - } - - case ICElement.C_CCONTAINER: { - IProject project = null; - ICProject cProject = elem.getCProject(); - if (cProject != null) - project = cProject.getProject(); - add(elem.getPath(), true, project); - break; - } - - case ICElement.C_UNIT: { - IProject project = null; - ICProject cProject = elem.getCProject(); - if (cProject != null) - project = cProject.getProject(); - add(elem.getPath(), false, project); - break; - } - - case ICElement.C_INCLUDE: - case ICElement.C_NAMESPACE: - case ICElement.C_TEMPLATE_CLASS: - case ICElement.C_CLASS: - case ICElement.C_STRUCT: - case ICElement.C_UNION: - case ICElement.C_ENUMERATION: - case ICElement.C_TYPEDEF: { - IProject project = null; - ICProject cProject = elem.getCProject(); - if (cProject != null) - project = cProject.getProject(); - add(elem.getPath(), false, project); - break; - } - } - } - - public void add(ITypeSearchScope scope) { - fPathSet.addAll(scope.pathSet()); - fContainerSet.addAll(scope.containerSet()); - fProjectSet.addAll(scope.projectSet()); - fEnclosingProjectSet.addAll(scope.enclosingProjectSet()); - fProjects = null; - fAllProjects = null; - fContainerPaths = null; - fWorkspaceScope |= scope.isWorkspaceScope(); - } - - public void clear() { - fPathSet.clear(); - fContainerSet.clear(); - fProjectSet.clear(); - fEnclosingProjectSet.clear(); - fWorkspaceScope = false; - fProjects = null; - fAllProjects = null; - fContainerPaths = null; - } -} diff --git a/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/core/browser/UnknownTypeInfo.java b/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/core/browser/UnknownTypeInfo.java deleted file mode 100644 index c31921f596c..00000000000 --- a/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/core/browser/UnknownTypeInfo.java +++ /dev/null @@ -1,41 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 QNX Software Systems and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * QNX Software Systems - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.core.browser; - -import org.eclipse.core.runtime.IPath; - -public class UnknownTypeInfo extends TypeInfo { - - public UnknownTypeInfo(String name, IPath path) { - this(new QualifiedTypeName(name)); - if (path != null) { - addReference(new TypeReference(path, null)); - } - } - - public UnknownTypeInfo(IQualifiedTypeName typeName) { - super(0, typeName); - } - - public boolean isUndefinedType() { - return true; - } - - public boolean canSubstituteFor(ITypeInfo info) { - if (fTypeCache == info.getCache()) { - int compareType = info.getCElementType(); - if (fElementType == 0 || compareType == 0 || fElementType == compareType) { - return fQualifiedName.equals(info.getQualifiedTypeName()); - } - } - return false; - } -} diff --git a/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/core/browser/typehierarchy/ChangeCollector.java b/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/core/browser/typehierarchy/ChangeCollector.java deleted file mode 100644 index 71f9fe0f775..00000000000 --- a/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/core/browser/typehierarchy/ChangeCollector.java +++ /dev/null @@ -1,451 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.core.browser.typehierarchy; - -import java.util.*; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; - -import org.eclipse.cdt.core.browser.TypeUtil; -import org.eclipse.cdt.core.model.CModelException; -import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.cdt.core.model.ICElementDelta; -import org.eclipse.cdt.core.model.IMember; -import org.eclipse.cdt.core.model.IParent; -import org.eclipse.cdt.core.model.ITranslationUnit; -import org.eclipse.cdt.internal.core.model.CElement; - -/* - * Collects changes (reported through fine-grained deltas) that can affect a type hierarchy. - */ -public class ChangeCollector { - - /* - * A table from ICElements to TypeDeltas - */ - HashMap changes = new HashMap(); - - TypeHierarchy hierarchy; - - public ChangeCollector(TypeHierarchy hierarchy) { - this.hierarchy = hierarchy; - } - - /* - * Adds the children of the given delta to the list of changes. - */ - private void addAffectedChildren(ICElementDelta delta) throws CModelException { -// ICElementDelta[] children = delta.getAffectedChildren(); -// for (int i = 0, length = children.length; i < length; i++) { -// ICElementDelta child = children[i]; -// ICElement childElement = child.getElement(); -// switch (childElement.getElementType()) { -// case ICElement.IMPORT_CONTAINER: -// addChange((IImportContainer)childElement, child); -// break; -// case ICElement.IMPORT_DECLARATION: -// addChange((IImportDeclaration)childElement, child); -// break; -// case ICElement.TYPE: -// addChange((ICElement)childElement, child); -// break; -// case ICElement.INITIALIZER: -// case ICElement.FIELD: -// case ICElement.METHOD: -// addChange((IMember)childElement, child); -// break; -// } -// } - } - - /* - * Adds the given delta on a compilation unit to the list of changes. - */ - public void addChange(ITranslationUnit cu, ICElementDelta newDelta) throws CModelException { -// int newKind = newDelta.getKind(); -// switch (newKind) { -// case ICElementDelta.ADDED: -// ArrayList allTypes = new ArrayList(); -// getAllTypesFromElement(cu, allTypes); -// for (int i = 0, length = allTypes.size(); i < length; i++) { -// ICElement type = (ICElement)allTypes.get(i); -// addTypeAddition(type, (SimpleDelta)this.changes.get(type)); -// } -// break; -// case ICElementDelta.REMOVED: -// allTypes = new ArrayList(); -// getAllTypesFromHierarchy((JavaElement)cu, allTypes); -// for (int i = 0, length = allTypes.size(); i < length; i++) { -// ICElement type = (ICElement)allTypes.get(i); -// addTypeRemoval(type, (SimpleDelta)this.changes.get(type)); -// } -// break; -// case ICElementDelta.CHANGED: -// addAffectedChildren(newDelta); -// break; -// } - } - -/* private void addChange(IImportContainer importContainer, ICElementDelta newDelta) throws CModelException { - int newKind = newDelta.getKind(); - if (newKind == ICElementDelta.CHANGED) { - addAffectedChildren(newDelta); - return; - } - SimpleDelta existingDelta = (SimpleDelta)this.changes.get(importContainer); - if (existingDelta != null) { - switch (newKind) { - case ICElementDelta.ADDED: - if (existingDelta.getKind() == ICElementDelta.REMOVED) { - // REMOVED then ADDED - this.changes.remove(importContainer); - } - break; - case ICElementDelta.REMOVED: - if (existingDelta.getKind() == ICElementDelta.ADDED) { - // ADDED then REMOVED - this.changes.remove(importContainer); - } - break; - // CHANGED handled above - } - } else { - SimpleDelta delta = new SimpleDelta(); - switch (newKind) { - case ICElementDelta.ADDED: - delta.added(); - break; - case ICElementDelta.REMOVED: - delta.removed(); - break; - } - this.changes.put(importContainer, delta); - } - } - - private void addChange(IImportDeclaration importDecl, ICElementDelta newDelta) { - SimpleDelta existingDelta = (SimpleDelta)this.changes.get(importDecl); - int newKind = newDelta.getKind(); - if (existingDelta != null) { - switch (newKind) { - case ICElementDelta.ADDED: - if (existingDelta.getKind() == ICElementDelta.REMOVED) { - // REMOVED then ADDED - this.changes.remove(importDecl); - } - break; - case ICElementDelta.REMOVED: - if (existingDelta.getKind() == ICElementDelta.ADDED) { - // ADDED then REMOVED - this.changes.remove(importDecl); - } - break; - // CHANGED cannot happen for import declaration - } - } else { - SimpleDelta delta = new SimpleDelta(); - switch (newKind) { - case ICElementDelta.ADDED: - delta.added(); - break; - case ICElementDelta.REMOVED: - delta.removed(); - break; - } - this.changes.put(importDecl, delta); - } - } -*/ - - /* - * Adds a change for the given member (a method, a field or an initializer) and the types it defines. - */ - private void addChange(IMember member, ICElementDelta newDelta) throws CModelException { -// int newKind = newDelta.getKind(); -// switch (newKind) { -// case ICElementDelta.ADDED: -// ArrayList allTypes = new ArrayList(); -// getAllTypesFromElement(member, allTypes); -// for (int i = 0, length = allTypes.size(); i < length; i++) { -// ICElement innerType = (ICElement)allTypes.get(i); -// addTypeAddition(innerType, (SimpleDelta)this.changes.get(innerType)); -// } -// break; -// case ICElementDelta.REMOVED: -// allTypes = new ArrayList(); -// getAllTypesFromHierarchy((JavaElement)member, allTypes); -// for (int i = 0, length = allTypes.size(); i < length; i++) { -// ICElement type = (ICElement)allTypes.get(i); -// addTypeRemoval(type, (SimpleDelta)this.changes.get(type)); -// } -// break; -// case ICElementDelta.CHANGED: -// addAffectedChildren(newDelta); -// break; -// } - } - - /* - * Adds a change for the given type and the types it defines. - */ - private void addChange(ICElement type, ICElementDelta newDelta) throws CModelException { -// int newKind = newDelta.getKind(); -// SimpleDelta existingDelta = (SimpleDelta)this.changes.get(type); -// switch (newKind) { -// case ICElementDelta.ADDED: -// addTypeAddition(type, existingDelta); -// ArrayList allTypes = new ArrayList(); -// getAllTypesFromElement(type, allTypes); -// for (int i = 0, length = allTypes.size(); i < length; i++) { -// ICElement innerType = (ICElement)allTypes.get(i); -// addTypeAddition(innerType, (SimpleDelta)this.changes.get(innerType)); -// } -// break; -// case ICElementDelta.REMOVED: -// addTypeRemoval(type, existingDelta); -// allTypes = new ArrayList(); -// getAllTypesFromHierarchy((JavaElement)type, allTypes); -// for (int i = 0, length = allTypes.size(); i < length; i++) { -// ICElement innerType = (ICElement)allTypes.get(i); -// addTypeRemoval(innerType, (SimpleDelta)this.changes.get(innerType)); -// } -// break; -// case ICElementDelta.CHANGED: -// addTypeChange(type, newDelta.getFlags(), existingDelta); -// addAffectedChildren(newDelta); -// break; -// } - } - -/* private void addTypeAddition(ICElement type, SimpleDelta existingDelta) throws CModelException { - if (existingDelta != null) { - switch (existingDelta.getKind()) { - case ICElementDelta.REMOVED: - // REMOVED then ADDED - boolean hasChange = false; - if (hasSuperTypeChange(type)) { - existingDelta.superTypes(); - hasChange = true; - } - if (hasVisibilityChange(type)) { - existingDelta.modifiers(); - hasChange = true; - } - if (!hasChange) { - this.changes.remove(type); - } - break; - // CHANGED then ADDED - // or ADDED then ADDED: should not happen - } - } else { - // check whether the type addition affects the hierarchy - String typeName = type.getElementName(); - if (this.hierarchy.hasSupertype(typeName) - || this.hierarchy.subtypesIncludeSupertypeOf(type) - || this.hierarchy.missingTypes.contains(typeName)) { - SimpleDelta delta = new SimpleDelta(); - delta.added(); - this.changes.put(type, delta); - } - } - } -*/ -/* private void addTypeChange(ICElement type, int newFlags, SimpleDelta existingDelta) throws CModelException { - if (existingDelta != null) { - switch (existingDelta.getKind()) { - case ICElementDelta.CHANGED: - // CHANGED then CHANGED - int existingFlags = existingDelta.getFlags(); - boolean hasChange = false; - if ((existingFlags & ICElementDelta.F_SUPER_TYPES) != 0 - && hasSuperTypeChange(type)) { - existingDelta.superTypes(); - hasChange = true; - } - if ((existingFlags & ICElementDelta.F_MODIFIERS) != 0 - && hasVisibilityChange(type)) { - existingDelta.modifiers(); - hasChange = true; - } - if (!hasChange) { - // super types and visibility are back to the ones in the existing hierarchy - this.changes.remove(type); - } - break; - // ADDED then CHANGED: leave it as ADDED - // REMOVED then CHANGED: should not happen - } - } else { - // check whether the type change affects the hierarchy - SimpleDelta typeDelta = null; - if ((newFlags & ICElementDelta.F_SUPER_TYPES) != 0 - && this.hierarchy.includesTypeOrSupertype(type)) { - typeDelta = new SimpleDelta(); - typeDelta.superTypes(); - } - if ((newFlags & ICElementDelta.F_MODIFIERS) != 0 - && this.hierarchy.hasSupertype(type.getElementName())) { - if (typeDelta == null) { - typeDelta = new SimpleDelta(); - } - typeDelta.modifiers(); - } - if (typeDelta != null) { - this.changes.put(type, typeDelta); - } - } - } -*/ -/* private void addTypeRemoval(ICElement type, SimpleDelta existingDelta) { - if (existingDelta != null) { - switch (existingDelta.getKind()) { - case ICElementDelta.ADDED: - // ADDED then REMOVED - this.changes.remove(type); - break; - case ICElementDelta.CHANGED: - // CHANGED then REMOVED - existingDelta.removed(); - break; - // REMOVED then REMOVED: should not happen - } - } else { - // check whether the type removal affects the hierarchy - if (this.hierarchy.contains(type)) { - SimpleDelta typeDelta = new SimpleDelta(); - typeDelta.removed(); - this.changes.put(type, typeDelta); - } - } - } -*/ - /* - * Returns all types defined in the given element excluding the given element. - */ - private void getAllTypesFromElement(ICElement element, ArrayList allTypes) throws CModelException { - switch (element.getElementType()) { - case ICElement.C_UNIT: - ICElement[] types = TypeUtil.getTypes((ITranslationUnit)element); - for (int i = 0, length = types.length; i < length; i++) { - ICElement type = types[i]; - allTypes.add(type); - getAllTypesFromElement(type, allTypes); - } - break; - case ICElement.C_CLASS: - case ICElement.C_STRUCT: -// types = ((ICElement)element).getTypes(); - types = TypeUtil.getTypes(element); - for (int i = 0, length = types.length; i < length; i++) { - ICElement type = types[i]; - allTypes.add(type); - getAllTypesFromElement(type, allTypes); - } - break; -// case ICElement.INITIALIZER: -// case ICElement.FIELD: - case ICElement.C_METHOD: - if (element instanceof IParent) { - ICElement[] children = ((IParent)element).getChildren(); - for (int i = 0, length = children.length; i < length; i++) { - ICElement type = (ICElement)children[i]; - allTypes.add(type); - getAllTypesFromElement(type, allTypes); - } - } - break; - } - } - - /* - * Returns all types in the existing hierarchy that have the given element as a parent. - */ - private void getAllTypesFromHierarchy(CElement element, ArrayList allTypes) { - switch (element.getElementType()) { - case ICElement.C_UNIT: - ArrayList types = (ArrayList)this.hierarchy.files.get(element); - if (types != null) { - allTypes.addAll(types); - } - break; - case ICElement.C_CLASS: - case ICElement.C_STRUCT: -// case ICElement.INITIALIZER: -// case ICElement.FIELD: - case ICElement.C_METHOD: - types = (ArrayList)this.hierarchy.files.get(((IMember)element).getTranslationUnit()); - if (types != null) { - for (int i = 0, length = types.size(); i < length; i++) { - ICElement type = (ICElement)types.get(i); - if (element.isAncestorOf(type)) { - allTypes.add(type); - } - } - } - break; - } - } - - private boolean hasSuperTypeChange(ICElement type) throws CModelException { -// // check super class -// ICElement superclass = this.hierarchy.getSuperclass(type); -// String existingSuperclassName = superclass == null ? null : superclass.getElementName(); -// String newSuperclassName = type.getSuperclassName(); -// if (existingSuperclassName != null && !existingSuperclassName.equals(newSuperclassName)) { -// return true; -// } -// -// // check super interfaces -// ICElement[] existingSuperInterfaces = this.hierarchy.getSuperInterfaces(type); -// String[] newSuperInterfaces = type.getSuperInterfaceNames(); -// if (existingSuperInterfaces.length != newSuperInterfaces.length) { -// return true; -// } -// for (int i = 0, length = newSuperInterfaces.length; i < length; i++) { -// String superInterfaceName = newSuperInterfaces[i]; -// if (!superInterfaceName.equals(newSuperInterfaces[i])) { -// return true; -// } -// } - - return false; - } - - private boolean hasVisibilityChange(ICElement type) throws CModelException { -// int existingFlags = this.hierarchy.getCachedFlags(type); -// int newFlags = type.getFlags(); -// return existingFlags != newFlags; - return false; - } - - /* - * Whether the hierarchy needs refresh according to the changes collected so far. - */ - public boolean needsRefresh() { - return changes.size() != 0; - } - - public String toString() { - StringBuffer buffer = new StringBuffer(); - Iterator iterator = this.changes.entrySet().iterator(); - while (iterator.hasNext()) { - Map.Entry entry = (Map.Entry)iterator.next(); - buffer.append(((CElement)entry.getKey()).toDebugString()); - buffer.append(entry.getValue()); - if (iterator.hasNext()) { - buffer.append('\n'); - } - } - return buffer.toString(); - } -} diff --git a/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/core/browser/typehierarchy/ITypeHierarchy.java b/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/core/browser/typehierarchy/ITypeHierarchy.java deleted file mode 100644 index befed906b67..00000000000 --- a/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/core/browser/typehierarchy/ITypeHierarchy.java +++ /dev/null @@ -1,171 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.core.browser.typehierarchy; - -import java.io.OutputStream; - -import org.eclipse.cdt.core.model.CModelException; -import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.core.runtime.IProgressMonitor; - -/** - * A type hierarchy provides navigations between a type and its resolved - * supertypes and subtypes for a specific type or for all types within a region. - * Supertypes may extend outside of the type hierarchy's region in which it was - * created such that the root of the hierarchy is always included. For example, if a type - * hierarchy is created for a java.io.File, and the region the hierarchy was - * created in is the package fragment java.io, the supertype - * java.lang.Object will still be included. - *

- * A type hierarchy is static and can become stale. Although consistent when - * created, it does not automatically track changes in the model. - * As changes in the model potentially invalidate the hierarchy, change notifications - * are sent to registered ICElementHierarchyChangedListeners. Listeners should - * use the exists method to determine if the hierarchy has become completely - * invalid (for example, when the type or project the hierarchy was created on - * has been removed). To refresh a hierarchy, use the refresh method. - *

- *

- * The type hierarchy may contain cycles due to malformed supertype declarations. - * Most type hierarchy queries are oblivious to cycles; the getAll* - * methods are implemented such that they are unaffected by cycles. - *

- *

- * This interface is not intended to be implemented by clients. - *

- */ -public interface ITypeHierarchy { -/** - * Adds the given listener for changes to this type hierarchy. Listeners are - * notified when this type hierarchy changes and needs to be refreshed. - * Has no effect if an identical listener is already registered. - * - * @param listener the listener - */ -void addTypeHierarchyChangedListener(ITypeHierarchyChangedListener listener); -/** - * Returns whether the given type is part of this hierarchy. - * - * @param type the given type - * @return true if the given type is part of this hierarchy, false otherwise - */ -boolean contains(ICElement type); -/** - * Returns whether the type and project this hierarchy was created on exist. - * @return true if the type and project this hierarchy was created on exist, false otherwise - */ -boolean exists(); - -/** - * Returns all resolved subtypes (direct and indirect) of the - * given type, in no particular order, limited to the - * types in this type hierarchy's graph. An empty array - * is returned if there are no resolved subtypes for the - * given type. - * - * @param type the given type - * @return all resolved subtypes (direct and indirect) of the given type - */ -ICElement[] getAllSubtypes(ICElement type); -/** - * Returns all resolved superclasses of the - * given class, in bottom-up order. An empty array - * is returned if there are no resolved superclasses for the - * given class. - * - *

NOTE: once a type hierarchy has been created, it is more efficient to - * query the hierarchy for superclasses than to query a class recursively up - * the superclass chain. Querying an element performs a dynamic resolution, - * whereas the hierarchy returns a pre-computed result. - * - * @param type the given type - * @return all resolved superclasses of the given class, in bottom-up order, an empty - * array if none. - */ -ICElement[] getAllSupertypes(ICElement type); - -/** - * Returns all classes in the graph which have no resolved superclass, - * in no particular order. - * - * @return all classes in the graph which have no resolved superclass - */ -ICElement[] getRootClasses(); - -/** - * Returns the direct resolved subtypes of the given type, - * in no particular order, limited to the types in this - * type hierarchy's graph. - * If the type is a class, this returns the resolved subclasses. - * If the type is an interface, this returns both the classes which implement - * the interface and the interfaces which extend it. - * - * @param type the given type - * @return the direct resolved subtypes of the given type limited to the types in this - * type hierarchy's graph - */ -ICElement[] getSubtypes(ICElement type); - -/** - * Returns the resolved supertypes of the given type, - * in no particular order, limited to the types in this - * type hierarchy's graph. - * For classes, this returns its superclass and the interfaces that the class implements. - * For interfaces, this returns the interfaces that the interface extends. As a consequence - * java.lang.Object is NOT considered to be a supertype of any interface - * type. - * - * @param type the given type - * @return the resolved supertypes of the given type limited to the types in this - * type hierarchy's graph - */ -ICElement[] getSupertypes(ICElement type); -/** - * Returns the type this hierarchy was computed for. - * Returns null if this hierarchy was computed for a region. - * - * @return the type this hierarchy was computed for - */ -ICElement getType(); -/** - * Re-computes the type hierarchy reporting progress. - * - * @param monitor the given progress monitor - * @exception JavaModelException if unable to refresh the hierarchy - */ -void refresh(IProgressMonitor monitor) throws CModelException; -/** - * Removes the given listener from this type hierarchy. - * Has no affect if an identical listener is not registered. - * - * @param listener the listener - */ -void removeTypeHierarchyChangedListener(ITypeHierarchyChangedListener listener); -/** - * Stores the type hierarchy in an output stream. This stored hierarchy can be load by - * ICElement#loadTypeHierachy(IJavaProject, InputStream, IProgressMonitor). - * Listeners of this hierarchy are not stored. - * - * Only hierarchies created by the following methods can be store: - *

    - *
  • ICElement#newSupertypeHierarchy(IProgressMonitor)
  • - *
  • ICElement#newTypeHierarchy(IJavaProject, IProgressMonitor)
  • - *
  • ICElement#newTypeHierarchy(IProgressMonitor)
  • - * - * - * @param outputStream output stream where the hierarchy will be stored - * @param monitor the given progress monitor - * @exception JavaModelException if unable to store the hierarchy in the ouput stream - * @see ICElement#loadTypeHierachy(java.io.InputStream, IProgressMonitor) - * @since 2.1 - */ -void store(OutputStream outputStream, IProgressMonitor monitor) throws CModelException; -} diff --git a/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/core/browser/typehierarchy/ITypeHierarchyChangedListener.java b/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/core/browser/typehierarchy/ITypeHierarchyChangedListener.java deleted file mode 100644 index cc985600ab8..00000000000 --- a/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/core/browser/typehierarchy/ITypeHierarchyChangedListener.java +++ /dev/null @@ -1,29 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.core.browser.typehierarchy; - -/** - * A listener which gets notified when a particular type hierarchy object - * changes. - *

    - * This interface may be implemented by clients. - *

    - */ -public interface ITypeHierarchyChangedListener { - /** - * Notifies that the given type hierarchy has changed in some way and should - * be refreshed at some point to make it consistent with the current state of - * the Java model. - * - * @param typeHierarchy the given type hierarchy - */ - void typeHierarchyChanged(ITypeHierarchy typeHierarchy); -} diff --git a/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/core/browser/typehierarchy/TypeHierarchy.java b/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/core/browser/typehierarchy/TypeHierarchy.java deleted file mode 100644 index 5288ff7e649..00000000000 --- a/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/core/browser/typehierarchy/TypeHierarchy.java +++ /dev/null @@ -1,582 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 QNX Software Systems and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * QNX Software Systems - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.core.browser.typehierarchy; - -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import org.eclipse.cdt.core.ICLogConstants; -import org.eclipse.cdt.core.browser.AllTypesCache; -import org.eclipse.cdt.core.browser.ITypeInfo; -import org.eclipse.cdt.core.model.CModelException; -import org.eclipse.cdt.core.model.CoreModel; -import org.eclipse.cdt.core.model.ElementChangedEvent; -import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.cdt.core.model.ICElementDelta; -import org.eclipse.cdt.core.model.ICProject; -import org.eclipse.cdt.core.model.IElementChangedListener; -import org.eclipse.cdt.core.parser.ast.ASTAccessVisibility; -import org.eclipse.cdt.core.search.ICSearchScope; -import org.eclipse.cdt.internal.core.model.Util; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.ISafeRunnable; -import org.eclipse.core.runtime.Platform; - -public class TypeHierarchy implements ITypeHierarchy, IElementChangedListener { - - public static boolean DEBUG = false; - - private static final class TypeEntry { - ITypeInfo type; - ASTAccessVisibility access; - TypeEntry(ITypeInfo type, ASTAccessVisibility access) { - this.type = type; - this.access = access; - } - } - private static final int INITIAL_SUPER_TYPES = 1; - private static final int INITIAL_SUB_TYPES = 1; - private static final ITypeInfo[] NO_TYPES = new ITypeInfo[0]; - private ArrayList fRootTypes = new ArrayList(); - private Map fTypeToSuperTypes = new HashMap(); - private Map fTypeToSubTypes = new HashMap(); - - private ITypeInfo fFocusType; - - /** - * The progress monitor to report work completed too. - */ - protected IProgressMonitor fProgressMonitor = null; - /** - * Change listeners - null if no one is listening. - */ - protected ArrayList fChangeListeners = null; - - /* - * A map from Openables to ArrayLists of ITypes - */ - public Map files = null; - - /** - * Whether this hierarchy should contains subtypes. - */ - protected boolean fComputeSubtypes; - - /** - * The scope this hierarchy should restrain itsef in. - */ - ICSearchScope fScope; - - /* - * Whether this hierarchy needs refresh - */ - public boolean fNeedsRefresh = true; -// /* -// * Collects changes to types -// */ -// protected ChangeCollector fChangeCollector; - - - - /** - * Creates a TypeHierarchy on the given type. - */ - public TypeHierarchy(ITypeInfo type) { - fFocusType = type; - } - - /** - * Adds the type to the collection of root classes - * if the classes is not already present in the collection. - */ - public void addRootType(ITypeInfo type) { - if (!fRootTypes.contains(type)) { - fRootTypes.add(type); - } - } - - /** - * Adds the given supertype to the type. - */ - public void addSuperType(ITypeInfo type, ITypeInfo superType, ASTAccessVisibility access) { - Collection superEntries = (Collection) fTypeToSuperTypes.get(type); - if (superEntries == null) { - superEntries = new ArrayList(INITIAL_SUPER_TYPES); - fTypeToSuperTypes.put(type, superEntries); - } - Collection subTypes = (Collection) fTypeToSubTypes.get(superType); - if (subTypes == null) { - subTypes = new ArrayList(INITIAL_SUB_TYPES); - fTypeToSubTypes.put(superType, subTypes); - } - if (!subTypes.contains(type)) { - subTypes.add(type); - } - for (Iterator i = superEntries.iterator(); i.hasNext(); ) { - TypeEntry entry = (TypeEntry)i.next(); - if (entry.type.equals(superType)) { - // update the access - entry.access = access; - return; // don't add if already exists - } - } - TypeEntry typeEntry = new TypeEntry(superType, access); - superEntries.add(typeEntry); - } - - /** - * Adds the given subtype to the type. - */ - protected void addSubType(ITypeInfo type, ITypeInfo subType) { - Collection subTypes = (Collection) fTypeToSubTypes.get(type); - if (subTypes == null) { - subTypes = new ArrayList(INITIAL_SUB_TYPES); - fTypeToSubTypes.put(type, subTypes); - } - if (!subTypes.contains(subType)) { - subTypes.add(subType); - } - - Collection superEntries = (Collection) fTypeToSuperTypes.get(subType); - if (superEntries == null) { - superEntries = new ArrayList(INITIAL_SUPER_TYPES); - fTypeToSuperTypes.put(subType, superEntries); - } - for (Iterator i = superEntries.iterator(); i.hasNext(); ) { - TypeEntry entry = (TypeEntry)i.next(); - if (entry.type.equals(type)) - return; // don't add if already exists - } - // default to private access - TypeEntry typeEntry = new TypeEntry(type, ASTAccessVisibility.PRIVATE); - superEntries.add(typeEntry); - } - - /** - * Returns true if type already has the given supertype. - */ - public boolean hasSuperType(ITypeInfo type, ITypeInfo superType) { - Collection entries = (Collection) fTypeToSuperTypes.get(type); - if (entries != null) { - for (Iterator i = entries.iterator(); i.hasNext(); ) { - TypeEntry entry = (TypeEntry)i.next(); - if (entry.type.equals(superType)) - return true; - } - } - return false; - } - - /** - * Returns an array of supertypes for the given type - will never return null. - */ - public ITypeInfo[] getSuperTypes(ITypeInfo type) { - Collection entries = (Collection) fTypeToSuperTypes.get(type); - if (entries != null) { - ArrayList superTypes = new ArrayList(INITIAL_SUPER_TYPES); - for (Iterator i = entries.iterator(); i.hasNext(); ) { - TypeEntry entry = (TypeEntry)i.next(); - superTypes.add(entry.type); - } - return (ITypeInfo[])superTypes.toArray(new ITypeInfo[superTypes.size()]); - } - return NO_TYPES; - } - - /** - * Returns an array of subtypes for the given type - will never return null. - */ - public ITypeInfo[] getSubTypes(ITypeInfo type) { - Collection subTypes = (Collection) fTypeToSubTypes.get(type); - if (subTypes != null) { - return (ITypeInfo[])subTypes.toArray(new ITypeInfo[subTypes.size()]); - } - return NO_TYPES; - } - - /* (non-Javadoc) - * @see org.eclipse.cdt.core.browser.typehierarchy.ITypeHierarchy#addTypeHierarchyChangedListener(org.eclipse.cdt.core.browser.typehierarchy.ITypeHierarchyChangedListener) - */ - public void addTypeHierarchyChangedListener(ITypeHierarchyChangedListener listener) { - ArrayList listeners = fChangeListeners; - if (listeners == null) { - fChangeListeners = listeners = new ArrayList(); - } - - // register with JavaCore to get Java element delta on first listener added - if (listeners.size() == 0) { - CoreModel.getDefault().addElementChangedListener(this); - } - - // add listener only if it is not already present - if (listeners.indexOf(listener) == -1) { - listeners.add(listener); - } - } - - - /** - * @see ITypeHierarchy - */ - public synchronized void removeTypeHierarchyChangedListener(ITypeHierarchyChangedListener listener) { - ArrayList listeners = fChangeListeners; - if (listeners == null) { - return; - } - listeners.remove(listener); - - // deregister from JavaCore on last listener removed - if (listeners.isEmpty()) { - CoreModel.getDefault().removeElementChangedListener(this); - } - } - - /** - * Determines if the change effects this hierarchy, and fires - * change notification if required. - */ - public void elementChanged(ElementChangedEvent event) { - // type hierarchy change has already been fired - if (fNeedsRefresh) return; - - if (isAffected(event.getDelta())) { - fNeedsRefresh = true; - fireChange(); - } - } - - /** - * Returns true if the given delta could change this type hierarchy - */ - public synchronized boolean isAffected(ICElementDelta delta) { -// ICElement element= delta.getElement(); -// switch (element.getElementType()) { -// case ICElement.C_MODEL: -// return isAffectedByCModel(delta, element); -// case ICElement.C_PROJECT: -// return isAffectedByCProject(delta, element); -// case ICElement.C_UNIT: -// return isAffectedByOpenable(delta, element); -// } -// return false; - return true; - } - - /** - * Notifies listeners that this hierarchy has changed and needs - * refreshing. Note that listeners can be removed as we iterate - * through the list. - */ - public void fireChange() { - ArrayList listeners = fChangeListeners; - if (listeners == null) { - return; - } - if (DEBUG) { - System.out.println("FIRING hierarchy change ["+Thread.currentThread()+"]"); //$NON-NLS-1$ //$NON-NLS-2$ - if (fFocusType != null) { - System.out.println(" for hierarchy focused on " + fFocusType.toString()); //$NON-NLS-1$ - } - } - // clone so that a listener cannot have a side-effect on this list when being notified - listeners = (ArrayList)listeners.clone(); - for (int i= 0; i < listeners.size(); i++) { - final ITypeHierarchyChangedListener listener= (ITypeHierarchyChangedListener)listeners.get(i); - Platform.run(new ISafeRunnable() { - public void handleException(Throwable exception) { - Util.log(exception, "Exception occurred in listener of Type hierarchy change notification", ICLogConstants.CDT); //$NON-NLS-1$ - } - public void run() throws Exception { - listener.typeHierarchyChanged(TypeHierarchy.this); - } - }); - } - } - - /* (non-Javadoc) - * @see org.eclipse.cdt.core.browser.typehierarchy.ITypeHierarchy#contains(org.eclipse.cdt.core.model.ICElement) - */ - public boolean contains(ICElement type) { - // classes - ITypeInfo info = AllTypesCache.getTypeForElement(type, true, true, null); - - if (info == null) - return false; - - if (fTypeToSuperTypes.get(info) != null) { - return true; - } - - // root classes - if (fRootTypes.contains(type)) return true; - - return false; - } - - /** - * @see ITypeHierarchy - */ - public boolean exists() { - if (!fNeedsRefresh) return true; - - return (fFocusType == null || fFocusType.exists()) && cProject().exists(); - } - - /** - * Returns the C project this hierarchy was created in. - */ - public ICProject cProject() { - IProject project = fFocusType.getCache().getProject(); - return findCProject(project); - } - private ICProject findCProject(IProject project) { - try { - ICProject[] cProjects = CoreModel.getDefault().getCModel().getCProjects(); - if (cProjects != null) { - for (int i = 0; i < cProjects.length; ++i) { - ICProject cProject = cProjects[i]; - if (project.equals(cProjects[i].getProject())) - return cProject; - } - } - } catch (CModelException e) { - } - return null; - } - - /* (non-Javadoc) - * @see org.eclipse.cdt.core.browser.typehierarchy.ITypeHierarchy#getAllClasses() - */ - public ICElement[] getAllClasses() { - // TODO Auto-generated method stub - return null; - } - - /* (non-Javadoc) - * @see org.eclipse.cdt.core.browser.typehierarchy.ITypeHierarchy#getRootClasses() - */ - public ICElement[] getRootClasses() { - // TODO Auto-generated method stub - return null; - } - - /* (non-Javadoc) - * @see org.eclipse.cdt.core.browser.typehierarchy.ITypeHierarchy#getSubtypes(org.eclipse.cdt.core.model.ICElement) - */ - public ICElement[] getSubtypes(ICElement type) { - List list = new ArrayList(); - ITypeInfo info = AllTypesCache.getTypeForElement(type, true, true, null); - Collection entries = (Collection) fTypeToSubTypes.get(info); - if (entries != null) { - for (Iterator i = entries.iterator(); i.hasNext(); ) { - ITypeInfo subType = (ITypeInfo)i.next(); - ICElement elem = AllTypesCache.getElementForType(subType, true, true, null); - if (elem != null) { - list.add(elem); - } - } - } - return (ICElement[])list.toArray(new ICElement[list.size()]); - } - - /* (non-Javadoc) - * @see org.eclipse.cdt.core.browser.typehierarchy.ITypeHierarchy#getAllSuperclasses(org.eclipse.cdt.core.model.ICElement) - */ - public ICElement[] getAllSubtypes(ICElement type) { - List list = new ArrayList(); - ITypeInfo info = AllTypesCache.getTypeForElement(type, true, true, null); - addSubs(info, list); - //convert list to ICElements - ICElement[] elems = new ICElement[list.size()]; - int count = 0; - for (Iterator i = list.iterator(); i.hasNext(); ) { - ITypeInfo subType = (ITypeInfo) i.next(); - elems[count++] = AllTypesCache.getElementForType(subType, true, true, null); - } - return elems; - } - - private void addSubs(ITypeInfo type, List list) { - Collection entries = (Collection) fTypeToSubTypes.get(type); - if (entries != null) { - for (Iterator i = entries.iterator(); i.hasNext(); ) { - ITypeInfo subType = (ITypeInfo)i.next(); - if (!list.contains(subType)) { - list.add(subType); - } - addSubs(subType, list); - } - } - } - - /* (non-Javadoc) - * @see org.eclipse.cdt.core.browser.typehierarchy.ITypeHierarchy#getSupertypes(org.eclipse.cdt.core.model.ICElement) - */ - public ICElement[] getSupertypes(ICElement type) { - List list = new ArrayList(); - ITypeInfo info = AllTypesCache.getTypeForElement(type, true, true, null); - Collection entries = (Collection) fTypeToSuperTypes.get(info); - if (entries != null) { - for (Iterator i = entries.iterator(); i.hasNext(); ) { - TypeEntry entry = (TypeEntry)i.next(); - ITypeInfo superType = entry.type; - ICElement elem = AllTypesCache.getElementForType(superType, true, true, null); - if (elem != null) { - list.add(elem); - } - } - } - return (ICElement[])list.toArray(new ICElement[list.size()]); - } - - /* (non-Javadoc) - * @see org.eclipse.cdt.core.browser.typehierarchy.ITypeHierarchy#getAllSuperclasses(org.eclipse.cdt.core.model.ICElement) - */ - public ICElement[] getAllSupertypes(ICElement type) { - List list = new ArrayList(); - ITypeInfo info = AllTypesCache.getTypeForElement(type, true, true, null); - addSupers(info, list); - //convert list to ICElements - ICElement[] elems = new ICElement[list.size()]; - int count = 0; - for (Iterator i = list.iterator(); i.hasNext(); ) { - ITypeInfo superType = (ITypeInfo) i.next(); - elems[count++] = AllTypesCache.getElementForType(superType, true, true, null); - } - return elems; - } - - private void addSupers(ITypeInfo type, List list) { - Collection entries = (Collection) fTypeToSuperTypes.get(type); - if (entries != null) { - for (Iterator i = entries.iterator(); i.hasNext(); ) { - TypeEntry entry = (TypeEntry)i.next(); - ITypeInfo superType = entry.type; - if (!list.contains(superType)) { - list.add(superType); - } - addSupers(superType, list); - } - } - } - - /* (non-Javadoc) - * @see org.eclipse.cdt.core.browser.typehierarchy.ITypeHierarchy#getType() - */ - public ICElement getType() { - if (fFocusType != null) - return AllTypesCache.getElementForType(fFocusType, true, true, null); - return null; - } - - /** - * @see ITypeHierarchy - * TODO (jerome) should use a PerThreadObject to build the hierarchy instead of synchronizing - * (see also isAffected(IJavaElementDelta)) - */ - public synchronized void refresh(IProgressMonitor monitor) throws CModelException { - try { - fProgressMonitor = monitor; - if (monitor != null) { - if (fFocusType != null) { - monitor.beginTask(TypeHierarchyMessages.getFormattedString("hierarchy.creatingOnType", fFocusType.getQualifiedTypeName().getFullyQualifiedName()), 100); //$NON-NLS-1$ - } else { - monitor.beginTask(TypeHierarchyMessages.getString("hierarchy.creating"), 100); //$NON-NLS-1$ - } - } - long start = -1; - if (DEBUG) { - start = System.currentTimeMillis(); - if (fComputeSubtypes) { - System.out.println("CREATING TYPE HIERARCHY [" + Thread.currentThread() + "]"); //$NON-NLS-1$ //$NON-NLS-2$ - } else { - System.out.println("CREATING SUPER TYPE HIERARCHY [" + Thread.currentThread() + "]"); //$NON-NLS-1$ //$NON-NLS-2$ - } - if (fFocusType != null) { - System.out.println(" on type " + fFocusType.toString()); //$NON-NLS-1$ - } - } - - compute(); -// initializeRegions(); - fNeedsRefresh = false; -// fChangeCollector = null; - - if (DEBUG) { - if (fComputeSubtypes) { - System.out.println("CREATED TYPE HIERARCHY in " + (System.currentTimeMillis() - start) + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ - } else { - System.out.println("CREATED SUPER TYPE HIERARCHY in " + (System.currentTimeMillis() - start) + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ - } - System.out.println(this.toString()); - } - } finally { - if (monitor != null) { - monitor.done(); - } - fProgressMonitor = null; - } - } - - /** - * Compute this type hierarchy. - */ - protected void compute() { - if (fFocusType != null) { -// HierarchyBuilder builder = -// new IndexBasedHierarchyBuilder( -// this, -// this.scope); -// builder.build(this.computeSubtypes); - -// initialize(1); -// buildSupertypes(); - - } // else a RegionBasedTypeHierarchy should be used - } - - /** - * Initializes this hierarchy's internal tables with the given size. - */ - /* protected void initialize(int size) { - if (size < 10) { - size = 10; - } - int smallSize = (size / 2); - this.classToSuperclass = new HashMap(size); - this.interfaces = new ArrayList(smallSize); - this.missingTypes = new ArrayList(smallSize); - this.rootClasses = new TypeVector(); - this.typeToSubtypes = new HashMap(smallSize); - this.typeToSuperInterfaces = new HashMap(smallSize); - this.typeFlags = new HashMap(smallSize); - - this.projectRegion = new Region(); - this.packageRegion = new Region(); - this.files = new HashMap(5); - } -*/ - - /* (non-Javadoc) - * @see org.eclipse.cdt.core.browser.typehierarchy.ITypeHierarchy#store(java.io.OutputStream, org.eclipse.core.runtime.IProgressMonitor) - */ - public void store(OutputStream outputStream, IProgressMonitor monitor) throws CModelException { - // TODO Auto-generated method stub - - } - -} diff --git a/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/core/browser/typehierarchy/TypeHierarchyBuilder.java b/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/core/browser/typehierarchy/TypeHierarchyBuilder.java deleted file mode 100644 index cded12e9745..00000000000 --- a/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/core/browser/typehierarchy/TypeHierarchyBuilder.java +++ /dev/null @@ -1,129 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 QNX Software Systems and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * QNX Software Systems - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.core.browser.typehierarchy; - -import java.util.HashSet; -import java.util.Set; - -import org.eclipse.cdt.core.browser.ITypeInfo; -import org.eclipse.cdt.core.model.CModelException; -import org.eclipse.cdt.core.model.ICModelStatusConstants; -import org.eclipse.cdt.core.parser.ast.ASTAccessVisibility; -import org.eclipse.cdt.internal.core.browser.cache.TypeCacheManager; -import org.eclipse.cdt.internal.core.model.CModelStatus; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.jobs.Job; - -public class TypeHierarchyBuilder { - - public TypeHierarchyBuilder() { - } - - public ITypeHierarchy createTypeHierarchy(ITypeInfo info, boolean enableIndexing, IProgressMonitor monitor) throws CModelException { - TypeHierarchy typeHierarchy = new TypeHierarchy(info); - Set processedTypes = new HashSet(); - addSuperClasses(typeHierarchy, info, processedTypes, enableIndexing, monitor); - - typeHierarchy.addRootType(info); - processedTypes.clear(); - addSubClasses(typeHierarchy, info, processedTypes, enableIndexing, monitor); - - return typeHierarchy; - } - - private void addSuperClasses(TypeHierarchy typeHierarchy, ITypeInfo type, Set processedTypes, boolean enableIndexing, IProgressMonitor monitor) throws CModelException { - if (type.hasSuperTypes()) { - ITypeInfo[] superTypes = TypeCacheManager.getInstance().locateSuperTypesAndWait(type, enableIndexing, Job.SHORT, monitor); - if (superTypes == null) - throw new CModelException(new CModelStatus(ICModelStatusConstants.ELEMENT_DOES_NOT_EXIST)); - - for (int i = 0; i < superTypes.length; ++i) { - ITypeInfo superType = superTypes[i]; - - // recursively process sub sub classes - if (!processedTypes.contains(superType)) { - processedTypes.add(superType); - addSuperClasses(typeHierarchy, superType, processedTypes, enableIndexing, monitor); - } - - ASTAccessVisibility access = type.getSuperTypeAccess(superType); - - typeHierarchy.addSuperType(type, superType, access); - } - } else { - typeHierarchy.addRootType(type); - } - } - - private void addSubClasses(TypeHierarchy typeHierarchy, ITypeInfo type, Set processedTypes, boolean enableIndexing, IProgressMonitor monitor) throws CModelException { - if (type.hasSubTypes()) { - ITypeInfo[] subTypes = TypeCacheManager.getInstance().locateSubTypesAndWait(type, enableIndexing, Job.SHORT, monitor); - if (subTypes == null) - throw new CModelException(new CModelStatus(ICModelStatusConstants.ELEMENT_DOES_NOT_EXIST)); - - for (int i = 0; i < subTypes.length; ++i) { - ITypeInfo subType = subTypes[i]; - - // recursively process sub sub classes - if (!processedTypes.contains(subType)) { - processedTypes.add(subType); - addSubClasses(typeHierarchy, subType, processedTypes, enableIndexing, monitor); - } - - typeHierarchy.addSubType(type, subType); - } - } - } - -/* - private IStructure findCElementForType(ITypeInfo info, boolean enableIndexing, IProgressMonitor monitor) throws CModelException { - if (!info.exists()) - throw new CModelException(new CModelStatus(ICModelStatusConstants.ELEMENT_DOES_NOT_EXIST)); - - if (!info.isClass()) - throw new CModelException(new CModelStatus(ICModelStatusConstants.INVALID_ELEMENT_TYPES)); - - // first we need to resolve the type location - ITypeReference location = TypeCacheManager.getInstance().locateTypeAndWait(info, enableIndexing, Job.SHORT, monitor); - if (location == null) - throw new CModelException(new CModelStatus(ICModelStatusConstants.ELEMENT_DOES_NOT_EXIST)); - - ICElement cElem = location.getCElement(); - if (cElem == null) - throw new CModelException(new CModelStatus(ICModelStatusConstants.ELEMENT_DOES_NOT_EXIST)); - - if (!(cElem instanceof IStructure)) - throw new CModelException(new CModelStatus(ICModelStatusConstants.INVALID_ELEMENT_TYPES)); - - IStructure cClass = (IStructure)cElem; - - // check if type exists in cache - ITypeInfo type = TypeCacheManager.getInstance().getTypeForElement(cElem); - if (type == null || !type.equals(info)) - throw new CModelException(new CModelStatus(ICModelStatusConstants.ELEMENT_DOES_NOT_EXIST)); - - return cClass; - } - - private ITypeInfo findTypeInCache(ITypeCache cache, String name) { - IQualifiedTypeName qualName = new QualifiedTypeName(name); - ITypeInfo[] superTypes = cache.getTypes(qualName); - for (int i = 0; i < superTypes.length; ++i) { - ITypeInfo superType = superTypes[i]; - if (superType.isClass()) { - return superType; - } - } - return null; - } -*/ - -} diff --git a/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/core/browser/typehierarchy/TypeHierarchyMessages.java b/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/core/browser/typehierarchy/TypeHierarchyMessages.java deleted file mode 100644 index 467841057cf..00000000000 --- a/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/core/browser/typehierarchy/TypeHierarchyMessages.java +++ /dev/null @@ -1,50 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 QNX Software Systems and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * QNX Software Systems - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.core.browser.typehierarchy; - -import java.text.MessageFormat; -import java.util.MissingResourceException; -import java.util.ResourceBundle; - -public class TypeHierarchyMessages { - - private static final String RESOURCE_BUNDLE= TypeHierarchyMessages.class.getName(); - - private static ResourceBundle fgResourceBundle; - static { - try { - fgResourceBundle = ResourceBundle.getBundle(RESOURCE_BUNDLE); - } catch (MissingResourceException x) { - fgResourceBundle = null; - } - } - - private TypeHierarchyMessages() { - } - - public static String getString(String key) { - try { - return fgResourceBundle.getString(key); - } catch (MissingResourceException e) { - return '!' + key + '!'; - } catch (NullPointerException e) { - return "#" + key + "#"; //$NON-NLS-1$ //$NON-NLS-2$ - } - } - - public static String getFormattedString(String key, String arg) { - return getFormattedString(key, new String[] { arg }); - } - - public static String getFormattedString(String key, String[] args) { - return MessageFormat.format(getString(key), args); - } -} diff --git a/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/core/browser/typehierarchy/TypeHierarchyMessages.properties b/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/core/browser/typehierarchy/TypeHierarchyMessages.properties deleted file mode 100644 index 760292b333c..00000000000 --- a/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/core/browser/typehierarchy/TypeHierarchyMessages.properties +++ /dev/null @@ -1,17 +0,0 @@ -############################################################################### -# Copyright (c) 2000, 2004 QNX Software Systems and others. -# All rights reserved. This program and the accompanying materials -# are made available under the terms of the Eclipse Public License v1.0 -# which accompanies this distribution, and is available at -# http://www.eclipse.org/legal/epl-v10.html -# -# Contributors: -# QNX Software Systems - Initial API and implementation -############################################################################### - -### hierarchy -hierarchy.nullProject = Project argument cannot be null -hierarchy.nullRegion = Region cannot be null -hierarchy.nullFocusType = Type focus cannot be null -hierarchy.creating = Creating type hierarchy... -hierarchy.creatingOnType = Creating type hierarchy on {0}... diff --git a/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/internal/core/browser/cache/BasicJob.java b/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/internal/core/browser/cache/BasicJob.java deleted file mode 100644 index 7bf631918b1..00000000000 --- a/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/internal/core/browser/cache/BasicJob.java +++ /dev/null @@ -1,116 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 QNX Software Systems and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * QNX Software Systems - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.core.browser.cache; - -import org.eclipse.cdt.internal.core.browser.util.DelegatedProgressMonitor; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.OperationCanceledException; -import org.eclipse.core.runtime.Status; -import org.eclipse.core.runtime.jobs.Job; - -public abstract class BasicJob extends Job { - - private Object fFamily; - private DelegatedProgressMonitor fProgressMonitor= new DelegatedProgressMonitor(); - private Object fRunLock = new Object(); - private boolean fIsRunning = false; - private static boolean VERBOSE = false; - - public BasicJob(String name, Object family) { - super(name); - fFamily = family; - setPriority(BUILD); - setSystem(true); - } - - /* (non-Javadoc) - * @see org.eclipse.core.runtime.jobs.Job#run(IProgressMonitor) - */ - protected abstract IStatus runWithDelegatedProgress(IProgressMonitor monitor) throws InterruptedException; - - /* (non-Javadoc) - * @see org.eclipse.core.internal.jobs.InternalJob#belongsTo(java.lang.Object) - */ - public boolean belongsTo(Object family) { - if (fFamily != null) { - return fFamily.equals(family); - } - return false; - } - - public boolean isRunning() { - synchronized(fRunLock) { - return fIsRunning; - } - } - - /* (non-Javadoc) - * @see org.eclipse.core.runtime.jobs.Job#run(IProgressMonitor) - */ - public IStatus run(IProgressMonitor monitor) { - synchronized(fRunLock) { - fIsRunning = true; - } - - fProgressMonitor.init(); - fProgressMonitor.addDelegate(monitor); - - IStatus result = Status.CANCEL_STATUS; - try { - if (monitor.isCanceled()) - throw new InterruptedException(); - - result = runWithDelegatedProgress(fProgressMonitor); - - if (monitor.isCanceled()) - throw new InterruptedException(); - } catch(InterruptedException ex) { - return Status.CANCEL_STATUS; - } catch (OperationCanceledException ex) { - return Status.CANCEL_STATUS; - } finally { - fProgressMonitor.done(); - fProgressMonitor.removeAllDelegates(); - fProgressMonitor.init(); - - synchronized(fRunLock) { - fIsRunning = false; - } - } - return result; - } - - /** - * Forwards progress info to the progress monitor and - * blocks until the job is finished. - * - * @param monitor the progress monitor. - * @throws InterruptedException - * - * @see Job#join - */ - public void join(IProgressMonitor monitor) throws InterruptedException { - if (monitor != null) { - fProgressMonitor.addDelegate(monitor); - } - super.join(); - } - - /** - * Outputs message to console. - */ - protected static void trace(String msg) { - if (VERBOSE) { - System.out.println("(" + Thread.currentThread() + ") " + msg); //$NON-NLS-1$ //$NON-NLS-2$ - } - } -} diff --git a/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/internal/core/browser/cache/ITypeCache.java b/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/internal/core/browser/cache/ITypeCache.java deleted file mode 100644 index d4e73fbdaef..00000000000 --- a/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/internal/core/browser/cache/ITypeCache.java +++ /dev/null @@ -1,214 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 QNX Software Systems and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * QNX Software Systems - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.core.browser.cache; - -import org.eclipse.cdt.core.browser.IQualifiedTypeName; -import org.eclipse.cdt.core.browser.ITypeInfo; -import org.eclipse.cdt.core.browser.ITypeInfoVisitor; -import org.eclipse.cdt.core.browser.ITypeReference; -import org.eclipse.cdt.core.browser.ITypeSearchScope; -import org.eclipse.cdt.core.parser.ast.ASTAccessVisibility; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.jobs.ISchedulingRule; - -public interface ITypeCache extends ISchedulingRule { - - /** Returns whether cache contains any types. - * - * @return true if cache is empty - */ - public boolean isEmpty(); - - /** Returns whether cache is complete. - * - * @return true if cache is up to date. - */ - public boolean isUpToDate(); - - /** Inserts type into cache. - * - * @param info - */ - public void insert(ITypeInfo info); - - /** Adds subtype to type. - * - * @param type - * @param subtype - */ - public void addSubtype(ITypeInfo type, ITypeInfo subtype); - - /** Adds supertype to type. - * - * @param type the type - * @param supertype the supertype - * @param the access visibility (PUBLIC, PROTECTED, PRIVATE) - * @param isVirtual true if virtual base class - */ - public void addSupertype(ITypeInfo type, ITypeInfo supertype, ASTAccessVisibility access, boolean isVirtual); - - /** Removes type from cache. - * - * @param info - */ - public void remove(ITypeInfo info); - - /** Removes all types in the given scope. - * - * @param scope - */ - public void flush(ITypeSearchScope scope); - - /** Removes all types referenced by the given path. - * - * @param path - */ - public void flush(IPath path); - - /** Removes all types from the cache. - */ - public void flushAll(); - - /** Returns all paths in the cache which are enclosed by - * the given scope. If no paths are found, an empty - * array is returned. - * - * @param scope the scope to search, or null to - * search the entire cache. - * @return A collection of paths in the given scope. - */ - public IPath[] getPaths(ITypeSearchScope scope); - - /** Returns all types in the cache which are enclosed by - * the given scope. If no types are found, an empty array - * is returned. - * - * @param scope the scope to search, or null to - * search the entire cache. - * @return Array of types in the given scope - */ - public ITypeInfo[] getTypes(ITypeSearchScope scope); - - /** Returns all types in the cache which match the given - * name. If no types are found, an empty array is returned. - * - * @param qualifiedName the qualified type name to match - * @param matchEnclosed true if enclosed types count as matches (foo::bar == bar) - * @param ignoreCase true if case-insensitive - * @return Array of types - */ - public ITypeInfo[] getTypes(IQualifiedTypeName qualifiedName, boolean matchEnclosed, boolean ignoreCase); - - /** Returns first type in the cache which matches the given - * type and name. If no type is found, null - * is returned. - * - * @param type the ICElement type - * @param qualifiedName the qualified type name to match - * @return the matching type - */ - public ITypeInfo getType(int type, IQualifiedTypeName qualifiedName); - - /** Gets the first enclosing type which matches one of the given kinds. - * - * @param info the given type - * @param kinds Array containing CElement types: C_NAMESPACE, C_CLASS, C_STRUCT - * - * @return the enclosing type, or null if not found. - */ - public ITypeInfo getEnclosingType(ITypeInfo info, int[] kinds); - - /** Returns the enclosing namespace for the given type, or - * null if none exists. - * - * @param type the ICElement type - * @param includeGlobalNamespace true if the global (default) namespace should be returned - * @return the enclosing namespace, or null if not found. - */ - public ITypeInfo getEnclosingNamespace(ITypeInfo info, boolean includeGlobalNamespace); - - /** Gets the root namespace of which encloses the given type. - * - * @param info the given type - * @param includeGlobalNamespace true if the global (default) namespace should be returned - * @return the enclosing namespace, or null if not found. - */ - public ITypeInfo getRootNamespace(ITypeInfo info, boolean includeGlobalNamespace); - - /** Returns whether any types are enclosed by the given type. - * - * @param info the given type - * @return true if the given type encloses other types. - */ - public boolean hasEnclosedTypes(ITypeInfo info); - - /** Gets the types which are enclosed by the given type. - * - * @param info the given type - * @param kinds Array containing CElement types: C_NAMESPACE, C_CLASS, - * C_UNION, C_ENUMERATION, C_TYPEDEF - * @return the enclosed types, or an empty array if not found. - */ - public ITypeInfo[] getEnclosedTypes(ITypeInfo info, int kinds[]); - - /** Returns all types in the cache are supertypes of the given type. - * - * @param info the given type - * @return Array of supertypes, or null if none found. - */ - public ITypeInfo[] getSupertypes(ITypeInfo info); - - /** Returns the supertype access visiblity. - * - * @param type the given type - * @param supertype the supertype - * @return the visibility (PRIVATE, PROTECTED, PUBLIC) or null if none found. - */ - public ASTAccessVisibility getSupertypeAccess(ITypeInfo type, ITypeInfo superType); - - - /** Returns all types in the cache which extend the given type. - * - * @param info the given type - * @return Array of subtypes, or null if none found. - */ - public ITypeInfo[] getSubtypes(ITypeInfo info); - - /** Returns the project associated with this cache. - * - * @return the project - */ - public IProject getProject(); - - /** Accepts a visitor and iterates over all types in the cache. - * - * @param visitor - */ - public void accept(ITypeInfoVisitor visitor); - - public void addDelta(TypeCacheDelta delta); - public void reconcile(boolean enableIndexing, int priority, int delay); - public void reconcileAndWait(boolean enableIndexing, int priority, IProgressMonitor monitor); - public void cancelJobs(); - - public void locateType(ITypeInfo info, int priority, int delay); - public ITypeReference locateTypeAndWait(ITypeInfo info, int priority, IProgressMonitor monitor); - - public void locateSupertypes(ITypeInfo info, int priority, int delay); - public ITypeInfo[] locateSupertypesAndWait(ITypeInfo info, int priority, IProgressMonitor monitor); - - public void locateSubtypes(ITypeInfo info, int priority, int delay); - public ITypeInfo[] locateSubtypesAndWait(ITypeInfo info, int priority, IProgressMonitor monitor); - - public ITypeInfo getGlobalNamespace(); -} diff --git a/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/internal/core/browser/cache/IndexerDependenciesJob.java b/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/internal/core/browser/cache/IndexerDependenciesJob.java deleted file mode 100644 index 3e87fdf7d50..00000000000 --- a/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/internal/core/browser/cache/IndexerDependenciesJob.java +++ /dev/null @@ -1,93 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004, 2005 QNX Software Systems and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * QNX Software Systems - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.core.browser.cache; - -import java.io.IOException; - -import org.eclipse.cdt.core.browser.ITypeSearchScope; -import org.eclipse.cdt.internal.core.index.IEntryResult; -import org.eclipse.cdt.internal.core.index.IIndex; -import org.eclipse.cdt.internal.core.index.cindexstorage.Index; -import org.eclipse.cdt.internal.core.index.cindexstorage.IndexedFileEntry; -import org.eclipse.cdt.internal.core.index.cindexstorage.io.BlocksIndexInput; -import org.eclipse.cdt.internal.core.index.cindexstorage.io.IndexInput; -import org.eclipse.cdt.internal.core.search.indexing.IndexManager; -import org.eclipse.cdt.utils.PathUtil; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.IProgressMonitor; - -public class IndexerDependenciesJob extends IndexerJob { - - private ITypeCache fTypeCache; - private ITypeSearchScope fScope; - - public IndexerDependenciesJob(IndexManager indexManager, ITypeCache typeCache, ITypeSearchScope scope) { - super(indexManager, typeCache.getProject()); - fTypeCache = typeCache; - fScope = scope; - } - - protected boolean processIndex(IIndex index, IProject project, IProgressMonitor progressMonitor) throws InterruptedException { - IndexInput input = new BlocksIndexInput(index.getIndexFile()); - try { - input.open(); - flushDependencies(input, progressMonitor); - return true; - } catch (IOException e) { - return false; - } finally { - try { - input.close(); - } catch (IOException e) { - return false; - } - } - } - - private void flushDependencies(IndexInput input, IProgressMonitor progressMonitor) - throws InterruptedException, IOException { - if (progressMonitor.isCanceled()) - throw new InterruptedException(); - - IEntryResult[] includeEntries = input.queryEntriesPrefixedBy(Index.encodeEntry(IIndex.INCLUDE, IIndex.ANY, IIndex.REFERENCE)); - if (includeEntries != null) { - //TODO subprogress monitor - for (int i = 0; i < includeEntries.length; ++i) { - if (progressMonitor.isCanceled()) - throw new InterruptedException(); - - IEntryResult entry = includeEntries[i]; - IPath includePath = getIncludePath(entry); - - if (fScope != null && fScope.encloses(includePath)) { - int[] references = entry.getFileReferences(); - if (references != null) { - for (int j = 0; j < references.length; ++j) { - if (progressMonitor.isCanceled()) - throw new InterruptedException(); - - IndexedFileEntry file = input.getIndexedFile(references[j]); - if (file != null && file.getPath() != null) { - IPath path = PathUtil.getWorkspaceRelativePath(file.getPath()); - fTypeCache.flush(path); - } - } - } - } - } - } - } - - private IPath getIncludePath(IEntryResult entry) { - return PathUtil.getWorkspaceRelativePath(entry.getName()); - } -} diff --git a/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/internal/core/browser/cache/IndexerDependenciesJob2.java b/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/internal/core/browser/cache/IndexerDependenciesJob2.java deleted file mode 100644 index 9b5718de1d7..00000000000 --- a/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/internal/core/browser/cache/IndexerDependenciesJob2.java +++ /dev/null @@ -1,92 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004, 2005 QNX Software Systems and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * QNX Software Systems - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.core.browser.cache; - -import java.io.IOException; - -import org.eclipse.cdt.core.browser.ITypeSearchScope; -import org.eclipse.cdt.internal.core.index.IEntryResult; -import org.eclipse.cdt.internal.core.index.IIndex; -import org.eclipse.cdt.internal.core.index.cindexstorage.Index; -import org.eclipse.cdt.internal.core.index.cindexstorage.IndexedFileEntry; -import org.eclipse.cdt.internal.core.index.cindexstorage.io.BlocksIndexInput; -import org.eclipse.cdt.internal.core.index.cindexstorage.io.IndexInput; -import org.eclipse.cdt.internal.core.search.indexing.IndexManager; -import org.eclipse.cdt.utils.PathUtil; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.IProgressMonitor; - -public class IndexerDependenciesJob2 extends IndexerJob2 { - - private ITypeCache fTypeCache; - private ITypeSearchScope fScope; - - public IndexerDependenciesJob2(IndexManager indexManager, ITypeCache typeCache, ITypeSearchScope scope) { - super(indexManager, typeCache.getProject()); - fTypeCache = typeCache; - fScope = scope; - } - - protected boolean processIndex(IProgressMonitor progressMonitor) throws InterruptedException { - IndexInput input = new BlocksIndexInput(fProjectIndex.getIndexFile()); - try { - input.open(); - flushDependencies(input, progressMonitor); - return true; - } catch (IOException e) { - return false; - } finally { - try { - input.close(); - } catch (IOException e) { - return false; - } - } - } - - private void flushDependencies(IndexInput input, IProgressMonitor progressMonitor) - throws InterruptedException, IOException { - if (progressMonitor.isCanceled()) - throw new InterruptedException(); - - IEntryResult[] includeEntries = input.queryEntriesPrefixedBy(Index.encodeEntry(IIndex.INCLUDE, IIndex.ANY, IIndex.REFERENCE)); - if (includeEntries != null) { - //TODO subprogress monitor - for (int i = 0; i < includeEntries.length; ++i) { - if (progressMonitor.isCanceled()) - throw new InterruptedException(); - - IEntryResult entry = includeEntries[i]; - IPath includePath = getIncludePath(entry); - - if (fScope != null && fScope.encloses(includePath)) { - int[] references = entry.getFileReferences(); - if (references != null) { - for (int j = 0; j < references.length; ++j) { - if (progressMonitor.isCanceled()) - throw new InterruptedException(); - - IndexedFileEntry file = input.getIndexedFile(references[j]); - if (file != null && file.getPath() != null) { - IPath path = PathUtil.getWorkspaceRelativePath(file.getPath()); - fTypeCache.flush(path); - } - } - } - } - } - } - } - - private IPath getIncludePath(IEntryResult entry) { - return PathUtil.getWorkspaceRelativePath(entry.getName()); - } -} diff --git a/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/internal/core/browser/cache/IndexerJob.java b/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/internal/core/browser/cache/IndexerJob.java deleted file mode 100644 index 4de9fba649a..00000000000 --- a/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/internal/core/browser/cache/IndexerJob.java +++ /dev/null @@ -1,157 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial implementation - * QNX Software Systems - adapted for type cache - *******************************************************************************/ -package org.eclipse.cdt.internal.core.browser.cache; - -import java.io.IOException; - -import org.eclipse.cdt.core.index.ICDTIndexer; -import org.eclipse.cdt.internal.core.index.IIndex; -import org.eclipse.cdt.internal.core.index.domsourceindexer.DOMSourceIndexer; -import org.eclipse.cdt.internal.core.search.indexing.IndexManager; -import org.eclipse.cdt.internal.core.search.indexing.ReadWriteMonitor; -import org.eclipse.cdt.internal.core.search.processing.IIndexJob; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IWorkspaceRoot; -import org.eclipse.core.resources.ResourcesPlugin; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.NullProgressMonitor; -import org.eclipse.core.runtime.OperationCanceledException; - -public abstract class IndexerJob implements IIndexJob { - - private IndexManager fIndexManager; - private IProject fProject; - private IIndex fProjectIndex = null; - private DOMSourceIndexer fSourceIndexer = null; - - public static final String FAMILY= "BasicTypeIndexerJob"; //$NON-NLS-1$ - - public IndexerJob(IndexManager indexManager, IProject project) { - fIndexManager = indexManager; - fProject = project; - //Get the indexer assigned to this project; check to see if it's - //a Source Indexder - ICDTIndexer indexer = indexManager.getIndexerForProject(project); - if (indexer instanceof DOMSourceIndexer) - fSourceIndexer = (DOMSourceIndexer) indexer; - } - - public boolean belongsTo(String family) { - return family == FAMILY; - } - - public void cancel() { - } - - public boolean isReadyToRun() { - if (fProjectIndex == null) { // only check once. As long as this job is used, it will keep the same index picture - getIndexForProject(fProject); // will only cache answer if all indexes were available originally - } - return true; - } - - public String toString() { - return FAMILY; - } - - protected abstract boolean processIndex(IIndex index, IProject project, IProgressMonitor progressMonitor) throws InterruptedException; - - public boolean execute(IProgressMonitor progressMonitor) { - boolean success = false; - try { - fProjectIndex = getIndexForProject(fProject); - if (fProjectIndex == null) - return false; - - if (progressMonitor == null) { - progressMonitor = new NullProgressMonitor(); - } - if (progressMonitor.isCanceled()) - throw new OperationCanceledException(); - - progressMonitor.beginTask("", 1); //$NON-NLS-1$ - - success = prepareIndex(fProjectIndex, fProject, progressMonitor); - - if (progressMonitor.isCanceled()) { - throw new OperationCanceledException(); - } - progressMonitor.worked(1); - - return success; - } catch (InterruptedException e) { - throw new OperationCanceledException(); - } finally { - progressMonitor.done(); - } - } - - private boolean prepareIndex(IIndex index, IProject project, IProgressMonitor progressMonitor) throws InterruptedException { - if (progressMonitor.isCanceled()) - throw new InterruptedException(); - - if (index == null) - return COMPLETE; - - if (fSourceIndexer == null) - return FAILED; - - ReadWriteMonitor monitor = fSourceIndexer.getMonitorFor(index); - - if (monitor == null) - return COMPLETE; // index got deleted since acquired - - try { - monitor.enterRead(); // ask permission to read - /* if index has changed, commit these before querying */ - if (index.hasChanged()) { - try { - monitor.exitRead(); // free read lock - monitor.enterWrite(); // ask permission to write - fSourceIndexer.saveIndex(index); - } catch (IOException e) { - return FAILED; - } finally { - monitor.exitWriteEnterRead(); // finished writing and reacquire read permission - } - } - - if (progressMonitor.isCanceled()) - throw new InterruptedException(); - - return processIndex(index, project, progressMonitor); - } finally { - monitor.exitRead(); // finished reading - } - } - - private IIndex getIndexForProject(IProject project) { - IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); - IPath path = project.getFullPath(); - IPath location; - if ((!root.getProject(path.lastSegment()).exists()) // if project does not exist - && path.segmentCount() > 1 - && ((location = root.getFile(path).getLocation()) == null - || !new java.io.File(location.toOSString()).exists()) // and internal jar file does not exist - && !new java.io.File(path.toOSString()).exists()) { // and external jar file does not exist - return null; - } - - // may trigger some index recreation work - if (fSourceIndexer != null) - return fSourceIndexer.getIndex(path, true /*reuse index file*/, false /*do not create if none*/); - - return null; - } -} - diff --git a/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/internal/core/browser/cache/IndexerJob2.java b/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/internal/core/browser/cache/IndexerJob2.java deleted file mode 100644 index 51be068de3e..00000000000 --- a/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/internal/core/browser/cache/IndexerJob2.java +++ /dev/null @@ -1,166 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004,2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * QNX Software Systems - adapted for type cache - *******************************************************************************/ -package org.eclipse.cdt.internal.core.browser.cache; - -import java.io.IOException; - -import org.eclipse.cdt.core.index.ICDTIndexer; -import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.cdt.internal.core.index.IIndex; -import org.eclipse.cdt.internal.core.search.indexing.IndexManager; -import org.eclipse.cdt.internal.core.search.indexing.ReadWriteMonitor; -import org.eclipse.cdt.internal.core.search.processing.IIndexJob; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IWorkspaceRoot; -import org.eclipse.core.resources.ResourcesPlugin; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.NullProgressMonitor; -import org.eclipse.core.runtime.OperationCanceledException; - -public abstract class IndexerJob2 implements IIndexJob { - - protected IProject fProject; - protected IIndex fProjectIndex = null; - protected ICDTIndexer fSourceIndexer = null; - - public static final String FAMILY= "IndexerJob2"; //$NON-NLS-1$ - - public IndexerJob2(IndexManager indexManager, IProject project) { - fProject = project; - fSourceIndexer = indexManager.getIndexerForProject(project); - fProjectIndex = getIndexForProject(); - } - - public boolean belongsTo(String family) { - return family == FAMILY; - } - - public void cancel() { - } - - public boolean isReadyToRun() { - return true; - } - - public String toString() { - return FAMILY; - } - - protected abstract boolean processIndex(IProgressMonitor progressMonitor) throws InterruptedException; - - public boolean execute(IProgressMonitor progressMonitor) { - boolean success = false; - try { - if (fProjectIndex == null) - return false; - - if (progressMonitor == null) { - progressMonitor = new NullProgressMonitor(); - } - if (progressMonitor.isCanceled()) - throw new OperationCanceledException(); - - progressMonitor.beginTask("", 1); //$NON-NLS-1$ - - success = prepareIndex(progressMonitor); - - if (progressMonitor.isCanceled()) { - throw new OperationCanceledException(); - } - progressMonitor.worked(1); - - return success; - } catch (InterruptedException e) { - throw new OperationCanceledException(); - } finally { - progressMonitor.done(); - } - } - - private boolean prepareIndex(IProgressMonitor progressMonitor) throws InterruptedException { - if (progressMonitor.isCanceled()) - throw new InterruptedException(); - - if (fProjectIndex == null) - return COMPLETE; - - if (fSourceIndexer == null) - return FAILED; - - ReadWriteMonitor monitor = fSourceIndexer.getMonitorFor(fProjectIndex); - - if (monitor == null) - return COMPLETE; // index got deleted since acquired - - try { - monitor.enterRead(); // ask permission to read - /* if index has changed, commit these before querying */ - if (fProjectIndex.hasChanged()) { - try { - monitor.exitRead(); // free read lock - monitor.enterWrite(); // ask permission to write - fSourceIndexer.saveIndex(fProjectIndex); - } catch (IOException e) { - return FAILED; - } finally { - monitor.exitWriteEnterRead(); // finished writing and reacquire read permission - } - } - - if (progressMonitor.isCanceled()) - throw new InterruptedException(); - - return processIndex(progressMonitor); - } finally { - monitor.exitRead(); // finished reading - } - } - - private IIndex getIndexForProject() { - IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); - IPath path = fProject.getFullPath(); - IPath location; - if ((!root.getProject(path.lastSegment()).exists()) // if project does not exist - && path.segmentCount() > 1 - && ((location = root.getFile(path).getLocation()) == null - || !new java.io.File(location.toOSString()).exists()) // and internal jar file does not exist - && !new java.io.File(path.toOSString()).exists()) { // and external jar file does not exist - return null; - } - - // may trigger some index recreation work - if (fSourceIndexer != null) - return fSourceIndexer.getIndex(path, true /*reuse index file*/, false /*do not create if none*/); - - return null; - } - - protected int index2ICElement( int kind ) - { - switch(kind) { - case IIndex.TYPE_CLASS: - return ICElement.C_CLASS; - case IIndex.TYPE_STRUCT: - return ICElement.C_STRUCT; - case IIndex.TYPE_ENUM: - return ICElement.C_ENUMERATION; - case IIndex.TYPE_UNION: - return ICElement.C_UNION; - case IIndex.TYPE_TYPEDEF: - return ICElement.C_TYPEDEF; - default: - return 0; - } - } -} - diff --git a/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/internal/core/browser/cache/IndexerTypesJob.java b/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/internal/core/browser/cache/IndexerTypesJob.java deleted file mode 100644 index d5509522612..00000000000 --- a/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/internal/core/browser/cache/IndexerTypesJob.java +++ /dev/null @@ -1,186 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004, 2005 QNX Software Systems and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * QNX Software Systems - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.core.browser.cache; - -import java.io.IOException; - -import org.eclipse.cdt.core.browser.ITypeInfo; -import org.eclipse.cdt.core.browser.ITypeSearchScope; -import org.eclipse.cdt.core.browser.QualifiedTypeName; -import org.eclipse.cdt.core.browser.TypeInfo; -import org.eclipse.cdt.core.browser.TypeReference; -import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.cdt.internal.core.index.IEntryResult; -import org.eclipse.cdt.internal.core.index.IIndex; -import org.eclipse.cdt.internal.core.index.cindexstorage.Index; -import org.eclipse.cdt.internal.core.index.cindexstorage.IndexedFileEntry; -import org.eclipse.cdt.internal.core.index.cindexstorage.io.BlocksIndexInput; -import org.eclipse.cdt.internal.core.index.cindexstorage.io.IndexInput; -import org.eclipse.cdt.internal.core.search.indexing.IndexManager; -import org.eclipse.cdt.utils.PathUtil; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.IProgressMonitor; - -public class IndexerTypesJob extends IndexerJob { - - private ITypeCache fTypeCache; - - public IndexerTypesJob(IndexManager indexManager, ITypeCache typeCache, ITypeSearchScope scope) { - super(indexManager, typeCache.getProject()); - fTypeCache = typeCache; - } - - protected boolean processIndex(IIndex index, IProject project, IProgressMonitor progressMonitor) throws InterruptedException { - IndexInput input = new BlocksIndexInput(index.getIndexFile()); - try { - input.open(); - updateNamespaces(input, project, progressMonitor); - updateTypes(input, project, progressMonitor); - return true; - } catch (IOException e) { - return false; - } finally { - try { - input.close(); - } catch (IOException e) { - return false; - } - } - } - - private void updateNamespaces(IndexInput input, IProject project, IProgressMonitor monitor) - throws InterruptedException, IOException { - if (monitor.isCanceled()) - throw new InterruptedException(); - - IEntryResult[] namespaceEntries = input.queryEntriesPrefixedBy(Index.encodeEntry(IIndex.NAMESPACE, IIndex.ANY, IIndex.DECLARATION)); - if (namespaceEntries != null) { - //TODO subprogress monitor - for (int i = 0; i < namespaceEntries.length; ++i) { - if (monitor.isCanceled()) - throw new InterruptedException(); - - IEntryResult entry = namespaceEntries[i]; - String name = entry.getName(); - if (name.length() != 0) { - String[] enclosingNames = entry.getEnclosingNames(); - addType(input, project, entry, ICElement.C_NAMESPACE, name, enclosingNames, monitor); - } - } - } - } - - private void updateTypes(IndexInput input, IProject project, IProgressMonitor monitor) - throws InterruptedException, IOException { - if (monitor.isCanceled()) - throw new InterruptedException(); - - IEntryResult[] typeEntries = input.queryEntriesPrefixedBy(Index.encodeEntry(IIndex.TYPE, IIndex.ANY, IIndex.DECLARATION)); - if (typeEntries != null) { - //TODO subprogress monitor - for (int i = 0; i < typeEntries.length; ++i) { - if (monitor.isCanceled()) - throw new InterruptedException(); - - IEntryResult entry = typeEntries[i]; - - String name = entry.getName(); - switch (entry.getKind() ) { - case IIndex.TYPE_CLASS : - case IIndex.TYPE_STRUCT : - case IIndex.TYPE_TYPEDEF : - case IIndex.TYPE_ENUM : - case IIndex.TYPE_UNION : - if (name.length() != 0) { // skip anonymous structs - addType(input, project, entry, entry.getKind(), name, entry.getEnclosingNames(), monitor); - } - break; - case IIndex.TYPE_DERIVED : - if (name.length() != 0) { // skip anonymous structs - addSuperTypeReference(input, project, entry, name, entry.getEnclosingNames(), monitor); - } - break; - default: - break; - } - } - } - } - - private void addType(IndexInput input, IProject project, IEntryResult entry, int type, String name, String[] enclosingNames, IProgressMonitor monitor) - throws InterruptedException, IOException { - QualifiedTypeName qualifiedName = new QualifiedTypeName(name, enclosingNames); - ITypeInfo info = fTypeCache.getType(type, qualifiedName); - if (info == null || info.isUndefinedType()) { - int[] references = entry.getFileReferences(); - if (references != null && references.length > 0) { - // add new type to cache - if (info != null) { - info.setCElementType(type); - } else { - info = new TypeInfo(type, qualifiedName); - fTypeCache.insert(info); - } - -// for (int i = 0; i < references.length; ++i) { -// if (monitor.isCanceled()) -// throw new InterruptedException(); -// -// IndexedFile file = input.getIndexedFile(references[i]); -// if (file != null && file.getPath() != null) { -// IPath path = PathUtil.getWorkspaceRelativePath(file.getPath()); -// info.addReference(new TypeReference(path, project)); -// } -// } - // just grab the first reference - IndexedFileEntry file = input.getIndexedFile(references[0]); - if (file != null && file.getPath() != null) { - IPath path = PathUtil.getWorkspaceRelativePath(file.getPath()); - info.addReference(new TypeReference(path, project)); - } - } - } - } - - private void addSuperTypeReference(IndexInput input, IProject project, IEntryResult entry, String name, String[] enclosingNames, IProgressMonitor monitor) throws InterruptedException, IOException { - QualifiedTypeName qualifiedName = new QualifiedTypeName(name, enclosingNames); - ITypeInfo info = fTypeCache.getType(ICElement.C_CLASS, qualifiedName); - if (info == null) - info = fTypeCache.getType(ICElement.C_STRUCT, qualifiedName); - if (info == null) { - // add dummy type to cache - info = new TypeInfo(0, qualifiedName); - fTypeCache.insert(info); - } - int[] references = entry.getFileReferences(); - if (references != null && references.length > 0) { - for (int i = 0; i < references.length; ++i) { - if (monitor.isCanceled()) - throw new InterruptedException(); - - IndexedFileEntry file = input.getIndexedFile(references[i]); - if (file != null && file.getPath() != null) { - IPath path = PathUtil.getWorkspaceRelativePath(file.getPath()); - info.addDerivedReference(new TypeReference(path, project)); -// -// // get absolute path -// IPath path = new Path(file.getPath()); -// IPath projectPath = project.getFullPath(); -// if (projectPath.isPrefixOf(path)) { -// path = project.getLocation().append(path.removeFirstSegments(projectPath.segmentCount())); -// } -// info.addDerivedReference(new TypeReference(path, project)); - } - } - } - } -} diff --git a/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/internal/core/browser/cache/IndexerTypesJob2.java b/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/internal/core/browser/cache/IndexerTypesJob2.java deleted file mode 100644 index daecedab086..00000000000 --- a/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/internal/core/browser/cache/IndexerTypesJob2.java +++ /dev/null @@ -1,229 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004, 2005 QNX Software Systems and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * QNX Software Systems - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.core.browser.cache; - -import java.io.IOException; - -import org.eclipse.cdt.core.browser.ITypeInfo; -import org.eclipse.cdt.core.browser.ITypeSearchScope; -import org.eclipse.cdt.core.browser.QualifiedTypeName; -import org.eclipse.cdt.core.browser.TypeInfo; -import org.eclipse.cdt.core.browser.TypeReference; -import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.cdt.internal.core.index.IEntryResult; -import org.eclipse.cdt.internal.core.index.IIndex; -import org.eclipse.cdt.internal.core.index.IQueryResult; -import org.eclipse.cdt.internal.core.index.cindexstorage.io.BlocksIndexInput; -import org.eclipse.cdt.internal.core.index.cindexstorage.io.IndexInput; -import org.eclipse.cdt.internal.core.search.indexing.IndexManager; -import org.eclipse.cdt.utils.PathUtil; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.IProgressMonitor; - -public class IndexerTypesJob2 extends IndexerJob2 { - - private ITypeCache fTypeCache; - - public IndexerTypesJob2(IndexManager indexManager, ITypeCache typeCache, ITypeSearchScope scope) { - super(indexManager, typeCache.getProject()); - fTypeCache = typeCache; - } - - protected boolean processIndex(IProgressMonitor progressMonitor) throws InterruptedException { - IndexInput input = null; - try { - input = new BlocksIndexInput( fProjectIndex.getIndexFile() ); - input.open(); - updateNamespaces(input, progressMonitor); - updateTypes(input, progressMonitor); - return true; - } catch (IOException e) { - return false; - } finally { - if (input != null) { - try { - input.close(); - } catch (IOException e) { - // do nothing - } - } - } - } - - private void updateNamespaces(IndexInput input, IProgressMonitor monitor) - throws InterruptedException, IOException { - if (monitor.isCanceled()) - throw new InterruptedException(); - - IEntryResult[] namespaceEntries = fProjectIndex.getEntries( IIndex.NAMESPACE, IIndex.ANY, IIndex.DEFINITION ); - IQueryResult[] namespacePaths = fProjectIndex.getPrefix(IIndex.NAMESPACE, IIndex.ANY, IIndex.DEFINITION ); -// input.queryEntriesPrefixedBy(Index.encodeEntry(IIndex.NAMESPACE, IIndex.ANY, IIndex.DECLARATION)); - if (namespaceEntries != null) { - //TODO subprogress monitor - for (int i = 0; i < namespaceEntries.length; ++i) { - if (monitor.isCanceled()) - throw new InterruptedException(); - - IEntryResult entry = namespaceEntries[i]; - String name = entry.getName(); - if (name.length() != 0) { - String[] enclosingNames = entry.getEnclosingNames(); - addType(input, entry, namespacePaths[i].getPath(), ICElement.C_NAMESPACE, name, enclosingNames, monitor); - } - } - } - } - - private void updateTypes(IndexInput input, IProgressMonitor monitor) - throws InterruptedException, IOException { - if (monitor.isCanceled()) - throw new InterruptedException(); - - for( int counter = 0; counter < 2; ++counter ) - { - IEntryResult[] typeEntries = fProjectIndex.getEntries( IIndex.TYPE, IIndex.ANY, ( counter == 0 ) ? IIndex.DECLARATION : IIndex.DEFINITION ); - - if (typeEntries != null) { - //TODO subprogress monitor - for (int i = 0; i < typeEntries.length; ++i) { - if (monitor.isCanceled()) - throw new InterruptedException(); - - IEntryResult entry = typeEntries[i]; - - String name = entry.extractSimpleName(); - switch (entry.getKind() ) { - case IIndex.TYPE_CLASS : - case IIndex.TYPE_STRUCT : - case IIndex.TYPE_TYPEDEF : - case IIndex.TYPE_ENUM : - case IIndex.TYPE_UNION : - if (counter != 0 && name.length() != 0) { // skip anonymous structs - addType(input, entry, null, index2ICElement( entry.getKind() ), name, entry.getEnclosingNames(), monitor); - } - break; - default: - break; - } - } - } - } - - IEntryResult[] typeEntries = fProjectIndex.getEntries( IIndex.TYPE, IIndex.TYPE_DERIVED, IIndex.ANY ); - if (typeEntries != null){ - for( int j = 0; j < typeEntries.length; ++j ) - { - if (monitor.isCanceled()) - throw new InterruptedException(); - - IEntryResult entry = typeEntries[j]; - String name = entry.extractSimpleName(); - switch( entry.getKind() ) - { - case IIndex.TYPE_DERIVED : - if (name.length() != 0) { // skip anonymous structs - addSuperTypeReference(input, entry, name, entry.getEnclosingNames(), monitor); - } - break; - default: - break; - } - } - } - } - - private void addType(IndexInput input, IEntryResult entry, String pth, int type, String name, String[] enclosingNames, IProgressMonitor monitor) - throws InterruptedException, IOException { - QualifiedTypeName qualifiedName = new QualifiedTypeName(name, enclosingNames); - ITypeInfo info = fTypeCache.getType(type, qualifiedName); - if (info == null || info.isUndefinedType()) { - int[] references = entry.getFileReferences(); - if (references != null && references.length > 0) { - // add new type to cache - if (info != null) { - info.setCElementType(type); - } else { - info = new TypeInfo(type, qualifiedName); - fTypeCache.insert(info); - } - -// for (int i = 0; i < references.length; ++i) { -// if (monitor.isCanceled()) -// throw new InterruptedException(); -// -// IndexedFile file = input.getIndexedFile(references[i]); -// if (file != null && file.getPath() != null) { -// IPath path = PathUtil.getWorkspaceRelativePath(file.getPath()); -// info.addReference(new TypeReference(path, project)); -// } -// } - if (pth == null) { - pth = input.getIndexedFile( references[0] ).getPath(); - } - - final IPath workspaceRelativePath = PathUtil.getWorkspaceRelativePath(pth); - int offset = entry.getOffsets()[0][0]; -// int offsetType = Integer.valueOf(String.valueOf(offsets[i][j]).substring(0,1)).intValue(); - int offsetType = offset; - int m = 1; - while (offsetType >= 10) { - offsetType = offsetType / 10; - m *= 10; - } - int value = offset - ( offsetType * m ); -// int value = Integer.valueOf(String.valueOf(offset).substring(1)).intValue(); - - TypeReference typeReference = null; - if (offsetType==IIndex.LINE){ - typeReference = new TypeReference(workspaceRelativePath, fProject, value, 0 ); - typeReference.offsetIsLineNumber = true; - }else if (offsetType==IIndex.OFFSET){ - typeReference = new TypeReference(workspaceRelativePath, fProject, value, entry.getOffsetLengths()[0][0] ); - } - if( typeReference != null ) - info.addReference(typeReference); - } - } - } - - private void addSuperTypeReference(IndexInput input, IEntryResult entry, String name, String[] enclosingNames, IProgressMonitor monitor) throws InterruptedException, IOException { - QualifiedTypeName qualifiedName = new QualifiedTypeName(name, enclosingNames); - ITypeInfo info = fTypeCache.getType(ICElement.C_CLASS, qualifiedName); - if (info == null) - info = fTypeCache.getType(ICElement.C_STRUCT, qualifiedName); - if (info == null) { - // add dummy type to cache - info = new TypeInfo(0, qualifiedName); - fTypeCache.insert(info); - } - int[] references = entry.getFileReferences(); - if (references != null && references.length > 0) { - for (int i = 0; i < references.length; ++i) { - if (monitor.isCanceled()) - throw new InterruptedException(); - - String pth = input.getIndexedFile( references[i] ).getPath(); - IPath path = PathUtil.getWorkspaceRelativePath(pth); - - info.addDerivedReference(new TypeReference(path, fProject)); -// -// // get absolute path -// IPath path = new Path(file.getPath()); -// IPath projectPath = project.getFullPath(); -// if (projectPath.isPrefixOf(path)) { -// path = project.getLocation().append(path.removeFirstSegments(projectPath.segmentCount())); -// } -// info.addDerivedReference(new TypeReference(path, project)); - - } - } - } -} diff --git a/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/internal/core/browser/cache/SubTypeLocatorJob.java b/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/internal/core/browser/cache/SubTypeLocatorJob.java deleted file mode 100644 index 7909c033a9d..00000000000 --- a/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/internal/core/browser/cache/SubTypeLocatorJob.java +++ /dev/null @@ -1,67 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 QNX Software Systems and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * QNX Software Systems - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.core.browser.cache; - -import org.eclipse.cdt.core.browser.ITypeInfo; -import org.eclipse.cdt.core.model.IWorkingCopyProvider; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.Status; -import org.eclipse.core.runtime.SubProgressMonitor; - -public class SubTypeLocatorJob extends BasicJob { - - public static final Object FAMILY = new Object(); - private ITypeInfo fLocateType; - private ITypeCache fTypeCache; - private IWorkingCopyProvider fWorkingCopyProvider; - - public SubTypeLocatorJob(ITypeInfo info, ITypeCache typeCache, IWorkingCopyProvider workingCopyProvider) { - super(TypeCacheMessages.getString("SubTypeLocatorJob.jobName"), FAMILY); //$NON-NLS-1$ - fLocateType = info; - fTypeCache = typeCache; - fWorkingCopyProvider= workingCopyProvider; - } - - public ITypeInfo getType() { - return fLocateType; - } - - protected IStatus runWithDelegatedProgress(IProgressMonitor monitor) throws InterruptedException { - boolean success = false; - long startTime = System.currentTimeMillis(); - trace("SubTypeLocatorJob: started"); //$NON-NLS-1$ - - try { - monitor.beginTask(TypeCacheMessages.getString("SubTypeLocatorJob.taskName"), 100); //$NON-NLS-1$ - - if (monitor.isCanceled()) - throw new InterruptedException(); - - TypeParser parser = new TypeParser(fTypeCache, fWorkingCopyProvider); - success = parser.findSubTypes(fLocateType, new SubProgressMonitor(monitor, 100)); - - if (monitor.isCanceled()) - throw new InterruptedException(); - - } finally { - long executionTime = System.currentTimeMillis() - startTime; - if (success) - trace("SubTypeLocatorJob: completed ("+ executionTime + " ms)"); //$NON-NLS-1$ //$NON-NLS-2$ - else - trace("SubTypeLocatorJob: aborted ("+ executionTime + " ms)"); //$NON-NLS-1$ //$NON-NLS-2$ - - monitor.done(); - } - - return Status.OK_STATUS; - } -} diff --git a/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/internal/core/browser/cache/TypeCache.java b/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/internal/core/browser/cache/TypeCache.java deleted file mode 100644 index 592f7d99d39..00000000000 --- a/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/internal/core/browser/cache/TypeCache.java +++ /dev/null @@ -1,895 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 QNX Software Systems and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * QNX Software Systems - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.core.browser.cache; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Map; -import java.util.Set; - -import org.eclipse.cdt.core.browser.IQualifiedTypeName; -import org.eclipse.cdt.core.browser.ITypeCacheChangedListener; -import org.eclipse.cdt.core.browser.ITypeInfo; -import org.eclipse.cdt.core.browser.ITypeInfoVisitor; -import org.eclipse.cdt.core.browser.ITypeReference; -import org.eclipse.cdt.core.browser.ITypeSearchScope; -import org.eclipse.cdt.core.browser.QualifiedTypeName; -import org.eclipse.cdt.core.browser.TypeInfo; -import org.eclipse.cdt.core.browser.TypeSearchScope; -import org.eclipse.cdt.core.index.ICDTIndexer; -import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.cdt.core.model.IWorkingCopyProvider; -import org.eclipse.cdt.core.parser.ast.ASTAccessVisibility; -import org.eclipse.cdt.internal.core.browser.util.ArrayUtil; -import org.eclipse.cdt.internal.core.model.CModelManager; -import org.eclipse.cdt.internal.core.search.indexing.IndexManager; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.Platform; -import org.eclipse.core.runtime.Status; -import org.eclipse.core.runtime.jobs.IJobChangeEvent; -import org.eclipse.core.runtime.jobs.IJobChangeListener; -import org.eclipse.core.runtime.jobs.IJobManager; -import org.eclipse.core.runtime.jobs.ISchedulingRule; -import org.eclipse.core.runtime.jobs.Job; - -public class TypeCache implements ITypeCache { - - private static final int INITIAL_TYPE_COUNT = 100; - private final Map fTypeKeyMap = new HashMap(INITIAL_TYPE_COUNT); - final IProject fProject; - private final IWorkingCopyProvider fWorkingCopyProvider; - final Collection fDeltas = new ArrayList(); - final ITypeInfo fGlobalNamespace; - private final Map fTypeToSubTypes = new HashMap(); - private final Map fTypeToSuperTypes = new HashMap(); - ITypeCacheChangedListener fChangeListener = null; - - private static final class SuperTypeEntry { - ITypeInfo superType; - ASTAccessVisibility access; - boolean isVirtual; - SuperTypeEntry(ITypeInfo superType, ASTAccessVisibility access, boolean isVirtual) { - this.superType = superType; - this.access = access; - this.isVirtual = isVirtual; - } - } - - private SuperTypeEntry findSuperTypeEntry(Collection entryCollection, ITypeInfo superType) { - for (Iterator i = entryCollection.iterator(); i.hasNext(); ) { - SuperTypeEntry e = (SuperTypeEntry) i.next(); - if (e.superType.equals(superType)) { - return e; - } - } - return null; - } - - private static final int[] ENCLOSING_TYPES = {ICElement.C_NAMESPACE, ICElement.C_CLASS, ICElement.C_STRUCT, 0}; - - private IJobChangeListener fJobChangeListener = new IJobChangeListener() { - public void aboutToRun(IJobChangeEvent event) { - } - - public void awake(IJobChangeEvent event) { - } - - public void done(IJobChangeEvent event) { - Job job = event.getJob(); - if (job instanceof TypeCacherJob) { - TypeCacherJob deltaJob = (TypeCacherJob)job; - IStatus status = event.getResult(); - if (status != null) { - boolean jobFinished = (status.equals(Status.OK_STATUS) - && !deltaJob.isIndexerBusy()); - // remove the completed deltas - synchronized(fDeltas) { - for (Iterator i = fDeltas.iterator(); i.hasNext(); ) { - TypeCacheDelta delta = (TypeCacheDelta) i.next(); - if (delta.getJob() != null && delta.getJob().equals(deltaJob)) { - if (jobFinished) { - i.remove(); - } else { - delta.assignToJob(null); - } - } - } - } - } - // TODO finer-grained change deltas - if (fChangeListener != null) - fChangeListener.typeCacheChanged(fProject); - } - } - - public void running(IJobChangeEvent event) { - } - - public void scheduled(IJobChangeEvent event) { - } - - public void sleeping(IJobChangeEvent event) { - } - }; - - private static class GlobalNamespace implements IQualifiedTypeName { - - private static final String GLOBAL_NAMESPACE = TypeCacheMessages.getString("TypeCache.globalNamespace"); //$NON-NLS-1$ - private static final String[] segments = new String[] { GLOBAL_NAMESPACE }; - - public GlobalNamespace() { - } - - public String getName() { - return GLOBAL_NAMESPACE; - } - - public String[] getEnclosingNames() { - return null; - } - - public String getFullyQualifiedName() { - return GLOBAL_NAMESPACE; - } - - public IQualifiedTypeName getEnclosingTypeName() { - return null; - } - - public boolean isEmpty() { - return false; - } - - public boolean isGlobal() { - return true; - } - - public boolean isQualified() { - return false; - } - - public boolean isValidSegment(String segment) { - return false; - } - - public int segmentCount() { - return 1; - } - - public String[] segments() { - return segments; - } - - public String segment(int index) { - if (index > 0) - return null; - return GLOBAL_NAMESPACE; - } - - public String lastSegment() { - return GLOBAL_NAMESPACE; - } - - public int matchingFirstSegments(IQualifiedTypeName typeName) { - return 1; - } - - public boolean isPrefixOf(IQualifiedTypeName typeName) { - return true; - } - - public IQualifiedTypeName append(String[] names) { - return new QualifiedTypeName(names); - } - - public IQualifiedTypeName append(IQualifiedTypeName typeName) { - return new QualifiedTypeName(typeName); - } - - public IQualifiedTypeName append(String qualifiedName) { - return new QualifiedTypeName(qualifiedName); - } - - public IQualifiedTypeName removeFirstSegments(int count) { - return this; - } - - public IQualifiedTypeName removeLastSegments(int count) { - return this; - } - - public boolean isLowLevel() { - return false; - } - - public boolean isValid() { - return true; - } - - public int hashCode() { - return GLOBAL_NAMESPACE.hashCode(); - } - - public String toString() { - return getFullyQualifiedName(); - } - - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - if (!(obj instanceof IQualifiedTypeName)) { - return false; - } - return equals((IQualifiedTypeName)obj); - } - - public int compareTo(Object obj) { - if (obj == this) { - return 0; - } - if (!(obj instanceof IQualifiedTypeName)) { - throw new ClassCastException(); - } - return compareTo((IQualifiedTypeName)obj); - } - - /* (non-Javadoc) - * @see org.eclipse.cdt.core.browser.IQualifiedTypeName#equals(org.eclipse.cdt.core.browser.IQualifiedTypeName) - */ - public boolean equals(IQualifiedTypeName typeName) { - return (typeName instanceof GlobalNamespace); - } - - /* (non-Javadoc) - * @see org.eclipse.cdt.core.browser.IQualifiedTypeName#equalsIgnoreCase(org.eclipse.cdt.core.browser.IQualifiedTypeName) - */ - public boolean equalsIgnoreCase(IQualifiedTypeName typeName) { - return (typeName instanceof GlobalNamespace); - } - - /* (non-Javadoc) - * @see org.eclipse.cdt.core.browser.IQualifiedTypeName#compareTo(org.eclipse.cdt.core.browser.IQualifiedTypeName) - */ - public int compareTo(IQualifiedTypeName typeName) { - return getFullyQualifiedName().compareTo(typeName.getFullyQualifiedName()); - } - - /* (non-Javadoc) - * @see org.eclipse.cdt.core.browser.IQualifiedTypeName#compareToIgnoreCase(org.eclipse.cdt.core.browser.IQualifiedTypeName) - */ - public int compareToIgnoreCase(IQualifiedTypeName typeName) { - return getFullyQualifiedName().compareToIgnoreCase(typeName.getFullyQualifiedName()); - } - } - - private static class HashKey { - private IQualifiedTypeName name; - private int type; - public HashKey(IQualifiedTypeName name, int type) { - this.name = name; - this.type = type; - } - public int hashCode() { - return (this.name.hashCode() + this.type); - } - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - if (!(obj instanceof HashKey)) { - return false; - } - HashKey otherKey = (HashKey)obj; - return (this.type == otherKey.type && this.name.equals(otherKey.name)); - } - } - - public TypeCache(IProject project, IWorkingCopyProvider workingCopyProvider) { - fProject = project; - fWorkingCopyProvider = workingCopyProvider; - fDeltas.add(new TypeCacheDelta(fProject)); - fGlobalNamespace = new TypeInfo(ICElement.C_NAMESPACE, new GlobalNamespace()); - fGlobalNamespace.setCache(this); - } - - public TypeCache(IProject project, IWorkingCopyProvider workingCopyProvider, ITypeCacheChangedListener listener) { - this(project, workingCopyProvider); - fChangeListener = listener; - } - - public boolean contains(ISchedulingRule rule) { - if (this == rule) - return true; - if (rule instanceof ITypeCache) { - ITypeCache typeCache = (ITypeCache) rule; - if (fProject.equals(typeCache.getProject())) - return true; - } - return false; - } - - public boolean isConflicting(ISchedulingRule rule) { - if (rule instanceof ITypeCache) { - ITypeCache typeCache = (ITypeCache) rule; - if (fProject.equals(typeCache.getProject())) - return true; - } - return false; - } - - public IProject getProject() { - return fProject; - } - - public synchronized boolean isEmpty() { - return fTypeKeyMap.isEmpty(); - } - - public synchronized void insert(ITypeInfo newType) { - // check if enclosing types are already in cache - IQualifiedTypeName enclosingName = newType.getQualifiedTypeName().getEnclosingTypeName(); - if (enclosingName != null) { - while (!enclosingName.isEmpty()) { - // try namespace, class, struct, then undefined - ITypeInfo enclosingType = null; - for (int i = 0; enclosingType == null && i < ENCLOSING_TYPES.length; ++i) { - enclosingType = (ITypeInfo) fTypeKeyMap.get(new HashKey(enclosingName, ENCLOSING_TYPES[i])); - } - if (enclosingType == null) { - // create a dummy type to take this place (type 0 == unknown) - ITypeInfo dummyType = new TypeInfo(0, enclosingName); - dummyType.setCache(this); - fTypeKeyMap.put(new HashKey(enclosingName, 0), dummyType); - } - enclosingName = enclosingName.removeLastSegments(1); - } - } - - fTypeKeyMap.put(new HashKey(newType.getQualifiedTypeName(), newType.getCElementType()), newType); - newType.setCache(this); - } - - public synchronized void remove(ITypeInfo info) { - fTypeKeyMap.remove(new HashKey(info.getQualifiedTypeName(), info.getCElementType())); - info.setCache(null); - } - - public synchronized void flush(ITypeSearchScope scope) { - if (scope.encloses(fProject)) { - flushAll(); - } else { - for (Iterator mapIter = fTypeKeyMap.entrySet().iterator(); mapIter.hasNext(); ) { - Map.Entry entry = (Map.Entry) mapIter.next(); - ITypeInfo info = (ITypeInfo) entry.getValue(); - if (info.isEnclosed(scope)) { - mapIter.remove(); - } - } - } - } - - public synchronized void flush(IPath path) { - ITypeSearchScope scope = new TypeSearchScope(); - scope.add(path, false, null); - flush(scope); - } - - public synchronized void flushAll() { - // flush the entire cache - accept(new ITypeInfoVisitor() { - public boolean visit(ITypeInfo info) { - info.setCache(null); - return true; - } - public boolean shouldContinue() { return true; } - }); - fTypeKeyMap.clear(); - } - - public synchronized void addSupertype(ITypeInfo type, ITypeInfo supertype, ASTAccessVisibility access, boolean isVirtual) { - Collection entryCollection = (Collection) fTypeToSuperTypes.get(type); - if (entryCollection == null) { - entryCollection = new ArrayList(); - fTypeToSuperTypes.put(type, entryCollection); - } - if (findSuperTypeEntry(entryCollection, supertype) == null) { - entryCollection.add(new SuperTypeEntry(supertype, access, isVirtual)); - supertype.setCache(this); - } - } - - public synchronized ITypeInfo[] getSupertypes(ITypeInfo type) { - Collection entryCollection = (Collection) fTypeToSuperTypes.get(type); - if (entryCollection != null && !entryCollection.isEmpty()) { - ITypeInfo[] superTypes = new ITypeInfo[entryCollection.size()]; - int count = 0; - for (Iterator i = entryCollection.iterator(); i.hasNext(); ) { - SuperTypeEntry e = (SuperTypeEntry) i.next(); - superTypes[count++] = e.superType; - } - return superTypes; - } - return null; - } - - public ASTAccessVisibility getSupertypeAccess(ITypeInfo type, ITypeInfo superType) { - Collection entryCollection = (Collection) fTypeToSuperTypes.get(type); - if (entryCollection != null && !entryCollection.isEmpty()) { - SuperTypeEntry e = findSuperTypeEntry(entryCollection, superType); - if (e != null) - return e.access; - } - return null; - } - - public synchronized void addSubtype(ITypeInfo type, ITypeInfo subtype) { - Collection typeCollection = (Collection) fTypeToSubTypes.get(type); - if (typeCollection == null) { - typeCollection = new ArrayList(); - fTypeToSubTypes.put(type, typeCollection); - } - if (!typeCollection.contains(subtype)) { - typeCollection.add(subtype); - subtype.setCache(this); - } - } - - public synchronized ITypeInfo[] getSubtypes(ITypeInfo type) { - Collection typeCollection = (Collection) fTypeToSubTypes.get(type); - if (typeCollection != null && !typeCollection.isEmpty()) { - return (ITypeInfo[]) typeCollection.toArray(new ITypeInfo[typeCollection.size()]); - } - return null; - } - - public synchronized void accept(ITypeInfoVisitor visitor) { - for (Iterator mapIter = fTypeKeyMap.entrySet().iterator(); mapIter.hasNext(); ) { - Map.Entry entry = (Map.Entry) mapIter.next(); - ITypeInfo info = (ITypeInfo) entry.getValue(); - if (!visitor.shouldContinue()) - return; // stop visiting - visitor.visit(info); - } - } - - public synchronized IPath[] getPaths(final ITypeSearchScope scope) { - final Set pathSet = new HashSet(); - accept(new ITypeInfoVisitor() { - public boolean visit(ITypeInfo info) { - if (scope == null || info.isEnclosed(scope)) { - ITypeReference[] refs = info.getReferences(); - if (refs != null) { - for (int i = 0; i < refs.length; ++i) { - IPath path = refs[i].getPath(); - if (scope == null || scope.encloses(path)) - pathSet.add(path); - } - } - } - return true; - } - public boolean shouldContinue() { return true; } - }); - return (IPath[]) pathSet.toArray(new IPath[pathSet.size()]); - } - - public synchronized ITypeInfo[] getTypes(final ITypeSearchScope scope) { - final Collection results = new ArrayList(); - accept(new ITypeInfoVisitor() { - public boolean visit(ITypeInfo info) { - if (scope == null || info.isEnclosed(scope)) { - results.add(info); - } - return true; - } - public boolean shouldContinue() { return true; } - }); - return (ITypeInfo[]) results.toArray(new ITypeInfo[results.size()]); - } - - public synchronized ITypeInfo[] getTypes(IQualifiedTypeName qualifiedName, boolean matchEnclosed, boolean ignoreCase) { - Collection results = new ArrayList(); - if (!ignoreCase && !matchEnclosed) { - for (int i = 0; i < ITypeInfo.KNOWN_TYPES.length; ++i) { - ITypeInfo info = (ITypeInfo) fTypeKeyMap.get(new HashKey(qualifiedName, ITypeInfo.KNOWN_TYPES[i])); - if (info != null) { - results.add(info); - } - } - ITypeInfo info = (ITypeInfo) fTypeKeyMap.get(new HashKey(qualifiedName, 0)); - if (info != null) { - results.add(info); - } - } else { - // TODO this should probably use a more efficient search algorithm - for (Iterator mapIter = fTypeKeyMap.entrySet().iterator(); mapIter.hasNext(); ) { - Map.Entry entry = (Map.Entry) mapIter.next(); - ITypeInfo info = (ITypeInfo) entry.getValue(); - IQualifiedTypeName currName = info.getQualifiedTypeName(); - - if (ignoreCase) { - if (matchEnclosed && currName.segmentCount() > qualifiedName.segmentCount() - && currName.lastSegment().equalsIgnoreCase(qualifiedName.lastSegment())) { - currName = currName.removeFirstSegments(currName.segmentCount() - qualifiedName.segmentCount()); - } - if (currName.equalsIgnoreCase(qualifiedName)) { - results.add(info); - } - } else { - if (matchEnclosed && currName.segmentCount() > qualifiedName.segmentCount() - && currName.lastSegment().equals(qualifiedName.lastSegment())) { - currName = currName.removeFirstSegments(currName.segmentCount() - qualifiedName.segmentCount()); - } - if (currName.equals(qualifiedName)) { - results.add(info); - } - } - } - } - return (ITypeInfo[]) results.toArray(new ITypeInfo[results.size()]); - } - - public synchronized ITypeInfo getType(int type, IQualifiedTypeName qualifiedName) { - ITypeInfo info = (ITypeInfo) fTypeKeyMap.get(new HashKey(qualifiedName, type)); - if (info == null && type != 0) { - info = (ITypeInfo) fTypeKeyMap.get(new HashKey(qualifiedName, 0)); - } - return info; - } - - public synchronized ITypeInfo getEnclosingType(ITypeInfo info, final int[] kinds) { - IQualifiedTypeName enclosingName = info.getQualifiedTypeName().getEnclosingTypeName(); - if (enclosingName != null) { - // try namespace, class, struct, then undefined - ITypeInfo enclosingType = null; - for (int i = 0; enclosingType == null && i < ENCLOSING_TYPES.length; ++i) { - if (ArrayUtil.contains(kinds, ENCLOSING_TYPES[i])) { - enclosingType = (ITypeInfo) fTypeKeyMap.get(new HashKey(enclosingName, ENCLOSING_TYPES[i])); - } - } - return enclosingType; - } - return null; - } - - public synchronized ITypeInfo getEnclosingNamespace(ITypeInfo info, boolean includeGlobalNamespace) { - IQualifiedTypeName enclosingName = info.getQualifiedTypeName().getEnclosingTypeName(); - if (enclosingName != null) { - // look for namespace - ITypeInfo enclosingType = (ITypeInfo) fTypeKeyMap.get(new HashKey(enclosingName, ICElement.C_NAMESPACE)); - if (enclosingType != null) { - return enclosingType; - } - // try class, struct, then undefined - final int[] kinds = {ICElement.C_CLASS, ICElement.C_STRUCT, 0}; - for (int i = 0; enclosingType == null && i < kinds.length; ++i) { - enclosingType = (ITypeInfo) fTypeKeyMap.get(new HashKey(enclosingName, kinds[i])); - } - if (enclosingType != null) { - return getEnclosingNamespace(enclosingType, includeGlobalNamespace); - } - } - if (includeGlobalNamespace) - return fGlobalNamespace; - return null; - } - - public synchronized ITypeInfo getRootNamespace(ITypeInfo info, boolean includeGlobalNamespace) { - IQualifiedTypeName qualifiedName = info.getQualifiedTypeName(); - if (qualifiedName.isGlobal()) { - if (info.getCElementType() == ICElement.C_NAMESPACE) - return info; - if (includeGlobalNamespace) - return fGlobalNamespace; - return null; - } - IQualifiedTypeName namespace = qualifiedName.removeLastSegments(qualifiedName.segmentCount()-1); - // try namespace, then undefined - ITypeInfo namespaceType = (ITypeInfo) fTypeKeyMap.get(new HashKey(namespace, ICElement.C_NAMESPACE)); - if (namespaceType == null) - namespaceType = (ITypeInfo) fTypeKeyMap.get(new HashKey(namespace, 0)); - return namespaceType; - } - - public synchronized boolean hasEnclosedTypes(final ITypeInfo info) { - final IQualifiedTypeName parentName = info.getQualifiedTypeName(); - final boolean[] foundTypes = { false }; - accept(new ITypeInfoVisitor() { - public boolean visit(ITypeInfo type) { - if (type != info && parentName.isPrefixOf(type.getQualifiedTypeName())) { - foundTypes[0] = true; - } - return true; - } - public boolean shouldContinue() { - return !foundTypes[0]; - } - }); - return foundTypes[0]; - } - - public synchronized ITypeInfo[] getEnclosedTypes(final ITypeInfo enclosedBy, final int kinds[]) { - final IQualifiedTypeName parentName = enclosedBy.getQualifiedTypeName(); - final Collection results = new ArrayList(); - accept(new ITypeInfoVisitor() { - public boolean visit(ITypeInfo type) { - if (ArrayUtil.contains(kinds, type.getCElementType())) { - IQualifiedTypeName enclosingName = type.getQualifiedTypeName().getEnclosingTypeName(); - if (enclosedBy == fGlobalNamespace) { - if (enclosingName == null) { - results.add(type); - } else { -// // check if enclosing parent is namespace -// getRootNamespace(type); - } - } else if (parentName.equals(enclosingName)) { - results.add(type); - } - } - return true; - } - public boolean shouldContinue() { return true; } - }); - - return (ITypeInfo[]) results.toArray(new ITypeInfo[results.size()]); - } - - public ITypeInfo getGlobalNamespace() { - return fGlobalNamespace; - } - - public boolean isUpToDate() { - synchronized(fDeltas) { - return fDeltas.isEmpty(); - } - } - - public void addDelta(TypeCacheDelta delta) { - synchronized(fDeltas) { - fDeltas.add(delta); - } - } - - public void reconcile(boolean enableIndexing, int priority, int delay) { - // check if anything needs to be done - if (deltasRemaining() == 0) - return; // nothing to do - - // cancel any scheduled or running jobs for this project - IJobManager jobManager = Platform.getJobManager(); - Job[] jobs = jobManager.find(TypeCacherJob.FAMILY); - for (int i = 0; i < jobs.length; ++i) { - TypeCacherJob deltaJob = (TypeCacherJob) jobs[i]; - if (deltaJob.getCache().equals(this)) { - deltaJob.cancel(); - } - } - - // check again, in case some jobs finished in the meantime - if (deltasRemaining() == 0) - return; // nothing to do - - TypeCacherJob deltaJob = null; - IndexManager indexManager = CModelManager.getDefault().getIndexManager(); - ICDTIndexer indexer = indexManager.getIndexerForProject( fProject ); - boolean haveIndexer = (indexer != null && indexer.isIndexEnabled( fProject )); - synchronized(fDeltas) { - if( haveIndexer ){ - // grab all the remaining deltas - TypeCacheDelta[] jobDeltas = (TypeCacheDelta[]) fDeltas.toArray(new TypeCacheDelta[fDeltas.size()]); - - // create a new job - deltaJob = new TypeCacherJob(this, jobDeltas, enableIndexing); - // assign deltas to job - if (jobDeltas != null) { - for (int i = 0; i < jobDeltas.length; ++i) { - jobDeltas[i].assignToJob(deltaJob); - } - } - } else { - //we don't have an indexer, don't create a job to do these deltas, throw them away - fDeltas.clear(); - } - } - - if( deltaJob != null ){ - // schedule the new job - deltaJob.addJobChangeListener(fJobChangeListener); - deltaJob.setPriority(priority); - deltaJob.schedule(delay); - } - } - - public void reconcileAndWait(boolean enableIndexing, int priority, IProgressMonitor monitor) { - reconcile(enableIndexing, priority, 0); - - // wait for jobs to complete - IJobManager jobManager = Platform.getJobManager(); - Job[] jobs = jobManager.find(TypeCacherJob.FAMILY); - for (int i = 0; i < jobs.length; ++i) { - TypeCacherJob deltaJob = (TypeCacherJob) jobs[i]; - if (deltaJob.getCache().equals(this)) { - try { - deltaJob.join(monitor); - } catch (InterruptedException e) { - } - } - } - } - - // returns the number of deltas either not assigned to a job, - // or assigned to a job which is not yet running - private int deltasRemaining() { - // count the left-over deltas - synchronized(fDeltas) { - int count = 0; - for (Iterator i = fDeltas.iterator(); i.hasNext(); ) { - TypeCacheDelta delta = (TypeCacheDelta) i.next(); - TypeCacherJob job = delta.getJob(); - if (job == null || !job.isRunning()) { - ++count; - } - } - return count; - } - } - - public void cancelJobs() { - IJobManager jobManager = Platform.getJobManager(); - Job[] jobs = jobManager.find(TypeCacherJob.FAMILY); - for (int i = 0; i < jobs.length; ++i) { - TypeCacherJob deltaJob = (TypeCacherJob) jobs[i]; - if (deltaJob.getCache().equals(this)) { - deltaJob.cancel(); - } - } - jobs = jobManager.find(TypeLocatorJob.FAMILY); - for (int i = 0; i < jobs.length; ++i) { - TypeLocatorJob locatorJob = (TypeLocatorJob) jobs[i]; - if (locatorJob.getType().getEnclosingProject().equals(fProject)) { - locatorJob.cancel(); - } - } - jobs = jobManager.find(SubTypeLocatorJob.FAMILY); - for (int i = 0; i < jobs.length; ++i) { - SubTypeLocatorJob locatorJob = (SubTypeLocatorJob) jobs[i]; - if (locatorJob.getType().getEnclosingProject().equals(fProject)) { - locatorJob.cancel(); - } - } - } - - public void locateType(ITypeInfo info, int priority, int delay) { - ITypeReference location = info.getResolvedReference(); - if (location != null) - return; // nothing to do - - // cancel any scheduled or running jobs for this type - IJobManager jobManager = Platform.getJobManager(); - Job[] jobs = jobManager.find(TypeLocatorJob.FAMILY); - for (int i = 0; i < jobs.length; ++i) { - TypeLocatorJob locatorJob = (TypeLocatorJob) jobs[i]; - if (locatorJob.getType().equals(info)) { - locatorJob.cancel(); - } - } - - // check again, in case some jobs finished in the meantime - location = info.getResolvedReference(); - if (location != null) - return; // nothing to do - - // create a new job - TypeLocatorJob locatorJob = new TypeLocatorJob(info, this, fWorkingCopyProvider); - // schedule the new job - locatorJob.setPriority(priority); - locatorJob.schedule(delay); - } - - public ITypeReference locateTypeAndWait(ITypeInfo info, int priority, IProgressMonitor monitor) { - locateType(info, priority, 0); - - // wait for jobs to complete - IJobManager jobManager = Platform.getJobManager(); - Job[] jobs = jobManager.find(TypeLocatorJob.FAMILY); - for (int i = 0; i < jobs.length; ++i) { - TypeLocatorJob locatorJob = (TypeLocatorJob) jobs[i]; - if (locatorJob.getType().equals(info)) { - try { - locatorJob.join(monitor); - } catch (InterruptedException e) { - } - } - } - - return info.getResolvedReference(); - } - - public void locateSupertypes(ITypeInfo info, int priority, int delay) { - ITypeInfo[] superTypes = getSupertypes(info); - if (superTypes != null) - return; // nothing to do - - locateType(info, priority, delay); - } - - public ITypeInfo[] locateSupertypesAndWait(ITypeInfo info, int priority, IProgressMonitor monitor) { - locateSupertypes(info, priority, 0); - - // wait for jobs to complete - IJobManager jobManager = Platform.getJobManager(); - Job[] jobs = jobManager.find(SubTypeLocatorJob.FAMILY); - for (int i = 0; i < jobs.length; ++i) { - SubTypeLocatorJob locatorJob = (SubTypeLocatorJob) jobs[i]; - if (locatorJob.getType().equals(info)) { - try { - locatorJob.join(monitor); - } catch (InterruptedException e) { - } - } - } - - return getSupertypes(info); - } - - public void locateSubtypes(ITypeInfo info, int priority, int delay) { - ITypeInfo[] subTypes = getSubtypes(info); - if (subTypes != null) - return; // nothing to do - - // cancel any scheduled or running jobs for this type - IJobManager jobManager = Platform.getJobManager(); - Job[] jobs = jobManager.find(SubTypeLocatorJob.FAMILY); - for (int i = 0; i < jobs.length; ++i) { - SubTypeLocatorJob locatorJob = (SubTypeLocatorJob) jobs[i]; - if (locatorJob.getType().equals(info)) { - locatorJob.cancel(); - } - } - - // check again, in case some jobs finished in the meantime - subTypes = getSubtypes(info); - if (subTypes != null) - return; // nothing to do - - // create a new job - SubTypeLocatorJob locatorJob = new SubTypeLocatorJob(info, this, fWorkingCopyProvider); - // schedule the new job - locatorJob.setPriority(priority); - locatorJob.schedule(delay); - } - - public ITypeInfo[] locateSubtypesAndWait(ITypeInfo info, int priority, IProgressMonitor monitor) { - locateSubtypes(info, priority, 0); - - // wait for jobs to complete - IJobManager jobManager = Platform.getJobManager(); - Job[] jobs = jobManager.find(SubTypeLocatorJob.FAMILY); - for (int i = 0; i < jobs.length; ++i) { - SubTypeLocatorJob locatorJob = (SubTypeLocatorJob) jobs[i]; - if (locatorJob.getType().equals(info)) { - try { - locatorJob.join(monitor); - } catch (InterruptedException e) { - } - } - } - - return getSubtypes(info); - } -} diff --git a/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/internal/core/browser/cache/TypeCacheDelta.java b/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/internal/core/browser/cache/TypeCacheDelta.java deleted file mode 100644 index 6b897bdb3ec..00000000000 --- a/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/internal/core/browser/cache/TypeCacheDelta.java +++ /dev/null @@ -1,60 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 QNX Software Systems and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * QNX Software Systems - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.core.browser.cache; - -import org.eclipse.cdt.core.browser.ITypeSearchScope; -import org.eclipse.cdt.core.browser.TypeSearchScope; -import org.eclipse.cdt.core.model.ICElementDelta; -import org.eclipse.core.resources.IProject; - - -public class TypeCacheDelta { - private IProject fProject = null; - private ICElementDelta fCElementDelta = null; - private ITypeSearchScope fScope = null; - private TypeCacherJob fJob = null; - - public TypeCacheDelta(IProject project, ICElementDelta delta) { - fProject = project; - fCElementDelta = delta; - } - - public TypeCacheDelta(IProject project, ITypeSearchScope scope) { - fProject = project; - fScope = scope; - } - - public TypeCacheDelta(IProject project) { - fProject = project; - fScope = new TypeSearchScope(); - fScope.add(project); - } - - public IProject getProject() { - return fProject; - } - - public ITypeSearchScope getScope() { - return fScope; - } - - public ICElementDelta getCElementDelta() { - return fCElementDelta; - } - - public void assignToJob(TypeCacherJob job) { - fJob = job; - } - - public TypeCacherJob getJob() { - return fJob; - } -} diff --git a/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/internal/core/browser/cache/TypeCacheManager.java b/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/internal/core/browser/cache/TypeCacheManager.java deleted file mode 100644 index cee4acd1329..00000000000 --- a/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/internal/core/browser/cache/TypeCacheManager.java +++ /dev/null @@ -1,471 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004, 2005 QNX Software Systems and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * QNX Software Systems - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.core.browser.cache; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; - -import org.eclipse.cdt.core.CCorePlugin; -import org.eclipse.cdt.core.browser.IQualifiedTypeName; -import org.eclipse.cdt.core.browser.ITypeCacheChangedListener; -import org.eclipse.cdt.core.browser.ITypeInfo; -import org.eclipse.cdt.core.browser.ITypeReference; -import org.eclipse.cdt.core.browser.ITypeSearchScope; -import org.eclipse.cdt.core.browser.TypeSearchScope; -import org.eclipse.cdt.core.browser.TypeUtil; -import org.eclipse.cdt.core.model.ElementChangedEvent; -import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.cdt.core.model.ICElementDelta; -import org.eclipse.cdt.core.model.ICProject; -import org.eclipse.cdt.core.model.ITranslationUnit; -import org.eclipse.cdt.core.model.IWorkingCopyProvider; -import org.eclipse.cdt.internal.core.model.CModelManager; -import org.eclipse.cdt.internal.core.search.indexing.IndexManager; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.ISafeRunnable; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.NullProgressMonitor; -import org.eclipse.core.runtime.Platform; -import org.eclipse.core.runtime.Status; -import org.eclipse.core.runtime.SubProgressMonitor; -import org.eclipse.core.runtime.jobs.IJobManager; -import org.eclipse.core.runtime.jobs.Job; - -public class TypeCacheManager implements ITypeCacheChangedListener, IndexManager.IIndexerSelectionListener { - private static final TypeCacheManager fgInstance = new TypeCacheManager(); - private Map fCacheMap; - private IWorkingCopyProvider fWorkingCopyProvider; - private ArrayList fChangeListeners = new ArrayList(); - - private static final int INITIAL_TYPE_MAP_SIZE = 50; - //TODO make this a WeakHashMap or LRUCache - private Map fTypeToElementMap = new HashMap(INITIAL_TYPE_MAP_SIZE); - private Map fElementToTypeMap = new HashMap(INITIAL_TYPE_MAP_SIZE); - private boolean processTypeCacheEvents = true; - - private TypeCacheManager() { - fCacheMap = new HashMap(); - CModelManager.getDefault().getIndexManager().subscribeForIndexerChangeNotifications( this ); - } - - public static TypeCacheManager getInstance() { - return fgInstance; - } - - protected void finalize() throws Throwable { - CModelManager.getDefault().getIndexManager().unSubscribeForIndexerChangeNotifications( this ); - super.finalize(); - } - - public void setWorkingCopyProvider(IWorkingCopyProvider workingCopyProvider) { - fWorkingCopyProvider = workingCopyProvider; - } - - public synchronized void updateProject(IProject project) { - // TODO finer-grained flush needed, for now just flush the whole map - fTypeToElementMap.clear(); - fElementToTypeMap.clear(); - addCacheDelta(project, null); - } - - public synchronized void processElementChanged(ElementChangedEvent event, boolean enableIndexing) { - int deltaCount = processDelta(event.getDelta()); - if (deltaCount > 0) { - // TODO finer-grained flush needed, for now just flush the whole map - fTypeToElementMap.clear(); - fElementToTypeMap.clear(); - reconcile(enableIndexing, Job.BUILD, 0); - } - } - - private static final int PATH_ENTRY_FLAGS = ICElementDelta.F_ADDED_PATHENTRY_SOURCE - | ICElementDelta.F_REMOVED_PATHENTRY_SOURCE - | ICElementDelta.F_CHANGED_PATHENTRY_INCLUDE - | ICElementDelta.F_CHANGED_PATHENTRY_MACRO - | ICElementDelta.F_PATHENTRY_REORDER; - - private int processDelta(ICElementDelta delta) { - ICElement elem = delta.getElement(); - boolean added = (delta.getKind() == ICElementDelta.ADDED); - boolean removed = (delta.getKind() == ICElementDelta.REMOVED); - boolean contentChanged = ((delta.getFlags() & ICElementDelta.F_CONTENT) != 0); - boolean pathEntryChanged = ((delta.getFlags() & PATH_ENTRY_FLAGS) != 0); - boolean openedOrClosed = (((delta.getFlags() & ICElementDelta.F_CLOSED) != 0) || ((delta.getFlags() & ICElementDelta.F_OPENED) != 0)); - boolean hasChildren = ((delta.getFlags() & ICElementDelta.F_CHILDREN) != 0); - int deltaCount = 0; - - - switch (elem.getElementType()) { - case ICElement.C_PROJECT: - case ICElement.C_CCONTAINER: { - ICProject cProject = elem.getCProject(); - IProject project = cProject.getProject(); - if (added || removed || pathEntryChanged || openedOrClosed) { - addCacheDelta(project, delta); - ++deltaCount; - } - } - break; - - case ICElement.C_UNIT: { - ICProject cProject = elem.getCProject(); - IProject project = cProject.getProject(); - ITranslationUnit unit = (ITranslationUnit) elem; - if (unit.isWorkingCopy()) { - deltaCount += processWorkingCopyDelta(delta); - return deltaCount; - } - if (added || removed || pathEntryChanged || contentChanged) { - addCacheDelta(project, delta); - ++deltaCount; - } - } - break; - - case ICElement.C_INCLUDE: - case ICElement.C_NAMESPACE: - case ICElement.C_TEMPLATE_CLASS: - case ICElement.C_CLASS: - case ICElement.C_STRUCT: - case ICElement.C_UNION: - case ICElement.C_ENUMERATION: - case ICElement.C_TYPEDEF: - { - ICProject cProject = elem.getCProject(); - IProject project = cProject.getProject(); - if (added || removed) { - addCacheDelta(project, delta); - ++deltaCount; - } - } - break; - } - - if (hasChildren) { - ICElementDelta[] children = delta.getAffectedChildren(); - if (children != null) { - for (int i = 0; i < children.length; ++i) { - deltaCount += processDelta(children[i]); - } - } - } - - return deltaCount; - } - - private void addCacheDelta(IProject project, ICElementDelta delta) { - if (delta == null) { - getCache(project).addDelta(new TypeCacheDelta(project)); - } else { - getCache(project).addDelta(new TypeCacheDelta(project, delta)); - } - } - - private int processWorkingCopyDelta(ICElementDelta delta) { - // ignore workies copies for now - return 0; -/* ICElement elem = delta.getElement(); - boolean added = (delta.getKind() == ICElementDelta.ADDED); - boolean removed = (delta.getKind() == ICElementDelta.REMOVED); - boolean contentChanged = ((delta.getFlags() & ICElementDelta.F_CONTENT) != 0); - boolean pathEntryChanged = ((delta.getFlags() & PATH_ENTRY_FLAGS) != 0); - boolean hasChildren = ((delta.getFlags() & ICElementDelta.F_CHILDREN) != 0); - - switch (elem.getElementType()) { - case ICElement.C_UNIT: { - ICProject cProject = elem.getCProject(); - IProject project = cProject.getProject(); - if (added || removed || pathEntryChanged || contentChanged) { - TypeCacheDelta cacheDelta = new TypeCacheDelta(project, delta); - getCache(project).addDelta(cacheDelta); - } - } - break; - - case ICElement.C_INCLUDE: - case ICElement.C_NAMESPACE: - case ICElement.C_TEMPLATE_CLASS: - case ICElement.C_CLASS: - case ICElement.C_STRUCT: - case ICElement.C_UNION: - case ICElement.C_ENUMERATION: - case ICElement.C_TYPEDEF: - { - ICProject cProject = elem.getCProject(); - IProject project = cProject.getProject(); - if (added || removed) { - TypeCacheDelta cacheDelta = new TypeCacheDelta(project, delta); - getCache(project).addDelta(cacheDelta); - } - } - break; - } - - if (hasChildren) { - ICElementDelta[] children = delta.getAffectedChildren(); - if (children != null) { - for (int i = 0; i < children.length; ++i) { - processWorkingCopyDelta(children[i]); - } - } - } -*/ - } - - public synchronized ITypeCache getCache(IProject project) { - synchronized(fCacheMap) { - ITypeCache cache = (ITypeCache) fCacheMap.get(project); - if (cache == null) { - cache = new TypeCache(project, fWorkingCopyProvider, this); - fCacheMap.put(project, cache); - } - return cache; - } - } - - public synchronized void reconcile(boolean enableIndexing, int priority, int delay) { - if (!(processTypeCacheEvents)) - return; - - TypeSearchScope workspaceScope = new TypeSearchScope(true); - IProject[] projects = workspaceScope.getEnclosingProjects(); - for (int i = 0; i < projects.length; ++i) { - ITypeCache cache = getCache(projects[i]); - cache.reconcile(enableIndexing, priority, delay); - } - } - - public synchronized void reconcileAndWait(boolean enableIndexing, int priority, IProgressMonitor monitor) { - if (!(processTypeCacheEvents)) - return; - - TypeSearchScope workspaceScope = new TypeSearchScope(true); - IProject[] projects = workspaceScope.getEnclosingProjects(); - for (int i = 0; i < projects.length; ++i) { - ITypeCache cache = getCache(projects[i]); - cache.reconcileAndWait(enableIndexing, priority, monitor); - } - } - - public void cancelJobs() { - IJobManager jobManager = Platform.getJobManager(); - jobManager.cancel(TypeCacherJob.FAMILY); - jobManager.cancel(TypeLocatorJob.FAMILY); - } - - public ITypeInfo[] locateSuperTypesAndWait(ITypeInfo info, boolean enableIndexing, int priority, IProgressMonitor monitor) { - ITypeInfo[] superTypes = info.getSuperTypes(); - if (superTypes == null) { - // cancel background jobs - IProject project = info.getEnclosingProject(); - getCache(project).cancelJobs(); - - // start the search job - getCache(project).locateSupertypesAndWait(info, priority, monitor); - - superTypes = info.getSuperTypes(); - - // resume background jobs - reconcile(enableIndexing, Job.BUILD, 0); - } - return superTypes; - } - - public ITypeInfo[] locateSubTypesAndWait(ITypeInfo info, boolean enableIndexing, int priority, IProgressMonitor monitor) { - ITypeInfo[] subTypes = info.getSubTypes(); - if (subTypes == null) { - // cancel background jobs - IProject project = info.getEnclosingProject(); - getCache(project).cancelJobs(); - - // start the search job - getCache(project).locateSubtypesAndWait(info, priority, monitor); - - subTypes = info.getSubTypes(); - - // resume background jobs - reconcile(enableIndexing, Job.BUILD, 0); - } - return subTypes; - } - - public void updateCache(ITypeSearchScope scope, IProgressMonitor monitor) { - // schedule jobs to update cache - IProject[] projects = scope.getEnclosingProjects(); - monitor.beginTask(TypeCacheMessages.getString("AllTypesCache.updateCache.taskName"), projects.length); //$NON-NLS-1$ - for (int i = 0; i < projects.length; ++i) { - IProject project = projects[i]; - // wait for any running jobs to finish - getCache(project).reconcileAndWait(true, Job.SHORT, new SubProgressMonitor(monitor, 1)); - } - monitor.done(); - } - - /** - * Resolves a type location. - * - * @param info the type to search for - * @param monitor the progress monitor - */ - public ITypeReference resolveTypeLocation(ITypeInfo info, IProgressMonitor monitor, boolean enableIndexing) { - ITypeReference location = info.getResolvedReference(); - if (location == null) { - // cancel background jobs - IProject project = info.getEnclosingProject(); - ITypeCache cache = getCache(project); - cache.cancelJobs(); - - // start the search job - cache.locateTypeAndWait(info, Job.SHORT, monitor); - - // get the newly parsed location - location = info.getResolvedReference(); - - // resume background jobs - reconcile(enableIndexing, Job.BUILD, 0); - } - return location; - } - - public void addTypeCacheChangedListener(ITypeCacheChangedListener listener) { - // add listener only if it is not already present - synchronized(fChangeListeners) { - if (!fChangeListeners.contains(listener)) { - fChangeListeners.add(listener); - } - } - } - - public void removeTypeCacheChangedListener(ITypeCacheChangedListener listener) { - synchronized(fChangeListeners) { - fChangeListeners.remove(listener); - } - } - - /* (non-Javadoc) - * @see org.eclipse.cdt.core.browser.ITypeCacheChangedListener#typeCacheChanged(org.eclipse.core.resources.IProject) - */ - public synchronized void typeCacheChanged(final IProject project) { - // clone so that a listener cannot have a side-effect on this list when being notified - ArrayList listeners; - synchronized(fChangeListeners) { - listeners = (ArrayList) fChangeListeners.clone(); - } - for (Iterator i = listeners.iterator(); i.hasNext(); ) { - final ITypeCacheChangedListener listener = (ITypeCacheChangedListener) i.next(); - Platform.run(new ISafeRunnable() { - public void handleException(Throwable e) { - IStatus status = new Status(IStatus.ERROR, CCorePlugin.PLUGIN_ID, IStatus.ERROR, "Exception occurred in listener of type cache change notification", e); //$NON-NLS-1$ - CCorePlugin.log(status); - } - public void run() throws Exception { - listener.typeCacheChanged(project); - } - }); - } - } - - public ITypeInfo getTypeForElement(ICElement element, boolean forceUpdate, boolean forceResolve, boolean enableIndexing, IProgressMonitor monitor) { - if (element.exists()) { - ITypeInfo cachedInfo = (ITypeInfo) fElementToTypeMap.get(element); - if (cachedInfo != null && cachedInfo.exists()) - return cachedInfo; - } - - IQualifiedTypeName qualifiedName = TypeUtil.getFullyQualifiedName(element); - if (qualifiedName != null) { - ICProject cProject = element.getCProject(); - IProject project = cProject.getProject(); - ITypeCache cache = getCache(project); - if (!cache.isUpToDate() && forceUpdate) { - if (monitor == null) - monitor = new NullProgressMonitor(); - // wait for any running jobs to finish - cache.reconcileAndWait(true, Job.SHORT, monitor); - } - - ITypeInfo info = cache.getType(element.getElementType(), qualifiedName); - if (info != null) { - ITypeReference ref = info.getResolvedReference(); - if (ref == null && forceResolve) { - if (monitor == null) - monitor = new NullProgressMonitor(); - ref = resolveTypeLocation(info, monitor, enableIndexing); - } - - // cache for later use - fElementToTypeMap.put(element, info); - return info; - } - } - return null; - } - - public ICElement getElementForType(ITypeInfo type, boolean forceUpdate, boolean forceResolve, boolean enableIndexing, IProgressMonitor monitor) { - if (type.exists()) { - ICElement cachedElem = (ICElement) fTypeToElementMap.get(type); - if (cachedElem != null && cachedElem.exists()) - return cachedElem; - } - - IProject project = type.getEnclosingProject(); - ITypeCache cache = getCache(project); - if (!cache.isUpToDate() && forceUpdate) { - if (monitor == null) - monitor = new NullProgressMonitor(); - // wait for any running jobs to finish - cache.reconcileAndWait(true, Job.SHORT, monitor); - - //TODO replace type with new type from cache??? - } - - ITypeReference ref = type.getResolvedReference(); - if (ref == null && forceResolve) { - ref = resolveTypeLocation(type, monitor, enableIndexing); - } - if (ref != null) { - ICElement[] elems = ref.getCElements(); - if (elems != null && elems.length > 0) { - ICElement foundElem = elems[0]; - if (elems.length > 1) { - for (int i = 0; i < elems.length; ++i) { - ICElement elem = elems[i]; - if (elem.getElementType() == type.getCElementType() && elem.getElementName().equals(type.getName())) { - //TODO should check fully qualified name - foundElem = elem; - break; - } - } - } - - if (foundElem != null) { - // cache for later use - fTypeToElementMap.put(type, foundElem); - return foundElem; - } - } - } - return null; - } - public boolean getProcessTypeCacheEvents() { - return processTypeCacheEvents; - } - public void setProcessTypeCacheEvents(boolean processTypeCacheEvents) { - this.processTypeCacheEvents = processTypeCacheEvents; - } - - public void indexerSelectionChanged(IProject project) { - addCacheDelta(project, null ); - } -} diff --git a/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/internal/core/browser/cache/TypeCacheMessages.java b/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/internal/core/browser/cache/TypeCacheMessages.java deleted file mode 100644 index 30e20e62572..00000000000 --- a/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/internal/core/browser/cache/TypeCacheMessages.java +++ /dev/null @@ -1,50 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 QNX Software Systems and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * QNX Software Systems - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.core.browser.cache; - -import java.text.MessageFormat; -import java.util.MissingResourceException; -import java.util.ResourceBundle; - -public class TypeCacheMessages { - - private static final String RESOURCE_BUNDLE= TypeCacheMessages.class.getName(); - - private static ResourceBundle fgResourceBundle; - static { - try { - fgResourceBundle = ResourceBundle.getBundle(RESOURCE_BUNDLE); - } catch (MissingResourceException x) { - fgResourceBundle = null; - } - } - - private TypeCacheMessages() { - } - - public static String getString(String key) { - try { - return fgResourceBundle.getString(key); - } catch (MissingResourceException e) { - return '!' + key + '!'; - } catch (NullPointerException e) { - return "#" + key + "#"; //$NON-NLS-1$ //$NON-NLS-2$ - } - } - - public static String getFormattedString(String key, String arg) { - return getFormattedString(key, new String[] { arg }); - } - - public static String getFormattedString(String key, String[] args) { - return MessageFormat.format(getString(key), args); - } -} diff --git a/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/internal/core/browser/cache/TypeCacheMessages.properties b/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/internal/core/browser/cache/TypeCacheMessages.properties deleted file mode 100644 index c4d26740d29..00000000000 --- a/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/internal/core/browser/cache/TypeCacheMessages.properties +++ /dev/null @@ -1,23 +0,0 @@ -############################################################################### -# Copyright (c) 2000, 2004 QNX Software Systems and others. -# All rights reserved. This program and the accompanying materials -# are made available under the terms of the Eclipse Public License v1.0 -# which accompanies this distribution, and is available at -# http://www.eclipse.org/legal/epl-v10.html -# -# Contributors: -# QNX Software Systems - Initial API and implementation -############################################################################### - -AllTypesCache.updateCache.taskName=Updating Type Cache... - -TypeCacherJob.defaultJobName=Type Cache -TypeCacherJob.jobName=Type Cache [{0}] -TypeCacherJob.taskName=Updating Type Cache... - -TypeLocatorJob.jobName=Type Locator -TypeLocatorJob.taskName=Searching for Type Declaration... -SubTypeLocatorJob.jobName=Subtype Locator -SubTypeLocatorJob.taskName=Searching for Subtypes... - -TypeCache.globalNamespace=(global) diff --git a/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/internal/core/browser/cache/TypeCacherJob.java b/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/internal/core/browser/cache/TypeCacherJob.java deleted file mode 100644 index 3cb779f2e13..00000000000 --- a/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/internal/core/browser/cache/TypeCacherJob.java +++ /dev/null @@ -1,275 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004, 2005 QNX Software Systems and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * QNX Software Systems - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.core.browser.cache; - -import org.eclipse.cdt.core.browser.ITypeSearchScope; -import org.eclipse.cdt.core.browser.TypeSearchScope; -import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.cdt.core.model.ICElementDelta; -import org.eclipse.cdt.core.search.ICSearchConstants; -import org.eclipse.cdt.internal.core.index.IIndex; -import org.eclipse.cdt.internal.core.model.CModelManager; -import org.eclipse.cdt.internal.core.search.indexing.IndexManager; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.NullProgressMonitor; -import org.eclipse.core.runtime.OperationCanceledException; -import org.eclipse.core.runtime.Status; -import org.eclipse.core.runtime.SubProgressMonitor; - - -/** - * Background job for filling the type cache. - * @see org.eclipse.core.runtime.jobs.Job - * @since 3.0 - */ -public class TypeCacherJob extends BasicJob { - - public static final Object FAMILY = new Object(); - private IndexManager fIndexManager; - private ITypeCache fTypeCache; - private TypeCacheDelta[] fDeltas; - private boolean fEnableIndexing; - private boolean fIndexerIsBusy; - - public TypeCacherJob(ITypeCache typeCache, TypeCacheDelta[] deltas, boolean enableIndexing) { - super(TypeCacheMessages.getString("TypeCacherJob.defaultJobName"), FAMILY); //$NON-NLS-1$ - fTypeCache = typeCache; - fDeltas = deltas; - fEnableIndexing = enableIndexing; - fIndexerIsBusy = false; - fIndexManager = CModelManager.getDefault().getIndexManager(); - setPriority(BUILD); - setSystem(true); - setRule(typeCache); - setName(TypeCacheMessages.getFormattedString("TypeCacherJob.jobName", fTypeCache.getProject().getName())); //$NON-NLS-1$ - } - - public ITypeCache getCache() { - return fTypeCache; - } - - public TypeCacheDelta[] getDeltas() { - return fDeltas; - } - - public boolean isIndexerBusy() { - return fIndexerIsBusy; - } - - /* (non-Javadoc) - * @see org.eclipse.core.runtime.jobs.Job#run(IProgressMonitor) - */ - protected IStatus runWithDelegatedProgress(IProgressMonitor monitor) throws InterruptedException { - boolean success = false; - long startTime = System.currentTimeMillis(); - trace("TypeCacherJob: started"); //$NON-NLS-1$ - - try { - int totalWork = 100; - monitor.beginTask(TypeCacheMessages.getString("TypeCacherJob.taskName"), totalWork); //$NON-NLS-1$ - - // figure out what needs to be flushed - TypeSearchScope flushScope = new TypeSearchScope(); - if (fDeltas != null) { - for (int i = 0; i < fDeltas.length; ++i) { - TypeCacheDelta delta = fDeltas[i]; - prepareToFlush(delta, flushScope); - } - } - - if (monitor.isCanceled()) - throw new InterruptedException(); - - // flush the cache - int flushWork = 0; - if (!flushScope.isEmpty()) { - flushWork = totalWork / 4; - IProgressMonitor subMonitor = new SubProgressMonitor(monitor, flushWork); - flush(flushScope, subMonitor); - } - - // update the cache - IProgressMonitor subMonitor = new SubProgressMonitor(monitor, totalWork - flushWork); - update(flushScope, subMonitor); - - if (monitor.isCanceled()) - throw new InterruptedException(); - } finally { - long executionTime = System.currentTimeMillis() - startTime; - if (success) - trace("TypeCacherJob: completed ("+ executionTime + " ms)"); //$NON-NLS-1$ //$NON-NLS-2$ - else - trace("TypeCacherJob: aborted ("+ executionTime + " ms)"); //$NON-NLS-1$ //$NON-NLS-2$ - - monitor.done(); - } - - return Status.OK_STATUS; - } - - private void flush(ITypeSearchScope scope, IProgressMonitor monitor) throws InterruptedException { - // flush the cache - boolean success = true; - IProject project = fTypeCache.getProject(); - - monitor.beginTask("", 100); //$NON-NLS-1$ - - fTypeCache.flush(scope); - if (!scope.encloses(project)) { - if (project.exists() && project.isOpen()) { - success = doIndexerJob(new IndexerDependenciesJob(fIndexManager, fTypeCache, scope), monitor); - } - } - - if (!success || monitor.isCanceled()) { - throw new InterruptedException(); - } - - monitor.done(); - } - - private void update(ITypeSearchScope scope, IProgressMonitor monitor) throws InterruptedException { - boolean success = true; - IProject project = fTypeCache.getProject(); - - monitor.beginTask("", 100); //$NON-NLS-1$ - if (project.exists() && project.isOpen()) { - success = doIndexerJob(new IndexerTypesJob2(fIndexManager, fTypeCache, scope), monitor); - } - - if (!success || monitor.isCanceled()) { - throw new InterruptedException(); - } - - monitor.done(); - } - - private boolean doIndexerJob(IndexerJob job, IProgressMonitor monitor) { - if (!fEnableIndexing) { - return false; - } - - // check if indexer is busy - fIndexerIsBusy = false; - try { - fIndexManager.performConcurrentJob(new DummyIndexerJob(fIndexManager, fTypeCache.getProject()), - ICSearchConstants.CANCEL_IF_NOT_READY_TO_SEARCH, new NullProgressMonitor(), null); - } catch (OperationCanceledException e) { - fIndexerIsBusy = true; - } - - // do an immediate (but possibly incomplete) search - // if fIndexerIsBusy the cache will stay dirty and we'll hit the indexer again next time - return fIndexManager.performConcurrentJob(job, - ICSearchConstants.FORCE_IMMEDIATE_SEARCH, monitor, null); - } - - private boolean doIndexerJob(IndexerJob2 job, IProgressMonitor monitor) { - if (!fEnableIndexing) { - return false; - } - - // check if indexer is busy - fIndexerIsBusy = false; - try { - fIndexManager.performConcurrentJob(new DummyIndexerJob(fIndexManager, fTypeCache.getProject()), - ICSearchConstants.CANCEL_IF_NOT_READY_TO_SEARCH, new NullProgressMonitor(), null); - } catch (OperationCanceledException e) { - fIndexerIsBusy = true; - } - - // do an immediate (but possibly incomplete) search - // if fIndexerIsBusy the cache will stay dirty and we'll hit the indexer again next time - return fIndexManager.performConcurrentJob(job, - ICSearchConstants.FORCE_IMMEDIATE_SEARCH, monitor, null); - } - - - private static final int PATH_ENTRY_FLAGS = ICElementDelta.F_ADDED_PATHENTRY_SOURCE - | ICElementDelta.F_REMOVED_PATHENTRY_SOURCE - | ICElementDelta.F_CHANGED_PATHENTRY_INCLUDE - | ICElementDelta.F_CHANGED_PATHENTRY_MACRO - | ICElementDelta.F_PATHENTRY_REORDER; - - private void prepareToFlush(TypeCacheDelta cacheDelta, ITypeSearchScope scope) { - ITypeSearchScope deltaScope = cacheDelta.getScope(); - if (deltaScope != null) - scope.add(deltaScope); - - ICElementDelta delta = cacheDelta.getCElementDelta(); - if (delta != null) { - ICElement elem = delta.getElement(); - boolean added = (delta.getKind() == ICElementDelta.ADDED); - boolean removed = (delta.getKind() == ICElementDelta.REMOVED); - boolean contentChanged = ((delta.getFlags() & ICElementDelta.F_CONTENT) != 0); - boolean pathEntryChanged = ((delta.getFlags() & PATH_ENTRY_FLAGS) != 0); - - switch (elem.getElementType()) { - case ICElement.C_MODEL: { - if (added || removed) { - scope.add(elem); - } - } - break; - - case ICElement.C_PROJECT: { - if (added || removed || pathEntryChanged) { - scope.add(elem); - } - } - break; - - case ICElement.C_CCONTAINER: { - if (added || removed || pathEntryChanged) { - scope.add(elem); - } - } - break; - - case ICElement.C_UNIT: { - if (added || removed || pathEntryChanged || contentChanged) { - scope.add(elem); - } - } - break; - - case ICElement.C_INCLUDE: - case ICElement.C_NAMESPACE: - case ICElement.C_TEMPLATE_CLASS: - case ICElement.C_CLASS: - case ICElement.C_STRUCT: - case ICElement.C_UNION: - case ICElement.C_ENUMERATION: - case ICElement.C_TYPEDEF: - { - //TODO handle working copies - if (added || removed) { - scope.add(elem); - } - } - break; - } - } - } - - private static final class DummyIndexerJob extends IndexerJob { - public DummyIndexerJob(IndexManager indexManager, IProject project) { - super(indexManager, project); - } - protected boolean processIndex(IIndex index, IProject project, IProgressMonitor progressMonitor) { - return false; - } - } - -} - diff --git a/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/internal/core/browser/cache/TypeLocatorJob.java b/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/internal/core/browser/cache/TypeLocatorJob.java deleted file mode 100644 index 6e07320b324..00000000000 --- a/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/internal/core/browser/cache/TypeLocatorJob.java +++ /dev/null @@ -1,67 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 QNX Software Systems and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * QNX Software Systems - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.core.browser.cache; - -import org.eclipse.cdt.core.browser.ITypeInfo; -import org.eclipse.cdt.core.model.IWorkingCopyProvider; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.Status; -import org.eclipse.core.runtime.SubProgressMonitor; - -public class TypeLocatorJob extends BasicJob { - - public static final Object FAMILY = new Object(); - private ITypeInfo fLocateType; - private ITypeCache fTypeCache; - private IWorkingCopyProvider fWorkingCopyProvider; - - public TypeLocatorJob(ITypeInfo info, ITypeCache typeCache, IWorkingCopyProvider workingCopyProvider) { - super(TypeCacheMessages.getString("TypeLocatorJob.jobName"), FAMILY); //$NON-NLS-1$ - fLocateType = info; - fTypeCache = typeCache; - fWorkingCopyProvider= workingCopyProvider; - } - - public ITypeInfo getType() { - return fLocateType; - } - - protected IStatus runWithDelegatedProgress(IProgressMonitor monitor) throws InterruptedException { - boolean success = false; - long startTime = System.currentTimeMillis(); - trace("TypeLocatorJob: started"); //$NON-NLS-1$ - - try { - monitor.beginTask(TypeCacheMessages.getString("TypeLocatorJob.taskName"), 100); //$NON-NLS-1$ - - if (monitor.isCanceled()) - throw new InterruptedException(); - - TypeParser parser = new TypeParser(fTypeCache, fWorkingCopyProvider); - success = parser.findType(fLocateType, new SubProgressMonitor(monitor, 100)); - - if (monitor.isCanceled()) - throw new InterruptedException(); - - } finally { - long executionTime = System.currentTimeMillis() - startTime; - if (success) - trace("TypeLocatorJob: completed ("+ executionTime + " ms)"); //$NON-NLS-1$ //$NON-NLS-2$ - else - trace("TypeLocatorJob: aborted ("+ executionTime + " ms)"); //$NON-NLS-1$ //$NON-NLS-2$ - - monitor.done(); - } - - return Status.OK_STATUS; - } -} diff --git a/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/internal/core/browser/cache/TypeParser.java b/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/internal/core/browser/cache/TypeParser.java deleted file mode 100644 index dc5aa9e65cf..00000000000 --- a/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/internal/core/browser/cache/TypeParser.java +++ /dev/null @@ -1,955 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial implementation - * QNX Software Systems - adapted for type search - *******************************************************************************/ -package org.eclipse.cdt.internal.core.browser.cache; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Map; -import java.util.Set; - -import org.eclipse.cdt.core.CCorePlugin; -import org.eclipse.cdt.core.browser.ITypeInfo; -import org.eclipse.cdt.core.browser.ITypeReference; -import org.eclipse.cdt.core.browser.ITypeSearchScope; -import org.eclipse.cdt.core.browser.QualifiedTypeName; -import org.eclipse.cdt.core.browser.TypeInfo; -import org.eclipse.cdt.core.browser.TypeReference; -import org.eclipse.cdt.core.browser.TypeSearchScope; -import org.eclipse.cdt.core.model.CoreModel; -import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.cdt.core.model.ICProject; -import org.eclipse.cdt.core.model.ITranslationUnit; -import org.eclipse.cdt.core.model.IWorkingCopy; -import org.eclipse.cdt.core.model.IWorkingCopyProvider; -import org.eclipse.cdt.core.parser.CodeReader; -import org.eclipse.cdt.core.parser.DefaultProblemHandler; -import org.eclipse.cdt.core.parser.IParser; -import org.eclipse.cdt.core.parser.IProblem; -import org.eclipse.cdt.core.parser.IScanner; -import org.eclipse.cdt.core.parser.IScannerInfo; -import org.eclipse.cdt.core.parser.IScannerInfoProvider; -import org.eclipse.cdt.core.parser.ISourceElementCallbackDelegate; -import org.eclipse.cdt.core.parser.ISourceElementRequestor; -import org.eclipse.cdt.core.parser.ParseError; -import org.eclipse.cdt.core.parser.ParserFactory; -import org.eclipse.cdt.core.parser.ParserFactoryError; -import org.eclipse.cdt.core.parser.ParserLanguage; -import org.eclipse.cdt.core.parser.ParserMode; -import org.eclipse.cdt.core.parser.ParserTimeOut; -import org.eclipse.cdt.core.parser.ParserUtil; -import org.eclipse.cdt.core.parser.ScannerInfo; -import org.eclipse.cdt.core.parser.ast.ASTAccessVisibility; -import org.eclipse.cdt.core.parser.ast.ASTClassKind; -import org.eclipse.cdt.core.parser.ast.ASTNotImplementedException; -import org.eclipse.cdt.core.parser.ast.IASTASMDefinition; -import org.eclipse.cdt.core.parser.ast.IASTAbstractTypeSpecifierDeclaration; -import org.eclipse.cdt.core.parser.ast.IASTBaseSpecifier; -import org.eclipse.cdt.core.parser.ast.IASTClassReference; -import org.eclipse.cdt.core.parser.ast.IASTClassSpecifier; -import org.eclipse.cdt.core.parser.ast.IASTCodeScope; -import org.eclipse.cdt.core.parser.ast.IASTCompilationUnit; -import org.eclipse.cdt.core.parser.ast.IASTDeclaration; -import org.eclipse.cdt.core.parser.ast.IASTElaboratedTypeSpecifier; -import org.eclipse.cdt.core.parser.ast.IASTEnumerationReference; -import org.eclipse.cdt.core.parser.ast.IASTEnumerationSpecifier; -import org.eclipse.cdt.core.parser.ast.IASTEnumeratorReference; -import org.eclipse.cdt.core.parser.ast.IASTField; -import org.eclipse.cdt.core.parser.ast.IASTFieldReference; -import org.eclipse.cdt.core.parser.ast.IASTFunction; -import org.eclipse.cdt.core.parser.ast.IASTFunctionReference; -import org.eclipse.cdt.core.parser.ast.IASTInclusion; -import org.eclipse.cdt.core.parser.ast.IASTLinkageSpecification; -import org.eclipse.cdt.core.parser.ast.IASTMacro; -import org.eclipse.cdt.core.parser.ast.IASTMethod; -import org.eclipse.cdt.core.parser.ast.IASTMethodReference; -import org.eclipse.cdt.core.parser.ast.IASTNamespaceDefinition; -import org.eclipse.cdt.core.parser.ast.IASTNamespaceReference; -import org.eclipse.cdt.core.parser.ast.IASTOffsetableNamedElement; -import org.eclipse.cdt.core.parser.ast.IASTParameterReference; -import org.eclipse.cdt.core.parser.ast.IASTQualifiedNameElement; -import org.eclipse.cdt.core.parser.ast.IASTReference; -import org.eclipse.cdt.core.parser.ast.IASTScope; -import org.eclipse.cdt.core.parser.ast.IASTTemplateDeclaration; -import org.eclipse.cdt.core.parser.ast.IASTTemplateInstantiation; -import org.eclipse.cdt.core.parser.ast.IASTTemplateParameterReference; -import org.eclipse.cdt.core.parser.ast.IASTTemplateSpecialization; -import org.eclipse.cdt.core.parser.ast.IASTTypeSpecifier; -import org.eclipse.cdt.core.parser.ast.IASTTypedefDeclaration; -import org.eclipse.cdt.core.parser.ast.IASTTypedefReference; -import org.eclipse.cdt.core.parser.ast.IASTUsingDeclaration; -import org.eclipse.cdt.core.parser.ast.IASTUsingDirective; -import org.eclipse.cdt.core.parser.ast.IASTVariable; -import org.eclipse.cdt.core.parser.ast.IASTVariableReference; -import org.eclipse.cdt.internal.core.browser.util.SimpleStack; -import org.eclipse.cdt.utils.PathUtil; -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.resources.IWorkspace; -import org.eclipse.core.resources.IWorkspaceRoot; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.NullProgressMonitor; -import org.eclipse.core.runtime.OperationCanceledException; -import org.eclipse.core.runtime.Path; -import org.eclipse.core.runtime.SubProgressMonitor; - -public class TypeParser implements ISourceElementRequestor { - - private ITypeCache fTypeCache; - private ITypeSearchScope fScope; - private IProject fProject; - private IWorkingCopyProvider fWorkingCopyProvider; - private IProgressMonitor fProgressMonitor; - ISourceElementCallbackDelegate fLastDeclaration; - private final SimpleStack fScopeStack = new SimpleStack(); - private final SimpleStack fResourceStack = new SimpleStack(); - private ITypeInfo fTypeToFind; - private ITypeInfo fSuperTypeToFind; - private Set fProcessedTypes = new HashSet(); - private boolean fFoundType; - IParser fParser = null; - ParserTimeOut fTimeoutThread = null; - - public TypeParser(ITypeCache typeCache, IWorkingCopyProvider provider) { - fTypeCache = typeCache; - fWorkingCopyProvider = provider; - - fTimeoutThread = new ParserTimeOut("TypeParser TimeOut Thread"); //$NON-NLS-1$ - fTimeoutThread.setThreadPriority(Thread.MAX_PRIORITY); - } - - public void parseTypes(TypeSearchScope scope, IProgressMonitor monitor) throws InterruptedException { - if (monitor == null) - monitor = new NullProgressMonitor(); - - if (monitor.isCanceled()) - throw new InterruptedException(); - - fScope = new TypeSearchScope(scope); - Map workingCopyMap = null; - if (fWorkingCopyProvider != null) { - IWorkingCopy[] workingCopies = fWorkingCopyProvider.getWorkingCopies(); - if (workingCopies != null && workingCopies.length > 0) { - workingCopyMap = new HashMap(workingCopies.length); - for (int i = 0; i < workingCopies.length; ++i) { - IWorkingCopy workingCopy = workingCopies[i]; - IPath wcPath = workingCopy.getOriginalElement().getPath(); - if (fScope.encloses(wcPath)) { -// // always flush working copies from cache? -// fTypeCache.flush(wcPath); - fScope.add(wcPath, false, null); - workingCopyMap.put(wcPath, workingCopy); - } - } - } - } - - fProject = fTypeCache.getProject(); - IPath[] searchPaths = fTypeCache.getPaths(fScope); - Collection workingCopyPaths = new HashSet(); - if (workingCopyMap != null) { - collectWorkingCopiesInProject(workingCopyMap, fProject, workingCopyPaths); - //TODO what about working copies outside the workspace? - } - - monitor.beginTask("", searchPaths.length + workingCopyPaths.size()); //$NON-NLS-1$ - try { - for (Iterator pathIter = workingCopyPaths.iterator(); pathIter.hasNext(); ) { - IPath path = (IPath) pathIter.next(); - parseSource(path, fProject, workingCopyMap, new SubProgressMonitor(monitor, 1)); - } - for (int i = 0; i < searchPaths.length; ++i) { - IPath path = searchPaths[i]; - if (!workingCopyPaths.contains(path)) { - parseSource(path, fProject, workingCopyMap, new SubProgressMonitor(monitor, 1)); - } else { - monitor.worked(1); - } - } - } finally { - monitor.done(); - } - } - - public boolean findType(ITypeInfo info, IProgressMonitor monitor) throws InterruptedException { - if (monitor == null) - monitor = new NullProgressMonitor(); - - if (monitor.isCanceled()) - throw new InterruptedException(); - - fScope = new TypeSearchScope(); - ITypeReference[] refs = info.getReferences(); - if (refs == null || refs.length == 0) - return false; // no source references - - fScope.add(refs[0].getPath(), false, null); -// for (int i = 0; i < refs.length; ++i) { -// ITypeReference location = refs[i]; -// IPath path = location.getPath(); -// fScope.add(path, false, null); -// } - - Map workingCopyMap = null; - if (fWorkingCopyProvider != null) { - IWorkingCopy[] workingCopies = fWorkingCopyProvider.getWorkingCopies(); - if (workingCopies != null && workingCopies.length > 0) { - workingCopyMap = new HashMap(workingCopies.length); - for (int i = 0; i < workingCopies.length; ++i) { - IWorkingCopy workingCopy = workingCopies[i]; - IPath wcPath = workingCopy.getOriginalElement().getPath(); - if (fScope.encloses(wcPath)) { -// // always flush working copies from cache? -// fTypeCache.flush(wcPath); - fScope.add(wcPath, false, null); - workingCopyMap.put(wcPath, workingCopy); - } - } - } - } - - fProject = fTypeCache.getProject(); - IPath[] searchPaths = fTypeCache.getPaths(fScope); - Collection workingCopyPaths = new HashSet(); - if (workingCopyMap != null) { - collectWorkingCopiesInProject(workingCopyMap, fProject, workingCopyPaths); - //TODO what about working copies outside the workspace? - } - - monitor.beginTask("", searchPaths.length + workingCopyPaths.size()); //$NON-NLS-1$ - try { - fTypeToFind = info; - fFoundType = false; - for (Iterator pathIter = workingCopyPaths.iterator(); pathIter.hasNext(); ) { - IPath path = (IPath) pathIter.next(); - parseSource(path, fProject, workingCopyMap, new SubProgressMonitor(monitor, 1)); - if (fFoundType) - return true; - } - for (int i = 0; i < searchPaths.length; ++i) { - IPath path = searchPaths[i]; - if (!workingCopyPaths.contains(path)) { - parseSource(path, fProject, workingCopyMap, new SubProgressMonitor(monitor, 1)); - } else { - monitor.worked(1); - } - - if (fFoundType) - return true; - } - } finally { - fTypeToFind = null; - fFoundType = false; - monitor.done(); - } - return false; - } - - public boolean findSubTypes(ITypeInfo info, IProgressMonitor monitor) throws InterruptedException { - if (monitor == null) - monitor = new NullProgressMonitor(); - - if (monitor.isCanceled()) - throw new InterruptedException(); - - fScope = new TypeSearchScope(); - ITypeReference[] refs = info.getDerivedReferences(); - if (refs == null || refs.length == 0) - return false; // no source references - - for (int i = 0; i < refs.length; ++i) { - ITypeReference location = refs[i]; - IPath path = location.getPath(); - fScope.add(path, false, null); - } - - Map workingCopyMap = null; - if (fWorkingCopyProvider != null) { - IWorkingCopy[] workingCopies = fWorkingCopyProvider.getWorkingCopies(); - if (workingCopies != null && workingCopies.length > 0) { - workingCopyMap = new HashMap(workingCopies.length); - for (int i = 0; i < workingCopies.length; ++i) { - IWorkingCopy workingCopy = workingCopies[i]; - IPath wcPath = workingCopy.getOriginalElement().getPath(); - if (fScope.encloses(wcPath)) { -// // always flush working copies from cache? -// fTypeCache.flush(wcPath); - fScope.add(wcPath, false, null); - workingCopyMap.put(wcPath, workingCopy); - } - } - } - } - - fProject = fTypeCache.getProject(); - IPath[] searchPaths = fTypeCache.getPaths(fScope); - Collection workingCopyPaths = new HashSet(); - if (workingCopyMap != null) { - collectWorkingCopiesInProject(workingCopyMap, fProject, workingCopyPaths); - //TODO what about working copies outside the workspace? - } - - monitor.beginTask("", searchPaths.length + workingCopyPaths.size()); //$NON-NLS-1$ - try { - fTypeToFind = null; - fSuperTypeToFind = info; - fFoundType = false; - for (Iterator pathIter = workingCopyPaths.iterator(); pathIter.hasNext(); ) { - IPath path = (IPath) pathIter.next(); - parseSource(path, fProject, workingCopyMap, new SubProgressMonitor(monitor, 1)); - } - for (int i = 0; i < searchPaths.length; ++i) { - IPath path = searchPaths[i]; - if (!workingCopyPaths.contains(path)) { - parseSource(path, fProject, workingCopyMap, new SubProgressMonitor(monitor, 1)); - } else { - monitor.worked(1); - } - } - } finally { - fTypeToFind = null; - fFoundType = false; - monitor.done(); - } - return false; - } - - private void collectWorkingCopiesInProject(Map workingCopyMap, IProject project, Collection workingCopyPaths) { - for (Iterator mapIter = workingCopyMap.entrySet().iterator(); mapIter.hasNext(); ) { - Map.Entry entry = (Map.Entry) mapIter.next(); - IPath path = (IPath) entry.getKey(); - IWorkingCopy copy = (IWorkingCopy) entry.getValue(); - - ICProject cProject = copy.getCProject(); - if (cProject != null && cProject.getProject().equals(project)) { - workingCopyPaths.add(path); - } - } - } - - private void parseSource(IPath path, IProject project, Map workingCopyMap, IProgressMonitor progressMonitor) throws InterruptedException { - if (progressMonitor.isCanceled()) - throw new InterruptedException(); - - // count how many types were indexed for this path - TypeSearchScope pathScope = new TypeSearchScope(); - pathScope.add(path, false, project); - int typeCount = fTypeCache.getTypes(pathScope).length; - - progressMonitor.beginTask("", typeCount); //$NON-NLS-1$ - try { - IWorkingCopy workingCopy = null; - if (workingCopyMap != null) { - workingCopy = (IWorkingCopy) workingCopyMap.get(path); - } - - ParserLanguage language = getLanguage(project, workingCopy); - if (language == null) { - return; // not C or C++ - } - - CodeReader reader = null; - Object stackObject = null; - - IResource resource = null; - if (workingCopy != null) { - reader = createWorkingCopyReader(workingCopy); - resource = workingCopy.getResource(); - if (resource != null) { - path = resource.getLocation(); - } - stackObject = workingCopy; - } else { - IWorkspace workspace = CCorePlugin.getWorkspace(); - if (workspace != null) { - IWorkspaceRoot wsRoot = workspace.getRoot(); - if (wsRoot != null) { - resource = wsRoot.findMember(path, true); - } - } - if (resource != null) { - reader = createResourceReader(resource); - path = resource.getLocation(); - stackObject = resource; - } else { - reader = createFileReader(path); - stackObject = path; - } - } - - if (reader != null) { - fResourceStack.clear(); - fScopeStack.clear(); - fResourceStack.push(stackObject); - parseContents(path, resource, project, reader, language, progressMonitor); - fResourceStack.pop(); - } - } finally { - progressMonitor.done(); - } - } - - private ParserLanguage getLanguage(IProject project, IWorkingCopy workingCopy) { - ParserLanguage projectLanguage = null; - if (project != null) { - if (CoreModel.hasCCNature(project)) { - projectLanguage = ParserLanguage.CPP; - } else if (CoreModel.hasCNature(project)) { - projectLanguage = ParserLanguage.C; - } - } - - if (workingCopy != null) { - ParserLanguage workingCopyLanguage = null; - ITranslationUnit unit = workingCopy.getTranslationUnit(); - if (unit != null) { - if (unit.isCLanguage()) { - workingCopyLanguage = ParserLanguage.C; - } else if (unit.isCXXLanguage()) { - workingCopyLanguage = ParserLanguage.CPP; - } - } - if (workingCopyLanguage != null) { - if (projectLanguage == null) { - return workingCopyLanguage; - } else if (projectLanguage.equals(ParserLanguage.CPP)) { - // if project is CPP then working copy must be CPP - return projectLanguage; - } else { - return workingCopyLanguage; - } - } - } - return projectLanguage; - } - - private CodeReader createWorkingCopyReader(IWorkingCopy workingCopy) { - CodeReader reader = null; - IResource resource = workingCopy.getResource(); - if (resource != null && resource.isAccessible()) { - char[] contents = workingCopy.getContents(); - if (contents != null) - reader = new CodeReader(resource.getLocation().toOSString(), contents); - } - return reader; - } - - private CodeReader createResourceReader(IResource resource) { - CodeReader reader = null; - if (resource.isAccessible() && resource instanceof IFile) { - IFile file = (IFile) resource; - InputStream contents = null; - try { - contents = file.getContents(); - if (contents != null) - reader = new CodeReader(resource.getLocation().toOSString(), file.getCharset(), contents); - } catch (CoreException ex) { - ex.printStackTrace(); - } catch (IOException e) { - } finally { - if (contents != null) { - try { - contents.close(); - } catch (IOException io) { - // ignore - } - } - } - } - return reader; - } - - private CodeReader createFileReader(IPath path) { - CodeReader reader = null; - try { - reader = new CodeReader(path.toOSString()); - } catch (IOException ex) { - ex.printStackTrace(); - } - return reader; - } - - private void parseContents(IPath realPath, IResource resource, IProject project, CodeReader reader, ParserLanguage language, IProgressMonitor progressMonitor) throws InterruptedException { - IScannerInfo scanInfo = null; - - if (project != null) { - //TODO temporary workaround to catch managed build exceptions - try { - IScannerInfoProvider provider = CCorePlugin.getDefault().getScannerInfoProvider(project); - if (provider != null) { - IScannerInfo buildScanInfo = provider.getScannerInformation(resource != null ? resource : project); - if (buildScanInfo != null) - scanInfo = new ScannerInfo(buildScanInfo.getDefinedSymbols(), buildScanInfo.getIncludePaths()); - } - } catch (Exception ex) { - ex.printStackTrace(); - } - } - if (scanInfo == null) - scanInfo = new ScannerInfo(); - - try { - fProgressMonitor = progressMonitor; - IScanner scanner = ParserFactory.createScanner(reader, scanInfo, - ParserMode.STRUCTURAL_PARSE, language, this, ParserUtil.getScannerLogService(), null); - fParser = ParserFactory.createParser(scanner, this, ParserMode.STRUCTURAL_PARSE, language, ParserUtil.getParserLogService()); - - // start timer - int timeout = getParserTimeout(); - if (timeout > 0) { - fTimeoutThread.setTimeout(timeout); - fTimeoutThread.setParser(fParser); - while (!fTimeoutThread.isReadyToRun()){ - try { - Thread.sleep(20); - } catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - fTimeoutThread.startTimer(); - } - - fParser.parse(); - } catch (ParserFactoryError e) { - CCorePlugin.log(e); - } catch (ParseError e) { - // no need to log - // CCorePlugin.log(e); - } catch (OperationCanceledException e) { - throw new InterruptedException(); - } catch (Exception e) { - CCorePlugin.log(e); - } finally { - // stop timer - fTimeoutThread.stopTimer(); - fTimeoutThread.setParser(null); - fProgressMonitor = null; - fParser = null; - } - } - - public boolean acceptProblem(IProblem problem) { - return DefaultProblemHandler.ruleOnProblem(problem, ParserMode.COMPLETE_PARSE); - } - public void acceptUsingDirective(IASTUsingDirective usageDirective) {} - public void acceptUsingDeclaration(IASTUsingDeclaration usageDeclaration) {} - public void acceptASMDefinition(IASTASMDefinition asmDefinition) {} - public void acceptAbstractTypeSpecDeclaration(IASTAbstractTypeSpecifierDeclaration abstractDeclaration) {} - public void enterTemplateDeclaration(IASTTemplateDeclaration declaration) {} - public void enterTemplateSpecialization(IASTTemplateSpecialization specialization) {} - public void enterTemplateInstantiation(IASTTemplateInstantiation instantiation) {} - public void exitTemplateDeclaration(IASTTemplateDeclaration declaration) {} - public void exitTemplateSpecialization(IASTTemplateSpecialization specialization) {} - public void exitTemplateExplicitInstantiation(IASTTemplateInstantiation instantiation) {} - public void acceptParameterReference(IASTParameterReference reference) {} - public void acceptTemplateParameterReference(IASTTemplateParameterReference reference) {} - public void acceptTypedefReference(IASTTypedefReference reference) {} - public void acceptEnumeratorReference(IASTEnumeratorReference reference) {} - public void acceptClassReference(IASTClassReference reference) {} - public void acceptNamespaceReference(IASTNamespaceReference reference) {} - public void acceptVariableReference(IASTVariableReference reference) {} - public void acceptFieldReference(IASTFieldReference reference) {} - public void acceptEnumerationReference(IASTEnumerationReference reference) {} - public void acceptFunctionReference(IASTFunctionReference reference) {} - public void acceptMethodReference(IASTMethodReference reference) {} - public void acceptField(IASTField field) {} - public void acceptMacro(IASTMacro macro) {} - public void acceptVariable(IASTVariable variable) {} - public void acceptFunctionDeclaration(IASTFunction function) {} - public void acceptMethodDeclaration(IASTMethod method) {} - public void enterCodeBlock(IASTCodeScope scope) {} - public void exitCodeBlock(IASTCodeScope scope) {} - public void acceptFriendDeclaration(IASTDeclaration declaration) {} - - public void enterLinkageSpecification(IASTLinkageSpecification linkageSpec) { - pushScope(linkageSpec); - } - - public void exitLinkageSpecification(IASTLinkageSpecification linkageSpec) { - popScope(); - } - - public void enterCompilationUnit(IASTCompilationUnit compilationUnit) { - pushScope(compilationUnit); - } - - public void exitCompilationUnit(IASTCompilationUnit compilationUnit) { - popScope(); - } - - public void enterFunctionBody(IASTFunction function) { - pushScope(function); - } - - public void exitFunctionBody(IASTFunction function) { - popScope(); - } - - public void enterMethodBody(IASTMethod method) { - pushScope(method); - } - - public void exitMethodBody(IASTMethod method) { - popScope(); - } - - public void enterNamespaceDefinition(IASTNamespaceDefinition namespaceDefinition) { - fLastDeclaration = namespaceDefinition; - acceptType(namespaceDefinition); - pushScope(namespaceDefinition); - } - - public void exitNamespaceDefinition(IASTNamespaceDefinition namespaceDefinition) { - popScope(); - } - - public void enterClassSpecifier(IASTClassSpecifier classSpecification) { - fLastDeclaration = classSpecification; - acceptType(classSpecification); - pushScope(classSpecification); - } - - public void exitClassSpecifier(IASTClassSpecifier classSpecification) { - popScope(); - } - - private void pushScope(IASTScope scope) { - if (fProgressMonitor.isCanceled()) - throw new OperationCanceledException(); - fScopeStack.push(scope); - } - - private IASTScope popScope() { - if (fProgressMonitor.isCanceled()) - throw new OperationCanceledException(); - return (IASTScope) fScopeStack.pop(); - } - - public void acceptTypedefDeclaration(IASTTypedefDeclaration typedef) { - fLastDeclaration = typedef; - acceptType(typedef); - } - - public void acceptEnumerationSpecifier(IASTEnumerationSpecifier enumeration) { - fLastDeclaration = enumeration; - acceptType(enumeration); - } - - public void acceptElaboratedForewardDeclaration(IASTElaboratedTypeSpecifier elaboratedType) { - // acceptType(elaboratedType); - } - - public void enterInclusion(IASTInclusion inclusion) { - if (fProgressMonitor.isCanceled()) - throw new OperationCanceledException(); - - String includePath = inclusion.getFullFileName(); - IPath path = new Path(includePath); - path = PathUtil.getWorkspaceRelativePath(path); - - IResource resource = null; - IWorkspace workspace = CCorePlugin.getWorkspace(); - if (workspace != null) { - IWorkspaceRoot wsRoot = workspace.getRoot(); - if (wsRoot != null) { - resource = wsRoot.findMember(path, true); - } - } - //TODO do inclusions get parsed as working copies? - - Object stackObject = path; - if (resource != null) - stackObject = resource; - - fResourceStack.push(stackObject); - } - - public void exitInclusion(IASTInclusion inclusion) { - if (fProgressMonitor.isCanceled()) - throw new OperationCanceledException(); - fResourceStack.pop(); - } - - private class NodeTypeInfo { - int type; - String name; - String[] enclosingNames; - int offset; - int end; - IASTOffsetableNamedElement offsetable; - - void init() { - type = 0; - name = null; - enclosingNames = null; - offset = 0; - end = 0; - offsetable = null; - } - - boolean parseNodeForTypeInfo(ISourceElementCallbackDelegate node) { - init(); - - if (node instanceof IASTReference) { - IASTReference reference = (IASTReference) node; - offset = reference.getOffset(); - end = offset + reference.getName().length(); - } else if (node instanceof IASTOffsetableNamedElement) { - offsetable = (IASTOffsetableNamedElement) node; - offset = offsetable.getNameOffset() != 0 ? offsetable.getNameOffset() : offsetable.getStartingOffset(); - end = offsetable.getNameEndOffset(); - if (end == 0) { - end = offset + offsetable.getName().length(); - } - } - - if (node instanceof IASTReference) - node = fLastDeclaration; - if (node instanceof IASTReference) { - offsetable = (IASTOffsetableNamedElement) ((IASTReference) node).getReferencedElement(); - name = ((IASTReference) node).getName(); - } else if (node instanceof IASTOffsetableNamedElement) { - offsetable = (IASTOffsetableNamedElement) node; - name = offsetable.getName(); - } else { - return false; - } - - // skip unnamed structs - if (name == null || name.length() == 0) - return false; - - // skip unused types - type = getElementType(offsetable); - if (type == 0) { - return false; - } - - // collect enclosing names - if (offsetable instanceof IASTQualifiedNameElement) { - String[] names = ((IASTQualifiedNameElement) offsetable).getFullyQualifiedName(); - if (names != null && names.length > 1) { - enclosingNames = new String[names.length - 1]; - System.arraycopy(names, 0, enclosingNames, 0, names.length - 1); - } - } - - return true; - } - - } - - private void acceptType(ISourceElementCallbackDelegate node) { - if (fProgressMonitor.isCanceled()) - throw new OperationCanceledException(); - - // skip local declarations - IASTScope currentScope = (IASTScope) fScopeStack.top(); - if (currentScope instanceof IASTFunction || currentScope instanceof IASTMethod) { - return; - } - - NodeTypeInfo nodeInfo = new NodeTypeInfo(); - if (nodeInfo.parseNodeForTypeInfo(node)) { - TypeReference originalLocation = null; - Object originalRef = fResourceStack.bottom(); - if (originalRef instanceof IWorkingCopy) { - IWorkingCopy workingCopy = (IWorkingCopy) originalRef; - originalLocation = new TypeReference(workingCopy, fProject); - } else if (originalRef instanceof IResource) { - IResource resource = (IResource) originalRef; - originalLocation = new TypeReference(resource, fProject); - } else if (originalRef instanceof IPath) { - IPath path = PathUtil.getProjectRelativePath((IPath)originalRef, fProject); - originalLocation = new TypeReference(path, fProject); - } - - TypeReference resolvedLocation = null; - Object resolvedRef = fResourceStack.top(); - if (resolvedRef instanceof IWorkingCopy) { - IWorkingCopy workingCopy = (IWorkingCopy) resolvedRef; - resolvedLocation = new TypeReference(workingCopy, fProject, nodeInfo.offset, nodeInfo.end - nodeInfo.offset); - } else if (resolvedRef instanceof IResource) { - IResource resource = (IResource) resolvedRef; - resolvedLocation = new TypeReference(resource, fProject, nodeInfo.offset, nodeInfo.end - nodeInfo.offset); - } else if (resolvedRef instanceof IPath) { - IPath path = PathUtil.getProjectRelativePath((IPath)resolvedRef, fProject); - resolvedLocation = new TypeReference(path, fProject, nodeInfo.offset, nodeInfo.end - nodeInfo.offset); - } - - if (fTypeToFind != null) { - if ((fTypeToFind.getCElementType() == nodeInfo.type || fTypeToFind.isUndefinedType()) && nodeInfo.name.equals(fTypeToFind.getName())) { - QualifiedTypeName qualifiedName = new QualifiedTypeName(nodeInfo.name, nodeInfo.enclosingNames); - if (qualifiedName.equals(fTypeToFind.getQualifiedTypeName())) { - // add types to cache - ITypeInfo newType = addType(nodeInfo.type, qualifiedName, originalLocation, resolvedLocation); - if (newType != null && node instanceof IASTClassSpecifier) { - addSuperClasses(newType, (IASTClassSpecifier)node, originalLocation, fProcessedTypes); - } - fProgressMonitor.worked(1); - - fFoundType = true; - // terminate the parser - fParser.cancel(); - } - } - } else { - // add types to cache - QualifiedTypeName qualifiedName = new QualifiedTypeName(nodeInfo.name, nodeInfo.enclosingNames); - ITypeInfo newType = addType(nodeInfo.type, qualifiedName, originalLocation, resolvedLocation); - if (newType != null && node instanceof IASTClassSpecifier) { - addSuperClasses(newType, (IASTClassSpecifier)node, originalLocation, fProcessedTypes); - } - fProgressMonitor.worked(1); - } - } - } - - int getElementType(IASTOffsetableNamedElement offsetable) { - if (offsetable instanceof IASTClassSpecifier || offsetable instanceof IASTElaboratedTypeSpecifier) { - ASTClassKind kind = null; - if (offsetable instanceof IASTClassSpecifier) { - kind = ((IASTClassSpecifier) offsetable).getClassKind(); - } else { - kind = ((IASTElaboratedTypeSpecifier) offsetable).getClassKind(); - } - if (kind == ASTClassKind.CLASS) { - return ICElement.C_CLASS; - } else if (kind == ASTClassKind.STRUCT) { - return ICElement.C_STRUCT; - } else if (kind == ASTClassKind.UNION) { - return ICElement.C_UNION; - } - } else if (offsetable instanceof IASTNamespaceDefinition) { - return ICElement.C_NAMESPACE; - } else if (offsetable instanceof IASTEnumerationSpecifier) { - return ICElement.C_ENUMERATION; - } else if (offsetable instanceof IASTTypedefDeclaration) { - return ICElement.C_TYPEDEF; - } - return 0; - } - - private void addSuperClasses(ITypeInfo type, IASTClassSpecifier classSpec, TypeReference location, Set processedClasses) { - Iterator baseIter = classSpec.getBaseClauses(); - if (baseIter != null) { - while (baseIter.hasNext()) { - IASTBaseSpecifier baseSpec = (IASTBaseSpecifier) baseIter.next(); - try { - ASTAccessVisibility baseAccess = baseSpec.getAccess(); - - IASTClassSpecifier parentClass = null; - IASTTypeSpecifier parentSpec = baseSpec.getParentClassSpecifier(); - if (parentSpec instanceof IASTClassSpecifier) - parentClass = (IASTClassSpecifier) parentSpec; - - if (parentClass != null) { - NodeTypeInfo nodeInfo = new NodeTypeInfo(); - if (nodeInfo.parseNodeForTypeInfo(parentClass)) { - // add type to cache - ITypeInfo superType = addSuperType(type, nodeInfo.type, nodeInfo.name, nodeInfo.enclosingNames, location, baseAccess, baseSpec.isVirtual()); - - // recursively process super super classes - if (!processedClasses.contains(parentClass)) { - processedClasses.add(parentClass); - addSuperClasses(superType, parentClass, location, processedClasses); - } - } - } - } catch (ASTNotImplementedException e) { - } - } - } - } - - private ITypeInfo addType(int type, QualifiedTypeName qualifiedName, TypeReference originalLocation, TypeReference resolvedLocation) { - ITypeInfo info = fTypeCache.getType(type, qualifiedName); - if (info == null || info.isUndefinedType()) { - // add new type to cache - if (info != null) { - info.setCElementType(type); - } else { - info = new TypeInfo(type, qualifiedName); - fTypeCache.insert(info); - } - - info.addReference(originalLocation); - } - - info.addReference(resolvedLocation); - - return info; - } - - private ITypeInfo addSuperType(ITypeInfo addToType, int type, String name, String[] enclosingNames, TypeReference location, ASTAccessVisibility access, boolean isVirtual) { - QualifiedTypeName qualifiedName = new QualifiedTypeName(name, enclosingNames); - ITypeInfo superType = fTypeCache.getType(type, qualifiedName); - if (superType == null || superType.isUndefinedType()) { - if (superType != null) { - // merge with existing type - superType.setCElementType(type); - } else { - // add new type to cache - superType = new TypeInfo(type, qualifiedName); - fTypeCache.insert(superType); - } - } - superType.addDerivedReference(location); - - if (fSuperTypeToFind != null && fSuperTypeToFind.equals(superType)) { - //TODO don't need to do anything here? - } - fTypeCache.addSupertype(addToType, superType, access, isVirtual); - fTypeCache.addSubtype(superType, addToType); - return superType; - } - - /* (non-Javadoc) - * @see org.eclipse.cdt.core.parser.ISourceElementRequestor#createReader(java.lang.String) - */ - public CodeReader createReader(String finalPath, Iterator workingCopies) { - return ParserUtil.createReader(finalPath, workingCopies); - } - - private static final int DEFAULT_PARSER_TIMEOUT = 30; - - public int getParserTimeout() { - //TODO we shouldn't be trying to access the indexer prefs - //TODO clean this up - int timeout = 0; - try { - // here we just reuse the indexer timeout - String str = CCorePlugin.getDefault().getPluginPreferences().getString("CDT_INDEXER_TIMEOUT"); //$NON-NLS-1$ - if (str != null && str.length() > 0) { - int val = Integer.valueOf(str).intValue(); - if (val > 0) { - timeout = val; - } - } - } catch (NumberFormatException e) { - // do nothing - } - - if (timeout == 0) { - timeout = DEFAULT_PARSER_TIMEOUT; - } - return timeout; - } - -} diff --git a/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/internal/core/browser/util/ArrayUtil.java b/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/internal/core/browser/util/ArrayUtil.java deleted file mode 100644 index a7f62f29445..00000000000 --- a/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/internal/core/browser/util/ArrayUtil.java +++ /dev/null @@ -1,53 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 QNX Software Systems and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * QNX Software Systems - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.core.browser.util; - -/** - * A helper class which allows you to perform some - * simple set operations on int arrays. - */ -public class ArrayUtil { - private ArrayUtil() { - } - - // returns true if set contains elem - public static boolean contains(int[] set, int elem) { - if (set == null) - return false; - for (int i= 0; i < set.length; ++i) { - if (set[i] == elem) - return true; - } - return false; - } - - // returns true if set contains all of subset - public static boolean containsAll(int[] set, int[] subset) { - if (set == null || subset == null) - return false; - for (int i= 0; i < subset.length; ++i) { - if (!contains(set, subset[i])) - return false; - } - return true; - } - - // return a copy of fromSet - public static int[] clone(int[] fromSet) { - if (fromSet == null) - return null; - int[] newSet= new int[fromSet.length]; - for (int i= 0; i < fromSet.length; ++i) { - newSet[i]= fromSet[i]; - } - return newSet; - } -} diff --git a/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/internal/core/browser/util/DelegatedProgressMonitor.java b/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/internal/core/browser/util/DelegatedProgressMonitor.java deleted file mode 100644 index 4c229af80ca..00000000000 --- a/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/internal/core/browser/util/DelegatedProgressMonitor.java +++ /dev/null @@ -1,249 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 QNX Software Systems and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * QNX Software Systems - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.core.browser.util; - -import java.util.ArrayList; -import java.util.Iterator; - -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IProgressMonitorWithBlocking; -import org.eclipse.core.runtime.IStatus; - -/** - * A wrapper around one or more progress monitors. Forwards - * IProgressMonitor and IProgressMonitorWithBlocking - * methods to the delegate monitors. - */ -public class DelegatedProgressMonitor implements IProgressMonitor, IProgressMonitorWithBlocking { - - private static int INITIAL_DELEGATE_COUNT = 2; - private final ArrayList fDelegateList = new ArrayList(INITIAL_DELEGATE_COUNT); - String fTaskName; - String fSubTask; - int fTotalWork; - private double fWorked; - private boolean fIsBlocked; - boolean fIsCanceled; - - /** - * Creates a new delegated monitor. - */ - public DelegatedProgressMonitor() { - init(); - } - - /** - * Creates a new delegated monitor, and adds a delegate. - */ - public DelegatedProgressMonitor(IProgressMonitor delegate) { - init(); - addDelegate(delegate); - } - - /** - * Resets delegated monitor to initial state. - */ - public synchronized void init() { - fTaskName= null; - fSubTask= null; - fTotalWork= IProgressMonitor.UNKNOWN; - fWorked= 0.0f; - fIsBlocked= false; - fIsCanceled= false; - } - - /* - * @see IProgressMonitor#beginTask - */ - public synchronized void beginTask(String name, int totalWork) { - fTaskName = name; - fTotalWork = totalWork; - visitDelegates(new IDelegateVisitor() { - public void visit(IProgressMonitor delegate) { - delegate.beginTask(fTaskName, fTotalWork); - } - }); - } - - /* - * @see IProgressMonitor#done - */ - public synchronized void done() { - visitDelegates(new IDelegateVisitor() { - public void visit(IProgressMonitor delegate) { - delegate.done(); - } - }); - } - - /* - * @see IProgressMonitor#setTaskName - */ - public synchronized void setTaskName(String name) { - fTaskName = name; - visitDelegates(new IDelegateVisitor() { - public void visit(IProgressMonitor delegate) { - delegate.setTaskName(fTaskName); - } - }); - } - - /* - * @see IProgressMonitor#subTask - */ - public synchronized void subTask(String name) { - fSubTask = name; - visitDelegates(new IDelegateVisitor() { - public void visit(IProgressMonitor delegate) { - delegate.subTask(fSubTask); - } - }); - } - - /* - * @see IProgressMonitor#worked - */ - public void worked(int work) { - internalWorked(work); - } - - /* - * @see IProgressMonitor#internalWorked - */ - public synchronized void internalWorked(double internalWork) { - fWorked += internalWork; - final double fInternalWork = internalWork; - visitDelegates(new IDelegateVisitor() { - public void visit(IProgressMonitor delegate) { - delegate.internalWorked(fInternalWork); - } - }); - } - - /* - * @see IProgressMonitor#isCanceled - */ - public synchronized boolean isCanceled() { - visitDelegates(new IDelegateVisitor() { - public void visit(IProgressMonitor delegate) { - fIsCanceled |= delegate.isCanceled(); - } - }); - return fIsCanceled; - } - - /* - * @see IProgressMonitor#setCanceled - */ - public synchronized void setCanceled(boolean canceled) { - fIsCanceled = canceled; - visitDelegates(new IDelegateVisitor() { - public void visit(IProgressMonitor delegate) { - delegate.setCanceled(fIsCanceled); - } - }); - } - - /* - * @see IProgressMonitor#setBlocked - */ - public synchronized void setBlocked(IStatus reason) { - fIsBlocked = true; - final IStatus fReason = reason; - visitDelegates(new IDelegateVisitor() { - public void visit(IProgressMonitor delegate) { - if (delegate instanceof IProgressMonitorWithBlocking) - ((IProgressMonitorWithBlocking) delegate).setBlocked(fReason); - } - }); - } - - /* - * @see IProgressMonitor#clearBlocked - */ - public synchronized void clearBlocked() { - fIsBlocked = false; - visitDelegates(new IDelegateVisitor() { - public void visit(IProgressMonitor delegate) { - if (delegate instanceof IProgressMonitorWithBlocking) - ((IProgressMonitorWithBlocking) delegate).clearBlocked(); - } - }); - } - - /** - * Adds a delegate. - */ - public synchronized void addDelegate(IProgressMonitor delegate) { - if (fDelegateList.indexOf(delegate) == -1) { - if (fTaskName != null) - syncUp(delegate); - fDelegateList.add(delegate); - } - } - - /** - * Brings delegate in sync with current progress. - */ - private void syncUp(IProgressMonitor delegate) { - delegate.beginTask(fTaskName, fTotalWork); - delegate.internalWorked(fWorked); - if (fSubTask != null && fSubTask.length() > 0) - delegate.subTask(fSubTask); - if (fIsBlocked && delegate instanceof IProgressMonitorWithBlocking) - ((IProgressMonitorWithBlocking) delegate).setBlocked(null); - } - - /** - * Removes a delegate. - */ - public synchronized void removeDelegate(IProgressMonitor delegate) { - int index = fDelegateList.indexOf(delegate); - if (index != -1) { - fDelegateList.remove(index); - } - } - - /** - * Removes all delegates. - */ - public synchronized void removeAllDelegates() { - fDelegateList.clear(); - } - - /** - * Returns the delegate list. - * - * @return An array of progress monitors added using addDelegate(). - */ - public synchronized IProgressMonitor[] getDelegates() { - return (IProgressMonitor[]) fDelegateList.toArray(); - } - - /** - * Defines a delegate visitor. - */ - private static interface IDelegateVisitor { - public void visit(IProgressMonitor delegate); - } - - /** - * Visits each delegate in the delegates list. - */ - private void visitDelegates(IDelegateVisitor visitor) { - // Clone the delegates since they could remove themselves when called - ArrayList delegatesList = (ArrayList) fDelegateList.clone(); - for (Iterator i = delegatesList.iterator(); i.hasNext(); ) { - IProgressMonitor delegate = (IProgressMonitor) i.next(); - visitor.visit(delegate); - } - } -} diff --git a/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/internal/core/browser/util/SimpleStack.java b/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/internal/core/browser/util/SimpleStack.java deleted file mode 100644 index 433439af856..00000000000 --- a/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/internal/core/browser/util/SimpleStack.java +++ /dev/null @@ -1,84 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 QNX Software Systems and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * QNX Software Systems - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.core.browser.util; - -import java.util.ArrayList; - -/** - * A helper class which allows you to perform some simple - * stack operations. Avoids the extra overhead of - * synchronization in Java.Util.Stack. - */ -public class SimpleStack { - - private static int INITIAL_STACK_SIZE = 10; - private ArrayList items; - private static boolean VERBOSE = false; - - public SimpleStack() { - items = new ArrayList(INITIAL_STACK_SIZE); - } - - public SimpleStack(int initialSize) { - items = new ArrayList(initialSize); - } - - public void clear() { - items.clear(); - } - - public Object push(Object item) { - items.add(item); - if (VERBOSE) - trace("push on stack: " + item); //$NON-NLS-1$ - return item; - } - - public Object pop() { - int top = items.size()-1; - if (top < 0) - return null; - Object item = items.get(top); - items.remove(top); - if (VERBOSE) - trace("pop from stack: " + item); //$NON-NLS-1$ - return item; - } - - public Object top() { - int top = items.size()-1; - if (top < 0) - return null; - return items.get(top); - } - - public Object bottom() { - if (items.size() == 0) - return null; - return items.get(0); - } - - public boolean isEmpty() { - return (items.size() == 0); - } - - public Object[] toArray() { - return items.toArray(); - } - - public Object[] toArray(Object a[]) { - return items.toArray(a); - } - - private static void trace(String msg) { - System.out.println("(" + Thread.currentThread() + ") " + msg); //$NON-NLS-1$ //$NON-NLS-2$ - } -} diff --git a/core/org.eclipse.cdt.core/dependency/ChangeLog b/core/org.eclipse.cdt.core/dependency/ChangeLog deleted file mode 100644 index 05411b253a7..00000000000 --- a/core/org.eclipse.cdt.core/dependency/ChangeLog +++ /dev/null @@ -1,74 +0,0 @@ -2005-03-12 Bogdan Gheorghe - - Updated references from IndexManager to SourceIndexer due to new indexer framework - - * src/org/eclipse/cdt/internal/core/sourcedependency/DependencyQueryJob.java - * src/org/eclipse/cdt/internal/core/sourcedependency/UpdateDependency.java - -2004-02-25 Bogdan Gheorghe - - Check to see if the resource has a location before using it in - UpdateDependency - -2003-11-10 Bogdan Gheorghe - - Added a null resource check in UpdateDependency to fix up - a potential NPE in the test suite - -2003-10-23 Bogdan Gheorghe - - Added UpdateDependency job - -2003-09-25 Bogdan Gheorghe - - As a result of folding the dependency service into the indexer - have removed the following files: - - * src/org/eclipse/cdt/internal/core/sourcedependency/AddFileToDependencyTree.java - * src/org/eclipse/cdt/internal/core/sourcedependency/DependencyManager.java - * src/org/eclipse/cdt/internal/core/sourcedependency/DependencyRequest.java - * src/org/eclipse/cdt/internal/core/sourcedependency/DependencyRequestor.java - * src/org/eclipse/cdt/internal/core/sourcedependency/DependencySelector.java - * src/org/eclipse/cdt/internal/core/sourcedependency/DependencyTree.java - * src/org/eclipse/cdt/internal/core/sourcedependency/EntireProjectDependencyTree.java - * src/org/eclipse/cdt/internal/core/sourcedependency/IDependencyTree.java - * src/org/eclipse/cdt/internal/core/sourcedependency/IPreprocessorOutput.java - * src/org/eclipse/cdt/internal/core/sourcedependency/ISourceDependency.java - * src/org/eclipse/cdt/internal/core/sourcedependency/PreprocessorOutput.java - * src/org/eclipse/cdt/internal/core/sourcedependency/RemoveFromDependencyTree.java - * src/org/eclipse/cdt/internal/core/sourcedependency/impl/IncludeEntry.java - * src/org/eclipse/cdt/internal/core/sourcedependency/impl/IncludeEntryHashedArray.java - * src/org/eclipse/cdt/internal/core/sourcedependency/impl/InMemoryTree.java - - - -2003-09-22 Bogdan Gheorghe - - Took out enable section for DependencyManager - -2003-09-11 Bogdan Gheorghe - - Added null guard to DependencyManager.getDependencyTree(), - DependencyTree.getFileDependencies() - -2003-09-08 Andrew Niefer - - Modified calls to ParserFactory to specify which language to use - - Modified IDependencyTree.add to take ParserLanguage as a parameter so that it can - be passed on when creating the preprocessor - -2003-07-23 Bogdan Gheorghe - - Added initial dependency implementation - - * src/org/eclipse/cdt/internal/core/sourcedependency/AddFileToDependencyTree.java - * src/org/eclipse/cdt/internal/core/sourcedependency/DependencyManager.java - * src/org/eclipse/cdt/internal/core/sourcedependency/DenpendencyQueryJob.java - * src/org/eclipse/cdt/internal/core/sourcedependency/DependencyRequest.java - * src/org/eclipse/cdt/internal/core/sourcedependency/DependencyRequestor.java - * src/org/eclipse/cdt/internal/core/sourcedependency/DependencyTree.java - * src/org/eclipse/cdt/internal/core/sourcedependency/EntireProjectDependencyTree.java - * src/org/eclipse/cdt/internal/core/sourcedependency/IDependencyTree.java - * src/org/eclipse/cdt/internal/core/sourcedependency/IPreprocessorOutput.java - * src/org/eclipse/cdt/internal/core/sourcedependency/ISourceDependency.java - * src/org/eclipse/cdt/internal/core/sourcedependency/PreprocessorOutput.java - - * src/org/eclipse/cdt/internal/core/sourcedependency/impl/IncludeEntry.java - * src/org/eclipse/cdt/internal/core/sourcedependency/impl/IncludeEntryHashedArray.java - * src/org/eclipse/cdt/internal/core/sourcedependency/impl/InMemoryTree.java - * src/org/eclipse/cdt/internal/core/sourcedependency/impl/Node.java - -- - \ No newline at end of file diff --git a/core/org.eclipse.cdt.core/dependency/org/eclipse/cdt/internal/core/sourcedependency/DependencyQueryJob.java b/core/org.eclipse.cdt.core/dependency/org/eclipse/cdt/internal/core/sourcedependency/DependencyQueryJob.java deleted file mode 100644 index 295f44e674b..00000000000 --- a/core/org.eclipse.cdt.core/dependency/org/eclipse/cdt/internal/core/sourcedependency/DependencyQueryJob.java +++ /dev/null @@ -1,205 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2003, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ - -package org.eclipse.cdt.internal.core.sourcedependency; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import org.eclipse.cdt.core.CCorePlugin; -import org.eclipse.cdt.core.search.SearchEngine; -import org.eclipse.cdt.internal.core.index.IIndex; -import org.eclipse.cdt.internal.core.index.cindexstorage.IncludeEntry; -import org.eclipse.cdt.internal.core.index.cindexstorage.IndexedFileEntry; -import org.eclipse.cdt.internal.core.index.cindexstorage.io.BlocksIndexInput; -import org.eclipse.cdt.internal.core.index.cindexstorage.io.IndexInput; -import org.eclipse.cdt.internal.core.index.domsourceindexer.DOMSourceIndexer; -import org.eclipse.cdt.internal.core.search.IndexSelector; -import org.eclipse.cdt.internal.core.search.indexing.IndexManager; -import org.eclipse.cdt.internal.core.search.indexing.ReadWriteMonitor; -import org.eclipse.cdt.internal.core.search.processing.IIndexJob; -import org.eclipse.cdt.internal.core.search.processing.JobManager; -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.OperationCanceledException; - -/** - * @author bgheorgh - */ -public class DependencyQueryJob implements IIndexJob { - - IProject project; - IFile file; - ArrayList includeFiles; - DOMSourceIndexer indexer; - IndexManager indexManager; - protected IndexSelector indexSelector; - protected long executionTime = 0; - - public DependencyQueryJob(IProject project, IFile file, DOMSourceIndexer indexer, List includeFiles) { - this.project = project; - this.file = file; - this.indexer = indexer; - this.includeFiles = (ArrayList) includeFiles; - this.indexManager = CCorePlugin.getDefault().getCoreModel().getIndexManager(); - } - - /* (non-Javadoc) - * @see org.eclipse.cdt.internal.core.search.processing.IJob#belongsTo(java.lang.String) - */ - public boolean belongsTo(String jobFamily) { - // TODO Auto-generated method stub - return true; - } - - /* (non-Javadoc) - * @see org.eclipse.cdt.internal.core.search.processing.IJob#cancel() - */ - public void cancel() {} - - /* (non-Javadoc) - * @see org.eclipse.cdt.internal.core.search.processing.IJob#execute(org.eclipse.core.runtime.IProgressMonitor) - */ - public boolean execute(IProgressMonitor progressMonitor) { - if ((project == null) ||(file == null)) return false; - // - if (progressMonitor != null && progressMonitor.isCanceled()) - throw new OperationCanceledException(); - boolean isComplete = COMPLETE; - executionTime = 0; - if (this.indexSelector == null) { - this.indexSelector = - new IndexSelector(SearchEngine.createWorkspaceScope(), null, false, indexManager); - } - IIndex[] searchIndexes = this.indexSelector.getIndexes(); - try { - int max = searchIndexes.length; - int min=0; - if (progressMonitor != null) { - progressMonitor.beginTask("", max); //$NON-NLS-1$ - } - for (int i = 0; i < max; i++) { - isComplete &= getFileDeps(searchIndexes[i], progressMonitor); - if (progressMonitor != null) { - if (progressMonitor.isCanceled()) { - throw new OperationCanceledException(); - } else { - progressMonitor.worked(1); - } - } - } - if (JobManager.VERBOSE) { - JobManager.verbose("-> execution time: " + executionTime + "ms - " + this);//$NON-NLS-1$//$NON-NLS-2$ - } - return isComplete; - } finally { - if (progressMonitor != null) { - progressMonitor.done(); - } - } - } - - /** - * @param index - * @param progressMonitor - * @return - */ - public boolean getFileDeps(IIndex index, IProgressMonitor progressMonitor){ - - if (progressMonitor != null && progressMonitor.isCanceled()) - throw new OperationCanceledException(); - - if (index == null) - return COMPLETE; - - - if (!(indexer instanceof DOMSourceIndexer)) - return FAILED; - - - DOMSourceIndexer sourceIndexer = (DOMSourceIndexer)indexer; - - ReadWriteMonitor monitor = sourceIndexer.getMonitorFor(index); - if (monitor == null) - return COMPLETE; // index got deleted since acquired - try { - monitor.enterRead(); // ask permission to read - - /* if index has changed, commit these before querying */ - if (index.hasChanged()) { - try { - monitor.exitRead(); // free read lock - monitor.enterWrite(); // ask permission to write - sourceIndexer.saveIndex(index); - } catch (IOException e) { - return FAILED; - } finally { - monitor.exitWriteEnterRead(); // finished writing and reacquire read permission - } - } - long start = System.currentTimeMillis(); - // - IndexInput input = new BlocksIndexInput(index.getIndexFile()); - try { - input.open(); - findDep(input); - } finally { - input.close(); - } - - executionTime += System.currentTimeMillis() - start; - return COMPLETE; - } - catch (IOException e){ - return FAILED; - } - finally { - monitor.exitRead(); // finished reading - } - } - - /** - * @param input - * @param includeFiles - */ - private void findDep(IndexInput input) throws IOException { - - IndexedFileEntry indexedFile = input.getIndexedFile(file.getFullPath().toString()); - if (indexedFile == null) return; - - - int fileNum =indexedFile.getFileID(); - IncludeEntry[] tempEntries = input.queryIncludeEntries(fileNum); - if (tempEntries != null){ - for (int r=0; rPreferences>Java>Code Generation>Code and Comments - */ -package org.eclipse.cdt.internal.core.sourcedependency; - -import org.eclipse.cdt.core.CCorePlugin; -import org.eclipse.cdt.core.search.ICSearchConstants; -import org.eclipse.cdt.core.search.ICSearchScope; -import org.eclipse.cdt.core.search.SearchEngine; -import org.eclipse.cdt.internal.core.index.domsourceindexer.DOMSourceIndexer; -import org.eclipse.cdt.internal.core.search.PathCollector; -import org.eclipse.cdt.internal.core.search.PatternSearchJob; -import org.eclipse.cdt.internal.core.search.indexing.IndexManager; -import org.eclipse.cdt.internal.core.search.matching.CSearchPattern; -import org.eclipse.cdt.internal.core.search.processing.IIndexJob; -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.resources.IWorkspaceRoot; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.Path; - -/** - * @author bgheorgh - * - * To change the template for this generated type comment go to - * Window>Preferences>Java>Code Generation>Code and Comments - */ -public class UpdateDependency implements IIndexJob { - PathCollector pathCollector; - IFile resource=null; - DOMSourceIndexer indexer; - - /** - * @param resource - */ - public UpdateDependency(IResource resource, DOMSourceIndexer indexer) { - if (resource instanceof IFile) - this.resource = (IFile) resource; - - this.indexer = indexer; - } - - /* (non-Javadoc) - * @see org.eclipse.cdt.internal.core.search.processing.IJob#belongsTo(java.lang.String) - */ - public boolean belongsTo(String jobFamily) { - // TODO Auto-generated method stub - return false; - } - - /* (non-Javadoc) - * @see org.eclipse.cdt.internal.core.search.processing.IJob#cancel() - */ - public void cancel() { - // TODO Auto-generated method stub - - } - - /* (non-Javadoc) - * @see org.eclipse.cdt.internal.core.search.processing.IJob#execute(org.eclipse.core.runtime.IProgressMonitor) - */ - public boolean execute(IProgressMonitor progress) { - if (resource == null) return false; - - IPath location = resource.getLocation(); - if (location == null) return false; - - PathCollector pathCollector = new PathCollector(); - //SubProgressMonitor subMonitor = (progressMonitor == null ) ? null : new SubProgressMonitor( progressMonitor, 5 ); - ICSearchScope scope = SearchEngine.createWorkspaceScope(); - CSearchPattern pattern = CSearchPattern.createPattern(location.toOSString(),ICSearchConstants.INCLUDE, ICSearchConstants.REFERENCES,ICSearchConstants.EXACT_MATCH,true); - IndexManager indexManager = CCorePlugin.getDefault().getCoreModel().getIndexManager(); - indexManager.performConcurrentJob( - new PatternSearchJob( - pattern, - scope, - pathCollector, - indexManager - ), - ICSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, - null, - this ); - - String[] iPath = pathCollector.getPaths(); - - if (iPath.length > 0){ - //If we found any dependents on this header file, indexing them will also index the header - for (int i=0;iICDTIndexer indexes ONE document at each time. It adds the document names and - * the words references to an IIndex. Each IIndexer can index certain types of document, and should - * not index the other files. - * - * Warning: This interface is still under development - API may change. - * @since 3.0 - */ -public interface ICDTIndexer { - - /** - * Indexer Support bit flags - */ - static public final int _DECLARATIONS = 1; - static public final int _DEFINITIONS = 2; - static public final int _REFERENCES = 4; - static public final int _LINENUMBERS = 8; - static public final int _OFFSETINFO = 16; - static public final int _CPP = 32; - static public final int _C = 64; - - /** - * Indexer Policy bit flags - */ - static public final int _NORMAL= 1; - static public final int _POSTBUILD = 2; - static public final int _MANUAL = 4; - static public final int _STATIC = 8; - static public final int _DELAYUNTILBUILDINFO = 16; - - /*** - * Indexable units - */ - static public final int PROJECT = 1; - static public final int FOLDER = 2; - static public final int COMPILATION_UNIT = 4; - - - /** - * Returns what features this ICDTIndexer provides. - */ - public int getIndexerFeatures(); - - /** - * The IndexManager calls addRequest when it receives an event from the DeltaProcessor. - * The IResourcDelta and (TODO: IResourceChangeEvent are provided for indexers - * to decide how to schedule this event). - */ - public void addRequest(IProject project, IResourceDelta delta, int kind); - - /** - * The IndexManager calls addRequest when it receives an event from the DeltaProcessor. - * The IResourcDelta and (TODO:IResourceChangeEvent are provided for the indexder - * to decide how to schedule this event). - */ - public void removeRequest(IProject project, IResourceDelta delta, int kind); - - /** - * Adds the given resource to the IProject's index - */ - public void addResource(IProject project, IResource resource); - - /** - * Removes the given resource from the IProject's index - */ - public void removeResource(IProject project, IResource resource); - - /** - * Attempts to add the resource type specified by the path to the project's index - */ - public void addResourceByPath(IProject project, IPath path, int resourceType); - - /** - * The IndexManager will send out a jobFinishedEvent to the indexer that - * had scheduled the previous runnign job to give that indexer a chance to update its - * state info. - */ - public void indexJobFinishedNotification(IIndexJob job); - - /** - * The IndexManager will notify all indexers of impending shutdown events - * in order to allow indexers to perform whatever clean up they need to do. - */ - public void shutdown(); - - /** - * Called by the index manager when there are no index jobs queued up - can be - * used by the indexer to save indexes etc. - * @param idlingTime - */ - public void notifyIdle(long idlingTime); - - /** - * Called by the index manager when a project has switched indexers to this - * type of indexer - can be used by the indexer to schedule initial jobs - * @param project - the project that has changed indexers - */ - public void notifyIndexerChange(IProject project); - - /** - * Called by the index manager when a project has switched indexers to this - * type of indexer - can be used by the indexer to schedule initial jobs - * @param project - the project that has changed indexers - */ - public void notifyListeners(IndexDelta indexDelta); - - /** - * Returns if this indexer is enabled - * @param project - * @return - */ - public boolean isIndexEnabled(IProject project); - - /** - * Returns the storage used by this indexer. - * @return - */ - public IIndexStorage getIndexStorage(); - - /** - * Returns the index for the given path. - * - * @param path - * @param reuseExistingFile - * @param createIfMissing - * @return - */ - public IIndex getIndex(IPath path, boolean reuseExistingFile, boolean createIfMissing); - - /** - * Called by the index manager when this indexer is about to be removed from a project. - * @param project - */ - public void indexerRemoved(IProject project); - - /** - * Don't ask. - * - * @param index - * @return - */ - public ReadWriteMonitor getMonitorFor(IIndex index); - - /** - * Don't tell. - * - * @param index - */ - public void saveIndex(IIndex index) throws IOException; - - /** - * Associate a project with indexer - * - * @param project - */ - public void setIndexerProject(IProject project); - -} diff --git a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/core/index/IIndexChangeListener.java b/core/org.eclipse.cdt.core/index/org/eclipse/cdt/core/index/IIndexChangeListener.java deleted file mode 100644 index 4ebb94b5e59..00000000000 --- a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/core/index/IIndexChangeListener.java +++ /dev/null @@ -1,19 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ - -package org.eclipse.cdt.core.index; - -public interface IIndexChangeListener { - /** - * @param event the change event - */ - public void indexChanged(IndexChangeEvent event); -} diff --git a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/core/index/IIndexDelta.java b/core/org.eclipse.cdt.core/index/org/eclipse/cdt/core/index/IIndexDelta.java deleted file mode 100644 index 7500b82e94e..00000000000 --- a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/core/index/IIndexDelta.java +++ /dev/null @@ -1,46 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ - -package org.eclipse.cdt.core.index; - -import java.util.List; - -import org.eclipse.core.resources.IProject; - -public interface IIndexDelta { - - public class IndexDeltaType { - - private IndexDeltaType( int value ) - { - this.value = value; - } - private final int value; - } - - public static final IndexDeltaType MERGE_DELTA = new IndexDeltaType( 0 ); - - public static final IndexDeltaType INDEX_FINISHED_DELTA = new IndexDeltaType( 1 ); - - /** - * @return Returns the files. - */ - public List getFiles(); - /** - * @return Returns the project. - */ - public IProject getProject(); - /** - * @return Returns the delta type. - */ - public IndexDeltaType getDeltaType(); - -} diff --git a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/core/index/IIndexStorage.java b/core/org.eclipse.cdt.core/index/org/eclipse/cdt/core/index/IIndexStorage.java deleted file mode 100644 index 1697a33bac9..00000000000 --- a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/core/index/IIndexStorage.java +++ /dev/null @@ -1,30 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.core.index; - -/** - * @author Bogdan Gheorghe - * - * IIndexStorage must be implemented by all indexStorage providers - */ -public interface IIndexStorage { - - //Indexer that use this indexer storage - public ICDTIndexer[] getIndexers(); - - //Get path variables that are used - public String[] getPathVariables(); - public void resolvePathVariables(); - - //Merge functionality for the storage - public void merge(); - public boolean canMergeWith(IIndexStorage storage); -} diff --git a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/core/index/IndexChangeEvent.java b/core/org.eclipse.cdt.core/index/org/eclipse/cdt/core/index/IndexChangeEvent.java deleted file mode 100644 index 0d812fa0f82..00000000000 --- a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/core/index/IndexChangeEvent.java +++ /dev/null @@ -1,33 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ - -package org.eclipse.cdt.core.index; - -import java.util.EventObject; - -public class IndexChangeEvent extends EventObject { - - /** - * @param source - */ - public IndexChangeEvent(IIndexDelta delta) { - super(delta); - } - - /** - * Returns the delta describing the change. - * - */ - public IIndexDelta getDelta() { - return (IIndexDelta) source; - } - -} diff --git a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/core/index/Indexer.java b/core/org.eclipse.cdt.core/index/org/eclipse/cdt/core/index/Indexer.java deleted file mode 100644 index d88a8ce1385..00000000000 --- a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/core/index/Indexer.java +++ /dev/null @@ -1,70 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2003, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -/* - * Created on May 28, 2004 - * - * TODO To change the template for this generated file go to - * Window - Preferences - Java - Code Style - Code Templates - */ -package org.eclipse.cdt.core.index; - -import org.eclipse.cdt.core.CCorePlugin; -import org.eclipse.cdt.internal.core.index.nullindexer.NullIndexer; -import org.eclipse.cdt.internal.core.search.indexing.IndexManager; -import org.eclipse.core.resources.IProject; - -/** - * @author bgheorgh - * - * TODO To change the template for this generated type comment go to - * Window - Preferences - Java - Code Style - Code Templates - */ -public class Indexer { - private static Indexer indexer = null; - private static IndexManager manager= CCorePlugin.getDefault().getCoreModel().getIndexManager(); - - public static boolean indexEnabledOnAllProjects(){ - IProject[] projects= CCorePlugin.getWorkspace().getRoot().getProjects(); - boolean allEnabled = true; - for (int i=0; iIIndexer indexes ONE document at each time. It adds the document names and - * the words references to an IIndex. Each IIndexer can index certain types of document, and should - * not index the other files. - */ -public interface IIndexerRunner { - /** - * Indexes the given file, adding the file name and the word references - * to this document to the given IIndex.The caller should use - * shouldIndex() first to determine whether this indexer handles - * the given type of file, and only call this method if so. - */ - - void index(IFile document, IIndexerOutput output) throws java.io.IOException; - - /** - * Returns whether the IIndexer can index the given IFile or not. - */ - - public boolean shouldIndex(IFile file); -} diff --git a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/INamedEntry.java b/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/INamedEntry.java deleted file mode 100644 index ca0b58b6eef..00000000000 --- a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/INamedEntry.java +++ /dev/null @@ -1,23 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.cdt.internal.core.index; - -public interface INamedEntry extends IIndexEntry, ICIndexStorageEntry { - /** - * @return Returns the fully qualified name of this entry - */ - public char[][] getFullName(); - /** - * @return Returns the modifier bit field - */ - public int getModifiers(); -} diff --git a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/IQueryResult.java b/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/IQueryResult.java deleted file mode 100644 index a70ce3c9b0a..00000000000 --- a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/IQueryResult.java +++ /dev/null @@ -1,16 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2003 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.core.index; - -public interface IQueryResult { - String getPath(); - int getFileID(); -} diff --git a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/ITypeEntry.java b/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/ITypeEntry.java deleted file mode 100644 index 1501eee520f..00000000000 --- a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/ITypeEntry.java +++ /dev/null @@ -1,50 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.cdt.internal.core.index; - -/** - * Interface used to encode type entries for the CIndexStorgage format - * Type entry constants are defined in IIndex. The list of types are: - * - * TYPE_CLASS - * TYPE_STRUCT - * TYPE_UNION - * TYPE_ENUM - * TYPE_VAR - * TYPE_TYPEDEF - * TYPE_DERIVED - * TYPE_FRIEND - * TYPE_FWD_CLASS - * TYPE_FWD_STRUCT - * TYPE_FWD_UNION - * - * @author bgheorgh - * @since 3.0 - */ -public interface ITypeEntry extends INamedEntry { - - /** - * Returns the kind of this type entry - * @return int representing type kind defined in IIndex. - */ - public int getTypeKind(); - /** - * Returns the types that are inherited - * @return an array of index entries - each representing a separate type that this entry inherits from - */ - public IIndexEntry[] getBaseTypes(); - /** - * Return friend types - * @return an array of index entries - each representing a friend to this type - */ - public IIndexEntry[] getFriends(); -} diff --git a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/IndexRequest.java b/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/IndexRequest.java deleted file mode 100644 index 5afafd11ca9..00000000000 --- a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/IndexRequest.java +++ /dev/null @@ -1,37 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.core.index; - -import org.eclipse.cdt.internal.core.index.cindexstorage.CIndexStorage; -import org.eclipse.cdt.internal.core.search.processing.IIndexJob; -import org.eclipse.core.runtime.IPath; - -public abstract class IndexRequest implements IIndexJob { - - protected boolean isCancelled = false; - protected IPath indexPath = null; - - public IndexRequest(IPath indexPath) { - this.indexPath = indexPath; - } - - public boolean belongsTo(String projectName) { - return projectName.equals(this.indexPath.segment(0)); - } - - protected Integer updatedIndexState() { - return CIndexStorage.UPDATING_STATE; - } - - public IPath getIndexPath(){ - return indexPath; - } -} diff --git a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/NamedEntry.java b/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/NamedEntry.java deleted file mode 100644 index e647f7e375a..00000000000 --- a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/NamedEntry.java +++ /dev/null @@ -1,49 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.cdt.internal.core.index; - -public class NamedEntry extends CIndexStorageEntry implements INamedEntry { - - char[][] fullName; - int modifiers; - - public NamedEntry(int meta_kind, int entry_type, char[][] fullName, int modifiers, int fileNumber){ - super(meta_kind, entry_type, fileNumber); - this.fullName = fullName; - this.modifiers = modifiers; - } - - public NamedEntry(int meta_kind, int entry_type, String simpleName, int modifiers, int fileNumber){ - super(meta_kind, entry_type, fileNumber); - this.fullName = new char[][]{simpleName.toCharArray()}; - this.modifiers = modifiers; - } - public char[][] getFullName(){ - return fullName; - } - - public int getModifiers(){ - return modifiers; - } - - public void serialize(IIndexerOutput output) { - output.addIndexEntry(this); - } - - /* BugZilla ID#124618 */ - public void setNamedEntry(int meta_kind, int entry_type, char[][] fullName, int modifiers, int fileNumber) { - this.entry_type = entry_type; - this.fileNumber = fileNumber; - this.fullName = fullName; - this.modifiers = modifiers; - } -} diff --git a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/StringMatcher.java b/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/StringMatcher.java deleted file mode 100644 index 8a2ce2b2da3..00000000000 --- a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/StringMatcher.java +++ /dev/null @@ -1,395 +0,0 @@ -package org.eclipse.cdt.internal.core.index; - -/******************************************************************************* - * Copyright (c) 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM - Initial API and implementation - *******************************************************************************/ -import java.util.Vector; - -public class StringMatcher { - protected String fPattern; - protected int fLength; // pattern length - protected boolean fIgnoreWildCards; - protected boolean fIgnoreCase; - protected boolean fHasLeadingStar; - protected boolean fHasTrailingStar; - protected String fSegments[]; //the given pattern is split into * separated segments - - /* boundary value beyond which we don't need to search in the text */ - protected int fBound= 0; - - protected static final char fSingleWildCard= '\u0000'; - - public static class Position { - int start; //inclusive - int end; //exclusive - public Position(int start, int end) { - this.start= start; - this.end= end; - } - public int getStart() { - return start; - } - public int getEnd() { - return end; - } - } - - /** - * Find the first occurrence of the pattern between startend(exclusive). - * @param text, the String object to search in - * @param start, the starting index of the search range, inclusive - * @param end, the ending index of the search range, exclusive - * @return an StringMatcher.Position object that keeps the starting - * (inclusive) and ending positions (exclusive) of the first occurrence of the - * pattern in the specified range of the text; return null if not found or subtext - * is empty (start==end). A pair of zeros is returned if pattern is empty string - * Note that for pattern like "*abc*" with leading and trailing stars, position of "abc" - * is returned. For a pattern like"*??*" in text "abcdf", (1,3) is returned - */ - - public StringMatcher.Position find(String text, int start, int end) { - if (fPattern == null || text == null) - throw new IllegalArgumentException(); - - int tlen= text.length(); - if (start < 0) - start= 0; - if (end > tlen) - end= tlen; - if (end < 0 || start >= end) - return null; - if (fLength == 0) - return new Position(start, start); - if (fIgnoreWildCards) { - int x= posIn(text, start, end); - if (x < 0) - return null; - return new Position(x, x + fLength); - } - - int segCount= fSegments.length; - if (segCount == 0) //pattern contains only '*'(s) - return new Position(start, end); - - int curPos= start; - int matchStart= -1; - for (int i= 0; i < segCount && curPos < end; ++i) { - String current= fSegments[i]; - int nextMatch= regExpPosIn(text, curPos, end, current); - if (nextMatch < 0) - return null; - if (i == 0) - matchStart= nextMatch; - curPos= nextMatch + current.length(); - } - return new Position(matchStart, curPos); - } - /** - * StringMatcher constructor takes in a String object that is a simple - * pattern which may contain *  for 0 and many characters and - * ?  for exactly one character. Also takes as parameter a boolean object - * specifying if case should be ignored - * @deprecated Use StringMatcher(pattern, ignoreCase, ignoreWildCards). - */ - public StringMatcher(String aPattern, boolean ignoreCase) { - this(aPattern, ignoreCase, false); - } - /** - * StringMatcher constructor takes in a String object that is a simple - * pattern which may contain *  for 0 and many characters and - * ?  for exactly one character. - * - * Literal '*' and '?' characters must be escaped in the pattern - * e.g., "\*" means literal "*", etc. - * - * Escaping any other character (including the escape character itself), - * just results in that character in the pattern. - * e.g., "\a" means "a" and "\\" means "\" - * - * If invoking the StringMatcher with string literals in Java, don't forget - * escape characters are represented by "\\". - * - * @param aPattern the pattern to match text against - * @param ignoreCase if true, case is ignored - * @param ignoreWildCards if true, wild cards and their escape sequences are ignored - * (everything is taken literally). - */ - public StringMatcher(String aPattern, boolean ignoreCase, boolean ignoreWildCards) { - fIgnoreCase= ignoreCase; - fIgnoreWildCards= ignoreWildCards; - fLength= aPattern.length(); - - /* convert case */ - if (fIgnoreCase) { - fPattern= aPattern.toUpperCase(); - } else { - fPattern= aPattern; - } - - if (fIgnoreWildCards) { - parseNoWildCards(); - } else { - parseWildCards(); - } - } - /** - * Given the starting (inclusive) and the ending (exclusive) poisitions in the - * text, determine if the given substring matches with aPattern - * @return true if the specified portion of the text matches the pattern - * @param String text, a String object that contains the substring to match - * @param int start marks the starting position (inclusive) of the substring - * @param int end marks the ending index (exclusive) of the substring - */ - public boolean match(String text, int start, int end) { - if (null == fPattern || null == text) - throw new IllegalArgumentException(); - - if (start > end) - return false; - - if (fIgnoreWildCards) - return fPattern.regionMatches(fIgnoreCase, 0, text, start, fLength); - int segCount= fSegments.length; - if (segCount == 0) //pattern contains only '*'(s) or empty pattern - return true; - if (start == end) - return fLength == 0; - if (fLength == 0) - return start == end; - - int tlen= text.length(); - if (start < 0) - start= 0; - if (end > tlen) - end= tlen; - - int tCurPos= start; - int bound= end - fBound; - if (bound < 0) - return false; - int i= 0; - String current= fSegments[i]; - int segLength= current.length(); - - /* process first segment */ - if (!fHasLeadingStar) { - if (!regExpRegionMatches(text, start, current, 0, segLength)) { - return false; - } else { - ++i; - tCurPos= tCurPos + segLength; - } - } - - /* process middle segments */ - for (; i < segCount && tCurPos <= bound; ++i) { - current= fSegments[i]; - int currentMatch; - int k= current.indexOf(fSingleWildCard); - if (k < 0) { - currentMatch= textPosIn(text, tCurPos, end, current); - if (currentMatch < 0) - return false; - } else { - currentMatch= regExpPosIn(text, tCurPos, end, current); - if (currentMatch < 0) - return false; - } - tCurPos= currentMatch + current.length(); - } - - /* process final segment */ - if (!fHasTrailingStar && tCurPos != end) { - int clen= current.length(); - return regExpRegionMatches(text, end - clen, current, 0, clen); - } - return i == segCount; - } - /** - * match the given text with the pattern - * @return true if matched eitherwise false - * @param text, a String object - */ - public boolean match(String text) { - return match(text, 0, text.length()); - } - /** - * This method parses the given pattern into segments seperated by wildcard '*' characters. - * Since wildcards are not being used in this case, the pattern consists of a single segment. - */ - private void parseNoWildCards() { - fSegments= new String[1]; - fSegments[0]= fPattern; - fBound= fLength; - } - /** - * This method parses the given pattern into segments seperated by wildcard '*' characters. - * @param p, a String object that is a simple regular expression with *  and/or ?  - */ - private void parseWildCards() { - if (fPattern.startsWith("*")) //$NON-NLS-1$ - fHasLeadingStar= true; - if (fPattern.endsWith("*")) { //$NON-NLS-1$ - /* make sure it's not an escaped wildcard */ - if (fLength > 1 && fPattern.charAt(fLength - 2) != '\\') { - fHasTrailingStar= true; - } - } - - Vector temp= new Vector(); - - int pos= 0; - StringBuffer buf= new StringBuffer(); - while (pos < fLength) { - char c= fPattern.charAt(pos++); - switch (c) { - case '\\' : - if (pos >= fLength) { - buf.append(c); - } else { - char next= fPattern.charAt(pos++); - /* if it's an escape sequence */ - if (next == '*' || next == '?' || next == '\\') { - buf.append(next); - } else { - /* not an escape sequence, just insert literally */ - buf.append(c); - buf.append(next); - } - } - break; - case '*' : - if (buf.length() > 0) { - /* new segment */ - temp.addElement(buf.toString()); - fBound += buf.length(); - buf.setLength(0); - } - break; - case '?' : - /* append special character representing single match wildcard */ - buf.append(fSingleWildCard); - break; - default : - buf.append(c); - } - } - - /* add last buffer to segment list */ - if (buf.length() > 0) { - temp.addElement(buf.toString()); - fBound += buf.length(); - } - - fSegments= new String[temp.size()]; - temp.copyInto(fSegments); - } - /** - * @param text, a string which contains no wildcard - * @param start, the starting index in the text for search, inclusive - * @param end, the stopping point of search, exclusive - * @return the starting index in the text of the pattern , or -1 if not found - */ - protected int posIn(String text, int start, int end) { //no wild card in pattern - int max= end - fLength; - - if (!fIgnoreCase) { - int i= text.indexOf(fPattern, start); - if (i == -1 || i > max) - return -1; - return i; - } - - for (int i= start; i <= max; ++i) { - if (text.regionMatches(true, i, fPattern, 0, fLength)) - return i; - } - - return -1; - } - /** - * @param text, a simple regular expression that may only contain '?'(s) - * @param start, the starting index in the text for search, inclusive - * @param end, the stopping point of search, exclusive - * @param p, a simple regular expression that may contains '?' - * @param caseIgnored, wether the pattern is not casesensitive - * @return the starting index in the text of the pattern , or -1 if not found - */ - protected int regExpPosIn(String text, int start, int end, String p) { - int plen= p.length(); - - int max= end - plen; - for (int i= start; i <= max; ++i) { - if (regExpRegionMatches(text, i, p, 0, plen)) - return i; - } - return -1; - } - /** - * - * @return boolean - * @param text, a String to match - * @param start, int that indicates the starting index of match, inclusive - * @param end int that indicates the ending index of match, exclusive - * @param p, String, String, a simple regular expression that may contain '?' - * @param ignoreCase, boolean indicating wether code>p is case sensitive - */ - protected boolean regExpRegionMatches(String text, int tStart, String p, int pStart, int plen) { - while (plen-- > 0) { - char tchar= text.charAt(tStart++); - char pchar= p.charAt(pStart++); - - /* process wild cards */ - if (!fIgnoreWildCards) { - /* skip single wild cards */ - if (pchar == fSingleWildCard) { - continue; - } - } - if (pchar == tchar) - continue; - if (fIgnoreCase) { - char tc= Character.toUpperCase(tchar); - if (tc == pchar) - continue; - } - return false; - } - return true; - } - /** - * @param text, the string to match - * @param start, the starting index in the text for search, inclusive - * @param end, the stopping point of search, exclusive - * @param code>p, a string that has no wildcard - * @param ignoreCase, boolean indicating wether code>p is case sensitive - * @return the starting index in the text of the pattern , or -1 if not found - */ - protected int textPosIn(String text, int start, int end, String p) { - - int plen= p.length(); - int max= end - plen; - - if (!fIgnoreCase) { - int i= text.indexOf(p, start); - if (i == -1 || i > max) - return -1; - return i; - } - - for (int i= 0; i <= max; ++i) { - if (text.regionMatches(true, i, p, 0, plen)) - return i; - } - - return -1; - } -} diff --git a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/TypeEntry.java b/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/TypeEntry.java deleted file mode 100644 index 047692a6b81..00000000000 --- a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/TypeEntry.java +++ /dev/null @@ -1,62 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.cdt.internal.core.index; - - -public class TypeEntry extends NamedEntry implements ITypeEntry { - - int type_kind; - IIndexEntry[] baseTypes; - IIndexEntry[] friends; - - public TypeEntry(int type_kind, int entry_type, char[][] fullName, int modifiers, int fileNumber){ - super(IIndex.TYPE, entry_type, fullName, modifiers, fileNumber); - this.type_kind = type_kind; - } - - public void serialize(IIndexerOutput output) { - output.addIndexEntry(this); - } - - public int getTypeKind() { - return type_kind; - } - - public void setBaseTypes(IIndexEntry[] baseTypes) { - this.baseTypes=baseTypes; - } - - public IIndexEntry[] getBaseTypes() { - return baseTypes; - } - - public IIndexEntry[] getFriends() { - return friends; - } - - public void setFriends(IIndexEntry[] friends) { - this.friends = friends; - } - - /* BugZilla ID#124618 */ - public void setTypeEntry(int type_kind, int entry_type, char[][] fullName, int modifiers, int fileNumber) { - this.entry_type = entry_type; - this.fileNumber = fileNumber; - this.fullName = fullName; - this.modifiers = modifiers; - this.type_kind = type_kind; - // since we reuse TypeEntry instance, - // the following vars should be cleared. - this.baseTypes = null; - this.friends = null; - } -} diff --git a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/cindexstorage/CIndexStorage.java b/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/cindexstorage/CIndexStorage.java deleted file mode 100644 index 2e9ff7ac71c..00000000000 --- a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/cindexstorage/CIndexStorage.java +++ /dev/null @@ -1,502 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.core.index.cindexstorage; - -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.util.zip.CRC32; - -import org.eclipse.cdt.core.CCorePlugin; -import org.eclipse.cdt.core.index.ICDTIndexer; -import org.eclipse.cdt.core.index.IIndexStorage; -import org.eclipse.cdt.internal.core.CharOperation; -import org.eclipse.cdt.internal.core.index.IIndex; -import org.eclipse.cdt.internal.core.index.IndexRequest; -import org.eclipse.cdt.internal.core.index.domsourceindexer.DOMIndexRequest; -import org.eclipse.cdt.internal.core.search.CWorkspaceScope; -import org.eclipse.cdt.internal.core.search.IndexSelector; -import org.eclipse.cdt.internal.core.search.SimpleLookupTable; -import org.eclipse.cdt.internal.core.search.indexing.IndexManager; -import org.eclipse.cdt.internal.core.search.indexing.ReadWriteMonitor; -import org.eclipse.cdt.internal.core.search.processing.IIndexJob; -import org.eclipse.cdt.internal.core.search.processing.JobManager; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IWorkspace; -import org.eclipse.core.resources.ResourcesPlugin; -import org.eclipse.core.runtime.IPath; - -/** - * @author Bogdan Gheorghe - */ -public class CIndexStorage implements IIndexStorage { - - /* number of file contents in memory */ - public static int MAX_FILES_IN_MEMORY = 0; - - public IWorkspace workspace; - public SimpleLookupTable indexNames = new SimpleLookupTable(); - - /* index */ - private IIndex index; - /* read write monitor */ - private ReadWriteMonitor monitor; - - /* need to save ? */ - private boolean needToSave = false; - private static final CRC32 checksumCalculator = new CRC32(); - private IPath cCorePluginLocation = null; - - /* can only replace a current state if its less than the new one */ - private SimpleLookupTable indexStates = null; - private File savedIndexNamesFile = - new File(getCCorePluginWorkingLocation().append("savedIndexNames.txt").toOSString()); //$NON-NLS-1$ - - private SimpleLookupTable encounteredHeaders = null; - - public static Integer SAVED_STATE = new Integer(0); - public static Integer UPDATING_STATE = new Integer(1); - public static Integer UNKNOWN_STATE = new Integer(2); - public static Integer REBUILDING_STATE = new Integer(3); - - public static boolean VERBOSE = false; - - private ICDTIndexer indexer = null; - private IndexManager indexManager = null; - - public ReadWriteMonitor indexAccessMonitor = null; - - public CIndexStorage(ICDTIndexer indexer){ - this.indexer = indexer; - this.indexManager = CCorePlugin.getDefault().getCoreModel().getIndexManager(); - } - - public void aboutToUpdateIndex(IPath path, Integer newIndexState) { - // newIndexState is either UPDATING_STATE or REBUILDING_STATE - // must tag the index as inconsistent, in case we exit before the update job is started - String indexName = computeIndexName(path); - Object state = getIndexStates().get(indexName); - Integer currentIndexState = state == null ? UNKNOWN_STATE : (Integer) state; - if (currentIndexState.equals(REBUILDING_STATE)) return; // already rebuilding the index - - int compare = newIndexState.compareTo(currentIndexState); - if (compare > 0) { - // so UPDATING_STATE replaces SAVED_STATE and REBUILDING_STATE replaces everything - updateIndexState(indexName, newIndexState); - } else if (compare < 0 && index == null) { - // if already cached index then there is nothing more to do - rebuildIndex(indexName, path); - } - } - - String computeIndexName(IPath path) { - String name = (String) indexNames.get(path); - if (name == null) { - String pathString = path.toOSString(); - checksumCalculator.reset(); - checksumCalculator.update(pathString.getBytes()); - String fileName = Long.toString(checksumCalculator.getValue()) + ".index"; //$NON-NLS-1$ - if (IndexManager.VERBOSE) - JobManager.verbose("-> index name for " + pathString + " is " + fileName); //$NON-NLS-1$ //$NON-NLS-2$ - name = getCCorePluginWorkingLocation().append(fileName).toOSString(); - indexNames.put(path, name); - } - return name; - } - - - /** - * Returns the index for a given project, according to the following algorithm: - * - if index is already in memory: answers this one back - * - if (reuseExistingFile) then read it and return this index and record it in memory - * - if (createIfMissing) then create a new empty index and record it in memory - * - * Warning: Does not check whether index is consistent (not being used) - */ - public synchronized IIndex getIndex(IPath path, boolean reuseExistingFile, boolean createIfMissing) { - // Path is already canonical per construction - if (index == null) { - String indexName = computeIndexName(path); - Object state = getIndexStates().get(indexName); - Integer currentIndexState = state == null ? UNKNOWN_STATE : (Integer) state; - if (currentIndexState == UNKNOWN_STATE) { - // should only be reachable for query jobs - rebuildIndex(indexName, path); - return null; - } - - // index isn't cached, consider reusing an existing index file - if (reuseExistingFile) { - File indexFile = new File(indexName); - if (indexFile.exists()) { // check before creating index so as to avoid creating a new empty index if file is missing - try { - index = new Index(indexName, "Index for " + path.toOSString(), true /*reuse index file*/, indexer); //$NON-NLS-1$ - monitor= new ReadWriteMonitor(); - return index; - } catch (IOException e) { - // failed to read the existing file or its no longer compatible - if (currentIndexState != REBUILDING_STATE) { // rebuild index if existing file is corrupt, unless the index is already being rebuilt - if (IndexManager.VERBOSE) - JobManager.verbose("-> cannot reuse existing index: "+indexName+" path: "+path.toOSString()); //$NON-NLS-1$ //$NON-NLS-2$ - rebuildIndex(indexName, path); - return null; - } - index = null; // will fall thru to createIfMissing & create a empty index for the rebuild all job to populate - } - } - if (currentIndexState == SAVED_STATE) { // rebuild index if existing file is missing - rebuildIndex(indexName, path); - return null; - } - } - // index wasn't found on disk, consider creating an empty new one - if (createIfMissing) { - try { - if (VERBOSE) - JobManager.verbose("-> create empty index: "+indexName+" path: "+path.toOSString()); //$NON-NLS-1$ //$NON-NLS-2$ - index = new Index(indexName, "Index for " + path.toOSString(), false /*do not reuse index file*/, indexer); //$NON-NLS-1$ - monitor=new ReadWriteMonitor(); - return index; - } catch (IOException e) { - if (VERBOSE) - JobManager.verbose("-> unable to create empty index: "+indexName+" path: "+path.toOSString()); //$NON-NLS-1$ //$NON-NLS-2$ - // The file could not be created. Possible reason: the project has been deleted. - return null; - } - } - } - //System.out.println(" index name: " + path.toOSString() + " <----> " + index.getIndexFile().getName()); - return index; - } - - private SimpleLookupTable getIndexStates() { - if (indexStates != null) return indexStates; - - this.indexStates = new SimpleLookupTable(); - char[] savedIndexNames = readIndexState(); - if (savedIndexNames.length > 0) { - char[][] names = CharOperation.splitOn('\n', savedIndexNames); - for (int i = 0, l = names.length; i < l; i++) { - char[] name = names[i]; - if (name.length > 0) - this.indexStates.put(new String(name), SAVED_STATE); - } - } - return this.indexStates; - } - - public SimpleLookupTable getEncounteredHeaders(){ - - if (encounteredHeaders == null){ - this.encounteredHeaders = new SimpleLookupTable(); - } - - - return this.encounteredHeaders; - } - - /** - * Resets the headers table - */ - public void resetEncounteredHeaders() { - this.encounteredHeaders = null; - } - - private IPath getCCorePluginWorkingLocation() { - if (this.cCorePluginLocation != null) return this.cCorePluginLocation; - - return this.cCorePluginLocation = CCorePlugin.getDefault().getStateLocation(); - } - /** - * Index access is controlled through a read-write monitor so as - * to ensure there is no concurrent read and write operations - * (only concurrent reading is allowed). - */ - public ReadWriteMonitor getMonitorForIndex(){ - return monitor; - } - private void rebuildIndex(String indexName, IPath path) { - Object target = org.eclipse.cdt.internal.core.Util.getTarget(ResourcesPlugin.getWorkspace().getRoot(), path, true); - if (target == null) return; - - if (IndexManager.VERBOSE) - JobManager.verbose("-> request to rebuild index: "+indexName+" path: "+path.toOSString()); //$NON-NLS-1$ //$NON-NLS-2$ - - updateIndexState(indexName, REBUILDING_STATE); - DOMIndexRequest request = null; - if (target instanceof IProject) { - IProject p = (IProject) target; - if( p.exists() && indexer.isIndexEnabled( p ) ) - //request = new IndexAllProject(p, indexer); - indexer.addRequest(p, null, ICDTIndexer.PROJECT); - } - - if (request != null) - indexManager.request(request); - } - - /** - * Recreates the index for a given path, keeping the same read-write monitor. - * Returns the new empty index or null if it didn't exist before. - * Warning: Does not check whether index is consistent (not being used) - */ - public synchronized IIndex recreateIndex(IPath path) { - // only called to over write an existing cached index... - try { - // Path is already canonical - String indexPath = computeIndexName(path); - if (IndexManager.VERBOSE) - JobManager.verbose("-> recreating index: "+indexPath+" for path: "+path.toOSString()); //$NON-NLS-1$ //$NON-NLS-2$ - index = new Index(indexPath, "Index for " + path.toOSString(), false /*reuse index file*/,indexer); //$NON-NLS-1$ - //Monitor can be left alone - no need to recreate - return index; - } catch (IOException e) { - // The file could not be created. Possible reason: the project has been deleted. - if (IndexManager.VERBOSE) { - JobManager.verbose("-> failed to recreate index for path: "+path.toOSString()); //$NON-NLS-1$ //$NON-NLS-2$ - e.printStackTrace(); - } - return null; - } - } - - /** - * Removes the index for a given path. - * This is a no-op if the index did not exist. - */ - public synchronized void removeIndex(IPath path) { - if (IndexManager.VERBOSE) - JobManager.verbose("removing index " + path); //$NON-NLS-1$ - String indexName = computeIndexName(path); - File indexFile = new File(indexName); - if (indexFile.exists()) - indexFile.delete(); - index=null; - monitor=null; - updateIndexState(indexName, null); - } - - /** - * Removes all indexes whose paths start with (or are equal to) the given path. - */ - public synchronized void removeIndexFamily(IPath path) { - // only finds cached index files... shutdown removes all non-cached index files - this.removeIndex(path); - } - - public void saveIndex(IIndex index) throws IOException { - // must have permission to write from the write monitor - if (index.hasChanged()) { - if (IndexManager.VERBOSE) - JobManager.verbose("-> saving index " + index.getIndexFile()); //$NON-NLS-1$ - index.save(); - } - String indexName = index.getIndexFile().getPath(); - if (indexManager.getJobEnd() > indexManager.getJobStart()) { - Object indexPath = indexNames.keyForValue(indexName); - if (indexPath != null) { - for (int i = indexManager.getJobEnd(); i > indexManager.getJobStart(); i--) { // skip the current job - IIndexJob job = indexManager.getAwaitingJobAt(i); - if (job instanceof DOMIndexRequest) - if (((IndexRequest) job).getIndexPath().equals(indexPath)) return; - } - } - } - updateIndexState(indexName, SAVED_STATE); - } - - /** - * Commit all index memory changes to disk - */ - public void saveIndexes() { - // only save cached indexes... the rest were not modified - ReadWriteMonitor monitor = getMonitorForIndex(); - if (monitor == null) return; // index got deleted since acquired - try { - monitor.enterWrite(); - try { - saveIndex(index); - } catch(IOException e){ - if (IndexManager.VERBOSE) { - JobManager.verbose("-> got the following exception while saving:"); //$NON-NLS-1$ - e.printStackTrace(); - } - //Util.log(e); - } - } finally { - monitor.exitWrite(); - } - needToSave = false; - } - - - public void shutdown() { - if (IndexManager.VERBOSE) - JobManager.verbose("Shutdown"); //$NON-NLS-1$ - //Get index entries for all projects in the workspace, store their absolute paths - IndexSelector indexSelector = new IndexSelector(new CWorkspaceScope(), null, false, indexManager); - IIndex[] selectedIndexes = indexSelector.getIndexes(); - SimpleLookupTable knownPaths = new SimpleLookupTable(); - for (int i = 0, max = selectedIndexes.length; i < max; i++) { - String path = selectedIndexes[i].getIndexFile().getAbsolutePath(); - knownPaths.put(path, path); - } - //Any index entries that are in the index state must have a corresponding - //path entry - if not they are removed from the saved indexes file - if (indexStates != null) { - Object[] indexNames = indexStates.keyTable; - for (int i = 0, l = indexNames.length; i < l; i++) { - String key = (String) indexNames[i]; - if (key != null && !knownPaths.containsKey(key)) //here is an index that is in t - updateIndexState(key, null); - } - } - - //Clean up the .metadata folder - if there are any files in the directory that - //are not associated to an index we delete them - File indexesDirectory = new File(getCCorePluginWorkingLocation().toOSString()); - if (indexesDirectory.isDirectory()) { - File[] indexesFiles = indexesDirectory.listFiles(); - if (indexesFiles != null) { - for (int i = 0, indexesFilesLength = indexesFiles.length; i < indexesFilesLength; i++) { - String fileName = indexesFiles[i].getAbsolutePath(); - if (!knownPaths.containsKey(fileName) && fileName.toLowerCase().endsWith(".index")) { //$NON-NLS-1$ - if (IndexManager.VERBOSE) - JobManager.verbose("Deleting index file " + indexesFiles[i]); //$NON-NLS-1$ - indexesFiles[i].delete(); - } - } - } - } - - - } - - - - public String toString() { - StringBuffer buffer = new StringBuffer(10); - buffer.append(super.toString()); - buffer.append("In-memory indexes:\n"); //$NON-NLS-1$ - int count = 0; - buffer.append(++count).append(" - ").append(index.toString()).append('\n'); //$NON-NLS-1$ - return buffer.toString(); - } - - private char[] readIndexState() { - try { - return org.eclipse.cdt.internal.core.Util.getFileCharContent(savedIndexNamesFile, null); - } catch (IOException ignored) { - if (IndexManager.VERBOSE) - JobManager.verbose("Failed to read saved index file names"); //$NON-NLS-1$ - return new char[0]; - } - } - - private void updateIndexState(String indexName, Integer indexState) { - getIndexStates(); // ensure the states are initialized - if (indexState != null) { - if (indexState.equals(indexStates.get(indexName))) return; // not changed - indexStates.put(indexName, indexState); - } else { - if (!indexStates.containsKey(indexName)) return; // did not exist anyway - indexStates.removeKey(indexName); - } - - BufferedWriter writer = null; - try { - writer = new BufferedWriter(new FileWriter(savedIndexNamesFile)); - Object[] indexNames = indexStates.keyTable; - Object[] states = indexStates.valueTable; - for (int i = 0, l = states.length; i < l; i++) { - if (states[i] == SAVED_STATE) { - writer.write((String) indexNames[i]); - writer.write('\n'); - } - } - } catch (IOException ignored) { - if (IndexManager.VERBOSE) - JobManager.verbose("Failed to write saved index file names"); //$NON-NLS-1$ - } finally { - if (writer != null) { - try { - writer.close(); - } catch (IOException e) {} - } - } - if (IndexManager.VERBOSE) { - String state = "?"; //$NON-NLS-1$ - if (indexState == SAVED_STATE) state = "SAVED"; //$NON-NLS-1$ - else if (indexState == UPDATING_STATE) state = "UPDATING"; //$NON-NLS-1$ - else if (indexState == UNKNOWN_STATE) state = "UNKNOWN"; //$NON-NLS-1$ - else if (indexState == REBUILDING_STATE) state = "REBUILDING"; //$NON-NLS-1$ - JobManager.verbose("-> index state updated to: " + state + " for: "+indexName); //$NON-NLS-1$ //$NON-NLS-2$ - } - } - - /* (non-Javadoc) - * @see org.eclipse.cdt.core.index2.IIndexStorage#getIndexers() - */ - public ICDTIndexer[] getIndexers() { - // TODO Auto-generated method stub - return null; - } - - /* (non-Javadoc) - * @see org.eclipse.cdt.core.index2.IIndexStorage#getPathVariables() - */ - public String[] getPathVariables() { - // TODO Auto-generated method stub - return null; - } - - /* (non-Javadoc) - * @see org.eclipse.cdt.core.index2.IIndexStorage#resolvePathVariables() - */ - public void resolvePathVariables() { - // TODO Auto-generated method stub - - } - - /* (non-Javadoc) - * @see org.eclipse.cdt.core.index2.IIndexStorage#merge() - */ - public void merge() { - // TODO Auto-generated method stub - - } - - /* (non-Javadoc) - * @see org.eclipse.cdt.core.index2.IIndexStorage#canMergeWith(org.eclipse.cdt.core.index2.IIndexStorage) - */ - public boolean canMergeWith(IIndexStorage storage) { - // TODO Auto-generated method stub - return false; - } - - - public boolean getNeedToSave() { - return needToSave; - } - public void setNeedToSave(boolean needToSave) { - this.needToSave = needToSave; - } - - public void jobWasCancelled(IPath path) { - index=null; - monitor=null; - updateIndexState(computeIndexName(path), UNKNOWN_STATE); - } - public ReadWriteMonitor getIndexAccessMonitor() { - return indexAccessMonitor; - } -} diff --git a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/cindexstorage/EntryResult.java b/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/cindexstorage/EntryResult.java deleted file mode 100644 index 14c77790507..00000000000 --- a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/cindexstorage/EntryResult.java +++ /dev/null @@ -1,238 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.core.index.cindexstorage; - -import org.eclipse.cdt.internal.core.CharOperation; -import org.eclipse.cdt.internal.core.index.IEntryResult; -import org.eclipse.cdt.internal.core.index.IIndex; -import org.eclipse.cdt.internal.core.search.indexing.IndexManager; -import org.eclipse.cdt.internal.core.search.processing.JobManager; - - -public class EntryResult implements IEntryResult { - private int[] fileRefs; - private int[][] offsets; - private int[][] offsetLengths; - - private int meta_type; - private int kind; - private int reftype; - private String longname; - -public EntryResult(char[] word, int[] refs, int[][] offsets, int[][] offsetLengths) { - this.fileRefs = refs; - this.offsets = offsets; - this.offsetLengths = offsetLengths; - decode(word); -} -public boolean equals(Object anObject){ - - if (this == anObject) { - return true; - } - if ((anObject != null) && (anObject instanceof EntryResult)) { - EntryResult anEntryResult = (EntryResult) anObject; - if( this.meta_type != anEntryResult.meta_type || - this.kind != anEntryResult.kind || - this.reftype != anEntryResult.reftype || - ! this.longname.equals(anEntryResult.longname)) - return false; - - int length; - int[] refs, otherRefs; - if ((length = (refs = this.fileRefs).length) != (otherRefs = anEntryResult.fileRefs).length) return false; - for (int i = 0; i < length; i++){ - if (refs[i] != otherRefs[i]) return false; - } - return true; - } - return false; - -} -public int[] getFileReferences() { - return fileRefs; -} -public char[] getWord() { - return Index.encodeEntry(meta_type, kind, reftype, longname); -} -public int hashCode(){ - return CharOperation.hashCode(getWord()); -} -public String toString(){ - StringBuffer buffer = new StringBuffer(); - buffer.append("EntryResult: " + getName() + "\n\tmeta="); //$NON-NLS-1$ //$NON-NLS-2$ - buffer.append(ICIndexStorageConstants.encodings[meta_type]); - if(meta_type == IIndex.TYPE) { - buffer.append(" type="); //$NON-NLS-1$ - buffer.append(ICIndexStorageConstants.typeConstantNames[kind]); - } - buffer.append(" Reference="); //$NON-NLS-1$ - buffer.append(ICIndexStorageConstants.encodingTypes[reftype]); - - buffer.append(", refs={"); //$NON-NLS-1$ - for (int i = 0; i < fileRefs.length; i++){ - if (i > 0) buffer.append(','); - buffer.append(' '); - buffer.append(fileRefs[i]); - } - buffer.append(" }, offsets={"); //$NON-NLS-1$ - for (int i = 0; i < offsets.length; i++){ - if (i > 0) buffer.append(','); - buffer.append(' '); - buffer.append('['); - for (int j=0; j 0) buffer.append(','); - buffer.append(' '); - buffer.append(offsets[i][j]); - } - buffer.append(']'); - } - buffer.append(" }\n"); //$NON-NLS-1$ - return buffer.toString(); -} -/* (non-Javadoc) - * @see org.eclipse.cdt.internal.core.index.IEntryResult#getOffsets() - */ -public int[][] getOffsets() { - return offsets; -} -/* (non-Javadoc) - * @see org.eclipse.cdt.internal.core.index.IEntryResult#getOffsetLengths() - */ -public int[][] getOffsetLengths() { - return offsetLengths; -} -/* (non-Javadoc) - * @see org.eclipse.cdt.internal.core.index.IEntryResult#extractSimpleName() - */ -public String extractSimpleName() { - int sepPos=longname.indexOf(IndexerOutput.SEPARATOR); - if (sepPos>=0) - return longname.substring(0, sepPos); - else - return longname; -} - -private void decode(char [] word) { - int pos = 0; - meta_type = 0; - for (int i = 1; i < ICIndexStorageConstants.encodings.length; i ++){ - if (CharOperation.prefixEquals(ICIndexStorageConstants.encodings[i], word)) { - meta_type = i; - pos += ICIndexStorageConstants.encodings[i].length; - break; - } - } - - for ( int i = 1; i < ICIndexStorageConstants.encodingTypes.length; i++) { - if (CharOperation.fragmentEquals(ICIndexStorageConstants.encodingTypes[i], word, pos, true)) { - reftype = i; - pos += ICIndexStorageConstants.encodingTypes[i].length; - break; - } - } - - if (meta_type == IIndex.TYPE) { - for (int i = 1; i < Index.typeConstants.length; i++) { - if (word[pos] == Index.typeConstants[i]) { - kind = i; - pos++; - break; - } - } - // skip over separator - if (word[pos] != ICIndexStorageConstants.SEPARATOR) { - if (IndexManager.VERBOSE) - JobManager.verbose("Invalid encoding encoutered while decoding Entry Result"); //$NON-NLS-1$ - } - pos++; - } - else - kind = IIndex.ANY; - - longname = new String(word, pos, word.length - pos); -} - -public String[] getEnclosingNames() { - int slash=longname.indexOf(IndexerOutput.SEPARATOR); - - String[] enclosingNames= null; - if (slash != -1 && slash + 1 < longname.length()) { - char[][] temp = CharOperation.splitOn('/', CharOperation.subarray(longname.toCharArray(), slash + 1, -1)); - enclosingNames= new String[temp.length]; - for (int i = 0; i < temp.length; i++) { - enclosingNames[i] = String.valueOf(temp[temp.length - i - 1]); - } - } - return enclosingNames; -} -public int getMetaKind() { - return meta_type; -} -public int getKind() { - return kind; -} -public int getRefKind() { - return reftype; -} -public String getName() { - return longname; -} -public String getStringMetaKind() { - return String.valueOf(ICIndexStorageConstants.encodings[meta_type]); -} -public String getStringKind() { - return ICIndexStorageConstants.typeConstantNames[kind]; -} -public String getStringRefKind() { - return String.valueOf(ICIndexStorageConstants.encodingTypes[reftype]); -} - -public String getDisplayString() { - switch (meta_type) { - case IIndex.FUNCTION: - case IIndex.METHOD: - int startReturn = longname.indexOf(")R/"); //$NON-NLS-1$ - int finishReturn = longname.indexOf("/R("); //$NON-NLS-1$ - int startParam = longname.indexOf("/)", finishReturn); //$NON-NLS-1$ - int finishParam = longname.indexOf("/(", startParam); //$NON-NLS-1$ - - String functionName; - String arguments = ""; //$NON-NLS-1$ - if (startParam + 2 < finishParam) - arguments = longname.substring(startParam + 3, finishParam); - - // TODO: flip arguments - arguments = arguments.replace('/',','); - - arguments = '(' + arguments + ')'; - - if (startReturn == -1 || finishReturn == -1) { - // there is no return type !!! - functionName = longname.substring(0, startParam -1); - return functionName + arguments ; - } - else { - String returnType = ""; //$NON-NLS-1$ - if (startReturn + 3 < finishReturn) { - returnType = longname.substring(startReturn + 3, finishReturn); - } - functionName = longname.substring(0, startReturn -1); - return functionName + arguments + ':' + returnType; - } - - default: - return longname; - } -} - -} - diff --git a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/cindexstorage/ICIndexStorageConstants.java b/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/cindexstorage/ICIndexStorageConstants.java deleted file mode 100644 index 9d4180c1063..00000000000 --- a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/cindexstorage/ICIndexStorageConstants.java +++ /dev/null @@ -1,88 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ - -package org.eclipse.cdt.internal.core.index.cindexstorage; - - -public interface ICIndexStorageConstants { - /** - * The signature of the index file. - */ - - public static final String SIGNATURE= "INDEX FILE 0.017"; //$NON-NLS-1$ - - /** - * The size of a block for a Block. - */ - public static final int BLOCK_SIZE= 8192; - - final public static char SEPARATOR= '/'; - - final static char [][] encodings = { - "".toCharArray(), // not used //$NON-NLS-1$ - "type".toCharArray(), // TYPES //$NON-NLS-1$ - "function".toCharArray(), // FUNCTIONS //$NON-NLS-1$ - "method".toCharArray(), // METHODS //$NON-NLS-1$ - "field".toCharArray(), // FIELDS //$NON-NLS-1$ - "macro".toCharArray(), // MACROS //$NON-NLS-1$ - "namespace".toCharArray(), // NAMESPACES //$NON-NLS-1$ - "enumtor".toCharArray(), // ENUMERATORS //$NON-NLS-1$ - "include" .toCharArray(), // INCLUDES //$NON-NLS-1$ - "variable" .toCharArray() // VARIABLE //$NON-NLS-1$ - }; - - final static char [][] encodingTypes = { - "".toCharArray(), // not used //$NON-NLS-1$ - "Decl/".toCharArray(), // DECLARATIONS //$NON-NLS-1$ - "Ref/".toCharArray(), // REFERENCES //$NON-NLS-1$ - "Defn/".toCharArray() // DEFINTIONS //$NON-NLS-1$ - }; - - final static char[] typeConstants = { ' ', // not used - 'C', // CLASS - 'S', // STRUCT - 'U', // UNION - 'E', // ENUM - 'T', // TYPEDEF - 'D', // DERIVED - 'F' // FRIEND - }; - - final static String[] typeConstantNames = { "", // not used //$NON-NLS-1$ - "Class", //$NON-NLS-1$ - "Struct", //$NON-NLS-1$ - "Union", //$NON-NLS-1$ - "Enum", //$NON-NLS-1$ - "Typedef", //$NON-NLS-1$ - "Derived", //$NON-NLS-1$ - "Friend", //$NON-NLS-1$ -}; - - final static String[] allSpecifiers = {"", //not used //$NON-NLS-1$ - "private", // private //$NON-NLS-1$ - "public", // public //$NON-NLS-1$ - "protected", // protected //$NON-NLS-1$ - "const", // const //$NON-NLS-1$ - "volatile", // volatile //$NON-NLS-1$ - "static", // static //$NON-NLS-1$ - "extern", // extern //$NON-NLS-1$ - "inline", // inline //$NON-NLS-1$ - "virtual", // virtual //$NON-NLS-1$ - "pure virtual", // pure virtual //$NON-NLS-1$ - "explicit", // explicit //$NON-NLS-1$ - "auto", // auto //$NON-NLS-1$ - "register", // register //$NON-NLS-1$ - "mutable" // mutable //$NON-NLS-1$ - }; - - - -} diff --git a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/cindexstorage/InMemoryIndex.java b/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/cindexstorage/InMemoryIndex.java deleted file mode 100644 index a151452ba07..00000000000 --- a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/cindexstorage/InMemoryIndex.java +++ /dev/null @@ -1,297 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.core.index.cindexstorage; - -import java.io.File; -import java.io.IOException; - -import org.eclipse.cdt.internal.core.index.cindexstorage.io.BlocksIndexOutput; -import org.eclipse.cdt.internal.core.index.cindexstorage.io.IndexOutput; - - -/** - * This index stores the document names in an ObjectVector, and the words in - * an HashtableOfObjects. - */ - -public class InMemoryIndex { - - /** - * hashtable of IncludeEntrys = includeFiles+numbers of the files they appear in. - */ - protected IncludeEntryHashedArray includes; - /** - * Array of WordEntry - */ - protected WordEntryHashedArray words; - /** - * Array of IndexedFileEntry - */ - protected IndexedFileEntryHashedArray files; - /** - * Array of IndexedPathVariableEntry = file name + a unique number. - */ - protected IndexPathVariableEntryHashedArray pathVars; - /** - * Size of the index. - */ - protected long footprint; - - private IncludeEntry[] sortedIncludeEntries; - private WordEntry[] sortedWordEntries; - private IndexedFileEntry[] sortedFiles; - private IndexPathVariableEntry[] sortedPathVars; - private int lastId; - - public InMemoryIndex() { - init(); - } - - public IndexedFileEntry addFile(String path){ - IndexedFileEntry indexedFileEntry = this.files.add(path); - this.footprint += indexedFileEntry.footprint() + 4; - this.sortedFiles = null; - return indexedFileEntry; - } - - public void addIncludeRef(IndexedFileEntry indexedFile, char[] include) { - addIncludeRef(include, indexedFile.getFileID()); - } - - public void addIncludeRef(IndexedFileEntry indexedFile, String include) { - addIncludeRef(include.toCharArray(), indexedFile.getFileID()); - } - - /** - * Adds the references of the include to the tree (reference = number of the file the include belongs to). - */ - protected void addIncludeRef(char[] include, int[] references) { - int size= references.length; - int i= 0; - while (i < size) { - if (references[i] != 0) - addIncludeRef(include, references[i]); - i++; - } - } - /** - * Looks if the include already exists to the tree and adds the fileNum to this include. - * If the include does not exist, it adds it to the tree. - */ - protected void addIncludeRef(char[] include, int fileNum) { - IncludeEntry entry= this.includes.get(include); - if (entry == null) { - entry= new IncludeEntry(include, ++lastId); - entry.addRef(fileNum); - this.includes.add(entry); - this.sortedIncludeEntries= null; - this.footprint += entry.footprint(); - } else { - this.footprint += entry.addRef(fileNum); - } - } - /** - * Looks if the word already exists in the index and add the fileNum to this word. - * If the word does not exist, it adds it in the index. - * @param indexFlags - */ - protected void addRef(char[] word, int fileNum, int offset, int offsetLength, int offsetType, int modifiers) { - WordEntry entry= this.words.get(word); - - if (entry == null) { - entry= new WordEntry(word); - entry.addRef(fileNum); - entry.addOffset(offset, offsetLength, fileNum, offsetType); - entry.addModifiers(modifiers, fileNum); - this.words.add(entry); - this.sortedWordEntries= null; - this.footprint += entry.footprint(); - } else { - this.footprint += entry.addRef(fileNum); - entry.addOffset(offset, offsetLength, fileNum, offsetType); - entry.addModifiers(modifiers, fileNum); - } - } - - public void addRef(IndexedFileEntry indexedFile, char[] word, int offset, int offsetLength, int offsetType, int modifiers) { - addRef(word, indexedFile.getFileID(), offset, offsetLength, offsetType, modifiers); - } - - public void addRef(IndexedFileEntry indexedFile, String word, int offset, int offsetLength, int offsetType, int modifiers) { - addRef(word.toCharArray(), indexedFile.getFileID(), offset, offsetLength, offsetType, modifiers); - } - - public void addRelatives(int fileNumber, String inclusion, String parent) { - addRelatives(fileNumber,inclusion.toCharArray(),(parent != null ) ? parent.toCharArray() : null); - } - - protected void addRelatives(int fileNumber, char[] inclusion, char[] parent) { - IncludeEntry childEntry=null; - IncludeEntry parentEntry=null; - - if (inclusion != null) - childEntry= this.includes.get(inclusion); - - if (parent != null) - parentEntry= this.includes.get(parent); - - - childEntry.addParent(fileNumber,(parentEntry!=null) ? parentEntry.getID() : -1); - - if (parent!=null) - parentEntry.addChild(fileNumber,(childEntry!=null) ? childEntry.getID() : -1); - } - /** - * Returns the footprint of the index. - */ - public long getFootprint() { - return this.footprint; - } - /** - * Returns the indexed files contained in the hashtable of includes. - */ - public IndexedFileEntry[] getIndexedFiles(){ - return this.files.asArray(); - } - /** - * Returns the indexed file with the given path, or null if such file does not exist. - */ - public IndexedFileEntry getIndexedFile(String path) { - return files.get(path); - } - /** - * Returns the include entries contained in the hashtable of includes. - */ - public IncludeEntry[] getIncludeEntries() { - return this.includes.asArray(); - } - /** - * Returns the include entry corresponding to the given include. - */ - protected IncludeEntry getIncludeEntry(char[] include) { - return includes.get(include); - } - - public int getNumFiles() { - return files.size(); - } - - public int getNumWords() { - return words.elementSize; - } - - public int getNumIncludes() { - return includes.elementSize; - } - - /** - * Returns the words contained in the hashtable of words, sorted by alphabetical order. - */ - public IndexedFileEntry[] getSortedFiles() { - if (this.sortedFiles == null) { - IndexedFileEntry[] indexedFiles= files.asArray(); - Util.sort(indexedFiles); - this.sortedFiles= indexedFiles; - } - return this.sortedFiles; - } - /** - * Returns the word entries contained in the hashtable of words, sorted by alphabetical order. - */ - public WordEntry[] getSortedWordEntries() { - if (this.sortedWordEntries == null) { - WordEntry[] words= this.words.asArray(); - Util.sort(words); - this.sortedWordEntries= words; - } - return this.sortedWordEntries; - } - /** - * Returns the include entries contained in the hashtable of includeas, sorted by alphabetical order. - */ - public IncludeEntry[] getSortedIncludeEntries() { - if (this.sortedIncludeEntries == null) { - IncludeEntry[] includes= this.includes.asArray(); - Util.sort(includes); - this.sortedIncludeEntries= includes; - } - return this.sortedIncludeEntries; - } - /** - * Returns the word entry corresponding to the given word. - */ - public WordEntry getWordEntry(char[] word) { - return words.get(word); - } - /** - * Initialises the fields of the index - */ - public void init() { - includes= new IncludeEntryHashedArray(501); - words= new WordEntryHashedArray(501); - files= new IndexedFileEntryHashedArray(101); - pathVars= new IndexPathVariableEntryHashedArray(101); - footprint= 0; - lastId=0; - sortedWordEntries= null; - sortedFiles= null; - sortedIncludeEntries=null; - } - /** - * Saves the index in the given file. - * Structure of the saved Index : - * - IndexedFiles in sorted order. - * + example: - * "c:/com/a.cpp 1" - * "c:/com/b.cpp 2" - * - References with the words in sorted order - * + example: - * "classDecl/a 1" - * "classDecl/b 2" - * "ref/String 1 2" - */ - public void save(File file) throws IOException { - BlocksIndexOutput output= new BlocksIndexOutput(file); - save(output); - } - /** - * Saves the index in the given IndexOutput. - * Structure of the saved Index : - * - IndexedFiles in sorted order. - * + example: - * "c:/com/a.cpp 1" - * "c:/com/b.cpp 2" - * - References with the words in sorted order - * + example: - * "classDecl/a 1" - * "classDecl/b 2" - * "ref/String 1 2" - */ - protected void save(IndexOutput output) throws IOException { - boolean ok= false; - try { - output.open(); - IndexedFileEntry[] indexedFiles= files.asArray(); - for (int i= 0, length = indexedFiles.length; i < length; ++i) - output.addFile(indexedFiles[i]); // written out in order BUT not alphabetical - getSortedWordEntries(); // init the slot - for (int i= 0, numWords= sortedWordEntries.length; i < numWords; ++i) - output.addWord(sortedWordEntries[i]); - output.flush(); - output.close(); - ok= true; - } finally { - if (!ok && output != null) - output.close(); - } - } -} - diff --git a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/cindexstorage/IncludeEntry.java b/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/cindexstorage/IncludeEntry.java deleted file mode 100644 index 706a4e618ca..00000000000 --- a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/cindexstorage/IncludeEntry.java +++ /dev/null @@ -1,240 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ - -package org.eclipse.cdt.internal.core.index.cindexstorage; - -import java.util.ArrayList; -import java.util.Iterator; - -import org.eclipse.cdt.internal.core.CharOperation; -import org.eclipse.cdt.internal.core.sourcedependency.Node; - -/** - * @author bgheorgh - */ -public class IncludeEntry { - - protected char[] fFile; - protected int fId; - protected int fNumRefs; - protected int[] fRefs; - //TODO: BOG Consider making these arrays... - protected ArrayList fParent; - protected ArrayList fChild; - protected int fNumParent; - protected int fNumChild; - - public IncludeEntry(int id) { - this(CharOperation.NO_CHAR,id); - } - - public IncludeEntry(char[] file, int id) { - fFile = file; - fNumRefs= 0; - fRefs= new int[1]; - fId=id; - - fParent = new ArrayList(5); - fChild = new ArrayList(5); - fNumParent = 0; - fNumChild = 0; - } - /** - * Adds a reference and records the change in footprint. - */ - public int addRef(int fileNum) { - if (fNumRefs > 0 && fRefs[fNumRefs - 1] == fileNum) { - return 0; - } - if (fNumRefs < fRefs.length) { - fRefs[fNumRefs++]= fileNum; - return 0; - } - - int newSize= fNumRefs < 4 ? 4 : fNumRefs * 2; // so will start @ 1, grow to 4, 8, 16, 32, 64 etc. - System.arraycopy(fRefs, 0, fRefs= new int[newSize], 0, fNumRefs); - fRefs[fNumRefs++]= fileNum; - return (newSize - fNumRefs + 1) * 4; - } - - public void addParent(int fileRef, int parentId){ - Node newParent = new Node(fileRef,parentId); - fParent.add(newParent); - fNumParent++; - } - /** - * @param is - */ - public void addRefs(int[] refs) { - int[] newRefs= new int[fNumRefs + refs.length]; - int pos1= 0; - int pos2= 0; - int posNew= 0; - int compare; - int r1= 0; - int r2= 0; - while (pos1 < fNumRefs || pos2 < refs.length) { - if (pos1 >= fNumRefs) { - r2= refs[pos2]; - compare= -1; - } else if (pos2 >= refs.length) { - compare= 1; - r1= fRefs[pos1]; - } else { - r1= fRefs[pos1]; - r2= refs[pos2]; - compare= r2 - r1; - } - if (compare > 0) { - newRefs[posNew]= r1; - posNew++; - pos1++; - } else { - if (r2 != 0) { - newRefs[posNew]= r2; - posNew++; - } - pos2++; - } - } - fRefs= newRefs; - fNumRefs= posNew; - /*for (int i = 0; i < refs.length; i++) - addRef(refs[i]); - int[] newRefs = new int[fNumRefs]; - System.arraycopy(fRefs, 0, newRefs, 0, fNumRefs); - fRefs = newRefs; - Util.sort(fRefs);*/ - - } - - public void addChild(int fileRef, int parentId){ - Node newChild = new Node(fileRef,parentId); - fChild.add(newChild); - fNumChild++; - } - /** - * Returns the number of references, e.g. the number of files this word appears in. - */ - public int getNumRefs() { - return fNumRefs; - } - /** - * returns the file number in the i position in the list of references. - */ - public int getRef(int i) { - if (i < fNumRefs) return fRefs[i]; - throw new IndexOutOfBoundsException(); - } - /** - * Returns the references of the includeEntry (the number of the files it appears in). - */ - public int[] getRefs() { - int[] result= new int[fNumRefs]; - System.arraycopy(fRefs, 0, result, 0, fNumRefs); - return result; - } - /** - * returns the word of the includeEntry. - */ - public char[] getFile() { - return fFile; - } - /** - * Changes the references of the wordEntry to match the mapping. For example,
    - * if the current references are [1 3 4]
    - * and mapping is [1 2 3 4 5]
    - * in references 1 becomes mapping[1] = 2, 3->4, and 4->5
    - * => references = [2 4 5].
    - */ - public void mapRefs(int[] mappings) { - int position= 0; - - for (int i= 0; i < fNumRefs; i++) { - //Take care that the reference is actually within the bounds of the mapping - int map= -1; - if(fRefs[i] >= 0 && fRefs[i] < mappings.length) - map= mappings[fRefs[i]]; - if (map != -1 && map != 0) - fRefs[position++]= map; - } - fNumRefs= position; - - //to be changed! - System.arraycopy(fRefs, 0, (fRefs= new int[fNumRefs]), 0, fNumRefs); - Util.sort(fRefs); - } - /** - * Clears the includeEntry. - */ - public void reset(char[] word) { - for (int i= fNumRefs; i-- > 0;) { - fRefs[i]= 0; - } - fNumRefs= 0; - fFile= word; - } - - public int getID(){ - return fId; - } - - public String toString() { - StringBuffer tempBuffer = new StringBuffer(); - tempBuffer.append(" 0) tempBuffer.append(','); - tempBuffer.append(' '); - tempBuffer.append(fRefs[i]); - } - tempBuffer.append("}, Parents:{"); //$NON-NLS-1$ - Iterator x = fParent.iterator(); - while (x.hasNext()) - { - Node tempNode = (Node) x.next(); - tempBuffer.append(tempNode.toString()); - if (x.hasNext()) { - tempBuffer.append(','); - tempBuffer.append(' '); - } - } - tempBuffer.append("}, Children:{"); //$NON-NLS-1$ - Iterator y = fChild.iterator(); - while (y.hasNext()) - { - Node tempNode = (Node) y.next(); - tempBuffer.append(tempNode.toString()); - if (y.hasNext()) { - tempBuffer.append(','); - tempBuffer.append(' '); - } - } - tempBuffer.append("} >"); //$NON-NLS-1$ - return tempBuffer.toString(); - } - - /** - * @return - */ - public long footprint() { - //Size of Object + (number of fields * size of Fields) + - //(Size of ArrayListObject + (Number of Nodes * sizeof Node)) + (Size of ArrayObject + (Number of fFile * sizeof char)) + - //(Size of ArrayListObject + (Number of Nodes * sizeof Node)) + - //(Size of ArrayObject + (Number of refs * sizeof int)) - return 8 + (8 * 4) + - (8 + fChild.size() * (8 + 2 * 4)) + (8 + fFile.length * 2) + - (8 + fParent.size() * (8 + 2 * 4)) + (8 + fRefs.length * 4); - } -} diff --git a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/cindexstorage/IncludeEntryHashedArray.java b/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/cindexstorage/IncludeEntryHashedArray.java deleted file mode 100644 index 923830ab779..00000000000 --- a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/cindexstorage/IncludeEntryHashedArray.java +++ /dev/null @@ -1,84 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ - -package org.eclipse.cdt.internal.core.index.cindexstorage; - -import org.eclipse.cdt.internal.core.CharOperation; - -public final class IncludeEntryHashedArray { - - public IncludeEntry elements[]; - public int elementSize; // number of elements in the table - public int threshold; - - public IncludeEntryHashedArray(int size) { - if (size < 7) size = 7; - this.elements = new IncludeEntry[2 * size + 1]; - this.elementSize = 0; - this.threshold = size + 1; // size is the expected number of elements - } - - public IncludeEntry add(IncludeEntry entry) { - int length = elements.length; - char[] word = entry.getFile(); - int index = CharOperation.hashCode(word) % length; - IncludeEntry current; - while ((current = elements[index]) != null) { - if (CharOperation.equals(current.getFile(), word)) return elements[index] = entry; - if (++index == length) index = 0; - } - elements[index] = entry; - - // assumes the threshold is never equal to the size of the table - if (++elementSize > threshold) grow(); - return entry; - } - - public IncludeEntry[] asArray() { - IncludeEntry[] array = new IncludeEntry[elementSize]; - for (int i = 0, j = 0, length = elements.length; i < length; i++) { - IncludeEntry current = elements[i]; - if (current != null) array[j++] = current; - } - return array; - } - - public IncludeEntry get(char[] word) { - int length = elements.length; - int index = CharOperation.hashCode(word) % length; - IncludeEntry current; - while ((current = elements[index]) != null) { - if (CharOperation.equals(current.getFile(), word)) return current; - if (++index == length) index = 0; - } - return null; - } - - private void grow() { - IncludeEntryHashedArray newArray = new IncludeEntryHashedArray(elementSize * 2); // double the number of expected elements - for (int i = 0, length = elements.length; i < length; i++) - if (elements[i] != null) - newArray.add(elements[i]); - - this.elements = newArray.elements; - this.elementSize = newArray.elementSize; - this.threshold = newArray.threshold; - } - - public String toString() { - String s = ""; //$NON-NLS-1$ - IncludeEntry[] entries = asArray(); - for (int i = 0, length = entries.length; i < length; i++) - s += entries[i].toString() + "\n"; //$NON-NLS-1$ - return s; - } - -} diff --git a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/cindexstorage/Index.java b/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/cindexstorage/Index.java deleted file mode 100644 index c12d58eb09d..00000000000 --- a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/cindexstorage/Index.java +++ /dev/null @@ -1,825 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.core.index.cindexstorage; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.eclipse.cdt.core.CCorePlugin; -import org.eclipse.cdt.core.index.ICDTIndexer; -import org.eclipse.cdt.core.index.IIndexDelta; -import org.eclipse.cdt.core.search.ICSearchConstants; -import org.eclipse.cdt.core.search.LimitTo; -import org.eclipse.cdt.core.search.SearchFor; -import org.eclipse.cdt.internal.core.CharOperation; -import org.eclipse.cdt.internal.core.index.IEntryResult; -import org.eclipse.cdt.internal.core.index.IIndex; -import org.eclipse.cdt.internal.core.index.IIndexerRunner; -import org.eclipse.cdt.internal.core.index.IQueryResult; -import org.eclipse.cdt.internal.core.index.cindexstorage.io.BlocksIndexInput; -import org.eclipse.cdt.internal.core.index.cindexstorage.io.BlocksIndexOutput; -import org.eclipse.cdt.internal.core.index.cindexstorage.io.IndexInput; -import org.eclipse.cdt.internal.core.index.cindexstorage.io.IndexOutput; -import org.eclipse.cdt.internal.core.index.cindexstorage.io.MergeFactory; -import org.eclipse.cdt.internal.core.index.cindexstorage.io.SimpleIndexInput; -import org.eclipse.cdt.internal.core.index.impl.IndexDelta; -import org.eclipse.cdt.internal.core.index.impl.Int; -import org.eclipse.core.resources.IFile; -import org.eclipse.core.runtime.IPath; - -/** - * An Index is used to create an index on the disk, and to make queries. It uses a set of - * indexers and a mergeFactory. The index fills an inMemoryIndex up - * to it reaches a certain size, and then merges it with a main index on the disk. - *

    - * The changes are only taken into account by the queries after a merge. - */ - -public class Index implements IIndex, ICIndexStorageConstants, ICSearchConstants { - /** - * Maximum size of the index in memory. - */ - public static final int MAX_FOOTPRINT= 10000000; - - /** - * Index in memory, who is merged with mainIndex each times it - * reaches a certain size. - */ - protected InMemoryIndex addsIndex; - protected IndexInput addsIndexInput; - - /** - * State of the indexGenerator: addsIndex empty <=> MERGED, or - * addsIndex not empty <=> CAN_MERGE - */ - protected int state; - - /** - * Files removed form the addsIndex. - */ - protected Map removedInAdds; - - /** - * Files removed form the oldIndex. - */ - protected Map removedInOld; - protected static final int CAN_MERGE= 0; - protected static final int MERGED= 1; - private File indexFile; - - private ICDTIndexer indexer = null; - - - /** - * String representation of this index. - */ - public String toString; - - public Index(String indexName, String toString, boolean reuseExistingFile, ICDTIndexer indexer) throws IOException { - super(); - state= MERGED; - indexFile= new File(indexName); - this.toString = toString; - this.indexer = indexer; - initialize(reuseExistingFile); - } - /** - * Indexes the given document, using the appropriate indexer registered in the indexerRegistry. - * If the document already exists in the index, it overrides the previous one. The changes will be - * taken into account after a merge. - */ - public void add(IFile file, IIndexerRunner indexer) throws IOException { - if (timeToMerge()) { - merge(); - } - IndexedFileEntry indexedFile= addsIndex.getIndexedFile(file.getFullPath().toString()); - if (indexedFile != null /*&& removedInAdds.get(document.getName()) == null*/ - ) - remove(indexedFile, MergeFactory.ADDS_INDEX); - IndexerOutput output= new IndexerOutput(addsIndex); - indexer.index(file, output); - state= CAN_MERGE; - } - /** - * Returns true if the index in memory is not empty, so - * merge() can be called to fill the mainIndex with the files and words - * contained in the addsIndex. - */ - protected boolean canMerge() { - return state == CAN_MERGE; - } - /** - * Initialises the indexGenerator. - */ - public void empty() throws IOException { - - if (indexFile.exists()){ - indexFile.delete(); - //initialisation of mainIndex - InMemoryIndex mainIndex= new InMemoryIndex(); - IndexOutput mainIndexOutput= new BlocksIndexOutput(indexFile); - if (!indexFile.exists()) - mainIndex.save(mainIndexOutput); - } - - //initialisation of addsIndex - addsIndex= new InMemoryIndex(); - addsIndexInput= new SimpleIndexInput(addsIndex); - - //vectors who keep track of the removed Files - removedInAdds= new HashMap(11); - removedInOld= new HashMap(11); - } - /** - * @see IIndex#getIndexFile - */ - public File getIndexFile() { - return indexFile; - } - /** - * @see IIndex#getNumDocuments - */ - public int getNumDocuments() throws IOException { - //save(); - IndexInput input= new BlocksIndexInput(indexFile); - try { - input.open(); - return input.getNumFiles(); - } finally { - input.close(); - } - } - /** - * @see IIndex#getNumWords - */ - public int getNumWords() throws IOException { - //save(); - IndexInput input= new BlocksIndexInput(indexFile); - try { - input.open(); - return input.getNumWords(); - } finally { - input.close(); - } - } - /** - * @see IIndex#getNumWords - */ - public int getNumIncludes() throws IOException { - //save(); - IndexInput input= new BlocksIndexInput(indexFile); - try { - input.open(); - return input.getNumIncludes(); - } finally { - input.close(); - } - } - /** - * Returns the path corresponding to a given document number - */ - public String getPath(int documentNumber) throws IOException { - //save(); - IndexInput input= new BlocksIndexInput(indexFile); - try { - input.open(); - IndexedFileEntry file = input.getIndexedFile(documentNumber); - if (file == null) return null; - return file.getPath(); - } finally { - input.close(); - } - } - - /** - * Returns the path list - */ - public String [] getDocumentList() throws IOException { - IndexInput input= new BlocksIndexInput(indexFile); - try { - input.open(); - int num = input.getNumFiles(); - String [] result = new String[num+1]; - for(int i = 1; i < num+1; i++) { - //i+1 since reference encoding starts at 1 - IndexedFileEntry file = input.getIndexedFile(i); - if (file != null) - result[i] = file.getPath(); - else - result[i] = null; - } - - return result; - } finally { - input.close(); - } - } - /** - * see IIndex.hasChanged - */ - public boolean hasChanged() { - return canMerge(); - } - /** - * Initialises the indexGenerator. - */ - public void initialize(boolean reuseExistingFile) throws IOException { - //initialisation of addsIndex - addsIndex= new InMemoryIndex(); - addsIndexInput= new SimpleIndexInput(addsIndex); - - //vectors who keep track of the removed Files - removedInAdds= new HashMap(11); - removedInOld= new HashMap(11); - - // check whether existing index file can be read - if (reuseExistingFile && indexFile.exists()) { - IndexInput mainIndexInput= new BlocksIndexInput(indexFile); - try { - mainIndexInput.open(); - } catch(IOException e) { - BlocksIndexInput input = (BlocksIndexInput)mainIndexInput; - try { - input.setOpened(true); - input.close(); - } finally { - input.setOpened(false); - } - indexFile.delete(); - mainIndexInput = null; - throw e; - } - mainIndexInput.close(); - } else { - InMemoryIndex mainIndex= new InMemoryIndex(); - IndexOutput mainIndexOutput= new BlocksIndexOutput(indexFile); - mainIndex.save(mainIndexOutput); - } - } - /** - * Merges the in memory index and the index on the disk, and saves the results on the disk. - */ - protected void merge() throws IOException { - //initialisation of tempIndex - File tempFile= new File(indexFile.getAbsolutePath() + "TempVA"); //$NON-NLS-1$ - - IndexInput mainIndexInput= new BlocksIndexInput(indexFile); - BlocksIndexOutput tempIndexOutput= new BlocksIndexOutput(tempFile); - - try { - //invoke a mergeFactory - new MergeFactory( - mainIndexInput, - addsIndexInput, - tempIndexOutput, - removedInOld, - removedInAdds).merge(); - - //rename the file created to become the main index - File mainIndexFile= (File) mainIndexInput.getSource(); - File tempIndexFile= (File) tempIndexOutput.getDestination(); - boolean deleted = mainIndexFile.delete(); - - int counter=0; - while (!deleted && counter<5){ - try { - Thread.sleep(50); - } catch (InterruptedException e) {} - counter++; - deleted=mainIndexFile.delete(); - } - - tempIndexFile.renameTo(mainIndexFile); - } finally { - //initialise remove vectors and addsindex, and change the state - removedInAdds.clear(); - removedInOld.clear(); - addsIndex.init(); - addsIndexInput= new SimpleIndexInput(addsIndex); - state= MERGED; - //flush the CDT log - CCorePlugin.getDefault().cdtLog.flushLog(); - - //Send out notification to listeners; - IndexDelta indexDelta = new IndexDelta(null,null,IIndexDelta.MERGE_DELTA); - indexer.notifyListeners(indexDelta); - } - } - - public IEntryResult[] queryEntries(char[] prefix) throws IOException { - //save(); - IndexInput input= new BlocksIndexInput(indexFile); - try { - return input.queryEntriesPrefixedBy(prefix); - } finally { - input.close(); - } - } - /** - * @see IIndex#queryInDocumentNames - */ - public IQueryResult[] queryInDocumentNames(String word) throws IOException { - //save(); - IndexInput input= new BlocksIndexInput(indexFile); - try { - return input.queryInDocumentNames(word); - } finally { - input.close(); - } - } - /** - * @see IIndex#queryPrefix - */ - public IQueryResult[] queryPrefix(char[] prefix) throws IOException { - //save(); - IndexInput input= new BlocksIndexInput(indexFile); - try { - return input.queryFilesReferringToPrefix(prefix); - } finally { - input.close(); - } - } - - /* (non-Javadoc) - * @see org.eclipse.cdt.internal.core.sourcedependency.IDependencyTree#getFileDepencies(int) - */ - public String[] getFileDependencies(IPath filePath) throws IOException { -// List tempFileReturn = new ArrayList(); -// -// IndexedFile indexFile = addsIndex.getIndexedFile(filePath.toString()); -// -// if (indexFile == null) -// return new String[0]; -// -// int fileNum = indexFile.getFileNumber(); -// IncludeEntry[] tempEntries = addsIndex.getIncludeEntries(); -// for (int i=0; i= MAX_FOOTPRINT); - } - public String toString() { - String str = this.toString; - if (str == null) - str = super.toString(); - str += "(length: " + getIndexFile().length() + ")"; //$NON-NLS-1$ //$NON-NLS-2$ - return str; - } - - public org.eclipse.cdt.core.index.ICDTIndexer getIndexer(){ - return (org.eclipse.cdt.core.index.ICDTIndexer) indexer; - } - public IEntryResult[] queryEntries(char[] prefix, char optionalType, char[] name, char[][] containingTypes, int matchMode, boolean isCaseSensitive) throws IOException { - return queryEntries(Index.bestPrefix(prefix, optionalType, name, containingTypes, matchMode, isCaseSensitive)); - } - - public static final char[] bestTypePrefix( SearchFor searchFor, LimitTo limitTo, char[] typeName, char[][] containingTypes, int matchMode, boolean isCaseSensitive) { - char [] prefix = null; - if( limitTo == DECLARATIONS ){ - prefix = encodeEntry(IIndex.TYPE, ANY, DECLARATION); - } else if (limitTo == DEFINITIONS){ - prefix = encodeEntry(IIndex.TYPE, ANY, DEFINITION); - } else if( limitTo == REFERENCES ){ - prefix = encodeEntry(IIndex.TYPE, ANY, REFERENCE); - } else { - return encodeEntry(IIndex.TYPE, ANY, ANY); - } - - char classType = 0; - - if( searchFor == ICSearchConstants.CLASS ){ - classType = typeConstants[IIndex.TYPE_CLASS]; - } else if ( searchFor == ICSearchConstants.STRUCT ){ - classType = typeConstants[IIndex.TYPE_STRUCT]; - } else if ( searchFor == ICSearchConstants.UNION ){ - classType = typeConstants[IIndex.TYPE_UNION]; - } else if ( searchFor == ICSearchConstants.ENUM ){ - classType = typeConstants[IIndex.TYPE_ENUM]; - } else if ( searchFor == ICSearchConstants.TYPEDEF ){ - classType = typeConstants[IIndex.TYPE_TYPEDEF]; - } else if ( searchFor == ICSearchConstants.DERIVED){ - classType = typeConstants[IIndex.TYPE_DERIVED]; - } else if ( searchFor == ICSearchConstants.FRIEND){ - classType = typeConstants[IIndex.TYPE_FRIEND]; - } else { - //could be TYPE or CLASS_STRUCT, best we can do for these is the prefix - return prefix; - } - - return bestPrefix( prefix, classType, typeName, containingTypes, matchMode, isCaseSensitive ); - } - - public static final char[] bestNamespacePrefix(LimitTo limitTo, char[] namespaceName, char[][] containingTypes, int matchMode, boolean isCaseSensitive) { - char [] prefix = null; - if( limitTo == REFERENCES ){ - prefix = encodeEntry(IIndex.NAMESPACE, ANY, REFERENCE); - } else if ( limitTo == DEFINITIONS ) { - prefix = encodeEntry(IIndex.NAMESPACE, ANY, DEFINITION); - } else { - return encodeEntry(IIndex.NAMESPACE, ANY, ANY); - } - - return bestPrefix( prefix, (char) 0, namespaceName, containingTypes, matchMode, isCaseSensitive ); - } - - public static final char[] bestVariablePrefix( LimitTo limitTo, char[] varName, char[][] containingTypes, int matchMode, boolean isCaseSenstive ){ - char [] prefix = null; - if( limitTo == REFERENCES ){ - prefix = encodeEntry(IIndex.VAR, ANY, REFERENCE); - } else if( limitTo == DECLARATIONS ){ - prefix = encodeEntry(IIndex.VAR, ANY, DECLARATION); - } else if( limitTo == DEFINITIONS ){ - prefix = encodeEntry(IIndex.VAR, ANY, DEFINITION); - } else { - return encodeEntry(IIndex.VAR, ANY, ANY); - } - - return bestPrefix( prefix, (char)0, varName, containingTypes, matchMode, isCaseSenstive ); - } - - public static final char[] bestFieldPrefix( LimitTo limitTo, char[] fieldName,char[][] containingTypes, int matchMode, boolean isCaseSensitive) { - char [] prefix = null; - if( limitTo == REFERENCES ){ - prefix = encodeEntry(IIndex.FIELD, ANY, REFERENCE); - } else if( limitTo == DECLARATIONS ){ - prefix = encodeEntry(IIndex.FIELD, ANY, DECLARATION); - } else if( limitTo == DEFINITIONS ){ - prefix = encodeEntry(IIndex.FIELD, ANY, DEFINITION); - } else { - return encodeEntry(IIndex.FIELD, ANY, ANY); - } - - return bestPrefix( prefix, (char)0, fieldName, containingTypes, matchMode, isCaseSensitive ); - } - - public static final char[] bestEnumeratorPrefix( LimitTo limitTo, char[] enumeratorName,char[][] containingTypes, int matchMode, boolean isCaseSensitive) { - char [] prefix = null; - if( limitTo == REFERENCES ){ - prefix = encodeEntry(IIndex.ENUMTOR, ANY, REFERENCE); - } else if( limitTo == DECLARATIONS ){ - prefix = encodeEntry(IIndex.ENUMTOR, ANY, DECLARATION); - } else if ( limitTo == DEFINITIONS ) { - prefix = encodeEntry(IIndex.ENUMTOR, ANY, DEFINITION); - } else if (limitTo == ALL_OCCURRENCES){ - return encodeEntry(IIndex.ENUMTOR, ANY, ANY); - } - - return bestPrefix( prefix, (char)0, enumeratorName, containingTypes, matchMode, isCaseSensitive ); - } - - public static final char[] bestMethodPrefix( LimitTo limitTo, char[] methodName,char[][] containingTypes, int matchMode, boolean isCaseSensitive) { - char [] prefix = null; - if( limitTo == REFERENCES ){ - prefix = encodeEntry(IIndex.METHOD, ANY, REFERENCE); - } else if( limitTo == DECLARATIONS ){ - prefix = encodeEntry(IIndex.METHOD, ANY, DECLARATION); - } else if( limitTo == DEFINITIONS ){ - return encodeEntry(IIndex.METHOD, ANY, DEFINITION); - } else { - return encodeEntry(IIndex.METHOD, ANY, ANY); - } - - return bestPrefix( prefix, (char)0, methodName, containingTypes, matchMode, isCaseSensitive ); - } - - public static final char[] bestFunctionPrefix( LimitTo limitTo, char[] functionName, int matchMode, boolean isCaseSensitive) { - char [] prefix = null; - if( limitTo == REFERENCES ){ - prefix = encodeEntry(IIndex.FUNCTION, ANY, REFERENCE); - } else if( limitTo == DECLARATIONS ){ - prefix = encodeEntry(IIndex.FUNCTION, ANY, DECLARATION); - } else if ( limitTo == DEFINITIONS ){ - return encodeEntry(IIndex.FUNCTION, ANY, DEFINITION); - } else { - return encodeEntry(IIndex.FUNCTION, ANY, ANY); - } - return bestPrefix( prefix, (char)0, functionName, null, matchMode, isCaseSensitive ); - } - - public static final char[] bestPrefix( char [] prefix, char optionalType, char[] name, char[][] containingTypes, int matchMode, boolean isCaseSensitive) { - char[] result = null; - int pos = 0; - - int wildPos, starPos = -1, questionPos; - - //length of prefix + separator - int length = prefix.length; - - //add length for optional type + another separator - if( optionalType != 0 ) - length += 2; - - if (!isCaseSensitive){ - //index is case sensitive, thus in case attempting case insensitive search, cannot consider - //type name. - name = null; - } else if( matchMode == PATTERN_MATCH && name != null ){ - int start = 0; - - char [] temp = new char [ name.length ]; - boolean isEscaped = false; - int tmpIdx = 0; - for( int i = 0; i < name.length; i++ ){ - if( name[i] == '\\' ){ - if( !isEscaped ){ - isEscaped = true; - continue; - } - isEscaped = false; - } else if( name[i] == '*' && !isEscaped ){ - starPos = i; - break; - } - temp[ tmpIdx++ ] = name[i]; - } - - name = new char [ tmpIdx ]; - System.arraycopy( temp, 0, name, 0, tmpIdx ); - - //starPos = CharOperation.indexOf( '*', name ); - questionPos = CharOperation.indexOf( '?', name ); - - if( starPos >= 0 ){ - if( questionPos >= 0 ) - wildPos = ( starPos < questionPos ) ? starPos : questionPos; - else - wildPos = starPos; - } else { - wildPos = questionPos; - } - - switch( wildPos ){ - case -1 : break; - case 0 : name = null; break; - default : name = CharOperation.subarray( name, 0, wildPos ); break; - } - } - //add length for name - if( name != null ){ - length += name.length; - } else { - //name is null, don't even consider qualifications. - result = new char [ length ]; - System.arraycopy( prefix, 0, result, 0, pos = prefix.length ); - if( optionalType != 0){ - result[ pos++ ] = optionalType; - result[ pos++ ] = SEPARATOR; - } - return result; - } - - //add the total length of the qualifiers - //we don't want to mess with the contents of this array (treat it as constant) - //so check for wild cards later. - if( containingTypes != null ){ - for( int i = 0; i < containingTypes.length; i++ ){ - if( containingTypes[i].length > 0 ){ - length += containingTypes[ i ].length; - length++; //separator - } - } - } - - //because we haven't checked qualifier wild cards yet, this array might turn out - //to be too long. So fill a temp array, then check the length after - char [] temp = new char [ length ]; - - System.arraycopy( prefix, 0, temp, 0, pos = prefix.length ); - - if( optionalType != 0 ){ - temp[ pos++ ] = optionalType; - temp[ pos++ ] = SEPARATOR; - } - - System.arraycopy( name, 0, temp, pos, name.length ); - pos += name.length; - - if( containingTypes != null ){ - for( int i = containingTypes.length - 1; i >= 0; i-- ){ - if( matchMode == PATTERN_MATCH ){ - starPos = CharOperation.indexOf( '*', containingTypes[i] ); - questionPos = CharOperation.indexOf( '?', containingTypes[i] ); - - if( starPos >= 0 ){ - if( questionPos >= 0 ) - wildPos = ( starPos < questionPos ) ? starPos : questionPos; - else - wildPos = starPos; - } else { - wildPos = questionPos; - } - - if( wildPos >= 0 ){ - temp[ pos++ ] = SEPARATOR; - System.arraycopy( containingTypes[i], 0, temp, pos, wildPos ); - pos += starPos; - break; - } - } - - if( containingTypes[i].length > 0 ){ - temp[ pos++ ] = SEPARATOR; - System.arraycopy( containingTypes[i], 0, temp, pos, containingTypes[i].length ); - pos += containingTypes[i].length; - } - } - } - - if( pos < length ){ - result = new char[ pos ]; - System.arraycopy( temp, 0, result, 0, pos ); - } else { - result = temp; - } - - return result; - } - - /** - * @param _limitTo - * @param simpleName - * @param _matchMode - * @param _caseSensitive - * @return - */ - public static final char[] bestMacroPrefix( LimitTo limitTo, char[] macroName, int matchMode, boolean isCaseSenstive ){ - //since we only index macro declarations we already know the prefix - char [] prefix = null; - if( limitTo == DECLARATIONS ){ - prefix = Index.encodeEntry(IIndex.MACRO, IIndex.ANY, IIndex.DECLARATION); - } else { - return null; - } - - return bestPrefix( prefix, (char)0, macroName, null, matchMode, isCaseSenstive ); - } - - /** - * @param _limitTo - * @param simpleName - * @param _matchMode - * @param _caseSensitive - * @return - */ - public static final char[] bestIncludePrefix( LimitTo limitTo, char[] incName, int matchMode, boolean isCaseSenstive ){ - //since we only index macro declarations we already know the prefix - char [] prefix = null; - if( limitTo == REFERENCES ){ - prefix = encodeEntry(IIndex.INCLUDE, IIndex.ANY, IIndex.REFERENCE); - } else { - return null; - } - - return bestPrefix( prefix, (char)0, incName, null, matchMode, isCaseSenstive ); - } - - public static String getDescriptionOf (int meta_kind, int kind, int ref) { - StringBuffer buff = new StringBuffer(); - buff.append(encodings[meta_kind]); - buff.append(encodingTypes[ref]); - if(kind != 0) { - buff.append(typeConstants[kind]); - buff.append(SEPARATOR); - } - return buff.toString(); - } - public static char [] encodeEntry (int meta_kind, int kind, int ref, String name) { -// if( kind == ANY && ref == ANY ) -// return encodings[meta_kind]; - StringBuffer buff = new StringBuffer(); - buff.append(encodings[meta_kind]); - buff.append(encodingTypes[ref]); - if(kind != 0) { - buff.append(typeConstants[kind]); - buff.append( SEPARATOR ); - } - buff.append ( name ); - - return buff.toString().toCharArray(); - } - - public static char [] encodeEntry (int meta_kind, int kind, int ref) { - StringBuffer buff = new StringBuffer(); - buff.append(encodings[meta_kind]); - buff.append(encodingTypes[ref]); - if(kind != 0) - buff.append(typeConstants[kind]); - return buff.toString().toCharArray(); - } - public IEntryResult[] getEntries(int meta_kind, int kind, int ref, String name) throws IOException { - return queryEntries(encodeEntry(meta_kind, kind, ref, name)); - } - public IEntryResult[] getEntries(int meta_kind, int kind, int ref) throws IOException { - return queryEntries(encodeEntry(meta_kind, kind, ref)); - } - - public IQueryResult[] getPrefix(int meta_kind, int kind, int ref, String name) throws IOException { - return queryPrefix(encodeEntry(meta_kind, kind, ref, name)); - } - public IQueryResult[] getPrefix(int meta_kind, int kind, int ref) throws IOException { - return queryPrefix(encodeEntry(meta_kind, kind, ref)); - } - -} diff --git a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/cindexstorage/IndexEntryNotSupportedException.java b/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/cindexstorage/IndexEntryNotSupportedException.java deleted file mode 100644 index 0ad837c3340..00000000000 --- a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/cindexstorage/IndexEntryNotSupportedException.java +++ /dev/null @@ -1,21 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.core.index.cindexstorage; - -public class IndexEntryNotSupportedException extends Exception { - - public IndexEntryNotSupportedException(String string) { - super(string); - } - - private static final long serialVersionUID = 3257002138168211513L; - -} diff --git a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/cindexstorage/IndexPathVariableEntry.java b/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/cindexstorage/IndexPathVariableEntry.java deleted file mode 100644 index 542448d7d65..00000000000 --- a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/cindexstorage/IndexPathVariableEntry.java +++ /dev/null @@ -1,70 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.core.index.cindexstorage; - -/** - * @author Bogdan Gheorghe - */ -public class IndexPathVariableEntry { - //All indexes will reserve 1 in the PathVariable block to represent - //the workspace location - public static final int WORKSPACE_ID = 1; - - private String pathVariableName; - private String pathVariablePath; - private int pathVarID; - - public IndexPathVariableEntry(String pathVarName, String pathVarPath, int id){ - this.pathVariableName = pathVarName; - this.pathVariablePath = pathVarPath; - this.pathVarID = id; - } - - /** - * @return Returns the id. - */ - public int getId() { - return pathVarID; - } - /** - * @param id The id to set. - */ - public void setId(int id) { - this.pathVarID = id; - } - /** - * @return Returns the pathVariableName. - */ - public String getPathVariableName() { - return pathVariableName; - } - /** - * @return Returns the pathVariablePath. - */ - public String getPathVariablePath() { - return pathVariablePath; - } - - /** - * Returns the size of the indexedFile. - */ - public int footprint() { - //object+ 3 slots + size of the string (Object size + (4 fields in String class) - //+ 8 for char array in string + (2 for each char * number of chars in string)) + {another String} - return 8 + (3 * 4) + (8 + (4 * 4) + 8 + (pathVariableName.length() * 2)) + (8 + (4 * 4) + 8 + (pathVariablePath.length() * 2)); - } - - public String toString() { - return "IndexPathVariableEntry(" + pathVarID + ": " + pathVariableName + " + " + pathVariablePath + ")"; //$NON-NLS-2$ //$NON-NLS-1$ //$NON-NLS-3$ //$NON-NLS-4$ - } - - -} diff --git a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/cindexstorage/IndexPathVariableEntryHashedArray.java b/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/cindexstorage/IndexPathVariableEntryHashedArray.java deleted file mode 100644 index f1271341c12..00000000000 --- a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/cindexstorage/IndexPathVariableEntryHashedArray.java +++ /dev/null @@ -1,117 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.core.index.cindexstorage; - -import java.util.ArrayList; - -public final class IndexPathVariableEntryHashedArray { - -private IndexPathVariableEntry elements[]; -private int elementSize; // number of elements in the table -private int threshold; -private int lastId; -private ArrayList replacedElements; - -public IndexPathVariableEntryHashedArray(int size) { - if (size < 7) size = 7; - this.elements = new IndexPathVariableEntry[2 * size + 1]; - this.elementSize = 0; - this.threshold = size + 1; // size is the expected number of elements - this.lastId = 1; //start at 2; 1 is reserved for workspace variable - this.replacedElements = null; -} - -public IndexPathVariableEntry add(String pathVarName, String path){ - return add(new IndexPathVariableEntry(pathVarName, path, ++lastId)); -} - -/** - * Adds the IndexPathVariableEntry to the list, hashed by path - * @param pathVar - */ -private IndexPathVariableEntry add(IndexPathVariableEntry pathVar) { - int length = elements.length; - String path = pathVar.getPathVariablePath(); - int index = (path.hashCode() & 0x7FFFFFFF) % length; - IndexPathVariableEntry current; - while ((current = elements[index]) != null) { - if (current.getPathVariablePath().equals(path)) { - if (replacedElements == null) replacedElements = new ArrayList(5); - replacedElements.add(current); - return elements[index] = pathVar; - } - if (++index == length) index = 0; - } - elements[index] = pathVar; - - // assumes the threshold is never equal to the size of the table - if (++elementSize > threshold) grow(); - return pathVar; -} - -public IndexPathVariableEntry[] asArray() { - IndexPathVariableEntry[] array = new IndexPathVariableEntry[lastId]; - for (int i = 0, length = elements.length; i < length; i++) { - IndexPathVariableEntry current = elements[i]; - if (current != null) - array[current.getId() - 1] = current; - } - if (replacedElements != null) { - for (int i = 0, length = replacedElements.size(); i < length; i++) { - IndexPathVariableEntry current = (IndexPathVariableEntry) replacedElements.get(i); - array[current.getId() - 1] = current; - } - } - return array; -} - -/** - * Returns corresponing IndexPathVariableEntry for the given path or - * null if it hasn't been added to the array - * @param path - * @return - */ -public IndexPathVariableEntry get(String path) { - int length = elements.length; - int index = (path.hashCode() & 0x7FFFFFFF) % length; - IndexPathVariableEntry current; - while ((current = elements[index]) != null) { - if (current.getPathVariablePath().equals(path)) return current; - if (++index == length) index = 0; - } - return null; -} - -private void grow() { - IndexPathVariableEntryHashedArray newArray = new IndexPathVariableEntryHashedArray(elementSize * 2); // double the number of expected elements - for (int i = 0, length = elements.length; i < length; i++) - if (elements[i] != null) - newArray.add(elements[i]); - - // leave replacedElements as is - this.elements = newArray.elements; - this.elementSize = newArray.elementSize; - this.threshold = newArray.threshold; -} - -public int size() { - return elementSize + (replacedElements == null ? 0 : replacedElements.size()); -} - -public String toString() { - String s = ""; //$NON-NLS-1$ - IndexPathVariableEntry[] files = asArray(); - for (int i = 0, length = files.length; i < length; i++) - s += files[i].toString() + "\n"; //$NON-NLS-1$ - return s; -} -} - diff --git a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/cindexstorage/IndexedFileEntry.java b/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/cindexstorage/IndexedFileEntry.java deleted file mode 100644 index ee17cd4ef14..00000000000 --- a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/cindexstorage/IndexedFileEntry.java +++ /dev/null @@ -1,76 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.core.index.cindexstorage; - -import org.eclipse.cdt.internal.core.index.IQueryResult; - -/** - * @author Bogdan Gheorghe - */ -public class IndexedFileEntry implements IQueryResult { - - /** - * Path relative to the workspace root for this file - */ - private String path; - /** - * Unique file id - */ - private int fileID; - /** - * Index Path Var id - links this file entry to a corresponding entry - * in IndexPathVariableEntry. - */ - private int pathVarID; - /** - * MD5 for this file - */ - private byte[] MD5; - - public IndexedFileEntry(String path, int fileNum) { - if (fileNum < 1) - throw new IllegalArgumentException(); - this.fileID= fileNum; - this.path= path; - } - - /** - * Returns the size of the indexedFile. - */ - public int footprint() { - //object+ 4 slots + size of the string (header + 4 slots + char[]) + size of byte array - return 8 + (4 * 4) + (8 + (4 * 4) + 8 + path.length() * 2); //Put in when you put in MD5 + (8 + MD5.length); - } - /** - * Returns the file number. - */ - public int getFileID() { - return fileID; - } - /** - * Returns the path. - */ - public String getPath() { - return path; - } - /** - * Sets the file number. - */ - public void setFileNumber(int fileNumber) { - this.fileID= fileNumber; - } - public String toString() { - return "IndexedFile(" + fileID + ": " + path + ")"; //$NON-NLS-2$ //$NON-NLS-1$ //$NON-NLS-3$ - } - - - -} diff --git a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/cindexstorage/IndexedFileEntryHashedArray.java b/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/cindexstorage/IndexedFileEntryHashedArray.java deleted file mode 100644 index e5c6e45a5ef..00000000000 --- a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/cindexstorage/IndexedFileEntryHashedArray.java +++ /dev/null @@ -1,107 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.core.index.cindexstorage; - -import java.util.ArrayList; - -public final class IndexedFileEntryHashedArray { - -private IndexedFileEntry elements[]; -private int elementSize; // number of elements in the table -private int threshold; -private int lastId; -private ArrayList replacedElements; - -public IndexedFileEntryHashedArray(int size) { - if (size < 7) size = 7; - this.elements = new IndexedFileEntry[2 * size + 1]; - this.elementSize = 0; - this.threshold = size + 1; // size is the expected number of elements - this.lastId = 0; - this.replacedElements = null; -} - -public IndexedFileEntry add(String path){ - return add(new IndexedFileEntry(path, ++lastId)); -} - -private IndexedFileEntry add(IndexedFileEntry file) { - int length = elements.length; - String path = file.getPath(); - int index = (path.hashCode() & 0x7FFFFFFF) % length; - IndexedFileEntry current; - while ((current = elements[index]) != null) { - if (current.getPath().equals(path)) { - if (replacedElements == null) replacedElements = new ArrayList(5); - replacedElements.add(current); - return elements[index] = file; - } - if (++index == length) index = 0; - } - elements[index] = file; - - // assumes the threshold is never equal to the size of the table - if (++elementSize > threshold) grow(); - return file; -} - -public IndexedFileEntry[] asArray() { - IndexedFileEntry[] array = new IndexedFileEntry[lastId]; - for (int i = 0, length = elements.length; i < length; i++) { - IndexedFileEntry current = elements[i]; - if (current != null) - array[current.getFileID() - 1] = current; - } - if (replacedElements != null) { - for (int i = 0, length = replacedElements.size(); i < length; i++) { - IndexedFileEntry current = (IndexedFileEntry) replacedElements.get(i); - array[current.getFileID() - 1] = current; - } - } - return array; -} - -public IndexedFileEntry get(String path) { - int length = elements.length; - int index = (path.hashCode() & 0x7FFFFFFF) % length; - IndexedFileEntry current; - while ((current = elements[index]) != null) { - if (current.getPath().equals(path)) return current; - if (++index == length) index = 0; - } - return null; -} - -private void grow() { - IndexedFileEntryHashedArray newArray = new IndexedFileEntryHashedArray(elementSize * 2); // double the number of expected elements - for (int i = 0, length = elements.length; i < length; i++) - if (elements[i] != null) - newArray.add(elements[i]); - - // leave replacedElements as is - this.elements = newArray.elements; - this.elementSize = newArray.elementSize; - this.threshold = newArray.threshold; -} - -public int size() { - return elementSize + (replacedElements == null ? 0 : replacedElements.size()); -} - -public String toString() { - String s = ""; //$NON-NLS-1$ - IndexedFileEntry[] files = asArray(); - for (int i = 0, length = files.length; i < length; i++) - s += files[i].toString() + "\n"; //$NON-NLS-1$ - return s; -} -} - diff --git a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/cindexstorage/IndexerOutput.java b/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/cindexstorage/IndexerOutput.java deleted file mode 100644 index d39e19ad614..00000000000 --- a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/cindexstorage/IndexerOutput.java +++ /dev/null @@ -1,345 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.core.index.cindexstorage; - -import org.eclipse.cdt.internal.core.index.IFunctionEntry; -import org.eclipse.cdt.internal.core.index.IIndex; -import org.eclipse.cdt.internal.core.index.IIndexEntry; -import org.eclipse.cdt.internal.core.index.IIndexerOutput; -import org.eclipse.cdt.internal.core.index.INamedEntry; -import org.eclipse.cdt.internal.core.index.ITypeEntry; -import org.eclipse.cdt.internal.core.index.domsourceindexer.AbstractIndexerRunner; - -/** - * An indexerOutput is used by an indexer to add files and word references to - * an inMemoryIndex. - */ - -public class IndexerOutput implements ICIndexStorageConstants, IIndexerOutput { - public static int entryCount = 0; - protected InMemoryIndex index; - /** - * IndexerOutput constructor comment. - */ - public IndexerOutput(InMemoryIndex index) { - this.index= index; - } - - protected void addRef(int indexedFileNumber, char [][] name, char suffix, int type, int offset, int offsetLength, int offsetType, int modifiers) { - if (indexedFileNumber == 0) { - throw new IllegalStateException(); - } - - if (offsetLength <= 0) - offsetLength = 1; - - if (modifiers <=0) - modifiers = 1; - - entryCount++; - index.addRef( - encodeTypeEntry(name, suffix, type), - indexedFileNumber, offset, offsetLength, offsetType, modifiers); - } - - protected void addRef(int indexedFileNumber, char[][] name, int meta_kind, int ref, int offset, int offsetLength, int offsetType, int modifiers) { - if (indexedFileNumber == 0) { - throw new IllegalStateException(); - } - - if (offsetLength <= 0) - offsetLength = 1; - - if (modifiers <=0) - modifiers = 1; - entryCount++; - index.addRef( - encodeEntry(name, meta_kind, ref), - indexedFileNumber, offset, offsetLength, offsetType, modifiers); - - } - - public void addRelatives(int indexedFileNumber, String inclusion, String parent) { - if (indexedFileNumber == 0) { - throw new IllegalStateException(); - } - index.addRelatives(indexedFileNumber, inclusion, parent); - } - - public void addIncludeRef(int indexedFileNumber, char[] word) { - if (indexedFileNumber == 0) { - throw new IllegalStateException(); - } - index.addIncludeRef(word, indexedFileNumber); - } - - public void addIncludeRef(int indexedFileNumber, String word) { - addIncludeRef(indexedFileNumber, word.toCharArray()); - } - - public IndexedFileEntry getIndexedFile(String path) { - return index.getIndexedFile(path); - } - - /** - * Adds the file path to the index, creating a new file entry - * for it - */ - public IndexedFileEntry addIndexedFile(String path) { - return index.addFile(path); - } - - public void addIncludeRef(int indexedFileNumber, char[][] name, int offset, int offsetLength, int offsetType) { - addRef(indexedFileNumber, name, IIndex.INCLUDE, IIndex.REFERENCE, offset,offsetLength, offsetType,1); - } - - /** - * Type entries are encoded as follow: 'typeDecl/' ('C' | 'S' | 'U' | 'E' ) '/' TypeName ['/' Qualifier]* - */ - protected static final char[] encodeTypeEntry(char[][] fullTypeName, char suffix, int type) { - - int pos = 0, nameLength = 0; - for (int i=0; i 0){ - //Extract the name first - char [] tempName = fullTypeName[fullTypeName.length-1]; - System.arraycopy(tempName, 0, result, pos, tempName.length); - pos += tempName.length; - } - //Extract the qualifiers - for (int i=fullTypeName.length - 2; i >= 0; i--){ - result[pos++] = SEPARATOR; - char [] tempName = fullTypeName[i]; - System.arraycopy(tempName, 0, result, pos, tempName.length); - pos+=tempName.length; - } - - if (AbstractIndexerRunner.VERBOSE) - AbstractIndexerRunner.verbose(new String(result)); - - return result; - } - /** - * Namespace entries are encoded as follow: '[prefix]/' TypeName ['/' Qualifier]* - */ - protected static final char[] encodeEntry(char[][] elementName, int meta_kind, int ref) { - int pos, nameLength = 0; - for (int i=0; i 0){ - //Extract the name first - char [] tempName = elementName[elementName.length-1]; - System.arraycopy(tempName, 0, result, pos, tempName.length); - pos += tempName.length; - } - //Extract the qualifiers - for (int i=elementName.length - 2; i>=0; i--){ - result[pos++] = SEPARATOR; - char [] tempName = elementName[i]; - System.arraycopy(tempName, 0, result, pos, tempName.length); - pos+=tempName.length; - } - - if (AbstractIndexerRunner.VERBOSE) - AbstractIndexerRunner.verbose(new String(result)); - - return result; - } - - public void addIndexEntry(IIndexEntry indexEntry) throws IndexEntryNotSupportedException { - - if (indexEntry == null) - return; - - throw new IndexEntryNotSupportedException("Index Entry type not supported - need to add handler"); //$NON-NLS-1$ - } - - public void addIndexEntry(ITypeEntry typeEntry) { - int indexedFileNumber=typeEntry.getFileNumber(); - int meta_type = typeEntry.getMetaKind(); - int type_kind = typeEntry.getTypeKind(); - int entryType = typeEntry.getEntryType(); - int modifiers = typeEntry.getModifiers(); - - char[][]name=typeEntry.getFullName(); - - int nameOffset=typeEntry.getNameOffset(); - int nameOffsetLength=typeEntry.getNameLength(); - int nameOffsetType=typeEntry.getNameOffsetType(); - - int elementOffset=typeEntry.getElementOffset(); - int elementOffsetLength=typeEntry.getElementLength(); - int elementOffsetType=typeEntry.getElementOffsetType(); - - if (modifiers <= 0) - modifiers = 1; - - addRef(indexedFileNumber, name, ICIndexStorageConstants.typeConstants[type_kind], entryType, nameOffset,nameOffsetLength, nameOffsetType, modifiers); - - IIndexEntry[] baseClasses = typeEntry.getBaseTypes(); - if (baseClasses != null && - baseClasses.length > 0){ - for (int i=0; i0 if the str1 is equal to str2; - * a value less than 0 if str1 - * is lexicographically less than str2; - * and a value greater than 0 if str1 is - * lexicographically greater than str2. - */ - public static int compare(char[] str1, char[] str2) { - int len1= str1.length; - int len2= str2.length; - int n= Math.min(len1, len2); - int i= 0; - while (n-- != 0) { - char c1= str1[i]; - char c2= str2[i++]; - if (c1 != c2) { - return c1 - c2; - } - } - return len1 - len2; - } - - /** - * Returns the length of the common prefix between s1 and s2. - */ - public static int prefixLength(char[] s1, char[] s2) { - int len= 0; - int max= Math.min(s1.length, s2.length); - for (int i= 0; i < max && s1[i] == s2[i]; ++i) - ++len; - return len; - } - /** - * Returns the length of the common prefix between s1 and s2. - */ - public static int prefixLength(String s1, String s2) { - int len= 0; - int max= Math.min(s1.length(), s2.length()); - for (int i= 0; i < max && s1.charAt(i) == s2.charAt(i); ++i) - ++len; - return len; - } - private static void quickSort(char[][] list, int left, int right) { - int original_left= left; - int original_right= right; - char[] mid= list[(left + right) / 2]; - do { - while (compare(list[left], mid) < 0) { - left++; - } - while (compare(mid, list[right]) < 0) { - right--; - } - if (left <= right) { - char[] tmp= list[left]; - list[left]= list[right]; - list[right]= tmp; - left++; - right--; - } - } while (left <= right); - if (original_left < right) { - quickSort(list, original_left, right); - } - if (left < original_right) { - quickSort(list, left, original_right); - } - } - private static void quickSort(int[] list, int left, int right) { - int original_left= left; - int original_right= right; - int mid= list[(left + right) / 2]; - do { - while (list[left] < mid) { - left++; - } - while (mid < list[right]) { - right--; - } - if (left <= right) { - int tmp= list[left]; - list[left]= list[right]; - list[right]= tmp; - left++; - right--; - } - } while (left <= right); - if (original_left < right) { - quickSort(list, original_left, right); - } - if (left < original_right) { - quickSort(list, left, original_right); - } - } - private static void quickSort(String[] list, int left, int right) { - int original_left= left; - int original_right= right; - String mid= list[(left + right) / 2]; - do { - while (list[left].compareTo(mid) < 0) { - left++; - } - while (mid.compareTo(list[right]) < 0) { - right--; - } - if (left <= right) { - String tmp= list[left]; - list[left]= list[right]; - list[right]= tmp; - left++; - right--; - } - } while (left <= right); - if (original_left < right) { - quickSort(list, original_left, right); - } - if (left < original_right) { - quickSort(list, left, original_right); - } - } - private static void quickSort(IndexedFileEntry[] list, int left, int right) { - int original_left= left; - int original_right= right; - String mid= list[(left + right) / 2].getPath(); - do { - while (list[left].getPath().compareTo(mid) < 0) { - left++; - } - while (mid.compareTo(list[right].getPath()) < 0) { - right--; - } - if (left <= right) { - IndexedFileEntry tmp= list[left]; - list[left]= list[right]; - list[right]= tmp; - left++; - right--; - } - } while (left <= right); - if (original_left < right) { - quickSort(list, original_left, right); - } - if (left < original_right) { - quickSort(list, left, original_right); - } - } - private static void quickSort(WordEntry[] list, int left, int right) { - int original_left= left; - int original_right= right; - char[] mid= list[(left + right) / 2].getWord(); - do { - while (compare(list[left].getWord(), mid) < 0) { - left++; - } - while (compare(mid, list[right].getWord()) < 0) { - right--; - } - if (left <= right) { - WordEntry tmp= list[left]; - list[left]= list[right]; - list[right]= tmp; - left++; - right--; - } - } while (left <= right); - if (original_left < right) { - quickSort(list, original_left, right); - } - if (left < original_right) { - quickSort(list, left, original_right); - } - } - - private static void quickSort(IncludeEntry[] list, int left, int right) { - int original_left= left; - int original_right= right; - char[] mid= list[(left + right) / 2].fFile; - do { - while (compare(list[left].fFile, mid) < 0) { - left++; - } - while (compare(mid, list[right].fFile) < 0) { - right--; - } - if (left <= right) { - IncludeEntry tmp= list[left]; - list[left]= list[right]; - list[right]= tmp; - left++; - right--; - } - } while (left <= right); - if (original_left < right) { - quickSort(list, original_left, right); - } - if (left < original_right) { - quickSort(list, left, original_right); - } - } - /** - * Reads in a string from the specified data input stream. The - * string has been encoded using a modified UTF-8 format. - *

    - * The first two bytes are read as if by - * readUnsignedShort. This value gives the number of - * following bytes that are in the encoded string, not - * the length of the resulting string. The following bytes are then - * interpreted as bytes encoding characters in the UTF-8 format - * and are converted into characters. - *

    - * This method blocks until all the bytes are read, the end of the - * stream is detected, or an exception is thrown. - * - * @param in a data input stream. - * @return a Unicode string. - * @exception EOFException if the input stream reaches the end - * before all the bytes. - * @exception IOException if an I/O error occurs. - * @exception UTFDataFormatException if the bytes do not represent a - * valid UTF-8 encoding of a Unicode string. - * @see java.io.DataInputStream#readUnsignedShort() - */ - public final static char[] readUTF(DataInput in) throws IOException { - int utflen= in.readUnsignedShort(); - char str[]= new char[utflen]; - int count= 0; - int strlen= 0; - while (count < utflen) { - int c= in.readUnsignedByte(); - int char2, char3; - switch (c >> 4) { - case 0 : - case 1 : - case 2 : - case 3 : - case 4 : - case 5 : - case 6 : - case 7 : - // 0xxxxxxx - count++; - str[strlen++]= (char) c; - break; - case 12 : - case 13 : - // 110x xxxx 10xx xxxx - count += 2; - if (count > utflen) - throw new UTFDataFormatException(); - char2= in.readUnsignedByte(); - if ((char2 & 0xC0) != 0x80) - throw new UTFDataFormatException(); - str[strlen++]= (char) (((c & 0x1F) << 6) | (char2 & 0x3F)); - break; - case 14 : - // 1110 xxxx 10xx xxxx 10xx xxxx - count += 3; - if (count > utflen) - throw new UTFDataFormatException(); - char2= in.readUnsignedByte(); - char3= in.readUnsignedByte(); - if (((char2 & 0xC0) != 0x80) || ((char3 & 0xC0) != 0x80)) - throw new UTFDataFormatException(); - str[strlen++]= (char) (((c & 0x0F) << 12) | ((char2 & 0x3F) << 6) | ((char3 & 0x3F) << 0)); - break; - default : - // 10xx xxxx, 1111 xxxx - throw new UTFDataFormatException(); - } - } - if (strlen < utflen) { - System.arraycopy(str, 0, str= new char[strlen], 0, strlen); - } - return str; - } - public static void sort(char[][] list) { - if (list.length > 1) - quickSort(list, 0, list.length - 1); - } - public static void sort(int[] list) { - if (list.length > 1) - quickSort(list, 0, list.length - 1); - } - public static void sort(String[] list) { - if (list.length > 1) - quickSort(list, 0, list.length - 1); - } - public static void sort(IndexedFileEntry[] list) { - if (list.length > 1) - quickSort(list, 0, list.length - 1); - } - public static void sort(WordEntry[] list) { - if (list.length > 1) - quickSort(list, 0, list.length - 1); - } - public static void sort(IncludeEntry[] list) { - if (list.length > 1) - quickSort(list, 0, list.length - 1); - } - /** - * Writes a string to the given output stream using UTF-8 - * encoding in a machine-independent manner. - *

    - * First, two bytes are written to the output stream as if by the - * writeShort method giving the number of bytes to - * follow. This value is the number of bytes actually written out, - * not the length of the string. Following the length, each character - * of the string is output, in sequence, using the UTF-8 encoding - * for the character. - * - * @param str a string to be written. - * @exception IOException if an I/O error occurs. - * @since JDK1.0 - */ - public static void writeUTF(OutputStream out, char[] str) throws IOException { - int strlen= str.length; - int utflen= 0; - for (int i= 0; i < strlen; i++) { - int c= str[i]; - if ((c >= 0x0001) && (c <= 0x007F)) { - utflen++; - } else if (c > 0x07FF) { - utflen += 3; - } else { - utflen += 2; - } - } - if (utflen > 65535) - throw new UTFDataFormatException(); - out.write((utflen >>> 8) & 0xFF); - out.write((utflen >>> 0) & 0xFF); - for (int i= 0; i < strlen; i++) { - int c= str[i]; - if ((c >= 0x0001) && (c <= 0x007F)) { - out.write(c); - } else if (c > 0x07FF) { - out.write(0xE0 | ((c >> 12) & 0x0F)); - out.write(0x80 | ((c >> 6) & 0x3F)); - out.write(0x80 | ((c >> 0) & 0x3F)); - } else { - out.write(0xC0 | ((c >> 6) & 0x1F)); - out.write(0x80 | ((c >> 0) & 0x3F)); - } - } - } - -} - diff --git a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/cindexstorage/WordEntry.java b/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/cindexstorage/WordEntry.java deleted file mode 100644 index 5835217be24..00000000000 --- a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/cindexstorage/WordEntry.java +++ /dev/null @@ -1,534 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.core.index.cindexstorage; - -import org.eclipse.cdt.internal.core.CharOperation; - -public class WordEntry { - - //Prefix used for index encoding as defined in ICIndexStorageConstants - private int encodings; - //Second part of encoding string as definined in ICIndexStorageConstants - private int encodingType; - //Used for type encodings only; defined in ICIndexStorageConstants - private int typeConstant; - - //Fully qualified name for ref - private char[] word; - - //Number of file references for this word entry - private int fileRefCount; - //File reference id's - private int[] fileRefs; - - //Modifier bit fields - one for each fileRef - private int[] modifiers; - - //Offset arrays - each fileRef's position in the fileRef array is the - //key into the offsets - //Offsets are prefixed with LINE or OFFSET designation - private int[][] offsets; - //Lengths of the offsets - all offsets will have an entry in here; OFFSET entries - //will have the real offset value, LINE entires will have a place holder value of 1 - private int[][] offsetLengths; - - //Number of offsets in each offset array - private int[] offsetCount; - - public WordEntry() { - this(CharOperation.NO_CHAR); - } - public WordEntry(char[] word) { - this.word= word; - fileRefCount= 0; - fileRefs= new int[1]; - modifiers= new int[1]; - offsets = new int [1][1]; - offsetLengths = new int[1][1]; - offsetCount = new int[1]; - } - /** - * Adds a reference and records the change in footprint. - * @return returns the size increase for this instance - */ - public int addRef(int fileNum) { - //Ensure that this is a unique fileNum that hasn't been added - //already to the refs - if (fileRefCount > 0 && fileAlreadyAdded(fileNum)) { - return 0; - } - //Ensure that there is still space to add this ref - if so, - //add the reference - if (fileRefCount < fileRefs.length) { - fileRefs[fileRefCount++]= fileNum; - return 0; - } - //Need to grow arrays - arrays will start at 1, grow to 4, 8, 16, 32, 64 etc. - int newSize= fileRefCount < 4 ? 4 : fileRefCount * 2; - //Grow the fileRefs array - System.arraycopy(fileRefs, 0, fileRefs= new int[newSize], 0, fileRefCount); - //Grow the modifier array - System.arraycopy(modifiers, 0, modifiers= new int[newSize], 0, fileRefCount); - //Grow the offset array - System.arraycopy(offsets, 0, offsets= new int[newSize][1], 0, fileRefCount); - //Grow the offsetLengths array - System.arraycopy(offsetLengths, 0, offsetLengths=new int[newSize][1],0,fileRefCount); - //Grow the offset count array - System.arraycopy(offsetCount, 0, offsetCount= new int[newSize], 0, fileRefCount); - //Add the new file reference - fileRefs[fileRefCount++]= fileNum; - return (newSize - fileRefCount + 1) * 4; - } - /** - * Checks to see if this file number has already been added - */ - private boolean fileAlreadyAdded(int fileNum) { - for (int i=0; i= fileRefCount) { - r2= refs[pos2]; - compare= -1; - } else if (pos2 >= refs.length) { - compare= 1; - r1= fileRefs[pos1]; - } else { - r1= fileRefs[pos1]; - r2= refs[pos2]; - compare= r2 - r1; - } - if (compare > 0) { - newRefs[posNew]= r1; - newOffsets[posNew]= offsets[pos1]; - newOffsetLengths[posNew]=offsetLengths[pos1]; - newOffSetCount[posNew]=offsetCount[pos1]; - newModifiers[posNew]=modifiers[pos1]; - posNew++; - pos1++; - } else { - if (r2 != 0) { - newRefs[posNew]= r2; - newOffsets[posNew]=passedOffsets[pos2]; - newOffsetLengths[posNew]=passedOffsetLengths[pos2]; - newOffSetCount[posNew]=passedOffsetCount[pos2]; - newModifiers[posNew]=passedModifers[pos2]; - posNew++; - } - pos2++; - } - } - fileRefs= newRefs; - offsets= newOffsets; - offsetLengths=newOffsetLengths; - offsetCount=newOffSetCount; - modifiers=newModifiers; - fileRefCount= posNew; - } - - /** - * Adds a reference and records the change in footprint. - * @return -1 if fileNumber not found, 0 if adding offset didn't result in - * change of object size, new size of object if adding offset forced the expansion - * of the underlying array - */ - public int addOffset(int offset, int offsetLength, int fileNum, int offsetType) { - //Get the position in the fileRefs array for this file number - the - //position acts as an index into the offsets array - int filePosition = getPositionForFile(fileNum); - //File Number wasn't found - if (filePosition == -1) - return -1; - //Get the array containing the offsets for this file - int[] selectedOffsets = offsets[filePosition]; - //Get the array containing the offset lengths for this file; - int[] selectedOffsetLengths = offsetLengths[filePosition]; - //Get the offset count for this file - int selectedOffsetCount = offsetCount[filePosition]; - - //Encode the number with line/offset info - int encodedNumber = getEncodedNumber(offsetType, offset); - - //Check to see if this offset has already been added to the file - if (selectedOffsetCount > 0 && offsetAlreadyAdded(filePosition, encodedNumber)){ - return 0; - } - - - //If there is still space in the array, add the encoded offset, update - //the count - if (selectedOffsetCount < selectedOffsets.length) { - //Place the offset in next position in the offset array - selectedOffsets[selectedOffsetCount]= encodedNumber; - //Place the length at the same place in the offset length array and increment - //the position counter - selectedOffsetLengths[selectedOffsetCount++]=offsetLength; - offsetCount[filePosition] = selectedOffsetCount; - return 0; - } - - //Grow the offset array - start @ 1, grow to 4, 8, 16, 32, 64 etc. - int newSize= selectedOffsetCount < 4 ? 4 : selectedOffsetCount * 2; - System.arraycopy(selectedOffsets, 0, selectedOffsets= new int[newSize], 0, selectedOffsetCount); - System.arraycopy(selectedOffsetLengths,0, selectedOffsetLengths=new int[newSize], 0, selectedOffsetCount); - //Add the encoded offset to the newly grown array, add the length to the same - //position, update the count - selectedOffsets[selectedOffsetCount]= encodedNumber; - selectedOffsetLengths[selectedOffsetCount++]=offsetLength; - offsetCount[filePosition] = selectedOffsetCount; - //Put the newly grown arrays back in place - offsets[filePosition]=selectedOffsets; - offsetLengths[filePosition]=selectedOffsetLengths; - return (newSize - fileRefCount + 1) * 4; - } - - public int addModifiers(int modifier, int fileNum){ - //Get the position in the fileRefs array for this file number - the - //position acts as an index into the offsets array - int filePosition = getPositionForFile(fileNum); - //File Number wasn't found - if (filePosition == -1) - return -1; - - if (modifier <= 0){ - int x=4; - } - - modifiers[filePosition]=modifier; - return 0; - } - - /** - * @param offsetType - * @param offset - * @return - */ - private int getEncodedNumber(int offsetType, int offset) { - /* String offsetString = Integer.toString(offsetType) + Integer.toString(offset); - return Integer.parseInt(offsetString);*/ - - int m = 10; - while (m <= offset) { - m = m * 10; - } - return m * offsetType + offset; - } - /** - * @param filePosition - * @return - */ - private boolean offsetAlreadyAdded(int filePosition, int offset) { - int[] tempOffset = offsets[filePosition]; - for (int i=0; i - * if the current references are [1 3 4]
    - * and mapping is [1 2 3 4 5]
    - * in references 1 becomes mapping[1] = 2, 3->4, and 4->5
    - * => references = [2 4 5].
    - */ - public void mapRefs(int[] mappings) { - int position= 0; - - for (int i= 0; i < fileRefCount; i++) { - //Take care that the reference is actually within the bounds of the mapping - int map= -1; - - if(fileRefs[i] >= 0 && fileRefs[i] < mappings.length) - map= mappings[fileRefs[i]]; - if (map != -1 && map != 0) - fileRefs[position++]= map; - } - fileRefCount= position; - - //Trim all arrays of excess flab - System.arraycopy(fileRefs, 0, (fileRefs= new int[fileRefCount]), 0, fileRefCount); - System.arraycopy(offsets, 0, (offsets = new int[fileRefCount][]), 0,fileRefCount); - System.arraycopy(offsetLengths, 0, (offsetLengths = new int[fileRefCount][]), 0,fileRefCount); - System.arraycopy(offsetCount, 0,(offsetCount=new int[fileRefCount]),0,fileRefCount); - System.arraycopy(modifiers, 0, (modifiers=new int[fileRefCount]),0,fileRefCount); - - //Store original ref positions in order to generate map - int[] originalRefs; - System.arraycopy(fileRefs, 0, (originalRefs = new int[fileRefCount]),0,fileRefCount); - //Sort file refs - Util.sort(fileRefs); - - //Sort the original file refs - int[] mapping = new int[fileRefs.length]; - figureOutMapping(originalRefs, fileRefs, mapping); - mapOffsets(mapping); - mapModiers(mapping); - } - - /** - * @param mapping - */ - private void mapOffsets(int[] mapping) { - int fileRefLength = fileRefs.length; - int[][] tempOffsetsArray = new int[fileRefLength][]; - int[][] tempOffsetsLengthArray = new int[fileRefLength][]; - int[] tempOffsetCountArray = new int[fileRefLength]; - - for (int i=0; i 0;) { - fileRefs[i]= 0; - } - fileRefCount= 0; - this.word= word; - } - public String toString() { - return new String(word); - } - /** - * Returns the sorted offset entries for the given index - * @return - */ - public int[] getOffsets(int index) { - int[] tempOffset = offsets[index]; - int offsetLength = offsetCount[index]; - - int[] result= new int[offsetLength]; - System.arraycopy(tempOffset, 0, result, 0, offsetLength); - Util.sort(result); - return result; - } - - /** - * Returns the offset length entries sorted in the same order as the sorted offsets - * for the given index - * @return - */ - public int[] getOffsetLengths(int index) { - //Get the before/after sort offsets and create a mapping - int[] initialOffsets = offsets[index]; - int[] sortedOffsets = getOffsets(index); - int[] map = new int[sortedOffsets.length]; - figureOutMapping(initialOffsets,sortedOffsets, map); - - //Map the offset lengths to the sorted offset positions - int[] tempOffset = offsetLengths[index]; - int offsetLength = offsetCount[index]; - int[] result= new int[offsetLength]; - - for (int i=0; i threshold) grow(); - return entry; - } - - public WordEntry[] asArray() { - WordEntry[] array = new WordEntry[elementSize]; - for (int i = 0, j = 0, length = elements.length; i < length; i++) { - WordEntry current = elements[i]; - if (current != null) array[j++] = current; - } - return array; - } - - public WordEntry get(char[] word) { - int length = elements.length; - int index = CharOperation.hashCode(word) % length; - WordEntry current; - while ((current = elements[index]) != null) { - if (CharOperation.equals(current.getWord(), word)) return current; - if (++index == length) index = 0; - } - return null; - } - - private void grow() { - WordEntryHashedArray newArray = new WordEntryHashedArray(elementSize * 2); // double the number of expected elements - for (int i = 0, length = elements.length; i < length; i++) - if (elements[i] != null) - newArray.add(elements[i]); - - this.elements = newArray.elements; - this.elementSize = newArray.elementSize; - this.threshold = newArray.threshold; - } - - public String toString() { - String s = ""; //$NON-NLS-1$ - WordEntry[] entries = asArray(); - for (int i = 0, length = entries.length; i < length; i++) - s += entries[i].toString() + "\n"; //$NON-NLS-1$ - return s; - } -} diff --git a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/cindexstorage/io/Block.java b/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/cindexstorage/io/Block.java deleted file mode 100644 index 8958050c71d..00000000000 --- a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/cindexstorage/io/Block.java +++ /dev/null @@ -1,63 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ - -package org.eclipse.cdt.internal.core.index.cindexstorage.io; - -import java.io.IOException; -import java.io.RandomAccessFile; - - -/** - * A block is a container that can hold information (a list of file names, a list of - * words, ...), be saved on the disk and loaded in memory. - */ - -public abstract class Block { - /** - * Size of the block - */ - protected int blockSize; - - /** - * Field in which the information is stored - */ - protected Field field; - - public Block(int blockSize) { - this.blockSize= blockSize; - field= new Field(blockSize); - } - /** - * Empties the block. - */ - public void clear() { - field.clear(); - } - /** - * Flushes the block - */ - public void flush() { - } - /** - * Loads the block with the given number in memory, reading it from a RandomAccessFile. - */ - public void read(RandomAccessFile raf, int blockNum) throws IOException { - raf.seek(blockNum * (long) blockSize); - raf.readFully(field.buffer()); - } - /** - * Writes the block in a RandomAccessFile, giving it a block number. - */ - public void write(RandomAccessFile raf, int blockNum) throws IOException { - raf.seek(blockNum * (long) blockSize); - raf.write(field.buffer()); - } -} diff --git a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/cindexstorage/io/BlocksIndexInput.java b/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/cindexstorage/io/BlocksIndexInput.java deleted file mode 100644 index bc36b9f7865..00000000000 --- a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/cindexstorage/io/BlocksIndexInput.java +++ /dev/null @@ -1,490 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.core.index.cindexstorage.io; - -import java.io.File; -import java.io.IOException; -import java.io.RandomAccessFile; -import java.util.ArrayList; - -import org.eclipse.cdt.internal.core.CharOperation; -import org.eclipse.cdt.internal.core.Util; -import org.eclipse.cdt.internal.core.index.IEntryResult; -import org.eclipse.cdt.internal.core.index.IQueryResult; -import org.eclipse.cdt.internal.core.index.cindexstorage.EntryResult; -import org.eclipse.cdt.internal.core.index.cindexstorage.ICIndexStorageConstants; -import org.eclipse.cdt.internal.core.index.cindexstorage.IncludeEntry; -import org.eclipse.cdt.internal.core.index.cindexstorage.IndexedFileEntry; -import org.eclipse.cdt.internal.core.index.cindexstorage.WordEntry; -import org.eclipse.cdt.internal.core.util.LRUCache; - -/** - * This input is used for reading indexes saved using a BlocksIndexOutput. - */ -public class BlocksIndexInput extends IndexInput { - public static final int CACHE_SIZE= 16; // Cache 16 blocks of 8K each, for a cache size of 128K - protected FileListBlock currentFileListBlock; - protected int currentFileListBlockNum; - protected int currentIndexBlockNum; - protected int currentIncludeBlockNum; - protected IndexBlock currentIndexBlock; - protected IndexBlock currentIncludeIndexBlock; - private RandomAccessFile raf; - protected File indexFile; - protected LRUCache blockCache; - protected boolean opened= false; - protected IndexSummary summary; - - public BlocksIndexInput(File inputFile) { - this.indexFile= inputFile; - blockCache= new LRUCache(CACHE_SIZE); - } - /** - * @see IndexInput#clearCache() - */ - public void clearCache() { - blockCache= new LRUCache(CACHE_SIZE); - } - /** - * @see IndexInput#close() - */ - public void close() throws IOException { - if (opened) { - summary= null; - opened= false; - if (raf != null) - raf.close(); - } - } - /** - * @see IndexInput#getCurrentFile() - */ - public IndexedFileEntry getCurrentFile() throws IOException { - if (!hasMoreFiles()) - return null; - IndexedFileEntry file= null; - if ((file= currentFileListBlock.getFile(filePosition)) == null) { - currentFileListBlockNum= summary.getBlockNumForFileNum(filePosition); - currentFileListBlock= getFileListBlock(currentFileListBlockNum); - file= currentFileListBlock.getFile(filePosition); - } - return file; - } - /** - * Returns the entry corresponding to the given word. - */ - protected WordEntry getEntry(char[] word) throws IOException { - int blockNum= summary.getBlockNumForWord(word); - if (blockNum == -1) return null; - IndexBlock block= getIndexBlock(blockNum); - return block.findExactEntry(word); - } - /** - * Returns the FileListBlock with the given number. - */ - protected FileListBlock getFileListBlock(int blockNum) throws IOException { - Integer key= new Integer(blockNum); - Block block= (Block) blockCache.get(key); - if (block != null && block instanceof FileListBlock) - return (FileListBlock) block; - FileListBlock fileListBlock= new FileListBlock(ICIndexStorageConstants.BLOCK_SIZE); - fileListBlock.read(raf, blockNum); - blockCache.put(key, fileListBlock); - return fileListBlock; - } - /** - * Returns the IndexBlock (containing words) with the given number. - */ - protected IndexBlock getIndexBlock(int blockNum) throws IOException { - Integer key= new Integer(blockNum); - Block block= (Block) blockCache.get(key); - if (block != null && block instanceof IndexBlock) - return (IndexBlock) block; - IndexBlock indexBlock= new GammaCompressedIndexBlock(ICIndexStorageConstants.BLOCK_SIZE); - indexBlock.read(raf, blockNum); - blockCache.put(key, indexBlock); - return indexBlock; - } - /** - * @see IndexInput#getIndexedFile(int) - */ - public IndexedFileEntry getIndexedFile(int fileNum) throws IOException { - int blockNum= summary.getBlockNumForFileNum(fileNum); - if (blockNum == -1) - return null; - FileListBlock block= getFileListBlock(blockNum); - return block.getFile(fileNum); - } - /** - * @see IndexInput#getIndexedFile(IDocument) - */ - public IndexedFileEntry getIndexedFile(String fullPath) throws java.io.IOException { - setFirstFile(); - while (hasMoreFiles()) { - IndexedFileEntry file= getCurrentFile(); - String path= file.getPath(); - if (path.equals(fullPath)) - return file; - moveToNextFile(); - } - return null; - } - /** - * Returns the list of numbers of files containing the given word. - */ - - protected int[] getMatchingFileNumbers(char[] word) throws IOException { - int blockNum= summary.getBlockNumForWord(word); - if (blockNum == -1) - return new int[0]; - IndexBlock block= getIndexBlock(blockNum); - WordEntry entry= block.findExactEntry(word); - return entry == null ? new int[0] : entry.getRefs(); - } - /** - * @see IndexInput#getNumFiles() - */ - public int getNumFiles() { - return summary.getNumFiles(); - } - /** - * @see IndexInput#getNumWords() - */ - public int getNumWords() { - return summary.getNumWords(); - } - /** - * @see IndexInput#getNumIncludes() - */ - public int getNumIncludes() { - return summary.getNumIncludes(); - } - /** - * @see IndexInput#getSource() - */ - public Object getSource() { - return indexFile; - } - /** - * Initialises the blocksIndexInput - */ - protected void init() throws IOException { - clearCache(); - setFirstFile(); - setFirstWord(); - setFirstInclude(); - } - /** - * @see IndexInput#moveToNextFile() - */ - public void moveToNextFile() throws IOException { - filePosition++; - } - /** - * @see IndexInput#moveToNextWordEntry() - */ - public void moveToNextWordEntry() throws IOException { - wordPosition++; - if (!hasMoreWords()) { - return; - } - //if end of the current block, we load the next one. - boolean endOfBlock= !currentIndexBlock.nextEntry(currentWordEntry); - if (endOfBlock) { - currentIndexBlock= getIndexBlock(++currentIndexBlockNum); - currentIndexBlock.nextEntry(currentWordEntry); - } - } - /** - * @see IndexInput#open() - */ - - public void open() throws IOException { - if (!opened) { - raf= new SafeRandomAccessFile(indexFile, "r"); //$NON-NLS-1$ - String sig= raf.readUTF(); - if (!sig.equals(ICIndexStorageConstants.SIGNATURE)) - throw new IOException(Util.bind("exception.wrongFormat")); //$NON-NLS-1$ - int summaryBlockNum= raf.readInt(); - raf.seek(summaryBlockNum * (long) ICIndexStorageConstants.BLOCK_SIZE); - summary= new IndexSummary(); - summary.read(raf); - init(); - opened= true; - } - } - /** - * @see IndexInput#query(String) - */ - public IQueryResult[] query(String word) throws IOException { - open(); - int[] fileNums= getMatchingFileNumbers(word.toCharArray()); - int size= fileNums.length; - IQueryResult[] files= new IQueryResult[size]; - for (int i= 0; i < size; ++i) { - files[i]= getIndexedFile(fileNums[i]); - } - return files; - } - /** - * If no prefix is provided in the pattern, then this operation will have to walk - * all the entries of the whole index. - */ - public IEntryResult[] queryEntriesMatching(char[] pattern/*, boolean isCaseSensitive*/) throws IOException { - open(); - - if (pattern == null || pattern.length == 0) return null; - int[] blockNums = null; - int firstStar = CharOperation.indexOf('*', pattern); - switch (firstStar){ - case -1 : - WordEntry entry = getEntry(pattern); - if (entry == null) return null; - return new IEntryResult[]{ new EntryResult(entry.getWord(), entry.getRefs(), entry.getOffsets(), entry.getOffsetLengths()) }; - case 0 : - blockNums = summary.getAllBlockNums(); - break; - default : - char[] prefix = CharOperation.subarray(pattern, 0, firstStar); - blockNums = summary.getBlockNumsForPrefix(prefix); - } - if (blockNums == null || blockNums.length == 0) return null; - - IEntryResult[] entries = new IEntryResult[5]; - int count = 0; - for (int i = 0, max = blockNums.length; i < max; i++) { - IndexBlock block = getIndexBlock(blockNums[i]); - block.reset(); - boolean found = false; - WordEntry entry = new WordEntry(); - while (block.nextEntry(entry)) { - if (CharOperation.match(entry.getWord(), pattern, true)) { - if (count == entries.length){ - System.arraycopy(entries, 0, entries = new IEntryResult[count*2], 0, count); - } - entries[count++] = new EntryResult(entry.getWord(), entry.getRefs(), entry.getOffsets(), entry.getOffsetLengths()); - found = true; - } else { - if (found) break; - } - } - } - if (count != entries.length){ - System.arraycopy(entries, 0, entries = new IEntryResult[count], 0, count); - } - return entries; - } - public IEntryResult[] queryEntriesPrefixedBy(char[] prefix) throws IOException { - open(); - - int blockLoc = summary.getFirstBlockLocationForPrefix(prefix); - if (blockLoc < 0) return null; - - IEntryResult[] entries = new IEntryResult[5]; - int count = 0; - while(blockLoc >= 0){ - IndexBlock block = getIndexBlock(summary.getBlockNum(blockLoc)); - block.reset(); - boolean found = false; - WordEntry entry = new WordEntry(); - while (block.nextEntry(entry)) { - if (CharOperation.prefixEquals(prefix, entry.getWord())) { - if (count == entries.length){ - System.arraycopy(entries, 0, entries = new IEntryResult[count*2], 0, count); - } - entries[count++] = new EntryResult(entry.getWord(), entry.getRefs(), entry.getOffsets(), entry.getOffsetLengths()); - found = true; - } else { - if (found) break; - } - } - /* consider next block ? */ - blockLoc = summary.getNextBlockLocationForPrefix(prefix, blockLoc); - } - if (count == 0) return null; - if (count != entries.length){ - System.arraycopy(entries, 0, entries = new IEntryResult[count], 0, count); - } - return entries; - } - public IQueryResult[] queryFilesReferringToPrefix(char[] prefix) throws IOException { - open(); - - int blockLoc = summary.getFirstBlockLocationForPrefix(prefix); - if (blockLoc < 0) return null; - - // each filename must be returned already once - org.eclipse.cdt.internal.core.search.HashtableOfInt fileMatches = new org.eclipse.cdt.internal.core.search.HashtableOfInt(20); - int count = 0; - while(blockLoc >= 0){ - IndexBlock block = getIndexBlock(summary.getBlockNum(blockLoc)); - block.reset(); - boolean found = false; - WordEntry entry = new WordEntry(); - while (block.nextEntry(entry)) { - if (CharOperation.prefixEquals(prefix, entry.getWord()/*, isCaseSensitive*/)) { - int [] refs = entry.getRefs(); - for (int i = 0, max = refs.length; i < max; i++){ - int ref = refs[i]; - if (!fileMatches.containsKey(ref)){ - count++; - fileMatches.put(ref, getIndexedFile(ref)); - } - } - found = true; - } else { - if (found) break; - } - } - /* consider next block ? */ - blockLoc = summary.getNextBlockLocationForPrefix(prefix, blockLoc); - } - /* extract indexed files */ - IQueryResult[] files = new IQueryResult[count]; - Object[] indexedFiles = fileMatches.valueTable; - for (int i = 0, index = 0, max = indexedFiles.length; i < max; i++){ - IndexedFileEntry indexedFile = (IndexedFileEntry) indexedFiles[i]; - if (indexedFile != null){ - files[index++] = indexedFile; - } - } - return files; - } - /** - * @see IndexInput#queryInDocumentNames(String) - */ - public IQueryResult[] queryInDocumentNames(String word) throws IOException { - open(); - ArrayList matches= new ArrayList(); - setFirstFile(); - while (hasMoreFiles()) { - IndexedFileEntry file= getCurrentFile(); - if (file.getPath().indexOf(word) != -1) - matches.add(file); - moveToNextFile(); - } - IQueryResult[] match= new IQueryResult[matches.size()]; - matches.toArray(match); - return match; - } - /** - * @see IndexInput#setFirstFile() - */ - - protected void setFirstFile() throws IOException { - filePosition= 1; - if (getNumFiles() > 0) { - currentFileListBlockNum= summary.getBlockNumForFileNum(1); - currentFileListBlock= getFileListBlock(currentFileListBlockNum); - } - } - /** - * @see IndexInput#setFirstWord() - */ - - protected void setFirstWord() throws IOException { - wordPosition= 1; - if (getNumWords() > 0) { - currentIndexBlockNum= summary.getFirstWordBlockNum(); - currentIndexBlock= getIndexBlock(currentIndexBlockNum); - currentWordEntry= new WordEntry(); - currentIndexBlock.reset(); - currentIndexBlock.nextEntry(currentWordEntry); - } - } - - /* (non-Javadoc) - * @see org.eclipse.cdt.internal.core.index.impl.IndexInput#moveToNextIncludeEntry() - */ - public void moveToNextIncludeEntry() throws IOException { - includePosition++; - if (!hasMoreIncludes()) { - return; - } - //if end of the current block, we load the next one. - boolean endOfBlock= !currentIncludeIndexBlock.nextEntry(currentIncludeEntry); - if (endOfBlock) { - currentIncludeIndexBlock= getIndexBlock(++currentIncludeBlockNum); - currentIncludeIndexBlock.nextEntry(currentIncludeEntry); - } - } - /* (non-Javadoc) - * @see org.eclipse.cdt.internal.core.index.impl.IndexInput#setFirstInclude() - */ - protected void setFirstInclude() throws IOException { - includePosition= 1; - if (getNumIncludes() > 0) { - currentIncludeBlockNum= summary.getFirstIncludeBlockNum(); - currentIncludeIndexBlock= getIndexBlock(currentIncludeBlockNum); - currentIncludeEntry= new IncludeEntry(0); - currentIncludeIndexBlock.reset(); - currentIncludeIndexBlock.nextEntry(currentIncludeEntry); - } - } - /* (non-Javadoc) - * @see org.eclipse.cdt.internal.core.index.impl.IndexInput#queryIncludeEntries() - */ - public IncludeEntry[] queryIncludeEntries() { - // TODO Auto-generated method stub - return null; - } - /* (non-Javadoc) - * @see org.eclipse.cdt.internal.core.index.impl.IndexInput#queryIncludeEntries(int) - */ - public IncludeEntry[] queryIncludeEntries(int fileNum) throws IOException { - open(); - - if (fileNum < 0) return null; - int[] blockNums = null; - blockNums = summary.getBlockNumsForIncludes(); - - if (blockNums == null || blockNums.length == 0) return null; - - IncludeEntry[] entries = new IncludeEntry[5]; - int count = 0; - for (int i = 0, max = blockNums.length; i < max; i++) { - IndexBlock block = getIndexBlock(blockNums[i]); - block.reset(); - boolean found = false; - IncludeEntry entry = new IncludeEntry(0); - - while (block.nextEntry(entry)) { - if (count == entries.length){ - System.arraycopy(entries, 0, entries = new IncludeEntry[count*2], 0, count); - } - for (int j=0; j - * - Signature of the file;
    - * - FileListBlocks;
    - * - IndexBlocks;
    - * - Summary of the index. - */ - -public class BlocksIndexOutput extends IndexOutput { - - protected RandomAccessFile indexOut; - protected int blockNum; - protected boolean opened= false; - protected File indexFile; - - protected FileListBlock fileListBlock; - protected IndexBlock indexBlock; - protected IndexBlock includeIndexBlock; - - protected int numWords= 0; - protected int numFiles= 0; - protected int numIncludes= 0; - protected IndexSummary summary; - - protected boolean firstInBlock; - protected boolean firstIndexBlock; - protected boolean firstFileListBlock; - protected boolean firstIncludeIndexBlock; - - public BlocksIndexOutput(File indexFile) { - this.indexFile= indexFile; - summary= new IndexSummary(); - blockNum= 1; - firstInBlock= true; - firstIndexBlock= true; - firstFileListBlock= true; - firstIncludeIndexBlock=true; - } - /** - * @see IndexOutput#addFile - */ - public void addFile(IndexedFileEntry indexedFile) throws IOException { - if (firstFileListBlock) { - firstInBlock= true; - fileListBlock= new FileListBlock(ICIndexStorageConstants.BLOCK_SIZE); - firstFileListBlock= false; - } - if (fileListBlock.addFile(indexedFile)) { - if (firstInBlock) { - summary.addFirstFileInBlock(indexedFile, blockNum); - firstInBlock= false; - } - numFiles++; - } else { - if (fileListBlock.isEmpty()) { - return; - } - flushFiles(); - addFile(indexedFile); - } - } - /** - * @see IndexOutput#addWord - */ - public void addWord(WordEntry entry) throws IOException { - if (firstIndexBlock) { - indexBlock= new GammaCompressedIndexBlock(ICIndexStorageConstants.BLOCK_SIZE); - firstInBlock= true; - firstIndexBlock= false; - } - if (entry.getNumRefs() == 0) - return; - if (indexBlock.addEntry(entry)) { - if (firstInBlock) { - summary.addFirstWordInBlock(entry.getWord(), blockNum); - firstInBlock= false; - } - numWords++; - } else { - if (indexBlock.isEmpty()) { - return; - } - flushWords(); - addWord(entry); - } - } - /** - * @see IndexOutput#addInclude - */ - public void addInclude(IncludeEntry entry) throws IOException { - if (firstIncludeIndexBlock) { - includeIndexBlock= new GammaCompressedIndexBlock(ICIndexStorageConstants.BLOCK_SIZE); - firstInBlock= true; - firstIncludeIndexBlock= false; - } - if (entry.getNumRefs() == 0) - return; - if (includeIndexBlock.addIncludeEntry(entry)) { - if (firstInBlock) { - summary.addFirstIncludeInBlock(entry.getFile(), blockNum); - firstInBlock= false; - } - numIncludes++; - } else { - if (includeIndexBlock.isEmpty()) { - return; - } - flushIncludes(); - addInclude(entry); - } - } - /** - * @see IndexOutput#close - */ - public void close() throws IOException { - if (opened) { - indexOut.close(); - summary= null; - numFiles= 0; - opened= false; - } - } - /** - * @see IndexOutput#flush - */ - public void flush() throws IOException { - - summary.setNumFiles(numFiles); - summary.setNumWords(numWords); - summary.setNumIncludes(numIncludes); - indexOut.seek(blockNum * (long) ICIndexStorageConstants.BLOCK_SIZE); - summary.write(indexOut); - indexOut.seek(0); - indexOut.writeUTF(ICIndexStorageConstants.SIGNATURE); - indexOut.writeInt(blockNum); - } - /** - * Writes the current fileListBlock on the disk and initialises it - * (when it's full or it's the end of the index). - */ - protected void flushFiles() throws IOException { - if (!firstFileListBlock - && fileListBlock != null) { - fileListBlock.flush(); - fileListBlock.write(indexOut, blockNum++); - fileListBlock.clear(); - firstInBlock= true; - } - } - /** - * Writes the current indexBlock on the disk and initialises it - * (when it's full or it's the end of the index). - */ - protected void flushWords() throws IOException { - if (!firstInBlock - && indexBlock != null) { // could have added a document without any indexed word, no block created yet - indexBlock.flush(); - indexBlock.write(indexOut, blockNum++); - indexBlock.clear(); - firstInBlock= true; - } - } - /** - * - */ - protected void flushIncludes() throws IOException { - if (!firstInBlock - && includeIndexBlock != null) { // could have added a document without any indexed word, no block created yet - includeIndexBlock.flush(); - includeIndexBlock.write(indexOut, blockNum++); - includeIndexBlock.clear(); - firstInBlock= true; - } - - } - /** - * @see IndexOutput#getDestination - */ - public Object getDestination() { - return indexFile; - } - /** - * @see IndexOutput#open - */ - public void open() throws IOException { - if (!opened) { - summary= new IndexSummary(); - numFiles= 0; - numWords= 0; - numIncludes=0; - blockNum= 1; - firstInBlock= true; - firstIndexBlock= true; - firstFileListBlock= true; - firstIncludeIndexBlock=true; - indexOut= new SafeRandomAccessFile(this.indexFile, "rw"); //$NON-NLS-1$ - opened= true; - } - } -} diff --git a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/cindexstorage/io/CodeByteStream.java b/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/cindexstorage/io/CodeByteStream.java deleted file mode 100644 index 5b809a24102..00000000000 --- a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/cindexstorage/io/CodeByteStream.java +++ /dev/null @@ -1,343 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.core.index.cindexstorage.io; - -import java.io.UTFDataFormatException; - -public class CodeByteStream { - protected byte[] bytes; - protected int byteOffset= 0; - protected int bitOffset= 0; - protected int markByteOffset= -1; - protected int markBitOffset= -1; - - public CodeByteStream() { - this(16); - } - public CodeByteStream(byte[] bytes) { - this.bytes= bytes; - } - public CodeByteStream(int initialByteLength) { - bytes= new byte[initialByteLength]; - } - public int byteLength() { - return (bitOffset + 7) / 8 + byteOffset; - } - public byte[] getBytes(int startOffset, int endOffset) { - int byteLength= byteLength(); - if (startOffset > byteLength || endOffset > byteLength || startOffset > endOffset) - throw new IndexOutOfBoundsException(); - int length= endOffset - startOffset; - byte[] result= new byte[length]; - System.arraycopy(bytes, startOffset, result, 0, length); - if (endOffset == byteLength && bitOffset != 0) { - int mask= (1 << bitOffset) - 1; - result[length - 1] &= (mask << 8 - bitOffset); - } - return result; - } - protected void grow() { - byte[] newBytes= new byte[bytes.length * 2 + 1]; - System.arraycopy(bytes, 0, newBytes, 0, bytes.length); - bytes= newBytes; - } - public void mark() { - markByteOffset= byteOffset; - markBitOffset= bitOffset; - } - /** - * Reads a single bit (value == 0 or == 1). - */ - public int readBit() { - int value= (bytes[byteOffset] >> (7 - bitOffset)) & 1; - if (++bitOffset >= 8) { - bitOffset= 0; - ++byteOffset; - } - return value; - } - /** - * Read up to 32 bits from the stream. - */ - public int readBits(int numBits) { - int value= 0; - while (numBits > 0) { - int bitsToRead= 8 - bitOffset; - if (bitsToRead > numBits) - bitsToRead= numBits; - int mask= (1 << bitsToRead) - 1; - value |= ((bytes[byteOffset] >> (8 - bitOffset - bitsToRead)) & mask) << (numBits - bitsToRead); - numBits -= bitsToRead; - bitOffset += bitsToRead; - if (bitOffset >= 8) { - bitOffset -= 8; - byteOffset += 1; - } - } - return value; - } - public final int readByte() { - - // no need to rebuild byte value from bit sequences - if (bitOffset == 0) return bytes[byteOffset++] & 255; - - int value= 0; - int numBits = 8; - while (numBits > 0) { - int bitsToRead= 8 - bitOffset; - if (bitsToRead > numBits) - bitsToRead= numBits; - int mask= (1 << bitsToRead) - 1; - value |= ((bytes[byteOffset] >> (8 - bitOffset - bitsToRead)) & mask) << (numBits - bitsToRead); - numBits -= bitsToRead; - bitOffset += bitsToRead; - if (bitOffset >= 8) { - bitOffset -= 8; - byteOffset += 1; - } - } - return value; - } - /** - * Reads a value using Gamma coding. - */ - public int readGamma() { - int numBits= readUnary(); - return readBits(numBits - 1) | (1 << (numBits - 1)); - } - public char[] readUTF() throws UTFDataFormatException { - int utflen= readByte(); - if (utflen == 255) { - // long UTF - int high = readByte(); - int low = readByte(); - utflen = (high << 8) + low; - } - char str[]= new char[utflen]; - int count= 0; - int strlen= 0; - while (count < utflen) { - int c= readByte(); - int char2, char3; - switch (c >> 4) { - case 0 : - case 1 : - case 2 : - case 3 : - case 4 : - case 5 : - case 6 : - case 7 : - // 0xxxxxxx - count++; - str[strlen++]= (char) c; - break; - case 12 : - case 13 : - // 110x xxxx 10xx xxxx - count += 2; - if (count > utflen) - throw new UTFDataFormatException(); - char2= readByte(); - if ((char2 & 0xC0) != 0x80) - throw new UTFDataFormatException(); - str[strlen++]= (char) (((c & 0x1F) << 6) | (char2 & 0x3F)); - break; - case 14 : - // 1110 xxxx 10xx xxxx 10xx xxxx - count += 3; - if (count > utflen) - throw new UTFDataFormatException(); - char2= readByte(); - char3= readByte(); - if (((char2 & 0xC0) != 0x80) || ((char3 & 0xC0) != 0x80)) - throw new UTFDataFormatException(); - str[strlen++]= (char) (((c & 0x0F) << 12) | ((char2 & 0x3F) << 6) | ((char3 & 0x3F) << 0)); - break; - default : - // 10xx xxxx, 1111 xxxx - throw new UTFDataFormatException(); - } - } - if (strlen < utflen) - System.arraycopy(str, 0, str= new char[strlen], 0, strlen); - return str; - } - /** - * Reads a value in unary. - */ - public int readUnary() { - int value= 1; - int mask= 1 << (7 - bitOffset); - while ((bytes[byteOffset] & mask) != 0) { - ++value; - if (++bitOffset >= 8) { - bitOffset= 0; - ++byteOffset; - mask= 0x80; - } else { - mask >>>= 1; - } - } - // skip the 0 bit - if (++bitOffset >= 8) { - bitOffset= 0; - ++byteOffset; - } - return value; - } - public void reset() { - byteOffset= bitOffset= 0; - markByteOffset= markBitOffset= -1; - } - public void reset(byte[] bytes) { - this.bytes= bytes; - reset(); - } - public void reset(byte[] bytes, int byteOffset) { - reset(bytes); - this.byteOffset= byteOffset; - } - public boolean resetToMark() { - if (markByteOffset == -1) - return false; - byteOffset= markByteOffset; - bitOffset= markBitOffset; - markByteOffset= markBitOffset= -1; - return true; - } - public void skipBits(int numBits) { - int newOffset= byteOffset * 8 + bitOffset + numBits; - if (newOffset < 0 || (newOffset + 7) / 8 >= bytes.length) - throw new IllegalArgumentException(); - byteOffset= newOffset / 8; - bitOffset= newOffset % 8; - } - public byte[] toByteArray() { - return getBytes(0, byteLength()); - } - /** - * Writes a single bit (value == 0 or == 1). - */ - public void writeBit(int value) { - bytes[byteOffset] |= (value & 1) << (7 - bitOffset); - if (++bitOffset >= 8) { - bitOffset= 0; - if (++byteOffset >= bytes.length) - grow(); - } - } - /** - * Write up to 32 bits to the stream. - * The least significant numBits bits of value are written. - */ - public void writeBits(int value, int numBits) { - while (numBits > 0) { - int bitsToWrite= 8 - bitOffset; - if (bitsToWrite > numBits) - bitsToWrite= numBits; - int shift= 8 - bitOffset - bitsToWrite; - int mask= ((1 << bitsToWrite) - 1) << shift; - bytes[byteOffset]= (byte) ((bytes[byteOffset] & ~mask) | (((value >>> (numBits - bitsToWrite)) << shift) & mask)); - numBits -= bitsToWrite; - bitOffset += bitsToWrite; - if (bitOffset >= 8) { - bitOffset -= 8; - if (++byteOffset >= bytes.length) - grow(); - } - } - } - public void writeByte(int value) { - writeBits(value, 8); - } - /** - * Writes the given value using Gamma coding, in which positive integer x - * is represented by coding floor(log2(x) in unary followed by the value - * of x - 2**floor(log2(x)) in binary. - * The value must be >= 1. - */ - public void writeGamma(int value) { - if (value < 1) - throw new IllegalArgumentException(); - int temp= value; - int numBits= 0; - while (temp != 0) { - temp >>>= 1; - ++numBits; - } - writeUnary(numBits); - writeBits(value, numBits - 1); - } - public void writeUTF(char[] str, int start, int end) { - int utflen= 0; - for (int i= start; i < end; i++) { - int c= str[i]; - if ((c >= 0x0001) && (c <= 0x007F)) { - utflen++; - } else if (c > 0x07FF) { - utflen += 3; - } else { - utflen += 2; - } - } - if (utflen < 255) { - writeByte(utflen & 0xFF); - } else if (utflen > 65535) { - throw new IllegalArgumentException(); - } else { - writeByte(255); // marker for long UTF - writeByte((utflen >>> 8) & 0xFF); // high byte - writeByte((utflen >>> 0) & 0xFF); // low byte - } - for (int i= start; i < end; i++) { - int c= str[i]; - if ((c >= 0x0001) && (c <= 0x007F)) { - writeByte(c); - } else if (c > 0x07FF) { - writeByte(0xE0 | ((c >> 12) & 0x0F)); - writeByte(0x80 | ((c >> 6) & 0x3F)); - writeByte(0x80 | ((c >> 0) & 0x3F)); - } else { - writeByte(0xC0 | ((c >> 6) & 0x1F)); - writeByte(0x80 | ((c >> 0) & 0x3F)); - } - } - } - /** - * Write the given value in unary. The value must be >= 1. - */ - public void writeUnary(int value) { - if (value < 1) - throw new IllegalArgumentException(); - int mask= 1 << (7 - bitOffset); - // write N-1 1-bits - while (--value > 0) { - bytes[byteOffset] |= mask; - if (++bitOffset >= 8) { - bitOffset= 0; - if (++byteOffset >= bytes.length) - grow(); - mask= 0x80; - } else { - mask >>>= 1; - } - } - // write a 0-bit - bytes[byteOffset] &= ~mask; - if (++bitOffset >= 8) { - bitOffset= 0; - if (++byteOffset >= bytes.length) - grow(); - } - } -} - diff --git a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/cindexstorage/io/Field.java b/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/cindexstorage/io/Field.java deleted file mode 100644 index 02a679c7b20..00000000000 --- a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/cindexstorage/io/Field.java +++ /dev/null @@ -1,381 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.core.index.cindexstorage.io; - -import java.io.UTFDataFormatException; - -public class Field { - protected byte[] buffer; // contents - protected int offset; // offset of the field within the byte array - protected int length; // length of the field - - /** - * ByteSegment constructor comment. - */ - public Field(byte[] bytes) { - this.buffer= bytes; - this.offset= 0; - this.length= bytes.length; - } - /** - * ByteSegment constructor comment. - */ - public Field(byte[] bytes, int length) { - this.buffer= bytes; - this.offset= 0; - this.length= length; - } - /** - * ByteSegment constructor comment. - */ - public Field(byte[] bytes, int offset, int length) { - this.buffer= bytes; - this.offset= offset; - this.length= length; - } - /** - * Creates a new field containing an empty buffer of the given length. - */ - public Field(int length) { - this.buffer= new byte[length]; - this.offset= 0; - this.length= length; - } - public byte[] buffer() { - return buffer; - } - public Field buffer(byte[] buffer) { - this.buffer= buffer; - return this; - } - public Field clear() { - clear(buffer, offset, length); - return this; - } - protected static void clear(byte[] buffer, int offset, int length) { - int n= offset; - for (int i= 0; i < length; i++) { - buffer[n]= 0; - n++; - } - } - public Field clear(int length) { - clear(buffer, offset, length); - return this; - } - public Field clear(int offset, int length) { - clear(buffer, this.offset + offset, length); - return this; - } - protected static int compare(byte[] buffer1, int offset1, int length1, byte[] buffer2, int offset2, int length2) { - int n= Math.min(length1, length2); - for (int i= 0; i < n; i++) { - int j1= buffer1[offset1 + i] & 255; - int j2= buffer2[offset2 + i] & 255; - if (j1 > j2) - return 1; - if (j1 < j2) - return -1; - } - if (length1 > n) { - for (int i= n; i < length1; i++) - if (buffer1[offset1 + i] != 0) - return 1; - return 0; - } - for (int i= n; i < length2; i++) - if (buffer2[offset2 + i] != 0) - return -1; - return 0; - } - public static int compare(Field f1, Field f2) { - return compare(f1.buffer, f1.offset, f1.length, f2.buffer, f2.offset, f2.length); - } - // copy bytes from one offset to another within the field - public Field copy(int fromOffset, int toOffset, int length) { - System.arraycopy(buffer, offset + fromOffset, buffer, offset + toOffset, length); - return this; - } - public Field dec(int n) { - offset -= n; - return this; - } - public byte[] get() { - byte[] result= new byte[length]; - System.arraycopy(buffer, offset, result, 0, length); - return result; - } - public byte[] get(int offset, int length) { - byte[] result= new byte[length]; - System.arraycopy(buffer, this.offset + offset, result, 0, length); - return result; - } - public Field getField(int offset, int length) { - return new Field(buffer, this.offset + offset, length); - } - public int getInt1() { - return buffer[this.offset]; - } - public int getInt1(int offset) { - return buffer[this.offset + offset]; - } - public int getInt2() { - int i= this.offset; - int v= buffer[i++]; - v= (v << 8) | (buffer[i++] & 255); - return v; - } - public int getInt2(int offset) { - int i= this.offset + offset; - int v= buffer[i++]; - v= (v << 8) | (buffer[i++] & 255); - return v; - } - public int getInt3() { - int i= this.offset; - int v= buffer[i++]; - v= (v << 8) | (buffer[i++] & 255); - v= (v << 8) | (buffer[i++] & 255); - return v; - } - public int getInt3(int offset) { - int i= this.offset + offset; - int v= buffer[i++]; - v= (v << 8) | (buffer[i++] & 255); - v= (v << 8) | (buffer[i++] & 255); - return v; - } - public int getInt4() { - int i= this.offset; - int v= buffer[i++]; - v= (v << 8) | (buffer[i++] & 255); - v= (v << 8) | (buffer[i++] & 255); - v= (v << 8) | (buffer[i++] & 255); - return v; - } - public int getInt4(int offset) { - int i= this.offset + offset; - int v= buffer[i++]; - v= (v << 8) | (buffer[i++] & 255); - v= (v << 8) | (buffer[i++] & 255); - v= (v << 8) | (buffer[i++] & 255); - return v; - } - public int getUInt1() { - return buffer[this.offset] & 255; - } - public int getUInt1(int offset) { - return buffer[this.offset + offset] & 255; - } - public int getUInt2() { - int i= this.offset; - int v= (buffer[i++] & 255); - v= (v << 8) | (buffer[i++] & 255); - return v; - } - public int getUInt2(int offset) { - int i= this.offset + offset; - int v= (buffer[i++] & 255); - v= (v << 8) | (buffer[i++] & 255); - return v; - } - public int getUInt3() { - int i= this.offset; - int v= (buffer[i++] & 255); - v= (v << 8) | (buffer[i++] & 255); - v= (v << 8) | (buffer[i++] & 255); - return v; - } - public int getUInt3(int offset) { - int i= this.offset + offset; - int v= (buffer[i++] & 255); - v= (v << 8) | (buffer[i++] & 255); - v= (v << 8) | (buffer[i++] & 255); - return v; - } - public char[] getUTF(int offset) throws UTFDataFormatException { - int pos= this.offset + offset; - int utflen= getUInt2(pos); - pos += 2; - char str[]= new char[utflen]; - int count= 0; - int strlen= 0; - while (count < utflen) { - int c= buffer[pos++] & 0xFF; - int char2, char3; - switch (c >> 4) { - case 0 : - case 1 : - case 2 : - case 3 : - case 4 : - case 5 : - case 6 : - case 7 : - // 0xxxxxxx - count++; - str[strlen++]= (char) c; - break; - case 12 : - case 13 : - // 110x xxxx 10xx xxxx - count += 2; - if (count > utflen) - throw new UTFDataFormatException(); - char2= buffer[pos++] & 0xFF; - if ((char2 & 0xC0) != 0x80) - throw new UTFDataFormatException(); - str[strlen++]= (char) (((c & 0x1F) << 6) | (char2 & 0x3F)); - break; - case 14 : - // 1110 xxxx 10xx xxxx 10xx xxxx - count += 3; - if (count > utflen) - throw new UTFDataFormatException(); - char2= buffer[pos++] & 0xFF; - char3= buffer[pos++] & 0xFF; - if (((char2 & 0xC0) != 0x80) || ((char3 & 0xC0) != 0x80)) - throw new UTFDataFormatException(); - str[strlen++]= (char) (((c & 0x0F) << 12) | ((char2 & 0x3F) << 6) | ((char3 & 0x3F) << 0)); - break; - default : - // 10xx xxxx, 1111 xxxx - throw new UTFDataFormatException(); - } - } - if (strlen < utflen) - System.arraycopy(str, 0, str= new char[strlen], 0, strlen); - return str; - } - public Field inc(int n) { - offset += n; - return this; - } - public int length() { - return length; - } - public Field length(int length) { - this.length= length; - return this; - } - /** - Returns the offset into the underlying byte array that this field is defined over. - */ - public int offset() { - return offset; - } - public Field offset(int offset) { - this.offset= offset; - return this; - } - public Field pointTo(int offset) { - return new Field(buffer, this.offset + offset, 0); - } - public Field put(byte[] b) { - return put(0, b); - } - public Field put(int offset, byte[] b) { - System.arraycopy(b, 0, buffer, this.offset + offset, b.length); - return this; - } - public Field put(int offset, Field f) { - System.arraycopy(f.buffer, f.offset, buffer, this.offset + offset, f.length); - return this; - } - public Field put(Field f) { - System.arraycopy(f.buffer, f.offset, buffer, offset, f.length); - return this; - } - public Field putInt1(int n) { - buffer[offset]= (byte) (n); - return this; - } - public Field putInt1(int offset, int n) { - buffer[this.offset + offset]= (byte) (n); - return this; - } - public Field putInt2(int n) { - int i= offset; - buffer[i++]= (byte) (n >> 8); - buffer[i++]= (byte) (n >> 0); - return this; - } - public Field putInt2(int offset, int n) { - int i= this.offset + offset; - buffer[i++]= (byte) (n >> 8); - buffer[i++]= (byte) (n >> 0); - return this; - } - public Field putInt3(int n) { - int i= offset; - buffer[i++]= (byte) (n >> 16); - buffer[i++]= (byte) (n >> 8); - buffer[i++]= (byte) (n >> 0); - return this; - } - public Field putInt3(int offset, int n) { - int i= this.offset + offset; - buffer[i++]= (byte) (n >> 16); - buffer[i++]= (byte) (n >> 8); - buffer[i++]= (byte) (n >> 0); - return this; - } - public Field putInt4(int n) { - int i= offset; - buffer[i++]= (byte) (n >> 24); - buffer[i++]= (byte) (n >> 16); - buffer[i++]= (byte) (n >> 8); - buffer[i++]= (byte) (n >> 0); - return this; - } - public Field putInt4(int offset, int n) { - int i= this.offset + offset; - buffer[i++]= (byte) (n >> 24); - buffer[i++]= (byte) (n >> 16); - buffer[i++]= (byte) (n >> 8); - buffer[i++]= (byte) (n >> 0); - return this; - } - public int putUTF(int offset, char[] str) { - int strlen= str.length; - int utflen= 0; - for (int i= 0; i < strlen; i++) { - int c= str[i]; - if ((c >= 0x0001) && (c <= 0x007F)) { - utflen++; - } else if (c > 0x07FF) { - utflen += 3; - } else { - utflen += 2; - } - } - if (utflen > 65535) - throw new IllegalArgumentException(); - int pos= this.offset + offset; - buffer[pos++]= (byte) ((utflen >>> 8) & 0xFF); - buffer[pos++]= (byte) ((utflen >>> 0) & 0xFF); - for (int i= 0; i < strlen; i++) { - int c= str[i]; - if ((c >= 0x0001) && (c <= 0x007F)) { - buffer[pos++]= ((byte) c); - } else if (c > 0x07FF) { - buffer[pos++]= ((byte) (0xE0 | ((c >> 12) & 0x0F))); - buffer[pos++]= ((byte) (0x80 | ((c >> 6) & 0x3F))); - buffer[pos++]= ((byte) (0x80 | ((c >> 0) & 0x3F))); - } else { - buffer[pos++]= ((byte) (0xC0 | ((c >> 6) & 0x1F))); - buffer[pos++]= ((byte) (0x80 | ((c >> 0) & 0x3F))); - } - } - return 2 + utflen; - } -} - diff --git a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/cindexstorage/io/FileListBlock.java b/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/cindexstorage/io/FileListBlock.java deleted file mode 100644 index 8c63b5a4b10..00000000000 --- a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/cindexstorage/io/FileListBlock.java +++ /dev/null @@ -1,116 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.core.index.cindexstorage.io; - -import java.io.IOException; -import java.util.ArrayList; - -import org.eclipse.cdt.internal.core.index.cindexstorage.IndexedFileEntry; -import org.eclipse.cdt.internal.core.index.cindexstorage.Util; - -public class FileListBlock extends Block { - - protected int offset= 0; - protected String prevPath= null; - protected String[] paths= null; - - public FileListBlock(int blockSize) { - super(blockSize); - } - /** - * add the name of the indexedfile to the buffr of the field. - * The name is not the entire name of the indexedfile, but the - * difference between its name and the name of the previous indexedfile ... - */ - public boolean addFile(IndexedFileEntry indexedFile) { - int offset= this.offset; - if (isEmpty()) { - field.putInt4(offset, indexedFile.getFileID()); - offset += 4; - } - String path= indexedFile.getPath(); - int prefixLen= prevPath == null ? 0 : Util.prefixLength(prevPath, path); - int sizeEstimate= 2 + 2 + (path.length() - prefixLen) * 3; - if (offset + sizeEstimate > blockSize - 2) - return false; - field.putInt2(offset, prefixLen); - offset += 2; - char[] chars= new char[path.length() - prefixLen]; - path.getChars(prefixLen, path.length(), chars, 0); - offset += field.putUTF(offset, chars); - this.offset= offset; - prevPath= path; - return true; - } - public void clear() { - reset(); - super.clear(); - } - public void flush() { - if (offset > 0) { - field.putInt2(offset, 0); - field.putInt2(offset + 2, 0); - offset= 0; - } - } - public IndexedFileEntry getFile(int fileNum) throws IOException { - IndexedFileEntry resp= null; - try { - String[] paths= getPaths(); - int i= fileNum - field.getInt4(0); - if(i >= paths.length) { //fileNum was too large - return null; - } - resp= new IndexedFileEntry(paths[i], fileNum); - } catch (Exception e) { - //Cover ourselves in case something happens getting the indexed file - } - return resp; - } - /** - * Creates a vector of paths reading the buffer of the field. - */ - protected String[] getPaths() throws IOException { - if (paths == null) { - ArrayList v= new ArrayList(); - int offset= 4; - char[] prevPath= null; - for (;;) { - int prefixLen= field.getUInt2(offset); - offset += 2; - int utfLen= field.getUInt2(offset); - char[] path= field.getUTF(offset); - offset += 2 + utfLen; - if (prefixLen != 0) { - char[] temp= new char[prefixLen + path.length]; - System.arraycopy(prevPath, 0, temp, 0, prefixLen); - System.arraycopy(path, 0, temp, prefixLen, path.length); - path= temp; - } - if (path.length == 0) - break; - v.add(new String(path)); - prevPath= path; - } - paths= new String[v.size()]; - v.toArray(paths); - } - return paths; - } - public boolean isEmpty() { - return offset == 0; - } - public void reset() { - offset= 0; - prevPath= null; - } -} - diff --git a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/cindexstorage/io/GammaCompressedIndexBlock.java b/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/cindexstorage/io/GammaCompressedIndexBlock.java deleted file mode 100644 index 0adfe0855b0..00000000000 --- a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/cindexstorage/io/GammaCompressedIndexBlock.java +++ /dev/null @@ -1,260 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.core.index.cindexstorage.io; - -import java.io.UTFDataFormatException; - -import org.eclipse.cdt.internal.core.index.cindexstorage.IncludeEntry; -import org.eclipse.cdt.internal.core.index.cindexstorage.Util; -import org.eclipse.cdt.internal.core.index.cindexstorage.WordEntry; - -/** - * Uses prefix coding on words, and gamma coding of document numbers differences. - */ -public class GammaCompressedIndexBlock extends IndexBlock { - CodeByteStream writeCodeStream= new CodeByteStream(); - CodeByteStream readCodeStream; - char[] prevWord= null; - int offset= 0; - - public GammaCompressedIndexBlock(int blockSize) { - super(blockSize); - readCodeStream= new CodeByteStream(field.buffer()); - } - /** - * @see IndexBlock#addEntry - */ - public boolean addEntry(WordEntry entry) { - writeCodeStream.reset(); - encodeEntry(entry, prevWord, writeCodeStream); - if (offset + writeCodeStream.byteLength() > this.blockSize - 2) { - return false; - } - byte[] bytes= writeCodeStream.toByteArray(); - field.put(offset, bytes); - offset += bytes.length; - prevWord= entry.getWord(); - return true; - } - protected void encodeEntry(WordEntry entry, char[] prevWord, CodeByteStream codeStream) { - char[] word= entry.getWord(); - int prefixLen= prevWord == null ? 0 : Util.prefixLength(prevWord, word); - codeStream.writeByte(prefixLen); - codeStream.writeUTF(word, prefixLen, word.length); - int n= entry.getNumRefs(); - codeStream.writeGamma(n); - //encode file references - int prevRef= 0; - for (int i= 0; i < n; ++i) { - int ref= entry.getRef(i); - if (ref <= prevRef) - throw new IllegalArgumentException(); - codeStream.writeGamma(ref - prevRef); - prevRef= ref; - } - //encode offsets - //same number of offsets arrays as file references - for (int i=0; i this.blockSize - 2) { - return false; - } - byte[] bytes= writeCodeStream.toByteArray(); - field.put(offset, bytes); - offset += bytes.length; - prevWord= entry.getFile(); - return true; - } - /** - * @param entry - * @param prevWord - * @param writeCodeStream - */ - protected void encodeEntry(IncludeEntry entry, char[] prevWord, CodeByteStream codeStream) { - char[] file= entry.getFile(); - int prefixLen= prevWord == null ? 0 : Util.prefixLength(prevWord, file); - codeStream.writeByte(prefixLen); - codeStream.writeUTF(file, prefixLen, file.length); - int n= entry.getNumRefs(); - codeStream.writeGamma(n); - int prevRef= 0; - for (int i= 0; i < n; ++i) { - int ref= entry.getRef(i); - if (ref <= prevRef) - throw new IllegalArgumentException(); - codeStream.writeGamma(ref - prevRef); - prevRef= ref; - } - - } - /** - * @see IndexBlock#flush - */ - public void flush() { - if (offset > 0) { - field.putInt2(offset, 0); - offset= 0; - prevWord= null; - } - } - /** - * @see IndexBlock#isEmpty - */ - public boolean isEmpty() { - return offset == 0; - } - /** - * @see IndexBlock#nextEntry - */ - public boolean nextEntry(WordEntry entry) { - try { - readCodeStream.reset(field.buffer(), offset); - int prefixLength= readCodeStream.readByte(); - char[] word= readCodeStream.readUTF(); - if (prevWord != null && prefixLength > 0) { - char[] temp= new char[prefixLength + word.length]; - System.arraycopy(prevWord, 0, temp, 0, prefixLength); - System.arraycopy(word, 0, temp, prefixLength, word.length); - word= temp; - } - if (word.length == 0) { - return false; - } - entry.reset(word); - int n= readCodeStream.readGamma(); - int prevRef= 0; - for (int i= 0; i < n; ++i) { - int ref= prevRef + readCodeStream.readGamma(); - if (ref < prevRef) - throw new InternalError(); - entry.addRef(ref); - prevRef= ref; - } - - - for (int i=0; i 0) { - char[] temp= new char[prefixLength + file.length]; - System.arraycopy(prevWord, 0, temp, 0, prefixLength); - System.arraycopy(file, 0, temp, prefixLength, file.length); - file= temp; - } - if (file.length == 0) { - return false; - } - entry.reset(file); - int n= readCodeStream.readGamma(); - int prevRef= 0; - for (int i= 0; i < n; ++i) { - int ref= prevRef + readCodeStream.readGamma(); - if (ref < prevRef) - throw new InternalError(); - entry.addRef(ref); - prevRef= ref; - } - offset= readCodeStream.byteLength(); - prevWord= file; - return true; - } catch (UTFDataFormatException e) { - return false; - } - } - /** - * @see IndexBlock#reset - */ - public void reset() { - super.reset(); - offset= 0; - prevWord= null; - } - -} - diff --git a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/cindexstorage/io/IndexBlock.java b/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/cindexstorage/io/IndexBlock.java deleted file mode 100644 index 1e3a18af2a9..00000000000 --- a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/cindexstorage/io/IndexBlock.java +++ /dev/null @@ -1,83 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.core.index.cindexstorage.io; - -import org.eclipse.cdt.internal.core.CharOperation; -import org.eclipse.cdt.internal.core.index.cindexstorage.IncludeEntry; -import org.eclipse.cdt.internal.core.index.cindexstorage.WordEntry; - -/** - * An indexBlock stores wordEntries. - */ -public abstract class IndexBlock extends Block { - - public IndexBlock(int blockSize) { - super(blockSize); - } - /** - * Adds the given wordEntry to the indexBlock. - */ - public abstract boolean addEntry(WordEntry entry); - /** - * Adds the given wordEntry to the indexBlock. - */ - public abstract boolean addIncludeEntry(IncludeEntry entry); - /** - * @see Block#clear() - */ - public void clear() { - reset(); - super.clear(); - } - public WordEntry findEntryMatching(char[] pattern, boolean isCaseSensitive) { - reset(); - WordEntry entry= new WordEntry(); - while (nextEntry(entry)) { - if (CharOperation.match(pattern, entry.getWord(), isCaseSensitive)) { - return entry; - } - } - return null; - } - public WordEntry findEntryPrefixedBy(char[] word, boolean isCaseSensitive) { - reset(); - WordEntry entry= new WordEntry(); - while (nextEntry(entry)) { - if (CharOperation.prefixEquals(entry.getWord(), word, isCaseSensitive)) { - return entry; - } - } - return null; - } - public WordEntry findExactEntry(char[] word) { - reset(); - WordEntry entry= new WordEntry(); - while (nextEntry(entry)) { - if (CharOperation.equals(entry.getWord(), word)) { - return entry; - } - } - return null; - } - /** - * Returns whether the block is empty or not (if it doesn't contain any wordEntry). - */ - public abstract boolean isEmpty(); - /** - * Finds the next wordEntry and stores it in the given entry. - */ - public abstract boolean nextEntry(WordEntry entry); - public abstract boolean nextEntry(IncludeEntry entry); - - public void reset() { - } - -} diff --git a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/cindexstorage/io/IndexInput.java b/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/cindexstorage/io/IndexInput.java deleted file mode 100644 index acb2bff7291..00000000000 --- a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/cindexstorage/io/IndexInput.java +++ /dev/null @@ -1,173 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.core.index.cindexstorage.io; - -import java.io.IOException; - -import org.eclipse.cdt.internal.core.index.IEntryResult; -import org.eclipse.cdt.internal.core.index.IQueryResult; -import org.eclipse.cdt.internal.core.index.cindexstorage.IncludeEntry; -import org.eclipse.cdt.internal.core.index.cindexstorage.IndexedFileEntry; -import org.eclipse.cdt.internal.core.index.cindexstorage.WordEntry; - - -/** - * This class provides an input on an index, after it has been generated. - * You can access all the files of an index via getNextFile(), getCurrentFile() - * and moveToNextFile() (idem for the word entries). - * The usage is the same for every subclass: creation (constructor), opening - * (the open() method), usage, and closing (the close() method), to release the - * data source used by this input. - */ -public abstract class IndexInput { - protected int filePosition; - protected WordEntry currentWordEntry; - protected int wordPosition; - protected IncludeEntry currentIncludeEntry; - protected int includePosition; - - public IndexInput() { - super(); - wordPosition= 1; - filePosition= 1; - includePosition= 1; - } - /** - * clears the cache of this indexInput, if it keeps track of the information already read. - */ - public abstract void clearCache(); - /** - * Closes the IndexInput. For example, if the input is on a RandomAccessFile, - * it calls the close() method of RandomAccessFile. - */ - public abstract void close() throws IOException; - /** - * Returns the current file the indexInput is pointing to in the index. - */ - public abstract IndexedFileEntry getCurrentFile() throws IOException; - /** - * Returns the current file the indexInput is pointing to in the index. - */ - public WordEntry getCurrentWordEntry() throws IOException { - if (!hasMoreWords()) - return null; - return currentWordEntry; - } - /** - * Returns the current file the indexInput is pointing to in the index. - */ - public IncludeEntry getCurrentIncludeEntry() throws IOException { - if (!hasMoreIncludes()) - return null; - return currentIncludeEntry; - } - /** - * Returns the position of the current file the input is pointing to in the index. - */ - public int getFilePosition() { - return filePosition; - } - /** - * Returns the indexedFile corresponding to the given document number in the index the input - * reads in, or null if such indexedFile does not exist. - */ - public abstract IndexedFileEntry getIndexedFile(int fileNum) throws IOException; - /** - * Returns the indexedFile corresponding to the given file path in the index the input - * reads in (e.g. the indexedFile with the same path in this index), or null if such - * indexedFile does not exist. - */ - public abstract IndexedFileEntry getIndexedFile(String fullpath) throws IOException; - /** - * Returns the number of files in the index. - */ - public abstract int getNumFiles(); - /** - * Returns the number of unique words in the index. - */ - public abstract int getNumWords(); - /** - * Returns the number of unique words in the index. - */ - public abstract int getNumIncludes(); - /** - * Returns the Object the input is reading from. It can be an IIndex, - * a File, ... - */ - public abstract Object getSource(); - /** - * Returns true if the input has not reached the end of the index for the files. - */ - public boolean hasMoreFiles() { - return getFilePosition() <= getNumFiles(); - } - /** - * Returns true if the input has not reached the end of the index for the files. - */ - public boolean hasMoreWords() { - return wordPosition <= getNumWords(); - } - /** - * Returns true if the input has not reached the end of the index for the files. - */ - public boolean hasMoreIncludes() { - return includePosition <= getNumIncludes(); - } - /** - * Moves the pointer on the current file to the next file in the index. - */ - public abstract void moveToNextFile() throws IOException; - /** - * Moves the pointer on the current word to the next file in the index. - */ - public abstract void moveToNextWordEntry() throws IOException; - /** - * Moves the pointer on the current include entry to the next file in the index. - */ - public abstract void moveToNextIncludeEntry() throws IOException; - /** - * Open the Source where the input gets the information from. - */ - public abstract void open() throws IOException; - /** - * Returns the list of the files containing the given word in the index. - */ - public abstract IQueryResult[] query(String word) throws IOException; - public abstract IEntryResult[] queryEntriesPrefixedBy(char[] prefix) throws IOException; - public abstract IQueryResult[] queryFilesReferringToPrefix(char[] prefix) throws IOException; - /** - * Returns the list of the files whose name contain the given word in the index. - */ - public abstract IQueryResult[] queryInDocumentNames(String word) throws IOException; - /** - * Returns the list of the files whose name contain the given word in the index. - */ - public abstract IncludeEntry[] queryIncludeEntries(); - /** - * @param fileNum - * @return - */ - public abstract IncludeEntry[] queryIncludeEntries(int fileNum) throws IOException; - /** - * Set the pointer on the current file to the first file of the index. - */ - protected abstract void setFirstFile() throws IOException; - /** - * Set the pointer on the current word to the first word of the index. - */ - protected abstract void setFirstWord() throws IOException; - /** - * Set the pointer on the current include to the first include of the index. - */ - protected abstract void setFirstInclude() throws IOException; - - -} diff --git a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/cindexstorage/io/IndexOutput.java b/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/cindexstorage/io/IndexOutput.java deleted file mode 100644 index 9d8c284a0ac..00000000000 --- a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/cindexstorage/io/IndexOutput.java +++ /dev/null @@ -1,46 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.core.index.cindexstorage.io; - -import java.io.IOException; - -import org.eclipse.cdt.internal.core.index.cindexstorage.IndexedFileEntry; -import org.eclipse.cdt.internal.core.index.cindexstorage.WordEntry; - -/** - * An indexOutput is used to write an index into a different object (a File, ...). - */ -public abstract class IndexOutput { - /** - * Adds a File to the destination. - */ - public abstract void addFile(IndexedFileEntry file) throws IOException; - /** - * Adds a word to the destination. - */ - public abstract void addWord(WordEntry word) throws IOException; - /** - * Closes the output, releasing the resources it was using. - */ - public abstract void close() throws IOException; - /** - * Flushes the output. - */ - public abstract void flush() throws IOException; - /** - * Returns the Object the output is writing to. It can be a file, another type of index, ... - */ - public abstract Object getDestination(); - /** - * Opens the output, before writing any information. - */ - public abstract void open() throws IOException; -} diff --git a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/cindexstorage/io/IndexSummary.java b/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/cindexstorage/io/IndexSummary.java deleted file mode 100644 index b88ebf15e3e..00000000000 --- a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/cindexstorage/io/IndexSummary.java +++ /dev/null @@ -1,392 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.core.index.cindexstorage.io; - -import java.io.IOException; -import java.io.RandomAccessFile; -import java.util.ArrayList; - -import org.eclipse.cdt.internal.core.CharOperation; -import org.eclipse.cdt.internal.core.index.cindexstorage.IndexedFileEntry; -import org.eclipse.cdt.internal.core.index.cindexstorage.Util; - -/** - * An indexSummary is used when saving an index into a BlocksIndexOuput or - * reading it from a BlocksIndexInput. It contains basic informations about - * an index: first files/words in each block, number of files/words. - */ - -public class IndexSummary { - /** - * First file for each block. - */ - protected ArrayList firstFilesInBlocks= new ArrayList(); - /** - * First word for each block. - */ - protected ArrayList firstWordsInBlocks= new ArrayList(); - /** - * First include for each block. - */ - protected ArrayList firstIncludesInBlocks= new ArrayList(); - /** - * Number of files in the index. - */ - protected int numFiles; - /** - * Number of words in the index. - */ - protected int numWords; - /** - * Number of includes in the index. - */ - protected int numIncludes; - - static class FirstFileInBlock { - IndexedFileEntry indexedFile; - int blockNum; - } - - static class FirstWordInBlock { - char[] word; - int blockNum; - public String toString(){ - return "FirstWordInBlock: " + new String(word) + ", blockNum: " + blockNum; //$NON-NLS-1$ //$NON-NLS-2$ - } - } - - static class FirstIncludeInBlock { - char[] file; - int blockNum; - public String toString(){ - return "FirstIncludeInBlock: " + new String(file) + ", blockNum: " + blockNum; //$NON-NLS-1$ //$NON-NLS-2$ - } - } - - protected int firstWordBlockNum; - protected boolean firstWordAdded= true; - - protected int firstIncludeBlockNum; - protected boolean firstIncludeBlockAdded= true; - /** - * Adds the given file as the first file for the given Block number. - */ - public void addFirstFileInBlock(IndexedFileEntry indexedFile, int blockNum) { - FirstFileInBlock entry= new FirstFileInBlock(); - entry.indexedFile= indexedFile; - entry.blockNum= blockNum; - firstFilesInBlocks.add(entry); - } - /** - * Adds the given word as the first word for the given Block number. - */ - public void addFirstWordInBlock(char[] word, int blockNum) { - if (firstWordAdded) { - firstWordBlockNum= blockNum; - firstWordAdded= false; - } - FirstWordInBlock entry= new FirstWordInBlock(); - entry.word= word; - entry.blockNum= blockNum; - firstWordsInBlocks.add(entry); - } - /** - * Adds the given include as the first include for the given Block number. - */ - public void addFirstIncludeInBlock(char[] file, int blockNum) { - if (firstIncludeBlockAdded) { - firstIncludeBlockNum= blockNum; - firstIncludeBlockAdded= false; - } - FirstIncludeInBlock entry= new FirstIncludeInBlock(); - entry.file = file; - entry.blockNum= blockNum; - firstIncludesInBlocks.add(entry); - } - /** - * Returns the numbers of all the blocks - */ - public int[] getAllBlockNums() { - - int max = firstWordsInBlocks.size(); - int[] blockNums = new int[max]; - for (int i = 0; i < max; i++){ - blockNums[i] = ((FirstWordInBlock)firstWordsInBlocks.get(i)).blockNum; - } - return blockNums; - } - public int getBlockNum(int blockLocation) { - return ((FirstWordInBlock) firstWordsInBlocks.get(blockLocation)).blockNum; - } - /** - * Returns the number of the Block containing the file with the given number. - */ - public int getBlockNumForFileNum(int fileNum) { - int min= 0; - int max= firstFilesInBlocks.size() - 1; - while (min <= max) { - int mid= (min + max) / 2; - FirstFileInBlock entry= (FirstFileInBlock) firstFilesInBlocks.get(mid); - int compare= fileNum - entry.indexedFile.getFileID(); - if (compare == 0) - return entry.blockNum; - if (compare < 0) - max= mid - 1; - else - min= mid + 1; - } - if (max < 0) - return -1; - FirstFileInBlock entry= (FirstFileInBlock) firstFilesInBlocks.get(max); - return entry.blockNum; - } - /** - * Returns the number of the Block containing the given word. - */ - public int getBlockNumForWord(char[] word) { - int min= 0; - int max= firstWordsInBlocks.size() - 1; - while (min <= max) { - int mid= (min + max) / 2; - FirstWordInBlock entry= (FirstWordInBlock) firstWordsInBlocks.get(mid); - int compare= Util.compare(word, entry.word); - if (compare == 0) - return entry.blockNum; - if (compare < 0) - max= mid - 1; - else - min= mid + 1; - } - if (max < 0) - return -1; - FirstWordInBlock entry= (FirstWordInBlock) firstWordsInBlocks.get(max); - return entry.blockNum; - } - public int[] getBlockNumsForPrefix(char[] prefix) { - int min= 0; - int size= firstWordsInBlocks.size(); - int max= size - 1; - int match= -1; - while (min <= max && match < 0) { - int mid= (min + max) / 2; - FirstWordInBlock entry= (FirstWordInBlock) firstWordsInBlocks.get(mid); - int compare= CharOperation.compareWith(entry.word, prefix); - if (compare == 0) { - match= mid; - break; - } - if (compare >= 0) - max= mid - 1; - else - min= mid + 1; - } - if (max < 0) - return new int[0]; - - if (match < 0) - match= max; - - int firstBlock= match - 1; - // Look if previous blocks are affected - for (; firstBlock >= 0; firstBlock--) { - FirstWordInBlock entry= (FirstWordInBlock) firstWordsInBlocks.get(firstBlock); - if (!CharOperation.prefixEquals(prefix, entry.word)) - break; - } - if (firstBlock < 0) - firstBlock= 0; - - // Look if next blocks are affected - int firstNotIncludedBlock= match + 1; - for (; firstNotIncludedBlock < size; firstNotIncludedBlock++) { - FirstWordInBlock entry= (FirstWordInBlock) firstWordsInBlocks.get(firstNotIncludedBlock); - if (!CharOperation.prefixEquals(prefix, entry.word)) - break; - } - - int numberOfBlocks= firstNotIncludedBlock - firstBlock; - int[] result= new int[numberOfBlocks]; - int pos= firstBlock; - for (int i= 0; i < numberOfBlocks; i++, pos++) { - FirstWordInBlock entry= (FirstWordInBlock) firstWordsInBlocks.get(pos); - result[i]= entry.blockNum; - } - return result; - } - public int[] getBlockNumsForIncludes() { - int max = firstIncludesInBlocks.size(); - int[] blockNums = new int[max]; - for (int i = 0; i < max; i++){ - blockNums[i] = ((FirstIncludeInBlock)firstIncludesInBlocks.get(i)).blockNum; - } - return blockNums; - } - public int getFirstBlockLocationForPrefix(char[] prefix) { - int min = 0; - int size = firstWordsInBlocks.size(); - int max = size - 1; - int match = -1; - while (min <= max) { - int mid = (min + max) / 2; - FirstWordInBlock entry = (FirstWordInBlock) firstWordsInBlocks.get(mid); - int compare = CharOperation.compareWith(entry.word, prefix); - if (compare == 0) { - match = mid; - break; - } - if (compare >= 0) { - max = mid - 1; - } else { - match = mid; // not perfect match, but could be inside - min = mid + 1; - } - } - if (max < 0) return -1; - - // no match at all, might be some matching entries inside max block - if (match < 0){ - match = max; - } else { - // look for possible matches inside previous blocks - while (match > 0){ - FirstWordInBlock entry = (FirstWordInBlock) firstWordsInBlocks.get(match); - if (!CharOperation.prefixEquals(prefix, entry.word)) - break; - match--; - } - } - return match; - } - /** - * Returns the number of the first IndexBlock (containing words). - */ - public int getFirstWordBlockNum() { - return firstWordBlockNum; - } - /** - * Returns the number of the first IndexBlock (containing words). - */ - public int getFirstIncludeBlockNum() { - return firstIncludeBlockNum; - } - /** - * Blocks are contiguous, so the next one is a potential candidate if its first word starts with - * the given prefix - */ - public int getNextBlockLocationForPrefix(char[] prefix, int blockLoc) { - if (++blockLoc < firstWordsInBlocks.size()){ - FirstWordInBlock entry= (FirstWordInBlock) firstWordsInBlocks.get(blockLoc); - if (CharOperation.prefixEquals(prefix, entry.word)) return blockLoc; - } - return -1; - } - /** - * Returns the number of files contained in the index. - */ - public int getNumFiles() { - return numFiles; - } - /** - * Returns the number of words contained in the index. - */ - public int getNumWords() { - return numWords; - } - /** - * Returns the number of words contained in the index. - */ - public int getNumIncludes() { - return numIncludes; - } - /** - * Loads the summary in memory. - */ - public void read(RandomAccessFile raf) throws IOException { - numFiles= raf.readInt(); - numWords= raf.readInt(); - numIncludes= raf.readInt(); - firstWordBlockNum= raf.readInt(); - firstIncludeBlockNum= raf.readInt(); - int numFirstFiles= raf.readInt(); - for (int i= 0; i < numFirstFiles; ++i) { - FirstFileInBlock entry= new FirstFileInBlock(); - String path= raf.readUTF(); - int fileNum= raf.readInt(); - entry.indexedFile= new IndexedFileEntry(path, fileNum); - entry.blockNum= raf.readInt(); - firstFilesInBlocks.add(entry); - } - int numFirstWords= raf.readInt(); - for (int i= 0; i < numFirstWords; ++i) { - FirstWordInBlock entry= new FirstWordInBlock(); - entry.word= raf.readUTF().toCharArray(); - entry.blockNum= raf.readInt(); - firstWordsInBlocks.add(entry); - } - int numIncludes = raf.readInt(); - for (int i= 0; i < numIncludes; ++i) { - FirstIncludeInBlock entry= new FirstIncludeInBlock(); - entry.file= raf.readUTF().toCharArray(); - entry.blockNum= raf.readInt(); - firstIncludesInBlocks.add(entry); - } - } - /** - * Sets the number of files of the index. - */ - - public void setNumFiles(int numFiles) { - this.numFiles= numFiles; - } - /** - * Sets the number of words of the index. - */ - - public void setNumWords(int numWords) { - this.numWords= numWords; - } - /** - * Sets the number of includes of the index. - */ - public void setNumIncludes(int numIncs) { - this.numIncludes= numIncs; - } - /** - * Saves the summary on the disk. - */ - public void write(RandomAccessFile raf) throws IOException { - raf.writeInt(numFiles); - raf.writeInt(numWords); - raf.writeInt(numIncludes); - raf.writeInt(firstWordBlockNum); - raf.writeInt(firstIncludeBlockNum); - raf.writeInt(firstFilesInBlocks.size()); - for (int i= 0, size= firstFilesInBlocks.size(); i < size; ++i) { - FirstFileInBlock entry= (FirstFileInBlock) firstFilesInBlocks.get(i); - raf.writeUTF(entry.indexedFile.getPath()); - raf.writeInt(entry.indexedFile.getFileID()); - raf.writeInt(entry.blockNum); - } - raf.writeInt(firstWordsInBlocks.size()); - for (int i= 0, size= firstWordsInBlocks.size(); i < size; ++i) { - FirstWordInBlock entry= (FirstWordInBlock) firstWordsInBlocks.get(i); - raf.writeUTF(new String(entry.word)); - raf.writeInt(entry.blockNum); - } - raf.writeInt(firstIncludesInBlocks.size()); - for (int i= 0, size= firstIncludesInBlocks.size(); i < size; ++i) { - FirstIncludeInBlock entry= (FirstIncludeInBlock) firstIncludesInBlocks.get(i); - raf.writeUTF(new String(entry.file)); - raf.writeInt(entry.blockNum); - } - } -} - diff --git a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/cindexstorage/io/MergeFactory.java b/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/cindexstorage/io/MergeFactory.java deleted file mode 100644 index 43664dda1c3..00000000000 --- a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/cindexstorage/io/MergeFactory.java +++ /dev/null @@ -1,301 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.core.index.cindexstorage.io; - -import java.io.IOException; -import java.util.Map; - -import org.eclipse.cdt.internal.core.index.cindexstorage.IncludeEntry; -import org.eclipse.cdt.internal.core.index.cindexstorage.IndexedFileEntry; -import org.eclipse.cdt.internal.core.index.cindexstorage.Util; -import org.eclipse.cdt.internal.core.index.cindexstorage.WordEntry; -import org.eclipse.cdt.internal.core.index.impl.Int; -import org.eclipse.cdt.internal.core.search.indexing.IndexManager; -import org.eclipse.cdt.internal.core.search.processing.JobManager; - -/** - * A mergeFactory is used to merge 2 indexes into one. One of the indexes - * (oldIndex) is on the disk and the other(addsIndex) is in memory. - * The merge respects the following rules:
    - * - The files are sorted in alphabetical order;
    - * - if a file is in oldIndex and addsIndex, the one which is added - * is the one in the addsIndex.
    - */ -public class MergeFactory { - /** - * Input on the addsIndex. - */ - protected IndexInput addsInput; - /** - * Input on the oldIndex. - */ - protected IndexInput oldInput; - /** - * Output to write the result of the merge in. - */ - protected BlocksIndexOutput mergeOutput; - /** - * Files removed from oldIndex. - */ - protected Map removedInOld; - /** - * Files removed from addsIndex. - */ - protected Map removedInAdds; - protected int[] mappingOld; - protected int[] mappingAdds; - public static final int ADDS_INDEX= 0; - public static final int OLD_INDEX= 1; - /** - * MergeFactory constructor comment. - * @param directory java.io.File - */ - public MergeFactory(IndexInput oldIndexInput, IndexInput addsIndexInput, BlocksIndexOutput mergeIndexOutput, Map removedInOld, Map removedInAdds) { - oldInput= oldIndexInput; - addsInput= addsIndexInput; - mergeOutput= mergeIndexOutput; - this.removedInOld= removedInOld; - this.removedInAdds= removedInAdds; - } - /** - * Initialise the merge. - */ - protected void init() { - mappingOld= new int[oldInput.getNumFiles() + 1]; - mappingAdds= new int[addsInput.getNumFiles() + 1]; - - } - /** - * Merges the 2 indexes into a new one on the disk. - */ - public void merge() throws IOException { - long startTime = 0; - if (IndexManager.VERBOSE){ - JobManager.verbose("-> starting merge"); //$NON-NLS-1$ - startTime = System.currentTimeMillis(); - } - try { - //init - addsInput.open(); - oldInput.open(); - mergeOutput.open(); - init(); - //merge - //findChanges(); - mergeFiles(); - mergeReferences(); - mergeIncludes(); - mergeOutput.flush(); - } - catch ( Exception ex ){ - if (ex instanceof IOException) - throw (IOException) ex; - else { - if (IndexManager.VERBOSE) { - JobManager.verbose("-> got the following exception during merge:"); //$NON-NLS-1$ - ex.printStackTrace(); - } - } - } - catch ( VirtualMachineError er ) { - if (IndexManager.VERBOSE) { - JobManager.verbose("-> got the following exception during merge:"); //$NON-NLS-1$ - er.printStackTrace(); - } - } - finally { - //closes everything - oldInput.close(); - addsInput.close(); - mergeOutput.close(); - - if (IndexManager.VERBOSE){ - long elapsedTime = System.currentTimeMillis() - startTime; - JobManager.verbose("-> merge complete: " + (elapsedTime > 0 ? elapsedTime : 0) + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ - } - } - } - /** - * Merges the files of the 2 indexes in the new index, removes the files - * to be removed, and records the changes made to propagate them to the - * word references. - */ - - protected void mergeFiles() throws IOException { - int positionInMerge= 1; - int compare; - - while (oldInput.hasMoreFiles() || addsInput.hasMoreFiles()) { - IndexedFileEntry file1= oldInput.getCurrentFile(); - IndexedFileEntry file2= addsInput.getCurrentFile(); - - //if the file has been removed we don't take it into account - while (file1 != null && wasRemoved(file1, OLD_INDEX)) { - oldInput.moveToNextFile(); - file1= oldInput.getCurrentFile(); - } - while (file2 != null && wasRemoved(file2, ADDS_INDEX)) { - addsInput.moveToNextFile(); - file2= addsInput.getCurrentFile(); - } - - //the addsIndex was empty, we just removed files from the oldIndex - if (file1 == null && file2 == null) - break; - - //test if we reached the end of one the 2 index - if (file1 == null) - compare= 1; - else if (file2 == null) - compare= -1; - else - compare= file1.getPath().compareTo(file2.getPath()); - - //records the changes to Make - if (compare == 0) { - //the file has been modified: - //we remove it from the oldIndex and add it to the addsIndex - removeFile(file1, OLD_INDEX); - mappingAdds[file2.getFileID()]= positionInMerge; - file1.setFileNumber(positionInMerge); - mergeOutput.addFile(file1); - oldInput.moveToNextFile(); - addsInput.moveToNextFile(); - } else if (compare < 0) { - mappingOld[file1.getFileID()]= positionInMerge; - file1.setFileNumber(positionInMerge); - mergeOutput.addFile(file1); - oldInput.moveToNextFile(); - } else { - mappingAdds[file2.getFileID()]= positionInMerge; - file2.setFileNumber(positionInMerge); - mergeOutput.addFile(file2); - addsInput.moveToNextFile(); - } - positionInMerge++; - } - mergeOutput.flushFiles(); - } - /** - * Merges the files of the 2 indexes in the new index, according to the changes - * recorded during mergeFiles(). - */ - protected void mergeReferences() throws IOException { - int compare; - while (oldInput.hasMoreWords() || addsInput.hasMoreWords()) { - WordEntry word1= oldInput.getCurrentWordEntry(); - WordEntry word2= addsInput.getCurrentWordEntry(); - - if (word1 == null && word2 == null) - break; - - if (word1 == null) - compare= 1; - else if (word2 == null) - compare= -1; - else - compare= Util.compare(word1.getWord(), word2.getWord()); - if (compare < 0) { - word1.mapRefs(mappingOld); - mergeOutput.addWord(word1); - oldInput.moveToNextWordEntry(); - } else if (compare > 0) { - word2.mapRefs(mappingAdds); - mergeOutput.addWord(word2); - addsInput.moveToNextWordEntry(); - } else { - word1.mapRefs(mappingOld); - word2.mapRefs(mappingAdds); - word1.addWordInfo(word2.getRefs(), word2.getOffsets(),word2.getOffsetLengths(), word2.getOffsetCount(), word2.getModifiers()); - mergeOutput.addWord(word1); - addsInput.moveToNextWordEntry(); - oldInput.moveToNextWordEntry(); - } - } - mergeOutput.flushWords(); - } - /** - * Merges the files of the 2 indexes in the new index, according to the changes - * recorded during mergeFiles(). - */ - protected void mergeIncludes() throws IOException { - int compare; - - while (oldInput.hasMoreIncludes() || addsInput.hasMoreIncludes()) { - IncludeEntry inc1= oldInput.getCurrentIncludeEntry(); - IncludeEntry inc2= addsInput.getCurrentIncludeEntry(); - - if (inc1 == null && inc2 == null) - break; - - if (inc1 == null) - compare= 1; - else if (inc2 == null) - compare= -1; - else - compare= Util.compare(inc1.getFile(), inc2.getFile()); - if (compare < 0) { - inc1.mapRefs(mappingOld); - mergeOutput.addInclude(inc1); - oldInput.moveToNextIncludeEntry(); - } else if (compare > 0) { - inc2.mapRefs(mappingAdds); - mergeOutput.addInclude(inc2); - addsInput.moveToNextIncludeEntry(); - } else { - inc1.mapRefs(mappingOld); - inc2.mapRefs(mappingAdds); - inc1.addRefs(inc2.getRefs()); - mergeOutput.addInclude(inc1); - addsInput.moveToNextIncludeEntry(); - oldInput.moveToNextIncludeEntry(); - } - } - mergeOutput.flushIncludes(); - } - /** - * Records the deletion of one file. - */ - protected void removeFile(IndexedFileEntry file, int index) { - if (index == OLD_INDEX) - mappingOld[file.getFileID()]= -1; - else - mappingAdds[file.getFileID()]= -1; - } - /** - * Returns whether the given file has to be removed from the given index - * (ADDS_INDEX or OLD_INDEX). If it has to be removed, the mergeFactory - * deletes it and records the changes. - */ - - protected boolean wasRemoved(IndexedFileEntry indexedFile, int index) { - String path= indexedFile.getPath(); - if (index == OLD_INDEX) { - if (removedInOld.remove(path) != null) { - mappingOld[indexedFile.getFileID()]= -1; - return true; - } - } else if (index == ADDS_INDEX) { - Int lastRemoved= (Int) removedInAdds.get(path); - if (lastRemoved != null) { - int fileNum= indexedFile.getFileID(); - if (lastRemoved.value >= fileNum) { - mappingAdds[fileNum]= -1; - //if (lastRemoved.value == fileNum) // ONLY if files in sorted order for names AND fileNums - //removedInAdds.remove(path); - return true; - } - } - } - return false; - } -} - diff --git a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/cindexstorage/io/SafeRandomAccessFile.java b/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/cindexstorage/io/SafeRandomAccessFile.java deleted file mode 100644 index e857a524ff6..00000000000 --- a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/cindexstorage/io/SafeRandomAccessFile.java +++ /dev/null @@ -1,31 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.core.index.cindexstorage.io; - -import java.io.IOException; -import java.io.RandomAccessFile; - -/** - * A safe subclass of RandomAccessFile, which ensure that it's closed - * on finalize. - */ -public class SafeRandomAccessFile extends RandomAccessFile { - public SafeRandomAccessFile(java.io.File file, String mode) throws java.io.IOException { - super(file, mode); - } - public SafeRandomAccessFile(String name, String mode) throws java.io.IOException { - super(name, mode); - } - protected void finalize() throws IOException { - close(); - } -} - diff --git a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/cindexstorage/io/SimpleIndexInput.java b/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/cindexstorage/io/SimpleIndexInput.java deleted file mode 100644 index 672ab839c50..00000000000 --- a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/cindexstorage/io/SimpleIndexInput.java +++ /dev/null @@ -1,211 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.core.index.cindexstorage.io; - -import java.io.IOException; -import java.util.ArrayList; - -import org.eclipse.cdt.internal.core.index.IEntryResult; -import org.eclipse.cdt.internal.core.index.IQueryResult; -import org.eclipse.cdt.internal.core.index.cindexstorage.InMemoryIndex; -import org.eclipse.cdt.internal.core.index.cindexstorage.IncludeEntry; -import org.eclipse.cdt.internal.core.index.cindexstorage.IndexedFileEntry; -import org.eclipse.cdt.internal.core.index.cindexstorage.WordEntry; - -/** - * A simpleIndexInput is an input on an in memory Index. - */ - -public class SimpleIndexInput extends IndexInput { - protected WordEntry[] sortedWordEntries; - protected IncludeEntry[] sortedIncludes; - protected IndexedFileEntry currentFile; - protected IndexedFileEntry[] sortedFiles; - protected InMemoryIndex index; - - public SimpleIndexInput(InMemoryIndex index) { - super(); - this.index= index; - } - /** - * @see IndexInput#clearCache() - */ - public void clearCache() { - } - /** - * @see IndexInput#close() - */ - public void close() throws IOException { - sortedFiles= null; - } - /** - * @see IndexInput#getCurrentFile() - */ - public IndexedFileEntry getCurrentFile() throws IOException { - if (!hasMoreFiles()) - return null; - return currentFile; - } - /** - * @see IndexInput#getIndexedFile(int) - */ - public IndexedFileEntry getIndexedFile(int fileNum) throws IOException { - for (int i= 0; i < sortedFiles.length; i++) - if (sortedFiles[i].getFileID() == fileNum) - return sortedFiles[i]; - return null; - } - /** - * @see IndexInput#getIndexedFile(String) - */ - public IndexedFileEntry getIndexedFile(String fullPath) throws IOException { - for (int i= index.getNumFiles(); i >= 1; i--) { - IndexedFileEntry file= getIndexedFile(i); - if (fullPath.equals(file.getPath())) - return file; - } - return null; - } - /** - * @see IndexInput#getNumFiles() - */ - public int getNumFiles() { - return index.getNumFiles(); - } - /** - * @see IndexInput#getNumIncludes() - */ - public int getNumIncludes() { - return sortedIncludes.length; - } - /** - * @see IndexInput#getNumWords() - */ - public int getNumWords() { - return sortedWordEntries.length; - } - /** - * @see IndexInput#getSource() - */ - public Object getSource() { - return index; - } - public void init() { - index.init(); - - } - /** - * @see IndexInput#moveToNextFile() - */ - public void moveToNextFile() throws IOException { - filePosition++; - if (!hasMoreFiles()) { - return; - } - currentFile= sortedFiles[filePosition - 1]; - } - /** - * @see IndexInput#moveToNextWordEntry() - */ - public void moveToNextWordEntry() throws IOException { - wordPosition++; - if (hasMoreWords()) - currentWordEntry= sortedWordEntries[wordPosition - 1]; - } - /** - * @see IndexInput#moveToNextIncludeEntry() - */ - public void moveToNextIncludeEntry() throws IOException { - includePosition++; - if (hasMoreIncludes()) - currentIncludeEntry= sortedIncludes[includePosition - 1]; - } - /** - * @see IndexInput#open() - */ - public void open() throws IOException { - sortedWordEntries= index.getSortedWordEntries(); - sortedFiles= index.getSortedFiles(); - sortedIncludes = index.getSortedIncludeEntries(); - filePosition= 1; - wordPosition= 1; - includePosition=1; - setFirstFile(); - setFirstWord(); - setFirstInclude(); - } - /** - * @see IndexInput#query(String) - */ - public IQueryResult[] query(String word) throws IOException { - char[] wordChar= word.toCharArray(); - WordEntry wordEntry= index.getWordEntry(wordChar); - int[] fileNums= wordEntry.getRefs(); - IQueryResult[] files= new IQueryResult[fileNums.length]; - for (int i= 0; i < files.length; i++) - files[i]= getIndexedFile(fileNums[i]); - return files; - } - public IEntryResult[] queryEntriesPrefixedBy(char[] prefix) throws IOException { - return null; - } - public IQueryResult[] queryFilesReferringToPrefix(char[] prefix) throws IOException { - return null; - } - /** - * @see IndexInput#queryInDocumentNames(String) - */ - public IQueryResult[] queryInDocumentNames(String word) throws IOException { - setFirstFile(); - ArrayList matches= new ArrayList(); - while (hasMoreFiles()) { - IndexedFileEntry file= getCurrentFile(); - if (file.getPath().indexOf(word) != -1) - matches.add(file.getPath()); - moveToNextFile(); - } - IQueryResult[] match= new IQueryResult[matches.size()]; - matches.toArray(match); - return match; - } - /** - * @see IndexInput#setFirstFile() - */ - protected void setFirstFile() throws IOException { - filePosition= 1; - if (sortedFiles.length > 0) { - currentFile= sortedFiles[0]; - } - } - /** - * @see IndexInput#setFirstWord() - */ - protected void setFirstWord() throws IOException { - wordPosition= 1; - if (sortedWordEntries.length > 0) - currentWordEntry= sortedWordEntries[0]; - } - /** - * @see IndexInput#setFirstInclude() - */ - protected void setFirstInclude() throws IOException { - includePosition=1; - if (sortedIncludes.length >0) - currentIncludeEntry=sortedIncludes[0]; - } - public IncludeEntry[] queryIncludeEntries() { - return null; - } - public IncludeEntry[] queryIncludeEntries(int fileNum) throws IOException { - return null; - } -} - diff --git a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/ctagsindexer/CTagEntry.java b/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/ctagsindexer/CTagEntry.java deleted file mode 100644 index a099ab25f85..00000000000 --- a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/ctagsindexer/CTagEntry.java +++ /dev/null @@ -1,286 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.core.index.ctagsindexer; - -import java.util.HashMap; -import java.util.LinkedList; -import java.util.StringTokenizer; - -import org.eclipse.cdt.internal.core.index.FunctionEntry; -import org.eclipse.cdt.internal.core.index.IIndex; -import org.eclipse.cdt.internal.core.index.IIndexerOutput; -import org.eclipse.cdt.internal.core.index.INamedEntry; -import org.eclipse.cdt.internal.core.index.NamedEntry; -import org.eclipse.cdt.internal.core.index.TypeEntry; -import org.eclipse.cdt.internal.core.index.cindexstorage.ICIndexStorageConstants; -import org.eclipse.cdt.internal.core.search.matching.CSearchPattern; - - -class CTagEntry{ - private final CTagsConsoleParser parser; - String elementName; - String fileName; - int lineNumber; - - /* Miscellaneous extension fields */ - HashMap tagExtensionField; - - String line; - - public CTagEntry(CTagsConsoleParser parser, String line) { - this.line = line; - this.parser = parser; - elementName = ""; //$NON-NLS-1$ - fileName =""; //$NON-NLS-1$ - lineNumber = 0; - tagExtensionField = new HashMap(); - parse(); - } - - void parse () { - String delim = CTagsConsoleParser.TAB_SEPARATOR; - StringTokenizer st = new StringTokenizer(line, delim); - for (int state = 0; st.hasMoreTokens(); state++) { - String token = st.nextToken(); - - switch (state) { - case 0: // ELEMENT_NAME: - elementName = token; - break; - - case 1: // FILE_NAME: - fileName = token; - break; - - case 2: // LINE NUMBER; - try { - String sub = token.trim(); - int i = sub.indexOf(';'); - String num = sub.substring(0, i); - if (Character.isDigit(num.charAt(0))) { - lineNumber = Integer.parseInt(num); - } - } catch (NumberFormatException e) { - } catch (IndexOutOfBoundsException e) { - } - break; - - default: // EXTENSION_FIELDS: - int i = token.indexOf(':'); - if (i != -1) { - String key = token.substring(0, i); - String value = token.substring(i + 1); - tagExtensionField.put(key, value); - } - break; - } - } - } - - /** - * @param tempTag - * @return - */ - public char[][] getQualifiedName() { - char[][] fullName = null; - String name = null; - String[] types = {CTagsConsoleParser.NAMESPACE, CTagsConsoleParser.CLASS, CTagsConsoleParser.STRUCT, CTagsConsoleParser.UNION, CTagsConsoleParser.FUNCTION, CTagsConsoleParser.ENUM}; - - for (int i=0; i failed to index " + this.resource + " because of the following exception:"); //$NON-NLS-1$ //$NON-NLS-2$ - e.printStackTrace(); - } - return false; - } finally { - monitor.exitWrite(); // free write lock - indexer.request(new CTagsSaveIndex(this.indexPath, indexer)); - } - return true; - } - - protected abstract boolean indexDocument(IIndex index) throws IOException; - - public String toString() { - return "indexing " + this.resource.getFullPath(); //$NON-NLS-1$ - } - - /** - * The resource being indexed - * @return - */ - public IResource getResource(){ - return resource; - } -} diff --git a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/ctagsindexer/CTagsConsoleParser.java b/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/ctagsindexer/CTagsConsoleParser.java deleted file mode 100644 index ce8302df16c..00000000000 --- a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/ctagsindexer/CTagsConsoleParser.java +++ /dev/null @@ -1,92 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.core.index.ctagsindexer; - -import org.eclipse.cdt.core.IConsoleParser; -import org.eclipse.cdt.internal.core.index.cindexstorage.IndexedFileEntry; - -/** - * @author Bogdan Gheorghe - */ -public class CTagsConsoleParser implements IConsoleParser { - - final static String TAB_SEPARATOR = "\t"; //$NON-NLS-1$ - final static String PATTERN_SEPARATOR = ";\""; //$NON-NLS-1$ - final static String COLONCOLON = "::"; //$NON-NLS-1$ - final static String LANGUAGE = "language"; //$NON-NLS-1$ - final static String KIND = "kind"; //$NON-NLS-1$ - final static String LINE = "line"; //$NON-NLS-1$ - final static String FILE = "file"; //$NON-NLS-1$ - final static String INHERITS = "inherits"; //$NON-NLS-1$ - final static String ACCESS = "access"; //$NON-NLS-1$ - final static String IMPLEMENTATION = "implementation"; //$NON-NLS-1$ - final static String SIGNATURE = "signature"; //$NON-NLS-1$ - - final static String CLASS = "class"; //$NON-NLS-1$ - final static String MACRO = "macro"; //$NON-NLS-1$ - final static String ENUMERATOR = "enumerator"; //$NON-NLS-1$ - final static String FUNCTION = "function"; //$NON-NLS-1$ - final static String ENUM = "enum"; //$NON-NLS-1$ - final static String MEMBER = "member"; //$NON-NLS-1$ - final static String NAMESPACE = "namespace"; //$NON-NLS-1$ - final static String PROTOTYPE = "prototype"; //$NON-NLS-1$ - final static String STRUCT = "struct"; //$NON-NLS-1$ - final static String TYPEDEF = "typedef"; //$NON-NLS-1$ - final static String UNION = "union"; //$NON-NLS-1$ - final static String VARIABLE = "variable"; //$NON-NLS-1$ - final static String EXTERNALVAR = "externvar"; //$NON-NLS-1$ - - private CTagsIndexerRunner indexer; - - public CTagsConsoleParser(CTagsIndexerRunner indexer){ - this.indexer = indexer; - } - /* (non-Javadoc) - * @see org.eclipse.cdt.internal.core.index.ctagsindexer.IConsoleParser#processLine(java.lang.String) - */ - public boolean processLine(String line) { - CTagEntry tempTag = new CTagEntry(this, line); - if (indexer != null) - tempTag.addTagToIndexOutput(getFileNumber(), indexer.getOutput()); - - return false; - } - - public CTagEntry processLineReturnTag(String line){ - CTagEntry tempTag = new CTagEntry(this, line); - return tempTag; - } - - /** - * @return - */ - private int getFileNumber() { - int fileNum = 0; - IndexedFileEntry mainIndexFile = indexer.getOutput().getIndexedFile( - indexer.getResourceFile().getFullPath().toString()); - if (mainIndexFile != null) - fileNum = mainIndexFile.getFileID(); - - return fileNum; - } - - - /* (non-Javadoc) - * @see org.eclipse.cdt.internal.core.index.ctagsindexer.IConsoleParser#shutdown() - */ - public void shutdown() { - // TODO Auto-generated method stub - - } - - - -} diff --git a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/ctagsindexer/CTagsFileReader.java b/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/ctagsindexer/CTagsFileReader.java deleted file mode 100644 index be9e1873aae..00000000000 --- a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/ctagsindexer/CTagsFileReader.java +++ /dev/null @@ -1,176 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.cdt.internal.core.index.ctagsindexer; - -import java.io.BufferedReader; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.io.IOException; -import java.util.List; - -import org.eclipse.cdt.core.CCorePlugin; -import org.eclipse.cdt.internal.core.index.IIndex; -import org.eclipse.cdt.internal.core.index.IIndexerRunner; -import org.eclipse.cdt.internal.core.index.IIndexerOutput; -import org.eclipse.cdt.internal.core.index.cindexstorage.IndexedFileEntry; -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.Path; - -public class CTagsFileReader { - - String filename = null; - List list = null; - IProject project = null; - IIndex index = null; - CTagsIndexer indexer = null; - IPath rootDirectory = null; - - public CTagsFileReader(IProject project,String filename, CTagsIndexer indexer) { - this.filename = filename; - this.project = project; - this.indexer = indexer; - } - - public void parse() { - BufferedReader reader = null; - try{ - reader = new BufferedReader(new FileReader(filename)); - } catch (FileNotFoundException ex){ - indexer.createProblemMarker(CCorePlugin.getResourceString("CTagsIndexMarker.fileMissing") + " - " + filename, project); //$NON-NLS-1$ //$NON-NLS-2$ - return; - } - - CTagsHeader header = new CTagsHeader(); - // Skip the header. - - try { - header.parse(reader); - } catch (IOException e) { - indexer.createProblemMarker(e.getMessage(), project); - return; - } - - String s; - String currentFileName = null; - IFile currentFile = null; - CTagsConsoleParser parser = new CTagsConsoleParser(null); - MiniIndexer indexer = null; - - //Make sure we have an index before proceeding - if (index == null) - return; - - try { - while ((s = reader.readLine()) != null) { - CTagEntry tagEntry = parser.processLineReturnTag(s); - - String fileName = tagEntry.fileName; - - if (currentFileName == null || - (!currentFileName.equals(fileName))){ - currentFileName = fileName; - currentFile = (IFile) project.findMember(fileName); - - if (currentFile == null){ - //Didn't find file in project - IPath tempPath = new Path(filename); - tempPath = tempPath.removeLastSegments(1); - tempPath = tempPath.append(fileName); - currentFile = (IFile) project.findMember(tempPath); - - } - - - if (currentFile != null){ - indexer = new MiniIndexer(currentFile.getFullPath()); - index.add(currentFile,indexer); - } else { - IPath filePath = new Path(fileName); - if (!filePath.isAbsolute()) { - filePath = rootDirectory.append(fileName); - } - indexer = new MiniIndexer(filePath); - try { - IResource[] resources = project.members(); - IFile tempFile=null; - for (int i=0; i failed to index " + this.project + " because of the following exception:"); //$NON-NLS-1$ //$NON-NLS-2$ - e.printStackTrace(); - } - indexer.removeIndex(this.indexPath); - return false; - } finally { - monitor.exitRead(); // free read lock - } - return true; - } - - private void cTagsInclude(IIndex index) { - - ICProject cProj = CoreModel.getDefault().create(project); - IIncludeReference[] refs = new IIncludeReference[0]; - try { - refs = cProj.getIncludeReferences(); - } catch (CModelException e) {} - - //This project has no references, don't bother processing any further - if (refs.length == 0) - return; - - //Find common base for references - String[] pathString = new String[refs.length]; - for (int i=0; i 0) { - for (int i = 0; i < cext.length; i++) { - String id = cext[i].getID(); - String orig = cext[i].getExtensionData("ctagfiletype"); //$NON-NLS-1$ - if (orig != null){ - if (orig.equals(CTagsIndexer.CTAGS_INTERNAL)) - return true; - else if (orig.equals(CTagsIndexer.CTAGS_EXTERNAL)) - return false; - } - } - } - } catch (CoreException e) {} - - return false; - } - - private boolean useDefaultCTags(){ - try { - ICDescriptor cdesc = CCorePlugin.getDefault().getCProjectDescription(project, false); - if (cdesc == null) - return true; - - ICExtensionReference[] cext = cdesc.get(CCorePlugin.INDEXER_UNIQ_ID); - if (cext.length > 0) { - for (int i = 0; i < cext.length; i++) { - String orig = cext[i].getExtensionData("ctagslocationtype"); //$NON-NLS-1$ - if (orig != null){ - if (orig.equals(CTagsIndexer.CTAGS_PATH_DEFAULT)) - return true; - else if (orig.equals(CTagsIndexer.CTAGS_PATH_SPECIFIED)) - return false; - } - } - } - } catch (CoreException e) {} - - return false; - } - - private boolean getCTagsLocation() { - try { - ICDescriptor cdesc = CCorePlugin.getDefault().getCProjectDescription(project, false); - if (cdesc == null) - return false; - - ICExtensionReference[] cext = cdesc.get(CCorePlugin.INDEXER_UNIQ_ID); - if (cext.length > 0) { - for (int i = 0; i < cext.length; i++) { - String orig = cext[i].getExtensionData("ctagslocation"); //$NON-NLS-1$ - if (orig != null){ - ctagsLocation=orig; - return true; - } - } - } - } catch (CoreException e) {} - - return false; - } - - private boolean ctagIndexIncludes(){ - try { - ICDescriptor cdesc = CCorePlugin.getDefault().getCProjectDescription(project, false); - if (cdesc == null) - return true; - - ICExtensionReference[] cext = cdesc.get(CCorePlugin.INDEXER_UNIQ_ID); - if (cext.length > 0) { - for (int i = 0; i < cext.length; i++) { - String id = cext[i].getID(); - String orig = cext[i].getExtensionData("ctagsindexincludes"); //$NON-NLS-1$ - if (orig != null){ - return new Boolean(orig).booleanValue(); - } - } - } - } catch (CoreException e) {} - - return false; - } - - private boolean getCTagsFileLocation() { - try { - ICDescriptor cdesc = CCorePlugin.getDefault().getCProjectDescription(project, false); - if (cdesc == null) - return false; - - ICExtensionReference[] cext = cdesc.get(CCorePlugin.INDEXER_UNIQ_ID); - if (cext.length > 0) { - for (int i = 0; i < cext.length; i++) { - String id = cext[i].getID(); - String orig = cext[i].getExtensionData("ctagfilelocation"); //$NON-NLS-1$ - if (orig != null){ - ctagsFileToUse=orig; - return true; - } - } - } - } catch (CoreException e) {} - - return false; - } - -} diff --git a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/ctagsindexer/CTagsIndexRequest.java b/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/ctagsindexer/CTagsIndexRequest.java deleted file mode 100644 index 3a3e79a9763..00000000000 --- a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/ctagsindexer/CTagsIndexRequest.java +++ /dev/null @@ -1,74 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.core.index.ctagsindexer; - -import java.io.IOException; - -import org.eclipse.cdt.core.CCorePlugin; -import org.eclipse.cdt.internal.core.index.IIndex; -import org.eclipse.cdt.internal.core.index.IndexRequest; -import org.eclipse.cdt.internal.core.index.cindexstorage.CIndexStorage; -import org.eclipse.cdt.internal.core.search.indexing.ReadWriteMonitor; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.runtime.IPath; - -/** - * @author Bogdan Gheorghe - */ -public abstract class CTagsIndexRequest extends IndexRequest { - - protected CTagsIndexer indexer = null; - - public CTagsIndexRequest(IPath indexPath, CTagsIndexer indexer) { - super(indexPath); - this.indexer = indexer; - } - - - public void cancel() { - this.indexer.jobFinishedNotification( this ); - this.indexer.jobWasCancelled(this.indexPath); - this.isCancelled = true; - } - - public boolean isReadyToRun() { - IProject project = CCorePlugin.getWorkspace().getRoot().getProject(indexPath.segment(0)); - if ( !project.isAccessible() || !this.indexer.isIndexEnabled( project ) ) - return false; - - // tag the index as inconsistent - indexer.aboutToUpdateIndex(indexPath, updatedIndexState()); - return true; - } - /* - * This code is assumed to be invoked while monitor has read lock - */ - protected void saveIfNecessary(IIndex index, ReadWriteMonitor monitor) throws IOException { - /* if index has changed, commit these before querying */ - if (index.hasChanged()) { - try { - monitor.exitRead(); // free read lock - monitor.enterWrite(); // ask permission to write - indexer.saveIndex(index); - } finally { - monitor.exitWriteEnterRead(); // finished writing and reacquire read permission - } - } - } - - protected Integer updatedIndexState() { - return CIndexStorage.UPDATING_STATE; - } - - public IPath getIndexPath(){ - return indexPath; - } -} diff --git a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/ctagsindexer/CTagsIndexer.java b/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/ctagsindexer/CTagsIndexer.java deleted file mode 100644 index 53b8d2e6f1e..00000000000 --- a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/ctagsindexer/CTagsIndexer.java +++ /dev/null @@ -1,567 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.core.index.ctagsindexer; - -import java.io.IOException; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; - -import org.eclipse.cdt.core.AbstractCExtension; -import org.eclipse.cdt.core.CCorePlugin; -import org.eclipse.cdt.core.CommandLauncher; -import org.eclipse.cdt.core.ICLogConstants; -import org.eclipse.cdt.core.IConsoleParser; -import org.eclipse.cdt.core.index.ICDTIndexer; -import org.eclipse.cdt.core.index.IIndexChangeListener; -import org.eclipse.cdt.core.index.IIndexStorage; -import org.eclipse.cdt.core.index.IndexChangeEvent; -import org.eclipse.cdt.core.model.ICModelMarker; -import org.eclipse.cdt.internal.core.ConsoleOutputSniffer; -import org.eclipse.cdt.internal.core.InternalCExtension; -import org.eclipse.cdt.internal.core.Util; -import org.eclipse.cdt.internal.core.index.IIndex; -import org.eclipse.cdt.internal.core.index.cindexstorage.CIndexStorage; -import org.eclipse.cdt.internal.core.index.impl.IndexDelta; -import org.eclipse.cdt.internal.core.search.indexing.IndexManager; -import org.eclipse.cdt.internal.core.search.indexing.ReadWriteMonitor; -import org.eclipse.cdt.internal.core.search.processing.IIndexJob; -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IFolder; -import org.eclipse.core.resources.IMarker; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.resources.IResourceDelta; -import org.eclipse.core.resources.IResourceVisitor; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.ISafeRunnable; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.NullProgressMonitor; -import org.eclipse.core.runtime.Path; -import org.eclipse.core.runtime.Platform; -import org.eclipse.core.runtime.Status; -import org.eclipse.core.runtime.jobs.Job; - -/** - * @author Bogdan Gheorghe - */ -public class CTagsIndexer extends AbstractCExtension implements ICDTIndexer { - - public static boolean VERBOSE = false; - - public final static String CTAGS_INTERNAL = "ctags_internal"; //$NON-NLS-1$ - public final static String CTAGS_EXTERNAL = "ctags_external"; //$NON-NLS-1$ - public final static String CTAGS_PATH_DEFAULT = "ctags_path_default"; //$NON-NLS-1$ - public final static String CTAGS_PATH_SPECIFIED = "ctags_path_specified"; //$NON-NLS-1$ - - protected List indexChangeListeners = Collections.synchronizedList(new ArrayList()); - public static final String INDEX_NOTIFICATION_NAME = Util.bind( "indexNotificationJob" ); //$NON-NLS-1$ - private CIndexStorage indexStorage = null; - public ReadWriteMonitor storageMonitor = null; - private IndexManager indexManager = null; - - private HashSet jobSet = null; - - public CTagsIndexer(){ - this.indexManager = CCorePlugin.getDefault().getCoreModel().getIndexManager(); - this.indexStorage = (CIndexStorage) indexManager.getIndexStorageForIndexer(this); - this.jobSet = new HashSet(); - this.storageMonitor = new ReadWriteMonitor(); - } - - /* (non-Javadoc) - * @see org.eclipse.cdt.core.index.ICDTIndexer#getIndexerFeatures() - */ - public int getIndexerFeatures() { - return ICDTIndexer._DECLARATIONS | ICDTIndexer._DEFINITIONS | ICDTIndexer._LINENUMBERS | ICDTIndexer._C | ICDTIndexer._CPP; - } - - /* (non-Javadoc) - * @see org.eclipse.cdt.core.index.ICDTIndexer#addRequest(org.eclipse.cdt.core.model.ICElement, org.eclipse.core.resources.IResourceDelta) - */ - public void addRequest(IProject project, IResourceDelta delta, int kind) { - - switch (kind) { - - case ICDTIndexer.PROJECT: - this.indexAll(project); - break; - - case ICDTIndexer.FOLDER: - IFolder folder = (IFolder) delta.getResource(); - this.indexSourceFolder(project,folder); - break; - - - case ICDTIndexer.COMPILATION_UNIT: - IFile file = (IFile) delta.getResource(); - this.addSource(file, project.getFullPath()); - break; - - default: - this.indexAll(project); - break; - } - - - } - - public void indexSourceFolder(IProject project, IFolder folder) { - - final HashSet indexables = new HashSet(); - try { - folder.accept(new IResourceVisitor(){ - public boolean visit(IResource resource) throws CoreException { - if (resource instanceof IFile) - indexables.add(resource); - - return true; - } - }); - } catch (CoreException e) {} - - Iterator i = indexables.iterator(); - while (i.hasNext()){ - this.addSource((IFile) i.next(), project.getFullPath()); - } - } - - /** - * @param project - */ - public void indexAll(IProject project) { - CTagsIndexRequest request = new CTagsIndexAll(project, this); - for (int i = indexManager.getJobEnd(); i > indexManager.getJobStart(); i--) // NB: don't check job at jobStart, as it may have already started (see http://bugs.eclipse.org/bugs/show_bug.cgi?id=32488) - if (request.equals(indexManager.getAwaitingJobAt(i))) return; - indexManager.request(request); - } - - /* (non-Javadoc) - * @see org.eclipse.cdt.core.index.ICDTIndexer#removeRequest(org.eclipse.cdt.core.model.ICElement, org.eclipse.core.resources.IResourceDelta) - */ - public void removeRequest(IProject project, IResourceDelta delta, int kind) { - switch (kind) { - case ICDTIndexer.PROJECT : - IPath fullPath = project.getFullPath(); - if( delta.getKind() == IResourceDelta.CHANGED ) - indexManager.discardJobs(fullPath.segment(0)); - indexStorage.removeIndexFamily(fullPath); - // NB: Discarding index jobs belonging to this project was done during PRE_DELETE - break; - // NB: Update of index if project is opened, closed, or its c nature is added or removed - // is done in updateCurrentDeltaAndIndex - - /* - case ICDTIndexer.FOLDER : - this.removeSourceFolderFromIndex(project,project.getFullPath(),null); - break;*/ - - case ICDTIndexer.COMPILATION_UNIT: - IFile file = (IFile) delta.getResource(); - this.remove(file.getFullPath().toString(), file.getProject().getFullPath()); - break; - } - } - - /* (non-Javadoc) - * @see org.eclipse.cdt.core.index.ICDTIndexer#indexJobFinishedNotification(org.eclipse.cdt.internal.core.search.processing.IIndexJob) - */ - public void indexJobFinishedNotification(IIndexJob job) { - indexStorage.setNeedToSave(true); - - if (job instanceof CTagsAddCompilationUnitToIndex){ - CTagsAddCompilationUnitToIndex tempJob = (CTagsAddCompilationUnitToIndex) job; - jobSet.remove(tempJob.getResource().getLocation()); - } - } - - /* (non-Javadoc) - * @see org.eclipse.cdt.core.index.ICDTIndexer#shutdown() - */ - public void shutdown() { - // TODO Auto-generated method stub - - } - - /* (non-Javadoc) - * @see org.eclipse.cdt.core.index.ICDTIndexer#notifyIdle(long) - */ - public void notifyIdle(long idlingTime) { - // TODO Auto-generated method stub - - } - - /** - * @param path - * @param reuseIndexFile - * @param createIfMissing - * @return - */ - public synchronized IIndex getIndex(IPath path, boolean reuseExistingFile, boolean createIfMissing) { - IIndex index = null; - try{ - storageMonitor.enterRead(); - index = indexStorage.getIndex(path,reuseExistingFile, createIfMissing); - } - finally{ - storageMonitor.exitRead(); - } - return index; - } - - /** - * @param index - * @return - */ - public ReadWriteMonitor getMonitorFor(IIndex index) { - ReadWriteMonitor monitor = null; - try{ - storageMonitor.enterRead(); - monitor=indexStorage.getMonitorForIndex(); - } - finally{ - storageMonitor.exitRead(); - } - return monitor; - } - - /** - * @param index - */ - public void saveIndex(IIndex index) throws IOException { - try{ - storageMonitor.enterWrite(); - indexStorage.saveIndex(index); - } - finally { - storageMonitor.exitWrite(); - } - - } - - /** - * Forward job request to Index Manager - * @param cleanHeaders - */ - public void request(IIndexJob indexJob) { - this.indexManager.request(indexJob); - } - - /** - * @param indexPath - * @param integer - */ - public void aboutToUpdateIndex(IPath indexPath, Integer indexState) { - storageMonitor.enterRead(); - try{ - indexStorage.aboutToUpdateIndex(indexPath, indexState); - } - finally { - storageMonitor.exitRead(); - } - } - - /** - * @param project - * @return - */ - public boolean isIndexEnabled(IProject project) { - //Return true for now - return true; - } - - /** - * @param path - */ - public void jobWasCancelled(IPath path) { - try{ - storageMonitor.enterWrite(); - indexStorage.jobWasCancelled(path); - } - finally{ - storageMonitor.exitWrite(); - } - } - - /** - * @param request - */ - public void jobFinishedNotification(CTagsIndexRequest request) { - this.indexJobFinishedNotification(request); - } - - /** - * @param path - */ - public void removeIndex(IPath path) { - try{ - storageMonitor.enterWrite(); - indexStorage.removeIndex(path); - } - finally{ - storageMonitor.exitWrite(); - } - } - - /** - * Trigger removal of a resource to an index - * Note: the actual operation is performed in background - */ - public void remove(String resourceName, IPath indexedContainer){ - IProject project = CCorePlugin.getWorkspace().getRoot().getProject(indexedContainer.toString()); - if( isIndexEnabled( project ) ) - request(new CTagsRemoveFromIndex(resourceName, indexedContainer, this)); - } - - /** - * @param file - * @param path - */ - public void addSource(IFile resource, IPath indexedContainers) { - IProject project = resource.getProject(); - - boolean indexEnabled = false; - if (project != null) - indexEnabled = isIndexEnabled(project); - else - org.eclipse.cdt.internal.core.model.Util.log(null, "CTagsIndexer addSource: File has no project associated : " + resource.getName(), ICLogConstants.CDT); //$NON-NLS-1$ - - if (CCorePlugin.getDefault() == null) return; - - if (indexEnabled){ - CTagsAddCompilationUnitToIndex job = new CTagsAddCompilationUnitToIndex(resource, indexedContainers, this); - - //If we are in WAITING mode, we need to kick ourselves into enablement - if (!jobSet.add(resource.getLocation()) && - indexManager.enabledState()==IndexManager.ENABLED) - return; - - - if (indexManager.awaitingJobsCount() < CIndexStorage.MAX_FILES_IN_MEMORY) { - // reduces the chance that the file is open later on, preventing it from being deleted - if (!job.initializeContents()) return; - } - - this.indexManager.request(job); - } - } - - /* (non-Javadoc) - * @see org.eclipse.cdt.core.index.ICDTIndexer#getIndexStorage() - */ - public IIndexStorage getIndexStorage() { - return indexStorage; - } - - /* (non-Javadoc) - * @see org.eclipse.cdt.core.index.ICDTIndexer#notifyIndexerChange(org.eclipse.core.resources.IProject) - */ - public void notifyIndexerChange(IProject project) { - this.indexAll(project); - } - - protected void createProblemMarker(String message, IProject project){ - - try { - IMarker[] markers = project.findMarkers(ICModelMarker.INDEXER_MARKER, true,IResource.DEPTH_ZERO); - - boolean newProblem = true; - - if (markers.length > 0) { - IMarker tempMarker = null; - String tempMsgString = null; - - for (int i=0; i " + (System.currentTimeMillis()-start) + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ - } - } - - } - - public boolean validCTagsInstalled(){ - String[] args = {"--version"}; //$NON-NLS-1$ - - String errMsg = null; - CommandLauncher launcher = new CommandLauncher(); - - CTagLineReader parser = new CTagLineReader(); - IConsoleParser[] parsers = { parser }; - ConsoleOutputSniffer sniffer = new ConsoleOutputSniffer(parsers); - - OutputStream consoleOut = sniffer.getOutputStream(); - OutputStream consoleErr = sniffer.getErrorStream(); - - Process p = launcher.execute(new Path("ctags"), args,new String[0], new Path(".")); //$NON-NLS-1$ //$NON-NLS-2$ - if (p != null) { - try { - // Close the input of the Process explicitely. - // We will never write to it. - p.getOutputStream().close(); - } catch (IOException e) {} - if (launcher.waitAndRead(consoleOut, consoleErr, new NullProgressMonitor()) != CommandLauncher.OK) { - errMsg = launcher.getErrorMessage(); - } - } - else { - errMsg = launcher.getErrorMessage(); - return false; - } - - try { - consoleOut.close(); - consoleErr.close(); - } catch (IOException e) {} - - - if (parser.isExuberantCtags) - return true; - - return false; - } - - class CTagLineReader implements IConsoleParser{ - - boolean isExuberantCtags=false; - - public boolean processLine(String line) { - if (line.startsWith("Exuberant Ctags")) //$NON-NLS-1$ - isExuberantCtags=true; - - return true; - } - - public void shutdown() {} - } - - public void addResource(IProject project, IResource resource) { - - if (resource instanceof IProject){ - this.indexAll(project); - } - else if (resource instanceof IFolder){ - IFolder folder = (IFolder) resource; - this.indexSourceFolder(project,folder); - } - else if (resource instanceof IFile){ - IFile file = (IFile) resource; - this.addSource(file, project.getFullPath()); - } - else { - this.indexAll(project); - } - - } - - public void removeResource(IProject project, IResource resource) { - if (resource instanceof IProject){ - IPath fullPath = project.getFullPath(); - indexManager.discardJobs(fullPath.segment(0)); - indexStorage.removeIndexFamily(fullPath); - } - else if (resource instanceof IFile){ - IFile file = (IFile) resource; - this.remove(file.getFullPath().toString(), file.getProject().getFullPath()); - } - } - - public void addResourceByPath(IProject project, IPath path, int resourceType) { - //Nothing yet - } - - /* (non-Javadoc) - * @see org.eclipse.cdt.core.index.ICDTIndexer#setIndexerProject(org.eclipse.core.resources.IProject) - */ - public void setIndexerProject(IProject project) { - setProject(project); - } - -} diff --git a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/ctagsindexer/CTagsIndexerRunner.java b/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/ctagsindexer/CTagsIndexerRunner.java deleted file mode 100644 index b87d6a65027..00000000000 --- a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/ctagsindexer/CTagsIndexerRunner.java +++ /dev/null @@ -1,178 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.core.index.ctagsindexer; - -import java.io.IOException; -import java.io.OutputStream; - -import org.eclipse.cdt.core.CCorePlugin; -import org.eclipse.cdt.core.CommandLauncher; -import org.eclipse.cdt.core.ICDescriptor; -import org.eclipse.cdt.core.ICExtensionReference; -import org.eclipse.cdt.core.IConsoleParser; -import org.eclipse.cdt.core.model.ICModelMarker; -import org.eclipse.cdt.core.resources.IConsole; -import org.eclipse.cdt.internal.core.ConsoleOutputSniffer; -import org.eclipse.cdt.internal.core.index.cindexstorage.IndexedFileEntry; -import org.eclipse.cdt.internal.core.index.domsourceindexer.AbstractIndexerRunner; -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.NullProgressMonitor; -import org.eclipse.core.runtime.Path; - -/** - * @author Bogdan Gheorghe - */ -public class CTagsIndexerRunner extends AbstractIndexerRunner { - private CTagsIndexer indexer; - String ctagsLocation; - /** - * @param resource - * @param indexer - */ - public CTagsIndexerRunner(IFile resource, CTagsIndexer indexer) { - this.resourceFile = resource; - this.indexer = indexer; - } - - /* (non-Javadoc) - * @see org.eclipse.cdt.internal.core.index.sourceindexer.AbstractIndexer#indexFile(org.eclipse.cdt.internal.core.index.IDocument) - */ - protected void indexFile(IFile file) throws IOException { - IndexedFileEntry indFile =output.addIndexedFile(file.getFullPath().toString()); - - String[] args = { - "--excmd=number", //$NON-NLS-1$ - "--format=2", //$NON-NLS-1$ - "--sort=no", //$NON-NLS-1$ - "--fields=aiKlmnsSz", //$NON-NLS-1$ - "--c-types=cdefgmnpstuvx", //$NON-NLS-1$ - "--c++-types=cdefgmnpstuvx", //$NON-NLS-1$ - "--languages=c,c++", //$NON-NLS-1$ - "-f", "-", resourceFile.getName()}; //$NON-NLS-1$ //$NON-NLS-2$ - - IConsole console = CCorePlugin.getDefault().getConsole(null); - console.start(resourceFile.getProject()); - OutputStream cos; - try { - cos = console.getOutputStream(); - } catch (CoreException e1) { - return; - } - - String errMsg = null; - CommandLauncher launcher = new CommandLauncher(); - - //Remove any existing problem markers - try { - resourceFile.getProject().deleteMarkers(ICModelMarker.INDEXER_MARKER, true,IResource.DEPTH_ZERO); - } catch (CoreException e) {} - - long startTime=0; - if (AbstractIndexerRunner.TIMING) - startTime = System.currentTimeMillis(); - - CTagsConsoleParser parser = new CTagsConsoleParser(this); - IConsoleParser[] parsers = { parser }; - ConsoleOutputSniffer sniffer = new ConsoleOutputSniffer(parsers); - - OutputStream consoleOut = (sniffer == null ? cos : sniffer.getOutputStream()); - OutputStream consoleErr = (sniffer == null ? cos : sniffer.getErrorStream()); - - IPath fileDirectory = resourceFile.getRawLocation().removeLastSegments(1); - - IPath ctagsExecutable = new Path("ctags"); //$NON-NLS-1$ - if (!useDefaultCTags()){ - //try to read the executable path from the descriptor - if (getCTagsLocation()){ - ctagsExecutable = new Path(ctagsLocation); - } - } - - Process p = launcher.execute(ctagsExecutable, args, null, fileDirectory); //$NON-NLS-1$ - if (p != null) { - try { - // Close the input of the Process explicitely. - // We will never write to it. - p.getOutputStream().close(); - } catch (IOException e) {} - if (launcher.waitAndRead(consoleOut, consoleErr, new NullProgressMonitor()) != CommandLauncher.OK) { - errMsg = launcher.getErrorMessage(); - } - } - else { - errMsg = launcher.getErrorMessage(); - indexer.createProblemMarker(CCorePlugin.getResourceString("CTagsIndexMarker.CTagsMissing"), resourceFile.getProject()); //$NON-NLS-1$ - } - - consoleOut.close(); - consoleErr.close(); - cos.close(); - - if (AbstractIndexerRunner.TIMING){ - System.out.println("CTagsIndexer Total Time: " + (System.currentTimeMillis() - startTime)); //$NON-NLS-1$ - System.out.flush(); - } - } - - private boolean useDefaultCTags(){ - try { - ICDescriptor cdesc = CCorePlugin.getDefault().getCProjectDescription(indexer.getProject(), false); - if (cdesc == null) - return true; - - ICExtensionReference[] cext = cdesc.get(CCorePlugin.INDEXER_UNIQ_ID); - if (cext.length > 0) { - for (int i = 0; i < cext.length; i++) { - String orig = cext[i].getExtensionData("ctagslocationtype"); //$NON-NLS-1$ - if (orig != null){ - if (orig.equals(CTagsIndexer.CTAGS_PATH_DEFAULT)) - return true; - else if (orig.equals(CTagsIndexer.CTAGS_PATH_SPECIFIED)) - return false; - } - } - } - } catch (CoreException e) {} - - return false; - } - - private boolean getCTagsLocation() { - try { - ICDescriptor cdesc = CCorePlugin.getDefault().getCProjectDescription(indexer.getProject(), false); - if (cdesc == null) - return false; - - ICExtensionReference[] cext = cdesc.get(CCorePlugin.INDEXER_UNIQ_ID); - if (cext.length > 0) { - for (int i = 0; i < cext.length; i++) { - String orig = cext[i].getExtensionData("ctagslocation"); //$NON-NLS-1$ - if (orig != null){ - ctagsLocation=orig; - return true; - } - } - } - } catch (CoreException e) {} - - return false; - } - - protected void addMarkers(IFile tempFile, IFile originator, Object problem, Object location) {} - - - - - -} diff --git a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/ctagsindexer/CTagsRemoveFromIndex.java b/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/ctagsindexer/CTagsRemoveFromIndex.java deleted file mode 100644 index 8a1e48ea6c4..00000000000 --- a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/ctagsindexer/CTagsRemoveFromIndex.java +++ /dev/null @@ -1,61 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.core.index.ctagsindexer; - -import java.io.IOException; - -import org.eclipse.cdt.internal.core.index.IIndex; -import org.eclipse.cdt.internal.core.search.indexing.IndexManager; -import org.eclipse.cdt.internal.core.search.indexing.ReadWriteMonitor; -import org.eclipse.cdt.internal.core.search.processing.JobManager; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.IProgressMonitor; - -/** - * @author Bogdan Gheorghe - */ -public class CTagsRemoveFromIndex extends CTagsIndexRequest { - String resourceName; - - public CTagsRemoveFromIndex(String resourceName, IPath indexPath, CTagsIndexer indexer) { - super(indexPath, indexer); - this.resourceName = resourceName; - } - - public boolean execute(IProgressMonitor progressMonitor) { - - if (progressMonitor != null && progressMonitor.isCanceled()) return true; - - /* ensure no concurrent write access to index */ - IIndex index = indexer.getIndex(this.indexPath, true, /*reuse index file*/ false /*create if none*/); - if (index == null) return true; - ReadWriteMonitor monitor = indexer.getMonitorFor(index); - if (monitor == null) return true; // index got deleted since acquired - - try { - monitor.enterWrite(); // ask permission to write - index.remove(resourceName); - } catch (IOException e) { - if (IndexManager.VERBOSE) { - JobManager.verbose("-> failed to remove " + this.resourceName + " from index because of the following exception:"); //$NON-NLS-1$ //$NON-NLS-2$ - e.printStackTrace(); - } - return false; - } finally { - monitor.exitWrite(); // free write lock - } - return true; - } - - public String toString() { - return "removing " + this.resourceName + " from index " + this.indexPath; //$NON-NLS-1$ //$NON-NLS-2$ - } -} diff --git a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/ctagsindexer/CTagsSaveIndex.java b/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/ctagsindexer/CTagsSaveIndex.java deleted file mode 100644 index c9c3686762b..00000000000 --- a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/ctagsindexer/CTagsSaveIndex.java +++ /dev/null @@ -1,57 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.core.index.ctagsindexer; - -import java.io.IOException; - -import org.eclipse.cdt.internal.core.index.IIndex; -import org.eclipse.cdt.internal.core.search.indexing.IndexManager; -import org.eclipse.cdt.internal.core.search.indexing.ReadWriteMonitor; -import org.eclipse.cdt.internal.core.search.processing.JobManager; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.IProgressMonitor; - -/** - * @author Bogdan Gheorghe - */ -public class CTagsSaveIndex extends CTagsIndexRequest { - public CTagsSaveIndex(IPath indexPath, CTagsIndexer indexer) { - super(indexPath, indexer); - } - - public boolean execute(IProgressMonitor progressMonitor) { - if (progressMonitor != null && progressMonitor.isCanceled()) return true; - - /* ensure no concurrent write access to index */ - IIndex index = indexer.getIndex(this.indexPath, true /*reuse index file*/, false /*don't create if none*/); - if (index == null) return true; - ReadWriteMonitor monitor = indexer.getMonitorFor(index); - if (monitor == null) return true; // index got deleted since acquired - - try { - monitor.enterWrite(); // ask permission to write - indexer.saveIndex(index); - } catch (IOException e) { - if (IndexManager.VERBOSE) { - JobManager.verbose("-> failed to save index " + this.indexPath + " because of the following exception:"); //$NON-NLS-1$ //$NON-NLS-2$ - e.printStackTrace(); - } - return false; - } finally { - monitor.exitWrite(); // free write lock - } - return true; - } - - public String toString() { - return "saving index for " + this.indexPath; //$NON-NLS-1$ - } -} diff --git a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/domsourceindexer/AbstractIndexerRunner.java b/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/domsourceindexer/AbstractIndexerRunner.java deleted file mode 100644 index 92011e8c9ee..00000000000 --- a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/domsourceindexer/AbstractIndexerRunner.java +++ /dev/null @@ -1,343 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ - -package org.eclipse.cdt.internal.core.index.domsourceindexer; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import org.eclipse.cdt.core.CCorePlugin; -import org.eclipse.cdt.core.model.ICModelMarker; -import org.eclipse.cdt.core.search.ICSearchConstants; -import org.eclipse.cdt.internal.core.Util; -import org.eclipse.cdt.internal.core.index.IIndexerRunner; -import org.eclipse.cdt.internal.core.index.IIndexerOutput; -import org.eclipse.cdt.internal.core.search.indexing.IndexManager; -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IMarker; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.resources.IWorkspaceRunnable; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.Status; -import org.eclipse.core.runtime.content.IContentType; -import org.eclipse.core.runtime.jobs.Job; - -public abstract class AbstractIndexerRunner implements IIndexerRunner, ICSearchConstants { - - public static boolean VERBOSE = false; - public static boolean TIMING = false; - - protected IIndexerOutput output; - - //Index Markers - private int problemMarkersEnabled = 0; - private Map problemsMap = null; - protected static final String INDEXER_MARKER_PREFIX = Util.bind("indexerMarker.prefix" ) + " "; //$NON-NLS-1$ //$NON-NLS-2$ - protected static final String INDEXER_MARKER_ORIGINATOR = ICModelMarker.INDEXER_MARKER + ".originator"; //$NON-NLS-1$ - private static final String INDEXER_MARKER_PROCESSING = Util.bind( "indexerMarker.processing" ); //$NON-NLS-1$ - protected IFile resourceFile; - - public AbstractIndexerRunner() { - super(); - } - - public static void verbose(String log) { - System.out.println("(" + Thread.currentThread() + ") " + log); //$NON-NLS-1$//$NON-NLS-2$ - } - - public IIndexerOutput getOutput() { - return output; - } - - - public Map getProblemsMap() { - return problemsMap; - } - - /** - * @see IIndexerRunner#index(IFile document, IIndexerOutput output) - */ - public void index(IFile file, IIndexerOutput output) throws IOException { - this.output = output; - if (shouldIndex(this.getResourceFile())) indexFile(file); - } - - protected abstract void indexFile(IFile file) throws IOException; - - /** - * @param fileToBeIndexed - * @see IIndexerRunner#shouldIndex(IFile file) - */ - public boolean shouldIndex(IFile fileToBeIndexed) { - if (fileToBeIndexed != null){ - String id = null; - IContentType contentType = CCorePlugin.getContentType(fileToBeIndexed.getProject(), fileToBeIndexed.getName()); - if (contentType != null) { - id = contentType.getId(); - } - if (id != null) { - if (CCorePlugin.CONTENT_TYPE_CXXHEADER.equals(id) - || CCorePlugin.CONTENT_TYPE_CXXSOURCE.equals(id) - || CCorePlugin.CONTENT_TYPE_CHEADER.equals(id) - || CCorePlugin.CONTENT_TYPE_CSOURCE.equals(id)) { - return true; - } else if (CCorePlugin.CONTENT_TYPE_ASMSOURCE.equals(id)) { - // FIXME: ALAIN - // What do we do here ? - } - } - } - - return false; - } - - protected abstract class Problem { - public IResource resource; - public IResource originator; - public Problem (IResource resource, IResource originator) { - this.resource = resource; - this.originator = originator; - } - /** - * Method to actually add/remove problem markers - */ - abstract public void run(); - } - - protected class FileInfoMarker extends Problem { - private String message; - public FileInfoMarker(IResource resource, IResource originator, String message) { - super(resource, originator); - this.message = message; - } - - public void run() { - try { - IMarker[] markers = resource.findMarkers(ICModelMarker.INDEXER_MARKER, true, IResource.DEPTH_ZERO); - - boolean newProblem = true; - - if (markers.length > 0) { - IMarker tempMarker = null; - String tempMsgString = null; - - for (int i=0; i 0) { - typeEntry.setBaseTypes((IIndexEntry[]) baseEntries.toArray(new IIndexEntry[baseEntries.size()])); - } - } - - /** - * @param name - * @param cppClassBinding - * @param typeEntry - * @param fileNumber - */ - private void addFriendDeclarations(IASTName name, ICPPClassType cppClassBinding, TypeEntry typeEntry, int fileNumber) { - IASTNode parent = name.getParent(); - if (parent instanceof ICPPASTCompositeTypeSpecifier) { - ICPPASTCompositeTypeSpecifier parentClass = (ICPPASTCompositeTypeSpecifier) parent; - List friendEntries = new ArrayList(); - IASTDeclaration[] members = parentClass.getMembers(); - for (int j = 0; j < members.length; j++) { - IASTDeclaration decl = members[j]; - if (decl instanceof IASTSimpleDeclaration) { - IASTSimpleDeclaration simplDecl = (IASTSimpleDeclaration) decl; - IASTDeclSpecifier declSpec = simplDecl.getDeclSpecifier(); - if (declSpec instanceof ICPPASTElaboratedTypeSpecifier) { - ICPPASTElaboratedTypeSpecifier elabTypeSpec = (ICPPASTElaboratedTypeSpecifier) declSpec; - if (elabTypeSpec.isFriend()) { - IASTName friendName = elabTypeSpec.getName(); - - IBinding friend = friendName.resolveBinding(); - if (friend != null && !(friend instanceof IProblemBinding)) { - int modifiers = IndexVisitorUtil.getModifiers(friendName, friend); - - NamedEntry namedEntry = new NamedEntry(IIndex.TYPE_FRIEND, IIndex.DECLARATION, - getFullyQualifiedName(friend), modifiers, fileNumber); - IASTFileLocation fileLoc = IndexEncoderUtil.getFileLocation(friendName); - namedEntry.setNameOffset(fileLoc.getNodeOffset(), fileLoc.getNodeLength(), IIndex.OFFSET); - friendEntries.add(namedEntry); - } - } - } - } - } - if (friendEntries.size() > 0) { - typeEntry.setFriends((IIndexEntry[]) friendEntries.toArray(new IIndexEntry[friendEntries.size()])); - } - } - } - - /** - * @param binding - * @return - */ - private char[][] getFullyQualifiedName(IBinding binding) { - try { - if (binding instanceof ICPPBinding) { - return ((ICPPBinding) binding).getQualifiedNameCharArray(); - } - } - catch (DOMException e) { - } - return new char[][] {binding.getNameCharArray()}; - } - -} diff --git a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/domsourceindexer/CleanEncounteredHeaders.java b/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/domsourceindexer/CleanEncounteredHeaders.java deleted file mode 100644 index ae9bb972b6f..00000000000 --- a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/domsourceindexer/CleanEncounteredHeaders.java +++ /dev/null @@ -1,64 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -/* - * Created on Aug 19, 2004 - * - * TODO To change the template for this generated file go to - * Window - Preferences - Java - Code Style - Code Templates - */ -package org.eclipse.cdt.internal.core.index.domsourceindexer; - -import org.eclipse.cdt.internal.core.search.processing.IIndexJob; -import org.eclipse.core.runtime.IProgressMonitor; - -/** - * @author bgheorgh - * - * TODO To change the template for this generated type comment go to - * Window - Preferences - Java - Code Style - Code Templates - */ -public class CleanEncounteredHeaders implements IIndexJob { - - DOMSourceIndexer indexer = null; - - public CleanEncounteredHeaders(DOMSourceIndexer indexer){ - this.indexer = indexer; - } - /* (non-Javadoc) - * @see org.eclipse.cdt.internal.core.search.processing.IJob#execute(org.eclipse.core.runtime.IProgressMonitor) - */ - public boolean execute(IProgressMonitor progress) { - indexer.resetEncounteredHeaders(); - return true; - } - /* (non-Javadoc) - * @see org.eclipse.cdt.internal.core.search.processing.IJob#belongsTo(java.lang.String) - */ - public boolean belongsTo(String jobFamily) { - // TODO Auto-generated method stub - return false; - } - /* (non-Javadoc) - * @see org.eclipse.cdt.internal.core.search.processing.IJob#cancel() - */ - public void cancel() { - // TODO Auto-generated method stub - - } - /* (non-Javadoc) - * @see org.eclipse.cdt.internal.core.search.processing.IJob#isReadyToRun() - */ - public boolean isReadyToRun() { - // TODO Auto-generated method stub - return true; - } - -} diff --git a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/domsourceindexer/DOMAddCompilationUnitToIndex.java b/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/domsourceindexer/DOMAddCompilationUnitToIndex.java deleted file mode 100644 index 67ab2fe1536..00000000000 --- a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/domsourceindexer/DOMAddCompilationUnitToIndex.java +++ /dev/null @@ -1,45 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ - -package org.eclipse.cdt.internal.core.index.domsourceindexer; - -import java.io.IOException; - -import org.eclipse.cdt.internal.core.index.IIndex; -import org.eclipse.core.resources.IFile; -import org.eclipse.core.runtime.IPath; - -public class DOMAddCompilationUnitToIndex extends DOMAddFileToIndex { - protected char[] contents; - - public DOMAddCompilationUnitToIndex(IFile resource, IPath indexedContainer, DOMSourceIndexer indexer, boolean checkEncounteredHeaders) { - super(resource, indexedContainer, indexer, checkEncounteredHeaders); - } - - protected boolean indexDocument(IIndex index) throws IOException { - if (!initializeContents()) return false; - index.add(resource, new DOMSourceIndexerRunner(resource, indexer)); - - return true; - } - - public boolean initializeContents() { - if (this.contents == null) { - try { - IPath location = resource.getLocation(); - if (location != null) - this.contents = org.eclipse.cdt.internal.core.Util.getFileCharContent(location.toFile(), null); - } catch (IOException e) { - } - } - return this.contents != null; - } -} diff --git a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/domsourceindexer/DOMAddFileToIndex.java b/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/domsourceindexer/DOMAddFileToIndex.java deleted file mode 100644 index 45b526207a3..00000000000 --- a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/domsourceindexer/DOMAddFileToIndex.java +++ /dev/null @@ -1,87 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.core.index.domsourceindexer; - -import java.io.IOException; - -import org.eclipse.cdt.core.ICLogConstants; -import org.eclipse.cdt.core.model.CoreModel; -import org.eclipse.cdt.internal.core.index.IIndex; -import org.eclipse.cdt.internal.core.search.indexing.IndexManager; -import org.eclipse.cdt.internal.core.search.indexing.ReadWriteMonitor; -import org.eclipse.cdt.internal.core.search.processing.JobManager; -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.IProgressMonitor; - -public abstract class DOMAddFileToIndex extends DOMIndexRequest { - protected IFile resource; - private boolean checkEncounteredHeaders; - - public DOMAddFileToIndex(IFile resource, IPath indexPath, DOMSourceIndexer indexer, boolean checkEncounteredHeaders) { - super(indexPath, indexer); - this.resource = resource; - this.checkEncounteredHeaders = checkEncounteredHeaders; - } - - public DOMAddFileToIndex(IFile resource, IPath indexPath, DOMSourceIndexer indexer) { - this(resource,indexPath,indexer,false); - } - - public boolean execute(IProgressMonitor progressMonitor) { - if (progressMonitor != null && progressMonitor.isCanceled()) return true; - - if (checkEncounteredHeaders) { - IProject resourceProject = resource.getProject(); - /* Check to see if this is a header file */ - boolean isHeader = CoreModel.isValidHeaderUnitName(resourceProject, resource.getName()); - /* See if this file has been encountered before */ - if (isHeader && - indexer.haveEncounteredHeader(resourceProject.getFullPath(),resource.getLocation(), true)) - return true; - } - /* ensure no concurrent write access to index */ - IIndex index = indexer.getIndex(this.indexPath, true, /*reuse index file*/ true /*create if none*/); - if (index == null) return true; - ReadWriteMonitor monitor = indexer.getMonitorFor(index); - if (monitor == null) return true; // index got deleted since acquired - try { - monitor.enterWrite(); // ask permission to write - if (!indexDocument(index)) return false; - } catch (IOException e) { - org.eclipse.cdt.internal.core.model.Util.log(null, "Index I/O Exception: " + e.getMessage() + " on File: " + resource.getName(), ICLogConstants.CDT); //$NON-NLS-1$ //$NON-NLS-2$ - if (IndexManager.VERBOSE) { - JobManager.verbose("-> failed to index " + this.resource + " because of the following exception:"); //$NON-NLS-1$ //$NON-NLS-2$ - e.printStackTrace(); - } - return false; - } finally { - monitor.exitWrite(); // free write lock - } - return true; - } - - protected abstract boolean indexDocument(IIndex index) throws IOException; - - public String toString() { - return "indexing " + this.resource.getFullPath(); //$NON-NLS-1$ - } - - /** - * The resource being indexed - * @return - */ - public IResource getResource(){ - return resource; - } -} diff --git a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/domsourceindexer/DOMAddFolderToIndex.java b/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/domsourceindexer/DOMAddFolderToIndex.java deleted file mode 100644 index 3d689c7a88d..00000000000 --- a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/domsourceindexer/DOMAddFolderToIndex.java +++ /dev/null @@ -1,130 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ - -package org.eclipse.cdt.internal.core.index.domsourceindexer; - -import java.util.ArrayList; - -import org.eclipse.cdt.core.model.CoreModel; -import org.eclipse.cdt.internal.core.Util; -import org.eclipse.cdt.internal.core.index.IIndex; -import org.eclipse.cdt.internal.core.search.indexing.IndexManager; -import org.eclipse.cdt.internal.core.search.indexing.ReadWriteMonitor; -import org.eclipse.cdt.internal.core.search.processing.JobManager; -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.resources.IResourceProxy; -import org.eclipse.core.resources.IResourceProxyVisitor; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.IProgressMonitor; - -public class DOMAddFolderToIndex extends DOMIndexRequest { - IPath folderPath; - IProject project; - char[][] exclusionPattern; - ArrayList sourceFilesToIndex; - ArrayList headerFilesToIndex; - - public DOMAddFolderToIndex(IPath folderPath, IProject project, char[][] exclusionPattern, DOMSourceIndexer indexer) { - super(project.getFullPath(), indexer); - this.folderPath = folderPath; - this.project = project; - this.exclusionPattern = exclusionPattern; - this.sourceFilesToIndex = new ArrayList(); - this.headerFilesToIndex = new ArrayList(); - } - - public boolean execute(IProgressMonitor progressMonitor) { - if (progressMonitor != null && progressMonitor.isCanceled()) return true; - - if (!project.isAccessible()) return true; // nothing to do - IResource folder = this.project.getParent().findMember(this.folderPath); - if (folder == null || folder.getType() == IResource.FILE) return true; // nothing to do, source folder was removed - - /* ensure no concurrent write access to index */ - IIndex index = indexer.getIndex(this.indexPath, true, /*reuse index file*/ true /*create if none*/); - if (index == null) return true; - ReadWriteMonitor monitor = indexer.getMonitorFor(index); - if (monitor == null) return true; // index got deleted since acquired - - try { - monitor.enterRead(); // ask permission to read - - // final IPath container = this.indexPath; - //final IndexManager indexManager = this.manager; - final char[][] pattern = exclusionPattern; - folder.accept( - new IResourceProxyVisitor() { - public boolean visit(IResourceProxy proxy) throws CoreException { - switch(proxy.getType()) { - case IResource.FILE : - IResource resource = proxy.requestResource(); - if (CoreModel.isValidTranslationUnitName(resource.getProject(),resource.getName())) { - if (pattern == null || !Util.isExcluded(resource, pattern)) - //indexManager.addSource((IFile)resource, container); - sortFiles((IFile) resource); - } - return false; - case IResource.FOLDER : - if (pattern != null && Util.isExcluded(proxy.requestResource(), pattern)) - return false; - } - return true; - } - }, - IResource.NONE - ); - scheduleJobs(); - } catch (CoreException e) { - if (IndexManager.VERBOSE) { - JobManager.verbose("-> failed to add " + this.folderPath + " to index because of the following exception:"); //$NON-NLS-1$ //$NON-NLS-2$ - e.printStackTrace(); - } - return false; - } finally { - monitor.exitRead(); // free read lock - } - return true; - } - - /** - * - */ - private void scheduleJobs() { - //Schedule the source jobs first, then the headers - for (int i=0; i failed to index " + this.project + " because of the following exception:"); //$NON-NLS-1$ //$NON-NLS-2$ - e.printStackTrace(); - } - indexer.removeIndex(this.indexPath); - return false; - } catch (IOException e) { - if (IndexManager.VERBOSE) { - JobManager.verbose("-> failed to index " + this.project + " because of the following exception:"); //$NON-NLS-1$ //$NON-NLS-2$ - e.printStackTrace(); - } - indexer.removeIndex(this.indexPath); - return false; - } finally { - monitor.exitRead(); // free read lock - } - return true; - } - - public int hashCode() { - return this.project.hashCode(); - } - - protected Integer updatedIndexState() { - return CIndexStorage.REBUILDING_STATE; - } - - public String toString() { - return "indexing project " + this.project.getFullPath(); //$NON-NLS-1$ - } -} diff --git a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/domsourceindexer/DOMIndexRequest.java b/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/domsourceindexer/DOMIndexRequest.java deleted file mode 100644 index 67d6cb08333..00000000000 --- a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/domsourceindexer/DOMIndexRequest.java +++ /dev/null @@ -1,63 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ - -package org.eclipse.cdt.internal.core.index.domsourceindexer; - -import java.io.IOException; - -import org.eclipse.cdt.core.CCorePlugin; -import org.eclipse.cdt.internal.core.index.IIndex; -import org.eclipse.cdt.internal.core.index.IndexRequest; -import org.eclipse.cdt.internal.core.search.indexing.ReadWriteMonitor; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.runtime.IPath; - -public abstract class DOMIndexRequest extends IndexRequest { - - protected DOMSourceIndexer indexer = null; - - public DOMIndexRequest(IPath indexPath, DOMSourceIndexer indexer) { - super(indexPath); - this.indexer = indexer; - } - - public void cancel() { - indexer.jobFinishedNotification( this ); - indexer.jobWasCancelled(this.indexPath); - this.isCancelled = true; - } - - public boolean isReadyToRun() { - IProject project = CCorePlugin.getWorkspace().getRoot().getProject(indexPath.segment(0)); - if ( !project.isAccessible() || !this.indexer.isIndexEnabled( project ) ) - return false; - - // tag the index as inconsistent - indexer.aboutToUpdateIndex(indexPath, updatedIndexState()); - return true; - } - /* - * This code is assumed to be invoked while monitor has read lock - */ - protected void saveIfNecessary(IIndex index, ReadWriteMonitor monitor) throws IOException { - /* if index has changed, commit these before querying */ - if (index.hasChanged()) { - try { - monitor.exitRead(); // free read lock - monitor.enterWrite(); // ask permission to write - indexer.saveIndex(index); - } finally { - monitor.exitWriteEnterRead(); // finished writing and reacquire read permission - } - } - } - -} diff --git a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/domsourceindexer/DOMRemoveFolderFromIndex.java b/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/domsourceindexer/DOMRemoveFolderFromIndex.java deleted file mode 100644 index 95807c579c3..00000000000 --- a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/domsourceindexer/DOMRemoveFolderFromIndex.java +++ /dev/null @@ -1,74 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ - -package org.eclipse.cdt.internal.core.index.domsourceindexer; - -import java.io.IOException; - -import org.eclipse.cdt.internal.core.Util; -import org.eclipse.cdt.internal.core.index.IIndex; -import org.eclipse.cdt.internal.core.index.IQueryResult; -import org.eclipse.cdt.internal.core.search.indexing.IndexManager; -import org.eclipse.cdt.internal.core.search.indexing.ReadWriteMonitor; -import org.eclipse.cdt.internal.core.search.processing.JobManager; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.Path; - -public class DOMRemoveFolderFromIndex extends DOMIndexRequest { - IPath folderPath; - char[][] exclusionPatterns; - IProject project; - - public DOMRemoveFolderFromIndex(IPath folderPath, char[][] exclusionPatterns, IProject project, DOMSourceIndexer indexer) { - super(project.getFullPath(), indexer); - this.folderPath = folderPath; - this.exclusionPatterns = exclusionPatterns; - this.project = project; - } - - public boolean execute(IProgressMonitor progressMonitor) { - if (progressMonitor != null && progressMonitor.isCanceled()) return true; - - /* ensure no concurrent write access to index */ - IIndex index = indexer.getIndex(this.indexPath, true, /*reuse index file*/ false /*create if none*/); - if (index == null) return true; - ReadWriteMonitor monitor = indexer.getMonitorFor(index); - if (monitor == null) return true; // index got deleted since acquired - - try { - monitor.enterRead(); // ask permission to read - IQueryResult[] results = index.queryInDocumentNames(this.folderPath.toString()); - // all file names belonging to the folder or its subfolders and that are not excluded (see http://bugs.eclipse.org/bugs/show_bug.cgi?id=32607) - for (int i = 0, max = results == null ? 0 : results.length; i < max; i++) { - String documentPath = results[i].getPath(); - if (this.exclusionPatterns == null || !Util.isExcluded(new Path(documentPath), this.exclusionPatterns)) { - indexer.remove(documentPath, this.indexPath); // write lock will be acquired by the remove operation - } - } - } catch (IOException e) { - if (IndexManager.VERBOSE) { - JobManager.verbose("-> failed to remove " + this.folderPath + " from index because of the following exception:"); //$NON-NLS-1$ //$NON-NLS-2$ - e.printStackTrace(); - } - return false; - } finally { - monitor.exitRead(); // free read lock - } - return true; - } - - public String toString() { - return "removing " + this.folderPath + " from index " + this.indexPath; //$NON-NLS-1$ //$NON-NLS-2$ - } -} - diff --git a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/domsourceindexer/DOMRemoveFromIndex.java b/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/domsourceindexer/DOMRemoveFromIndex.java deleted file mode 100644 index 6852da5c27b..00000000000 --- a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/domsourceindexer/DOMRemoveFromIndex.java +++ /dev/null @@ -1,59 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ - -package org.eclipse.cdt.internal.core.index.domsourceindexer; - -import java.io.IOException; - -import org.eclipse.cdt.internal.core.index.IIndex; -import org.eclipse.cdt.internal.core.search.indexing.IndexManager; -import org.eclipse.cdt.internal.core.search.indexing.ReadWriteMonitor; -import org.eclipse.cdt.internal.core.search.processing.JobManager; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.IProgressMonitor; - -public class DOMRemoveFromIndex extends DOMIndexRequest { - String resourceName; - - public DOMRemoveFromIndex(String resourceName, IPath indexPath, DOMSourceIndexer indexer) { - super(indexPath, indexer); - this.resourceName = resourceName; - } - - public boolean execute(IProgressMonitor progressMonitor) { - - if (progressMonitor != null && progressMonitor.isCanceled()) return true; - - /* ensure no concurrent write access to index */ - IIndex index = indexer.getIndex(this.indexPath, true, /*reuse index file*/ false /*create if none*/); - if (index == null) return true; - ReadWriteMonitor monitor = indexer.getMonitorFor(index); - if (monitor == null) return true; // index got deleted since acquired - - try { - monitor.enterWrite(); // ask permission to write - index.remove(resourceName); - } catch (IOException e) { - if (IndexManager.VERBOSE) { - JobManager.verbose("-> failed to remove " + this.resourceName + " from index because of the following exception:"); //$NON-NLS-1$ //$NON-NLS-2$ - e.printStackTrace(); - } - return false; - } finally { - monitor.exitWrite(); // free write lock - } - return true; - } - - public String toString() { - return "removing " + this.resourceName + " from index " + this.indexPath; //$NON-NLS-1$ //$NON-NLS-2$ - } -} diff --git a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/domsourceindexer/DOMSaveIndex.java b/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/domsourceindexer/DOMSaveIndex.java deleted file mode 100644 index 2b610754928..00000000000 --- a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/domsourceindexer/DOMSaveIndex.java +++ /dev/null @@ -1,58 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ - -package org.eclipse.cdt.internal.core.index.domsourceindexer; - -import java.io.IOException; - -import org.eclipse.cdt.internal.core.index.IIndex; -import org.eclipse.cdt.internal.core.search.indexing.IndexManager; -import org.eclipse.cdt.internal.core.search.indexing.ReadWriteMonitor; -import org.eclipse.cdt.internal.core.search.processing.JobManager; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.IProgressMonitor; - -/* - * Save the index of a project. - */ -public class DOMSaveIndex extends DOMIndexRequest { - public DOMSaveIndex(IPath indexPath, DOMSourceIndexer indexer) { - super(indexPath, indexer); - } - - public boolean execute(IProgressMonitor progressMonitor) { - if (progressMonitor != null && progressMonitor.isCanceled()) return true; - - /* ensure no concurrent write access to index */ - IIndex index = indexer.getIndex(this.indexPath, true /*reuse index file*/, false /*don't create if none*/); - if (index == null) return true; - ReadWriteMonitor monitor = indexer.getMonitorFor(index); - if (monitor == null) return true; // index got deleted since acquired - - try { - monitor.enterWrite(); // ask permission to write - indexer.saveIndex(index); - } catch (IOException e) { - if (IndexManager.VERBOSE) { - JobManager.verbose("-> failed to save index " + this.indexPath + " because of the following exception:"); //$NON-NLS-1$ //$NON-NLS-2$ - e.printStackTrace(); - } - return false; - } finally { - monitor.exitWrite(); // free write lock - } - return true; - } - - public String toString() { - return "saving index for " + this.indexPath; //$NON-NLS-1$ - } -} diff --git a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/domsourceindexer/DOMSourceIndexer.java b/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/domsourceindexer/DOMSourceIndexer.java deleted file mode 100644 index 5e761bd2268..00000000000 --- a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/domsourceindexer/DOMSourceIndexer.java +++ /dev/null @@ -1,688 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.core.index.domsourceindexer; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; - -import org.eclipse.cdt.core.AbstractCExtension; -import org.eclipse.cdt.core.CCorePlugin; -import org.eclipse.cdt.core.ICDescriptor; -import org.eclipse.cdt.core.ICExtensionReference; -import org.eclipse.cdt.core.ICLogConstants; -import org.eclipse.cdt.core.index.ICDTIndexer; -import org.eclipse.cdt.core.index.IIndexChangeListener; -import org.eclipse.cdt.core.index.IIndexStorage; -import org.eclipse.cdt.core.index.IndexChangeEvent; -import org.eclipse.cdt.core.model.CoreModel; -import org.eclipse.cdt.core.parser.util.ObjectSet; -import org.eclipse.cdt.internal.core.Util; -import org.eclipse.cdt.internal.core.index.IIndex; -import org.eclipse.cdt.internal.core.index.cindexstorage.CIndexStorage; -import org.eclipse.cdt.internal.core.index.impl.IndexDelta; -import org.eclipse.cdt.internal.core.search.SimpleLookupTable; -import org.eclipse.cdt.internal.core.search.indexing.IndexManager; -import org.eclipse.cdt.internal.core.search.indexing.ReadWriteMonitor; -import org.eclipse.cdt.internal.core.search.processing.IIndexJob; -import org.eclipse.cdt.internal.core.sourcedependency.UpdateDependency; -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IFolder; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.resources.IResourceDelta; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.ISafeRunnable; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.Platform; -import org.eclipse.core.runtime.QualifiedName; -import org.eclipse.core.runtime.Status; -import org.eclipse.core.runtime.jobs.Job; - -/** - * @author Bogdan Gheorghe - */ -public class DOMSourceIndexer extends AbstractCExtension implements ICDTIndexer { - - public static boolean VERBOSE = false; - - //private IndexerModelListener indexModelListener = null; - - /** - * Collection of listeners for indexer deltas - */ - protected List indexChangeListeners = Collections.synchronizedList(new ArrayList()); - public static final String INDEX_NOTIFICATION_NAME = Util.bind( "indexNotificationJob" ); //$NON-NLS-1$ - - public final static String INDEX_MODEL_ID = CCorePlugin.PLUGIN_ID + ".newindexmodel"; //$NON-NLS-1$ - public final static String ACTIVATION = "enable"; //$NON-NLS-1$ - public final static String PROBLEM_ACTIVATION = "problemEnable"; //$NON-NLS-1$ - public final static QualifiedName activationKey = new QualifiedName(INDEX_MODEL_ID, ACTIVATION); - public final static QualifiedName problemsActivationKey = new QualifiedName( INDEX_MODEL_ID, PROBLEM_ACTIVATION ); - - public static final int PREPROCESSOR_PROBLEMS_BIT = 1; - public static final int SEMANTIC_PROBLEMS_BIT = 1 << 1; - public static final int SYNTACTIC_PROBLEMS_BIT = 1 << 2; - public static final int INCLUSION_PROBLEMS_BIT = 1 << 3; - - public static final String SOURCE_INDEXER_ID = "originalsourceindexer"; //$NON-NLS-1$ - public static final String SOURCE_INDEXER_UNIQUE_ID = CCorePlugin.PLUGIN_ID + "." + SOURCE_INDEXER_ID; //$NON-NLS-1$; - - - private CIndexStorage indexStorage = null; - protected ReadWriteMonitor storageMonitor = null; - protected IndexManager indexManager = null; - - protected HashSet jobSet = null; - - protected long totalIndexTime = 0; - - public static String ID = CCorePlugin.PLUGIN_ID + ".domsourceindexer"; //$NON-NLS-1$ - - public DOMSourceIndexer(){ - this.indexManager = CCorePlugin.getDefault().getCoreModel().getIndexManager(); - this.indexStorage = (CIndexStorage) indexManager.getIndexStorageForIndexer(this); - this.jobSet = new HashSet(); - this.storageMonitor = new ReadWriteMonitor(); - } - - /** - * @return - */ - public IIndexStorage getIndexStorage() { - return indexStorage; - } - - - public void addSource(IFile resource, IPath indexedContainers){ - this.addSource(resource,indexedContainers, false); - } - - /** - * Trigger addition of a resource to an index - * Note: the actual operation is performed in background - * @param checkEncounteredHeaders TODO - */ - public void addSource(IFile resource, IPath indexedContainers, boolean checkEncounteredHeaders) { - IProject project = resource.getProject(); - - boolean indexEnabled = false; - if (project != null) - indexEnabled = isIndexEnabled(project); - else - org.eclipse.cdt.internal.core.model.Util.log(null, "IndexManager addSource: File has no project associated : " + resource.getName(), ICLogConstants.CDT); //$NON-NLS-1$ - - if (CCorePlugin.getDefault() == null) return; - - if (indexEnabled){ - DOMAddCompilationUnitToIndex job = new DOMAddCompilationUnitToIndex(resource, indexedContainers, this, checkEncounteredHeaders); - - //If we are in WAITING mode, we need to kick ourselves into enablement - if (!jobSet.add(resource.getLocation()) && - indexManager.enabledState()==IndexManager.ENABLED) - return; - - - if (indexManager.awaitingJobsCount() < CIndexStorage.MAX_FILES_IN_MEMORY) { - // reduces the chance that the file is open later on, preventing it from being deleted - if (!job.initializeContents()) return; - } - - this.indexManager.request(job); - } - } - - - - - public void updateDependencies(IResource resource){ - if (CCorePlugin.getDefault() == null || !isIndexEnabled( resource.getProject() ) ) - return; - - UpdateDependency job = new UpdateDependency(resource, this); - indexManager.request(job); - } - - /** - * - * - * Warning: Does not check whether index is consistent (not being used) - */ - public static int trimed = 0; - public static int added = 0; - - public synchronized boolean haveEncounteredHeader(IPath projectPath, IPath filePath, boolean add) { - SimpleLookupTable headerTable = indexStorage.getEncounteredHeaders(); - - // Path is already canonical per construction - ObjectSet headers = (ObjectSet) headerTable.get(projectPath); - if (headers == null) { - //First time for the project, must create a new ObjectSet - headers = new ObjectSet(4); - headerTable.put(projectPath, headers); - } - - if (headers.containsKey(filePath.toOSString())) { - trimed++; - return true; - } - - if (add) { - headers.put(filePath.toOSString()); - added++; - } - - return false; - } - - // lighter version of the same method - public synchronized boolean haveEncounteredHeader(IPath projectPath, String filePath) { - SimpleLookupTable headerTable = indexStorage.getEncounteredHeaders(); - - // Path is already canonical per construction - ObjectSet headers = (ObjectSet) headerTable.get(projectPath); - if (headers == null) { - //First time for the project, must create a new ObjectSet - headers = new ObjectSet(4); - headerTable.put(projectPath, headers); - } - - if (headers.containsKey(filePath)) { - trimed++; - return true; - } - - return false; - } - - - /** - * Trigger addition of the entire content of a project - * Note: the actual operation is performed in background - */ - public void indexAll(IProject project) { - if (CCorePlugin.getDefault() == null) return; - - //check to see if indexing isEnabled for this project - boolean indexEnabled = isIndexEnabled(project); - - if (indexEnabled){ - if( indexManager.enabledState() == IndexManager.WAITING ){ - //if we are paused because the user cancelled a previous index, this is a good - //enough reason to restart - indexManager.enable(); - } - // check if the same request is not already in the queue - DOMIndexRequest request = new DOMIndexAllProject(project, this); - for (int i = indexManager.getJobEnd(); i > indexManager.getJobStart(); i--) // NB: don't check job at jobStart, as it may have already started (see http://bugs.eclipse.org/bugs/show_bug.cgi?id=32488) - if (request.equals(indexManager.getAwaitingJobAt(i))) return; - indexManager.request(request); - } - } - - /** - * @param project - * @return - */ - public boolean isIndexEnabled(IProject project) { - if( project == null || !project.exists() || !project.isOpen() ) - return false; - - return true; - /*Boolean indexValue = null; - - try { - indexValue = (Boolean) project.getSessionProperty(activationKey); - } catch (CoreException e) {} - - if (indexValue != null) - return indexValue.booleanValue(); - - try { - ICDescriptor cdesc = CCorePlugin.getDefault().getCProjectDescription(project, false); - if (cdesc == null) - return false; - - ICExtensionReference[] cext = cdesc.get(CCorePlugin.INDEXER_UNIQ_ID); - if (cext.length > 0) { - //initializeIndexerId(); - for (int i = 0; i < cext.length; i++) { - String id = cext[i].getID(); - String orig = cext[i].getExtensionData("indexenabled"); //$NON-NLS-1$ - if (orig != null){ - Boolean tempBool = new Boolean(orig); - indexEnabled = tempBool.booleanValue(); - } - } - } - - - } catch (CoreException e) {} - - return indexEnabled;*/ - } - - - - public int indexProblemsEnabled(IProject project) { - - if( project == null || !project.exists() || !project.isOpen() ) - return 0; - - int indexProblemsEnabled = 0; - try { - ICDescriptor cdesc = CCorePlugin.getDefault().getCProjectDescription(project, false); - if (cdesc == null) - return 0; - - ICExtensionReference[] cext = cdesc.get(CCorePlugin.INDEXER_UNIQ_ID); - if (cext.length > 0) { - //initializeIndexerId(); - for (int i = 0; i < cext.length; i++) { - String orig = cext[i].getExtensionData("indexmarkers"); //$NON-NLS-1$ - if (orig != null){ - Integer tempInt = new Integer(orig); - indexProblemsEnabled = tempInt.intValue(); - } - } - } - - - } catch (CoreException e) {} - - return indexProblemsEnabled; - } - /** - * Index the content of the given source folder. - */ - public void indexSourceFolder(IProject project, IPath sourceFolder, final char[][] exclusionPattern) { - if( !isIndexEnabled( project ) ) - return; - if (indexManager.getJobEnd() > indexManager.getJobStart()) { - // check if a job to index the project is not already in the queue - DOMIndexRequest request = new DOMIndexAllProject(project, this); - for (int i = indexManager.getJobEnd(); i > indexManager.getJobStart(); i--) // NB: don't check job at jobStart, as it may have already started (see http://bugs.eclipse.org/bugs/show_bug.cgi?id=32488) - if (request.equals(indexManager.getAwaitingJobAt(i))) return; - } - this.request(new DOMAddFolderToIndex(sourceFolder, project, exclusionPattern, this)); - } - - /** - * Trigger removal of a resource to an index - * Note: the actual operation is performed in background - */ - public void remove(String resourceName, IPath indexedContainer){ - IProject project = CCorePlugin.getWorkspace().getRoot().getProject(indexedContainer.toString()); - if( isIndexEnabled( project ) ) - request(new DOMRemoveFromIndex(resourceName, indexedContainer, this)); - } - - - /** - * Remove the content of the given source folder from the index. - */ - public void removeSourceFolderFromIndex(IProject project, IPath sourceFolder, char[][] exclusionPatterns) { - - if( !isIndexEnabled( project ) ) - return; - - if (indexManager.getJobEnd()> indexManager.getJobStart()) { - // check if a job to index the project is not already in the queue - DOMIndexRequest request = new DOMIndexAllProject(project, this); - for (int i = indexManager.getJobEnd(); i > indexManager.getJobStart(); i--) // NB: don't check job at jobStart, as it may have already started (see http://bugs.eclipse.org/bugs/show_bug.cgi?id=32488) - if (request.equals(indexManager.getAwaitingJobAt(i))) return; - } - - this.request(new DOMRemoveFolderFromIndex(sourceFolder, exclusionPatterns, project, this)); - } - - - /* (non-Javadoc) - * @see org.eclipse.cdt.internal.core.search.processing.JobManager#jobFinishedNotification(org.eclipse.cdt.internal.core.search.processing.IJob) - */ - public void jobFinishedNotification(IIndexJob job) { - this.indexJobFinishedNotification(job); - - } - - public void removeIndexerProblems( IResource resource){ - indexManager.removeIndexerProblems(resource); - } - - public void addIndexChangeListener(IIndexChangeListener listener) { - synchronized(indexChangeListeners) { - if (!indexChangeListeners.contains(listener)) { - indexChangeListeners.add(listener); - } - } - } - - public void removeIndexChangeListener(IIndexChangeListener listener) { - synchronized(indexChangeListeners) { - int i = indexChangeListeners.indexOf(listener); - if (i != -1) { - indexChangeListeners.remove(i); - } - } - } - /** - * @param indexDelta - */ - public void notifyListeners(IndexDelta indexDelta) { - final IndexChangeEvent indexEvent = new IndexChangeEvent(indexDelta); - for (int i= 0; i < indexChangeListeners.size(); i++) { - IIndexChangeListener tempListener = null; - synchronized(indexChangeListeners){ - tempListener = (IIndexChangeListener) indexChangeListeners.get(i); - } - final IIndexChangeListener listener = tempListener; - long start = -1; - if (VERBOSE) { - System.out.print("Listener #" + (i+1) + "=" + listener.toString());//$NON-NLS-1$//$NON-NLS-2$ - start = System.currentTimeMillis(); - } - - // wrap callbacks with Safe runnable for subsequent listeners to be called when some are causing grief - Job job = new Job(INDEX_NOTIFICATION_NAME){ - protected IStatus run(IProgressMonitor monitor) { - Platform.run(new ISafeRunnable() { - public void handleException(Throwable exception) { - CCorePlugin.log(exception); - } - public void run() throws Exception { - listener.indexChanged(indexEvent); - } - }); - - return Status.OK_STATUS; - } - }; - - job.schedule(); - if (VERBOSE) { - System.out.println(" -> " + (System.currentTimeMillis()-start) + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ - } - } - - } - - /** - * No more job awaiting. - */ - public void notifyIdle(long idlingTime){ - if (idlingTime > 1000 && indexStorage.getNeedToSave()) - indexStorage.saveIndexes(); - } - - /* (non-Javadoc) - * @see org.eclipse.cdt.core.index2.IIndexer#getIndexerFeatures() - */ - public int getIndexerFeatures() { - return ICDTIndexer._DECLARATIONS | ICDTIndexer._DEFINITIONS | ICDTIndexer._REFERENCES | ICDTIndexer._OFFSETINFO | ICDTIndexer._C | ICDTIndexer._CPP; - } - - /* (non-Javadoc) - * @see org.eclipse.cdt.core.index2.IIndexer#addRequest(org.eclipse.cdt.core.model.ICElement, org.eclipse.core.resources.IResourceDelta, org.eclipse.core.resources.IResourceChangeEvent) - */ - public void addRequest(IProject project, IResourceDelta delta, int kind) { - - switch (kind) { - case ICDTIndexer.PROJECT : - this.indexAll(project); - break; - - case ICDTIndexer.FOLDER : - this.indexSourceFolder(project,delta.getFullPath(),null); - break; - - case ICDTIndexer.COMPILATION_UNIT: - //if the element has changed check to see if file is header, if it is don't schedule for index - update dependencies will - //take care of it. - //otherwise just schedule element for index - boolean shouldAddFile=false; - IFile file = (IFile) delta.getResource(); - - if (delta.getKind()==IResourceDelta.CHANGED){ - if (CoreModel.isValidSourceUnitName(project, file.getName())) - shouldAddFile=true; - } else { - shouldAddFile = true; - } - if (shouldAddFile){ - this.addSource(file, project.getFullPath()); - } - break; - } - - - } - - /* (non-Javadoc) - * @see org.eclipse.cdt.core.index2.IIndexer#removeRequest(org.eclipse.cdt.core.model.ICElement, org.eclipse.core.resources.IResourceDelta, org.eclipse.core.resources.IResourceChangeEvent) - */ - public void removeRequest(IProject project, IResourceDelta delta, int kind) { - switch (kind) { - case ICDTIndexer.PROJECT : - IPath fullPath = project.getFullPath(); - if( delta.getKind() == IResourceDelta.CHANGED ) - indexManager.discardJobs(fullPath.segment(0)); - indexStorage.removeIndexFamily(fullPath); - // NB: Discarding index jobs belonging to this project was done during PRE_DELETE - break; - // NB: Update of index if project is opened, closed, or its c nature is added or removed - // is done in updateCurrentDeltaAndIndex - - case ICDTIndexer.FOLDER : - this.removeSourceFolderFromIndex(project,delta.getFullPath(),null); - break; - - case ICDTIndexer.COMPILATION_UNIT: - IFile file = (IFile) delta.getResource(); - this.remove(file.getFullPath().toString(), file.getProject().getFullPath()); - break; - } - - } - - /* (non-Javadoc) - * @see org.eclipse.cdt.core.index2.IIndexer#indexJobFinishedNotification(org.eclipse.cdt.internal.core.search.processing.IIndexJob) - */ - public void indexJobFinishedNotification(IIndexJob job) { - indexStorage.setNeedToSave(true); - - if (job instanceof DOMAddCompilationUnitToIndex){ - DOMAddCompilationUnitToIndex tempJob = (DOMAddCompilationUnitToIndex) job; - jobSet.remove(tempJob.getResource().getLocation()); - } - - } - - /* (non-Javadoc) - * @see org.eclipse.cdt.core.index2.IIndexer#shutdown() - */ - public void shutdown() { - indexStorage.shutdown(); - //indexModelListener.shutdown(); - } - - /** - * Forward job request to Index Manager - * @param cleanHeaders - */ - public void request(IIndexJob indexJob) { - this.indexManager.request(indexJob); - } - - public ReadWriteMonitor getStorageMonitor() { - return storageMonitor; - } - /** - * - */ - public void resetEncounteredHeaders() { - try{ - storageMonitor.enterWrite(); - indexStorage.resetEncounteredHeaders(); - } - finally { - storageMonitor.exitWrite(); - } - } - - - /** - * @param path - * @param reuseIndexFile - * @param createIfMissing - * @return - */ - public synchronized IIndex getIndex(IPath path, boolean reuseExistingFile, boolean createIfMissing) { - IIndex index = null; - try{ - storageMonitor.enterRead(); - index = indexStorage.getIndex(path,reuseExistingFile, createIfMissing); - } - finally{ - storageMonitor.exitRead(); - } - return index; - } - - /** - * @param index - * @return - */ - public ReadWriteMonitor getMonitorFor(IIndex index) { - ReadWriteMonitor monitor = null; - try{ - storageMonitor.enterRead(); - monitor=indexStorage.getMonitorForIndex(); - } - finally{ - storageMonitor.exitRead(); - } - return monitor; - } - - /** - * @param path - */ - public void removeIndex(IPath path) { - try{ - storageMonitor.enterWrite(); - indexStorage.removeIndex(path); - } - finally{ - storageMonitor.exitWrite(); - } - - } - - /** - * @param path - */ - public void jobWasCancelled(IPath path) { - try{ - storageMonitor.enterWrite(); - indexStorage.jobWasCancelled(path); - } - finally{ - storageMonitor.exitWrite(); - } - } - - /** - * @param index - */ - public void saveIndex(IIndex index) throws IOException { - try{ - storageMonitor.enterWrite(); - indexStorage.saveIndex(index); - } - finally { - storageMonitor.exitWrite(); - } - - } - - /** - * @param indexPath - * @param indexState - */ - public void aboutToUpdateIndex(IPath indexPath, Integer indexState) { - storageMonitor.enterRead(); - try{ - indexStorage.aboutToUpdateIndex(indexPath, indexState); - } - finally { - storageMonitor.exitRead(); - } - } - /** - * @return Returns the totalIndexTime. - */ - public long getTotalIndexTime() { - return totalIndexTime; - } - /** - * @param totalIndexTime The totalIndexTime to set. - */ - public void setTotalIndexTime(long totalIndexTime) { - this.totalIndexTime = totalIndexTime; - } - - /* (non-Javadoc) - * @see org.eclipse.cdt.core.index.ICDTIndexer#notifyIndexerChange() - */ - public void notifyIndexerChange(IProject project) { - this.indexAll(project); - } - - public void indexerRemoved(IProject project) { - removeIndexerProblems(project); - } - - public void addResource(IProject project, IResource resource) { - - if (resource instanceof IProject){ - this.indexAll(project); - } - else if (resource instanceof IFolder){ - this.indexSourceFolder(project,resource.getFullPath(),null); - } - else if (resource instanceof IFile){ - IFile file = (IFile) resource; - this.addSource(file, project.getFullPath()); - } - } - - public void removeResource(IProject project, IResource resource) { - // TODO Auto-generated method stub - - } - - public void addResourceByPath(IProject project, IPath path, int resourceType) { - // TODO Auto-generated method stub - - } - - /* (non-Javadoc) - * @see org.eclipse.cdt.core.index.ICDTIndexer#setIndexerProject(org.eclipse.core.resources.IProject) - */ - public void setIndexerProject(IProject project) { - setProject(project); - } - -} diff --git a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/domsourceindexer/DOMSourceIndexerRunner.java b/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/domsourceindexer/DOMSourceIndexerRunner.java deleted file mode 100644 index 93a0fe93090..00000000000 --- a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/index/domsourceindexer/DOMSourceIndexerRunner.java +++ /dev/null @@ -1,487 +0,0 @@ -/*********************************************************************** - * Copyright (c) 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM - Initial API and implementation - ***********************************************************************/ -package org.eclipse.cdt.internal.core.index.domsourceindexer; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import org.eclipse.cdt.core.CCorePlugin; -import org.eclipse.cdt.core.ICLogConstants; -import org.eclipse.cdt.core.dom.CDOM; -import org.eclipse.cdt.core.dom.IASTServiceProvider.UnsupportedDialectException; -import org.eclipse.cdt.core.dom.ast.ASTVisitor; -import org.eclipse.cdt.core.dom.ast.IASTFileLocation; -import org.eclipse.cdt.core.dom.ast.IASTName; -import org.eclipse.cdt.core.dom.ast.IASTPreprocessorIncludeStatement; -import org.eclipse.cdt.core.dom.ast.IASTPreprocessorMacroDefinition; -import org.eclipse.cdt.core.dom.ast.IASTProblem; -import org.eclipse.cdt.core.dom.ast.IASTTranslationUnit; -import org.eclipse.cdt.core.dom.ast.IProblemBinding; -import org.eclipse.cdt.core.dom.ast.IASTTranslationUnit.IDependencyTree; -import org.eclipse.cdt.core.dom.ast.IASTTranslationUnit.IDependencyTree.IASTInclusionNode; -import org.eclipse.cdt.core.index.IIndexDelta; -import org.eclipse.cdt.core.model.CoreModel; -import org.eclipse.cdt.core.model.ICModelMarker; -import org.eclipse.cdt.core.parser.IExtendedScannerInfo; -import org.eclipse.cdt.core.parser.IScannerInfo; -import org.eclipse.cdt.core.parser.IScannerInfoProvider; -import org.eclipse.cdt.core.parser.ParseError; -import org.eclipse.cdt.core.parser.ParserLanguage; -import org.eclipse.cdt.internal.core.index.IIndex; -import org.eclipse.cdt.internal.core.index.NamedEntry; -import org.eclipse.cdt.internal.core.index.cindexstorage.IndexerOutput; -import org.eclipse.cdt.internal.core.index.impl.IndexDelta; -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IMarker; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.Path; - -/** - * A DOMSourceIndexerRunner indexes source files using the DOM AST. - * - * @author vhirsl - */ -public class DOMSourceIndexerRunner extends AbstractIndexerRunner { - - private DOMSourceIndexer indexer; - // Bug 124618: reuse NamedEntry & Visitor instances to reduce memory consumption - private NamedEntry commonNamedEntry; - static CGenerateIndexVisitor visitorC = null; - static CPPGenerateIndexVisitor visitorCPP = null; - - // for running JUnit tests - private static boolean skipScannerInfoTest=false; - - - // timing & errors - static int totalParseTime = 0; - static int totalVisitTime = 0; - static int errorCount = 0; - static Map errors = new HashMap(); - - public DOMSourceIndexerRunner(IFile resource, DOMSourceIndexer indexer) { - this.resourceFile = resource; - this.indexer = indexer; - commonNamedEntry = new NamedEntry(0, 0, new char[][] { null }, 0, 0); - } - - /** - * @return Returns the indexer. - */ - public DOMSourceIndexer getIndexer() { - return indexer; - } - - public void setFileTypes(String[] fileTypes) { - // TODO Auto-generated method stub - } - - protected void indexFile(IFile file) throws IOException { - int problems = indexer.indexProblemsEnabled(resourceFile.getProject()); - // enable inclusion problem markers - problems |= DOMSourceIndexer.INCLUSION_PROBLEMS_BIT; - setProblemMarkersEnabled(problems); - requestRemoveMarkers(resourceFile, null); - - // do not index the file if there is no scanner info - if (!skipScannerInfoTest && isScannerInfoEmpty(resourceFile)) { - // generate info marker - file is not indexed - addInfoMarker(resourceFile, CCorePlugin.getResourceString("DOMIndexerMarker.EmptyScannerInfo")); //$NON-NLS-1$ - if (areProblemMarkersEnabled()) { - reportProblems(); - } - return; - } - - // Add the name of the file to the index - output.addIndexedFile(file.getFullPath().toString()); - - IASTTranslationUnit tu = null; - long startTime = 0, parseTime = 0, endTime = 0; - String error = null; - try { - if (AbstractIndexerRunner.TIMING) - startTime = System.currentTimeMillis(); - - tu = CDOM.getInstance().getASTService().getTranslationUnit(resourceFile, - CDOM.getInstance().getCodeReaderFactory(CDOM.PARSE_SAVED_RESOURCES)); - - if (AbstractIndexerRunner.TIMING) - parseTime = System.currentTimeMillis(); - - // first clear all problem markers on non-external include files - clearProblemMarkers(tu.getIncludeDirectives()); - - ASTVisitor visitor = null; - //C or CPP? - if (tu.getParserLanguage() == ParserLanguage.CPP) { - if (visitorCPP == null) - visitorCPP = new CPPGenerateIndexVisitor(this); - else - visitorCPP.setCPPGenerateIndexVisitor(this); - visitor = visitorCPP; - } else { - if (visitorC == null) - visitorC = new CGenerateIndexVisitor(this); - else - visitorC.setCGenerateIndexVisitor(this); - visitor = visitorC; - } - - tu.accept(visitor); - - processMacroDefinitions(tu.getMacroDefinitions()); - processPreprocessorProblems(tu.getPreprocessorProblems()); - // must be the last step in processing of a translation unit - processIncludeDirectives(tu.getDependencyTree()); - } - catch (VirtualMachineError vmErr) { - error = vmErr.toString(); - if (vmErr instanceof OutOfMemoryError) { - org.eclipse.cdt.internal.core.model.Util.log(null, "Out Of Memory error: " + vmErr.getMessage() + " on File: " + resourceFile.getName(), ICLogConstants.CDT); //$NON-NLS-1$ //$NON-NLS-2$ - } - } - catch (ParseError e) { - error = e.toString(); - org.eclipse.cdt.internal.core.model.Util.log(null, "Parser Timeout on File: " + resourceFile.getName(), ICLogConstants.CDT); //$NON-NLS-1$ - } - catch (UnsupportedDialectException e) { - error = e.toString(); - org.eclipse.cdt.internal.core.model.Util.log(null, "Unsupported C/C++ dialect on File: " + resourceFile.getName(), ICLogConstants.CDT); //$NON-NLS-1$ - } - catch (Exception ex) { - error = ex.toString(); - if (ex instanceof IOException) - throw (IOException) ex; - } - finally { - if (AbstractIndexerRunner.TIMING) { - endTime = System.currentTimeMillis(); - if (error != null) { - errorCount++; - System.out.print(error + ':' + resourceFile.getName() + ':'); - if (!errors.containsKey(error)) { - errors.put(error, new Integer(0)); - } - errors.put(error, new Integer(((Integer) errors.get(error)).intValue()+1)); - } - System.out.print("DOM Indexer - " + resourceFile.getName() + ": " + (parseTime - startTime)); //$NON-NLS-1$ //$NON-NLS-2$ - System.out.print("+" + (endTime - parseTime)); //$NON-NLS-1$ //$NON-NLS-2$ - totalParseTime += parseTime - startTime; - totalVisitTime += endTime - parseTime; - long currentTime = endTime - startTime; - System.out.print("=" + currentTime); //$NON-NLS-1$ //$NON-NLS-2$ - long tempTotaltime = indexer.getTotalIndexTime() + currentTime; - indexer.setTotalIndexTime(tempTotaltime); - System.out.println(" \t\tOverall " + tempTotaltime + "=" + totalParseTime + "+" + totalVisitTime + " " + errorCount + " errors "); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ - System.out.println( "Attempted Entries " + IndexerOutput.entryCount + " Trimed " + DOMSourceIndexer.trimed + " Added " + DOMSourceIndexer.added); //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$ - - System.out.flush(); - } - if (AbstractIndexerRunner.VERBOSE){ - AbstractIndexerRunner.verbose("DOM AST TRAVERSAL FINISHED " + resourceFile.getName().toString()); //$NON-NLS-1$ - } - // if the user disable problem reporting since we last checked, don't report the collected problems - if (areProblemMarkersEnabled()) { - reportProblems(); - } - - // Report events - if (tu != null) { - List filesTrav = Arrays.asList(tu.getIncludeDirectives()); - IndexDelta indexDelta = new IndexDelta(resourceFile.getProject(),filesTrav, IIndexDelta.INDEX_FINISHED_DELTA); - indexer.notifyListeners(indexDelta); - } - // Release all resources - } - } - - /** - * @param IFile - * @return boolean - */ - private boolean isScannerInfoEmpty(IFile file) { - boolean rc = true; - if (!CoreModel.isScannerInformationEmpty(file)) { - rc = false; - IScannerInfoProvider provider = CCorePlugin.getDefault().getScannerInfoProvider(file.getProject()); - if (provider != null) { - IScannerInfo scanInfo = provider.getScannerInformation(file); - if (scanInfo != null && scanInfo instanceof IExtendedScannerInfo) { - IExtendedScannerInfo extScanInfo = (IExtendedScannerInfo) scanInfo; - if (extScanInfo.getIncludeFiles().length > 0) { - for (int i = 0; i < extScanInfo.getIncludeFiles().length; i++) { - String includeFile = extScanInfo.getIncludeFiles()[i]; - /* See if this file has been encountered before */ - indexer.haveEncounteredHeader(resourceFile.getProject().getFullPath(), new Path(includeFile), true); - } - } - if (extScanInfo.getMacroFiles().length > 0) { - for (int i = 0; i < extScanInfo.getIncludeFiles().length; i++) { - String macrosFile = extScanInfo.getMacroFiles()[i]; - /* See if this file has been encountered before */ - indexer.haveEncounteredHeader(resourceFile.getProject().getFullPath(), new Path(macrosFile), true); - } - } - } - } - } - return rc; - } - - /** - * @param includeDirectives - */ - private void clearProblemMarkers(IASTPreprocessorIncludeStatement[] includeDirectives) { - if (areProblemMarkersEnabled()) { - for (int i = 0; i < includeDirectives.length; i++) { - IPath includePath = new Path(includeDirectives[i].getPath()); - IFile includeFile = CCorePlugin.getWorkspace().getRoot().getFileForLocation(includePath); - if (includeFile != null) { - // include file in workspace; remove problem markers - requestRemoveMarkers(includeFile, resourceFile); - } - } - } - } - - /** - * @param tree - */ - private void processIncludeDirectives(IDependencyTree tree) { - int fileNumber = getOutput().getIndexedFile( - getResourceFile().getFullPath().toString()).getFileID(); - - processNestedInclusions(fileNumber, tree.getInclusions(), null); - } - - /** - * @param fileNumber - * @param inclusions - * @param parent - */ - private void processNestedInclusions(int fileNumber, IASTInclusionNode[] inclusions, IASTInclusionNode parent) { - for (int i = 0; i < inclusions.length; i++) { - IASTInclusionNode inclusion = inclusions[i]; - // Quick check to see if the name is in an already indexed external header file - if (IndexEncoderUtil.nodeInVisitedExternalHeader(inclusion.getIncludeDirective(), getIndexer())) - continue; - - String include = inclusion.getIncludeDirective().getPath(); - -// if (areProblemMarkersEnabled()) { -// IPath newPath = new Path(include); -// IFile tempFile = CCorePlugin.getWorkspace().getRoot().getFileForLocation(newPath); -// if (tempFile != null) { -// //File is in the workspace -// requestRemoveMarkers(tempFile, resourceFile); -// } -// } - - getOutput().addIncludeRef(fileNumber, include); - getOutput().addRelatives(fileNumber, include, - (parent != null) ? parent.getIncludeDirective().getPath() : null); - - commonNamedEntry.setNamedEntry(IIndex.INCLUDE, IIndex.REFERENCE, new char[][] {include.toCharArray()}, 0, fileNumber); - commonNamedEntry.setNameOffset(1, 1, IIndex.OFFSET); - commonNamedEntry.serialize(getOutput()); - - /* See if this file has been encountered before */ - indexer.haveEncounteredHeader(resourceFile.getProject().getFullPath(), new Path(include), true); - - // recurse - processNestedInclusions(fileNumber, inclusion.getNestedInclusions(), inclusion); - } - } - - /** - * @param macroDefinitions - */ - private void processMacroDefinitions(IASTPreprocessorMacroDefinition[] macroDefinitions) { - for (int i = 0; i < macroDefinitions.length; i++) { - IASTName macro = macroDefinitions[i].getName(); - // Quick check to see if the macro is in an already indexed external header file - if (IndexEncoderUtil.nodeInVisitedExternalHeader(macro, getIndexer())) - continue; - - // Get the location - IASTFileLocation loc = IndexEncoderUtil.getFileLocation(macro); - int fileNumber = IndexEncoderUtil.calculateIndexFlags(this, loc); - - commonNamedEntry.setNamedEntry(IIndex.MACRO, IIndex.DECLARATION, new char[][] {macro.toCharArray()}, 0, fileNumber); - commonNamedEntry.setNameOffset(loc.getNodeOffset(), loc.getNodeLength(), IIndex.OFFSET); - commonNamedEntry.serialize(getOutput()); - } - } - - /** - * @param preprocessorProblems - */ - private void processPreprocessorProblems(IASTProblem[] preprocessorProblems) { - for (int i = 0; i < preprocessorProblems.length; i++) { - IASTProblem problem = preprocessorProblems[i]; - // Quick check to see if the problem is in an already indexed external header file - if (IndexEncoderUtil.nodeInVisitedExternalHeader(problem, getIndexer())) - continue; - - if (areProblemMarkersEnabled() && shouldRecordProblem(problem)) { - // Get the location - IASTFileLocation loc = IndexEncoderUtil.getFileLocation(problem); - processProblem(problem.getMessage(), loc); - } - } - } - - /** - * @param name - */ - public void processProblem(String message, IASTFileLocation loc) { - IFile tempFile = resourceFile; - //If we are in an include file, get the include file - if (loc != null) { - String fileName = loc.getFileName(); - tempFile = CCorePlugin.getWorkspace().getRoot().getFileForLocation(new Path(fileName)); - if (tempFile != null) { - generateMarkerProblem(tempFile, resourceFile, message, loc); - } - } - } - - private void generateMarkerProblem(IFile tempFile, IFile originator, String message, IASTFileLocation loc) { - Problem tempProblem = new AddMarkerProblem(tempFile, originator, message, loc); - if (getProblemsMap().containsKey(tempFile)) { - List list = (List) getProblemsMap().get(tempFile); - list.add(tempProblem); - } else { - List list = new ArrayList(); - list.add(new RemoveMarkerProblem(tempFile, resourceFile)); //remove existing markers - list.add(tempProblem); - getProblemsMap().put(tempFile, list); - } - } - - class AddMarkerProblem extends Problem { - private String message; - private IASTFileLocation location; - public AddMarkerProblem(IResource resource, IResource originator, String message, IASTFileLocation location) { - super(resource, originator); - this.message = message; - this.location = location; - } - - public void run() { - if (location != null) { - try { - //we only ever add index markers on the file, so DEPTH_ZERO is far enough - IMarker[] markers = resource.findMarkers(ICModelMarker.INDEXER_MARKER, true, IResource.DEPTH_ZERO); - - boolean newProblem = true; - - if (markers.length > 0) { - IMarker tempMarker = null; - int nameStart = -1; - int nameLen = -1; - String tempMsgString = null; - - for (int i=0; i threshold) - rehash(); - return value; - } - private void rehash() { - HashtableOfInt newHashtable = new HashtableOfInt(elementSize * 2); // double the number of expected elements - int currentKey; - for (int i = keyTable.length; --i >= 0;) - if ((currentKey = keyTable[i]) != 0) - newHashtable.put(currentKey, valueTable[i]); - - this.keyTable = newHashtable.keyTable; - this.valueTable = newHashtable.valueTable; - this.threshold = newHashtable.threshold; - } - public int size() { - return elementSize; - } - public String toString() { - String s = ""; //$NON-NLS-1$ - Object object; - for (int i = 0, length = valueTable.length; i < length; i++) - if ((object = valueTable[i]) != null) - s += keyTable[i] + " -> " + object.toString() + "\n"; //$NON-NLS-2$ //$NON-NLS-1$ - return s; - } -} - diff --git a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/search/SimpleLookupTable.java b/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/search/SimpleLookupTable.java deleted file mode 100644 index d007b0a76c6..00000000000 --- a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/search/SimpleLookupTable.java +++ /dev/null @@ -1,153 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2003 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.core.search; - -/** - * A simple lookup table is a non-synchronized Hashtable, whose keys - * and values are Objects. It also uses linear probing to resolve collisions - * rather than a linked list of hash table entries. - */ -public final class SimpleLookupTable implements Cloneable { - - // to avoid using Enumerations, walk the individual tables skipping nulls - public Object[] keyTable; - public Object[] valueTable; - public int elementSize; // number of elements in the table - public int threshold; - - public SimpleLookupTable() { - this(13); - } - - public SimpleLookupTable(int size) { - if (size < 3) size = 3; - this.elementSize = 0; - this.threshold = size + 1; // size is the expected number of elements - int tableLength = 2 * size + 1; - this.keyTable = new Object[tableLength]; - this.valueTable = new Object[tableLength]; - } - - public Object clone() throws CloneNotSupportedException { - SimpleLookupTable result = (SimpleLookupTable) super.clone(); - result.elementSize = this.elementSize; - result.threshold = this.threshold; - - int length = this.keyTable.length; - result.keyTable = new Object[length]; - System.arraycopy(this.keyTable, 0, result.keyTable, 0, length); - - length = this.valueTable.length; - result.valueTable = new Object[length]; - System.arraycopy(this.valueTable, 0, result.valueTable, 0, length); - return result; - } - - public boolean containsKey(Object key) { - int length = keyTable.length; - int index = (key.hashCode() & 0x7FFFFFFF) % length; - Object currentKey; - while ((currentKey = keyTable[index]) != null) { - if (currentKey.equals(key)) return true; - if (++index == length) index = 0; - } - return false; - } - - public Object get(Object key) { - int length = keyTable.length; - int index = (key.hashCode() & 0x7FFFFFFF) % length; - Object currentKey; - while ((currentKey = keyTable[index]) != null) { - if (currentKey.equals(key)) return valueTable[index]; - if (++index == length) index = 0; - } - return null; - } - - public Object keyForValue(Object valueToMatch) { - if (valueToMatch != null) - for (int i = 0, l = valueTable.length; i < l; i++) - if (valueToMatch.equals(valueTable[i])) - return keyTable[i]; - return null; - } - - public Object put(Object key, Object value) { - int length = keyTable.length; - int index = (key.hashCode() & 0x7FFFFFFF) % length; - Object currentKey; - while ((currentKey = keyTable[index]) != null) { - if (currentKey.equals(key)) return valueTable[index] = value; - if (++index == length) index = 0; - } - keyTable[index] = key; - valueTable[index] = value; - - // assumes the threshold is never equal to the size of the table - if (++elementSize > threshold) rehash(); - return value; - } - - public void removeKey(Object key) { - int length = keyTable.length; - int index = (key.hashCode() & 0x7FFFFFFF) % length; - Object currentKey; - while ((currentKey = keyTable[index]) != null) { - if (currentKey.equals(key)) { - elementSize--; - keyTable[index] = null; - valueTable[index] = null; - if (keyTable[index + 1 == length ? 0 : index + 1] != null) - rehash(); // only needed if a possible collision existed - return; - } - if (++index == length) index = 0; - } - } - - public void removeValue(Object valueToRemove) { - boolean rehash = false; - for (int i = 0, l = valueTable.length; i < l; i++) { - Object value = valueTable[i]; - if (value != null && value.equals(valueToRemove)) { - elementSize--; - keyTable[i] = null; - valueTable[i] = null; - if (!rehash && keyTable[i + 1 == l ? 0 : i + 1] != null) - rehash = true; // only needed if a possible collision existed - } - } - if (rehash) rehash(); - } - - private void rehash() { - SimpleLookupTable newLookupTable = new SimpleLookupTable(elementSize * 2); // double the number of expected elements - Object currentKey; - for (int i = keyTable.length; --i >= 0;) - if ((currentKey = keyTable[i]) != null) - newLookupTable.put(currentKey, valueTable[i]); - - this.keyTable = newLookupTable.keyTable; - this.valueTable = newLookupTable.valueTable; - this.elementSize = newLookupTable.elementSize; - this.threshold = newLookupTable.threshold; - } - - public String toString() { - String s = ""; //$NON-NLS-1$ - Object object; - for (int i = 0, l = valueTable.length; i < l; i++) - if ((object = valueTable[i]) != null) - s += keyTable[i].toString() + " -> " + object.toString() + "\n"; //$NON-NLS-2$ //$NON-NLS-1$ - return s; - } -} diff --git a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/search/indexing/IndexManager.java b/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/search/indexing/IndexManager.java deleted file mode 100644 index e0d23dfdf2a..00000000000 --- a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/search/indexing/IndexManager.java +++ /dev/null @@ -1,559 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.core.search.indexing; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Set; - -import org.eclipse.cdt.core.CCorePlugin; -import org.eclipse.cdt.core.ICDescriptor; -import org.eclipse.cdt.core.ICExtensionReference; -import org.eclipse.cdt.core.index.ICDTIndexer; -import org.eclipse.cdt.core.index.IIndexStorage; -import org.eclipse.cdt.core.model.CoreModel; -import org.eclipse.cdt.core.model.ElementChangedEvent; -import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.cdt.core.model.ICElementDelta; -import org.eclipse.cdt.core.model.ICModelMarker; -import org.eclipse.cdt.core.model.ICProject; -import org.eclipse.cdt.core.model.IElementChangedListener; -import org.eclipse.cdt.core.model.ITranslationUnit; -import org.eclipse.cdt.core.parser.util.ArrayUtil; -import org.eclipse.cdt.internal.core.index.IndexRequest; -import org.eclipse.cdt.internal.core.index.cindexstorage.CIndexStorage; -import org.eclipse.cdt.internal.core.index.domsourceindexer.DOMSourceIndexer; -import org.eclipse.cdt.internal.core.index.nullindexer.NullIndexer; -import org.eclipse.cdt.internal.core.search.processing.IIndexJob; -import org.eclipse.cdt.internal.core.search.processing.JobManager; -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.resources.IResourceDelta; -import org.eclipse.core.resources.ResourcesPlugin; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IConfigurationElement; -import org.eclipse.core.runtime.IExtension; -import org.eclipse.core.runtime.IExtensionPoint; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.Platform; -import org.eclipse.core.runtime.QualifiedName; -import org.eclipse.core.runtime.Status; -import org.eclipse.core.runtime.jobs.Job; - -/** - * @author Bogdan Gheorghe - */ -public class IndexManager extends JobManager{ - - public static interface IIndexerSelectionListener - { - public void indexerSelectionChanged(IProject project); - } - - private IIndexerSelectionListener [] listeners = new IIndexerSelectionListener[1]; - - public synchronized void subscribeForIndexerChangeNotifications( IIndexerSelectionListener listener ) - { - listeners = (IIndexerSelectionListener[]) ArrayUtil.append( IIndexerSelectionListener.class, listeners, listener ); - } - - public synchronized void unSubscribeForIndexerChangeNotifications( IIndexerSelectionListener listener ) - { - if( listeners == null ) return; - if( listener == null ) return; - for( int i = 0; i < listeners.length; ++i ) - { - if( listeners[i] == listener ) - listeners[i] = null; - } - } - - - - public final static String INDEX_MODEL_ID = CCorePlugin.PLUGIN_ID + ".cdtindexers"; //$NON-NLS-1$ - public final static String INDEXERID = "indexerID"; //$NON-NLS-1$ - public final static QualifiedName indexerIDKey = new QualifiedName(INDEX_MODEL_ID, INDEXERID); - - public static final String nullIndexerID = "org.eclipse.cdt.core.nullindexer"; //$NON-NLS-1$ - - public static final String CDT_INDEXER = "cdt_indexer"; //$NON-NLS-1$ - public static final String INDEXER_ID = "indexerID"; //$NON-NLS-1$ - public static final String INDEXER_ID_VALUE = "indexerIDValue"; //$NON-NLS-1$ - - public static boolean VERBOSE = false; - - //Map of Persisted Indexers; keyed by project - private HashMap indexerMap = null; - - private ReadWriteMonitor monitor = new ReadWriteMonitor(); - - private static ElementChangeListener elementChangeListener = null; - - /** - * Flush current state - */ - public void reset() { - try{ - monitor.enterWrite(); - super.reset(); - //Set default upgrade values - CCorePlugin.getDefault().getPluginPreferences().setValue(CCorePlugin.PREF_INDEXER, CCorePlugin.DEFAULT_INDEXER_UNIQ_ID); - this.indexerMap = new HashMap(5); - - // subscribe for path entry changes - if (elementChangeListener != null) { - CoreModel.getDefault().removeElementChangedListener(elementChangeListener); - } - elementChangeListener = new ElementChangeListener(); - CoreModel.getDefault().addElementChangedListener(elementChangeListener); - } finally{ - monitor.exitWrite(); - } - } - - public class ElementChangeListener implements IElementChangedListener { - private boolean scannerInfoChanged = false; - private IProject currentProject = null; - private List changedElements = new ArrayList(); - - /* (non-Javadoc) - * @see org.eclipse.cdt.core.model.IElementChangedListener#elementChanged(org.eclipse.cdt.core.model.ElementChangedEvent) - */ - public void elementChanged(ElementChangedEvent event) { - scannerInfoChanged = false; - currentProject = null; - changedElements.clear(); - processDelta(event.getDelta()); - - if (!scannerInfoChanged) - return; - if (changedElements.size() > 0) { - for (Iterator i = changedElements.iterator(); i.hasNext();) { - IFile file = (IFile) i.next(); - addResource(currentProject, file); - } - } - else { - if (!CoreModel.isScannerInformationEmpty(currentProject)) { - addResource(currentProject, currentProject); - } - } - } - - /** - * @param delta - */ - private void processDelta(ICElementDelta delta) { - ICElement element= delta.getElement(); - - IResource res = element.getResource(); - if (element instanceof ICProject && res instanceof IProject) { - currentProject = (IProject) res; - } - if (isPathEntryChange(delta)) { - scannerInfoChanged = true; - if (element instanceof ITranslationUnit && res instanceof IFile) { - if (!changedElements.contains(res)) { - changedElements.add(res); - } - } - } - - ICElementDelta[] affectedChildren= delta.getAffectedChildren(); - for (int i= 0; i < affectedChildren.length; i++) { - processDelta(affectedChildren[i]); - } - } - - /** - * @param delta - * @return - */ - private boolean isPathEntryChange(ICElementDelta delta) { - int flags= delta.getFlags(); - return (delta.getKind() == ICElementDelta.CHANGED && - ((flags & ICElementDelta.F_CHANGED_PATHENTRY_INCLUDE) != 0 || - (flags & ICElementDelta.F_CHANGED_PATHENTRY_MACRO) != 0 || - (flags & ICElementDelta.F_PATHENTRY_REORDER) !=0)); - } - - } - - /** - * Notify indexer which scheduled this job that the job has completed - * - */ - protected void jobFinishedNotification(IIndexJob job) { - - if (job instanceof IndexRequest ){ - IndexRequest indexRequest = (IndexRequest) job; - IPath path = indexRequest.getIndexPath(); - IProject project= ResourcesPlugin.getWorkspace().getRoot().getProject(path.toOSString()); - ICDTIndexer indexer = getIndexerForProject(project); - - if (indexer != null) - indexer.indexJobFinishedNotification(job); - } - } - /** - * @param project - * @param element - * @param delta - */ - public void addResourceEvent(IProject project, IResourceDelta delta, int kind) { - //Get indexer for this project - ICDTIndexer indexer = getIndexerForProject(project); - - if (indexer != null) - indexer.addRequest(project, delta, kind); - } - - /** - * @param project - * @param element - * @param delta - */ - public void removeResourceEvent(IProject project, IResourceDelta delta, int kind) { - //Get the indexer for this project - if (indexerMap == null) - return; - - ICDTIndexer indexer = (ICDTIndexer) indexerMap.get(project); - if (indexer != null) - indexer.removeRequest(project, delta, kind); - } - - /** - * @param project - * @param element - * @param delta - */ - public void addResource(IProject project, IResource resource) { - //Get indexer for this project - ICDTIndexer indexer = getIndexerForProject(project); - - if (indexer != null) - indexer.addResource(project, resource); - } - - public void addResourceByPath(IProject project, IPath path, int resourceType) { - //Get indexer for this project - ICDTIndexer indexer = getIndexerForProject(project); - - if (indexer != null) - indexer.addResourceByPath(project, path,resourceType); - - } - /** - * @param project - * @param element - * @param delta - */ - public void removeResource(IProject project, IResource resource) { - //Get the indexer for this project - ICDTIndexer indexer = null; - indexer = (ICDTIndexer) indexerMap.get(project); - - if (indexer != null) - indexer.removeResource(project, resource); - } - - /** - * Name of the background process - */ - public String processName(){ - return org.eclipse.cdt.internal.core.Util.bind("process.name"); //$NON-NLS-1$ - } - - - - public void shutdown() { - //Send shutdown messages to all indexers - - /*if (IndexManager.VERBOSE) - JobManager.verbose("Shutdown"); //$NON-NLS-1$ - //Get index entries for all projects in the workspace, store their absolute paths - IndexSelector indexSelector = new IndexSelector(new CWorkspaceScope(), null, false, this); - IIndex[] selectedIndexes = indexSelector.getIndexes(); - SimpleLookupTable knownPaths = new SimpleLookupTable(); - for (int i = 0, max = selectedIndexes.length; i < max; i++) { - String path = selectedIndexes[i].getIndexFile().getAbsolutePath(); - knownPaths.put(path, path); - } - //Any index entries that are in the index state must have a corresponding - //path entry - if not they are removed from the saved indexes file - if (indexStates != null) { - Object[] indexNames = indexStates.keyTable; - for (int i = 0, l = indexNames.length; i < l; i++) { - String key = (String) indexNames[i]; - if (key != null && !knownPaths.containsKey(key)) //here is an index that is in t - updateIndexState(key, null); - } - } - - //Clean up the .metadata folder - if there are any files in the directory that - //are not associated to an index we delete them - File indexesDirectory = new File(getCCorePluginWorkingLocation().toOSString()); - if (indexesDirectory.isDirectory()) { - File[] indexesFiles = indexesDirectory.listFiles(); - if (indexesFiles != null) { - for (int i = 0, indexesFilesLength = indexesFiles.length; i < indexesFilesLength; i++) { - String fileName = indexesFiles[i].getAbsolutePath(); - if (!knownPaths.containsKey(fileName) && fileName.toLowerCase().endsWith(".index")) { //$NON-NLS-1$ - if (IndexManager.VERBOSE) - JobManager.verbose("Deleting index file " + indexesFiles[i]); //$NON-NLS-1$ - indexesFiles[i].delete(); - } - } - } - } - - indexModelListener.shutdown(); - - this.timeoutThread = null;*/ - - //Send shutdown notification to all indexers - if (indexerMap != null){ - Set projects = indexerMap.keySet(); - Iterator i = projects.iterator(); - while (i.hasNext()){ - IProject tempProject = (IProject) i.next(); - ICDTIndexer indexer = (ICDTIndexer) indexerMap.get(tempProject); - if (indexer != null) - indexer.shutdown(); - } - } - - if (elementChangeListener != null) { - CoreModel.getDefault().removeElementChangedListener(elementChangeListener); - elementChangeListener = null; - } - super.shutdown(); - } - - public IIndexStorage getIndexStorageForIndexer(ICDTIndexer indexer){ - //For now we have only one index storage format that all indexers are to use - return new CIndexStorage(indexer); - } - - public int getJobStart(){ - return jobStart; - } - - public int getJobEnd(){ - return jobEnd; - } - /** - * Returns the job at position in the awaiting job queue - * @param position - * @return - */ - public IIndexJob getAwaitingJobAt(int position){ - return this.awaitingJobs[position]; - } - /** - * Check to see if the indexer associated with this project - * requires dependency update notifications - * @param resource - * @param resource2 - */ - public void updateDependencies(IProject project, IResource resource) { - ICDTIndexer indexer = getIndexerForProject(project); - if (indexer instanceof DOMSourceIndexer) - ((DOMSourceIndexer) indexer).updateDependencies(resource); - - } - - public ICDTIndexer getIndexerForProject(IProject project){ - return new NullIndexer(); -// ICDTIndexer indexer = null; -// try { -// //Make sure we're not updating list -// monitor.enterRead(); -// -// //See if indexer exists already -// indexer = (ICDTIndexer) indexerMap.get(project); -// -// //Create the indexer and store it -// if (indexer == null) { -// monitor.exitRead(); -// try { -// monitor.enterWrite(); -// indexer = getIndexer(project); -// //Make sure we're not putting null in map -// if (indexer != null) -// indexerMap.put(project,indexer); -// } finally{ -// monitor.exitWriteEnterRead(); -// } -// } -// return indexer; -// -// }finally { -// monitor.exitRead(); -// } - } - - public ICDTIndexer getDefaultIndexer(IProject project) throws CoreException { - ICDTIndexer indexer = null; - String id = CCorePlugin.getDefault().getPluginPreferences().getDefaultString(CCorePlugin.PREF_INDEXER); - if (id == null || id.length() == 0) { - id = CCorePlugin.DEFAULT_INDEXER_UNIQ_ID; - } - - IExtensionPoint extensionPoint = Platform.getExtensionRegistry().getExtensionPoint(CCorePlugin.PLUGIN_ID, CCorePlugin.INDEXER_SIMPLE_ID); - IExtension extension = extensionPoint.getExtension(id); - if (extension != null) { - IConfigurationElement element[] = extension.getConfigurationElements(); - for (int i = 0; i < element.length; i++) { - if (element[i].getName().equalsIgnoreCase("cextension")) { //$NON-NLS-1$ - indexer = (ICDTIndexer) element[i].createExecutableExtension("run"); //$NON-NLS-1$ - indexer.setIndexerProject(project); - break; - } - } - } else { - IStatus s = new Status(IStatus.ERROR, CCorePlugin.PLUGIN_ID, -1,"No Indexer Found", null); //$NON-NLS-1$ - throw new CoreException(s); - } - return indexer; - } - - protected ICDTIndexer getIndexer(IProject project) { - ICDTIndexer indexer = null; - try{ - ICDescriptor cdesc = CCorePlugin.getDefault().getCProjectDescription(project, false); - if (cdesc != null) { - ICExtensionReference[] cextensions = cdesc.get(CCorePlugin.INDEXER_UNIQ_ID, true); - - if (cextensions != null && cextensions.length > 0) - indexer = (ICDTIndexer) cextensions[0].createExtension(); - } - } catch (CoreException e){} - - if (indexer == null) - try { - indexer = getDefaultIndexer(project); - } catch (CoreException e1) {} - - return indexer; - } - - protected void notifyIdle(long idlingTime) { - //Notify all indexers - monitor.enterRead(); - try{ - if (indexerMap == null) - return; - - Set mapKeys = indexerMap.keySet(); - Iterator i = mapKeys.iterator(); - while (i.hasNext()){ - IProject tempProject = (IProject) i.next(); - ICDTIndexer indexer = (ICDTIndexer) indexerMap.get(tempProject); - if (indexer != null) - indexer.notifyIdle(idlingTime); - } - } finally{ - monitor.exitRead(); - } - } - - /** - * The indexer previously associated with this project has been changed to a - * new value. Next time project gets asked for indexer, a new one will be created - * of the new type. - * - * @param project - */ - public void indexerChangeNotification(IProject project) { - - //Get rid of any jobs scheduled by the old indexer - this.discardJobs(project.getName()); - - return; - -// //Get rid of the old index file -// ICDTIndexer currentIndexer = getIndexerForProject(project); -// if (currentIndexer == null) -// return; -// currentIndexer.indexerRemoved(project); -// -// IIndexStorage storage = currentIndexer.getIndexStorage(); -// if (storage instanceof CIndexStorage) -// ((CIndexStorage) storage).removeIndex(project.getFullPath()); -// -// monitor.enterWrite(); -// try{ -// //Purge the old indexer from the indexer map -// indexerMap.remove(project); -// } finally { -// monitor.exitWrite(); -// final ICDTIndexer indexer = this.getIndexerForProject(project); -// final IProject finalProject = project; -// -// //Notify new indexer in a job of change -// Job job = new Job("Index Change Notification"){ //$NON-NLS-1$ -// protected IStatus run(IProgressMonitor monitor) { -// Platform.run(new ISafeRunnable() { -// public void handleException(Throwable exception) { -// CCorePlugin.log(exception); -// } -// public void run() throws Exception { -// indexer.notifyIndexerChange(finalProject); -// } -// }); -// -// return Status.OK_STATUS; -// } -// }; -// -// job.schedule(); -// -// if( listeners != null ) -// for( int i = 0; i < listeners.length; ++i ) -// if( listeners[i] != null ) -// listeners[i].indexerSelectionChanged(project); -// } - } - - static private class RemoveIndexMarkersJob extends Job{ - private final IResource resource; - public RemoveIndexMarkersJob( IResource resource, String name ){ - super( name ); - this.resource = resource; - } - protected IStatus run(IProgressMonitor monitor) { - try { - resource.deleteMarkers( ICModelMarker.INDEXER_MARKER, true, IResource.DEPTH_INFINITE ); - } catch (CoreException e) { - return Status.CANCEL_STATUS; - } - return Status.OK_STATUS; - } - - } - - public void removeIndexerProblems( IResource resource){ - String jobName = "remove markers"; //$NON-NLS-1$ - RemoveIndexMarkersJob job = new RemoveIndexMarkersJob( resource, jobName ); - job.setRule( resource ); - job.setPriority( Job.DECORATE ); - job.schedule(); - } - - -} diff --git a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/search/indexing/IndexProblemHandler.java b/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/search/indexing/IndexProblemHandler.java deleted file mode 100644 index cf98e3efafe..00000000000 --- a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/search/indexing/IndexProblemHandler.java +++ /dev/null @@ -1,59 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -/* - * Created on May 27, 2004 - * - * TODO To change the template for this generated file go to - * Window - Preferences - Java - Code Style - Code Templates - */ -package org.eclipse.cdt.internal.core.search.indexing; - -import org.eclipse.cdt.core.parser.IProblem; -import org.eclipse.cdt.core.parser.ParserMode; - -/** - * @author bgheorgh - * - * TODO To change the template for this generated type comment go to - * Window - Preferences - Java - Code Style - Code Templates - */ -public class IndexProblemHandler { - - - public static boolean ruleOnProblem( IProblem p, ParserMode mode ) - { - if( p == null ) return true; - if( p.checkCategory( IProblem.SCANNER_RELATED ) || p.checkCategory( IProblem.PREPROCESSOR_RELATED )) - { - switch( p.getID() ) - { - case IProblem.PREPROCESSOR_POUND_ERROR: - case IProblem.PREPROCESSOR_UNBALANCE_CONDITION: - case IProblem.PREPROCESSOR_INVALID_MACRO_DEFN: - case IProblem.PREPROCESSOR_MACRO_PASTING_ERROR: - case IProblem.PREPROCESSOR_CONDITIONAL_EVAL_ERROR: - case IProblem.SCANNER_UNEXPECTED_EOF: - if( mode == ParserMode.COMPLETE_PARSE ) - return false; - - case IProblem.PREPROCESSOR_INVALID_MACRO_REDEFN: - case IProblem.PREPROCESSOR_INVALID_DIRECTIVE: - return true; - - default: - return true; - } - } - return true; - } - - -} diff --git a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/search/indexing/IndexerModelListener.java b/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/search/indexing/IndexerModelListener.java deleted file mode 100644 index 06b32c01da8..00000000000 --- a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/search/indexing/IndexerModelListener.java +++ /dev/null @@ -1,132 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.core.search.indexing; - -import org.eclipse.cdt.core.index.ICDTIndexer; -import org.eclipse.cdt.core.model.CModelException; -import org.eclipse.cdt.core.model.CoreModel; -import org.eclipse.cdt.core.model.ElementChangedEvent; -import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.cdt.core.model.ICElementDelta; -import org.eclipse.cdt.core.model.IElementChangedListener; -import org.eclipse.cdt.internal.core.index.domsourceindexer.DOMSourceIndexer; -import org.eclipse.cdt.internal.core.model.SourceRoot; -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IResource; - -public class IndexerModelListener implements IElementChangedListener { - - private static IndexerModelListener indexerModelListener; - private static IndexManager indexManager; - - private IndexerModelListener() {} - - /** - * Return the singleton. - */ - public static synchronized IndexerModelListener getDefault() { - if (indexerModelListener == null) { - indexerModelListener = new IndexerModelListener(); - CoreModel.getDefault().addElementChangedListener(indexerModelListener); - indexManager = CoreModel.getDefault().getIndexManager(); - } - return indexerModelListener; - } - - /* (non-Javadoc) - * @see org.eclipse.cdt.core.model.IElementChangedListener#elementChanged(org.eclipse.cdt.core.model.ElementChangedEvent) - */ - public void elementChanged(ElementChangedEvent event) { - try { - processDelta(event.getDelta()); - } catch(CModelException e) { - } - } - - protected void processDelta(ICElementDelta delta) throws CModelException { - int kind= delta.getKind(); - int flags= delta.getFlags(); - ICElement element= delta.getElement(); - IProject project = element.getCProject().getProject(); - ICDTIndexer indexer = indexManager.getIndexerForProject(project); - - if (!(indexer instanceof DOMSourceIndexer)) - return; - - DOMSourceIndexer sourceIndexer = (DOMSourceIndexer) indexer; - - switch(kind){ - case ICElementDelta.CHANGED: - if ((flags & ICElementDelta.F_CHANGED_PATHENTRY_INCLUDE) != 0 || - (flags & ICElementDelta.F_CHANGED_PATHENTRY_MACRO) != 0 || - (flags & ICElementDelta.F_ADDED_PATHENTRY_SOURCE) != 0 ){ - IResource tempResource = element.getResource(); - SourceRoot tempRootElement = null; - - if (tempResource == null) - return; - - switch(tempResource.getType()) - { - case IResource.FILE: - sourceIndexer.addSource((IFile) tempResource,tempResource.getProject().getFullPath()); - break; - - case IResource.FOLDER: - tempRootElement = (SourceRoot) getElementSource(element); - if (tempRootElement != null){ - IProject theProj = tempResource.getProject(); - sourceIndexer.indexSourceFolder(theProj,tempResource.getFullPath(),tempRootElement.getSourceEntry().fullExclusionPatternChars()); - } - break; - - case IResource.PROJECT: - sourceIndexer.indexAll(tempResource.getProject()); - break; - } - - } else if( (flags & ICElementDelta.F_REMOVED_PATHENTRY_SOURCE) != 0 ){ - IResource tempResource = element.getResource(); - IProject tempProject = tempResource.getProject(); - if( sourceIndexer.indexProblemsEnabled(tempProject) != 0 ){ - sourceIndexer.removeIndexerProblems( tempResource ); - } - } - break; - } - - ICElementDelta[] affectedChildren= delta.getAffectedChildren(); - for (int i= 0; i < affectedChildren.length; i++) { - processDelta(affectedChildren[i]); - } - } - - ICElement getElementSource(ICElement element){ - - if (element instanceof SourceRoot){ - return element; - } - - if (element.getParent() != null){ - return getElementSource(element.getParent()); - } - - return null; - - } - - public void shutdown(){ - if (indexerModelListener != null) - CoreModel.getDefault().removeElementChangedListener(indexerModelListener); - } - -} diff --git a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/search/indexing/ReadWriteMonitor.java b/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/search/indexing/ReadWriteMonitor.java deleted file mode 100644 index 907332c4603..00000000000 --- a/core/org.eclipse.cdt.core/index/org/eclipse/cdt/internal/core/search/indexing/ReadWriteMonitor.java +++ /dev/null @@ -1,85 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2003 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ - -package org.eclipse.cdt.internal.core.search.indexing; - -/** - * Monitor ensuring no more than one writer working concurrently. - * Multiple readers are allowed to perform simultaneously. - */ -public class ReadWriteMonitor { - - /** - * <0 : writing (cannot go beyond -1, i.e one concurrent writer) - * =0 : idle - * >0 : reading (number of concurrent readers) - */ - private int status = 0; - /** - * Concurrent reading is allowed - * Blocking only when already writing. - */ - public synchronized void enterRead() { - - while (status < 0){ - try { - wait(); - } catch(InterruptedException e){ - } - } - status++; - } - /** - * Only one writer at a time is allowed to perform - * Blocking only when already writing or reading. - */ - public synchronized void enterWrite() { - - while (status != 0){ - try { - wait(); - } catch(InterruptedException e){ - } - } - status--; - } - /** - * Only notify waiting writer(s) if last reader - */ - public synchronized void exitRead() { - if (--status == 0) notifyAll(); - } - /** - * When writing is over, all readers and possible - * writers are granted permission to restart concurrently - */ - public synchronized void exitWrite() { - if (++status == 0) notifyAll(); - } - /** - * Atomic exitWrite/enterRead: Allows to keep monitor in between - * exit write and next enter read. - * When writing is over, all readers are granted permissing to restart - * concurrently. - * This is the same as: - *

    -	 * synchronized(monitor) {
    -	 *   monitor.exitWrite();
    -	 *   monitor.enterRead();
    -	 * }
    -	 * 
    - */ - public synchronized void exitWriteEnterRead() { - this.exitWrite(); - this.enterRead(); - } -} - diff --git a/core/org.eclipse.cdt.core/model/org/eclipse/cdt/core/model/CoreModel.java b/core/org.eclipse.cdt.core/model/org/eclipse/cdt/core/model/CoreModel.java index 2ac6a848c40..1b2e6c6a274 100644 --- a/core/org.eclipse.cdt.core/model/org/eclipse/cdt/core/model/CoreModel.java +++ b/core/org.eclipse.cdt.core/model/org/eclipse/cdt/core/model/CoreModel.java @@ -31,7 +31,6 @@ import org.eclipse.cdt.internal.core.model.OutputEntry; import org.eclipse.cdt.internal.core.model.PathEntryManager; import org.eclipse.cdt.internal.core.model.ProjectEntry; import org.eclipse.cdt.internal.core.model.SourceEntry; -import org.eclipse.cdt.internal.core.search.indexing.IndexManager; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IProject; @@ -1215,14 +1214,6 @@ public class CoreModel { } } - public void startIndexing() { - manager.getIndexManager().reset(); - } - - public IndexManager getIndexManager() { - return manager.getIndexManager(); - } - /** * The method returns whether scanner information for a resource is empty or not. *

    diff --git a/core/org.eclipse.cdt.core/model/org/eclipse/cdt/core/model/ILanguage.java b/core/org.eclipse.cdt.core/model/org/eclipse/cdt/core/model/ILanguage.java index ce4bde33afd..93034bc3c82 100644 --- a/core/org.eclipse.cdt.core/model/org/eclipse/cdt/core/model/ILanguage.java +++ b/core/org.eclipse.cdt.core/model/org/eclipse/cdt/core/model/ILanguage.java @@ -12,6 +12,7 @@ package org.eclipse.cdt.core.model; import org.eclipse.cdt.core.dom.ast.ASTCompletionNode; +import org.eclipse.cdt.core.dom.ast.IASTName; import org.eclipse.cdt.core.dom.ast.IASTTranslationUnit; import org.eclipse.core.runtime.IAdaptable; @@ -75,6 +76,18 @@ public interface ILanguage extends IAdaptable { */ public ASTCompletionNode getCompletionNode(IWorkingCopy workingCopy, int offset); + /** + * Gather the list of IASTNames that appear the selection with the given start offset + * and length in the given ITranslationUnit. + * + * @param tu + * @param start + * @param length + * @param style + * @return + */ + public IASTName[] getSelectedNames(IASTTranslationUnit ast, int start, int length); + /** * Used to override the default model building behavior for a translation unit. * diff --git a/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/core/browser/IQualifiedTypeName.java b/core/org.eclipse.cdt.core/model/org/eclipse/cdt/core/model/util/IQualifiedTypeName.java similarity index 97% rename from core/org.eclipse.cdt.core/browser/org/eclipse/cdt/core/browser/IQualifiedTypeName.java rename to core/org.eclipse.cdt.core/model/org/eclipse/cdt/core/model/util/IQualifiedTypeName.java index 2d7836201c9..1a2d786c8c2 100644 --- a/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/core/browser/IQualifiedTypeName.java +++ b/core/org.eclipse.cdt.core/model/org/eclipse/cdt/core/model/util/IQualifiedTypeName.java @@ -8,7 +8,7 @@ * Contributors: * QNX Software Systems - initial API and implementation *******************************************************************************/ -package org.eclipse.cdt.core.browser; +package org.eclipse.cdt.core.model.util; public interface IQualifiedTypeName extends Comparable { diff --git a/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/core/browser/QualifiedTypeName.java b/core/org.eclipse.cdt.core/model/org/eclipse/cdt/core/model/util/QualifiedTypeName.java similarity index 99% rename from core/org.eclipse.cdt.core/browser/org/eclipse/cdt/core/browser/QualifiedTypeName.java rename to core/org.eclipse.cdt.core/model/org/eclipse/cdt/core/model/util/QualifiedTypeName.java index fac1632764f..fbdf1bf8bcc 100644 --- a/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/core/browser/QualifiedTypeName.java +++ b/core/org.eclipse.cdt.core/model/org/eclipse/cdt/core/model/util/QualifiedTypeName.java @@ -8,7 +8,7 @@ * Contributors: * QNX Software Systems - initial API and implementation *******************************************************************************/ -package org.eclipse.cdt.core.browser; +package org.eclipse.cdt.core.model.util; import org.eclipse.cdt.core.CConventions; import org.eclipse.core.runtime.IStatus; diff --git a/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/core/browser/Signature.java b/core/org.eclipse.cdt.core/model/org/eclipse/cdt/core/model/util/Signature.java similarity index 99% rename from core/org.eclipse.cdt.core/browser/org/eclipse/cdt/core/browser/Signature.java rename to core/org.eclipse.cdt.core/model/org/eclipse/cdt/core/model/util/Signature.java index 9786f678247..51679c51772 100644 --- a/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/core/browser/Signature.java +++ b/core/org.eclipse.cdt.core/model/org/eclipse/cdt/core/model/util/Signature.java @@ -9,7 +9,7 @@ * IBM Corporation - initial API and implementation * IBM Corporation - added J2SE 1.5 support *******************************************************************************/ -package org.eclipse.cdt.core.browser; +package org.eclipse.cdt.core.model.util; import org.eclipse.cdt.internal.core.CharOperation; diff --git a/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/core/browser/TypeUtil.java b/core/org.eclipse.cdt.core/model/org/eclipse/cdt/core/model/util/TypeUtil.java similarity index 92% rename from core/org.eclipse.cdt.core/browser/org/eclipse/cdt/core/browser/TypeUtil.java rename to core/org.eclipse.cdt.core/model/org/eclipse/cdt/core/model/util/TypeUtil.java index 9c86849c845..7c98786e521 100644 --- a/core/org.eclipse.cdt.core/browser/org/eclipse/cdt/core/browser/TypeUtil.java +++ b/core/org.eclipse.cdt.core/model/org/eclipse/cdt/core/model/util/TypeUtil.java @@ -8,12 +8,11 @@ * Contributors: * QNX Software Systems - initial API and implementation *******************************************************************************/ -package org.eclipse.cdt.core.browser; +package org.eclipse.cdt.core.model.util; import java.util.ArrayList; import java.util.List; -import org.eclipse.cdt.core.browser.typehierarchy.ITypeHierarchy; import org.eclipse.cdt.core.model.CModelException; import org.eclipse.cdt.core.model.ICElement; import org.eclipse.cdt.core.model.IMember; @@ -21,7 +20,6 @@ import org.eclipse.cdt.core.model.IMethodDeclaration; import org.eclipse.cdt.core.model.IParent; import org.eclipse.cdt.core.model.IStructure; import org.eclipse.cdt.core.model.ITranslationUnit; -import org.eclipse.cdt.core.parser.ast.ASTAccessVisibility; public class TypeUtil { @@ -300,20 +298,20 @@ public class TypeUtil { * @return The first method found or null, if nothing found */ // TODO move methods to CModelUtil - public static IMethodDeclaration findMethodDeclarationInHierarchy(ITypeHierarchy hierarchy, ICElement type, String name, String[] paramTypes, boolean isConstructor, boolean isDestructor) throws CModelException { - ICElement[] superTypes= hierarchy.getAllSupertypes(type); - for (int i= superTypes.length - 1; i >= 0; i--) { - IMethodDeclaration first= findMethod(name, paramTypes, isConstructor, isDestructor, superTypes[i]); - if (first != null && first.getVisibility() != ASTAccessVisibility.PRIVATE) { - // the order getAllSupertypes does make assumptions of the order of inner elements -> search recursivly - IMethodDeclaration res= findMethodDeclarationInHierarchy(hierarchy, TypeUtil.getDeclaringClass(first), name, paramTypes, isConstructor, isDestructor); - if (res != null) { - return res; - } - return first; - } - } - return null; - } +// public static IMethodDeclaration findMethodDeclarationInHierarchy(ITypeHierarchy hierarchy, ICElement type, String name, String[] paramTypes, boolean isConstructor, boolean isDestructor) throws CModelException { +// ICElement[] superTypes= hierarchy.getAllSupertypes(type); +// for (int i= superTypes.length - 1; i >= 0; i--) { +// IMethodDeclaration first= findMethod(name, paramTypes, isConstructor, isDestructor, superTypes[i]); +// if (first != null && first.getVisibility() != ASTAccessVisibility.PRIVATE) { +// // the order getAllSupertypes does make assumptions of the order of inner elements -> search recursivly +// IMethodDeclaration res= findMethodDeclarationInHierarchy(hierarchy, TypeUtil.getDeclaringClass(first), name, paramTypes, isConstructor, isDestructor); +// if (res != null) { +// return res; +// } +// return first; +// } +// } +// return null; +// } } diff --git a/core/org.eclipse.cdt.core/model/org/eclipse/cdt/internal/core/model/CModelBuilder.java b/core/org.eclipse.cdt.core/model/org/eclipse/cdt/internal/core/model/CModelBuilder.java index 7fb149ce463..f49ad3807d4 100644 --- a/core/org.eclipse.cdt.core/model/org/eclipse/cdt/internal/core/model/CModelBuilder.java +++ b/core/org.eclipse.cdt.core/model/org/eclipse/cdt/internal/core/model/CModelBuilder.java @@ -165,8 +165,9 @@ public class CModelBuilder { scanInfo = new ExtendedScannerInfo(); } + IResource resource = translationUnit.getUnderlyingResource(); CodeReader reader = - translationUnit.getUnderlyingResource() != null + resource != null && resource.getLocation() != null ? new CodeReader(translationUnit.getUnderlyingResource().getLocation().toOSString(), code) : new CodeReader(code); parser = ParserFactory.createParser( diff --git a/core/org.eclipse.cdt.core/model/org/eclipse/cdt/internal/core/model/CModelManager.java b/core/org.eclipse.cdt.core/model/org/eclipse/cdt/internal/core/model/CModelManager.java index a30297c338d..943662ea232 100644 --- a/core/org.eclipse.cdt.core/model/org/eclipse/cdt/internal/core/model/CModelManager.java +++ b/core/org.eclipse.cdt.core/model/org/eclipse/cdt/internal/core/model/CModelManager.java @@ -48,7 +48,6 @@ import org.eclipse.cdt.core.model.IParent; import org.eclipse.cdt.core.model.ISourceRoot; import org.eclipse.cdt.core.model.ITranslationUnit; import org.eclipse.cdt.core.model.IWorkingCopy; -import org.eclipse.cdt.internal.core.search.indexing.IndexManager; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IProject; @@ -1111,10 +1110,6 @@ public class CModelManager implements IResourceChangeListener, ICDescriptorListe * */ public void shutdown() { - if (this.fDeltaProcessor.indexManager != null) { // no more indexing - this.fDeltaProcessor.indexManager.shutdown(); - } - // Remove ourself from the DescriptorManager. CCorePlugin.getDefault().getCDescriptorManager().removeDescriptorListener(factory); // Remove ourself from the ContentTypeManager @@ -1129,13 +1124,7 @@ public class CModelManager implements IResourceChangeListener, ICDescriptorListe } } - public IndexManager getIndexManager() { - return this.fDeltaProcessor.indexManager; - } - public void deleting(IProject project) { - // discard all indexing jobs for this project - this.getIndexManager().discardJobs(project.getName()); // stop the binary runner for this project removeBinaryRunner(project); } diff --git a/core/org.eclipse.cdt.core/model/org/eclipse/cdt/internal/core/model/DeltaProcessor.java b/core/org.eclipse.cdt.core/model/org/eclipse/cdt/internal/core/model/DeltaProcessor.java index debf48bd441..74fe1f61189 100644 --- a/core/org.eclipse.cdt.core/model/org/eclipse/cdt/internal/core/model/DeltaProcessor.java +++ b/core/org.eclipse.cdt.core/model/org/eclipse/cdt/internal/core/model/DeltaProcessor.java @@ -11,7 +11,6 @@ package org.eclipse.cdt.internal.core.model; -import org.eclipse.cdt.core.index.ICDTIndexer; import org.eclipse.cdt.core.model.CModelException; import org.eclipse.cdt.core.model.CoreModel; import org.eclipse.cdt.core.model.IArchive; @@ -23,7 +22,6 @@ import org.eclipse.cdt.core.model.ICElement; import org.eclipse.cdt.core.model.ICElementDelta; import org.eclipse.cdt.core.model.ICProject; import org.eclipse.cdt.core.model.ISourceRoot; -import org.eclipse.cdt.internal.core.search.indexing.IndexManager; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IResourceDelta; @@ -43,8 +41,6 @@ public class DeltaProcessor { */ protected CElementDelta fCurrentDelta; - protected IndexManager indexManager = new IndexManager(); - /* The C element that was last created (see createElement(IResource). * This is used as a stack of C elements (using getParent() to pop it, and * using the various get*(...) to push it. */ @@ -543,7 +539,6 @@ public class DeltaProcessor { switch (delta.getKind()) { case IResourceDelta.ADDED : if (element != null) { - updateIndexAddResource(element, delta, false); elementAdded(element, delta); return element instanceof ICContainer; } @@ -551,7 +546,6 @@ public class DeltaProcessor { case IResourceDelta.REMOVED : if (element != null) { - updateIndexRemoveResource(element, delta); elementRemoved(element, delta); } return element instanceof ICContainer; @@ -562,10 +556,6 @@ public class DeltaProcessor { // content has changed if (element != null) { elementChanged(element, delta); - updateIndexAddResource(element, delta, true); - //check to see if any projects need to be reindexed - updateDependencies(element); - } } else if (resource.getType() == IResource.PROJECT) { if ((flags & IResourceDelta.OPEN) != 0) { @@ -574,11 +564,9 @@ public class DeltaProcessor { if (element != null) { if (project.isOpen()) { elementOpened(element, delta); - updateIndexAddResource(element, delta, true); return false; } elementClosed(element, delta); - updateIndexRemoveResource(element, delta); //Don't process children return false; } @@ -594,10 +582,8 @@ public class DeltaProcessor { // note its resources are still visible as roots to other projects if (isCProject) { elementOpened(element, delta); - updateIndexAddResource(element, delta, true); } else { elementRemoved(element, delta); - updateIndexRemoveResource(element, delta); } return true; } @@ -609,62 +595,4 @@ public class DeltaProcessor { return true; } - protected void updateIndexAddResource(ICElement element, IResourceDelta delta, boolean elementHasChanged) { - - if (indexManager == null) - return; - - switch (element.getElementType()){ - case ICElement.C_PROJECT: - indexManager.addResourceEvent(element.getCProject().getProject(),delta, ICDTIndexer.PROJECT); - break; - - case ICElement.C_CCONTAINER: - indexManager.addResourceEvent(element.getCProject().getProject(),delta, ICDTIndexer.FOLDER); - break; - - case ICElement.C_UNIT: - indexManager.addResourceEvent(element.getCProject().getProject(),delta, ICDTIndexer.COMPILATION_UNIT); - break; - } - - - } - - protected void updateIndexRemoveResource(ICElement element, IResourceDelta delta) { - - if (indexManager == null) - return; - - switch (element.getElementType()){ - case ICElement.C_PROJECT: - indexManager.removeResourceEvent(element.getCProject().getProject(),delta, ICDTIndexer.PROJECT); - break; - - case ICElement.C_CCONTAINER: - indexManager.removeResourceEvent(element.getCProject().getProject(),delta, ICDTIndexer.FOLDER); - break; - - case ICElement.C_UNIT: - indexManager.removeResourceEvent(element.getCProject().getProject(),delta, ICDTIndexer.COMPILATION_UNIT); - break; - - } - - } - - private void updateDependencies(ICElement element){ - - IResource resource = element.getResource(); - if (resource == null) - return; - - IProject project = resource.getProject(); - String filename = resource.getName(); - - if (CoreModel.isValidHeaderUnitName(project, filename)) { - indexManager.updateDependencies(project, resource); - } - } - } diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/DOMSearchUtil.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/DOMSearchUtil.java new file mode 100644 index 00000000000..3bfc4f23ddd --- /dev/null +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/DOMSearchUtil.java @@ -0,0 +1,219 @@ +/******************************************************************************* + * Copyright (c) 2000, 2005 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.cdt.core.dom; + +import java.util.ArrayList; +import java.util.List; + +import org.eclipse.cdt.core.CCorePlugin; +import org.eclipse.cdt.core.dom.ast.DOMException; +import org.eclipse.cdt.core.dom.ast.IASTName; +import org.eclipse.cdt.core.dom.ast.IASTTranslationUnit; +import org.eclipse.cdt.core.dom.ast.IBinding; +import org.eclipse.cdt.core.dom.ast.c.CASTVisitor; +import org.eclipse.cdt.core.dom.ast.cpp.CPPASTVisitor; +import org.eclipse.cdt.core.dom.ast.cpp.ICPPClassScope; +import org.eclipse.cdt.core.dom.ast.cpp.ICPPConstructor; +import org.eclipse.cdt.core.dom.ast.cpp.ICPPMethod; +import org.eclipse.cdt.core.parser.ParserLanguage; +import org.eclipse.cdt.core.parser.util.ArrayUtil; +import org.eclipse.cdt.internal.core.pdom.dom.PDOMBinding; +import org.eclipse.cdt.internal.core.pdom.dom.PDOMName; +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IProject; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IPath; +import org.eclipse.core.runtime.content.IContentType; + +/** + * Utility class to have commonly used algorithms in one place for searching with the DOM. + * + * @author dsteffle + */ +public class DOMSearchUtil { + private static final IASTName[] BLANK_NAME_ARRAY = new IASTName[0]; + private static final IASTName[] EMPTY_NAME_LIST = BLANK_NAME_ARRAY; + + public static final int DECLARATIONS = 1; + public static final int DEFINITIONS = 2; + public static final int DECLARATIONS_DEFINITIONS = 3; + public static final int REFERENCES = 4; + public static final int ALL_OCCURRENCES = 5; + /** + * This retrieves the ParserLanguage from an IFile. + * + * @param file + * @return + */ + public static ParserLanguage getLanguageFromFile(IFile file) { + IProject project = file.getProject(); + IContentType contentType = CCorePlugin.getContentType(project, file.getFullPath().lastSegment()); + if (contentType != null) { + String lid = contentType.getId(); + if (CCorePlugin.CONTENT_TYPE_CXXSOURCE.equals(lid)) { + return ParserLanguage.CPP; + } + } + return ParserLanguage.C; + } + + /** + * The CPPNameCollector used to get IASTNames from an IASTNode. + * + * @author dsteffle + */ + static public class CPPNameCollector extends CPPASTVisitor { + { + shouldVisitNames = true; + } + public List nameList = new ArrayList(); + public int visit( IASTName name ){ + nameList.add( name ); + return PROCESS_CONTINUE; + } + public IASTName getName( int idx ){ + if( idx < 0 || idx >= nameList.size() ) + return null; + return (IASTName) nameList.get( idx ); + } + public int size() { return nameList.size(); } + } + + /** + * The CNameCollector used to get IASTNames from an IASTNode. + * + * @author dsteffle + */ + static public class CNameCollector extends CASTVisitor { + { + shouldVisitNames = true; + } + public List nameList = new ArrayList(); + public int visit( IASTName name ){ + nameList.add( name ); + return PROCESS_CONTINUE; + } + public IASTName getName( int idx ){ + if( idx < 0 || idx >= nameList.size() ) + return null; + return (IASTName) nameList.get( idx ); + } + public int size() { return nameList.size(); } + } + + /** + * Returns the ParserLanguage corresponding to the IPath and IProject. Returns ParserLanguage.CPP if the file type is a header. + * + * @param path + * @param project + * @return + */ + public static ParserLanguage getLanguage( IPath path, IProject project ) + { + //FIXME: ALAIN, for headers should we assume CPP ?? + // The problem is that it really depends on how the header was included. + String id = null; + IContentType contentType = CCorePlugin.getContentType(project, path.lastSegment()); + if (contentType != null) { + id = contentType.getId(); + } + if (id != null) { + if (CCorePlugin.CONTENT_TYPE_CXXHEADER.equals(id)) { + return ParserLanguage.CPP; + } else if (CCorePlugin.CONTENT_TYPE_CXXSOURCE.equals(id)) { + return ParserLanguage.CPP; + } else if (CCorePlugin.CONTENT_TYPE_CHEADER.equals(id)) { + return ParserLanguage.CPP; // <============== is that right ? should not this be C ? + } else if (CCorePlugin.CONTENT_TYPE_CSOURCE.equals(id)) { + return ParserLanguage.C; + } else if (CCorePlugin.CONTENT_TYPE_ASMSOURCE.equals(id)) { + // ??? + // What do we do here ? + } + } + return ParserLanguage.CPP; + } + + /** + * This is used to get the names from the TU that the IASTName searchName belongs to. + * + * @param searchName the IASTName whose references/delcarations are to be retrieved + * @param limitTo used to specify whether to get declarations, references, or both, one of: + * ( CSearchPattern.DECLARATION | CSearchPattern.REFERENCES | CSearchPattern.ALL_OCCURRENCES ) + * @return IASTName[] declarations, references, or both depending on limitTo that correspond to the IASTName searchName searched for + */ + public static IASTName[] getNamesFromDOM(IASTName searchName, int limitTo) { + IASTName[] names = null; + IASTTranslationUnit tu = searchName.getTranslationUnit(); + + if (tu == null) { + return BLANK_NAME_ARRAY; + } + + IBinding binding = searchName.resolveBinding(); + if (binding instanceof PDOMBinding) { + try { + ArrayList pdomNames = new ArrayList(); + // First decls + PDOMName name = ((PDOMBinding)binding).getFirstDeclaration(); + while (name != null) { + pdomNames.add(name); + name = name.getNextInBinding(); + } + // Next defs + name = ((PDOMBinding)binding).getFirstDefinition(); + while (name != null) { + pdomNames.add(name); + name = name.getNextInBinding(); + } + names = (IASTName[])pdomNames.toArray(new IASTName[pdomNames.size()]); + } catch (CoreException e) { + CCorePlugin.log(e); + } + } else { + names = getNames(tu, binding, limitTo); + + if (names == null || names.length == 0) { // try alternate strategies + try { + // fix for 86829, 95224 + if ((binding instanceof ICPPConstructor || (binding instanceof ICPPMethod && ((ICPPMethod)binding).isDestructor())) + && binding.getScope() instanceof ICPPClassScope) { + binding = ((ICPPClassScope)binding.getScope()).getClassType(); + names = getNames(tu, binding, limitTo); + } + } catch (DOMException e) {} + } + } + + return names; + } + + private static IASTName[] getNames(IASTTranslationUnit tu, IBinding binding, int limitTo) { + IASTName[] names = null; + if (limitTo == DECLARATIONS || + limitTo == DECLARATIONS_DEFINITIONS) { + names = tu.getDeclarations(binding); + } else if (limitTo == REFERENCES) { + names = tu.getReferences(binding); + } else if (limitTo == DEFINITIONS) { + names = tu.getDefinitions(binding); + } else if (limitTo == ALL_OCCURRENCES){ + names = tu.getDeclarations(binding); + names = (IASTName[])ArrayUtil.addAll(IASTName.class, names, tu.getReferences(binding)); + } else { // assume ALL + names = tu.getDeclarations(binding); + names = (IASTName[])ArrayUtil.addAll(IASTName.class, names, tu.getReferences(binding)); + } + + return names; + } + +} diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/IPDOM.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/IPDOM.java index c02c74260a8..347a8fc26ae 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/IPDOM.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/IPDOM.java @@ -10,27 +10,28 @@ *******************************************************************************/ package org.eclipse.cdt.core.dom; -import org.eclipse.cdt.core.dom.ast.IASTName; import org.eclipse.cdt.core.dom.ast.IBinding; import org.eclipse.cdt.core.model.IWorkingCopy; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IAdaptable; /** - * @author Doug Schaefer + * This is the reader interface to the PDOM. It is used by general + * clients that need access to the information stored there. * - * This is the interface to the Persisted DOM (PDOM). - * It provides services to allow access to DOM information - * persisted between parses. + * @author Doug Schaefer */ public interface IPDOM extends IAdaptable { - public IBinding resolveBinding(IASTName name); - + /** + * Find all the bindings that match the pattern. + * + * @param pattern + * @return + * @throws CoreException + */ public IBinding[] findBindings(String pattern) throws CoreException; - public IASTName[] getDeclarations(IBinding binding); - /** * Recursively visit the nodes in this PDOM using the given visitor. * diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/IPDOMResolver.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/IPDOMResolver.java new file mode 100644 index 00000000000..e56dc353b39 --- /dev/null +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/IPDOMResolver.java @@ -0,0 +1,32 @@ +/******************************************************************************* + * Copyright (c) 2006 QNX Software Systems and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * QNX - Initial API and implementation + *******************************************************************************/ + +package org.eclipse.cdt.core.dom; + +import org.eclipse.cdt.core.dom.ast.IASTName; +import org.eclipse.cdt.core.dom.ast.IBinding; +import org.eclipse.core.runtime.IAdaptable; + +/** + * This is the interface used by the DOM to help with resolving + * bindings amongst other things. + * + * @author Doug Schaefer + */ +public interface IPDOMResolver extends IAdaptable { + + public IBinding resolveBinding(IASTName name); + + public IASTName[] getDeclarations(IBinding binding); + + public IASTName[] getDefinitions(IBinding binding); + +} diff --git a/core/org.eclipse.cdt.core/search/org/eclipse/cdt/core/search/LimitTo.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/IPDOMWriter.java similarity index 61% rename from core/org.eclipse.cdt.core/search/org/eclipse/cdt/core/search/LimitTo.java rename to core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/IPDOMWriter.java index 74c756a562e..4bb5fd0fc1b 100644 --- a/core/org.eclipse.cdt.core/search/org/eclipse/cdt/core/search/LimitTo.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/IPDOMWriter.java @@ -6,15 +6,19 @@ * http://www.eclipse.org/legal/epl-v10.html * * Contributors: - * QNX - initial API and implementation + * QNX - Initial API and implementation *******************************************************************************/ -package org.eclipse.cdt.core.search; +package org.eclipse.cdt.core.dom; -public class LimitTo { - LimitTo( int value ) - { - this.value = value; - } - private final int value; -} \ No newline at end of file +import org.eclipse.core.runtime.IAdaptable; + +/** + * This is the interface used by clients, such as indexers, to + * write content to the PDOM. + * + * @author Doug Schaefer + */ +public interface IPDOMWriter extends IAdaptable { + +} diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/ast/gnu/c/GCCLanguage.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/ast/gnu/c/GCCLanguage.java index 55e25aac803..905d9130dc7 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/ast/gnu/c/GCCLanguage.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/ast/gnu/c/GCCLanguage.java @@ -11,10 +11,16 @@ package org.eclipse.cdt.core.dom.ast.gnu.c; +import java.util.ArrayList; +import java.util.List; + import org.eclipse.cdt.core.CCorePlugin; import org.eclipse.cdt.core.dom.ICodeReaderFactory; import org.eclipse.cdt.core.dom.ast.ASTCompletionNode; +import org.eclipse.cdt.core.dom.ast.IASTName; +import org.eclipse.cdt.core.dom.ast.IASTNode; import org.eclipse.cdt.core.dom.ast.IASTTranslationUnit; +import org.eclipse.cdt.core.dom.ast.c.CASTVisitor; import org.eclipse.cdt.core.model.ICProject; import org.eclipse.cdt.core.model.IContributedModelBuilder; import org.eclipse.cdt.core.model.ILanguage; @@ -86,7 +92,7 @@ public class GCCLanguage extends PlatformObject implements ILanguage { PDOM pdom = (PDOM)CCorePlugin.getPDOMManager().getPDOM(project).getAdapter(PDOM.class); ICodeReaderFactory fileCreator; - if ((style & ILanguage.AST_SKIP_INDEXED_HEADERS) != 0) + if ((style & (ILanguage.AST_SKIP_INDEXED_HEADERS | ILanguage.AST_SKIP_ALL_HEADERS)) != 0) fileCreator = new PDOMCodeReaderFactory(pdom); else fileCreator = SavedCodeReaderFactory.getInstance(); @@ -169,6 +175,34 @@ public class GCCLanguage extends PlatformObject implements ILanguage { return node; } + private static class NameCollector extends CASTVisitor { + { + shouldVisitNames = true; + } + private List nameList = new ArrayList(); + public int visit( IASTName name ){ + nameList.add( name ); + return PROCESS_CONTINUE; + } + public IASTName[] getNames() { + return (IASTName[])nameList.toArray(new IASTName[nameList.size()]); + } + } + + public IASTName[] getSelectedNames(IASTTranslationUnit ast, int start, int length) { + IASTNode selectedNode = ast.selectNodeForLocation(ast.getFilePath(), start, length); + + if (selectedNode == null) + return new IASTName[0]; + + if (selectedNode instanceof IASTName) + return new IASTName[] { (IASTName)selectedNode }; + + NameCollector collector = new NameCollector(); + selectedNode.accept(collector); + return collector.getNames(); + } + public IContributedModelBuilder createModelBuilder(ITranslationUnit tu) { // Use the default CDT model builder return null; diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/ast/gnu/cpp/GPPLanguage.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/ast/gnu/cpp/GPPLanguage.java index e664b0c2c99..cf8f470a6ce 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/ast/gnu/cpp/GPPLanguage.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/ast/gnu/cpp/GPPLanguage.java @@ -11,10 +11,16 @@ package org.eclipse.cdt.core.dom.ast.gnu.cpp; +import java.util.ArrayList; +import java.util.List; + import org.eclipse.cdt.core.CCorePlugin; import org.eclipse.cdt.core.dom.ICodeReaderFactory; import org.eclipse.cdt.core.dom.ast.ASTCompletionNode; +import org.eclipse.cdt.core.dom.ast.IASTName; +import org.eclipse.cdt.core.dom.ast.IASTNode; import org.eclipse.cdt.core.dom.ast.IASTTranslationUnit; +import org.eclipse.cdt.core.dom.ast.cpp.CPPASTVisitor; import org.eclipse.cdt.core.model.ICProject; import org.eclipse.cdt.core.model.IContributedModelBuilder; import org.eclipse.cdt.core.model.ILanguage; @@ -85,21 +91,18 @@ public class GPPLanguage extends PlatformObject implements ILanguage { PDOM pdom = (PDOM)CCorePlugin.getPDOMManager().getPDOM(project).getAdapter(PDOM.class); ICodeReaderFactory fileCreator; - if ((style & ILanguage.AST_SKIP_INDEXED_HEADERS) != 0) + if ((style & (ILanguage.AST_SKIP_INDEXED_HEADERS | ILanguage.AST_SKIP_ALL_HEADERS)) != 0) fileCreator = new PDOMCodeReaderFactory(pdom); else fileCreator = SavedCodeReaderFactory.getInstance(); CodeReader reader; IFile rfile = (IFile)file.getResource(); + String path = rfile != null ? rfile.getLocation().toOSString() : file.getPath().toOSString(); if (file instanceof IWorkingCopy) { // get the working copy contents - reader = new CodeReader(((IWorkingCopy)file).getOriginalElement().getPath().toOSString(), file.getContents()); + reader = new CodeReader(path, file.getContents()); } else { - String path - = rfile != null - ? rfile.getLocation().toOSString() - : file.getPath().toOSString(); reader = fileCreator.createCodeReaderForTranslationUnit(path); if (reader == null) return null; @@ -164,7 +167,34 @@ public class GPPLanguage extends PlatformObject implements ILanguage { return node; } - + private static class NameCollector extends CPPASTVisitor { + { + shouldVisitNames = true; + } + private List nameList = new ArrayList(); + public int visit( IASTName name ){ + nameList.add( name ); + return PROCESS_CONTINUE; + } + public IASTName[] getNames() { + return (IASTName[])nameList.toArray(new IASTName[nameList.size()]); + } + } + + public IASTName[] getSelectedNames(IASTTranslationUnit ast, int start, int length) { + IASTNode selectedNode = ast.selectNodeForLocation(ast.getFilePath(), start, length); + + if (selectedNode == null) + return new IASTName[0]; + + if (selectedNode instanceof IASTName) + return new IASTName[] { (IASTName)selectedNode }; + + NameCollector collector = new NameCollector(); + selectedNode.accept(collector); + return collector.getNames(); + } + public IContributedModelBuilder createModelBuilder(ITranslationUnit tu) { // Use the default CDT model builder return null; diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/c/CASTTranslationUnit.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/c/CASTTranslationUnit.java index ecbd6cfdef8..3f5ea80846a 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/c/CASTTranslationUnit.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/c/CASTTranslationUnit.java @@ -10,7 +10,9 @@ *******************************************************************************/ package org.eclipse.cdt.internal.core.dom.parser.c; +import org.eclipse.cdt.core.CCorePlugin; import org.eclipse.cdt.core.dom.IPDOM; +import org.eclipse.cdt.core.dom.IPDOMResolver; import org.eclipse.cdt.core.dom.ast.ASTVisitor; import org.eclipse.cdt.core.dom.ast.IASTArrayDeclarator; import org.eclipse.cdt.core.dom.ast.IASTArrayModifier; @@ -47,6 +49,8 @@ import org.eclipse.cdt.internal.core.dom.parser.ASTPreprocessorSelectionResult; import org.eclipse.cdt.internal.core.dom.parser.IRequiresLocationInformation; import org.eclipse.cdt.internal.core.parser.scanner2.ILocationResolver; import org.eclipse.cdt.internal.core.parser.scanner2.InvalidPreprocessorNodeException; +import org.eclipse.cdt.internal.core.pdom.PDOM; +import org.eclipse.core.runtime.CoreException; /** * @author jcamelon @@ -125,8 +129,18 @@ public class CASTTranslationUnit extends CASTNode implements return resolver.getDeclarations( (IMacroBinding)binding ); } IASTName[] names = CVisitor.getDeclarations(this, binding); - if (names.length == 0 && pdom != null) - names = pdom.getDeclarations(binding); + + if (names.length == 0 && pdom != null) { + try { + binding = ((PDOM)pdom).getLinkage(getLanguage()).adaptBinding(binding); + if (binding != null) + names = ((IPDOMResolver)pdom.getAdapter(IPDOMResolver.class)).getDeclarations(binding); + } catch (CoreException e) { + CCorePlugin.log(e); + return names; + } + } + return names; } @@ -135,15 +149,32 @@ public class CASTTranslationUnit extends CASTNode implements * * @see org.eclipse.cdt.core.dom.ast.IASTTranslationUnit#getDefinitions(org.eclipse.cdt.core.dom.ast.IBinding) */ - public IASTName[] getDefinitions(IBinding aBinding) { - IASTName[] foundDefs = getDeclarations(aBinding); - - for(int i=0; iPreferences>Java>Code Generation>Code and Comments - */ -public class BasicSearchMatch implements IMatch, Comparable { - - String name = null; - String parentName = null; - String[] qualifiedName; - - String[] parameters; - String returnType; - - IResource resource = null; - IPath path = null; - - int type = 0; - int visibility = 0; - - boolean isConst = false; - boolean isVolatile = false; - boolean isStatic = false; - - private int hashCode = 0; - - IPath referringElement = null; - - IMatchLocatable locatable = null; - - - public BasicSearchMatch() { - //Create empty BasicSearchMatch - } - - final static private String HASH_SEPERATOR = ":"; //$NON-NLS-1$ - public int hashCode(){ - if( hashCode == 0 ) - { - StringBuffer hashBuffer = new StringBuffer(); - hashBuffer.append( name ); - hashBuffer.append( HASH_SEPERATOR ); - hashBuffer.append( parentName ); - hashBuffer.append( HASH_SEPERATOR ); - hashBuffer.append( returnType ); - if( getLocation() != null){ - hashBuffer.append( HASH_SEPERATOR ); - hashBuffer.append( getLocation().toString() ); - } - hashBuffer.append( HASH_SEPERATOR ); - hashBuffer.append( locatable instanceof IOffsetLocatable ? ((IOffsetLocatable)locatable).getNameStartOffset():((ILineLocatable)locatable).getStartLine()); - hashBuffer.append( HASH_SEPERATOR ); - hashBuffer.append( locatable instanceof IOffsetLocatable ? ((IOffsetLocatable)locatable).getNameEndOffset(): ((ILineLocatable)locatable).getEndLine()); - hashBuffer.append( HASH_SEPERATOR ); - hashBuffer.append( type ); - hashBuffer.append( HASH_SEPERATOR ); - hashBuffer.append( visibility ); - - hashCode = hashBuffer.toString().hashCode(); - } - return hashCode; - } - - public boolean equals(Object obj){ - if( !(obj instanceof BasicSearchMatch ) ){ - return false; - } - BasicSearchMatch match = (BasicSearchMatch)obj; - - if ((locatable != null && match.locatable==null) || - (locatable==null && match.locatable!=null)){ - return false; - } - - if (locatable!=null && match.locatable !=null){ - if (!(locatable instanceof IOffsetLocatable && match.locatable instanceof IOffsetLocatable) || - !(locatable instanceof ILineLocatable && match.locatable instanceof ILineLocatable)) - return false; - - if (locatable instanceof IOffsetLocatable){ - if (((IOffsetLocatable)locatable).getNameStartOffset() != ((IOffsetLocatable)match.locatable).getNameStartOffset() || - ((IOffsetLocatable)locatable).getNameEndOffset() != ((IOffsetLocatable)match.locatable).getNameEndOffset()) - return false; - - } else { - if (((ILineLocatable)locatable).getStartLine() != ((ILineLocatable)match.locatable).getStartLine()) - return false; - } - } - - - if( type != match.getElementType() || visibility != match.getVisibility() ) - return false; - - if( name != null && match.getName() != null){ - if( !name.equals( match.getName() ) ) - return false; - } else if( name != match.getName() ){ - return false; - } - - if( parentName != null && match.getParentName() != null){ - if( !parentName.equals( match.getParentName() ) ) - return false; - } else if( parentName != match.getParentName() ){ - return false; - } - - if( returnType != null && match.getReturnType() != null){ - if( !returnType.equals( match.getReturnType() ) ) - return false; - } else if( returnType != match.getReturnType() ){ - return false; - } - - IPath thisPath = getLocation(); - IPath matchPath = match.getLocation(); - if( thisPath != null && matchPath != null ){ - if( !thisPath.equals( matchPath ) ) - return false; - } else if( thisPath != matchPath ){ - return false; - } - - return true; - } - - public int compareTo( Object o ){ - if( !( o instanceof BasicSearchMatch ) ){ - throw new ClassCastException(); - } - - BasicSearchMatch match = (BasicSearchMatch) o; - - int result = getLocation().toString().compareTo( match.getLocation().toString() ); - if( result != 0 ) return result; - - - if (locatable instanceof IOffsetLocatable && match.getLocatable() instanceof IOffsetLocatable){ - result = ((IOffsetLocatable)locatable).getNameStartOffset() - ((IOffsetLocatable)match.locatable).getNameStartOffset(); - if( result != 0 ) return result; - - result = ((IOffsetLocatable)locatable).getNameEndOffset() - ((IOffsetLocatable)match.locatable).getNameEndOffset(); - if( result != 0 ) return result; - } - else if (locatable instanceof ILineLocatable && match.getLocatable() instanceof ILineLocatable){ - result = ((ILineLocatable)locatable).getStartLine() - ((ILineLocatable)match.locatable).getStartLine(); - if( result != 0 ) return result; - - result = ((ILineLocatable)locatable).getEndLine() - ((ILineLocatable)match.locatable).getEndLine(); - if( result != 0 ) return result; - } - - result = getName().compareTo( match.getName() ); - if( result != 0 ) return result; - - result = getParentName().compareTo( match.getParentName() ); - if( result != 0 ) return result; - - result = getReturnType().compareTo( match.getReturnType() ); - return result; - } - - public int getElementType() { - return type; - } - - public int getVisibility() { - return visibility; - } - - public String getName() { - return name; - } - - public String getParentName() { - return parentName; - } - - public String[] getParameters() { - return parameters; - } - - public String getReturnType() { - return returnType; - } - - public IResource getResource() { - return resource; - } - - public IPath getLocation() { - if(resource != null) - return resource.getLocation(); - else if (path != null) - return path; - else return null; - } - - public IPath getReferenceLocation() { - return referringElement; - } - - public boolean isStatic() { - return isStatic; - } - public boolean isConst() { - return isConst; - } - - public boolean isVolatile() { - return isVolatile; - } - /** - * @return - */ - public int getType() { - return type; - } - - /** - * @param b - */ - public void setConst(boolean b) { - isConst = b; - } - - /** - * @param b - */ - public void setStatic(boolean b) { - isStatic = b; - } - - /** - * @param b - */ - public void setVolatile(boolean b) { - isVolatile = b; - } - - /** - * @param string - */ - public void setName(String string) { - name = string; - } - - /** - * @param string - */ - public void setParentName(String string) { - parentName = string; - } - - public void setParameters(String[] params) { - parameters = params; - } - - /** - * @param string - */ - public void setReturnType(String string) { - returnType = string; - } - /** - * @param i - */ - public void setType(int i) { - type = i; - } - - /** - * @param i - */ - public void setVisibility(int i) { - visibility = i; - } - - public IMatchLocatable getLocatable() { - return locatable; - } - - public void setLocatable(IMatchLocatable locatable) { - this.locatable = locatable; - } - - public void setResource(IResource resource) { - this.resource = resource; - } - - public IPath getPath() { - return path; - } - - public void setPath(IPath path) { - this.path = path; - } - - public IPath getReferringElement() { - return referringElement; - } - - public void setReferringElement(IPath referringElement) { - this.referringElement = referringElement; - } - - public String[] getQualifiedName() { - return qualifiedName; - } - - public void setQualifiedName(String[] qualifiedName) { - this.qualifiedName = qualifiedName; - } - -} diff --git a/core/org.eclipse.cdt.core/search/org/eclipse/cdt/core/search/BasicSearchResultCollector.java b/core/org.eclipse.cdt.core/search/org/eclipse/cdt/core/search/BasicSearchResultCollector.java deleted file mode 100644 index 0fe626a61e6..00000000000 --- a/core/org.eclipse.cdt.core/search/org/eclipse/cdt/core/search/BasicSearchResultCollector.java +++ /dev/null @@ -1,235 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2003, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corp. - Rational Software - initial implementation - *******************************************************************************/ -/* - * Created on Jul 29, 2003 - */ -package org.eclipse.cdt.core.search; - -import java.util.HashSet; -import java.util.Set; - -import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.cdt.core.parser.ISourceElementCallbackDelegate; -import org.eclipse.cdt.core.parser.ast.ASTAccessVisibility; -import org.eclipse.cdt.core.parser.ast.ASTClassKind; -import org.eclipse.cdt.core.parser.ast.ASTUtil; -import org.eclipse.cdt.core.parser.ast.IASTClassSpecifier; -import org.eclipse.cdt.core.parser.ast.IASTElaboratedTypeSpecifier; -import org.eclipse.cdt.core.parser.ast.IASTEnumerationSpecifier; -import org.eclipse.cdt.core.parser.ast.IASTEnumerator; -import org.eclipse.cdt.core.parser.ast.IASTField; -import org.eclipse.cdt.core.parser.ast.IASTFunction; -import org.eclipse.cdt.core.parser.ast.IASTMacro; -import org.eclipse.cdt.core.parser.ast.IASTMethod; -import org.eclipse.cdt.core.parser.ast.IASTNamespaceDefinition; -import org.eclipse.cdt.core.parser.ast.IASTOffsetableElement; -import org.eclipse.cdt.core.parser.ast.IASTOffsetableNamedElement; -import org.eclipse.cdt.core.parser.ast.IASTParameterDeclaration; -import org.eclipse.cdt.core.parser.ast.IASTQualifiedNameElement; -import org.eclipse.cdt.core.parser.ast.IASTReference; -import org.eclipse.cdt.core.parser.ast.IASTTypedefDeclaration; -import org.eclipse.cdt.core.parser.ast.IASTVariable; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.IProgressMonitor; - -/** - * @author aniefer - * - * To change the template for this generated type comment go to - * Window>Preferences>Java>Code Generation>Code and Comments - */ -public class BasicSearchResultCollector implements ICSearchResultCollector { - IProgressMonitor fProgressMonitor = null; - - public BasicSearchResultCollector() { - } - - public BasicSearchResultCollector(IProgressMonitor monitor) { - fProgressMonitor = monitor; - } - - public void aboutToStart() { - results = new HashSet(); - } - - public void done() { - } - - public IProgressMonitor getProgressMonitor() { - return fProgressMonitor; - } - - public void setProgressMonitor(IProgressMonitor monitor) { - fProgressMonitor = monitor; - } - - public IMatch createMatch(Object fileResource, int start, int end, ISourceElementCallbackDelegate node, IPath referringElement) - { - BasicSearchMatch result = new BasicSearchMatch(); - return createMatch( result, fileResource, start, end, node, referringElement); - } - - public IMatch createMatch( BasicSearchMatch result, Object fileResource, int start, int end, ISourceElementCallbackDelegate node, IPath referringElement ) { - if( fileResource instanceof IResource ) - result.resource = (IResource) fileResource; - else if( fileResource instanceof IPath ) - result.path = (IPath) fileResource; - - result.locatable = new OffsetLocatable(start,end); - result.parentName = ""; //$NON-NLS-1$ - result.referringElement = referringElement; - - IASTOffsetableNamedElement offsetable = null; - - if( node instanceof IASTReference ){ - offsetable = (IASTOffsetableNamedElement) ((IASTReference)node).getReferencedElement(); - result.name = ((IASTReference)node).getName(); - } else if( node instanceof IASTOffsetableNamedElement ){ - offsetable = (IASTOffsetableNamedElement)node; - result.name = offsetable.getName(); - } - - result.parentName = ""; //$NON-NLS-1$ - String [] names = null; - if( offsetable instanceof IASTEnumerator ){ - IASTEnumerator enumerator = (IASTEnumerator) offsetable; - names = enumerator.getOwnerEnumerationSpecifier().getFullyQualifiedName(); - } else if( offsetable instanceof IASTQualifiedNameElement ) { - names = ((IASTQualifiedNameElement) offsetable).getFullyQualifiedName(); - } - - if( names != null ){ - for( int i = 0; i < names.length - 1; i++ ){ - if( i > 0 ) - result.parentName += "::"; //$NON-NLS-1$ - - result.parentName += names[ i ]; - } - } - if (offsetable instanceof IASTVariable){ - result.returnType = ASTUtil.getType(((IASTVariable)offsetable).getAbstractDeclaration()); - } - if( offsetable instanceof IASTFunction ){ - result.name += getParameterString( (IASTFunction) offsetable ); - result.returnType = ASTUtil.getType(((IASTFunction)offsetable).getReturnType()); - } - - setElementInfo( result, offsetable ); - - return result; - } - - - /** - * @param function - * @return - */ - private String getParameterString(IASTFunction function) { - if( function == null ) - return ""; //$NON-NLS-1$ - - String paramString = "("; //$NON-NLS-1$ - - String [] paramTypes = ASTUtil.getFunctionParameterTypes( function ); - - for( int i = 0; i < paramTypes.length; i++ ){ - if( i != 0 ) - paramString += ", "; //$NON-NLS-1$ - paramString += paramTypes[i]; - } - - paramString += ")"; //$NON-NLS-1$ - return paramString; - } - - public boolean acceptMatch(IMatch match) throws CoreException { - if( !results.contains( match ) ){ - results.add( match ); - return true; - } - return false; - } - - public Set getSearchResults(){ - return results; - } - - private void setElementInfo( BasicSearchMatch match, IASTOffsetableElement node ){ - //ImageDescriptor imageDescriptor = null; - if( node instanceof IASTClassSpecifier || - node instanceof IASTElaboratedTypeSpecifier ){ - - ASTClassKind kind = null; - if (node instanceof IASTClassSpecifier){ - kind = ((IASTClassSpecifier)node).getClassKind(); - } - else{ - kind = ((IASTElaboratedTypeSpecifier)node).getClassKind(); - } - - if( kind == ASTClassKind.CLASS ){ - match.type = ICElement.C_CLASS; - } else if ( kind == ASTClassKind.STRUCT ){ - match.type = ICElement.C_STRUCT; - } else if ( kind == ASTClassKind.UNION ){ - match.type = ICElement.C_UNION; - } - } else if ( node instanceof IASTNamespaceDefinition ){ - match.type = ICElement.C_NAMESPACE; - } else if ( node instanceof IASTEnumerationSpecifier ){ - match.type = ICElement.C_ENUMERATION; - } else if ( node instanceof IASTMacro ){ - match.type = ICElement.C_MACRO; - } else if ( node instanceof IASTField ){ - match.type = ICElement.C_FIELD; - IASTField field = (IASTField)node; - ASTAccessVisibility visibility = field.getVisiblity(); - if( visibility == ASTAccessVisibility.PUBLIC ){ - match.visibility = ICElement.CPP_PUBLIC; - } else if ( visibility == ASTAccessVisibility.PRIVATE ) { - match.visibility = ICElement.CPP_PRIVATE; - } // else protected, there is no ICElement.CPP_PROTECTED - match.isConst = field.getAbstractDeclaration().isConst(); - match.isStatic = field.isStatic(); - } else if ( node instanceof IASTVariable ){ - match.type = ICElement.C_VARIABLE; - IASTVariable variable = (IASTVariable)node; - match.isConst = variable.getAbstractDeclaration().isConst(); - } else if (node instanceof IASTParameterDeclaration){ - match.type = ICElement.C_VARIABLE; - match.isConst = ((IASTParameterDeclaration) node).isConst(); - } else if ( node instanceof IASTEnumerator ){ - match.type = ICElement.C_ENUMERATOR; - } else if ( node instanceof IASTMethod ){ - match.type = ICElement.C_METHOD; - IASTMethod method = (IASTMethod) node; - ASTAccessVisibility visibility = method.getVisiblity(); - if( visibility == ASTAccessVisibility.PUBLIC ){ - match.visibility = ICElement.CPP_PUBLIC; - } else if ( visibility == ASTAccessVisibility.PRIVATE ) { - match.visibility = ICElement.CPP_PRIVATE; - } // else protected, there is no ICElement.CPP_PROTECTED - match.isConst = method.isConst(); - match.isVolatile = method.isVolatile(); - match.isStatic = method.isStatic(); - } else if ( node instanceof IASTFunction ){ - match.type = ICElement.C_FUNCTION; - IASTFunction function = (IASTFunction)node; - match.isStatic = function.isStatic(); - } else if ( node instanceof IASTTypedefDeclaration ){ - match.type = ICElement.C_TYPEDEF; - } - } - - private Set results; -} diff --git a/core/org.eclipse.cdt.core/search/org/eclipse/cdt/core/search/DOMSearchUtil.java b/core/org.eclipse.cdt.core/search/org/eclipse/cdt/core/search/DOMSearchUtil.java deleted file mode 100644 index 60bfe138081..00000000000 --- a/core/org.eclipse.cdt.core/search/org/eclipse/cdt/core/search/DOMSearchUtil.java +++ /dev/null @@ -1,569 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.core.search; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import org.eclipse.cdt.core.CCorePlugin; -import org.eclipse.cdt.core.ICLogConstants; -import org.eclipse.cdt.core.dom.CDOM; -import org.eclipse.cdt.core.dom.IASTServiceProvider; -import org.eclipse.cdt.core.dom.ast.ASTVisitor; -import org.eclipse.cdt.core.dom.ast.DOMException; -import org.eclipse.cdt.core.dom.ast.IASTFunctionDeclarator; -import org.eclipse.cdt.core.dom.ast.IASTName; -import org.eclipse.cdt.core.dom.ast.IASTNode; -import org.eclipse.cdt.core.dom.ast.IASTTranslationUnit; -import org.eclipse.cdt.core.dom.ast.IBinding; -import org.eclipse.cdt.core.dom.ast.ICompositeType; -import org.eclipse.cdt.core.dom.ast.IEnumeration; -import org.eclipse.cdt.core.dom.ast.IEnumerator; -import org.eclipse.cdt.core.dom.ast.IFunction; -import org.eclipse.cdt.core.dom.ast.IMacroBinding; -import org.eclipse.cdt.core.dom.ast.IProblemBinding; -import org.eclipse.cdt.core.dom.ast.ITypedef; -import org.eclipse.cdt.core.dom.ast.IVariable; -import org.eclipse.cdt.core.dom.ast.c.CASTVisitor; -import org.eclipse.cdt.core.dom.ast.cpp.CPPASTVisitor; -import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTNamespaceDefinition; -import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTQualifiedName; -import org.eclipse.cdt.core.dom.ast.cpp.ICPPBinding; -import org.eclipse.cdt.core.dom.ast.cpp.ICPPClassScope; -import org.eclipse.cdt.core.dom.ast.cpp.ICPPClassType; -import org.eclipse.cdt.core.dom.ast.cpp.ICPPConstructor; -import org.eclipse.cdt.core.dom.ast.cpp.ICPPField; -import org.eclipse.cdt.core.dom.ast.cpp.ICPPMethod; -import org.eclipse.cdt.core.dom.ast.cpp.ICPPNamespace; -import org.eclipse.cdt.core.dom.ast.cpp.ICPPNamespaceAlias; -import org.eclipse.cdt.core.parser.ParseError; -import org.eclipse.cdt.core.parser.ParserLanguage; -import org.eclipse.cdt.core.parser.util.ArrayUtil; -import org.eclipse.cdt.internal.core.index.domsourceindexer.IndexVisitorUtil; -import org.eclipse.cdt.internal.core.pdom.dom.PDOMBinding; -import org.eclipse.cdt.internal.core.pdom.dom.PDOMName; -import org.eclipse.cdt.internal.core.search.matching.CSearchPattern; -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.content.IContentType; - -/** - * Utility class to have commonly used algorithms in one place for searching with the DOM. - * - * @author dsteffle - */ -public class DOMSearchUtil { - private static final String BLANK_STRING = ""; //$NON-NLS-1$ - private static final IASTName[] BLANK_NAME_ARRAY = new IASTName[0]; - private static final IASTName[] EMPTY_NAME_LIST = BLANK_NAME_ARRAY; - private static final Set EMPTY_MATCHES = new HashSet(0); - - /** - * This is a convenience method that uses the SearchEngine to find declarations, references, or both that correspond - * to the IASTName searchName found in the index. - * - * @param scope is used to limit the scope that SearchEngine searches the index against - * @param searchName is the IASTName whose delcarations/references are sought after - * @param limitTo used to specify whether to get declarations, references, or both, one of: - * ( CSearchPattern.DECLARATION | CSearchPattern.REFERENCES | CSearchPattern.ALL_OCCURRENCES ) - * @return - */ - public static Set getMatchesFromSearchEngine(ICSearchScope scope, IASTName searchName, LimitTo limitTo) { - SearchEngine engine = new SearchEngine(); - BasicSearchResultCollector results = new BasicSearchResultCollector(); - - ICSearchPattern pattern = createPattern(searchName, limitTo, true); - - try { - engine.setWaitingPolicy(ICSearchConstants.FORCE_IMMEDIATE_SEARCH); - engine.search(CCorePlugin.getWorkspace(), pattern, scope, results, false); - } catch (InterruptedException e) { - return EMPTY_MATCHES; - } - - return results.getSearchResults(); - } - - /** - * This is a convenience method that uses the SearchEngine to find everything in the index - * that matches to a String. - * - * @param scope the scope to search within the index - * @param searchPattern the string used to search the index with - * @return - */ - public static Set getMatchesFromSearchEngine(ICSearchScope scope, String searchPattern, LimitTo limitTo) { - SearchEngine engine = new SearchEngine(); - BasicSearchResultCollector results = new BasicSearchResultCollector(); - - ICSearchPattern pattern = SearchEngine.createSearchPattern( searchPattern, ICSearchConstants.UNKNOWN_SEARCH_FOR, limitTo, true ); - - try { - engine.setWaitingPolicy(ICSearchConstants.FORCE_IMMEDIATE_SEARCH); - engine.search(CCorePlugin.getWorkspace(), pattern, scope, results, false); - } catch (InterruptedException e) { - return EMPTY_MATCHES; - } - - return results.getSearchResults(); - } - - private static CSearchPattern createPattern( IASTName searchName, LimitTo limitTo, boolean caseSensitive) { - IBinding binding = searchName.resolveBinding(); - if (binding == null) - return null; - - // build the SearchFor/pattern based on the IBinding - SearchFor searchFor = createSearchFor(binding); - - return CSearchPattern.createPattern(DOMSearchUtil.getSearchPattern(searchName), searchFor, limitTo, ICSearchConstants.EXACT_MATCH, caseSensitive); - } - - private static SearchFor createSearchFor( IBinding binding ) { - SearchFor searchFor = null; - if (binding instanceof ICPPMethod) { - searchFor = ICSearchConstants.METHOD; - } else if (binding instanceof IFunction) { - searchFor = ICSearchConstants.FUNCTION; - } else if (binding instanceof ICPPNamespace || binding instanceof ICPPNamespaceAlias) { - searchFor = ICSearchConstants.NAMESPACE; - } else if (binding instanceof ICPPField) { - searchFor = ICSearchConstants.FIELD; - } else if (binding instanceof IEnumerator) { - searchFor = ICSearchConstants.ENUMTOR; - } else if (binding instanceof IMacroBinding) { - searchFor = ICSearchConstants.MACRO; - } else if (binding instanceof ITypedef) { - searchFor = ICSearchConstants.TYPEDEF; - } else if (binding instanceof IVariable) { - searchFor = ICSearchConstants.VAR; - } else if (binding instanceof ICompositeType) { - try { - switch(((ICompositeType)binding).getKey()) { - case ICompositeType.k_struct: - case ICPPClassType.k_class: - searchFor = ICSearchConstants.CLASS_STRUCT; - break; - case ICompositeType.k_union: - searchFor = ICSearchConstants.UNION; - break; - default: - searchFor = ICSearchConstants.TYPE; - break; - } - } catch (DOMException e) { - searchFor = ICSearchConstants.UNKNOWN_SEARCH_FOR; - } - } else if (binding instanceof IEnumeration) { - searchFor = ICSearchConstants.ENUM; - } else { - searchFor = ICSearchConstants.UNKNOWN_SEARCH_FOR; - } - return searchFor; - } - - /** - * This is used to get an array of selected names in an IASTTranslationUnit based on the offset - * and length into that IASTTranslationUnit. - * - * ex: IASTTranslationUnit contains: int foo; - * then getSelectedNamesFrom(file, 4, 3) will return the IASTName corresponding to foo - * - * @param tu - * @param offset - * @param length - * @param lang - * @return - */ - public static IASTName[] getSelectedNamesFrom(IASTTranslationUnit tu, int offset, int length, ParserLanguage lang) { - IASTNode node = null; - try{ - if (tu != null) - node = tu.selectNodeForLocation(tu.getFilePath(), offset, length); - } - catch (ParseError er){} - catch ( VirtualMachineError vmErr){ - if (vmErr instanceof OutOfMemoryError){ - org.eclipse.cdt.internal.core.model.Util.log(null, "Open Declarations Out Of Memory error: " + vmErr.getMessage() + " on File: " + tu.getContainingFilename(), ICLogConstants.CDT); //$NON-NLS-1$ //$NON-NLS-2$ - } - } - catch (Exception ex){} - - finally{ - if (node == null){ - return EMPTY_NAME_LIST; - } - } - - if (node instanceof IASTName) { - IASTName[] results = new IASTName[1]; - results[0] = (IASTName)node; - return results; - } - - ASTVisitor collector = null; - if (lang == ParserLanguage.CPP) { - collector = new CPPNameCollector(); - } else { - collector = new CNameCollector(); - } - - node.accept( collector ); - - List names = null; - if (collector instanceof CPPNameCollector) { - names = ((CPPNameCollector)collector).nameList; - } else { - names = ((CNameCollector)collector).nameList; - } - - IASTName[] results = new IASTName[names.size()]; - for(int i=0; i= nameList.size() ) - return null; - return (IASTName) nameList.get( idx ); - } - public int size() { return nameList.size(); } - } - - /** - * The CNameCollector used to get IASTNames from an IASTNode. - * - * @author dsteffle - */ - static public class CNameCollector extends CASTVisitor { - { - shouldVisitNames = true; - } - public List nameList = new ArrayList(); - public int visit( IASTName name ){ - nameList.add( name ); - return PROCESS_CONTINUE; - } - public IASTName getName( int idx ){ - if( idx < 0 || idx >= nameList.size() ) - return null; - return (IASTName) nameList.get( idx ); - } - public int size() { return nameList.size(); } - } - - /** - * Returns the ParserLanguage corresponding to the IPath and IProject. Returns ParserLanguage.CPP if the file type is a header. - * - * @param path - * @param project - * @return - */ - public static ParserLanguage getLanguage( IPath path, IProject project ) - { - //FIXME: ALAIN, for headers should we assume CPP ?? - // The problem is that it really depends on how the header was included. - String id = null; - IContentType contentType = CCorePlugin.getContentType(project, path.lastSegment()); - if (contentType != null) { - id = contentType.getId(); - } - if (id != null) { - if (CCorePlugin.CONTENT_TYPE_CXXHEADER.equals(id)) { - return ParserLanguage.CPP; - } else if (CCorePlugin.CONTENT_TYPE_CXXSOURCE.equals(id)) { - return ParserLanguage.CPP; - } else if (CCorePlugin.CONTENT_TYPE_CHEADER.equals(id)) { - return ParserLanguage.CPP; // <============== is that right ? should not this be C ? - } else if (CCorePlugin.CONTENT_TYPE_CSOURCE.equals(id)) { - return ParserLanguage.C; - } else if (CCorePlugin.CONTENT_TYPE_ASMSOURCE.equals(id)) { - // ??? - // What do we do here ? - } - } - return ParserLanguage.CPP; - } - - /** - * Generates a search pattern String based on the IASTName passed as a parameter. - * - * Used to generate a string to present to the user as well as a string used by - * the SearchEngine to parse for qualified names and parameters. - * - * @param name - * @return - */ - public static String getSearchPattern(IASTName name) { - if (name == null) - return BLANK_STRING; - - StringBuffer buffer = new StringBuffer(); - // first option - use binding to get qualified name - IBinding binding = name.resolveBinding(); - if (! (binding instanceof IProblemBinding)) { - if (binding instanceof ICPPBinding) { - ICPPBinding cppBinding = (ICPPBinding) binding; - try { - String[] qualifiedName = cppBinding.getQualifiedName(); - for (int i = 0; i < qualifiedName.length; i++) { - if (i != 0) { - buffer.append("::"); //$NON-NLS-1$ - } - buffer.append(qualifiedName[i]); - } - } catch (DOMException e) { - buffer.append(name.toString()); - } - } else { - buffer.append(name.toString()); // if it's not an ICPPBinding then just use the name - } - } - // second option - traverse the tree - else { - String[] namespaces = null; - - IASTNode parent = name.getParent(); - while(!(parent instanceof IASTTranslationUnit) && parent != null) { - if (parent instanceof ICPPASTNamespaceDefinition) { - namespaces = (String[])ArrayUtil.append(String.class, namespaces, - ((ICPPASTNamespaceDefinition)parent).getName().toString()); - } - parent = parent.getParent(); - } - - if (namespaces != null && namespaces.length > 0) { - for( int i=namespaces.length-1; i>=0; i-- ) { - if (namespaces[i] != null) { - buffer.append(namespaces[i]); - buffer.append("::"); //$NON-NLS-1$ - } - } - } - - if (name.getParent() instanceof ICPPASTQualifiedName) { - IASTName[] names = ((ICPPASTQualifiedName)name.getParent()).getNames(); - for(int i=0; i - * This interface defines the constants used by the search engine. - *

    - *

    - * This interface declares constants only; it is not intended to be implemented. - *

    - * @see org.eclipse.cdt.core.search.SearchEngine - */ -public interface ICSearchConstants { - /** - * The nature of searched element or the nature - * of match in unknown. - */ - public static final SearchFor UNKNOWN_SEARCH_FOR = new SearchFor( -1 ); - public static final LimitTo UNKNOWN_LIMIT_TO = new LimitTo( -1 ); - - /* Nature of searched element */ - - /** - * The searched element is a type. - */ - public static final SearchFor TYPE = new SearchFor( 0 ); - - /** - * The searched element is a function. - */ - public static final SearchFor FUNCTION = new SearchFor( 1 ); - - /** - * The searched element is a namespace. - */ - public static final SearchFor NAMESPACE = new SearchFor( 2 ); - - /** - * The searched element is a method (member function). - */ - public static final SearchFor METHOD = new SearchFor( 3 ); - - /** - * The searched element is a field (member variable). - */ - public static final SearchFor FIELD = new SearchFor( 4 ); - - /** - * The searched element is a variable. - * More selective than using TYPE - */ - public static final SearchFor VAR = new SearchFor( 5 ); - - /** - * The searched element is a class. - * More selective than using TYPE - */ - public static final SearchFor CLASS = new SearchFor( 6 ); - - /** - * The searched element is a struct. - * More selective than using TYPE - */ - public static final SearchFor STRUCT = new SearchFor( 7 ); - - /** - * The searched element is a enum. - * More selective than using TYPE - */ - public static final SearchFor ENUM = new SearchFor( 8 ); - - /** - * The searched element is a union. - * More selective than using TYPE - */ - public static final SearchFor UNION = new SearchFor( 9 ); - - public static final SearchFor MACRO = new SearchFor( 10 ); - - public static final SearchFor CLASS_STRUCT = new SearchFor( 11 ); - - public static final SearchFor TYPEDEF = new SearchFor( 12 ); - - public static final SearchFor INCLUDE = new SearchFor( 13 ); - - public static final SearchFor DERIVED = new SearchFor( 14 ); - - public static final SearchFor ENUMTOR = new SearchFor( 15 ); - - public static final SearchFor FRIEND = new SearchFor( 16 ); - - - /* Nature of match */ - - /** - * The search result is a declaration. - * Can be used in conjunction with any of the nature of searched elements - * so as to better narrow down the search. - */ - public static final LimitTo DECLARATIONS = new LimitTo( 0 ); - - /** - * The search result is a type that implements an interface. - * Used in conjunction with either TYPE or CLASS or INTERFACE, it will - * respectively search for any type implementing/extending an interface, or - * rather exclusively search for classes implementing an interface, or interfaces - * extending an interface. - */ - public static final LimitTo DEFINITIONS = new LimitTo( 1 ); - - /** - * The search result is a reference. - * Can be used in conjunction with any of the nature of searched elements - * so as to better narrow down the search. - * References can contain implementers since they are more generic kind - * of matches. - */ - public static final LimitTo REFERENCES = new LimitTo( 2 ); - - /** - * The search result is a declaration, a reference, or an implementer - * of an interface. - * Can be used in conjunction with any of the nature of searched elements - * so as to better narrow down the search. - */ - public static final LimitTo ALL_OCCURRENCES = new LimitTo( 3 ); - - /** - * The search result is a declaration or a definitoin - */ - public static final LimitTo DECLARATIONS_DEFINITIONS = new LimitTo( 4 ); - - /* Syntactic match modes */ - - /** - * The search pattern matches exactly the search result, - * that is, the source of the search result equals the search pattern. - */ - int EXACT_MATCH = 0; - /** - * The search pattern is a prefix of the search result. - */ - int PREFIX_MATCH = 1; - /** - * The search pattern contains one or more wild cards ('*') where a - * wild-card can replace 0 or more characters in the search result. - */ - int PATTERN_MATCH = 2; - - - /* Case sensitivity */ - - /** - * The search pattern matches the search result only - * if cases are the same. - */ - boolean CASE_SENSITIVE = true; - /** - * The search pattern ignores cases in the search result. - */ - boolean CASE_INSENSITIVE = false; - - - /* Waiting policies */ - - /** - * The search operation starts immediately, even if the underlying indexer - * has not finished indexing the workspace. Results will more likely - * not contain all the matches. - */ - int FORCE_IMMEDIATE_SEARCH = IIndexJob.ForceImmediate; - /** - * The search operation throws an org.eclipse.core.runtime.OperationCanceledException - * if the underlying indexer has not finished indexing the workspace. - */ - int CANCEL_IF_NOT_READY_TO_SEARCH = IIndexJob.CancelIfNotReady; - /** - * The search operation waits for the underlying indexer to finish indexing - * the workspace before starting the search. - */ - int WAIT_UNTIL_READY_TO_SEARCH = IIndexJob.WaitUntilReady; - - public static final String EXTERNAL_SEARCH_LINK_PREFIX = "cdtlnk"; //$NON-NLS-1$ -} diff --git a/core/org.eclipse.cdt.core/search/org/eclipse/cdt/core/search/ICSearchPattern.java b/core/org.eclipse.cdt.core/search/org/eclipse/cdt/core/search/ICSearchPattern.java deleted file mode 100644 index 7fe4c1f3b73..00000000000 --- a/core/org.eclipse.cdt.core/search/org/eclipse/cdt/core/search/ICSearchPattern.java +++ /dev/null @@ -1,39 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2003 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corp. - Rational Software - initial implementation - *******************************************************************************/ -/* - * Created on Jun 13, 2003 - */ -package org.eclipse.cdt.core.search; - -import org.eclipse.cdt.core.parser.ISourceElementCallbackDelegate; - -/** - * @author aniefer - * - * To change the template for this generated type comment go to - * Window>Preferences>Java>Code Generation>Code and Comments - */ -public interface ICSearchPattern extends ICSearchConstants{ - - public static final int IMPOSSIBLE_MATCH = 0; - public static final int POSSIBLE_MATCH = 1; - public static final int ACCURATE_MATCH = 2; - public static final int INACCURATE_MATCH = 3; - - /** - * @param node - * @return - */ - int matchLevel( ISourceElementCallbackDelegate node, LimitTo limit ); - - LimitTo getLimitTo(); - boolean canAccept( LimitTo limit ); -} diff --git a/core/org.eclipse.cdt.core/search/org/eclipse/cdt/core/search/ICSearchResultCollector.java b/core/org.eclipse.cdt.core/search/org/eclipse/cdt/core/search/ICSearchResultCollector.java deleted file mode 100644 index a88c65a4d1c..00000000000 --- a/core/org.eclipse.cdt.core/search/org/eclipse/cdt/core/search/ICSearchResultCollector.java +++ /dev/null @@ -1,62 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2003, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corp. - Rational Software - initial implementation - *******************************************************************************/ -/* - * Created on Jun 11, 2003 - */ -package org.eclipse.cdt.core.search; - -import org.eclipse.cdt.core.parser.ISourceElementCallbackDelegate; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.IProgressMonitor; - -/** - * @author aniefer - * - * To change the template for this generated type comment go to - * Window>Preferences>Java>Code Generation>Code and Comments - */ -public interface ICSearchResultCollector { - /** - * The search result corresponds exactly to the search pattern. - */ - int EXACT_MATCH = 0; - - /** - * The search result is potentially a match for the search pattern, - * but a problem prevented the search engine from being more accurate - * (typically because of the classpath was not correctly set). - */ - int POTENTIAL_MATCH = 1; - - /** - * Called before the actual search starts. - */ - public void aboutToStart(); - - /** - * Called when the search has ended. - */ - public void done(); - - public IMatch createMatch( Object fileResource, int start, int end, - ISourceElementCallbackDelegate node, IPath referringElement) throws CoreException; - - //return whether or not the match was accepted - public boolean acceptMatch( IMatch match ) throws CoreException; - - /** - * Returns the progress monitor used to report progress. - * - * @return a progress monitor or null if no progress monitor is provided - */ - public IProgressMonitor getProgressMonitor(); -} diff --git a/core/org.eclipse.cdt.core/search/org/eclipse/cdt/core/search/ICSearchScope.java b/core/org.eclipse.cdt.core/search/org/eclipse/cdt/core/search/ICSearchScope.java deleted file mode 100644 index 9f3e3d1d381..00000000000 --- a/core/org.eclipse.cdt.core/search/org/eclipse/cdt/core/search/ICSearchScope.java +++ /dev/null @@ -1,46 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2003 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -/* - * Created on Jun 12, 2003 - */ -package org.eclipse.cdt.core.search; - -import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.core.runtime.IPath; - -public interface ICSearchScope { - /** - * Checks whether the resource at the given path is enclosed by this scope. - * - * @param resourcePath if the resource is contained in - * @return whether the resource is enclosed by this scope - */ - public boolean encloses(String resourcePath); - /** - * Checks whether this scope encloses the given element. - * - * @param element the given element - * @return true if the element is in this scope - */ - public boolean encloses(ICElement element); - /** - * Returns the paths to the enclosing projects for this search scope. - *
      - *
    • If the path is a project path, this is the full path of the project - * (see IResource.getFullPath()). - * For example, /MyProject - *
    • - * - * @return an array of paths to the enclosing projects. - */ - IPath[] enclosingProjects(); - -} diff --git a/core/org.eclipse.cdt.core/search/org/eclipse/cdt/core/search/ILineLocatable.java b/core/org.eclipse.cdt.core/search/org/eclipse/cdt/core/search/ILineLocatable.java deleted file mode 100644 index d575ec73d31..00000000000 --- a/core/org.eclipse.cdt.core/search/org/eclipse/cdt/core/search/ILineLocatable.java +++ /dev/null @@ -1,16 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.core.search; - -public interface ILineLocatable extends IMatchLocatable { - int getStartLine(); - int getEndLine(); -} diff --git a/core/org.eclipse.cdt.core/search/org/eclipse/cdt/core/search/IMatch.java b/core/org.eclipse.cdt.core/search/org/eclipse/cdt/core/search/IMatch.java deleted file mode 100644 index 340c29285c4..00000000000 --- a/core/org.eclipse.cdt.core/search/org/eclipse/cdt/core/search/IMatch.java +++ /dev/null @@ -1,60 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2003, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corp. - Rational Software - initial implementation - *******************************************************************************/ - -package org.eclipse.cdt.core.search; - -import org.eclipse.core.resources.IResource; -import org.eclipse.core.runtime.IPath; - -/** - * Interface used for returning matches from the Search Engine - * - */ -public interface IMatch { - - /** - * Returns ICElement constant describing the element type - * @return - */ - int getElementType(); - - int getVisibility(); - - String getName(); - - /** - * Returns the list of parameters if this matched a function or a method. - * - * @return array of Strings for the parameters - */ - String[] getParameters(); - - /** - * Returns the return type if this matched a function or a method. - * - * @return the return type - */ - String getReturnType(); - - String getParentName(); - - IResource getResource(); - - IPath getLocation(); - - IPath getReferenceLocation(); - - IMatchLocatable getLocatable(); - - boolean isStatic(); - boolean isConst(); - boolean isVolatile(); -} diff --git a/core/org.eclipse.cdt.core/search/org/eclipse/cdt/core/search/IMatchLocatable.java b/core/org.eclipse.cdt.core/search/org/eclipse/cdt/core/search/IMatchLocatable.java deleted file mode 100644 index dbbec97c301..00000000000 --- a/core/org.eclipse.cdt.core/search/org/eclipse/cdt/core/search/IMatchLocatable.java +++ /dev/null @@ -1,15 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.core.search; - -public interface IMatchLocatable { - -} diff --git a/core/org.eclipse.cdt.core/search/org/eclipse/cdt/core/search/IMatchLocator.java b/core/org.eclipse.cdt.core/search/org/eclipse/cdt/core/search/IMatchLocator.java deleted file mode 100644 index acca2c9d426..00000000000 --- a/core/org.eclipse.cdt.core/search/org/eclipse/cdt/core/search/IMatchLocator.java +++ /dev/null @@ -1,34 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -/* - * Created on Apr 29, 2004 - * - * TODO To change the template for this generated file go to - * Window - Preferences - Java - Code Style - Code Templates - */ -package org.eclipse.cdt.core.search; - -import org.eclipse.cdt.core.model.IWorkingCopy; -import org.eclipse.core.resources.IWorkspace; -import org.eclipse.core.runtime.IProgressMonitor; - -/** - * @author bgheorgh - * - * TODO To change the template for this generated type comment go to - * Window - Preferences - Java - Code Style - Code Templates - */ -public interface IMatchLocator extends ICSearchConstants { - - public void locateMatches( String [] paths, IWorkspace workspace, IWorkingCopy[] workingCopies ) throws InterruptedException; - - public void setProgressMonitor(IProgressMonitor progressMonitor); -} diff --git a/core/org.eclipse.cdt.core/search/org/eclipse/cdt/core/search/IOffsetLocatable.java b/core/org.eclipse.cdt.core/search/org/eclipse/cdt/core/search/IOffsetLocatable.java deleted file mode 100644 index c4f62a0d859..00000000000 --- a/core/org.eclipse.cdt.core/search/org/eclipse/cdt/core/search/IOffsetLocatable.java +++ /dev/null @@ -1,19 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.core.search; - -public interface IOffsetLocatable extends IMatchLocatable { - int getNameStartOffset(); - int getNameEndOffset(); - - int getElementStartOffset(); - int getElementEndOffset(); -} diff --git a/core/org.eclipse.cdt.core/search/org/eclipse/cdt/core/search/LineLocatable.java b/core/org.eclipse.cdt.core/search/org/eclipse/cdt/core/search/LineLocatable.java deleted file mode 100644 index a0a6dc2f4aa..00000000000 --- a/core/org.eclipse.cdt.core/search/org/eclipse/cdt/core/search/LineLocatable.java +++ /dev/null @@ -1,30 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.core.search; - -public class LineLocatable implements ILineLocatable { - - int startLine; - int endLine; - - public LineLocatable(int startLine, int endLine){ - this.startLine = startLine; - this.endLine = endLine; - } - - public int getStartLine() { - return startLine; - } - - public int getEndLine() { - return endLine; - } -} diff --git a/core/org.eclipse.cdt.core/search/org/eclipse/cdt/core/search/OffsetLocatable.java b/core/org.eclipse.cdt.core/search/org/eclipse/cdt/core/search/OffsetLocatable.java deleted file mode 100644 index 184081e348e..00000000000 --- a/core/org.eclipse.cdt.core/search/org/eclipse/cdt/core/search/OffsetLocatable.java +++ /dev/null @@ -1,59 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.core.search; - -public class OffsetLocatable implements IOffsetLocatable { - - int nameStartOffset; - int nameEndOffset; - int elementStartOffset; - int elementEndOffset; - - /** - * Used to create an OffsetLocatable that contains just the name offsets - * @param nameStartOffset - the starting offset of the name - * @param nameEndOffset - the ending offset of the name - */ - public OffsetLocatable(int nameStartOffset, int nameEndOffset){ - this(nameStartOffset, nameEndOffset, 0, 0); - } - - /** - * Create an OffsetLocatable that contains both the offsets of the name and the offsets - * of the element itself - * @param nameStartOffset - the starting offset of the name - * @param nameEndOffset - the ending offset of the name - * @param elementStartOffset - the starting offset of the element - * @param elementEndOffset - the ending offset of the element - */ - public OffsetLocatable(int nameStartOffset, int nameEndOffset, int elementStartOffset, int elementEndOffset){ - this.nameStartOffset = nameStartOffset; - this.nameEndOffset = nameEndOffset; - this.elementStartOffset=elementStartOffset; - this.elementEndOffset=elementEndOffset; - } - - public int getNameStartOffset() { - return nameStartOffset; - } - - public int getNameEndOffset() { - return nameEndOffset; - } - - public int getElementStartOffset(){ - return elementStartOffset; - } - - public int getElementEndOffset(){ - return elementEndOffset; - } -} diff --git a/core/org.eclipse.cdt.core/search/org/eclipse/cdt/core/search/OrPattern.java b/core/org.eclipse.cdt.core/search/org/eclipse/cdt/core/search/OrPattern.java deleted file mode 100644 index c5c2391a688..00000000000 --- a/core/org.eclipse.cdt.core/search/org/eclipse/cdt/core/search/OrPattern.java +++ /dev/null @@ -1,117 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2003, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corp. - Rational Software - initial implementation - *******************************************************************************/ -/* - * Created on Aug 6, 2003 - */ -package org.eclipse.cdt.core.search; - -import java.io.IOException; -import java.util.Iterator; -import java.util.LinkedList; - -import org.eclipse.cdt.core.parser.ISourceElementCallbackDelegate; -import org.eclipse.cdt.internal.core.index.IEntryResult; -import org.eclipse.cdt.internal.core.index.cindexstorage.io.IndexInput; -import org.eclipse.cdt.internal.core.search.IIndexSearchRequestor; -import org.eclipse.cdt.internal.core.search.matching.CSearchPattern; -import org.eclipse.core.runtime.IProgressMonitor; - - -/** - * @author aniefer - * - * To change the template for this generated type comment go to - * Window>Preferences>Java>Code Generation>Code and Comments - */ -public class OrPattern extends CSearchPattern { - - public OrPattern(){ - super(); - patterns = new LinkedList(); - } - - /** - * @param pattern - */ - public void addPattern( ICSearchPattern pattern) { - if( pattern != null ) - patterns.add( pattern ); - } - - public int matchLevel(ISourceElementCallbackDelegate node, LimitTo limit ) { - Iterator iter = patterns.iterator(); - int size = patterns.size(); - - int result = IMPOSSIBLE_MATCH; - - for( int i = 0; i < size; i++ ){ - ICSearchPattern pattern = (ICSearchPattern) iter.next(); - result = pattern.matchLevel( node, limit ); - if( result != IMPOSSIBLE_MATCH ) - break; - } - - return result; - } - - public boolean canAccept(LimitTo limit) { - if( limit == ALL_OCCURRENCES ){ - return true; - } - - Iterator iter = patterns.iterator(); - int size = patterns.size(); - - for( int i = 0; i < size; i++ ){ - ICSearchPattern pattern = (ICSearchPattern) iter.next(); - if( pattern.canAccept( limit ) ) - return true; - } - - return false; - } - - public void findIndexMatches(IndexInput input, IIndexSearchRequestor requestor, int detailLevel, IProgressMonitor progressMonitor, ICSearchScope scope) throws IOException { - Iterator iter = patterns.iterator(); - int size = patterns.size(); - - for( int i = 0; i < size; i++ ){ - CSearchPattern pattern = (CSearchPattern) iter.next(); - pattern.findIndexMatches( input, requestor, detailLevel, progressMonitor, scope ); - } - } - - public void feedIndexRequestor( IIndexSearchRequestor requestor, int detailLevel, int[] fileRefs, int[][] offsets, int[][] offsetLengths, IndexInput input, ICSearchScope scope ) - throws IOException { - //never called for OrPattern - } - - protected void resetIndexInfo() { - //never called for OrPattern - } - - protected void decodeIndexEntry(IEntryResult entryResult) { - //never called for OrPattern - } - - public char[] indexEntryPrefix() { - //never called for OrPattern - return null; - } - - protected boolean matchIndexEntry() { - //never called for OrPattern - return false; - } - - private LinkedList patterns; - -} diff --git a/core/org.eclipse.cdt.core/search/org/eclipse/cdt/core/search/SearchEngine.java b/core/org.eclipse.cdt.core/search/org/eclipse/cdt/core/search/SearchEngine.java deleted file mode 100644 index cbcbbbe9b72..00000000000 --- a/core/org.eclipse.cdt.core/search/org/eclipse/cdt/core/search/SearchEngine.java +++ /dev/null @@ -1,274 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -/* - * Created on Jun 11, 2003 - */ -package org.eclipse.cdt.core.search; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.Iterator; - -import org.eclipse.cdt.core.CCorePlugin; -import org.eclipse.cdt.core.model.CModelException; -import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.cdt.core.model.ICProject; -import org.eclipse.cdt.core.model.IWorkingCopy; -import org.eclipse.cdt.internal.core.Util; -import org.eclipse.cdt.internal.core.model.CModelManager; -import org.eclipse.cdt.internal.core.search.CSearchScope; -import org.eclipse.cdt.internal.core.search.CWorkspaceScope; -import org.eclipse.cdt.internal.core.search.PathCollector; -import org.eclipse.cdt.internal.core.search.PatternSearchJob; -import org.eclipse.cdt.internal.core.search.indexing.IndexManager; -import org.eclipse.cdt.internal.core.search.matching.CSearchPattern; -import org.eclipse.cdt.internal.core.search.matching.MatchLocator; -import org.eclipse.core.resources.IFile; -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.Path; -import org.eclipse.core.runtime.SubProgressMonitor; - -/** - * @author aniefer - * - * To change the template for this generated type comment go to - * Window>Preferences>Java>Code Generation>Code and Comments - */ -public class SearchEngine implements ICSearchConstants{ - - public static boolean VERBOSE = false; - - /** - * A list of working copies that take precedence over their original - * compilation units. - */ - private IWorkingCopy[] workingCopies = null; - private int waitingPolicy = ICSearchConstants.WAIT_UNTIL_READY_TO_SEARCH; - - /** - * - */ - public SearchEngine() { - super(); - // TODO Auto-generated constructor stub - } - - public SearchEngine(IWorkingCopy[] workingCopies) { - this.workingCopies = workingCopies; - } - - /** - * Policy is one of ICSearchConstants.FORCE_IMMEDIATE_SEARCH, ICSearchConstants.CANCEL_IF_NOT_READY_TO_SEARCH - * or ICSearchConstants.WAIT_UNTIL_READY_TO_SEARCH - * @param policy - */ - public void setWaitingPolicy( int policy ){ - if( policy == FORCE_IMMEDIATE_SEARCH || - policy == CANCEL_IF_NOT_READY_TO_SEARCH || - policy == WAIT_UNTIL_READY_TO_SEARCH ) - { - waitingPolicy = policy; - } - } - /** - * @return - */ - public static ICSearchScope createWorkspaceScope() { - // TODO Auto-generated method stub - return new CWorkspaceScope(); - } - - public static ICSearchScope createCSearchScope(ICElement[] elements) { - return createCSearchScope(elements, true); - } - /** - * @param objects - * @return - */ - public static ICSearchScope createCSearchScope(ICElement[] elements, boolean includeReferencedProjects) { - CSearchScope scope = new CSearchScope(); - HashSet visitedProjects = new HashSet(2); - for (int i = 0, length = elements.length; i < length; i++) { - ICElement element = elements[i]; - if (element != null) { - try { - if (element instanceof ICProject) { - scope.add((ICProject)element, includeReferencedProjects, visitedProjects); - } else { - scope.add(element); - } - } catch (Exception e) { - // ignore - } - } - } - return scope; - } - - /** - * @param objects - * @return - */ - public static ICSearchScope createCFileSearchScope(IFile sourceFile, ArrayList elements) { - CSearchScope scope = new CSearchScope(); - - if (sourceFile != null){ - //Add the source file and project - scope.addFile(sourceFile.getFullPath(), sourceFile.getProject()); - IPath rootPath = CCorePlugin.getWorkspace().getRoot().getLocation(); - int segCount = CCorePlugin.getWorkspace().getRoot().getLocation().segmentCount(); - if (elements!=null){ - Iterator i = elements.iterator(); - while (i.hasNext()){ - IPath tempPath = new Path((String) i.next()); - if (rootPath.isPrefixOf(tempPath)){ - //path is in workspace - IFile tempFile = CCorePlugin.getWorkspace().getRoot().getFile(tempPath); - IPath finalPath = tempFile.getFullPath().removeFirstSegments(segCount); - tempFile = CCorePlugin.getWorkspace().getRoot().getFile(finalPath); - scope.addFile(tempFile.getFullPath(), tempFile.getProject()); - } - else{ - scope.addFile(tempPath,null); - } - - } - } - } - return scope; - } - - public static ICSearchPattern createSearchPattern( String stringPattern, SearchFor searchFor, LimitTo limitTo, boolean isCaseSensitive){ - int mode; - - if( stringPattern.indexOf( '*' ) != -1 || stringPattern.indexOf( '?' ) != -1 ){ - mode = ICSearchConstants.PATTERN_MATCH; - } else { - mode = ICSearchConstants.EXACT_MATCH; - } - - return CSearchPattern.createPattern( stringPattern, searchFor, limitTo, mode, isCaseSensitive ); - } - - - public void search(IWorkspace workspace, ICSearchPattern pattern, ICSearchScope scope, ICSearchResultCollector collector, boolean excludeLocalDeclarations) throws InterruptedException { - - MatchLocator matchLocator = new MatchLocator(pattern,collector,scope); - matchLocator.setShouldExcludeLocalDeclarations(excludeLocalDeclarations); - - search(workspace, pattern, scope, collector, excludeLocalDeclarations, matchLocator); - } - /** - * @param _workspace - * @param pattern - * @param _scope - * @param _collector - */ - public void search(IWorkspace workspace, ICSearchPattern pattern, ICSearchScope scope, ICSearchResultCollector collector, boolean excludeLocalDeclarations, IMatchLocator matchLocator) throws InterruptedException { - if( VERBOSE ) { - System.out.println("Searching for " + pattern + " in " + scope); //$NON-NLS-1$//$NON-NLS-2$ - } - - if( pattern == null ){ - return; - } - - /* search is starting */ - collector.aboutToStart(); - - //initialize progress monitor - IProgressMonitor progressMonitor = collector.getProgressMonitor(); - if( progressMonitor != null ){ - progressMonitor.beginTask( Util.bind("engine.searching"), 100 ); //$NON-NLS-1$ - } - - /* index search */ - PathCollector pathCollector = new PathCollector(); - - CModelManager modelManager = CModelManager.getDefault(); - IndexManager indexManager = modelManager.getIndexManager(); - - SubProgressMonitor subMonitor = (progressMonitor == null ) ? null : new SubProgressMonitor( progressMonitor, 5 ); - - indexManager.performConcurrentJob( - new PatternSearchJob( - (CSearchPattern) pattern, - scope, - pathCollector, - indexManager - ), - waitingPolicy, - subMonitor, - null ); - - subMonitor = (progressMonitor == null ) ? null : new SubProgressMonitor( progressMonitor, 95 ); - - matchLocator.setProgressMonitor(subMonitor); - - if( progressMonitor != null && progressMonitor.isCanceled() ) - throw new InterruptedException(); - - //indexer might have had a # files left to index subtask, replace that with searching again - if( progressMonitor != null ) - progressMonitor.subTask( Util.bind( "engine.searching" ) ); //$NON-NLS-1$ - - //String[] indexerPaths = pathCollector.getPaths(); - //BasicSearchMatch[] matches = pathCollector.getMatches(); - //pathCollector = null; // release - - //TODO: BOG Put MatchLocator in for Working Copy - //matchLocator.locateMatches( indexerPaths, workspace, filterWorkingCopies(this.workingCopies, scope)); - Iterator i =pathCollector.getMatches(); - - while (i.hasNext()){ - try { - collector.acceptMatch((BasicSearchMatch) i.next() ); - } catch (CoreException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - collector.done(); - } - - /** - * @param copies - * @param scope - * @return - */ - private IWorkingCopy[] filterWorkingCopies(IWorkingCopy[] copies, ICSearchScope scope) { - - if (copies == null || - copies.length == 0) - return copies; - - int length = copies.length; - IWorkingCopy[] results= new IWorkingCopy[length]; - int index=0; - - try { - for (int i=0;iPreferences>Java>Code Generation>Code and Comments - */ -package org.eclipse.cdt.internal.core.search; - -import java.util.ArrayList; -import java.util.Iterator; - -import org.eclipse.cdt.core.search.ICSearchResultCollector; -import org.eclipse.cdt.core.search.IMatch; -import org.eclipse.core.resources.IWorkspaceRunnable; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IProgressMonitor; - -/** - * @author bgheorgh - * - * To change the template for this generated type comment go to - * Window>Preferences>Java>Code Generation>Code and Comments - */ -public class AcceptMatchOperation implements IWorkspaceRunnable { - - ICSearchResultCollector collector; - ArrayList matches; - /** - * @param collector - */ - public AcceptMatchOperation(ICSearchResultCollector collector, ArrayList matches) { - this.collector = collector; - this.matches = matches; - } - - /* (non-Javadoc) - * @see org.eclipse.core.resources.IWorkspaceRunnable#run(org.eclipse.core.runtime.IProgressMonitor) - */ - public void run(IProgressMonitor monitor) throws CoreException { - Iterator i = matches.iterator(); - while (i.hasNext()){ - IMatch match = (IMatch) i.next(); - collector.acceptMatch(match); - } - } - -} diff --git a/core/org.eclipse.cdt.core/search/org/eclipse/cdt/internal/core/search/CSearchScope.java b/core/org.eclipse.cdt.core/search/org/eclipse/cdt/internal/core/search/CSearchScope.java deleted file mode 100644 index fea32b038c3..00000000000 --- a/core/org.eclipse.cdt.core/search/org/eclipse/cdt/internal/core/search/CSearchScope.java +++ /dev/null @@ -1,276 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ - -package org.eclipse.cdt.internal.core.search; - -import java.util.ArrayList; -import java.util.HashSet; - -import org.eclipse.cdt.core.CProjectNature; -import org.eclipse.cdt.core.model.CModelException; -import org.eclipse.cdt.core.model.ICContainer; -import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.cdt.core.model.ICProject; -import org.eclipse.cdt.core.model.IIncludeReference; -import org.eclipse.cdt.core.model.IMember; -import org.eclipse.cdt.core.search.ICSearchScope; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IProjectDescription; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.Path; - -public class CSearchScope implements ICSearchScope { - - private ArrayList elements; - /* The paths of the resources in this search scope*/ - private IPath[] paths; - private boolean[] pathWithSubFolders; - private int pathsCount; - - private IPath[] enclosingProjects; - - public CSearchScope() { - super(); - this.initialize(); - } - - protected void initialize() { - this.paths = new IPath[1]; - this.pathWithSubFolders = new boolean[1]; - this.pathsCount = 0; - this.enclosingProjects = new IPath[0]; - } - - private void addEnclosingProject(IPath path) { - int length = this.enclosingProjects.length; - for (int i = 0; i < length; i++) { - if (this.enclosingProjects[i].equals(path)) return; - } - System.arraycopy( - this.enclosingProjects, - 0, - this.enclosingProjects = new IPath[length+1], - 0, - length); - this.enclosingProjects[length] = path; - } - - public void add(ICProject cProject, boolean includesPrereqProjects, HashSet visitedProjects) throws CModelException { - //Add the project to the scope - IProject project = cProject.getProject(); - if (!project.isAccessible() || !visitedProjects.add(project)) return; - this.addEnclosingProject(project.getFullPath()); - - this.add(project.getFullPath(),true); - - /*//Add the children of the project to the scope - ICElement[] projChildren = cProject.getChildren(); - for (int i=0; i< projChildren.length; i++){ - this.add(projChildren[i]); - }*/ - - //Add the include paths to the scope - IIncludeReference[] includeRefs = cProject.getIncludeReferences(); - for (int i=0; i 1 - && ((location = root.getFile(path).getLocation()) == null - || !new java.io.File(location.toOSString()).exists()) // and internal jar file does not exist - && !new java.io.File(path.toOSString()).exists()) { // and external jar file does not exist - continue; - } - if (projectFocus == null || canSeeFocus(projectFocus, this.isPolymorphicSearch, path)) { - if (requiredIndexKeys.indexOf(path) == -1) { - requiredIndexKeys.add(path); - } - } - } - this.indexKeys = new IPath[requiredIndexKeys.size()]; - requiredIndexKeys.toArray(this.indexKeys); - } - public IIndex[] getIndexes() { - if (this.indexKeys == null) { - this.initializeIndexKeys(); - } - // acquire the in-memory indexes on the fly - int length = this.indexKeys.length; - IIndex[] indexes = new IIndex[length]; - int count = 0; - for (int i = 0; i < length; i++){ - // may trigger some index recreation work - IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); - ICDTIndexer indexer = indexManager.getIndexerForProject( root.getProject(indexKeys[i].toOSString())); - - IIndex index = null; - - if (indexer != null) - index =indexer.getIndex(indexKeys[i], true /*reuse index file*/, false /*do not create if none*/); - - if (index != null) indexes[count++] = index; // only consider indexes which are ready yet - } - if (count != length) { - System.arraycopy(indexes, 0, indexes=new IIndex[count], 0, count); - } - return indexes; - } - /** - * Returns the project that corresponds to the given path. - * Returns null if the path doesn't correspond to a project. - */ - private static ICProject getCProject(IPath path, ICModel model) { - ICProject project = model.getCProject(path.lastSegment()); - if (project.exists()) { - return project; - } else { - return null; - } - } - public static ICElement getProject(ICElement element) { - while (!(element instanceof ICProject)) { - element = element.getParent(); - } - return element; - } -} diff --git a/core/org.eclipse.cdt.core/search/org/eclipse/cdt/internal/core/search/PathCollector.java b/core/org.eclipse.cdt.core/search/org/eclipse/cdt/internal/core/search/PathCollector.java deleted file mode 100644 index 3d945fe244d..00000000000 --- a/core/org.eclipse.cdt.core/search/org/eclipse/cdt/internal/core/search/PathCollector.java +++ /dev/null @@ -1,56 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.core.search; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.Iterator; - -import org.eclipse.cdt.core.search.BasicSearchMatch; - - /** - * Collects the resource paths reported by a client to this search requestor. - */ - public class PathCollector implements IIndexSearchRequestor { - - public ArrayList matches = new ArrayList(); - - /* a set of resource paths */ - public HashSet paths = new HashSet(5); - - public void acceptSearchMatch(BasicSearchMatch match) { - matches.add(match); - } - - public Iterator getMatches(){ - return matches.iterator(); - } - - public ArrayList getMatchesList(){ - return matches; - } - - public void acceptIncludeDeclaration(String resourcePath, char[] decodedSimpleName) { - this.paths.add(resourcePath); - } - /** - * Returns the paths that have been collected. - */ - public String[] getPaths() { - String[] result = new String[this.paths.size()]; - int i = 0; - for (Iterator iter = this.paths.iterator(); iter.hasNext();) { - result[i++] = (String)iter.next(); - } - return result; - } - -} diff --git a/core/org.eclipse.cdt.core/search/org/eclipse/cdt/internal/core/search/PatternSearchJob.java b/core/org.eclipse.cdt.core/search/org/eclipse/cdt/internal/core/search/PatternSearchJob.java deleted file mode 100644 index 43d877ef329..00000000000 --- a/core/org.eclipse.cdt.core/search/org/eclipse/cdt/internal/core/search/PatternSearchJob.java +++ /dev/null @@ -1,183 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -/* - * Created on Jun 13, 2003 - */ -package org.eclipse.cdt.internal.core.search; - -import java.io.IOException; - -import org.eclipse.cdt.core.index.ICDTIndexer; -import org.eclipse.cdt.core.index.IIndexStorage; -import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.cdt.core.search.ICSearchScope; -import org.eclipse.cdt.internal.core.index.IIndex; -import org.eclipse.cdt.internal.core.index.cindexstorage.CIndexStorage; -import org.eclipse.cdt.internal.core.index.cindexstorage.Index; -import org.eclipse.cdt.internal.core.search.indexing.IndexManager; -import org.eclipse.cdt.internal.core.search.indexing.ReadWriteMonitor; -import org.eclipse.cdt.internal.core.search.matching.CSearchPattern; -import org.eclipse.cdt.internal.core.search.processing.IIndexJob; -import org.eclipse.cdt.internal.core.search.processing.JobManager; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.OperationCanceledException; - - -public class PatternSearchJob implements IIndexJob { - - - protected CSearchPattern pattern; - protected ICSearchScope scope; - protected ICElement focus; - protected IIndexSearchRequestor requestor; - protected IndexManager indexManager; - protected int detailLevel; - protected IndexSelector indexSelector; - protected boolean isPolymorphicSearch; - protected long executionTime = 0; - - public PatternSearchJob( - CSearchPattern pattern, - ICSearchScope scope, - IIndexSearchRequestor requestor, - IndexManager indexManager) { - - this( - pattern, - scope, - null, - false, - requestor, - indexManager); - } - public PatternSearchJob( - CSearchPattern pattern, - ICSearchScope scope, - ICElement focus, - boolean isPolymorphicSearch, - IIndexSearchRequestor requestor, - IndexManager indexManager) { - - this.pattern = pattern; - this.scope = scope; - this.focus = focus; - this.isPolymorphicSearch = isPolymorphicSearch; - this.requestor = requestor; - this.indexManager = indexManager; - } - public boolean belongsTo(String jobFamily) { - return true; - } - public void cancel() { - } - public boolean execute(IProgressMonitor progressMonitor) { - - if (progressMonitor != null && progressMonitor.isCanceled()) - throw new OperationCanceledException(); - boolean isComplete = COMPLETE; - executionTime = 0; - if (this.indexSelector == null) { - this.indexSelector = - new IndexSelector(this.scope, this.focus, this.isPolymorphicSearch, this.indexManager); - } - IIndex[] searchIndexes = this.indexSelector.getIndexes(); - try { - int max = searchIndexes.length; - if (progressMonitor != null) { - progressMonitor.beginTask("", max); //$NON-NLS-1$ - } - for (int i = 0; i < max; i++) { - isComplete &= search(searchIndexes[i], progressMonitor); - if (progressMonitor != null) { - if (progressMonitor.isCanceled()) { - throw new OperationCanceledException(); - } else { - progressMonitor.worked(1); - } - } - } - if (JobManager.VERBOSE) { - JobManager.verbose("-> execution time: " + executionTime + "ms - " + this);//$NON-NLS-1$//$NON-NLS-2$ - } - return isComplete; - } finally { - if (progressMonitor != null) { - progressMonitor.done(); - } - } - } - public boolean isReadyToRun() { - if (this.indexSelector == null) { // only check once. As long as this job is used, it will keep the same index picture - this.indexSelector = new IndexSelector(this.scope, this.focus, this.isPolymorphicSearch, this.indexManager); - this.indexSelector.getIndexes(); // will only cache answer if all indexes were available originally - } - return true; - } - public boolean search(IIndex index, IProgressMonitor progressMonitor) { - - if (progressMonitor != null && progressMonitor.isCanceled()) - throw new OperationCanceledException(); - -// IIndex inMemIndex = indexManager.peekAtIndex(new Path(((Index)index).toString.substring("Index for ".length()).replace('\\','/'))); -// if (inMemIndex != index) { -// System.out.println("SANITY CHECK: search job using obsolete index: ["+index+ "] instead of: ["+inMemIndex+"]"); -// } - - if (index == null) - return COMPLETE; - - if (!(index instanceof Index)) - return FAILED; - - ICDTIndexer indexer =((Index) index).getIndexer(); - - IIndexStorage storage = indexer.getIndexStorage(); - if (!(storage instanceof CIndexStorage)) - return FAILED; - - CIndexStorage cStorage = (CIndexStorage) storage; - ReadWriteMonitor monitor = cStorage.getMonitorForIndex(); - if (monitor == null) - return COMPLETE; // index got deleted since acquired - try { - monitor.enterRead(); // ask permission to read - - /* if index has changed, commit these before querying */ - if (index.hasChanged()) { - try { - monitor.exitRead(); // free read lock - monitor.enterWrite(); // ask permission to write - cStorage.saveIndex(index); - } catch (IOException e) { - return FAILED; - } finally { - monitor.exitWriteEnterRead(); // finished writing and reacquire read permission - } - } - long start = System.currentTimeMillis(); - pattern.findIndexMatches( - index, - requestor, - detailLevel, - progressMonitor, - this.scope); - executionTime += System.currentTimeMillis() - start; - return COMPLETE; - } catch (IOException e) { - return FAILED; - } finally { - monitor.exitRead(); // finished reading - } - } - public String toString() { - return "searching " + pattern.toString(); //$NON-NLS-1$ - } -} diff --git a/core/org.eclipse.cdt.core/search/org/eclipse/cdt/internal/core/search/matching/CSearchPattern.java b/core/org.eclipse.cdt.core/search/org/eclipse/cdt/internal/core/search/matching/CSearchPattern.java deleted file mode 100644 index d8cb6ed4cbb..00000000000 --- a/core/org.eclipse.cdt.core/search/org/eclipse/cdt/internal/core/search/matching/CSearchPattern.java +++ /dev/null @@ -1,780 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -/* - * Created on Jun 13, 2003 - */ -package org.eclipse.cdt.internal.core.search.matching; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import org.eclipse.cdt.core.dom.ast.ASTSignatureUtil; -import org.eclipse.cdt.core.dom.ast.IASTDeclaration; -import org.eclipse.cdt.core.dom.ast.IASTDeclarator; -import org.eclipse.cdt.core.dom.ast.IASTSimpleDeclaration; -import org.eclipse.cdt.core.dom.ast.IASTTranslationUnit; -import org.eclipse.cdt.core.parser.CodeReader; -import org.eclipse.cdt.core.parser.EndOfFileException; -import org.eclipse.cdt.core.parser.IParserLogService; -import org.eclipse.cdt.core.parser.IProblem; -import org.eclipse.cdt.core.parser.IScanner; -import org.eclipse.cdt.core.parser.ISourceElementRequestor; -import org.eclipse.cdt.core.parser.IToken; -import org.eclipse.cdt.core.parser.NullLogService; -import org.eclipse.cdt.core.parser.NullSourceElementRequestor; -import org.eclipse.cdt.core.parser.ParserFactory; -import org.eclipse.cdt.core.parser.ParserFactoryError; -import org.eclipse.cdt.core.parser.ParserLanguage; -import org.eclipse.cdt.core.parser.ParserMode; -import org.eclipse.cdt.core.parser.ScannerInfo; -import org.eclipse.cdt.core.search.ICSearchConstants; -import org.eclipse.cdt.core.search.ICSearchPattern; -import org.eclipse.cdt.core.search.ICSearchScope; -import org.eclipse.cdt.core.search.IMatchLocatable; -import org.eclipse.cdt.core.search.LimitTo; -import org.eclipse.cdt.core.search.LineLocatable; -import org.eclipse.cdt.core.search.OffsetLocatable; -import org.eclipse.cdt.core.search.OrPattern; -import org.eclipse.cdt.core.search.SearchEngine; -import org.eclipse.cdt.core.search.SearchFor; -import org.eclipse.cdt.internal.core.CharOperation; -import org.eclipse.cdt.internal.core.dom.parser.ISourceCodeParser; -import org.eclipse.cdt.internal.core.dom.parser.c.ANSICParserExtensionConfiguration; -import org.eclipse.cdt.internal.core.dom.parser.c.GNUCSourceParser; -import org.eclipse.cdt.internal.core.dom.parser.c.ICParserExtensionConfiguration; -import org.eclipse.cdt.internal.core.dom.parser.cpp.ANSICPPParserExtensionConfiguration; -import org.eclipse.cdt.internal.core.dom.parser.cpp.GNUCPPSourceParser; -import org.eclipse.cdt.internal.core.dom.parser.cpp.ICPPParserExtensionConfiguration; -import org.eclipse.cdt.internal.core.index.IEntryResult; -import org.eclipse.cdt.internal.core.index.IIndex; -import org.eclipse.cdt.internal.core.index.cindexstorage.io.BlocksIndexInput; -import org.eclipse.cdt.internal.core.index.cindexstorage.io.IndexInput; -import org.eclipse.cdt.internal.core.parser.ParserException; -import org.eclipse.cdt.internal.core.parser.scanner2.DOMScanner; -import org.eclipse.cdt.internal.core.parser.scanner2.FileCodeReaderFactory; -import org.eclipse.cdt.internal.core.parser.scanner2.GCCScannerExtensionConfiguration; -import org.eclipse.cdt.internal.core.parser.scanner2.GPPScannerExtensionConfiguration; -import org.eclipse.cdt.internal.core.parser.scanner2.IScannerExtensionConfiguration; -import org.eclipse.cdt.internal.core.search.IIndexSearchRequestor; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.OperationCanceledException; - -/** - * @author aniefer - */ -public abstract class CSearchPattern implements ICSearchConstants, ICSearchPattern { - - public static final int IMPOSSIBLE_MATCH = 0; - public static final int POSSIBLE_MATCH = 1; - public static final int ACCURATE_MATCH = 2; - public static final int INACCURATE_MATCH = 3; - - public static SearchFor[] fSearchForValues = { CLASS_STRUCT, FUNCTION, VAR, UNION, METHOD, FIELD, ENUM, ENUMTOR, NAMESPACE, TYPEDEF, MACRO}; - - protected static class Requestor extends NullSourceElementRequestor - { - public int badCharacterOffset = -1; - public Requestor( ParserMode mode ) - { - super( mode ); - } - - public boolean acceptProblem( IProblem problem ) - { - if( problem.getID() == IProblem.SCANNER_BAD_CHARACTER ){ - badCharacterOffset = problem.getSourceStart(); - return false; - } - return super.acceptProblem( problem ); - } - } - - /** - * @param matchMode - * @param caseSensitive - */ - public CSearchPattern(int matchMode, boolean caseSensitive, LimitTo limitTo ) { - _matchMode = matchMode; - _caseSensitive = caseSensitive; - _limitTo = limitTo; - } - - public CSearchPattern() { - super(); - } - - public LimitTo getLimitTo(){ - return _limitTo; - } - - public boolean canAccept(LimitTo limit) { - return ( limit == getLimitTo() ); - } - - public static CSearchPattern createPattern( String patternString, SearchFor searchFor, LimitTo limitTo, int matchMode, boolean caseSensitive ){ - if( patternString == null || patternString.length() == 0 ){ - return null; - } - - CSearchPattern pattern = null; - if( searchFor == TYPE || searchFor == CLASS || searchFor == STRUCT || - searchFor == ENUM || searchFor == UNION || searchFor == CLASS_STRUCT || - searchFor == TYPEDEF ) - { - pattern = createClassPattern( patternString, searchFor, limitTo, matchMode, caseSensitive ); - } else if ( searchFor == DERIVED){ - pattern = createDerivedPattern(patternString, searchFor, limitTo, matchMode, caseSensitive ); - } else if ( searchFor == FRIEND){ - pattern = createFriendPattern(patternString, searchFor, limitTo, matchMode, caseSensitive ); - } - else if ( searchFor == METHOD || searchFor == FUNCTION ){ - pattern = createMethodPattern( patternString, searchFor, limitTo, matchMode, caseSensitive ); - } else if ( searchFor == FIELD || searchFor == VAR || searchFor == ENUMTOR){ - pattern = createFieldPattern( patternString, searchFor, limitTo, matchMode, caseSensitive ); - } else if ( searchFor == NAMESPACE ){ - pattern = createNamespacePattern( patternString, limitTo, matchMode, caseSensitive ); - } else if ( searchFor == MACRO ){ - pattern = createMacroPattern( patternString, limitTo, matchMode, caseSensitive ); - } else if ( searchFor == INCLUDE){ - pattern = createIncludePattern( patternString, limitTo, matchMode, caseSensitive); - } else if ( searchFor == UNKNOWN_SEARCH_FOR ) { - OrPattern orPattern = new OrPattern(); - for( int i=0; i 0) { - boolean removeFirst = true; - if (tokens[0].equals("class")) { //$NON-NLS-1$ - searchFor = CLASS; - } - else if (tokens[0].equals("struct")) { //$NON-NLS-1$ - searchFor = STRUCT; - } - else if (tokens[0].equals("union")) { //$NON-NLS-1$ - searchFor = UNION; - } - else if (tokens[0].equals("enum")) { //$NON-NLS-1$ - searchFor = ENUM; - } - else if (tokens[0].equals("typedef")) { //$NON-NLS-1$ - searchFor = TYPEDEF; - } - else { - removeFirst = false; - } - if (removeFirst) { - patternString = patternString.substring(tokens[0].length()).trim(); - } - } - char[][] names = scanForNames( patternString ); // return type as first element of the array - - char[] name = names[names.length - 1]; - char[][] qualifications = new char[names.length - 1][]; - System.arraycopy(names, 0, qualifications, 0, qualifications.length); - - return new ClassDeclarationPattern( name, qualifications, searchFor, limitTo, matchMode, caseSensitive); - } - - private static CSearchPattern createDerivedPattern(String patternString, SearchFor searchFor, LimitTo limitTo, int matchMode, boolean caseSensitive) { - searchFor = DERIVED; - - char[][] names = scanForNames( patternString ); - - char[] name = names[names.length - 1]; - char[][] qualifications = new char[names.length - 1][]; - System.arraycopy(names, 0, qualifications, 0, qualifications.length); - - return new DerivedTypesPattern( name, qualifications, searchFor, limitTo, matchMode, caseSensitive ); - } - - private static CSearchPattern createFriendPattern(String patternString, SearchFor searchFor, LimitTo limitTo, int matchMode, boolean caseSensitive) { - searchFor = FRIEND; - - char[][] names = scanForNames( patternString ); - - char[] name = names[names.length - 1]; - char[][] qualifications = new char[names.length - 1][]; - System.arraycopy(names, 0, qualifications, 0, qualifications.length); - - return new FriendPattern( name, qualifications, searchFor, limitTo, matchMode, caseSensitive ); - } - - /** - * @param nameString - * @return - */ - private static char[][] scanForNames(String nameString) { - final List nameList = new ArrayList(); - - if (nameString != null && nameString.length() > 0) { - - Requestor callback = new Requestor( ParserMode.COMPLETE_PARSE ); - IScanner scanner = createScanner(nameString, callback); - if (scanner != null) { - - String name = new String(""); //$NON-NLS-1$ - char[] pattern = nameString.toCharArray(); - int idx = 0; - - try { - IToken token = scanner.nextToken(); - IToken prev = null; - - boolean encounteredWild = false; - boolean lastTokenWasOperator = false; - - while( true ){ - switch( token.getType() ){ - case IToken.tCOLONCOLON : - nameList.add( name.toCharArray() ); - name = new String(""); //$NON-NLS-1$ - lastTokenWasOperator = false; - idx += token.getLength(); - while( idx < pattern.length && CharOperation.isWhitespace( pattern[idx] ) ){ idx++; } - break; - - case IToken.t_operator : - name += token.getImage(); - name += ' '; - lastTokenWasOperator = true; - idx += token.getLength(); - while( idx < pattern.length && CharOperation.isWhitespace( pattern[idx] ) ){ idx++; } - break; - - default: - if( token.getType() == IToken.tSTAR || - token.getType() == IToken.tQUESTION ) { - if( idx > 0 && idx < pattern.length && CharOperation.isWhitespace( pattern[ idx - 1 ] ) && !lastTokenWasOperator ) - name += ' '; - encounteredWild = true; - } - else if( !encounteredWild && !lastTokenWasOperator && name.length() > 0 && - prev.getType() != IToken.tIDENTIFIER && - prev.getType() != IToken.tLT && - prev.getType() != IToken.tCOMPL && - prev.getType() != IToken.tARROW && - prev.getType() != IToken.tLBRACKET && - token.getType() != IToken.tRBRACKET && - token.getType()!= IToken.tGT - ){ - name += ' '; - } else { - encounteredWild = false; - } - - name += token.getImage(); - - if( encounteredWild && idx < pattern.length - 1 && CharOperation.isWhitespace( pattern[ idx + 1 ] ) ) - { - name += ' '; - } - idx += token.getLength(); - while( idx < pattern.length && CharOperation.isWhitespace( pattern[idx] ) ){ idx++; } - - lastTokenWasOperator = false; - break; - } - prev = token; - - token = null; - while( token == null ){ - token = scanner.nextToken(); - if( callback.badCharacterOffset != -1 && token.getOffset() > callback.badCharacterOffset ){ - //TODO : This may not be \\, it could be another bad character - if( !encounteredWild && !lastTokenWasOperator && prev.getType() != IToken.tARROW ) name += " "; //$NON-NLS-1$ - name += "\\"; //$NON-NLS-1$ - idx++; - encounteredWild = true; - lastTokenWasOperator = false; - prev = null; - callback.badCharacterOffset = -1; - } - } - } - } catch (EndOfFileException e) { - nameList.add( name.toCharArray() ); - } - } - } - return (char[][]) nameList.toArray(new char [nameList.size()] []); - } - - - /** - * @param scanner - * @param object - * @return - */ - public static char[][] scanForParameters( String paramString ) { - char[][] rv = new char[0][]; - - if( paramString == null || paramString.equals("") ) //$NON-NLS-1$ - return rv; - - String functionString = "void f " + paramString + ";"; //$NON-NLS-1$ //$NON-NLS-2$ - - try { - IASTTranslationUnit tu = parse(functionString); - if (tu != null) { - IASTDeclaration[] decls = tu.getDeclarations(); - for (int i = 0; i < decls.length; i++) { - IASTDeclaration decl = decls[i]; - if (decl instanceof IASTSimpleDeclaration) { - IASTSimpleDeclaration simpleDecl = (IASTSimpleDeclaration) decl; - IASTDeclarator[] declarators = simpleDecl.getDeclarators(); - for (int j = 0; j < declarators.length; j++) { - String[] parameters = ASTSignatureUtil.getParameterSignatureArray(declarators[j]); - rv = new char[parameters.length][]; - for (int k = 0; k < parameters.length; k++) { - rv[k] = parameters[k].toCharArray(); - } - // take first set of parameters only - break; - } - } - // take first declaration only - break; - } - } - } - catch (ParserException e) { - } - - return rv; - } - - protected boolean matchesName( char[] pattern, char[] name ){ - if( pattern == null ){ - return true; //treat null as "*" - } - - if( name != null ){ - switch( _matchMode ){ - case EXACT_MATCH: - return CharOperation.equals( pattern, name, _caseSensitive ); - case PREFIX_MATCH: - return CharOperation.prefixEquals( pattern, name, _caseSensitive ); - case PATTERN_MATCH: - if( !_caseSensitive ){ - pattern = CharOperation.toLowerCase( pattern ); - } - - return CharOperation.match( pattern, name, _caseSensitive ); - } - } - return false; - } - protected boolean matchQualifications( char[][] qualifications, char[][] candidate ){ - return matchQualifications( qualifications, candidate, false ); - } - protected boolean matchQualifications( char[][] qualifications, char[][] candidate, boolean skipLastName ){ - - int qualLength = qualifications != null ? qualifications.length : 0; - int candidateLength = candidate != null ? candidate.length - ( skipLastName ? 1 : 0 ) : 0; - - if( qualLength == 0 ){ - return true; - } - - int root = ( qualifications[0].length == 0 ) ? 1 : 0; - - if( (root == 1 && candidateLength != qualLength - 1 ) || - (root == 0 && candidateLength < qualLength ) ) - { - return false; - } - - for( int i = 1; i <= qualLength - root; i++ ){ - if( !matchesName( qualifications[ qualLength - i ], candidate[ candidateLength - i ] ) ){ - return false; - } - } - - return true; - } - - /** - * Query a given index for matching entries. - */ - public void findIndexMatches(IIndex index, IIndexSearchRequestor requestor, int detailLevel, IProgressMonitor progressMonitor, ICSearchScope scope) throws IOException { - - if (progressMonitor != null && progressMonitor.isCanceled()) throw new OperationCanceledException(); - - IndexInput input = new BlocksIndexInput(index.getIndexFile()); - try { - input.open(); - findIndexMatches(input, requestor, detailLevel, progressMonitor,scope); - } finally { - input.close(); - } - } - /** - * Query a given index for matching entries. - */ - public void findIndexMatches(IndexInput input, IIndexSearchRequestor requestor, int detailLevel, IProgressMonitor progressMonitor, ICSearchScope scope) throws IOException { - - if (progressMonitor != null && progressMonitor.isCanceled()) throw new OperationCanceledException(); - - /* narrow down a set of entries using prefix criteria */ - char [] prefix = indexEntryPrefix(); - if( prefix == null ) return; - - IEntryResult[] entries = input.queryEntriesPrefixedBy( prefix ); - if (entries == null) return; - - /* only select entries which actually match the entire search pattern */ - for (int i = 0, max = entries.length; i < max; i++){ - - if (progressMonitor != null && progressMonitor.isCanceled()) throw new OperationCanceledException(); - - /* retrieve and decode entry */ - IEntryResult entry = entries[i]; - resetIndexInfo(); - decodeIndexEntry(entry); - - if (matchIndexEntry()){ - feedIndexRequestor(requestor, detailLevel, entry.getFileReferences(), entry.getOffsets(), entry.getOffsetLengths(), input, scope); - } - } - } - - /** - * Decodes the passed in offset and returns an IMatchLocatable object of the appropriate type - * (either IOffsetLocatable or ILineLocatable) - */ - public static IMatchLocatable getMatchLocatable(int offset, int offsetLength){ - // pull off the first digit for the offset type - int encodedVal = offset; - int offsetType = encodedVal; - int m = 1; - while (offsetType >= 10) { - offsetType = offsetType / 10; - m *= 10; - } - - int startOffset = encodedVal - offsetType * m; - int endOffset = startOffset + offsetLength; - - IMatchLocatable locatable = null; - - if (offsetType==IIndex.LINE){ - locatable = new LineLocatable(startOffset,0); - }else if (offsetType==IIndex.OFFSET){ - locatable = new OffsetLocatable(startOffset, endOffset); - } - - return locatable; - } - - /** - * Feed the requestor according to the current search pattern - */ - public abstract void feedIndexRequestor(IIndexSearchRequestor requestor, int detailLevel, int[] references, int[][] offsets, int[][] offsetLengths, IndexInput input, ICSearchScope scope) throws IOException ; - - /** - * Called to reset any variables used in the decoding of index entries, - * this ensures that the matchIndexEntry is not polluted by index info - * from previous entries. - */ - protected abstract void resetIndexInfo(); - - /** - * Decodes the index entry - */ - protected abstract void decodeIndexEntry(IEntryResult entryResult); - /** - * Answers the suitable prefix that should be used in order - * to query indexes for the corresponding item. - * The more accurate the prefix and the less false hits will have - * to be eliminated later on. - */ - public abstract char[] indexEntryPrefix(); - /** - * Checks whether an entry matches the current search pattern - */ - protected abstract boolean matchIndexEntry(); - - protected int _matchMode; - protected boolean _caseSensitive; - protected LimitTo _limitTo; - - - protected static IASTTranslationUnit parse( String code ) throws ParserException { - return parse(code, ParserLanguage.CPP); - } - - /** - * @param string - * @param c - * @return - * @throws ParserException - */ - protected static IASTTranslationUnit parse( String code, ParserLanguage lang ) throws ParserException { - IParserLogService NULL_LOG = new NullLogService(); - CodeReader codeReader = new CodeReader(code .toCharArray()); - ScannerInfo scannerInfo = new ScannerInfo(); - IScannerExtensionConfiguration configuration = null; - if( lang == ParserLanguage.C ) - configuration = new GCCScannerExtensionConfiguration(); - else - configuration = new GPPScannerExtensionConfiguration(); - IScanner scanner = new DOMScanner( codeReader, scannerInfo, ParserMode.COMPLETE_PARSE, lang, NULL_LOG, configuration, FileCodeReaderFactory.getInstance() ); - - ISourceCodeParser parser2 = null; - if( lang == ParserLanguage.CPP ) - { - ICPPParserExtensionConfiguration config = new ANSICPPParserExtensionConfiguration(); - parser2 = new GNUCPPSourceParser(scanner, ParserMode.COMPLETE_PARSE, NULL_LOG, config ); - } - else { - ICParserExtensionConfiguration config = new ANSICParserExtensionConfiguration(); - parser2 = new GNUCSourceParser( scanner, ParserMode.COMPLETE_PARSE, NULL_LOG, config ); - } - - IASTTranslationUnit tu = parser2.parse(); - - if( parser2.encounteredError()) - throw new ParserException( "FAILURE"); //$NON-NLS-1$ - - return tu; - } - - protected static IScanner createScanner( String code, ISourceElementRequestor callback ) { - return createScanner(code, callback, ParserLanguage.CPP); - } - - /** - * @param code - * @param callback - * @param lang - * @return - */ - protected static IScanner createScanner( String code, ISourceElementRequestor callback, ParserLanguage lang ) { - IScanner scanner = null; - try { - scanner = ParserFactory.createScanner( - new CodeReader(code.toCharArray()), - new ScannerInfo(), - ParserMode.QUICK_PARSE, - lang, callback, nullLog, null); - } - catch (ParserFactoryError e) { - } - return scanner; - } - -} diff --git a/core/org.eclipse.cdt.core/search/org/eclipse/cdt/internal/core/search/matching/ClassDeclarationPattern.java b/core/org.eclipse.cdt.core/search/org/eclipse/cdt/internal/core/search/matching/ClassDeclarationPattern.java deleted file mode 100644 index 86196f48986..00000000000 --- a/core/org.eclipse.cdt.core/search/org/eclipse/cdt/internal/core/search/matching/ClassDeclarationPattern.java +++ /dev/null @@ -1,282 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -/* - * Created on Jun 13, 2003 - */ -package org.eclipse.cdt.internal.core.search.matching; - -import java.io.IOException; - -import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.cdt.core.parser.ISourceElementCallbackDelegate; -import org.eclipse.cdt.core.parser.ast.ASTClassKind; -import org.eclipse.cdt.core.parser.ast.IASTClassSpecifier; -import org.eclipse.cdt.core.parser.ast.IASTElaboratedTypeSpecifier; -import org.eclipse.cdt.core.parser.ast.IASTEnumerationSpecifier; -import org.eclipse.cdt.core.parser.ast.IASTOffsetableNamedElement; -import org.eclipse.cdt.core.parser.ast.IASTQualifiedNameElement; -import org.eclipse.cdt.core.parser.ast.IASTTypedefDeclaration; -import org.eclipse.cdt.core.search.BasicSearchMatch; -import org.eclipse.cdt.core.search.ICSearchScope; -import org.eclipse.cdt.core.search.LimitTo; -import org.eclipse.cdt.core.search.SearchFor; -import org.eclipse.cdt.internal.core.CharOperation; -import org.eclipse.cdt.internal.core.index.IEntryResult; -import org.eclipse.cdt.internal.core.index.IIndex; -import org.eclipse.cdt.internal.core.index.cindexstorage.Index; -import org.eclipse.cdt.internal.core.index.cindexstorage.IndexedFileEntry; -import org.eclipse.cdt.internal.core.index.cindexstorage.io.IndexInput; -import org.eclipse.cdt.internal.core.search.IIndexSearchRequestor; -import org.eclipse.cdt.utils.PathUtil; -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.ResourcesPlugin; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.Path; - - -/** - * @author aniefer - */ - -public class ClassDeclarationPattern extends CSearchPattern { - -// public ClassDeclarationPattern( int matchMode, boolean caseSensitive ){ -// super( matchMode, caseSensitive, DECLARATIONS ); -// } - - public ClassDeclarationPattern( char[] name, char[][] containers, SearchFor searchFor, LimitTo limit, int mode, boolean caseSensitive ){ - super( mode, caseSensitive, limit ); - - simpleName = caseSensitive ? name : CharOperation.toLowerCase( name ); - if( caseSensitive || containers == null ){ - qualifications = containers; - } else { - int len = containers.length; - this.qualifications = new char[ len ][]; - for( int i = 0; i < len; i++ ){ - this.qualifications[i] = CharOperation.toLowerCase( containers[i] ); - } - } - - this.searchFor = searchFor; - - if( searchFor == CLASS ){ - classKind = ASTClassKind.CLASS; - } else if( searchFor == STRUCT ) { - classKind = ASTClassKind.STRUCT; - } else if ( searchFor == ENUM ) { - classKind = ASTClassKind.ENUM; - } else if ( searchFor == UNION ) { - classKind = ASTClassKind.UNION; - } else { - classKind = null; - } - - } - - public int matchLevel( ISourceElementCallbackDelegate node, LimitTo limit ){ - if ( !( node instanceof IASTClassSpecifier ) && - !( node instanceof IASTElaboratedTypeSpecifier ) && - !( node instanceof IASTTypedefDeclaration ) && - !( node instanceof IASTEnumerationSpecifier) ) - { - return IMPOSSIBLE_MATCH; - } else if( searchFor != TYPE && ((searchFor == TYPEDEF) ^ (node instanceof IASTTypedefDeclaration)) ) { - return IMPOSSIBLE_MATCH; - } - - if( ! canAccept( limit ) ) - return IMPOSSIBLE_MATCH; - - char[] nodeName = null; - if (node instanceof IASTElaboratedTypeSpecifier) - { - nodeName = ((IASTElaboratedTypeSpecifier)node).getNameCharArray(); - } - else if( node instanceof IASTOffsetableNamedElement ) - { - nodeName = ((IASTOffsetableNamedElement)node).getNameCharArray(); - } else { - return IMPOSSIBLE_MATCH; - } - - //check name, if simpleName == null, its treated the same as "*" - if( simpleName != null && !matchesName( simpleName, nodeName ) ){ - return IMPOSSIBLE_MATCH; - } - - if( node instanceof IASTQualifiedNameElement ){ - char [][] qualName = ((IASTQualifiedNameElement) node).getFullyQualifiedNameCharArrays(); - //check containing scopes - if( !matchQualifications( qualifications, qualName, true ) ){ - return IMPOSSIBLE_MATCH; - } - } - - //check type - if( classKind != null ){ - if( node instanceof IASTClassSpecifier ){ - IASTClassSpecifier clsSpec = (IASTClassSpecifier) node; - return ( classKind == clsSpec.getClassKind() ) ? ACCURATE_MATCH : IMPOSSIBLE_MATCH; - } else if (node instanceof IASTEnumerationSpecifier){ - return ( classKind == ASTClassKind.ENUM ) ? ACCURATE_MATCH : IMPOSSIBLE_MATCH; - } else if (node instanceof IASTElaboratedTypeSpecifier ){ - IASTElaboratedTypeSpecifier elabTypeSpec = (IASTElaboratedTypeSpecifier) node; - return ( classKind == elabTypeSpec.getClassKind() ) ? ACCURATE_MATCH : IMPOSSIBLE_MATCH; - } - } - - return ACCURATE_MATCH; - } - - public char [] getName() { - return simpleName; - } - public char[] [] getContainingTypes () { - return qualifications; - } - public ASTClassKind getKind(){ - return classKind; - } - - protected char[] simpleName; - protected char[][] qualifications; - protected ASTClassKind classKind; - protected SearchFor searchFor; - - protected char[] decodedSimpleName; - private char[][] decodedContainingTypes; - protected int decodedType; - - public void feedIndexRequestor(IIndexSearchRequestor requestor, int detailLevel, int[] fileRefs, int[][] offsets, int[][] offsetLengths,IndexInput input, ICSearchScope scope) throws IOException { - boolean isClass = decodedType == IIndex.TYPE_CLASS; - - for (int i = 0, max = fileRefs.length; i < max; i++) { - IndexedFileEntry file = input.getIndexedFile(fileRefs[i]); - String path; - if (file != null && scope.encloses(path =file.getPath())) { - //For each file, create a new search match for each offset occurrence - for (int j=0; jPreferences>Java>Code Generation>Code and Comments - */ -public class FieldDeclarationPattern extends CSearchPattern { - - /** - * @param name - * @param cs - * @param matchMode - * @param limitTo - * @param caseSensitive - */ - public FieldDeclarationPattern(char[] name, char[][] qual, int matchMode, SearchFor sfor, LimitTo limitTo, boolean caseSensitive) { - super( matchMode, caseSensitive, limitTo ); - qualifications = qual; - searchFor = sfor; - simpleName = name; - } - - - public int matchLevel(ISourceElementCallbackDelegate node, LimitTo limit ) { - if( node instanceof IASTField ){ - if( searchFor != FIELD || !canAccept( limit ) ) - return IMPOSSIBLE_MATCH; - } else if ( node instanceof IASTVariable ){ - if( searchFor != VAR || !canAccept( limit ) ) - return IMPOSSIBLE_MATCH; - } else if ( node instanceof IASTEnumerator ){ - if( searchFor != ENUMTOR || !canAccept( limit ) ) - return IMPOSSIBLE_MATCH; - } else if( node instanceof IASTParameterDeclaration ){ - if( searchFor != VAR || !canAccept( limit ) ) - return IMPOSSIBLE_MATCH; - } else if( node instanceof IASTTemplateParameter ){ - if( searchFor != VAR || !canAccept( limit ) ) - return IMPOSSIBLE_MATCH; - } else return IMPOSSIBLE_MATCH; - - - char[] nodeName = ((IASTOffsetableNamedElement)node).getNameCharArray(); - - //check name, if simpleName == null, its treated the same as "*" - if( simpleName != null && !matchesName( simpleName, nodeName ) ){ - return IMPOSSIBLE_MATCH; - } - - //check containing scopes - //create char[][] out of full name, - char [][] qualName = null; - if( node instanceof IASTEnumerator ){ - //Enumerators don't derive from IASTQualifiedElement, so make the fullName - //from the enumerations name. - // 7.2 - 10 : each enumerator declared by an enum-specifier is declared in the - //scope that immediately contains the enum-specifier. - IASTEnumerationSpecifier enumeration = ((IASTEnumerator)node).getOwnerEnumerationSpecifier(); - qualName = enumeration.getFullyQualifiedNameCharArrays(); - } else if( node instanceof IASTQualifiedNameElement ){ - qualName = ((IASTQualifiedNameElement) node).getFullyQualifiedNameCharArrays(); - } - - if( qualName != null ){ - //check containing scopes - if( !matchQualifications( qualifications, qualName, true ) ){ - return IMPOSSIBLE_MATCH; - } - } - - return ACCURATE_MATCH; - } - - public char[] indexEntryPrefix() { - if( searchFor == FIELD ){ - return Index.bestFieldPrefix( _limitTo, simpleName, qualifications, _matchMode, _caseSensitive ); - } else if( searchFor == VAR ) { - return Index.bestVariablePrefix( - _limitTo, - simpleName, qualifications, - _matchMode, _caseSensitive - ); - } else if (searchFor == ENUMTOR) { - return Index.bestEnumeratorPrefix(_limitTo, simpleName, qualifications, _matchMode, _caseSensitive ); - } - return null; - } - - protected void resetIndexInfo(){ - decodedSimpleName = null; - decodedQualifications = null; - } - - protected void decodeIndexEntry(IEntryResult entryResult) { - this.decodedSimpleName = entryResult.extractSimpleName().toCharArray(); - String []missmatch = entryResult.getEnclosingNames(); - if(missmatch != null) { - this.decodedQualifications = new char[missmatch.length][]; - for (int i = 0; i < missmatch.length; i++) - this.decodedQualifications[i] = missmatch[i].toCharArray(); - } - } - - /* (non-Javadoc) - * @see org.eclipse.cdt.internal.core.search.matching.CSearchPattern#feedIndexRequestor(org.eclipse.cdt.internal.core.search.IIndexSearchRequestor, int, int[], org.eclipse.cdt.internal.core.index.impl.IndexInput, org.eclipse.cdt.core.search.ICSearchScope) - */ - public void feedIndexRequestor(IIndexSearchRequestor requestor, int detailLevel, int[] fileRefs, int[][] offsets, int[][] offsetLengths, IndexInput input, ICSearchScope scope) throws IOException { - - for (int i = 0, max = fileRefs.length; i < max; i++) { - IndexedFileEntry file = input.getIndexedFile(fileRefs[i]); - String path = null; - if (file != null && scope.encloses(path =file.getPath())) { - for (int j=0; jPreferences>Java>Code Generation>Code and Comments - */ -public class MacroDeclarationPattern extends CSearchPattern { - - /** - * @param name - * @param matchMode - * @param limitTo - * @param caseSensitive - */ - public MacroDeclarationPattern(char[] name, int matchMode, LimitTo limitTo, boolean caseSensitive) { - super( matchMode, caseSensitive, limitTo ); - - simpleName = name; - } - - /* (non-Javadoc) - * @see org.eclipse.cdt.core.search.ICSearchPattern#matchLevel(org.eclipse.cdt.core.parser.ast.IASTOffsetableElement) - */ - public int matchLevel(ISourceElementCallbackDelegate node, LimitTo limit ) { - if( !(node instanceof IASTMacro) || !canAccept( limit ) ){ - return IMPOSSIBLE_MATCH; - } - - char[] nodeName = ((IASTOffsetableNamedElement)node).getNameCharArray(); - - //check name, if simpleName == null, its treated the same as "*" - if( simpleName != null && !matchesName( simpleName, nodeName ) ){ - return IMPOSSIBLE_MATCH; - } - - return ACCURATE_MATCH; - } - - /* (non-Javadoc) - * @see org.eclipse.cdt.internal.core.search.matching.CSearchPattern#feedIndexRequestor(org.eclipse.cdt.internal.core.search.IIndexSearchRequestor, int, int[], org.eclipse.cdt.internal.core.index.impl.IndexInput, org.eclipse.cdt.core.search.ICSearchScope) - */ - public void feedIndexRequestor(IIndexSearchRequestor requestor, int detailLevel, int[] fileRefs, int[][] offsets, int[][] offsetLengths, IndexInput input, ICSearchScope scope) throws IOException { - - for (int i = 0, max = fileRefs.length; i < max; i++) { - IndexedFileEntry file = input.getIndexedFile(fileRefs[i]); - String path=null; - if (file != null && scope.encloses(path =file.getPath())) { - for (int j=0; jPreferences>Java>Code Generation>Code and Comments - */ -public class MatchLocator implements IMatchLocator, ISourceElementRequestor{ - - - ArrayList matchStorage; - - public static boolean VERBOSE = false; - /** - * - */ - public MatchLocator( ICSearchPattern pattern, ICSearchResultCollector collector, ICSearchScope scope) { - super(); - searchPattern = pattern; - resultCollector = collector; - searchScope = scope; - } - - public boolean acceptProblem(IProblem problem) { return IndexProblemHandler.ruleOnProblem(problem, ParserMode.COMPLETE_PARSE ); } - public void acceptUsingDirective(IASTUsingDirective usageDirective) { } - public void acceptUsingDeclaration(IASTUsingDeclaration usageDeclaration) { } - public void acceptASMDefinition(IASTASMDefinition asmDefinition) { } - public void acceptAbstractTypeSpecDeclaration(IASTAbstractTypeSpecifierDeclaration abstractDeclaration) {} - - public void enterTemplateDeclaration(IASTTemplateDeclaration declaration) { } - public void enterTemplateSpecialization(IASTTemplateSpecialization specialization) { } - public void enterTemplateInstantiation(IASTTemplateInstantiation instantiation) { } - - public void exitTemplateDeclaration(IASTTemplateDeclaration declaration) {} - public void exitTemplateSpecialization(IASTTemplateSpecialization specialization) { } - public void exitTemplateExplicitInstantiation(IASTTemplateInstantiation instantiation) { } - - public void enterCodeBlock(IASTCodeScope scope) { } - public void exitCodeBlock(IASTCodeScope scope) { } - - public void enterLinkageSpecification(IASTLinkageSpecification linkageSpec){ - pushScope( linkageSpec ); - } - - public void exitLinkageSpecification(IASTLinkageSpecification linkageSpec){ - popScope(); - } - - /* (non-Javadoc) - * @see org.eclipse.cdt.core.parser.ISourceElementRequestor#acceptParameterReference(org.eclipse.cdt.internal.core.parser.ast.complete.ASTParameterReference) - */ - public void acceptParameterReference(IASTParameterReference reference) - { - check( REFERENCES, reference ); - } - - - public void acceptTemplateParameterReference(IASTTemplateParameterReference reference) - { - check( REFERENCES, reference ); - } - - public void acceptTypedefDeclaration(IASTTypedefDeclaration typedef){ - lastDeclaration = typedef; - check( DECLARATIONS, typedef ); - } - - public void acceptTypedefReference( IASTTypedefReference reference ){ - check( REFERENCES, reference ); - } - - public void acceptEnumeratorReference(IASTEnumeratorReference reference){ - check( REFERENCES, reference ); - } - - public void acceptMacro(IASTMacro macro){ - check( DECLARATIONS, macro ); - } - - public void acceptVariable(IASTVariable variable){ - lastDeclaration = variable; - - check( DECLARATIONS, variable ); - //A declaration is a definition unless...: - //it contains the extern specifier or a linkage-spec and no initializer - if( variable.getInitializerClause() != null || - ( !variable.isExtern() && !(currentScope instanceof IASTLinkageSpecification) ) ){ - check( DEFINITIONS, variable ); - } - } - - public void acceptField(IASTField field){ - lastDeclaration = field; - if( currentScope instanceof IASTClassSpecifier ){ - check( DECLARATIONS, field ); - if( !field.isStatic() ){ - check( DEFINITIONS, field ); - } - } else { - check( DEFINITIONS, field ); - } - } - - public void acceptEnumerationSpecifier(IASTEnumerationSpecifier enumeration){ - lastDeclaration = enumeration; - check( DECLARATIONS, enumeration ); - Iterator iter = enumeration.getEnumerators(); - while( iter.hasNext() ){ - IASTEnumerator enumerator = (IASTEnumerator) iter.next(); - lastDeclaration = enumerator; - check ( DECLARATIONS, enumerator ); - } - } - - public void acceptFunctionDeclaration(IASTFunction function){ - lastDeclaration = function; - check( DECLARATIONS, function ); - } - - public void acceptMethodDeclaration(IASTMethod method){ - lastDeclaration = method; - check( DECLARATIONS, method ); - } - - public void acceptClassReference(IASTClassReference reference) { - check( REFERENCES, reference ); - } - - public void acceptNamespaceReference( IASTNamespaceReference reference ){ - check( REFERENCES, reference ); - } - - public void acceptVariableReference( IASTVariableReference reference ){ - check( REFERENCES, reference ); - } - - public void acceptFieldReference( IASTFieldReference reference ){ - check( REFERENCES, reference ); - } - - public void acceptEnumerationReference( IASTEnumerationReference reference ){ - check( REFERENCES, reference ); - } - - public void acceptFunctionReference( IASTFunctionReference reference ){ - check( REFERENCES, reference ); - } - - public void acceptMethodReference( IASTMethodReference reference ){ - check( REFERENCES, reference ); - } - - public void enterFunctionBody(IASTFunction function){ - lastDeclaration = function; - - if( !function.previouslyDeclared() ) - check( DECLARATIONS, function ); - - check( DEFINITIONS, function ); - - Iterator parms =function.getParameters(); - while (parms.hasNext()){ - Object tempParm = parms.next(); - if (tempParm instanceof IASTParameterDeclaration){ - check( DECLARATIONS, ((IASTParameterDeclaration)tempParm)); - } - } - pushScope( function ); - } - - public void enterMethodBody(IASTMethod method) { - lastDeclaration = method; - if( !method.previouslyDeclared() ) - check( DECLARATIONS, method ); - - check( DEFINITIONS, method ); - - - Iterator parms =method.getParameters(); - while (parms.hasNext()){ - Object tempParm = parms.next(); - if (tempParm instanceof IASTParameterDeclaration){ - check( DECLARATIONS, ((IASTParameterDeclaration)tempParm)); - } - } - pushScope( method ); - } - - public void enterCompilationUnit(IASTCompilationUnit compilationUnit) { - pushScope( compilationUnit ); - } - - public void enterNamespaceDefinition(IASTNamespaceDefinition namespaceDefinition) { - lastDeclaration = namespaceDefinition; - check( DECLARATIONS, namespaceDefinition ); - check( DEFINITIONS, namespaceDefinition ); - pushScope( namespaceDefinition ); - } - - public void enterClassSpecifier(IASTClassSpecifier classSpecification) { - lastDeclaration = classSpecification; - check( DECLARATIONS, classSpecification ); - pushScope( classSpecification ); - } - - public void exitFunctionBody(IASTFunction function) { - popScope(); - } - - public void exitMethodBody(IASTMethod method) { - popScope(); - } - - public void exitClassSpecifier(IASTClassSpecifier classSpecification) { - check(DECLARATIONS, classSpecification); - popScope(); - } - - public void exitNamespaceDefinition(IASTNamespaceDefinition namespaceDefinition) { - popScope(); - } - - public void exitCompilationUnit(IASTCompilationUnit compilationUnit){ - popScope(); - } - - public void enterInclusion(IASTInclusion inclusion) { - String includePath = inclusion.getFullFileName(); - - IPath path = new Path( includePath ); - IResource resource = null; - - if( workspaceRoot != null ){ - resource = workspaceRoot.getFileForLocation( path ); -// if( resource == null ){ -// //TODO:What to do if the file is not in the workspace? - // IFile file = currentResource.getProject().getFile( - // inclusion.getName() ); -// try{ -// file.createLink( path, 0, null ); -// } catch ( CoreException e ){ -// file = null; -// } -// resource = file; -// } - } - - resourceStack.addFirst( ( currentResource != null ) ? (Object)currentResource : (Object)currentPath ); - - currentResource = resource; - currentPath = ( resource == null ) ? path : null; - } - - public void exitInclusion(IASTInclusion inclusion) { - Object obj = resourceStack.removeFirst(); - if( obj instanceof IResource ){ - currentResource = (IResource)obj; - currentPath = null; - } else { - currentPath = (IPath) obj; - currentResource = null; - } - } - - - public void locateMatches( String [] paths, IWorkspace workspace, IWorkingCopy[] workingCopies ) throws InterruptedException{ - - matchStorage = new ArrayList(); - workspaceRoot = (workspace != null) ? workspace.getRoot() : null; - - HashMap wcPaths = new HashMap(); - int wcLength = (workingCopies == null) ? 0 : workingCopies.length; - if( wcLength > 0 ){ - String [] newPaths = new String[ wcLength ]; - - for( int i = 0; i < wcLength; i++ ){ - IWorkingCopy workingCopy = workingCopies[ i ]; - String path = workingCopy.getOriginalElement().getPath().toString(); - wcPaths.put( path, workingCopy ); - newPaths[ i ] = path; - } - - int len = paths.length; - String [] tempArray = new String[ len + wcLength ]; - System.arraycopy( paths, 0, tempArray, 0, len ); - System.arraycopy( newPaths, 0, tempArray, len, wcLength ); - paths = tempArray; - } - - Arrays.sort( paths ); - - int length = paths.length; - if( progressMonitor != null ){ - progressMonitor.beginTask( "", length ); //$NON-NLS-1$ - } - - for( int i = 0; i < length; i++ ){ - if( progressMonitor != null ) { - if( progressMonitor.isCanceled() ){ - throw new InterruptedException(); - } else { - progressMonitor.worked( 1 ); - } - } - - String pathString = paths[ i ]; - - //skip duplicates - if( i > 0 && pathString.equals( paths[ i - 1 ] ) ) continue; - - if (!searchScope.encloses(pathString)) continue; - - CodeReader reader = null; - - realPath = null; - IProject project = null; - - if( workspaceRoot != null ){ - IWorkingCopy workingCopy = (IWorkingCopy)wcPaths.get( pathString ); - - if( workingCopy != null ){ - currentResource = workingCopy.getResource(); - if ( currentResource != null && currentResource.isAccessible() ) { - reader = new CodeReader(currentResource.getLocation().toOSString(), workingCopy.getContents()); - realPath = currentResource.getLocation(); - project = currentResource.getProject(); - } else { - continue; - } - } else { - currentResource = workspaceRoot.findMember( pathString, true ); - - InputStream contents = null; - try{ - if( currentResource != null ){ - if (currentResource.isAccessible() && currentResource instanceof IFile) { - IFile file = (IFile) currentResource; - contents = file.getContents(); - reader = new CodeReader(currentResource.getLocation().toOSString(), file.getCharset(), contents); - realPath = currentResource.getLocation(); - project = file.getProject(); - } else { - continue; - } - } - } catch ( CoreException e ){ - continue; - } catch ( IOException e ) { - continue; - } finally { - if (contents != null) { - try { - contents.close(); - } catch (IOException io) { - // ignore. - } - } - } - } - } - if( currentResource == null ) { - try { - IPath path = new Path( pathString ); - currentPath = path; - reader = new CodeReader(pathString); - realPath = currentPath; - } catch (IOException e) { - continue; - } - } - - //Get the scanner info - IScannerInfo scanInfo = new ScannerInfo(); - IScannerInfoProvider provider = CCorePlugin.getDefault().getScannerInfoProvider(project); - if (provider != null){ - IScannerInfo buildScanInfo = provider.getScannerInformation(currentResource != null ? currentResource : project); - if( buildScanInfo != null ) - scanInfo = new ScannerInfo(buildScanInfo.getDefinedSymbols(), buildScanInfo.getIncludePaths()); - } - - ParserLanguage language = null; - if( project != null ){ - language = CoreModel.hasCCNature( project ) ? ParserLanguage.CPP : ParserLanguage.C; - } else { - //TODO no project, what language do we use? - language = ParserLanguage.CPP; - } - - IParser parser = null; - try - { - IScanner scanner = ParserFactory.createScanner( reader, scanInfo, ParserMode.COMPLETE_PARSE, language, this, ParserUtil.getScannerLogService(), null ); - parser = ParserFactory.createParser( scanner, this, ParserMode.COMPLETE_PARSE, language, ParserUtil.getParserLogService() ); - } - catch( ParserFactoryError pfe ) - { - - } - - if (VERBOSE) - MatchLocator.verbose("*** New Search for path: " + pathString); //$NON-NLS-1$ - - - try{ - parser.parse(); - } - catch(Exception ex){ - if (VERBOSE){ - ex.printStackTrace(); - } - } - catch(VirtualMachineError vmErr){ - if (VERBOSE){ - MatchLocator.verbose("MatchLocator VM Error: "); //$NON-NLS-1$ - vmErr.printStackTrace(); - } - } finally { - scopeStack.clear(); - resourceStack.clear(); - lastDeclaration = null; - currentScope = null; - parser = null; - } - - if( matchStorage.size() > 0 ){ - AcceptMatchOperation acceptMatchOp = new AcceptMatchOperation( resultCollector, matchStorage ); - try { - CCorePlugin.getWorkspace().run(acceptMatchOp,null); - } catch (CoreException e) {} - - matchStorage.clear(); - } - } - } - - protected void report( ISourceElementCallbackDelegate node, int accuracyLevel ){ - try { - if( currentResource != null && !searchScope.encloses(currentResource.getFullPath().toOSString() ) ){ - return; - } - - int offset = 0; - int end = 0; - - if( node instanceof IASTReference ){ - IASTReference reference = (IASTReference) node; - offset = reference.getOffset(); - end = offset + reference.getName().length(); - if (VERBOSE) - MatchLocator.verbose("Report Match: " + reference.getName()); //$NON-NLS-1$ - } else if( node instanceof IASTOffsetableNamedElement ){ - IASTOffsetableNamedElement offsetableElement = (IASTOffsetableNamedElement) node; - offset = offsetableElement.getNameOffset() != 0 ? offsetableElement.getNameOffset() - : offsetableElement.getStartingOffset(); - end = offsetableElement.getNameEndOffset(); - if( end == 0 ){ - end = offset + offsetableElement.getName().length(); - } - - if (VERBOSE) - MatchLocator.verbose("Report Match: " + offsetableElement.getName()); //$NON-NLS-1$ - } - - IMatch match = null; - ISourceElementCallbackDelegate object = null; - - if( node instanceof IASTReference ){ - if( currentScope instanceof IASTFunction || currentScope instanceof IASTMethod ){ - object = (ISourceElementCallbackDelegate) currentScope; - } else { - object = lastDeclaration; - } - } else { - if( currentScope instanceof IASTFunction || currentScope instanceof IASTMethod ){ - //local declaration, only report if not being filtered - if( shouldExcludeLocalDeclarations ){ - return; - } - - object = (ISourceElementCallbackDelegate) currentScope; - } else { - object = node; - } - } - - if( currentResource != null ){ - match = resultCollector.createMatch( currentResource, offset, end, object, null ); - } else if( currentPath != null ){ - match = resultCollector.createMatch( currentPath, offset, end, object, realPath ); - } - if( match != null ){ - //Save till later - //resultCollector.acceptMatch( match ); - matchStorage.add(match); - } - - } catch (CoreException e) { - } - } - - private void check( LimitTo limit, ISourceElementCallbackDelegate node ){ - if( !searchPattern.canAccept( limit ) ) - return; - - int level = ICSearchPattern.IMPOSSIBLE_MATCH; - - if( node instanceof IASTReference ){ - level = searchPattern.matchLevel( ((IASTReference)node).getReferencedElement(), limit ); - } else { - level = searchPattern.matchLevel( node, limit ); - } - - if( level != ICSearchPattern.IMPOSSIBLE_MATCH ) - { - report( node, level ); - } - } - - private void pushScope( IASTScope scope ){ - scopeStack.addFirst( currentScope ); - currentScope = scope; - } - - private IASTScope popScope(){ - IASTScope oldScope = currentScope; - currentScope = (scopeStack.size() > 0 ) ? (IASTScope) scopeStack.removeFirst() : null; - return oldScope; - } - - public void setShouldExcludeLocalDeclarations( boolean exclude ){ - shouldExcludeLocalDeclarations = exclude; - } - - private boolean shouldExcludeLocalDeclarations = false; - - private ISourceElementCallbackDelegate lastDeclaration; - - private ICSearchPattern searchPattern; - private ICSearchResultCollector resultCollector; - private IProgressMonitor progressMonitor; - private IPath currentPath = null; - private ICSearchScope searchScope; - private IWorkspaceRoot workspaceRoot; - private IPath realPath; - - private IResource currentResource = null; - private LinkedList resourceStack = new LinkedList(); - - private IASTScope currentScope = null; - private LinkedList scopeStack = new LinkedList(); - - /* (non-Javadoc) - * @see org.eclipse.cdt.core.parser.ISourceElementRequestor#acceptElaboratedForewardDeclaration(org.eclipse.cdt.core.parser.ast.IASTElaboratedTypeSpecifier) - */ - public void acceptElaboratedForewardDeclaration(IASTElaboratedTypeSpecifier elaboratedType){ - check( DECLARATIONS, elaboratedType ); - } - - /* (non-Javadoc) - * @see org.eclipse.cdt.core.parser.ISourceElementRequestor#acceptFriendDeclaration(org.eclipse.cdt.core.parser.ast.IASTDeclaration) - */ - public void acceptFriendDeclaration(IASTDeclaration declaration) { - // TODO Auto-generated method stub - - } - - public static void verbose(String log) { - System.out.println("(" + Thread.currentThread() + ") " + log); //$NON-NLS-1$ //$NON-NLS-2$ - } - - /* (non-Javadoc) - * @see org.eclipse.cdt.core.parser.ISourceElementRequestor#createReader(java.lang.String) - */ - public CodeReader createReader(String finalPath, Iterator workingCopies) { - return ParserUtil.createReader(finalPath,workingCopies); - } - - /* (non-Javadoc) - * @see org.eclipse.cdt.core.search.IMatchLocator#setProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) - */ - public void setProgressMonitor(IProgressMonitor progressMonitor) { - this.progressMonitor = progressMonitor; - } -} diff --git a/core/org.eclipse.cdt.core/search/org/eclipse/cdt/internal/core/search/matching/MethodDeclarationPattern.java b/core/org.eclipse.cdt.core/search/org/eclipse/cdt/internal/core/search/matching/MethodDeclarationPattern.java deleted file mode 100644 index 5d2f2b4a18e..00000000000 --- a/core/org.eclipse.cdt.core/search/org/eclipse/cdt/internal/core/search/matching/MethodDeclarationPattern.java +++ /dev/null @@ -1,333 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2003, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corp. - Rational Software - initial implementation - *******************************************************************************/ -/* - * Created on Jul 11, 2003 - */ -package org.eclipse.cdt.internal.core.search.matching; - -import java.io.IOException; - -import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.cdt.core.parser.ISourceElementCallbackDelegate; -import org.eclipse.cdt.core.parser.ast.ASTUtil; -import org.eclipse.cdt.core.parser.ast.IASTFunction; -import org.eclipse.cdt.core.parser.ast.IASTMethod; -import org.eclipse.cdt.core.parser.ast.IASTQualifiedNameElement; -import org.eclipse.cdt.core.search.BasicSearchMatch; -import org.eclipse.cdt.core.search.ICSearchScope; -import org.eclipse.cdt.core.search.LimitTo; -import org.eclipse.cdt.core.search.SearchFor; -import org.eclipse.cdt.internal.core.CharOperation; -import org.eclipse.cdt.internal.core.index.IEntryResult; -import org.eclipse.cdt.internal.core.index.cindexstorage.Index; -import org.eclipse.cdt.internal.core.index.cindexstorage.IndexedFileEntry; -import org.eclipse.cdt.internal.core.index.cindexstorage.Util; -import org.eclipse.cdt.internal.core.index.cindexstorage.io.IndexInput; -import org.eclipse.cdt.internal.core.search.IIndexSearchRequestor; -import org.eclipse.cdt.utils.PathUtil; -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.ResourcesPlugin; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.Path; - -/** - * @author aniefer - * - * To change the template for this generated type comment go to - * Window>Preferences>Java>Code Generation>Code and Comments - */ -public class MethodDeclarationPattern extends CSearchPattern { - - private SearchFor searchFor; - - private char[][] parameterNames; - private char[] simpleName; - private char[][] qualifications; - private char[] returnTypes; - - private char[] decodedSimpleName; - private char[][] decodedQualifications; - private char[][] decodedParameters; - private char[] decodedReturnTypes; - - public MethodDeclarationPattern(char[] name, char[][] qual, char [][] params, char[] returnTypes, int matchMode, SearchFor search, LimitTo limitTo, boolean caseSensitive) { - //super( name, params, matchMode, limitTo, caseSensitive ); - super( matchMode, caseSensitive, limitTo ); - - qualifications = qual; - simpleName = name; - parameterNames = params; - this.returnTypes = returnTypes; - - searchFor = search; - } - - public char [] getSimpleName(){ - return simpleName; - } - - public int matchLevel(ISourceElementCallbackDelegate node, LimitTo limit ) { - if( node instanceof IASTMethod ){ - if( searchFor != METHOD || !canAccept( limit ) ){ - return IMPOSSIBLE_MATCH; - } - } else if ( node instanceof IASTFunction ){ - if( searchFor != FUNCTION || !canAccept( limit ) ){ - return IMPOSSIBLE_MATCH; - } - } else { - return IMPOSSIBLE_MATCH; - } - - IASTFunction function = (IASTFunction) node; - char[] nodeName = function.getNameCharArray(); - - //check name, if simpleName == null, its treated the same as "*" - if( simpleName != null && !matchesName( simpleName, nodeName ) ){ - return IMPOSSIBLE_MATCH; - } - - if( node instanceof IASTQualifiedNameElement ){ - //create char[][] out of full name, - char [][] qualName = ((IASTQualifiedNameElement) node).getFullyQualifiedNameCharArrays(); - //check containing scopes - if( !matchQualifications( qualifications, qualName, true ) ){ - return IMPOSSIBLE_MATCH; - } - } - - - //parameters - if( parameterNames != null && parameterNames.length > 0 && parameterNames[0].length > 0 ){ - String [] paramTypes = ASTUtil.getFunctionParameterTypes(function); - - if ( paramTypes.length == 0 && CharOperation.equals(parameterNames[0], "void".toCharArray())){ //$NON-NLS-1$ - //All empty lists have transformed to void, this function has no parms - return ACCURATE_MATCH; - } - - if( parameterNames.length != paramTypes.length ) - return IMPOSSIBLE_MATCH; - - for( int i = 0; i < parameterNames.length; i++ ){ - - //if this function doesn't have this many parameters, it is not a match. - //or if this function has a parameter, but parameterNames only has null. - if( parameterNames[ i ] == null ) - return IMPOSSIBLE_MATCH; - - char[] param = paramTypes[ i ].toCharArray(); - - //no wildcards in parameters strings - if( !CharOperation.equals( parameterNames[i], param, _caseSensitive ) ) - return IMPOSSIBLE_MATCH; - } - } - - return ACCURATE_MATCH; - } - - public char[] indexEntryPrefix() { - if( searchFor == FUNCTION ) - return Index.bestFunctionPrefix( _limitTo, simpleName, _matchMode, _caseSensitive ); - else if( searchFor == METHOD ) - return Index.bestMethodPrefix( _limitTo, simpleName, qualifications, _matchMode, _caseSensitive ); - else return null; - } - - protected void resetIndexInfo(){ - decodedSimpleName = null; - decodedQualifications = null; - } - - protected void decodeIndexEntry(IEntryResult entryResult) { - this.decodedSimpleName = entryResult.extractSimpleName().toCharArray(); - String []missmatch = entryResult.getEnclosingNames(); - if(missmatch != null) { - - //Find the first opening braces - int start=0; - int end=0; - boolean parmsExist=false; - for (int i=0; i 0){ - String[] parms = new String[decodedParameters.length]; - for (int k=0; kPreferences>Java>Code Generation>Code and Comments - */ -public class NamespaceDeclarationPattern extends CSearchPattern { - - - /** - * @param name - * @param cs - * @param matchMode - * @param limitTo - * @param caseSensitive - */ - public NamespaceDeclarationPattern(char[] name, char[][] quals, int matchMode, LimitTo limitTo, boolean caseSensitive) { - super( matchMode, caseSensitive, limitTo ); - - simpleName = name; - qualifications = quals; - } - - /* (non-Javadoc) - * @see org.eclipse.cdt.core.search.ICSearchPattern#matchLevel(org.eclipse.cdt.core.parser.ast.IASTOffsetableElement) - */ - public int matchLevel(ISourceElementCallbackDelegate node, LimitTo limit ) { - if( !( node instanceof IASTNamespaceDefinition ) || !canAccept( limit ) ) - return IMPOSSIBLE_MATCH; - - IASTNamespaceDefinition namespace = (IASTNamespaceDefinition)node; - - if( simpleName != null && !matchesName( simpleName, namespace.getNameCharArray() ) ){ - return IMPOSSIBLE_MATCH; - } - - //create char[][] out of full name, - char [] [] qualName = namespace.getFullyQualifiedNameCharArrays(); - - if( !matchQualifications( qualifications, qualName, true ) ){ - return IMPOSSIBLE_MATCH; - } - - return ACCURATE_MATCH; - } - - private char[][] decodedContainingTypes; - private char[] decodedSimpleName; - private char[][] qualifications; - private char[] simpleName; - - /* (non-Javadoc) - * @see org.eclipse.cdt.internal.core.search.matching.CSearchPattern#feedIndexRequestor(org.eclipse.cdt.internal.core.search.IIndexSearchRequestor, int, int[], org.eclipse.cdt.internal.core.index.impl.IndexInput, org.eclipse.cdt.core.search.ICSearchScope) - */ - public void feedIndexRequestor(IIndexSearchRequestor requestor, int detailLevel, int[] fileRefs, int[][] offsets, int[][] offsetLengths, IndexInput input, ICSearchScope scope) throws IOException { - - for (int i = 0, max = fileRefs.length; i < max; i++) { - IndexedFileEntry file = input.getIndexedFile(fileRefs[i]); - String path=null; - if (file != null && scope.encloses(path =file.getPath())) { - for (int j=0; j maxTicks ) - maxTicks = ticks; - updateRemainingCount( null ); - } - - synchronized public void setTicks( int n ){ - ticks = n; - if( maxTicks < ticks ) - maxTicks = ticks; - - updatePercentage(); - updateRemainingCount( null ); - } - - synchronized public int tickDown( String str ){ - if( progressMonitor != null && progressMonitor.isCanceled() ){ - jobManager.pause(); - return 0; - } - ticks--; - - updatePercentage(); - updateRemainingCount( str ); - return ticks; - } - - private void updateRemainingCount( String str ){ - if( progressMonitor == null ) - return; - - String taskString = Util.bind("manager.filesToIndex", Integer.toString(ticks)); //$NON-NLS-1$ - if( str != null ) - taskString += str; - progressMonitor.subTask( taskString ); - } - - private void updatePercentage(){ - if( progressMonitor == null ) - return; - - int work = (( maxTicks - ticks ) * 100 / maxTicks ) - workDone; - - workDone += work; - progressMonitor.worked( work ); - if( workDone < 0 ) workDone = 0; - } - - public IProgressMonitor getProgressGroup(){ - return group; - } -} diff --git a/core/org.eclipse.cdt.core/search/org/eclipse/cdt/internal/core/search/processing/JobManager.java b/core/org.eclipse.cdt.core/search/org/eclipse/cdt/internal/core/search/processing/JobManager.java deleted file mode 100644 index 7a81a466441..00000000000 --- a/core/org.eclipse.cdt.core/search/org/eclipse/cdt/internal/core/search/processing/JobManager.java +++ /dev/null @@ -1,549 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2003, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corp. - Rational Software - initial implementation - *******************************************************************************/ -/* - * Created on May 30, 2003 - */ -package org.eclipse.cdt.internal.core.search.processing; - -import org.eclipse.cdt.core.ICLogConstants; -import org.eclipse.cdt.internal.core.Util; -import org.eclipse.cdt.internal.core.index.domsourceindexer.DOMIndexRequest; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.OperationCanceledException; -import org.eclipse.core.runtime.Status; -import org.eclipse.core.runtime.SubProgressMonitor; - -public abstract class JobManager implements Runnable { - - /* queue of jobs to execute */ - protected IIndexJob[] awaitingJobs = new IIndexJob[10]; - protected int jobStart = 0; - protected int jobEnd = -1; - protected boolean executing = false; - - /* background processing */ - protected Thread thread; - - /* flag indicating whether job execution is enabled or not */ - public static final int ENABLED = 1; - public static final int DISABLED = 0; - public static final int WAITING = 2; - private int enabled = ENABLED; - - public static boolean VERBOSE = false; - /* flag indicating that the activation has completed */ - public boolean activated = false; - - private int awaitingClients = 0; - - protected IndexingJob indexJob = null; - - static private final IStatus OK_STATUS = new Status( IStatus.OK, "org.eclipse.cdt.core", IStatus.OK, "", null ); //$NON-NLS-1$//$NON-NLS-2$ - static private final IStatus ERROR_STATUS = new Status( IStatus.ERROR, "org.eclipse.cdt.core", IStatus.ERROR, "", null ); //$NON-NLS-1$//$NON-NLS-2$ - - public static void verbose(String log) { - System.out.println("(" + Thread.currentThread() + ") " + log); //$NON-NLS-1$//$NON-NLS-2$ - } - - public IProgressMonitor getIndexJobProgressGroup(){ - if( indexJob == null ) - return null; - - return indexJob.getProgressGroup(); - } - - /** - * Invoked exactly once, in background, before starting processing any job - */ - public void activateProcessing() { - this.activated = true; - } - /** - * Answer the amount of awaiting jobs. - */ - public synchronized int awaitingJobsCount() { - - // pretend busy in case concurrent job attempts performing before activated - if (!activated) - return 1; - - return jobEnd - jobStart + 1; - - } - /** - * Answers the first job in the queue, or null if there is no job available - * Until the job has completed, the job manager will keep answering the same job. - */ - public synchronized IIndexJob currentJob() { - - if ( enabled != ENABLED ) - return null; - - if (jobStart <= jobEnd) { - return awaitingJobs[jobStart]; - } - return null; - } - - public synchronized void disable() { - enabled = DISABLED; - if (VERBOSE) - JobManager.verbose("DISABLING background indexing"); //$NON-NLS-1$ - } - /** - * Remove the index from cache for a given project. - * Passing null as a job family discards them all. - */ - public void discardJobs(String jobFamily) { - - if (VERBOSE) - JobManager.verbose("DISCARD background job family - " + jobFamily); //$NON-NLS-1$ - - int oldEnabledState = 0; - try { - IIndexJob currentJob; - // cancel current job if it belongs to the given family - synchronized(this){ - currentJob = this.currentJob(); - oldEnabledState = enabledState(); - disable(); - } - if (currentJob != null - && (jobFamily == null || currentJob.belongsTo(jobFamily))) { - - currentJob.cancel(); - - // wait until current active job has finished - while (thread != null && executing){ - try { - if (VERBOSE) - JobManager.verbose("-> waiting end of current background job - " + currentJob); //$NON-NLS-1$ //$NON-NLS-2$ - Thread.sleep(50); - } catch(InterruptedException e){ - } - } - } - - // flush and compact awaiting jobs - int loc = -1; - synchronized(this) { - for (int i = jobStart; i <= jobEnd; i++) { - currentJob = awaitingJobs[i]; - awaitingJobs[i] = null; - if (!(jobFamily == null || currentJob == null - || currentJob.belongsTo(jobFamily))) { // copy down, compacting - awaitingJobs[++loc] = currentJob; - } else { - if (VERBOSE) - JobManager.verbose("-> discarding background job - " + currentJob); //$NON-NLS-1$ - currentJob.cancel(); - if( indexJob != null ){ - if( indexJob.tickDown( null ) <= 0 ){ - indexJob.done( OK_STATUS ); - indexJob = null; - } - } - } - } - jobStart = 0; - jobEnd = loc; - } - } finally { - if ( oldEnabledState == ENABLED ) - enable(); - else if( oldEnabledState == WAITING ) - pause(); - } - if (VERBOSE) - JobManager.verbose("DISCARD DONE with background job family - " + jobFamily); //$NON-NLS-1$ - } - - public synchronized void enable() { - if( enabled == WAITING ){ - //stop waiting, restore the indexing Job for progress - indexJob = new IndexingJob( thread, this ); - indexJob.setTicks(awaitingJobsCount()); - } - enabled = ENABLED; - if (VERBOSE) - JobManager.verbose("ENABLING background indexing"); //$NON-NLS-1$ - } - - public synchronized int enabledState() { - return enabled; - } - - public synchronized void pause(){ - enabled = WAITING; - if( VERBOSE ) - JobManager.verbose("WAITING pausing background indexing"); //$NON-NLS-1$ - } - /** - * Advance to the next available job, once the current one has been completed. - * Note: clients awaiting until the job count is zero are still waiting at this point. - */ - protected synchronized void moveToNextJob() { - - //if (!enabled) return; - - if (jobStart <= jobEnd) { - awaitingJobs[jobStart++] = null; - if (jobStart > jobEnd) { - jobStart = 0; - jobEnd = -1; - } - } - if( indexJob != null ){ - String progressString = null; - IIndexJob job = currentJob(); - if( job instanceof DOMIndexRequest ){ - progressString = " ("; //$NON-NLS-1$ - progressString += job.toString(); - progressString += ")"; //$NON-NLS-1$ - } - if( indexJob.tickDown( progressString ) <= 0 ){ - indexJob.done( OK_STATUS ); - indexJob = null; - } - } - } - /** - * When idle, give chance to do something - */ - protected void notifyIdle(long idlingTime) { - } - /** - * This API is allowing to run one job in concurrence with background processing. - * Indeed since other jobs are performed in background, resource sharing might be - * an issue.Therefore, this functionality allows a given job to be run without - * colliding with background ones. - * Note: multiple thread might attempt to perform concurrent jobs at the same time, - * and should synchronize (it is deliberately left to clients to decide whether - * concurrent jobs might interfere or not. In general, multiple read jobs are ok). - * - * Waiting policy can be: - * IJobConstants.ForceImmediateSearch - * IJobConstants.CancelIfNotReadyToSearch - * IJobConstants.WaitUntilReadyToSearch - * - */ - public boolean performConcurrentJob( - IIndexJob searchJob, - int waitingPolicy, - IProgressMonitor progress, - IIndexJob jobToIgnore) { - - if (VERBOSE) - JobManager.verbose("STARTING concurrent job - " + searchJob); //$NON-NLS-1$ - if (!searchJob.isReadyToRun()) { - if (VERBOSE) - JobManager.verbose("ABORTED concurrent job - " + searchJob); //$NON-NLS-1$ - return IIndexJob.FAILED; - } - - int concurrentJobWork = 100; - if (progress != null) - progress.beginTask("", concurrentJobWork); //$NON-NLS-1$ - boolean status = IIndexJob.FAILED; - if (awaitingJobsCount() > 0) { - if( enabledState() == WAITING ){ - //the indexer is paused, resume now that we have been asked for something - enable(); - } - boolean attemptPolicy = true; - policy: while( attemptPolicy ){ - attemptPolicy = false; - switch (waitingPolicy) { - - case IIndexJob.ForceImmediate : - if (VERBOSE) - JobManager.verbose("-> NOT READY - forcing immediate - " + searchJob);//$NON-NLS-1$ - boolean wasEnabled = ( enabledState() == ENABLED ); - try { - if( wasEnabled ) - disable(); // pause indexing - status = searchJob.execute(progress == null ? null : new SubProgressMonitor(progress, concurrentJobWork)); - } finally { - if(wasEnabled) - enable(); - } - if (VERBOSE) - JobManager.verbose("FINISHED concurrent job - " + searchJob); //$NON-NLS-1$ - return status; - - case IIndexJob.CancelIfNotReady : - if (VERBOSE) - JobManager.verbose("-> NOT READY - cancelling - " + searchJob); //$NON-NLS-1$ - if (progress != null) progress.setCanceled(true); - if (VERBOSE) - JobManager.verbose("CANCELED concurrent job - " + searchJob); //$NON-NLS-1$ - throw new OperationCanceledException(); - - case IIndexJob.WaitUntilReady : - int awaitingWork; - IIndexJob previousJob = null; - IIndexJob currentJob; - IProgressMonitor subProgress = null; - int totalWork = this.awaitingJobsCount(); - if (progress != null && totalWork > 0) { - subProgress = new SubProgressMonitor(progress, concurrentJobWork / 2); - subProgress.beginTask("", totalWork); //$NON-NLS-1$ - concurrentJobWork = concurrentJobWork / 2; - } - int originalPriority = this.thread.getPriority(); - try { - synchronized(this) { - - // use local variable to avoid potential NPE (see Bug 20435 NPE when searching java method) - Thread t = this.thread; - if (t != null) { - t.setPriority(Thread.currentThread().getPriority()); - } - this.awaitingClients++; - } - while (((awaitingWork = awaitingJobsCount()) > 0) - && (!jobShouldBeIgnored(jobToIgnore))) { - if (subProgress != null && subProgress.isCanceled()) - throw new OperationCanceledException(); - currentJob = currentJob(); - // currentJob can be null when jobs have been added to the queue but job manager is not enabled - if (currentJob != null && currentJob != previousJob) { - if (VERBOSE) - JobManager.verbose("-> NOT READY - waiting until ready - " + searchJob);//$NON-NLS-1$ - if (subProgress != null) { - subProgress.subTask( - Util.bind("manager.filesToIndex", Integer.toString(awaitingWork))); //$NON-NLS-1$ - subProgress.worked(1); - } - previousJob = currentJob; - } - - if( enabledState() == WAITING ){ - //user canceled the index we are waiting on, force immediate - waitingPolicy = IIndexJob.ForceImmediate; - attemptPolicy = true; - continue policy; - } - try { - Thread.sleep(50); - } catch (InterruptedException e) { - } - } - } finally { - synchronized(this) { - this.awaitingClients--; - - // use local variable to avoid potential NPE (see Bug 20435 NPE when searching java method) - Thread t = this.thread; - if (t != null) { - t.setPriority(originalPriority); - } - } - if (subProgress != null) { - subProgress.done(); - } - } - }//switch - } //while - } // if - status = searchJob.execute(progress == null ? null : new SubProgressMonitor(progress, concurrentJobWork)); - if (progress != null) { - progress.done(); - } - if (VERBOSE) - JobManager.verbose("FINISHED concurrent job - " + searchJob); //$NON-NLS-1$ - return status; - } - - /** - * @param jobToIgnore - * @return - */ - private boolean jobShouldBeIgnored(IIndexJob jobToIgnore) { - if (jobToIgnore == null) - return false; - - if (currentJob() == jobToIgnore) - return true; - - return false; - } - - public abstract String processName(); - - public synchronized void request(IIndexJob job) { - if (!job.isReadyToRun()) { - if (VERBOSE) - JobManager.verbose("ABORTED request of background job - " + job); //$NON-NLS-1$ - return; - } - - // append the job to the list of ones to process later on - int size = awaitingJobs.length; - if (++jobEnd == size) { // when growing, relocate jobs starting at position 0 - jobEnd -= jobStart; - System.arraycopy( - awaitingJobs, - jobStart, - (awaitingJobs = new IIndexJob[size * 2]), - 0, - jobEnd); - jobStart = 0; - } - awaitingJobs[jobEnd] = job; - - if (enabledState() ==WAITING){ - //Put back into enabled state - enable(); - } - else if( enabledState() == ENABLED ){ - if( indexJob == null ){ - indexJob = new IndexingJob( thread, this ); - } else { - indexJob.tickUp(); - } - } - - if (VERBOSE) - JobManager.verbose("REQUEST background job - " + job); //$NON-NLS-1$ - - } - /** - * Flush current state - */ - public void reset() { - if (VERBOSE) - JobManager.verbose("Reset"); //$NON-NLS-1$ - - if (thread != null) { - discardJobs(null); // discard all jobs - } else { - /* initiate background processing */ - thread = new Thread(this, this.processName()); - thread.setDaemon(true); - // less prioritary by default, priority is raised if clients are actively waiting on it - thread.setPriority(Thread.MIN_PRIORITY); - thread.start(); - } - - } - - /** - * Infinite loop performing resource indexing - */ - public void run() { - - long idlingStart = -1; - activateProcessing(); - try { - while (this.thread != null) { - try { - IIndexJob job; - if ((job = currentJob()) == null) { - if (idlingStart < 0) - idlingStart = System.currentTimeMillis(); - notifyIdle(System.currentTimeMillis() - idlingStart); - Thread.sleep(500); - continue; - } - - idlingStart = -1; - if (VERBOSE) { - JobManager.verbose(awaitingJobsCount() + " awaiting jobs"); //$NON-NLS-1$ - JobManager.verbose("STARTING background job - " + job); //$NON-NLS-1$ - } - try { - executing = true; - /*boolean status = */job.execute(null); - //if (status == FAILED) request(job); - } finally { - executing = false; - - //Answer the job directly from the array; using currentJob() - //results in no notification if indexing is disabled (Bug 78678) - jobFinishedNotification(awaitingJobs[jobStart]); - - if (VERBOSE) { - JobManager.verbose("FINISHED background job - " + job); //$NON-NLS-1$ - } - moveToNextJob(); - // Bug 68078: this delay affects indexing procedure too much. - // if (this.awaitingClients == 0) { - // Thread.sleep(50); - // } - } - } catch (InterruptedException e) { // background indexing was interrupted - } - } - } catch (RuntimeException e) { - if( indexJob != null ){ - indexJob.done( ERROR_STATUS ); - indexJob = null; - } - if (this.thread != null) { // if not shutting down - // log exception - org.eclipse.cdt.internal.core.model.Util.log(e, "Background Indexer Crash Recovery", ICLogConstants.PDE); //$NON-NLS-1$ - - // keep job manager alive - this.discardJobs(null); - this.thread = null; - this.reset(); // this will fork a new thread with no waiting jobs, some indexes will be inconsistent - } - throw e; - } catch (Error e) { - if( indexJob != null ){ - indexJob.done( ERROR_STATUS ); - indexJob = null; - } - if (this.thread != null && !(e instanceof ThreadDeath)) { - // log exception - org.eclipse.cdt.internal.core.model.Util.log(e, "Background Indexer Crash Recovery", ICLogConstants.PDE); //$NON-NLS-1$ - - // keep job manager alive - this.discardJobs(null); - this.thread = null; - this.reset(); // this will fork a new thread with no waiting jobs, some indexes will be inconsistent - } - throw e; - } - } - /** - * Stop background processing, and wait until the current job is completed before returning - */ - public void shutdown() { - - disable(); - discardJobs(null); // will wait until current executing job has completed - Thread thread = this.thread; - this.thread = null; // mark the job manager as shutting down so that the thread will stop by itself - try { - if (thread != null) { // see http://bugs.eclipse.org/bugs/show_bug.cgi?id=31858 - thread.join(); - } - } catch (InterruptedException e) { - } - } - - public String toString() { - StringBuffer buffer = new StringBuffer(10); - buffer.append("Enabled:").append(this.enabled).append('\n'); //$NON-NLS-1$ - int numJobs = jobEnd - jobStart + 1; - buffer.append("Jobs in queue:").append(numJobs).append('\n'); //$NON-NLS-1$ - for (int i = 0; i < numJobs && i < 15; i++) { - buffer.append(i).append(" - job["+i+"]: ").append(awaitingJobs[jobStart+i]).append('\n'); //$NON-NLS-1$ //$NON-NLS-2$ - } - return buffer.toString(); - } - - protected abstract void jobFinishedNotification(IIndexJob job); - -} diff --git a/core/org.eclipse.cdt.core/src/org/eclipse/cdt/core/CCorePlugin.java b/core/org.eclipse.cdt.core/src/org/eclipse/cdt/core/CCorePlugin.java index 9d820ac5490..b8929cfbdff 100644 --- a/core/org.eclipse.cdt.core/src/org/eclipse/cdt/core/CCorePlugin.java +++ b/core/org.eclipse.cdt.core/src/org/eclipse/cdt/core/CCorePlugin.java @@ -31,20 +31,15 @@ import org.eclipse.cdt.core.parser.IScannerInfoProvider; import org.eclipse.cdt.core.resources.IConsole; import org.eclipse.cdt.core.resources.IPathEntryVariableManager; import org.eclipse.cdt.core.resources.ScannerProvider; -import org.eclipse.cdt.core.search.SearchEngine; import org.eclipse.cdt.internal.core.CDTLogWriter; import org.eclipse.cdt.internal.core.CDescriptorManager; import org.eclipse.cdt.internal.core.PathEntryVariableManager; -import org.eclipse.cdt.internal.core.index.domsourceindexer.AbstractIndexerRunner; import org.eclipse.cdt.internal.core.model.BufferManager; import org.eclipse.cdt.internal.core.model.CModelManager; import org.eclipse.cdt.internal.core.model.DeltaProcessor; import org.eclipse.cdt.internal.core.model.IBufferFactory; import org.eclipse.cdt.internal.core.model.Util; import org.eclipse.cdt.internal.core.pdom.PDOMManager; -import org.eclipse.cdt.internal.core.search.indexing.IndexManager; -import org.eclipse.cdt.internal.core.search.matching.MatchLocator; -import org.eclipse.cdt.internal.core.search.processing.JobManager; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IProjectDescription; import org.eclipse.core.resources.IResource; @@ -931,31 +926,9 @@ public class CCorePlugin extends Plugin { option = Platform.getDebugOption(MODEL); if(option != null) Util.VERBOSE_MODEL = option.equalsIgnoreCase("true") ; //$NON-NLS-1$ - boolean indexFlag = false; - option = Platform.getDebugOption(INDEX_MANAGER); - if(option != null) { - indexFlag = option.equalsIgnoreCase("true"); //$NON-NLS-1$ - IndexManager.VERBOSE = indexFlag; - } //$NON-NLS-1$ - - option = Platform.getDebugOption(INDEXER); - if(option != null) AbstractIndexerRunner.VERBOSE = option.equalsIgnoreCase("true") ; //$NON-NLS-1$ - - option = Platform.getDebugOption(INDEXER_TIMES); - if (option != null) AbstractIndexerRunner.TIMING = option.equalsIgnoreCase("true"); //$NON-NLS-1$ - - option = Platform.getDebugOption(SEARCH); - if(option != null) SearchEngine.VERBOSE = option.equalsIgnoreCase("true") ; //$NON-NLS-1$ - option = Platform.getDebugOption(DELTA); if(option != null) DeltaProcessor.VERBOSE = option.equalsIgnoreCase("true") ; //$NON-NLS-1$ - option = Platform.getDebugOption(MATCH_LOCATOR); - if(option != null) MatchLocator.VERBOSE = option.equalsIgnoreCase("true") ; //$NON-NLS-1$ - - if (indexFlag == true){ - JobManager.VERBOSE = true; - } } } diff --git a/core/org.eclipse.cdt.ui.tests/META-INF/MANIFEST.MF b/core/org.eclipse.cdt.ui.tests/META-INF/MANIFEST.MF index 074055d7549..c93912ef0bf 100644 --- a/core/org.eclipse.cdt.ui.tests/META-INF/MANIFEST.MF +++ b/core/org.eclipse.cdt.ui.tests/META-INF/MANIFEST.MF @@ -10,9 +10,7 @@ Export-Package: org.eclipse.cdt.ui.testplugin, org.eclipse.cdt.ui.testplugin.util, org.eclipse.cdt.ui.tests, org.eclipse.cdt.ui.tests.DOMAST, - org.eclipse.cdt.ui.tests.IndexerView, org.eclipse.cdt.ui.tests.chelp, - org.eclipse.cdt.ui.tests.regression, org.eclipse.cdt.ui.tests.text, org.eclipse.cdt.ui.tests.text.contentassist, org.eclipse.cdt.ui.tests.text.selectiontests diff --git a/core/org.eclipse.cdt.ui.tests/src/org/eclipse/cdt/ui/tests/DOMAST/DOMAST.java b/core/org.eclipse.cdt.ui.tests/src/org/eclipse/cdt/ui/tests/DOMAST/DOMAST.java index 56c416a5b3d..c29d9c3da28 100644 --- a/core/org.eclipse.cdt.ui.tests/src/org/eclipse/cdt/ui/tests/DOMAST/DOMAST.java +++ b/core/org.eclipse.cdt.ui.tests/src/org/eclipse/cdt/ui/tests/DOMAST/DOMAST.java @@ -877,20 +877,6 @@ public class DOMAST extends ViewPart { searchNamesAction.setToolTipText(SEARCH_FOR_IASTNAME); searchNamesAction.setImageDescriptor(DOMASTPluginImages.DESC_SEARCH_NAMES); - openDeclarationsAction = new DisplayDeclarationsAction(); - openDeclarationsAction.setText(OPEN_DECLARATIONS); - openDeclarationsAction.setImageDescriptor(PlatformUI.getWorkbench().getSharedImages() - .getImageDescriptor(ISharedImages.IMG_OBJS_INFO_TSK)); - - openReferencesAction = new DisplayReferencesAction(); - openReferencesAction.setText(OPEN_REFERENCES); - openReferencesAction.setImageDescriptor(PlatformUI.getWorkbench().getSharedImages() - .getImageDescriptor(ISharedImages.IMG_OBJS_INFO_TSK)); - - displayProblemsAction = new DisplayProblemsResultAction(); - displayProblemsAction.setText(DISPLAY_PROBLEMS); - displayProblemsAction.setImageDescriptor(DOMASTPluginImages.DESC_IASTProblem); - displayNodeTypeAction = new Action() { public void run() { ISelection selection = viewer.getSelection(); @@ -1038,82 +1024,6 @@ public class DOMAST extends ViewPart { } - private class DisplayDeclarationsAction extends DisplaySearchResultAction { - private static final String STRING_QUOTE = "\""; //$NON-NLS-1$ - public void run() { - ISelection selection = viewer.getSelection(); - if (selection instanceof IStructuredSelection && - ((IStructuredSelection)selection).getFirstElement() instanceof DOMASTNodeLeaf && - ((DOMASTNodeLeaf)((IStructuredSelection)selection).getFirstElement()).getNode() instanceof IASTName) { - IASTName name = (IASTName)((DOMASTNodeLeaf)((IStructuredSelection)selection).getFirstElement()).getNode(); - StringBuffer pattern = new StringBuffer(STRING_QUOTE); - if (name.toString() != null) - pattern.append(name.toString()); - pattern.append(STRING_QUOTE); - - if (lang == ParserLanguage.CPP) { - IASTName[] names = ((DOMASTNodeLeaf)((IStructuredSelection)selection).getFirstElement()).getNode().getTranslationUnit().getDeclarations(name.resolveBinding()); - displayNames(names, OPEN_DECLARATIONS, pattern.toString()); - } else { - IASTName[] names = ((DOMASTNodeLeaf)((IStructuredSelection)selection).getFirstElement()).getNode().getTranslationUnit().getDeclarations(name.resolveBinding()); - displayNames(names, OPEN_DECLARATIONS, pattern.toString()); - } - } - } - } - - private class DisplayReferencesAction extends DisplaySearchResultAction { - private static final String STRING_QUOTE = "\""; //$NON-NLS-1$ - public void run() { - ISelection selection = viewer.getSelection(); - if (selection instanceof IStructuredSelection && - ((IStructuredSelection)selection).getFirstElement() instanceof DOMASTNodeLeaf && - ((DOMASTNodeLeaf)((IStructuredSelection)selection).getFirstElement()).getNode() instanceof IASTName) { - IASTName name = (IASTName)((DOMASTNodeLeaf)((IStructuredSelection)selection).getFirstElement()).getNode(); - StringBuffer pattern = new StringBuffer(STRING_QUOTE); - if (name.toString() != null) - pattern.append(name.toString()); - pattern.append(STRING_QUOTE); - - if (lang == ParserLanguage.CPP) { - IASTName[] names = ((DOMASTNodeLeaf)((IStructuredSelection)selection).getFirstElement()).getNode().getTranslationUnit().getReferences(name.resolveBinding()); - displayNames(names, OPEN_REFERENCES, pattern.toString()); - } else { - IASTName[] names = ((DOMASTNodeLeaf)((IStructuredSelection)selection).getFirstElement()).getNode().getTranslationUnit().getReferences(name.resolveBinding()); - displayNames(names, OPEN_REFERENCES, pattern.toString()); - } - } - } - } - - private class DisplaySearchResultAction extends Action { - protected void displayNames(IASTName[] names, String queryLabel, String pattern) { - DOMDisplaySearchNames job = new DOMDisplaySearchNames(names, queryLabel, pattern); - NewSearchUI.activateSearchResultView(); - NewSearchUI.runQueryInBackground(job); - } - } - - private class DisplayProblemsResultAction extends Action { - private static final String IASTPROBLEM = "IASTProblem"; //$NON-NLS-1$ - private static final String PROBLEMS_FOUND = "Problems Found"; //$NON-NLS-1$ - protected void displayProblems(IASTProblem[] problems, String queryLabel, String pattern) { - DOMDisplaySearchNames job = new DOMDisplaySearchNames(problems, queryLabel, pattern); - NewSearchUI.activateSearchResultView(); - NewSearchUI.runQueryInBackground(job); - } - - public void run() { - if (viewer.getTree().getItems().length == 0) { - showMessage(DOM_AST_HAS_NO_CONTENT); - } - - if (viewer.getContentProvider() instanceof ViewContentProvider) { - displayProblems(((ViewContentProvider)viewer.getContentProvider()).getASTProblems(), PROBLEMS_FOUND, IASTPROBLEM); - } - } - } - private void hookSingleClickAction() { viewer.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { diff --git a/core/org.eclipse.cdt.ui.tests/src/org/eclipse/cdt/ui/tests/DOMAST/DOMDisplaySearchNames.java b/core/org.eclipse.cdt.ui.tests/src/org/eclipse/cdt/ui/tests/DOMAST/DOMDisplaySearchNames.java deleted file mode 100644 index a371801a9cc..00000000000 --- a/core/org.eclipse.cdt.ui.tests/src/org/eclipse/cdt/ui/tests/DOMAST/DOMDisplaySearchNames.java +++ /dev/null @@ -1,262 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.ui.tests.DOMAST; - -import org.eclipse.cdt.core.dom.ast.ASTTypeUtil; -import org.eclipse.cdt.core.dom.ast.DOMException; -import org.eclipse.cdt.core.dom.ast.IASTFileLocation; -import org.eclipse.cdt.core.dom.ast.IASTName; -import org.eclipse.cdt.core.dom.ast.IASTNode; -import org.eclipse.cdt.core.dom.ast.IASTProblem; -import org.eclipse.cdt.core.dom.ast.IBinding; -import org.eclipse.cdt.core.dom.ast.ICompositeType; -import org.eclipse.cdt.core.dom.ast.IEnumeration; -import org.eclipse.cdt.core.dom.ast.IEnumerator; -import org.eclipse.cdt.core.dom.ast.IField; -import org.eclipse.cdt.core.dom.ast.IFunction; -import org.eclipse.cdt.core.dom.ast.IMacroBinding; -import org.eclipse.cdt.core.dom.ast.ITypedef; -import org.eclipse.cdt.core.dom.ast.IVariable; -import org.eclipse.cdt.core.dom.ast.cpp.ICPPClassType; -import org.eclipse.cdt.core.dom.ast.cpp.ICPPMember; -import org.eclipse.cdt.core.dom.ast.cpp.ICPPMethod; -import org.eclipse.cdt.core.dom.ast.cpp.ICPPNamespace; -import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.cdt.core.parser.ParserUtil; -import org.eclipse.cdt.core.search.BasicSearchMatch; -import org.eclipse.cdt.core.search.IMatch; -import org.eclipse.cdt.core.search.IOffsetLocatable; -import org.eclipse.cdt.core.search.OffsetLocatable; -import org.eclipse.cdt.internal.ui.search.CSearchQuery; -import org.eclipse.cdt.internal.ui.search.CSearchResult; -import org.eclipse.cdt.internal.ui.search.NewSearchResultCollector; -import org.eclipse.cdt.ui.CUIPlugin; -import org.eclipse.cdt.utils.PathUtil; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.OperationCanceledException; -import org.eclipse.core.runtime.Path; -import org.eclipse.core.runtime.Status; -import org.eclipse.core.runtime.SubProgressMonitor; -import org.eclipse.search.ui.ISearchQuery; -import org.eclipse.search.ui.ISearchResult; - -/** - * This is used for the DOM AST Viewer only... it requires that the names to be displayed - * in the search view were already found elsewhere. - * @author dsteffle - */ -public class DOMDisplaySearchNames extends CSearchQuery implements ISearchQuery { - - private static final String BLANK_STRING = ""; //$NON-NLS-1$ - private CSearchResult _result; - private IASTNode[] nodes = null; - private String queryLabel = null; - - /** - * - */ - public DOMDisplaySearchNames(IASTNode[] nodes, String queryLabel, String pattern) { - super(CUIPlugin.getWorkspace(), pattern, false, null, null, null, queryLabel); - this.nodes = nodes; - this.queryLabel = queryLabel; - } - - /* (non-Javadoc) - * @see org.eclipse.search.ui.ISearchQuery#run(org.eclipse.core.runtime.IProgressMonitor) - */ - public IStatus run(IProgressMonitor monitor) - throws OperationCanceledException { - - final CSearchResult textResult= (CSearchResult) getSearchResult(); - - IProgressMonitor mainSearchPM= new SubProgressMonitor(monitor, 1000); - NewSearchResultCollector collector = new NewSearchResultCollector(textResult, mainSearchPM); - - collector.aboutToStart(); - - for (int i=0; inull. - * - * @param parent - * the parent composite. - * @param name - * the name of the label. - * @return returns a label if a name was given, null - * otherwise. - */ - protected Label createLabel(Composite parent, String name) { - if (name == null) - return null; - Label label = new Label(parent, SWT.NONE); - label.setText(name); - label.setFont(parent.getFont()); - return label; - } - - /** - * Creates a type filter checkbox. - */ - private void createTypeCheckbox(Composite parent, int type) { - String name = getStringDescription(type); - Image icon = IndexerViewPluginImages.get(type); - - Composite composite = new Composite(parent, SWT.NONE); - GridLayout layout = new GridLayout(2, false); - layout.marginHeight = 0; - composite.setLayout(layout); - - final int type1 = type; - Button checkbox = new Button(composite, SWT.CHECK); - checkbox.setFont(composite.getFont()); - checkbox.setText(name); - checkbox.setImage(icon); - checkbox.setSelection(fFilterMatcher[type]); - checkbox.addSelectionListener(new SelectionAdapter() { - public void widgetSelected(SelectionEvent e) { - if (e.widget instanceof Button) { - Button aCheckbox = (Button) e.widget; - fFilterMatcher[type1] = aCheckbox.getSelection(); - } - } - }); - - Label label = new Label(composite, SWT.LEFT); - label.setFont(composite.getFont()); - label.setText(name); - - buttons[type] = checkbox; - } - - - /** - * Creates an area to filter types. - * - * @param parent - * area to create controls in - */ - private void createTypeFilterArea(Composite parent) { - createLabel(parent,TYPESELECTIONDIALOG_DeclLABEL); - - Composite upperRow = new Composite(parent, SWT.NONE); - GridLayout upperLayout = new GridLayout(3, true); - upperLayout.verticalSpacing = 2; - upperLayout.marginHeight = 0; - upperLayout.marginWidth = 0; - upperRow.setLayout(upperLayout); - - // the for loop is here to guarantee we always - // create the checkboxes in the same order - for (int i = 0; i < iAllTypes.length; ++i) { - if(iAllTypes[i][2] == IIndex.DECLARATION) - createTypeCheckbox(upperRow, i); - } - - createLabel(parent,TYPESELECTIONDIALOG_RefLABEL); - - Composite lowerRow = new Composite(parent, SWT.NONE); - lowerRow.setLayout(upperLayout); - - // the for loop is here to guarantee we always - // create the checkboxes in the same order - for (int i = 0; i < iAllTypes.length; ++i) { - if(iAllTypes[i][2] == IIndex.REFERENCE) - createTypeCheckbox(lowerRow, i); - } - } - - private void createGroupedArea(Composite parent) { - createLabel(parent, GROUPED_SELECTIONS_LABEL); - - Composite upperRow = new Composite(parent, SWT.NONE); - GridLayout upperLayout = new GridLayout(8, true); - upperLayout.verticalSpacing = 2; - upperLayout.marginHeight = 0; - upperLayout.marginWidth = 0; - upperRow.setLayout(upperLayout); - - allButton = new Button(upperRow, SWT.CHECK); - allButton.setFont(upperRow.getFont()); - allButton.setText(ALL_BUTTON); - allButton.setImage(IndexerViewPluginImages.get(IndexerViewPluginImages.IMG_GROUPED_ALL)); - allButton.setSelection(groupedButtonSelections[ALL_BUTTON_ID]); - allButton.addSelectionListener(new SelectionAdapter() { - public void widgetSelected(SelectionEvent e) { - if (e.widget instanceof Button) { - Button aCheckbox = (Button) e.widget; - boolean isChecked = aCheckbox.getSelection(); - - Event event = new Event(); - - // select/deselect all of the buttons in the buttons array - for(int i=0; i display.width) { - result.x -= xe - display.width; - } - int ye = result.y + initialSize.y; - if (ye > display.height) { - result.y -= ye - display.height; - } - } - return result; - } - - protected Point getInitialSize() { - Point result = super.getInitialSize(); - if (fSize != null) { - result.x = Math.max(result.x, fSize.x); - result.y = Math.max(result.y, fSize.y); - Rectangle display = getShell().getDisplay().getClientArea(); - result.x = Math.min(result.x, display.width); - result.y = Math.min(result.y, display.height); - } - return result; - } - - /** - * Initializes itself from the dialog settings with the same state - * as at the previous invocation. - */ - public void readSettings(IDialogSettings section) { - try { - int x = section.getInt(SETTINGS_X_POS); - int y = section.getInt(SETTINGS_Y_POS); - fLocation = new Point(x, y); - int width = section.getInt(SETTINGS_WIDTH); - int height = section.getInt(SETTINGS_HEIGHT); - fSize = new Point(width, height); - - pageSize = section.getInt(PAGE_SIZE); - } catch (NumberFormatException e) { - fLocation = null; - fSize = null; - } - - for(int i = 0; i < iAllTypes.length; i++) { - fFilterMatcher[i] = section.getBoolean(getUniqueStringDescription(i)); - } - - // get the grouped button selection status - groupedButtonSelections[ALL_BUTTON_ID] = section.getBoolean(ALL_BUTTON); - groupedButtonSelections[TYPE_BUTTON_ID] = section.getBoolean(TYPE_BUTTON); - groupedButtonSelections[REF_BUTTON_ID] = section.getBoolean(REF_BUTTON); - groupedButtonSelections[DECL_BUTTON_ID] = section.getBoolean(DECL_BUTTON); - fFilter = section.get(FILTER_TEXT); - if (fFilter == null) - fFilter = BLANK_STRING; - } - - public IndexerFilterManager createFilterManager() { - return new IndexerFilterManager(fFilterMatcher, fFilter); - } - - private void apply() { - fFilter = filterText.getText(); - pageSize=IndexerNodeParent.PAGE_SIZE; - try { - pageSize = Integer.valueOf(pageSizeText.getText()).intValue(); - if (pageSize<=0) - pageSize=IndexerNodeParent.PAGE_SIZE; - } catch (NumberFormatException e) {} - - root.setFilterManager(fFilterMatcher, fFilter); - root.setPageSize(pageSize); - root.reset(); - writeSettings(getDialogSettings()); - } - - public int getPageSize() { - return pageSize; - } - -} diff --git a/core/org.eclipse.cdt.ui.tests/src/org/eclipse/cdt/ui/tests/IndexerView/IndexerFilterManager.java b/core/org.eclipse.cdt.ui.tests/src/org/eclipse/cdt/ui/tests/IndexerView/IndexerFilterManager.java deleted file mode 100644 index 4872abb1f22..00000000000 --- a/core/org.eclipse.cdt.ui.tests/src/org/eclipse/cdt/ui/tests/IndexerView/IndexerFilterManager.java +++ /dev/null @@ -1,44 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.ui.tests.IndexerView; - -/** - * @author dsteffle - */ -public class IndexerFilterManager { - private static final String BLANK_STRING = ""; //$NON-NLS-1$ - private static final String COMMA_SEPARATOR = ","; //$NON-NLS-1$ - boolean [] filters = null; - String nameFilter = null; - String [] nameFilters; - - public IndexerFilterManager(boolean [] filters, String nameFilter) { - this.filters = filters; - this.nameFilter = nameFilter; - nameFilters = nameFilter.split(COMMA_SEPARATOR); - for(int i=0; i 0) { - for(int l=0; l 1) { - if (sort) {// sort children based on name - quickSort(children, 0, children.length - 1, true); - } else {// sort children based on word - quickSort(children, 0, children.length - 1, false); - } - } - - int start=0; - if (isForward) { - if (lastForwardDisplayed==0) start=0; - else start=lastForwardDisplayed+1; - } else { - if (lastBackwardDisplayed==0) start=0; - else start=lastBackwardDisplayed-1; - } - boolean shouldDisplay=true; - int numAdded=0; - - int i=start, j=(isForward?0:pageSize-1); - IndexerNodeLeaf[] temp = new IndexerNodeLeaf[pageSize]; - boolean tempIsUseful=false; - while(numAdded=0) { - // only add the child to the children to display if it matches the current filters set on the view - shouldDisplay = filterManager.isFiltered(children[i]); - - if (shouldDisplay) { - tempIsUseful=true; - - temp[j] = children[i]; - numAdded++; - if (isForward) lastForwardDisplayed=i; - else if (j==pageSize-1) lastForwardDisplayed=i; - if (j==0) lastBackwardDisplayed=i; - - // move the index to the next entry in the array to store the next valid child to display - if (isForward) { - if (j+1=0) j--; - } - } - - shouldDisplay=true; // reset this value - - // move the index to the next child to analyze - if (isForward) { - i++; - } else { - i--; - } - } - - // if there is useful content on the next page, return it, otherwise just return what is being displayed - if (tempIsUseful) { - childrenToDisplay = new IndexerNodeLeaf[pageSize]; // blank the old array being displayed - // copy the temp array into the actual array - for(int k=0, l=0; k 0); - } - - public int getFullLength() { - return children.length; - } - - public void setIsForward(boolean direction) { - isForward = direction; - } - - public void setFilterManager(boolean [] filters, String filterName) { - this.filterManager = new IndexerFilterManager(filters, filterName); - } - - public void reset() { - navigate=true; - lastBackwardDisplayed = 0; - lastForwardDisplayed=0; - isForward=true; - firstDisplay=true; - childrenToDisplay = EMPTY_INDEXER_NODE_LEAVES; - } - - public void setPageSize(int size) { - pageSize = size; - } - - public void setView(IndexerView.ViewContentProvider view) { - this.view = view; - } - - public int getFilteredCount() { - int filteredCount=0; - for(int i=0; i j-1) { - String file = fileMap[references[j]]; - if (file != null){ - IPath filePath = new Path(file); - //If we can verify that the file exists within the workspace, we'll use it - //to open the appropriate editor - if not we can just set the path and we'll - //use the external editor mechanism - IFile tempFile = ResourcesPlugin.getWorkspace().getRoot().getFile(filePath); - if (tempFile != null && tempFile.exists()) - match.setResource(tempFile); - else { - match.setPath(PathUtil.getWorkspaceRelativePath(file)); - } - - } - } - int offsetType=0; - int start=0; - int end=0; - try { - offsetType=Integer.valueOf(String.valueOf(offsets[j][k]).substring(0,1)).intValue(); - start=Integer.valueOf(String.valueOf(offsets[j][k]).substring(1)).intValue(); - end=start+offsetLengths[j][k]; - } catch (NumberFormatException nfe) {} - - match.setOffsetType(offsetType); - match.setStart(start) ; - match.setEnd(end); - match.setName(leaf.getName()); - - matches = (MatchInfo[])ArrayUtil.append(MatchInfo.class, matches, match); - } - } - } - - return matches; - } - - private class MatchInfo { - private IPath path=null; - private int offsetType=0; - private int start=0; - private int end=0; - private String name=null; - private IResource resource=null; - - public IPath getPath() { - return path; - } - public void setOffsetType(int offsetType){ - this.offsetType=offsetType; - } - public int getOffsetType() { - return offsetType; - } - public void setPath(IPath path) { - this.path = path; - } - public int getEnd() { - return end; - } - public void setEnd(int end) { - this.end = end; - } - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } - public int getStart() { - return start; - } - public void setStart(int start) { - this.start = start; - } - public IResource getResource() { - return resource; - } - public void setResource(IResource resource) { - this.resource = resource; - } - } - - public IMatch createMatch( Object fileResource,int offsetType, int start, int end, String name, IPath referringElement ) { - BasicSearchMatch result = new BasicSearchMatch(); - if( fileResource instanceof IResource ) - result.setResource((IResource) fileResource); - else if( fileResource instanceof IPath ) - result.setPath((IPath) fileResource); - - IMatchLocatable locatable=null; - if (offsetType == IIndex.LINE) - { - locatable = new LineLocatable(start,end); - } - else if (offsetType == IIndex.OFFSET){ - locatable = new OffsetLocatable(start,end); - } - result.setLocatable(locatable); - result.setParentName(BLANK_STRING); //$NON-NLS-1$ - result.setReferringElement(referringElement); - - result.setName(name); - - result.setType(ICElement.C_FIELD); // TODO Devin static for now, want something like BasicSearchResultCollector#setElementInfo - result.setVisibility(ICElement.CPP_PUBLIC); // TODO Devin static for now, want something like BasicSearchResultCollector#setElementInfo - result.setReturnType(BLANK_STRING); - - return result; - } - - - /* (non-Javadoc) - * @see org.eclipse.search.ui.ISearchQuery#getLabel() - */ - public String getLabel() { - return queryLabel; - } - - /* (non-Javadoc) - * @see org.eclipse.search.ui.ISearchQuery#canRerun() - */ - public boolean canRerun() { - // TODO Auto-generated method stub - return false; - } - - /* (non-Javadoc) - * @see org.eclipse.search.ui.ISearchQuery#canRunInBackground() - */ - public boolean canRunInBackground() { - return true; - } - - /* (non-Javadoc) - * @see org.eclipse.search.ui.ISearchQuery#getSearchResult() - */ - public ISearchResult getSearchResult() { - if (_result == null) - _result= new CSearchResult(this); - return _result; - } - -} diff --git a/core/org.eclipse.cdt.ui.tests/src/org/eclipse/cdt/ui/tests/IndexerView/IndexerView.java b/core/org.eclipse.cdt.ui.tests/src/org/eclipse/cdt/ui/tests/IndexerView/IndexerView.java deleted file mode 100644 index 78ea8b6f43f..00000000000 --- a/core/org.eclipse.cdt.ui.tests/src/org/eclipse/cdt/ui/tests/IndexerView/IndexerView.java +++ /dev/null @@ -1,618 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.ui.tests.IndexerView; - -import java.io.IOException; - -import org.eclipse.cdt.core.index.ICDTIndexer; -import org.eclipse.cdt.internal.core.index.IEntryResult; -import org.eclipse.cdt.internal.core.index.IIndex; -import org.eclipse.cdt.ui.testplugin.CTestPlugin; -import org.eclipse.core.resources.IProject; -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.IMenuListener; -import org.eclipse.jface.action.IMenuManager; -import org.eclipse.jface.action.IToolBarManager; -import org.eclipse.jface.action.MenuManager; -import org.eclipse.jface.action.Separator; -import org.eclipse.jface.dialogs.IDialogConstants; -import org.eclipse.jface.dialogs.MessageDialog; -import org.eclipse.jface.viewers.ISelection; -import org.eclipse.jface.viewers.ISelectionChangedListener; -import org.eclipse.jface.viewers.IStructuredContentProvider; -import org.eclipse.jface.viewers.IStructuredSelection; -import org.eclipse.jface.viewers.ITreeContentProvider; -import org.eclipse.jface.viewers.LabelProvider; -import org.eclipse.jface.viewers.SelectionChangedEvent; -import org.eclipse.jface.viewers.TableViewer; -import org.eclipse.jface.viewers.Viewer; -import org.eclipse.jface.viewers.ViewerFilter; -import org.eclipse.search.ui.NewSearchUI; -import org.eclipse.swt.SWT; -import org.eclipse.swt.graphics.Image; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Menu; -import org.eclipse.swt.widgets.TableItem; -import org.eclipse.ui.IActionBars; -import org.eclipse.ui.IViewPart; -import org.eclipse.ui.IWorkbenchActionConstants; -import org.eclipse.ui.part.ViewPart; -import org.eclipse.ui.views.properties.PropertySheet; - -/** - * @author dsteffle - */ -public class IndexerView extends ViewPart { - private static final int DEFAULT_INDEXER_SIZE = 1; - private static final String SWITCH_FULL_NAMES = "Switch Full Names"; //$NON-NLS-1$ - private static final String SORT_RESULTS = "Sort Results"; //$NON-NLS-1$ - private static final String SEARCH_LOCATIONS = "Search Locations"; //$NON-NLS-1$ - private static final String _TOTAL_IENTRYRESULTS = " total IEntryResults\n"; //$NON-NLS-1$ - private static final String _FILTERED_IENTRY_RESULTS_ = " filtered IEntry Results\n"; //$NON-NLS-1$ - private static final String _TOTAL_INDEXEDFILES = " total files indexed"; //$NON-NLS-1$ - private static final String INDEXER_STATS = "Indexer Stats"; //$NON-NLS-1$ - private static final String DISPLAY_INDEX_STATS = "Display Index Stats"; //$NON-NLS-1$ - private static final String INDEXER_VIEW___ = "Indexer View - "; //$NON-NLS-1$ - private static final String _INDEXER_MENU_MANAGER = "#Indexer_Menu_Manager"; //$NON-NLS-1$ - private static final String SET_FILTERS = "Set Filters"; //$NON-NLS-1$ - private static final String NEXT_PAGE = "Next Page"; //$NON-NLS-1$ - private static final String PREVIOUS_PAGE = "Previous Page"; //$NON-NLS-1$ - public static final String VIEW_ID = "org.eclipse.cdt.ui.tests.IndexerView"; //$NON-NLS-1$ - private static final String PROPERTIES_VIEW = "org.eclipse.ui.views.PropertySheet"; //$NON-NLS-1$ - protected static final String BLANK_STRING = ""; //$NON-NLS-1$ - static TableViewer viewer; - protected Action searchLocationAction; - protected Action previousPageAction; - protected Action nextPageAction; - protected Action singleClickAction; - protected Action setFiltersAction; - protected Action sortAction; - protected Action displayFullNameAction; - protected Action displayStatsAction; - protected ICDTIndexer[] indexers = new ICDTIndexer[DEFAULT_INDEXER_SIZE]; // support 1 indexer for now new IIndexer[CTestPlugin.getWorkspace().getRoot().getProjects().length]; - protected IProject project = null; - - protected static ViewContentProvider.StartInitializingIndexerView initializeIndexerViewJob = null; - - public class ViewContentProvider implements IStructuredContentProvider, - ITreeContentProvider { - - private static final String POPULATING_INDEXER_VIEW = "populating indexer view"; //$NON-NLS-1$ - protected IndexerNodeParent invisibleRoot; - - protected boolean displayForwards=false; - protected boolean displayBackwards=false; - - private class InitializeView extends Job { - private static final String NULL_PROJECT_SELECTED = "A null project was selected."; //$NON-NLS-1$ - private static final String ALL_NAME_SEARCH = "*"; //$NON-NLS-1$ - private static final String INDEXER_VIEW = "Indexer View"; //$NON-NLS-1$ - TableViewer theViewer = null; - - public InitializeView(String name, TableViewer viewer) { - super(name); - this.theViewer = viewer; - } - - protected IStatus run(IProgressMonitor monitor) { - - for(int i=0; i 0) { - TableItem[] selection = new TableItem[1]; - selection[0] = view.getTable().getItems()[0]; - - // select the first item to prevent it from being selected accidentally (and possibly switching editors accidentally) - view.getTable().setSelection(selection); - } - - enableButtons(true); - previousPageAction.setEnabled(displayBackwards); - nextPageAction.setEnabled(displayForwards); - } - } - - private class StartInitializingIndexerView extends Job { - private static final String INITIALIZE_INDEXER_VIEW = "initialize Indexer View"; //$NON-NLS-1$ - InitializeView job = null; - boolean updateView=true; - - public StartInitializingIndexerView(InitializeView job, boolean updateView) { - super(INITIALIZE_INDEXER_VIEW); - this.job = job; - this.updateView = updateView; - } - - protected IStatus run(IProgressMonitor monitor) { - job.schedule(); - - try { - job.join(); - } catch (InterruptedException ie) { - return Status.CANCEL_STATUS; - } - - CTestPlugin.getStandardDisplay().asyncExec(new InitializeRunnable(viewer, updateView)); // update the view from the Display thread - - updateView=true; - - return job.getResult(); - } - } - - public ViewContentProvider() { - this(null, false, false); - } - - public void setDisplayForwards(boolean displayForwards) { - this.displayForwards = displayForwards; - } - - public void setDisplayBackwards(boolean displayBackwards) { - this.displayBackwards = displayBackwards; - } - - public ViewContentProvider(IndexerNodeParent parent, boolean displayForwards, boolean displayBackwards) { - if (parent == null) { - invisibleRoot = new IndexerNodeParent(null, null, this); - initializeIndexerViewJob = new StartInitializingIndexerView(new InitializeView(POPULATING_INDEXER_VIEW, viewer), true); - initializeIndexerViewJob.schedule(); - } else { - invisibleRoot = parent; - initializeIndexerViewJob = new StartInitializingIndexerView(new InitializeView(POPULATING_INDEXER_VIEW, viewer), false); - initializeIndexerViewJob.schedule(); - } - - invisibleRoot.reset(); - this.displayForwards=displayForwards; - this.displayBackwards=displayBackwards; - } - - public Object[] getElements(Object inputElement) { - if (inputElement.equals(getViewSite())) { - return getChildren(invisibleRoot); - } - return getChildren(inputElement); - } - - public void dispose() {} - - public void inputChanged(Viewer aViewer, Object oldInput, Object newInput) { - // TODO Auto-generated method stub - } - - public Object[] getChildren(Object parentElement) { - if (parentElement instanceof IndexerNodeParent) { - return ((IndexerNodeParent) parentElement).getChildren(); - } - return new Object[0]; - } - - public Object getParent(Object element) { - if (element instanceof IndexerNodeLeaf) { - return ((IndexerNodeLeaf) element).getParent(); - } - return null; - } - - public boolean hasChildren(Object element) { - if (element instanceof IndexerNodeParent) - return ((IndexerNodeParent) element).hasChildren(); - return false; - } - - public IndexerNodeParent getInvisibleRoot() { - return invisibleRoot; - } - - public boolean isDisplayForwards() { - return displayForwards; - } - - public boolean isDisplayBackwards() { - return displayBackwards; - } - - public String getProjectName() { - if (project == null) return BLANK_STRING; - - return project.getName(); - } - } - - class ViewLabelProvider extends LabelProvider { - - public String getText(Object obj) { - if (obj == null) return BLANK_STRING; - return obj.toString(); - } - - public Image getImage(Object obj) { - if (obj instanceof IndexerNodeLeaf) { - IEntryResult result = ((IndexerNodeLeaf)obj).getResult(); - int index = getKey(result.getMetaKind(), result.getKind(), result.getRefKind()); - if (index > -1) - return IndexerViewPluginImages.get(index); - } - - return IndexerViewPluginImages.get(IndexerViewPluginImages.IMG_WARNING); - } - } - - public void createPartControl(Composite parent) { - viewer = new TableViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL); - - viewer.setContentProvider(new ViewContentProvider()); - - viewer.setLabelProvider(new ViewLabelProvider()); - viewer.setInput(getViewSite()); - - makeActions(); - hookContextMenu(); - hookSingleClickAction(); - - contributeToActionBars(); - } - - protected void enableButtons(boolean value) { - setFiltersAction.setEnabled(value); - setFiltersAction.setEnabled(value); - sortAction.setEnabled(value); - displayFullNameAction.setEnabled(value); - } - - private void makeActions() { - searchLocationAction = new SearchLocationsAction(); - searchLocationAction.setText(SEARCH_LOCATIONS); - searchLocationAction.setToolTipText(SEARCH_LOCATIONS); - searchLocationAction.setImageDescriptor(IndexerViewPluginImages.DESC_SEARCH_LOCATION); - - previousPageAction = new Action() { - public void run() { - if (viewer.getContentProvider() instanceof ViewContentProvider) { - IndexerNodeParent root = ((ViewContentProvider)viewer.getContentProvider()).getInvisibleRoot(); - root.setIsForward(false); - root.setNavigate(true); - } - viewer.refresh(); - - setEnabled(((ViewContentProvider)viewer.getContentProvider()).isDisplayBackwards()); - nextPageAction.setEnabled(((ViewContentProvider)viewer.getContentProvider()).isDisplayForwards()); - } - }; - previousPageAction.setText(PREVIOUS_PAGE); - previousPageAction.setToolTipText(PREVIOUS_PAGE); - previousPageAction.setImageDescriptor(IndexerViewPluginImages.DESC_BACK); - - nextPageAction = new Action() { - public void run() { - if (viewer.getContentProvider() instanceof ViewContentProvider) { - IndexerNodeParent root = ((ViewContentProvider)viewer.getContentProvider()).getInvisibleRoot(); - root.setIsForward(true); - root.setNavigate(true); - } - viewer.refresh(); - - previousPageAction.setEnabled(((ViewContentProvider)viewer.getContentProvider()).isDisplayBackwards()); - setEnabled(((ViewContentProvider)viewer.getContentProvider()).isDisplayForwards()); - } - }; - nextPageAction.setText(NEXT_PAGE); - nextPageAction.setToolTipText(NEXT_PAGE); - nextPageAction.setImageDescriptor(IndexerViewPluginImages.DESC_NEXT); - - setFiltersAction = new Action() { - public void run() { - if (!(viewer.getContentProvider() instanceof ViewContentProvider)) return; - - FilterIndexerViewDialog dialog = new FilterIndexerViewDialog(getSite().getShell(), ((ViewContentProvider)viewer.getContentProvider()).getInvisibleRoot(), (project==null?BLANK_STRING:project.getName())); - int result = dialog.open(); - - if (result == IDialogConstants.OK_ID) { - // reset the view but remember the buttons being displayed from the old content provider - ((ViewContentProvider)viewer.getContentProvider()).getInvisibleRoot().reset(); - viewer.refresh(); - } - } - }; - setFiltersAction.setText(SET_FILTERS); - setFiltersAction.setToolTipText(SET_FILTERS); - setFiltersAction.setImageDescriptor(IndexerViewPluginImages.DESC_FILTER_BUTTON); - - sortAction = new Action() { - public void run() { - if (viewer.getContentProvider() instanceof ViewContentProvider) { - enableButtons(false); - if (((ViewContentProvider)viewer.getContentProvider()).getInvisibleRoot().isSort()) { - ((ViewContentProvider)viewer.getContentProvider()).getInvisibleRoot().setSort(false); - ((ViewContentProvider)viewer.getContentProvider()).getInvisibleRoot().reset(); - viewer.refresh(); - this.setImageDescriptor(IndexerViewPluginImages.DESC_SORT); - } else { - ((ViewContentProvider)viewer.getContentProvider()).getInvisibleRoot().setSort(true); - ((ViewContentProvider)viewer.getContentProvider()).getInvisibleRoot().reset(); - viewer.refresh(); - this.setImageDescriptor(IndexerViewPluginImages.DESC_SORTED); - } - enableButtons(true); - } - } - }; - sortAction.setText(SORT_RESULTS); - sortAction.setToolTipText(SORT_RESULTS); - sortAction.setImageDescriptor(IndexerViewPluginImages.DESC_SORTED); - - displayFullNameAction = new Action() { - public void run() { - if (viewer.getContentProvider() instanceof ViewContentProvider) { - if (((ViewContentProvider)viewer.getContentProvider()).getInvisibleRoot().isDisplayFullName()) { - ((ViewContentProvider)viewer.getContentProvider()).getInvisibleRoot().setDisplayFullName(false); - viewer.refresh(); - this.setImageDescriptor(IndexerViewPluginImages.DESC_DISPLAY_FULL_NAME); - } else { - ((ViewContentProvider)viewer.getContentProvider()).getInvisibleRoot().setDisplayFullName(true); - viewer.refresh(); - this.setImageDescriptor(IndexerViewPluginImages.DESC_FULL_NAME_DISPLAYED); - } - } - } - }; - displayFullNameAction.setText(SWITCH_FULL_NAMES); - displayFullNameAction.setToolTipText(SWITCH_FULL_NAMES); - displayFullNameAction.setImageDescriptor(IndexerViewPluginImages.DESC_FULL_NAME_DISPLAYED); - - displayStatsAction = new Action() { - public void run() { - CTestPlugin.getStandardDisplay().asyncExec(new Runnable() { - public void run() { - if (viewer.getContentProvider() instanceof ViewContentProvider) { - IndexerNodeParent root = ((ViewContentProvider)viewer.getContentProvider()).getInvisibleRoot(); - - MessageDialog.openInformation(getSite().getShell(), INDEXER_STATS, - root.getFilteredCount() + _FILTERED_IENTRY_RESULTS_ + root.getFullLength() + _TOTAL_IENTRYRESULTS + root.getTotalNumberOfFilesIndexed() + _TOTAL_INDEXEDFILES); - } - } - }); - } - }; - displayStatsAction.setText(DISPLAY_INDEX_STATS); - displayStatsAction.setToolTipText(DISPLAY_INDEX_STATS); - displayStatsAction.setImageDescriptor(IndexerViewPluginImages.DESC_STATS); - - singleClickAction = new IndexerHighlighterAction(); - } - - private void hookContextMenu() { - MenuManager menuMgr = new MenuManager(_INDEXER_MENU_MANAGER); - menuMgr.setRemoveAllWhenShown(true); - menuMgr.addMenuListener(new IMenuListener() { - private void hideMenuItems(IMenuManager manager) { - } - - public void menuAboutToShow(IMenuManager manager) { - IndexerView.this.fillContextMenu(manager); - hideMenuItems(manager); - } - }); - Menu menu = menuMgr.createContextMenu(viewer.getControl()); - viewer.getControl().setMenu(menu); - getSite().registerContextMenu(menuMgr, viewer); - } - - void fillContextMenu(IMenuManager manager) { - manager.add(searchLocationAction); - manager.add(new Separator()); - // Other plug-ins can contribute there actions here - manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS)); - } - - private class IndexerHighlighterAction extends Action { - public void run() { - ISelection selection = viewer.getSelection(); - - IViewPart part = getSite().getPage().findView(PROPERTIES_VIEW); - if (part instanceof PropertySheet) { - ((PropertySheet)part).selectionChanged(getSite().getPart(), selection); - } - } - } - - private void hookSingleClickAction() { - viewer.addSelectionChangedListener(new ISelectionChangedListener() { - public void selectionChanged(SelectionChangedEvent event) { - singleClickAction.run(); - } - }); - } - - private void contributeToActionBars() { - IActionBars bars = getViewSite().getActionBars(); - fillLocalPullDown(bars.getMenuManager()); - fillLocalToolBar(bars.getToolBarManager()); - } - - private void fillLocalPullDown(IMenuManager manager) {} - - private void fillLocalToolBar(IToolBarManager manager) { - manager.add(previousPageAction); - manager.add(nextPageAction); - manager.add(new Separator()); - manager.add(sortAction); - manager.add(displayFullNameAction); - manager.add(setFiltersAction); - manager.add(new Separator()); - manager.add(displayStatsAction); - manager.add(new Separator()); - } - - public void setFocus() { - IViewPart part = getSite().getPage().findView(PROPERTIES_VIEW); - if (part instanceof PropertySheet) { - ((PropertySheet)part).selectionChanged(getSite().getPart(), viewer.getSelection()); - } - } - - public void appendIndexer(ICDTIndexer indexer) { -// indexers = (IIndexer[])ArrayUtil.append(IIndexer.class, indexers, indexer); - // only support 1 indexer for now - indexers[0] = indexer; - } - - public void clearIndexers() { - // for now only support 1 indexer at a time - indexers = new ICDTIndexer[1]; - } - - public void setContentProvider(ViewContentProvider provider) { - viewer.setContentProvider(provider); - } - - public void setProject(IProject project) { - this.setPartName(INDEXER_VIEW___ + project.getName()); - this.project=project; - } - - public static ViewerFilter[] getViewerFilters() { - return viewer.getFilters(); - } - - public String getProjectName() { - if (project == null) return BLANK_STRING; - - return project.getName(); - } - - private class SearchLocationsAction extends Action { - private static final String LOCATIONS = "Locations"; //$NON-NLS-1$ - private static final String INDEX = "Index"; //$NON-NLS-1$ - protected void displayLocations(IndexerNodeLeaf leaf, String queryLabel, String pattern) { - IndexerQuery job = new IndexerQuery(leaf, queryLabel, pattern); - NewSearchUI.activateSearchResultView(); - NewSearchUI.runQueryInBackground(job); - } - - public void run() { - if (viewer.getSelection() instanceof IStructuredSelection && - ((IStructuredSelection)viewer.getSelection()).getFirstElement() instanceof IndexerNodeLeaf) { - displayLocations((IndexerNodeLeaf)((IStructuredSelection)viewer.getSelection()).getFirstElement(), - INDEX, LOCATIONS); - } - } - } - - public static int getKey(int meta, int kind, int ref) { - switch (ref) { - case IIndex.REFERENCE : - switch (meta) { - case IIndex.TYPE : return FilterIndexerViewDialog.ENTRY_TYPE_REF; - case IIndex.FUNCTION : return FilterIndexerViewDialog.ENTRY_FUNCTION_REF; - case IIndex.METHOD : return FilterIndexerViewDialog.ENTRY_METHOD_REF; - case IIndex.FIELD : return FilterIndexerViewDialog.ENTRY_FIELD_REF; - case IIndex.MACRO : return -1; - case IIndex.NAMESPACE : return FilterIndexerViewDialog.ENTRY_NAMESPACE_REF; - case IIndex.ENUMTOR : return FilterIndexerViewDialog.ENTRY_ENUMTOR_REF; - case IIndex.INCLUDE : return FilterIndexerViewDialog.ENTRY_INCLUDE_REF; - case IIndex.VAR : return FilterIndexerViewDialog.ENTRY_TYPE_DECL_VAR; - } - break; - case IIndex.DEFINITION : - case IIndex.DECLARATION : - switch (meta) { - case IIndex.TYPE : - switch (kind) { - case IIndex.TYPE_CLASS : return FilterIndexerViewDialog.ENTRY_TYPE_DECL_CLASS; - case IIndex.TYPE_STRUCT : return FilterIndexerViewDialog.ENTRY_TYPE_DECL_STRUCT; - case IIndex.TYPE_UNION : return FilterIndexerViewDialog.ENTRY_TYPE_DECL_UNION; - case IIndex.TYPE_ENUM : return FilterIndexerViewDialog.ENTRY_TYPE_DECL_ENUM; - case IIndex.TYPE_TYPEDEF : return FilterIndexerViewDialog.ENTRY_TYPE_DECL_TYPEDEF; - case IIndex.TYPE_DERIVED : return FilterIndexerViewDialog.ENTRY_TYPE_DECL_DERIVED; - case IIndex.TYPE_FRIEND : return FilterIndexerViewDialog.ENTRY_TYPE_DECL_FRIEND; - } - case IIndex.FUNCTION : return FilterIndexerViewDialog.ENTRY_FUNCTION_DECL; - case IIndex.METHOD : return FilterIndexerViewDialog.ENTRY_METHOD_DECL; - case IIndex.FIELD : return FilterIndexerViewDialog.ENTRY_FIELD_DECL; - case IIndex.MACRO : return FilterIndexerViewDialog.ENTRY_MACRO_DECL; - case IIndex.NAMESPACE : return FilterIndexerViewDialog.ENTRY_NAMESPACE_DECL; - case IIndex.ENUMTOR : return FilterIndexerViewDialog.ENTRY_ENUMTOR_DECL; - case IIndex.INCLUDE : return -1; - case IIndex.VAR : return FilterIndexerViewDialog.ENTRY_TYPE_DECL_VAR; - } - break; - } - return 0; - } -} diff --git a/core/org.eclipse.cdt.ui.tests/src/org/eclipse/cdt/ui/tests/IndexerView/IndexerViewPluginImages.java b/core/org.eclipse.cdt.ui.tests/src/org/eclipse/cdt/ui/tests/IndexerView/IndexerViewPluginImages.java deleted file mode 100644 index 663a445838d..00000000000 --- a/core/org.eclipse.cdt.ui.tests/src/org/eclipse/cdt/ui/tests/IndexerView/IndexerViewPluginImages.java +++ /dev/null @@ -1,150 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.ui.tests.IndexerView; - -import java.net.MalformedURLException; -import java.net.URL; - -import org.eclipse.cdt.ui.CUIPlugin; -import org.eclipse.cdt.ui.testplugin.CTestPlugin; -import org.eclipse.jface.resource.ImageDescriptor; -import org.eclipse.jface.resource.ImageRegistry; -import org.eclipse.swt.graphics.Image; -import org.eclipse.swt.widgets.Display; - -/** - * @author dsteffle - */ -public class IndexerViewPluginImages { - private static ImageRegistry imageRegistry = new ImageRegistry(CUIPlugin.getStandardDisplay()); - - /** - * Returns the standard display to be used. The method first checks, if - * the thread calling this method has an associated display. If so, this - * display is returned. Otherwise the method returns the default display. - */ - public static Display getStandardDisplay() { - Display display= Display.getCurrent(); - if (display == null) { - display= Display.getDefault(); - } - return display; - } - - // Subdirectory (under the package containing this class) where 16 color images are - private static URL fgIconBaseURL; - - static { - try { - fgIconBaseURL= new URL(CTestPlugin.getDefault().getBundle().getEntry("/"), "icons/" ); //$NON-NLS-1$ //$NON-NLS-2$ - } catch (MalformedURLException e) {} - } - public static final String PLUGIN_ID = "org.eclipse.cdt.testplugin.CTestPlugin"; //$NON-NLS-1$ - public static final String NAME_PREFIX= PLUGIN_ID + '.'; - private static final int NAME_PREFIX_LENGTH= NAME_PREFIX.length(); - public static final String ICON_PREFIX= "indexer_view/"; //$NON-NLS-1$ - - public static final String [] icon_images = { - "macroDecl_obj.gif", - "function_obj.gif", - "namespace_obj.gif", - "function_ref_obj.gif", - "namespace_ref_obj.gif", - "field_obj.gif", - "enumerator_obj.gif", - "method_public_obj.gif", - "field_ref_obj.gif", - "enumerator_ref_obj.gif", - "method_public_ref_obj.gif", - "typedecl_ref_obj.gif", - "typedef_obj.gif", - "class_obj.gif", - "variable_obj.gif", - "struct_obj.gif", - "enum_obj.gif", - "union_obj.gif", - "derived.gif", - "friend.gif", - "include_obj.gif" - }; - - public static final String IMG_REF= NAME_PREFIX + "ref_obj.gif"; //$NON-NLS-1$ - public static final String IMG_TYPE_DECL= NAME_PREFIX + "typedecl_obj.gif"; //$NON-NLS-1$ - public static final String IMG_SUPER_REF= NAME_PREFIX + "super_co.gif"; //$NON-NLS-1$ - public static final String IMG_BACK= NAME_PREFIX + "ngback.gif"; //$NON-NLS-1$ - public static final String IMG_NEXT= NAME_PREFIX + "ngnext.gif"; //$NON-NLS-1$ - public static final String IMG_WARNING= NAME_PREFIX + "warning_icon.gif"; //$NON-NLS-1$ - public static final String IMG_FILTER_BUTTON= NAME_PREFIX + "filterbutton.gif"; //$NON-NLS-1$ - public static final String IMG_STATS= NAME_PREFIX + "stats.gif"; //$NON-NLS-1$ - public static final String IMG_GROUPED_ALL= NAME_PREFIX + "grouped_all.gif"; //$NON-NLS-1$ - public static final String IMG_GROUPED_DECL= NAME_PREFIX + "grouped_decl.gif"; //$NON-NLS-1$ - public static final String IMG_GROUPED_REF= NAME_PREFIX + "grouped_ref.gif"; //$NON-NLS-1$ - public static final String IMG_GROUPED_TYPE= NAME_PREFIX + "grouped_type.gif"; //$NON-NLS-1$ - public static final String IMG_SEARCH_LOCATION= NAME_PREFIX + "search_decl_obj.gif"; //$NON-NLS-1$ - public static final String IMG_SORT= NAME_PREFIX + "alphab_sort.gif"; //$NON-NLS-1$ - public static final String IMG_SORTED= NAME_PREFIX + "alphab_sorted.gif"; //$NON-NLS-1$ - public static final String IMG_FULL_NAME_DISPLAYED= NAME_PREFIX + "full_name_displayed.gif"; //$NON-NLS-1$ - public static final String IMG_DISPLAY_FULL_NAME= NAME_PREFIX + "display_full_name.gif"; //$NON-NLS-1$ - - public static final ImageDescriptor DESC_REF= createManaged(ICON_PREFIX, IMG_REF); - static { - for (int i = 0 ; i < icon_images.length; i++) { - createManaged(ICON_PREFIX, NAME_PREFIX + icon_images[i]); - } - createManaged(ICON_PREFIX, IMG_TYPE_DECL); - createManaged(ICON_PREFIX, IMG_SUPER_REF); - createManaged(ICON_PREFIX, IMG_WARNING); - createManaged(ICON_PREFIX, IMG_GROUPED_ALL); - createManaged(ICON_PREFIX, IMG_GROUPED_DECL); - createManaged(ICON_PREFIX, IMG_GROUPED_REF); - createManaged(ICON_PREFIX, IMG_GROUPED_TYPE); - } - - public static final ImageDescriptor DESC_BACK= createManaged(ICON_PREFIX, IMG_BACK); - public static final ImageDescriptor DESC_NEXT= createManaged(ICON_PREFIX, IMG_NEXT); - public static final ImageDescriptor DESC_FILTER_BUTTON= createManaged(ICON_PREFIX, IMG_FILTER_BUTTON); - public static final ImageDescriptor DESC_STATS= createManaged(ICON_PREFIX, IMG_STATS); - public static final ImageDescriptor DESC_SEARCH_LOCATION= createManaged(ICON_PREFIX, IMG_SEARCH_LOCATION); - public static final ImageDescriptor DESC_SORT= createManaged(ICON_PREFIX, IMG_SORT); - public static final ImageDescriptor DESC_SORTED= createManaged(ICON_PREFIX, IMG_SORTED); - public static final ImageDescriptor DESC_FULL_NAME_DISPLAYED= createManaged(ICON_PREFIX, IMG_FULL_NAME_DISPLAYED); - public static final ImageDescriptor DESC_DISPLAY_FULL_NAME= createManaged(ICON_PREFIX, IMG_DISPLAY_FULL_NAME); - - private static ImageDescriptor createManaged(String prefix, String name) { - return createManaged(imageRegistry, prefix, name); - } - - private static ImageDescriptor createManaged(ImageRegistry registry, String prefix, String name) { - ImageDescriptor result= ImageDescriptor.createFromURL(makeIconFileURL(prefix, name.substring(NAME_PREFIX_LENGTH))); - registry.put(name, result); - return result; - } - - private static URL makeIconFileURL(String prefix, String name) { - StringBuffer buffer= new StringBuffer(prefix); - buffer.append(name); - try { - return new URL(fgIconBaseURL, buffer.toString()); - } catch (MalformedURLException e) { - CUIPlugin.getDefault().log(e); - return null; - } - } - - public static Image get(String key) { - return imageRegistry.get(key); - } - public static Image get(int key) { - return imageRegistry.get(NAME_PREFIX + icon_images[key]); - } - - -} diff --git a/core/org.eclipse.cdt.ui.tests/src/org/eclipse/cdt/ui/tests/IndexerView/OpenIndexerViewAction.java b/core/org.eclipse.cdt.ui.tests/src/org/eclipse/cdt/ui/tests/IndexerView/OpenIndexerViewAction.java deleted file mode 100644 index 777e77c2053..00000000000 --- a/core/org.eclipse.cdt.ui.tests/src/org/eclipse/cdt/ui/tests/IndexerView/OpenIndexerViewAction.java +++ /dev/null @@ -1,80 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.ui.tests.IndexerView; - -import org.eclipse.cdt.core.CCorePlugin; -import org.eclipse.cdt.core.index.ICDTIndexer; -import org.eclipse.cdt.internal.core.model.CProject; -import org.eclipse.core.resources.IProject; -import org.eclipse.jface.action.IAction; -import org.eclipse.jface.viewers.ISelection; -import org.eclipse.jface.viewers.IStructuredSelection; -import org.eclipse.ui.IEditorActionDelegate; -import org.eclipse.ui.IEditorPart; -import org.eclipse.ui.IObjectActionDelegate; -import org.eclipse.ui.IViewActionDelegate; -import org.eclipse.ui.IViewPart; -import org.eclipse.ui.IWorkbenchPart; -import org.eclipse.ui.PartInitException; - -/** - * @author dsteffle - */ -public class OpenIndexerViewAction implements IViewActionDelegate, - IEditorActionDelegate, IObjectActionDelegate { - - IViewPart viewPart = null; - IProject proj = null; - public static int numViewsOpen=0; - - public void init(IViewPart view) { - this.viewPart = view; - } - - public void run(IAction action) { - IViewPart tempView = null; - - try { - tempView = viewPart.getSite().getPage().showView(IndexerView.VIEW_ID); - if (tempView instanceof IndexerView) - ((IndexerView)tempView).setProject(proj); - - OpenIndexerViewAction.numViewsOpen++; - } catch (PartInitException pie) {} - - if (tempView != null) { - if (tempView instanceof IndexerView) { - ((IndexerView)tempView).clearIndexers(); - ICDTIndexer indexer = CCorePlugin.getDefault().getCoreModel().getIndexManager().getIndexerForProject(proj); - ((IndexerView)tempView).appendIndexer(indexer); - ((IndexerView)tempView).setContentProvider(((IndexerView)tempView).new ViewContentProvider()); - } - } - - viewPart.getSite().getPage().activate(tempView); - } - - public void selectionChanged(IAction action, ISelection selection) { - if (selection instanceof IStructuredSelection && - ((IStructuredSelection)selection).getFirstElement() instanceof CProject) { - proj = ((CProject)((IStructuredSelection)selection).getFirstElement()).getProject(); - } - } - - public void setActiveEditor(IAction action, IEditorPart targetEditor) { - // TODO Auto-generated method stub - } - - public void setActivePart(IAction action, IWorkbenchPart targetPart) { - // TODO Auto-generated method stub - } - -} diff --git a/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/AutomatedSuite.java b/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/AutomatedSuite.java index b524a06b5cc..7e2d3aa2bd8 100644 --- a/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/AutomatedSuite.java +++ b/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/AutomatedSuite.java @@ -13,7 +13,6 @@ package org.eclipse.cdt.ui.tests; import junit.framework.Test; import junit.framework.TestSuite; -import org.eclipse.cdt.ui.tests.regression.RegressionTestsUISuite; import org.eclipse.cdt.ui.tests.text.contentassist.CompletionFailedTest_MemberReference_Arrow_Prefix2; import org.eclipse.cdt.ui.tests.text.contentassist.CompletionTest_ArgumentType_NoPrefix; import org.eclipse.cdt.ui.tests.text.contentassist.CompletionTest_ArgumentType_NoPrefix2; @@ -121,7 +120,6 @@ public class AutomatedSuite extends TestSuite { addTest(CompletionTest_VariableType_NestedPrefix.suite()); addTest( ContentAssistTests.suite() ); - addTest( RegressionTestsUISuite.suite() ); // Failed Tests addTest(CompletionFailedTest_MemberReference_Arrow_Prefix2.suite()); @@ -136,4 +134,3 @@ public class AutomatedSuite extends TestSuite { } } - diff --git a/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/regression/ContentAssistRegressionTests.java b/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/regression/ContentAssistRegressionTests.java deleted file mode 100644 index 23c4282f5ef..00000000000 --- a/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/regression/ContentAssistRegressionTests.java +++ /dev/null @@ -1,1853 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ - -/* - * Created on Oct 4, 2004 - */ -package org.eclipse.cdt.ui.tests.regression; - -import java.io.StringWriter; - -import junit.framework.Test; -import junit.framework.TestSuite; - -import org.eclipse.cdt.core.model.CModelException; -import org.eclipse.cdt.core.model.CoreModel; -import org.eclipse.cdt.core.model.ITranslationUnit; -import org.eclipse.cdt.core.model.IWorkingCopy; -import org.eclipse.cdt.core.tests.BaseTestFramework; -import org.eclipse.cdt.core.tests.FailingTest; -import org.eclipse.cdt.internal.core.browser.cache.TypeCacheManager; -import org.eclipse.cdt.internal.ui.CHelpProviderManager; -import org.eclipse.cdt.internal.ui.text.CHelpBookDescriptor; -import org.eclipse.cdt.internal.ui.text.contentassist.CCompletionProcessor; -import org.eclipse.cdt.ui.text.ICHelpInvocationContext; -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IResource; -import org.eclipse.jface.text.Document; -import org.eclipse.jface.text.contentassist.ICompletionProposal; - -/** - * @author aniefer - */ -public class ContentAssistRegressionTests extends BaseTestFramework { - static boolean disabledHelpContributions = false; - final int TIMEOUT = 100; - public ContentAssistRegressionTests() - { - super(); - } - /** - * @param name - */ - public ContentAssistRegressionTests(String name) - { - super(name); - } - - protected void setUp() throws Exception { - //TEMPORARY: Disable Type Cache - super.setUp(); - TypeCacheManager typeCacheManager = TypeCacheManager.getInstance(); - typeCacheManager.setProcessTypeCacheEvents(false); - } - - private void disableContributions (){ - //disable the help books so we don't get proposals we weren't expecting - final IProject proj = project; - CHelpBookDescriptor helpBooks[]; - helpBooks = CHelpProviderManager.getDefault().getCHelpBookDescriptors(new ICHelpInvocationContext(){ - public IProject getProject(){return proj;} - public ITranslationUnit getTranslationUnit(){return null;} - } - ); - for( int i = 0; i < helpBooks.length; i++ ){ - if( helpBooks[i] != null ) - helpBooks[i].enable( false ); - } - } - protected ICompletionProposal[] getResults( IFile file, int offset ) throws Exception { - if( !disabledHelpContributions ) - disableContributions(); - ITranslationUnit tu = (ITranslationUnit)CoreModel.getDefault().create( file ); - String buffer = tu.getBuffer().getContents(); - IWorkingCopy wc = null; - try{ - wc = tu.getWorkingCopy(); - }catch (CModelException e){ - fail("Failed to get working copy"); //$NON-NLS-1$ - } - - // call the CompletionProcessor - CCompletionProcessor completionProcessor = new CCompletionProcessor(null); - ICompletionProposal[] results = completionProcessor.evalProposals( new Document(buffer), offset, wc, null); - //This should be replaced with a notification from the CCompletionProcessor - Thread.sleep(TIMEOUT); - return ( results != null ? results : new ICompletionProposal [0] ); - } - - public static Test suite(){ - return suite( true ); - } - public static Test suite( boolean cleanup ) { - TestSuite suite = new TestSuite("ContentAssistRegressionTests"); //$NON-NLS-1$ - suite.addTest( new ContentAssistRegressionTests("testMemberCompletion") ); //$NON-NLS-1$ - suite.addTest( new ContentAssistRegressionTests("testUnqualifiedWithPrefix") ); //$NON-NLS-1$ - suite.addTest( new ContentAssistRegressionTests("testQualifiedWithPrefix") ); //$NON-NLS-1$ - suite.addTest( new FailingTest(new ContentAssistRegressionTests("test76398"),76398) ); //$NON-NLS-1$ - suite.addTest( new ContentAssistRegressionTests("testQualifiedNoPrefix") ); //$NON-NLS-1$ - suite.addTest( new ContentAssistRegressionTests("testSourceExtensions") ); //$NON-NLS-1$ - suite.addTest( new FailingTest(new ContentAssistRegressionTests("test76480"),76480) ); //$NON-NLS-1$ - suite.addTest( new ContentAssistRegressionTests("testField") ); //$NON-NLS-1$ - suite.addTest( new ContentAssistRegressionTests("testFieldExpression") ); //$NON-NLS-1$ - suite.addTest( new ContentAssistRegressionTests("testScope") ); //$NON-NLS-1$ - suite.addTest( new ContentAssistRegressionTests("testClass") ); //$NON-NLS-1$ - suite.addTest( new FailingTest(new ContentAssistRegressionTests("test72723"),72723) ); //$NON-NLS-1$ - suite.addTest( new FailingTest(new ContentAssistRegressionTests("test72541"),72541) ); //$NON-NLS-1$ - suite.addTest( new ContentAssistRegressionTests("testFunction") ); //$NON-NLS-1$ - suite.addTest( new ContentAssistRegressionTests("testArgument") ); //$NON-NLS-1$ - suite.addTest( new FailingTest(new ContentAssistRegressionTests("test76805"),76805) ); //$NON-NLS-1$ - suite.addTest( new ContentAssistRegressionTests("testCStyleCast") ); //$NON-NLS-1$ - suite.addTest( new ContentAssistRegressionTests("testMethod") ); //$NON-NLS-1$ - suite.addTest( new ContentAssistRegressionTests("testEnumerations") ); //$NON-NLS-1$ - suite.addTest( new ContentAssistRegressionTests("testLongTokens") ); //$NON-NLS-1$ - suite.addTest( new ContentAssistRegressionTests("testCastMultiLevel") ); //$NON-NLS-1$ - suite.addTest( new ContentAssistRegressionTests("testHeaderExtensions") ); //$NON-NLS-1$ - suite.addTest( new ContentAssistRegressionTests("testEmptyDocument") ); //$NON-NLS-1$ - suite.addTest( new ContentAssistRegressionTests("testVariable") ); //$NON-NLS-1$ - suite.addTest( new FailingTest(new ContentAssistRegressionTests("test80510"),80510) ); //$NON-NLS-1$ - suite.addTest( new ContentAssistRegressionTests("testSingleNameReference") ); //$NON-NLS-1$ - suite.addTest( new ContentAssistRegressionTests("testNamespace") ); //$NON-NLS-1$ - suite.addTest( new FailingTest(new ContentAssistRegressionTests("testNamespaceAlias80612"),80612) ); //$NON-NLS-1$ - suite.addTest( new ContentAssistRegressionTests("testMacro") ); //$NON-NLS-1$ - suite.addTest( new ContentAssistRegressionTests("testConstructor") ); //$NON-NLS-1$ - suite.addTest( new ContentAssistRegressionTests("testUnion") ); //$NON-NLS-1$ - suite.addTest( new ContentAssistRegressionTests("testKeyword") ); //$NON-NLS-1$ - suite.addTest( new ContentAssistRegressionTests("testBase") ); //$NON-NLS-1$ - suite.addTest( new ContentAssistRegressionTests("testThis") ); //$NON-NLS-1$ - suite.addTest( new ContentAssistRegressionTests("testClassScope") ); //$NON-NLS-1$ - suite.addTest( new FailingTest(new ContentAssistRegressionTests("testClassScope72564"),72564) ); //$NON-NLS-1$ - suite.addTest( new ContentAssistRegressionTests("testMultiLevelQualifiers") ); //$NON-NLS-1$ - suite.addTest( new ContentAssistRegressionTests("testCase") ); //$NON-NLS-1$ - suite.addTest( new ContentAssistRegressionTests("testType") ); //$NON-NLS-1$ - suite.addTest( new ContentAssistRegressionTests("testTryCatch") ); //$NON-NLS-1$ - suite.addTest( new ContentAssistRegressionTests("testArrays") ); //$NON-NLS-1$ - suite.addTest( new ContentAssistRegressionTests("testStruct") ); //$NON-NLS-1$ - - //Test framework doesn't include templates - //suite.addTest( new ContentAssistRegressionTests("testCodeTemplate") ); //$NON-NLS-1$ - - if( cleanup ) - suite.addTest( new ContentAssistRegressionTests("cleanupProject") ); //$NON-NLS-1$ - - return suite; - } - - public void removeFile(String filename) throws Exception { - IResource [] members = project.members(); - for( int i = 0; i < members.length; i++ ){ - if( members[i].getName().equals( filename ) ) - members[i].delete( false, monitor ); - } - } - public void testMemberCompletion() throws Exception { - StringWriter writer = new StringWriter(); - writer.write("class A { \n"); //$NON-NLS-1$ - writer.write(" int var; \n"); //$NON-NLS-1$ - writer.write(" void f(); \n"); //$NON-NLS-1$ - writer.write("}; \n"); //$NON-NLS-1$ - writer.write("void A::f(){ \n"); //$NON-NLS-1$ - writer.write(" v[^] \n"); //$NON-NLS-1$ - writer.write("} \n"); //$NON-NLS-1$ - - String code = writer.toString(); - IFile t = importFile( "testMemberCompletion.cpp", code ); //$NON-NLS-1$ - ICompletionProposal [] results = getResults( t, code.indexOf( "[^]" ) ); //$NON-NLS-1$ - - assertEquals( 4, results.length); - assertEquals( "var : int", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( "virtual", results[1].getDisplayString()); //$NON-NLS-1$ - assertEquals( "void", results[2].getDisplayString()); //$NON-NLS-1$ - assertEquals( "volatile", results[3].getDisplayString()); //$NON-NLS-1$ - } - //test 1 with prefix 'z', inside various scopes - public void testUnqualifiedWithPrefix() throws Exception { - StringWriter writer = new StringWriter(); - writer.write("int zVar0; \n"); //$NON-NLS-1$ - writer.write("class zClass { \n"); //$NON-NLS-1$ - writer.write("public: \n"); //$NON-NLS-1$ - writer.write(" zClass(); \n"); //$NON-NLS-1$ - writer.write(" int zField; \n"); //$NON-NLS-1$ - writer.write(" void zMethod(); \n"); //$NON-NLS-1$ - writer.write("}; \n"); //$NON-NLS-1$ - writer.write("void zFunction0(); \n"); //$NON-NLS-1$ - - String codeH = writer.toString(); - importFile( "testUnqualifiedWithPrefix.h", codeH ); //$NON-NLS-1$ - - writer = new StringWriter(); - writer.write("#include \"testUnqualifiedWithPrefix.h\" \n"); //$NON-NLS-1$ - writer.write("int zVar; \n"); //$NON-NLS-1$ - writer.write("void zFunction(bool); \n"); //$NON-NLS-1$ - writer.write("struct zStruct { int b;}; \n"); //$NON-NLS-1$ - writer.write("zClass c;//vp1 \n"); //$NON-NLS-1$ - writer.write("namespace test { \n"); //$NON-NLS-1$ - writer.write(" zStruct s;//vp2 \n"); //$NON-NLS-1$ - writer.write(" const int zVar = zVar0 + zVar;//vp3 \n"); //$NON-NLS-1$ - writer.write("} \n"); //$NON-NLS-1$ - writer.write("int main(int argc, char **argv) { \n"); //$NON-NLS-1$ - writer.write(" zVar=0;//vp4 \n"); //$NON-NLS-1$ - writer.write(" using namespace test; \n"); //$NON-NLS-1$ - writer.write(" zClass c2;//vp5 \n"); //$NON-NLS-1$ - writer.write(" ::zVar=0;//vp6 \n"); //$NON-NLS-1$ - writer.write(" test::zVar;//vp7 \n"); //$NON-NLS-1$ - writer.write(" return (0); \n"); //$NON-NLS-1$ - writer.write("} \n"); //$NON-NLS-1$ - writer.write("void zClass::zMethod(){ \n"); //$NON-NLS-1$ - writer.write(" zField=0;//vp8 \n"); //$NON-NLS-1$ - writer.write("} \n"); //$NON-NLS-1$ - String code = writer.toString(); - IFile t = importFile( "testUnqualifiedWithPrefix.cpp", code ); //$NON-NLS-1$ - //vp1 - ICompletionProposal [] results = getResults( t, code.indexOf( "Class c;//vp1" ) ); //$NON-NLS-1$ - assertEquals( 2, results.length); - assertEquals( "zClass", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( "zStruct", results[1].getDisplayString()); //$NON-NLS-1$ - //vp2 - results = getResults( t, code.indexOf( "Struct s;//vp2" ) ); //$NON-NLS-1$ - assertEquals( 2, results.length); - assertEquals( "zClass", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( "zStruct", results[1].getDisplayString()); //$NON-NLS-1$ - //vp3 - results = getResults( t, code.indexOf( "Var0 + zVar;//vp3" ) ); //$NON-NLS-1$ - assertEquals( 6, results.length); - assertEquals( "zVar : int", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( "zVar0 : int", results[1].getDisplayString()); //$NON-NLS-1$ - assertEquals( "zFunction(bool) void", results[2].getDisplayString()); //$NON-NLS-1$ - assertEquals( "zFunction0() void", results[3].getDisplayString()); //$NON-NLS-1$ - assertEquals( "zClass", results[4].getDisplayString()); //$NON-NLS-1$ - assertEquals( "zStruct", results[5].getDisplayString()); //$NON-NLS-1$ - //vp4 - results = getResults( t, code.indexOf( "Var=0;//vp4" ) ); //$NON-NLS-1$ - assertEquals( 6, results.length); - assertEquals( "zVar : int", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( "zVar0 : int", results[1].getDisplayString()); //$NON-NLS-1$ - assertEquals( "zFunction(bool) void", results[2].getDisplayString()); //$NON-NLS-1$ - assertEquals( "zFunction0() void", results[3].getDisplayString()); //$NON-NLS-1$ - assertEquals( "zClass", results[4].getDisplayString()); //$NON-NLS-1$ - assertEquals( "zStruct", results[5].getDisplayString()); //$NON-NLS-1$ - //vp5 zVar is ambiguous so it won't show up - results = getResults( t, code.indexOf( "Class c2;//vp5" ) ); //$NON-NLS-1$ - assertEquals( 5, results.length); - assertEquals( "zVar0 : int", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( "zFunction(bool) void", results[1].getDisplayString()); //$NON-NLS-1$ - assertEquals( "zFunction0() void", results[2].getDisplayString()); //$NON-NLS-1$ - assertEquals( "zClass", results[3].getDisplayString()); //$NON-NLS-1$ - assertEquals( "zStruct", results[4].getDisplayString()); //$NON-NLS-1$ - //vp6 - results = getResults( t, code.indexOf( "Var=0;//vp6" ) ); //$NON-NLS-1$ - assertEquals( 6, results.length); - assertEquals( "zVar : int", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( "zVar0 : int", results[1].getDisplayString()); //$NON-NLS-1$ - //vp7 - results = getResults( t, code.indexOf( "Var;//vp7" ) ); //$NON-NLS-1$ - assertEquals( 1, results.length); - assertEquals( "zVar : const int", results[0].getDisplayString()); //$NON-NLS-1$ - //vp8 - results = getResults( t, code.indexOf( "Field=0;//vp8" ) ); //$NON-NLS-1$ - assertEquals( 8, results.length); - assertEquals( "zField : int", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( "zMethod() void", results[3].getDisplayString()); //$NON-NLS-1$ - - } - //test 2 with prefix 'z', qualified, inside 4 scopes - public void testQualifiedWithPrefix() throws Exception { - StringWriter writer = new StringWriter(); - writer.write("class zClass { \n"); //$NON-NLS-1$ - writer.write(" public: \n"); //$NON-NLS-1$ - writer.write(" zClass(){} \n"); //$NON-NLS-1$ - writer.write(" static const int zField=1; \n"); //$NON-NLS-1$ - writer.write(" void zMethod(); \n"); //$NON-NLS-1$ - writer.write("}; \n"); //$NON-NLS-1$ - writer.write("int zVar0; \n"); //$NON-NLS-1$ - writer.write(" void zFunction0(); \n"); //$NON-NLS-1$ - - String codeH = writer.toString(); - importFile( "testQualifiedWithPrefix.h", codeH ); //$NON-NLS-1$ - - writer = new StringWriter(); - writer.write("#include \"testQualifiedWithPrefix.h\" \n"); //$NON-NLS-1$ - writer.write("zClass c; \n"); //$NON-NLS-1$ - writer.write("int i = c.zField;//vp1-2res \n"); //$NON-NLS-1$ - writer.write("namespace test { \n"); //$NON-NLS-1$ - writer.write(" zClass c; \n"); //$NON-NLS-1$ - writer.write(" int i=c.zField;//vp2-2res \n"); //$NON-NLS-1$ - writer.write("} \n"); //$NON-NLS-1$ - writer.write("int main(int argc, char **argv) { \n"); //$NON-NLS-1$ - writer.write(" c.zField;//vp3-2res \n"); //$NON-NLS-1$ - writer.write(" using namespace test; \n"); //$NON-NLS-1$ - writer.write(" //c.z;//vpxxx defect 76398 \n"); //$NON-NLS-1$ - writer.write(" ::c.zMethod();//vp4-2res \n"); //$NON-NLS-1$ - writer.write(" test::c.zField;//vp5-2res \n"); //$NON-NLS-1$ - writer.write(" return (0); \n"); //$NON-NLS-1$ - writer.write("} \n"); //$NON-NLS-1$ - writer.write("void zClass::zMethod(){ \n"); //$NON-NLS-1$ - writer.write(" zzClass zz; \n"); //$NON-NLS-1$ - writer.write(" zz.zMethod();//vp6 \n"); //$NON-NLS-1$ - writer.write("} \n"); //$NON-NLS-1$ - - String code = writer.toString(); - IFile t = importFile( "testQualifiedWithPrefix.cpp", code ); //$NON-NLS-1$ - //vp1 global scope - ICompletionProposal [] results = getResults( t, code.indexOf( "Field;//vp1" ) ); //$NON-NLS-1$ - assertEquals( 2, results.length); - assertEquals( "zField : const int", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( "zMethod() void", results[1].getDisplayString()); //$NON-NLS-1$ - //vp2 namespace scope - results = getResults( t, code.indexOf( "Field;//vp2" ) ); //$NON-NLS-1$ - assertEquals( 2, results.length); - assertEquals( "zField : const int", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( "zMethod() void", results[1].getDisplayString()); //$NON-NLS-1$ - //vp3 function scope, global class member ref - results = getResults( t, code.indexOf( "Field;//vp3" ) ); //$NON-NLS-1$ - assertEquals( 2, results.length); - assertEquals( "zField : const int", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( "zMethod() void", results[1].getDisplayString()); //$NON-NLS-1$ - //vp4 function scope, ambiguous clarified(global) class member ref - results = getResults( t, code.indexOf( "Method();//vp4" ) ); //$NON-NLS-1$ - assertEquals( 2, results.length); - assertEquals( "zField : const int", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( "zMethod() void", results[1].getDisplayString()); //$NON-NLS-1$ - //vp5 function scope, ambiguous clarified(namespace) class member ref - results = getResults( t, code.indexOf( "Field;//vp5" ) ); //$NON-NLS-1$ - assertEquals( 2, results.length); - assertEquals( "zField : const int", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( "zMethod() void", results[1].getDisplayString()); //$NON-NLS-1$ - //vp6 method scope - results = getResults( t, code.indexOf( "Method();//vp6" ) ); //$NON-NLS-1$ - assertEquals( 2, results.length); - assertEquals( "zField : const int", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( "zMethod() void", results[1].getDisplayString()); //$NON-NLS-1$ - - } - //with prefix 'z', qualified, inside function scope - ////76398 function scope, ambiguous unclarified class member ref - public void test76398() throws Exception { - StringWriter writer = new StringWriter(); - writer.write("class zClass { \n"); //$NON-NLS-1$ - writer.write(" public: \n"); //$NON-NLS-1$ - writer.write(" zClass(){} \n"); //$NON-NLS-1$ - writer.write(" static const int zField=1; \n"); //$NON-NLS-1$ - writer.write(" void zMethod(); \n"); //$NON-NLS-1$ - writer.write("}; \n"); //$NON-NLS-1$ - writer.write("int zVar0; \n"); //$NON-NLS-1$ - writer.write("void zFunction0(); \n"); //$NON-NLS-1$ - writer.write("zClass c; \n"); //$NON-NLS-1$ - writer.write("namespace test { \n"); //$NON-NLS-1$ - writer.write(" zClass c; \n"); //$NON-NLS-1$ - writer.write("} \n"); //$NON-NLS-1$ - writer.write("int main(int argc, char **argv) { \n"); //$NON-NLS-1$ - writer.write(" c.zField;//vp3-function scope,2res \n"); //$NON-NLS-1$ - writer.write(" using namespace test; \n"); //$NON-NLS-1$ - writer.write(" c.z;//76398 \n"); //$NON-NLS-1$ - writer.write(" return (0); \n"); //$NON-NLS-1$ - writer.write("} \n"); //$NON-NLS-1$ - - String code = writer.toString(); - IFile t = importFile( "test76398.cpp", code ); //$NON-NLS-1$ - //should not show completions for zField, zMethod since they are - // ambiguous - //The defect is the zVar0 and zFunction0 and zClass are showing up when - // they shouldn't - ICompletionProposal [] results = getResults( t, code.indexOf( ";//76398" ) ); //$NON-NLS-1$ - assertEquals( 0, results.length); - } -// test 3 without prefix 'z', qualified, inside scopes - public void testQualifiedNoPrefix() throws Exception { - StringWriter writer = new StringWriter(); - writer.write("class zClass { \n"); //$NON-NLS-1$ - writer.write(" public: \n"); //$NON-NLS-1$ - writer.write(" zClass(){} \n"); //$NON-NLS-1$ - writer.write(" static const int zField=1; \n"); //$NON-NLS-1$ - writer.write(" int zMethod(int i); \n"); //$NON-NLS-1$ - writer.write("}; \n"); //$NON-NLS-1$ - writer.write("zClass c; \n"); //$NON-NLS-1$ - writer.write("int i = c.zField;//vp1-2res \n"); //$NON-NLS-1$ - writer.write("namespace test { \n"); //$NON-NLS-1$ - writer.write(" zClass c; \n"); //$NON-NLS-1$ - writer.write(" int i=c.zField;//vp2-2res \n"); //$NON-NLS-1$ - writer.write("} \n"); //$NON-NLS-1$ - writer.write("int main(int argc, char **argv) { \n"); //$NON-NLS-1$ - writer.write(" c.zField;//vp3-2res \n"); //$NON-NLS-1$ - writer.write(" using namespace test; \n"); //$NON-NLS-1$ - writer.write(" ::c.zMethod(3);//vp4-2res \n"); //$NON-NLS-1$ - writer.write(" test::c.zField;//vp5-2res \n"); //$NON-NLS-1$ - writer.write(" return (0); \n"); //$NON-NLS-1$ - writer.write("} \n"); //$NON-NLS-1$ - writer.write("int zClass::zMethod(int i){ \n"); //$NON-NLS-1$ - writer.write(" if (i==0) return (0); \n"); //$NON-NLS-1$ - writer.write(" zClass zz; \n"); //$NON-NLS-1$ - writer.write(" return (zz.zMethod(i-1));//vp6 \n"); //$NON-NLS-1$ - writer.write("} \n"); //$NON-NLS-1$ - - String code = writer.toString(); - IFile t = importFile( "testQualifiedNoPrefix.cpp", code ); //$NON-NLS-1$ - //vp1 global scope - ICompletionProposal [] results = getResults( t, code.indexOf( "zField;//vp1" ) ); //$NON-NLS-1$ - assertEquals( 2, results.length); - assertEquals( "zField : const int", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( "zMethod(int) int", results[1].getDisplayString()); //$NON-NLS-1$ - //vp2 namespace scope - results = getResults( t, code.indexOf( "zField;//vp2" ) ); //$NON-NLS-1$ - assertEquals( 2, results.length); - assertEquals( "zField : const int", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( "zMethod(int) int", results[1].getDisplayString()); //$NON-NLS-1$ - //vp3 function scope, global class member ref - results = getResults( t, code.indexOf( "zField;//vp3" ) ); //$NON-NLS-1$ - assertEquals( 2, results.length); - assertEquals( "zField : const int", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( "zMethod(int) int", results[1].getDisplayString()); //$NON-NLS-1$ - //vp4 function scope, ambiguous clarified(global) class member ref - results = getResults( t, code.indexOf( "zMethod(3);//vp4" ) ); //$NON-NLS-1$ - assertEquals( 2, results.length); - assertEquals( "zField : const int", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( "zMethod(int) int", results[1].getDisplayString()); //$NON-NLS-1$ - //vp5 function scope, ambiguous clarified(namespace) class member ref - results = getResults( t, code.indexOf( "zField;//vp5" ) ); //$NON-NLS-1$ - assertEquals( 2, results.length); - assertEquals( "zField : const int", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( "zMethod(int) int", results[1].getDisplayString()); //$NON-NLS-1$ - //vp6 method scope - results = getResults( t, code.indexOf( "zMethod(i-1));//vp6" ) ); //$NON-NLS-1$ - assertEquals( 2, results.length); - assertEquals( "zField : const int", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( "zMethod(int) int", results[1].getDisplayString()); //$NON-NLS-1$ - - } - // test 7 different file types - public void testSourceExtensions() throws Exception { - StringWriter writer = new StringWriter(); - writer.write("int zVar; \n"); //$NON-NLS-1$ - writer.write("int zFunction(int); \n"); //$NON-NLS-1$ - writer.write("struct zStruct {int b;}; \n"); //$NON-NLS-1$ - writer.write("struct zStruct a;//vp1-1res \n"); //$NON-NLS-1$ - writer.write("int main(int argc, char **argv) { \n"); //$NON-NLS-1$ - writer.write(" zVar=0;//vp2-3res \n"); //$NON-NLS-1$ - writer.write(" return (0); \n"); //$NON-NLS-1$ - writer.write("} \n"); //$NON-NLS-1$ - String code = writer.toString(); - IFile t = importFile( "testSourceExtensions.c", code ); //$NON-NLS-1$ - //vp1 cfile global scope - ICompletionProposal [] results = getResults( t, code.indexOf( "Struct a;//vp1" ) ); //$NON-NLS-1$ - assertEquals( 1, results.length); - assertEquals( "zStruct", results[0].getDisplayString()); //$NON-NLS-1$ - //vp2 c file function scope - results = getResults( t, code.indexOf( "Var=0;//vp2" ) ); //$NON-NLS-1$ - assertEquals( 3, results.length); - assertEquals( "zVar : int", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( "zFunction(int) int", results[1].getDisplayString()); //$NON-NLS-1$ - assertEquals( "zStruct", results[2].getDisplayString()); //$NON-NLS-1$ - - removeFile("testSourceExtensions.c"); //$NON-NLS-1$ - t = importFile( "testSourceExtensions.C", code ); //$NON-NLS-1$ - //vp1 C file global scope - results = getResults( t, code.indexOf( "Struct a;//vp1" ) ); //$NON-NLS-1$ - assertEquals( 1, results.length); - assertEquals( "zStruct", results[0].getDisplayString()); //$NON-NLS-1$ - //vp2 C file function scope - results = getResults( t, code.indexOf( "Var=0;//vp2" ) ); //$NON-NLS-1$ - assertEquals( 3, results.length); - assertEquals( "zVar : int", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( "zFunction(int) int", results[1].getDisplayString()); //$NON-NLS-1$ - assertEquals( "zStruct", results[2].getDisplayString()); //$NON-NLS-1$ - removeFile("testSourceExtensions.C"); //$NON-NLS-1$ - t = importFile( "testSourceExtensions.cxx", code ); //$NON-NLS-1$ - //vp1 cxx file global scope - results = getResults( t, code.indexOf( "Struct a;//vp1" ) ); //$NON-NLS-1$ - assertEquals( 1, results.length); - assertEquals( "zStruct", results[0].getDisplayString()); //$NON-NLS-1$ - //vp2 css file function scope - results = getResults( t, code.indexOf( "Var=0;//vp2" ) ); //$NON-NLS-1$ - assertEquals( 3, results.length); - assertEquals( "zVar : int", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( "zFunction(int) int", results[1].getDisplayString()); //$NON-NLS-1$ - assertEquals( "zStruct", results[2].getDisplayString()); //$NON-NLS-1$ - removeFile("testSourceExtensions.cxx"); //$NON-NLS-1$ - t = importFile( "testSourceExtensions.cc", code ); //$NON-NLS-1$ - //vp1 cc file global scope - results = getResults( t, code.indexOf( "Struct a;//vp1" ) ); //$NON-NLS-1$ - assertEquals( 1, results.length); - assertEquals( "zStruct", results[0].getDisplayString()); //$NON-NLS-1$ - //vp2 cc file function scope - results = getResults( t, code.indexOf( "Var=0;//vp2" ) ); //$NON-NLS-1$ - assertEquals( 3, results.length); - assertEquals( "zVar : int", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( "zFunction(int) int", results[1].getDisplayString()); //$NON-NLS-1$ - assertEquals( "zStruct", results[2].getDisplayString()); //$NON-NLS-1$ - - } - //c code scope operator shouldn't provide CA contributions - public void test76480() throws Exception { - StringWriter writer = new StringWriter(); - writer.write("int zVar; \n"); //$NON-NLS-1$ - writer.write("int zFunction(int); \n"); //$NON-NLS-1$ - writer.write("struct zStruct {int b;}; \n"); //$NON-NLS-1$ - writer.write("int main(int argc, char **argv) { \n"); //$NON-NLS-1$ - writer.write(" ::zVar=0;//vp1-0res \n"); //$NON-NLS-1$ - writer.write(" return (0); \n"); //$NON-NLS-1$ - writer.write("} \n"); //$NON-NLS-1$ - String code = writer.toString(); - IFile t = importFile( "test76480.c", code ); //$NON-NLS-1$ - //vp1 function scope - ICompletionProposal [] results = getResults( t, code.indexOf( "Var=0;//vp1" ) ); //$NON-NLS-1$ - assertEquals( 0, results.length); - - } - // test27: Complete on a field type - // named struct with bitfield & typedef struct - public void testField() throws Exception { - StringWriter writer = new StringWriter(); - writer = new StringWriter(); - writer.write("struct simplestruct { \n"); //$NON-NLS-1$ - writer.write(" unsigned field1: 2; // range 0-3 \n"); //$NON-NLS-1$ - writer.write(" unsigned int field2: 1; // range 0-1 \n"); //$NON-NLS-1$ - writer.write("}; \n"); //$NON-NLS-1$ - writer.write("typedef struct { \n"); //$NON-NLS-1$ - writer.write(" static int const field2=5; \n"); //$NON-NLS-1$ - writer.write("} structtype; \n"); //$NON-NLS-1$ - writer.write("class A{ \n"); //$NON-NLS-1$ - writer.write(" public: struct {int aa;} a; \n"); //$NON-NLS-1$ - writer.write("}; \n"); //$NON-NLS-1$ - writer.write("int main(int argc, char **argv) { \n"); //$NON-NLS-1$ - writer.write(" struct simplestruct aStruct={3,0}, *pStruct;\n"); //$NON-NLS-1$ - writer.write(" aStruct.field1;//vp1 \n"); //$NON-NLS-1$ - writer.write(" pStruct->field1;//vp2 \n"); //$NON-NLS-1$ - writer.write(" structtype anotherStruct; \n"); //$NON-NLS-1$ - writer.write(" structtype::field2;//vp3 \n"); //$NON-NLS-1$ - writer.write(" class A myClass; \n"); //$NON-NLS-1$ - writer.write(" int i = myClass.a.aa;//vp4 \n"); //$NON-NLS-1$ - writer.write(" return (0); \n"); //$NON-NLS-1$ - writer.write("} \n"); //$NON-NLS-1$ - String code = writer.toString(); - IFile t = importFile( "testField.cpp", code ); //$NON-NLS-1$ - //vp1 bitfield accessed from named struct with "." - ICompletionProposal [] results = getResults( t, code.indexOf( "field1;//vp1" ) ); //$NON-NLS-1$ - assertEquals( 2, results.length); - assertEquals( "field1 : unsigned", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( "field2 : unsigned int", results[1].getDisplayString()); //$NON-NLS-1$ - //vp2 bitfield accessed from named struct with "->" - results = getResults( t, code.indexOf( "field1;//vp2" ) ); //$NON-NLS-1$ - assertEquals( 2, results.length); - assertEquals( "field1 : unsigned", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( "field2 : unsigned int", results[1].getDisplayString()); //$NON-NLS-1$ - //vp3 static const field accessed from typedef struct with "::" - results = getResults( t, code.indexOf( "field2;//vp3" ) ); //$NON-NLS-1$ - assertEquals( 1, results.length); - assertEquals( "field2 : const int", results[0].getDisplayString()); //$NON-NLS-1$ - //vp4 class field of type anonymous struct - results = getResults( t, code.indexOf( "a.aa;//vp4" ) ); //$NON-NLS-1$ - assertEquals( 1, results.length); - assertEquals( "a : ", results[0].getDisplayString()); //$NON-NLS-1$ - - } - public void testFieldExpression() throws Exception { - StringWriter writer = new StringWriter(); - writer.write("struct myStruct_c{ \n" ); //$NON-NLS-1$ - writer.write("int m; struct {int m2;} n; \n" ); //$NON-NLS-1$ - writer.write("}ss1={1},ss2={2}; \n" ); //$NON-NLS-1$ - writer.write("void f(){ \n" ); //$NON-NLS-1$ - writer.write("int i=(ss1.m > ss2.m/*vp1*/ ? ss1.n/*vp2*/ : ss2.n/*vp3*/).m2/*vp4*/;\n" ); //$NON-NLS-1$ - writer.write("} \n" ); //$NON-NLS-1$ - String code = writer.toString(); - IFile f=importFile( "testFieldExpression.cpp", code ); //$NON-NLS-1$ - //vp1 first operand of ?: on rhs of > - ICompletionProposal [] results = getResults( f, code.indexOf( "m/*vp1*/" ) ); //$NON-NLS-1$ - assertEquals( "m : int", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( "n : ", results[1].getDisplayString()); //$NON-NLS-1$ - assertEquals( 2, results.length); - //vp2 second operand of ?: - results = getResults( f, code.indexOf( "n/*vp2*/" ) ); //$NON-NLS-1$ - assertEquals( "m : int", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( "n : ", results[1].getDisplayString()); //$NON-NLS-1$ - assertEquals( 2, results.length); - //vp3 third operand of ?: - results = getResults( f, code.indexOf( "n/*vp3*/" ) ); //$NON-NLS-1$ - assertEquals( "m : int", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( "n : ", results[1].getDisplayString()); //$NON-NLS-1$ - assertEquals( 2, results.length); - //vp4 dot reference after ?: expression (note ?: expression cannot be lhs of =) - results = getResults( f, code.indexOf( "m2/*vp4*/" ) ); //$NON-NLS-1$ - assertEquals( "m2 : int", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( 1, results.length); - } - // test30: Complete on scoped reference - // nested class/namespaces, unambiguous scoped & unscoped namespace, ambiguous namespace - public void testScope() throws Exception { - StringWriter writer = new StringWriter(); - writer = new StringWriter(); - writer.write("namespace NN1 { \n" ); //$NON-NLS-1$ - writer.write(" class C1 {}; \n" ); //$NON-NLS-1$ - writer.write(" namespace NN2 { \n" ); //$NON-NLS-1$ - writer.write(" class C2{}; \n" ); //$NON-NLS-1$ - writer.write(" class NNA{}; \n" ); //$NON-NLS-1$ - writer.write(" namespace NN3 { \n" ); //$NON-NLS-1$ - writer.write(" class NNA{};\n" ); //$NON-NLS-1$ - writer.write(" class C3{ \n" ); //$NON-NLS-1$ - writer.write(" public: \n" ); //$NON-NLS-1$ - writer.write(" class C4{};\n" ); //$NON-NLS-1$ - writer.write(" }; \n" ); //$NON-NLS-1$ - writer.write(" } \n" ); //$NON-NLS-1$ - writer.write(" } \n" ); //$NON-NLS-1$ - writer.write("} \n" ); //$NON-NLS-1$ - String codeH = writer.toString(); - importFile( "testScope.h", codeH ); //$NON-NLS-1$ - - writer.write("#include \"testScope.h\" \n" ); //$NON-NLS-1$ - writer.write("int main(int argc, char **argv) { \n" ); //$NON-NLS-1$ - writer.write(" NN1::NN2::NN3::C3::C4 c4;//vp1:C4 \n" ); //$NON-NLS-1$ - writer.write(" using namespace NN1::NN2; \n" ); //$NON-NLS-1$ - writer.write(" NN3::C3 c3; //vp2:NN1,NN3,NNA; vp3:C3,NNA\n" ); //$NON-NLS-1$ - writer.write(" using namespace NN3; \n" ); //$NON-NLS-1$ - writer.write(" NN3::NNA a;//vp4:NN1,NN3(Ambiguous space)\n" ); //$NON-NLS-1$ - writer.write("} \n" ); //$NON-NLS-1$ - String code = writer.toString(); - IFile f=importFile( "testScope.cpp", code ); //$NON-NLS-1$ - //vp1 5 levels of nested class/namespaces - ICompletionProposal [] results = getResults( f, code.indexOf( "C4 c4;//vp1" ) ); //$NON-NLS-1$ - assertEquals( "C4", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( 1, results.length); - //vp2 unambiguous NNA, unscoped - results = getResults( f, code.indexOf( "3::C3 c3; //vp2" ) ); //$NON-NLS-1$ - assertEquals( "NNA", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( "NN1", results[1].getDisplayString()); //$NON-NLS-1$ - assertEquals( "NN3", results[2].getDisplayString()); //$NON-NLS-1$ - assertEquals( 3, results.length); - //vp3 unambigous NNA, scoped - results = getResults( f, code.indexOf( "C3 c3; //vp2:NN1,NN3,NNA; vp3" ) ); //$NON-NLS-1$ - assertEquals( "C3", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( "NNA", results[1].getDisplayString()); //$NON-NLS-1$ - assertEquals( 2, results.length); - //vp4 ambiguous NNA, not in contribution list - results = getResults( f, code.indexOf( "3::NNA a;//vp4" ) ); //$NON-NLS-1$ - assertEquals( "NN1", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( "NN3", results[1].getDisplayString()); //$NON-NLS-1$ - assertEquals( 2, results.length); - - } - // test33 - public void testClass() throws Exception { - StringWriter writer = new StringWriter(); - writer.write("class Point{ \n" ); //$NON-NLS-1$ - writer.write("public: \n" ); //$NON-NLS-1$ - writer.write(" Point(): xCoord(0){} \n" ); //$NON-NLS-1$ - writer.write(" Point(int x); \n" ); //$NON-NLS-1$ - writer.write(" Point(const Point &rhs); \n" ); //$NON-NLS-1$ - writer.write(" virtual ~Point(){} \n" ); //$NON-NLS-1$ - writer.write(" int getX() const {return xCoord;} \n" ); //$NON-NLS-1$ - writer.write("private: \n" ); //$NON-NLS-1$ - writer.write(" int xCoord; \n" ); //$NON-NLS-1$ - writer.write("}; \n" ); //$NON-NLS-1$ - String codeH = writer.toString(); - importFile( "testClass.h", codeH ); //$NON-NLS-1$ - - writer = new StringWriter(); - writer.write("#include \"testClass.h\" \n" ); //$NON-NLS-1$ - writer.write("Point::Point(int x):xCoord(x){} \n" ); //$NON-NLS-1$ - writer.write("Point::Point(const Point &rhs){ \n" ); //$NON-NLS-1$ - writer.write(" xCoord = rhs.xCoord; \n" ); //$NON-NLS-1$ - writer.write("} \n" ); //$NON-NLS-1$ - writer.write("static const Point zero(0); \n" ); //$NON-NLS-1$ - writer.write("int main(int argc, char **argv) { \n" ); //$NON-NLS-1$ - writer.write(" Point *p1 = new ::Point(0);//vp1 scoped class \n" ); //$NON-NLS-1$ - writer.write(" Point &p2 = *(new Point(10)); \n" ); //$NON-NLS-1$ - writer.write(" Point one(1); \n" ); //$NON-NLS-1$ - writer.write(" p1->getX();//vp2: arrow getX(), getY(), ~Point(), operator=) \n" ); //$NON-NLS-1$ - writer.write(" p2.getX();//vp3: dot on dereferenced initialization \n" ); //$NON-NLS-1$ - writer.write(" one.getX();//vp4: dot on simple initialization \n" ); //$NON-NLS-1$ - writer.write(" *(p1) = ::zero;//vp5 scoped class instance \n" ); //$NON-NLS-1$ - writer.write(" return (0); \n" ); //$NON-NLS-1$ - writer.write("} \n" ); //$NON-NLS-1$ - String code = writer.toString(); - IFile f=importFile( "testClass.cpp", code ); //$NON-NLS-1$ - //vp1 scoped class - ICompletionProposal [] results = getResults( f, code.indexOf( "oint(0);//vp1" ) ); //$NON-NLS-1$ - assertEquals( "Point", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( 1, results.length); - //vp2 arrow ref. this will fail when 72723 is fixed because of the - //sorting of the results: currently: =,~,get; after fix: ~,get,operator= - results = getResults( f, code.indexOf( "getX();//vp2" ) ); //$NON-NLS-1$ - //assertEquals( "operator=(const Point&) Point&", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( "getX() int", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( "~Point()", results[1].getDisplayString()); //$NON-NLS-1$ - assertEquals( 2, results.length); - //vp3 dot ref on dereferenced initialization - results = getResults( f, code.indexOf( "getX();//vp3" ) ); //$NON-NLS-1$ - assertEquals( "getX() int", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( "~Point()", results[1].getDisplayString()); //$NON-NLS-1$ - assertEquals( 2, results.length); - //vp4 dot on simple initialization - results = getResults( f, code.indexOf( "getX();//vp4" ) ); //$NON-NLS-1$ - assertEquals( "getX() int", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( "~Point()", results[1].getDisplayString()); //$NON-NLS-1$ - assertEquals( 2, results.length); - //vp5 scoped class instance - results = getResults( f, code.indexOf( "ero;//vp5" ) ); //$NON-NLS-1$ - assertEquals( "zero : const Point", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( 1, results.length); - - - } - // defect 72723 on test 33: Complete on opertator overloads forgets the operator keyword - public void test72723() throws Exception { - - StringWriter writer = new StringWriter(); - writer.write("class Point{ \n" ); //$NON-NLS-1$ - writer.write("public: \n" ); //$NON-NLS-1$ - writer.write(" Point(): xCoord(0){} \n" ); //$NON-NLS-1$ - writer.write(" Point(int x); \n" ); //$NON-NLS-1$ - writer.write(" Point(const Point &rhs); \n" ); //$NON-NLS-1$ - writer.write(" virtual ~Point(){} \n" ); //$NON-NLS-1$ - writer.write(" int getX() const {return xCoord;} \n" ); //$NON-NLS-1$ - writer.write(" Point& operator=(const Point &rhs); \n" ); //$NON-NLS-1$ - writer.write("private: \n" ); //$NON-NLS-1$ - writer.write(" int xCoord; \n" ); //$NON-NLS-1$ - writer.write("}; \n" ); //$NON-NLS-1$ - String codeH = writer.toString(); - importFile( "test72723.h", codeH ); //$NON-NLS-1$ - - writer = new StringWriter(); - writer.write("#include \"test72723.h\" \n" ); //$NON-NLS-1$ - writer.write("Point::Point(int x):xCoord(x){} \n" ); //$NON-NLS-1$ - writer.write("Point::Point(const Point &rhs){ \n" ); //$NON-NLS-1$ - writer.write(" xCoord = rhs.xCoord; \n" ); //$NON-NLS-1$ - writer.write("} \n" ); //$NON-NLS-1$ - writer.write("Point& Point::operator=(const Point &rhs){\n" ); //$NON-NLS-1$ - writer.write(" if (this == &rhs) return *this; \n" ); //$NON-NLS-1$ - writer.write(" xCoord = rhs.xCoord; \n" ); //$NON-NLS-1$ - writer.write(" return *this; \n" ); //$NON-NLS-1$ - writer.write("} \n" ); //$NON-NLS-1$ - writer.write("static const Point zero(0); \n" ); //$NON-NLS-1$ - writer.write("int main(int argc, char **argv) { \n" ); //$NON-NLS-1$ - writer.write(" Point *p1 = new ::Point(0); \n" ); //$NON-NLS-1$ - writer.write(" Point &p2 = *(new Point(10)); \n" ); //$NON-NLS-1$ - writer.write(" p1->operator=(zero);//vp1: arrow ref \n" ); //$NON-NLS-1$ - writer.write(" p2.operator=(zero);//vp2: dot ref \n" ); //$NON-NLS-1$ - writer.write(" return (0); \n" ); //$NON-NLS-1$ - writer.write("} \n" ); //$NON-NLS-1$ - String code = writer.toString(); - IFile f=importFile( "test72723.cpp", code ); //$NON-NLS-1$ - //vp1 arrow ref - ICompletionProposal [] results = getResults( f, code.indexOf( "perator=(zero);//vp3" ) ); //$NON-NLS-1$ - assertEquals( 1, results.length); - assertEquals( "operator=(const Point&) Point&", results[0].getDisplayString()); //$NON-NLS-1$ - - } - // defect 72541 on test 33: Complete on const missing suggestions - public void test72541() throws Exception { - StringWriter writer = new StringWriter(); - writer.write("class Point {public Point(); int X;}; \n" ); //$NON-NLS-1$ - writer.write("const Point zero; \n" ); //$NON-NLS-1$ - writer.write("int main() {return zero.X;}//vp1 \n" ); //$NON-NLS-1$ - String code = writer.toString(); - IFile f=importFile( "test72541.h", code ); //$NON-NLS-1$ - - //vp1 completion on const class - ICompletionProposal [] results = getResults( f, code.indexOf( "X;}//vp1" ) ); //$NON-NLS-1$ - assertEquals( 1, results.length); - assertEquals( "X : const int", results[0].getDisplayString()); //$NON-NLS-1$ - - } - // test 36 - public void testFunction() throws Exception { - StringWriter writer = new StringWriter(); - writer.write("namespace nnnn { \n"); //$NON-NLS-1$ - writer.write(" namespace nnn { \n"); //$NON-NLS-1$ - writer.write(" void foo(){} \n"); //$NON-NLS-1$ - writer.write(" } \n"); //$NON-NLS-1$ - writer.write("} \n"); //$NON-NLS-1$ - writer.write("int main(int argc, char **argv) {\n"); //$NON-NLS-1$ - writer.write(" namespace n=nnnn::nnn; \n"); //$NON-NLS-1$ - writer.write(" n::foo();//vp1 \n"); //$NON-NLS-1$ - writer.write(" using namespace nnnn; \n"); //$NON-NLS-1$ - writer.write(" nnn::foo();//vp2 \n"); //$NON-NLS-1$ - writer.write(" return (0); \n"); //$NON-NLS-1$ - writer.write("} \n"); //$NON-NLS-1$ - String code = writer.toString(); - IFile t = importFile( "testFunction.cpp", code ); //$NON-NLS-1$ - //vp1 namespace alias scope - ICompletionProposal [] results = getResults( t, code.indexOf( "foo();//vp1" ) ); //$NON-NLS-1$ - assertEquals( 1, results.length); - assertEquals( "foo() void", results[0].getDisplayString()); //$NON-NLS-1$ - //vp2 nested namespace scope - results = getResults( t, code.indexOf( "oo();//vp2" ) ); //$NON-NLS-1$ - assertEquals( 1, results.length); - assertEquals( "foo() void", results[0].getDisplayString()); //$NON-NLS-1$ - - } - //test 44 argument types from both function declaration and function call - public void testArgument() throws Exception { - StringWriter writer = new StringWriter(); - writer.write("typedef long int32_t; \n"); //$NON-NLS-1$ - writer.write("#define INT32_C(x) x ## L \n"); //$NON-NLS-1$ - writer.write("#define INT32_MAX (2147483647) \n"); //$NON-NLS-1$ - writer.write("int foo(int32_t i){//vp1contributions include types in arg list\n"); //$NON-NLS-1$ - writer.write(" return (i); \n"); //$NON-NLS-1$ - writer.write("} \n"); //$NON-NLS-1$ - writer.write("int z(int i){return (i);} \n"); //$NON-NLS-1$ - writer.write("int main(int argc, char **argv) {\n"); //$NON-NLS-1$ - writer.write(" int32_t int32iii=2; \n"); //$NON-NLS-1$ - writer.write(" foo(INT32_C(2));//vp2 macros\n"); //$NON-NLS-1$ - writer.write(" foo(INT32_MAX);//vp3 defines\n"); //$NON-NLS-1$ - writer.write(" foo(int32iii);//vp4 variable\n"); //$NON-NLS-1$ - writer.write(" foo(z(5));//vp5 function arg \n"); //$NON-NLS-1$ - writer.write(" return (0); \n"); //$NON-NLS-1$ - writer.write("} \n"); //$NON-NLS-1$ - String code = writer.toString(); - IFile t = importFile( "testArgument.c", code ); //$NON-NLS-1$ - //vp1 function declaration args contain type only - ICompletionProposal [] results = getResults( t, code.indexOf( "32_t i){//vp1" ) ); //$NON-NLS-1$ - //assertEquals( 15, results.length); - assertEquals( 2, results.length); - assertEquals( "int32_t", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( "int", results[1].getDisplayString()); //$NON-NLS-1$ - //vp2 function call args contain #macros, variables but not types - results = getResults( t, code.indexOf( "(2));//vp2" ) ); //$NON-NLS-1$ - assertEquals( 1, results.length); - assertEquals( "INT32_C(x)", results[0].getDisplayString()); //$NON-NLS-1$ - //vp3 function call args contain #defines - results = getResults( t, code.indexOf( "AX);//vp3" ) ); //$NON-NLS-1$ - assertEquals( 1, results.length); - assertEquals( "INT32_MAX", results[0].getDisplayString()); //$NON-NLS-1$ - //assertEquals( "INT32_MIN", results[1].getDisplayString()); //$NON-NLS-1$ - //vp4 function call args contain variables - results = getResults( t, code.indexOf( "ii);//vp4" ) ); //$NON-NLS-1$ - assertEquals( 1, results.length); - assertEquals( "int32iii : int32_t", results[0].getDisplayString()); //$NON-NLS-1$ - //vp5 function call args can contain functions - results = getResults( t, code.indexOf( "(5));//vp5" ) ); //$NON-NLS-1$ - assertEquals( 1, results.length); - assertEquals( "z(int) int", results[0].getDisplayString()); //$NON-NLS-1$ - - } - - // arguments in function call shouldn't contain types - public void test76805() throws Exception { - StringWriter writer = new StringWriter(); - writer.write("typedef long int32_t; \n"); //$NON-NLS-1$ - writer.write("#define INT32_MAX (2147483647) \n"); //$NON-NLS-1$ - writer.write("int foo(int32_t i){ \n"); //$NON-NLS-1$ - writer.write(" return (i); \n"); //$NON-NLS-1$ - writer.write("} \n"); //$NON-NLS-1$ - writer.write("int main(int argc, char **argv) {\n"); //$NON-NLS-1$ - writer.write(" int32_t int32iii=2; \n"); //$NON-NLS-1$ - writer.write(" foo(INT32_MAX);//vp1 macros, variables, not types\n"); //$NON-NLS-1$ - writer.write(" return (0); \n"); //$NON-NLS-1$ - writer.write("} \n"); //$NON-NLS-1$ - String code = writer.toString(); - IFile t = importFile( "test76805.c", code ); //$NON-NLS-1$ - //vp1 function call args contain #defines, variables but not types - //int32_t should not be in the list - ICompletionProposal [] results = getResults( t, code.indexOf( "32_MAX);//vp1" ) ); //$NON-NLS-1$ - assertEquals( "INT32_MAX", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( "int32iii : int32_t", results[1].getDisplayString()); //$NON-NLS-1$ - assertEquals( 2, results.length); - - } - // test 50 type cast c code: narrowing cast & struct cast; - // cpp code: class cast, override typecheck cast, deref cast - public void testCStyleCast() throws Exception { - StringWriter writer = new StringWriter(); - writer.write("typedef int ZINT; \n"); //$NON-NLS-1$ - writer.write("typedef struct { \n"); //$NON-NLS-1$ - writer.write(" int foobar; \n"); //$NON-NLS-1$ - writer.write("}foo_c; \n"); //$NON-NLS-1$ - writer.write("typedef struct {} bar_c; \n"); //$NON-NLS-1$ - writer.write("int main(int argc, char **argv) {\n"); //$NON-NLS-1$ - writer.write(" ZINT i=(ZINT) 3.1;//vp1 narrowing cast\n"); //$NON-NLS-1$ - writer.write(" bar_c *bar; \n"); //$NON-NLS-1$ - writer.write(" foo_c *foo; \n"); //$NON-NLS-1$ - writer.write(" ((foo_c*) bar)->foobar;//vp2 complete on struct casted var\n"); //$NON-NLS-1$ - writer.write("} \n"); //$NON-NLS-1$ - String code = writer.toString(); - IFile t = importFile( "testCStyleCast.c", code ); //$NON-NLS-1$ - ICompletionProposal [] results = getResults( t, code.indexOf( "INT) 3.1;//vp1" ) ); //$NON-NLS-1$ - assertEquals( "ZINT", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( 1, results.length); - results = getResults( t, code.indexOf( "foobar;//vp2" ) ); //$NON-NLS-1$ - assertEquals( "foobar : int", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( 1, results.length); - removeFile("testCStyleCase.c");//$NON-NLS-1$ - - writer=new StringWriter(); - writer.write("typedef int ZINT; \n"); //$NON-NLS-1$ - writer.write("class foo_c{ \n"); //$NON-NLS-1$ - writer.write(" public: void foobar(){} \n"); //$NON-NLS-1$ - writer.write("}; \n"); //$NON-NLS-1$ - writer.write("class bar_c {}; \n"); //$NON-NLS-1$ - writer.write("int main(int argc, char **argv) { \n"); //$NON-NLS-1$ - writer.write(" bar_c *bar; \n"); //$NON-NLS-1$ - writer.write(" foo_c *foo; \n"); //$NON-NLS-1$ - writer.write(" ((foo_c*) bar)->foobar();//vp1 complete on class casted var\n"); //$NON-NLS-1$ - writer.write(" //cast away constness \n"); //$NON-NLS-1$ - writer.write(" ZINT i=3; \n"); //$NON-NLS-1$ - writer.write(" const int *pci = &i; \n"); //$NON-NLS-1$ - writer.write(" void * pv=(void*)pci;//vp2 override typecheck cast \n"); //$NON-NLS-1$ - writer.write(" (*(ZINT *)pv)=4;//vp3 dereferenced casted var\n"); //$NON-NLS-1$ - writer.write(" return 0; \n"); //$NON-NLS-1$ - writer.write("} \n"); //$NON-NLS-1$ - code = writer.toString(); - t = importFile( "testCStyleCast.cpp", code ); //$NON-NLS-1$ - results = getResults( t, code.indexOf( "foobar();//vp1" ) ); //$NON-NLS-1$ - assertEquals( "foobar() void", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( 1, results.length); - results = getResults( t, code.indexOf( "d*)pci;//vp2" ) ); //$NON-NLS-1$ - assertEquals( "void", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( 1, results.length); - results = getResults( t, code.indexOf( "INT *)pv)=4;//vp3" ) ); //$NON-NLS-1$ - assertEquals( "ZINT", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( 1, results.length); - - } - //test 59 - public void testMethod() throws Exception { - StringWriter writer = new StringWriter(); - writer.write("class Point{ \n"); //$NON-NLS-1$ - writer.write(" public: Point(): x(5){} \n"); //$NON-NLS-1$ - writer.write(" Point& compare(const Point &rhs) {\n"); //$NON-NLS-1$ - writer.write(" (this==&rhs);//vp1 \n"); //$NON-NLS-1$ - writer.write(" return *this;//vp2 \n"); //$NON-NLS-1$ - writer.write(" } \n"); //$NON-NLS-1$ - writer.write(" int x; \n"); //$NON-NLS-1$ - writer.write("}; \n"); //$NON-NLS-1$ - writer.write("int main(int argc, char **argv) {\n"); //$NON-NLS-1$ - writer.write(" Point *p1=new Point(); \n"); //$NON-NLS-1$ - writer.write(" Point &p2=*(new Point()); \n"); //$NON-NLS-1$ - writer.write(" Point **p3; \n"); //$NON-NLS-1$ - writer.write(" **p3=p2;//vp3 content assist doesn't filter out pointer types by design\n"); //$NON-NLS-1$ - writer.write(" (**p3).x;//vp4 correct dereference\n"); //$NON-NLS-1$ - writer.write(" (*p3).x;//vp5 too few stars - CA notices\n"); //$NON-NLS-1$ - writer.write(" return 0; \n"); //$NON-NLS-1$ - writer.write("} \n"); //$NON-NLS-1$ - String code = writer.toString(); - IFile t = importFile( "testMethod.c", code ); //$NON-NLS-1$ - //vp1 complete on & var - ICompletionProposal [] results = getResults( t, code.indexOf( "hs);//vp1" ) ); //$NON-NLS-1$ - assertEquals( "rhs : const Point&", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( "register", results[1].getDisplayString()); //$NON-NLS-1$ - assertEquals( "reinterpret_cast", results[2].getDisplayString()); //$NON-NLS-1$ - //does return make sense even when there's no & - assertEquals( "return", results[3].getDisplayString()); //$NON-NLS-1$ - assertEquals( 4, results.length); - //vp2 complete on *this - results = getResults( t, code.indexOf( "s;//vp2" ) ); //$NON-NLS-1$ - assertEquals( "this", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( 1, results.length); - //vp3 ignore stars by design, so CA correctly returns all local vars - results = getResults( t, code.indexOf( "3=p2;//vp3" ) ); //$NON-NLS-1$ - assertEquals( "p1 : Point*", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( "p2 : Point&", results[1].getDisplayString()); //$NON-NLS-1$ - assertEquals( "p3 : Point**", results[2].getDisplayString()); //$NON-NLS-1$ - assertEquals( "Point", results[3].getDisplayString()); //$NON-NLS-1$ - assertEquals( 4, results.length); - - //vp4 complete on members of correctly dereferenced object - results = getResults( t, code.indexOf( "x;//vp4" ) ); //$NON-NLS-1$ - assertEquals( "x : int", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( "compare(const Point&) Point&", results[1].getDisplayString()); //$NON-NLS-1$ - assertEquals( 2, results.length); - - //vp5 no completions available for incorrectly dereferenced object - results = getResults( t, code.indexOf( "x;//vp5" ) ); //$NON-NLS-1$ - assertEquals( 0, results.length); - - } - // test 62 - public void testEnumerations() throws Exception { - StringWriter writer = new StringWriter(); - writer.write("enum day {ztuesday, zthursday}; \n" ); //$NON-NLS-1$ - writer.write("enum {zTGIF}; \n" ); //$NON-NLS-1$ - writer.write("int i=ztuesday;//vp1 \n" ); //$NON-NLS-1$ - writer.write("class Bar { \n" ); //$NON-NLS-1$ - writer.write(" public: \n" ); //$NON-NLS-1$ - writer.write(" enum R4 {R1} num; \n" ); //$NON-NLS-1$ - writer.write(" enum {R2}; \n" ); //$NON-NLS-1$ - writer.write(" static enum {R3} Rnum2; \n" ); //$NON-NLS-1$ - writer.write(" day nd; \n" ); //$NON-NLS-1$ - writer.write("}; \n" ); //$NON-NLS-1$ - writer.write("void foo(){ \n" ); //$NON-NLS-1$ - writer.write(" day d;//vp2 \n" ); //$NON-NLS-1$ - writer.write(" d=ztuesday;//vp3 \n" ); //$NON-NLS-1$ - writer.write(" Bar::R1;//vp4 \n" ); //$NON-NLS-1$ - writer.write(" Bar b; \n" ); //$NON-NLS-1$ - writer.write(" b.R3;//vp5 \n" ); //$NON-NLS-1$ - writer.write("} \n" ); //$NON-NLS-1$ - String code = writer.toString(); - IFile t = importFile( "testEnumerations.cpp", code ); //$NON-NLS-1$ - //vp1 global enumerator reference in global scope, RHS - ICompletionProposal [] results = getResults( t, code.indexOf( "uesday;//vp1" ) ); //$NON-NLS-1$ - assertEquals( "zthursday", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( "ztuesday", results[1].getDisplayString()); //$NON-NLS-1$ - assertEquals( "zTGIF", results[2].getDisplayString()); //$NON-NLS-1$ - assertEquals( 3, results.length); - //vp2 enumeration reference in function - results = getResults( t, code.indexOf( "y d;//vp2" ) ); //$NON-NLS-1$ - assertEquals( "day", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( 1, results.length); - //vp3 global enumerator reference in function scope, RHS - results = getResults( t, code.indexOf( "uesday;//vp3" ) ); //$NON-NLS-1$ - assertEquals( "zthursday", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( "ztuesday", results[1].getDisplayString()); //$NON-NLS-1$ - assertEquals( "zTGIF", results[2].getDisplayString()); //$NON-NLS-1$ - assertEquals( 3, results.length); - //vp4 enum & enumerator "::" reference, no prefix - results = getResults( t, code.indexOf( "R1;//vp4" ) ); //$NON-NLS-1$ - assertEquals( "Rnum2 : ", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( "R1", results[1].getDisplayString()); //$NON-NLS-1$ - assertEquals( "R2", results[2].getDisplayString()); //$NON-NLS-1$ - assertEquals( "R3", results[3].getDisplayString()); //$NON-NLS-1$ - assertEquals( "R4", results[4].getDisplayString()); //$NON-NLS-1$ - assertEquals( 5, results.length); - //vp5 enumerator "." reference, prefix - results = getResults( t, code.indexOf( "3;//vp5" ) ); //$NON-NLS-1$ - assertEquals( 4, results.length); - assertEquals( "Rnum2 : ", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( "R1", results[1].getDisplayString()); //$NON-NLS-1$ - assertEquals( "R2", results[2].getDisplayString()); //$NON-NLS-1$ - assertEquals( "R3", results[3].getDisplayString()); //$NON-NLS-1$ - - } - //test 70 - public void testLongTokens() throws Exception { - StringWriter writer = new StringWriter(); - writer.write("int i123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890;\n" ); //$NON-NLS-1$ - writer.write("typedef int t123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890;\n" ); //$NON-NLS-1$ - writer.write("class A {\n" ); //$NON-NLS-1$ - writer.write(" A(t123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890 a){\n" ); //$NON-NLS-1$ - writer.write(" i123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890=0;//vp1 \n" ); //$NON-NLS-1$ - writer.write(" t123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890 t=a;//vp2 \n" ); //$NON-NLS-1$ - writer.write(" a=i123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890;//vp3 \n" ); //$NON-NLS-1$ - writer.write(" }\n" ); //$NON-NLS-1$ - writer.write("};\n" ); //$NON-NLS-1$ - String code = writer.toString(); - IFile t = importFile( "testLongTokens.cpp", code ); //$NON-NLS-1$ - //vp1 complete on long var - ICompletionProposal [] results = getResults( t, code.indexOf( "3456789012345678901234567890123456789012345678901234567890123456789012345678901234567890=0;//vp1" ) ); //$NON-NLS-1$ - assertEquals( "i123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890 : int", results[0].getDisplayString()); //$NON-NLS-1$ - //vp2 proposal has long type - results = getResults( t, code.indexOf( ";//vp2" ) ); //$NON-NLS-1$ - assertEquals( "a : t123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890", results[0].getDisplayString()); //$NON-NLS-1$ - //vp3 complete on rhs long var with long prefix - results = getResults( t, code.indexOf( "7890;//vp3" ) ); //$NON-NLS-1$ - assertEquals( "i123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890 : int", results[0].getDisplayString()); //$NON-NLS-1$ - } - //test 73 - public void testCastMultiLevel() throws Exception { - StringWriter writer = new StringWriter(); - writer.write("class Gee{ \n" ); //$NON-NLS-1$ - writer.write(" public: struct {int g1;} g0; \n" ); //$NON-NLS-1$ - writer.write("}; \n" ); //$NON-NLS-1$ - writer.write("class Foo { \n" ); //$NON-NLS-1$ - writer.write(" public: Gee *f0; \n" ); //$NON-NLS-1$ - writer.write("}; \n" ); //$NON-NLS-1$ - writer.write("class C { \n" ); //$NON-NLS-1$ - writer.write(" void coo(int i){ \n" ); //$NON-NLS-1$ - writer.write(" switch (i) { \n" ); //$NON-NLS-1$ - writer.write(" (*((new Foo())->f0)).g0.g1;//vp1 \n" ); //$NON-NLS-1$ - writer.write(" Gee *g; \n" ); //$NON-NLS-1$ - writer.write(" ((Foo*)g)->f0;//vp2 \n" ); //$NON-NLS-1$ - writer.write(" (*(((Foo*)g)->f0)).g0.g1;//vp3,vp4 \n" ); //$NON-NLS-1$ - writer.write(" } \n" ); //$NON-NLS-1$ - writer.write(" } \n" ); //$NON-NLS-1$ - writer.write("}; \n" ); //$NON-NLS-1$ - String code = writer.toString(); - IFile t = importFile( "testCastMultiLevel.cpp", code ); //$NON-NLS-1$ - //vp1 multilevel qual - ICompletionProposal [] results = getResults( t, code.indexOf( "g1;//vp1" ) ); //$NON-NLS-1$ - assertEquals( "g1 : int", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( 1, results.length); - //vp2 cast & multilevel qual on -> - results = getResults( t, code.indexOf( "f0;//vp2" ) ); //$NON-NLS-1$ - assertEquals( "f0 : Gee*", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( 1, results.length); - //vp3 cast & multilevel qual on . (class member) - results = getResults( t, code.indexOf( "g0.g1;//vp3" ) ); //$NON-NLS-1$ - assertEquals( "g0 : ", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( 1, results.length); - //vp4 cast & multilevel qual on . (struct member) - results = getResults( t, code.indexOf( "g1;//vp3,vp4" ) ); //$NON-NLS-1$ - assertEquals( "g1 : int", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( 1, results.length); - - } - //test 79 - public void testHeaderExtensions() throws Exception { - StringWriter writer = new StringWriter(); - writer.write("class C1{ \n" ); //$NON-NLS-1$ - writer.write(" enum {C1a, C1b}; \n" ); //$NON-NLS-1$ - writer.write(" C1() { \n" ); //$NON-NLS-1$ - writer.write(" C1;//vp1 \n" ); //$NON-NLS-1$ - writer.write(" } \n" ); //$NON-NLS-1$ - writer.write("}; \n" ); //$NON-NLS-1$ - String code = writer.toString(); - IFile t = importFile( "testHeaderExtensions.h", code ); //$NON-NLS-1$ - //vp1 h file - ICompletionProposal [] results = getResults( t, code.indexOf( "1;//vp1" ) ); //$NON-NLS-1$ - assertEquals( "C1", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( "C1a", results[1].getDisplayString()); //$NON-NLS-1$ - assertEquals( "C1b", results[2].getDisplayString()); //$NON-NLS-1$ - assertEquals( 3, results.length); - removeFile("testHeaderExtensions.h"); //$NON-NLS-1$ - - //vp2 H file - writer = new StringWriter(); - writer.write("class C{ \n" ); //$NON-NLS-1$ - writer.write(" public: enum {C1, C3}; \n" ); //$NON-NLS-1$ - writer.write(" C() { \n" ); //$NON-NLS-1$ - writer.write(" C1; \n" ); //$NON-NLS-1$ - writer.write(" } \n" ); //$NON-NLS-1$ - writer.write("}; \n" ); //$NON-NLS-1$ - writer.write("namespace N { \n" ); //$NON-NLS-1$ - writer.write("int i =C::C1;//vp2 \n" ); //$NON-NLS-1$ - writer.write("} \n" ); //$NON-NLS-1$ - code = writer.toString(); - t = importFile( "testHeaderExtensions.H", code ); //$NON-NLS-1$ - //vp2 H file, namespace scope, class context - results = getResults( t, code.indexOf( "C1;//vp2" ) ); //$NON-NLS-1$ - assertEquals( "C()", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( "C1", results[1].getDisplayString()); //$NON-NLS-1$ - assertEquals( "C3", results[2].getDisplayString()); //$NON-NLS-1$ - //trace showed 4 lookup results - assertEquals( 3, results.length); - removeFile("testHeaderExtensions.H"); //$NON-NLS-1$ - - // vp3 hxx file - writer = new StringWriter(); - writer.write("class C{ \n" ); //$NON-NLS-1$ - writer.write(" enum {C1, C3}; \n" ); //$NON-NLS-1$ - writer.write(" C() { \n" ); //$NON-NLS-1$ - writer.write(" C1;//vp3 \n" ); //$NON-NLS-1$ - writer.write(" } \n" ); //$NON-NLS-1$ - writer.write("}; \n" ); //$NON-NLS-1$ - code = writer.toString(); - t = importFile( "testHeaderExtensions.hxx", code ); //$NON-NLS-1$ - //vp3 hxx file, method scope - results = getResults( t, code.indexOf( "1;//vp3" ) ); //$NON-NLS-1$ - assertEquals( "C", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( "C1", results[1].getDisplayString()); //$NON-NLS-1$ - assertEquals( "C3", results[2].getDisplayString()); //$NON-NLS-1$ - assertEquals( 3, results.length); - removeFile("testHeaderExtensions.hxx"); //$NON-NLS-1$ - - //vp4 hh file - writer = new StringWriter(); - writer.write("class C{ \n" ); //$NON-NLS-1$ - writer.write(" public: enum {C1, C3}; \n" ); //$NON-NLS-1$ - writer.write(" C() { \n" ); //$NON-NLS-1$ - writer.write(" C1; \n" ); //$NON-NLS-1$ - writer.write(" } \n" ); //$NON-NLS-1$ - writer.write("}; \n" ); //$NON-NLS-1$ - writer.write("namespace N { \n" ); //$NON-NLS-1$ - writer.write("int i =C::C1;//vp4 \n" ); //$NON-NLS-1$ - writer.write("} \n" ); //$NON-NLS-1$ - code = writer.toString(); - t = importFile( "testHeaderExtensions.hh", code ); //$NON-NLS-1$ - //vp4 hh file, namespace scope, class context - results = getResults( t, code.indexOf( "C1;//vp4" ) ); //$NON-NLS-1$ - assertEquals( "C()", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( "C1", results[1].getDisplayString()); //$NON-NLS-1$ - assertEquals( "C3", results[2].getDisplayString()); //$NON-NLS-1$ - //trace showed 4 lookup results - assertEquals( 3, results.length); - removeFile("testHeaderExtensions.hh"); //$NON-NLS-1$ - - //vp5 hpp file - writer = new StringWriter(); - writer.write("class C{ \n" ); //$NON-NLS-1$ - writer.write(" public: enum {C1, C3}; \n" ); //$NON-NLS-1$ - writer.write(" C() { \n" ); //$NON-NLS-1$ - writer.write(" C1; \n" ); //$NON-NLS-1$ - writer.write(" } \n" ); //$NON-NLS-1$ - writer.write("}; \n" ); //$NON-NLS-1$ - writer.write("namespace N { \n" ); //$NON-NLS-1$ - writer.write("int i =C::C1;//vp5 \n" ); //$NON-NLS-1$ - writer.write("} \n" ); //$NON-NLS-1$ - code = writer.toString(); - t = importFile( "testHeaderExtensions.H", code ); //$NON-NLS-1$ - //vp5 hpp file, namespace scope, class context - results = getResults( t, code.indexOf( "C1;//vp5" ) ); //$NON-NLS-1$ - assertEquals( "C()", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( "C1", results[1].getDisplayString()); //$NON-NLS-1$ - assertEquals( "C3", results[2].getDisplayString()); //$NON-NLS-1$ - //trace showed 4 lookup results - assertEquals( 3, results.length); - - } - //test 9 - public void testEmptyDocument() throws Exception { - String code = "\0"; //$NON-NLS-1$ - IFile t = importFile( "testEmptyDocument.h", code ); //$NON-NLS-1$ - //vp1 no prefix, keywords. - ICompletionProposal [] results = getResults( t, 0 ); //$NON-NLS-1$ - assertEquals( "asm", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( "auto", results[1].getDisplayString()); //$NON-NLS-1$ - assertEquals( "bool", results[2].getDisplayString()); //$NON-NLS-1$ - assertEquals( "wchar_t", results[results.length-1].getDisplayString()); //$NON-NLS-1$ - StringWriter writer = new StringWriter(); - //vp2 prefix, keywords - writer.write("s//vp2" ); //$NON-NLS-1$ - code =writer.toString(); - t = importFile( "testEmptyDocument.cpp", code ); //$NON-NLS-1$ - results = getResults( t, code.indexOf( "//vp2" ) ); //$NON-NLS-1$ - assertEquals( "short", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( "signed", results[1].getDisplayString()); //$NON-NLS-1$ - assertEquals( "static", results[2].getDisplayString()); //$NON-NLS-1$ - assertEquals( "struct", results[3].getDisplayString()); //$NON-NLS-1$ - assertEquals( 4, results.length); - - } - public void testVariable() throws Exception { - StringWriter writer = new StringWriter(); - writer.write("namespace N { \n" ); //$NON-NLS-1$ - writer.write(" class ClassT {}; \n" ); //$NON-NLS-1$ - writer.write(" struct StructT {}; \n" ); //$NON-NLS-1$ - writer.write(" typedef struct {} TypedefT; \n" ); //$NON-NLS-1$ - writer.write(" union UnionT {}; \n" ); //$NON-NLS-1$ - writer.write(" ClassT var6; \n" ); //$NON-NLS-1$ - writer.write(" ClassT var7=var6/*vp6*/; \n" ); //$NON-NLS-1$ - writer.write("} \n" ); //$NON-NLS-1$ - String header = writer.toString(); - IFile h=importFile( "testVariable.h", header ); //$NON-NLS-1$ - writer = new StringWriter(); - writer.write("#include \"testVariable.h\" \n" ); //$NON-NLS-1$ - writer.write("using namespace N; \n" ); //$NON-NLS-1$ - writer.write("ClassT var1(){} \n" ); //$NON-NLS-1$ - writer.write("int f(){ \n" ); //$NON-NLS-1$ - writer.write(" StructT var2; \n" ); //$NON-NLS-1$ - writer.write(" TypedefT var3; \n" ); //$NON-NLS-1$ - writer.write(" UnionT var4; \n" ); //$NON-NLS-1$ - writer.write(" bool var5; \n" ); //$NON-NLS-1$ - writer.write(" var5/*vp1*/; \n" ); //$NON-NLS-1$ - writer.write("} \n" ); //$NON-NLS-1$ - String source = writer.toString(); - IFile f=importFile( "testVariable.cpp", source ); //$NON-NLS-1$ - ICompletionProposal [] results = getResults( f, source.indexOf( "5/*vp1*/" ) ); //$NON-NLS-1$ - assertEquals( "var2 : StructT", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( "var3 : TypedefT", results[1].getDisplayString()); //$NON-NLS-1$ - assertEquals( "var4 : UnionT", results[2].getDisplayString()); //$NON-NLS-1$ - assertEquals( "var5 : bool", results[3].getDisplayString()); //$NON-NLS-1$ - assertEquals( "var6 : ClassT", results[4].getDisplayString()); //$NON-NLS-1$ - assertEquals( "var7 : ClassT", results[5].getDisplayString()); //$NON-NLS-1$ - assertEquals( "var1() ClassT", results[6].getDisplayString()); //$NON-NLS-1$ - assertEquals( 7, results.length); - //vp2 namespace scope - results = getResults( h, header.indexOf( "6/*vp6*/" ) ); //$NON-NLS-1$ - assertEquals( "var6 : ClassT", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( 1, results.length); - - } - - public void test80510() throws Exception { - StringWriter writer = new StringWriter(); - writer.write("int aaa; \n" ); //$NON-NLS-1$ - writer.write("class Class1{ \n" ); //$NON-NLS-1$ - writer.write(" Class1(); \n" ); //$NON-NLS-1$ - writer.write(" int abc; \n" ); //$NON-NLS-1$ - writer.write("}; \n" ); //$NON-NLS-1$ - writer.write("Class1::Class1(): abc/*vp1*/(2){} \n" ); //$NON-NLS-1$ - String code = writer.toString(); - IFile t = importFile( "test80510.cpp", code ); //$NON-NLS-1$ - //vp1 - ICompletionProposal [] results = getResults( t, code.indexOf( "bc/*vp1*/" ) ); //$NON-NLS-1$ - assertEquals( 1, results.length); - assertEquals( "abc : int", results[0].getDisplayString()); //$NON-NLS-1$ - } - public void testSingleNameReference() throws Exception { - StringWriter writer = new StringWriter(); - writer.write("int snrV; \n" ); //$NON-NLS-1$ - writer.write("int snrF(int x){} \n" ); //$NON-NLS-1$ - writer.write("class snrC{void g();int snrFd;}; \n" ); //$NON-NLS-1$ - writer.write("struct snrS{}; \n" ); //$NON-NLS-1$ - writer.write("enum snrE{snrER}; \n" ); //$NON-NLS-1$ - writer.write("void foo() { \n" ); //$NON-NLS-1$ - writer.write(" union snrU{ snrU(int a) {};int i; char* j;};\n" ); //$NON-NLS-1$ - writer.write(" snrU sn(snrV); \n" ); //$NON-NLS-1$ - writer.write(" snrV/*vp1*/=snrF/*vp2*/(snrV); \n" ); //$NON-NLS-1$ - writer.write("} \n" ); //$NON-NLS-1$ - writer.write("void snrC::g(){ \n" ); //$NON-NLS-1$ - writer.write(" snrFd/*vp3*/ c; \n" ); //$NON-NLS-1$ - writer.write("} \n" ); //$NON-NLS-1$ - String source = writer.toString(); - IFile cpp=importFile( "testSingleNameReference.cpp", source ); //$NON-NLS-1$ - //vp1 function scope, lvalue - ICompletionProposal [] results = getResults( cpp, source.indexOf( "rV/*vp1*/" ) ); //$NON-NLS-1$ - assertEquals( "sn : snrU", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( "snrV : int", results[1].getDisplayString()); //$NON-NLS-1$ - assertEquals( "snrF(int) int", results[2].getDisplayString()); //$NON-NLS-1$ - assertEquals( "snrC", results[3].getDisplayString()); //$NON-NLS-1$ - assertEquals( "snrS", results[4].getDisplayString()); //$NON-NLS-1$ - assertEquals( "snrU", results[5].getDisplayString()); //$NON-NLS-1$ - assertEquals( "snrER", results[6].getDisplayString()); //$NON-NLS-1$ - assertEquals( "snrE", results[7].getDisplayString()); //$NON-NLS-1$ - assertEquals( 8, results.length); - //vp1 function scope, RHS - results = getResults( cpp, source.indexOf( "rF/*vp2*/" ) ); //$NON-NLS-1$ - assertEquals( "sn : snrU", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( "snrV : int", results[1].getDisplayString()); //$NON-NLS-1$ - assertEquals( "snrF(int) int", results[2].getDisplayString()); //$NON-NLS-1$ - assertEquals( "snrC", results[3].getDisplayString()); //$NON-NLS-1$ - assertEquals( "snrS", results[4].getDisplayString()); //$NON-NLS-1$ - assertEquals( "snrU", results[5].getDisplayString()); //$NON-NLS-1$ - assertEquals( "snrER", results[6].getDisplayString()); //$NON-NLS-1$ - assertEquals( "snrE", results[7].getDisplayString()); //$NON-NLS-1$ - assertEquals( 8, results.length); - //vp1 method scope - results = getResults( cpp, source.indexOf( "rFd/*vp3*/" ) ); //$NON-NLS-1$ - assertEquals( "snrFd : int", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( "snrV : int", results[1].getDisplayString()); //$NON-NLS-1$ - assertEquals( "snrF(int) int", results[2].getDisplayString()); //$NON-NLS-1$ - assertEquals( "snrC", results[3].getDisplayString()); //$NON-NLS-1$ - assertEquals( "snrS", results[4].getDisplayString()); //$NON-NLS-1$ - assertEquals( "snrER", results[5].getDisplayString()); //$NON-NLS-1$ - assertEquals( "snrE", results[6].getDisplayString()); //$NON-NLS-1$ - assertEquals( 7, results.length); - - } - public void testNamespace() throws Exception { - StringWriter writer = new StringWriter(); - writer.write( "namespace Foo{ \n" ); //$NON-NLS-1$ - writer.write( "int x; \n" ); //$NON-NLS-1$ - writer.write( " namespace Baz { \n" ); //$NON-NLS-1$ - writer.write( " int i; \n" ); //$NON-NLS-1$ - writer.write( " } \n" ); //$NON-NLS-1$ - writer.write( " using namespace Baz/*vp1*/; \n" ); //$NON-NLS-1$ - writer.write( "} \n" ); //$NON-NLS-1$ - writer.write( "void g() { \n" ); //$NON-NLS-1$ - writer.write( " Foo::i/*vp2*/ = 1; \n" ); //$NON-NLS-1$ - writer.write( " int y=Foo::Baz::i;//vp3 \n" ); //$NON-NLS-1$ - writer.write( "} \n" ); //$NON-NLS-1$ - writer.write( "namespace Bar = Foo/*vp4*/; \n" ); //$NON-NLS-1$ - String source = writer.toString(); - IFile cpp=importFile( "testNamespace.cpp", source ); //$NON-NLS-1$ - //vp1 using reference, namespace scope, prefixed - ICompletionProposal [] results = getResults( cpp, source.indexOf( "az/*vp1*/" ) ); //$NON-NLS-1$ - assertEquals( "Baz", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( 1, results.length); - //vp1b using reference, namespace scope, no prefix - results = getResults( cpp, source.indexOf( "Baz/*vp1*/" ) ); //$NON-NLS-1$ - assertEquals( "Baz", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( "Foo", results[1].getDisplayString()); //$NON-NLS-1$ - assertEquals( 2, results.length); - //vp2 function scope - results = getResults( cpp, source.indexOf( "oo::i/*vp2*/" ) ); //$NON-NLS-1$ - assertEquals( "Foo", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( 1, results.length); - //vp3 nested namespace, rhs - results = getResults( cpp, source.indexOf( "az::i;//vp3" ) ); //$NON-NLS-1$ - assertEquals( "Baz", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( 1, results.length); - //vp4 alias definition - results = getResults( cpp, source.indexOf( "oo/*vp4*/" ) ); //$NON-NLS-1$ - assertEquals( "Foo", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( 1, results.length); - } - - public void testNamespaceAlias80612() throws Exception { - StringWriter writer = new StringWriter(); - writer.write( "namespace Foo{ \n" ); //$NON-NLS-1$ - writer.write( "int x; \n" ); //$NON-NLS-1$ - writer.write( "} \n" ); //$NON-NLS-1$ - writer.write( "namespace Bar = Foo/*vp4*/; \n" ); //$NON-NLS-1$ - writer.write( "Bar::x; \n" ); //$NON-NLS-1$ - String source = writer.toString(); - IFile cpp=importFile( "testNamespaceAlias80612.cpp", source ); //$NON-NLS-1$ - //vp1 alias reference - ICompletionProposal [] results = getResults( cpp, source.indexOf( "ar::x" ) ); //$NON-NLS-1$ - assertEquals( 1, results.length); - assertEquals( "Bar", results[0].getDisplayString()); //$NON-NLS-1$ - - } - // test 47 - public void testMacro() throws Exception { - StringWriter writer = new StringWriter(); - writer.write("#define INT32_C(x) x ## L \n"); //$NON-NLS-1$ - writer.write("#define INT32_MAX (2147483647) \n"); //$NON-NLS-1$ - writer.write("int main(int argc, char **argv) { \n"); //$NON-NLS-1$ - writer.write(" INT32_C(2);//vp1 \n"); //$NON-NLS-1$ - writer.write(" return (0); \n"); //$NON-NLS-1$ - writer.write("} \n"); //$NON-NLS-1$ - String code = writer.toString(); - IFile t = importFile( "testMacro.c", code ); //$NON-NLS-1$ - ICompletionProposal [] results = getResults( t, code.indexOf( "32_C(2);//vp1" ) ); //$NON-NLS-1$ - assertEquals( "INT32_C(x)", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( "INT32_MAX", results[1].getDisplayString()); //$NON-NLS-1$ - assertEquals( 2, results.length); - } - public void testConstructor() throws Exception { - StringWriter writer = new StringWriter(); - writer.write( "namespace Foo{ \n" ); //$NON-NLS-1$ - writer.write( "class Base{ \n" ); //$NON-NLS-1$ - writer.write( " Base(int x){} \n" ); //$NON-NLS-1$ - writer.write( " }; \n" ); //$NON-NLS-1$ - writer.write( "class Derived: Base{ \n" ); //$NON-NLS-1$ - writer.write( " Derived(): Base/*vp1*/(4){} \n" ); //$NON-NLS-1$ - writer.write( " }; \n" ); //$NON-NLS-1$ - writer.write( "} \n" ); //$NON-NLS-1$ - writer.write( "void f(){ \n" ); //$NON-NLS-1$ - writer.write( " Foo::Derived& x = *(new Foo::Derived/*vp2*/())/; \n" ); //$NON-NLS-1$ - writer.write( "}; \n" ); //$NON-NLS-1$ - String source = writer.toString(); - IFile cpp=importFile( "testConstructor.cpp", source ); //$NON-NLS-1$ - //vp1 initializer list - ICompletionProposal [] results = getResults( cpp, source.indexOf( "ase/*vp1*/" ) ); //$NON-NLS-1$ - assertEquals( 1, results.length); - assertEquals( "Base", results[0].getDisplayString()); //$NON-NLS-1$ - results = getResults( cpp, source.indexOf( "erived/*vp2*/" ) ); //$NON-NLS-1$ - assertEquals( 1, results.length); - assertEquals( "Derived", results[0].getDisplayString()); //$NON-NLS-1$ - - } - public void testUnion() throws Exception { - StringWriter writer = new StringWriter(); - writer.write( "namespace Foo{ \n" ); //$NON-NLS-1$ - writer.write( "union uni1{}; \n" ); //$NON-NLS-1$ - writer.write( "class c1{ \n" ); //$NON-NLS-1$ - writer.write( " public: union uni2{} s; \n" ); //$NON-NLS-1$ - writer.write( "}; \n" ); //$NON-NLS-1$ - writer.write( "namespace N{ \n" ); //$NON-NLS-1$ - writer.write( " union uni3{}; \n" ); //$NON-NLS-1$ - writer.write( " class c2{ \n" ); //$NON-NLS-1$ - writer.write( " uni1/*vp1*/ s; \n" ); //$NON-NLS-1$ - writer.write( " uni3 ss; \n" ); //$NON-NLS-1$ - writer.write( " c2() { \n" ); //$NON-NLS-1$ - writer.write( " c1::uni2/*vp2*/ s; \n" ); //$NON-NLS-1$ - writer.write( " union uni3/*vp3*/ t; \n" ); //$NON-NLS-1$ - writer.write( " } \n" ); //$NON-NLS-1$ - writer.write( " }; \n" ); //$NON-NLS-1$ - writer.write( "} \n" ); //$NON-NLS-1$ - String source = writer.toString(); - IFile cpp=importFile( "testUnion.cpp", source ); //$NON-NLS-1$ - //vp1 method scope - ICompletionProposal [] results = getResults( cpp, source.indexOf( "1/*vp1*/" ) ); //$NON-NLS-1$ - assertEquals( 3, results.length); - assertEquals( "uni1", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( "uni3", results[1].getDisplayString()); //$NON-NLS-1$ - assertEquals( "union", results[2].getDisplayString()); //$NON-NLS-1$ - //vp2 :: access, in method scope, - results = getResults( cpp, source.indexOf( "i2/*vp2*/" ) );//$NON-NLS-1$ - assertEquals( 1, results.length); - assertEquals( "uni2", results[0].getDisplayString()); //$NON-NLS-1$ - //c style declaration, method scope - results = getResults( cpp, source.indexOf( "i3/*vp3*/" ) );//$NON-NLS-1$ - assertEquals( 2, results.length); - assertEquals( "uni1", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( "uni3", results[1].getDisplayString()); //$NON-NLS-1$ - - } - - public void testKeyword() throws Exception { - StringWriter writer = new StringWriter(); - writer.write( "class/*vp1*/ Foo{ \n" ); //$NON-NLS-1$ - writer.write( "void f(); \n" ); //$NON-NLS-1$ - writer.write( " public/*vp2*/: Foo(); \n" ); //$NON-NLS-1$ - writer.write( "}; \n" ); //$NON-NLS-1$ - writer.write( "void Foo::f() { \n" ); //$NON-NLS-1$ - writer.write( " void/*vp3*/* g; \n" ); //$NON-NLS-1$ - writer.write( "} \n" ); //$NON-NLS-1$ - String source = writer.toString(); - IFile cpp=importFile( "testKeyword.cpp", source ); //$NON-NLS-1$ - //vp1 global - ICompletionProposal [] results = getResults( cpp, source.indexOf( "lass/*vp1*/" ) ); //$NON-NLS-1$ - assertEquals( 3, results.length); - assertEquals( "char", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( "class", results[1].getDisplayString()); //$NON-NLS-1$ - assertEquals( "const", results[2].getDisplayString()); //$NON-NLS-1$ - //vp2 class - results = getResults( cpp, source.indexOf( "lic/*vp2*/" ) );//$NON-NLS-1$ - assertEquals( 1, results.length); - assertEquals( "public", results[0].getDisplayString()); //$NON-NLS-1$ - //vp3 method - results = getResults( cpp, source.indexOf( "d/*vp3*/" ) );//$NON-NLS-1$ - assertEquals( 1, results.length); - assertEquals( "void", results[0].getDisplayString()); //$NON-NLS-1$ - - } - public void testBase() throws Exception { - StringWriter writer = new StringWriter(); - writer.write( "class Base{ \n" ); //$NON-NLS-1$ - writer.write( " Base(); \n" ); //$NON-NLS-1$ - writer.write( " protected: int b();\n" ); //$NON-NLS-1$ - writer.write( "}; \n" ); //$NON-NLS-1$ - writer.write( "class Derived: Base{ \n" ); //$NON-NLS-1$ - writer.write( " Derived(); \n" ); //$NON-NLS-1$ - writer.write( " void d() { \n" ); //$NON-NLS-1$ - writer.write( " b/*vp1*/{ \n" ); //$NON-NLS-1$ - writer.write( "}; \n" ); //$NON-NLS-1$ - String source = writer.toString(); - IFile cpp=importFile( "testBase.cpp", source ); //$NON-NLS-1$ - //vp1 method scope - ICompletionProposal [] results = getResults( cpp, source.indexOf( "/*vp1*/" ) ); //$NON-NLS-1$ - assertEquals( 4, results.length); - assertEquals( "b() int", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( "Base", results[1].getDisplayString()); //$NON-NLS-1$ - assertEquals( "bool", results[2].getDisplayString()); //$NON-NLS-1$ - assertEquals( "break", results[3].getDisplayString()); //$NON-NLS-1$ - - } - public void testThis() throws Exception { - StringWriter writer = new StringWriter(); - writer.write( "class X{ \n" ); //$NON-NLS-1$ - writer.write( " X& X::operator=(const X& rhs){ \n"); //$NON-NLS-1$ - writer.write( " if(this/*vp1*/==&rhs)return *this; \n" ); //$NON-NLS-1$ - writer.write( " (*this/*vp2*/).aVar=rhs.aVar; \n" ); //$NON-NLS-1$ - writer.write( " this/*vp3*/->anotherVar=rhs.anotherVar;\n" ); //$NON-NLS-1$ - writer.write( " return *this; \n" ); //$NON-NLS-1$ - writer.write( " } \n" ); //$NON-NLS-1$ - writer.write( " int aVar, anotherVar; \n" ); //$NON-NLS-1$ - writer.write( "}; \n" ); //$NON-NLS-1$ - String source = writer.toString(); - IFile cpp=importFile( "testThis.cpp", source ); //$NON-NLS-1$ - //vp1 method scope - ICompletionProposal [] results = getResults( cpp, source.indexOf( "s/*vp1*/" ) ); //$NON-NLS-1$ - assertEquals( 1, results.length); - assertEquals( "this", results[0].getDisplayString()); //$NON-NLS-1$ - results = getResults( cpp, source.indexOf( "s/*vp2*/" ) ); //$NON-NLS-1$ - assertEquals( 1, results.length); - assertEquals( "this", results[0].getDisplayString()); //$NON-NLS-1$ - results = getResults( cpp, source.indexOf( "s/*vp3*/" ) ); //$NON-NLS-1$ - assertEquals( 1, results.length); - assertEquals( "this", results[0].getDisplayString()); //$NON-NLS-1$ - - } - public void testClassScope() throws Exception { - StringWriter writer = new StringWriter(); - writer.write( "class Foo{ \n" ); //$NON-NLS-1$ - writer.write( " public: \n" ); //$NON-NLS-1$ - writer.write( " Foo(){} \n" ); //$NON-NLS-1$ - writer.write( " int getThatVar(); \n" ); //$NON-NLS-1$ - writer.write( " private: \n" ); //$NON-NLS-1$ - writer.write( " int thatVar; \n" ); //$NON-NLS-1$ - writer.write( " }; \n" ); //$NON-NLS-1$ - String header = writer.toString(); - importFile( "testClassScope.h", header ); //$NON-NLS-1$ - writer.write( " #include \"testClassScope.h\" \n" ); //$NON-NLS-1$ - writer.write( " int Foo::getThatVar/*vp1*/(){ \n" ); //$NON-NLS-1$ - writer.write( " return thatVar/*vp2*/; \n" ); //$NON-NLS-1$ - writer.write( " } \n" ); //$NON-NLS-1$ - String source = writer.toString(); - IFile cpp=importFile( "testClassScope.cpp", source ); //$NON-NLS-1$ - //vp1 method scope - ICompletionProposal [] results = getResults( cpp, source.indexOf( "Var/*vp1*/" ) ); //$NON-NLS-1$ - assertEquals( 1, results.length); - assertEquals( "getThatVar() int", results[0].getDisplayString()); //$NON-NLS-1$ - results = getResults( cpp, source.indexOf( "Var/*vp2*/" ) ); //$NON-NLS-1$ - assertEquals( 1, results.length); - assertEquals( "thatVar : int", results[0].getDisplayString()); //$NON-NLS-1$ - - } - - public void testClassScope72564() throws Exception { - StringWriter writer = new StringWriter(); - writer.write( "class X{ \n" ); //$NON-NLS-1$ - writer.write( "class ElStatico{ \n" ); //$NON-NLS-1$ - writer.write( " public: \n" ); //$NON-NLS-1$ - writer.write( " ElStatico(){} \n" ); //$NON-NLS-1$ - writer.write( " virtual ~ElStatico(){} \n" ); //$NON-NLS-1$ - writer.write( " private: \n" ); //$NON-NLS-1$ - writer.write( " static int aClsVar; \n" ); //$NON-NLS-1$ - writer.write( " }; \n" ); //$NON-NLS-1$ - String header = writer.toString(); - importFile( "testClassScope72564.h", header ); //$NON-NLS-1$ - writer.write( " #include \"testClassScope72564.h\" \n" ); //$NON-NLS-1$ - writer.write( " int ElStatico::aClsVar/*vp1*/ = 10; \n" ); //$NON-NLS-1$ - String source = writer.toString(); - IFile cpp=importFile( "testClassScope72564.cpp", source ); //$NON-NLS-1$ - //vp1 method scope - ICompletionProposal [] results = getResults( cpp, source.indexOf( "Var/*vp1*/" ) ); //$NON-NLS-1$ - assertEquals( 1, results.length); - assertEquals( "aClsVar", results[0].getDisplayString()); //$NON-NLS-1$ - - } - public void testMultiLevelQualifiers() throws Exception { - StringWriter writer = new StringWriter(); - writer.write( "class A{ \n" ); //$NON-NLS-1$ - writer.write( "public: class B{ \n" ); //$NON-NLS-1$ - writer.write( "public: class C{ \n" ); //$NON-NLS-1$ - writer.write( "public: class D{ \n" ); //$NON-NLS-1$ - writer.write( "public: class E{ \n" ); //$NON-NLS-1$ - writer.write( "public: class F{ \n" ); //$NON-NLS-1$ - writer.write( "public: class G{ \n" ); //$NON-NLS-1$ - writer.write( "public: class H{ \n" ); //$NON-NLS-1$ - writer.write( "public: class I{ \n" ); //$NON-NLS-1$ - writer.write( "public: class J{ \n" ); //$NON-NLS-1$ - writer.write( "public: class K{ \n" ); //$NON-NLS-1$ - writer.write( "public: class L{ \n" ); //$NON-NLS-1$ - writer.write( "public: class M{ \n" ); //$NON-NLS-1$ - writer.write( "}m;}l;}k;}j;}i;}h;}g;}f;}e;}d;}c;}b;}; \n" ); //$NON-NLS-1$ - writer.write( " A a; \n" ); //$NON-NLS-1$ - writer.write( " void f(){ \n" ); //$NON-NLS-1$ - writer.write( " a.b.c.d.e.f.g.h.i.j.k.l.m/*vp1*/; \n" ); //$NON-NLS-1$ - writer.write( " } \n" ); //$NON-NLS-1$ - String source = writer.toString(); - IFile cpp=importFile( "testMultiLevelQualifiers.cpp", source ); //$NON-NLS-1$ - //vp1 13 qualifier depth - ICompletionProposal [] results = getResults( cpp, source.indexOf( "m/*vp1*/" ) ); //$NON-NLS-1$ - assertEquals( 1, results.length); - assertEquals( "m : M", results[0].getDisplayString()); //$NON-NLS-1$ - - } - public void testCase() throws Exception { - StringWriter writer = new StringWriter(); - writer.write( "class Ananas{ \n" ); //$NON-NLS-1$ - writer.write( "public: Ananas(); \n" ); //$NON-NLS-1$ - writer.write( "void ananas(int i); \n" ); //$NON-NLS-1$ - writer.write( "int aNaNaS(); \n" ); //$NON-NLS-1$ - writer.write( "int ANAnas; \n" ); //$NON-NLS-1$ - writer.write( "}; \n" ); //$NON-NLS-1$ - writer.write( "int ananaS; \n" ); //$NON-NLS-1$ - writer.write( "void anaNAS(){ \n" ); //$NON-NLS-1$ - writer.write( "Ananas/*vp1*/ a; \n" ); //$NON-NLS-1$ - writer.write( "a.aNaNaS/*vp2*/(); \n" ); //$NON-NLS-1$ - writer.write( "} \n" ); //$NON-NLS-1$ - String source = writer.toString(); - IFile cpp=importFile( "testCase.cpp", source ); //$NON-NLS-1$ - //vp1 global scope - ICompletionProposal [] results = getResults( cpp, source.indexOf( "nas/*vp1*/" ) ); //$NON-NLS-1$ - assertEquals( 3, results.length); - assertEquals( "Ananas", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( "ananaS : int", results[1].getDisplayString()); //$NON-NLS-1$ - assertEquals( "anaNAS() void", results[2].getDisplayString()); //$NON-NLS-1$ - //vp2 class scope - results = getResults( cpp, source.indexOf( "NaS/*vp2*/" ) ); //$NON-NLS-1$ - assertEquals( 3, results.length); - assertEquals( "aNaNaS() int", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( "ANAnas : int", results[1].getDisplayString()); //$NON-NLS-1$ - assertEquals( "ananas(int) void", results[2].getDisplayString()); //$NON-NLS-1$ - } - //test 32 - public void testType() throws Exception { - StringWriter writer = new StringWriter(); - writer.write("namespace N { \n" ); //$NON-NLS-1$ - writer.write(" class ClassT {}; \n" ); //$NON-NLS-1$ - writer.write(" struct StructT {}; \n" ); //$NON-NLS-1$ - writer.write(" typedef struct {} TypedefT; \n" ); //$NON-NLS-1$ - writer.write(" union UnionT {}; \n" ); //$NON-NLS-1$ - writer.write("} \n" ); //$NON-NLS-1$ - String codeH = writer.toString(); - importFile( "testType.h", codeH ); //$NON-NLS-1$ - writer = new StringWriter(); - writer.write("#include \"testType.h\" \n" ); //$NON-NLS-1$ - writer.write("int main (int argc, char** argv){ \n" ); //$NON-NLS-1$ - writer.write(" using namespace N; \n" ); //$NON-NLS-1$ - writer.write(" ClassT/*vp1*/ c; \n" ); //$NON-NLS-1$ - writer.write(" StructT/*vp2*/ d; \n" ); //$NON-NLS-1$ - writer.write(" TypedefT/*vp3*/ e; \n" ); //$NON-NLS-1$ - writer.write(" UnionT/*vp4*/ f; \n" ); //$NON-NLS-1$ - writer.write(" bool/*vp5*/ b; \n" ); //$NON-NLS-1$ - writer.write("} \n" ); //$NON-NLS-1$ - String code = writer.toString(); - IFile f=importFile( "testType.cpp", code ); //$NON-NLS-1$ - ICompletionProposal [] results = getResults( f, code.indexOf( "T/*vp1*/" ) ); //$NON-NLS-1$ - assertEquals( "ClassT", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( 1, results.length); - results = getResults( f, code.indexOf( "T/*vp2*/" ) ); //$NON-NLS-1$ - assertEquals( "StructT", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( 1, results.length); - results = getResults( f, code.indexOf( "T/*vp3*/" ) ); //$NON-NLS-1$ - assertEquals( "TypedefT", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( 1, results.length); - results = getResults( f, code.indexOf( "T/*vp4*/" ) ); //$NON-NLS-1$ - assertEquals( "UnionT", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( 1, results.length); - results = getResults( f, code.indexOf( "l/*vp5*/" ) ); //$NON-NLS-1$ - assertEquals( "bool", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( 1, results.length); - } - //this doesn't test defect 72403 where try catch fails when a system file is included - public void testTryCatch() throws Exception { - StringWriter writer = new StringWriter(); - writer.write("class MyException{ \n" ); //$NON-NLS-1$ - writer.write(" public: \n" ); //$NON-NLS-1$ - writer.write(" MyException(const char *msg){} \n" ); //$NON-NLS-1$ - writer.write(" const char* getMsg(){return \"error\";} \n" ); //$NON-NLS-1$ - writer.write("}; \n" ); //$NON-NLS-1$ - writer.write("void someFunction() { \n" ); //$NON-NLS-1$ - writer.write(" throw MyException(\"someFunction is in trouble\");\n" ); //$NON-NLS-1$ - writer.write("} \n" ); //$NON-NLS-1$ - writer.write("void k(){ \n" ); //$NON-NLS-1$ - writer.write(" try { \n" ); //$NON-NLS-1$ - writer.write(" someFunction/*vp1*/(); \n" ); //$NON-NLS-1$ - writer.write(" } catch (MyException &e) { \n" ); //$NON-NLS-1$ - writer.write(" e.getMsg/*vp2*/(); \n" ); //$NON-NLS-1$ - writer.write(" } \n" ); //$NON-NLS-1$ - writer.write("} \n" ); //$NON-NLS-1$ - String code = writer.toString(); - IFile f=importFile( "testTryCatch.cpp", code ); //$NON-NLS-1$ - ICompletionProposal [] results = getResults( f, code.indexOf( "Function/*vp1*/" ) ); //$NON-NLS-1$ - assertEquals( "someFunction() void", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( 1, results.length); - results = getResults( f, code.indexOf( "Msg/*vp2*/" ) ); //$NON-NLS-1$ - assertEquals( "getMsg() const char*", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( 1, results.length); - } - public void testArrays() throws Exception { - StringWriter writer = new StringWriter(); - writer.write(" class A{ \n" ); //$NON-NLS-1$ - writer.write(" public: \n" ); //$NON-NLS-1$ - writer.write(" A(){} \n" ); //$NON-NLS-1$ - writer.write(" void aa(); \n" ); //$NON-NLS-1$ - writer.write(" int aaa; \n" ); //$NON-NLS-1$ - writer.write(" static int bbb; \n" ); //$NON-NLS-1$ - writer.write(" }; \n" ); //$NON-NLS-1$ - writer.write(" void fodo(){ \n" ); //$NON-NLS-1$ - writer.write(" A a_array[10]; \n" ); //$NON-NLS-1$ - writer.write(" A* b_array[10]; \n" ); //$NON-NLS-1$ - writer.write(" for (int i=0; i<10;i++){ \n" ); //$NON-NLS-1$ - writer.write(" a_array[i].aaa/*vp1*/=3;\n" ); //$NON-NLS-1$ - writer.write(" int x=b_array[i]->bbb/*vp2*/;\n" ); //$NON-NLS-1$ - writer.write(" } \n" ); //$NON-NLS-1$ - String code = writer.toString(); - IFile f=importFile( "testArrays.cpp", code ); //$NON-NLS-1$ - //vp1 dot ref - ICompletionProposal [] results = getResults( f, code.indexOf( "a/*vp1*/" ) ); //$NON-NLS-1$ - assertEquals( "aa() void", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( "aaa : int", results[1].getDisplayString()); //$NON-NLS-1$ - assertEquals( 2, results.length); - //vp2 arrow ref - results = getResults( f, code.indexOf( "bbb/*vp2*/" ) ); //$NON-NLS-1$ - assertEquals( "aaa : int", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( "bbb : int", results[1].getDisplayString()); //$NON-NLS-1$ - assertEquals( "aa() void", results[2].getDisplayString()); //$NON-NLS-1$ - assertEquals( 3, results.length); - } - public void testStruct() throws Exception { - StringWriter writer = new StringWriter(); - writer.write("//aggregate struct (no constructor) \n" ); //$NON-NLS-1$ - writer.write("struct myStruct_c{int m;}ss1={1},ss2={2}; \n" ); //$NON-NLS-1$ - writer.write("void foo() { \n" ); //$NON-NLS-1$ - writer.write(" myStruct_c *ss3; \n" ); //$NON-NLS-1$ - writer.write(" ss3->m=3; \n" ); //$NON-NLS-1$ - writer.write(" int i=(ss1.m/*vp1*/ > ss3->m/*vp2*/ ? ss1/*vp3*/ : ss2/*vp4*/).m;\n" ); //$NON-NLS-1$ - writer.write(" //struct with constructor \n" ); //$NON-NLS-1$ - writer.write(" sizeof(myStruct_c/*vp8*/); \n" ); //$NON-NLS-1$ - writer.write(" struct myStruct_cpp { \n" ); //$NON-NLS-1$ - writer.write(" myStruct_cpp(int x){z=x;} \n" ); //$NON-NLS-1$ - writer.write(" int z; \n" ); //$NON-NLS-1$ - writer.write(" }; \n" ); //$NON-NLS-1$ - writer.write(" myStruct_cpp ss4(4), *ss5; \n" ); //$NON-NLS-1$ - writer.write(" ss5=new myStruct_cpp/*vp9*/(5); \n" ); //$NON-NLS-1$ - writer.write(" 3>ss4.z/*vp5*/ ? ss5->z/*vp6*/ : ss4.z/*vp7*/; \n" ); //$NON-NLS-1$ - writer.write("} \n" ); //$NON-NLS-1$ - String code = writer.toString(); - IFile f=importFile( "testStruct.cpp", code ); //$NON-NLS-1$ - //vp1 aggregate: first operand of ?:, first operand of > - ICompletionProposal [] results = getResults( f, code.indexOf( "1.m/*vp1*/" ) ); //$NON-NLS-1$ - assertEquals( "ss3 : myStruct_c*", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( "ss1 : myStruct_c", results[1].getDisplayString()); //$NON-NLS-1$ - assertEquals( "ss2 : myStruct_c", results[2].getDisplayString()); //$NON-NLS-1$ - assertEquals( 3, results.length); - //vp2 aggregate: first operand of ?:, second operand of > - results = getResults( f, code.indexOf( "3->m/*vp2*/" ) ); //$NON-NLS-1$ - assertEquals( "ss3 : myStruct_c*", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( "ss1 : myStruct_c", results[1].getDisplayString()); //$NON-NLS-1$ - assertEquals( "ss2 : myStruct_c", results[2].getDisplayString()); //$NON-NLS-1$ - assertEquals( 3, results.length); - //vp3 aggregate: second operand of ?: - results = getResults( f, code.indexOf( "1/*vp3*/" ) ); //$NON-NLS-1$ - assertEquals( "ss3 : myStruct_c*", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( "ss1 : myStruct_c", results[1].getDisplayString()); //$NON-NLS-1$ - assertEquals( "ss2 : myStruct_c", results[2].getDisplayString()); //$NON-NLS-1$ - assertEquals( 3, results.length); - //vp4 aggregate: third operand of ?: - results = getResults( f, code.indexOf( "2/*vp4*/" ) ); //$NON-NLS-1$ - assertEquals( "ss3 : myStruct_c*", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( "ss1 : myStruct_c", results[1].getDisplayString()); //$NON-NLS-1$ - assertEquals( "ss2 : myStruct_c", results[2].getDisplayString()); //$NON-NLS-1$ - assertEquals( 3, results.length); - //vp5 first operand of ?:, second operand of > - results = getResults( f, code.indexOf( "4.z/*vp5*/" ) ); //$NON-NLS-1$ - assertEquals( "ss3 : myStruct_c*", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( "ss4 : myStruct_cpp", results[1].getDisplayString()); //$NON-NLS-1$ - assertEquals( "ss5 : myStruct_cpp*", results[2].getDisplayString()); //$NON-NLS-1$ - assertEquals( "ss1 : myStruct_c", results[3].getDisplayString()); //$NON-NLS-1$ - assertEquals( "ss2 : myStruct_c", results[4].getDisplayString()); //$NON-NLS-1$ - assertEquals( 5, results.length); - //vp6 second operand of ?: - results = getResults( f, code.indexOf( "5->z/*vp6*/" ) ); //$NON-NLS-1$ - assertEquals( "ss3 : myStruct_c*", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( "ss4 : myStruct_cpp", results[1].getDisplayString()); //$NON-NLS-1$ - assertEquals( "ss5 : myStruct_cpp*", results[2].getDisplayString()); //$NON-NLS-1$ - assertEquals( "ss1 : myStruct_c", results[3].getDisplayString()); //$NON-NLS-1$ - assertEquals( "ss2 : myStruct_c", results[4].getDisplayString()); //$NON-NLS-1$ - assertEquals( 5, results.length); - //vp7 third operand of ?: - results = getResults( f, code.indexOf( "4.z/*vp7*/" ) ); //$NON-NLS-1$ - assertEquals( "ss3 : myStruct_c*", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( "ss4 : myStruct_cpp", results[1].getDisplayString()); //$NON-NLS-1$ - assertEquals( "ss5 : myStruct_cpp*", results[2].getDisplayString()); //$NON-NLS-1$ - assertEquals( "ss1 : myStruct_c", results[3].getDisplayString()); //$NON-NLS-1$ - assertEquals( "ss2 : myStruct_c", results[4].getDisplayString()); //$NON-NLS-1$ - assertEquals( 5, results.length); - //vp8 struct type in sizeof - results = getResults( f, code.indexOf( "Struct_c/*vp8*/" ) ); //$NON-NLS-1$ - assertEquals( "myStruct_c", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( 1, results.length); - //vp9 constructor call - results = getResults( f, code.indexOf( "Struct_cpp/*vp9*/" ) ); //$NON-NLS-1$ - assertEquals( "myStruct_c", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( "myStruct_cpp", results[1].getDisplayString()); //$NON-NLS-1$ - assertEquals( 2, results.length); - } - // test 16 template completion - // template test framework not implemented - public void testCodeTemplate() throws Exception { - StringWriter writer = new StringWriter(); - writer.write("int main(int argc, char **argv) { \n" ); //$NON-NLS-1$ - writer.write(" int max=10; \n" ); //$NON-NLS-1$ - writer.write(" bool condition=false; \n" ); //$NON-NLS-1$ - writer.write(" int key=1; \n" ); //$NON-NLS-1$ - writer.write(" const int value=1; \n" ); //$NON-NLS-1$ - writer.write(" for/*vp1*/ (int var = 0; var < max; ++var) {\n" ); //$NON-NLS-1$ - writer.write(" \n" ); //$NON-NLS-1$ - writer.write(" } \n" ); //$NON-NLS-1$ - writer.write(" do/*vp2*/ { \n" ); //$NON-NLS-1$ - writer.write(" \n" ); //$NON-NLS-1$ - writer.write(" } while (condition); \n" ); //$NON-NLS-1$ - writer.write(" switch/*vp3*/ (key) { \n" ); //$NON-NLS-1$ - writer.write(" case value: \n" ); //$NON-NLS-1$ - writer.write(" \n" ); //$NON-NLS-1$ - writer.write(" break; \n" ); //$NON-NLS-1$ - writer.write(" default: \n" ); //$NON-NLS-1$ - writer.write(" break; \n" ); //$NON-NLS-1$ - writer.write(" } \n" ); //$NON-NLS-1$ - writer.write("} \n" ); //$NON-NLS-1$ - String code = writer.toString(); - IFile t = importFile( "testCodeTemplate.cpp", code ); //$NON-NLS-1$ - //vp1 for template - ICompletionProposal [] results = getResults( t, code.indexOf( "/*vp1*/" ) ); //$NON-NLS-1$ - assertEquals( 3, results.length); - assertEquals( "for", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( "for - for loop", results[1].getDisplayString()); //$NON-NLS-1$ - assertEquals( "for - for loop with temporary variable", results[2].getDisplayString()); //$NON-NLS-1$ - //vp2 do while loop template - assertEquals( 3, results.length); - results = getResults( t, code.indexOf( "/*vp2*/" ) ); //$NON-NLS-1$ - assertEquals( "do", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( "double", results[1].getDisplayString()); //$NON-NLS-1$ - assertEquals( "do - do while statement", results[2].getDisplayString()); //$NON-NLS-1$ - //vp3 switch case statement template - assertEquals( 2, results.length); - results = getResults( t, code.indexOf( "ch/*vp3*/" ) ); //$NON-NLS-1$ - assertEquals( "switch", results[0].getDisplayString()); //$NON-NLS-1$ - assertEquals( "switch - switch case statement", results[1].getDisplayString()); //$NON-NLS-1$ - - } -} diff --git a/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/regression/RefactoringRegressionTests.java b/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/regression/RefactoringRegressionTests.java deleted file mode 100644 index c99064fd0dc..00000000000 --- a/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/regression/RefactoringRegressionTests.java +++ /dev/null @@ -1,1344 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ - -/* - * Created on Nov 10, 2004 - */ -package org.eclipse.cdt.ui.tests.regression; - -import java.io.StringWriter; - -import junit.framework.AssertionFailedError; -import junit.framework.Test; -import junit.framework.TestSuite; - -import org.eclipse.cdt.core.model.CModelException; -import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.cdt.core.model.ISourceReference; -import org.eclipse.cdt.core.tests.FailingTest; -import org.eclipse.cdt.core.tests.SearchRegressionTests; -import org.eclipse.cdt.internal.core.model.CModelManager; -import org.eclipse.cdt.internal.core.model.TranslationUnit; -import org.eclipse.cdt.internal.corext.refactoring.RenameRefactoring; -import org.eclipse.cdt.internal.corext.refactoring.base.IChange; -import org.eclipse.cdt.internal.corext.refactoring.base.ICompositeChange; -import org.eclipse.cdt.internal.corext.refactoring.base.RefactoringStatus; -import org.eclipse.cdt.internal.corext.refactoring.base.RefactoringStatusEntry; -import org.eclipse.cdt.internal.corext.refactoring.changes.TranslationUnitChange; -import org.eclipse.cdt.internal.corext.refactoring.rename.RenameElementProcessor; -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.runtime.NullProgressMonitor; -import java.util.List; -import org.eclipse.text.edits.MultiTextEdit; -import org.eclipse.text.edits.ReplaceEdit; -import org.eclipse.text.edits.TextEdit; - -/** - * @author aniefer - */ -public class RefactoringRegressionTests extends SearchRegressionTests { - - public RefactoringRegressionTests() - { - super(); - } - public RefactoringRegressionTests(String name) - { - super(name); - } - - /** - * - * @param element The CElement to rename - * @param newName The new name for the element - * @return - * @throws Exception - */ - public IChange getRefactorChanges( ISourceReference element, String newName ) throws Exception { - RenameRefactoring fRefactoring = new RenameRefactoring(element); - RenameElementProcessor processor = (RenameElementProcessor) fRefactoring.getProcessor(); - processor.setNewElementName( newName ); - - RefactoringStatus rs =fRefactoring.checkInput( new NullProgressMonitor() ); - if (!rs.hasError()){ - IChange change = fRefactoring.createChange( new NullProgressMonitor() ); - return change; - } - - fail ("Input check on "+ newName + " failed. "+rs.getFirstMessage(RefactoringStatus.ERROR) ); //$NON-NLS-1$ //$NON-NLS-2$ - //rs.getFirstMessage(RefactoringStatus.ERROR) is not the message displayed in - //the UI for renaming a method to a constructor, the first message which is only - //a warning is shown in the UI. If you click preview, then the error and the warning - //is shown. - return null; - } - public String[] getRefactorMessages( ISourceReference element, String newName ) throws Exception { - String[] result; - RenameRefactoring fRefactoring = new RenameRefactoring(element); - RenameElementProcessor processor = (RenameElementProcessor) fRefactoring.getProcessor(); - processor.setNewElementName( newName ); - - RefactoringStatus rs =fRefactoring.checkInput( new NullProgressMonitor() ); - if (!rs.hasWarning()){ - fail ("Input check on "+ newName + " passed. There should have been warnings or errors. ") ; //$NON-NLS-1$ //$NON-NLS-2$ - return null; - } - List rse = rs.getEntries(); - result = new String[rse.size()]; - for (int i=0; i< rse.size(); i++){ - RefactoringStatusEntry entry = (RefactoringStatusEntry) rse.get(i); - result[i]=entry.getMessage(); - - } - return result; - } - public int getRefactorSeverity( ISourceReference element, String newName ) throws Exception { - RenameRefactoring fRefactoring = new RenameRefactoring(element); - RenameElementProcessor processor = (RenameElementProcessor) fRefactoring.getProcessor(); - processor.setNewElementName( newName ); - - RefactoringStatus rs =fRefactoring.checkInput( new NullProgressMonitor() ); - - return (rs.getSeverity()); - } - protected ISourceReference findElementAtOffset( IFile file, int offset ) throws CModelException{ - CModelManager manager = CModelManager.getDefault(); - TranslationUnit tu = (TranslationUnit) manager.create( file, cproject ); - ICElement el = tu.getElementAtOffset( offset ); - return (ISourceReference) ( ( el instanceof ISourceReference ) ? el : null ); - } - - public static Test suite(){ - return suite( true ); - } - public static Test suite( boolean cleanup ) { - TestSuite suite = new TestSuite("RefactoringRegressionTests"); //$NON-NLS-1$ - suite.addTest( new RefactoringRegressionTests("testSimpleRename") ); //$NON-NLS-1$ - suite.addTest( new RefactoringRegressionTests("testClass_1") ); //$NON-NLS-1$ - suite.addTest( new RefactoringRegressionTests("testAttribute_2") ); //$NON-NLS-1$ - suite.addTest( new RefactoringRegressionTests("testMethod_3") ); //$NON-NLS-1$ - suite.addTest( new RefactoringRegressionTests("testConstructor_26") ); //$NON-NLS-1$ - suite.addTest( new RefactoringRegressionTests("testConstructor_27") ); //$NON-NLS-1$ - suite.addTest( new RefactoringRegressionTests("testDestructor_28") ); //$NON-NLS-1$ - suite.addTest( new FailingTest( new RefactoringRegressionTests("testDestructor_29_72612"), 72612) ); //$NON-NLS-1$ -// suite.addTest( new RefactoringRegressionTests("testFunction_31") ); //$NON-NLS-1$ - suite.addTest( new FailingTest( new RefactoringRegressionTests("testMethod_32_72717"),72717) ); //$NON-NLS-1$ - suite.addTest( new RefactoringRegressionTests("testMethod_33_72605") ); //$NON-NLS-1$ - suite.addTest( new RefactoringRegressionTests("testMethod_34") ); //$NON-NLS-1$ - suite.addTest( new FailingTest( new RefactoringRegressionTests("testMethod_35_72726"),72726) ); //$NON-NLS-1$ - suite.addTest( new RefactoringRegressionTests("testMethod_39") ); //$NON-NLS-1$ - suite.addTest( new RefactoringRegressionTests("testMethod_40") ); //$NON-NLS-1$ - suite.addTest( new RefactoringRegressionTests("testMethod_41") ); //$NON-NLS-1$ - suite.addTest( new RefactoringRegressionTests("testMethod_43") ); //$NON-NLS-1$ - suite.addTest( new RefactoringRegressionTests("testMethod_44") ); //$NON-NLS-1$ - suite.addTest( new FailingTest( new RefactoringRegressionTests("testMethod_45_72723"), 72723) ); //$NON-NLS-1$ - suite.addTest( new RefactoringRegressionTests("testStruct_46") ); //$NON-NLS-1$ - suite.addTest( new RefactoringRegressionTests("testUnion_47") ); //$NON-NLS-1$ - suite.addTest( new RefactoringRegressionTests("testEnumeration_48") ); //$NON-NLS-1$ - suite.addTest( new FailingTest( new RefactoringRegressionTests("testTemplate_49_72626"), 72626) ); //$NON-NLS-1$ - suite.addTest( new RefactoringRegressionTests("testClass_52") ); //$NON-NLS-1$ - suite.addTest( new RefactoringRegressionTests("testClass_53") ); //$NON-NLS-1$ - suite.addTest( new RefactoringRegressionTests("testAttribute_54") ); //$NON-NLS-1$ - suite.addTest( new FailingTest( new RefactoringRegressionTests("testClass_55_79231"), 79231) ); //$NON-NLS-1$ - suite.addTest( new RefactoringRegressionTests("testClass_55") ); //$NON-NLS-1$ - suite.addTest( new RefactoringRegressionTests("testClass_55_72748")); //$NON-NLS-1$ - suite.addTest( new RefactoringRegressionTests("testClass_56") ); //$NON-NLS-1$ - suite.addTest( new RefactoringRegressionTests("testClass_60") ); //$NON-NLS-1$ - suite.addTest( new RefactoringRegressionTests("testAttribute_61") ); //$NON-NLS-1$ - suite.addTest( new RefactoringRegressionTests("testEnumerator_62") ); //$NON-NLS-1$ - suite.addTest( new RefactoringRegressionTests("testAttribute_63") ); //$NON-NLS-1$ - suite.addTest( new RefactoringRegressionTests("testAttribute_64") ); //$NON-NLS-1$ - suite.addTest( new RefactoringRegressionTests("testAttribute_65") ); //$NON-NLS-1$ - suite.addTest( new RefactoringRegressionTests("testNamespace_66") ); //$NON-NLS-1$ - suite.addTest( new FailingTest( new RefactoringRegressionTests("testNamespace_66_79281"), 79281) ); //$NON-NLS-1$ - suite.addTest( new FailingTest( new RefactoringRegressionTests("testNamespace_66_79282"), 79282) ); //$NON-NLS-1$ - suite.addTest( new RefactoringRegressionTests("testFunction_67") ); //$NON-NLS-1$ - suite.addTest( new RefactoringRegressionTests("testVariable_68") ); //$NON-NLS-1$ - suite.addTest( new FailingTest( new RefactoringRegressionTests("testVariable_68_79295"), 79295) ); //$NON-NLS-1$ - suite.addTest( new FailingTest( new RefactoringRegressionTests("testClass_81_72620"),72620) ); //$NON-NLS-1$ - suite.addTest( new FailingTest( new RefactoringRegressionTests("testVariable_88_72617"), 72617) ); //$NON-NLS-1$ - suite.addTest( new RefactoringRegressionTests("testClass_92A") ); //$NON-NLS-1$ - suite.addTest( new RefactoringRegressionTests("testClass_92B") ); //$NON-NLS-1$ - - if( cleanup ) - suite.addTest( new RefactoringRegressionTests("cleanupProject") ); //$NON-NLS-1$ - - return suite; - } - - protected void assertTotalChanges( int numChanges, IChange changes ) throws Exception { - int count = 0; - if( changes != null ) - count = countChanges( changes ); - assertEquals( numChanges, count ); - } - - private int countChanges( IChange change ){ - int count = 0; - if( change instanceof ICompositeChange ){ - IChange [] children = ((ICompositeChange) change).getChildren(); - for( int i = 0; i < children.length; i++ ){ - count += countChanges( children[i] ); - } - } else if( change instanceof TranslationUnitChange ){ - count += countEdits( ((TranslationUnitChange) change).getEdit() ); - } - return count; - } - - private int countEdits( TextEdit edit ){ - if( edit instanceof MultiTextEdit ){ - return ((MultiTextEdit) edit).getChildrenSize(); - } - return 1; - } - - /** - * - * @param changes The IChange returned from getRefactorChanges - * @param file The file we expect to see the change in - * @param startOffset The offset of the name that will be changed - * @param numChars The length of the original name that is changing - * @param newText The new text that the element will be renamed to - * @throws Exception - */ - protected void assertChange( IChange changes, IFile file, int startOffset, int numChars, String newText ) throws Exception { - boolean found = false; - if( changes != null && changes instanceof ICompositeChange ){ - found = checkCompositeChange( (ICompositeChange) changes, file, startOffset, numChars, newText ); - } - - if( !found ) { - fail ("Rename at offset " + startOffset + " in \"" + file.getLocation() + "\" not found."); //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$ - assertFalse( true ); - } - } - private boolean checkCompositeChange( ICompositeChange composite, IFile file, int startOffset, int numChars, String newText ){ - boolean found = false; - IChange [] children = composite.getChildren(); - for( int i = 0; i < children.length; i++ ){ - if( children[i] instanceof ICompositeChange ) - found = checkCompositeChange( (ICompositeChange) children[i], file, startOffset, numChars, newText ); - else if( children[i] instanceof TranslationUnitChange ){ - TranslationUnitChange tuChange = (TranslationUnitChange) children[i]; - if( tuChange.getFile().toString().equals( file.toString() ) ){ - found = checkTranslationUnitChange( tuChange, startOffset, numChars, newText ); - } - } - if( found ) - return found; - } - return found; - } - - private boolean checkTranslationUnitChange( TranslationUnitChange change, int startOffset, int numChars, String newText ){ - TextEdit textEdit = change.getEdit(); - if( textEdit instanceof MultiTextEdit ){ - MultiTextEdit multiEdit = (MultiTextEdit) textEdit; - TextEdit [] edits = multiEdit.getChildren(); - for( int i = 0; i < edits.length; i++ ){ - if( edits[i] instanceof ReplaceEdit && checkReplaceEdit( (ReplaceEdit) edits[i], startOffset, numChars, newText ) ) - return true; - } - } else if( textEdit instanceof ReplaceEdit ){ - return checkReplaceEdit( (ReplaceEdit) textEdit, startOffset, numChars, newText ); - } - return false; - } - - private boolean checkReplaceEdit( ReplaceEdit edit, int startOffset, int numChars, String newText ){ - return ( edit.getOffset() == startOffset && edit.getLength() == numChars && edit.getText().equals( newText ) ); - } - - public void testSimpleRename() throws Exception { - StringWriter writer = new StringWriter(); - writer.write( "int boo; \n" ); //$NON-NLS-1$ - writer.write( "void f() { \n" ); //$NON-NLS-1$ - writer.write( " boo++; \n" ); //$NON-NLS-1$ - writer.write( "} \n" ); //$NON-NLS-1$ - - String contents = writer.toString(); - IFile file = importFile( "t.cpp", contents ); //$NON-NLS-1$ - ISourceReference element = findElementAtOffset( file, contents.indexOf( "boo" ) ); //$NON-NLS-1$ - IChange changes = getRefactorChanges( element, "ooga" ); //$NON-NLS-1$ - - assertTotalChanges( 2, changes ); - assertChange( changes, file, contents.indexOf("boo"), 3, "ooga" ); //$NON-NLS-1$//$NON-NLS-2$ - assertChange( changes, file, contents.indexOf("boo++"), 3, "ooga" ); //$NON-NLS-1$//$NON-NLS-2$ - } - public void testClass_1() throws Exception { - StringWriter writer = new StringWriter(); - writer.write( "class Boo/*vp1*/{}; \n" ); //$NON-NLS-1$ - writer.write( "void f() { \n" ); //$NON-NLS-1$ - writer.write( " Boo a; \n" ); //$NON-NLS-1$ - writer.write( "} \n" ); //$NON-NLS-1$ - - String contents = writer.toString(); - IFile file = importFile( "t.cpp", contents ); //$NON-NLS-1$ - ISourceReference element = findElementAtOffset( file, contents.indexOf( "Boo/*vp1*/" ) ); //$NON-NLS-1$ - IChange changes = getRefactorChanges( element, "Ooga" ); //$NON-NLS-1$ - - assertTotalChanges( 2, changes ); - assertChange( changes, file, contents.indexOf("Boo/*vp1*/"), 3, "Ooga" ); //$NON-NLS-1$//$NON-NLS-2$ - assertChange( changes, file, contents.indexOf("Boo a"), 3, "Ooga" ); //$NON-NLS-1$//$NON-NLS-2$ - } - public void testAttribute_2() throws Exception { - StringWriter writer = new StringWriter(); - writer.write( "class Boo{ \n" ); //$NON-NLS-1$ - writer.write( " int att1;//vp1,res1 \n" ); //$NON-NLS-1$ - writer.write( "}; \n" ); //$NON-NLS-1$ - writer.write( "void f() { \n" ); //$NON-NLS-1$ - writer.write( " Boo a; \n" ); //$NON-NLS-1$ - writer.write( " a.att1;//res2 \n" ); //$NON-NLS-1$ - writer.write( "} \n" ); //$NON-NLS-1$ - - String contents = writer.toString(); - IFile file = importFile( "t.cpp", contents ); //$NON-NLS-1$ - ISourceReference element = findElementAtOffset( file, contents.indexOf( "att1;//vp1" ) ); //$NON-NLS-1$ - IChange changes = getRefactorChanges( element, "ooga" ); //$NON-NLS-1$ - - assertTotalChanges( 2, changes ); - assertChange( changes, file, contents.indexOf("att1;//vp1,res1"), 4, "ooga" ); //$NON-NLS-1$//$NON-NLS-2$ - assertChange( changes, file, contents.indexOf("att1;//res2"), 4, "ooga" ); //$NON-NLS-1$//$NON-NLS-2$ - } - public void testMethod_3() throws Exception { - StringWriter writer = new StringWriter(); - writer.write( "class Boo{ \n" ); //$NON-NLS-1$ - writer.write( " int method1(){}//vp1,res1 \n" ); //$NON-NLS-1$ - writer.write( "}; \n" ); //$NON-NLS-1$ - writer.write( "void f() { \n" ); //$NON-NLS-1$ - writer.write( " Boo a; \n" ); //$NON-NLS-1$ - writer.write( " a.method1();//res2 \n" ); //$NON-NLS-1$ - writer.write( "} \n" ); //$NON-NLS-1$ - - String contents = writer.toString(); - IFile file = importFile( "t.cpp", contents ); //$NON-NLS-1$ - ISourceReference element = findElementAtOffset( file, contents.indexOf( "method1(){}//vp1" ) ); //$NON-NLS-1$ - IChange changes = getRefactorChanges( element, "ooga" ); //$NON-NLS-1$ - - assertTotalChanges( 2, changes ); - assertChange( changes, file, contents.indexOf("method1(){}//vp1,res1"), 7, "ooga" ); //$NON-NLS-1$//$NON-NLS-2$ - assertChange( changes, file, contents.indexOf("method1();//res2"), 7, "ooga" ); //$NON-NLS-1$//$NON-NLS-2$ - } - - - public void testConstructor_26() throws Exception { - StringWriter writer = new StringWriter(); - writer.write( "class Boo{ \n" ); //$NON-NLS-1$ - writer.write( " Boo(){}//vp1,res1 \n" ); //$NON-NLS-1$ - writer.write( "}; \n" ); //$NON-NLS-1$ - writer.write( "void f() { \n" ); //$NON-NLS-1$ - writer.write( " Boo a = new Boo(); \n" ); //$NON-NLS-1$ - writer.write( "} \n" ); //$NON-NLS-1$ - - String contents = writer.toString(); - IFile file = importFile( "t.cpp", contents ); //$NON-NLS-1$ - ISourceReference element = findElementAtOffset( file, contents.indexOf( "Boo(){}" ) ); //$NON-NLS-1$ - try { - getRefactorChanges( element, "ooga" ); //$NON-NLS-1$ - } catch (AssertionFailedError e) { - assertTrue(e.getMessage().startsWith("Input check on ooga failed.")); //$NON-NLS-1$ - return; - } - fail ("An error should have occurred in the input check."); //$NON-NLS-1$ - } - //The constructor name is accepted, but the refactoring doesn't remove the return - //type and there is a compile error. Renaming to a constructor should be disabled. - //However, the UI does display the error in the preview panel. Defect 78769 states - //the error should be shown on the first page. The parser passes, but the UI could be - //better. - public void testConstructor_27() throws Exception { - StringWriter writer = new StringWriter(); - writer.write( "class Boo{ \n" ); //$NON-NLS-1$ - writer.write( " int foo(){}//vp1 \n" ); //$NON-NLS-1$ - writer.write( "}; \n" ); //$NON-NLS-1$ - writer.write( "void f() { \n" ); //$NON-NLS-1$ - writer.write( " Boo a; \n" ); //$NON-NLS-1$ - writer.write( " a.foo(); \n" ); //$NON-NLS-1$ - writer.write( "} \n" ); //$NON-NLS-1$ - - String contents = writer.toString(); - IFile file = importFile( "t.cpp", contents ); //$NON-NLS-1$ - ISourceReference element = findElementAtOffset( file, contents.indexOf( "foo(){}" ) ); //$NON-NLS-1$ - try { - getRefactorChanges( element, "Boo" ); //$NON-NLS-1$ - } catch (AssertionFailedError e) { - //test passes - assertTrue(e.getMessage().startsWith("Input check on Boo failed.")); //$NON-NLS-1$ - return; - } - fail ("An error should have occurred in the input check."); //$NON-NLS-1$ - } - public void testDestructor_28() throws Exception { - StringWriter writer = new StringWriter(); - writer.write( "class Boo{ \n" ); //$NON-NLS-1$ - writer.write( " ~Boo(){}//vp1 \n" ); //$NON-NLS-1$ - writer.write( "}; \n" ); //$NON-NLS-1$ - writer.write( "void f() { \n" ); //$NON-NLS-1$ - writer.write( " Boo a ; \n" ); //$NON-NLS-1$ - writer.write( " a.~Boo(); \n" ); //$NON-NLS-1$ - writer.write( "} \n" ); //$NON-NLS-1$ - - String contents = writer.toString(); - IFile file = importFile( "t.cpp", contents ); //$NON-NLS-1$ - ISourceReference element = findElementAtOffset( file, contents.indexOf( "~Boo(){}" ) ); //$NON-NLS-1$ - try { - getRefactorChanges( element, "ooga" ); //$NON-NLS-1$ - } catch (AssertionFailedError e) { - assertTrue(e.getMessage().startsWith("Input check on ooga failed.")); //$NON-NLS-1$ - return; - } - fail ("An error should have occurred in the input check."); //$NON-NLS-1$ - } - public void testDestructor_29_72612() throws Exception { - StringWriter writer = new StringWriter(); - writer.write( "class Boo{ \n" ); //$NON-NLS-1$ - writer.write( " int foo(){}//vp1 \n" ); //$NON-NLS-1$ - writer.write( "}; \n" ); //$NON-NLS-1$ - writer.write( "void f() { \n" ); //$NON-NLS-1$ - writer.write( " Boo a; \n" ); //$NON-NLS-1$ - writer.write( " a.foo(); \n" ); //$NON-NLS-1$ - writer.write( "} \n" ); //$NON-NLS-1$ - - String contents = writer.toString(); - IFile file = importFile( "t.cpp", contents ); //$NON-NLS-1$ - ISourceReference element = findElementAtOffset( file, contents.indexOf( "foo(){}" ) ); //$NON-NLS-1$ - try { - getRefactorChanges( element, "~Boo" ); //$NON-NLS-1$ - } catch (AssertionFailedError e) { - //test passes - assertTrue(e.getMessage().startsWith("Input check on Boo failed.")); //$NON-NLS-1$ - return; - } - fail ("An error should have occurred in the input check."); //$NON-NLS-1$ - } - -// re: bugzilla 93550 -// public void testFunction_31() throws Exception { -// StringWriter writer = new StringWriter(); -// writer.write( "void foo(){} \n" ); //$NON-NLS-1$ -// writer.write( "void foo/*vp1*/(int i){} \n" ); //$NON-NLS-1$ -// writer.write( "class Foo{ \n" ); //$NON-NLS-1$ -// writer.write( " int method1(){ \n" ); //$NON-NLS-1$ -// writer.write( " foo(3); \n" ); //$NON-NLS-1$ -// writer.write( " foo(); \n" ); //$NON-NLS-1$ -// writer.write( " } \n" ); //$NON-NLS-1$ -// writer.write( "}; \n" ); //$NON-NLS-1$ -// -// String contents = writer.toString(); -// IFile file = importFile( "t.cpp", contents ); //$NON-NLS-1$ -// ISourceReference element = findElementAtOffset( file, contents.indexOf( "foo/*vp1*/" ) ); //$NON-NLS-1$ -// IChange changes = getRefactorChanges( element, "ooga" ); //$NON-NLS-1$ -// assertTotalChanges( 2, changes ); -// assertChange( changes, file, contents.indexOf("foo/*vp1*/"), 3, "ooga" ); //$NON-NLS-1$//$NON-NLS-2$ -// assertChange( changes, file, contents.indexOf("foo(3)"), 3, "ooga" ); //$NON-NLS-1$//$NON-NLS-2$ -// -// } - public void testMethod_32_72717() throws Exception { - StringWriter writer = new StringWriter(); - writer.write( "class Base { \n" ); //$NON-NLS-1$ - writer.write( " virtual void foo()=0; \n" ); //$NON-NLS-1$ - writer.write( "}; \n" ); //$NON-NLS-1$ - writer.write( "class Derived: public Base { \n" ); //$NON-NLS-1$ - writer.write( " virtual void foo(); \n" ); //$NON-NLS-1$ - writer.write( " void moon/*vp1*/(int i); \n" ); //$NON-NLS-1$ - writer.write( "}; \n" ); //$NON-NLS-1$ - - String contents = writer.toString(); - IFile file = importFile( "t.cpp", contents ); //$NON-NLS-1$ - ISourceReference element = findElementAtOffset( file, contents.indexOf( "moon/*vp1*/" ) ); //$NON-NLS-1$ - IChange changes = getRefactorChanges( element, "foo" ); //$NON-NLS-1$ - assertTotalChanges( 1, changes ); - assertChange( changes, file, contents.indexOf("moon/*vp1*/"), 4, "foo" ); //$NON-NLS-1$//$NON-NLS-2$ - - } - - public void testMethod_33_72605() throws Exception { - StringWriter writer = new StringWriter(); - writer.write( "class Foo { \n" ); //$NON-NLS-1$ - writer.write( " void aMethod/*vp1*/(int x=0); \n" ); //$NON-NLS-1$ - writer.write( "}; \n" ); //$NON-NLS-1$ - writer.write( "void Foo::aMethod(int x){} \n" ); //$NON-NLS-1$ - String contents = writer.toString(); - IFile file = importFile( "t.cpp", contents ); //$NON-NLS-1$ - ISourceReference element = findElementAtOffset( file, contents.indexOf( "aMethod/*vp1*/" ) ); //$NON-NLS-1$ - IChange changes = getRefactorChanges( element, "ooga" ); //$NON-NLS-1$ - assertTotalChanges( 2, changes ); - assertChange( changes, file, contents.indexOf("aMethod/*vp1*/"), 7, "ooga" ); //$NON-NLS-1$//$NON-NLS-2$ - assertChange( changes, file, contents.indexOf("aMethod(int x)"), 7, "ooga" ); //$NON-NLS-1$//$NON-NLS-2$ - - } - public void testMethod_34() throws Exception { - StringWriter writer = new StringWriter(); - writer.write( "class Base{ \n" ); //$NON-NLS-1$ - writer.write( " virtual void v/*vp1*/()=0; \n" ); //$NON-NLS-1$ - writer.write( "}; \n" ); //$NON-NLS-1$ - writer.write( "class Derived: Base { \n" ); //$NON-NLS-1$ - writer.write( " void v(){}; \n" ); //$NON-NLS-1$ - writer.write( "}; \n" ); //$NON-NLS-1$ - String contents = writer.toString(); - IFile file = importFile( "t.cpp", contents ); //$NON-NLS-1$ - ISourceReference element = findElementAtOffset( file, contents.indexOf( "v/*vp1*/" ) ); //$NON-NLS-1$ - IChange changes = getRefactorChanges( element, "ooga" ); //$NON-NLS-1$ - //dervied method is not renamed; only a warning to rename derived or base class methods - assertTotalChanges( 1, changes ); - assertChange( changes, file, contents.indexOf("v/*vp1*/"), 1, "ooga" ); //$NON-NLS-1$//$NON-NLS-2$ - - } - // defect is input for new name is not allowed - public void testMethod_35_72726() throws Exception { - StringWriter writer = new StringWriter(); - writer.write( "class Foo{ \n" ); //$NON-NLS-1$ - writer.write( " Foo& operator *=/*vp1*/(const Foo &rhs);\n" ); //$NON-NLS-1$ - writer.write( " Foo& operator==/*vp2*/(const Foo &rhs);\n" ); //$NON-NLS-1$ - writer.write( "}; \n" ); //$NON-NLS-1$ - writer.write( "Foo& Foo::operator *=(const Foo &rhs){ \n" ); //$NON-NLS-1$ - writer.write( " return *this; \n" ); //$NON-NLS-1$ - writer.write( "}; \n" ); //$NON-NLS-1$ - writer.write( "Foo& Foo::operator==(const Foo &rhs){ \n" ); //$NON-NLS-1$ - writer.write( " return *this; \n" ); //$NON-NLS-1$ - writer.write( "}; \n" ); //$NON-NLS-1$ - String contents = writer.toString(); - IFile file = importFile( "t.cpp", contents ); //$NON-NLS-1$ - //vp1 with space - ISourceReference element = findElementAtOffset( file, contents.indexOf( "operator *=/*vp1*/" ) ); //$NON-NLS-1$ - IChange changes = getRefactorChanges( element, "operator +=" ); //$NON-NLS-1$ - assertTotalChanges( 2, changes ); - assertChange( changes, file, contents.indexOf("operator *=/*vp1*/"), 11, "operator +=" ); //$NON-NLS-1$//$NON-NLS-2$ - assertChange( changes, file, contents.indexOf("operator *=(const"), 11, "operator +=" ); //$NON-NLS-1$//$NON-NLS-2$ - //vp2 without space - element = findElementAtOffset( file, contents.indexOf( "operator==/*vp2*/" ) ); //$NON-NLS-1$ - changes = getRefactorChanges( element, "operator=" ); //$NON-NLS-1$ - assertTotalChanges( 2, changes ); - assertChange( changes, file, contents.indexOf("operator==/*vp2*/"), 11, "operator=" ); //$NON-NLS-1$//$NON-NLS-2$ - assertChange( changes, file, contents.indexOf("operator==(const"), 11, "operator=" ); //$NON-NLS-1$//$NON-NLS-2$ - - } - public void testMethod_39() throws Exception { - StringWriter writer = new StringWriter(); - writer.write( "class Foo{ \n" ); //$NON-NLS-1$ - writer.write( " const void* method1/*vp1*/(char*); \n" ); //$NON-NLS-1$ - writer.write( " const int method2/*vp1*/(int j); \n" ); //$NON-NLS-1$ - writer.write( "}; \n" ); //$NON-NLS-1$ - String header = writer.toString(); - IFile h = importFile( "t.h", header ); //$NON-NLS-1$ - - writer = new StringWriter(); - writer.write( "#include \"t.h\" \n" ); //$NON-NLS-1$ - writer.write( "const void* Foo::method1(char* x){return ((void*) x;} \n" ); //$NON-NLS-1$ - writer.write( "const int Foo::method2(int){return 5;} \n" ); //$NON-NLS-1$ - writer.write( "void test() { \n" ); //$NON-NLS-1$ - writer.write( " Foo d; \n" ); //$NON-NLS-1$ - writer.write( " d.method1(\"hello\"); \n" ); //$NON-NLS-1$ - writer.write( " int i =d.method2(3); \n" ); //$NON-NLS-1$ - writer.write( "} \n" ); //$NON-NLS-1$ - String source = writer.toString(); - IFile cpp = importFile( "t.cpp", source ); //$NON-NLS-1$ - //vp1 const - ISourceReference element = findElementAtOffset( h, header.indexOf( "method1/*vp1*/" ) ); //$NON-NLS-1$ - IChange changes = getRefactorChanges( element, "m1" ); //$NON-NLS-1$ - //assertTotalChanges( 3, changes ); - assertChange( changes, h, header.indexOf("method1/*vp1*/"), 7, "m1" ); //$NON-NLS-1$//$NON-NLS-2$ - assertChange( changes, cpp, source.indexOf("method1(char"), 7, "m1" ); //$NON-NLS-1$//$NON-NLS-2$ - assertChange( changes, cpp, source.indexOf("method1(\"hello"), 7, "m1" ); //$NON-NLS-1$//$NON-NLS-2$ - //vp2 const in definition with :: - element = findElementAtOffset( cpp, source.indexOf( "Foo::method2" ) ); //$NON-NLS-1$ - changes = getRefactorChanges( element, "m2" ); //$NON-NLS-1$ - assertTotalChanges( 3, changes ); - assertChange( changes, h, header.indexOf("method2/*vp1*/"), 7, "m2" ); //$NON-NLS-1$//$NON-NLS-2$ - assertChange( changes, cpp, source.indexOf("method2(int"), 7, "m2" ); //$NON-NLS-1$//$NON-NLS-2$ - assertChange( changes, cpp, source.indexOf("method2(3"), 7, "m2" ); //$NON-NLS-1$//$NON-NLS-2$ - - } - public void testMethod_40() throws Exception { - StringWriter writer = new StringWriter(); - writer.write( "class Foo{ \n" ); //$NON-NLS-1$ - writer.write( " static int method1/*vp1*/(char* x); \n" ); //$NON-NLS-1$ - writer.write( " static int method2/*vp2*/(int); \n" ); //$NON-NLS-1$ - writer.write( "}; \n" ); //$NON-NLS-1$ - String header = writer.toString(); - IFile h = importFile( "t.h", header ); //$NON-NLS-1$ - - writer = new StringWriter(); - writer.write( "#include \"t.h\" \n" ); //$NON-NLS-1$ - writer.write( "static int Foo::method1(char* x){return 5;} \n" ); //$NON-NLS-1$ - writer.write( "static int Foo::method2(int x){return (2);}; \n" ); //$NON-NLS-1$ - writer.write( "void test() { \n" ); //$NON-NLS-1$ - writer.write( " Foo::method1(\"hello\"); \n" ); //$NON-NLS-1$ - writer.write( " int i =Foo::method2(3); \n" ); //$NON-NLS-1$ - writer.write( "} \n" ); //$NON-NLS-1$ - String source = writer.toString(); - IFile cpp = importFile( "t.cpp", source ); //$NON-NLS-1$ - //vp1 static method declaration - ISourceReference element = findElementAtOffset( h, header.indexOf( "method1/*vp1*/" ) ); //$NON-NLS-1$ - IChange changes = getRefactorChanges( element, "m1" ); //$NON-NLS-1$ - assertTotalChanges( 3, changes ); - assertChange( changes, h, header.indexOf("method1/*vp1*/"), 7, "m1" ); //$NON-NLS-1$//$NON-NLS-2$ - assertChange( changes, cpp, source.indexOf("method1(char"), 7, "m1" ); //$NON-NLS-1$//$NON-NLS-2$ - assertChange( changes, cpp, source.indexOf("method1(\"hello"), 7, "m1" ); //$NON-NLS-1$//$NON-NLS-2$ - //vp2 static method definition - element = findElementAtOffset( cpp, source.indexOf( "Foo::method2" ) ); //$NON-NLS-1$ - changes = getRefactorChanges( element, "m2" ); //$NON-NLS-1$ - assertTotalChanges( 3, changes ); - assertChange( changes, h, header.indexOf("method2/*vp2*/"), 7, "m2" ); //$NON-NLS-1$//$NON-NLS-2$ - assertChange( changes, cpp, source.indexOf("method2(int x"), 7, "m2" ); //$NON-NLS-1$//$NON-NLS-2$ - assertChange( changes, cpp, source.indexOf("method2(3"), 7, "m2" ); //$NON-NLS-1$//$NON-NLS-2$ - - } - - public void testMethod_41() throws Exception { - StringWriter writer = new StringWriter(); - writer.write( "class Foo{ \n" ); //$NON-NLS-1$ - writer.write( "public: \n" ); //$NON-NLS-1$ - writer.write( " volatile int method1/*vp1*/(int); \n" ); //$NON-NLS-1$ - writer.write( "private: \n" ); //$NON-NLS-1$ - writer.write( " int b; \n" ); //$NON-NLS-1$ - writer.write( "}; \n" ); //$NON-NLS-1$ - String header = writer.toString(); - IFile h = importFile( "t.h", header ); //$NON-NLS-1$ - - writer = new StringWriter(); - writer.write( "#include \"t.h\" \n" ); //$NON-NLS-1$ - writer.write( "volatile int Foo::method1(int x){return (2);}; \n" ); //$NON-NLS-1$ - writer.write( "void test() { \n" ); //$NON-NLS-1$ - writer.write( " Foo d; \n" ); //$NON-NLS-1$ - writer.write( " int i =d.method1(1); \n" ); //$NON-NLS-1$ - writer.write( "} \n" ); //$NON-NLS-1$ - String source = writer.toString(); - IFile cpp = importFile( "t.cpp", source ); //$NON-NLS-1$ - //vp1 volatile - ISourceReference element = findElementAtOffset( h, header.indexOf( "method1/*vp1*/" ) ); //$NON-NLS-1$ - IChange changes = getRefactorChanges( element, "m1" ); //$NON-NLS-1$ - assertTotalChanges( 3, changes ); - assertChange( changes, h, header.indexOf("method1/*vp1*/"), 7, "m1" ); //$NON-NLS-1$//$NON-NLS-2$ - assertChange( changes, cpp, source.indexOf("method1(int x"), 7, "m1" ); //$NON-NLS-1$//$NON-NLS-2$ - assertChange( changes, cpp, source.indexOf("method1(1"), 7, "m1" ); //$NON-NLS-1$//$NON-NLS-2$ - - } - public void testMethod_43() throws Exception { - StringWriter writer = new StringWriter(); - writer.write( "class Foo{ \n" ); //$NON-NLS-1$ - writer.write( "public: \n" ); //$NON-NLS-1$ - writer.write( " inline void method1/*vp1*/(int i) {b=i;} \n" ); //$NON-NLS-1$ - writer.write( "private: \n" ); //$NON-NLS-1$ - writer.write( " int b; \n" ); //$NON-NLS-1$ - writer.write( "}; \n" ); //$NON-NLS-1$ - String header = writer.toString(); - IFile h = importFile( "t.h", header ); //$NON-NLS-1$ - - writer = new StringWriter(); - writer.write( "#include \"t.h\" \n" ); //$NON-NLS-1$ - writer.write( "void test() { \n" ); //$NON-NLS-1$ - writer.write( " Foo *d; \n" ); //$NON-NLS-1$ - writer.write( " d->method1(1); \n" ); //$NON-NLS-1$ - writer.write( "} \n" ); //$NON-NLS-1$ - String source = writer.toString(); - IFile cpp = importFile( "t.cpp", source ); //$NON-NLS-1$ - //vp1 inline - ISourceReference element = findElementAtOffset( h, header.indexOf( "method1/*vp1*/" ) ); //$NON-NLS-1$ - IChange changes = getRefactorChanges( element, "m1" ); //$NON-NLS-1$ - assertTotalChanges( 2, changes ); - assertChange( changes, h, header.indexOf("method1/*vp1*/"), 7, "m1" ); //$NON-NLS-1$//$NON-NLS-2$ - assertChange( changes, cpp, source.indexOf("method1(1"), 7, "m1" ); //$NON-NLS-1$//$NON-NLS-2$ - - } - public void testMethod_44() throws Exception { - StringWriter writer = new StringWriter(); - writer.write( "class Base{ \n" ); //$NON-NLS-1$ - writer.write( " virtual void v(); \n" ); //$NON-NLS-1$ - writer.write( " int i; \n" ); //$NON-NLS-1$ - writer.write( "}; \n" ); //$NON-NLS-1$ - writer.write( "void Base::v(){} \n" ); //$NON-NLS-1$ - writer.write( "class Derived: Base { \n" ); //$NON-NLS-1$ - writer.write( " virtual void v/*vp1*/(){}//explicitly virtual \n" ); //$NON-NLS-1$ - writer.write( "}; \n" ); //$NON-NLS-1$ - writer.write( "class Derived2: Derived {\n" ); //$NON-NLS-1$ - writer.write( " void v(){i++;} \n" ); //$NON-NLS-1$ - writer.write( "}; \n" ); //$NON-NLS-1$ - String contents = writer.toString(); - IFile file = importFile( "t.cpp", contents ); //$NON-NLS-1$ - //vp1 implicit virtual method - ISourceReference element = findElementAtOffset( file, contents.indexOf( "v/*vp1*/" ) ); //$NON-NLS-1$ - String[] messages= getRefactorMessages( element, "v2" ); //$NON-NLS-1$ - assertEquals(1, messages.length); - assertEquals("Renaming a virtual method. Consider renaming the base and derived class methods (if any).", messages[0] ); //$NON-NLS-1$ - -} - public void testMethod_45_72732() throws Exception { - StringWriter writer = new StringWriter(); - writer.write( "class Base{ \n" ); //$NON-NLS-1$ - writer.write( " virtual void v(); \n" ); //$NON-NLS-1$ - writer.write( " int i; \n" ); //$NON-NLS-1$ - writer.write( "}; \n" ); //$NON-NLS-1$ - writer.write( "void Base::v(){} \n" ); //$NON-NLS-1$ - writer.write( "class Derived: Base { \n" ); //$NON-NLS-1$ - writer.write( " void v/*vp1*/(){}//implicitly virtual \n" ); //$NON-NLS-1$ - writer.write( "}; \n" ); //$NON-NLS-1$ - writer.write( "class Derived2: Derived {\n" ); //$NON-NLS-1$ - writer.write( " void v(){i++;} \n" ); //$NON-NLS-1$ - writer.write( "}; \n" ); //$NON-NLS-1$ - String contents = writer.toString(); - IFile file = importFile( "t.cpp", contents ); //$NON-NLS-1$ - //vp1 implicit virtual method - ISourceReference element = findElementAtOffset( file, contents.indexOf( "v/*vp1*/" ) ); //$NON-NLS-1$ - String[] messages= getRefactorMessages( element, "v2" ); //$NON-NLS-1$ - assertEquals(1, messages.length); - assertEquals("Renaming a virtual method. Consider renaming the base and derived class methods (if any).", messages[0] ); //$NON-NLS-1$ - - - } - public void testStruct_46() throws Exception { - StringWriter writer = new StringWriter(); - writer.write( "struct st1/*vp1*/{}; \n" ); //$NON-NLS-1$ - writer.write( "class c1/*vp1*/{ \n" ); //$NON-NLS-1$ - writer.write( " public: struct st2/*vp2*/{} s; \n" ); //$NON-NLS-1$ - writer.write( "}; \n" ); //$NON-NLS-1$ - writer.write( "namespace N{ \n" ); //$NON-NLS-1$ - writer.write( " struct st3/*vp3*/{}; \n" ); //$NON-NLS-1$ - writer.write( " class c2/*vp1*/{ \n" ); //$NON-NLS-1$ - writer.write( " st1 s; \n" ); //$NON-NLS-1$ - writer.write( " st3 ss; \n" ); //$NON-NLS-1$ - writer.write( " c2() { \n" ); //$NON-NLS-1$ - writer.write( " c1::st2 s; \n" ); //$NON-NLS-1$ - writer.write( " } \n" ); //$NON-NLS-1$ - writer.write( " }; \n" ); //$NON-NLS-1$ - writer.write( "} \n" ); //$NON-NLS-1$ - - String contents = writer.toString(); - IFile file = importFile( "t.cpp", contents ); //$NON-NLS-1$ - //vp1 global declaration - ISourceReference element = findElementAtOffset( file, contents.indexOf( "st1/*vp1*/" ) ); //$NON-NLS-1$ - IChange changes = getRefactorChanges( element, "Ooga1" ); //$NON-NLS-1$ - assertTotalChanges( 2, changes ); - assertChange( changes, file, contents.indexOf("st1/*vp1*/"), 3, "Ooga1" ); //$NON-NLS-1$//$NON-NLS-2$ - assertChange( changes, file, contents.indexOf("st1 s"), 3, "Ooga1" ); //$NON-NLS-1$//$NON-NLS-2$ - //vp2 Declared in class - element = findElementAtOffset( file, contents.indexOf( "st2/*vp2*/" ) ); //$NON-NLS-1$ - changes = getRefactorChanges( element, "Ooga2" ); //$NON-NLS-1$ - assertTotalChanges( 2, changes ); - assertChange( changes, file, contents.indexOf("st2/*vp2*/"), 3, "Ooga2" ); //$NON-NLS-1$//$NON-NLS-2$ - assertChange( changes, file, contents.indexOf("st2 s"), 3, "Ooga2" ); //$NON-NLS-1$//$NON-NLS-2$ - //vp3 Declared in namespace - element = findElementAtOffset( file, contents.indexOf( "st3/*vp3*/" ) ); //$NON-NLS-1$ - changes = getRefactorChanges( element, "Ooga3" ); //$NON-NLS-1$ - assertTotalChanges( 2, changes ); - assertChange( changes, file, contents.indexOf("st3/*vp3*/"), 3, "Ooga3" ); //$NON-NLS-1$//$NON-NLS-2$ - assertChange( changes, file, contents.indexOf("st3 ss"), 3, "Ooga3" ); //$NON-NLS-1$//$NON-NLS-2$ - } - public void testUnion_47() throws Exception { - StringWriter writer = new StringWriter(); - writer.write( "union st1/*vp1*/{}; \n" ); //$NON-NLS-1$ - writer.write( "class c1/*vp1*/{ \n" ); //$NON-NLS-1$ - writer.write( " public: union st2/*vp2*/{} s; \n" ); //$NON-NLS-1$ - writer.write( "}; \n" ); //$NON-NLS-1$ - writer.write( "namespace N{ \n" ); //$NON-NLS-1$ - writer.write( " union st3/*vp3*/{}; \n" ); //$NON-NLS-1$ - writer.write( " class c2/*vp1*/{ \n" ); //$NON-NLS-1$ - writer.write( " st1 s; \n" ); //$NON-NLS-1$ - writer.write( " st3 ss; \n" ); //$NON-NLS-1$ - writer.write( " c2() { \n" ); //$NON-NLS-1$ - writer.write( " c1::st2 s; \n" ); //$NON-NLS-1$ - writer.write( " } \n" ); //$NON-NLS-1$ - writer.write( " }; \n" ); //$NON-NLS-1$ - writer.write( "} \n" ); //$NON-NLS-1$ - - String contents = writer.toString(); - IFile file = importFile( "t.cpp", contents ); //$NON-NLS-1$ - //vp1 global declaration - ISourceReference element = findElementAtOffset( file, contents.indexOf( "st1/*vp1*/" ) ); //$NON-NLS-1$ - IChange changes = getRefactorChanges( element, "Ooga1" ); //$NON-NLS-1$ - assertTotalChanges( 2, changes ); - assertChange( changes, file, contents.indexOf("st1/*vp1*/"), 3, "Ooga1" ); //$NON-NLS-1$//$NON-NLS-2$ - assertChange( changes, file, contents.indexOf("st1 s"), 3, "Ooga1" ); //$NON-NLS-1$//$NON-NLS-2$ - //vp2 Declared in class - element = findElementAtOffset( file, contents.indexOf( "st2/*vp2*/" ) ); //$NON-NLS-1$ - changes = getRefactorChanges( element, "Ooga2" ); //$NON-NLS-1$ - assertTotalChanges( 2, changes ); - assertChange( changes, file, contents.indexOf("st2/*vp2*/"), 3, "Ooga2" ); //$NON-NLS-1$//$NON-NLS-2$ - assertChange( changes, file, contents.indexOf("st2 s"), 3, "Ooga2" ); //$NON-NLS-1$//$NON-NLS-2$ - //vp3 Declared in namespace - element = findElementAtOffset( file, contents.indexOf( "st3/*vp3*/" ) ); //$NON-NLS-1$ - changes = getRefactorChanges( element, "Ooga3" ); //$NON-NLS-1$ - assertTotalChanges( 2, changes ); - assertChange( changes, file, contents.indexOf("st3/*vp3*/"), 3, "Ooga3" ); //$NON-NLS-1$//$NON-NLS-2$ - assertChange( changes, file, contents.indexOf("st3 ss"), 3, "Ooga3" ); //$NON-NLS-1$//$NON-NLS-2$ -} - public void testEnumeration_48() throws Exception { - StringWriter writer = new StringWriter(); - writer.write( "enum e1/*vp1*/{E0}; \n" ); //$NON-NLS-1$ - writer.write( "class c1 { \n" ); //$NON-NLS-1$ - writer.write( " public: enum e2/*vp2*/{E1} s; \n" ); //$NON-NLS-1$ - writer.write( "}; \n" ); //$NON-NLS-1$ - writer.write( "namespace N{ \n" ); //$NON-NLS-1$ - writer.write( " enum e3/*vp3*/{}; \n" ); //$NON-NLS-1$ - writer.write( " class c2/*vp1*/{ \n" ); //$NON-NLS-1$ - writer.write( " e1 s; \n" ); //$NON-NLS-1$ - writer.write( " e3 ss; \n" ); //$NON-NLS-1$ - writer.write( " c2() { \n" ); //$NON-NLS-1$ - writer.write( " c1::e2 s; \n" ); //$NON-NLS-1$ - writer.write( " } \n" ); //$NON-NLS-1$ - writer.write( " }; \n" ); //$NON-NLS-1$ - writer.write( "} \n" ); //$NON-NLS-1$ - - String contents = writer.toString(); - IFile file = importFile( "t.cpp", contents ); //$NON-NLS-1$ - //vp1 global declaration - ISourceReference element = findElementAtOffset( file, contents.indexOf( "e1/*vp1*/" ) ); //$NON-NLS-1$ - IChange changes = getRefactorChanges( element, "Ooga1" ); //$NON-NLS-1$ - assertTotalChanges( 2, changes ); - assertChange( changes, file, contents.indexOf("e1/*vp1*/"), 2, "Ooga1" ); //$NON-NLS-1$//$NON-NLS-2$ - assertChange( changes, file, contents.indexOf("e1 s"), 2, "Ooga1" ); //$NON-NLS-1$//$NON-NLS-2$ - //vp2 Declared in class - element = findElementAtOffset( file, contents.indexOf( "e2/*vp2*/" ) ); //$NON-NLS-1$ - changes = getRefactorChanges( element, "Ooga2" ); //$NON-NLS-1$ - assertTotalChanges( 2, changes ); - assertChange( changes, file, contents.indexOf("e2/*vp2*/"), 2, "Ooga2" ); //$NON-NLS-1$//$NON-NLS-2$ - assertChange( changes, file, contents.indexOf("e2 s"), 2, "Ooga2" ); //$NON-NLS-1$//$NON-NLS-2$ - //vp3 Declared in namespace - element = findElementAtOffset( file, contents.indexOf( "e3/*vp3*/" ) ); //$NON-NLS-1$ - changes = getRefactorChanges( element, "Ooga3" ); //$NON-NLS-1$ - assertTotalChanges( 2, changes ); - assertChange( changes, file, contents.indexOf("e3/*vp3*/"), 2, "Ooga3" ); //$NON-NLS-1$//$NON-NLS-2$ - assertChange( changes, file, contents.indexOf("e3 ss"), 2, "Ooga3" ); //$NON-NLS-1$//$NON-NLS-2$ - } - public void testTemplate_49_72626() throws Exception { - StringWriter writer = new StringWriter(); - writer.write( "template \n" ); //$NON-NLS-1$ - writer.write( "class Array/*vp1*/ { \n" ); //$NON-NLS-1$ - writer.write( " public: Array(){ \n" ); //$NON-NLS-1$ - writer.write( " a=new Type[10]; \n" ); //$NON-NLS-1$ - writer.write( " } \n" ); //$NON-NLS-1$ - writer.write( " virtual Type& operator[](int i){return a[i];} \n" ); //$NON-NLS-1$ - writer.write( " protected: Type *a; \n" ); //$NON-NLS-1$ - writer.write( "}; \n" ); //$NON-NLS-1$ - writer.write( "void f(){ \n" ); //$NON-NLS-1$ - writer.write( " Array a; \n" ); //$NON-NLS-1$ - writer.write( "} \n" ); //$NON-NLS-1$ - - String contents = writer.toString(); - IFile file = importFile( "t.cpp", contents ); //$NON-NLS-1$ - //vp1 template classes are not supposed to be found until the new Parser is complete (May '05) - ISourceReference element = findElementAtOffset( file, contents.indexOf( "Array" ) ); //$NON-NLS-1$ - String[] messages= getRefactorMessages( element, "Arr2" ); //$NON-NLS-1$ - assertEquals(1, messages.length); - assertEquals("Renaming a template class. Parsing templates are not fully functional. Check the results if you continue.", messages[0] ); //$NON-NLS-1$ - } - public void testClass_52() throws Exception { - StringWriter writer = new StringWriter(); - writer.write( "namespace N1 { \n" ); //$NON-NLS-1$ - writer.write( "class Boo{}; \n" ); //$NON-NLS-1$ - writer.write( "} \n" ); //$NON-NLS-1$ - writer.write( "namespace N2 { \n" ); //$NON-NLS-1$ - writer.write( "class Boo/*vp1*/{}; \n" ); //$NON-NLS-1$ - writer.write( "} \n" ); //$NON-NLS-1$ - writer.write( "void f() { \n" ); //$NON-NLS-1$ - writer.write( " N1::Boo c1; \n" ); //$NON-NLS-1$ - writer.write( " N2::Boo c2; \n" ); //$NON-NLS-1$ - writer.write( "} \n" ); //$NON-NLS-1$ - - String contents = writer.toString(); - IFile file = importFile( "t.cpp", contents ); //$NON-NLS-1$ - ISourceReference element = findElementAtOffset( file, contents.indexOf( "Boo/*vp1*/" ) ); //$NON-NLS-1$ - IChange changes = getRefactorChanges( element, "Ooga" ); //$NON-NLS-1$ - - assertTotalChanges( 2, changes ); - assertChange( changes, file, contents.indexOf("Boo/*vp1*/"), 3, "Ooga" ); //$NON-NLS-1$//$NON-NLS-2$ - assertChange( changes, file, contents.indexOf("Boo c2"), 3, "Ooga" ); //$NON-NLS-1$//$NON-NLS-2$ - } - public void testClass_53() throws Exception { - StringWriter writer = new StringWriter(); - writer.write( "class Foo/*vp1*/ {//ren1 \n" ); //$NON-NLS-1$ - writer.write( " Foo();//ren2 \n" ); //$NON-NLS-1$ - writer.write( " virtual ~Foo();//ren3 \n" ); //$NON-NLS-1$ - writer.write( "}; \n" ); //$NON-NLS-1$ - writer.write( "Foo::Foo() {}//ren4,5 \n" ); //$NON-NLS-1$ - writer.write( "Foo::~Foo() {}//ren6,7 \n" ); //$NON-NLS-1$ - writer.write( "void f() { \n" ); //$NON-NLS-1$ - writer.write( " Foo *f=new Foo();//ren8,9 \n" ); //$NON-NLS-1$ - writer.write( " f->~Foo();//ren10 \n" ); //$NON-NLS-1$ - writer.write( "} \n" ); //$NON-NLS-1$ - - String contents = writer.toString(); - IFile file = importFile( "t.cpp", contents ); //$NON-NLS-1$ - ISourceReference element = findElementAtOffset( file, contents.indexOf( "Foo/*vp1*/" ) ); //$NON-NLS-1$ - IChange changes = getRefactorChanges( element, "Ooga" ); //$NON-NLS-1$ - - assertTotalChanges( 10, changes ); - assertChange( changes, file, contents.indexOf("Foo/*vp1*/"), 3, "Ooga" ); //$NON-NLS-1$//$NON-NLS-2$ - assertChange( changes, file, contents.indexOf("Foo();//ren2"), 3, "Ooga" ); //$NON-NLS-1$//$NON-NLS-2$ - assertChange( changes, file, contents.indexOf("Foo();//ren3"), 3, "Ooga" ); //$NON-NLS-1$//$NON-NLS-2$ - assertChange( changes, file, contents.indexOf("Foo::Foo() {}//ren4,5"), 3, "Ooga" ); //$NON-NLS-1$//$NON-NLS-2$ - assertChange( changes, file, contents.indexOf("Foo() {}//ren4,5"), 3, "Ooga" ); //$NON-NLS-1$//$NON-NLS-2$ - assertChange( changes, file, contents.indexOf("Foo::~Foo() {}//ren6,7"), 3, "Ooga" ); //$NON-NLS-1$//$NON-NLS-2$ - assertChange( changes, file, contents.indexOf("Foo() {}//ren6,7"), 3, "Ooga" ); //$NON-NLS-1$//$NON-NLS-2$ - assertChange( changes, file, contents.indexOf("Foo *f=new Foo();//ren8,9"), 3, "Ooga" ); //$NON-NLS-1$//$NON-NLS-2$ - assertChange( changes, file, contents.indexOf("Foo();//ren8,9"), 3, "Ooga" ); //$NON-NLS-1$//$NON-NLS-2$ - assertChange( changes, file, contents.indexOf("Foo();//ren10"), 3, "Ooga" ); //$NON-NLS-1$//$NON-NLS-2$ - } - public void testAttribute_54() throws Exception { - StringWriter writer = new StringWriter(); - writer.write( "class Boo{ \n" ); //$NON-NLS-1$ - writer.write( " static int att;//vp1,rn1 \n" ); //$NON-NLS-1$ - writer.write( "}; \n" ); //$NON-NLS-1$ - writer.write( "void f() { \n" ); //$NON-NLS-1$ - writer.write( " Boo a; \n" ); //$NON-NLS-1$ - writer.write( " a.att;//rn2 \n" ); //$NON-NLS-1$ - writer.write( " Boo::att;//rn3 \n" ); //$NON-NLS-1$ - writer.write( "} \n" ); //$NON-NLS-1$ - - String contents = writer.toString(); - IFile file = importFile( "t.cpp", contents ); //$NON-NLS-1$ - ISourceReference element = findElementAtOffset( file, contents.indexOf( "att;//vp1" ) ); //$NON-NLS-1$ - IChange changes = getRefactorChanges( element, "ooga" ); //$NON-NLS-1$ - - assertTotalChanges( 3, changes ); - assertChange( changes, file, contents.indexOf("att;//vp1"), 3, "ooga" ); //$NON-NLS-1$//$NON-NLS-2$ - assertChange( changes, file, contents.indexOf("att;//rn2"), 3, "ooga" ); //$NON-NLS-1$//$NON-NLS-2$ - assertChange( changes, file, contents.indexOf("att;//rn3"), 3, "ooga" ); //$NON-NLS-1$//$NON-NLS-2$ - } - public void testClass_55() throws Exception { - StringWriter writer = new StringWriter(); - writer.write( "class Foo{ \n" ); //$NON-NLS-1$ - writer.write( " class Hoo{//vp1 \n" ); //$NON-NLS-1$ - writer.write( " public: Hoo(); \n" ); //$NON-NLS-1$ - writer.write( " }; \n" ); //$NON-NLS-1$ - writer.write( " Foo(){ \n" ); //$NON-NLS-1$ - writer.write( " Foo::Hoo h; \n" ); //$NON-NLS-1$ - writer.write( " } \n" ); //$NON-NLS-1$ - writer.write( "}; \n" ); //$NON-NLS-1$ - writer.write( "Foo::Hoo::Hoo(){} \n" ); //$NON-NLS-1$ - - String contents = writer.toString(); - IFile file = importFile( "t.cpp", contents ); //$NON-NLS-1$ - ISourceReference element = findElementAtOffset( file, contents.indexOf( "Hoo{" ) ); //$NON-NLS-1$ - IChange changes = getRefactorChanges( element, "ooga" ); //$NON-NLS-1$ - - assertTotalChanges( 5, changes ); - assertChange( changes, file, contents.indexOf("Hoo{//vp1"), 3, "ooga" ); //$NON-NLS-1$//$NON-NLS-2$ - assertChange( changes, file, contents.indexOf("Hoo();"), 3, "ooga" ); //$NON-NLS-1$//$NON-NLS-2$ - assertChange( changes, file, contents.indexOf("Hoo h;"), 3, "ooga" ); //$NON-NLS-1$//$NON-NLS-2$ - assertChange( changes, file, contents.indexOf("Hoo::Hoo(){}"), 3, "ooga" ); //$NON-NLS-1$//$NON-NLS-2$ - assertChange( changes, file, contents.indexOf("Hoo(){}"), 3, "ooga" ); //$NON-NLS-1$//$NON-NLS-2$ - } - public void testClass_55_79231() throws Exception { - StringWriter writer = new StringWriter(); - writer.write( "class Boo{};//vp1 \n" ); //$NON-NLS-1$ - writer.write( "class Foo{ \n" ); //$NON-NLS-1$ - writer.write( " Foo() { \n" ); //$NON-NLS-1$ - writer.write( " class Boo{}; \n" ); //$NON-NLS-1$ - writer.write( " Boo t; \n" ); //$NON-NLS-1$ - writer.write( "}; \n" ); //$NON-NLS-1$ - - String contents = writer.toString(); - IFile file = importFile( "t.cpp", contents ); //$NON-NLS-1$ - //defect is that the inner class defined in a method is also renamed, when it - // shouldn't be. - ISourceReference element = findElementAtOffset( file, contents.indexOf( "Boo{};//vp1" ) ); //$NON-NLS-1$ - IChange changes = getRefactorChanges( element, "Ooga" ); //$NON-NLS-1$ - - assertTotalChanges( 1, changes ); - assertChange( changes, file, contents.indexOf("Boo{};//vp1"), 3, "Ooga" ); //$NON-NLS-1$//$NON-NLS-2$ - } - - public void testClass_55_72748() throws Exception { - StringWriter writer = new StringWriter(); - writer.write( "class Foo{};//vp1 \n" ); //$NON-NLS-1$ - writer.write( "void f(){ \n" ); //$NON-NLS-1$ - writer.write( " Foo *somePtr; \n" ); //$NON-NLS-1$ - writer.write( " if (somePtr == reinterpret_cast(0)){} \n" ); //$NON-NLS-1$ - writer.write( "} \n" ); //$NON-NLS-1$ - - String contents = writer.toString(); - IFile file = importFile( "t.cpp", contents ); //$NON-NLS-1$ - //defect is that the Foo in <> is not renamed - ISourceReference element = findElementAtOffset( file, contents.indexOf( "Foo{};//vp1" ) ); //$NON-NLS-1$ - IChange changes = getRefactorChanges( element, "Ooga" ); //$NON-NLS-1$ - - assertTotalChanges( 3, changes ); - assertChange( changes, file, contents.indexOf("Foo{};//vp1"), 3, "Ooga" ); //$NON-NLS-1$//$NON-NLS-2$ - assertChange( changes, file, contents.indexOf("Foo *somePtr"), 3, "Ooga" ); //$NON-NLS-1$//$NON-NLS-2$ - assertChange( changes, file, contents.indexOf("Foo*>(0)"), 3, "Ooga" ); //$NON-NLS-1$//$NON-NLS-2$ - } - public void testClass_56() throws Exception { - StringWriter writer = new StringWriter(); - writer.write( "class Foo{};//vp1,rn1 \n" ); //$NON-NLS-1$ - writer.write( "class Derived: public Foo{//rn2 \n" ); //$NON-NLS-1$ - writer.write( " Derived():Foo(){}//rn3 \n" ); //$NON-NLS-1$ - writer.write( "}; \n" ); //$NON-NLS-1$ - - String contents = writer.toString(); - IFile file = importFile( "t.cpp", contents ); //$NON-NLS-1$ - //defect is that the inner class defined in a method is also renamed, when it - // shouldn't be. - ISourceReference element = findElementAtOffset( file, contents.indexOf( "Foo{};//vp1" ) ); //$NON-NLS-1$ - IChange changes = getRefactorChanges( element, "Ooga" ); //$NON-NLS-1$ - - assertTotalChanges( 3, changes ); - assertChange( changes, file, contents.indexOf("Foo{};//vp1"), 3, "Ooga" ); //$NON-NLS-1$//$NON-NLS-2$ - assertChange( changes, file, contents.indexOf("Foo{//rn2"), 3, "Ooga" ); //$NON-NLS-1$//$NON-NLS-2$ - assertChange( changes, file, contents.indexOf("Foo(){}//rn3"), 3, "Ooga" ); //$NON-NLS-1$//$NON-NLS-2$ - } - public void testClass_60() throws Exception { - StringWriter writer = new StringWriter(); - writer.write( "class Foo{public: Foo();};//vp1 \n" ); //$NON-NLS-1$ - String header = writer.toString(); - IFile h = importFile( "Foo.h", header ); //$NON-NLS-1$ - writer = new StringWriter(); - writer.write( "#include \"Foo.h\" \n" ); //$NON-NLS-1$ - writer.write( "Foo::Foo{}; \n" ); //$NON-NLS-1$ - - String source = writer.toString(); - importFile( "Foo.cpp", source ); //$NON-NLS-1$ - ISourceReference element = findElementAtOffset( h, header.indexOf( "Foo{" ) ); //$NON-NLS-1$ - getRefactorChanges( element, "Ooga" ); //$NON-NLS-1$ - IResource [] members = project.members(); - boolean foundh=false, foundcpp=false; - // make sure file names haven't changed - for( int i = 0; i < members.length; i++ ){ - if( members[i].getName().equals( "Foo.h" ) ) //$NON-NLS-1$ - foundh=true; - if( members[i].getName().equals( "Foo.cpp" ) ) //$NON-NLS-1$ - foundcpp=true; - } - if (!foundh || !foundcpp){ - fail ("At least one of Foo.h and Foo.cpp was incorrectly renamed."); //$NON-NLS-1$ - } - } - public void testAttribute_61() throws Exception { - StringWriter writer = new StringWriter(); - writer.write( "class Foo{ \n" ); //$NON-NLS-1$ - writer.write( " private: static int count;//vp1 \n" ); //$NON-NLS-1$ - writer.write( "}; \n" ); //$NON-NLS-1$ - String header = writer.toString(); - IFile h = importFile( "Foo.h", header ); //$NON-NLS-1$ - writer = new StringWriter(); - writer.write( "#include \"Foo.h\" \n" ); //$NON-NLS-1$ - writer.write( "int Foo::count=10; \n" ); //$NON-NLS-1$ - - String source = writer.toString(); - IFile cpp = importFile( "Foo.cpp", source ); //$NON-NLS-1$ - ISourceReference element = findElementAtOffset( h, header.indexOf( "count" ) ); //$NON-NLS-1$ - IChange changes = getRefactorChanges( element, "ooga" ); //$NON-NLS-1$ - - assertTotalChanges( 2, changes ); - assertChange( changes, h, header.indexOf("count"), 5, "ooga" ); //$NON-NLS-1$//$NON-NLS-2$ - assertChange( changes, cpp, source.indexOf("count"), 5, "ooga" ); //$NON-NLS-1$//$NON-NLS-2$ - - } - public void testEnumerator_62() throws Exception { - StringWriter writer = new StringWriter(); - writer.write( "enum Foo{E0, E1};//vp1 \n" ); //$NON-NLS-1$ - String header = writer.toString(); - IFile h = importFile( "Foo.h", header ); //$NON-NLS-1$ - writer = new StringWriter(); - writer.write( "#include \"Foo.h\" \n" ); //$NON-NLS-1$ - writer.write( "void f() { \n" ); //$NON-NLS-1$ - writer.write( " int i=E1; \n" ); //$NON-NLS-1$ - writer.write( "} \n" ); //$NON-NLS-1$ - - String source = writer.toString(); - IFile cpp=importFile( "Foo.cpp", source ); //$NON-NLS-1$ - ISourceReference element = findElementAtOffset( h, header.indexOf( "E1" ) ); //$NON-NLS-1$ - getRefactorChanges( element, "Ooga" ); //$NON-NLS-1$ - IChange changes = getRefactorChanges( element, "ooga" ); //$NON-NLS-1$ - - assertTotalChanges( 2, changes ); - assertChange( changes, h, header.indexOf("E1"), 2, "ooga" ); //$NON-NLS-1$//$NON-NLS-2$ - assertChange( changes, cpp, source.indexOf("E1"), 2, "ooga" ); //$NON-NLS-1$//$NON-NLS-2$ - - } - public void testAttribute_63() throws Exception { - StringWriter writer = new StringWriter(); - writer.write( "class Foo{ \n" ); //$NON-NLS-1$ - writer.write( " int att; \n" ); //$NON-NLS-1$ - writer.write( " Foo(int i); \n" ); //$NON-NLS-1$ - writer.write( "}; \n" ); //$NON-NLS-1$ - String header = writer.toString(); - IFile h = importFile( "Foo.h", header ); //$NON-NLS-1$ - writer = new StringWriter(); - writer.write( "#include \"Foo.h\" \n" ); //$NON-NLS-1$ - writer.write( "Foo::Foo(int i): att(i) {} \n" ); //$NON-NLS-1$ - - String source = writer.toString(); - IFile cpp = importFile( "Foo.cpp", source ); //$NON-NLS-1$ - ISourceReference element = findElementAtOffset( h, header.indexOf( "att" ) ); //$NON-NLS-1$ - IChange changes = getRefactorChanges( element, "ooga" ); //$NON-NLS-1$ - - assertTotalChanges( 2, changes ); - assertChange( changes, h, header.indexOf("att"), 3, "ooga" ); //$NON-NLS-1$//$NON-NLS-2$ - assertChange( changes, cpp, source.indexOf("att"), 3, "ooga" ); //$NON-NLS-1$//$NON-NLS-2$ - - } - public void testAttribute_64() throws Exception { - StringWriter writer = new StringWriter(); - writer.write( "class Foo{ \n" ); //$NON-NLS-1$ - writer.write( " private: \n" ); //$NON-NLS-1$ - writer.write( " int b;//vp1,rn1 \n" ); //$NON-NLS-1$ - writer.write( " int m(int b) { \n" ); //$NON-NLS-1$ - writer.write( " return b; \n" ); //$NON-NLS-1$ - writer.write( " } \n" ); //$NON-NLS-1$ - writer.write( " int n() { \n" ); //$NON-NLS-1$ - writer.write( " return b;//rn2 \n" ); //$NON-NLS-1$ - writer.write( " } \n" ); //$NON-NLS-1$ - writer.write( " int o() { \n" ); //$NON-NLS-1$ - writer.write( " int b=2; \n" ); //$NON-NLS-1$ - writer.write( " return b; \n" ); //$NON-NLS-1$ - writer.write( " } \n" ); //$NON-NLS-1$ - writer.write( "}; \n" ); //$NON-NLS-1$ - String header = writer.toString(); - IFile h = importFile( "Foo.h", header ); //$NON-NLS-1$ - ISourceReference element = findElementAtOffset( h, header.indexOf( "b;//vp1" ) ); //$NON-NLS-1$ - IChange changes = getRefactorChanges( element, "ooga" ); //$NON-NLS-1$ - - assertTotalChanges( 2, changes ); - assertChange( changes, h, header.indexOf("b;//vp1"), 1, "ooga" ); //$NON-NLS-1$//$NON-NLS-2$ - assertChange( changes, h, header.indexOf("b;//rn2"), 1, "ooga" ); //$NON-NLS-1$//$NON-NLS-2$ - - } - public void testAttribute_65() throws Exception { - StringWriter writer = new StringWriter(); - writer.write( "class A{ \n" ); //$NON-NLS-1$ - writer.write( " int x(); \n" ); //$NON-NLS-1$ - writer.write( "}; \n" ); //$NON-NLS-1$ - writer.write( "class B{ \n" ); //$NON-NLS-1$ - writer.write( " friend class A; \n" ); //$NON-NLS-1$ - writer.write( " private: \n" ); //$NON-NLS-1$ - writer.write( " int att; \n" ); //$NON-NLS-1$ - writer.write( "}; \n" ); //$NON-NLS-1$ - String header = writer.toString(); - IFile h = importFile( "Foo.h", header ); //$NON-NLS-1$ - writer = new StringWriter(); - writer.write( "#include \"Foo.h\" \n" ); //$NON-NLS-1$ - writer.write( "int A::x() { \n" ); //$NON-NLS-1$ - writer.write( " B b; \n" ); //$NON-NLS-1$ - writer.write( " int att=b.att; \n" ); //$NON-NLS-1$ - writer.write( "} \n" ); //$NON-NLS-1$ - String source = writer.toString(); - IFile cpp = importFile( "Foo.cpp", source ); //$NON-NLS-1$ - ISourceReference element = findElementAtOffset( h, header.indexOf( "att" ) ); //$NON-NLS-1$ - IChange changes = getRefactorChanges( element, "ooga" ); //$NON-NLS-1$ - - assertTotalChanges( 2, changes ); - assertChange( changes, h, header.indexOf("att"), 3, "ooga" ); //$NON-NLS-1$//$NON-NLS-2$ - assertChange( changes, cpp, source.indexOf("att;"), 3, "ooga" ); //$NON-NLS-1$//$NON-NLS-2$ - - } - public void testNamespace_66() throws Exception { - StringWriter writer = new StringWriter(); - writer.write( "namespace Foo/*vp1*/{ \n" ); //$NON-NLS-1$ - writer.write( " namespace Baz/*vp2*/ { \n" ); //$NON-NLS-1$ - writer.write( " int i; \n" ); //$NON-NLS-1$ - writer.write( " } \n" ); //$NON-NLS-1$ - writer.write( " using namespace Baz; \n" ); //$NON-NLS-1$ - writer.write( "} \n" ); //$NON-NLS-1$ - writer.write( "void f() { \n" ); //$NON-NLS-1$ - writer.write( " Foo::i = 1; \n" ); //$NON-NLS-1$ - writer.write( "} \n" ); //$NON-NLS-1$ - - String contents = writer.toString(); - IFile file = importFile( "t.cpp", contents ); //$NON-NLS-1$ - //vp1 Foo with ref in function - ISourceReference element = findElementAtOffset( file, contents.indexOf( "Foo/*vp1*/" ) ); //$NON-NLS-1$ - IChange changes = getRefactorChanges( element, "Ooga" ); //$NON-NLS-1$ - assertTotalChanges( 2, changes ); - assertChange( changes, file, contents.indexOf("Foo/*vp1*/"), 3, "Ooga" ); //$NON-NLS-1$//$NON-NLS-2$ - assertChange( changes, file, contents.indexOf("Foo::"), 3, "Ooga" ); //$NON-NLS-1$//$NON-NLS-2$ - //vp2 nested Baz with ref in using - element = findElementAtOffset( file, contents.indexOf( "Baz/*vp2*/" ) ); //$NON-NLS-1$ - changes = getRefactorChanges( element, "Wooga" ); //$NON-NLS-1$ - assertTotalChanges( 2, changes ); - assertChange( changes, file, contents.indexOf("Baz/*vp2*/"), 3, "Wooga" ); //$NON-NLS-1$//$NON-NLS-2$ - assertChange( changes, file, contents.indexOf("Baz;"), 3, "Wooga" ); //$NON-NLS-1$//$NON-NLS-2$ - - } - - public void testNamespace_66_79281() throws Exception { - StringWriter writer = new StringWriter(); - writer.write( "namespace Foo{ \n" ); //$NON-NLS-1$ - writer.write( " int i; \n" ); //$NON-NLS-1$ - writer.write( "} \n" ); //$NON-NLS-1$ - writer.write( "namespace Bar/*vp1*/ = Foo; \n" ); //$NON-NLS-1$ - writer.write( "void f() { \n" ); //$NON-NLS-1$ - writer.write( " Bar::i = 1; \n" ); //$NON-NLS-1$ - writer.write( "} \n" ); //$NON-NLS-1$ - - String contents = writer.toString(); - IFile file = importFile( "t.cpp", contents ); //$NON-NLS-1$ - ISourceReference element = findElementAtOffset( file, contents.indexOf( "Bar/*vp1*/" ) ); //$NON-NLS-1$ - IChange changes = getRefactorChanges( element, "Ooga" ); //$NON-NLS-1$ - assertTotalChanges( 2, changes ); - assertChange( changes, file, contents.indexOf("Bar/*vp1*/"), 3, "Ooga" ); //$NON-NLS-1$//$NON-NLS-2$ - assertChange( changes, file, contents.indexOf("Bar::"), 3, "Ooga" ); //$NON-NLS-1$//$NON-NLS-2$ - } - - public void testNamespace_66_79282() throws Exception { - StringWriter writer = new StringWriter(); - writer.write( "namespace Foo/*vp1*/{} \n" ); //$NON-NLS-1$ - writer.write( "namespace Bar = Foo; \n" ); //$NON-NLS-1$ - - String contents = writer.toString(); - IFile file = importFile( "t.cpp", contents ); //$NON-NLS-1$ - //defect is Foo on line 2 is not renamed - ISourceReference element = findElementAtOffset( file, contents.indexOf( "Foo/*vp1*/" ) ); //$NON-NLS-1$ - IChange changes = getRefactorChanges( element, "Ooga" ); //$NON-NLS-1$ - assertTotalChanges( 2, changes ); - assertChange( changes, file, contents.indexOf("Foo/*vp1*/"), 3, "Ooga" ); //$NON-NLS-1$//$NON-NLS-2$ - assertChange( changes, file, contents.indexOf("Foo;"), 3, "Ooga" ); //$NON-NLS-1$//$NON-NLS-2$ - } - public void testFunction_67() throws Exception { - StringWriter writer = new StringWriter(); - writer.write( "void foo/*vp1*/(){}//rn1 \n" ); //$NON-NLS-1$ - writer.write( "void bar(){ \n" ); //$NON-NLS-1$ - writer.write( " foo();//rn2 \n" ); //$NON-NLS-1$ - writer.write( "} \n" ); //$NON-NLS-1$ - writer.write( "namespace N{ \n" ); //$NON-NLS-1$ - writer.write( " class A{ \n" ); //$NON-NLS-1$ - writer.write( " A() {foo();}//rn3 \n" ); //$NON-NLS-1$ - writer.write( " }; \n" ); //$NON-NLS-1$ - writer.write( "} \n" ); //$NON-NLS-1$ - - String contents = writer.toString(); - IFile file = importFile( "t.cpp", contents ); //$NON-NLS-1$ - ISourceReference element = findElementAtOffset( file, contents.indexOf( "foo/*vp1*/" ) ); //$NON-NLS-1$ - IChange changes = getRefactorChanges( element, "ooga" ); //$NON-NLS-1$ - assertTotalChanges( 3, changes ); - assertChange( changes, file, contents.indexOf("foo/*vp1*/"), 3, "ooga" ); //$NON-NLS-1$//$NON-NLS-2$ - assertChange( changes, file, contents.indexOf("foo();//rn2"), 3, "ooga" ); //$NON-NLS-1$//$NON-NLS-2$ - assertChange( changes, file, contents.indexOf("foo();}//rn3"), 3, "ooga" ); //$NON-NLS-1$//$NON-NLS-2$ - } - public void testVariable_68() throws Exception { - StringWriter writer = new StringWriter(); - writer.write( "class A{ \n" ); //$NON-NLS-1$ - writer.write( " public: int i; \n" ); //$NON-NLS-1$ - writer.write( "}; \n" ); //$NON-NLS-1$ - writer.write( "A var;//vp1,rn1 \n" ); //$NON-NLS-1$ - writer.write( "void f(){ \n" ); //$NON-NLS-1$ - writer.write( " int j = ::var.i;//rn2 \n" ); //$NON-NLS-1$ - writer.write( "} \n" ); //$NON-NLS-1$ - writer.write( "class B{ \n" ); //$NON-NLS-1$ - writer.write( " void g(){ \n" ); //$NON-NLS-1$ - writer.write( " var.i=3;//rn3 \n" ); //$NON-NLS-1$ - writer.write( " } \n" ); //$NON-NLS-1$ - writer.write( "}; \n" ); //$NON-NLS-1$ - - String contents = writer.toString(); - IFile file = importFile( "t.cpp", contents ); //$NON-NLS-1$ - ISourceReference element = findElementAtOffset( file, contents.indexOf( "var;//vp1" ) ); //$NON-NLS-1$ - IChange changes = getRefactorChanges( element, "ooga" ); //$NON-NLS-1$ - assertTotalChanges( 3, changes ); - assertChange( changes, file, contents.indexOf("var;//vp1"), 3, "ooga" ); //$NON-NLS-1$//$NON-NLS-2$ - assertChange( changes, file, contents.indexOf("var.i;//rn2"), 3, "ooga" ); //$NON-NLS-1$//$NON-NLS-2$ - assertChange( changes, file, contents.indexOf("var.i=3;//rn3"), 3, "ooga" ); //$NON-NLS-1$//$NON-NLS-2$ - } - public void testVariable_68_79295() throws Exception { - StringWriter writer = new StringWriter(); - writer.write( "int var;//vp1 \n" ); //$NON-NLS-1$ - writer.write( "void f(int var){ \n" ); //$NON-NLS-1$ - writer.write( " int i = var; \n" ); //$NON-NLS-1$ - writer.write( "} \n" ); //$NON-NLS-1$ - - String contents = writer.toString(); - IFile file = importFile( "t.cpp", contents ); //$NON-NLS-1$ - //defect is the argument and local variable var are incorrectly renamed - ISourceReference element = findElementAtOffset( file, contents.indexOf( "var;//vp1" ) ); //$NON-NLS-1$ - IChange changes = getRefactorChanges( element, "ooga" ); //$NON-NLS-1$ - assertTotalChanges( 1, changes ); - assertChange( changes, file, contents.indexOf("var;//vp1"), 3, "ooga" ); //$NON-NLS-1$//$NON-NLS-2$ - } - public void testVariable_69() throws Exception { - StringWriter writer = new StringWriter(); - writer.write( "int i;//vp1 \n" ); //$NON-NLS-1$ - writer.write( "in t j; \n" ); //$NON-NLS-1$ - - String contents = writer.toString(); - IFile file = importFile( "t.cpp", contents ); //$NON-NLS-1$ - ISourceReference element = findElementAtOffset( file, contents.indexOf( "i;//vp1" ) ); //$NON-NLS-1$ - - String[] messages = getRefactorMessages( element, "ooga" ); //$NON-NLS-1$ - assertEquals(1, messages.length); - assertEquals("Code modification may not be accurate as affected resoure 'RegressionTestProject/t.cpp' has compile errors.", messages[0] ); //$NON-NLS-1$ - } - //similar to test 92, except this one will continue with warning, or error status - //while case in 92 must stop refactor with fatal status - public void testClass_81_72620() throws Exception { - StringWriter writer = new StringWriter(); - writer.write( "union u_haul{}; \n" ); //$NON-NLS-1$ - writer.write( "struct s_haul{}; \n" ); //$NON-NLS-1$ - String contents = writer.toString(); - IFile file = importFile( "t.cpp", contents ); //$NON-NLS-1$ - ISourceReference element = findElementAtOffset( file, contents.indexOf( "s_haul" ) ); //$NON-NLS-1$ - try { - getRefactorChanges( element, "u_haul" ); //$NON-NLS-1$ - } catch (AssertionFailedError e) { - assertTrue(e.getMessage().startsWith("Input check on u_haul failed.")); //$NON-NLS-1$ - return; - } - fail ("An error should have occurred in the input check."); //$NON-NLS-1$ - } - public void testVariable_88_72617() throws Exception { - StringWriter writer = new StringWriter(); - writer.write( "class A{}; \n" ); //$NON-NLS-1$ - writer.write( "A a;//vp1 \n" ); //$NON-NLS-1$ - String header = writer.toString(); - IFile h = importFile( "Foo.h", header ); //$NON-NLS-1$ - writer = new StringWriter(); - writer.write( "#include \"Foo.h\" \n" ); //$NON-NLS-1$ - writer.write( "void f() { \n" ); //$NON-NLS-1$ - writer.write( " A a; \n" ); //$NON-NLS-1$ - writer.write( "} \n" ); //$NON-NLS-1$ - String source = writer.toString(); - importFile( "Foo.cpp", source ); //$NON-NLS-1$ - ISourceReference element = findElementAtOffset( h, header.indexOf( "a;//vp1" ) ); //$NON-NLS-1$ - IChange changes = getRefactorChanges( element, "ooga" ); //$NON-NLS-1$ - - assertTotalChanges( 1, changes ); - assertChange( changes, h, header.indexOf("a;//vp1"), 1, "ooga" ); //$NON-NLS-1$//$NON-NLS-2$ - } - //2 ways to test name collistion on same type: - //if you don't know the error message, catch on getRefactorChanges - //or if you want to verify a message or severity, use getRefactorMessages - //and getRefactorSeverity - public void testClass_92A() throws Exception { - StringWriter writer = new StringWriter(); - writer.write( "class Boo{}; \n" ); //$NON-NLS-1$ - writer.write( " void f() {} \n" ); //$NON-NLS-1$ - writer.write( "}; \n" ); //$NON-NLS-1$ - writer.write( "class Foo/*vp1*/{}; \n" ); //$NON-NLS-1$ - - String contents = writer.toString(); - IFile file = importFile( "t.cpp", contents ); //$NON-NLS-1$ - ISourceReference element = findElementAtOffset( file, contents.indexOf( "Foo/*vp1*/" ) ); //$NON-NLS-1$ - try { - getRefactorChanges( element, "Boo" ); //$NON-NLS-1$ - } catch (AssertionFailedError e) { - assertTrue(e.getMessage().startsWith("Input check on Boo failed.")); //$NON-NLS-1$ - return; - } - fail ("An error or warning should have occurred in the input check."); //$NON-NLS-1$ - } - public void testClass_92B() throws Exception { - StringWriter writer = new StringWriter(); - writer.write( "class A{}; \n" ); //$NON-NLS-1$ - writer.write( "class B{};//vp1 \n" ); //$NON-NLS-1$ - - String contents = writer.toString(); - IFile file = importFile( "t.cpp", contents ); //$NON-NLS-1$ - ISourceReference element = findElementAtOffset( file, contents.indexOf( "B{};//vp1" ) ); //$NON-NLS-1$ - - String[] messages = getRefactorMessages( element, "A" ); //$NON-NLS-1$ - assertEquals(1, messages.length); - assertEquals("Another element named 'A' already exists in 't.cpp'", messages[0] ); //$NON-NLS-1$ - // assert that you cannot refactor because severity is FATAL (4) - int s = getRefactorSeverity(element, "A"); //$NON-NLS-1$ - assertEquals(RefactoringStatus.FATAL,s); - } -} diff --git a/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/regression/RegressionTestsUISuite.java b/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/regression/RegressionTestsUISuite.java deleted file mode 100644 index fbdadcbaeba..00000000000 --- a/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/regression/RegressionTestsUISuite.java +++ /dev/null @@ -1,50 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ - -/* - * Created on Nov 16, 2004 - */ -package org.eclipse.cdt.ui.tests.regression; - -import junit.framework.Test; -import junit.framework.TestSuite; - -/** - * @author aniefer - */ -public class RegressionTestsUISuite extends TestSuite { - public RegressionTestsUISuite() { - super(); - } - - public RegressionTestsUISuite(Class theClass, String name) { - super(theClass, name); - } - - public RegressionTestsUISuite(Class theClass) { - super(theClass); - } - - public RegressionTestsUISuite(String name) { - super(name); - } - - public static Test suite() { - final RegressionTestsUISuite suite = new RegressionTestsUISuite(); - - suite.addTest( ContentAssistRegressionTests.suite( false ) ); - //suite.addTest( RefactoringRegressionTests.suite( false ) ); - - //suite.addTest( new RefactoringRegressionTests("cleanupProject") ); //$NON-NLS-1$ - return suite; - } - -} diff --git a/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/text/contentassist/CompletionProposalsBaseTest.java b/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/text/contentassist/CompletionProposalsBaseTest.java index 47586da69bb..71640524066 100644 --- a/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/text/contentassist/CompletionProposalsBaseTest.java +++ b/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/text/contentassist/CompletionProposalsBaseTest.java @@ -27,11 +27,7 @@ import org.eclipse.cdt.core.model.ICProject; import org.eclipse.cdt.core.model.ITranslationUnit; import org.eclipse.cdt.core.model.IWorkingCopy; import org.eclipse.cdt.core.parser.ast.IASTCompletionNode; -import org.eclipse.cdt.core.parser.ast.IASTNode; -import org.eclipse.cdt.core.parser.ast.IASTScope; import org.eclipse.cdt.core.testplugin.CProjectHelper; -import org.eclipse.cdt.internal.core.browser.cache.TypeCacheManager; -import org.eclipse.cdt.internal.ui.text.contentassist.CCompletionProcessor; import org.eclipse.cdt.ui.testplugin.CTestPlugin; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; @@ -41,7 +37,6 @@ import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Path; import org.eclipse.jface.text.Document; -import org.eclipse.jface.text.contentassist.ICompletionProposal; public abstract class CompletionProposalsBaseTest extends TestCase{ protected static final String EMPTY_STRING = ""; //$NON-NLS-1$ @@ -98,12 +93,6 @@ public abstract class CompletionProposalsBaseTest extends TestCase{ addNatureToProject(fCProject.getProject(), CCProjectNature.CC_NATURE_ID, null); } - //TEMPORARY: Disable type cache - TypeCacheManager typeCacheManager = TypeCacheManager.getInstance(); - typeCacheManager.setProcessTypeCacheEvents(false); - - // use the new indexer - //IndexManager indexManager = CCorePlugin.getDefault().getCoreModel().getIndexManager(); } private static void addNatureToProject(IProject proj, String natureId, IProgressMonitor monitor) throws CoreException { @@ -130,58 +119,15 @@ public abstract class CompletionProposalsBaseTest extends TestCase{ int pos = getCompletionPosition(); - CCompletionProcessor completionProcessor = new CCompletionProcessor(null); IWorkingCopy wc = null; try{ wc = tu.getWorkingCopy(); }catch (CModelException e){ fail("Failed to get working copy"); //$NON-NLS-1$ } - - // call the CompletionProcessor - ICompletionProposal[] results = completionProcessor.evalProposals(document, pos, wc, null); - assertTrue(results != null); - - // check the completion node - IASTCompletionNode completionNode = completionProcessor.getCurrentCompletionNode(); - assertNotNull(completionNode); - // scope - IASTScope scope = completionNode.getCompletionScope(); - assertNotNull(scope); - assertTrue(scope.getClass().getName().endsWith(getExpectedScopeClassName())); - // context - IASTNode context = completionNode.getCompletionContext(); - if(context == null) - assertTrue(getExpectedContextClassName().equals("null")); //$NON-NLS-1$ - else - assertTrue(context.getClass().getName().endsWith(getExpectedContextClassName())); - // kind - IASTCompletionNode.CompletionKind kind = completionNode.getCompletionKind(); - assertTrue(kind == getExpectedKind()); - // prefix - String prefix = completionNode.getCompletionPrefix(); - assertEquals(prefix, getExpectedPrefix()); - - assertEquals( completionNode.getFunctionName(), getFunctionOrConstructorName() ); - - String[] expected = getExpectedResultsValues(); - assertTrue(results.length >= expected.length); - - for (int i = 0; i< expected.length; i++){ - boolean found = false; - for(int j = 0; j< results.length; j++){ - ICompletionProposal proposal = results[j]; - String displayString = proposal.getDisplayString(); - if(expected[i].equals(displayString)){ - found = true; - break; - } - } - assertTrue( "Lookup failed for " + expected[i], found ); //$NON-NLS-1$ - } } catch(CModelException e){ - } + } } /** diff --git a/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/text/contentassist/ContentAssistTests.java b/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/text/contentassist/ContentAssistTests.java index 5e593b51429..307599b67d6 100644 --- a/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/text/contentassist/ContentAssistTests.java +++ b/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/text/contentassist/ContentAssistTests.java @@ -29,10 +29,8 @@ import org.eclipse.cdt.core.model.ITranslationUnit; import org.eclipse.cdt.core.model.IWorkingCopy; import org.eclipse.cdt.core.testplugin.CProjectHelper; import org.eclipse.cdt.core.testplugin.FileManager; -import org.eclipse.cdt.internal.core.index.domsourceindexer.DOMSourceIndexer; import org.eclipse.cdt.internal.ui.CHelpProviderManager; import org.eclipse.cdt.internal.ui.text.CHelpBookDescriptor; -import org.eclipse.cdt.internal.ui.text.contentassist.CCompletionProcessor; import org.eclipse.cdt.ui.text.ICHelpInvocationContext; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; @@ -41,7 +39,6 @@ import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.NullProgressMonitor; -import org.eclipse.jface.text.Document; import org.eclipse.jface.text.contentassist.ICompletionProposal; /** @@ -64,7 +61,6 @@ public class ContentAssistTests extends TestCase { cPrj = CProjectHelper.createCCProject("ContentAssistTestProject", "bin"); //$NON-NLS-1$ //$NON-NLS-2$ project = cPrj.getProject(); - project.setSessionProperty(DOMSourceIndexer.activationKey,new Boolean(false)); } catch ( CoreException e ) { /*boo*/ } @@ -161,9 +157,7 @@ public class ContentAssistTests extends TestCase { } // call the CompletionProcessor - CCompletionProcessor completionProcessor = new CCompletionProcessor(null); - ICompletionProposal[] results = completionProcessor.evalProposals( new Document(buffer), offset, wc, null); - return results; + return new ICompletionProposal[0]; } public void testBug69334() throws Exception { diff --git a/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/text/contentassist2/CompletionProposalsBaseTest.java b/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/text/contentassist2/CompletionProposalsBaseTest.java index 009c9da44f1..0e08b6c0020 100644 --- a/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/text/contentassist2/CompletionProposalsBaseTest.java +++ b/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/text/contentassist2/CompletionProposalsBaseTest.java @@ -27,10 +27,7 @@ import org.eclipse.cdt.core.model.CoreModel; import org.eclipse.cdt.core.model.ICProject; import org.eclipse.cdt.core.model.ITranslationUnit; import org.eclipse.cdt.core.parser.ast.IASTCompletionNode; -import org.eclipse.cdt.core.parser.ast.IASTNode; -import org.eclipse.cdt.core.parser.ast.IASTScope; import org.eclipse.cdt.core.testplugin.CProjectHelper; -import org.eclipse.cdt.internal.core.browser.cache.TypeCacheManager; import org.eclipse.cdt.internal.ui.editor.CEditor; import org.eclipse.cdt.internal.ui.text.contentassist.CCompletionProcessor2; import org.eclipse.cdt.ui.testplugin.CTestPlugin; @@ -103,13 +100,6 @@ public abstract class CompletionProposalsBaseTest extends TestCase{ if (!fCProject.getProject().hasNature(CCProjectNature.CC_NATURE_ID)) { addNatureToProject(fCProject.getProject(), CCProjectNature.CC_NATURE_ID, null); } - - //TEMPORARY: Disable type cache - TypeCacheManager typeCacheManager = TypeCacheManager.getInstance(); - typeCacheManager.setProcessTypeCacheEvents(false); - - // use the new indexer - //IndexManager indexManager = CCorePlugin.getDefault().getCoreModel().getIndexManager(); } private static void addNatureToProject(IProject proj, String natureId, IProgressMonitor monitor) throws CoreException { diff --git a/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/text/selectiontests/BaseSelectionTestsIndexer.java b/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/text/selectiontests/BaseSelectionTestsIndexer.java index 657871ba31e..d86bfb760fc 100644 --- a/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/text/selectiontests/BaseSelectionTestsIndexer.java +++ b/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/text/selectiontests/BaseSelectionTestsIndexer.java @@ -21,9 +21,9 @@ import org.eclipse.cdt.core.ICDescriptor; import org.eclipse.cdt.core.ICDescriptorOperation; import org.eclipse.cdt.core.dom.ast.IASTName; import org.eclipse.cdt.core.dom.ast.IASTNode; -import org.eclipse.cdt.core.index.IIndexDelta; -import org.eclipse.cdt.core.index.IndexChangeEvent; -import org.eclipse.cdt.core.search.DOMSearchUtil; +import org.eclipse.cdt.core.dom.ast.IASTTranslationUnit; +import org.eclipse.cdt.core.model.CoreModel; +import org.eclipse.cdt.core.model.ITranslationUnit; import org.eclipse.cdt.core.testplugin.FileManager; import org.eclipse.cdt.internal.core.parser.ParserException; import org.eclipse.cdt.internal.ui.editor.ICEditorActionDefinitionIds; @@ -38,6 +38,7 @@ import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Path; import org.eclipse.jface.action.IAction; +import org.eclipse.jface.text.ITextSelection; import org.eclipse.jface.text.TextSelection; import org.eclipse.jface.viewers.ISelection; import org.eclipse.ui.IEditorInput; @@ -73,13 +74,6 @@ public class BaseSelectionTestsIndexer extends TestCase { } } - public void indexChanged(IndexChangeEvent event) { - IIndexDelta delta = event.getDelta(); - if (delta.getDeltaType() == IIndexDelta.MERGE_DELTA){ - fileIndexed = true; - } - } - protected String getMessage(IStatus status) { StringBuffer message = new StringBuffer("["); //$NON-NLS-1$ message.append(status.getMessage()); @@ -177,11 +171,11 @@ public class BaseSelectionTestsIndexer extends TestCase { fileIndexed = false; } - protected IASTNode testF3(IFile file, int offset) throws ParserException { + protected IASTNode testF3(IFile file, int offset) throws ParserException, CoreException { return testF3(file, offset, 0); } - protected IASTNode testF3(IFile file, int offset, int length) throws ParserException { + protected IASTNode testF3(IFile file, int offset, int length) throws ParserException, CoreException { if (offset < 0) throw new ParserException("offset can not be less than 0 and was " + offset); //$NON-NLS-1$ @@ -211,12 +205,15 @@ public class BaseSelectionTestsIndexer extends TestCase { // the action above should highlight the declaration, so now retrieve it and use that selection to get the IASTName selected on the TU ISelection sel = ((AbstractTextEditor)part).getSelectionProvider().getSelection(); - if (sel instanceof TextSelection) { - IASTName[] names = DOMSearchUtil.getSelectedNamesFrom(file, ((TextSelection)sel).getOffset(), ((TextSelection)sel).getLength()); - + if (sel instanceof ITextSelection) { + ITextSelection textSel = (ITextSelection)sel; + ITranslationUnit tu = (ITranslationUnit)CoreModel.getDefault().create(file); + IASTTranslationUnit ast = tu.getLanguage().getASTTranslationUnit(tu, 0); + IASTName[] names = tu.getLanguage().getSelectedNames(ast, textSel.getOffset(), textSel.getLength()); + if (names == null || names.length == 0) return null; - + return names[0]; } } @@ -262,11 +259,11 @@ public class BaseSelectionTestsIndexer extends TestCase { return null; } - protected IASTNode testCtrl_F3(IFile file, int offset) throws ParserException { + protected IASTNode testCtrl_F3(IFile file, int offset) throws ParserException, CoreException { return testCtrl_F3(file, offset, 0); } - protected IASTNode testCtrl_F3(IFile file, int offset, int length) throws ParserException { + protected IASTNode testCtrl_F3(IFile file, int offset, int length) throws ParserException, CoreException { if (offset < 0) throw new ParserException("offset can not be less than 0 and was " + offset); //$NON-NLS-1$ @@ -297,7 +294,10 @@ public class BaseSelectionTestsIndexer extends TestCase { ISelection sel = ((AbstractTextEditor)part).getSelectionProvider().getSelection(); if (sel instanceof TextSelection) { - IASTName[] names = DOMSearchUtil.getSelectedNamesFrom(file, ((TextSelection)sel).getOffset(), ((TextSelection)sel).getLength()); + ITextSelection textSel = (ITextSelection)sel; + ITranslationUnit tu = (ITranslationUnit)CoreModel.getDefault().create(file); + IASTTranslationUnit ast = tu.getLanguage().getASTTranslationUnit(tu, 0); + IASTName[] names = tu.getLanguage().getSelectedNames(ast, textSel.getOffset(), textSel.getLength()); if (names == null || names.length == 0) return null; @@ -386,7 +386,6 @@ public class BaseSelectionTestsIndexer extends TestCase { }; try { CCorePlugin.getDefault().getCDescriptorManager().runDescriptorOperation(project, op, new NullProgressMonitor()); - CCorePlugin.getDefault().getCoreModel().getIndexManager().indexerChangeNotification(project); } catch (CoreException e) {} } } diff --git a/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/text/selectiontests/CPPSelectionTestsCTagsIndexer.java b/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/text/selectiontests/CPPSelectionTestsCTagsIndexer.java index 97cfca96482..ebd6514397d 100644 --- a/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/text/selectiontests/CPPSelectionTestsCTagsIndexer.java +++ b/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/text/selectiontests/CPPSelectionTestsCTagsIndexer.java @@ -20,13 +20,9 @@ import org.eclipse.cdt.core.CCProjectNature; import org.eclipse.cdt.core.CCorePlugin; import org.eclipse.cdt.core.dom.ast.IASTName; import org.eclipse.cdt.core.dom.ast.IASTNode; -import org.eclipse.cdt.core.index.IIndexChangeListener; import org.eclipse.cdt.core.model.ICProject; import org.eclipse.cdt.core.testplugin.CProjectHelper; import org.eclipse.cdt.internal.core.dom.parser.ASTNode; -import org.eclipse.cdt.internal.core.index.ctagsindexer.CTagsIndexer; -import org.eclipse.cdt.internal.core.index.domsourceindexer.DOMSourceIndexer; -import org.eclipse.cdt.internal.core.search.indexing.IndexManager; import org.eclipse.cdt.make.core.MakeProjectNature; import org.eclipse.cdt.make.core.scannerconfig.ScannerConfigNature; import org.eclipse.cdt.make.internal.core.scannerconfig2.PerProjectSICollector; @@ -45,14 +41,11 @@ import org.eclipse.jface.viewers.ISelection; * * @author dsteffle */ -public class CPPSelectionTestsCTagsIndexer extends BaseSelectionTestsIndexer - implements IIndexChangeListener { +public class CPPSelectionTestsCTagsIndexer extends BaseSelectionTestsIndexer { private static final String INDEX_TAG = "3931153591.index"; //$NON-NLS-1$ IFile file; NullProgressMonitor monitor; - IndexManager indexManager; - CTagsIndexer sourceIndexer; static final String sourceIndexerID = "org.eclipse.cdt.core.ctagsindexer"; //$NON-NLS-1$ @@ -71,13 +64,6 @@ public class CPPSelectionTestsCTagsIndexer extends BaseSelectionTestsIndexer if (indexFile.exists()) indexFile.delete(); - //Set the id of the source indexer extension point as a session property to allow - //index manager to instantiate it - project.setSessionProperty(IndexManager.indexerIDKey, sourceIndexerID); - - //Enable indexing on test project - project.setSessionProperty(DOMSourceIndexer.activationKey,new Boolean(true)); - if (project==null) fail("Unable to create project"); //$NON-NLS-1$ IProjectDescription description = ResourcesPlugin.getWorkspace().newProjectDescription(project.getName()); CCProjectNature.addCCNature(project,monitor); @@ -85,24 +71,15 @@ public class CPPSelectionTestsCTagsIndexer extends BaseSelectionTestsIndexer ScannerConfigNature.addScannerConfigNature(project); PerProjectSICollector.calculateCompilerBuiltins(project); - indexManager = CCorePlugin.getDefault().getCoreModel().getIndexManager(); - resetIndexer(sourceIndexerID); // set indexer //indexManager.reset(); //Get the indexer used for the test project - sourceIndexer = (CTagsIndexer) indexManager.getIndexerForProject(project); - - if (!sourceIndexer.validCTagsInstalled()) - fail("Exuberant CTags not installed"); //$NON-NLS-1$ - - sourceIndexer.addIndexChangeListener(this); } protected void tearDown() { try { super.tearDown(); - sourceIndexer.removeIndexChangeListener(this); } catch (Exception e1) { } //Delete project diff --git a/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/text/selectiontests/CPPSelectionTestsDOMIndexer.java b/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/text/selectiontests/CPPSelectionTestsDOMIndexer.java index 11b61709447..e47297014f4 100644 --- a/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/text/selectiontests/CPPSelectionTestsDOMIndexer.java +++ b/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/text/selectiontests/CPPSelectionTestsDOMIndexer.java @@ -22,12 +22,9 @@ import org.eclipse.cdt.core.CCProjectNature; import org.eclipse.cdt.core.CCorePlugin; import org.eclipse.cdt.core.dom.ast.IASTName; import org.eclipse.cdt.core.dom.ast.IASTNode; -import org.eclipse.cdt.core.index.IIndexChangeListener; import org.eclipse.cdt.core.model.ICProject; import org.eclipse.cdt.core.testplugin.CProjectHelper; import org.eclipse.cdt.internal.core.dom.parser.ASTNode; -import org.eclipse.cdt.internal.core.index.domsourceindexer.DOMSourceIndexer; -import org.eclipse.cdt.internal.core.search.indexing.IndexManager; import org.eclipse.cdt.make.core.MakeProjectNature; import org.eclipse.cdt.make.core.scannerconfig.ScannerConfigNature; import org.eclipse.cdt.make.internal.core.scannerconfig2.PerProjectSICollector; @@ -44,12 +41,10 @@ import org.eclipse.core.runtime.NullProgressMonitor; * * @author dsteffle */ -public class CPPSelectionTestsDOMIndexer extends BaseSelectionTestsIndexer implements IIndexChangeListener { +public class CPPSelectionTestsDOMIndexer extends BaseSelectionTestsIndexer { private static final String INDEX_TAG = "1196338025.index"; //$NON-NLS-1$ IFile file; NullProgressMonitor monitor; - IndexManager indexManager; - DOMSourceIndexer sourceIndexer; static final String sourceIndexerID = "org.eclipse.cdt.core.domsourceindexer"; //$NON-NLS-1$ @@ -70,10 +65,8 @@ public class CPPSelectionTestsDOMIndexer extends BaseSelectionTestsIndexer imple //Set the id of the source indexer extension point as a session property to allow //index manager to instantiate it - project.setSessionProperty(IndexManager.indexerIDKey, sourceIndexerID); //Enable indexing on test project - project.setSessionProperty(DOMSourceIndexer.activationKey,new Boolean(true)); if (project==null) fail("Unable to create project"); //$NON-NLS-1$ IProjectDescription description = ResourcesPlugin.getWorkspace().newProjectDescription(project.getName()); @@ -82,20 +75,15 @@ public class CPPSelectionTestsDOMIndexer extends BaseSelectionTestsIndexer imple ScannerConfigNature.addScannerConfigNature(project); PerProjectSICollector.calculateCompilerBuiltins(project); - indexManager = CCorePlugin.getDefault().getCoreModel().getIndexManager(); - resetIndexer(sourceIndexerID); // set indexer //indexManager.reset(); //Get the indexer used for the test project - sourceIndexer = (DOMSourceIndexer) indexManager.getIndexerForProject(project); - sourceIndexer.addIndexChangeListener(this); } protected void tearDown() { try { super.tearDown(); - sourceIndexer.removeIndexChangeListener(this); } catch (Exception e1) { } //Delete project diff --git a/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/text/selectiontests/CPPSelectionTestsNoIndexer.java b/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/text/selectiontests/CPPSelectionTestsNoIndexer.java index 498a8b2e44e..388128f7584 100644 --- a/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/text/selectiontests/CPPSelectionTestsNoIndexer.java +++ b/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/text/selectiontests/CPPSelectionTestsNoIndexer.java @@ -23,8 +23,10 @@ import junit.framework.TestSuite; import org.eclipse.cdt.core.CCorePlugin; import org.eclipse.cdt.core.dom.ast.IASTName; import org.eclipse.cdt.core.dom.ast.IASTNode; +import org.eclipse.cdt.core.dom.ast.IASTTranslationUnit; +import org.eclipse.cdt.core.model.CoreModel; import org.eclipse.cdt.core.model.ICProject; -import org.eclipse.cdt.core.search.DOMSearchUtil; +import org.eclipse.cdt.core.model.ITranslationUnit; import org.eclipse.cdt.core.testplugin.CProjectHelper; import org.eclipse.cdt.core.testplugin.FileManager; import org.eclipse.cdt.internal.core.dom.parser.ASTNode; @@ -40,6 +42,7 @@ import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Path; import org.eclipse.jface.action.IAction; +import org.eclipse.jface.text.ITextSelection; import org.eclipse.jface.text.TextSelection; import org.eclipse.jface.viewers.ISelection; import org.eclipse.ui.IEditorPart; @@ -198,11 +201,11 @@ public class CPPSelectionTestsNoIndexer extends TestCase { return file; } - protected IASTNode testF3(IFile file, int offset) throws ParserException { + protected IASTNode testF3(IFile file, int offset) throws ParserException, CoreException { return testF3(file, offset, 0); } - protected IASTNode testF3(IFile file, int offset, int length) throws ParserException { + protected IASTNode testF3(IFile file, int offset, int length) throws ParserException, CoreException { disableIndex(); if (offset < 0) @@ -226,7 +229,10 @@ public class CPPSelectionTestsNoIndexer extends TestCase { ISelection sel = ((AbstractTextEditor)part).getSelectionProvider().getSelection(); if (sel instanceof TextSelection) { - IASTName[] names = DOMSearchUtil.getSelectedNamesFrom(file, ((TextSelection)sel).getOffset(), ((TextSelection)sel).getLength()); + ITextSelection textSel = (ITextSelection)sel; + ITranslationUnit tu = (ITranslationUnit)CoreModel.getDefault().create(file); + IASTTranslationUnit ast = tu.getLanguage().getASTTranslationUnit(tu, 0); + IASTName[] names = tu.getLanguage().getSelectedNames(ast, textSel.getOffset(), textSel.getLength()); if (names.length == 0) { assertFalse(true); @@ -239,11 +245,11 @@ public class CPPSelectionTestsNoIndexer extends TestCase { return null; } - protected IASTNode testCtrl_F3(IFile file, int offset) throws ParserException { + protected IASTNode testCtrl_F3(IFile file, int offset) throws ParserException, CoreException { return testCtrl_F3(file, offset, 0); } - protected IASTNode testCtrl_F3(IFile file, int offset, int length) throws ParserException { + protected IASTNode testCtrl_F3(IFile file, int offset, int length) throws ParserException, CoreException { disableIndex(); if (offset < 0) @@ -267,7 +273,10 @@ public class CPPSelectionTestsNoIndexer extends TestCase { ISelection sel = ((AbstractTextEditor)part).getSelectionProvider().getSelection(); if (sel instanceof TextSelection) { - IASTName[] names = DOMSearchUtil.getSelectedNamesFrom(file, ((TextSelection)sel).getOffset(), ((TextSelection)sel).getLength()); + ITextSelection textSel = (ITextSelection)sel; + ITranslationUnit tu = (ITranslationUnit)CoreModel.getDefault().create(file); + IASTTranslationUnit ast = tu.getLanguage().getASTTranslationUnit(tu, 0); + IASTName[] names = tu.getLanguage().getSelectedNames(ast, textSel.getOffset(), textSel.getLength()); if (names == null || names.length == 0) return null; diff --git a/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/text/selectiontests/CSelectionTestsCTagsIndexer.java b/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/text/selectiontests/CSelectionTestsCTagsIndexer.java index baf1323e46c..76948e71694 100644 --- a/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/text/selectiontests/CSelectionTestsCTagsIndexer.java +++ b/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/text/selectiontests/CSelectionTestsCTagsIndexer.java @@ -18,13 +18,9 @@ import junit.framework.TestSuite; import org.eclipse.cdt.core.CCorePlugin; import org.eclipse.cdt.core.dom.ast.IASTName; import org.eclipse.cdt.core.dom.ast.IASTNode; -import org.eclipse.cdt.core.index.IIndexChangeListener; import org.eclipse.cdt.core.model.ICProject; import org.eclipse.cdt.core.testplugin.CProjectHelper; import org.eclipse.cdt.internal.core.dom.parser.ASTNode; -import org.eclipse.cdt.internal.core.index.ctagsindexer.CTagsIndexer; -import org.eclipse.cdt.internal.core.index.domsourceindexer.DOMSourceIndexer; -import org.eclipse.cdt.internal.core.search.indexing.IndexManager; import org.eclipse.cdt.make.core.MakeProjectNature; import org.eclipse.cdt.make.core.scannerconfig.ScannerConfigNature; import org.eclipse.cdt.make.internal.core.scannerconfig2.PerProjectSICollector; @@ -43,14 +39,11 @@ import org.eclipse.jface.viewers.ISelection; * * @author dsteffle */ -public class CSelectionTestsCTagsIndexer extends BaseSelectionTestsIndexer - implements IIndexChangeListener { +public class CSelectionTestsCTagsIndexer extends BaseSelectionTestsIndexer { private static final String INDEX_TAG = "3931153591.index"; //$NON-NLS-1$ IFile file; NullProgressMonitor monitor; - IndexManager indexManager; - CTagsIndexer sourceIndexer; static final String sourceIndexerID = "org.eclipse.cdt.core.ctagsindexer"; //$NON-NLS-1$ @@ -71,10 +64,8 @@ public class CSelectionTestsCTagsIndexer extends BaseSelectionTestsIndexer //Set the id of the source indexer extension point as a session property to allow //index manager to instantiate it - project.setSessionProperty(IndexManager.indexerIDKey, sourceIndexerID); //Enable indexing on test project - project.setSessionProperty(DOMSourceIndexer.activationKey,new Boolean(true)); if (project==null) fail("Unable to create project"); //$NON-NLS-1$ IProjectDescription description = ResourcesPlugin.getWorkspace().newProjectDescription(project.getName()); @@ -82,20 +73,16 @@ public class CSelectionTestsCTagsIndexer extends BaseSelectionTestsIndexer ScannerConfigNature.addScannerConfigNature(project); PerProjectSICollector.calculateCompilerBuiltins(project); - indexManager = CCorePlugin.getDefault().getCoreModel().getIndexManager(); resetIndexer(sourceIndexerID); // set indexer //indexManager.reset(); //Get the indexer used for the test project - sourceIndexer = (CTagsIndexer) indexManager.getIndexerForProject(project); - sourceIndexer.addIndexChangeListener(this); } protected void tearDown() { try { super.tearDown(); - sourceIndexer.removeIndexChangeListener(this); } catch (Exception e1) { } //Delete project diff --git a/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/text/selectiontests/CSelectionTestsDOMIndexer.java b/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/text/selectiontests/CSelectionTestsDOMIndexer.java index 30d1feebb6e..4a4dc4daf34 100644 --- a/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/text/selectiontests/CSelectionTestsDOMIndexer.java +++ b/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/text/selectiontests/CSelectionTestsDOMIndexer.java @@ -18,12 +18,9 @@ import junit.framework.TestSuite; import org.eclipse.cdt.core.CCorePlugin; import org.eclipse.cdt.core.dom.ast.IASTName; import org.eclipse.cdt.core.dom.ast.IASTNode; -import org.eclipse.cdt.core.index.IIndexChangeListener; import org.eclipse.cdt.core.model.ICProject; import org.eclipse.cdt.core.testplugin.CProjectHelper; import org.eclipse.cdt.internal.core.dom.parser.ASTNode; -import org.eclipse.cdt.internal.core.index.domsourceindexer.DOMSourceIndexer; -import org.eclipse.cdt.internal.core.search.indexing.IndexManager; import org.eclipse.cdt.make.core.MakeProjectNature; import org.eclipse.cdt.make.core.scannerconfig.ScannerConfigNature; import org.eclipse.cdt.make.internal.core.scannerconfig2.PerProjectSICollector; @@ -40,12 +37,10 @@ import org.eclipse.core.runtime.NullProgressMonitor; * * @author dsteffle */ -public class CSelectionTestsDOMIndexer extends BaseSelectionTestsIndexer implements IIndexChangeListener { +public class CSelectionTestsDOMIndexer extends BaseSelectionTestsIndexer { private static final String INDEX_TAG = "1161844423.index"; //$NON-NLS-1$ IFile file; NullProgressMonitor monitor; - IndexManager indexManager; - DOMSourceIndexer sourceIndexer; static final String sourceIndexerID = "org.eclipse.cdt.core.domsourceindexer"; //$NON-NLS-1$ @@ -66,10 +61,8 @@ public class CSelectionTestsDOMIndexer extends BaseSelectionTestsIndexer impleme //Set the id of the source indexer extension point as a session property to allow //index manager to instantiate it - project.setSessionProperty(IndexManager.indexerIDKey, sourceIndexerID); //Enable indexing on test project - project.setSessionProperty(DOMSourceIndexer.activationKey,new Boolean(true)); if (project==null) fail("Unable to create project"); //$NON-NLS-1$ IProjectDescription description = ResourcesPlugin.getWorkspace().newProjectDescription(project.getName()); @@ -77,20 +70,15 @@ public class CSelectionTestsDOMIndexer extends BaseSelectionTestsIndexer impleme ScannerConfigNature.addScannerConfigNature(project); PerProjectSICollector.calculateCompilerBuiltins(project); - indexManager = CCorePlugin.getDefault().getCoreModel().getIndexManager(); - resetIndexer(sourceIndexerID); // set indexer //indexManager.reset(); //Get the indexer used for the test project - sourceIndexer = (DOMSourceIndexer) indexManager.getIndexerForProject(project); - sourceIndexer.addIndexChangeListener(this); } protected void tearDown() { try { super.tearDown(); - sourceIndexer.removeIndexChangeListener(this); } catch (Exception e1) { } //Delete project diff --git a/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/text/selectiontests/CSelectionTestsNoIndexer.java b/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/text/selectiontests/CSelectionTestsNoIndexer.java index 8dd5b756f6f..df41a73a0ba 100644 --- a/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/text/selectiontests/CSelectionTestsNoIndexer.java +++ b/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/text/selectiontests/CSelectionTestsNoIndexer.java @@ -21,8 +21,10 @@ import junit.framework.TestSuite; import org.eclipse.cdt.core.CCorePlugin; import org.eclipse.cdt.core.dom.ast.IASTName; import org.eclipse.cdt.core.dom.ast.IASTNode; +import org.eclipse.cdt.core.dom.ast.IASTTranslationUnit; +import org.eclipse.cdt.core.model.CoreModel; import org.eclipse.cdt.core.model.ICProject; -import org.eclipse.cdt.core.search.DOMSearchUtil; +import org.eclipse.cdt.core.model.ITranslationUnit; import org.eclipse.cdt.core.testplugin.CProjectHelper; import org.eclipse.cdt.core.testplugin.FileManager; import org.eclipse.cdt.internal.core.dom.parser.ASTNode; @@ -38,6 +40,7 @@ import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Path; import org.eclipse.jface.action.IAction; +import org.eclipse.jface.text.ITextSelection; import org.eclipse.jface.text.TextSelection; import org.eclipse.jface.viewers.ISelection; import org.eclipse.ui.IEditorPart; @@ -250,11 +253,11 @@ public class CSelectionTestsNoIndexer extends TestCase { // return folder; // } - protected IASTNode testF3(IFile file, int offset) throws ParserException { + protected IASTNode testF3(IFile file, int offset) throws ParserException, CoreException { return testF3(file, offset, 0); } - protected IASTNode testF3(IFile file, int offset, int length) throws ParserException { + protected IASTNode testF3(IFile file, int offset, int length) throws ParserException, CoreException { disableIndex(); if (offset < 0) @@ -278,7 +281,10 @@ public class CSelectionTestsNoIndexer extends TestCase { ISelection sel = ((AbstractTextEditor)part).getSelectionProvider().getSelection(); if (sel instanceof TextSelection) { - IASTName[] names = DOMSearchUtil.getSelectedNamesFrom(file, ((TextSelection)sel).getOffset(), ((TextSelection)sel).getLength()); + ITextSelection textSel = (ITextSelection)sel; + ITranslationUnit tu = (ITranslationUnit)CoreModel.getDefault().create(file); + IASTTranslationUnit ast = tu.getLanguage().getASTTranslationUnit(tu, 0); + IASTName[] names = tu.getLanguage().getSelectedNames(ast, textSel.getOffset(), textSel.getLength()); if (names == null || names.length == 0) return null; @@ -290,11 +296,11 @@ public class CSelectionTestsNoIndexer extends TestCase { return null; } - protected IASTNode testCtrl_F3(IFile file, int offset) throws ParserException { + protected IASTNode testCtrl_F3(IFile file, int offset) throws ParserException, CoreException { return testCtrl_F3(file, offset, 0); } - protected IASTNode testCtrl_F3(IFile file, int offset, int length) throws ParserException { + protected IASTNode testCtrl_F3(IFile file, int offset, int length) throws ParserException, CoreException { disableIndex(); if (offset < 0) @@ -318,7 +324,10 @@ public class CSelectionTestsNoIndexer extends TestCase { ISelection sel = ((AbstractTextEditor)part).getSelectionProvider().getSelection(); if (sel instanceof TextSelection) { - IASTName[] names = DOMSearchUtil.getSelectedNamesFrom(file, ((TextSelection)sel).getOffset(), ((TextSelection)sel).getLength()); + ITextSelection textSel = (ITextSelection)sel; + ITranslationUnit tu = (ITranslationUnit)CoreModel.getDefault().create(file); + IASTTranslationUnit ast = tu.getLanguage().getASTTranslationUnit(tu, 0); + IASTName[] names = tu.getLanguage().getSelectedNames(ast, textSel.getOffset(), textSel.getLength()); if (names == null || names.length == 0) return null; diff --git a/core/org.eclipse.cdt.ui/.classpath b/core/org.eclipse.cdt.ui/.classpath index aa069b2d8d0..23bb7906104 100644 --- a/core/org.eclipse.cdt.ui/.classpath +++ b/core/org.eclipse.cdt.ui/.classpath @@ -3,7 +3,6 @@ - diff --git a/core/org.eclipse.cdt.ui/META-INF/MANIFEST.MF b/core/org.eclipse.cdt.ui/META-INF/MANIFEST.MF index f1aefbf953d..5c82fb642f7 100644 --- a/core/org.eclipse.cdt.ui/META-INF/MANIFEST.MF +++ b/core/org.eclipse.cdt.ui/META-INF/MANIFEST.MF @@ -7,18 +7,12 @@ Bundle-Activator: org.eclipse.cdt.ui.CUIPlugin Bundle-Vendor: %providerName Bundle-Localization: plugin Export-Package: org.eclipse.cdt.internal.corext, - org.eclipse.cdt.internal.corext.refactoring, - org.eclipse.cdt.internal.corext.refactoring.base, - org.eclipse.cdt.internal.corext.refactoring.changes, - org.eclipse.cdt.internal.corext.refactoring.rename, org.eclipse.cdt.internal.corext.template.c, org.eclipse.cdt.internal.corext.textmanipulation, org.eclipse.cdt.internal.corext.util, org.eclipse.cdt.internal.ui, org.eclipse.cdt.internal.ui.actions, - org.eclipse.cdt.internal.ui.browser.cbrowsing, org.eclipse.cdt.internal.ui.browser.opentype, - org.eclipse.cdt.internal.ui.browser.typehierarchy, org.eclipse.cdt.internal.ui.buildconsole, org.eclipse.cdt.internal.ui.codemanipulation, org.eclipse.cdt.internal.ui.compare, @@ -30,9 +24,6 @@ Export-Package: org.eclipse.cdt.internal.corext, org.eclipse.cdt.internal.ui.editor.asm, org.eclipse.cdt.internal.ui.filters, org.eclipse.cdt.internal.ui.preferences, - org.eclipse.cdt.internal.ui.refactoring, - org.eclipse.cdt.internal.ui.refactoring.actions, - org.eclipse.cdt.internal.ui.search, org.eclipse.cdt.internal.ui.search.actions, org.eclipse.cdt.internal.ui.text, org.eclipse.cdt.internal.ui.text.c.hover, diff --git a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/cbrowsing/CBrowsingContentProvider.java b/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/cbrowsing/CBrowsingContentProvider.java deleted file mode 100644 index 9632d2278c1..00000000000 --- a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/cbrowsing/CBrowsingContentProvider.java +++ /dev/null @@ -1,364 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.browser.cbrowsing; - -import java.util.Collection; - -import org.eclipse.cdt.core.browser.AllTypesCache; -import org.eclipse.cdt.core.browser.ITypeCacheChangedListener; -import org.eclipse.cdt.core.browser.ITypeInfo; -import org.eclipse.cdt.core.model.CModelException; -import org.eclipse.cdt.core.model.CoreModel; -import org.eclipse.cdt.core.model.ElementChangedEvent; -import org.eclipse.cdt.core.model.IArchive; -import org.eclipse.cdt.core.model.IBinary; -import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.cdt.core.model.ICElementDelta; -import org.eclipse.cdt.core.model.ICElementVisitor; -import org.eclipse.cdt.core.model.ICModel; -import org.eclipse.cdt.core.model.ICProject; -import org.eclipse.cdt.core.model.IElementChangedListener; -import org.eclipse.cdt.core.model.ISourceRoot; -import org.eclipse.cdt.core.model.ITranslationUnit; -import org.eclipse.cdt.core.model.IWorkingCopy; -import org.eclipse.cdt.internal.ui.BaseCElementContentProvider; -import org.eclipse.cdt.ui.CUIPlugin; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.jface.viewers.ITreeContentProvider; -import org.eclipse.jface.viewers.StructuredViewer; -import org.eclipse.jface.viewers.Viewer; -import org.eclipse.swt.widgets.Control; -import org.eclipse.swt.widgets.Display; - -public abstract class CBrowsingContentProvider extends BaseCElementContentProvider implements ITreeContentProvider, - IElementChangedListener, ITypeCacheChangedListener { - - public static final Object CONTENT_CANCELLED = new Object(); - public static final Object CONTENT_ERROR = new Object(); - public static final Object CONTENT_EMPTY = new Object(); - - protected static final Object[] ERROR_NO_CHILDREN = new Object[] { CONTENT_ERROR }; - protected static final Object[] ERROR_CANCELLED = new Object[] { CONTENT_CANCELLED }; - protected static final Object[] EMPTY_CHILDREN = NO_CHILDREN; - protected static final Object[] INVALID_INPUT = NO_CHILDREN; - - protected StructuredViewer fViewer; - protected Object fInput = null; - protected IProject fProject = null; - protected CBrowsingPart fBrowsingPart; - protected int fReadsInDisplayThread; - - public CBrowsingContentProvider(CBrowsingPart browsingPart) { - fBrowsingPart = browsingPart; - fViewer = fBrowsingPart.getViewer(); - AllTypesCache.addTypeCacheChangedListener(this); - CoreModel.getDefault().addElementChangedListener(this); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.viewers.IContentProvider#inputChanged(org.eclipse.jface.viewers.Viewer, - * java.lang.Object, java.lang.Object) - */ - public synchronized void inputChanged(Viewer viewer, Object oldInput, Object newInput) { - if (newInput instanceof Collection) { - // Get a template object from the collection - Collection col = (Collection) newInput; - if (!col.isEmpty()) - newInput = col.iterator().next(); - else - newInput = null; - } - fInput = newInput; - fProject = getProject(newInput); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.viewers.IContentProvider#dispose() - */ - public void dispose() { - AllTypesCache.removeTypeCacheChangedListener(this); - CoreModel.getDefault().removeElementChangedListener(this); - } - - public void typeCacheChanged(IProject project) { - if (fInput != null && (fProject == null || !fProject.isAccessible() || fProject.equals(project))) { - Object input = null; - if (project != null && project.isAccessible()) { - input = getNewInput(project); - } - postAdjustInputAndSetSelection(input); - } - } - - private IProject getProject(Object input) { - if (input instanceof ICElement) { - ICProject cProj = ((ICElement) input).getCProject(); - if (cProj != null) - return cProj.getProject(); - } - if (input instanceof ITypeInfo) { - return ((ITypeInfo) input).getEnclosingProject(); - } - return null; - } - - private Object getNewInput(IProject project) { - if (fInput == null || fInput instanceof ICModel) { - return fInput; - } - if (fInput instanceof ICProject) { - ICProject cproject = CoreModel.getDefault().create(project); - if (!cproject.equals(fInput)) - return cproject; - return fInput; - } - if (fInput instanceof ISourceRoot) { - ICProject cproject = CoreModel.getDefault().create(project); - ISourceRoot cSourceRoot = (ISourceRoot) fInput; - if (!cSourceRoot.getCProject().equals(cproject)) { - return cSourceRoot; - } - try { - ISourceRoot[] roots = cproject.getSourceRoots(); - for (int i = 0; i < roots.length; ++i) { - ISourceRoot root = roots[i]; - if (!(root.getResource() instanceof IProject) && root.equals(cSourceRoot)) { - return root; - } - } - } catch (CModelException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - if (fInput instanceof ICElement) { - ICProject cproject = CoreModel.getDefault().create(project); - ICElement celem = (ICElement) fInput; - if (!celem.getCProject().equals(cproject)) { - return celem; - } - final ICElement[] searchInfo = new ICElement[] { celem, null }; - try { - cproject.accept(new ICElementVisitor() { - public boolean visit(ICElement element) throws CoreException { - if (searchInfo[1] != null) - return false; - if (element.equals(searchInfo[0])) { - searchInfo[1] = element; - return false; - } - return true; - } - }); - } catch (CoreException e) { - } - if (searchInfo[1] != null) - return searchInfo[1]; - return null; - } - if (fInput instanceof ITypeInfo) { - ITypeInfo info = (ITypeInfo) fInput; - if (info.exists()) - return info; - IProject infoProj = info.getEnclosingProject(); - if (infoProj == null) { - return null; - } - if (!infoProj.equals(project)) { - return info; - } - ITypeInfo globalNS = AllTypesCache.getGlobalNamespace(project); - if (info.equals(globalNS)) - return globalNS; - info = AllTypesCache.getType(project, info.getCElementType(), info.getQualifiedTypeName()); - if (info != null) { - return info; - } - return null; - } - return null; - } - - public void elementChanged(ElementChangedEvent event) { - try { - processDelta(event.getDelta()); - } catch (CModelException e) { - CUIPlugin.getDefault().log(e.getStatus()); - } - } - - protected boolean isPathEntryChange(ICElementDelta delta) { - int flags = delta.getFlags(); - return (delta.getKind() == ICElementDelta.CHANGED && ((flags & ICElementDelta.F_BINARY_PARSER_CHANGED) != 0 - || (flags & ICElementDelta.F_ADDED_PATHENTRY_LIBRARY) != 0 - || (flags & ICElementDelta.F_ADDED_PATHENTRY_SOURCE) != 0 - || (flags & ICElementDelta.F_REMOVED_PATHENTRY_LIBRARY) != 0 - || (flags & ICElementDelta.F_PATHENTRY_REORDER) != 0 - || (flags & ICElementDelta.F_REMOVED_PATHENTRY_SOURCE) != 0 || (flags & ICElementDelta.F_CHANGED_PATHENTRY_INCLUDE) != 0)); - } - - /** - * Processes a delta recursively. When more than two children are affected - * the tree is fully refreshed starting at this node. The delta is processed - * in the current thread but the viewer updates are posted to the UI thread. - */ - protected void processDelta(ICElementDelta delta) throws CModelException { - int kind = delta.getKind(); - int flags = delta.getFlags(); - ICElement element = delta.getElement(); - - if (element instanceof ITranslationUnit && ((ITranslationUnit) element).isWorkingCopy()) { - // ignore working copies - return; - } - - //System.out.println("Processing " + element); - - // handle open and closing of a solution or project - if (((flags & ICElementDelta.F_CLOSED) != 0) || ((flags & ICElementDelta.F_OPENED) != 0)) { - postRefresh(element); - } - - if (kind == ICElementDelta.REMOVED) { - postRemove(element); - } - - if (kind == ICElementDelta.ADDED) { - Object parent = internalGetParent(element); - postAdd(parent, element); - } - - if (kind == ICElementDelta.CHANGED) { - if (element instanceof ITranslationUnit || element instanceof IBinary || element instanceof IArchive) { - postRefresh(element); - return; - } - } - - if (isPathEntryChange(delta)) { - // throw the towel and do a full refresh of the affected C project. - postRefresh(element.getCProject()); - } - - ICElementDelta[] affectedChildren = delta.getAffectedChildren(); - for (int i = 0; i < affectedChildren.length; i++) { - processDelta(affectedChildren[i]); - } - } - - private void postAdjustInputAndSetSelection(final Object input) { - postRunnable(new Runnable() { - public void run() { - Control ctrl = fViewer.getControl(); - if (ctrl != null && !ctrl.isDisposed()) { - ctrl.setRedraw(false); - fBrowsingPart.adjustInputAndPreserveSelection(input); - ctrl.setRedraw(true); - } - } - }); - } - - private void postRefresh(final Object element) { - //System.out.println("UI refresh:" + root); - postRunnable(new Runnable() { - public void run() { - // 1GF87WR: ITPUI:ALL - SWTEx + NPE closing a workbench window. - Control ctrl = fViewer.getControl(); - if (ctrl != null && !ctrl.isDisposed()) { - if (element instanceof IWorkingCopy) { - if (fViewer.testFindItem(element) != null) { - fViewer.refresh(element); - } else { - fViewer.refresh(((IWorkingCopy) element).getOriginalElement()); - } - } else { - fViewer.refresh(element); - } - } - } - }); - } - - private void postAdd(final Object parent, final Object element) { - //System.out.println("UI add:" + parent + " " + element); - postRunnable(new Runnable() { - public void run() { - // 1GF87WR: ITPUI:ALL - SWTEx + NPE closing a workbench window. - Control ctrl = fViewer.getControl(); - if (ctrl != null && !ctrl.isDisposed()) { - if (parent instanceof IWorkingCopy) { - if (fViewer.testFindItem(parent) != null) { - fViewer.refresh(parent); - } else { - fViewer.refresh(((IWorkingCopy) parent).getOriginalElement()); - } - } else { - fViewer.refresh(parent); - } - } - } - }); - } - - private void postRemove(final Object element) { - //System.out.println("UI remove:" + element); - postRunnable(new Runnable() { - public void run() { - // 1GF87WR: ITPUI:ALL - SWTEx + NPE closing a workbench window. - Control ctrl = fViewer.getControl(); - if (ctrl != null && !ctrl.isDisposed()) { - Object parent = internalGetParent(element); - if (parent instanceof IWorkingCopy) { - if (fViewer.testFindItem(parent) != null) { - fViewer.refresh(parent); - } else { - fViewer.refresh(((IWorkingCopy) parent).getOriginalElement()); - } - } else { - fViewer.refresh(parent); - } - } - } - }); - } - - private void postRunnable(final Runnable r) { - Control ctrl = fViewer.getControl(); - if (ctrl != null && !ctrl.isDisposed()) { - ctrl.getDisplay().asyncExec(r); - } - } - - protected void startReadInDisplayThread() { - if (isDisplayThread()) - fReadsInDisplayThread++; - } - - protected void finishedReadInDisplayThread() { - if (isDisplayThread()) - fReadsInDisplayThread--; - } - - private boolean isDisplayThread() { - Control ctrl = fViewer.getControl(); - if (ctrl == null) - return false; - - Display currentDisplay = Display.getCurrent(); - return currentDisplay != null && currentDisplay.equals(ctrl.getDisplay()); - } -} diff --git a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/cbrowsing/CBrowsingElementComparer.java b/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/cbrowsing/CBrowsingElementComparer.java deleted file mode 100644 index a9289001f6f..00000000000 --- a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/cbrowsing/CBrowsingElementComparer.java +++ /dev/null @@ -1,26 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.browser.cbrowsing; - -import org.eclipse.cdt.internal.ui.cview.CViewElementComparer; - -public class CBrowsingElementComparer extends CViewElementComparer { - - public boolean equals(Object o1, Object o2) { - //TODO compare ITypeInfos - return super.equals(o1, o2); - } - - public int hashCode(Object o1) { - //TODO compare ITypeInfos - return super.hashCode(o1); - } -} diff --git a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/cbrowsing/CBrowsingElementFilter.java b/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/cbrowsing/CBrowsingElementFilter.java deleted file mode 100644 index a6685d4961f..00000000000 --- a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/cbrowsing/CBrowsingElementFilter.java +++ /dev/null @@ -1,24 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 QNX Software Systems and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * QNX Software Systems - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.browser.cbrowsing; - -import org.eclipse.cdt.core.browser.ITypeInfo; -import org.eclipse.cdt.internal.ui.filters.NonCElementFilter; -import org.eclipse.jface.viewers.Viewer; - -public class CBrowsingElementFilter extends NonCElementFilter { - - public boolean select(Viewer viewer, Object parent, Object element) { - if (element instanceof ITypeInfo) - return true; - return super.select(viewer, parent, element); - } -} diff --git a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/cbrowsing/CBrowsingLabelProvider.java b/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/cbrowsing/CBrowsingLabelProvider.java deleted file mode 100644 index 2a543ddccf6..00000000000 --- a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/cbrowsing/CBrowsingLabelProvider.java +++ /dev/null @@ -1,44 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 QNX Software Systems and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * QNX Software Systems - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.browser.cbrowsing; - -import org.eclipse.cdt.internal.ui.viewsupport.AppearanceAwareLabelProvider; -import org.eclipse.cdt.internal.ui.viewsupport.CElementImageProvider; -import org.eclipse.cdt.internal.ui.viewsupport.CElementLabels; -import org.eclipse.swt.graphics.Image; - -class CBrowsingLabelProvider extends AppearanceAwareLabelProvider { - - private static final int TEXTFLAGS = DEFAULT_TEXTFLAGS | CElementLabels.F_APP_TYPE_SIGNATURE; - private static final int IMAGEFLAGS = DEFAULT_IMAGEFLAGS | CElementImageProvider.SMALL_ICONS; - - CBrowsingLabelProvider() { - super(TEXTFLAGS, IMAGEFLAGS); - } - - public Image getImage(Object element) { - if (element == CBrowsingContentProvider.CONTENT_ERROR) { - return null; - } else if (element == CBrowsingContentProvider.CONTENT_CANCELLED) { - return null; - } - return super.getImage(element); - } - - public String getText(Object element) { - if (element == CBrowsingContentProvider.CONTENT_ERROR) { - return CBrowsingMessages.getString("CBrowsingLabelProvider.errorNoItems"); //$NON-NLS-1$ - } else if (element == CBrowsingContentProvider.CONTENT_CANCELLED) { - return CBrowsingMessages.getString("CBrowsingLabelProvider.errorCancelled"); //$NON-NLS-1$ - } - return super.getText(element); - } -} diff --git a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/cbrowsing/CBrowsingMessages.java b/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/cbrowsing/CBrowsingMessages.java deleted file mode 100644 index 9d691285e69..00000000000 --- a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/cbrowsing/CBrowsingMessages.java +++ /dev/null @@ -1,47 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.browser.cbrowsing; - -import java.text.MessageFormat; -import java.util.MissingResourceException; -import java.util.ResourceBundle; - -public class CBrowsingMessages { - - private static final String RESOURCE_BUNDLE= CBrowsingMessages.class.getName(); - - private static ResourceBundle fgResourceBundle= ResourceBundle.getBundle(RESOURCE_BUNDLE); - - private CBrowsingMessages() { - } - - public static String getString(String key) { - try { - return fgResourceBundle.getString(key); - } catch (MissingResourceException e) { - return "!" + key + "!";//$NON-NLS-2$ //$NON-NLS-1$ - } - } - /** - * Gets a string from the resource bundle and formats it with the argument - * - * @param key the string used to get the bundle value, must not be null - */ - public static String getFormattedString(String key, Object[] args) { - String format= null; - try { - format= fgResourceBundle.getString(key); - } catch (MissingResourceException e) { - return "!" + key + "!";//$NON-NLS-2$ //$NON-NLS-1$ - } - return MessageFormat.format(format, args); - } -} diff --git a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/cbrowsing/CBrowsingMessages.properties b/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/cbrowsing/CBrowsingMessages.properties deleted file mode 100644 index 127359a81bf..00000000000 --- a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/cbrowsing/CBrowsingMessages.properties +++ /dev/null @@ -1,31 +0,0 @@ -############################################################################### -# Copyright (c) 2004 IBM Corporation and others. -# All rights reserved. This program and the accompanying materials -# are made available under the terms of the Eclipse Public License v1.0 -# which accompanies this distribution, and is available at -# http://www.eclipse.org/legal/epl-v10.html -# -# Contributors: -# IBM Corporation - initial API and implementation -# QNX Software Systems - adapted for use in CDT -############################################################################### - -CBrowsingPart.toolTip= Working Set: {0} -CBrowsingPart.toolTip2= {0} - Working Set: {1} - -LexicalSortingAction.label= Sort -LexicalSortingAction.tooltip= Sort -LexicalSortingAction.description= Enable Sorting - -ClassesView.flatLayoutAction.label= &Flat -ClassesView.HierarchicalLayoutAction.label= &Hierarchical -ClassesView.LayoutActionGroup.layout.label= &Layout - -# the first argument is the string to which the second one is appended -StatusBar.concat= {0}, {1} - -ClassPathContainer.unbound_label={0} (unbound) -ClassPathContainer.unknown_label={0} (unknown) - -CBrowsingLabelProvider.errorNoItems= Unable to retrieve type information -CBrowsingLabelProvider.errorCancelled= Cancelled diff --git a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/cbrowsing/CBrowsingPart.java b/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/cbrowsing/CBrowsingPart.java deleted file mode 100644 index bfa53baea51..00000000000 --- a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/cbrowsing/CBrowsingPart.java +++ /dev/null @@ -1,1624 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.browser.cbrowsing; - -import java.lang.reflect.InvocationTargetException; -import java.util.Collection; -import java.util.Comparator; -import java.util.Iterator; -import java.util.List; - -import org.eclipse.cdt.core.browser.AllTypesCache; -import org.eclipse.cdt.core.browser.ITypeInfo; -import org.eclipse.cdt.core.browser.ITypeReference; -import org.eclipse.cdt.core.browser.TypeSearchScope; -import org.eclipse.cdt.core.browser.TypeUtil; -import org.eclipse.cdt.core.model.CModelException; -import org.eclipse.cdt.core.model.CoreModel; -import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.cdt.core.model.ICModel; -import org.eclipse.cdt.core.model.ICProject; -import org.eclipse.cdt.core.model.ISourceRoot; -import org.eclipse.cdt.core.model.ITranslationUnit; -import org.eclipse.cdt.core.model.IWorkingCopy; -import org.eclipse.cdt.core.resources.FileStorage; -import org.eclipse.cdt.internal.ui.browser.opentype.OpenTypeMessages; -import org.eclipse.cdt.internal.ui.editor.CEditor; -import org.eclipse.cdt.internal.ui.util.EditorUtility; -import org.eclipse.cdt.internal.ui.util.ExceptionHandler; -import org.eclipse.cdt.internal.ui.viewsupport.AppearanceAwareLabelProvider; -import org.eclipse.cdt.internal.ui.viewsupport.CElementLabels; -import org.eclipse.cdt.internal.ui.viewsupport.IViewPartInputProvider; -import org.eclipse.cdt.internal.ui.viewsupport.StatusBarUpdater; -import org.eclipse.cdt.internal.ui.workingsets.WorkingSetFilterActionGroup; -import org.eclipse.cdt.ui.CElementLabelProvider; -import org.eclipse.cdt.ui.CUIPlugin; -import org.eclipse.cdt.ui.IWorkingCopyManager; -import org.eclipse.cdt.ui.PreferenceConstants; -import org.eclipse.core.resources.IContainer; -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.resources.IStorage; -import org.eclipse.core.runtime.IAdaptable; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.jface.action.IMenuListener; -import org.eclipse.jface.action.IMenuManager; -import org.eclipse.jface.action.IStatusLineManager; -import org.eclipse.jface.action.IToolBarManager; -import org.eclipse.jface.action.MenuManager; -import org.eclipse.jface.dialogs.MessageDialog; -import org.eclipse.jface.operation.IRunnableWithProgress; -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.ITextSelection; -import org.eclipse.jface.util.Assert; -import org.eclipse.jface.util.IPropertyChangeListener; -import org.eclipse.jface.util.PropertyChangeEvent; -import org.eclipse.jface.viewers.IContentProvider; -import org.eclipse.jface.viewers.IElementComparer; -import org.eclipse.jface.viewers.ILabelProvider; -import org.eclipse.jface.viewers.IOpenListener; -import org.eclipse.jface.viewers.ISelection; -import org.eclipse.jface.viewers.ISelectionChangedListener; -import org.eclipse.jface.viewers.ISelectionProvider; -import org.eclipse.jface.viewers.IStructuredSelection; -import org.eclipse.jface.viewers.LabelProvider; -import org.eclipse.jface.viewers.OpenEvent; -import org.eclipse.jface.viewers.SelectionChangedEvent; -import org.eclipse.jface.viewers.StructuredSelection; -import org.eclipse.jface.viewers.StructuredViewer; -import org.eclipse.jface.viewers.ViewerSorter; -import org.eclipse.swt.SWT; -import org.eclipse.swt.events.KeyAdapter; -import org.eclipse.swt.events.KeyEvent; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Display; -import org.eclipse.swt.widgets.Menu; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.ui.IActionBars; -import org.eclipse.ui.IEditorInput; -import org.eclipse.ui.IEditorPart; -import org.eclipse.ui.IFileEditorInput; -import org.eclipse.ui.IMemento; -import org.eclipse.ui.IPartListener2; -import org.eclipse.ui.ISelectionListener; -import org.eclipse.ui.IViewSite; -import org.eclipse.ui.IWorkbenchPage; -import org.eclipse.ui.IWorkbenchPart; -import org.eclipse.ui.IWorkbenchPartReference; -import org.eclipse.ui.IWorkbenchPartSite; -import org.eclipse.ui.IWorkingSet; -import org.eclipse.ui.IWorkingSetManager; -import org.eclipse.ui.PartInitException; -import org.eclipse.ui.PlatformUI; -import org.eclipse.ui.part.IShowInSource; -import org.eclipse.ui.part.ShowInContext; -import org.eclipse.ui.part.ViewPart; -import org.eclipse.ui.progress.IProgressService; -import org.eclipse.ui.texteditor.ITextEditor; - -public abstract class CBrowsingPart extends ViewPart implements IMenuListener, ISelectionListener, IViewPartInputProvider { - -// private static final String TAG_SELECTED_ELEMENTS= "selectedElements"; //$NON-NLS-1$ -// private static final String TAG_SELECTED_ELEMENT= "selectedElement"; //$NON-NLS-1$ -// private static final String TAG_LOGICAL_PACKAGE= "logicalPackage"; //$NON-NLS-1$ -// private static final String TAG_SELECTED_ELEMENT_PATH= "selectedElementPath"; //$NON-NLS-1$ - - private LabelProvider fLabelProvider; - private ILabelProvider fTitleProvider; - private StructuredViewer fViewer; - private IMemento fMemento; - private TypeInfoComparator fTypeComparator; - - // Actions - private WorkingSetFilterActionGroup fWorkingSetFilterActionGroup; - private boolean fHasWorkingSetFilter= true; - private boolean fHasCustomFilter= true; -// private OpenEditorActionGroup fOpenEditorGroup; -// private CCPActionGroup fCCPActionGroup; -// private BuildActionGroup fBuildActionGroup; - private ToggleLinkingAction fToggleLinkingAction; -// protected CompositeActionGroup fActionGroups; - - -// // Filters -// private CustomFiltersActionGroup fCustomFiltersActionGroup; - - protected IWorkbenchPart fPreviousSelectionProvider; - protected Object fPreviousSelectedElement; - - // Linking - private boolean fLinkingEnabled; - - /* - * Ensure selection changed events being processed only if - * initiated by user interaction with this part. - */ - boolean fProcessSelectionEvents= true; - - private IPartListener2 fPartListener= new IPartListener2() { - public void partActivated(IWorkbenchPartReference ref) { - setSelectionFromEditor(ref); - } - public void partBroughtToTop(IWorkbenchPartReference ref) { - setSelectionFromEditor(ref); - } - public void partInputChanged(IWorkbenchPartReference ref) { - setSelectionFromEditor(ref); - } - public void partClosed(IWorkbenchPartReference ref) { - } - public void partDeactivated(IWorkbenchPartReference ref) { - } - public void partOpened(IWorkbenchPartReference ref) { - } - public void partVisible(IWorkbenchPartReference ref) { - if (ref != null && ref.getId() == getSite().getId()){ - fProcessSelectionEvents= true; - IWorkbenchPage page= getSite().getWorkbenchWindow().getActivePage(); - if (page != null) - selectionChanged(page.getActivePart(), page.getSelection()); - } - } - public void partHidden(IWorkbenchPartReference ref) { - if (ref != null && ref.getId() == getSite().getId()) - fProcessSelectionEvents= false; - } - }; - - public CBrowsingPart() { - super(); - initLinkingEnabled(); - } - - /* - * Implements method from IViewPart. - */ - public void init(IViewSite site, IMemento memento) throws PartInitException { - super.init(site, memento); - fMemento= memento; - } - - /* - * Implements method from IViewPart. - */ - public void saveState(IMemento memento) { - if (fViewer == null) { - // part has not been created - if (fMemento != null) //Keep the old state; - memento.putMemento(fMemento); - return; - } - if (fHasWorkingSetFilter) - fWorkingSetFilterActionGroup.saveState(memento); -// if (fHasCustomFilter) -// fCustomFiltersActionGroup.saveState(memento); - saveSelectionState(memento); - saveLinkingEnabled(memento); - } - - private void saveLinkingEnabled(IMemento memento) { - memento.putInteger(getLinkToEditorKey(), fLinkingEnabled ? 1 : 0); - } - - private void saveSelectionState(IMemento memento) { -/* Object elements[]= ((IStructuredSelection) fViewer.getSelection()).toArray(); - if (elements.length > 0) { - IMemento selectionMem= memento.createChild(TAG_SELECTED_ELEMENTS); - for (int i= 0; i < elements.length; i++) { - IMemento elementMem= selectionMem.createChild(TAG_SELECTED_ELEMENT); - Object o= elements[i]; - if (o instanceof ICElement) - elementMem.putString(TAG_SELECTED_ELEMENT_PATH, ((ICElement) elements[i]).getHandleIdentifier()); - else if (o instanceof LogicalPackage) { - IPackageFragment[] packages=((LogicalPackage)o).getFragments(); - for (int j= 0; j < packages.length; j++) { - IMemento packageMem= elementMem.createChild(TAG_LOGICAL_PACKAGE); - packageMem.putString(TAG_SELECTED_ELEMENT_PATH, packages[j].getHandleIdentifier()); - } - } - } - } -*/ - } - - protected void restoreState(IMemento memento) { - if (fHasWorkingSetFilter) - fWorkingSetFilterActionGroup.restoreState(memento); -// if (fHasCustomFilter) -// fCustomFiltersActionGroup.restoreState(memento); - - if (fHasCustomFilter || fHasWorkingSetFilter) { - fViewer.getControl().setRedraw(false); - fViewer.refresh(); - fViewer.getControl().setRedraw(true); - } - } - - private ISelection restoreSelectionState(IMemento memento) { -/* - if (memento == null) - return null; - - IMemento childMem; - childMem= memento.getChild(TAG_SELECTED_ELEMENTS); - if (childMem != null) { - ArrayList list= new ArrayList(); - IMemento[] elementMem= childMem.getChildren(TAG_SELECTED_ELEMENT); - for (int i= 0; i < elementMem.length; i++) { - String javaElementHandle= elementMem[i].getString(TAG_SELECTED_ELEMENT_PATH); - if (javaElementHandle == null) { - // logical package - IMemento[] packagesMem= elementMem[i].getChildren(TAG_LOGICAL_PACKAGE); - LogicalPackage lp= null; - for (int j= 0; j < packagesMem.length; j++) { - javaElementHandle= packagesMem[j].getString(TAG_SELECTED_ELEMENT_PATH); - Object pack= (IPackageFragment)JavaCore.create(javaElementHandle); - if (pack instanceof IPackageFragment && ((IPackageFragment)pack).exists()) { - if (lp == null) - lp= new LogicalPackage((IPackageFragment)pack); - else - lp.add((IPackageFragment)pack); - } - } - if (lp != null) - list.add(lp); - } else { - ICElement element= JavaCore.create(javaElementHandle); - if (element != null && element.exists()) - list.add(element); - } - } - return new StructuredSelection(list); - } -*/ - return null; - } - - private void restoreLinkingEnabled(IMemento memento) { - Integer val= memento.getInteger(getLinkToEditorKey()); - if (val != null) { - fLinkingEnabled= val.intValue() != 0; - } - } - - /** - * Creates the search list inner viewer. - */ - public void createPartControl(Composite parent) { - Assert.isTrue(fViewer == null); - - - fTypeComparator= new TypeInfoComparator(); - - // Setup viewer - fViewer= createViewer(parent); - - initDragAndDrop(); - - fLabelProvider= createLabelProvider(); - fViewer.setLabelProvider(fLabelProvider); - - fViewer.setSorter(createViewerSorter()); - fViewer.setComparer(createElementComparer()); - - fViewer.setUseHashlookup(true); - fTitleProvider= createTitleProvider(); - - fViewer.setComparer(new CBrowsingElementComparer()); - - createContextMenu(); - getSite().setSelectionProvider(fViewer); - - if (fMemento != null) { // initialize linking state before creating the actions - restoreLinkingEnabled(fMemento); - } - - createActions(); // call before registering for selection changes - addKeyListener(); - - if (fMemento != null) - restoreState(fMemento); - - getSite().setSelectionProvider(fViewer); - - // Status line - IStatusLineManager slManager= getViewSite().getActionBars().getStatusLineManager(); - fViewer.addSelectionChangedListener(createStatusBarUpdater(slManager)); - - - hookViewerListeners(); - - // Filters - addFilters(); - - // Initialize viewer input - fViewer.setContentProvider(createContentProvider()); - setInitialInput(); - - // Initialize selecton - setInitialSelection(); - fMemento= null; - - // Listen to page changes - getViewSite().getPage().addPostSelectionListener(this); - getViewSite().getPage().addPartListener(fPartListener); - - fillActionBars(getViewSite().getActionBars()); - - setHelp(); - } - - /** - * Answer the property defined by key. - */ - public Object getAdapter(Class key) { - if (key == IShowInSource.class) { - return getShowInSource(); - } - return super.getAdapter(key); - } - - /** - * Returns the IShowInSource for this view. - */ - protected IShowInSource getShowInSource() { - return new IShowInSource() { - public ShowInContext getShowInContext() { - return new ShowInContext( - null, - getSite().getSelectionProvider().getSelection()); - } - }; - } - -// protected DecoratingLabelProvider createDecoratingLabelProvider(CUILabelProvider provider) { -//// XXX: Work in progress for problem decorator being a workbench decorator// -//// return new ExcludingDecoratingLabelProvider(provider, decorationMgr, "org.eclipse.jdt.ui.problem.decorator"); //$NON-NLS-1$ -// return new DecoratingCLabelProvider(provider); -// } - - protected StatusBarUpdater createStatusBarUpdater(IStatusLineManager slManager) { - return new StatusBarUpdater(slManager); - } - - protected void createContextMenu() { - MenuManager menuManager= new MenuManager("#PopupMenu"); //$NON-NLS-1$ - menuManager.setRemoveAllWhenShown(true); - menuManager.addMenuListener(this); - Menu contextMenu= menuManager.createContextMenu(fViewer.getControl()); - fViewer.getControl().setMenu(contextMenu); - getSite().registerContextMenu(menuManager, fViewer); - } - - protected void initDragAndDrop() { -/* int ops= DND.DROP_COPY | DND.DROP_MOVE | DND.DROP_LINK; - // drop - Transfer[] dropTransfers= new Transfer[] { - LocalSelectionTransfer.getInstance() - }; - TransferDropTargetListener[] dropListeners= new TransferDropTargetListener[] { - new SelectionTransferDropAdapter(fViewer) - }; - fViewer.addDropSupport(ops | DND.DROP_DEFAULT, dropTransfers, new DelegatingDropAdapter(dropListeners)); - - // Drag - Transfer[] dragTransfers= new Transfer[] { - LocalSelectionTransfer.getInstance(), - ResourceTransfer.getInstance()}; - TransferDragSourceListener[] dragListeners= new TransferDragSourceListener[] { - new SelectionTransferDragAdapter(fViewer), - new ResourceTransferDragAdapter(fViewer) - }; - fViewer.addDragSupport(ops, dragTransfers, new JdtViewerDragAdapter(fViewer, dragListeners)); -*/ } - - protected void fillActionBars(IActionBars actionBars) { - IToolBarManager toolBar= actionBars.getToolBarManager(); - fillToolBar(toolBar); - - - if (fHasWorkingSetFilter) - fWorkingSetFilterActionGroup.fillActionBars(getViewSite().getActionBars()); - - actionBars.updateActionBars(); - -// fActionGroups.fillActionBars(actionBars); -// -// if (fHasCustomFilter) -// fCustomFiltersActionGroup.fillActionBars(actionBars); -// - IMenuManager menu= actionBars.getMenuManager(); - menu.add(fToggleLinkingAction); - } - - //---- IWorkbenchPart ------------------------------------------------------ - - - public void setFocus() { - fViewer.getControl().setFocus(); - } - - public void dispose() { - if (fViewer != null) { - getViewSite().getPage().removePostSelectionListener(this); - getViewSite().getPage().removePartListener(fPartListener); - fViewer= null; - } -// if (fActionGroups != null) -// fActionGroups.dispose(); - - if (fWorkingSetFilterActionGroup != null) { - fWorkingSetFilterActionGroup.dispose(); - } - - super.dispose(); - } - - /** - * Adds the KeyListener - */ - protected void addKeyListener() { - fViewer.getControl().addKeyListener(new KeyAdapter() { - public void keyReleased(KeyEvent event) { - handleKeyReleased(event); - } - }); - } - - protected void handleKeyReleased(KeyEvent event) { - if (event.stateMask != 0) - return; - - int key= event.keyCode; - if (key == SWT.F5) { -// IAction action= fBuildActionGroup.getRefreshAction(); -// if (action.isEnabled()) -// action.run(); - } - } - - //---- Adding Action to Toolbar ------------------------------------------- - - protected void fillToolBar(IToolBarManager tbm) { - } - - /** - * Called when the context menu is about to open. - * Override to add your own context dependent menu contributions. - */ - public void menuAboutToShow(IMenuManager menu) { - CUIPlugin.createStandardGroups(menu); - - IStructuredSelection selection= (IStructuredSelection) fViewer.getSelection(); - int size= selection.size(); - Object element= selection.getFirstElement(); - - if (size == 1) - addOpenNewWindowAction(menu, element); -// fActionGroups.setContext(new ActionContext(selection)); -// fActionGroups.fillContextMenu(menu); -// fActionGroups.setContext(null); - } - - private void addOpenNewWindowAction(IMenuManager menu, Object element) { - if (element instanceof ICElement) { - element= ((ICElement)element).getResource(); - } - if (!(element instanceof IContainer)) - return; -// menu.appendToGroup( -// IContextMenuConstants.GROUP_OPEN, -// new PatchedOpenInNewWindowAction(getSite().getWorkbenchWindow(), (IContainer)element)); - } - - protected void createActions() { -// fActionGroups= new CompositeActionGroup(new ActionGroup[] { -// new NewWizardsActionGroup(this.getSite()), -// fOpenEditorGroup= new OpenEditorActionGroup(this), -// new OpenViewActionGroup(this), -// fCCPActionGroup= new CCPActionGroup(this), -// new GenerateActionGroup(this), -// new RefactorActionGroup(this), -// new ImportActionGroup(this), -// fBuildActionGroup= new BuildActionGroup(this), -// new JavaSearchActionGroup(this)}); - - - if (fHasWorkingSetFilter) { - String viewId= getConfigurationElement().getAttribute("id"); //$NON-NLS-1$ - Assert.isNotNull(viewId); - IPropertyChangeListener workingSetListener= new IPropertyChangeListener() { - public void propertyChange(PropertyChangeEvent event) { - doWorkingSetChanged(event); - } - }; - fWorkingSetFilterActionGroup= new WorkingSetFilterActionGroup(viewId, getShell(), workingSetListener); - fViewer.addFilter(fWorkingSetFilterActionGroup.getWorkingSetFilter()); - } - -// // Custom filter group -// if (fHasCustomFilter) -// fCustomFiltersActionGroup= new CustomFiltersActionGroup(this, fViewer); -// - fToggleLinkingAction= new ToggleLinkingAction(this); - } - - void doWorkingSetChanged(PropertyChangeEvent event) { - String property= event.getProperty(); - if (IWorkingSetManager.CHANGE_WORKING_SET_NAME_CHANGE.equals(property)) - updateTitle(); - else if (IWorkingSetManager.CHANGE_WORKING_SET_CONTENT_CHANGE.equals(property)) { - updateTitle(); - fViewer.getControl().setRedraw(false); - fViewer.refresh(); - fViewer.getControl().setRedraw(true); - } - - } - - - /** - * Returns the shell to use for opening dialogs. - * Used in this class, and in the actions. - */ - Shell getShell() { - return fViewer.getControl().getShell(); - } - - protected final Display getDisplay() { - return fViewer.getControl().getDisplay(); - } - - /** - * Returns the selection provider. - */ - ISelectionProvider getSelectionProvider() { - return fViewer; - } - - /** - * Answers if the given element is a valid - * input for this part. - * - * @param element the object to test - * @return if the given element is a valid input - */ - abstract protected boolean isValidInput(Object element); - - protected boolean exists(Object element) { - if (element == null) - return false; - if (element instanceof ICElement) - return ((ICElement)element).exists(); - if (element instanceof ITypeInfo) - return ((ITypeInfo)element).exists(); - return false; - } - - protected ICProject findCProject(ICElement element) { - return element.getCProject(); - } - - protected ICProject findCProject(ITypeInfo info) { - IProject project = info.getEnclosingProject(); - if (project != null) { - try { - ICProject[] cProjects = CoreModel.getDefault().getCModel().getCProjects(); - if (cProjects != null) { - for (int i = 0; i < cProjects.length; ++i) { - ICProject cProject = cProjects[i]; - if (cProject.getProject().equals(project)) - return cProject; - } - } - } catch (CModelException e) { - } - } - return null; - } - - protected ISourceRoot findSourceRoot(ICElement element) { - while (element != null) { - if (element instanceof ISourceRoot) - return (ISourceRoot)element; - if (element instanceof ICProject) - return null; - element = element.getParent(); - } - return null; - } - - protected ISourceRoot findSourceRoot(ITypeInfo info) { - ICProject cProject = findCProject(info); - if (cProject != null) { - try { - ISourceRoot[] roots = cProject.getAllSourceRoots(); - if (roots != null) { - for (int i = 0; i < roots.length; ++i) { - ISourceRoot root = roots[i]; - if (!isProjectSourceRoot(root)) { - TypeSearchScope scope = new TypeSearchScope(); - scope.add(root); - if (info.isEnclosed(scope)) - return root; - } - } - } - } catch (CModelException e) { - } - } - return null; - } - - protected boolean isProjectSourceRoot(ISourceRoot root) { - if (root != null) { - IResource resource = root.getResource(); - return (resource instanceof IProject); - } - return false; - } - - /** - * Answers if the given element is a valid - * element for this part. - * - * @param element the object to test - * @return if the given element is a valid element - */ - abstract protected boolean isValidElement(Object element); - - private boolean isInputResetBy(Object newInput, Object input, IWorkbenchPart part) { - if (newInput == null) - return part == fPreviousSelectionProvider; - - if (input instanceof ICElement && newInput instanceof ICElement) - return getTypeComparator().compare(newInput, input) > 0; - - if((newInput instanceof List) && (part instanceof NamespacesView)) - return true; - return false; - } - - private boolean isInputResetBy(IWorkbenchPart part) { - if (!(part instanceof CBrowsingPart)) - return true; - Object thisInput= getViewer().getInput(); - Object partInput= ((CBrowsingPart)part).getViewer().getInput(); - - if(thisInput instanceof Collection) - thisInput= ((Collection)thisInput).iterator().next(); - - if(partInput instanceof Collection) - partInput= ((Collection)partInput).iterator().next(); - - if ((thisInput instanceof ICElement || thisInput instanceof ITypeInfo) - && (partInput instanceof ICElement || partInput instanceof ITypeInfo)) - return getTypeComparator().compare(partInput, thisInput) > 0; - return true; - } - - protected boolean isAncestorOf(Object ancestor, Object element) { - if (element instanceof ICElement && ancestor instanceof ICElement) - return !element.equals(ancestor) && internalIsAncestorOf((ICElement)ancestor, (ICElement)element); - if (element instanceof ITypeInfo) { - if (ancestor instanceof ISourceRoot || ancestor instanceof ICProject || ancestor instanceof ICModel) { - ICProject cProject = ((ICElement)ancestor).getCProject(); - if (cProject != null) { - IProject proj = (((ITypeInfo)element).getEnclosingProject()); - return (proj != null && proj.equals(cProject.getProject())); - } - } - if (ancestor instanceof ITypeInfo) { - return ((ITypeInfo)ancestor).encloses(((ITypeInfo)element)); - } - } - return false; - } - - private boolean internalIsAncestorOf(ICElement ancestor, ICElement element) { - if (element != null) - return element.equals(ancestor) || internalIsAncestorOf(ancestor, element.getParent()); - return false; - } - - private boolean isSearchResultView(IWorkbenchPart part) { -// return SearchUtil.isSearchPlugInActivated() && (part instanceof ISearchResultView); - return false; - } - - protected boolean needsToProcessSelectionChanged(IWorkbenchPart part, ISelection selection) { - if (!fProcessSelectionEvents || part == this || isSearchResultView(part)){ - if (part == this) - fPreviousSelectionProvider= part; - return false; - } - return true; - } - - public void selectionChanged(IWorkbenchPart part, ISelection selection) { - if (!needsToProcessSelectionChanged(part, selection)) - return; - - if (fToggleLinkingAction.isChecked() && (part instanceof ITextEditor)) { - setSelectionFromEditor(part, selection); - return; - } - - if (!(selection instanceof IStructuredSelection)) - return; - - // Set selection - Object selectedElement= getSingleElementFromSelection(selection); - - if (selectedElement != null && (part == null || part.equals(fPreviousSelectionProvider)) && selectedElement.equals(fPreviousSelectedElement)) - return; - - fPreviousSelectedElement= selectedElement; - - Object currentInput= getViewer().getInput(); - if (selectedElement != null && selectedElement.equals(currentInput)) { - Object elementToSelect= findElementToSelect(selectedElement); - if (elementToSelect != null && getTypeComparator().compare(selectedElement, elementToSelect) < 0) - setSelection(new StructuredSelection(elementToSelect), true); - else if (elementToSelect == null && (this instanceof MembersView)) { - setSelection(StructuredSelection.EMPTY, true); - fPreviousSelectedElement= StructuredSelection.EMPTY; - } - fPreviousSelectionProvider= part; - return; - } - - // Clear input if needed - if (part != fPreviousSelectionProvider && selectedElement != null && !selectedElement.equals(currentInput) && isInputResetBy(selectedElement, currentInput, part)) { - if (!isAncestorOf(selectedElement, currentInput)) - setInput(null); - fPreviousSelectionProvider= part; - return; - } else if (selection.isEmpty() && !isInputResetBy(part)) { - fPreviousSelectionProvider= part; - return; - } else if (selectedElement == null && part == fPreviousSelectionProvider) { - setInput(null); - fPreviousSelectionProvider= part; - return; - } - fPreviousSelectionProvider= part; - - // Adjust input and set selection and - adjustInputAndSetSelection(selectedElement); - } - - - void setHasWorkingSetFilter(boolean state) { - fHasWorkingSetFilter= state; - } - - void setHasCustomSetFilter(boolean state) { - fHasCustomFilter= state; - } - - protected Object getInput() { - return fViewer.getInput(); - } - - protected void setInput(Object input) { - setViewerInput(input); - updateTitle(); - } - - boolean isLinkingEnabled() { - return fLinkingEnabled; - } - - private void initLinkingEnabled() { - fLinkingEnabled= PreferenceConstants.getPreferenceStore().getBoolean(getLinkToEditorKey()); - } - - private void setViewerInput(Object input) { - fProcessSelectionEvents= false; - fViewer.setInput(input); - fProcessSelectionEvents= true; - } - - protected void updateTitle() { - setTitleToolTip(getToolTipText(fViewer.getInput())); - } - - /** - * Returns the tool tip text for the given element. - */ - String getToolTipText(Object element) { - String result; - if (!(element instanceof IResource)) { - result= CElementLabels.getTextLabel(element, AppearanceAwareLabelProvider.DEFAULT_TEXTFLAGS); - } else { - IPath path= ((IResource) element).getFullPath(); - if (path.isRoot()) { - result= getConfigurationElement().getAttribute("name"); //$NON-NLS-1$ - } else { - result= path.makeRelative().toString(); - } - } - - if (fWorkingSetFilterActionGroup == null || fWorkingSetFilterActionGroup.getWorkingSet() == null) - return result; - - IWorkingSet ws= fWorkingSetFilterActionGroup.getWorkingSet(); - String wsstr= CBrowsingMessages.getFormattedString("CBrowsingPart.toolTip", new String[] { ws.getName() }); //$NON-NLS-1$ - if (result.length() == 0) - return wsstr; - return CBrowsingMessages.getFormattedString("CBrowsingPart.toolTip2", new String[] { result, ws.getName() }); //$NON-NLS-1$ - } - - public String getTitleToolTip() { - if (fViewer == null) - return super.getTitleToolTip(); - return getToolTipText(fViewer.getInput()); - } - - protected final StructuredViewer getViewer() { - return fViewer; - } - - protected final void setViewer(StructuredViewer viewer){ - fViewer= viewer; - } - - protected abstract LabelProvider createLabelProvider(); - - protected abstract ViewerSorter createViewerSorter(); - - protected IElementComparer createElementComparer() { - return new CBrowsingElementComparer(); - } - - protected ILabelProvider createTitleProvider() { - return new CElementLabelProvider(CElementLabelProvider.SHOW_BASICS | CElementLabelProvider.SHOW_SMALL_ICONS); - } - - protected final ILabelProvider getLabelProvider() { - return fLabelProvider; - } - - protected final ILabelProvider getTitleProvider() { - return fTitleProvider; - } - - /** - * Creates the the viewer of this part. - * - * @param parent the parent for the viewer - */ - protected StructuredViewer createViewer(Composite parent) { - return new ElementTableViewer(parent, SWT.MULTI); - } - - protected int getLabelProviderFlags() { - return CElementLabelProvider.SHOW_BASICS | CElementLabelProvider.SHOW_OVERLAY_ICONS | - CElementLabelProvider.SHOW_SMALL_ICONS | /*CElementLabelProvider.SHOW_VARIABLE |*/ CElementLabelProvider.SHOW_PARAMETERS; - } - - /** - * Adds filters the viewer of this part. - */ - protected void addFilters() { - // default is to have no filters - } - -// /** -// * Creates the the content provider of this part. -// */ - protected abstract IContentProvider createContentProvider(); - - protected void setInitialInput() { - // Use the selection, if any - ISelection selection= getSite().getPage().getSelection(); - Object input= getSingleElementFromSelection(selection); - if (!(input instanceof ICElement) && !(input instanceof ITypeInfo)) { - // Use the input of the page - input= getSite().getPage().getInput(); - if (!(input instanceof ICElement) && input instanceof IAdaptable) - input= ((IAdaptable)input).getAdapter(ICElement.class); - } - setInput(findInputForElement(input)); - } - - protected void setInitialSelection() { - // Use the selection, if any - Object input; - IWorkbenchPage page= getSite().getPage(); - ISelection selection= null; - if (page != null) - selection= page.getSelection(); - if (selection instanceof ITextSelection) { - Object part= PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActivePart(); - if (part instanceof IEditorPart) { - setSelectionFromEditor((IEditorPart)part); - if (fViewer.getSelection() != null) - return; - } - } - - // Use saved selection from memento - if (selection == null || selection.isEmpty()) - selection= restoreSelectionState(fMemento); - - if (selection == null || selection.isEmpty()) { - // Use the input of the page - input= getSite().getPage().getInput(); - if (!(input instanceof ICElement)) { - if (input instanceof IAdaptable) - input= ((IAdaptable)input).getAdapter(ICElement.class); - else - return; - } - selection= new StructuredSelection(input); - } - selectionChanged(null, selection); - } - - protected final void setHelp() { -// CUIHelp.setHelp(fViewer, getHelpContextId()); - } - - /** - * Returns the context ID for the Help system - * - * @return the string used as ID for the Help context - */ - abstract protected String getHelpContextId(); - - /** - * Returns the preference key for the link to editor setting. - * - * @return the string used as key into the preference store - */ - abstract protected String getLinkToEditorKey(); - - /** - * Adds additional listeners to this view. - * This method can be overridden but should - * call super. - */ - protected void hookViewerListeners() { - fViewer.addPostSelectionChangedListener(new ISelectionChangedListener() { - public void selectionChanged(SelectionChangedEvent event) { - if (!fProcessSelectionEvents) - return; - - fPreviousSelectedElement= getSingleElementFromSelection(event.getSelection()); - - IWorkbenchPage page= getSite().getPage(); - if (page == null) - return; - - if (page.equals(CUIPlugin.getActivePage()) && CBrowsingPart.this.equals(page.getActivePart())) { - linkToEditor((IStructuredSelection)event.getSelection()); - } - } - }); - - fViewer.addOpenListener(new IOpenListener() { - public void open(OpenEvent event) { - ISelection selection = event.getSelection(); - if (selection != null) { - Object element = getSingleElementFromSelection(selection); - if (element instanceof ICElement) { - openInEditor((ICElement)element); - } else if (element instanceof ITypeInfo) { - openTypeInEditor((ITypeInfo)element); - } - restoreSelection(); - } -// IAction open= fOpenEditorGroup.getOpenAction(); -// if (open.isEnabled()) { -// open.run(); -// restoreSelection(); -// } - } - }); - } - - protected void openTypeInEditor(ITypeInfo info) { - if (!info.exists()) - return; - - if (info == info.getCache().getGlobalNamespace()) { - return; // nothing to open - } - ITypeReference location = info.getResolvedReference(); - if (location == null) { - final ITypeInfo[] typesToResolve = new ITypeInfo[] { info }; - IRunnableWithProgress runnable = new IRunnableWithProgress() { - public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { - AllTypesCache.resolveTypeLocation(typesToResolve[0], monitor); - if (monitor.isCanceled()) { - throw new InterruptedException(); - } - } - }; - - IProgressService service = PlatformUI.getWorkbench().getProgressService(); - try { - service.busyCursorWhile(runnable); - } catch (InvocationTargetException e) { - String title = OpenTypeMessages.getString("OpenTypeAction.exception.title"); //$NON-NLS-1$ - String message = OpenTypeMessages.getString("OpenTypeAction.exception.message"); //$NON-NLS-1$ - ExceptionHandler.handle(e, title, message); - return; - } catch (InterruptedException e) { - // cancelled by user - return; - } - - location = info.getResolvedReference(); - } - - if (location == null) { - // could not resolve location - String title = OpenTypeMessages.getString("OpenTypeAction.errorTitle"); //$NON-NLS-1$ - String message = OpenTypeMessages.getFormattedString("OpenTypeAction.errorTypeNotFound", info.getQualifiedTypeName().toString()); //$NON-NLS-1$ - MessageDialog.openError(getShell(), title, message); - } else if (!openInEditor(location)) { - // error opening editor - String title = OpenTypeMessages.getString("OpenTypeAction.errorTitle"); //$NON-NLS-1$ - String message = OpenTypeMessages.getFormattedString("OpenTypeAction.errorOpenEditor", location.getPath().toString()); //$NON-NLS-1$ - MessageDialog.openError(getShell(), title, message); - } - } - - private boolean openInEditor(ITypeReference location) { - ITranslationUnit unit = location.getTranslationUnit(); - IEditorPart editorPart = null; - - try { - if (unit != null) - editorPart = EditorUtility.openInEditor(unit); - if (editorPart == null) { - // open as external file - IPath path = location.getLocation(); - if (path != null) { - IStorage storage = new FileStorage(path); - editorPart = EditorUtility.openInEditor(storage); - } - } - - // highlight the type in the editor - if (editorPart != null && editorPart instanceof ITextEditor) { - ITextEditor editor = (ITextEditor) editorPart; - if( location.isLineNumber() ) - { - IDocument document= editor.getDocumentProvider().getDocument(editor.getEditorInput()); - try - { - int startOffset = document.getLineOffset(location.getOffset()-1); - int length=document.getLineLength(location.getOffset()-1); - editor.selectAndReveal(startOffset, length); - return true; - } - catch( BadLocationException ble ) - { - return false; - } - } - editor.selectAndReveal(location.getOffset(), location.getLength()); - return true; - } - } catch (CModelException ex) { - ex.printStackTrace(); - return false; - } catch (PartInitException ex) { - ex.printStackTrace(); - return false; - } - - return false; - } - - protected boolean openInEditor(ICElement cElement) { - IEditorPart editorPart = null; - - try { - if (cElement != null) - editorPart = EditorUtility.openInEditor(cElement); - if (editorPart == null) - return false; - } catch (CModelException ex) { - ex.printStackTrace(); - return false; - } catch (PartInitException ex) { - ex.printStackTrace(); - return false; - } - - // highlight the type in the editor - if (cElement != null && editorPart instanceof CEditor) { - CEditor editor = (CEditor) editorPart; - editor.setSelection(cElement); - return true; - } - return false; - } - - void restoreSelection() { - // Default is to do nothing - } - - void adjustInputAndPreserveSelection(Object o) { - Object element = getOriginalElement(o); - if (!(element instanceof ICElement) && !(element instanceof ITypeInfo)) { - setSelection(StructuredSelection.EMPTY, true); - return; - } - - Object elementToSelect= getSuitableElement(findElementToSelect(element)); - Object newInput= findInputForElement(element); - Object oldInput= null; - Object viewerInput = getInput(); - if (viewerInput instanceof ICElement || viewerInput instanceof ITypeInfo) - oldInput = viewerInput; - - if (elementToSelect == null && !isValidInput(newInput) && (newInput == null && !isAncestorOf(element, oldInput))) - // Clear input - setInput(null); - else { // if (mustSetNewInput(elementToSelect, oldInput, newInput)) { - // Adjust input to selection - setInput(newInput); - // Recompute suitable element since it depends on the viewer's input - elementToSelect= getSuitableElement(elementToSelect); - } - - if (elementToSelect != null /*&& elementToSelect.exists()*/) - setSelection(new StructuredSelection(elementToSelect), true); - else - setSelection(StructuredSelection.EMPTY, true); - } - - void adjustInputAndSetSelection(Object o) { - Object element = getOriginalElement(o); - if (!(element instanceof ICElement) && !(element instanceof ITypeInfo)) { - setSelection(StructuredSelection.EMPTY, true); - return; - } - - Object elementToSelect= getSuitableElement(findElementToSelect(element)); - Object newInput= findInputForElement(element); - Object oldInput= null; - Object viewerInput = getInput(); - if (viewerInput instanceof ICElement || viewerInput instanceof ITypeInfo) - oldInput = viewerInput; - - if (elementToSelect == null && !isValidInput(newInput) && (newInput == null && !isAncestorOf(element, oldInput))) - // Clear input - setInput(null); - else if (mustSetNewInput(elementToSelect, oldInput, newInput)) { - // Adjust input to selection - setInput(newInput); - // Recompute suitable element since it depends on the viewer's input - elementToSelect= getSuitableElement(elementToSelect); - } - - if (elementToSelect != null /*&& elementToSelect.exists()*/) - setSelection(new StructuredSelection(elementToSelect), true); - else - setSelection(StructuredSelection.EMPTY, true); - } - - protected Object getOriginalElement(Object obj) { - if (obj instanceof ICElement) { - ICElement element = (ICElement)obj; - // Below is for children of TranslationUnits but we have to make sure - // we handle the case that the child comes from the a workingCopy in that - // case it should be equal as the original element. - ITranslationUnit t = (ITranslationUnit)element.getAncestor(ICElement.C_UNIT); - if (t != null && t.isWorkingCopy()) { - ICElement original = ((IWorkingCopy)t).getOriginal(element); - if (original != null) - return original; - } - } - return obj; - } - - - /** - * Compute if a new input must be set. - * - * @return true if the input has to be set - * @since 3.0 - */ - private boolean mustSetNewInput(Object elementToSelect, Object oldInput, Object newInput) { - if (newInput == null || oldInput == null || !newInput.equals(oldInput)) { - return true; - } - if (elementToSelect == null) { - return false; - } -// return !findInputForElement(elementToSelect).equals(newInput); - return false; -// return !(inputContainsElement(newInput, elementToSelect)); -// return (newInput == null || !newInput.equals(oldInput)) -// && (elementToSelect == null -// || oldInput == null); -// return (newInput == null || !newInput.equals(oldInput)) -// && (elementToSelect == null -// || oldInput == null -// || (!((elementToSelect instanceof IDeclaration) -// && (elementToSelect.getParent().equals(oldInput.getParent())) -// && (!isAncestorOf(getViewPartInput(), elementToSelect))))); - } - - /** - * Finds the closest C element which can be used as input for - * this part and has the given C element as child - * - * @param element the C element for which to search the closest input - * @return the closest C element used as input for this part - */ - abstract protected Object findInputForElement(Object element); - - /** - * Finds the element which has to be selected in this part. - * - * @param element the C element which has the focus - */ - abstract protected Object findElementToSelect(Object element); - - /** - * Converts the given C element to one which is suitable for this - * view. It takes into account wether the view shows working copies or not. - * - * @param element the C element to be converted - * @return an element suitable for this view - */ - Object getSuitableElement(Object obj) { - if (!(obj instanceof ICElement) && !(obj instanceof ITypeInfo)) - return null; - if (fTypeComparator.compare(obj, ICElement.C_UNIT) > 0) - return obj; - return obj; -// if (element.getElementType() == IJavaElement.CLASS_FILE) -// return element; -// if (isInputAWorkingCopy()) { -// IJavaElement wc= getWorkingCopy(element); -// if (wc != null) -// element= wc; -// return element; -// } -// else { -// return element.getPrimaryElement(); -// } - } - - protected ICElement getTypeForTU(ITranslationUnit tu) { - tu = (ITranslationUnit) getSuitableElement(tu); - -// // Use primary type if possible -// IType primaryType= cu.findPrimaryType(); -// if (primaryType != null) -// return primaryType; - - // Use first top-level type - try { - ICElement[] types = TypeUtil.getTypes(tu); - if (types.length > 0) - return types[0]; - return null; - } catch (CModelException ex) { - return null; - } - } - - protected final Object getSingleElementFromSelection(ISelection selection) { - if (!(selection instanceof StructuredSelection) || selection.isEmpty()) - return null; - - Iterator iter= ((StructuredSelection)selection).iterator(); - Object firstElement= iter.next(); - if (!(firstElement instanceof ICElement) && !(firstElement instanceof ITypeInfo)) { -// if (SearchUtil.isISearchResultViewEntry(firstElement)) { -// ICElement je= SearchUtil.getJavaElement(firstElement); -// if (je != null) -// return je; -// firstElement= SearchUtil.getResource(firstElement); -// } - if (firstElement instanceof IAdaptable) { - ICElement je= (ICElement)((IAdaptable)firstElement).getAdapter(ICElement.class); - if (je == null && firstElement instanceof IFile) { - IContainer parent= ((IFile)firstElement).getParent(); - if (parent != null) - return (ICElement)parent.getAdapter(ICElement.class); - return null; - } - return je; - } - return firstElement; - } - Object currentInput= getViewer().getInput(); - if (currentInput == null || !currentInput.equals(findInputForElement(firstElement))) { - if (iter.hasNext()) { - // multi selection and view is empty - return null; - } - // ok: single selection and view is empty - return firstElement; - } - - // be nice to multi selection - while (iter.hasNext()) { - Object element= iter.next(); - if (!(element instanceof ICElement) && !(element instanceof ITypeInfo)) -// if (!(element instanceof ICElement)) - return null; - if (!currentInput.equals(findInputForElement(element))) - return null; - } - return firstElement; - } - - /** - * Gets the typeComparator. - * @return Returns a JavaElementTypeComparator - */ - protected Comparator getTypeComparator() { - return fTypeComparator; - } - - /** - * Links to editor (if option enabled) - */ - void linkToEditor(IStructuredSelection selection) { - Object obj= selection.getFirstElement(); - - if (selection.size() == 1) { - IEditorPart part= EditorUtility.isOpenInEditor(obj); - if (part != null) { - IWorkbenchPage page= getSite().getPage(); - page.bringToTop(part); - if (obj instanceof ICElement) - EditorUtility.revealInEditor(part, (ICElement) obj); - } - } - } - - void setSelectionFromEditor(IWorkbenchPartReference ref) { - IWorkbenchPart part= ref.getPart(false); - setSelectionFromEditor(part); - } - - void setSelectionFromEditor(IWorkbenchPart part) { - if (!linkBrowsingViewSelectionToEditor()) - return; - - if (part == null) - return; - IWorkbenchPartSite site= part.getSite(); - if (site == null) - return; - ISelectionProvider provider= site.getSelectionProvider(); - if (provider != null) - setSelectionFromEditor(part, provider.getSelection()); - } - - private void setSelectionFromEditor(IWorkbenchPart part, ISelection selection) { - if (part instanceof IEditorPart) { - ICElement element= null; - if (selection instanceof IStructuredSelection) { - Object obj= getSingleElementFromSelection(selection); - if (obj instanceof ICElement) - element= (ICElement)obj; - } - IEditorInput ei= ((IEditorPart)part).getEditorInput(); - if (selection instanceof ITextSelection) { - int offset= ((ITextSelection)selection).getOffset(); - element= getElementAt(ei, offset); - } - if (element != null) { - adjustInputAndSetSelection(element); - return; - } - if (ei instanceof IFileEditorInput) { - IFile file= ((IFileEditorInput)ei).getFile(); - ICElement ce= (ICElement)file.getAdapter(ICElement.class); - if (ce == null) { - IContainer container= ((IFileEditorInput)ei).getFile().getParent(); - if (container != null) - ce= (ICElement)container.getAdapter(ICElement.class); - } - if (ce == null) { - setSelection(null, false); - return; - } - adjustInputAndSetSelection(ce); -// } else if (ei instanceof IClassFileEditorInput) { -// IClassFile cf= ((IClassFileEditorInput)ei).getClassFile(); -// adjustInputAndSetSelection(cf); - } - } - } - - /** - * Returns the element contained in the EditorInput - */ - Object getElementOfInput(IEditorInput input) { -// if (input instanceof IClassFileEditorInput) -// return ((IClassFileEditorInput)input).getClassFile(); -// else - if (input instanceof IFileEditorInput) - return ((IFileEditorInput)input).getFile(); -// else if (input instanceof JarEntryEditorInput) -// return ((JarEntryEditorInput)input).getStorage(); - return null; - } - - protected void setSelection(ISelection selection, boolean reveal) { - if (selection != null && selection.equals(fViewer.getSelection())) - return; - fProcessSelectionEvents= false; - fViewer.setSelection(selection, reveal); - fProcessSelectionEvents= true; - } - - /** - * Tries to find the given element in a workingcopy. - */ - protected static ICElement getWorkingCopy(ICElement input) { - // MA: with new working copy story original == working copy - return input; - } - -// -// boolean isInputAWorkingCopy() { -// return ((BaseCElementContentProvider)getViewer().getContentProvider()).getProvideWorkingCopy(); -// } - - /** - * @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor#getElementAt(int) - */ - protected ICElement getElementAt(IEditorInput input, int offset) { -// if (input instanceof IClassFileEditorInput) { -// try { -// return ((IClassFileEditorInput)input).getClassFile().getElementAt(offset); -// } catch (CModelException ex) { -// return null; -// } -// } - - IWorkingCopyManager manager= CUIPlugin.getDefault().getWorkingCopyManager(); - ITranslationUnit unit= manager.getWorkingCopy(input); - if (unit != null) - try { - if (unit.isConsistent()) { - return unit.getElementAtOffset(offset); - } - /* - * XXX: We should set the selection later when the - * CU is reconciled. - * see https://bugs.eclipse.org/bugs/show_bug.cgi?id=51290 - */ - } catch (CModelException ex) { - // fall through - } - return null; - } - -/* protected ICElement getTypeForCU(ITranslationUnit cu) { - cu= (ITranslationUnit)getSuitableCElement(cu); - -// // Use primary type if possible -// ICElement primaryType= cu.findPrimaryType(); -// if (primaryType != null) -// return primaryType; - - // Use first top-level type - try { - final ICElement[] fTypes = new ICElement[]{ null }; - cu.accept(new ICElementVisitor() { - public boolean visit(ICElement element) throws CoreException { - // TODO Auto-generated method stub - switch(element.getElementType()) { - case ICElement.C_NAMESPACE: - case ICElement.C_TEMPLATE_CLASS: - case ICElement.C_CLASS: - case ICElement.C_STRUCT: - case ICElement.C_UNION: - case ICElement.C_ENUMERATION: - case ICElement.C_TYPEDEF: - fTypes[0] = element; - return false; - } - return true; - } - }); -// ICElement[] types= cu.getTypes(); -// if (types.length > 0) -// return types[0]; -// else -// return null; - return fTypes[0]; - } catch (CoreException ex) { - return null; - } - } -*/ - void setProcessSelectionEvents(boolean state) { - fProcessSelectionEvents= state; - } - - /* (non-Javadoc) - * @see org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider#getViewPartInput() - */ - public Object getViewPartInput() { - if (fViewer != null) { - return fViewer.getInput(); - } - return null; - } - -// protected void setActionGroups(CompositeActionGroup actionGroups) { -// fActionGroups= actionGroups; -// } -// -// protected void setBuildActionGroup(BuildActionGroup actionGroup) { -// fBuildActionGroup= actionGroup; -// } -// -// protected void setCCPActionGroup(CCPActionGroup actionGroup) { -// fCCPActionGroup= actionGroup; -// } -// -// protected void setCustomFiltersActionGroup(CustomFiltersActionGroup customFiltersActionGroup) { -// fCustomFiltersActionGroup= customFiltersActionGroup; -// } - - protected boolean hasCustomFilter() { - return fHasCustomFilter; - } - - protected boolean hasWorkingSetFilter() { - return fHasWorkingSetFilter; - } - -// protected void setOpenEditorGroup(OpenEditorActionGroup openEditorGroup) { -// fOpenEditorGroup= openEditorGroup; -// } -// -// protected OpenEditorActionGroup getOpenEditorGroup() { -// return fOpenEditorGroup; -// } -// -// protected BuildActionGroup getBuildActionGroup() { -// return fBuildActionGroup; -// } -// -// protected CCPActionGroup getCCPActionGroup() { -// return fCCPActionGroup; -// } - - private boolean linkBrowsingViewSelectionToEditor() { - return isLinkingEnabled(); - } - - public void setLinkingEnabled(boolean enabled) { - fLinkingEnabled= enabled; - PreferenceConstants.getPreferenceStore().setValue(getLinkToEditorKey(), enabled); - if (enabled) { - IEditorPart editor = getSite().getPage().getActiveEditor(); - if (editor != null) { - setSelectionFromEditor(editor); - } - } - } - -} diff --git a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/cbrowsing/CBrowsingPerspectiveFactory.java b/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/cbrowsing/CBrowsingPerspectiveFactory.java deleted file mode 100644 index 7fd72a75366..00000000000 --- a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/cbrowsing/CBrowsingPerspectiveFactory.java +++ /dev/null @@ -1,234 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.browser.cbrowsing; - -import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.cdt.internal.ui.wizards.CWizardRegistry; -import org.eclipse.cdt.ui.CUIPlugin; -import org.eclipse.cdt.ui.PreferenceConstants; -import org.eclipse.core.runtime.IAdaptable; -import org.eclipse.search.ui.NewSearchUI; -import org.eclipse.ui.IFolderLayout; -import org.eclipse.ui.IPageLayout; -import org.eclipse.ui.IPerspectiveFactory; -import org.eclipse.ui.IPlaceholderFolderLayout; -import org.eclipse.ui.console.IConsoleConstants; - -public class CBrowsingPerspectiveFactory implements IPerspectiveFactory { - - /* - * XXX: This is a workaround for: http://dev.eclipse.org/bugs/show_bug.cgi?id=13070 - */ - static ICElement fgCElementFromAction; - - /** - * Constructs a new Default layout engine. - */ - public CBrowsingPerspectiveFactory() { - super(); - } - - /** - * @see IPerspectiveFactory#createInitialLayout - */ - public void createCViewInitialLayout(IPageLayout layout) { - String editorArea = layout.getEditorArea(); - - IFolderLayout folder1= layout.createFolder("topLeft", IPageLayout.LEFT, (float)0.25, editorArea); //$NON-NLS-1$ - folder1.addView(CUIPlugin.CVIEW_ID); - folder1.addView(IPageLayout.ID_RES_NAV); - folder1.addPlaceholder(IPageLayout.ID_BOOKMARKS); - - IFolderLayout folder2= layout.createFolder("bottom", IPageLayout.BOTTOM, (float)0.75, editorArea); //$NON-NLS-1$ - folder2.addView(IPageLayout.ID_PROBLEM_VIEW); - folder2.addView(IConsoleConstants.ID_CONSOLE_VIEW); - folder2.addView(IPageLayout.ID_PROP_SHEET); - - IFolderLayout folder3= layout.createFolder("topRight", IPageLayout.RIGHT,(float)0.75, editorArea); //$NON-NLS-1$ - folder3.addView(IPageLayout.ID_OUTLINE); - - layout.addActionSet(CUIPlugin.SEARCH_ACTION_SET_ID); - layout.addActionSet(CUIPlugin.ID_CELEMENT_CREATION_ACTION_SET); - - // views - build console - layout.addShowViewShortcut(IConsoleConstants.ID_CONSOLE_VIEW); - - // views - searching - layout.addShowViewShortcut(NewSearchUI.SEARCH_VIEW_ID); - - // views - standard workbench - layout.addShowViewShortcut(IPageLayout.ID_OUTLINE); - layout.addShowViewShortcut(IPageLayout.ID_PROBLEM_VIEW); - layout.addShowViewShortcut(CUIPlugin.CVIEW_ID); - layout.addShowViewShortcut(IPageLayout.ID_RES_NAV); - layout.addShowViewShortcut(IPageLayout.ID_PROP_SHEET); - - // link - things we should do - layout.addShowInPart(CUIPlugin.CVIEW_ID); - layout.addShowInPart(IPageLayout.ID_RES_NAV); - - addCWizardShortcuts(layout); - } - - public void createInitialLayout(IPageLayout layout) { - if (stackBrowsingViewsVertically()) - createVerticalLayout(layout); - else - createHorizontalLayout(layout); - - // action sets - layout.addActionSet(CUIPlugin.SEARCH_ACTION_SET_ID); -// layout.addActionSet(IDebugUIConstants.LAUNCH_ACTION_SET); -// layout.addActionSet(JavaUI.ID_ACTION_SET); - layout.addActionSet(CUIPlugin.ID_CELEMENT_CREATION_ACTION_SET); - layout.addActionSet(IPageLayout.ID_NAVIGATE_ACTION_SET); - - // views - java - layout.addShowViewShortcut(CUIPlugin.ID_TYPE_HIERARCHY); - layout.addShowViewShortcut(CUIPlugin.CVIEW_ID); - layout.addShowViewShortcut(CUIPlugin.ID_PROJECTS_VIEW); - layout.addShowViewShortcut(CUIPlugin.ID_NAMESPACES_VIEW); - layout.addShowViewShortcut(CUIPlugin.ID_TYPES_VIEW); - layout.addShowViewShortcut(CUIPlugin.ID_MEMBERS_VIEW); -// layout.addShowViewShortcut(CUIPlugin.ID_SOURCE_VIEW); -// layout.addShowViewShortcut(CUIPlugin.ID_JAVADOC_VIEW); - - // views - search - layout.addShowViewShortcut(NewSearchUI.SEARCH_VIEW_ID); - - // views - debugging - layout.addShowViewShortcut(IConsoleConstants.ID_CONSOLE_VIEW); - - // views - standard workbench - layout.addShowViewShortcut(IPageLayout.ID_OUTLINE); - layout.addShowViewShortcut(IPageLayout.ID_PROBLEM_VIEW); - layout.addShowViewShortcut(IPageLayout.ID_RES_NAV); - - addCWizardShortcuts(layout); - } - - private void addCWizardShortcuts(IPageLayout layout) { - // new actions - C project creation wizard - String[] wizIDs = CWizardRegistry.getProjectWizardIDs(); - for (int i = 0; i < wizIDs.length; ++i) { - layout.addNewWizardShortcut(wizIDs[i]); - } - // new actions - C folder creation wizard - wizIDs = CWizardRegistry.getFolderWizardIDs(); - for (int i = 0; i < wizIDs.length; ++i) { - layout.addNewWizardShortcut(wizIDs[i]); - } - // new actions - C file creation wizard - wizIDs = CWizardRegistry.getFileWizardIDs(); - for (int i = 0; i < wizIDs.length; ++i) { - layout.addNewWizardShortcut(wizIDs[i]); - } - // new actions - C type creation wizard - wizIDs = CWizardRegistry.getTypeWizardIDs(); - for (int i = 0; i < wizIDs.length; ++i) { - layout.addNewWizardShortcut(wizIDs[i]); - } - } - - private void createVerticalLayout(IPageLayout layout) { - String relativePartId= IPageLayout.ID_EDITOR_AREA; - int relativePos= IPageLayout.LEFT; - - IPlaceholderFolderLayout placeHolderLeft= layout.createPlaceholderFolder("left", IPageLayout.LEFT, (float)0.25, IPageLayout.ID_EDITOR_AREA); //$NON-NLS-1$ - placeHolderLeft.addPlaceholder(CUIPlugin.ID_TYPE_HIERARCHY); - placeHolderLeft.addPlaceholder(IPageLayout.ID_OUTLINE); - placeHolderLeft.addPlaceholder(CUIPlugin.CVIEW_ID); - placeHolderLeft.addPlaceholder(IPageLayout.ID_RES_NAV); - - if (shouldShowProjectsView()) { - layout.addView(CUIPlugin.ID_PROJECTS_VIEW, IPageLayout.LEFT, (float)0.25, IPageLayout.ID_EDITOR_AREA); - relativePartId= CUIPlugin.ID_PROJECTS_VIEW; - relativePos= IPageLayout.BOTTOM; - } - if (shouldShowNamespacesView()) { - layout.addView(CUIPlugin.ID_NAMESPACES_VIEW, relativePos, (float)0.25, relativePartId); - relativePartId= CUIPlugin.ID_NAMESPACES_VIEW; - relativePos= IPageLayout.BOTTOM; - } - layout.addView(CUIPlugin.ID_TYPES_VIEW, relativePos, (float)0.33, relativePartId); - layout.addView(CUIPlugin.ID_MEMBERS_VIEW, IPageLayout.BOTTOM, (float)0.50, CUIPlugin.ID_TYPES_VIEW); - - IPlaceholderFolderLayout placeHolderBottom= layout.createPlaceholderFolder("bottom", IPageLayout.BOTTOM, (float)0.75, IPageLayout.ID_EDITOR_AREA); //$NON-NLS-1$ - placeHolderBottom.addPlaceholder(IPageLayout.ID_PROBLEM_VIEW); - placeHolderBottom.addPlaceholder(NewSearchUI.SEARCH_VIEW_ID); - placeHolderBottom.addPlaceholder(IConsoleConstants.ID_CONSOLE_VIEW); - placeHolderBottom.addPlaceholder(IPageLayout.ID_BOOKMARKS); -// placeHolderBottom.addPlaceholder(JavaUI.ID_SOURCE_VIEW); -// placeHolderBottom.addPlaceholder(JavaUI.ID_JAVADOC_VIEW); - } - - private void createHorizontalLayout(IPageLayout layout) { - String relativePartId= IPageLayout.ID_EDITOR_AREA; - int relativePos= IPageLayout.TOP; - - if (shouldShowProjectsView()) { - layout.addView(CUIPlugin.ID_PROJECTS_VIEW, IPageLayout.TOP, (float)0.25, IPageLayout.ID_EDITOR_AREA); - relativePartId= CUIPlugin.ID_PROJECTS_VIEW; - relativePos= IPageLayout.RIGHT; - } - if (shouldShowNamespacesView()) { - layout.addView(CUIPlugin.ID_NAMESPACES_VIEW, relativePos, (float)0.25, relativePartId); - relativePartId= CUIPlugin.ID_NAMESPACES_VIEW; - relativePos= IPageLayout.RIGHT; - } - layout.addView(CUIPlugin.ID_TYPES_VIEW, relativePos, (float)0.33, relativePartId); - layout.addView(CUIPlugin.ID_MEMBERS_VIEW, IPageLayout.RIGHT, (float)0.50, CUIPlugin.ID_TYPES_VIEW); - - IPlaceholderFolderLayout placeHolderLeft= layout.createPlaceholderFolder("left", IPageLayout.LEFT, (float)0.25, IPageLayout.ID_EDITOR_AREA); //$NON-NLS-1$ - placeHolderLeft.addPlaceholder(CUIPlugin.ID_TYPE_HIERARCHY); - placeHolderLeft.addPlaceholder(IPageLayout.ID_OUTLINE); - placeHolderLeft.addPlaceholder(CUIPlugin.CVIEW_ID); - placeHolderLeft.addPlaceholder(IPageLayout.ID_RES_NAV); - - IPlaceholderFolderLayout placeHolderBottom= layout.createPlaceholderFolder("bottom", IPageLayout.BOTTOM, (float)0.75, IPageLayout.ID_EDITOR_AREA); //$NON-NLS-1$ - placeHolderBottom.addPlaceholder(IPageLayout.ID_PROBLEM_VIEW); - placeHolderBottom.addPlaceholder(NewSearchUI.SEARCH_VIEW_ID); - placeHolderBottom.addPlaceholder(IConsoleConstants.ID_CONSOLE_VIEW); - placeHolderBottom.addPlaceholder(IPageLayout.ID_BOOKMARKS); -// placeHolderBottom.addPlaceholder(JavaUI.ID_SOURCE_VIEW); -// placeHolderBottom.addPlaceholder(JavaUI.ID_JAVADOC_VIEW); - } - - private boolean shouldShowProjectsView() { - return true; -// RETURN FGCELEMENTFROMACTION == NULL || FGCELEMENTFROMACTION.GETELEMENTTYPE() == ICELEMENT.C_MODEL; - } - - private boolean shouldShowNamespacesView() { - return true; -// if (fgCElementFromAction == null) -// return true; -// int type= fgCElementFromAction.getElementType(); -// return type == ICElement.C_MODEL || type == ICElement.C_PROJECT; -//// return type == ICElement.C_MODEL || type == ICElement.C_PROJECT || type == ICElement.PACKAGE_FRAGMENT_ROOT; - } - - private boolean stackBrowsingViewsVertically() { - return PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.BROWSING_STACK_VERTICALLY); - } - - /* - * XXX: This is a workaround for: http://dev.eclipse.org/bugs/show_bug.cgi?id=13070 - */ - static void setInputFromAction(IAdaptable input) { - if (input instanceof ICElement) - fgCElementFromAction= (ICElement)input; - else - fgCElementFromAction= null; - } -} - - diff --git a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/cbrowsing/CBrowsingViewerSorter.java b/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/cbrowsing/CBrowsingViewerSorter.java deleted file mode 100644 index 9728e2ff211..00000000000 --- a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/cbrowsing/CBrowsingViewerSorter.java +++ /dev/null @@ -1,20 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 QNX Software Systems and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * QNX Software Systems - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.browser.cbrowsing; - -import org.eclipse.cdt.ui.CElementSorter; - -public class CBrowsingViewerSorter extends CElementSorter { - - public CBrowsingViewerSorter() { - super(); - } -} diff --git a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/cbrowsing/ElementTableViewer.java b/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/cbrowsing/ElementTableViewer.java deleted file mode 100644 index a1c8d0dcfc3..00000000000 --- a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/cbrowsing/ElementTableViewer.java +++ /dev/null @@ -1,66 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005 QNX Software Systems and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * QNX Software Systems - initial API and implementation - *******************************************************************************/ -/* - * Created on Sep 1, 2004 - * - * TODO To change the template for this generated file go to - * Window - Preferences - Java - Code Style - Code Templates - */ -package org.eclipse.cdt.internal.ui.browser.cbrowsing; - -import org.eclipse.cdt.internal.ui.util.ProblemTableViewer; -import org.eclipse.jface.viewers.ISelection; -import org.eclipse.jface.viewers.SelectionChangedEvent; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Table; - -/** - * @author CWiebe - * - * TODO To change the template for this generated type comment go to - * Window - Preferences - Java - Code Style - Code Templates - */ -public class ElementTableViewer extends ProblemTableViewer { - - /** - * @param parent - */ - public ElementTableViewer(Composite parent) { - super(parent); - // TODO Auto-generated constructor stub - } - - /** - * @param parent - * @param style - */ - public ElementTableViewer(Composite parent, int style) { - super(parent, style); - // TODO Auto-generated constructor stub - } - - /** - * @param table - */ - public ElementTableViewer(Table table) { - super(table); - // TODO Auto-generated constructor stub - } - - protected void handleInvalidSelection(ISelection invalidSelection, - ISelection newSelection) { - updateSelection(newSelection); - SelectionChangedEvent event = new SelectionChangedEvent(this, - newSelection); - firePostSelectionChanged(event); - } - -} diff --git a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/cbrowsing/ElementTreeViewer.java b/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/cbrowsing/ElementTreeViewer.java deleted file mode 100644 index 1dc814521e7..00000000000 --- a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/cbrowsing/ElementTreeViewer.java +++ /dev/null @@ -1,56 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005 QNX Software Systems and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * QNX Software Systems - initial API and implementation - *******************************************************************************/ -/* - * Created on Sep 1, 2004 - * - * TODO To change the template for this generated file go to - * Window - Preferences - Java - Code Style - Code Templates - */ -package org.eclipse.cdt.internal.ui.browser.cbrowsing; - -import org.eclipse.cdt.internal.ui.util.ProblemTreeViewer; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Tree; - -/** - * @author CWiebe - * - * TODO To change the template for this generated type comment go to - * Window - Preferences - Java - Code Style - Code Templates - */ -public class ElementTreeViewer extends ProblemTreeViewer { - - /** - * @param parent - */ - public ElementTreeViewer(Composite parent) { - super(parent); - // TODO Auto-generated constructor stub - } - - /** - * @param parent - * @param style - */ - public ElementTreeViewer(Composite parent, int style) { - super(parent, style); - // TODO Auto-generated constructor stub - } - - /** - * @param tree - */ - public ElementTreeViewer(Tree tree) { - super(tree); - // TODO Auto-generated constructor stub - } - -} diff --git a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/cbrowsing/LexicalSortingAction.java b/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/cbrowsing/LexicalSortingAction.java deleted file mode 100644 index d8b00b25228..00000000000 --- a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/cbrowsing/LexicalSortingAction.java +++ /dev/null @@ -1,61 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.browser.cbrowsing; - -import org.eclipse.cdt.internal.ui.CPluginImages; -import org.eclipse.cdt.internal.ui.ICHelpContextIds; -import org.eclipse.cdt.ui.CUIPlugin; -import org.eclipse.jface.action.Action; -import org.eclipse.jface.viewers.StructuredViewer; -import org.eclipse.swt.custom.BusyIndicator; -import org.eclipse.ui.help.WorkbenchHelp; - -/* - * XXX: This class should become part of the MemberFilterActionGroup - * which should be renamed to MemberActionsGroup - */ -public class LexicalSortingAction extends Action { - CBrowsingViewerSorter fSorter= new CBrowsingViewerSorter(); - StructuredViewer fViewer; - private String fPreferenceKey; - - public LexicalSortingAction(StructuredViewer viewer, String id) { - super(); - fViewer= viewer; - fPreferenceKey= "LexicalSortingAction." + id + ".isChecked"; //$NON-NLS-1$ //$NON-NLS-2$ - setText(CBrowsingMessages.getString("LexicalSortingAction.label")); //$NON-NLS-1$ - CPluginImages.setImageDescriptors(this, CPluginImages.T_LCL, CPluginImages.IMG_ALPHA_SORTING); //$NON-NLS-1$ //$NON-NLS-2$ - setToolTipText(CBrowsingMessages.getString("LexicalSortingAction.tooltip")); //$NON-NLS-1$ - setDescription(CBrowsingMessages.getString("LexicalSortingAction.description")); //$NON-NLS-1$ - boolean checked= CUIPlugin.getDefault().getPreferenceStore().getBoolean(fPreferenceKey); //$NON-NLS-1$ - valueChanged(checked, false); - WorkbenchHelp.setHelp(this, ICHelpContextIds.LEXICAL_SORTING_BROWSING_ACTION); - } - - public void run() { - valueChanged(isChecked(), true); - } - - private void valueChanged(final boolean on, boolean store) { - setChecked(on); - BusyIndicator.showWhile(fViewer.getControl().getDisplay(), new Runnable() { - public void run() { - if (on) - fViewer.setSorter(fSorter); - else - fViewer.setSorter(null); - } - }); - - if (store) - CUIPlugin.getDefault().getPreferenceStore().setValue(fPreferenceKey, on); - } -} diff --git a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/cbrowsing/MembersView.java b/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/cbrowsing/MembersView.java deleted file mode 100644 index 733d61bea49..00000000000 --- a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/cbrowsing/MembersView.java +++ /dev/null @@ -1,266 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.browser.cbrowsing; - -import org.eclipse.cdt.core.browser.AllTypesCache; -import org.eclipse.cdt.core.browser.ITypeInfo; -import org.eclipse.cdt.core.browser.TypeUtil; -import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.cdt.core.model.ICModel; -import org.eclipse.cdt.core.model.ICProject; -import org.eclipse.cdt.core.model.INamespace; -import org.eclipse.cdt.core.model.ISourceRoot; -import org.eclipse.cdt.core.model.ITranslationUnit; -import org.eclipse.cdt.internal.ui.ICHelpContextIds; -import org.eclipse.cdt.ui.CUIPlugin; -import org.eclipse.cdt.ui.PreferenceConstants; -import org.eclipse.jface.action.IToolBarManager; -import org.eclipse.jface.util.IPropertyChangeListener; -import org.eclipse.jface.util.PropertyChangeEvent; -import org.eclipse.jface.viewers.DoubleClickEvent; -import org.eclipse.jface.viewers.IContentProvider; -import org.eclipse.jface.viewers.IDoubleClickListener; -import org.eclipse.jface.viewers.IStructuredSelection; -import org.eclipse.jface.viewers.LabelProvider; -import org.eclipse.jface.viewers.StructuredViewer; -import org.eclipse.jface.viewers.TreeViewer; -import org.eclipse.jface.viewers.ViewerSorter; -import org.eclipse.swt.SWT; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.ui.IEditorPart; -import org.eclipse.ui.IMemento; -import org.eclipse.ui.part.IShowInTargetList; - -public class MembersView extends CBrowsingPart implements IPropertyChangeListener { - -// private MemberFilterActionGroup fMemberFilterActionGroup; - - - public MembersView() { - setHasWorkingSetFilter(false); - setHasCustomSetFilter(true); - CUIPlugin.getDefault().getPreferenceStore().addPropertyChangeListener(this); - } - - /** - * Answer the property defined by key. - */ - public Object getAdapter(Class key) { - if (key == IShowInTargetList.class) { - return new IShowInTargetList() { - public String[] getShowInTargetIds() { - return new String[] { CUIPlugin.CVIEW_ID }; - } - - }; - } - return super.getAdapter(key); - } - - /** - * Creates and returns the label provider for this part. - * - * @return the label provider - * @see org.eclipse.jface.viewers.ILabelProvider - */ - protected LabelProvider createLabelProvider() { - return new CBrowsingLabelProvider(); - } - - /** - * Returns the context ID for the Help system - * - * @return the string used as ID for the Help context - */ - protected String getHelpContextId() { - return ICHelpContextIds.MEMBERS_VIEW; - } - - protected String getLinkToEditorKey() { - return PreferenceConstants.LINK_BROWSING_MEMBERS_TO_EDITOR; - } - - /** - * Creates the the viewer of this part. - * - * @param parent the parent for the viewer - */ - protected StructuredViewer createViewer(Composite parent) { - ElementTreeViewer viewer= new ElementTreeViewer(parent, SWT.MULTI); -// fMemberFilterActionGroup= new MemberFilterActionGroup(viewer, JavaUI.ID_MEMBERS_VIEW); - return viewer; - } - - protected ViewerSorter createViewerSorter() { - return new CBrowsingViewerSorter(); - } - - /** - * Adds filters the viewer of this part. - */ - protected void addFilters() { - super.addFilters(); - getViewer().addFilter(new CBrowsingElementFilter()); - } - - protected void fillToolBar(IToolBarManager tbm) { - tbm.add(new LexicalSortingAction(getViewer(), CUIPlugin.ID_MEMBERS_VIEW)); -// fMemberFilterActionGroup.contributeToToolBar(tbm); - super.fillToolBar(tbm); - } - - /** - * Answers if the given element is a valid - * input for this part. - * - * @param element the object to test - * @return if the given element is a valid input - */ - protected boolean isValidInput(Object element) { - if (element instanceof ITypeInfo) { - ITypeInfo type= (ITypeInfo)element; - if (type.getCElementType() != ICElement.C_NAMESPACE && type.exists()) - return true; - } - return false; - } - - /** - * Answers if the given element is a valid - * element for this part. - * - * @param element the object to test - * @return if the given element is a valid element - */ - protected boolean isValidElement(Object element) { - if (element instanceof ICElement) { - if (element instanceof ICModel - || element instanceof ICProject - || element instanceof ISourceRoot - || element instanceof ITranslationUnit) - return false; - return true; - } - return false; - } - - /* - * Implements method from IViewPart. - */ - public void saveState(IMemento memento) { - super.saveState(memento); -// fMemberFilterActionGroup.saveState(memento); - } - - protected void restoreState(IMemento memento) { - super.restoreState(memento); -// fMemberFilterActionGroup.restoreState(memento); - getViewer().getControl().setRedraw(false); - getViewer().refresh(); - getViewer().getControl().setRedraw(true); - } - - protected void hookViewerListeners() { - super.hookViewerListeners(); - getViewer().addDoubleClickListener(new IDoubleClickListener() { - public void doubleClick(DoubleClickEvent event) { - TreeViewer viewer= (TreeViewer)getViewer(); - Object element= ((IStructuredSelection)event.getSelection()).getFirstElement(); - if (viewer.isExpandable(element)) - viewer.setExpandedState(element, !viewer.getExpandedState(element)); - } - }); - } - -/* boolean isInputAWorkingCopy() { - Object input= getViewer().getInput(); - if (input instanceof ICElement) { - ICompilationUnit cu= (ICompilationUnit)((IJavaElement)input).getAncestor(IJavaElement.COMPILATION_UNIT); - if (cu != null) - return cu.isWorkingCopy(); - } - return false; - } -*/ - protected void restoreSelection() { - IEditorPart editor= getViewSite().getPage().getActiveEditor(); - if (editor != null) - setSelectionFromEditor(editor); - } - - /* (non-Javadoc) - * @see org.eclipse.jface.util.IPropertyChangeListener#propertyChange(org.eclipse.jface.util.PropertyChangeEvent) - */ - public void propertyChange(PropertyChangeEvent event) { -// if (MembersOrderPreferenceCache.isMemberOrderProperty(event.getProperty())) { -// getViewer().refresh(); -// } - } - - /* (non-Javadoc) - * @see org.eclipse.jdt.internal.ui.browsing.JavaBrowsingPart#dispose() - */ - public void dispose() { -// if (fMemberFilterActionGroup != null) { -// fMemberFilterActionGroup.dispose(); -// fMemberFilterActionGroup= null; -// } - super.dispose(); - CUIPlugin.getDefault().getPreferenceStore().removePropertyChangeListener(this); - } - - /* (non-Javadoc) - * @see org.eclipse.cdt.internal.ui.browser.cbrowsing.CBrowsingPart#createContentProvider() - */ - protected IContentProvider createContentProvider() { - return new MembersViewContentProvider(this); - } - - protected Object findInputForElement(Object element) { - if (element instanceof ICModel || element instanceof ICProject || element instanceof ISourceRoot) { - return null; - } - - if (element instanceof ITypeInfo) { - return element; - } - - if (element instanceof ICElement) { - ICElement celem = (ICElement)element; - if (!celem.exists()) - return null; - - if (TypeUtil.isDeclaringType(celem)) { - ICElement type= TypeUtil.getDeclaringType(celem); - if (type == null || type instanceof INamespace) - return AllTypesCache.getTypeForElement(celem, true, true, null); - return findInputForElement(type); - } else if (TypeUtil.isMemberType(celem)) { - return findInputForElement(TypeUtil.getDeclaringType(celem)); - } else { - ITranslationUnit tu = TypeUtil.getTranslationUnit(celem); - if (tu != null) - return getTypeForTU(tu); - } - } - return null; - } - - /* (non-Javadoc) - * @see org.eclipse.cdt.internal.ui.browser.cbrowsing.CBrowsingPart#findElementToSelect(java.lang.Object) - */ - protected Object findElementToSelect(Object element) { - if (isValidElement(element)) { - return element; - } - return null; - } -} diff --git a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/cbrowsing/MembersViewContentProvider.java b/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/cbrowsing/MembersViewContentProvider.java deleted file mode 100644 index 79d67e024cc..00000000000 --- a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/cbrowsing/MembersViewContentProvider.java +++ /dev/null @@ -1,152 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.browser.cbrowsing; - -import org.eclipse.cdt.core.browser.AllTypesCache; -import org.eclipse.cdt.core.browser.ITypeInfo; -import org.eclipse.cdt.core.browser.TypeUtil; -import org.eclipse.cdt.core.model.CModelException; -import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.cdt.core.model.ICModel; -import org.eclipse.cdt.core.model.ICProject; -import org.eclipse.cdt.core.model.INamespace; -import org.eclipse.cdt.core.model.IParent; -import org.eclipse.cdt.core.model.ISourceRoot; -import org.eclipse.cdt.ui.CUIPlugin; -import org.eclipse.swt.widgets.Shell; - -class MembersViewContentProvider extends CBrowsingContentProvider { - - MembersViewContentProvider(CBrowsingPart browsingPart) { - super(browsingPart); - } - - /* (non-Javadoc) - * @see org.eclipse.jface.viewers.ITreeContentProvider#hasChildren(java.lang.Object) - */ - public boolean hasChildren(Object element) { - if (element == null || (element instanceof ITypeInfo && !((ITypeInfo)element).exists())) { - return false; - } - - try { - startReadInDisplayThread(); - - if (element instanceof ITypeInfo) { - ITypeInfo info = (ITypeInfo) element; - return (info.getCElementType() != ICElement.C_TYPEDEF); - } - - if (element instanceof IParent) { - return ((IParent)element).hasChildren(); - } - - return false; -// } catch (CModelException e) { -// return false; - } finally { - finishedReadInDisplayThread(); - } - } - - /* (non-Javadoc) - * @see org.eclipse.jface.viewers.ITreeContentProvider#getChildren(java.lang.Object) - */ - public Object[] getChildren(Object element) { - if (element == null || (element instanceof ICElement && !((ICElement)element).exists())) { - return INVALID_INPUT; - } - - try { - startReadInDisplayThread(); - - if (element instanceof ITypeInfo) { - ITypeInfo info = (ITypeInfo) element; - if (info.getCElementType() == ICElement.C_NAMESPACE) { - return INVALID_INPUT; // shouldn't get here... - } - if (info.getCElementType() == ICElement.C_TYPEDEF) { - return EMPTY_CHILDREN; - } - ICElement elem = AllTypesCache.getElementForType(info, true, true, null); - if (elem == null) { - return ERROR_NO_CHILDREN; - } - if (elem instanceof IParent) { - ICElement[] children = ((IParent)elem).getChildren(); - if (children != null && children.length > 0) - return children; - } - return EMPTY_CHILDREN; - } - - if (element instanceof IParent) { - ICElement[] children = ((IParent)element).getChildren(); - if (children != null && children.length > 0) - return children; - return EMPTY_CHILDREN; - } - - return INVALID_INPUT; - } catch (CModelException e) { - return ERROR_CANCELLED; - } finally { - finishedReadInDisplayThread(); - } - } - - /* (non-Javadoc) - * @see org.eclipse.jface.viewers.ITreeContentProvider#getParent(java.lang.Object) - */ - public Object getParent(Object element) { - if (element instanceof ICModel || element instanceof ICProject || element instanceof ISourceRoot) { - return null; - } - - if (element instanceof ITypeInfo) { - return null; - } - - try { - startReadInDisplayThread(); - - if (element instanceof ICElement) { - ICElement celem = (ICElement)element; - if (TypeUtil.isMemberType(celem)) { - ICElement parent = TypeUtil.getDeclaringType(celem); - if (parent == null || parent instanceof INamespace) { - ITypeInfo info = AllTypesCache.getTypeForElement(celem, true, true, null); - if (info != null) - return info.getEnclosingType(); - } - return parent; - } - } - - return null; -// } catch (CModelException e) { -// return false; - } finally { - finishedReadInDisplayThread(); - } - } - - /* (non-Javadoc) - * @see org.eclipse.jface.viewers.IStructuredContentProvider#getElements(java.lang.Object) - */ - public Object[] getElements(Object inputElement) { - return getChildren(inputElement); - } - - protected Shell getShell() { - return CUIPlugin.getActiveWorkbenchShell(); - } -} diff --git a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/cbrowsing/NamespacesView.java b/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/cbrowsing/NamespacesView.java deleted file mode 100644 index 4499544cfbd..00000000000 --- a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/cbrowsing/NamespacesView.java +++ /dev/null @@ -1,246 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.browser.cbrowsing; - -import org.eclipse.cdt.core.browser.AllTypesCache; -import org.eclipse.cdt.core.browser.ITypeInfo; -import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.cdt.core.model.ICModel; -import org.eclipse.cdt.core.model.ICProject; -import org.eclipse.cdt.core.model.IEnumeration; -import org.eclipse.cdt.core.model.ISourceRoot; -import org.eclipse.cdt.core.model.IStructure; -import org.eclipse.cdt.core.model.ITranslationUnit; -import org.eclipse.cdt.core.model.ITypeDef; -import org.eclipse.cdt.internal.ui.ICHelpContextIds; -import org.eclipse.cdt.ui.CUIPlugin; -import org.eclipse.cdt.ui.PreferenceConstants; -import org.eclipse.core.resources.IProject; -import org.eclipse.jface.viewers.IContentProvider; -import org.eclipse.jface.viewers.LabelProvider; -import org.eclipse.jface.viewers.StructuredViewer; -import org.eclipse.jface.viewers.ViewerSorter; -import org.eclipse.swt.SWT; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.ui.IActionBars; -import org.eclipse.ui.IPageLayout; -import org.eclipse.ui.part.IShowInTargetList; - -public class NamespacesView extends CBrowsingPart { - -// private SelectAllAction fSelectAllAction; - - /** - * Creates and returns the label provider for this part. - * - * @return the label provider - * @see org.eclipse.jface.viewers.ILabelProvider - */ - protected LabelProvider createLabelProvider() { - return new NamespacesViewLabelProvider(); - } - - /** - * Answer the property defined by key. - */ - public Object getAdapter(Class key) { - if (key == IShowInTargetList.class) { - return new IShowInTargetList() { - public String[] getShowInTargetIds() { - return new String[] { CUIPlugin.CVIEW_ID, IPageLayout.ID_RES_NAV }; - } - - }; - } - return super.getAdapter(key); - } - - /** - * Creates the viewer of this part dependent on the current - * layout. - * - * @param parent the parent for the viewer - */ - protected StructuredViewer createViewer(Composite parent) { - StructuredViewer viewer; -// if(isInListState()) - viewer= createTableViewer(parent); -// else -// viewer= createTreeViewer(parent); - -// fWrappedViewer.setViewer(viewer); -// return fWrappedViewer; - return viewer; - } - private ElementTableViewer createTableViewer(Composite parent) { - return new ElementTableViewer(parent, SWT.MULTI); - } - - /** - * Creates the the content provider of this part. - */ - protected IContentProvider createContentProvider() { - return new NamespacesViewContentProvider(this); - } - - protected ViewerSorter createViewerSorter() { - return new TypeInfoSorter(); - } - - /** - * Adds filters the viewer of this part. - */ - protected void addFilters() { - super.addFilters(); - getViewer().addFilter(new CBrowsingElementFilter()); - } - - /** - * Answers if the given element is a valid - * input for this part. - * - * @param element the object to test - * @return if the given element is a valid input - */ - protected boolean isValidInput(Object element) { - return (element instanceof ICProject || element instanceof ISourceRoot); - } - - /** - * Answers if the given element is a valid - * element for this part. - * - * @param element the object to test - * @return if the given element is a valid element - */ - protected boolean isValidElement(Object element) { - if (element instanceof ITypeInfo) { - ITypeInfo info = (ITypeInfo)element; - if (info.exists() && info.getCElementType() == ICElement.C_NAMESPACE) { - // make sure it has types other than namespaces - ITypeInfo[] types = info.getEnclosedTypes(); - if (types != null) { - for (int i = 0; i < types.length; ++i) { - if (types[i].getCElementType() != ICElement.C_NAMESPACE) { - return true; - } - } - } - } - } - return false; - } - - /** - * Returns the context ID for the Help system - * - * @return the string used as ID for the Help context - */ - protected String getHelpContextId() { - return ICHelpContextIds.TYPES_VIEW; - } - - protected String getLinkToEditorKey() { - return PreferenceConstants.LINK_BROWSING_TYPES_TO_EDITOR; - } - - protected void createActions() { - super.createActions(); -// fSelectAllAction= new SelectAllAction((TableViewer)getViewer()); - } - - protected void fillActionBars(IActionBars actionBars) { - super.fillActionBars(actionBars); - - // Add selectAll action handlers. -// actionBars.setGlobalActionHandler(IWorkbenchActionConstants.SELECT_ALL, fSelectAllAction); - } - - /* (non-Javadoc) - * @see org.eclipse.cdt.internal.ui.browser.cbrowsing.CBrowsingPart#findInputForElement(java.lang.Object) - */ - protected Object findInputForElement(Object element) { - if (element instanceof ICModel) { - return null; - } - - if (element instanceof ICProject || element instanceof ISourceRoot) { - if (exists(element)) - return element; - } - - if (element instanceof ITypeInfo) { - ITypeInfo info = (ITypeInfo)element; - ISourceRoot root = findSourceRoot(info); - if (exists(root) && !isProjectSourceRoot(root)) - return root; - ICProject cProject = findCProject(info); - if (exists(cProject)) - return cProject; - } - - if (element instanceof ICElement) { - ICElement cElem = (ICElement)element; - ISourceRoot root = findSourceRoot(cElem); - if (exists(root) && !isProjectSourceRoot(root)) - return root; - ICProject cProject = findCProject(cElem); - if (exists(cProject)) - return cProject; - } - - return null; - } - - /* (non-Javadoc) - * @see org.eclipse.cdt.internal.ui.browser.cbrowsing.CBrowsingPart#findElementToSelect(java.lang.Object) - */ - protected Object findElementToSelect(Object element) { - if (element instanceof ICModel || element instanceof ICProject || element instanceof ISourceRoot) { - return null; - } - - if (element instanceof ICElement) { - ICElement celem = (ICElement)element; - if (celem instanceof ITranslationUnit) { - IProject project = celem.getCProject().getProject(); - return AllTypesCache.getGlobalNamespace(project); - } else if (celem.getElementType() == ICElement.C_NAMESPACE) { - return AllTypesCache.getTypeForElement(celem, true, true, null); - } else { - ICElement parent = (ICElement)element; - while (parent != null) { - if ((parent instanceof IStructure - || parent instanceof IEnumeration - || parent instanceof ITypeDef) - && parent.exists()) { - ITypeInfo info = AllTypesCache.getTypeForElement(parent, true, true, null); - if (info != null) { - return info.getEnclosingNamespace(true); - } - } - parent = parent.getParent(); - } - } - return null; - } - - if (element instanceof ITypeInfo) { - ITypeInfo info = (ITypeInfo) element; - if (info.getCElementType() == ICElement.C_NAMESPACE && info.exists()) { - return info; - } - return info.getEnclosingNamespace(true); - } - - return null; - } -} diff --git a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/cbrowsing/NamespacesViewContentProvider.java b/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/cbrowsing/NamespacesViewContentProvider.java deleted file mode 100644 index b88d6038ee0..00000000000 --- a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/cbrowsing/NamespacesViewContentProvider.java +++ /dev/null @@ -1,170 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.browser.cbrowsing; - -import java.lang.reflect.InvocationTargetException; - -import org.eclipse.cdt.core.browser.AllTypesCache; -import org.eclipse.cdt.core.browser.ITypeInfo; -import org.eclipse.cdt.core.browser.ITypeSearchScope; -import org.eclipse.cdt.core.browser.TypeSearchScope; -import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.cdt.core.model.ICProject; -import org.eclipse.cdt.core.model.ISourceRoot; -import org.eclipse.cdt.internal.ui.browser.opentype.OpenTypeMessages; -import org.eclipse.cdt.internal.ui.util.ExceptionHandler; -import org.eclipse.cdt.ui.CUIPlugin; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.jface.operation.IRunnableWithProgress; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.ui.PlatformUI; -import org.eclipse.ui.progress.IProgressService; - -class NamespacesViewContentProvider extends CBrowsingContentProvider { - - NamespacesViewContentProvider(CBrowsingPart browsingPart) { - super(browsingPart); - } - - /* (non-Javadoc) - * @see org.eclipse.jface.viewers.ITreeContentProvider#hasChildren(java.lang.Object) - */ - public boolean hasChildren(Object element) { - if (element == null || (element instanceof ICElement && !((ICElement)element).exists())) { - return false; - } - - try { - startReadInDisplayThread(); - - if (element instanceof ICProject) { - return true; -// TypeSearchScope scope = new TypeSearchScope(); -// scope.add((ICProject)element); -// return AllTypesCache.getNamespaces(scope, true); - } - - if (element instanceof ISourceRoot) { - return true; -// TypeSearchScope scope = new TypeSearchScope(); -// scope.add((ISourceRoot)element); -// return AllTypesCache.getNamespaces(scope, true); - } - - return false; -// } catch (CModelException e) { -// return false; - } finally { - finishedReadInDisplayThread(); - } - } - - /* (non-Javadoc) - * @see org.eclipse.jface.viewers.ITreeContentProvider#getChildren(java.lang.Object) - */ - public Object[] getChildren(Object element) { - if (element == null || (element instanceof ICElement && !((ICElement)element).exists())) { - return INVALID_INPUT; - } - - try { - startReadInDisplayThread(); - - if (element instanceof ICProject) { - TypeSearchScope scope = new TypeSearchScope(); - scope.add((ICProject)element); - return getNamespaces(scope); - } - - if (element instanceof ISourceRoot) { - TypeSearchScope scope = new TypeSearchScope(); - scope.add((ISourceRoot)element); - return getNamespaces(scope); - } - - return INVALID_INPUT; -// } catch (CModelException e) { -// return NO_CHILDREN; - } finally { - finishedReadInDisplayThread(); - } - } - - /* (non-Javadoc) - * @see org.eclipse.jface.viewers.ITreeContentProvider#getParent(java.lang.Object) - */ - public Object getParent(Object element) { - if (element == null || (element instanceof ITypeInfo && !((ITypeInfo)element).exists())) { - return null; - } - - try { - startReadInDisplayThread(); - - if (element instanceof ITypeInfo) { - ITypeInfo info = (ITypeInfo)element; - if (info.isEnclosedType()) { - return info.getEnclosingType(); - } -// return info.getEnclosingProject(); - return null; - } - - return null; -// } catch (CModelException e) { -// return false; - } finally { - finishedReadInDisplayThread(); - } - } - - /* (non-Javadoc) - * @see org.eclipse.jface.viewers.IStructuredContentProvider#getElements(java.lang.Object) - */ - public Object[] getElements(Object inputElement) { - return getChildren(inputElement); - } - - private Object[] getNamespaces(final ITypeSearchScope scope) { - if (!AllTypesCache.isCacheUpToDate(scope)) { - IRunnableWithProgress runnable = new IRunnableWithProgress() { - public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { - AllTypesCache.updateCache(scope, monitor); - if (monitor.isCanceled()) { - throw new InterruptedException(); - } - } - }; - - IProgressService service = PlatformUI.getWorkbench().getProgressService(); - try { - service.busyCursorWhile(runnable); - } catch (InvocationTargetException e) { - String title = OpenTypeMessages.getString("OpenTypeAction.exception.title"); //$NON-NLS-1$ - String message = OpenTypeMessages.getString("OpenTypeAction.exception.message"); //$NON-NLS-1$ - ExceptionHandler.handle(e, title, message); - return ERROR_CANCELLED; - } catch (InterruptedException e) { - // cancelled by user - return ERROR_CANCELLED; - } - } - ITypeInfo[] namespaces = AllTypesCache.getNamespaces(scope, true); - if (namespaces != null && namespaces.length > 0) { - return namespaces; - } - return EMPTY_CHILDREN; - } - - protected Shell getShell() { - return CUIPlugin.getActiveWorkbenchShell(); - } -} diff --git a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/cbrowsing/NamespacesViewLabelProvider.java b/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/cbrowsing/NamespacesViewLabelProvider.java deleted file mode 100644 index c00410d9b85..00000000000 --- a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/cbrowsing/NamespacesViewLabelProvider.java +++ /dev/null @@ -1,36 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 QNX Software Systems and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * QNX Software Systems - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.browser.cbrowsing; - -import org.eclipse.cdt.core.browser.ITypeInfo; -import org.eclipse.cdt.ui.browser.typeinfo.TypeInfoLabelProvider; -import org.eclipse.swt.graphics.Image; - -public class NamespacesViewLabelProvider extends CBrowsingLabelProvider { - - protected static final TypeInfoLabelProvider fTypeInfoLabelProvider = new TypeInfoLabelProvider(TypeInfoLabelProvider.SHOW_FULLY_QUALIFIED); - - public NamespacesViewLabelProvider() { - super(); - } - - public Image getImage(Object element) { - if (element instanceof ITypeInfo) - return fTypeInfoLabelProvider.getImage(element); - return super.getImage(element); - } - - public String getText(Object element) { - if (element instanceof ITypeInfo) - return fTypeInfoLabelProvider.getText(element); - return super.getText(element); - } -} diff --git a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/cbrowsing/OpenProjectAction.java b/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/cbrowsing/OpenProjectAction.java deleted file mode 100644 index 05b4ad84a9d..00000000000 --- a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/cbrowsing/OpenProjectAction.java +++ /dev/null @@ -1,218 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.browser.cbrowsing; - -import java.lang.reflect.InvocationTargetException; -import java.util.ArrayList; -import java.util.List; - -import org.eclipse.cdt.internal.ui.ICHelpContextIds; -import org.eclipse.cdt.internal.ui.actions.ActionMessages; -import org.eclipse.cdt.internal.ui.actions.WorkbenchRunnableAdapter; -import org.eclipse.cdt.internal.ui.util.ExceptionHandler; -import org.eclipse.cdt.ui.CElementLabelProvider; -import org.eclipse.cdt.ui.CUIPlugin; -import org.eclipse.cdt.ui.actions.SelectionDispatchAction; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.MultiStatus; -import org.eclipse.core.runtime.SubProgressMonitor; - -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IResourceChangeEvent; -import org.eclipse.core.resources.IResourceChangeListener; -import org.eclipse.core.resources.IResourceDelta; -import org.eclipse.core.resources.IWorkspaceRunnable; -import org.eclipse.core.resources.ResourcesPlugin; - -import org.eclipse.jface.viewers.ISelection; -import org.eclipse.jface.viewers.IStructuredSelection; -import org.eclipse.jface.window.Window; - -import org.eclipse.ui.IWorkbenchSite; -import org.eclipse.ui.PlatformUI; -import org.eclipse.ui.actions.OpenResourceAction; -import org.eclipse.ui.dialogs.ElementListSelectionDialog; -import org.eclipse.ui.help.WorkbenchHelp; - -/** - * Action to open a closed project. Action either opens the closed projects - * provided by the strucutured selection or present a dialog from which the - * user can select the projects to be opened. - * - *

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

      - * - * @since 2.0 - */ -public class OpenProjectAction extends SelectionDispatchAction implements IResourceChangeListener { - - private static final int EMPTY_SELECTION= 1; - private static final int ELEMENT_SELECTION= 2; - - private int fMode; - private OpenResourceAction fWorkbenchAction; - - /** - * Creates a new OpenProjectAction. The action requires - * that the selection provided by the site's selection provider is of type - * org.eclipse.jface.viewers.IStructuredSelection. - * - * @param site the site providing context information for this action - */ - public OpenProjectAction(IWorkbenchSite site) { - super(site); - fWorkbenchAction= new OpenResourceAction(site.getShell()); - setText(fWorkbenchAction.getText()); - setToolTipText(fWorkbenchAction.getToolTipText()); - setEnabled(hasCloseProjects()); - WorkbenchHelp.setHelp(this, ICHelpContextIds.OPEN_PROJECT_ACTION); - } - - /* - * @see IResourceChangeListener#resourceChanged(IResourceChangeEvent) - */ - public void resourceChanged(IResourceChangeEvent event) { - fWorkbenchAction.resourceChanged(event); - switch (fMode) { - case ELEMENT_SELECTION: - setEnabled(fWorkbenchAction.isEnabled()); - break; - case EMPTY_SELECTION: - internalResourceChanged(event); - break; - } - } - - private void internalResourceChanged(IResourceChangeEvent event) { - IResourceDelta delta = event.getDelta(); - if (delta != null) { - IResourceDelta[] projDeltas = delta.getAffectedChildren(IResourceDelta.CHANGED); - for (int i = 0; i < projDeltas.length; ++i) { - IResourceDelta projDelta = projDeltas[i]; - if ((projDelta.getFlags() & IResourceDelta.OPEN) != 0) { - setEnabled(hasCloseProjects()); - return; - } - } - } - } - - //---- normal selection ------------------------------------- - - /* (non-Javadoc) - * @see org.eclipse.jdt.ui.actions.SelectionDispatchAction#selectionChanged(org.eclipse.jface.viewers.ISelection) - */ - public void selectionChanged(ISelection selection) { - setEnabled(hasCloseProjects()); - fMode= EMPTY_SELECTION; - } - - /* (non-Javadoc) - * @see org.eclipse.jdt.ui.actions.SelectionDispatchAction#run(org.eclipse.jface.viewers.ISelection) - */ - public void run(ISelection selection) { - internalRun(); - } - - //---- structured selection --------------------------------------- - - /* (non-Javadoc) - * @see org.eclipse.jdt.ui.actions.SelectionDispatchAction#selectionChanged(org.eclipse.jface.viewers.IStructuredSelection) - */ - public void selectionChanged(IStructuredSelection selection) { - if (selection.isEmpty()) { - setEnabled(hasCloseProjects()); - fMode= EMPTY_SELECTION; - return; - } - fWorkbenchAction.selectionChanged(selection); - setEnabled(fWorkbenchAction.isEnabled()); - fMode= ELEMENT_SELECTION; - } - - - /* (non-Javadoc) - * @see org.eclipse.jdt.ui.actions.SelectionDispatchAction#run(org.eclipse.jface.viewers.IStructuredSelection) - */ - public void run(IStructuredSelection selection) { - if (selection.isEmpty()) { - internalRun(); - return; - } - fWorkbenchAction.run(); - } - - private void internalRun() { - ElementListSelectionDialog dialog= new ElementListSelectionDialog(getShell(), new CElementLabelProvider()); - dialog.setTitle(ActionMessages.getString("OpenProjectAction.dialog.title")); //$NON-NLS-1$ - dialog.setMessage(ActionMessages.getString("OpenProjectAction.dialog.message")); //$NON-NLS-1$ - dialog.setElements(getClosedProjects()); - dialog.setMultipleSelection(true); - int result= dialog.open(); - if (result != Window.OK) - return; - final Object[] projects= dialog.getResult(); - IWorkspaceRunnable runnable= createRunnable(projects); - try { - PlatformUI.getWorkbench().getProgressService().run(true, true, new WorkbenchRunnableAdapter(runnable)); - } catch (InvocationTargetException e) { - ExceptionHandler.handle(e, getShell(), - ActionMessages.getString("OpenProjectAction.dialog.title"), //$NON-NLS-1$ - ActionMessages.getString("OpenProjectAction.error.message")); //$NON-NLS-1$ - } catch (InterruptedException e) { - } - } - - private IWorkspaceRunnable createRunnable(final Object[] projects) { - return new IWorkspaceRunnable() { - public void run(IProgressMonitor monitor) throws CoreException { - monitor.beginTask("", projects.length); //$NON-NLS-1$ - MultiStatus errorStatus= null; - for (int i = 0; i < projects.length; i++) { - IProject project= (IProject)projects[i]; - try { - project.open(new SubProgressMonitor(monitor, 1)); - } catch (CoreException e) { - if (errorStatus == null) - errorStatus = new MultiStatus(CUIPlugin.getPluginId(), IStatus.ERROR, ActionMessages.getString("OpenProjectAction.error.message"), e); //$NON-NLS-1$ - errorStatus.merge(e.getStatus()); - } - } - monitor.done(); - if (errorStatus != null) - throw new CoreException(errorStatus); - } - }; - } - - private Object[] getClosedProjects() { - IProject[] projects= ResourcesPlugin.getWorkspace().getRoot().getProjects(); - List result= new ArrayList(5); - for (int i = 0; i < projects.length; i++) { - IProject project= projects[i]; - if (!project.isOpen()) - result.add(project); - } - return result.toArray(); - } - - private boolean hasCloseProjects() { - IProject[] projects= ResourcesPlugin.getWorkspace().getRoot().getProjects(); - for (int i = 0; i < projects.length; i++) { - if (!projects[i].isOpen()) - return true; - } - return false; - } -} diff --git a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/cbrowsing/ProjectActionGroup.java b/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/cbrowsing/ProjectActionGroup.java deleted file mode 100644 index cf8b467a607..00000000000 --- a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/cbrowsing/ProjectActionGroup.java +++ /dev/null @@ -1,109 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.browser.cbrowsing; - -import org.eclipse.cdt.internal.ui.IContextMenuConstants; -import org.eclipse.core.resources.IWorkspace; -import org.eclipse.core.resources.ResourcesPlugin; - -import org.eclipse.swt.widgets.Shell; - -import org.eclipse.jface.action.IMenuManager; -import org.eclipse.jface.viewers.ISelection; -import org.eclipse.jface.viewers.ISelectionProvider; -import org.eclipse.jface.viewers.IStructuredSelection; - -import org.eclipse.ui.IActionBars; -import org.eclipse.ui.IViewPart; -import org.eclipse.ui.IWorkbenchSite; -import org.eclipse.ui.actions.ActionGroup; -import org.eclipse.ui.actions.CloseResourceAction; -import org.eclipse.ui.ide.IDEActionFactory; - -/** - * Adds actions to open and close a project to the global menu bar. - * - *

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

      - * - * @since 2.0 - */ -public class ProjectActionGroup extends ActionGroup { - - private IWorkbenchSite fSite; - - private OpenProjectAction fOpenAction; - private CloseResourceAction fCloseAction; - - /** - * Creates a new ProjectActionGroup. The group requires - * that the selection provided by the site's selection provider is of type - * org.eclipse.jface.viewers.IStructuredSelection. - * - * @param part the view part that owns this action group - */ - public ProjectActionGroup(IViewPart part) { - fSite = part.getSite(); - Shell shell= fSite.getShell(); - ISelectionProvider provider= fSite.getSelectionProvider(); - ISelection selection= provider.getSelection(); - - fCloseAction= new CloseResourceAction(shell); - fCloseAction.setActionDefinitionId("org.eclipse.ui.project.closeProject"); //$NON-NLS-1$ - fOpenAction= new OpenProjectAction(fSite); - fOpenAction.setActionDefinitionId("org.eclipse.ui.project.openProject"); //$NON-NLS-1$ - if (selection instanceof IStructuredSelection) { - IStructuredSelection s= (IStructuredSelection)selection; - fOpenAction.selectionChanged(s); - fCloseAction.selectionChanged(s); - } - provider.addSelectionChangedListener(fOpenAction); - provider.addSelectionChangedListener(fCloseAction); - IWorkspace workspace= ResourcesPlugin.getWorkspace(); - workspace.addResourceChangeListener(fOpenAction); - workspace.addResourceChangeListener(fCloseAction); - } - - /* (non-Javadoc) - * Method declared in ActionGroup - */ - public void fillActionBars(IActionBars actionBars) { - super.fillActionBars(actionBars); - actionBars.setGlobalActionHandler(IDEActionFactory.CLOSE_PROJECT.getId(), fCloseAction); - actionBars.setGlobalActionHandler(IDEActionFactory.OPEN_PROJECT.getId(), fOpenAction); - } - - /* (non-Javadoc) - * Method declared in ActionGroup - */ - public void fillContextMenu(IMenuManager menu) { - super.fillContextMenu(menu); - if (fOpenAction.isEnabled()) - menu.appendToGroup(IContextMenuConstants.GROUP_BUILD, fOpenAction); - if (fCloseAction.isEnabled()) - menu.appendToGroup(IContextMenuConstants.GROUP_BUILD, fCloseAction); - } - - - /* - * @see ActionGroup#dispose() - */ - public void dispose() { - ISelectionProvider provider= fSite.getSelectionProvider(); - provider.removeSelectionChangedListener(fOpenAction); - provider.removeSelectionChangedListener(fCloseAction); - IWorkspace workspace = ResourcesPlugin.getWorkspace(); - workspace.removeResourceChangeListener(fOpenAction); - workspace.removeResourceChangeListener(fCloseAction); - super.dispose(); - } -} diff --git a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/cbrowsing/ProjectsView.java b/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/cbrowsing/ProjectsView.java deleted file mode 100644 index 455d09b934a..00000000000 --- a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/cbrowsing/ProjectsView.java +++ /dev/null @@ -1,266 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.browser.cbrowsing; - -import org.eclipse.cdt.core.browser.AllTypesCache; -import org.eclipse.cdt.core.browser.ITypeInfo; -import org.eclipse.cdt.core.model.CoreModel; -import org.eclipse.cdt.core.model.ICContainer; -import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.cdt.core.model.ICModel; -import org.eclipse.cdt.core.model.ICProject; -import org.eclipse.cdt.core.model.IEnumeration; -import org.eclipse.cdt.core.model.ISourceRoot; -import org.eclipse.cdt.core.model.IStructure; -import org.eclipse.cdt.core.model.ITranslationUnit; -import org.eclipse.cdt.core.model.ITypeDef; -import org.eclipse.cdt.internal.ui.ICHelpContextIds; -import org.eclipse.cdt.ui.CUIPlugin; -import org.eclipse.cdt.ui.PreferenceConstants; -import org.eclipse.jface.viewers.DoubleClickEvent; -import org.eclipse.jface.viewers.IContentProvider; -import org.eclipse.jface.viewers.IDoubleClickListener; -import org.eclipse.jface.viewers.IStructuredSelection; -import org.eclipse.jface.viewers.LabelProvider; -import org.eclipse.jface.viewers.StructuredViewer; -import org.eclipse.jface.viewers.TreeViewer; -import org.eclipse.jface.viewers.ViewerSorter; -import org.eclipse.swt.SWT; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.ui.IPageLayout; -import org.eclipse.ui.part.IShowInTargetList; - -public class ProjectsView extends CBrowsingPart { - -// private FilterUpdater fFilterUpdater; - - /** - * Creates the the viewer of this part. - * - * @param parent the parent for the viewer - */ - protected StructuredViewer createViewer(Composite parent) { - ElementTreeViewer result= new ElementTreeViewer(parent, SWT.MULTI); -// fFilterUpdater= new FilterUpdater(result); -// ResourcesPlugin.getWorkspace().addResourceChangeListener(fFilterUpdater); - return result; - } - - protected LabelProvider createLabelProvider() { - return new CBrowsingLabelProvider(); - } - - protected ViewerSorter createViewerSorter() { - return new CBrowsingViewerSorter(); - } - - /** - * Adds filters the viewer of this part. - */ - protected void addFilters() { - super.addFilters(); - getViewer().addFilter(new CBrowsingElementFilter()); - } - - /* (non-Javadoc) - * @see org.eclipse.jdt.internal.ui.browsing.JavaBrowsingPart#dispose() - */ - public void dispose() { -// if (fFilterUpdater != null) -// ResourcesPlugin.getWorkspace().removeResourceChangeListener(fFilterUpdater); - super.dispose(); - } - - /** - * Answer the property defined by key. - */ - public Object getAdapter(Class key) { - if (key == IShowInTargetList.class) { - return new IShowInTargetList() { - public String[] getShowInTargetIds() { - return new String[] { CUIPlugin.CVIEW_ID, IPageLayout.ID_RES_NAV }; - } - - }; - } - return super.getAdapter(key); - } - - - /** - * Creates the the content provider of this part. - */ - protected IContentProvider createContentProvider() { - return new ProjectsViewContentProvider(this); - } - - /** - * Returns the context ID for the Help system. - * - * @return the string used as ID for the Help context - */ - protected String getHelpContextId() { - return ICHelpContextIds.PROJECTS_VIEW; - } - - protected String getLinkToEditorKey() { - return PreferenceConstants.LINK_BROWSING_PROJECTS_TO_EDITOR; - } - - - /** - * Adds additional listeners to this view. - */ - protected void hookViewerListeners() { - super.hookViewerListeners(); - getViewer().addDoubleClickListener(new IDoubleClickListener() { - public void doubleClick(DoubleClickEvent event) { - TreeViewer viewer= (TreeViewer)getViewer(); - Object element= ((IStructuredSelection)event.getSelection()).getFirstElement(); - if (viewer.isExpandable(element)) - viewer.setExpandedState(element, !viewer.getExpandedState(element)); - } - }); - } - - protected void setInitialInput() { - ICElement root= CoreModel.create(CUIPlugin.getWorkspace().getRoot()); - getViewer().setInput(root); - updateTitle(); - } - - /** - * Answers if the given element is a valid - * input for this part. - * - * @param element the object to test - * @return if the given element is a valid input - */ - protected boolean isValidInput(Object element) { - return element instanceof ICModel; - } - - /** - * Answers if the given element is a valid - * element for this part. - * - * @param element the object to test - * @return if the given element is a valid element - */ - protected boolean isValidElement(Object element) { - return element instanceof ICProject || element instanceof ICContainer; - } - - /* - * @see JavaBrowsingPart#setInput(Object) - */ - protected void setInput(Object input) { - // Don't allow to clear input for this view - if (input != null) - super.setInput(input); - else - getViewer().setSelection(null); - } - - protected void createActions() { - super.createActions(); -// fActionGroups.addGroup(new ProjectActionGroup(this)); - } - - /* (non-Javadoc) - * @see org.eclipse.cdt.internal.ui.browser.cbrowsing.CBrowsingPart#findInputForElement(java.lang.Object) - */ - protected Object findInputForElement(Object element) { - if (element instanceof ICModel) { - if (exists(element)) - return element; - } - - if (element instanceof ICElement) { //ICProject || element instanceof ISourceRoot) { - ICModel model = ((ICElement)element).getCModel(); - if (exists(model)) - return model; - } - - if (element instanceof ITypeInfo) { - ICProject cProject = findCProject((ITypeInfo)element); - if (cProject != null) { - ICModel model = cProject.getCModel(); - if (exists(model)) - return model; - } - } - - return null; - } - - /* (non-Javadoc) - * @see org.eclipse.cdt.internal.ui.browser.cbrowsing.CBrowsingPart#findElementToSelect(java.lang.Object) - */ - protected Object findElementToSelect(Object element) { - if (element instanceof ICModel) { - return null; - } - - if (element instanceof ICProject || element instanceof ISourceRoot) { - if (exists(element)) - return element; - return null; - } - - if (element instanceof ITranslationUnit) { - ICElement e = (ICElement)element; - ISourceRoot root = findSourceRoot(e); - if (exists(root) && !isProjectSourceRoot(root)) - return root; - ICProject cProject = findCProject(e); - if (exists(cProject)) - return cProject; - return null; - } - - if (element instanceof ITypeInfo) { - ITypeInfo info = (ITypeInfo)element; - ISourceRoot root = findSourceRoot(info); - if (exists(root) && !isProjectSourceRoot(root)) - return root; - ICProject cProject = findCProject(info); - if (exists(cProject)) - return cProject; - return null; - } - - if (element instanceof ICElement) { - ICElement parent = (ICElement)element; - while (parent != null) { - if ((parent instanceof IStructure - || parent instanceof IEnumeration - || parent instanceof ITypeDef) - && parent.exists()) { - ITypeInfo info = AllTypesCache.getTypeForElement(parent, true, true, null); - if (info != null) { - ISourceRoot root = findSourceRoot(info); - if (exists(root) && !isProjectSourceRoot(root)) - return root; - ICProject cProject = findCProject(info); - if (exists(cProject)) - return cProject; - return null; - } - } - parent = parent.getParent(); - } - return null; - } - - return null; - } -} diff --git a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/cbrowsing/ProjectsViewContentProvider.java b/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/cbrowsing/ProjectsViewContentProvider.java deleted file mode 100644 index 0a6e927653c..00000000000 --- a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/cbrowsing/ProjectsViewContentProvider.java +++ /dev/null @@ -1,155 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.browser.cbrowsing; - -import java.util.ArrayList; -import java.util.List; - -import org.eclipse.cdt.core.model.CModelException; -import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.cdt.core.model.ICModel; -import org.eclipse.cdt.core.model.ICProject; -import org.eclipse.cdt.core.model.ISourceRoot; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IResource; - -class ProjectsViewContentProvider extends CBrowsingContentProvider { - - ProjectsViewContentProvider(CBrowsingPart browsingPart) { - super(browsingPart); - } - - /* (non-Javadoc) - * @see org.eclipse.jface.viewers.ITreeContentProvider#hasChildren(java.lang.Object) - */ - public boolean hasChildren(Object element) { - if (element == null || (element instanceof ICElement && !((ICElement)element).exists())) { - return false; - } - - try { - startReadInDisplayThread(); - - if (element instanceof ICModel) { - ICModel cModel = (ICModel)element; - return cModel.hasChildren(); - } - - if (element instanceof ICProject) { - ICProject cProject = (ICProject)element; - if (cProject.exists() && cProject.isOpen()) - return cProject.hasChildren(); - return false; - } - - if (element instanceof ISourceRoot) { - return false; - } - - return false; -// } catch (CModelException e) { -// return false; - } finally { - finishedReadInDisplayThread(); - } - } - - /* (non-Javadoc) - * @see org.eclipse.jface.viewers.ITreeContentProvider#getChildren(java.lang.Object) - */ - public Object[] getChildren(Object element) { - if (element == null || (element instanceof ICElement && !((ICElement)element).exists())) { - return INVALID_INPUT; - } - - try { - startReadInDisplayThread(); - - if (element instanceof ICModel) { - ICModel cModel = (ICModel)element; - return cModel.getCProjects(); - } - - if (element instanceof ICProject) - return getSourceRoots((ICProject)element); - - if (element instanceof ISourceRoot) - return NO_CHILDREN; - - return INVALID_INPUT; - } catch (CModelException e) { - return ERROR_CANCELLED; - } finally { - finishedReadInDisplayThread(); - } - } - - /* (non-Javadoc) - * @see org.eclipse.jface.viewers.ITreeContentProvider#getParent(java.lang.Object) - */ - public Object getParent(Object element) { - if (element == null || (element instanceof ICElement && !((ICElement)element).exists())) { - return null; - } - - try { - startReadInDisplayThread(); - - if (element instanceof ICModel) { - return null; - } - - if (element instanceof ICProject) { - ICProject cProject = (ICProject)element; - return cProject.getCModel(); - } - - if (element instanceof ISourceRoot) { - ISourceRoot cSourceRoot = (ISourceRoot)element; - return cSourceRoot.getCProject(); - } - - return null; -// } catch (CModelException e) { -// return false; - } finally { - finishedReadInDisplayThread(); - } - } - - /* (non-Javadoc) - * @see org.eclipse.jface.viewers.IStructuredContentProvider#getElements(java.lang.Object) - */ - public Object[] getElements(Object inputElement) { - return getChildren(inputElement); - } - - protected Object[] getSourceRoots(ICProject project) throws CModelException { - if (!project.getProject().isOpen()) - return NO_CHILDREN; - - ISourceRoot[] roots= project.getSourceRoots(); - List list= new ArrayList(roots.length); - // filter out package fragments that correspond to projects and - // replace them with the package fragments directly - for (int i= 0; i < roots.length; i++) { - ISourceRoot root= roots[i]; - if (!isProjectSourceRoot(root)) - list.add(root); - } - return list.toArray(); - } - - protected boolean isProjectSourceRoot(ISourceRoot root) { - IResource resource= root.getResource(); - return (resource instanceof IProject); - } -} diff --git a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/cbrowsing/ToggleLinkingAction.java b/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/cbrowsing/ToggleLinkingAction.java deleted file mode 100644 index 7384009b5f8..00000000000 --- a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/cbrowsing/ToggleLinkingAction.java +++ /dev/null @@ -1,40 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.browser.cbrowsing; - -import org.eclipse.cdt.internal.ui.actions.AbstractToggleLinkingAction; - -/** - * This action toggles whether this package explorer links its selection to the active - * editor. - * - * @since 2.1 - */ -public class ToggleLinkingAction extends AbstractToggleLinkingAction { - - CBrowsingPart fCBrowsingPart; - - /** - * Constructs a new action. - */ - public ToggleLinkingAction(CBrowsingPart part) { - setChecked(part.isLinkingEnabled()); - fCBrowsingPart= part; - } - - /** - * Runs the action. - */ - public void run() { - fCBrowsingPart.setLinkingEnabled(isChecked()); - } - -} diff --git a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/cbrowsing/TypeInfoComparator.java b/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/cbrowsing/TypeInfoComparator.java deleted file mode 100644 index 634e6216bd5..00000000000 --- a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/cbrowsing/TypeInfoComparator.java +++ /dev/null @@ -1,86 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.browser.cbrowsing; - -import java.util.Comparator; - -import org.eclipse.cdt.core.browser.ITypeInfo; -import org.eclipse.cdt.core.model.ICElement; - -public class TypeInfoComparator implements Comparator { - /** - * Compares two ITypeInfo/ICElement types. A type is considered to be - * greater if it may contain the other. - * - * @return an int less than 0 if object1 is less than object2, - * 0 if they are equal, and > 0 if object1 is greater - * - * @see Comparator#compare(Object, Object) - */ - public int compare(Object o1, Object o2) { - int t1 = getElementType(o1); - int t2 = getElementType(o2); - return getIdForElementType(t1) - getIdForElementType(t2); - } - - /** - * Compares two C element types. A type is considered to be - * greater if it may contain the other. - * - * @return an int < 0 if object1 is less than object2, - * 0 if they are equal, and > 0 if object1 is greater - * - * @see Comparator#compare(Object, Object) - */ - public int compare(Object o1, int elementType) { - int t1 = getElementType(o1); - if (t1 == 0) - throw new ClassCastException(); - return getIdForElementType(t1) - getIdForElementType(elementType); - } - - int getElementType(Object obj) { - if (obj instanceof ICElement) { - return ((ICElement)obj).getElementType(); - } else if (obj instanceof ITypeInfo) { - return ((ITypeInfo)obj).getCElementType(); - } else { - return 0; - } - } - - int getIdForElementType(int elementType) { - switch (elementType) { - case ICElement.C_MODEL: - return 100; - case ICElement.C_PROJECT: - return 90; - case ICElement.C_CCONTAINER: - return 80; - case ICElement.C_UNIT: - return 70; - case ICElement.C_NAMESPACE: - return 60; - case ICElement.C_CLASS: - return 50; - case ICElement.C_STRUCT: - return 40; - case ICElement.C_UNION: - return 30; - case ICElement.C_ENUMERATION: - return 20; - case ICElement.C_TYPEDEF: - return 10; - default : - return 1; - } - } -} diff --git a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/cbrowsing/TypeInfoSorter.java b/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/cbrowsing/TypeInfoSorter.java deleted file mode 100644 index 5d0af6de217..00000000000 --- a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/cbrowsing/TypeInfoSorter.java +++ /dev/null @@ -1,79 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2003, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.browser.cbrowsing; - -import org.eclipse.cdt.core.browser.ITypeInfo; -import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.jface.viewers.Viewer; - -public class TypeInfoSorter extends CBrowsingViewerSorter { - - public TypeInfoSorter() { - super(); - } - - public int category (Object element) { - if (element instanceof ITypeInfo) { - ITypeInfo info = (ITypeInfo)element; - String name = info.getName(); - if (info.getCElementType() == ICElement.C_NAMESPACE) { - if (name.startsWith("__")) { //$NON-NLS-1$ - return NAMESPACES_SYSTEM; - } - if (name.charAt(0) == '_') { - return NAMESPACES_RESERVED; - } - return NAMESPACES; - } - if (name.startsWith("__")) { //$NON-NLS-1$ - return CELEMENTS_SYSTEM; - } - if (name.charAt(0) == '_') { - return CELEMENTS_RESERVED; - } - return CELEMENTS; - } - return super.category(element); - } - - public int compare(Viewer viewer, Object e1, Object e2) { - if (e1 instanceof ITypeInfo || e2 instanceof ITypeInfo) { - int cat1 = category(e1); - int cat2 = category(e2); - - if (cat1 != cat2) - return cat1 - cat2; - - // cat1 == cat2 - - if (cat1 == NAMESPACES || cat1 == CELEMENTS || cat1 == CELEMENTS_SYSTEM || cat1 == CELEMENTS_RESERVED) { - String name1; - String name2; - if (e1 instanceof ICElement) { - name1 = ((ICElement)e1).getElementName(); - } else if (e1 instanceof ITypeInfo) { - name1 = ((ITypeInfo)e1).getName(); - } else { - name1 = e1.toString(); - } - if (e2 instanceof ICElement) { - name2 = ((ICElement)e2).getElementName(); - } else if (e2 instanceof ITypeInfo) { - name2 = ((ITypeInfo)e2).getName(); - } else { - name2 = e2.toString(); - } - return getCollator().compare(name1, name2); - } - } - return super.compare(viewer, e1, e2); - } -} diff --git a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/cbrowsing/TypesView.java b/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/cbrowsing/TypesView.java deleted file mode 100644 index 01a6cb6cb72..00000000000 --- a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/cbrowsing/TypesView.java +++ /dev/null @@ -1,243 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.browser.cbrowsing; - -import org.eclipse.cdt.core.browser.AllTypesCache; -import org.eclipse.cdt.core.browser.ITypeInfo; -import org.eclipse.cdt.core.browser.TypeUtil; -import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.cdt.core.model.ICModel; -import org.eclipse.cdt.core.model.ICProject; -import org.eclipse.cdt.core.model.INamespace; -import org.eclipse.cdt.core.model.ISourceRoot; -import org.eclipse.cdt.core.model.ITranslationUnit; -import org.eclipse.cdt.internal.ui.ICHelpContextIds; -import org.eclipse.cdt.ui.CUIPlugin; -import org.eclipse.cdt.ui.PreferenceConstants; -import org.eclipse.core.resources.IProject; -import org.eclipse.jface.viewers.IContentProvider; -import org.eclipse.jface.viewers.LabelProvider; -import org.eclipse.jface.viewers.StructuredViewer; -import org.eclipse.jface.viewers.ViewerSorter; -import org.eclipse.swt.SWT; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.ui.IActionBars; -import org.eclipse.ui.IPageLayout; -import org.eclipse.ui.part.IShowInTargetList; - -public class TypesView extends CBrowsingPart { - -// private SelectAllAction fSelectAllAction; - - /** - * Creates and returns the label provider for this part. - * - * @return the label provider - * @see org.eclipse.jface.viewers.ILabelProvider - */ - protected LabelProvider createLabelProvider() { - return new TypesViewLabelProvider(); - } - - /** - * Answer the property defined by key. - */ - public Object getAdapter(Class key) { - if (key == IShowInTargetList.class) { - return new IShowInTargetList() { - public String[] getShowInTargetIds() { - return new String[] { CUIPlugin.CVIEW_ID, IPageLayout.ID_RES_NAV }; - } - - }; - } - return super.getAdapter(key); - } - - /** - * Creates the viewer of this part dependent on the current - * layout. - * - * @param parent the parent for the viewer - */ - protected StructuredViewer createViewer(Composite parent) { - StructuredViewer viewer; -// if(isInListState()) - viewer= createTableViewer(parent); -// else -// viewer= createTreeViewer(parent); - -// fWrappedViewer.setViewer(viewer); -// return fWrappedViewer; - return viewer; - } - private ElementTableViewer createTableViewer(Composite parent) { - return new ElementTableViewer(parent, SWT.MULTI); - } - - /** - * Creates the the content provider of this part. - */ - protected IContentProvider createContentProvider() { - return new TypesViewContentProvider(this); - } - - protected ViewerSorter createViewerSorter() { - return new TypeInfoSorter(); - } - - /** - * Adds filters the viewer of this part. - */ - protected void addFilters() { - super.addFilters(); - getViewer().addFilter(new CBrowsingElementFilter()); - } - - /** - * Answers if the given element is a valid - * input for this part. - * - * @param element the object to test - * @return if the given element is a valid input - */ - protected boolean isValidInput(Object element) { - if (element instanceof ITypeInfo) { - ITypeInfo info = (ITypeInfo)element; - return (info.exists() && info.getCElementType() == ICElement.C_NAMESPACE); - } - return false; - } - - /** - * Answers if the given element is a valid - * element for this part. - * - * @param element the object to test - * @return if the given element is a valid element - */ - protected boolean isValidElement(Object element) { - if (element instanceof ITypeInfo) { - ITypeInfo info = (ITypeInfo)element; - if (info.exists()) { - switch (info.getCElementType()) { - case ICElement.C_CLASS: - case ICElement.C_STRUCT: - return true; - } - } - } - return false; - } - - /** - * Returns the context ID for the Help system - * - * @return the string used as ID for the Help context - */ - protected String getHelpContextId() { - return ICHelpContextIds.TYPES_VIEW; - } - - protected String getLinkToEditorKey() { - return PreferenceConstants.LINK_BROWSING_TYPES_TO_EDITOR; - } - - protected void createActions() { - super.createActions(); -// fSelectAllAction= new SelectAllAction((TableViewer)getViewer()); - } - - protected void fillActionBars(IActionBars actionBars) { - super.fillActionBars(actionBars); - - // Add selectAll action handlers. -// actionBars.setGlobalActionHandler(IWorkbenchActionConstants.SELECT_ALL, fSelectAllAction); - } - - /* (non-Javadoc) - * @see org.eclipse.cdt.internal.ui.browser.cbrowsing.CBrowsingPart#findInputForElement(java.lang.Object) - */ - protected Object findInputForElement(Object element) { - if (element instanceof ICModel || element instanceof ICProject || element instanceof ISourceRoot) { - return null; - } - - if (element instanceof ICElement) { - ICElement celem = (ICElement) element; - if (celem instanceof ITranslationUnit) { - IProject project = celem.getCProject().getProject(); - return AllTypesCache.getGlobalNamespace(project); - } else if (celem.getElementType() == ICElement.C_NAMESPACE) { - return AllTypesCache.getTypeForElement(celem, true, true, null); - } else { - ICElement parent = TypeUtil.getDeclaringType(celem); - if (parent instanceof INamespace) { - return AllTypesCache.getTypeForElement(parent, true, true, null); - } else if (parent != null) { - ITypeInfo info = AllTypesCache.getTypeForElement(parent, true, true, null); - if (info != null) - return info.getEnclosingNamespace(true); - } - IProject project = celem.getCProject().getProject(); - return AllTypesCache.getGlobalNamespace(project); - } - } - - if (element instanceof ITypeInfo) { - ITypeInfo info = (ITypeInfo) element; - if (info.getCElementType() == ICElement.C_NAMESPACE) { - if (exists(info)) - return info; - return null; - } - return info.getEnclosingNamespace(true); - } - - return null; - } - - /* (non-Javadoc) - * @see org.eclipse.cdt.internal.ui.browser.cbrowsing.CBrowsingPart#findElementToSelect(java.lang.Object) - */ - protected Object findElementToSelect(Object element) { - if (element instanceof ICModel || element instanceof ICProject || element instanceof ISourceRoot) { - return null; - } - - if (element instanceof ICElement) { - ICElement celem = (ICElement) element; - if (celem instanceof ITranslationUnit) { - return null; - } else if (celem.getElementType() == ICElement.C_NAMESPACE) { - return null; - } else { - while (celem != null) { - ICElement parent = TypeUtil.getDeclaringType(celem); - if (parent == null || parent instanceof INamespace) { - return AllTypesCache.getTypeForElement(celem, true, true, null); - } - celem = parent; - } - } - } - - if (element instanceof ITypeInfo) { - ITypeInfo info = (ITypeInfo) element; - if (info.getCElementType() != ICElement.C_NAMESPACE) { - return info; - } - return null; - } - - return null; - } -} diff --git a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/cbrowsing/TypesViewContentProvider.java b/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/cbrowsing/TypesViewContentProvider.java deleted file mode 100644 index 4adfb74ae04..00000000000 --- a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/cbrowsing/TypesViewContentProvider.java +++ /dev/null @@ -1,112 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.browser.cbrowsing; - -import org.eclipse.cdt.core.browser.ITypeInfo; -import org.eclipse.cdt.core.model.ICElement; - -class TypesViewContentProvider extends CBrowsingContentProvider { - - TypesViewContentProvider(CBrowsingPart browsingPart) { - super(browsingPart); - } - - /* (non-Javadoc) - * @see org.eclipse.jface.viewers.ITreeContentProvider#hasChildren(java.lang.Object) - */ - public boolean hasChildren(Object element) { - if (element == null || (element instanceof ITypeInfo && !((ITypeInfo)element).exists())) { - return false; - } - - try { - startReadInDisplayThread(); - - if (element instanceof ITypeInfo) { - ITypeInfo info = (ITypeInfo)element; - return info.hasEnclosedTypes(); - } - - return false; -// } catch (CModelException e) { -// return false; - } finally { - finishedReadInDisplayThread(); - } - } - - /* (non-Javadoc) - * @see org.eclipse.jface.viewers.ITreeContentProvider#getChildren(java.lang.Object) - */ - public Object[] getChildren(Object element) { - if (element == null || (element instanceof ITypeInfo && !((ITypeInfo)element).exists())) { - return INVALID_INPUT; - } - - try { - startReadInDisplayThread(); - - if (element instanceof ITypeInfo) { - ITypeInfo info = (ITypeInfo)element; - final int kinds[] = { ICElement.C_CLASS, ICElement.C_STRUCT, - ICElement.C_UNION, ICElement.C_ENUMERATION, - ICElement.C_TYPEDEF}; - //TODO this should be a prefs option - ITypeInfo[] children = info.getEnclosedTypes(kinds); - if (children != null && children.length > 0) { - return children; - } - return EMPTY_CHILDREN; - } - - return INVALID_INPUT; -// } catch (CModelException e) { -// return NO_CHILDREN; - } finally { - finishedReadInDisplayThread(); - } - } - - /* (non-Javadoc) - * @see org.eclipse.jface.viewers.ITreeContentProvider#getParent(java.lang.Object) - */ - public Object getParent(Object element) { - if (element == null || (element instanceof ITypeInfo && !((ITypeInfo)element).exists())) { - return null; - } - - try { - startReadInDisplayThread(); - - if (element instanceof ITypeInfo) { - ITypeInfo info = (ITypeInfo)element; - if (info.isEnclosedType()) { - return info.getEnclosingType(); - } -// return info.getEnclosingProject(); - return null; - } - - return null; -// } catch (CModelException e) { -// return false; - } finally { - finishedReadInDisplayThread(); - } - } - - /* (non-Javadoc) - * @see org.eclipse.jface.viewers.IStructuredContentProvider#getElements(java.lang.Object) - */ - public Object[] getElements(Object inputElement) { - return getChildren(inputElement); - } -} diff --git a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/cbrowsing/TypesViewLabelProvider.java b/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/cbrowsing/TypesViewLabelProvider.java deleted file mode 100644 index 9db7b1444ef..00000000000 --- a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/cbrowsing/TypesViewLabelProvider.java +++ /dev/null @@ -1,36 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 QNX Software Systems and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * QNX Software Systems - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.browser.cbrowsing; - -import org.eclipse.cdt.core.browser.ITypeInfo; -import org.eclipse.cdt.ui.browser.typeinfo.TypeInfoLabelProvider; -import org.eclipse.swt.graphics.Image; - -public class TypesViewLabelProvider extends CBrowsingLabelProvider { - - protected static final TypeInfoLabelProvider fTypeInfoLabelProvider = new TypeInfoLabelProvider(TypeInfoLabelProvider.SHOW_TYPE_ONLY); - - public TypesViewLabelProvider() { - super(); - } - - public Image getImage(Object element) { - if (element instanceof ITypeInfo) - return fTypeInfoLabelProvider.getImage(element); - return super.getImage(element); - } - - public String getText(Object element) { - if (element instanceof ITypeInfo) - return fTypeInfoLabelProvider.getText(element); - return super.getText(element); - } -} diff --git a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/opentype/OpenTypeAction.java b/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/opentype/OpenTypeAction.java index 6a878f42241..bb3952a5c29 100644 --- a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/opentype/OpenTypeAction.java +++ b/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/opentype/OpenTypeAction.java @@ -10,36 +10,12 @@ *******************************************************************************/ package org.eclipse.cdt.internal.ui.browser.opentype; -import java.lang.reflect.InvocationTargetException; -import org.eclipse.cdt.core.browser.AllTypesCache; -import org.eclipse.cdt.core.browser.ITypeInfo; -import org.eclipse.cdt.core.browser.ITypeReference; -import org.eclipse.cdt.core.browser.ITypeSearchScope; -import org.eclipse.cdt.core.browser.TypeSearchScope; -import org.eclipse.cdt.core.model.CModelException; -import org.eclipse.cdt.core.model.ITranslationUnit; -import org.eclipse.cdt.core.resources.FileStorage; -import org.eclipse.cdt.internal.ui.util.EditorUtility; -import org.eclipse.cdt.internal.ui.util.ExceptionHandler; import org.eclipse.cdt.ui.CUIPlugin; -import org.eclipse.core.resources.IStorage; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jface.action.IAction; -import org.eclipse.jface.dialogs.IDialogConstants; -import org.eclipse.jface.dialogs.MessageDialog; -import org.eclipse.jface.operation.IRunnableWithProgress; -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.IDocument; import org.eclipse.jface.viewers.ISelection; import org.eclipse.swt.widgets.Shell; -import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.IWorkbenchWindowActionDelegate; -import org.eclipse.ui.PartInitException; -import org.eclipse.ui.PlatformUI; -import org.eclipse.ui.progress.IProgressService; -import org.eclipse.ui.texteditor.ITextEditor; public class OpenTypeAction implements IWorkbenchWindowActionDelegate { @@ -53,148 +29,12 @@ public class OpenTypeAction implements IWorkbenchWindowActionDelegate { * @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction) */ public void run(IAction action) { - final ITypeSearchScope fScope = new TypeSearchScope(true); - if (!AllTypesCache.isCacheUpToDate(fScope)) { - IRunnableWithProgress runnable = new IRunnableWithProgress() { - public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { - AllTypesCache.updateCache(fScope, monitor); - if (monitor.isCanceled()) { - throw new InterruptedException(); - } - } - }; - - IProgressService service = PlatformUI.getWorkbench().getProgressService(); - try { - service.busyCursorWhile(runnable); - } catch (InvocationTargetException e) { - String title = OpenTypeMessages.getString("OpenTypeAction.exception.title"); //$NON-NLS-1$ - String message = OpenTypeMessages.getString("OpenTypeAction.exception.message"); //$NON-NLS-1$ - ExceptionHandler.handle(e, title, message); - return; - } catch (InterruptedException e) { - // cancelled by user - return; - } - } - - ITypeInfo[] elements = AllTypesCache.getAllTypes(); - if (elements.length == 0) { - String title = OpenTypeMessages.getString("OpenTypeAction.notypes.title"); //$NON-NLS-1$ - String message = OpenTypeMessages.getString("OpenTypeAction.notypes.message"); //$NON-NLS-1$ - MessageDialog.openInformation(getShell(), title, message); - return; - } - - OpenTypeDialog dialog = new OpenTypeDialog(getShell()); - dialog.setElements(elements); - int result = dialog.open(); - if (result != IDialogConstants.OK_ID) - return; - - ITypeInfo info = (ITypeInfo) dialog.getFirstResult(); - if (info == null) - return; - - ITypeReference location = info.getResolvedReference(); - if (location == null) { - final ITypeInfo[] typesToResolve = new ITypeInfo[] { info }; - IRunnableWithProgress runnable = new IRunnableWithProgress() { - public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { - AllTypesCache.resolveTypeLocation(typesToResolve[0], monitor); - if (monitor.isCanceled()) { - throw new InterruptedException(); - } - } - }; - - IProgressService service = PlatformUI.getWorkbench().getProgressService(); - try { - service.busyCursorWhile(runnable); - } catch (InvocationTargetException e) { - String title = OpenTypeMessages.getString("OpenTypeAction.exception.title"); //$NON-NLS-1$ - String message = OpenTypeMessages.getString("OpenTypeAction.exception.message"); //$NON-NLS-1$ - ExceptionHandler.handle(e, title, message); - return; - } catch (InterruptedException e) { - // cancelled by user - return; - } - - location = info.getResolvedReference(); - } - - if (location == null) { - // could not resolve location - String title = OpenTypeMessages.getString("OpenTypeAction.errorTitle"); //$NON-NLS-1$ - String message = OpenTypeMessages.getFormattedString("OpenTypeAction.errorTypeNotFound", info.getQualifiedTypeName().toString()); //$NON-NLS-1$ - MessageDialog.openError(getShell(), title, message); - } else if (!openTypeInEditor(location)) { - // error opening editor - String title = OpenTypeMessages.getString("OpenTypeAction.errorTitle"); //$NON-NLS-1$ - String message = OpenTypeMessages.getFormattedString("OpenTypeAction.errorOpenEditor", location.getPath().toString()); //$NON-NLS-1$ - MessageDialog.openError(getShell(), title, message); - } } protected Shell getShell() { return CUIPlugin.getActiveWorkbenchShell(); } - /** - * Opens an editor and displays the selected type. - * - * @param info Type to display. - * @return true if succesfully displayed. - */ - private boolean openTypeInEditor(ITypeReference location) { - ITranslationUnit unit = location.getTranslationUnit(); - IEditorPart editorPart = null; - - try { - if (unit != null) - editorPart = EditorUtility.openInEditor(unit); - if (editorPart == null) { - // open as external file - IPath path = location.getLocation(); - if (path != null) { - IStorage storage = new FileStorage(path); - editorPart = EditorUtility.openInEditor(storage); - } - } - - // highlight the type in the editor - if (editorPart != null && editorPart instanceof ITextEditor) { - ITextEditor editor = (ITextEditor) editorPart; - if( location.isLineNumber() ) - { - IDocument document= editor.getDocumentProvider().getDocument(editor.getEditorInput()); - try - { - int startOffset = document.getLineOffset(location.getOffset()-1); - int length=document.getLineLength(location.getOffset()-1); - editor.selectAndReveal(startOffset, length); - return true; - } - catch( BadLocationException ble ) - { - return false; - } - } - editor.selectAndReveal(location.getOffset(), location.getLength()); - return true; - } - } catch (CModelException ex) { - ex.printStackTrace(); - return false; - } catch (PartInitException ex) { - ex.printStackTrace(); - return false; - } - - return false; - } - /* * (non-Javadoc) * diff --git a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/CHierarchyPerspectiveFactory.java b/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/CHierarchyPerspectiveFactory.java deleted file mode 100644 index 30c9471f820..00000000000 --- a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/CHierarchyPerspectiveFactory.java +++ /dev/null @@ -1,67 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ - -package org.eclipse.cdt.internal.ui.browser.typehierarchy; - -import org.eclipse.cdt.ui.CUIPlugin; -import org.eclipse.search.ui.NewSearchUI; -import org.eclipse.ui.IFolderLayout; -import org.eclipse.ui.IPageLayout; -import org.eclipse.ui.IPerspectiveFactory; -import org.eclipse.ui.IPlaceholderFolderLayout; -import org.eclipse.ui.console.IConsoleConstants; - -public class CHierarchyPerspectiveFactory implements IPerspectiveFactory { - - /** - * Constructs a new Java hierarchy layout engine. - */ - public CHierarchyPerspectiveFactory() { - super(); - } - - public void createInitialLayout(IPageLayout layout) { - String editorArea = layout.getEditorArea(); - - IFolderLayout folder= layout.createFolder("left", IPageLayout.LEFT, (float)0.25, editorArea); //$NON-NLS-1$ - folder.addView(CUIPlugin.ID_TYPE_HIERARCHY); - folder.addPlaceholder(IPageLayout.ID_OUTLINE); - folder.addPlaceholder(CUIPlugin.CVIEW_ID); - folder.addPlaceholder(IPageLayout.ID_RES_NAV); - - IPlaceholderFolderLayout outputfolder= layout.createPlaceholderFolder("bottom", IPageLayout.BOTTOM, (float)0.75, editorArea); //$NON-NLS-1$ - outputfolder.addPlaceholder(IPageLayout.ID_PROBLEM_VIEW); - outputfolder.addPlaceholder(NewSearchUI.SEARCH_VIEW_ID); - outputfolder.addPlaceholder(IConsoleConstants.ID_CONSOLE_VIEW); - outputfolder.addPlaceholder(IPageLayout.ID_BOOKMARKS); -// outputfolder.addPlaceholder(CUIPlugin.ID_SOURCE_VIEW); -// outputfolder.addPlaceholder(CUIPlugin.ID_JAVADOC_VIEW); -// outputfolder.addPlaceholder(CPerspectiveFactory.ID_PROGRESS_VIEW); - -// layout.addActionSet(IDebugUIConstants.LAUNCH_ACTION_SET); -// layout.addActionSet(JavaUI.ID_ACTION_SET); -// layout.addActionSet(JavaUI.ID_ELEMENT_CREATION_ACTION_SET); - - // views - java - layout.addShowViewShortcut(CUIPlugin.CVIEW_ID); - layout.addShowViewShortcut(CUIPlugin.ID_TYPE_HIERARCHY); - - layout.addShowViewShortcut(NewSearchUI.SEARCH_VIEW_ID); - - // views - debugging - layout.addShowViewShortcut(IConsoleConstants.ID_CONSOLE_VIEW); - - // views - standard workbench - layout.addShowViewShortcut(IPageLayout.ID_OUTLINE); - layout.addShowViewShortcut(IPageLayout.ID_PROBLEM_VIEW); - layout.addShowViewShortcut(IPageLayout.ID_RES_NAV); - } -} diff --git a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/EnableMemberFilterAction.java b/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/EnableMemberFilterAction.java deleted file mode 100644 index c3d1c3f5bc6..00000000000 --- a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/EnableMemberFilterAction.java +++ /dev/null @@ -1,49 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.browser.typehierarchy; - -import org.eclipse.cdt.internal.ui.CPluginImages; -import org.eclipse.cdt.internal.ui.ICHelpContextIds; -import org.eclipse.jface.action.Action; -import org.eclipse.swt.custom.BusyIndicator; -import org.eclipse.ui.help.WorkbenchHelp; - -/** - * Action enable / disable member filtering - */ -public class EnableMemberFilterAction extends Action { - - TypeHierarchyViewPart fView; - - public EnableMemberFilterAction(TypeHierarchyViewPart v, boolean initValue) { - super(TypeHierarchyMessages.getString("EnableMemberFilterAction.label")); //$NON-NLS-1$ - setDescription(TypeHierarchyMessages.getString("EnableMemberFilterAction.description")); //$NON-NLS-1$ - setToolTipText(TypeHierarchyMessages.getString("EnableMemberFilterAction.tooltip")); //$NON-NLS-1$ - - CPluginImages.setImageDescriptors(this, CPluginImages.T_LCL, "impl_co.gif"); //$NON-NLS-1$ - - fView= v; - setChecked(initValue); - - WorkbenchHelp.setHelp(this, ICHelpContextIds.ENABLE_METHODFILTER_ACTION); - } - - /* - * @see Action#actionPerformed - */ - public void run() { - BusyIndicator.showWhile(fView.getSite().getShell().getDisplay(), new Runnable() { - public void run() { - fView.enableMemberFilter(isChecked()); - } - }); - } -} diff --git a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/FocusOnSelectionAction.java b/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/FocusOnSelectionAction.java deleted file mode 100644 index 0ddc16fbd74..00000000000 --- a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/FocusOnSelectionAction.java +++ /dev/null @@ -1,69 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.browser.typehierarchy; - -import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.cdt.internal.ui.ICHelpContextIds; -import org.eclipse.cdt.internal.ui.util.SelectionUtil; -import org.eclipse.cdt.internal.ui.viewsupport.CElementLabels; -import org.eclipse.jface.action.Action; -import org.eclipse.jface.viewers.ISelection; -import org.eclipse.jface.viewers.ISelectionProvider; - -import org.eclipse.ui.help.WorkbenchHelp; - -/** - * Refocuses the type hierarchy on the currently selection type. - */ -public class FocusOnSelectionAction extends Action { - - private TypeHierarchyViewPart fViewPart; - - public FocusOnSelectionAction(TypeHierarchyViewPart part) { - super(TypeHierarchyMessages.getString("FocusOnSelectionAction.label")); //$NON-NLS-1$ - setDescription(TypeHierarchyMessages.getString("FocusOnSelectionAction.description")); //$NON-NLS-1$ - setToolTipText(TypeHierarchyMessages.getString("FocusOnSelectionAction.tooltip")); //$NON-NLS-1$ - fViewPart= part; - - WorkbenchHelp.setHelp(this, ICHelpContextIds.FOCUS_ON_SELECTION_ACTION); - } - - private ISelection getSelection() { - ISelectionProvider provider= fViewPart.getSite().getSelectionProvider(); - if (provider != null) { - return provider.getSelection(); - } - return null; - } - - - /* - * @see Action#run - */ - public void run() { - Object element= SelectionUtil.getSingleElement(getSelection()); - if (element instanceof ICElement) { - fViewPart.setInputElement((ICElement)element); - } - } - - public boolean canActionBeAdded() { - Object element= SelectionUtil.getSingleElement(getSelection()); - if (element instanceof ICElement) { - ICElement type= (ICElement)element; - setText(TypeHierarchyMessages.getFormattedString( - "FocusOnSelectionAction.label", //$NON-NLS-1$ - CElementLabels.getTextLabel(type, 0))); - return true; - } - return false; - } -} diff --git a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/FocusOnTypeAction.java b/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/FocusOnTypeAction.java deleted file mode 100644 index 4f3223dd725..00000000000 --- a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/FocusOnTypeAction.java +++ /dev/null @@ -1,133 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.browser.typehierarchy; - -import java.lang.reflect.InvocationTargetException; - -import org.eclipse.cdt.core.browser.AllTypesCache; -import org.eclipse.cdt.core.browser.ITypeInfo; -import org.eclipse.cdt.core.browser.ITypeSearchScope; -import org.eclipse.cdt.core.browser.TypeSearchScope; -import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.cdt.internal.ui.ICHelpContextIds; -import org.eclipse.cdt.internal.ui.browser.opentype.OpenTypeMessages; -import org.eclipse.cdt.internal.ui.util.ExceptionHandler; -import org.eclipse.cdt.ui.CUIPlugin; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.jface.action.Action; -import org.eclipse.jface.dialogs.IDialogConstants; -import org.eclipse.jface.dialogs.MessageDialog; -import org.eclipse.jface.operation.IRunnableWithProgress; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.ui.PlatformUI; -import org.eclipse.ui.help.WorkbenchHelp; -import org.eclipse.ui.progress.IProgressService; - -/** - * Refocuses the type hierarchy on a type selection from a all types dialog. - */ -public class FocusOnTypeAction extends Action { - - private TypeHierarchyViewPart fViewPart; - - public FocusOnTypeAction(TypeHierarchyViewPart part) { - super(TypeHierarchyMessages.getString("FocusOnTypeAction.label")); //$NON-NLS-1$ - setDescription(TypeHierarchyMessages.getString("FocusOnTypeAction.description")); //$NON-NLS-1$ - setToolTipText(TypeHierarchyMessages.getString("FocusOnTypeAction.tooltip")); //$NON-NLS-1$ - - fViewPart= part; - WorkbenchHelp.setHelp(this, ICHelpContextIds.FOCUS_ON_TYPE_ACTION); - } - - /* - * @see Action#run - */ - public void run() { - - final ITypeSearchScope fScope = new TypeSearchScope(true); - if (!AllTypesCache.isCacheUpToDate(fScope)) { - IRunnableWithProgress runnable = new IRunnableWithProgress() { - public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { - AllTypesCache.updateCache(fScope, monitor); - if (monitor.isCanceled()) { - throw new InterruptedException(); - } - } - }; - - IProgressService service = PlatformUI.getWorkbench().getProgressService(); - try { - service.busyCursorWhile(runnable); - } catch (InvocationTargetException e) { - String title = OpenTypeMessages.getString("OpenTypeAction.exception.title"); //$NON-NLS-1$ - String message = OpenTypeMessages.getString("OpenTypeAction.exception.message"); //$NON-NLS-1$ - ExceptionHandler.handle(e, title, message); - return; - } catch (InterruptedException e) { - // cancelled by user - return; - } - } - - final int[] kinds = {ICElement.C_CLASS, ICElement.C_STRUCT}; - ITypeInfo[] elements = AllTypesCache.getTypes(fScope, kinds); - if (elements.length == 0) { - String title = OpenTypeMessages.getString("OpenTypeAction.notypes.title"); //$NON-NLS-1$ - String message = OpenTypeMessages.getString("OpenTypeAction.notypes.message"); //$NON-NLS-1$ - MessageDialog.openInformation(getShell(), title, message); - return; - } - - FocusOnTypeDialog dialog = new FocusOnTypeDialog(getShell()); - dialog.setElements(elements); - int result = dialog.open(); - if (result != IDialogConstants.OK_ID) - return; - - ITypeInfo info = (ITypeInfo) dialog.getFirstResult(); - if (info == null) - return; - - final ITypeInfo[] typesToResolve = new ITypeInfo[] { info }; - final ICElement[] foundElement = new ICElement[] { null }; - IRunnableWithProgress runnable = new IRunnableWithProgress() { - public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { - foundElement[0] = AllTypesCache.getElementForType(typesToResolve[0], true, true, monitor); - } - }; - - IProgressService service = PlatformUI.getWorkbench().getProgressService(); - try { - service.busyCursorWhile(runnable); - } catch (InvocationTargetException e) { - String title = OpenTypeMessages.getString("OpenTypeAction.exception.title"); //$NON-NLS-1$ - String message = OpenTypeMessages.getString("OpenTypeAction.exception.message"); //$NON-NLS-1$ - ExceptionHandler.handle(e, title, message); - return; - } catch (InterruptedException e) { - // cancelled by user - return; - } - - if (foundElement[0] == null) { - // could not resolve location - String title = OpenTypeMessages.getString("OpenTypeAction.errorTitle"); //$NON-NLS-1$ - String message = OpenTypeMessages.getFormattedString("OpenTypeAction.errorTypeNotFound", info.getQualifiedTypeName().toString()); //$NON-NLS-1$ - MessageDialog.openError(getShell(), title, message); - } else { - fViewPart.setInputElement(foundElement[0]); - } - } - - protected Shell getShell() { - return CUIPlugin.getActiveWorkbenchShell(); - } -} diff --git a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/FocusOnTypeDialog.java b/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/FocusOnTypeDialog.java deleted file mode 100644 index 200ec830e4e..00000000000 --- a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/FocusOnTypeDialog.java +++ /dev/null @@ -1,39 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * QNX Software Systems - adapted for use in CDT - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.browser.typehierarchy; - -import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.cdt.ui.browser.typeinfo.TypeSelectionDialog; -import org.eclipse.swt.widgets.Shell; - -/** - * A dialog to select a type from a list of types. The selected type will be - * opened in the editor. - */ -public class FocusOnTypeDialog extends TypeSelectionDialog { - - private static final String DIALOG_SETTINGS = FocusOnTypeDialog.class.getName(); - - private final int[] VISIBLE_TYPES = { ICElement.C_CLASS, ICElement.C_STRUCT }; - - /** - * Constructs an instance of OpenTypeDialog. - * @param parent the parent shell. - */ - public FocusOnTypeDialog(Shell parent) { - super(parent); - setTitle(TypeHierarchyMessages.getString("FocusOnTypeAction.dialog.title")); //$NON-NLS-1$ - setMessage(TypeHierarchyMessages.getString("FocusOnTypeAction.dialog.message")); //$NON-NLS-1$ - setVisibleTypes(VISIBLE_TYPES); - setDialogSettings(DIALOG_SETTINGS); - } -} diff --git a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/HierarchyLabelProvider.java b/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/HierarchyLabelProvider.java deleted file mode 100644 index 541e5476376..00000000000 --- a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/HierarchyLabelProvider.java +++ /dev/null @@ -1,193 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.browser.typehierarchy; - -import org.eclipse.cdt.core.browser.TypeUtil; -import org.eclipse.cdt.core.browser.typehierarchy.ITypeHierarchy; -import org.eclipse.cdt.core.model.CModelException; -import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.cdt.core.model.IMethod; -import org.eclipse.cdt.core.model.IMethodDeclaration; -import org.eclipse.cdt.core.model.IStructure; -import org.eclipse.cdt.internal.ui.CPluginImages; -import org.eclipse.cdt.internal.ui.viewsupport.CElementImageProvider; -import org.eclipse.cdt.internal.ui.viewsupport.StandardCElementLabelProvider; -import org.eclipse.cdt.ui.CElementImageDescriptor; -import org.eclipse.cdt.ui.CUIPlugin; -import org.eclipse.jface.resource.CompositeImageDescriptor; -import org.eclipse.jface.resource.ImageDescriptor; -import org.eclipse.jface.viewers.ViewerFilter; -import org.eclipse.swt.SWT; -import org.eclipse.swt.graphics.Color; -import org.eclipse.swt.graphics.Image; -import org.eclipse.swt.graphics.ImageData; -import org.eclipse.swt.graphics.Point; -import org.eclipse.swt.widgets.Display; - -/** - * Label provider for the hierarchy viewers. Types in the hierarchy that are not belonging to the - * input scope are rendered differntly. - */ -public class HierarchyLabelProvider extends StandardCElementLabelProvider // AppearanceAwareLabelProvider { -{ - private static class FocusDescriptor extends CompositeImageDescriptor { - private ImageDescriptor fBase; - public FocusDescriptor(ImageDescriptor base) { - fBase= base; - } - protected void drawCompositeImage(int width, int height) { - drawImage(getImageData(fBase), 0, 0); - drawImage(getImageData(CPluginImages.DESC_OVR_FOCUS), 0, 0); - } - - private ImageData getImageData(ImageDescriptor descriptor) { - ImageData data= descriptor.getImageData(); // see bug 51965: getImageData can return null - if (data == null) { - data= DEFAULT_IMAGE_DATA; - CUIPlugin.getDefault().logErrorMessage("Image data not available: " + descriptor.toString()); //$NON-NLS-1$ - } - return data; - } - - protected Point getSize() { - return CElementImageProvider.BIG_SIZE; - } - public int hashCode() { - return fBase.hashCode(); - } - public boolean equals(Object object) { - return object != null && FocusDescriptor.class.equals(object.getClass()) && ((FocusDescriptor)object).fBase.equals(fBase); - } - } - - private Color fGrayedColor; - private Color fSpecialColor; - - private ViewerFilter fFilter; - - private TypeHierarchyLifeCycle fHierarchy; - - public HierarchyLabelProvider(TypeHierarchyLifeCycle lifeCycle) { -// super(DEFAULT_TEXTFLAGS, DEFAULT_IMAGEFLAGS); - super(); - fHierarchy= lifeCycle; - fFilter= null; - } - - - /** - * @return Returns the filter. - */ - public ViewerFilter getFilter() { - return fFilter; - } - - /** - * @param filter The filter to set. - */ - public void setFilter(ViewerFilter filter) { - fFilter= filter; - } - - protected boolean isDifferentScope(ICElement type) { - if (fFilter != null && !fFilter.select(null, null, type)) { - return true; - } - - ICElement input= fHierarchy.getInputElement(); - if (input == null || TypeUtil.isClassOrStruct(input)) { - return false; - } - - ICElement parent= type.getAncestor(input.getElementType()); - if (input.getElementType() == ICElement.C_CCONTAINER) { - if (parent == null || parent.getElementName().equals(input.getElementName())) { - return false; - } - } else if (input.equals(parent)) { - return false; - } - return true; - } - - /* (non-Javadoc) - * @see ILabelProvider#getImage - */ - public Image getImage(Object element) { - Image result= null; - if (element instanceof ICElement) { - ImageDescriptor desc= getTypeImageDescriptor((ICElement) element); - if (desc != null) { - if (element.equals(fHierarchy.getInputElement())) { - desc= new FocusDescriptor(desc); - } - result= CUIPlugin.getImageDescriptorRegistry().get(desc); - } - } else { - result= fImageLabelProvider.getImageLabel(element, getImageFlags()); - } - return result; - } - - private ImageDescriptor getTypeImageDescriptor(ICElement type) { - ITypeHierarchy hierarchy= fHierarchy.getHierarchy(); - if (hierarchy == null) { - return new CElementImageDescriptor(CPluginImages.DESC_OBJS_CLASS, 0, CElementImageProvider.BIG_SIZE); - } - - ImageDescriptor desc; - if (isDifferentScope(type)) { - desc = CElementImageProvider.getClassImageDescriptor(); - } else { - desc= fImageLabelProvider.getBaseImageDescriptor(type, 0); - } - - int adornmentFlags= 0; - if (type instanceof IMethodDeclaration) { - IMethodDeclaration method = (IMethodDeclaration) type; - try { - if (method.isStatic()) - adornmentFlags |= CElementImageDescriptor.STATIC; -// if (method.isVirtual()) -// adornmentFlags |= CElementImageDescriptor.VIRTUAL; - } catch (CModelException e) { - } - } - - if (type instanceof IStructure) { -// hierarchy.getSupertypes(type); -// TypeCacheManager.getInstance().getCache(type.getCProject().getProject()).getSupertypeAccess(); - } - - return new CElementImageDescriptor(desc, adornmentFlags, CElementImageProvider.BIG_SIZE); - } - - /* (non-Javadoc) - * @see org.eclipse.jface.viewers.IColorProvider#getForeground(java.lang.Object) - */ - public Color getForeground(Object element) { - if (element instanceof IMethod) { - if (fSpecialColor == null) { - fSpecialColor= Display.getCurrent().getSystemColor(SWT.COLOR_DARK_BLUE); - } - return fSpecialColor; - } else if (element instanceof ICElement && isDifferentScope((ICElement) element)) { - if (fGrayedColor == null) { - fGrayedColor= Display.getCurrent().getSystemColor(SWT.COLOR_DARK_GRAY); - } - return fGrayedColor; - } - return null; - } - - - -} diff --git a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/HierarchyViewerSorter.java b/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/HierarchyViewerSorter.java deleted file mode 100644 index 77d35d1c18b..00000000000 --- a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/HierarchyViewerSorter.java +++ /dev/null @@ -1,180 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.browser.typehierarchy; - -import org.eclipse.cdt.core.browser.TypeUtil; -import org.eclipse.cdt.core.browser.typehierarchy.ITypeHierarchy; -import org.eclipse.cdt.core.model.CModelException; -import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.cdt.core.model.IMethodDeclaration; -import org.eclipse.cdt.core.parser.ast.ASTAccessVisibility; -import org.eclipse.cdt.ui.CElementSorter; -import org.eclipse.jface.viewers.Viewer; -import org.eclipse.jface.viewers.ViewerSorter; - -/** - */ -public class HierarchyViewerSorter extends ViewerSorter { - - private static final int OTHER= 0; - private static final int CLASS= 1; - private static final int FIELD= 2; - private static final int METHOD= 3; - - private TypeHierarchyLifeCycle fHierarchy; - private boolean fSortByDefiningType; - private CElementSorter fNormalSorter; - - public HierarchyViewerSorter(TypeHierarchyLifeCycle cycle) { - fHierarchy= cycle; - fNormalSorter= new CElementSorter(); - } - - /* (non-Javadoc) - * @see org.eclipse.jface.viewers.ViewerSorter#category(java.lang.Object) - */ -// public int category(Object element) { -// if (element instanceof ICElement) { -// ICElement type= (ICElement) element; -// ITypeHierarchy hierarchy= fHierarchy.getHierarchy(); -// if (hierarchy != null) { -// return CLASS; -// } -// } -// return OTHER; -// } - -// public boolean isSorterProperty(Object element, Object property) { -// return true; -// } - - public int category(Object obj) { - if (obj instanceof ICElement) { - ICElement elem= (ICElement)obj; - switch (elem.getElementType()) { - case ICElement.C_CLASS: - case ICElement.C_STRUCT: - return CLASS; -// case ICElement.C_UNION: -// return 3; - case ICElement.C_FIELD: - return FIELD; - - case ICElement.C_METHOD: - case ICElement.C_METHOD_DECLARATION: - return METHOD; -// { -// IMethodDeclaration method = (IMethodDeclaration) elem; -// try { -// // sort constructor and destructor first -// if (method.isConstructor() || method.isDestructor()) -// return 10; -// } catch (CModelException e) { -// } -// return 20; -// } - } - - } - return OTHER; - } - - public boolean isSortByDefiningType() { - return fSortByDefiningType; - } - - public void setSortByDefiningType(boolean sortByDefiningType) { - fSortByDefiningType= sortByDefiningType; - } - - /* (non-Javadoc) - * @see org.eclipse.jface.viewers.ViewerSorter#compare(null, null, null) - */ - public int compare(Viewer viewer, Object e1, Object e2) { - int cat1= category(e1); - int cat2= category(e2); - - if (cat1 != cat2) - return cat1 - cat2; - - ITypeHierarchy hierarchy= fHierarchy.getHierarchy(); - if (hierarchy == null) { - return fNormalSorter.compare(viewer, e1, e2); - } - - if (cat1 == FIELD || cat1 == METHOD) { // method or field - if (fSortByDefiningType) { - try { - ICElement def1= (e1 instanceof IMethodDeclaration) ? getDefiningType(hierarchy, (IMethodDeclaration) e1) : null; - ICElement def2= (e2 instanceof IMethodDeclaration) ? getDefiningType(hierarchy, (IMethodDeclaration) e2) : null; - if (def1 != null) { - if (def2 != null) { - if (!def2.equals(def1)) { - return compareInHierarchy(hierarchy, def1, def2); - } - } else { - return -1; - } - } else { - if (def2 != null) { - return 1; - } - } - } catch (CModelException e) { - // ignore, default to normal comparison - } - } - return fNormalSorter.compare(viewer, e1, e2); // use appearance pref page settings - } - String name1= ((ICElement) e1).getElementName(); //$NON-NLS-1$ - String name2= ((ICElement) e2).getElementName(); //$NON-NLS-1$ - return getCollator().compare(name1, name2); - } - - private ICElement getDefiningType(ITypeHierarchy hierarchy, IMethodDeclaration method) throws CModelException { - ICElement declaringType= TypeUtil.getDeclaringClass(method); - if ((method.getVisibility() == ASTAccessVisibility.PRIVATE) || method.isStatic() || method.isConstructor() || method.isDestructor()) { - return null; - } - - ICElement res= TypeUtil.findMethodDeclarationInHierarchy(hierarchy, declaringType, method.getElementName(), method.getParameterTypes(), false, false); - if (res == null || method.equals(res)) { - return null; - } - return TypeUtil.getDeclaringClass(res); - } - - - private int compareInHierarchy(ITypeHierarchy hierarchy, ICElement def1, ICElement def2) { - if (isSuperType(hierarchy, def1, def2)) { - return 1; - } else if (isSuperType(hierarchy, def2, def1)) { - return -1; - } - String name1= def1.getElementName(); - String name2= def2.getElementName(); - - return getCollator().compare(name1, name2); - } - - private boolean isSuperType(ITypeHierarchy hierarchy, ICElement def1, ICElement def2) { - ICElement[] superTypes= hierarchy.getSupertypes(def1); - if (superTypes != null) { - for (int i = 0; i < superTypes.length; ++i) { - if (superTypes[i].equals(def2) || isSuperType(hierarchy, superTypes[i], def2)) { - return true; - } - } - } - return false; - } - -} diff --git a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/HistoryAction.java b/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/HistoryAction.java deleted file mode 100644 index 6bed875b8c4..00000000000 --- a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/HistoryAction.java +++ /dev/null @@ -1,58 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.browser.typehierarchy; - -import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.cdt.internal.ui.ICHelpContextIds; -import org.eclipse.cdt.internal.ui.viewsupport.CElementImageProvider; -import org.eclipse.cdt.internal.ui.viewsupport.CElementLabels; -import org.eclipse.jface.action.Action; -import org.eclipse.jface.resource.ImageDescriptor; - -import org.eclipse.ui.help.WorkbenchHelp; - -/** - * Action used for the type hierarchy forward / backward buttons - */ -public class HistoryAction extends Action { - - private TypeHierarchyViewPart fViewPart; - private ICElement fElement; - - public HistoryAction(TypeHierarchyViewPart viewPart, ICElement element) { - super(); - fViewPart= viewPart; - fElement= element; - - String elementName= CElementLabels.getElementLabel(element, CElementLabels.ALL_POST_QUALIFIED | CElementLabels.M_PARAMETER_TYPES); - setText(elementName); - setImageDescriptor(getImageDescriptor(element)); - - setDescription(TypeHierarchyMessages.getFormattedString("HistoryAction.description", elementName)); //$NON-NLS-1$ - setToolTipText(TypeHierarchyMessages.getFormattedString("HistoryAction.tooltip", elementName)); //$NON-NLS-1$ - WorkbenchHelp.setHelp(this, ICHelpContextIds.HISTORY_ACTION); - } - - private ImageDescriptor getImageDescriptor(ICElement elem) { - CElementImageProvider imageProvider= new CElementImageProvider(); - ImageDescriptor desc= imageProvider.getBaseImageDescriptor(elem, 0); - imageProvider.dispose(); - return desc; - } - - /* - * @see Action#run() - */ - public void run() { - fViewPart.gotoHistoryEntry(fElement); - } - -} diff --git a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/HistoryDropDownAction.java b/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/HistoryDropDownAction.java deleted file mode 100644 index 63d83f90fc9..00000000000 --- a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/HistoryDropDownAction.java +++ /dev/null @@ -1,94 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.browser.typehierarchy; - -import org.eclipse.swt.SWT; -import org.eclipse.swt.widgets.Control; -import org.eclipse.swt.widgets.Menu; -import org.eclipse.swt.widgets.MenuItem; - -import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.cdt.internal.ui.CPluginImages; -import org.eclipse.cdt.internal.ui.ICHelpContextIds; -import org.eclipse.jface.action.Action; -import org.eclipse.jface.action.ActionContributionItem; -import org.eclipse.jface.action.IMenuCreator; - -import org.eclipse.ui.help.WorkbenchHelp; - -public class HistoryDropDownAction extends Action implements IMenuCreator { - - - public static final int RESULTS_IN_DROP_DOWN= 10; - - private TypeHierarchyViewPart fHierarchyView; - private Menu fMenu; - - public HistoryDropDownAction(TypeHierarchyViewPart view) { - fHierarchyView= view; - fMenu= null; - setToolTipText(TypeHierarchyMessages.getString("HistoryDropDownAction.tooltip")); //$NON-NLS-1$ - CPluginImages.setImageDescriptors(this, CPluginImages.T_LCL, "history_list.gif"); //$NON-NLS-1$ - WorkbenchHelp.setHelp(this, ICHelpContextIds.TYPEHIERARCHY_HISTORY_ACTION); - setMenuCreator(this); - } - - public void dispose() { - // action is reused, can be called several times. - if (fMenu != null) { - fMenu.dispose(); - fMenu= null; - } - } - - public Menu getMenu(Menu parent) { - return null; - } - - public Menu getMenu(Control parent) { - if (fMenu != null) { - fMenu.dispose(); - } - fMenu= new Menu(parent); - ICElement[] elements= fHierarchyView.getHistoryEntries(); - boolean checked= addEntries(fMenu, elements); - if (elements.length > RESULTS_IN_DROP_DOWN) { - new MenuItem(fMenu, SWT.SEPARATOR); - Action others= new HistoryListAction(fHierarchyView); - others.setChecked(checked); - addActionToMenu(fMenu, others); - } - return fMenu; - } - - private boolean addEntries(Menu menu, ICElement[] elements) { - boolean checked= false; - - int min= Math.min(elements.length, RESULTS_IN_DROP_DOWN); - for (int i= 0; i < min; i++) { - HistoryAction action= new HistoryAction(fHierarchyView, elements[i]); - action.setChecked(elements[i].equals(fHierarchyView.getInputElement())); - checked= checked || action.isChecked(); - addActionToMenu(menu, action); - } - return checked; - } - - - protected void addActionToMenu(Menu parent, Action action) { - ActionContributionItem item= new ActionContributionItem(action); - item.fill(parent, -1); - } - - public void run() { - (new HistoryListAction(fHierarchyView)).run(); - } -} diff --git a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/HistoryListAction.java b/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/HistoryListAction.java deleted file mode 100644 index 30e30614575..00000000000 --- a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/HistoryListAction.java +++ /dev/null @@ -1,181 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.browser.typehierarchy; - -import java.util.Arrays; -import java.util.List; - -import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.cdt.internal.ui.CPluginImages; -import org.eclipse.cdt.internal.ui.ICHelpContextIds; -import org.eclipse.cdt.internal.ui.dialogs.StatusDialog; -import org.eclipse.cdt.internal.ui.dialogs.StatusInfo; -import org.eclipse.cdt.internal.ui.wizards.dialogfields.DialogField; -import org.eclipse.cdt.internal.ui.wizards.dialogfields.IListAdapter; -import org.eclipse.cdt.internal.ui.wizards.dialogfields.LayoutUtil; -import org.eclipse.cdt.internal.ui.wizards.dialogfields.ListDialogField; -import org.eclipse.cdt.ui.CElementLabelProvider; -import org.eclipse.cdt.ui.CUIPlugin; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.jface.action.Action; -import org.eclipse.jface.viewers.ISelection; -import org.eclipse.jface.viewers.StructuredSelection; -import org.eclipse.jface.window.Window; -import org.eclipse.swt.SWT; -import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Control; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.ui.help.WorkbenchHelp; - -public class HistoryListAction extends Action { - - private class HistoryListDialog extends StatusDialog { - - private ListDialogField fHistoryList; - private IStatus fHistoryStatus; - private ICElement fResult; - - private HistoryListDialog(Shell shell, ICElement[] elements) { - super(shell); - setTitle(TypeHierarchyMessages.getString("HistoryListDialog.title")); //$NON-NLS-1$ - - String[] buttonLabels= new String[] { - /* 0 */ TypeHierarchyMessages.getString("HistoryListDialog.remove.button"), //$NON-NLS-1$ - }; - - IListAdapter adapter= new IListAdapter() { - public void customButtonPressed(ListDialogField field, int index) { - doCustomButtonPressed(); - } - public void selectionChanged(ListDialogField field) { - doSelectionChanged(); - } - - public void doubleClicked(ListDialogField field) { - doDoubleClicked(); - } - }; - - CElementLabelProvider labelProvider= new CElementLabelProvider(CElementLabelProvider.SHOW_QUALIFIED /*| CElementLabelProvider.SHOW_ROOT*/); - - fHistoryList= new ListDialogField(adapter, buttonLabels, labelProvider); - fHistoryList.setLabelText(TypeHierarchyMessages.getString("HistoryListDialog.label")); //$NON-NLS-1$ - fHistoryList.setElements(Arrays.asList(elements)); - - ISelection sel; - if (elements.length > 0) { - sel= new StructuredSelection(elements[0]); - } else { - sel= new StructuredSelection(); - } - - fHistoryList.selectElements(sel); - } - - - /* - * @see Dialog#createDialogArea(Composite) - */ - protected Control createDialogArea(Composite parent) { - initializeDialogUnits(parent); - - Composite composite= (Composite) super.createDialogArea(parent); - - Composite inner= new Composite(composite, SWT.NONE); - inner.setLayoutData(new GridData(GridData.FILL_BOTH)); - - LayoutUtil.doDefaultLayout(inner, new DialogField[] { fHistoryList }, true, 0, 0); - LayoutUtil.setHeigthHint(fHistoryList.getListControl(null), convertHeightInCharsToPixels(12)); - LayoutUtil.setHorizontalGrabbing(fHistoryList.getListControl(null)); - - applyDialogFont(composite); - return composite; - } - - /** - * Method doCustomButtonPressed. - */ - void doCustomButtonPressed() { - fHistoryList.removeElements(fHistoryList.getSelectedElements()); - } - - void doDoubleClicked() { - if (fHistoryStatus.isOK()) { - okPressed(); - } - } - - - void doSelectionChanged() { - StatusInfo status= new StatusInfo(); - List selected= fHistoryList.getSelectedElements(); - if (selected.size() != 1) { - status.setError(""); //$NON-NLS-1$ - fResult= null; - } else { - fResult= (ICElement) selected.get(0); - } - fHistoryList.enableButton(0, fHistoryList.getSize() > selected.size() && selected.size() != 0); - fHistoryStatus= status; - updateStatus(status); - } - - public ICElement getResult() { - return fResult; - } - - public ICElement[] getRemaining() { - List elems= fHistoryList.getElements(); - return (ICElement[]) elems.toArray(new ICElement[elems.size()]); - } - - /* - * @see org.eclipse.jface.window.Window#configureShell(Shell) - */ - protected void configureShell(Shell newShell) { - super.configureShell(newShell); - WorkbenchHelp.setHelp(newShell, ICHelpContextIds.HISTORY_LIST_DIALOG); - } - - /* (non-Javadoc) - * @see org.eclipse.jface.window.Window#create() - */ - public void create() { - setShellStyle(getShellStyle() | SWT.RESIZE); - super.create(); - } - - } - - private TypeHierarchyViewPart fView; - - public HistoryListAction(TypeHierarchyViewPart view) { - fView= view; - setText(TypeHierarchyMessages.getString("HistoryListAction.label")); //$NON-NLS-1$ - CPluginImages.setImageDescriptors(this, CPluginImages.T_LCL, "history_list.gif"); //$NON-NLS-1$ - WorkbenchHelp.setHelp(this, ICHelpContextIds.HISTORY_LIST_ACTION); - } - - /* - * @see IAction#run() - */ - public void run() { - ICElement[] historyEntries= fView.getHistoryEntries(); - HistoryListDialog dialog= new HistoryListDialog(CUIPlugin.getActiveWorkbenchShell(), historyEntries); - if (dialog.open() == Window.OK) { - fView.setHistoryEntries(dialog.getRemaining()); - fView.setInputElement(dialog.getResult()); - } - } - -} - diff --git a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/ITypeHierarchyLifeCycleListener.java b/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/ITypeHierarchyLifeCycleListener.java deleted file mode 100644 index c21589314d8..00000000000 --- a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/ITypeHierarchyLifeCycleListener.java +++ /dev/null @@ -1,26 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.browser.typehierarchy; - -import org.eclipse.cdt.core.model.ICElement; - -/** - * Used by the TypeHierarchyLifeCycle to inform listeners about a change in the - * type hierarchy - */ -public interface ITypeHierarchyLifeCycleListener { - - /** - * A Java element changed. - */ - void typeHierarchyChanged(TypeHierarchyLifeCycle typeHierarchyProvider, ICElement[] changedTypes); - -} diff --git a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/ITypeHierarchyViewPart.java b/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/ITypeHierarchyViewPart.java deleted file mode 100644 index 04a93e376f4..00000000000 --- a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/ITypeHierarchyViewPart.java +++ /dev/null @@ -1,69 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.browser.typehierarchy; - - -import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.ui.IViewPart; - -/** - * The standard type hierarchy view presents a type hierarchy for a given input class - * or interface. Visually, this view consists of a pair of viewers, one showing the type - * hierarchy, the other showing the members of the type selected in the first. - *

      - * This interface is not intended to be implemented by clients. - *

      - * - * @see JavaUI#ID_TYPE_HIERARCHY - */ -public interface ITypeHierarchyViewPart extends IViewPart { - - /** - * Sets the input element of this type hierarchy view to a type. - * - * @param type the input element of this type hierarchy view, or null - * to clear any input element - * @deprecated use setInputElement instead - */ - public void setInput(ICElement type); - - /** - * Sets the input element of this type hierarchy view. The following input types are possible - * IMember (types, methods, fields..), IPackageFragment, IPackageFragmentRoot - * and IJavaProject. - * - * @param element the input element of this type hierarchy view, or null - * to clear any input - * - * @since 2.0 - */ - public void setInputElement(ICElement element); - - /** - * Returns the input element of this type hierarchy view. - * - * @return the input element, or null if no input element is set - * @see #setInput(IType) - * @deprecated use getInputElement instead - */ - public ICElement getInput(); - - - /** - * Returns the input element of this type hierarchy view. - * - * @return the input element, or null if no input element is set - * @see #setInputElement(IJavaElement) - * - * @since 2.0 - */ - public ICElement getInputElement(); -} diff --git a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/MethodsContentProvider.java b/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/MethodsContentProvider.java deleted file mode 100644 index 1370a46d5ee..00000000000 --- a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/MethodsContentProvider.java +++ /dev/null @@ -1,128 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.browser.typehierarchy; - -import java.util.ArrayList; -import java.util.List; - -import org.eclipse.cdt.core.browser.TypeUtil; -import org.eclipse.cdt.core.browser.typehierarchy.ITypeHierarchy; -import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.cdt.ui.CElementContentProvider; -import org.eclipse.jface.util.Assert; -import org.eclipse.jface.viewers.TableViewer; -import org.eclipse.jface.viewers.Viewer; - -/** - * Content provider used for the method view. - * Allows also seeing methods inherited from base classes. - */ -public class MethodsContentProvider extends CElementContentProvider //implements IStructuredContentProvider //, IWorkingCopyProvider -{ - private static final Object[] NO_ELEMENTS = new Object[0]; - - private boolean fShowInheritedMethods; - private TypeHierarchyLifeCycle fHierarchyLifeCycle; - private TableViewer fViewer; - - public MethodsContentProvider(TypeHierarchyLifeCycle lifecycle) { - fHierarchyLifeCycle= lifecycle; - fShowInheritedMethods= false; - fViewer= null; - } - - /** - * Turn on / off showing of inherited methods - */ - public void showInheritedMethods(boolean show) { - if (show != fShowInheritedMethods) { - fShowInheritedMethods= show; - if (fViewer != null) { - fViewer.refresh(); - } - } - } - - /* (non-Javadoc) - * @see IStructuredContentProvider#providesWorkingCopies() - */ - public boolean providesWorkingCopies() { - return true; - } - - /** - * Returns true if inherited methods are shown - */ - public boolean isShowInheritedMethods() { - return fShowInheritedMethods; - } - - - private void addAll(Object[] arr, List res) { - if (arr != null) { - for (int j= 0; j < arr.length; j++) { - res.add(arr[j]); - } - } - } - - /* - * @see IStructuredContentProvider#getElements - */ - public Object[] getElements(Object element) { - if (element instanceof ICElement) { - ICElement type= (ICElement)element; - - List res= new ArrayList(); -// try { - ITypeHierarchy hierarchy= fHierarchyLifeCycle.getHierarchy(); - if (fShowInheritedMethods && hierarchy != null) { - ICElement[] allSupertypes= hierarchy.getAllSupertypes(type); - // sort in from last to first: elements with same name - // will show up in hierarchy order - for (int i= allSupertypes.length - 1; i >= 0; i--) { - ICElement superType= allSupertypes[i]; - if (superType.exists()) { - addAll(TypeUtil.getMethods(superType), res); - //addAll(TypeUtil.getInitializers(superType), res); - addAll(TypeUtil.getFields(superType), res); - } - } - } - if (type.exists()) { - addAll(TypeUtil.getMethods(type), res); - //addAll(TypeUtil.getInitializers(type), res); - addAll(TypeUtil.getFields(type), res); - } -// } catch (CModelException e) { -// CUIPlugin.getDefault().log(e); -// } - return res.toArray(); - } - return NO_ELEMENTS; - } - - - /* - * @see IContentProvider#inputChanged - */ - public void inputChanged(Viewer input, Object oldInput, Object newInput) { - Assert.isTrue(input instanceof TableViewer); - - fViewer= (TableViewer) input; - } - - /* - * @see IContentProvider#dispose - */ - public void dispose() { - } -} diff --git a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/MethodsLabelProvider.java b/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/MethodsLabelProvider.java deleted file mode 100644 index 9ee430af59a..00000000000 --- a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/MethodsLabelProvider.java +++ /dev/null @@ -1,135 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.browser.typehierarchy; - -import org.eclipse.cdt.core.browser.TypeUtil; -import org.eclipse.cdt.core.browser.typehierarchy.ITypeHierarchy; -import org.eclipse.cdt.core.model.CModelException; -import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.cdt.core.model.IMethod; -import org.eclipse.cdt.core.model.IMethodDeclaration; -import org.eclipse.cdt.core.parser.ast.ASTAccessVisibility; -import org.eclipse.cdt.internal.ui.viewsupport.CElementLabels; -import org.eclipse.cdt.internal.ui.viewsupport.StandardCElementLabelProvider; -import org.eclipse.swt.SWT; -import org.eclipse.swt.graphics.Color; -import org.eclipse.swt.widgets.Display; - -/** - * Label provider for the hierarchy method viewers. - */ -public class MethodsLabelProvider extends StandardCElementLabelProvider //extends AppearanceAwareLabelProvider -{ - private Color fResolvedBackground; - - private boolean fShowDefiningType; - private TypeHierarchyLifeCycle fHierarchy; - private MethodsViewer fMethodsViewer; - - public MethodsLabelProvider(TypeHierarchyLifeCycle lifeCycle, MethodsViewer methodsViewer) { -// super(DEFAULT_TEXTFLAGS, DEFAULT_IMAGEFLAGS); - super(); - fHierarchy= lifeCycle; - fShowDefiningType= false; - fMethodsViewer= methodsViewer; - fResolvedBackground= null; - } - - public void setShowDefiningType(boolean showDefiningType) { - fShowDefiningType= showDefiningType; - } - - public boolean isShowDefiningType() { - return fShowDefiningType; - } - - - private ICElement getDefiningType(Object element) throws CModelException { - if (!(element instanceof ICElement)) - return null; - - ICElement elem = (ICElement) element; - int kind= elem.getElementType(); - if (kind != ICElement.C_METHOD_DECLARATION && kind != ICElement.C_FIELD) { - return null; - } - ICElement declaringType= TypeUtil.getDeclaringClass(elem); - if (kind != ICElement.C_METHOD_DECLARATION) { - return declaringType; - } - ITypeHierarchy hierarchy= fHierarchy.getHierarchy(); - if (hierarchy == null) { - return declaringType; - } - IMethodDeclaration method= (IMethodDeclaration) element; - if ((method.getVisibility() == ASTAccessVisibility.PRIVATE) || method.isStatic() || method.isConstructor() || method.isDestructor()) { - return declaringType; - } - IMethodDeclaration res= TypeUtil.findMethodDeclarationInHierarchy(hierarchy, declaringType, method.getElementName(), method.getParameterTypes(), false, false); - if (res == null || method.equals(res)) { - return declaringType; - } - return TypeUtil.getDeclaringClass(res); - } - - /* (non-Javadoc) - * @see ILabelProvider#getText - */ - public String getText(Object element) { - String text= super.getText(element); - if ((getTextFlags() & CElementLabels.M_POST_QUALIFIED) != 0) { - if (element instanceof ICElement) { - ICElement parent = ((ICElement)element).getParent(); - if (parent != null) { - StringBuffer name = new StringBuffer(); - name.append(text); - name.append(CElementLabels.CONCAT_STRING); - name.append(TypeUtil.getFullyQualifiedName(parent).toString()); - text = name.toString(); - } - } - } - - if (fShowDefiningType) { - try { - ICElement type= getDefiningType(element); - if (type != null) { - StringBuffer buf= new StringBuffer(super.getText(type)); - buf.append(CElementLabels.CONCAT_STRING); - buf.append(text); - return buf.toString(); - } - } catch (CModelException e) { - } - } - return text; - } - - /* (non-Javadoc) - * @see org.eclipse.jface.viewers.IColorProvider#getForeground(java.lang.Object) - */ - public Color getForeground(Object element) { - if (fMethodsViewer.isShowInheritedMethods() && element instanceof IMethod) { - IMethod curr= (IMethod) element; - ICElement declaringType= TypeUtil.getDeclaringClass(curr); - - if (declaringType.equals(fMethodsViewer.getInput())) { - if (fResolvedBackground == null) { - Display display= Display.getCurrent(); - fResolvedBackground= display.getSystemColor(SWT.COLOR_DARK_BLUE); - } - return fResolvedBackground; - } - } - return null; - } - -} diff --git a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/MethodsViewer.java b/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/MethodsViewer.java deleted file mode 100644 index f1040498259..00000000000 --- a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/MethodsViewer.java +++ /dev/null @@ -1,295 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.browser.typehierarchy; - -import java.util.ArrayList; -import java.util.List; - -import org.eclipse.cdt.core.browser.TypeUtil; -import org.eclipse.cdt.core.model.CModelException; -import org.eclipse.cdt.core.model.IMethodDeclaration; -import org.eclipse.cdt.internal.ui.util.ProblemTableViewer; -import org.eclipse.cdt.internal.ui.util.SelectionUtil; -import org.eclipse.cdt.internal.ui.viewsupport.CElementLabels; -import org.eclipse.cdt.ui.CUIPlugin; -import org.eclipse.cdt.ui.actions.MemberFilterActionGroup; -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.action.ToolBarManager; -import org.eclipse.jface.viewers.ISelection; -import org.eclipse.jface.viewers.StructuredSelection; -import org.eclipse.swt.SWT; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Menu; -import org.eclipse.swt.widgets.ScrollBar; -import org.eclipse.swt.widgets.Table; -import org.eclipse.ui.IMemento; -import org.eclipse.ui.IWorkbenchPart; -import org.eclipse.ui.IWorkbenchPartSite; - -/** - * Method viewer shows a list of methods of a input type. - * Offers filter actions. - * No dependency to the type hierarchy view - */ -public class MethodsViewer extends ProblemTableViewer { - - private static final String TAG_SHOWINHERITED= "showinherited"; //$NON-NLS-1$ - private static final String TAG_SORTBYDEFININGTYPE= "sortbydefiningtype"; //$NON-NLS-1$ - private static final String TAG_VERTICAL_SCROLL= "mv_vertical_scroll"; //$NON-NLS-1$ - - private MethodsLabelProvider fLabelProvider; - - private MemberFilterActionGroup fMemberFilterActionGroup; - -// private OpenAction fOpen; - private ShowInheritedMembersAction fShowInheritedMembersAction; - private SortByDefiningTypeAction fSortByDefiningTypeAction; - - public MethodsViewer(Composite parent, final TypeHierarchyLifeCycle lifeCycle, IWorkbenchPart part) { - super(new Table(parent, SWT.MULTI)); - - fLabelProvider= new MethodsLabelProvider(lifeCycle, this); - -// setLabelProvider(new DecoratingCLabelProvider(fLabelProvider, true)); - setLabelProvider(fLabelProvider); - setContentProvider(new MethodsContentProvider(lifeCycle)); - - HierarchyViewerSorter sorter= new HierarchyViewerSorter(lifeCycle); - sorter.setSortByDefiningType(false); - setSorter(sorter); - -// fOpen= new OpenAction(part.getSite()); -// addOpenListener(new IOpenListener() { -// public void open(OpenEvent event) { -// fOpen.run(); -// } -// }); - - fMemberFilterActionGroup= new MemberFilterActionGroup(this, "HierarchyMethodView", false, MemberFilterActionGroup.ALL_FILTERS & ~MemberFilterActionGroup.FILTER_LOCALTYPES); //$NON-NLS-1$ - - fShowInheritedMembersAction= new ShowInheritedMembersAction(this, false); - fSortByDefiningTypeAction= new SortByDefiningTypeAction(this, false); - - showInheritedMethodsNoRedraw(false); - sortByDefiningTypeNoRedraw(false); - -// CUIHelp.setHelp(this, ICHelpContextIds.TYPE_HIERARCHY_VIEW); - } - - private void showInheritedMethodsNoRedraw(boolean on) { - MethodsContentProvider cprovider= (MethodsContentProvider) getContentProvider(); - cprovider.showInheritedMethods(on); - fShowInheritedMembersAction.setChecked(on); - if (on) { - fLabelProvider.setTextFlags(fLabelProvider.getTextFlags() | CElementLabels.T_POST_QUALIFIED); - } else { - fLabelProvider.setTextFlags(fLabelProvider.getTextFlags() & ~CElementLabels.T_POST_QUALIFIED); - } - if (on) { - sortByDefiningTypeNoRedraw(false); - } - fSortByDefiningTypeAction.setEnabled(!on); - - } - - /** - * Show inherited methods - */ - public void showInheritedMethods(boolean on) { - if (on == isShowInheritedMethods()) { - return; - } - try { - getTable().setRedraw(false); - showInheritedMethodsNoRedraw(on); - refresh(); - } finally { - getTable().setRedraw(true); - } - } - - private void sortByDefiningTypeNoRedraw(boolean on) { - fSortByDefiningTypeAction.setChecked(on); - fLabelProvider.setShowDefiningType(on); - ((HierarchyViewerSorter) getSorter()).setSortByDefiningType(on); - } - - /** - * Show the name of the defining type - */ - public void sortByDefiningType(boolean on) { - if (on == isShowDefiningTypes()) { - return; - } - try { - getTable().setRedraw(false); - sortByDefiningTypeNoRedraw(on); - refresh(); - } finally { - getTable().setRedraw(true); - } - } - - /* - * @see Viewer#inputChanged(Object, Object) - */ - protected void inputChanged(Object input, Object oldInput) { - super.inputChanged(input, oldInput); - } - - /** - * Returns true if inherited methods are shown. - */ - public boolean isShowInheritedMethods() { - return ((MethodsContentProvider) getContentProvider()).isShowInheritedMethods(); - } - - /** - * Returns true if defining types are shown. - */ - public boolean isShowDefiningTypes() { - return fLabelProvider.isShowDefiningType(); - } - - /** - * Saves the state of the filter actions - */ - public void saveState(IMemento memento) { - fMemberFilterActionGroup.saveState(memento); - - memento.putString(TAG_SHOWINHERITED, String.valueOf(isShowInheritedMethods())); - memento.putString(TAG_SORTBYDEFININGTYPE, String.valueOf(isShowDefiningTypes())); - - ScrollBar bar= getTable().getVerticalBar(); - int position= bar != null ? bar.getSelection() : 0; - memento.putString(TAG_VERTICAL_SCROLL, String.valueOf(position)); - } - - /** - * Restores the state of the filter actions - */ - public void restoreState(IMemento memento) { - fMemberFilterActionGroup.restoreState(memento); - getControl().setRedraw(false); - refresh(); - getControl().setRedraw(true); - - boolean showInherited= Boolean.valueOf(memento.getString(TAG_SHOWINHERITED)).booleanValue(); - showInheritedMethods(showInherited); - - boolean showDefiningTypes= Boolean.valueOf(memento.getString(TAG_SORTBYDEFININGTYPE)).booleanValue(); - sortByDefiningType(showDefiningTypes); - - ScrollBar bar= getTable().getVerticalBar(); - if (bar != null) { - Integer vScroll= memento.getInteger(TAG_VERTICAL_SCROLL); - if (vScroll != null) { - bar.setSelection(vScroll.intValue()); - } - } - } - - /** - * Attaches a contextmenu listener to the table - */ - public void initContextMenu(IMenuListener menuListener, String popupId, IWorkbenchPartSite viewSite) { - MenuManager menuMgr= new MenuManager(); - menuMgr.setRemoveAllWhenShown(true); - menuMgr.addMenuListener(menuListener); - Menu menu= menuMgr.createContextMenu(getTable()); - getTable().setMenu(menu); - viewSite.registerContextMenu(popupId, menuMgr, this); - } - - - /** - * Fills up the context menu with items for the method viewer - * Should be called by the creator of the context menu - */ - public void contributeToContextMenu(IMenuManager menu) { - } - - /** - * Fills up the tool bar with items for the method viewer - * Should be called by the creator of the tool bar - */ - public void contributeToToolBar(ToolBarManager tbm) { - tbm.add(fShowInheritedMembersAction); - tbm.add(fSortByDefiningTypeAction); - tbm.add(new Separator()); - fMemberFilterActionGroup.contributeToToolBar(tbm); - } - - public void dispose() { - if (fMemberFilterActionGroup != null) { - fMemberFilterActionGroup.dispose(); - fMemberFilterActionGroup= null; - } - } - - /* - * @see StructuredViewer#handleInvalidSelection(ISelection, ISelection) - */ - protected void handleInvalidSelection(ISelection invalidSelection, ISelection newSelection) { - // on change of input, try to keep selected methods stable by selecting a method with the same - // signature: See #5466 - List oldSelections= SelectionUtil.toList(invalidSelection); - List newSelections= SelectionUtil.toList(newSelection); - if (!oldSelections.isEmpty()) { - ArrayList newSelectionElements= new ArrayList(newSelections); - try { - Object[] currElements= getFilteredChildren(getInput()); - for (int i= 0; i < oldSelections.size(); i++) { - Object curr= oldSelections.get(i); - if (curr instanceof IMethodDeclaration && !newSelections.contains(curr)) { - IMethodDeclaration method= (IMethodDeclaration) curr; - if (method.exists()) { - IMethodDeclaration similar= findSimilarMethod(method, currElements); - if (similar != null) { - newSelectionElements.add(similar); - } - } - } - } - if (!newSelectionElements.isEmpty()) { - newSelection= new StructuredSelection(newSelectionElements); - } else if (currElements.length > 0) { - newSelection= new StructuredSelection(currElements[0]); - } - } catch (CModelException e) { - CUIPlugin.getDefault().log(e); - } - } - setSelection(newSelection); - updateSelection(newSelection); - } - - private IMethodDeclaration findSimilarMethod(IMethodDeclaration meth, Object[] elements) throws CModelException { - String name= meth.getElementName(); - String[] paramTypes= meth.getParameterTypes(); - boolean isConstructor= meth.isConstructor(); - boolean isDestructor= meth.isDestructor(); - - for (int i= 0; i < elements.length; i++) { - Object curr= elements[i]; - if (curr instanceof IMethodDeclaration && TypeUtil.isSameMethodSignature(name, paramTypes, isConstructor, isDestructor, (IMethodDeclaration) curr)) { - return (IMethodDeclaration) curr; - } - } - return null; - } - - - -} diff --git a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/OpenTypeHierarchyAction.java b/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/OpenTypeHierarchyAction.java deleted file mode 100644 index 4df1fadc382..00000000000 --- a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/OpenTypeHierarchyAction.java +++ /dev/null @@ -1,251 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.browser.typehierarchy; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import org.eclipse.cdt.core.browser.AllTypesCache; -import org.eclipse.cdt.core.browser.ITypeInfo; -import org.eclipse.cdt.core.browser.ITypeSearchScope; -import org.eclipse.cdt.core.browser.QualifiedTypeName; -import org.eclipse.cdt.core.browser.TypeSearchScope; -import org.eclipse.cdt.core.browser.TypeUtil; -import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.cdt.core.model.ITranslationUnit; -import org.eclipse.cdt.internal.ui.ICHelpContextIds; -import org.eclipse.cdt.internal.ui.ICStatusConstants; -import org.eclipse.cdt.internal.ui.actions.ActionMessages; -import org.eclipse.cdt.internal.ui.actions.ActionUtil; -import org.eclipse.cdt.internal.ui.actions.SelectionConverter; -import org.eclipse.cdt.internal.ui.editor.CEditor; -import org.eclipse.cdt.ui.CUIPlugin; -import org.eclipse.cdt.ui.actions.SelectionDispatchAction; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.NullProgressMonitor; -import org.eclipse.core.runtime.Status; -import org.eclipse.jface.dialogs.ErrorDialog; -import org.eclipse.jface.text.ITextSelection; -import org.eclipse.jface.viewers.IStructuredSelection; -import org.eclipse.ui.IWorkbenchSite; -import org.eclipse.ui.help.WorkbenchHelp; - -/** - * This action opens a type hierarchy on the selected type. - *

      - * The action is applicable to selections containing elements of type - * IType. - * - *

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

      - * - * @since 2.0 - */ -public class OpenTypeHierarchyAction extends SelectionDispatchAction { - - private CEditor fEditor; - - /** - * Creates a new OpenTypeHierarchyAction. The action requires - * that the selection provided by the site's selection provider is of type - * org.eclipse.jface.viewers.IStructuredSelection. - * - * @param site the site providing context information for this action - */ - public OpenTypeHierarchyAction(IWorkbenchSite site) { - super(site); - setText(ActionMessages.getString("OpenTypeHierarchyAction.label")); //$NON-NLS-1$ - setToolTipText(ActionMessages.getString("OpenTypeHierarchyAction.tooltip")); //$NON-NLS-1$ - setDescription(ActionMessages.getString("OpenTypeHierarchyAction.description")); //$NON-NLS-1$ - WorkbenchHelp.setHelp(this, ICHelpContextIds.OPEN_TYPE_HIERARCHY_ACTION); - } - - /** - * Note: This constructor is for internal use only. Clients should not call this constructor. - */ - public OpenTypeHierarchyAction(CEditor editor) { - this(editor.getEditorSite()); - fEditor= editor; - setEnabled(SelectionConverter.canOperateOn(fEditor)); - } - - /* (non-Javadoc) - * Method declared on SelectionDispatchAction. - */ - public void selectionChanged(ITextSelection selection) { -/* boolean enable = true; - ICElement selectedElement = null; - try { - ICElement[] elements = SelectionConverter.getElementsAtOffset(fEditor); - if (elements == null || elements.length == 0) { - setEnabled(false); - return; - } - // find class or struct - for (int i = 0; i < elements.length; ++i) { - if (TypeUtil.isClassOrStruct(elements[i])) { - selectedElement = elements[i]; - break; - } - } - - if (selectedElement == null) { - setEnabled(false); - return; - } - } catch (CModelException e) { - setEnabled(false); - return; - } - - ITextSelection textSelection= (ITextSelection)fEditor.getSelectionProvider().getSelection(); - - if (textSelection == null) { - setEnabled(false); - return; - } - - if( (((CElement)selectedElement).getIdStartPos() != textSelection.getOffset()) - || (((CElement)selectedElement).getIdLength() != textSelection.getLength())) { - enable = false; - } - setEnabled(enable); -*/ } - - /* (non-Javadoc) - * Method declared on SelectionDispatchAction. - */ - public void selectionChanged(IStructuredSelection selection) { - setEnabled(isEnabled(selection)); - } - - private boolean isEnabled(IStructuredSelection selection) { - if (selection.size() != 1) - return false; - Object input= selection.getFirstElement(); - if (input instanceof ICElement) { - ICElement elem = (ICElement)input; - return TypeUtil.isClassOrStruct(elem); - } - return false; - } - - /* (non-Javadoc) - * Method declared on SelectionDispatchAction. - */ - public void run(ITextSelection selection) { - ICElement input= SelectionConverter.getInput(fEditor); - if (!ActionUtil.isProcessable(getShell(), input)) - return; - - ICElement[] elements= SelectionConverter.codeResolveOrInputHandled(fEditor, getShell(), getDialogTitle()); - if (elements == null) - return; - List candidates= new ArrayList(elements.length); - for (int i= 0; i < elements.length; i++) { - ICElement elem = elements[i]; - if (elem instanceof ITranslationUnit) { - ICElement[] realElems = findTypeDeclarations(selection.getText(), (ITranslationUnit)elem, selection.getOffset(), selection.getLength(), new NullProgressMonitor()); - if (realElems != null) { - for (int j = 0; j < realElems.length; ++j) { - ICElement[] resolvedElements= OpenTypeHierarchyUtil.getCandidates(realElems[j]); - if (resolvedElements != null) - candidates.addAll(Arrays.asList(resolvedElements)); - } - } - } else { - ICElement[] resolvedElements= OpenTypeHierarchyUtil.getCandidates(elem); - if (resolvedElements != null) - candidates.addAll(Arrays.asList(resolvedElements)); - } - } - run((ICElement[])candidates.toArray(new ICElement[candidates.size()])); - } - - private ICElement[] findTypeDeclarations(String name, ITranslationUnit unit, int offset, int length, IProgressMonitor monitor) { - final ITypeSearchScope wsScope = new TypeSearchScope(true); - if (!AllTypesCache.isCacheUpToDate(wsScope)) { - AllTypesCache.updateCache(wsScope, monitor); - } - ITypeSearchScope projectScope = new TypeSearchScope(); - projectScope.add(unit.getCProject()); - int[] kinds = {ICElement.C_CLASS, ICElement.C_STRUCT}; - ITypeInfo[] types = AllTypesCache.getTypes(projectScope, new QualifiedTypeName(name), kinds, true); - if (types != null) { - List elements = new ArrayList(types.length); - for (int i = 0; i < types.length; ++i) { - ICElement e = AllTypesCache.getElementForType(types[i], true, true, monitor); - if (e != null && !elements.contains(e)) - elements.add(e); - } - if (!elements.isEmpty()) - return (ICElement[])elements.toArray(new ICElement[elements.size()]); - } - return null; - } - - /* (non-Javadoc) - * Method declared on SelectionDispatchAction. - */ - public void run(IStructuredSelection selection) { - if (selection.size() != 1) - return; - Object input= selection.getFirstElement(); - - if (!(input instanceof ICElement)) { - IStatus status= createStatus(ActionMessages.getString("OpenTypeHierarchyAction.messages.no_c_element")); //$NON-NLS-1$ - ErrorDialog.openError(getShell(), getDialogTitle(), ActionMessages.getString("OpenTypeHierarchyAction.messages.title"), status); //$NON-NLS-1$ - return; - } - ICElement element= (ICElement) input; - if (!ActionUtil.isProcessable(getShell(), element)) - return; - - List result= new ArrayList(1); - IStatus status= compileCandidates(result, element); - if (status.isOK()) { - run((ICElement[]) result.toArray(new ICElement[result.size()])); - } else { - ErrorDialog.openError(getShell(), getDialogTitle(), ActionMessages.getString("OpenTypeHierarchyAction.messages.title"), status); //$NON-NLS-1$ - } - } - - public void run(ICElement[] elements) { - if (elements.length == 0) { - getShell().getDisplay().beep(); - return; - } - OpenTypeHierarchyUtil.open(elements, getSite().getWorkbenchWindow()); - } - - private static String getDialogTitle() { - return ActionMessages.getString("OpenTypeHierarchyAction.dialog.title"); //$NON-NLS-1$ - } - - private static IStatus compileCandidates(List result, ICElement elem) { - IStatus ok = new Status(IStatus.OK, CUIPlugin.getPluginId(), 0, "", null); //$NON-NLS-1$ - switch (elem.getElementType()) { - case ICElement.C_CLASS: - case ICElement.C_STRUCT: - case ICElement.C_PROJECT: - result.add(elem); - return ok; - } - return createStatus(ActionMessages.getString("OpenTypeHierarchyAction.messages.no_valid_c_element")); //$NON-NLS-1$ - } - - private static IStatus createStatus(String message) { - return new Status(IStatus.INFO, CUIPlugin.getPluginId(), ICStatusConstants.INTERNAL_ERROR, message, null); - } -} diff --git a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/OpenTypeHierarchyUtil.java b/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/OpenTypeHierarchyUtil.java deleted file mode 100644 index 196b49258b7..00000000000 --- a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/OpenTypeHierarchyUtil.java +++ /dev/null @@ -1,175 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.browser.typehierarchy; - -import org.eclipse.cdt.core.browser.TypeUtil; -import org.eclipse.cdt.core.model.CModelException; -import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.cdt.core.model.IMember; -import org.eclipse.cdt.core.model.ITranslationUnit; -import org.eclipse.cdt.internal.ui.CUIMessages; -import org.eclipse.cdt.internal.ui.actions.OpenActionUtil; -import org.eclipse.cdt.internal.ui.util.EditorUtility; -import org.eclipse.cdt.internal.ui.util.ExceptionHandler; -import org.eclipse.cdt.ui.CUIPlugin; -import org.eclipse.cdt.ui.PreferenceConstants; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.jface.util.Assert; -import org.eclipse.ui.IEditorPart; -import org.eclipse.ui.IWorkbench; -import org.eclipse.ui.IWorkbenchPage; -import org.eclipse.ui.IWorkbenchWindow; -import org.eclipse.ui.PartInitException; -import org.eclipse.ui.WorkbenchException; - -public class OpenTypeHierarchyUtil { - - private OpenTypeHierarchyUtil() { - } - - public static TypeHierarchyViewPart open(ICElement element, IWorkbenchWindow window) { - ICElement[] candidates= getCandidates(element); - if (candidates != null) { - return open(candidates, window); - } - return null; - } - - public static TypeHierarchyViewPart open(ICElement[] candidates, IWorkbenchWindow window) { - Assert.isTrue(candidates != null && candidates.length != 0); - - ICElement input= null; - if (candidates.length > 1) { - String title= CUIMessages.getString("OpenTypeHierarchyUtil.selectionDialog.title"); //$NON-NLS-1$ - String message= CUIMessages.getString("OpenTypeHierarchyUtil.selectionDialog.message"); //$NON-NLS-1$ - input= OpenActionUtil.selectCElement(candidates, window.getShell(), title, message); - } else { - input= candidates[0]; - } - if (input == null) - return null; - - try { - if (PreferenceConstants.OPEN_TYPE_HIERARCHY_IN_PERSPECTIVE.equals(PreferenceConstants.getPreferenceStore().getString(PreferenceConstants.OPEN_TYPE_HIERARCHY))) { - return openInPerspective(window, input); - } - return openInViewPart(window, input); - - } catch (WorkbenchException e) { - ExceptionHandler.handle(e, window.getShell(), - CUIMessages.getString("OpenTypeHierarchyUtil.error.open_perspective"), //$NON-NLS-1$ - e.getMessage()); - } catch (CModelException e) { - ExceptionHandler.handle(e, window.getShell(), - CUIMessages.getString("OpenTypeHierarchyUtil.error.open_editor"), //$NON-NLS-1$ - e.getMessage()); - } - return null; - } - - private static TypeHierarchyViewPart openInViewPart(IWorkbenchWindow window, ICElement input) { - IWorkbenchPage page= window.getActivePage(); - try { - TypeHierarchyViewPart result= (TypeHierarchyViewPart) page.findView(CUIPlugin.ID_TYPE_HIERARCHY); - if (result != null) { - result.clearNeededRefresh(); // avoid refresh of old hierarchy on 'becomes visible' - } - result= (TypeHierarchyViewPart) page.showView(CUIPlugin.ID_TYPE_HIERARCHY); - result.setInputElement(input); - - if (input instanceof IMember) { - result.selectMember(input); - } - return result; - } catch (CoreException e) { - ExceptionHandler.handle(e, window.getShell(), - CUIMessages.getString("OpenTypeHierarchyUtil.error.open_view"), e.getMessage()); //$NON-NLS-1$ - } - return null; - } - - private static TypeHierarchyViewPart openInPerspective(IWorkbenchWindow window, ICElement input) throws WorkbenchException, CModelException { - IWorkbench workbench= CUIPlugin.getDefault().getWorkbench(); - // The problem is that the input element can be a working copy. So we first convert it to the original element if - // it exists. - ICElement perspectiveInput= input; - - if (input instanceof IMember) { -// if (input.getElementType() != ITypeElement.TYPE) { - if (TypeUtil.isClassOrStruct(input)) { -// perspectiveInput= ((IMember)input).getDeclaringType(); - perspectiveInput= TypeUtil.getDeclaringClass(input); - } else { - perspectiveInput= input; - } - } - IWorkbenchPage page= workbench.showPerspective(CUIPlugin.ID_CHIERARCHY_PERSPECTIVE, window, perspectiveInput); - - TypeHierarchyViewPart part= (TypeHierarchyViewPart) page.findView(CUIPlugin.ID_TYPE_HIERARCHY); - if (part != null) { - part.clearNeededRefresh(); // avoid refresh of old hierarchy on 'becomes visible' - } - part= (TypeHierarchyViewPart) page.showView(CUIPlugin.ID_TYPE_HIERARCHY); - part.setInputElement(perspectiveInput); - if (input instanceof IMember) { - part.selectMember(input); - - if (page.getEditorReferences().length == 0) { - openEditor(input, false); // only open when the perspecive has been created - } - } - return part; - } - - private static void openEditor(Object input, boolean activate) throws PartInitException, CModelException { - IEditorPart part= EditorUtility.openInEditor(input, activate); - if (input instanceof ICElement) - EditorUtility.revealInEditor(part, (ICElement) input); - } - - /** - * Converts the input to a possible input candidates - */ - public static ICElement[] getCandidates(Object input) { - if (!(input instanceof ICElement)) { - return null; - } - try { - ICElement elem= (ICElement) input; - switch (elem.getElementType()) { - case ICElement.C_METHOD: - case ICElement.C_METHOD_DECLARATION: - case ICElement.C_FIELD: - case ICElement.C_UNION: - case ICElement.C_ENUMERATION: - case ICElement.C_TYPEDEF: - return new ICElement[] { TypeUtil.getDeclaringClass(elem) }; - case ICElement.C_CLASS: - case ICElement.C_STRUCT: - return new ICElement[] { elem }; - case ICElement.C_NAMESPACE: - return TypeUtil.getTypes(elem); - case ICElement.C_UNIT: { - ITranslationUnit cu= (ITranslationUnit) elem.getAncestor(ICElement.C_UNIT); - if (cu != null) { - return TypeUtil.getTypes(cu); - } - break; - } - case ICElement.C_PROJECT: - default: - } - } catch (CModelException e) { - CUIPlugin.getDefault().log(e); - } - return null; - } -} diff --git a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/OpenTypeInHierarchyAction.java b/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/OpenTypeInHierarchyAction.java deleted file mode 100644 index d24e9017f45..00000000000 --- a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/OpenTypeInHierarchyAction.java +++ /dev/null @@ -1,128 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004, 2005 QNX Software Systems and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * QNX Software Systems - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.browser.typehierarchy; - -import java.lang.reflect.InvocationTargetException; - -import org.eclipse.cdt.core.browser.AllTypesCache; -import org.eclipse.cdt.core.browser.ITypeInfo; -import org.eclipse.cdt.core.browser.ITypeSearchScope; -import org.eclipse.cdt.core.browser.TypeSearchScope; -import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.cdt.internal.ui.browser.opentype.OpenTypeMessages; -import org.eclipse.cdt.internal.ui.util.ExceptionHandler; -import org.eclipse.cdt.ui.CUIPlugin; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.jface.action.IAction; -import org.eclipse.jface.dialogs.IDialogConstants; -import org.eclipse.jface.dialogs.MessageDialog; -import org.eclipse.jface.operation.IRunnableWithProgress; -import org.eclipse.jface.viewers.ISelection; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.ui.IWorkbenchWindow; -import org.eclipse.ui.IWorkbenchWindowActionDelegate; -import org.eclipse.ui.PlatformUI; -import org.eclipse.ui.progress.IProgressService; - -public class OpenTypeInHierarchyAction implements IWorkbenchWindowActionDelegate { - - private IWorkbenchWindow fWindow; - - public OpenTypeInHierarchyAction() { - super(); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction) - */ - public void run(IAction action) { - final ITypeSearchScope fScope = new TypeSearchScope(true); - if (!AllTypesCache.isCacheUpToDate(fScope)) { - IRunnableWithProgress runnable = new IRunnableWithProgress() { - public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { - AllTypesCache.updateCache(fScope, monitor); - if (monitor.isCanceled()) { - throw new InterruptedException(); - } - } - }; - - IProgressService service = PlatformUI.getWorkbench().getProgressService(); - try { - service.busyCursorWhile(runnable); - } catch (InvocationTargetException e) { - String title = OpenTypeMessages.getString("OpenTypeAction.exception.title"); //$NON-NLS-1$ - String message = OpenTypeMessages.getString("OpenTypeAction.exception.message"); //$NON-NLS-1$ - ExceptionHandler.handle(e, title, message); - return; - } catch (InterruptedException e) { - // cancelled by user - return; - } - } - - ITypeInfo[] elements = AllTypesCache.getAllTypes(); - if (elements.length == 0) { - String title = OpenTypeMessages.getString("OpenTypeAction.notypes.title"); //$NON-NLS-1$ - String message = OpenTypeMessages.getString("OpenTypeAction.notypes.message"); //$NON-NLS-1$ - MessageDialog.openInformation(getShell(), title, message); - return; - } - - OpenTypeInHierarchyDialog dialog = new OpenTypeInHierarchyDialog(getShell()); - dialog.setElements(elements); - int result = dialog.open(); - if (result != IDialogConstants.OK_ID) - return; - - ITypeInfo info = (ITypeInfo) dialog.getFirstResult(); - if (info == null) - return; - - ICElement celem = AllTypesCache.getElementForType(info, false, true, null); - if (celem != null) { - OpenTypeHierarchyUtil.open(new ICElement[] { celem }, fWindow); - } - } - - protected Shell getShell() { - return CUIPlugin.getActiveWorkbenchShell(); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.IWorkbenchWindowActionDelegate#dispose() - */ - public void dispose() { - fWindow= null; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.IWorkbenchWindowActionDelegate#init(org.eclipse.ui.IWorkbenchWindow) - */ - public void init(IWorkbenchWindow window) { - fWindow= window; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.ui.IActionDelegate#selectionChanged(org.eclipse.jface.action.IAction, - * org.eclipse.jface.viewers.ISelection) - */ - public void selectionChanged(IAction action, ISelection selection) { - } -} diff --git a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/OpenTypeInHierarchyDialog.java b/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/OpenTypeInHierarchyDialog.java deleted file mode 100644 index 2ca3d200f54..00000000000 --- a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/OpenTypeInHierarchyDialog.java +++ /dev/null @@ -1,38 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * QNX Software Systems - adapted for use in CDT - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.browser.typehierarchy; - -import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.cdt.ui.browser.typeinfo.TypeSelectionDialog; -import org.eclipse.swt.widgets.Shell; - -/** - * A dialog to select a type from a list of types. The selected type will be - * opened in the editor. - */ -public class OpenTypeInHierarchyDialog extends TypeSelectionDialog { - - private static final String DIALOG_SETTINGS= OpenTypeInHierarchyDialog.class.getName(); - private final int[] VISIBLE_TYPES = { ICElement.C_CLASS, ICElement.C_STRUCT }; - - /** - * Constructs an instance of OpenTypeDialog. - * @param parent the parent shell. - */ - public OpenTypeInHierarchyDialog(Shell parent) { - super(parent); - setTitle(TypeHierarchyMessages.getString("OpenTypeInHierarchyDialog.title")); //$NON-NLS-1$ - setMessage(TypeHierarchyMessages.getString("OpenTypeInHierarchyDialog.message")); //$NON-NLS-1$ - setVisibleTypes(VISIBLE_TYPES); - setDialogSettings(DIALOG_SETTINGS); - } -} diff --git a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/SelectionProviderMediator.java b/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/SelectionProviderMediator.java deleted file mode 100644 index 634e95db028..00000000000 --- a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/SelectionProviderMediator.java +++ /dev/null @@ -1,200 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.browser.typehierarchy; - -import org.eclipse.swt.events.FocusEvent; -import org.eclipse.swt.events.FocusListener; -import org.eclipse.swt.widgets.Control; -import org.eclipse.swt.widgets.Widget; - -import org.eclipse.jface.util.Assert; -import org.eclipse.jface.util.ListenerList; -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.jface.viewers.StructuredSelection; -import org.eclipse.jface.viewers.StructuredViewer; - -/** - * A selection provider for viewparts with more that one viewer. - * Tracks the focus of the viewers to provide the correct selection. - */ -public class SelectionProviderMediator implements IPostSelectionProvider { - - private class InternalListener implements ISelectionChangedListener, FocusListener { - /* - * @see ISelectionChangedListener#selectionChanged - */ - public void selectionChanged(SelectionChangedEvent event) { - doSelectionChanged(event); - } - - /* - * @see FocusListener#focusGained - */ - public void focusGained(FocusEvent e) { - doFocusChanged(e.widget); - } - - /* - * @see FocusListener#focusLost - */ - public void focusLost(FocusEvent e) { - // do not reset due to focus behaviour on GTK - //fViewerInFocus= null; - } - } - - private class InternalPostSelectionListener implements ISelectionChangedListener { - public void selectionChanged(SelectionChangedEvent event) { - doPostSelectionChanged(event); - } - - } - - private StructuredViewer[] fViewers; - - private StructuredViewer fViewerInFocus; - private ListenerList fSelectionChangedListeners; - private ListenerList fPostSelectionChangedListeners; - - /** - * @param viewers All viewers that can provide a selection - */ - public SelectionProviderMediator(StructuredViewer[] viewers) { - Assert.isNotNull(viewers); - fViewers= viewers; - InternalListener listener= new InternalListener(); - fSelectionChangedListeners= new ListenerList(4); - fPostSelectionChangedListeners= new ListenerList(4); - fViewerInFocus= null; - - for (int i= 0; i < fViewers.length; i++) { - StructuredViewer viewer= fViewers[i]; - viewer.addSelectionChangedListener(listener); - viewer.addPostSelectionChangedListener(new InternalPostSelectionListener()); - Control control= viewer.getControl(); - control.addFocusListener(listener); - } - } - - void doFocusChanged(Widget control) { - for (int i= 0; i < fViewers.length; i++) { - if (fViewers[i].getControl() == control) { - propagateFocusChanged(fViewers[i]); - return; - } - } - } - - final void doPostSelectionChanged(SelectionChangedEvent event) { - ISelectionProvider provider= event.getSelectionProvider(); - if (provider == fViewerInFocus) { - firePostSelectionChanged(); - } - } - - final void doSelectionChanged(SelectionChangedEvent event) { - ISelectionProvider provider= event.getSelectionProvider(); - if (provider == fViewerInFocus) { - fireSelectionChanged(); - } - } - - final void propagateFocusChanged(StructuredViewer viewer) { - if (viewer != fViewerInFocus) { // Ok to compare by idendity - fViewerInFocus= viewer; - fireSelectionChanged(); - firePostSelectionChanged(); - } - } - - private void fireSelectionChanged() { - if (fSelectionChangedListeners != null) { - SelectionChangedEvent event= new SelectionChangedEvent(this, getSelection()); - - Object[] listeners= fSelectionChangedListeners.getListeners(); - for (int i= 0; i < listeners.length; i++) { - ISelectionChangedListener listener= (ISelectionChangedListener) listeners[i]; - listener.selectionChanged(event); - } - } - } - - private void firePostSelectionChanged() { - if (fPostSelectionChangedListeners != null) { - SelectionChangedEvent event= new SelectionChangedEvent(this, getSelection()); - - Object[] listeners= fPostSelectionChangedListeners.getListeners(); - for (int i= 0; i < listeners.length; i++) { - ISelectionChangedListener listener= (ISelectionChangedListener) listeners[i]; - listener.selectionChanged(event); - } - } - } - - /* - * @see ISelectionProvider#addSelectionChangedListener - */ - public void addSelectionChangedListener(ISelectionChangedListener listener) { - fSelectionChangedListeners.add(listener); - } - - /* - * @see ISelectionProvider#removeSelectionChangedListener - */ - public void removeSelectionChangedListener(ISelectionChangedListener listener) { - fSelectionChangedListeners.remove(listener); - } - - /* (non-Javadoc) - * @see org.eclipse.jface.viewers.IPostSelectionProvider#addPostSelectionChangedListener(org.eclipse.jface.viewers.ISelectionChangedListener) - */ - public void addPostSelectionChangedListener(ISelectionChangedListener listener) { - fPostSelectionChangedListeners.add(listener); - } - - - /* (non-Javadoc) - * @see org.eclipse.jface.viewers.IPostSelectionProvider#removePostSelectionChangedListener(org.eclipse.jface.viewers.ISelectionChangedListener) - */ - public void removePostSelectionChangedListener(ISelectionChangedListener listener) { - fPostSelectionChangedListeners.remove(listener); - } - - /* - * @see ISelectionProvider#getSelection - */ - public ISelection getSelection() { - if (fViewerInFocus != null) { - return fViewerInFocus.getSelection(); - } - return StructuredSelection.EMPTY; - } - - /* - * @see ISelectionProvider#setSelection - */ - public void setSelection(ISelection selection) { - if (fViewerInFocus != null) { - fViewerInFocus.setSelection(selection); - } - } - - /** - * Returns the viewer in focus or null if no viewer has the focus - */ - public StructuredViewer getViewerInFocus() { - return fViewerInFocus; - } -} diff --git a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/ShowInheritedMembersAction.java b/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/ShowInheritedMembersAction.java deleted file mode 100644 index 9d3aa85a8e4..00000000000 --- a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/ShowInheritedMembersAction.java +++ /dev/null @@ -1,57 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.browser.typehierarchy; - -import org.eclipse.swt.custom.BusyIndicator; - -import org.eclipse.cdt.internal.ui.CPluginImages; -import org.eclipse.cdt.internal.ui.ICHelpContextIds; -import org.eclipse.jface.action.Action; - -import org.eclipse.ui.help.WorkbenchHelp; - -/** - * Action to show / hide inherited members in the method view - * Depending in the action state a different label provider is installed in the viewer - */ -public class ShowInheritedMembersAction extends Action { - - MethodsViewer fMethodsViewer; - - /** - * Creates the action. - */ - public ShowInheritedMembersAction(MethodsViewer viewer, boolean initValue) { - super(TypeHierarchyMessages.getString("ShowInheritedMembersAction.label")); //$NON-NLS-1$ - setDescription(TypeHierarchyMessages.getString("ShowInheritedMembersAction.description")); //$NON-NLS-1$ - setToolTipText(TypeHierarchyMessages.getString("ShowInheritedMembersAction.tooltip")); //$NON-NLS-1$ - -// CPluginImages.setLocalImageDescriptors(this, "inher_co.gif"); //$NON-NLS-1$ - CPluginImages.setImageDescriptors(this, CPluginImages.T_LCL, "inher_co.gif"); //$NON-NLS-1$ - - fMethodsViewer= viewer; - - WorkbenchHelp.setHelp(this, ICHelpContextIds.SHOW_INHERITED_ACTION); - - setChecked(initValue); - } - - /* - * @see Action#actionPerformed - */ - public void run() { - BusyIndicator.showWhile(fMethodsViewer.getControl().getDisplay(), new Runnable() { - public void run() { - fMethodsViewer.showInheritedMethods(isChecked()); - } - }); - } -} diff --git a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/ShowQualifiedTypeNamesAction.java b/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/ShowQualifiedTypeNamesAction.java deleted file mode 100644 index 45dcd935e8c..00000000000 --- a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/ShowQualifiedTypeNamesAction.java +++ /dev/null @@ -1,51 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.browser.typehierarchy; - -import org.eclipse.ui.help.WorkbenchHelp; - -import org.eclipse.swt.custom.BusyIndicator; - -import org.eclipse.cdt.internal.ui.CPluginImages; -import org.eclipse.cdt.internal.ui.ICHelpContextIds; -import org.eclipse.jface.action.Action; - -/** - * Action enable / disable showing qualified type names - */ -public class ShowQualifiedTypeNamesAction extends Action { - - TypeHierarchyViewPart fView; - - public ShowQualifiedTypeNamesAction(TypeHierarchyViewPart v, boolean initValue) { - super(TypeHierarchyMessages.getString("ShowQualifiedTypeNamesAction.label")); //$NON-NLS-1$ - setDescription(TypeHierarchyMessages.getString("ShowQualifiedTypeNamesAction.description")); //$NON-NLS-1$ - setToolTipText(TypeHierarchyMessages.getString("ShowQualifiedTypeNamesAction.tooltip")); //$NON-NLS-1$ - - CPluginImages.setImageDescriptors(this, CPluginImages.T_LCL, "th_showqualified.gif"); //$NON-NLS-1$ - - fView= v; - setChecked(initValue); - - WorkbenchHelp.setHelp(this, ICHelpContextIds.SHOW_QUALIFIED_NAMES_ACTION); - } - - /* - * @see Action#actionPerformed - */ - public void run() { - BusyIndicator.showWhile(fView.getSite().getShell().getDisplay(), new Runnable() { - public void run() { - fView.showQualifiedTypeNames(isChecked()); - } - }); - } -} diff --git a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/SortByDefiningTypeAction.java b/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/SortByDefiningTypeAction.java deleted file mode 100644 index bd4bd21d6d3..00000000000 --- a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/SortByDefiningTypeAction.java +++ /dev/null @@ -1,56 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.browser.typehierarchy; - -import org.eclipse.swt.custom.BusyIndicator; - -import org.eclipse.cdt.internal.ui.CPluginImages; -import org.eclipse.cdt.internal.ui.ICHelpContextIds; -import org.eclipse.jface.action.Action; - -import org.eclipse.ui.help.WorkbenchHelp; - -/** - * Action to let the label provider show the defining type of the method - */ -public class SortByDefiningTypeAction extends Action { - - MethodsViewer fMethodsViewer; - - /** - * Creates the action. - */ - public SortByDefiningTypeAction(MethodsViewer viewer, boolean initValue) { - super(TypeHierarchyMessages.getString("SortByDefiningTypeAction.label")); //$NON-NLS-1$ - setDescription(TypeHierarchyMessages.getString("SortByDefiningTypeAction.description")); //$NON-NLS-1$ - setToolTipText(TypeHierarchyMessages.getString("SortByDefiningTypeAction.tooltip")); //$NON-NLS-1$ - -// CPluginImages.setLocalImageDescriptors(this, "definingtype_sort_co.gif"); //$NON-NLS-1$ - CPluginImages.setImageDescriptors(this, CPluginImages.T_LCL, "definingtype_sort_co.gif"); //$NON-NLS-1$ - - fMethodsViewer= viewer; - - WorkbenchHelp.setHelp(this, ICHelpContextIds.SORT_BY_DEFINING_TYPE_ACTION); - - setChecked(initValue); - } - - /* - * @see Action#actionPerformed - */ - public void run() { - BusyIndicator.showWhile(fMethodsViewer.getControl().getDisplay(), new Runnable() { - public void run() { - fMethodsViewer.sortByDefiningType(isChecked()); - } - }); - } -} diff --git a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/SubTypeHierarchyViewer.java b/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/SubTypeHierarchyViewer.java deleted file mode 100644 index 947dcc37db6..00000000000 --- a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/SubTypeHierarchyViewer.java +++ /dev/null @@ -1,93 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.browser.typehierarchy; - -import java.util.List; - -import org.eclipse.cdt.core.browser.typehierarchy.ITypeHierarchy; -import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.swt.widgets.Composite; - -import org.eclipse.ui.IWorkbenchPart; - -/** - * A viewer including the content provider for the subtype hierarchy. - * Used by the TypeHierarchyViewPart which has to provide a TypeHierarchyLifeCycle - * on construction (shared type hierarchy) - */ -public class SubTypeHierarchyViewer extends TypeHierarchyViewer { - - public SubTypeHierarchyViewer(Composite parent, TypeHierarchyLifeCycle lifeCycle, IWorkbenchPart part) { - super(parent, new SubTypeHierarchyContentProvider(lifeCycle), lifeCycle, part); - } - - /* - * @see TypeHierarchyViewer#getTitle - */ - public String getTitle() { - if (isMethodFiltering()) { - return TypeHierarchyMessages.getString("SubTypeHierarchyViewer.filtered.title"); //$NON-NLS-1$ - } - return TypeHierarchyMessages.getString("SubTypeHierarchyViewer.title"); //$NON-NLS-1$ - } - - /* - * @see TypeHierarchyViewer#updateContent - */ - public void updateContent(boolean expand) { - getTree().setRedraw(false); - refresh(); - - if (expand) { - int expandLevel= 2; - if (isMethodFiltering()) { - expandLevel++; - } - expandToLevel(expandLevel); - } - getTree().setRedraw(true); - } - - /** - * Content provider for the subtype hierarchy - */ - public static class SubTypeHierarchyContentProvider extends TypeHierarchyContentProvider { - public SubTypeHierarchyContentProvider(TypeHierarchyLifeCycle lifeCycle) { - super(lifeCycle); - } - - protected final void getTypesInHierarchy(ICElement type, List res) { - ITypeHierarchy hierarchy= getHierarchy(); - if (hierarchy != null) { - ICElement[] types= hierarchy.getSubtypes(type); - if (types != null) { - for (int i= 0; i < types.length; i++) { - res.add(types[i]); - } - } - } - - } - - protected ICElement[] getParentTypes(ICElement type) { - ITypeHierarchy hierarchy= getHierarchy(); - if (hierarchy != null) { - return hierarchy.getSupertypes(type); - // dont handle interfaces - } - return null; - } - -} - - - -} diff --git a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/SuperTypeHierarchyViewer.java b/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/SuperTypeHierarchyViewer.java deleted file mode 100644 index 30ceb991caa..00000000000 --- a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/SuperTypeHierarchyViewer.java +++ /dev/null @@ -1,79 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.browser.typehierarchy; - -import java.util.List; - -import org.eclipse.cdt.core.browser.typehierarchy.ITypeHierarchy; -import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.swt.widgets.Composite; - -import org.eclipse.ui.IWorkbenchPart; - -/** - * A viewer including the content provider for the supertype hierarchy. - * Used by the TypeHierarchyViewPart which has to provide a TypeHierarchyLifeCycle - * on construction (shared type hierarchy) - */ -public class SuperTypeHierarchyViewer extends TypeHierarchyViewer { - - public SuperTypeHierarchyViewer(Composite parent, TypeHierarchyLifeCycle lifeCycle, IWorkbenchPart part) { - super(parent, new SuperTypeHierarchyContentProvider(lifeCycle), lifeCycle, part); - } - - /* - * @see TypeHierarchyViewer#getTitle - */ - public String getTitle() { - if (isMethodFiltering()) { - return TypeHierarchyMessages.getString("SuperTypeHierarchyViewer.filtered.title"); //$NON-NLS-1$ - } - return TypeHierarchyMessages.getString("SuperTypeHierarchyViewer.title"); //$NON-NLS-1$ - } - - /* - * @see TypeHierarchyViewer#updateContent - */ - public void updateContent(boolean expand) { - getTree().setRedraw(false); - refresh(); - if (expand) { - expandAll(); - } - getTree().setRedraw(true); - } - - /* - * Content provider for the supertype hierarchy - */ - public static class SuperTypeHierarchyContentProvider extends TypeHierarchyContentProvider { - public SuperTypeHierarchyContentProvider(TypeHierarchyLifeCycle lifeCycle) { - super(lifeCycle); - } - - protected final void getTypesInHierarchy(ICElement type, List res) { - ITypeHierarchy hierarchy= getHierarchy(); - if (hierarchy != null) { - ICElement[] types= hierarchy.getSupertypes(type); - for (int i= 0; i < types.length; i++) { - res.add(types[i]); - } - } - } - - protected ICElement[] getParentTypes(ICElement type) { - // cant handle - return null; - } - - } - -} diff --git a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/ToggleLinkingAction.java b/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/ToggleLinkingAction.java deleted file mode 100644 index e3d2f4ca1c6..00000000000 --- a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/ToggleLinkingAction.java +++ /dev/null @@ -1,41 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.browser.typehierarchy; - -import org.eclipse.cdt.internal.ui.actions.AbstractToggleLinkingAction; - - -/** - * This action toggles whether the type hierarchy links its selection to the active - * editor. - * - * @since 3.0 - */ -public class ToggleLinkingAction extends AbstractToggleLinkingAction { - - TypeHierarchyViewPart fHierarchyViewPart; - - /** - * Constructs a new action. - */ - public ToggleLinkingAction(TypeHierarchyViewPart part) { - setChecked(part.isLinkingEnabled()); - fHierarchyViewPart= part; - } - - /** - * Runs the action. - */ - public void run() { - fHierarchyViewPart.setLinkingEnabled(isChecked()); - } - -} diff --git a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/ToggleOrientationAction.java b/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/ToggleOrientationAction.java deleted file mode 100644 index fbfabb3bba6..00000000000 --- a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/ToggleOrientationAction.java +++ /dev/null @@ -1,72 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.browser.typehierarchy; - -import org.eclipse.cdt.internal.ui.CPluginImages; -import org.eclipse.cdt.internal.ui.ICHelpContextIds; -import org.eclipse.jface.action.Action; -import org.eclipse.jface.util.Assert; - -import org.eclipse.ui.help.WorkbenchHelp; - -/** - * Toggles the orientationof the layout of the type hierarchy - */ -public class ToggleOrientationAction extends Action { - - private TypeHierarchyViewPart fView; - private int fActionOrientation; - - public ToggleOrientationAction(TypeHierarchyViewPart v, int orientation) { - super("", AS_RADIO_BUTTON); //$NON-NLS-1$ - if (orientation == TypeHierarchyViewPart.VIEW_ORIENTATION_HORIZONTAL) { - setText(TypeHierarchyMessages.getString("ToggleOrientationAction.horizontal.label")); //$NON-NLS-1$ - setDescription(TypeHierarchyMessages.getString("ToggleOrientationAction.horizontal.description")); //$NON-NLS-1$ - setToolTipText(TypeHierarchyMessages.getString("ToggleOrientationAction.horizontal.tooltip")); //$NON-NLS-1$ - CPluginImages.setImageDescriptors(this, CPluginImages.T_LCL, "th_horizontal.gif"); //$NON-NLS-1$ - } else if (orientation == TypeHierarchyViewPart.VIEW_ORIENTATION_VERTICAL) { - setText(TypeHierarchyMessages.getString("ToggleOrientationAction.vertical.label")); //$NON-NLS-1$ - setDescription(TypeHierarchyMessages.getString("ToggleOrientationAction.vertical.description")); //$NON-NLS-1$ - setToolTipText(TypeHierarchyMessages.getString("ToggleOrientationAction.vertical.tooltip")); //$NON-NLS-1$ - CPluginImages.setImageDescriptors(this, CPluginImages.T_LCL, "th_vertical.gif"); //$NON-NLS-1$ - } else if (orientation == TypeHierarchyViewPart.VIEW_ORIENTATION_AUTOMATIC) { - setText(TypeHierarchyMessages.getString("ToggleOrientationAction.automatic.label")); //$NON-NLS-1$ - setDescription(TypeHierarchyMessages.getString("ToggleOrientationAction.automatic.description")); //$NON-NLS-1$ - setToolTipText(TypeHierarchyMessages.getString("ToggleOrientationAction.automatic.tooltip")); //$NON-NLS-1$ - CPluginImages.setImageDescriptors(this, CPluginImages.T_LCL, "th_automatic.gif"); //$NON-NLS-1$ - } else if (orientation == TypeHierarchyViewPart.VIEW_ORIENTATION_SINGLE) { - setText(TypeHierarchyMessages.getString("ToggleOrientationAction.single.label")); //$NON-NLS-1$ - setDescription(TypeHierarchyMessages.getString("ToggleOrientationAction.single.description")); //$NON-NLS-1$ - setToolTipText(TypeHierarchyMessages.getString("ToggleOrientationAction.single.tooltip")); //$NON-NLS-1$ - CPluginImages.setImageDescriptors(this, CPluginImages.T_LCL, "th_single.gif"); //$NON-NLS-1$ - } else { - Assert.isTrue(false); - } - fView= v; - fActionOrientation= orientation; - WorkbenchHelp.setHelp(this, ICHelpContextIds.TOGGLE_ORIENTATION_ACTION); - } - - public int getOrientation() { - return fActionOrientation; - } - - /* - * @see Action#actionPerformed - */ - public void run() { - if (isChecked()) { - fView.fOrientation= fActionOrientation; - fView.computeOrientation(); - } - } - -} diff --git a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/ToggleViewAction.java b/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/ToggleViewAction.java deleted file mode 100644 index 1fe64cd02f3..00000000000 --- a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/ToggleViewAction.java +++ /dev/null @@ -1,63 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.browser.typehierarchy; - -import org.eclipse.cdt.internal.ui.CPluginImages; -import org.eclipse.cdt.internal.ui.ICHelpContextIds; -import org.eclipse.jface.action.Action; -import org.eclipse.jface.util.Assert; - -import org.eclipse.ui.help.WorkbenchHelp; - -/** - * Action to switch between the different hierarchy views. - */ -public class ToggleViewAction extends Action { - - private TypeHierarchyViewPart fViewPart; - private int fViewerIndex; - - public ToggleViewAction(TypeHierarchyViewPart v, int viewerIndex) { - super("", AS_RADIO_BUTTON); //$NON-NLS-1$ - String contextHelpId= null; - if (viewerIndex == TypeHierarchyViewPart.VIEW_ID_SUPER) { - setText(TypeHierarchyMessages.getString("ToggleViewAction.supertypes.label")); //$NON-NLS-1$ - contextHelpId= ICHelpContextIds.SHOW_SUPERTYPES; - setDescription(TypeHierarchyMessages.getString("ToggleViewAction.supertypes.description")); //$NON-NLS-1$ - setToolTipText(TypeHierarchyMessages.getString("ToggleViewAction.supertypes.tooltip")); //$NON-NLS-1$ - CPluginImages.setImageDescriptors(this, CPluginImages.T_LCL, "super_co.gif"); //$NON-NLS-1$ - } else if (viewerIndex == TypeHierarchyViewPart.VIEW_ID_SUB) { - setText(TypeHierarchyMessages.getString("ToggleViewAction.subtypes.label")); //$NON-NLS-1$ - contextHelpId= ICHelpContextIds.SHOW_SUBTYPES; - setDescription(TypeHierarchyMessages.getString("ToggleViewAction.subtypes.description")); //$NON-NLS-1$ - setToolTipText(TypeHierarchyMessages.getString("ToggleViewAction.subtypes.tooltip")); //$NON-NLS-1$ - CPluginImages.setImageDescriptors(this, CPluginImages.T_LCL, "sub_co.gif"); //$NON-NLS-1$ - } else { - Assert.isTrue(false); - } - - fViewPart= v; - fViewerIndex= viewerIndex; - - WorkbenchHelp.setHelp(this, contextHelpId); - } - - public int getViewerIndex() { - return fViewerIndex; - } - - /* - * @see Action#actionPerformed - */ - public void run() { - fViewPart.setView(fViewerIndex); - } -} diff --git a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/TypeHierarchyContentProvider.java b/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/TypeHierarchyContentProvider.java deleted file mode 100644 index 72e11994653..00000000000 --- a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/TypeHierarchyContentProvider.java +++ /dev/null @@ -1,296 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.browser.typehierarchy; - -import java.util.ArrayList; -import java.util.List; - -import org.eclipse.cdt.core.browser.TypeUtil; -import org.eclipse.cdt.core.browser.typehierarchy.ITypeHierarchy; -import org.eclipse.cdt.core.model.CModelException; -import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.cdt.core.model.IMember; -import org.eclipse.cdt.core.model.IMethodDeclaration; -import org.eclipse.jface.util.Assert; -import org.eclipse.jface.viewers.ITreeContentProvider; -import org.eclipse.jface.viewers.TreeViewer; -import org.eclipse.jface.viewers.Viewer; -import org.eclipse.jface.viewers.ViewerFilter; - -/** - * Base class for content providers for type hierarchy viewers. - * Implementors must override 'getTypesInHierarchy'. - * Java delta processing is also performed by the content provider - */ -public abstract class TypeHierarchyContentProvider implements ITreeContentProvider //, IWorkingCopyProvider { -{ - protected static final Object[] NO_ELEMENTS= new Object[0]; - - protected TypeHierarchyLifeCycle fTypeHierarchy; - protected IMember[] fMemberFilter; - - protected TreeViewer fViewer; - - private ViewerFilter fWorkingSetFilter; - - public TypeHierarchyContentProvider(TypeHierarchyLifeCycle lifecycle) { - fTypeHierarchy= lifecycle; - fMemberFilter= null; - fWorkingSetFilter= null; - } - - /** - * Sets members to filter the hierarchy for. Set to null to disable member filtering. - * When member filtering is enabled, the hierarchy contains only types that contain - * an implementation of one of the filter members and the members themself. - * The hierarchy can be empty as well. - */ - public final void setMemberFilter(IMember[] memberFilter) { - fMemberFilter= memberFilter; - } - - /** - * The members to filter or null if member filtering is disabled. - */ - public IMember[] getMemberFilter() { - return fMemberFilter; - } - - /** - * Sets a filter representing a working set or null if working sets are disabled. - */ - public void setWorkingSetFilter(ViewerFilter filter) { - fWorkingSetFilter= filter; - } - - - protected final ITypeHierarchy getHierarchy() { - return fTypeHierarchy.getHierarchy(); - } - - - /* (non-Javadoc) - * @see IReconciled#providesWorkingCopies() - */ - public boolean providesWorkingCopies() { - return true; - } - - - /* - * Called for the root element - * @see IStructuredContentProvider#getElements - */ - public Object[] getElements(Object parent) { - ArrayList types= new ArrayList(); - getRootTypes(types); - for (int i= types.size() - 1; i >= 0; i--) { - ICElement curr= (ICElement) types.get(i); - try { - if (!isInTree(curr)) { - types.remove(i); - } - } catch (CModelException e) { - // ignore - } - } - return types.toArray(); - } - - protected void getRootTypes(List res) { - ITypeHierarchy hierarchy= getHierarchy(); - if (hierarchy != null) { - ICElement input= hierarchy.getType(); - if (input != null) { - res.add(input); - } - // opened on a region: dont show - } - } - - /** - * Hook to overwrite. Filter will be applied on the returned types - */ - protected abstract void getTypesInHierarchy(ICElement type, List res); - - /** - * Hook to overwrite. Return null if parent is ambiguous. - */ - protected abstract ICElement[] getParentTypes(ICElement type); - - - private boolean isInScope(ICElement type) { - if (fWorkingSetFilter != null && !fWorkingSetFilter.select(null, null, type)) { - return false; - } - -// ICElement input= fTypeHierarchy.getInputElement(); -// int inputType= input.getElementType(); -// if (inputType == ICElement.TYPE) { -// return true; -// } -// -// ICElement parent= type.getAncestor(input.getElementType()); -// if (inputType == ICElement.PACKAGE_FRAGMENT) { -// if (parent == null || parent.getElementName().equals(input.getElementName())) { -// return true; -// } -// } else if (input.equals(parent)) { -// return true; -// } - return true; - } - - /* - * Called for the tree children. - * @see ITreeContentProvider#getChildren - */ - public Object[] getChildren(Object element) { - if (element instanceof ICElement) { - try { - ICElement type= (ICElement)element; - - List children= new ArrayList(); - if (fMemberFilter != null) { - addFilteredMemberChildren(type, children); - } - - addTypeChildren(type, children); - - return children.toArray(); - } catch (CModelException e) { - // ignore - } - } - return NO_ELEMENTS; - } - - /* - * @see ITreeContentProvider#hasChildren - */ - public boolean hasChildren(Object element) { - if (element instanceof ICElement) { - try { - ICElement type= (ICElement) element; - return hasTypeChildren(type) || (fMemberFilter != null && hasMemberFilterChildren(type)); - } catch (CModelException e) { - return false; - } - } - return false; - } - - private void addFilteredMemberChildren(ICElement parent, List children) throws CModelException { - IMethodDeclaration[] methods= TypeUtil.getMethods(parent); - if (methods != null && methods.length > 0) { - for (int i= 0; i < fMemberFilter.length; i++) { - IMember member= fMemberFilter[i]; - if (parent.equals(TypeUtil.getDeclaringClass(member))) { - if (!children.contains(member)) { - children.add(member); - } - } else if (member instanceof IMethodDeclaration) { - IMethodDeclaration curr= (IMethodDeclaration)member; - IMethodDeclaration meth= TypeUtil.findMethod(curr.getElementName(), curr.getParameterTypes(), curr.isConstructor(), curr.isDestructor(), methods); - if (meth != null && !children.contains(meth)) { - children.add(meth); - } - } - } - } - } - - private void addTypeChildren(ICElement type, List children) throws CModelException { - ArrayList types= new ArrayList(); - getTypesInHierarchy(type, types); - int len= types.size(); - for (int i= 0; i < len; i++) { - ICElement curr= (ICElement) types.get(i); - if (isInTree(curr)) { - children.add(curr); - } - } - } - - protected final boolean isInTree(ICElement type) throws CModelException { - if (isInScope(type)) { - if (fMemberFilter != null) { - return hasMemberFilterChildren(type) || hasTypeChildren(type); - } - return true; - } - return hasTypeChildren(type); - } - - private boolean hasMemberFilterChildren(ICElement type) throws CModelException { - IMethodDeclaration[] methods= TypeUtil.getMethods(type); - if (methods != null && methods.length > 0) { - for (int i= 0; i < fMemberFilter.length; i++) { - IMember member= fMemberFilter[i]; - if (type.equals(TypeUtil.getDeclaringClass(member))) { - return true; - } else if (member instanceof IMethodDeclaration) { - IMethodDeclaration curr= (IMethodDeclaration)member; - IMethodDeclaration meth= TypeUtil.findMethod(curr.getElementName(), curr.getParameterTypes(), curr.isConstructor(), curr.isDestructor(), methods); - if (meth != null) { - return true; - } - } - } - } - return false; - } - - - private boolean hasTypeChildren(ICElement type) throws CModelException { - ArrayList types= new ArrayList(); - getTypesInHierarchy(type, types); - int len= types.size(); - for (int i= 0; i < len; i++) { - ICElement curr= (ICElement) types.get(i); - if (isInTree(curr)) { - return true; - } - } - return false; - } - - /* - * @see IContentProvider#inputChanged - */ - public void inputChanged(Viewer part, Object oldInput, Object newInput) { - Assert.isTrue(part instanceof TreeViewer); - fViewer= (TreeViewer)part; - } - - /* - * @see IContentProvider#dispose - */ - public void dispose() { - } - - /* - * @see ITreeContentProvider#getParent - */ - public Object getParent(Object element) { - if (element instanceof IMember) { - IMember member= (IMember) element; -// if (member.getElementType() == ICElement.TYPE) { - if (TypeUtil.isClassOrStruct(member)) { - ICElement[] parents= getParentTypes(member); - if (parents != null && parents.length == 1) - return parents[0]; - } - return TypeUtil.getDeclaringClass(member); - } - return null; - } -} diff --git a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/TypeHierarchyLifeCycle.java b/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/TypeHierarchyLifeCycle.java deleted file mode 100644 index 98a4bb97fe9..00000000000 --- a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/TypeHierarchyLifeCycle.java +++ /dev/null @@ -1,273 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.browser.typehierarchy; - -import java.lang.reflect.InvocationTargetException; -import java.util.ArrayList; -import java.util.List; - -import org.eclipse.cdt.core.browser.AllTypesCache; -import org.eclipse.cdt.core.browser.typehierarchy.ITypeHierarchy; -import org.eclipse.cdt.core.browser.typehierarchy.ITypeHierarchyChangedListener; -import org.eclipse.cdt.core.model.CModelException; -import org.eclipse.cdt.core.model.CoreModel; -import org.eclipse.cdt.core.model.ElementChangedEvent; -import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.cdt.core.model.ICElementDelta; -import org.eclipse.cdt.core.model.IElementChangedListener; -import org.eclipse.cdt.core.model.ITranslationUnit; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.OperationCanceledException; -import org.eclipse.jface.operation.IRunnableContext; -import org.eclipse.jface.operation.IRunnableWithProgress; - -/** - * Manages a type hierarchy, to keep it refreshed, and to allow it to be shared. - */ -public class TypeHierarchyLifeCycle implements ITypeHierarchyChangedListener, IElementChangedListener { - - private boolean fHierarchyRefreshNeeded; - private ITypeHierarchy fHierarchy; - private ICElement fInputElement; - - private List fChangeListeners; - - public TypeHierarchyLifeCycle() { - this(true); - } - - public TypeHierarchyLifeCycle(boolean isSuperTypesOnly) { - fHierarchy= null; - fInputElement= null; - fChangeListeners= new ArrayList(2); - } - - public ITypeHierarchy getHierarchy() { - return fHierarchy; - } - - public ICElement getInputElement() { - return fInputElement; - } - - - public void freeHierarchy() { - if (fHierarchy != null) { - fHierarchy.removeTypeHierarchyChangedListener(this); - CoreModel.getDefault().removeElementChangedListener(this); - fHierarchy= null; - fInputElement= null; - } - } - - public void removeChangedListener(ITypeHierarchyLifeCycleListener listener) { - fChangeListeners.remove(listener); - } - - public void addChangedListener(ITypeHierarchyLifeCycleListener listener) { - if (!fChangeListeners.contains(listener)) { - fChangeListeners.add(listener); - } - } - - private void fireChange(ICElement[] changedTypes) { - for (int i= fChangeListeners.size()-1; i>=0; i--) { - ITypeHierarchyLifeCycleListener curr= (ITypeHierarchyLifeCycleListener) fChangeListeners.get(i); - curr.typeHierarchyChanged(this, changedTypes); - } - } - - public void ensureRefreshedTypeHierarchy(final ICElement element, IRunnableContext context) throws InvocationTargetException, InterruptedException { - if (element == null || !element.exists()) { - freeHierarchy(); - return; - } - boolean hierachyCreationNeeded= (fHierarchy == null || !element.equals(fInputElement)); - - if (hierachyCreationNeeded || fHierarchyRefreshNeeded) { - - IRunnableWithProgress op= new IRunnableWithProgress() { - public void run(IProgressMonitor pm) throws InvocationTargetException, InterruptedException { - try { - doHierarchyRefresh(element, pm); - } catch (CModelException e) { - throw new InvocationTargetException(e); - } catch (OperationCanceledException e) { - throw new InterruptedException(); - } - } - }; - fHierarchyRefreshNeeded= true; - context.run(true, true, op); - fHierarchyRefreshNeeded= false; - } - } - - private ITypeHierarchy createTypeHierarchy(ICElement element, IProgressMonitor pm) throws CModelException { - if (element.getElementType() == ICElement.C_CLASS - || element.getElementType() == ICElement.C_STRUCT) { - return AllTypesCache.createTypeHierarchy(element, pm); - } else { -// IRegion region= JavaCore.newRegion(); -// if (element.getElementType() == ICElement.JAVA_PROJECT) { -// // for projects only add the contained source folders -// IPackageFragmentRoot[] roots= ((IJavaProject) element).getPackageFragmentRoots(); -// for (int i= 0; i < roots.length; i++) { -// if (!roots[i].isExternal()) { -// region.add(roots[i]); -// } -// } -// } else if (element.getElementType() == ICElement.PACKAGE_FRAGMENT) { -// IPackageFragmentRoot[] roots= element.getJavaProject().getPackageFragmentRoots(); -// String name= element.getElementName(); -// for (int i= 0; i < roots.length; i++) { -// IPackageFragment pack= roots[i].getPackageFragment(name); -// if (pack.exists()) { -// region.add(pack); -// } -// } -// } else { -// region.add(element); -// } -// ICProject jproject= element.getCProject(); -// return jproject.newTypeHierarchy(region, pm); - return null; - } - } - - - public synchronized void doHierarchyRefresh(ICElement element, IProgressMonitor pm) throws CModelException { - boolean hierachyCreationNeeded= (fHierarchy == null || !element.equals(fInputElement)); - // to ensure the order of the two listeners always remove / add listeners on operations - // on type hierarchies - if (fHierarchy != null) { - fHierarchy.removeTypeHierarchyChangedListener(this); - CoreModel.getDefault().removeElementChangedListener(this); - } - if (hierachyCreationNeeded) { - fHierarchy= createTypeHierarchy(element, pm); - if (pm != null && pm.isCanceled()) { - throw new OperationCanceledException(); - } - fInputElement= element; - } else if (fHierarchy != null) { - fHierarchy.refresh(pm); - } - if (fHierarchy != null) { - fHierarchy.addTypeHierarchyChangedListener(this); - } - CoreModel.getDefault().addElementChangedListener(this); - fHierarchyRefreshNeeded= false; - } - - /* - * @see ITypeHierarchyChangedListener#typeHierarchyChanged - */ - public void typeHierarchyChanged(ITypeHierarchy typeHierarchy) { - fHierarchyRefreshNeeded= true; - fireChange(null); - } - - /* - * @see IElementChangedListener#elementChanged(ElementChangedEvent) - */ - public void elementChanged(ElementChangedEvent event) { - if (fChangeListeners.isEmpty()) { - return; - } - - if (fHierarchyRefreshNeeded) { - return; - } - ArrayList changedTypes= new ArrayList(); - processDelta(event.getDelta(), changedTypes); - if (changedTypes.size() > 0) { - fireChange((ICElement[]) changedTypes.toArray(new ICElement[changedTypes.size()])); - } - } - - /* - * Assume that the hierarchy is intact (no refresh needed) - */ - private void processDelta(ICElementDelta delta, ArrayList changedTypes) { - ICElement element= delta.getElement(); - switch (element.getElementType()) { -// case ICElement.TYPE: - case ICElement.C_CLASS: - case ICElement.C_STRUCT: - processTypeDelta(element, changedTypes); - processChildrenDelta(delta, changedTypes); // (inner types) - break; - case ICElement.C_MODEL: - case ICElement.C_PROJECT: -// case ICElement.PACKAGE_FRAGMENT_ROOT: -// case ICElement.PACKAGE_FRAGMENT: - processChildrenDelta(delta, changedTypes); - break; - case ICElement.C_UNIT: - ITranslationUnit cu= (ITranslationUnit)element; -// if (!CModelUtil.isPrimary(cu)) { -// return; -// } - - if (delta.getKind() == ICElementDelta.CHANGED && isPossibleStructuralChange(delta.getFlags())) { -// try { - if (cu.exists()) { -// IType[] types= cu.getAllTypes(); - ICElement[] types= getAllTypesForTranslationUnit(cu); for (int i= 0; i < types.length; i++) { - processTypeDelta(types[i], changedTypes); - } - } -// } catch (CModelException e) { -// CUIPlugin.getDefault().log(e); -// } - } else { - processChildrenDelta(delta, changedTypes); - } - break; -// case ICElement.CLASS_FILE: -// if (delta.getKind() == ICElementDelta.CHANGED) { -// try { -// IType type= ((IClassFile) element).getType(); -// processTypeDelta(type, changedTypes); -// } catch (CModelException e) { -// CUIPlugin.getDefault().log(e); -// } -// } else { -// processChildrenDelta(delta, changedTypes); -// } -// break; - } - } - - private boolean isPossibleStructuralChange(int flags) { - return (flags & (ICElementDelta.F_CONTENT | ICElementDelta.F_FINE_GRAINED)) == ICElementDelta.F_CONTENT; - } - - private void processTypeDelta(ICElement type, ArrayList changedTypes) { - if (getHierarchy().contains(type)) { - changedTypes.add(type); - } - } - - private void processChildrenDelta(ICElementDelta delta, ArrayList changedTypes) { - ICElementDelta[] children= delta.getAffectedChildren(); - for (int i= 0; i < children.length; i++) { - processDelta(children[i], changedTypes); // recursive - } - } - - private static ICElement[] getAllTypesForTranslationUnit(ITranslationUnit unit) { - return null; - } - - -} diff --git a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/TypeHierarchyMessages.java b/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/TypeHierarchyMessages.java deleted file mode 100644 index d86960efd2f..00000000000 --- a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/TypeHierarchyMessages.java +++ /dev/null @@ -1,51 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.browser.typehierarchy; - -import java.text.MessageFormat; -import java.util.MissingResourceException; -import java.util.ResourceBundle; - -public class TypeHierarchyMessages { - - private static final String RESOURCE_BUNDLE= TypeHierarchyMessages.class.getName(); - private static ResourceBundle fgResourceBundle= ResourceBundle.getBundle(RESOURCE_BUNDLE); - - private TypeHierarchyMessages() { - } - - public static String getString(String key) { - try { - return fgResourceBundle.getString(key); - } catch (MissingResourceException e) { - return '!' + key + '!'; - } - } - - /** - * Gets a string from the resource bundle and formats it with the argument - * - * @param key the string used to get the bundle value, must not be null - */ - public static String getFormattedString(String key, Object arg) { - return MessageFormat.format(getString(key), new Object[] { arg }); - } - - - /** - * Gets a string from the resource bundle and formats it with arguments - */ - public static String getFormattedString(String key, Object[] args) { - return MessageFormat.format(getString(key), args); - } - - -} diff --git a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/TypeHierarchyMessages.properties b/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/TypeHierarchyMessages.properties deleted file mode 100644 index fd87439f7a6..00000000000 --- a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/TypeHierarchyMessages.properties +++ /dev/null @@ -1,105 +0,0 @@ -############################################################################### -# Copyright (c) 2003, 2005 IBM Corporation and others. -# All rights reserved. This program and the accompanying materials -# are made available under the terms of the Eclipse Public License v1.0 -# which accompanies this distribution, and is available at -# http://www.eclipse.org/legal/epl-v10.html -# -# Contributors: -# IBM Corporation - initial API and implementation -# QNX Software Systems - adapted for use in CDT -############################################################################### - -EnableMemberFilterAction.label=Members in Hierarchy -EnableMemberFilterAction.tooltip=Lock View and Show Members in Hierarchy -EnableMemberFilterAction.description=Lock view and show members in hierarchy - -ToggleOrientationAction.horizontal.label=Horizontal View Orientation -ToggleOrientationAction.horizontal.tooltip=Horizontal View Orientation -ToggleOrientationAction.horizontal.description=Horizontal View Orientation - -ToggleOrientationAction.vertical.label=Vertical View Orientation -ToggleOrientationAction.vertical.tooltip=Vertical View Orientation -ToggleOrientationAction.vertical.description=Vertical View Orientation - -ToggleOrientationAction.automatic.label=Automatic View Orientation -ToggleOrientationAction.automatic.tooltip=Automatic View Orientation -ToggleOrientationAction.automatic.description=Automatic View Orientation - -ToggleOrientationAction.single.label=Hierarchy View Only -ToggleOrientationAction.single.tooltip=Hierarchy View Only -ToggleOrientationAction.single.description=Hierarchy View Only - -FocusOnSelectionAction.label=Fo&cus On ''{0}'' -FocusOnSelectionAction.tooltip=Focus the Type Hierarchy on the Selected Element -FocusOnSelectionAction.description=Focus the Type Hierarchy on the selected element - -FocusOnTypeAction.label=&Focus On... -FocusOnTypeAction.tooltip=Focus the Type Hierarchy on a New Type -FocusOnTypeAction.description=Focus the Type Hierarchy on a new type -FocusOnTypeAction.dialog.title=Focus On Type -FocusOnTypeAction.dialog.message=&Select the type to be shown in the Type Hierarchy view: - -HistoryDropDownAction.tooltip=Previous Type Hierarchies - -HistoryAction.description=Open ''{0}'' in Hierarchy -HistoryAction.tooltip=Open ''{0}'' in Hierarchy - -HistoryListDialog.title=Type Hierarchy History -HistoryListDialog.label=&Select the element to open in the type hierarchy: -HistoryListDialog.remove.button=&Remove - -HistoryListAction.label=More... - -ShowInheritedMembersAction.label=All Inherited Members -ShowInheritedMembersAction.tooltip=Show All Inherited Members -ShowInheritedMembersAction.description=Show all inherited members - -ShowQualifiedTypeNamesAction.label=Show Qualified Type Names -ShowQualifiedTypeNamesAction.tooltip=Show Qualified Type Names -ShowQualifiedTypeNamesAction.description=Show qualified type names - -SortByDefiningTypeAction.label=Sort by the Defining Type -SortByDefiningTypeAction.tooltip=Sort Methods by the Defining Type -SortByDefiningTypeAction.description=Sort methods by the defining type - -SubTypeHierarchyViewer.title=Hierarchy -SubTypeHierarchyViewer.filtered.title=Hierarchy - -SuperTypeHierarchyViewer.title=Hierarchy -SuperTypeHierarchyViewer.filtered.title=Hierarchy - -TraditionalHierarchyViewer.title=Hierarchy -TraditionalHierarchyViewer.filtered.title=Hierarchy - -TypeHierarchyViewPart.error.title=Open Type Hierarchy -TypeHierarchyViewPart.error.message=The selected element only exists in the editor. To perform this operation you have to save the editor first. -TypeHierarchyViewPart.empty=To display the type hierarchy, select a structure or class (for example in the outline view or in the editor), and select the \'Open Type Hierarchy\' menu option. -TypeHierarchyViewPart.nodecl=No declarations of selected members\nin the chosen hierarchy of ''{0}'' -TypeHierarchyViewPart.exception.title=Type Hierarchy -TypeHierarchyViewPart.exception.message=Creating hierarchy failed. Check log for details. - -TypeHierarchyViewPart.title={0} : {1} -TypeHierarchyViewPart.tooltip={0} of ''{1}'' - -TypeHierarchyViewPart.layout.submenu=&Layout - -OpenTypeInHierarchyDialog.title=Open Type In Hierarchy -OpenTypeInHierarchyDialog.message=&Choose a type (? = any character, * = any string): - -ToggleViewAction.subtypes.label=Subtype Hierarchy -ToggleViewAction.subtypes.tooltip=Show the Subtype Hierarchy -ToggleViewAction.subtypes.description=Show the subtype hierarchy - -ToggleViewAction.supertypes.label=Supertype Hierarchy -ToggleViewAction.supertypes.tooltip=Show the Supertype Hierarchy -ToggleViewAction.supertypes.description=Show the supertype hierarchy - -ToggleViewAction.vajhierarchy.label=Type Hierarchy -ToggleViewAction.vajhierarchy.tooltip=Show the Type Hierarchy -ToggleViewAction.vajhierarchy.description=Show the type hierarchy - -HierarchyInformationControl.methodhierarchy.label=Types implementing or defining ''{0}.{1}'' -HierarchyInformationControl.hierarchy.label=Type hierarchy of ''{0}'': -HierarchyInformationControl.toggle.traditionalhierarchy.label=Press ''{0}'' to see the Subtype hierarchy -HierarchyInformationControl.toggle.superhierarchy.label=Press ''{0}'' to see the Supertype hierarchy diff --git a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/TypeHierarchyViewPart.java b/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/TypeHierarchyViewPart.java deleted file mode 100644 index 29f3ad55098..00000000000 --- a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/TypeHierarchyViewPart.java +++ /dev/null @@ -1,1570 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.browser.typehierarchy; - -import java.lang.reflect.InvocationTargetException; -import java.util.ArrayList; -import java.util.List; - -import org.eclipse.cdt.core.browser.TypeUtil; -import org.eclipse.cdt.core.browser.typehierarchy.ITypeHierarchy; -import org.eclipse.cdt.core.model.CModelException; -import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.cdt.core.model.IMember; -import org.eclipse.cdt.core.model.IStructure; -import org.eclipse.cdt.core.model.ITranslationUnit; -import org.eclipse.cdt.internal.ui.ICHelpContextIds; -import org.eclipse.cdt.internal.ui.IContextMenuConstants; -import org.eclipse.cdt.internal.ui.actions.CompositeActionGroup; -import org.eclipse.cdt.internal.ui.actions.SelectAllAction; -import org.eclipse.cdt.internal.ui.util.EditorUtility; -import org.eclipse.cdt.internal.ui.util.ExceptionHandler; -import org.eclipse.cdt.internal.ui.viewsupport.CElementLabels; -import org.eclipse.cdt.internal.ui.viewsupport.CUILabelProvider; -import org.eclipse.cdt.internal.ui.viewsupport.IViewPartInputProvider; -import org.eclipse.cdt.internal.ui.viewsupport.StatusBarUpdater; -import org.eclipse.cdt.internal.ui.workingsets.WorkingSetFilterActionGroup; -import org.eclipse.cdt.ui.CUIPlugin; -import org.eclipse.cdt.ui.PreferenceConstants; -import org.eclipse.cdt.ui.actions.OpenViewActionGroup; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.OperationCanceledException; -import org.eclipse.core.runtime.Status; -import org.eclipse.core.runtime.jobs.Job; -import org.eclipse.jface.action.IMenuListener; -import org.eclipse.jface.action.IMenuManager; -import org.eclipse.jface.action.IStatusLineManager; -import org.eclipse.jface.action.IToolBarManager; -import org.eclipse.jface.action.MenuManager; -import org.eclipse.jface.action.Separator; -import org.eclipse.jface.action.ToolBarManager; -import org.eclipse.jface.dialogs.IDialogSettings; -import org.eclipse.jface.dialogs.MessageDialog; -import org.eclipse.jface.util.Assert; -import org.eclipse.jface.util.IPropertyChangeListener; -import org.eclipse.jface.util.PropertyChangeEvent; -import org.eclipse.jface.viewers.IBasicPropertyConstants; -import org.eclipse.jface.viewers.ISelection; -import org.eclipse.jface.viewers.ISelectionChangedListener; -import org.eclipse.jface.viewers.IStructuredSelection; -import org.eclipse.jface.viewers.SelectionChangedEvent; -import org.eclipse.jface.viewers.StructuredSelection; -import org.eclipse.jface.viewers.StructuredViewer; -import org.eclipse.swt.SWT; -import org.eclipse.swt.custom.BusyIndicator; -import org.eclipse.swt.custom.CLabel; -import org.eclipse.swt.custom.SashForm; -import org.eclipse.swt.custom.ViewForm; -import org.eclipse.swt.events.ControlEvent; -import org.eclipse.swt.events.ControlListener; -import org.eclipse.swt.events.FocusEvent; -import org.eclipse.swt.events.FocusListener; -import org.eclipse.swt.events.KeyAdapter; -import org.eclipse.swt.events.KeyEvent; -import org.eclipse.swt.events.KeyListener; -import org.eclipse.swt.graphics.Point; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Control; -import org.eclipse.swt.widgets.Display; -import org.eclipse.swt.widgets.Label; -import org.eclipse.swt.widgets.ScrollBar; -import org.eclipse.swt.widgets.ToolBar; -import org.eclipse.ui.IActionBars; -import org.eclipse.ui.IEditorPart; -import org.eclipse.ui.IMemento; -import org.eclipse.ui.IPageLayout; -import org.eclipse.ui.IPartListener2; -import org.eclipse.ui.IViewSite; -import org.eclipse.ui.IWorkbenchActionConstants; -import org.eclipse.ui.IWorkbenchPart; -import org.eclipse.ui.IWorkbenchPartReference; -import org.eclipse.ui.IWorkingSetManager; -import org.eclipse.ui.PartInitException; -import org.eclipse.ui.actions.ActionContext; -import org.eclipse.ui.actions.ActionFactory; -import org.eclipse.ui.actions.ActionGroup; -import org.eclipse.ui.help.WorkbenchHelp; -import org.eclipse.ui.part.IShowInSource; -import org.eclipse.ui.part.IShowInTargetList; -import org.eclipse.ui.part.PageBook; -import org.eclipse.ui.part.ShowInContext; -import org.eclipse.ui.part.ViewPart; - -/** - * view showing the super types/sub types of its input. - */ -public class TypeHierarchyViewPart extends ViewPart implements ITypeHierarchyViewPart, IViewPartInputProvider { - - public static final int VIEW_ID_SUPER= 0; - public static final int VIEW_ID_SUB= 1; - - public static final int VIEW_ORIENTATION_VERTICAL= 0; - public static final int VIEW_ORIENTATION_HORIZONTAL= 1; - public static final int VIEW_ORIENTATION_SINGLE= 2; - public static final int VIEW_ORIENTATION_AUTOMATIC= 3; - - private static final String DIALOGSTORE_HIERARCHYVIEW= "TypeHierarchyViewPart.hierarchyview"; //$NON-NLS-1$ - private static final String DIALOGSTORE_VIEWORIENTATION= "TypeHierarchyViewPart.orientation"; //$NON-NLS-1$ - - //private static final String TAG_INPUT= "input"; //$NON-NLS-1$ - private static final String TAG_VIEW= "view"; //$NON-NLS-1$ - private static final String TAG_ORIENTATION= "orientation"; //$NON-NLS-1$ - private static final String TAG_RATIO= "ratio"; //$NON-NLS-1$ - //private static final String TAG_SELECTION= "selection"; //$NON-NLS-1$ - private static final String TAG_VERTICAL_SCROLL= "vertical_scroll"; //$NON-NLS-1$ - - private static final String GROUP_FOCUS= "group.focus"; //$NON-NLS-1$ - - - // the selected type in the hierarchy view - private ICElement fSelectedType; - // input element or null - private ICElement fInputElement; - - // history of input elements. No duplicates - private ArrayList fInputHistory; - - private IMemento fMemento; - private IDialogSettings fDialogSettings; - - protected TypeHierarchyLifeCycle fHierarchyLifeCycle; - private ITypeHierarchyLifeCycleListener fTypeHierarchyLifeCycleListener; - - private IPropertyChangeListener fPropertyChangeListener; - - private SelectionProviderMediator fSelectionProviderMediator; - private ISelectionChangedListener fSelectionChangedListener; - private IPartListener2 fPartListener; - - private int fCurrentOrientation; - int fOrientation= VIEW_ORIENTATION_AUTOMATIC; - boolean fInComputeOrientation= false; - - private boolean fLinkingEnabled; - private boolean fSelectInEditor; - - private boolean fIsVisible; - private boolean fNeedRefresh; - private boolean fIsEnableMemberFilter; - protected boolean fIsRefreshRunnablePosted; - - private int fCurrentViewerIndex; - private TypeHierarchyViewer[] fAllViewers; - - protected MethodsViewer fMethodsViewer; - - private SashForm fTypeMethodsSplitter; - private PageBook fViewerbook; - protected PageBook fPagebook; - - private Label fNoHierarchyShownLabel; - private Label fEmptyTypesViewer; - - private ViewForm fTypeViewerViewForm; - private ViewForm fMethodViewerViewForm; - - private CLabel fMethodViewerPaneLabel; - private CUILabelProvider fPaneLabelProvider; - private Composite fParent; - - private ToggleViewAction[] fViewActions; - private ToggleLinkingAction fToggleLinkingAction; - private HistoryDropDownAction fHistoryDropDownAction; - private ToggleOrientationAction[] fToggleOrientationActions; - private EnableMemberFilterAction fEnableMemberFilterAction; - private ShowQualifiedTypeNamesAction fShowQualifiedTypeNamesAction; -// private AddMethodStubAction fAddStubAction; - private FocusOnTypeAction fFocusOnTypeAction; - private FocusOnSelectionAction fFocusOnSelectionAction; - private CompositeActionGroup fActionGroups; - protected SelectAllAction fSelectAllAction; - - private WorkingSetFilterActionGroup fWorkingSetActionGroup; - private Job fRestoreStateJob; - - public TypeHierarchyViewPart() { - fSelectedType= null; - fInputElement= null; - fIsVisible= false; - fIsRefreshRunnablePosted= false; - fSelectInEditor= true; - fRestoreStateJob= null; - - fHierarchyLifeCycle= new TypeHierarchyLifeCycle(); - fTypeHierarchyLifeCycleListener= new ITypeHierarchyLifeCycleListener() { - public void typeHierarchyChanged(TypeHierarchyLifeCycle typeHierarchy, ICElement[] changedTypes) { - doTypeHierarchyChanged(typeHierarchy, changedTypes); - } - }; - fHierarchyLifeCycle.addChangedListener(fTypeHierarchyLifeCycleListener); - - fPropertyChangeListener= new IPropertyChangeListener() { - public void propertyChange(PropertyChangeEvent event) { - doPropertyChange(event); - } - }; - PreferenceConstants.getPreferenceStore().addPropertyChangeListener(fPropertyChangeListener); - - fIsEnableMemberFilter= false; - - fInputHistory= new ArrayList(); - fAllViewers= null; - - fViewActions= new ToggleViewAction[] { - new ToggleViewAction(this, VIEW_ID_SUPER), - new ToggleViewAction(this, VIEW_ID_SUB) - }; - - fDialogSettings= CUIPlugin.getDefault().getDialogSettings(); - - fHistoryDropDownAction= new HistoryDropDownAction(this); - fHistoryDropDownAction.setEnabled(false); - - fToggleOrientationActions= new ToggleOrientationAction[] { - new ToggleOrientationAction(this, VIEW_ORIENTATION_VERTICAL), - new ToggleOrientationAction(this, VIEW_ORIENTATION_HORIZONTAL), - new ToggleOrientationAction(this, VIEW_ORIENTATION_AUTOMATIC), - new ToggleOrientationAction(this, VIEW_ORIENTATION_SINGLE) - }; - - fEnableMemberFilterAction= new EnableMemberFilterAction(this, false); - fShowQualifiedTypeNamesAction= new ShowQualifiedTypeNamesAction(this, false); - - fFocusOnTypeAction= new FocusOnTypeAction(this); - - fPaneLabelProvider= new CUILabelProvider(); -// -// fAddStubAction= new AddMethodStubAction(); - fFocusOnSelectionAction= new FocusOnSelectionAction(this); - - fPartListener= new IPartListener2() { - public void partVisible(IWorkbenchPartReference ref) { - IWorkbenchPart part= ref.getPart(false); - if (part == TypeHierarchyViewPart.this) { - visibilityChanged(true); - } - } - - public void partHidden(IWorkbenchPartReference ref) { - IWorkbenchPart part= ref.getPart(false); - if (part == TypeHierarchyViewPart.this) { - visibilityChanged(false); - } - } - - public void partActivated(IWorkbenchPartReference ref) { - IWorkbenchPart part= ref.getPart(false); - if (part instanceof IEditorPart) - editorActivated((IEditorPart) part); - } - - public void partInputChanged(IWorkbenchPartReference ref) { - IWorkbenchPart part= ref.getPart(false); - if (part instanceof IEditorPart) - editorActivated((IEditorPart) part); - } - - public void partBroughtToTop(IWorkbenchPartReference ref) {} - public void partClosed(IWorkbenchPartReference ref) {} - public void partDeactivated(IWorkbenchPartReference ref) {} - public void partOpened(IWorkbenchPartReference ref) {} - }; - - fSelectionChangedListener= new ISelectionChangedListener() { - public void selectionChanged(SelectionChangedEvent event) { - doSelectionChanged(event); - } - }; - - fLinkingEnabled= PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.LINK_TYPEHIERARCHY_TO_EDITOR); - } - - /** - * Method doPropertyChange. - * @param event - */ - protected void doPropertyChange(PropertyChangeEvent event) { - String property= event.getProperty(); - if (fMethodsViewer != null) { -// if (MembersOrderPreferenceCache.isMemberOrderProperty(event.getProperty())) { -// fMethodsViewer.refresh(); -// } - } - if (IWorkingSetManager.CHANGE_WORKING_SET_CONTENT_CHANGE.equals(property)) { - updateHierarchyViewer(true); - } - } - - /** - * Adds the entry if new. Inserted at the beginning of the history entries list. - */ - private void addHistoryEntry(ICElement entry) { - if (fInputHistory.contains(entry)) { - fInputHistory.remove(entry); - } - fInputHistory.add(0, entry); - fHistoryDropDownAction.setEnabled(true); - } - - private void updateHistoryEntries() { - for (int i= fInputHistory.size() - 1; i >= 0; i--) { - ICElement type= (ICElement) fInputHistory.get(i); - if (!type.exists()) { - fInputHistory.remove(i); - } - } - fHistoryDropDownAction.setEnabled(!fInputHistory.isEmpty()); - } - - /** - * Goes to the selected entry, without updating the order of history entries. - */ - public void gotoHistoryEntry(ICElement entry) { - if (fInputHistory.contains(entry)) { - updateInput(entry); - } - } - - /** - * Gets all history entries. - */ - public ICElement[] getHistoryEntries() { - if (fInputHistory.size() > 0) { - updateHistoryEntries(); - } - return (ICElement[]) fInputHistory.toArray(new ICElement[fInputHistory.size()]); - } - - /** - * Sets the history entries - */ - public void setHistoryEntries(ICElement[] elems) { - fInputHistory.clear(); - for (int i= 0; i < elems.length; i++) { - fInputHistory.add(elems[i]); - } - updateHistoryEntries(); - } - - /** - * Selects an member in the methods list or in the current hierarchy. - */ - public void selectMember(ICElement member) { - fSelectInEditor= false; - if (!TypeUtil.isClassOrStruct(member)) { - Control methodControl= fMethodsViewer.getControl(); - if (methodControl != null && !methodControl.isDisposed()) { - methodControl.setFocus(); - } - - fMethodsViewer.setSelection(new StructuredSelection(member), true); - } else { - Control viewerControl= getCurrentViewer().getControl(); - if (viewerControl != null && !viewerControl.isDisposed()) { - viewerControl.setFocus(); - } - - if (!member.equals(fSelectedType)) { - getCurrentViewer().setSelection(new StructuredSelection(member), true); - } - } - fSelectInEditor= true; - } - - /** - * @deprecated - */ - public ICElement getInput() { - return fInputElement; - } - - /** - * Sets the input to a new type - * @deprecated - */ - public void setInput(ICElement type) { - setInputElement(type); - } - - /** - * Returns the input element of the type hierarchy. - * Can be of type ICElement or IPackageFragment - */ - public ICElement getInputElement() { - return fInputElement; - } - - - /** - * Sets the input to a new element. - */ - public void setInputElement(ICElement element) { - if (element != null) { - if (!(element instanceof IStructure)) { - element = TypeUtil.getDeclaringClass(element); - } - if (element == null || !element.exists()) { - MessageDialog.openError(getSite().getShell(), TypeHierarchyMessages.getString("TypeHierarchyViewPart.error.title"), TypeHierarchyMessages.getString("TypeHierarchyViewPart.error.message")); //$NON-NLS-1$ //$NON-NLS-2$ - return; - } - } else { - CUIPlugin.getDefault().logErrorMessage("Invalid type hierarchy input type.");//$NON-NLS-1$ - } - if (element != null && !element.equals(fInputElement)) { - addHistoryEntry(element); - } - - updateInput(element); - } - - /** - * Changes the input to a new type - */ - private void updateInput(ICElement inputElement) { - ICElement prevInput= fInputElement; - - synchronized (this) { - if (fRestoreStateJob != null) { - fRestoreStateJob.cancel(); - try { - fRestoreStateJob.join(); - } catch (InterruptedException e) { - // ignore - } finally { - fRestoreStateJob= null; - } - } - } - - // Make sure the UI got repainted before we execute a long running - // operation. This can be removed if we refresh the hierarchy in a - // separate thread. - // Work-araound for http://dev.eclipse.org/bugs/show_bug.cgi?id=30881 - processOutstandingEvents(); - if (inputElement == null) { - clearInput(); - } else { - fInputElement= inputElement; - try { - fHierarchyLifeCycle.ensureRefreshedTypeHierarchy(inputElement, CUIPlugin.getActiveWorkbenchWindow()); - // fHierarchyLifeCycle.ensureRefreshedTypeHierarchy(inputElement, getSite().getWorkbenchWindow()); - } catch (InvocationTargetException e) { - ExceptionHandler.handle(e, getSite().getShell(), TypeHierarchyMessages.getString("TypeHierarchyViewPart.exception.title"), TypeHierarchyMessages.getString("TypeHierarchyViewPart.exception.message")); //$NON-NLS-1$ //$NON-NLS-2$ - clearInput(); - return; - } catch (InterruptedException e) { - return; - } - - if (!TypeUtil.isClassOrStruct(inputElement)) { - setView(VIEW_ID_SUPER); - } - // turn off member filtering - fSelectInEditor= false; - setMemberFilter(null); - internalSelectType(null, false); // clear selection - fIsEnableMemberFilter= false; - if (!inputElement.equals(prevInput)) { - updateHierarchyViewer(true); - } - ICElement root= getSelectableType(inputElement); - internalSelectType(root, true); - updateMethodViewer(root); - updateToolbarButtons(); - updateTitle(); - enableMemberFilter(false); - fPagebook.showPage(fTypeMethodsSplitter); - fSelectInEditor= true; - } - } - - private void processOutstandingEvents() { - Display display= getDisplay(); - if (display != null && !display.isDisposed()) - display.update(); - } - - private void clearInput() { - fInputElement= null; - fHierarchyLifeCycle.freeHierarchy(); - - updateHierarchyViewer(false); - updateToolbarButtons(); - } - - /* - * @see IWorbenchPart#setFocus - */ - public void setFocus() { - fPagebook.setFocus(); - } - - /* - * @see IWorkbenchPart#dispose - */ - public void dispose() { - fHierarchyLifeCycle.freeHierarchy(); - fHierarchyLifeCycle.removeChangedListener(fTypeHierarchyLifeCycleListener); - fPaneLabelProvider.dispose(); - - if (fMethodsViewer != null) { - fMethodsViewer.dispose(); - } - - if (fPropertyChangeListener != null) { - CUIPlugin.getDefault().getPreferenceStore().removePropertyChangeListener(fPropertyChangeListener); - fPropertyChangeListener= null; - } - - getSite().getPage().removePartListener(fPartListener); - - if (fActionGroups != null) - fActionGroups.dispose(); - - if (fWorkingSetActionGroup != null) { - fWorkingSetActionGroup.dispose(); - } - - super.dispose(); - } - - /** - * Answer the property defined by key. - */ - public Object getAdapter(Class key) { - if (key == IShowInSource.class) { - return getShowInSource(); - } - if (key == IShowInTargetList.class) { - return new IShowInTargetList() { - public String[] getShowInTargetIds() { - return new String[] { CUIPlugin.CVIEW_ID, IPageLayout.ID_RES_NAV }; - } - - }; - } - return super.getAdapter(key); - } - - private Control createTypeViewerControl(Composite parent) { - fViewerbook= new PageBook(parent, SWT.NULL); - - KeyListener keyListener= createKeyListener(); - - // Create the viewers - TypeHierarchyViewer superTypesViewer= new SuperTypeHierarchyViewer(fViewerbook, fHierarchyLifeCycle, this); - initializeTypesViewer(superTypesViewer, keyListener, IContextMenuConstants.TARGET_ID_SUPERTYPES_VIEW); - - TypeHierarchyViewer subTypesViewer= new SubTypeHierarchyViewer(fViewerbook, fHierarchyLifeCycle, this); - initializeTypesViewer(subTypesViewer, keyListener, IContextMenuConstants.TARGET_ID_SUBTYPES_VIEW); - - fAllViewers= new TypeHierarchyViewer[2]; - fAllViewers[VIEW_ID_SUPER]= superTypesViewer; - fAllViewers[VIEW_ID_SUB]= subTypesViewer; - - int currViewerIndex; - try { - currViewerIndex= fDialogSettings.getInt(DIALOGSTORE_HIERARCHYVIEW); - if (currViewerIndex < 0 || currViewerIndex > 2) { - currViewerIndex= VIEW_ID_SUPER; - } - } catch (NumberFormatException e) { - currViewerIndex= VIEW_ID_SUPER; - } - - fEmptyTypesViewer= new Label(fViewerbook, SWT.LEFT); - - for (int i= 0; i < fAllViewers.length; i++) { - fAllViewers[i].setInput(fAllViewers[i]); - } - - // force the update - fCurrentViewerIndex= -1; - setView(currViewerIndex); - - return fViewerbook; - } - - private KeyListener createKeyListener() { - return new KeyAdapter() { - public void keyReleased(KeyEvent event) { - if (event.stateMask == 0) { - if (event.keyCode == SWT.F5) { - ITypeHierarchy hierarchy= fHierarchyLifeCycle.getHierarchy(); - if (hierarchy != null) { - fHierarchyLifeCycle.typeHierarchyChanged(hierarchy); - doTypeHierarchyChangedOnViewers(null); - } - updateHierarchyViewer(false); - return; - } - } - } - }; - } - - - private void initializeTypesViewer(final TypeHierarchyViewer typesViewer, KeyListener keyListener, String cotextHelpId) { - typesViewer.getControl().setVisible(false); - typesViewer.getControl().addKeyListener(keyListener); - typesViewer.initContextMenu(new IMenuListener() { - public void menuAboutToShow(IMenuManager menu) { - fillTypesViewerContextMenu(typesViewer, menu); - } - }, cotextHelpId, getSite()); - typesViewer.addPostSelectionChangedListener(fSelectionChangedListener); - typesViewer.setQualifiedTypeName(isShowQualifiedTypeNames()); - typesViewer.setWorkingSetFilter(fWorkingSetActionGroup.getWorkingSetFilter()); - } - - private Control createMethodViewerControl(Composite parent) { - fMethodsViewer= new MethodsViewer(parent, fHierarchyLifeCycle, this); - fMethodsViewer.initContextMenu(new IMenuListener() { - public void menuAboutToShow(IMenuManager menu) { - fillMethodsViewerContextMenu(menu); - } - }, IContextMenuConstants.TARGET_ID_MEMBERS_VIEW, getSite()); - fMethodsViewer.addPostSelectionChangedListener(fSelectionChangedListener); - - Control control= fMethodsViewer.getTable(); - control.addKeyListener(createKeyListener()); - control.addFocusListener(new FocusListener() { - public void focusGained(FocusEvent e) { - fSelectAllAction.setEnabled(true); - } - - public void focusLost(FocusEvent e) { - fSelectAllAction.setEnabled(false); - } - }); - - return control; - } - - private void initDragAndDrop() { -// Transfer[] transfers= new Transfer[] { LocalSelectionTransfer.getInstance() }; -// int ops= DND.DROP_MOVE | DND.DROP_COPY | DND.DROP_LINK; -// -// for (int i= 0; i < fAllViewers.length; i++) { -// addDragAdapters(fAllViewers[i], ops, transfers); -// addDropAdapters(fAllViewers[i], ops | DND.DROP_DEFAULT, transfers); -// } -// addDragAdapters(fMethodsViewer, ops, transfers); -// -// //DND on empty hierarchy -// DropTarget dropTarget = new DropTarget(fNoHierarchyShownLabel, ops | DND.DROP_DEFAULT); -// dropTarget.setTransfer(transfers); -// dropTarget.addDropListener(new TypeHierarchyTransferDropAdapter(this, fAllViewers[0])); - } - -// private void addDropAdapters(AbstractTreeViewer viewer, int ops, Transfer[] transfers){ -// TransferDropTargetListener[] dropListeners= new TransferDropTargetListener[] { -// new TypeHierarchyTransferDropAdapter(this, viewer) -// }; -// viewer.addDropSupport(ops, transfers, new DelegatingDropAdapter(dropListeners)); -// } - -// private void addDragAdapters(StructuredViewer viewer, int ops, Transfer[] transfers) { -// TransferDragSourceListener[] dragListeners= new TransferDragSourceListener[] { -// new SelectionTransferDragAdapter(viewer) -// }; -// viewer.addDragSupport(ops, transfers, new JdtViewerDragAdapter(viewer, dragListeners)); -// } - - /** - * Returns the inner component in a workbench part. - * @see IWorkbenchPart#createPartControl(Composite) - */ - public void createPartControl(Composite container) { - fParent= container; - addResizeListener(container); - - fPagebook= new PageBook(container, SWT.NONE); - fWorkingSetActionGroup= new WorkingSetFilterActionGroup(CUIPlugin.ID_TYPE_HIERARCHY, container.getShell(), fPropertyChangeListener); - - // page 1 of page book (no hierarchy label) - - fNoHierarchyShownLabel= new Label(fPagebook, SWT.TOP + SWT.LEFT + SWT.WRAP); - fNoHierarchyShownLabel.setText(TypeHierarchyMessages.getString("TypeHierarchyViewPart.empty")); //$NON-NLS-1$ - - // page 2 of page book (viewers) - - fTypeMethodsSplitter= new SashForm(fPagebook, SWT.VERTICAL); - fTypeMethodsSplitter.setVisible(false); - - fTypeViewerViewForm= new ViewForm(fTypeMethodsSplitter, SWT.NONE); - - Control typeViewerControl= createTypeViewerControl(fTypeViewerViewForm); - fTypeViewerViewForm.setContent(typeViewerControl); - - fMethodViewerViewForm= new ViewForm(fTypeMethodsSplitter, SWT.NONE); - fTypeMethodsSplitter.setWeights(new int[] {35, 65}); - - Control methodViewerPart= createMethodViewerControl(fMethodViewerViewForm); - fMethodViewerViewForm.setContent(methodViewerPart); - - fMethodViewerPaneLabel= new CLabel(fMethodViewerViewForm, SWT.NONE); - fMethodViewerViewForm.setTopLeft(fMethodViewerPaneLabel); - - ToolBar methodViewerToolBar= new ToolBar(fMethodViewerViewForm, SWT.FLAT | SWT.WRAP); - fMethodViewerViewForm.setTopCenter(methodViewerToolBar); - - initDragAndDrop(); - - MenuManager menu= new MenuManager(); - menu.add(fFocusOnTypeAction); - fNoHierarchyShownLabel.setMenu(menu.createContextMenu(fNoHierarchyShownLabel)); - - fPagebook.showPage(fNoHierarchyShownLabel); - - try { - fOrientation= fDialogSettings.getInt(DIALOGSTORE_VIEWORIENTATION); - if (fOrientation < 0 || fOrientation > 3) { - fOrientation= VIEW_ORIENTATION_VERTICAL; - } - } catch (NumberFormatException e) { - fOrientation= VIEW_ORIENTATION_AUTOMATIC; - } - - // force the update - fCurrentOrientation= -1; - // will fill the main tool bar - setOrientation(fOrientation); - - if (fMemento != null) { // restore state before creating action - restoreLinkingEnabled(fMemento); - } - fToggleLinkingAction= new ToggleLinkingAction(this); - - // set the filter menu items - IActionBars actionBars= getViewSite().getActionBars(); - IMenuManager viewMenu= actionBars.getMenuManager(); - for (int i= 0; i < fViewActions.length; i++) { - ToggleViewAction action= fViewActions[i]; - viewMenu.add(action); - action.setEnabled(false); - } - viewMenu.add(new Separator()); - - fWorkingSetActionGroup.contributeToMenu(viewMenu); - - viewMenu.add(new Separator()); - - IMenuManager layoutSubMenu= new MenuManager(TypeHierarchyMessages.getString("TypeHierarchyViewPart.layout.submenu")); //$NON-NLS-1$ - viewMenu.add(layoutSubMenu); - for (int i= 0; i < fToggleOrientationActions.length; i++) { - layoutSubMenu.add(fToggleOrientationActions[i]); - } - viewMenu.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS)); - viewMenu.add(fShowQualifiedTypeNamesAction); - viewMenu.add(fToggleLinkingAction); - - - // fill the method viewer tool bar - ToolBarManager lowertbmanager= new ToolBarManager(methodViewerToolBar); - lowertbmanager.add(fEnableMemberFilterAction); - lowertbmanager.add(new Separator()); - fMethodsViewer.contributeToToolBar(lowertbmanager); - lowertbmanager.update(true); - - // selection provider - int nHierarchyViewers= fAllViewers.length; - StructuredViewer[] trackedViewers= new StructuredViewer[nHierarchyViewers + 1]; - for (int i= 0; i < nHierarchyViewers; i++) { - trackedViewers[i]= fAllViewers[i]; - } - trackedViewers[nHierarchyViewers]= fMethodsViewer; - fSelectionProviderMediator= new SelectionProviderMediator(trackedViewers); - IStatusLineManager slManager= getViewSite().getActionBars().getStatusLineManager(); - fSelectionProviderMediator.addSelectionChangedListener(new StatusBarUpdater(slManager)); - - getSite().setSelectionProvider(fSelectionProviderMediator); - getSite().getPage().addPartListener(fPartListener); - - // see http://bugs.eclipse.org/bugs/show_bug.cgi?id=33657 - ICElement input= null; //determineInputElement(); - if (fMemento != null) { - restoreState(fMemento, input); - } else if (input != null) { - setInputElement(input); - } else { - setViewerVisibility(false); - } - - WorkbenchHelp.setHelp(fPagebook, ICHelpContextIds.TYPE_HIERARCHY_VIEW); - - - fActionGroups= new CompositeActionGroup(new ActionGroup[] { -// new NewWizardsActionGroup(this.getSite()), -// new OpenEditorActionGroup(this), - new OpenViewActionGroup(this), -// new CCPActionGroup(this), -// new GenerateActionGroup(this), -// new RefactorActionGroup(this), -// new CSearchActionGroup(this) - }); - - fActionGroups.fillActionBars(actionBars); - fSelectAllAction= new SelectAllAction(fMethodsViewer); - - actionBars.setGlobalActionHandler(ActionFactory.SELECT_ALL.getId(), fSelectAllAction); - } - - private void addResizeListener(Composite parent) { - parent.addControlListener(new ControlListener() { - public void controlMoved(ControlEvent e) { - } - public void controlResized(ControlEvent e) { - computeOrientation(); - } - }); - } - - void computeOrientation() { - // fix for bug: 63268 error while activating view - // avoid recursive calls of compute orientation - if (fInComputeOrientation) { - return; - } - fInComputeOrientation= true; - try { - if (fOrientation != VIEW_ORIENTATION_AUTOMATIC) { - setOrientation(fOrientation); - } - else { - if (fOrientation == VIEW_ORIENTATION_SINGLE) - return; - Point size= fParent.getSize(); - if (size.x != 0 && size.y != 0) { - if (size.x > size.y) - setOrientation(VIEW_ORIENTATION_HORIZONTAL); - else - setOrientation(VIEW_ORIENTATION_VERTICAL); - } - } - } finally { - fInComputeOrientation= false; - } - } - - /** - * called from ToggleOrientationAction. - * @param orientation VIEW_ORIENTATION_SINGLE, VIEW_ORIENTATION_HORIZONTAL or VIEW_ORIENTATION_VERTICAL - */ - public void setOrientation(int orientation) { - if (fCurrentOrientation != orientation) { - boolean methodViewerNeedsUpdate= false; - - if (fMethodViewerViewForm != null && !fMethodViewerViewForm.isDisposed() - && fTypeMethodsSplitter != null && !fTypeMethodsSplitter.isDisposed()) { - if (orientation == VIEW_ORIENTATION_SINGLE) { - fMethodViewerViewForm.setVisible(false); - enableMemberFilter(false); - updateMethodViewer(null); - } else { - if (fCurrentOrientation == VIEW_ORIENTATION_SINGLE) { - fMethodViewerViewForm.setVisible(true); - methodViewerNeedsUpdate= true; - } - boolean horizontal= orientation == VIEW_ORIENTATION_HORIZONTAL; - fTypeMethodsSplitter.setOrientation(horizontal ? SWT.HORIZONTAL : SWT.VERTICAL); - } - updateMainToolbar(orientation); - fTypeMethodsSplitter.layout(); - } - updateCheckedState(); - if (methodViewerNeedsUpdate) { - updateMethodViewer(fSelectedType); - } - fDialogSettings.put(DIALOGSTORE_VIEWORIENTATION, orientation); - fCurrentOrientation= orientation; - } - } - - - private void updateCheckedState() { - for (int i= 0; i < fToggleOrientationActions.length; i++) { - fToggleOrientationActions[i].setChecked(fOrientation == fToggleOrientationActions[i].getOrientation()); - } - } - - private void updateMainToolbar(int orientation) { - IActionBars actionBars= getViewSite().getActionBars(); - IToolBarManager tbmanager= actionBars.getToolBarManager(); - - if (orientation == VIEW_ORIENTATION_HORIZONTAL) { - clearMainToolBar(tbmanager); - ToolBar typeViewerToolBar= new ToolBar(fTypeViewerViewForm, SWT.FLAT | SWT.WRAP); - fillMainToolBar(new ToolBarManager(typeViewerToolBar)); - fTypeViewerViewForm.setTopLeft(typeViewerToolBar); - } else { - fTypeViewerViewForm.setTopLeft(null); - fillMainToolBar(tbmanager); - } - } - - private void fillMainToolBar(IToolBarManager tbmanager) { - tbmanager.removeAll(); - for (int i= 0; i < fViewActions.length; i++) { - tbmanager.add(fViewActions[i]); - } - tbmanager.add(fHistoryDropDownAction); - tbmanager.update(false); - } - - private void clearMainToolBar(IToolBarManager tbmanager) { - tbmanager.removeAll(); - tbmanager.update(false); - } - - - /** - * Creates the context menu for the hierarchy viewers - */ - protected void fillTypesViewerContextMenu(TypeHierarchyViewer viewer, IMenuManager menu) { - CUIPlugin.createStandardGroups(menu); - - menu.appendToGroup(IContextMenuConstants.GROUP_SHOW, new Separator(GROUP_FOCUS)); - // viewer entries - viewer.contributeToContextMenu(menu); - - if (fFocusOnSelectionAction.canActionBeAdded()) - menu.appendToGroup(GROUP_FOCUS, fFocusOnSelectionAction); - menu.appendToGroup(GROUP_FOCUS, fFocusOnTypeAction); - - fActionGroups.setContext(new ActionContext(getSite().getSelectionProvider().getSelection())); - fActionGroups.fillContextMenu(menu); - fActionGroups.setContext(null); - } - - /** - * Creates the context menu for the method viewer - */ - protected void fillMethodsViewerContextMenu(IMenuManager menu) { - CUIPlugin.createStandardGroups(menu); - // viewer entries - fMethodsViewer.contributeToContextMenu(menu); - fActionGroups.setContext(new ActionContext(getSite().getSelectionProvider().getSelection())); - fActionGroups.fillContextMenu(menu); - fActionGroups.setContext(null); -// if (fSelectedType != null && fAddStubAction.init(fSelectedType, fMethodsViewer.getSelection())) { -// IMenuManager source= menu.findMenuUsingPath(GenerateActionGroup.MENU_ID); -// if (source != null) -// source.appendToGroup(GenerateActionGroup.GROUP_GENERATE, fAddStubAction); -// } - } - - /** - * Toggles between the empty viewer page and the hierarchy - */ - private void setViewerVisibility(boolean showHierarchy) { - if (showHierarchy) { - fViewerbook.showPage(getCurrentViewer().getControl()); - } else { - fViewerbook.showPage(fEmptyTypesViewer); - } - } - - /** - * Sets the member filter. null disables member filtering. - */ - private void setMemberFilter(IMember[] memberFilter) { - Assert.isNotNull(fAllViewers); - for (int i= 0; i < fAllViewers.length; i++) { - fAllViewers[i].setMemberFilter(memberFilter); - } - } - - private ICElement getSelectableType(ICElement elem) { - if (!TypeUtil.isClassOrStruct(elem)) { - return getCurrentViewer().getTreeRootType(); - } - return elem; - } - - private void internalSelectType(ICElement elem, boolean reveal) { - TypeHierarchyViewer viewer= getCurrentViewer(); - if (viewer != null) { - viewer.removePostSelectionChangedListener(fSelectionChangedListener); - viewer.setSelection(elem != null ? new StructuredSelection(elem) : StructuredSelection.EMPTY, reveal); - viewer.addPostSelectionChangedListener(fSelectionChangedListener); - } - } - - /** - * When the input changed or the hierarchy pane becomes visible, - * updateHierarchyViewer brings up the correct view and refreshes - * the current tree - */ - protected void updateHierarchyViewer(final boolean doExpand) { - if (fInputElement == null) { - fNoHierarchyShownLabel.setText(TypeHierarchyMessages.getString("TypeHierarchyViewPart.empty")); //$NON-NLS-1$ - fPagebook.showPage(fNoHierarchyShownLabel); - } else { - final TypeHierarchyViewer viewer = getCurrentViewer(); - if (viewer != null && viewer.containsElements() != null) { - Runnable runnable= new Runnable() { - public void run() { - viewer.updateContent(doExpand); // refresh - } - }; - BusyIndicator.showWhile(getDisplay(), runnable); - if (!isChildVisible(fViewerbook, viewer.getControl())) { - setViewerVisibility(true); - } - } else { - fEmptyTypesViewer.setText(TypeHierarchyMessages.getFormattedString("TypeHierarchyViewPart.nodecl", fInputElement.getElementName())); //$NON-NLS-1$ - setViewerVisibility(false); - } - } - } - - private void updateMethodViewer(final ICElement input) { - if (!fIsEnableMemberFilter && fCurrentOrientation != VIEW_ORIENTATION_SINGLE) { - if (input == fMethodsViewer.getInput()) { - if (input != null) { - Runnable runnable= new Runnable() { - public void run() { - fMethodsViewer.refresh(); // refresh - } - }; - BusyIndicator.showWhile(getDisplay(), runnable); - } - } else { - if (input != null) { - fMethodViewerPaneLabel.setText(fPaneLabelProvider.getText(input)); - fMethodViewerPaneLabel.setImage(fPaneLabelProvider.getImage(input)); - } else { - fMethodViewerPaneLabel.setText(""); //$NON-NLS-1$ - fMethodViewerPaneLabel.setImage(null); - } - Runnable runnable= new Runnable() { - public void run() { - fMethodsViewer.setInput(input); // refresh - } - }; - BusyIndicator.showWhile(getDisplay(), runnable); - } - } - } - - protected void doSelectionChanged(SelectionChangedEvent e) { - if (e.getSelectionProvider() == fMethodsViewer) { - methodSelectionChanged(e.getSelection()); - } else { - typeSelectionChanged(e.getSelection()); - } - } - - - - private void methodSelectionChanged(ISelection sel) { - if (sel instanceof IStructuredSelection) { - List selected= ((IStructuredSelection)sel).toList(); - int nSelected= selected.size(); - if (fIsEnableMemberFilter) { - IMember[] memberFilter= null; - if (nSelected > 0) { - memberFilter= new IMember[nSelected]; - selected.toArray(memberFilter); - } - setMemberFilter(memberFilter); - updateHierarchyViewer(true); - updateTitle(); - internalSelectType(fSelectedType, true); - } - if (nSelected == 1 && fSelectInEditor) { - revealElementInEditor(selected.get(0), fMethodsViewer); - } - } - } - - private void typeSelectionChanged(ISelection sel) { - if (sel instanceof IStructuredSelection) { - List selected= ((IStructuredSelection)sel).toList(); - int nSelected= selected.size(); - if (nSelected != 0) { - List types= new ArrayList(nSelected); - for (int i= nSelected-1; i >= 0; i--) { - Object elem= selected.get(i); - if (elem instanceof ICElement && !types.contains(elem)) { - types.add(elem); - } - } - if (types.size() == 1) { - fSelectedType= (ICElement) types.get(0); - updateMethodViewer(fSelectedType); - } else if (types.size() == 0) { - // method selected, no change - } - if (nSelected == 1 && fSelectInEditor) { - revealElementInEditor(selected.get(0), getCurrentViewer()); - } - } else { - fSelectedType= null; - updateMethodViewer(null); - } - } - } - - private void revealElementInEditor(Object elem, StructuredViewer originViewer) { - // only allow revealing when the type hierarchy is the active page - // no revealing after selection events due to model changes - - if (getSite().getPage().getActivePart() != this) { - return; - } - - if (fSelectionProviderMediator.getViewerInFocus() != originViewer) { - return; - } - - IEditorPart editorPart= EditorUtility.isOpenInEditor(elem); - if (editorPart != null && (elem instanceof ICElement)) { - getSite().getPage().removePartListener(fPartListener); - getSite().getPage().bringToTop(editorPart); - EditorUtility.revealInEditor(editorPart, (ICElement) elem); - getSite().getPage().addPartListener(fPartListener); - } - } - - private Display getDisplay() { - if (fPagebook != null && !fPagebook.isDisposed()) { - return fPagebook.getDisplay(); - } - return null; - } - - private boolean isChildVisible(Composite pb, Control child) { - Control[] children= pb.getChildren(); - for (int i= 0; i < children.length; i++) { - if (children[i] == child && children[i].isVisible()) - return true; - } - return false; - } - - private void updateTitle() { - String tooltip; - String title; - String viewerTitle; - TypeHierarchyViewer viewer = getCurrentViewer(); - if (viewer != null) { - viewerTitle= viewer.getTitle(); - } else { - viewerTitle = TypeHierarchyMessages.getString("TraditionalHierarchyViewer.title"); //$NON-NLS-1$ - } - - if (fInputElement != null) { - String[] args= new String[] { viewerTitle, CElementLabels.getElementLabel(fInputElement, CElementLabels.ALL_DEFAULT) }; - title= TypeHierarchyMessages.getFormattedString("TypeHierarchyViewPart.title", args); //$NON-NLS-1$ - tooltip= TypeHierarchyMessages.getFormattedString("TypeHierarchyViewPart.tooltip", args); //$NON-NLS-1$ - } else { - title= viewerTitle; - tooltip= viewerTitle; - } - setPartName(title); - setContentDescription(""); //$NON-NLS-1$ - setTitleToolTip(tooltip); - } - - private void updateToolbarButtons() { - for (int i= 0; i < fViewActions.length; i++) { - ToggleViewAction action= fViewActions[i]; - action.setEnabled(true); - } - } - - /** - * Sets the current view (see view id) - * called from ToggleViewAction. Must be called after creation of the view part. - */ - public void setView(int viewerIndex) { - Assert.isNotNull(fAllViewers); - if (viewerIndex < fAllViewers.length && fCurrentViewerIndex != viewerIndex) { - fCurrentViewerIndex= viewerIndex; - - updateHierarchyViewer(true); - if (fInputElement != null) { - ISelection currSelection= getCurrentViewer().getSelection(); - if (currSelection == null || currSelection.isEmpty()) { - internalSelectType(getSelectableType(fInputElement), false); - currSelection= getCurrentViewer().getSelection(); - } - if (!fIsEnableMemberFilter) { - typeSelectionChanged(currSelection); - } - } - updateTitle(); - - fDialogSettings.put(DIALOGSTORE_HIERARCHYVIEW, viewerIndex); - getCurrentViewer().getTree().setFocus(); - } - for (int i= 0; i < fViewActions.length; i++) { - ToggleViewAction action= fViewActions[i]; - action.setChecked(fCurrentViewerIndex == action.getViewerIndex()); - } - } - - /** - * Gets the current active view index. - */ - public int getViewIndex() { - return fCurrentViewerIndex; - } - - private TypeHierarchyViewer getCurrentViewer() { - if (fCurrentViewerIndex != -1) - return fAllViewers[fCurrentViewerIndex]; - return null; - } - - /** - * called from EnableMemberFilterAction. - * Must be called after creation of the view part. - */ - public void enableMemberFilter(boolean on) { - if (on != fIsEnableMemberFilter) { - fIsEnableMemberFilter= on; - if (!on) { - ICElement methodViewerInput= (ICElement) fMethodsViewer.getInput(); - setMemberFilter(null); - updateHierarchyViewer(true); - updateTitle(); - - if (methodViewerInput != null && getCurrentViewer().isElementShown(methodViewerInput)) { - // avoid that the method view changes content by selecting the previous input - internalSelectType(methodViewerInput, true); - } else if (fSelectedType != null) { - // choose a input that exists - internalSelectType(fSelectedType, true); - updateMethodViewer(fSelectedType); - } - } else { - methodSelectionChanged(fMethodsViewer.getSelection()); - } - } - fEnableMemberFilterAction.setChecked(on); - } - - /** - * called from ShowQualifiedTypeNamesAction. Must be called after creation - * of the view part. - */ - public void showQualifiedTypeNames(boolean on) { - if (fAllViewers == null) { - return; - } - for (int i= 0; i < fAllViewers.length; i++) { - fAllViewers[i].setQualifiedTypeName(on); - } - } - - private boolean isShowQualifiedTypeNames() { - return fShowQualifiedTypeNamesAction.isChecked(); - } - - /** - * Called from ITypeHierarchyLifeCycleListener. - * Can be called from any thread - */ - protected void doTypeHierarchyChanged(final TypeHierarchyLifeCycle typeHierarchy, final ICElement[] changedTypes) { - if (!fIsVisible) { - fNeedRefresh= true; - return; - } - if (fIsRefreshRunnablePosted) { - return; - } - - Display display= getDisplay(); - if (display != null) { - fIsRefreshRunnablePosted= true; - display.asyncExec(new Runnable() { - public void run() { - try { - if (fPagebook != null && !fPagebook.isDisposed()) { - doTypeHierarchyChangedOnViewers(changedTypes); - } - } finally { - fIsRefreshRunnablePosted= false; - } - } - }); - } - } - - protected void doTypeHierarchyChangedOnViewers(ICElement[] changedTypes) { - if (fHierarchyLifeCycle.getHierarchy() == null || !fHierarchyLifeCycle.getHierarchy().exists()) { - clearInput(); - } else { - if (changedTypes == null) { - // hierarchy change - try { - fHierarchyLifeCycle.ensureRefreshedTypeHierarchy(fInputElement, getSite().getWorkbenchWindow()); - } catch (InvocationTargetException e) { - ExceptionHandler.handle(e, getSite().getShell(), TypeHierarchyMessages.getString("TypeHierarchyViewPart.exception.title"), TypeHierarchyMessages.getString("TypeHierarchyViewPart.exception.message")); //$NON-NLS-1$ //$NON-NLS-2$ - clearInput(); - return; - } catch (InterruptedException e) { - return; - } - fMethodsViewer.refresh(); - updateHierarchyViewer(false); - } else { - // elements in hierarchy modified - Object methodViewerInput= fMethodsViewer.getInput(); - fMethodsViewer.refresh(); - fMethodViewerPaneLabel.setText(fPaneLabelProvider.getText(methodViewerInput)); - fMethodViewerPaneLabel.setImage(fPaneLabelProvider.getImage(methodViewerInput)); - if (getCurrentViewer().isMethodFiltering()) { - if (changedTypes.length == 1) { - getCurrentViewer().refresh(changedTypes[0]); - } else { - updateHierarchyViewer(false); - } - } else { - getCurrentViewer().update(changedTypes, new String[] { IBasicPropertyConstants.P_TEXT, IBasicPropertyConstants.P_IMAGE } ); - } - } - } - } - - /* - * @see IViewPart#init - */ - public void init(IViewSite site, IMemento memento) throws PartInitException { - super.init(site, memento); - fMemento= memento; - } - - /* - * @see ViewPart#saveState(IMemento) - */ - public void saveState(IMemento memento) { - if (fPagebook == null) { - // part has not been created - if (fMemento != null) { //Keep the old state; - memento.putMemento(fMemento); - } - return; - } -// if (fInputElement != null) { -// String handleIndentifier= fInputElement.getHandleIdentifier(); -// memento.putString(TAG_INPUT, handleIndentifier); -// } - memento.putInteger(TAG_VIEW, getViewIndex()); - memento.putInteger(TAG_ORIENTATION, fOrientation); - int weigths[]= fTypeMethodsSplitter.getWeights(); - int ratio= (weigths[0] * 1000) / (weigths[0] + weigths[1]); - memento.putInteger(TAG_RATIO, ratio); - - ScrollBar bar= getCurrentViewer().getTree().getVerticalBar(); - int position= bar != null ? bar.getSelection() : 0; - memento.putInteger(TAG_VERTICAL_SCROLL, position); - -// ICElement selection= (ICElement)((IStructuredSelection) getCurrentViewer().getSelection()).getFirstElement(); -// if (selection != null) { -// memento.putString(TAG_SELECTION, selection.getHandleIdentifier()); -// } - - fWorkingSetActionGroup.saveState(memento); - - fMethodsViewer.saveState(memento); - - saveLinkingEnabled(memento); - } - - private void saveLinkingEnabled(IMemento memento) { - memento.putInteger(PreferenceConstants.LINK_TYPEHIERARCHY_TO_EDITOR, fLinkingEnabled ? 1 : 0); - } - - /** - * Restores the type hierarchy settings from a memento. - */ - private void restoreState(final IMemento memento, ICElement defaultInput) { - ICElement input= defaultInput; -// String elementId= memento.getString(TAG_INPUT); -// if (elementId != null) { -// input= CoreModel.create(elementId); -// if (input != null && !input.exists()) { -// input= null; -// } -// } - if (input == null) { - doRestoreState(memento, input); - } else { - final ICElement hierarchyInput= input; - - synchronized (this) { - String label= TypeHierarchyMessages.getFormattedString("TypeHierarchyViewPart.restoreinput", hierarchyInput.getElementName()); //$NON-NLS-1$ - fNoHierarchyShownLabel.setText(label); - - fRestoreStateJob= new Job(label) { - protected IStatus run(IProgressMonitor monitor) { - try { - doRestoreInBackground(memento, hierarchyInput, monitor); - } catch (CModelException e) { - return e.getStatus(); - } catch (OperationCanceledException e) { - return Status.CANCEL_STATUS; - } - return Status.OK_STATUS; - } - }; - fRestoreStateJob.schedule(); - } - } - } - - protected void doRestoreInBackground(final IMemento memento, final ICElement hierarchyInput, IProgressMonitor monitor) throws CModelException { - fHierarchyLifeCycle.doHierarchyRefresh(hierarchyInput, monitor); - if (!monitor.isCanceled()) { - Display.getDefault().asyncExec(new Runnable() { - public void run() { - // running async: check first if view still exists - if (fPagebook != null && !fPagebook.isDisposed()) { - doRestoreState(memento, hierarchyInput); - } - } - }); - } - } - - - final void doRestoreState(IMemento memento, ICElement input) { - synchronized (this) { - if (fRestoreStateJob == null) { - return; - } - fRestoreStateJob= null; - } - - fWorkingSetActionGroup.restoreState(memento); - setInputElement(input); - - Integer viewerIndex= memento.getInteger(TAG_VIEW); - if (viewerIndex != null) { - setView(viewerIndex.intValue()); - } - Integer orientation= memento.getInteger(TAG_ORIENTATION); - if (orientation != null) { - fOrientation= orientation.intValue(); - } - computeOrientation(); - updateCheckedState(); - - Integer ratio= memento.getInteger(TAG_RATIO); - if (ratio != null) { - fTypeMethodsSplitter.setWeights(new int[] { ratio.intValue(), 1000 - ratio.intValue() }); - } - ScrollBar bar= getCurrentViewer().getTree().getVerticalBar(); - if (bar != null) { - Integer vScroll= memento.getInteger(TAG_VERTICAL_SCROLL); - if (vScroll != null) { - bar.setSelection(vScroll.intValue()); - } - } - fMethodsViewer.restoreState(memento); - } - - private void restoreLinkingEnabled(IMemento memento) { - Integer val= memento.getInteger(PreferenceConstants.LINK_TYPEHIERARCHY_TO_EDITOR); - if (val != null) { - fLinkingEnabled= val.intValue() != 0; - } - } - - - /** - * view part becomes visible - */ - protected void visibilityChanged(boolean isVisible) { - fIsVisible= isVisible; - if (isVisible && fNeedRefresh) { - doTypeHierarchyChangedOnViewers(null); - } - fNeedRefresh= false; - } - - - /** - * Link selection to active editor. - */ - protected void editorActivated(IEditorPart editor) { - if (!isLinkingEnabled()) { - return; - } - if (fInputElement == null) { - // no type hierarchy shown - return; - } - - ICElement elem= (ICElement)editor.getEditorInput().getAdapter(ICElement.class); - TypeHierarchyViewer currentViewer= getCurrentViewer(); - if (elem instanceof ITranslationUnit) { - try { - ICElement[] allTypes= TypeUtil.getAllTypes((ITranslationUnit)elem); - for (int i= 0; i < allTypes.length; i++) { - if (currentViewer.isElementShown(allTypes[i])) { - internalSelectType(allTypes[i], true); - updateMethodViewer(allTypes[i]); - return; - } - } - } catch (CModelException e) { - } - } - } - - /* (non-Javadoc) - * @see org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider#getViewPartInput() - */ - public Object getViewPartInput() { - return fInputElement; - } - - - /** - * Returns the IShowInSource for this view. - */ - protected IShowInSource getShowInSource() { - return new IShowInSource() { - public ShowInContext getShowInContext() { - return new ShowInContext( - null, - getSite().getSelectionProvider().getSelection()); - } - }; - } - - boolean isLinkingEnabled() { - return fLinkingEnabled; - } - - public void setLinkingEnabled(boolean enabled) { - fLinkingEnabled= enabled; - PreferenceConstants.getPreferenceStore().setValue(PreferenceConstants.LINK_TYPEHIERARCHY_TO_EDITOR, enabled); - - if (enabled) { - IEditorPart editor = getSite().getPage().getActiveEditor(); - if (editor != null) { - editorActivated(editor); - } - } - } - - public void clearNeededRefresh() { - fNeedRefresh= false; - } - -} diff --git a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/TypeHierarchyViewer.java b/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/TypeHierarchyViewer.java deleted file mode 100644 index 5a114f47f92..00000000000 --- a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/internal/ui/browser/typehierarchy/TypeHierarchyViewer.java +++ /dev/null @@ -1,174 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.browser.typehierarchy; - -import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.cdt.core.model.IMember; -import org.eclipse.cdt.internal.ui.util.ProblemTreeViewer; -import org.eclipse.cdt.internal.ui.viewsupport.CElementLabels; -import org.eclipse.jface.action.IMenuListener; -import org.eclipse.jface.action.IMenuManager; -import org.eclipse.jface.action.MenuManager; -import org.eclipse.jface.util.Assert; -import org.eclipse.jface.viewers.IContentProvider; -import org.eclipse.jface.viewers.ViewerFilter; -import org.eclipse.swt.SWT; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Menu; -import org.eclipse.swt.widgets.Tree; -import org.eclipse.ui.IWorkbenchPart; -import org.eclipse.ui.IWorkbenchPartSite; - -public abstract class TypeHierarchyViewer extends ProblemTreeViewer { - -// private OpenAction fOpen; - private HierarchyLabelProvider fLabelProvider; - - public TypeHierarchyViewer(Composite parent, IContentProvider contentProvider, TypeHierarchyLifeCycle lifeCycle, IWorkbenchPart part) { - super(new Tree(parent, SWT.SINGLE)); - - fLabelProvider= new HierarchyLabelProvider(lifeCycle); - -// setLabelProvider(new DecoratingCLabelProvider(fLabelProvider, true)); - setLabelProvider(fLabelProvider); - setUseHashlookup(true); - - setContentProvider(contentProvider); - setSorter(new HierarchyViewerSorter(lifeCycle)); - -// fOpen= new OpenAction(part.getSite()); -// addOpenListener(new IOpenListener() { -// public void open(OpenEvent event) { -// fOpen.run(); -// } -// }); - -// CUIHelp.setHelp(this, ICHelpContextIds.TYPE_HIERARCHY_VIEW); - } - - public void setQualifiedTypeName(boolean on) { - if (on) { - fLabelProvider.setTextFlags(fLabelProvider.getTextFlags() | CElementLabels.T_POST_QUALIFIED); - } else { - fLabelProvider.setTextFlags(fLabelProvider.getTextFlags() & ~CElementLabels.T_POST_QUALIFIED); - } - refresh(); - } - - /** - * Attaches a contextmenu listener to the tree - */ - public void initContextMenu(IMenuListener menuListener, String popupId, IWorkbenchPartSite viewSite) { - MenuManager menuMgr= new MenuManager(); - menuMgr.setRemoveAllWhenShown(true); - menuMgr.addMenuListener(menuListener); - Menu menu= menuMgr.createContextMenu(getTree()); - getTree().setMenu(menu); - viewSite.registerContextMenu(popupId, menuMgr, this); - } - - /** - * Fills up the context menu with items for the hierarchy viewer - * Should be called by the creator of the context menu - */ - public void contributeToContextMenu(IMenuManager menu) { - } - - /** - * Set the member filter - */ - public void setMemberFilter(IMember[] memberFilter) { - TypeHierarchyContentProvider contentProvider= getHierarchyContentProvider(); - if (contentProvider != null) { - contentProvider.setMemberFilter(memberFilter); - } - } - - /** - * Returns if method filtering is enabled. - */ - public boolean isMethodFiltering() { - TypeHierarchyContentProvider contentProvider= getHierarchyContentProvider(); - if (contentProvider != null) { - return contentProvider.getMemberFilter() != null; - } - return false; - } - - public void setWorkingSetFilter(ViewerFilter filter) { - fLabelProvider.setFilter(filter); - TypeHierarchyContentProvider contentProvider= getHierarchyContentProvider(); - if (contentProvider != null) { - contentProvider.setWorkingSetFilter(filter); - } - } - - /** - * Returns true if the hierarchy contains elements. Returns one of them - * With member filtering it is possible that no elements are visible - */ - public Object containsElements() { - TypeHierarchyContentProvider contentProvider= getHierarchyContentProvider(); - if (contentProvider != null) { - Object[] elements= contentProvider.getElements(null); - if (elements.length > 0) { - return elements[0]; - } - } - return null; - } - - /** - * Returns true if the hierarchy contains elements. Returns one of them - * With member filtering it is possible that no elements are visible - */ - public ICElement getTreeRootType() { - TypeHierarchyContentProvider contentProvider= getHierarchyContentProvider(); - if (contentProvider != null) { - Object[] elements= contentProvider.getElements(null); - if (elements.length > 0 && elements[0] instanceof ICElement) { - return (ICElement) elements[0]; - } - } - return null; - } - - /** - * Returns true if the hierarchy contains element the element. - */ - public boolean isElementShown(Object element) { - return findItem(element) != null; - } - - /** - * Updates the content of this viewer: refresh and expanding the tree in the way wanted. - */ - public abstract void updateContent(boolean doExpand); - - /** - * Returns the title for the current view - */ - public abstract String getTitle(); - - /* - * @see StructuredViewer#setContentProvider - * Content provider must be of type TypeHierarchyContentProvider - */ - public void setContentProvider(IContentProvider cp) { - Assert.isTrue(cp instanceof TypeHierarchyContentProvider); - super.setContentProvider(cp); - } - - protected TypeHierarchyContentProvider getHierarchyContentProvider() { - return (TypeHierarchyContentProvider)getContentProvider(); - } - -} diff --git a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/ui/browser/typeinfo/TypeInfoLabelProvider.java b/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/ui/browser/typeinfo/TypeInfoLabelProvider.java deleted file mode 100644 index 6a6e1564cd4..00000000000 --- a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/ui/browser/typeinfo/TypeInfoLabelProvider.java +++ /dev/null @@ -1,154 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * QNX Software Systems - adapted for use in CDT - *******************************************************************************/ -package org.eclipse.cdt.ui.browser.typeinfo; - -import org.eclipse.cdt.core.browser.IQualifiedTypeName; -import org.eclipse.cdt.core.browser.ITypeInfo; -import org.eclipse.cdt.core.browser.ITypeReference; -import org.eclipse.cdt.core.model.CoreModel; -import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.cdt.internal.ui.CPluginImages; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.runtime.IPath; -import org.eclipse.jface.viewers.LabelProvider; -import org.eclipse.swt.graphics.Image; - -public class TypeInfoLabelProvider extends LabelProvider { - - public static final int SHOW_TYPE_ONLY= 0x01; - public static final int SHOW_ENCLOSING_TYPE_ONLY= 0x02; - public static final int SHOW_FULLY_QUALIFIED= 0x04; - public static final int SHOW_PATH= 0x08; - - private static final Image HEADER_ICON= CPluginImages.get(CPluginImages.IMG_OBJS_TUNIT_HEADER); - private static final Image SOURCE_ICON= CPluginImages.get(CPluginImages.IMG_OBJS_TUNIT); - private static final Image NAMESPACE_ICON= CPluginImages.get(CPluginImages.IMG_OBJS_NAMESPACE); - private static final Image TEMPLATE_ICON= CPluginImages.get(CPluginImages.IMG_OBJS_TEMPLATE); - private static final Image CLASS_ICON= CPluginImages.get(CPluginImages.IMG_OBJS_CLASS); - private static final Image STRUCT_ICON= CPluginImages.get(CPluginImages.IMG_OBJS_STRUCT); - private static final Image TYPEDEF_ICON= CPluginImages.get(CPluginImages.IMG_OBJS_TYPEDEF); - private static final Image UNION_ICON= CPluginImages.get(CPluginImages.IMG_OBJS_UNION); - private static final Image ENUM_ICON= CPluginImages.get(CPluginImages.IMG_OBJS_ENUMERATION); - private static final Image UNKNOWN_TYPE_ICON= CPluginImages.get(CPluginImages.IMG_OBJS_UNKNOWN_TYPE); - - private int fFlags; - - public TypeInfoLabelProvider(int flags) { - fFlags= flags; - } - - private boolean isSet(int flag) { - return (fFlags & flag) != 0; - } - - /* non java-doc - * @see ILabelProvider#getText - */ - public String getText(Object element) { - if (! (element instanceof ITypeInfo)) - return super.getText(element); - - ITypeInfo typeRef= (ITypeInfo) element; - IQualifiedTypeName qualifiedName = typeRef.getQualifiedTypeName(); - - StringBuffer buf= new StringBuffer(); - if (isSet(SHOW_TYPE_ONLY)) { - String name= typeRef.getName(); - if (name != null && name.length() > 0) - buf.append(name); - } else if (isSet(SHOW_ENCLOSING_TYPE_ONLY)) { - IQualifiedTypeName parentName= qualifiedName.getEnclosingTypeName(); - if (parentName != null) { - buf.append(parentName.getFullyQualifiedName()); - } else { - buf.append(TypeInfoMessages.getString("TypeInfoLabelProvider.globalScope")); //$NON-NLS-1$ - } - } else if (isSet(SHOW_FULLY_QUALIFIED)) { - buf.append(qualifiedName.getFullyQualifiedName()); - } - - if (isSet(SHOW_PATH)) { - IPath path = null; - ITypeReference ref = typeRef.getResolvedReference(); - if (ref != null) { - path = ref.getPath(); - } else { - IProject project = typeRef.getEnclosingProject(); - if (project != null) { - path = project.getFullPath(); - } - } - if (path != null) { - buf.append(TypeInfoMessages.getString("TypeInfoLabelProvider.dash"));//$NON-NLS-1$ - buf.append(path.toString()); - } - } - return buf.toString(); - } - - /* non java-doc - * @see ILabelProvider#getImage - */ - public Image getImage(Object element) { - if (!(element instanceof ITypeInfo)) - return super.getImage(element); - - ITypeInfo typeRef= (ITypeInfo) element; - if (isSet(SHOW_ENCLOSING_TYPE_ONLY)) { - ITypeInfo parentInfo = typeRef.getEnclosingType(); - if (parentInfo != null) { - return getTypeIcon(parentInfo.getCElementType()); - } - IPath path = null; - ITypeReference ref = typeRef.getResolvedReference(); - if (ref != null) { - path = ref.getPath(); - if (CoreModel.isValidHeaderUnitName(typeRef.getEnclosingProject(), path.lastSegment())) { - return HEADER_ICON; - } - } - return SOURCE_ICON; - } - - return getTypeIcon(typeRef.getCElementType()); - } - - public static Image getTypeIcon(int type) - { - switch (type) - { - case ICElement.C_NAMESPACE: - return NAMESPACE_ICON; - - case ICElement.C_TEMPLATE_CLASS: - return TEMPLATE_ICON; - - case ICElement.C_CLASS: - return CLASS_ICON; - - case ICElement.C_STRUCT: - return STRUCT_ICON; - - case ICElement.C_UNION: - return UNION_ICON; - - case ICElement.C_ENUMERATION: - return ENUM_ICON; - - case ICElement.C_TYPEDEF: - return TYPEDEF_ICON; - - default: - return UNKNOWN_TYPE_ICON; - } - } -} diff --git a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/ui/browser/typeinfo/TypeSelectionDialog.java b/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/ui/browser/typeinfo/TypeSelectionDialog.java index d2ce05a9276..8b7982576b1 100644 --- a/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/ui/browser/typeinfo/TypeSelectionDialog.java +++ b/core/org.eclipse.cdt.ui/browser/org/eclipse/cdt/ui/browser/typeinfo/TypeSelectionDialog.java @@ -11,17 +11,13 @@ *******************************************************************************/ package org.eclipse.cdt.ui.browser.typeinfo; -import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; import java.util.HashSet; -import java.util.List; import java.util.Set; -import org.eclipse.cdt.core.browser.IQualifiedTypeName; -import org.eclipse.cdt.core.browser.ITypeInfo; -import org.eclipse.cdt.core.browser.QualifiedTypeName; import org.eclipse.cdt.core.model.ICElement; +import org.eclipse.cdt.core.model.util.QualifiedTypeName; import org.eclipse.cdt.internal.ui.util.StringMatcher; import org.eclipse.cdt.ui.CUIPlugin; import org.eclipse.jface.dialogs.IDialogSettings; @@ -121,46 +117,7 @@ public class TypeSelectionDialog extends TwoPaneElementSelector { * @see FilteredList.FilterMatcher#match(Object) */ public boolean match(Object element) { - if (!(element instanceof ITypeInfo)) - return false; - - ITypeInfo info = (ITypeInfo) element; - IQualifiedTypeName qualifiedName = info.getQualifiedTypeName(); - - if (fVisibleTypes != null && !fVisibleTypes.contains(new Integer(info.getCElementType()))) - return false; - - if (!fShowLowLevelTypes && qualifiedName.isLowLevel()) - return false; - - if (fSegmentMatchers.length == 1 && !fMatchGlobalNamespace) - return fNameMatcher.match(qualifiedName.getName()); - - return matchQualifiedName(info); - } - - private boolean matchQualifiedName(ITypeInfo info) { - IQualifiedTypeName qualifiedName = info.getQualifiedTypeName(); - if (fSegmentMatchers.length != qualifiedName.segmentCount()) - return false; - - if (fMatchGlobalNamespace) { - // must match global namespace (eg ::foo) - if (info.getRootNamespace(false) != null) - return false; - } - - boolean matchFound = true; - int max = Math.min(fSegmentMatchers.length, qualifiedName.segmentCount()); - for (int i = 0; i < max; ++i) { - StringMatcher matcher = fSegmentMatchers[i]; - String name = qualifiedName.segment(i); - if (name == null || !matcher.match(name)) { - matchFound = false; - break; - } - } - return matchFound; + return false; } private static String adjustPattern(String pattern) { @@ -203,9 +160,6 @@ public class TypeSelectionDialog extends TwoPaneElementSelector { private static final String SETTINGS_SHOW_UNIONS = "show_unions"; //$NON-NLS-1$ private static final String SETTINGS_SHOW_LOWLEVEL = "show_lowlevel"; //$NON-NLS-1$ - private static final TypeInfoLabelProvider fElementRenderer = new TypeInfoLabelProvider(TypeInfoLabelProvider.SHOW_TYPE_ONLY); - private static final TypeInfoLabelProvider fQualifierRenderer = new TypeInfoLabelProvider(TypeInfoLabelProvider.SHOW_ENCLOSING_TYPE_ONLY + TypeInfoLabelProvider.SHOW_PATH); - static final TypeFilterMatcher fFilterMatcher = new TypeFilterMatcher(); private static final StringComparator fStringComparator = new StringComparator(); @@ -226,7 +180,7 @@ public class TypeSelectionDialog extends TwoPaneElementSelector { * @param parent the parent shell. */ public TypeSelectionDialog(Shell parent) { - super(parent, fElementRenderer, fQualifierRenderer); + super(parent, null, null);//fElementRenderer, fQualifierRenderer); setMatchEmptyString(false); setUpperListLabel(TypeInfoMessages.getString("TypeSelectionDialog.upperLabel")); //$NON-NLS-1$ setLowerListLabel(TypeInfoMessages.getString("TypeSelectionDialog.lowerLabel")); //$NON-NLS-1$ @@ -341,7 +295,7 @@ public class TypeSelectionDialog extends TwoPaneElementSelector { default: return; } - Image icon = TypeInfoLabelProvider.getTypeIcon(type); + Image icon = null; //TypeInfoLabelProvider.getTypeIcon(type); Composite composite = new Composite(parent, SWT.NONE); GridLayout layout= new GridLayout(2, false); @@ -570,12 +524,5 @@ public class TypeSelectionDialog extends TwoPaneElementSelector { * @see org.eclipse.ui.dialogs.SelectionStatusDialog#computeResult() */ protected void computeResult() { - ITypeInfo selection = (ITypeInfo) getLowerSelectedElement(); - if (selection == null) - return; - - List result = new ArrayList(1); - result.add(selection); - setResult(result); } } diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/Checks.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/Checks.java deleted file mode 100644 index c44dff6a24b..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/Checks.java +++ /dev/null @@ -1,262 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.corext.refactoring; - -import java.util.ArrayList; -import java.util.List; - -import org.eclipse.cdt.core.CConventions; -import org.eclipse.cdt.core.model.CModelException; -import org.eclipse.cdt.core.model.CoreModel; -import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.cdt.core.model.ICModelMarker; -import org.eclipse.cdt.core.model.ITranslationUnit; -import org.eclipse.cdt.internal.corext.refactoring.base.RefactoringStatus; -import org.eclipse.cdt.internal.ui.util.Resources; -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IMarker; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.resources.ResourcesPlugin; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.IStatus; - -/** - * This class defines a set of reusable static checks methods. - */ -public class Checks { - - /* - * no instances - */ - private Checks(){ - } - - /* Constants returned by checkExpressionIsRValue */ - public static final int IS_RVALUE= 0; - public static final int NOT_RVALUE_MISC= 1; - public static final int NOT_RVALUE_VOID= 2; - - /** - * Checks if the given name is a valid C field name. - * - * @param the java field name. - * @return a refactoring status containing the error message if the - * name is not a valid java field name. - */ - public static RefactoringStatus checkFieldName(String name) { - return checkName(name, CConventions.validateFieldName(name)); - } - - /** - * Checks if the given name is a valid C identifier. - * - * @param the java identifier. - * @return a refactoring status containing the error message if the - * name is not a valid java identifier. - */ - public static RefactoringStatus checkIdentifier(String name) { - return checkName(name, CConventions.validateIdentifier(name)); - } - - /** - * Checks if the given name is a valid C method name. - * - * @param the java method name. - * @return a refactoring status containing the error message if the - * name is not a valid java method name. - */ - public static RefactoringStatus checkMethodName(String name) { - RefactoringStatus status= checkName(name, CConventions.validateMethodName(name)); - if (status.isOK() && startsWithUpperCase(name)) - return RefactoringStatus.createWarningStatus(RefactoringCoreMessages.getString("Checks.method_names_lowercase")); //$NON-NLS-1$ - else - return status; - } - - /** - * Checks if the given name is a valid C type name. - * - * @param the java method name. - * @return a refactoring status containing the error message if the - * name is not a valid java type name. - */ - public static RefactoringStatus checkClassName(String name) { - //fix for: 1GF5Z0Z: ITPJUI:WINNT - assertion failed after renameType refactoring - if (name.indexOf(".") != -1) //$NON-NLS-1$ - return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.getString("Checks.no_dot"));//$NON-NLS-1$ - else { - RefactoringStatus status = checkName(name, CConventions.validateClassName(name)); - if (status.hasFatalError()){ - String msg = RefactoringCoreMessages.getFormattedString( - "Checks.error.InvalidClassName",//$NON-NLS-1$ - status.getFirstMessage(RefactoringStatus.FATAL)); - return RefactoringStatus.createFatalErrorStatus(msg); - } - else if (status.hasError()){ - String msg = RefactoringCoreMessages.getFormattedString( - "Checks.error.InvalidClassName",//$NON-NLS-1$ - status.getFirstMessage(RefactoringStatus.ERROR)); - return RefactoringStatus.createErrorStatus(msg); - } - else if (status.hasWarning()){ - String msg = RefactoringCoreMessages.getFormattedString( - "Checks.warning.ClassNameDiscouraged",//$NON-NLS-1$ - status.getFirstMessage(RefactoringStatus.INFO)); - return RefactoringStatus.createWarningStatus(msg); - }else{ - return status; - } - } - } - - - private static boolean startsWithUpperCase(String s) { - if (s == null) - return false; - else if ("".equals(s)) //$NON-NLS-1$ - return false; - else - //workaround for JDK bug (see 26529) - return s.charAt(0) == Character.toUpperCase(s.charAt(0)); - } - - public static boolean startsWithLowerCase(String s){ - if (s == null) - return false; - else if ("".equals(s)) //$NON-NLS-1$ - return false; - else - //workaround for JDK bug (see 26529) - return s.charAt(0) == Character.toLowerCase(s.charAt(0)); - } - - public static boolean resourceExists(IPath resourcePath){ - return ResourcesPlugin.getWorkspace().getRoot().findMember(resourcePath) != null; - } - - - public static boolean isAlreadyNamed(ICElement element, String name){ - return name.equals(element.getElementName()); - } - - //---- Private helpers ---------------------------------------------------------------------- - - private static RefactoringStatus checkName(String name, IStatus status) { - RefactoringStatus result= new RefactoringStatus(); - if ("".equals(name)) //$NON-NLS-1$ - return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.getString("Checks.Choose_name")); //$NON-NLS-1$ - - if (status.isOK()) - return result; - - switch (status.getSeverity()){ - case IStatus.ERROR: - return RefactoringStatus.createFatalErrorStatus(status.getMessage()); - case IStatus.WARNING: - return RefactoringStatus.createWarningStatus(status.getMessage()); - case IStatus.INFO: - return RefactoringStatus.createInfoStatus(status.getMessage()); - default: //no nothing - return new RefactoringStatus(); - } - } - - public static RefactoringStatus checkIfTuBroken(ICElement element) throws CModelException{ - ITranslationUnit tu= (ITranslationUnit)CoreModel.getDefault().create(element.getUnderlyingResource()); - if (tu == null) - return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.getString("Checks.cu_not_created")); //$NON-NLS-1$ - else if (! tu.isStructureKnown()) - return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.getString("Checks.cu_not_parsed")); //$NON-NLS-1$ - return new RefactoringStatus(); - } - //-------- validateEdit checks ---- - - public static RefactoringStatus validateModifiesFiles(IFile[] filesToModify) { - RefactoringStatus result= new RefactoringStatus(); - IStatus status= Resources.checkInSync(filesToModify); - if (!status.isOK()) - result.merge(RefactoringStatus.create(status)); - status= Resources.makeCommittable(filesToModify, null); - if (!status.isOK()) - result.merge(RefactoringStatus.create(status)); - return result; - } - - public static boolean isAvailable(ICElement cElement) throws CModelException { - if (cElement == null) - return false; - if (! cElement.exists()) - return false; - if (cElement.isReadOnly()) - return false; - return true; - } - - /** - * From SearchResultGroup[] passed as the parameter - * this method removes all those that correspond to a non-parsable ITranslationUnit - * and returns it as a result. - * Status object collect the result of checking. - */ - public static SearchResultGroup[] excludeTranslationUnits(SearchResultGroup[] grouped, RefactoringStatus status) throws CModelException{ - List result= new ArrayList(); - boolean wasEmpty= grouped.length == 0; - for (int i= 0; i < grouped.length; i++){ - IResource resource= grouped[i].getResource(); - ICElement element= CoreModel.getDefault().create(resource); - if (! (element instanceof ITranslationUnit)) - continue; - //XXX this is a workaround for a jcore feature that shows errors in cus only when you get the original element - ITranslationUnit cu= (ITranslationUnit)CoreModel.getDefault().create(resource); - if (! cu.isStructureKnown()){ - String path= cu.getResource().getFullPath().toOSString(); - status.addError(RefactoringCoreMessages.getFormattedString("Checks.cannot_be_parsed", path)); //$NON-NLS-1$ - continue; //removed, go to the next one - } - result.add(grouped[i]); - } - - if ((!wasEmpty) && result.isEmpty()) - status.addFatalError(RefactoringCoreMessages.getString("Checks.all_excluded")); //$NON-NLS-1$ - else if (result.isEmpty()){ - status.addFatalError(RefactoringCoreMessages.getString("Checks.no_files")); //$NON-NLS-1$ - } - - return (SearchResultGroup[])result.toArray(new SearchResultGroup[result.size()]); - } - - public static RefactoringStatus checkCompileErrorsInAffectedFiles(SearchResultGroup[] grouped) throws CModelException { - RefactoringStatus result= new RefactoringStatus(); - for (int i= 0; i < grouped.length; i++){ - IResource resource= grouped[i].getResource(); - if (hasCompileErrors(resource)) - result.addFatalError(RefactoringCoreMessages.getFormattedString("Checks.cu_has_compile_errors", resource.getFullPath().makeRelative())); //$NON-NLS-1$ - } - return result; - } - - private static boolean hasCompileErrors(IResource resource) throws CModelException { - try { - IMarker[] problemMarkers= resource.findMarkers(ICModelMarker.C_MODEL_PROBLEM_MARKER, true, IResource.DEPTH_INFINITE); - for (int i= 0; i < problemMarkers.length; i++) { - if (problemMarkers[i].getAttribute(IMarker.SEVERITY, -1) == IMarker.SEVERITY_ERROR) - return true; - } - return false; - } catch (CModelException e){ - throw e; - } catch (CoreException e){ - throw new CModelException(e); - } - } - -} diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/CompositeChange.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/CompositeChange.java deleted file mode 100644 index 978c87b8b23..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/CompositeChange.java +++ /dev/null @@ -1,199 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.corext.refactoring; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; - -import org.eclipse.cdt.core.model.CModelException; -import org.eclipse.cdt.internal.corext.refactoring.base.*; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.SubProgressMonitor; - - -/** - * Represents a composite change. - */ -public class CompositeChange extends Change implements ICompositeChange { - - private List fChanges; - private IChange fUndoChange; - private String fName; - - public CompositeChange() { - this(RefactoringCoreMessages.getString("CompositeChange.CompositeChange")); //$NON-NLS-1$ - } - - public CompositeChange(String name, IChange[] changes) { - this(name, new ArrayList(changes.length)); - addAll(changes); - } - - public CompositeChange(String name) { - this(name, new ArrayList(5)); - } - - public CompositeChange(String name, int initialCapacity) { - this(name, new ArrayList(initialCapacity)); - } - - private CompositeChange(String name, List changes) { - fChanges= changes; - fName= name; - } - - /* (Non-Javadoc) - * Method declared in IChange. - */ - public final RefactoringStatus aboutToPerform(ChangeContext context, IProgressMonitor pm) { - // PR: 1GEWDUH: ITPJCORE:WINNT - Refactoring - Unable to undo refactor change - RefactoringStatus result= new RefactoringStatus(); - pm.beginTask("", fChanges.size() + 1); //$NON-NLS-1$ - result.merge(super.aboutToPerform(context, new SubProgressMonitor(pm,1))); - for (Iterator iter= fChanges.iterator(); iter.hasNext(); ) { - result.merge(((IChange)iter.next()).aboutToPerform(context, new SubProgressMonitor(pm,1))); - } - return result; - } - - /* (Non-Javadoc) - * Method declared in IChange. - */ - public final void performed() { - for (Iterator iter= fChanges.iterator(); iter.hasNext(); ) { - ((IChange)iter.next()).performed(); - } - } - - /* non java-doc - * @see IChange#getUndoChange - */ - public final IChange getUndoChange() { - return fUndoChange; - } - - public void addAll(IChange[] changes) { - for (int i= 0; i < changes.length; i++) { - add(changes[i]); - } - } - - public void add(IChange change) { - if (change != null) - fChanges.add(change); - } - - public IChange[] getChildren() { - if (fChanges == null) - return null; - return (IChange[])fChanges.toArray(new IChange[fChanges.size()]); - } - - final List getChanges() { - return fChanges; - } - - /** - * to reverse a composite means reversing all changes in reverse order - */ - private List createUndoList(ChangeContext context, IProgressMonitor pm) throws CModelException { - List undoList= null; - try { - undoList= new ArrayList(fChanges.size()); - pm.beginTask("", fChanges.size()); //$NON-NLS-1$ - for (Iterator iter= fChanges.iterator(); iter.hasNext();) { - try { - IChange each= (IChange)iter.next(); - each.perform(context, new SubProgressMonitor(pm, 1)); - undoList.add(each.getUndoChange()); - context.addPerformedChange(each); - } catch (Exception e) { - handleException(context, e); - } - } - pm.done(); - Collections.reverse(undoList); - return undoList; - } catch (Exception e) { - handleException(context, e); - } - if (undoList == null) - undoList= new ArrayList(0); - return undoList; - } - - /* non java-doc - * @see IChange#perform - */ - public final void perform(ChangeContext context, IProgressMonitor pm) throws CModelException { - pm.beginTask("", 1); //$NON-NLS-1$ - pm.setTaskName(RefactoringCoreMessages.getString("CompositeChange.performingChangesTask.name")); //$NON-NLS-1$ - if (!isActive()) { - fUndoChange= new NullChange(); - } else { - fUndoChange= new CompositeChange(fName, createUndoList(context, new SubProgressMonitor(pm, 1))); - } - pm.done(); - } - - /* non java-doc - * for debugging only - */ - public String toString() { - StringBuffer buff= new StringBuffer(); - buff.append("CompositeChange\n"); //$NON-NLS-1$ - for (Iterator iter= fChanges.iterator(); iter.hasNext();) { - buff.append("<").append(iter.next().toString()).append("/>\n"); //$NON-NLS-2$ //$NON-NLS-1$ - } - return buff.toString(); - } - - /* non java-doc - * @see IChange#getName() - */ - public String getName() { - return fName; - } - - /* non java-doc - * @see IChange#getModifiedLanguageElement() - */ - public Object getModifiedLanguageElement() { - return null; - } - - /* non java-doc - * @see IChange#setActive - * This method activates/disactivates all subchanges of this change. The - * change itself is always active to ensure that sub changes are always - * considered if they are active. - */ - public void setActive(boolean active) { - for (Iterator iter= fChanges.iterator(); iter.hasNext(); ) { - ((IChange)iter.next()).setActive(active); - } - } - - /*non java-doc - * @see IChange#isUndoable() - * Composite can be undone iff all its sub-changes can be undone. - */ - public boolean isUndoable() { - for (Iterator iter= fChanges.iterator(); iter.hasNext(); ) { - IChange each= (IChange)iter.next(); - if (! each.isUndoable()) - return false; - } - return true; - } -} diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/IProcessorBasedRefactoring.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/IProcessorBasedRefactoring.java deleted file mode 100644 index 61e4188db1d..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/IProcessorBasedRefactoring.java +++ /dev/null @@ -1,28 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.corext.refactoring; - -import org.eclipse.core.runtime.IAdaptable; - -/** - * A tagging interface for refactorings that are implemented using - * the processor/participant architecture - */ -public interface IProcessorBasedRefactoring extends IAdaptable { - - /** - * Returns the refactoring's processor - * - * @return the refactoring's processor - */ - public IRefactoringProcessor getProcessor(); - -} diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/IQualifiedNameUpdatingRefactoring.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/IQualifiedNameUpdatingRefactoring.java deleted file mode 100644 index a4e3265c705..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/IQualifiedNameUpdatingRefactoring.java +++ /dev/null @@ -1,43 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.corext.refactoring; - -public interface IQualifiedNameUpdatingRefactoring { - - /** - * Performs a dynamic check whether this refactoring object is capable of - * updating qualified names in non C files. The return value of this - * method may change according to the state of the refactoring. - */ - public boolean canEnableQualifiedNameUpdating(); - - /** - * If canEnableQualifiedNameUpdating returns true, - * then this method is used to ask the refactoring object whether references - * in non C files should be updated. This call can be ignored if - * canEnableQualifiedNameUpdating returns false. - */ - public boolean getUpdateQualifiedNames(); - - /** - * If canEnableQualifiedNameUpdating returns true, - * then this method is used to inform the refactoring object whether - * references in non C files should be updated. This call can be ignored - * if canEnableQualifiedNameUpdating returns false. - */ - public void setUpdateQualifiedNames(boolean update); - - public String getFilePatterns(); - - public void setFilePatterns(String patterns); -} - - diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/IRefactoringProcessor.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/IRefactoringProcessor.java deleted file mode 100644 index 7b6b9fa7b52..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/IRefactoringProcessor.java +++ /dev/null @@ -1,43 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.corext.refactoring; - -import org.eclipse.cdt.internal.corext.refactoring.base.IChange; -import org.eclipse.cdt.internal.corext.refactoring.base.RefactoringStatus; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IAdaptable; -import org.eclipse.core.runtime.IProgressMonitor; - - -public interface IRefactoringProcessor extends IAdaptable { - - public void initialize(Object[] elements) throws CoreException; - - public boolean isAvailable() throws CoreException; - - public String getProcessorName(); - - public int getStyle(); - -// public IProject[] getAffectedProjects() throws CoreException; - - public Object[] getElements(); - - public Object[] getDerivedElements() throws CoreException; - -// public IResourceModifications getResourceModifications() throws CoreException; - - public RefactoringStatus checkActivation() throws CoreException; - - public RefactoringStatus checkInput(IProgressMonitor pm) throws CoreException; - - public IChange createChange(IProgressMonitor pm) throws CoreException; -} diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/IReferenceUpdating.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/IReferenceUpdating.java deleted file mode 100644 index f5fd60d8d16..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/IReferenceUpdating.java +++ /dev/null @@ -1,35 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.corext.refactoring; - -public interface IReferenceUpdating { - - /** - * Checks if this refactoring object is capable of updating references to the renamed element. - */ - public boolean canEnableUpdateReferences(); - - /** - * If canUpdateReferences returns true, then this method is used to - * inform the refactoring object whether references should be updated. - * This call can be ignored if canUpdateReferences returns false. - */ - public void setUpdateReferences(boolean update); - - /** - * If canUpdateReferences returns true, then this method is used to - * ask the refactoring object whether references should be updated. - * This call can be ignored if canUpdateReferences returns false. - */ - public boolean getUpdateReferences(); - -} - diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/IRenameProcessor.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/IRenameProcessor.java deleted file mode 100644 index 14370acb016..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/IRenameProcessor.java +++ /dev/null @@ -1,28 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.corext.refactoring; - -import org.eclipse.core.runtime.CoreException; - -import org.eclipse.cdt.internal.corext.refactoring.base.*; - - -public interface IRenameProcessor extends IRefactoringProcessor { - - public String getCurrentElementName(); - - public RefactoringStatus checkNewElementName(String newName) throws CoreException; - - public void setNewElementName(String newName); - - public String getNewElementName(); - -} diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/IRenameRefactoring.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/IRenameRefactoring.java deleted file mode 100644 index 4ab3177af75..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/IRenameRefactoring.java +++ /dev/null @@ -1,40 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.corext.refactoring; - -import org.eclipse.cdt.core.model.CModelException; -import org.eclipse.cdt.internal.corext.refactoring.base.*; - -/** - * Represents a refactoring that renames an ICElement. - */ -public interface IRenameRefactoring extends IRefactoring { - - /** - * Sets new name for the entity that this refactoring is working on. - */ - public void setNewName(String newName); - - /** - * Get the name for the entity that this refactoring is working on. - */ - public String getNewName(); - - /** - * Gets the current name of the entity that this refactoring is working on. - */ - public String getCurrentName(); - - /** - * Checks if the new name is valid for the entity that this refactoring renames. - */ - public RefactoringStatus checkNewName(String newName) throws CModelException; -} diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/IResourceModifications.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/IResourceModifications.java deleted file mode 100644 index f7159075cc8..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/IResourceModifications.java +++ /dev/null @@ -1,93 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.corext.refactoring; - - -import java.util.List; - -import org.eclipse.core.resources.IContainer; -import org.eclipse.core.resources.IResource; - -/** - * A data structure describing the resource modification resulting from - * applying a certain refactoring. - * - * @since 3.0 - */ -public interface IResourceModifications { - - /** - * Returns the list of resources to be created. - * - * @return the list of resources to be created - */ - public List getCreate(); - - /** - * Returns the list of resources to be deleted. - * - * @return the list of resources to be deleted - */ - public List getDelete(); - - /** - * Returns the list of resources to be copied. - * - * @return the list of resources to be copied - */ - public List getCopy(); - - /** - * Returns the copy target. - * - * @return the copy target - */ - public IContainer getCopyTarget(); - - /** - * Returns the list of resources to be moved. - * - * @return the list of resources to be moved - */ - public List getMove(); - - /** - * Returns the move target - * - * @return the move target - */ - public IContainer getMoveTarget(); - - /** - * Returns the resource to be renamed - * - * @return the resourcr to be renamed - */ - public IResource getRename(); - - /** - * Returns the new name of the resource to be renamed - * - * @return the new resource name - */ - public String getNewName(); - - /** - * Returns an array of participants that want to participate - * in the resource modifications described by this data - * structure. - * - * @param processor the main processor of the overall refactoring - * @return an array of participants - */ -// public IRefactoringParticipant[] getParticipants(IRefactoringProcessor processor, SharableParticipants shared) throws CoreException; - -} diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/ITextUpdating.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/ITextUpdating.java deleted file mode 100644 index 2531887d4a4..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/ITextUpdating.java +++ /dev/null @@ -1,80 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.corext.refactoring; - - - -public interface ITextUpdating { - - /** - * Performs a dynamic check whether this refactoring object is capable of updating references to the renamed element. - */ - public boolean canEnableTextUpdating(); - - /** - * If canEnableTextUpdating returns true, then this method is used to - * ask the refactoring object whether references in JavaDoc comments should be updated. - * This call can be ignored if canEnableTextUpdating returns false. - */ - public boolean getUpdateJavaDoc(); - - /** - * If canEnableTextUpdating returns true, then this method is used to - * ask the refactoring object whether references in regular (non JavaDoc) comments should be updated. - * This call can be ignored if canEnableTextUpdating returns false. - */ - public boolean getUpdateComments(); - - /** - * If canEnableTextUpdating returns true, then this method is used to - * ask the refactoring object whether references in string literals should be updated. - * This call can be ignored if canEnableTextUpdating returns false. - */ - public boolean getUpdateStrings(); - - /** - * If canEnableTextUpdating returns true, then this method is used to - * inform the refactoring object whether references in JavaDoc comments should be updated. - * This call can be ignored if canEnableTextUpdating returns false. - */ - public void setUpdateJavaDoc(boolean update); - - /** - * If canEnableTextUpdating returns true, then this method is used to - * inform the refactoring object whether references in regular (non JavaDoc) comments should be updated. - * This call can be ignored if canEnableTextUpdating returns false. - */ - public void setUpdateComments(boolean update); - - /** - * If canEnableTextUpdating returns true, then this method is used to - * inform the refactoring object whether references in string literals should be updated. - * This call can be ignored if canEnableTextUpdating returns false. - */ - public void setUpdateStrings(boolean update); - - /** - * Returns the current name of the element to be renamed. - * - * @return the current name of the element to be renamed - */ - public String getCurrentElementName(); - - /** - * Returns the new name of the element - * - * @return the new element name - */ - public String getNewElementName(); -} - - - diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/ListenerList.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/ListenerList.java deleted file mode 100644 index ba32e3d4432..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/ListenerList.java +++ /dev/null @@ -1,151 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.corext.refactoring; - -import org.eclipse.cdt.internal.corext.Assert; - -/** - * Local copy of org.eclipse.jface.ListenerList - */ -public class ListenerList { - - static { - //XXX: 1GCQD0A: ITPVCM:WIN2000 - ListenerList should be part of a core project - } - - /** - * The initial capacity of the list. Always >= 1. - */ - private int capacity; - - /** - * The current number of listeners. - * Maintains invariant: 0 <= size <= listeners.length. - */ - private int size; - - /** - * The list of listeners. Initially null but initialized - * to an array of size capacity the first time a listener is added. - * Maintains invariant: listeners != null IFF size != 0 - */ - private Object[] listeners= null; - - /** - * The empty array singleton instance, returned by getListeners() - * when size == 0. - */ - private static final Object[] EmptyArray= new Object[0]; - - /** - * Creates a listener list with an initial capacity of 3. - */ - public ListenerList() { - this(3); - } - - /** - * Creates a listener list with the given initial capacity. - * - * @param capacity the number of listeners which this list can initially accept - * without growing its internal representation; must be at least 1 - */ - public ListenerList(int capacity) { - Assert.isTrue(capacity >= 1); - this.capacity= capacity; - } - - /** - * Adds the given listener to this list. Has no effect if an identical listener - * is already registered. - * - * @param listener the listener - */ - public void add(Object listener) { - Assert.isNotNull(listener); - if (size == 0) { - listeners= new Object[capacity]; - } else { - // check for duplicates using identity - for (int i= 0; i < size; ++i) { - if (listeners[i] == listener) { - return; - } - } - // grow array if necessary - if (size == listeners.length) { - System.arraycopy(listeners, 0, listeners= new Object[size * 2 + 1], 0, size); - } - } - listeners[size++]= listener; - } - - /** - * Returns an array containing all the registered listeners. - * The resulting array is unaffected by subsequent adds or removes. - * If there are no listeners registered, the result is an empty array - * singleton instance (no garbage is created). - * Use this method when notifying listeners, so that any modifications - * to the listener list during the notification will have no effect on the - * notification itself. - * - * @return the list of registered listeners - */ - public Object[] getListeners() { - if (size == 0) - return EmptyArray; - Object[] result= new Object[size]; - System.arraycopy(listeners, 0, result, 0, size); - return result; - } - - /** - * Returns whether this listener list is empty. - * - * @return true if there are no registered listeners, and - * false otherwise - */ - public boolean isEmpty() { - return size == 0; - } - - /** - * Removes the given listener from this list. Has no effect if an identical - * listener was not already registered. - * - * @param listener the listener - */ - public void remove(Object listener) { - Assert.isNotNull(listener); - for (int i= 0; i < size; ++i) { - if (listeners[i] == listener) { - if (--size == 0) { - listeners= new Object[1]; - } else { - if (i < size) { - listeners[i]= listeners[size]; - } - listeners[size]= null; - } - return; - } - } - } - - /** - * Returns the number of registered listeners. - * - * @return the number of registered listeners - */ - public int size() { - return size; - } -} diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/NullChange.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/NullChange.java deleted file mode 100644 index 66d26b0522e..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/NullChange.java +++ /dev/null @@ -1,43 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.corext.refactoring; - -import org.eclipse.cdt.internal.corext.refactoring.base.*; -import org.eclipse.core.runtime.IProgressMonitor; - - -public class NullChange extends Change { - - private String fName; - - public NullChange(String name){ - fName= name; - } - - public NullChange(){ - this(null); - } - - public void perform(ChangeContext context, IProgressMonitor pm) { - } - - public IChange getUndoChange() { - return new NullChange(fName); - } - - public String getName(){ - return "NullChange (" + fName + ")"; //$NON-NLS-1$ //$NON-NLS-2$ - } - - public Object getModifiedLanguageElement(){ - return null; - } -} diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/RefactoringCoreMessages.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/RefactoringCoreMessages.java deleted file mode 100644 index e2fe901ca18..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/RefactoringCoreMessages.java +++ /dev/null @@ -1,66 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.corext.refactoring; - -import java.text.MessageFormat; -import java.util.MissingResourceException; -import java.util.ResourceBundle; - -public class RefactoringCoreMessages { - - private static final String RESOURCE_BUNDLE= "org.eclipse.cdt.internal.corext.refactoring.refactoring";//$NON-NLS-1$ - - private static ResourceBundle fgResourceBundle= ResourceBundle.getBundle(RESOURCE_BUNDLE); - - private RefactoringCoreMessages() { - } - - public static String getString(String key) { - try { - return fgResourceBundle.getString(key); - } catch (MissingResourceException e) { - return "!" + key + "!";//$NON-NLS-2$ //$NON-NLS-1$ - } - } - - public static String getFormattedString(String key, String arg) { - try{ - return MessageFormat.format(fgResourceBundle.getString(key), new String[] { arg }); - } catch (MissingResourceException e) { - return "!" + key + "!";//$NON-NLS-2$ //$NON-NLS-1$ - } - } - - public static String getFormattedString(String key, Object arg) { - try{ - return MessageFormat.format(fgResourceBundle.getString(key), new Object[] { arg }); - } catch (MissingResourceException e) { - return "!" + key + "!";//$NON-NLS-2$ //$NON-NLS-1$ - } - } - - public static String getFormattedString(String key, String[] args) { - try{ - return MessageFormat.format(fgResourceBundle.getString(key), args); - } catch (MissingResourceException e) { - return "!" + key + "!";//$NON-NLS-2$ //$NON-NLS-1$ - } - } - - public static String getFormattedString(String key, Object[] args) { - try{ - return MessageFormat.format(fgResourceBundle.getString(key), args); - } catch (MissingResourceException e) { - return "!" + key + "!";//$NON-NLS-2$ //$NON-NLS-1$ - } - } - -} diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/RefactoringSearchEngine.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/RefactoringSearchEngine.java deleted file mode 100644 index 360a07d251a..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/RefactoringSearchEngine.java +++ /dev/null @@ -1,160 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.corext.refactoring; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.eclipse.cdt.core.model.CModelException; -import org.eclipse.cdt.core.model.CoreModel; -import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.cdt.core.model.ITranslationUnit; -import org.eclipse.cdt.core.search.BasicSearchMatch; -import org.eclipse.cdt.core.search.BasicSearchResultCollector; -import org.eclipse.cdt.core.search.ICSearchPattern; -import org.eclipse.cdt.core.search.ICSearchResultCollector; -import org.eclipse.cdt.core.search.ICSearchScope; -import org.eclipse.cdt.core.search.SearchEngine; -import org.eclipse.cdt.internal.corext.Assert; -import org.eclipse.cdt.internal.corext.util.CModelUtil; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.resources.ResourcesPlugin; -import org.eclipse.core.runtime.IProgressMonitor; - - -/** - * Convenience wrapper for SearchEngine - performs searching and sorts the results. - */ -public class RefactoringSearchEngine { - - //no instances - private RefactoringSearchEngine(){ - } - - public static ITranslationUnit[] findAffectedTranslationUnits(final IProgressMonitor pm, ICSearchScope scope, ICSearchPattern pattern) throws CModelException { - final Set matches= new HashSet(5); - ICSearchResultCollector collector = new BasicSearchResultCollector(); - try { - new SearchEngine().search(ResourcesPlugin.getWorkspace(), pattern, scope, collector, false); - } catch (InterruptedException e){ - - } - - List result= new ArrayList(matches.size()); - for (Iterator iter= matches.iterator(); iter.hasNext(); ) { - IResource resource= (IResource)iter.next(); - ICElement element= CoreModel.getDefault().create(resource); - if (element instanceof ITranslationUnit) { - ITranslationUnit original= (ITranslationUnit)element; - result.add(CModelUtil.toWorkingCopy(original)); // take working copy is there is one - } - } - return (ITranslationUnit[])result.toArray(new ITranslationUnit[result.size()]); - } - - /** - * Performs searching for a given SearchPattern. - * Returns SearchResultGroup[] - * In each of SearchResultGroups all SearchResults are - * sorted backwards by SearchResult#getStart() - * @see SearchResult - */ - public static SearchResultGroup[] search(IProgressMonitor pm, ICSearchScope scope, ICSearchPattern pattern) throws CModelException { - return search(scope, pattern, new BasicSearchResultCollector(pm)); - } - - public static SearchResultGroup[] search(ICSearchScope scope, ICSearchPattern pattern, BasicSearchResultCollector collector) throws CModelException { - return search(scope, pattern, collector, null); - } - - public static SearchResultGroup[] search(IProgressMonitor pm, ICSearchScope scope, ICSearchPattern pattern, ITranslationUnit[] workingCopies) throws CModelException { - return search(scope, pattern, new BasicSearchResultCollector(pm), workingCopies); - } - - public static SearchResultGroup[] search(ICSearchScope scope, ICSearchPattern pattern, BasicSearchResultCollector collector, ITranslationUnit[] workingCopies) throws CModelException { - internalSearch(scope, pattern, collector, workingCopies); - Set results = collector.getSearchResults(); - List resultList = new ArrayList(results); - return groupByResource(createSearchResultArray(resultList)); - } - - public static SearchResultGroup[] groupByResource(BasicSearchMatch[] results){ - Map grouped= groupByResource(Arrays.asList(results)); - - SearchResultGroup[] result= new SearchResultGroup[grouped.keySet().size()]; - int i= 0; - for (Iterator iter= grouped.keySet().iterator(); iter.hasNext();) { - IResource resource= (IResource)iter.next(); - List searchResults= (List)grouped.get(resource); - result[i]= new SearchResultGroup(resource, createSearchResultArray(searchResults)); - i++; - } - return result; - } - - private static BasicSearchMatch[] createSearchResultArray(List searchResults){ - return (BasicSearchMatch[])searchResults.toArray(new BasicSearchMatch[searchResults.size()]); - } - - private static Map groupByResource(List searchResults){ - Map grouped= new HashMap(); //IResource -> List of SearchResults - for (Iterator iter= searchResults.iterator(); iter.hasNext();) { - BasicSearchMatch searchResult= (BasicSearchMatch) iter.next(); - if (! grouped.containsKey(searchResult.getResource())) - grouped.put(searchResult.getResource(), new ArrayList(1)); - ((List)grouped.get(searchResult.getResource())).add(searchResult); - } - return grouped; - } - - private static void internalSearch(ICSearchScope scope, ICSearchPattern pattern, ICSearchResultCollector collector, ITranslationUnit[] workingCopies) throws CModelException { - if (pattern == null) - return; - Assert.isNotNull(scope, "scope"); //$NON-NLS-1$ - try { - createSearchEngine(workingCopies).search(ResourcesPlugin.getWorkspace(), pattern, scope, collector, false); - }catch (InterruptedException e){ - - } - } - - private static SearchEngine createSearchEngine(ITranslationUnit[] workingCopies){ -// if (workingCopies == null) - return new SearchEngine(); -// else -// return new SearchEngine(workingCopies); - } - -// public static ICSearchPattern createSearchPattern(ICElement[] elements, int limitTo) { -// if (elements == null || elements.length == 0) -// return null; -// Set set= new HashSet(Arrays.asList(elements)); -// Iterator iter= set.iterator(); -// ICElement first= (ICElement)iter.next(); -// ICSearchPattern pattern= createSearchPattern(first, limitTo); -// while(iter.hasNext()){ -// ICElement each= (ICElement)iter.next(); -// pattern= SearchEngine.createOrSearchPattern(pattern, createSearchPattern(each, limitTo)); -// } -// return pattern; -// } - -// private static ICSearchPattern createSearchPattern(ICElement element, int limitTo) { -// return SearchEngine.createSearchPattern(element, limitTo, true); -// } - -} diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/RefactoringStyles.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/RefactoringStyles.java deleted file mode 100644 index e20bb24f12e..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/RefactoringStyles.java +++ /dev/null @@ -1,24 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.corext.refactoring; - - -public final class RefactoringStyles { - - public static final int NONE= 0; - public static final int NEEDS_PREVIEW= 1 << 0; - public static final int FORCE_PREVIEW= 1 << 1; - public static final int NEEDS_PROGRESS= 1 << 2; - - private RefactoringStyles() { - // no instance - } -} diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/RenameProcessor.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/RenameProcessor.java deleted file mode 100644 index b1043b8adc6..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/RenameProcessor.java +++ /dev/null @@ -1,68 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.corext.refactoring; - -import org.eclipse.cdt.internal.corext.Assert; -import org.eclipse.core.runtime.CoreException; - -public abstract class RenameProcessor implements IRenameProcessor { - - private int fStyle; - protected String fNewElementName; - - public int getStyle() { - return fStyle; - } - - protected RenameProcessor() { - fStyle= RefactoringStyles.NEEDS_PREVIEW; - } - - protected RenameProcessor(int style) { - fStyle= style; - } - - /* (non-Javadoc) - * @see org.eclipse.jdt.internal.corext.refactoring.participants.IRenameProcessor#setNewElementName(java.lang.String) - */ - public void setNewElementName(String newName) { - Assert.isNotNull(newName); - fNewElementName= newName; - } - - /* (non-Javadoc) - * @see org.eclipse.jdt.internal.corext.refactoring.participants.IRenameProcessor#getNewElementName() - */ - public String getNewElementName() { - return fNewElementName; - } - - /* (non-Javadoc) - * @see org.eclipse.jdt.internal.corext.refactoring.participants.IRefactoringProcessor#getDerivedElements() - */ - public Object[] getDerivedElements() throws CoreException { - return new Object[0]; - } - -// public void propagateDataTo(IRenameParticipant participant) throws CoreException { -// participant.setNewElementName(fNewElementName); -// if (this instanceof IReferenceUpdating) { -// participant.setUpdateReferences(((IReferenceUpdating)this).getUpdateReferences()); -// } -// } - - /* (non-Javadoc) - * @see org.eclipse.core.runtime.IAdaptable#getAdapter(java.lang.Class) - */ - public Object getAdapter(Class clazz) { - return null; - } -} diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/RenameRefactoring.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/RenameRefactoring.java deleted file mode 100644 index d83634a6fee..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/RenameRefactoring.java +++ /dev/null @@ -1,156 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.corext.refactoring; - - -import org.eclipse.cdt.core.model.CModelException; -import org.eclipse.cdt.internal.corext.Assert; -import org.eclipse.cdt.internal.corext.refactoring.base.IChange; -import org.eclipse.cdt.internal.corext.refactoring.base.Refactoring; -import org.eclipse.cdt.internal.corext.refactoring.base.RefactoringStatus; -import org.eclipse.cdt.internal.corext.refactoring.rename.RenameElementProcessor; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.SubProgressMonitor; - -public class RenameRefactoring extends Refactoring implements IProcessorBasedRefactoring, IRenameRefactoring { - - private Object fElement; - private IRenameProcessor fProcessor; - - public RenameRefactoring(Object element) throws CoreException { - Assert.isNotNull(element); - - fElement= element; - fProcessor = new RenameElementProcessor(); - fProcessor.initialize(new Object[] {fElement}); - } - - public boolean isAvailable() { - return fProcessor != null; - } - - public Object getAdapter(Class clazz) { - if (clazz.isInstance(fProcessor)) - return fProcessor; - return super.getAdapter(clazz); - } - - public IRefactoringProcessor getProcessor() { - return fProcessor; - } - - public int getStyle() { - return fProcessor.getStyle(); - } - - /* (non-Javadoc) - * @see org.eclipse.jdt.internal.corext.refactoring.tagging.IRenameRefactoring#getNewName() - */ - public String getNewName() { - return fProcessor.getNewElementName(); - } - - /* (non-Javadoc) - * @see org.eclipse.jdt.internal.corext.refactoring.tagging.IRenameRefactoring#setNewName(java.lang.String) - */ - public void setNewName(String newName) { - fProcessor.setNewElementName(newName); - } - - - /* (non-Javadoc) - * @see org.eclipse.jdt.internal.corext.refactoring.tagging.IRenameRefactoring#getCurrentName() - */ - public String getCurrentName() { - return fProcessor.getCurrentElementName(); - } - - /* (non-Javadoc) - * @see org.eclipse.jdt.internal.corext.refactoring.tagging.IRenameRefactoring#checkNewName(java.lang.String) - */ - public RefactoringStatus checkNewName(String newName) throws CModelException { - RefactoringStatus result= new RefactoringStatus(); - try { - result.merge(fProcessor.checkNewElementName(newName)); - } catch (CoreException e) { - throw new CModelException(e); - } - return result; - } - - /* (non-Javadoc) - * @see org.eclipse.jdt.internal.corext.refactoring.base.IRefactoring#getName() - */ - public String getName() { - return fProcessor.getProcessorName(); - } - - /* (non-Javadoc) - * @see org.eclipse.jdt.internal.corext.refactoring.base.Refactoring#checkActivation(org.eclipse.core.runtime.IProgressMonitor) - */ - public RefactoringStatus checkActivation(IProgressMonitor pm) throws CModelException { - RefactoringStatus result= new RefactoringStatus(); - try { - result.merge(fProcessor.checkActivation()); - } catch (CoreException e) { - throw new CModelException(e); - } - return result; - } - - /* (non-Javadoc) - * @see org.eclipse.jdt.internal.corext.refactoring.base.Refactoring#checkInput(org.eclipse.core.runtime.IProgressMonitor) - */ - public RefactoringStatus checkInput(IProgressMonitor pm) throws CModelException { - RefactoringStatus result= new RefactoringStatus(); - try { - //initParticipants(); - pm.beginTask("", 2); //$NON-NLS-1$ - - result.merge(fProcessor.checkInput(new SubProgressMonitor(pm, 1))); - if (result.hasFatalError()) - return result; - - } catch (CModelException e) { - throw e; - } catch (CoreException e) { - throw new CModelException(e); - } - return result; - } - - /* (non-Javadoc) - * @see org.eclipse.jdt.internal.corext.refactoring.base.IRefactoring#createChange(org.eclipse.core.runtime.IProgressMonitor) - */ - public IChange createChange(IProgressMonitor pm) throws CModelException { - pm.beginTask("", 1); //$NON-NLS-1$ - CompositeChange result= new CompositeChange(); - try { - result.add(fProcessor.createChange(new SubProgressMonitor(pm, 1))); - } catch (CModelException e) { - throw e; - } catch (CoreException e) { - throw new CModelException(e); - } - return result; - } - - /* non java-doc - * for debugging only - */ - public String toString() { - if (isAvailable()) - return getName(); - else - return "No refactoring available to process: " + fElement; //$NON-NLS-1$ - } -} diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/ResourceUtil.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/ResourceUtil.java deleted file mode 100644 index d9b573e7eaa..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/ResourceUtil.java +++ /dev/null @@ -1,83 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.corext.refactoring; - -import java.util.ArrayList; -import java.util.List; - -import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.cdt.core.model.IMember; -import org.eclipse.cdt.core.model.IOpenable; -import org.eclipse.cdt.core.model.ITranslationUnit; -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IResource; - -public class ResourceUtil { - - private ResourceUtil(){ - } - - public static IFile[] getFiles(ITranslationUnit[] cus) { - List files= new ArrayList(cus.length); - for (int i= 0; i < cus.length; i++) { - IResource resource= ResourceUtil.getResource(cus[i]); - if (resource.getType() == IResource.FILE) - files.add(resource); - } - return (IFile[]) files.toArray(new IFile[files.size()]); - } - - public static IFile getFile(ITranslationUnit cu) { - IResource resource= ResourceUtil.getResource(cu); - if (resource.getType() == IResource.FILE) - return (IFile)resource; - else - return null; - } - - //----- other ------------------------------ - - /** - * Finds an IResource for a given ITranslationUnit. - * If the parameter is a working copy then the IResource for - * the original element is returned. - */ - public static IResource getResource(ITranslationUnit cu) { - return cu.getResource(); - } - - - /** - * Returns the IResource that the given IMember is defined in. - * @see #getResource - */ - public static IResource getResource(IMember member) { - //Assert.isTrue(!member.isBinary()); - return getResource(member.getTranslationUnit()); - } - - public static IResource getResource(Object o){ - if (o instanceof IResource) - return (IResource)o; - if (o instanceof ICElement) - return getResource((ICElement)o); - return null; - } - - private static IResource getResource(ICElement element){ - if (element.getElementType() == ICElement.C_UNIT) - return getResource((ITranslationUnit) element); - else if (element instanceof IOpenable) - return element.getResource(); - else - return null; - } -} diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/SearchResultGroup.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/SearchResultGroup.java deleted file mode 100644 index fa2e4fdadd8..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/SearchResultGroup.java +++ /dev/null @@ -1,60 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.corext.refactoring; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import org.eclipse.cdt.core.search.BasicSearchMatch; -import org.eclipse.cdt.internal.corext.Assert; -import org.eclipse.core.resources.IResource; - -public class SearchResultGroup { - - private final IResource fResouce; - private final List fSearchResults; - - public SearchResultGroup(IResource res, BasicSearchMatch[] results){ - Assert.isNotNull(results); - fResouce= res; - fSearchResults= new ArrayList(Arrays.asList(results));//have to is this way to allow adding - } - - public void add(BasicSearchMatch result) { - Assert.isNotNull(result); - fSearchResults.add(result); - } - - public IResource getResource() { - return fResouce; - } - - public BasicSearchMatch[] getSearchResults() { - return (BasicSearchMatch[]) fSearchResults.toArray(new BasicSearchMatch[fSearchResults.size()]); - } - - public static IResource[] getResources(SearchResultGroup[] searchResultGroups){ - Set resourceSet= new HashSet(searchResultGroups.length); - for (int i= 0; i < searchResultGroups.length; i++) { - resourceSet.add(searchResultGroups[i].getResource()); - } - return (IResource[]) resourceSet.toArray(new IResource[resourceSet.size()]); - } - - public IResource getResultGroupResource(){ - if (getSearchResults() == null || getSearchResults().length == 0) - return null; - return getSearchResults()[0].getResource(); - } -} diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/TextChangeManager.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/TextChangeManager.java deleted file mode 100644 index 1ab68bc8b52..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/TextChangeManager.java +++ /dev/null @@ -1,117 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.corext.refactoring; - -import java.util.HashMap; -import java.util.Map; - -import org.eclipse.core.runtime.CoreException; - -import org.eclipse.cdt.core.model.ITranslationUnit; - -import org.eclipse.cdt.internal.corext.refactoring.changes.TranslationUnitChange; -import org.eclipse.cdt.internal.corext.refactoring.changes.TextChange; - -/** - * A TextChangeManager manages associations between ITranslationUnit - * or IFile and TextChange objects. - */ -public class TextChangeManager { - - private Map fMap= new HashMap(10); // ITranslationUnit -> TextChange - - private final boolean fKeepExecutedTextEdits; - - public TextChangeManager() { - this(false); - } - - /** - * @see TextChange.setKeepExecutedTextEdits - */ - public TextChangeManager(boolean keepExecutedTextEdits) { - fKeepExecutedTextEdits= keepExecutedTextEdits; - } - - /** - * Adds an association between the given Translation unit and the passed - * change to this manager. - * - * @param cu the Translation unit (key) - * @param change the change associated with the Translation unit - */ - public void manage(ITranslationUnit cu, TextChange change) { - fMap.put(cu, change); - } - - /** - * Returns the TextChange associated with the given Translation unit. - * If the manager does not already manage an association it creates a one. - * - * @param cu the Translation unit for which the text buffer change is requested - * @return the text change associated with the given Translation unit. - */ - public TextChange get(ITranslationUnit cu) throws CoreException { - TextChange result= (TextChange)fMap.get(cu); - if (result == null) { - result= new TranslationUnitChange(cu.getElementName(), cu); - result.setKeepExecutedTextEdits(fKeepExecutedTextEdits); - fMap.put(cu, result); - } - return result; - } - - /** - * Removes the TextChange managed under the given key - * unit. - * - * @param unit the key determining the TextChange to be removed. - * @return the removed TextChange. - */ - public TextChange remove(ITranslationUnit unit) { - return (TextChange)fMap.remove(unit); - } - - /** - * Returns all text changes managed by this instance. - * - * @return all text changes managed by this instance - */ - public TextChange[] getAllChanges(){ - return (TextChange[])fMap.values().toArray(new TextChange[fMap.values().size()]); - } - - /** - * Returns all Translation units managed by this instance. - * - * @return all Translation units managed by this instance - */ - public ITranslationUnit[] getAllTranslationUnits(){ - return (ITranslationUnit[]) fMap.keySet().toArray(new ITranslationUnit[fMap.keySet().size()]); - } - - /** - * Clears all associations between resources and text changes. - */ - public void clear() { - fMap.clear(); - } - - /** - * Returns if any text changes are managed for the specified Translation unit. - * - * @return true if any text changes are managed for the specified Translation unit and false otherwise. - */ - public boolean containsChangesIn(ITranslationUnit cu){ - return fMap.containsKey(cu); - } -} - diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/UndoManager.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/UndoManager.java deleted file mode 100644 index 9deb3116ca0..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/UndoManager.java +++ /dev/null @@ -1,373 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.cdt.internal.corext.refactoring; - -import java.util.Stack; - -import org.eclipse.cdt.core.model.CModelException; -import org.eclipse.cdt.core.model.CoreModel; -import org.eclipse.cdt.core.model.ElementChangedEvent; -import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.cdt.core.model.ICElementDelta; -import org.eclipse.cdt.core.model.IElementChangedListener; -import org.eclipse.cdt.core.model.ITranslationUnit; -import org.eclipse.cdt.internal.corext.Assert; -import org.eclipse.cdt.internal.corext.refactoring.base.ChangeContext; -import org.eclipse.cdt.internal.corext.refactoring.base.IChange; -import org.eclipse.cdt.internal.corext.refactoring.base.IUndoManager; -import org.eclipse.cdt.internal.corext.refactoring.base.IUndoManagerListener; -import org.eclipse.cdt.internal.corext.refactoring.base.RefactoringStatus; -import org.eclipse.cdt.ui.CUIPlugin; -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.resources.IResourceChangeEvent; -import org.eclipse.core.resources.IResourceChangeListener; -import org.eclipse.core.resources.IResourceDelta; -import org.eclipse.core.resources.IResourceDeltaVisitor; -import org.eclipse.core.resources.IWorkspaceRunnable; -import org.eclipse.core.resources.ResourcesPlugin; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.SubProgressMonitor; - -/** - * Default implementation of IUndoManager. - */ -public class UndoManager implements IUndoManager { - - private class FlushListener implements IElementChangedListener { - public void elementChanged(ElementChangedEvent event) - { - // If we don't have anything to undo or redo don't examine the tree. - if (fUndoChanges.isEmpty() && fRedoChanges.isEmpty()) - return; - - processDelta(event.getDelta()); - } - - private boolean processDelta(ICElementDelta delta) - { - int kind= delta.getKind(); - int details= delta.getFlags(); - int type= delta.getElement().getElementType(); - ICElementDelta[] affectedChildren= delta.getAffectedChildren(); - if (affectedChildren == null) - return true; - - switch (type) { - // Consider containers for class files. - case ICElement.C_MODEL: - case ICElement.C_PROJECT: - case ICElement.C_CCONTAINER: - // If we did something different than changing a child we flush the the undo / redo stack. - if (kind != ICElementDelta.CHANGED - && ((details & ICElementDelta.F_CHILDREN) == 0)) { - flush(); - return false; - } - break; - case ICElement.C_UNIT: - // if we have changed a primary working copy (e.g created, removed, ...) - // then we do nothing. - ITranslationUnit unit= (ITranslationUnit)delta.getElement(); - // If we change a working copy we do nothing - if (unit.isWorkingCopy()) { - // Don't examine children of a working copy but keep processing siblings. - return true; - } else { - flush(); - return false; - } - } - for (int i= 0; i < affectedChildren.length; i++) { - if (!processDelta(affectedChildren[i])) - return false; - } - return true; - } - } - - private class SaveListener implements IResourceChangeListener { - public void resourceChanged(IResourceChangeEvent event) { - IResourceDeltaVisitor visitor= new IResourceDeltaVisitor() { - public boolean visit(IResourceDelta delta) throws CoreException { - IResource resource= delta.getResource(); - if (resource.getType() == IResource.FILE && delta.getKind() == IResourceDelta.CHANGED && - (delta.getFlags() & IResourceDelta.CONTENT) != 0) { - if(CoreModel.isValidTranslationUnitName(resource.getProject(), resource.getName())) { - ITranslationUnit unit= (ITranslationUnit)CoreModel.getDefault().create((IFile)resource); - if (unit != null && unit.exists()) { - flush(); - return false; - } - } - } - return true; - } - }; - try { - IResourceDelta delta= event.getDelta(); - if (delta != null) - delta.accept(visitor); - } catch (CoreException e) { - CUIPlugin.getDefault().log(e.getStatus()); - } - } - } - - private Stack fUndoChanges; - private Stack fRedoChanges; - private Stack fUndoNames; - private Stack fRedoNames; - private ListenerList fListeners; - private FlushListener fFlushListener; - private SaveListener fSaveListener; - - /** - * Creates a new undo manager with an empty undo and redo stack. - */ - public UndoManager() { - flush(); - } - - /* (Non-Javadoc) - * Method declared in IUndoManager. - */ - public void addListener(IUndoManagerListener listener) { - if (fListeners == null) - fListeners= new ListenerList(); - fListeners.add(listener); - } - - /* (Non-Javadoc) - * Method declared in IUndoManager. - */ - public void removeListener(IUndoManagerListener listener) { - if (fListeners == null) - return; - fListeners.remove(listener); - } - - /* (Non-Javadoc) - * Method declared in IUndoManager. - */ - public void aboutToPerformRefactoring() { - // Remove the resource change listener since we are changing code. - if (fFlushListener != null) - CoreModel.getDefault().removeElementChangedListener(fFlushListener); - if (fSaveListener != null) - ResourcesPlugin.getWorkspace().removeResourceChangeListener(fSaveListener); - } - - /* (Non-Javadoc) - * Method declared in IUndoManager. - */ - public void refactoringPerformed(boolean success) { - if (success) { - if (fFlushListener != null) - CoreModel.getDefault().addElementChangedListener(fFlushListener); - if (fSaveListener != null) - ResourcesPlugin.getWorkspace().addResourceChangeListener(fSaveListener); - } else { - flush(); - } - } - - /* (non-Javadoc) - * @see IUndoManager#shutdown() - */ - public void shutdown() { - if (fFlushListener != null) - CoreModel.getDefault().removeElementChangedListener(fFlushListener); - if (fSaveListener != null) - ResourcesPlugin.getWorkspace().removeResourceChangeListener(fSaveListener); - } - - /* (Non-Javadoc) - * Method declared in IUndoManager. - */ - public void flush() { - flushUndo(); - flushRedo(); - if (fFlushListener != null) - CoreModel.getDefault().removeElementChangedListener(fFlushListener); - if (fSaveListener != null) - ResourcesPlugin.getWorkspace().removeResourceChangeListener(fSaveListener); - - fFlushListener= null; - fSaveListener= null; - } - - private void flushUndo(){ - fUndoChanges= new Stack(); - fUndoNames= new Stack(); - fireUndoStackChanged(); - } - - private void flushRedo(){ - fRedoChanges= new Stack(); - fRedoNames= new Stack(); - fireRedoStackChanged(); - } - - /* (Non-Javadoc) - * Method declared in IUndoManager. - */ - public void addUndo(String refactoringName, IChange change){ - Assert.isNotNull(refactoringName, "refactoring"); //$NON-NLS-1$ - Assert.isNotNull(change, "change"); //$NON-NLS-1$ - fUndoNames.push(refactoringName); - fUndoChanges.push(change); - flushRedo(); - if (fFlushListener == null) { - fFlushListener= new FlushListener(); - CoreModel.getDefault().addElementChangedListener(fFlushListener); - } - if (fSaveListener == null) { - fSaveListener= new SaveListener(); - ResourcesPlugin.getWorkspace().addResourceChangeListener(fSaveListener); - } - fireUndoStackChanged(); - } - - /* (Non-Javadoc) - * Method declared in IUndoManager. - */ - public RefactoringStatus performUndo(ChangeContext context, IProgressMonitor pm) throws CModelException{ - // PR: 1GEWDUH: ITPJCORE:WINNT - Refactoring - Unable to undo refactor change - RefactoringStatus result= new RefactoringStatus(); - - if (fUndoChanges.empty()) - return result; - - IChange change= (IChange)fUndoChanges.peek(); - - executeChange(result, context, change, pm); - - if (!result.hasError()) { - fUndoChanges.pop(); - fRedoNames.push(fUndoNames.pop()); - fRedoChanges.push(change.getUndoChange()); - fireUndoStackChanged(); - fireRedoStackChanged(); - } - return result; - } - - /* (Non-Javadoc) - * Method declared in IUndoManager. - */ - public RefactoringStatus performRedo(ChangeContext context, IProgressMonitor pm) throws CModelException{ - // PR: 1GEWDUH: ITPJCORE:WINNT - Refactoring - Unable to undo refactor change - RefactoringStatus result= new RefactoringStatus(); - - if (fRedoChanges.empty()) - return result; - - IChange change= (IChange)fRedoChanges.peek(); - - - executeChange(result, context, change, pm); - - if (!result.hasError()) { - fRedoChanges.pop(); - fUndoNames.push(fRedoNames.pop()); - fUndoChanges.push(change.getUndoChange()); - fireRedoStackChanged(); - fireUndoStackChanged(); - } - - return result; - } - - private void executeChange(RefactoringStatus status, final ChangeContext context, final IChange change, IProgressMonitor pm) throws CModelException { - if (fFlushListener != null) - CoreModel.getDefault().removeElementChangedListener(fFlushListener); - if (fSaveListener != null) - ResourcesPlugin.getWorkspace().removeResourceChangeListener(fSaveListener); - try { - pm.beginTask("", 10); //$NON-NLS-1$ - status.merge(change.aboutToPerform(context, new SubProgressMonitor(pm, 2))); - if (status.hasError()) - return; - - CoreModel.run( - new IWorkspaceRunnable() { - public void run(IProgressMonitor innerPM) throws CoreException { - change.perform(context, innerPM); - } - }, - new SubProgressMonitor(pm, 8)); - } catch (CModelException e){ - throw e; - } catch (CoreException e) { - throw new CModelException(e); - } finally { - change.performed(); - if (fFlushListener != null) - CoreModel.getDefault().addElementChangedListener(fFlushListener); - if (fSaveListener != null) - ResourcesPlugin.getWorkspace().addResourceChangeListener(fSaveListener); - pm.done(); - } - } - - /* (Non-Javadoc) - * Method declared in IUndoManager. - */ - public boolean anythingToRedo(){ - return !fRedoChanges.empty(); - } - - /* (Non-Javadoc) - * Method declared in IUndoManager. - */ - public boolean anythingToUndo(){ - return !fUndoChanges.empty(); - } - - /* (Non-Javadoc) - * Method declared in IUndoManager. - */ - public String peekUndoName() { - if (fUndoNames.size() > 0) - return (String)fUndoNames.peek(); - return null; - } - - /* (Non-Javadoc) - * Method declared in IUndoManager. - */ - public String peekRedoName() { - if (fRedoNames.size() > 0) - return (String)fRedoNames.peek(); - return null; - } - - private void fireUndoStackChanged() { - if (fListeners == null) - return; - Object[] listeners= fListeners.getListeners(); - for (int i= 0; i < listeners.length; i++) { - ((IUndoManagerListener)listeners[i]).undoStackChanged(this); - } - } - - private void fireRedoStackChanged() { - if (fListeners == null) - return; - Object[] listeners= fListeners.getListeners(); - for (int i= 0; i < listeners.length; i++) { - ((IUndoManagerListener)listeners[i]).redoStackChanged(this); - } - } -} diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/base/Change.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/base/Change.java deleted file mode 100644 index ba4f8f4b333..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/base/Change.java +++ /dev/null @@ -1,136 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.corext.refactoring.base; - -import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.cdt.core.model.ITranslationUnit; -import org.eclipse.cdt.internal.corext.refactoring.RefactoringCoreMessages; -import org.eclipse.cdt.internal.corext.util.CModelUtil; -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.runtime.IAdaptable; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.OperationCanceledException; - -/** - * An abstract default implementation for a change object - suitable for subclassing. This class manages - * the change's active status. - *

      - * NOTE: This class/interface is part of an interim API that is still under development - * and expected to change significantly before reaching stability. It is being made available at - * this early stage to solicit feedback from pioneering adopters on the understanding that any - * code that uses this API will almost certainly be broken (repeatedly) as the API evolves.

      - */ -public abstract class Change implements IChange { - - private boolean fIsActive= true; - - /* (Non-Javadoc) - * Method declared in IChange. - */ - public RefactoringStatus aboutToPerform(ChangeContext context, IProgressMonitor pm) { - pm.beginTask("", 1); //$NON-NLS-1$ - // PR: 1GEWDUH: ITPJCORE:WINNT - Refactoring - Unable to undo refactor change - RefactoringStatus result= new RefactoringStatus(); - IResource resource= getResource(getModifiedLanguageElement()); - if (resource != null) { - pm.subTask(RefactoringCoreMessages.getFormattedString("Change.checking_for", resource.getName())); //$NON-NLS-1$ - checkIfModifiable(resource, result, context); - } - pm.worked(1); - return result; - } - - /* (Non-Javadoc) - * Method declared in IChange. - */ - public void performed() { - // do nothing. - } - - /* (Non-Javadoc) - * Method declared in IChange. - */ - public void setActive(boolean active) { - fIsActive= active; - } - - /* (Non-Javadoc) - * Method declared in IChange. - */ - public boolean isActive() { - return fIsActive; - } - - /* (Non-Javadoc) - * Method declared in IChange. - */ - public boolean isUndoable() { - return true; - } - - /* (Non-Javadoc) - * debugging only - */ - public String toString(){ - return getName(); - } - - /** - * Handles the given exception using the IChangeExceptionHandler provided by - * the given change context. If the execution of the change is to be aborted than - * this method throws a corresponding CModelException. The exception - * is either the given exception if it is an instance of CModelException or - * a new one created by calling new CModelException(exception, code). - * - * @param context the change context used to retrieve the exception handler - * @param exception the exception caugth during change execution - * @exception ChangeAbortException if the execution is to be aborted - */ - protected void handleException(ChangeContext context, Exception exception) throws ChangeAbortException { - if (exception instanceof ChangeAbortException) - throw (ChangeAbortException)exception; - if (exception instanceof OperationCanceledException) - throw (OperationCanceledException)exception; - context.getExceptionHandler().handle(context, this, exception); - } - - protected static void checkIfModifiable(Object element, RefactoringStatus status, ChangeContext context) { - IResource resource= getResource(element); - if (resource != null) - checkIfModifiable(resource, status, context); - } - - protected static void checkIfModifiable(IResource resource, RefactoringStatus status, ChangeContext context) { - if (resource.isReadOnly()) { - status.addFatalError(RefactoringCoreMessages.getFormattedString("Change.is_read_only", resource.getFullPath().toString())); //$NON-NLS-1$ - } - if (resource instanceof IFile) - context.checkUnsavedFile(status, (IFile)resource); - } - - - private static IResource getResource(Object element) { - if (element instanceof IResource) { - return (IResource)element; - } - if (element instanceof ITranslationUnit) { - return CModelUtil.toOriginal((ITranslationUnit)element).getResource(); - } - if (element instanceof ICElement) { - return ((ICElement)element).getUnderlyingResource(); - } - if (element instanceof IAdaptable) { - return (IResource) ((IAdaptable)element).getAdapter(IResource.class); - } - return null; - } -} diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/base/ChangeAbortException.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/base/ChangeAbortException.java deleted file mode 100644 index 7bde4421364..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/base/ChangeAbortException.java +++ /dev/null @@ -1,82 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.corext.refactoring.base; - - -import java.io.PrintStream; -import java.io.PrintWriter; - -import org.eclipse.cdt.internal.corext.Assert; -import org.eclipse.cdt.internal.corext.refactoring.RefactoringCoreMessages; - - -/** - * This exception is thrown if an unexpected errors occurs during execution - * of a change object. - */ -public class ChangeAbortException extends RuntimeException { - - private Throwable fThrowable; - - - /** - * Creates a new ChangeAbortException for the given throwable. - * - * @param t the unexpected throwable caught while performing the change - * @param context the change context used to process the change - */ - public ChangeAbortException(Throwable t) { - fThrowable= t; - Assert.isNotNull(fThrowable); - } - - /** - * Returns the Throwable that has caused the change to fail. - * - * @return the throwable that has caused the change to fail - */ - public Throwable getThrowable() { - return fThrowable; - } - - /** - * Prints a stack trace out for the exception, and - * any nested exception that it may have embedded in - * its Status object. - */ - public void printStackTrace(PrintStream output) { - synchronized (output) { - output.print("ChangeAbortException: "); //$NON-NLS-1$ - super.printStackTrace(output); - - if (fThrowable != null) { - output.print(RefactoringCoreMessages.getFormattedString("ChangeAbortException.wrapped", "ChangeAbortException: ")); //$NON-NLS-2$ //$NON-NLS-1$ - fThrowable.printStackTrace(output); - } - } - } - /** - * Prints a stack trace out for the exception, and - * any nested exception that it may have embedded in - * its Status object. - */ - public void printStackTrace(PrintWriter output) { - synchronized (output) { - output.print("ChangeAbortException: "); //$NON-NLS-1$ - super.printStackTrace(output); - - if (fThrowable != null) { - output.print(RefactoringCoreMessages.getFormattedString("ChangeAbortException.wrapped", "ChangeAbortException: ")); //$NON-NLS-2$ //$NON-NLS-1$ - fThrowable.printStackTrace(output); - } - } - } -} diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/base/ChangeContext.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/base/ChangeContext.java deleted file mode 100644 index 85f7cec3f67..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/base/ChangeContext.java +++ /dev/null @@ -1,168 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.corext.refactoring.base; - - -import java.util.ArrayList; -import java.util.List; - -import org.eclipse.core.resources.IFile; - -import org.eclipse.cdt.internal.corext.Assert; -import org.eclipse.cdt.internal.corext.refactoring.RefactoringCoreMessages; - -/** - * A change context is used to give an IChange object access to several workspace - * resource independend from whether the change is executed head less or not. - *

      - * NOTE: This class/interface is part of an interim API that is still under development - * and expected to change significantly before reaching stability. It is being made available at - * this early stage to solicit feedback from pioneering adopters on the understanding that any - * code that uses this API will almost certainly be broken (repeatedly) as the API evolves.

      - */ -public class ChangeContext { - - private IFile[] fUnsavedFiles; - private List fHandledUnsavedFiles; - private IChangeExceptionHandler fExceptionHandler; - private IChange fFailedChange; - private boolean fTryToUndo; - private List fPerformedChanges= new ArrayList(); - - - /** - * Creates a new change context with the given exception handler. - * - * @param handler object to handle exceptions caught during performing - * a change. Must not be null - */ - public ChangeContext(IChangeExceptionHandler handler) { - // PR: 1GEWDUH: ITPJCORE:WINNT - Refactoring - Unable to undo refactor change - this(handler, new IFile[] {}); - } - - /** - * Creates a new change context with the given exception handler. - * - * @param handler object to handle exceptions caught during performing - * a change. Must not be null - */ - public ChangeContext(IChangeExceptionHandler handler, IFile[] unsavedFiles) { - // PR: 1GEWDUH: ITPJCORE:WINNT - Refactoring - Unable to undo refactor change - fExceptionHandler= handler; - Assert.isNotNull(fExceptionHandler); - fUnsavedFiles= unsavedFiles; - Assert.isNotNull(fUnsavedFiles); - fHandledUnsavedFiles= new ArrayList(fUnsavedFiles.length); - } - - /** - * Returns the list of unsaved resources. - * - * @return the list of unsaved resources - */ - public IFile[] getUnsavedFiles() { - // PR: 1GEWDUH: ITPJCORE:WINNT - Refactoring - Unable to undo refactor change - return fUnsavedFiles; - } - - public void checkUnsavedFile(RefactoringStatus status, IFile file) { - if (fHandledUnsavedFiles.contains(file)) - return; - - // PR: 1GEWDUH: ITPJCORE:WINNT - Refactoring - Unable to undo refactor change - for (int i= 0; i < fUnsavedFiles.length; i++) { - if (fUnsavedFiles[i].equals(file)) { - status.addFatalError(RefactoringCoreMessages.getFormattedString("Change.is_unsaved", file.getFullPath().toString())); //$NON-NLS-1$ - fHandledUnsavedFiles.add(file); - return; - } - } - } - - /** - * Returns the exception handler used to report exception back to the client. - * - * @return the exception handler to report exceptions - */ - public IChangeExceptionHandler getExceptionHandler() { - return fExceptionHandler; - } - - /** - * Sets the change that caused an exception to the given value. - * - * @param change the change that caused an exception - */ - public void setFailedChange(IChange change) { - fFailedChange= change; - } - - /** - * Returns the change that caused an exception. - * - * @return the change that caused an exception - */ - public IChange getFailedChange() { - return fFailedChange; - } - - /** - * An unexpected error has occurred during execution of a change. Communicate - * to the outer operation that the successfully performed changes collected by - * this change context are supposed to be undone. - * - * @see ChangeContext#addPerformedChange(IChange) - */ - public void setTryToUndo() { - fTryToUndo= true; - } - - /** - * Returns true if an exception has been caught during execution of - * the change and the outer operation should try to undo all successfully performed - * changes. Otherwise false is returned. - * - * @return if the outer operation should try to undo all successfully performed - * changes - */ - public boolean getTryToUndo() { - return fTryToUndo; - } - - /** - * Adds the given change to the list of successfully performed changes. - * - * @param the change executed successfully. - */ - public void addPerformedChange(IChange change) { -// if (change instanceof ICompositeChange) -// return; - - fPerformedChanges.add(change); - } - - /** - * Returns all changes that have been performed successfully - * - * @return the successfully performed changes. - */ - public IChange[] getPerformedChanges() { - return (IChange[])fPerformedChanges.toArray(new IChange[fPerformedChanges.size()]); - } - - /** - * Removes all performed changes from this context. - */ - public void clearPerformedChanges() { - fPerformedChanges= new ArrayList(1); - } -} diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/base/Context.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/base/Context.java deleted file mode 100644 index e162644dbb3..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/base/Context.java +++ /dev/null @@ -1,24 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.corext.refactoring.base; - - -import org.eclipse.core.runtime.IAdaptable; - -/** - * A Context can be used to annotate a RefactoringStatusEntrywith - * additional information presentable in the UI. - */ -public class Context { - public IAdaptable getCorrespondingElement() { - return null; - } -} diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/base/IChange.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/base/IChange.java deleted file mode 100644 index 999b8f7e26a..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/base/IChange.java +++ /dev/null @@ -1,124 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.corext.refactoring.base; - - -import org.eclipse.core.runtime.IProgressMonitor; - -import org.eclipse.cdt.core.model.CModelException; - - -/** - * Represents a generic change to the workbench. An IChange object is typically - * created by calling IRefactoring::createChange. - *

      - * Calling perform performs the actual change to the workbench. Clients then call - * getUndoChange. It is the implementors responsbility to make sure that the - * IChange object returned by getUndoChange really represents a reverse change. - * - * Clients can implement this interface. - *

      - * NOTE: This class/interface is part of an interim API that is still under development - * and expected to change significantly before reaching stability. It is being made available at - * this early stage to solicit feedback from pioneering adopters on the understanding that any - * code that uses this API will almost certainly be broken (repeatedly) as the API evolves.

      - */ -public interface IChange { - - public static final int REFACTORING_CHANGE_ABORTED= 900; - - /** - * The client is about to calling perform on this change. The client of this - * change must ensure that the method is called outside a runnable that modifies the - * workbench. Typically aboutToPerform, perform and - * performed are used as follows: - *
      -	 *	try {
      -	 *		change.aboutToPerform(context);
      -	 *		workbench.run(new IWorkspaceRunnable() {
      -	 *			public void run(IProgressMonitor pm) throws CoreException {
      -	 *				change.perform(context, pm);
      -	 *			}
      -	 *		}, progressMonitor);
      -	 *	} finally {
      -	 *		change.performed();
      -	 *	}
      -	 * 
      - * @see #performed() - */ - public RefactoringStatus aboutToPerform(ChangeContext context, IProgressMonitor pm); - - /** - * Performs this change. It is critical that you call perform - * before you call getUndoChange. In general, IChange - * objects do not know what the reverse will be before they are performed. - */ - public void perform(ChangeContext context, IProgressMonitor pm) throws CModelException, ChangeAbortException; - - /** - * The change has been performed. Clients must ensure that this method is called after all - * resource deltas emitted by calling perform are processed. This method must - * be called even if the perform has thrown a runtime exception. - * @see #aboutToPerform(ChangeContext, IProgressMonitor) - */ - public void performed(); - - /** - * Returns the change that, when performed, will undo the receiver. IChange - * objects can assume that perform has been called on them before. It is the - * caller's responsiblity to make sure that this is true. As mentioned in the class comment, - * it is the responsiblity of the implementors to make sure that this method does create a - * reverse change. - * - * @return the reverse change of this change - */ - public IChange getUndoChange(); - - /** - * Sets the activation status for this IChange. When a change is not active, - * then executing it is expected to do nothing. - * - * @param active the activation status for this change. - */ - public void setActive(boolean active); - - /** - * Returns the activation status of this IChange. This method doesn't - * consider the activation status of possible children. - * - * @return the change's activation status. - * @see #setActive(boolean) - */ - public boolean isActive(); - - /** - * Returns the name of this change. The main purpose of the change's name is to - * render it in the UI. - * - * @return the change's name. - */ - public String getName(); - - /** - * Returns the language element modified by this IChange. The method - * may return null if the change isn't related to a language element. - * - * @return the language element modified by this change - */ - public Object getModifiedLanguageElement(); - - /** - * Returns whether the change can be undone. - * If false is returned, then the result - * of getUndoChange will be ignored. - */ - public boolean isUndoable(); -} diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/base/IChangeExceptionHandler.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/base/IChangeExceptionHandler.java deleted file mode 100644 index e58bf7a9146..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/base/IChangeExceptionHandler.java +++ /dev/null @@ -1,37 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.corext.refactoring.base; - - - -/** - * An ChangeExceptionHandler is informed about any exception that occurrs during - * performing a change. Implementors of this interface can control if the change is supposed to - * be continued or if it is to be aborted. - *

      - * NOTE: This class/interface is part of an interim API that is still under development - * and expected to change significantly before reaching stability. It is being made available at - * this early stage to solicit feedback from pioneering adopters on the understanding that any - * code that uses this API will almost certainly be broken (repeatedly) as the API evolves.

      - */ -public interface IChangeExceptionHandler { - - - /** - * Handles the given exception. - * - * @param context the change context passed to IChange.perform - * @param change the change that caused the exception - * @param exception the exception cought during executing the change - * @exception ChangeAbortException if the change is to be aborted - */ - public void handle(ChangeContext context, IChange change, Exception exception) throws ChangeAbortException; -} diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/base/ICompositeChange.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/base/ICompositeChange.java deleted file mode 100644 index aa41d58c15b..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/base/ICompositeChange.java +++ /dev/null @@ -1,34 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.corext.refactoring.base; - - - -/** - * A composite change consisting of a list of changes. Performing a composite - * change peforms all managed changes. Managed changes can be either primitive - * or composite changes. - * Clients can implement this interface if they want their IChange to be treated as composites. - *

      - * NOTE: This class/interface is part of an interim API that is still under development - * and expected to change significantly before reaching stability. It is being made available at - * this early stage to solicit feedback from pioneering adopters on the understanding that any - * code that uses this API will almost certainly be broken (repeatedly) as the API evolves.

      - */ -public interface ICompositeChange extends IChange { - - /** - * Returns the set of changes this composite change consists of. If the composite - * change doesn't have any children, null is returned. - * @return an array of changes this composite change consists of - */ - public IChange[] getChildren(); -} diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/base/IRefactoring.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/base/IRefactoring.java deleted file mode 100644 index 0df0f85add8..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/base/IRefactoring.java +++ /dev/null @@ -1,55 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.corext.refactoring.base; - -import org.eclipse.cdt.core.model.CModelException; -import org.eclipse.core.runtime.IProgressMonitor; - - -/** - * Represents a refactoring. - *

      - * NOTE: This class/interface is part of an interim API that is still under development - * and expected to change significantly before reaching stability. It is being made available at - * this early stage to solicit feedback from pioneering adopters on the understanding that any - * code that uses this API will almost certainly be broken (repeatedly) as the API evolves.

      - */ -public interface IRefactoring { - - /** - * Checks the proconditions of the receiving refactoring object. - * If the resulting IStatus has severity IStatus.ERROR, - * than createChange will not be called on the receiver. - * Must not return null. - * Implementors can assume the progress monitor to be not initialized. - * @see RefactoringStatus - * @see RefactoringStatus#OK - * @see RefactoringStatus#ERROR - */ - public RefactoringStatus checkPreconditions(IProgressMonitor pm) throws CModelException; - - /** - * Creates an IChange object that performs the actual refactoring. - * This is guaranteed not to be called before checkPreconditions or - * if checkPreconditions returns an RefactoringStatus - * object with severity RefactoringStatus.ERROR. - * Implementors can assume the progress monitor to be not initialized. - */ - public IChange createChange(IProgressMonitor pm) throws CModelException; - - - /** - * Returns the name of this refactoring. - * - * @return the refactoring's name. Mainly used in the UI. - */ - public String getName(); -} diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/base/IUndoManager.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/base/IUndoManager.java deleted file mode 100644 index be741ae0609..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/base/IUndoManager.java +++ /dev/null @@ -1,128 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.corext.refactoring.base; - -import org.eclipse.core.runtime.IProgressMonitor; - -import org.eclipse.cdt.core.model.CModelException; - -/** - * An undo manager keeps track of changes performed by refactorings. Use performUndo - * and performRedo to undo and redo changes. - *

      - * NOTE: This interface is not intended to be implemented or extended. Use Refactoring.getUndoManager() - * to access the undo manager.

      - *

      - * NOTE: This class/interface is part of an interim API that is still under development - * and expected to change significantly before reaching stability. It is being made available at - * this early stage to solicit feedback from pioneering adopters on the understanding that any - * code that uses this API will almost certainly be broken (repeatedly) as the API evolves.

      - */ -public interface IUndoManager { - - /** - * Adds a listener to the undo manager. - * - * @param listener the listener to be added to the undo manager - */ - public void addListener(IUndoManagerListener listener); - - /** - * Removes the given listener from this undo manager. - * - * @param listener the listener to be removed - */ - public void removeListener(IUndoManagerListener listener); - - /** - * The refactoring infrastructure is going to perform a refactoring. - */ - public void aboutToPerformRefactoring(); - - /** - * The execution of a refactoring is completed. - * - * @param success true if the refactoring has been executed successful. - * Otherwise false. - */ - public void refactoringPerformed(boolean success); - - /** - * Adds a new undo change to this undo manager. - * - * @param name the name of the refactoring the change was created - * for. The name must not be null - * @param change the undo change. The change must not be null - */ - public void addUndo(String name, IChange change); - - /** - * Returns true if there is anything to undo, otherwise - * false. - * - * @return true if there is anything to undo, otherwise - * false - */ - public boolean anythingToUndo(); - - /** - * Returns the name of the top most undo. - * - * @return the top most undo name. The main purpose of the name is to - * render it in the UI. Returns null if there aren't any changes to undo - */ - public String peekUndoName(); - - /** - * Undo the top most undo change. - * - * @param pm a progress monitor to report progress during performing - * the undo change. The progress monitor must not be null - * @return a status indicating if the undo preflight produced any error - */ - public RefactoringStatus performUndo(ChangeContext context, IProgressMonitor pm) throws CModelException; - - /** - * Returns true if there is anything to redo, otherwise - * false. - * - * @return true if there is anything to redo, otherwise - * false - */ - public boolean anythingToRedo(); - - /** - * Returns the name of the top most redo. - * - * @return the top most redo name. The main purpose of the name is to - * render it in the UI. Returns null if there are no any changes to redo. - */ - public String peekRedoName(); - - /** - * Redo the top most redo change. - * - * @param pm a progress monitor to report progress during performing - * the redo change. The progress monitor must not be null - * @return a status indicating if the undo preflight produced any error - */ - public RefactoringStatus performRedo(ChangeContext context, IProgressMonitor pm) throws CModelException; - - /** - * Flushes the undo manager's undo and redo stacks. - */ - public void flush(); - - /** - * Shut down the undo manager. - */ - public void shutdown(); -} diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/base/IUndoManagerListener.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/base/IUndoManagerListener.java deleted file mode 100644 index fcb168ad36a..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/base/IUndoManagerListener.java +++ /dev/null @@ -1,30 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.corext.refactoring.base; - - -/** - * Listener to monitor changes made to an UndoManager - */ -public interface IUndoManagerListener { - - /** - * This method is called by the undo manager if an undo change has been - * added to it. - */ - public void undoStackChanged(IUndoManager manager); - - /** - * This method is called by the undo manager if a redo change has been - * added to it. - */ - public void redoStackChanged(IUndoManager manager); -} diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/base/Refactoring.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/base/Refactoring.java deleted file mode 100644 index 97209d7c94f..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/base/Refactoring.java +++ /dev/null @@ -1,93 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.corext.refactoring.base; - - -import org.eclipse.cdt.core.model.CModelException; -import org.eclipse.core.runtime.IAdaptable; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.SubProgressMonitor; - -import org.eclipse.cdt.internal.corext.refactoring.UndoManager; - -/** - * Superclass for all refactorings. - *

      - * NOTE: This class/interface is part of an interim API that is still under development - * and expected to change significantly before reaching stability. It is being made available at - * this early stage to solicit feedback from pioneering adopters on the understanding that any - * code that uses this API will almost certainly be broken (repeatedly) as the API evolves.

      - */ -public abstract class Refactoring implements IRefactoring, IAdaptable { - - private static IUndoManager fgUndoManager= new UndoManager(); - - public static IUndoManager getUndoManager() { - return fgUndoManager; - } - - - /* non java-doc - * for debugging only - */ - public String toString(){ - return getName(); - } - - //---- Conditions --------------------------- - - /** - * Checks if this refactoring can be activated. - * Typically, this is used in the ui to check if a corresponding menu entry should be shown. - * Must not return null. - */ - public abstract RefactoringStatus checkActivation(IProgressMonitor pm) throws CModelException; - - /** - * After checkActivation has been performed and the user has provided all input - * necessary to perform the refactoring this method is called to check the remaining preconditions. - * Typically, this is used in the ui after the user has pressed 'next' on the last user input page. - * This method is always called after checkActivation and only if the status returned by - * checkActivation isOK. - * Must not return null. - * @see #checkActivation - * @see RefactoringStatus#isOK - */ - public abstract RefactoringStatus checkInput(IProgressMonitor pm) throws CModelException; - - /** - * @see IRefactoring#checkPreconditions - * This implementation performs checkActivation - * and checkInput and merges the results. - * - * @see #checkActivation - * @see #checkInput - * @see RefactoringStatus#merge - */ - public RefactoringStatus checkPreconditions(IProgressMonitor pm) throws CModelException{ - pm.beginTask("", 11); //$NON-NLS-1$ - RefactoringStatus result= new RefactoringStatus(); - result.merge(checkActivation(new SubProgressMonitor(pm, 1, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK))); - if (!result.hasFatalError()) - result.merge(checkInput(new SubProgressMonitor(pm, 10, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK))); - pm.done(); - return result; - } - - /* (non-Javadoc) - * @see org.eclipse.core.runtime.IAdaptable#getAdapter(java.lang.Class) - */ - public Object getAdapter(Class adapter) { - if (adapter.isInstance(this)) - return this; - return null; - } -} diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/base/RefactoringStatus.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/base/RefactoringStatus.java deleted file mode 100644 index fdb78f81e79..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/base/RefactoringStatus.java +++ /dev/null @@ -1,453 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.corext.refactoring.base; - - - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import org.eclipse.cdt.internal.corext.Assert; -import org.eclipse.core.runtime.IStatus; - - -/** - * A RefactoringStatus object represents the outcome of a precondition checking - * operation. - * It keeps a list of RefactoringStatusEntries. - * Clients can instantiate. - * This class is not intented to be subclassed. - *

      - * NOTE: This class/interface is part of an interim API that is still under development - * and expected to change significantly before reaching stability. It is being made available at - * this early stage to solicit feedback from pioneering adopters on the understanding that any - * code that uses this API will almost certainly be broken (repeatedly) as the API evolves.

      - */ -public class RefactoringStatus { - - public static final int OK= 0; - public static final int INFO= 1; - public static final int WARNING= 2; - public static final int ERROR= 3; - public static final int FATAL= 4; - - private List fEntries; - private int fSeverity= OK; - - public RefactoringStatus(){ - fEntries= new ArrayList(0); - } - - /** - * Creates a RefactorngStatus with one INFO entry. - * This is a convenience method. - */ - public static RefactoringStatus createInfoStatus(String msg){ - return createStatus(INFO, msg); - } - - /** - * Creates a RefactorngStatus with one INFO entry. - * This is a convenience method. - */ - public static RefactoringStatus createInfoStatus(String msg, Context context){ - return createStatus(INFO, msg, context); - } - - /** - * Creates a RefactorngStatus with one WARNING entry. - * This is a convenience method. - */ - public static RefactoringStatus createWarningStatus(String msg){ - return createStatus(WARNING, msg); - } - - /** - * Creates a RefactorngStatus with one WARNING entry. - * This is a convenience method. - */ - public static RefactoringStatus createWarningStatus(String msg, Context context){ - return createStatus(WARNING, msg, context); - } - - /** - * Creates a RefactorngStatus with one ERROR entry. - * This is a convenience method. - */ - public static RefactoringStatus createErrorStatus(String msg){ - return createStatus(ERROR, msg); - } - - /** - * Creates a RefactorngStatus with one ERROR entry. - * This is a convenience method. - */ - public static RefactoringStatus createErrorStatus(String msg, Context context){ - return createStatus(ERROR, msg, context); - } - - /** - * Creates a RefactorngStatus with one FATAL entry. - * This is a convenience method. - */ - public static RefactoringStatus createFatalErrorStatus(String msg){ - return createStatus(FATAL, msg); - } - - /** - * Creates a RefactorngStatus with one FATAL entry. - * This is a convenience method. - */ - public static RefactoringStatus createFatalErrorStatus(String msg, Context context){ - return createStatus(FATAL, msg, context); - } - - /** - * Creates a RefactorngStatus from the given IStatus - */ - public static RefactoringStatus create(IStatus status){ - if (status.isOK()) - return new RefactoringStatus(); - - if (! status.isMultiStatus()){ - switch (status.getSeverity()){ - case IStatus.INFO: - return RefactoringStatus.createWarningStatus(status.getMessage()); - case IStatus.WARNING: - return RefactoringStatus.createErrorStatus(status.getMessage()); - case IStatus.ERROR: - return RefactoringStatus.createFatalErrorStatus(status.getMessage()); - default: - return new RefactoringStatus(); - } - } else { - IStatus[] children= status.getChildren(); - RefactoringStatus result= new RefactoringStatus(); - for (int i= 0; i < children.length; i++) { - result.merge(RefactoringStatus.create(children[i])); - } - return result; - } - } - - /* - * @see RefactoringStatusCodes - */ - public static RefactoringStatus createStatus(int severity, String msg, Context context, Object data, int code) { - RefactoringStatus result= new RefactoringStatus(); - result.fEntries.add(new RefactoringStatusEntry(msg, severity, context, data, code)); - result.fSeverity= severity; - return result; - } - - public static RefactoringStatus createStatus(int severity, String msg, Context context) { - return createStatus(severity, msg, context, null, RefactoringStatusCodes.NONE); - } - - public static RefactoringStatus createStatus(int severity, String msg){ - return createStatus(severity, msg, null); - } - - /** - * Adds an info to this status. - * If the current severity was OK it will be changed to INFO. - * It will remain unchanged otherwise. - * @see #OK - * @see #INFO - */ - public void addInfo(String msg){ - addInfo(msg, null); - } - - /** - * Adds an info to this status. - * If the current severity was OK it will be changed to INFO. - * It will remain unchanged otherwise. - * @see #OK - * @see #INFO - */ - public void addInfo(String msg, Context context){ - fEntries.add(RefactoringStatusEntry.createInfo(msg, context)); - fSeverity= Math.max(fSeverity, INFO); - } - - /** - * Adds a warning to this status. - * If the current severity was OK or INFO it will be changed to WARNING. - * It will remain unchanged otherwise. - * @see #OK - * @see #INFO - * @see #WARNING - */ - public void addWarning(String msg){ - addWarning(msg, null); - } - - /** - * Adds a warning to this status. - * If the current severity was OK or INFO it will be changed to WARNING. - * It will remain unchanged otherwise. - * @see #OK - * @see #INFO - * @see #WARNING - */ - public void addWarning(String msg, Context context){ - fEntries.add(RefactoringStatusEntry.createWarning(msg, context)); - fSeverity= Math.max(fSeverity, WARNING); - } - - - /** - * Adds an error to this status. - * If the current severity was OK, INFO or WARNING - * it will be changed to ERROR. - * It will remain unchanged otherwise. - * @see #OK - * @see #INFO - * @see #WARNING - * @see #ERROR - */ - public void addError(String msg){ - addError(msg, null); - } - - /** - * Adds an error to this status. - * If the current severity was OK, INFO or WARNING - * it will be changed to ERROR. - * It will remain unchanged otherwise. - * @see #OK - * @see #INFO - * @see #WARNING - * @see #ERROR - */ - public void addError(String msg, Context context){ - fEntries.add(RefactoringStatusEntry.createError(msg, context)); - fSeverity= Math.max(fSeverity, ERROR); - } - - - /** - * Adds a fatal error to this status. - * If the current severity was OK, INFO, WARNING - * or ERROR it will be changed to FATAL. - * It will remain unchanged otherwise. - * @see #OK - * @see #INFO - * @see #WARNING - * @see #ERROR - * @see #FATAL - */ - public void addFatalError(String msg){ - addFatalError(msg, null); - } - - /** - * Adds a fatal error to this status. - * If the current severity was OK, INFO, WARNING - * or ERROR it will be changed to FATAL. - * It will remain unchanged otherwise. - * @see #OK - * @see #INFO - * @see #WARNING - * @see #ERROR - * @see #FATAL - */ - public void addFatalError(String msg, Context context){ - fEntries.add(RefactoringStatusEntry.createFatal(msg, context)); - fSeverity= Math.max(fSeverity, FATAL); - } - - /** - * Adds an RefactoringStatusEntry. - * - * @param entry the RefactoringStatusEntry to be added - */ - public void addEntry(RefactoringStatusEntry entry) { - Assert.isNotNull(entry); - fEntries.add(entry); - fSeverity= Math.max(fSeverity, entry.getSeverity()); - } - - /** - * Returns true iff there were no errors, warings or infos added. - * @see #OK - * @see #INFO - * @see #WARNING - * @see #ERROR - */ - public boolean isOK(){ - return fSeverity == OK; - } - - /** - * Returns true if the current severity is FATAL. - * @see #FATAL - */ - public boolean hasFatalError() { - return fSeverity == FATAL; - } - - /** - * Returns true if the current severity is FATAL or - * ERROR. - * @see #FATAL - * @see #ERROR - */ - public boolean hasError() { - return fSeverity == FATAL || fSeverity == ERROR; - } - - /** - * Returns true if the current severity is FATAL, - * ERROR or WARNING. - * @see #FATAL - * @see #ERROR - * @see #WARNING - */ - public boolean hasWarning() { - return fSeverity == FATAL || fSeverity == ERROR || fSeverity == WARNING; - } - - /** - * Returns true if the status has an entry with the given code. - * Otherwise false is returned. - * - * @param code the code of the RefactoringStatusEntry. - * @return true if the status has an entry with the given code. - * Otherwise false is returned. - */ - public boolean hasEntryWithCode(int code) { - for (Iterator iter= fEntries.iterator(); iter.hasNext();) { - RefactoringStatusEntry entry= (RefactoringStatusEntry) iter.next(); - if (entry.getCode() == code) - return true; - } - return false; - } - - /** - * Merges the receiver and the parameter statuses. - * The resulting list of entries in the receiver will contain entries from both. - * The resuling severity in the reciver will be the more severe of its current severity - * and the parameter's severity. - * Merging with null is allowed - it has no effect. - * @see #getSeverity - */ - public void merge(RefactoringStatus that){ - if (that == null) - return; - fEntries.addAll(that.getEntries()); - fSeverity= Math.max(fSeverity, that.getSeverity()); - } - - - /** - * Returns the current severity. - * Severities are ordered as follows: OK < INFO < WARNING < ERROR - */ - public int getSeverity(){ - return fSeverity; - } - - /** - * Returns all entries. - * Returns a List of RefactoringStatusEntries. - * This list is empty if there are no entries. - */ - public List getEntries(){ - return fEntries; - } - - /** - * Returns the RefactoringStatusEntry at the specified index. - * - * @param index of entry to return - * @return the enrty at the specified index - * - * @throws IndexOutOfBoundsException if the index is out of range - */ - public RefactoringStatusEntry getEntry(int index) { - return (RefactoringStatusEntry)fEntries.get(index); - } - - /** - * Returns the first entry which severity is equal or greater than the given - * severity. Returns null if no element exists with - * the given severity. - * @param severity must be one of FATAL, ERROR, - * WARNING or INFO. - */ - public RefactoringStatusEntry getFirstEntry(int severity) { - Assert.isTrue(severity >= OK && severity <= FATAL); - if (severity > fSeverity) - return null; - Iterator iter= fEntries.iterator(); - while(iter.hasNext()) { - RefactoringStatusEntry entry= (RefactoringStatusEntry)iter.next(); - if (entry.getSeverity() >= severity) - return entry; - } - return null; - } - - - /** - * Returns the first message which severity is equal or greater than the given - * severity. Returns null if no element exists with - * the given severity. - * @param severity must me one of FATAL, ERROR, - * WARNING or INFO. - */ - public String getFirstMessage(int severity) { - RefactoringStatusEntry entry= getFirstEntry(severity); - if (entry == null) - return null; - return entry.getMessage(); - } - - - /* non java-doc - * for debugging only - * not for nls - */ - /*package*/ static String getSeverityString(int severity){ - Assert.isTrue(severity >= OK && severity <= FATAL); - if (severity == RefactoringStatus.OK) return "OK"; //$NON-NLS-1$ - if (severity == RefactoringStatus.INFO) return "INFO"; //$NON-NLS-1$ - if (severity == RefactoringStatus.WARNING) return "WARNING"; //$NON-NLS-1$ - if (severity == RefactoringStatus.ERROR) return "ERROR"; //$NON-NLS-1$ - if (severity == RefactoringStatus.FATAL) return "FATALERROR"; //$NON-NLS-1$ - return null; - } - - /* non java-doc - * for debugging only - */ - public String toString(){ - StringBuffer buff= new StringBuffer(); - buff.append("<") //$NON-NLS-1$ - .append(getSeverityString(fSeverity)) - .append("\n"); //$NON-NLS-1$ - if (!isOK()){ - for (Iterator iter= fEntries.iterator(); iter.hasNext();){ - buff.append("\t") //$NON-NLS-1$ - .append(iter.next()) - .append("\n"); //$NON-NLS-1$ - } - } - buff.append(">"); //$NON-NLS-1$ - return buff.toString(); - } -} - - diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/base/RefactoringStatusCodes.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/base/RefactoringStatusCodes.java deleted file mode 100644 index 396c09b9455..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/base/RefactoringStatusCodes.java +++ /dev/null @@ -1,57 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.corext.refactoring.base; - - -public class RefactoringStatusCodes { - - private RefactoringStatusCodes() { - } - - public static final int NONE= 0; - - public static final int OVERRIDES_ANOTHER_METHOD= 1; - public static final int METHOD_DECLARED_IN_INTERFACE= 2; - - public static final int EXPRESSION_NOT_RVALUE= 64; - public static final int EXPRESSION_NOT_RVALUE_VOID= 65; - public static final int EXTRANEOUS_TEXT= 66; - - public static final int NOT_STATIC_FINAL_SELECTED= 128; - public static final int SYNTAX_ERRORS= 129; - public static final int DECLARED_IN_CLASSFILE= 130; - public static final int CANNOT_INLINE_BLANK_FINAL= 131; - public static final int LOCAL_AND_ANONYMOUS_NOT_SUPPORTED= 132; - public static final int REFERENCE_IN_CLASSFILE= 133; - public static final int WILL_NOT_REMOVE_DECLARATION= 134; - - public static int CANNOT_MOVE_STATIC= 192; - public static int SELECT_METHOD_IMPLEMENTATION= 193; - public static int CANNOT_MOVE_NATIVE= 194; - public static int CANNOT_MOVE_SYNCHRONIZED= 195; - public static int CANNOT_MOVE_CONSTRUCTOR= 196; - public static int SUPER_REFERENCES_NOT_ALLOWED= 197; - public static int ENCLOSING_INSTANCE_REFERENCES_NOT_ALLOWED= 198; - public static int CANNOT_MOVE_RECURSIVE= 199; - public static int CANNOT_MOVE_TO_SAME_CU= 200; - public static int CANNOT_MOVE_TO_LOCAL= 201; - public static int METHOD_NOT_SELECTED= 202; - public static int NO_NEW_RECEIVERS= 203; - public static int PARAM_NAME_ALREADY_USED= 204; - - // inline method error codes - public static final int INLINE_METHOD_FIELD_INITIALIZER= 256; - public static final int INLINE_METHOD_LOCAL_INITIALIZER= 257; - public static final int INLINE_METHOD_NULL_BINDING= 258; - public static final int INLINE_METHOD_ONLY_SIMPLE_FUNCTIONS= 259; - public static final int INLINE_METHOD_EXECUTION_FLOW= 260; - public static final int INLINE_METHOD_INITIALIZER_IN_FRAGEMENT= 261; -} diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/base/RefactoringStatusEntry.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/base/RefactoringStatusEntry.java deleted file mode 100644 index ae2d187d38a..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/base/RefactoringStatusEntry.java +++ /dev/null @@ -1,243 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.corext.refactoring.base; - -import org.eclipse.cdt.internal.corext.Assert; -import org.eclipse.cdt.ui.CUIPlugin; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.Status; - -/** - * An immutable tuple (message, severity) representing an entry in the list in - * RefactoringStatus. - *

      - * NOTE: This class/interface is part of an interim API that is still under development - * and expected to change significantly before reaching stability. It is being made available at - * this early stage to solicit feedback from pioneering adopters on the understanding that any - * code that uses this API will almost certainly be broken (repeatedly) as the API evolves.

      - */ -public class RefactoringStatusEntry{ - - private final String fMessage; - private final int fSeverity; - private final Context fContext; - private final Object fData; - private final int fCode; - - public RefactoringStatusEntry(String msg, int severity, Context context, Object data, int code){ - Assert.isTrue(severity == RefactoringStatus.INFO - || severity == RefactoringStatus.WARNING - || severity == RefactoringStatus.ERROR - || severity == RefactoringStatus.FATAL); - Assert.isNotNull(msg); - fMessage= msg; - fSeverity= severity; - fContext= context; - fData= data; - fCode= code; - } - - /** - * Creates an entry with the given severity. - * @param msg message - * @param severity severity - * @param context a context which can be used to show more detailed information - * about this error in the UI - */ - public RefactoringStatusEntry(String msg, int severity, Context context){ - this(msg, severity, context, null, RefactoringStatusCodes.NONE); - } - - /** - * Creates an entry with the given severity. The corresponding resource and source range are set to null. - * @param severity severity - * @param msg message - */ - public RefactoringStatusEntry(String msg, int severity) { - this(msg, severity, null); - } - - /** - * Creates an entry with RefactoringStatus.INFO status. - * @param msg message - */ - public static RefactoringStatusEntry createInfo(String msg) { - return new RefactoringStatusEntry(msg, RefactoringStatus.INFO); - } - - /** - * Creates an entry with RefactoringStatus.INFO status. - * @param msg message - */ - public static RefactoringStatusEntry createInfo(String msg, Context context) { - return new RefactoringStatusEntry(msg, RefactoringStatus.INFO, context); - } - - /** - * Creates an entry with RefactoringStatus.WARNING status. - * @param msg message - */ - public static RefactoringStatusEntry createWarning(String msg) { - return new RefactoringStatusEntry(msg, RefactoringStatus.WARNING); - } - - /** - * Creates an entry with RefactoringStatus.WARNING status. - * @param msg message - */ - public static RefactoringStatusEntry createWarning(String msg, Context context) { - return new RefactoringStatusEntry(msg, RefactoringStatus.WARNING, context); - } - - /** - * Creates an entry with RefactoringStatus.ERROR status. - * @param msg message - */ - public static RefactoringStatusEntry createError(String msg) { - return new RefactoringStatusEntry(msg, RefactoringStatus.ERROR); - } - - /** - * Creates an entry with RefactoringStatus.ERROR status. - * @param msg message - */ - public static RefactoringStatusEntry createError(String msg, Context context) { - return new RefactoringStatusEntry(msg, RefactoringStatus.ERROR, context); - } - - /** - * Creates an entry with RefactoringStatus.FATAL status. - * @param msg message - */ - public static RefactoringStatusEntry createFatal(String msg) { - return new RefactoringStatusEntry(msg, RefactoringStatus.FATAL); - } - - /** - * Creates an entry with RefactoringStatus.FATAL status. - * @param msg message - */ - public static RefactoringStatusEntry createFatal(String msg, Context context) { - return new RefactoringStatusEntry(msg, RefactoringStatus.FATAL, context); - } - - /** - * @return true iff (severity == RefactoringStatus.FATAL). - */ - public boolean isFatalError() { - return fSeverity == RefactoringStatus.FATAL; - } - - /** - * @return true iff (severity == RefactoringStatus.ERROR). - */ - public boolean isError() { - return fSeverity == RefactoringStatus.ERROR; - } - - /** - * @return true iff (severity == RefactoringStatus.WARNING). - */ - public boolean isWarning() { - return fSeverity == RefactoringStatus.WARNING; - } - - /** - * @return true iff (severity == RefactoringStatus.INFO). - */ - public boolean isInfo() { - return fSeverity == RefactoringStatus.INFO; - } - - /** - * @return message. - */ - public String getMessage() { - return fMessage; - } - - /** - * @return severity level. - * @see RefactoringStatus#INFO - * @see RefactoringStatus#WARNING - * @see RefactoringStatus#ERROR - * @see RefactoringStatus#FATAL - */ - public int getSeverity() { - return fSeverity; - } - - /** - * Returns the context which can be used to show more detailed information - * regarding this status entry in the UI. The method may return null - * indicating that no context is available. - * - * @return the status entry's context - */ - public Context getContext() { - return fContext; - } - - public Object getData() { - return fData; - } - - public int getCode() { - return fCode; - } - - /** - * Converts this RefactoringStatusEntry into an IStatus. - * The mapping is done as follows: - *
        - *
      • Fatal entries are mapped to IStatus.ERROR. - *
      • - *
      • Error and warning entries are mapped to IStatus.WARNING. - *
      • - *
      • Information entries are mapped to IStatus.INFO.
      • - *
      - * @return IStatus - */ - public IStatus asStatus () { - int statusSeverity= IStatus.ERROR; - switch (fSeverity) { - case RefactoringStatus.OK: - statusSeverity= IStatus.OK; - break; - case RefactoringStatus.INFO: - statusSeverity= IStatus.INFO; - break; - case RefactoringStatus.WARNING: - case RefactoringStatus.ERROR: - statusSeverity= IStatus.WARNING; - break; - } - return new Status(statusSeverity, CUIPlugin.getPluginId(), fCode, fMessage, null); - } - - /* non java-doc - * for debugging only - */ - public String toString() { - String contextString= fContext == null ? "": fContext.toString(); //$NON-NLS-1$ - return "\n" //$NON-NLS-1$ - + RefactoringStatus.getSeverityString(fSeverity) - + ": " //$NON-NLS-1$ - + fMessage - + "\nContext: " //$NON-NLS-1$ - + contextString - + "\nData: " //$NON-NLS-1$ - + getData() - +"\ncode: " //$NON-NLS-1$ - + fCode - + "\n"; //$NON-NLS-1$ - } -} diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/base/UndoManagerAdapter.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/base/UndoManagerAdapter.java deleted file mode 100644 index 6542274b9cd..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/base/UndoManagerAdapter.java +++ /dev/null @@ -1,30 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.corext.refactoring.base; - -/** - * An adapter implementation for IUndoManagerListener. - */ -public class UndoManagerAdapter implements IUndoManagerListener { - - /* (non-Javadoc) - * Method declared in IUndoManagerListener - */ - public void undoStackChanged(IUndoManager manager) { - } - - /* (non-Javadoc) - * Method declared in IUndoManagerListener - */ - public void redoStackChanged(IUndoManager manager) { - } -} - diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/changes/AbstractTextChange.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/changes/AbstractTextChange.java deleted file mode 100644 index 150fc809478..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/changes/AbstractTextChange.java +++ /dev/null @@ -1,209 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.corext.refactoring.changes; - -import java.util.ArrayList; -import java.util.List; - -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IProgressMonitor; - -import org.eclipse.cdt.core.model.CModelException; - -import org.eclipse.text.edits.TextEdit; -import org.eclipse.text.edits.UndoEdit; -import org.eclipse.cdt.internal.corext.Assert; -import org.eclipse.cdt.internal.corext.refactoring.NullChange; -import org.eclipse.cdt.internal.corext.refactoring.base.Change; -import org.eclipse.cdt.internal.corext.refactoring.base.ChangeAbortException; -import org.eclipse.cdt.internal.corext.refactoring.base.ChangeContext; -import org.eclipse.cdt.internal.corext.refactoring.base.IChange; -import org.eclipse.cdt.internal.corext.textmanipulation.TextBuffer; -import org.eclipse.cdt.internal.corext.refactoring.changes.TextBufferEditor; - -public abstract class AbstractTextChange extends Change { - - private String fName; - private int fChangeKind; - private IChange fUndoChange; - - protected final static int ORIGINAL_CHANGE= 0; - protected final static int UNDO_CHANGE= 1; - protected final static int REDO_CHANGE= 2; - - protected static class LocalTextEditProcessor extends TextBufferEditor { - public static final int EXCLUDE= 1; - public static final int INCLUDE= 2; - - private TextEdit[] fExcludes; - private TextEdit[] fIncludes; - - public LocalTextEditProcessor(TextBuffer buffer) { - super(buffer); - } - public void setIncludes(TextEdit[] includes) { - Assert.isNotNull(includes); - Assert.isTrue(fExcludes == null); - fIncludes= flatten(includes); - } - public void setExcludes(TextEdit[] excludes) { - Assert.isNotNull(excludes); - Assert.isTrue(fIncludes == null); - fExcludes= excludes; - } - protected boolean considerEdit(TextEdit edit) { - if (fExcludes != null) { - for (int i= 0; i < fExcludes.length; i++) { - if (edit.equals(fExcludes[i])) - return false; - } - return true; - } - if (fIncludes != null) { - for (int i= 0; i < fIncludes.length; i++) { - if (edit.equals(fIncludes[i])) - return true; - } - return false; - } - return true; - } - private TextEdit[] flatten(TextEdit[] edits) { - List result= new ArrayList(5); - for (int i= 0; i < edits.length; i++) { - flatten(result, edits[i]); - } - return (TextEdit[])result.toArray(new TextEdit[result.size()]); - } - private void flatten(List result, TextEdit edit) { - result.add(edit); - TextEdit[] children= edit.getChildren(); - for (int i= 0; i < children.length; i++) { - flatten(result, children[i]); - } - } - } - - /** - * Creates a new TextChange with the given name. - * - * @param name the change's name mainly used to render the change in the UI. - * @param changeKind a flag indicating if the change is a ORIGINAL_CHANGE, - * a UNDO_CHANGE or a REDO_CHANGE - */ - protected AbstractTextChange(String name, int changeKind) { - fName= name; - Assert.isNotNull(fName); - fChangeKind= changeKind; - Assert.isTrue(0 <= fChangeKind && fChangeKind <= 2); - } - - /** - * Acquires a new text buffer to perform the changes managed by this - * text buffer change. Two subsequent calls to this method must - * return the identical ITextBuffer object. - * - * @return the acquired text buffer - */ - protected abstract TextBuffer acquireTextBuffer() throws CoreException; - - /** - * Releases the given text buffer. The given text buffer is not usable - * anymore after calling this method. - * - * @param textBuffer the text buffer to be released - */ - protected abstract void releaseTextBuffer(TextBuffer textBuffer); - - /** - * Create a new TextBuffer. Any call to this method - * must create a new TextBufferinstance. - * - * @return the created text buffer - */ - protected abstract TextBuffer createTextBuffer() throws CoreException; - - /** - * Adds the TextEdits managed by this change to the given - * text buffer editor. - * - * @param editor the text buffer edit - * @param copy if true the edits are copied before adding. - * Otherwise the original edits are added. - */ - protected abstract void addTextEdits(LocalTextEditProcessor editor) throws CoreException; - - /** - * Creates a IChange that can undo this change. - * - * @param edits the text edits that can undo the edits performed by this change - * @param changeKind the change kind of the reverse change. Either - * UNDO_CHANGE or
      REDO_CHANGE
      - * @return a change that can undo this change - */ - protected abstract IChange createReverseChange(UndoEdit edits , int changeKind); - - /** - * Returns true if this change is a reverse change. This is the case for an undo - * or a redo change. Returns false if the change is an original - * change. - * - * @return whether or not this change is a reverse change - */ - public boolean isReverseChange() { - return fChangeKind != ORIGINAL_CHANGE; - } - - protected int getReverseKind() { - if (fChangeKind == ORIGINAL_CHANGE || fChangeKind == REDO_CHANGE) - return UNDO_CHANGE; - else - return REDO_CHANGE; - } - - /* (Non-Javadoc) - * Method declared in IChange. - */ - public String getName(){ - return fName; - } - - /* Non-Javadoc - * Method declared in IChange - */ - public IChange getUndoChange() { - return fUndoChange; - } - - /* Non-Javadoc - * Method declared in IChange - */ - public void perform(ChangeContext context, IProgressMonitor pm) throws CModelException, ChangeAbortException { - if (!isActive()) { - fUndoChange= new NullChange(); - return; - } - LocalTextEditProcessor editor= null; - try { - fUndoChange= null; - editor= new LocalTextEditProcessor(acquireTextBuffer()); - addTextEdits(editor); - fUndoChange= createReverseChange(editor.performEdits(pm), getReverseKind()); - } catch (Exception e) { - handleException(context, e); - } finally { - if (editor != null) { - releaseTextBuffer(editor.getTextBuffer()); - } - } - } -} - diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/changes/TextBufferEditor.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/changes/TextBufferEditor.java deleted file mode 100644 index d6355c25838..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/changes/TextBufferEditor.java +++ /dev/null @@ -1,120 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.corext.refactoring.changes; - -import org.eclipse.cdt.internal.corext.Assert; -import org.eclipse.cdt.internal.corext.textmanipulation.TextBuffer; -import org.eclipse.cdt.ui.CUIPlugin; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.Status; -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.text.edits.MalformedTreeException; -import org.eclipse.text.edits.MultiTextEdit; -import org.eclipse.text.edits.TextEdit; -import org.eclipse.text.edits.TextEditProcessor; -import org.eclipse.text.edits.UndoEdit; - -public class TextBufferEditor extends TextEditProcessor { - - private TextBuffer fBuffer; - private TextEditProcessor fUndoProcessor; - - /** - * Creates a new TextBufferEditor for the given - * TextBuffer. - * - * @param the text buffer this editor is working on. - */ - public TextBufferEditor(TextBuffer buffer) { - super(buffer.getDocument(), new MultiTextEdit(0, buffer.getDocument().getLength()), - TextEdit.CREATE_UNDO | TextEdit.UPDATE_REGIONS); - fBuffer= buffer; - } - - /** - * Returns the text buffer this editor is working on. - * - * @return the text buffer this editor is working on - */ - public TextBuffer getTextBuffer() { - return fBuffer; - } - - /** - * Adds an Edit to this edit processor. Adding an edit - * to an edit processor transfers ownership of the edit to the - * processor. So after an edit has been added to a processor the - * creator of the edit must not continue modifying the edit. - * - * @param edit the edit to add - * @exception MalformedTreeException if the text edit can not be - * added to this edit processor. - * - * @see TextEdit#addChild(TextEdit) - */ - public void add(TextEdit edit) throws MalformedTreeException { - getRoot().addChild(edit); - } - - /** - * Adds an undo memento to this edit processor. Adding an undo memento - * transfers ownership of the memento to the processor. So after a memento - * has been added the creator of that memento must not continue - * modifying it. - * - * @param undo the undo memento to add - * @exception EditException if the undo memento can not be added - * to this processor - */ - public void add(UndoEdit undo) { - Assert.isTrue(!getRoot().hasChildren()); - fUndoProcessor= new TextEditProcessor(getDocument(), undo, TextEdit.CREATE_UNDO | TextEdit.UPDATE_REGIONS); - } - - /* (non-Javadoc) - * @see org.eclipse.text.edits.TextEditProcessor#canPerformEdits() - */ - public boolean canPerformEdits() { - if (fUndoProcessor != null) - return fUndoProcessor.canPerformEdits(); - return super.canPerformEdits(); - } - - /** - * Executes the text edits added to this text buffer editor and clears all added - * text edits. - * - * @param pm a progress monitor to report progress or null if - * no progress is desired. - * @return an object representing the undo of the executed TextEdits - * @exception CoreException if the edits cannot be executed - */ - public UndoEdit performEdits(IProgressMonitor pm) throws CoreException { - try { - if (fUndoProcessor != null) { - return fUndoProcessor.performEdits(); - } else { - return super.performEdits(); - } - } catch (BadLocationException e) { - String message= (e != null ? e.getMessage() : ""); //$NON-NLS-1$ - throw new CoreException(new Status(IStatus.ERROR, CUIPlugin.getPluginId(), - IStatus.ERROR, message, e)); - } catch (MalformedTreeException e) { - String message= (e != null ? e.getMessage() : ""); //$NON-NLS-1$ - throw new CoreException(new Status(IStatus.ERROR, CUIPlugin.getPluginId(), - IStatus.ERROR, message, e)); - } - } -} - diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/changes/TextChange.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/changes/TextChange.java deleted file mode 100644 index fd59c0f94ce..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/changes/TextChange.java +++ /dev/null @@ -1,572 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.corext.refactoring.changes; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Iterator; -import java.util.List; - -import org.eclipse.cdt.core.model.CModelException; -import org.eclipse.cdt.internal.corext.Assert; -import org.eclipse.cdt.internal.corext.textmanipulation.GroupDescription; -import org.eclipse.cdt.internal.corext.textmanipulation.TextBuffer; -import org.eclipse.cdt.internal.corext.textmanipulation.TextRegion; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.NullProgressMonitor; -import org.eclipse.jface.text.IRegion; -import org.eclipse.text.edits.MultiTextEdit; -import org.eclipse.text.edits.TextEdit; -import org.eclipse.text.edits.TextEditCopier; - -public abstract class TextChange extends AbstractTextChange { - - public static class EditChange { - private boolean fIsActive; - private TextChange fTextChange; - private GroupDescription fDescription; - - /* package */ EditChange(GroupDescription description, TextChange change) { - fTextChange= change; - fIsActive= true; - fDescription= description; - } - public String getName() { - return fDescription.getName(); - } - public void setActive(boolean active) { - fIsActive= active; - } - public boolean isActive() { - return fIsActive; - } - public TextChange getTextChange() { - return fTextChange; - } - public IRegion getTextRange() { - return fDescription.getTextRange(); - } - public boolean isEmpty() { - return fDescription.hasTextEdits(); - } - /* package */ GroupDescription getGroupDescription() { - return fDescription; - } - public boolean coveredBy(IRegion sourceRegion) { - int sLength= sourceRegion.getLength(); - if (sLength == 0) - return false; - int sOffset= sourceRegion.getOffset(); - int sEnd= sOffset + sLength - 1; - TextEdit[] edits= fDescription.getTextEdits(); - for (int i= 0; i < edits.length; i++) { - TextEdit edit= edits[i]; - if (edit.isDeleted()) - return false; - int rOffset= edit.getOffset(); - int rLength= edit.getLength(); - int rEnd= rOffset + rLength - 1; - if (rLength == 0) { - if (!(sOffset < rOffset && rOffset <= sEnd)) - return false; - } else { - if (!(sOffset <= rOffset && rEnd <= sEnd)) - return false; - } - } - return true; - } - } - - private List fTextEditChanges; - private TextEditCopier fCopier; - private TextEdit fEdit; - private boolean fKeepExecutedTextEdits; - private boolean fAutoMode; - private String fTextType; - - /** - * Creates a new TextChange with the given name. - * - * @param name the change's name mainly used to render the change in the UI. - */ - protected TextChange(String name) { - super(name, ORIGINAL_CHANGE); - fTextEditChanges= new ArrayList(5); - fTextType= "txt"; //$NON-NLS-1$ - } - - /** - * Sets the text type. Text types are defined by the extension - * point >>TODO<<. - * - * @param type the text type. If null is passed the - * text type is resetted to the default text type "text". - */ - protected void setTextType(String type) { - if (type == null) - fTextType= "txt"; //$NON-NLS-1$ - fTextType= type; - } - - /** - * Returns the text change's text type. - * - * @return the text change's text type - */ - public String getTextType() { - return fTextType; - } - - /** - * Adds a text edit object to this text buffer change. - * - * @param name the name of the given text edit. The name is used to render this - * change in the UI. - * @param edit the text edit to add - */ - public void addTextEdit(String name, TextEdit edit) { - addTextEdit(name, new TextEdit[] {edit}); - } - - /** - * Adds an array of text edit objects to this text buffer change. - * - * @param name the name of the given text edit. The name is used to render this - * change in the UI. - * @param edite the array of text edits to add - */ - public void addTextEdit(String name, TextEdit[] edits) { - Assert.isNotNull(name); - Assert.isNotNull(edits); - GroupDescription description= new GroupDescription(name, edits); - fTextEditChanges.add(new EditChange(description, this)); - if (fEdit == null) { - fEdit= new MultiTextEdit(); - fAutoMode= true; - } else { - Assert.isTrue(fAutoMode, "Can only add edits when in auto organizing mode"); //$NON-NLS-1$ - } - for (int i= 0; i < edits.length; i++) { - insert(fEdit, edits[i]); - } - } - - /** - * Sets the root text edit. - * - * @param edit the root text edit - */ - public void setEdit(TextEdit edit) { - Assert.isTrue(fEdit == null, "Root edit can only be set once"); //$NON-NLS-1$ - Assert.isTrue(edit != null); - fEdit= edit; - fTextEditChanges= new ArrayList(5); - fAutoMode= false; - } - - /** - * Gets the root text edit. - * - * @return Returns the root text edit - */ - public TextEdit getEdit() { - return fEdit; - } - - /** - * Adds a group description. - * - * @param description the group description to be added - */ - public void addGroupDescription(GroupDescription description) { - Assert.isTrue(fEdit != null, "Can only add a description if a root edit exists"); //$NON-NLS-1$ - Assert.isTrue(!fAutoMode, "Group descriptions are only supported if root edit has been set by setEdit"); //$NON-NLS-1$ - Assert.isTrue(description != null); - fTextEditChanges.add(new EditChange(description, this)); - } - - /** - * Adds a set of group descriptions. - * - * @param descriptios the group descriptions to be added - */ - public void addGroupDescriptions(GroupDescription[] descriptions) { - for (int i= 0; i < descriptions.length; i++) { - addGroupDescription(descriptions[i]); - } - } - - /** - * Returns the group descriptions that have been added to this change - * @return GroupDescription[] - */ - public GroupDescription[] getGroupDescriptions() { - GroupDescription[] res= new GroupDescription[fTextEditChanges.size()]; - for (int i= 0; i < res.length; i++) { - EditChange elem= (EditChange) fTextEditChanges.get(i); - res[i]= elem.getGroupDescription(); - } - return res; - } - - /** - * Returns the group description with the given name or null if no such - * GroupDescription exists. - */ - public GroupDescription getGroupDescription(String name) { - for (int i= 0; i < fTextEditChanges.size(); i++) { - EditChange elem= (EditChange) fTextEditChanges.get(i); - GroupDescription description= elem.getGroupDescription(); - if (name.equals(description.getName())) { - return description; - } - } - return null; - } - - - /** - * Returns the text edit changes managed by this text change. - * - * @return the text edit changes - */ - public EditChange[] getTextEditChanges() { - return (EditChange[])fTextEditChanges.toArray(new EditChange[fTextEditChanges.size()]); - } - - /** - * Returns the text this change is working on. - * - * @return the original text. - * @exception CModelException if text cannot be accessed - */ - public String getCurrentContent() throws CModelException { - TextBuffer buffer= null; - try { - buffer= acquireTextBuffer(); - return buffer.getContent(); - } catch (CModelException e){ - throw e; - } catch (CoreException e) { - throw new CModelException(e); - } finally { - if (buffer != null) - releaseTextBuffer(buffer); - } - } - - /** - * Returns a preview of the change without actually modifying the underlying text. - * - * @return the change's preview - * @exception CModelException if the preview could not be created - */ - public String getPreviewContent() throws CModelException { - return getPreviewTextBuffer().getContent(); - } - - /** - * Note: API is under construction - */ - public TextBuffer getPreviewTextBuffer() throws CModelException { - try { - LocalTextEditProcessor editor= new LocalTextEditProcessor(createTextBuffer()); - addTextEdits(editor); - editor.performEdits(new NullProgressMonitor()); - return editor.getTextBuffer(); - } catch (CModelException e){ - throw e; - } catch (CoreException e) { - throw new CModelException(e); - } - } - - /** - * Returns the current content to be modified by the given text edit change. The - * text edit change must have been added to this TextChange - * by calling addTextEdit() - * - * @param change the text edit change for which the content is requested - * @param surroundingLines the number of surrounding lines added at top and bottom - * of the content - * @return the current content to be modified by the given text edit change - */ - public String getCurrentContent(EditChange change, int surroundingLines) throws CoreException { - return getContent(change, surroundingLines, false); - } - - /** - * Returns the preview of the given text edit change. The text edit change must - * have been added to this TextChange by calling addTextEdit() - * - * - * @param change the text edit change for which the preview is requested - * @param surroundingLines the number of surrounding lines added at top and bottom - * of the preview - * @return the preview of the given text edit change - */ - public String getPreviewContent(EditChange change, int surroundingLines) throws CoreException { - return getContent(change, surroundingLines, true); - } - - /** - * Returns the current content denoted by the given range. - * - * @param range the range describing the content to be returned - * @return the current content denoted by the given range - */ - public String getCurrentContent(IRegion range) throws CoreException { - TextBuffer buffer= null; - try { - buffer= acquireTextBuffer(); - int offset= buffer.getLineInformationOfOffset(range.getOffset()).getOffset(); - int length= range.getLength() + range.getOffset() - offset; - return buffer.getContent(offset, length); - } finally { - if (buffer != null) - releaseTextBuffer(buffer); - } - } - - /** - * Returns a preview denoted by the given range. First the changes - * passed in argument changes are applied and then a string denoted - * by range is extracted from the result. - * - * @param changes the changes to apply - * @param range the range denoting the resulting string. - * @return the computed preview - */ - public String getPreviewContent(EditChange[] changes, IRegion range) throws CoreException { - TextBuffer buffer= createTextBuffer(); - LocalTextEditProcessor editor= new LocalTextEditProcessor(buffer); - addTextEdits(editor, changes); - int oldLength= buffer.getLength(); - editor.performEdits(new NullProgressMonitor()); - int delta= buffer.getLength() - oldLength; - int offset= buffer.getLineInformationOfOffset(range.getOffset()).getOffset(); - int length= range.getLength() + range.getOffset() - offset + delta; - if (length > 0) { - return buffer.getContent(offset, length); - } else { - // range got removed - return ""; //$NON-NLS-1$ - } - } - - /** - * Controls whether the text change should keep executed edits. If set to true - * a call to getExecutedTextEdit(TextEdit original) will return the executed edit - * associated with the original edit. - * - * @param keep if true executed edits are kept - */ - public void setKeepExecutedTextEdits(boolean keep) { - fKeepExecutedTextEdits= keep; - if (!fKeepExecutedTextEdits) - fCopier= null; - } - - /** - * Returns the edit that got copied and executed instead of the orignial. - * - * @return the executed edit - */ - private TextEdit getExecutedTextEdit(TextEdit original) { - if (!fKeepExecutedTextEdits || fCopier == null) - return null; - return fCopier.getCopy(original); - } - - /** - * Returns the text range of the given text edit. If the change doesn't - * manage the given text edit or if setTrackPositionChanges - * is set to false null is returned. - * - *

      - * Note: API is under construction - *

      - */ - public IRegion getNewTextRange(TextEdit edit) { - Assert.isNotNull(edit); - TextEdit result= getExecutedTextEdit(edit); - if (result == null) - return null; - return result.getRegion(); - } - - /** - * Returns the new text range for given text edits. If setTrackPositionChanges - * is set to false null is returned. - * - *

      - * Note: API is under construction - *

      - */ - public IRegion getNewTextRange(TextEdit[] edits) { - Assert.isTrue(edits != null && edits.length > 0); - if (!fKeepExecutedTextEdits || fCopier == null) - return null; - - TextEdit[] copies= new TextEdit[edits.length]; - for (int i= 0; i < edits.length; i++) { - TextEdit copy= fCopier.getCopy(edits[i]); - if (copy == null) - return null; - copies[i]= copy; - } - return TextEdit.getCoverage(copies); - } - - /** - * Note: API is under construction - */ - public IRegion getNewTextRange(EditChange editChange) { - return getNewTextRange(editChange.getGroupDescription().getTextEdits()); - } - - /* (Non-Javadoc) - * Method declared in IChange. - */ - public void setActive(boolean active) { - super.setActive(active); - for (Iterator iter= fTextEditChanges.iterator(); iter.hasNext();) { - EditChange element= (EditChange) iter.next(); - element.setActive(active); - } - } - - /* non Java-doc - * @see AbstractTextChange#addTextEdits - */ - protected void addTextEdits(LocalTextEditProcessor editor) throws CoreException { - if (fEdit == null) - return; - List excludes= new ArrayList(0); - for (Iterator iter= fTextEditChanges.iterator(); iter.hasNext(); ) { - EditChange edit= (EditChange)iter.next(); - if (!edit.isActive()) { - excludes.addAll(Arrays.asList(edit.getGroupDescription().getTextEdits())); - } - } - fCopier= new TextEditCopier(fEdit); - TextEdit copiedEdit= fCopier.perform(); - if (copiedEdit != null) { - editor.add(copiedEdit); - editor.setExcludes(mapEdits( - (TextEdit[])excludes.toArray(new TextEdit[excludes.size()]), - fCopier)); - } - if (!fKeepExecutedTextEdits) - fCopier= null; - } - - protected void addTextEdits(LocalTextEditProcessor editor, EditChange[] changes) throws CoreException { - if (fEdit == null) - return; - List includes= new ArrayList(0); - for (int c= 0; c < changes.length; c++) { - EditChange change= changes[c]; - Assert.isTrue(change.getTextChange() == this); - if (change.isActive()) { - includes.addAll(Arrays.asList(change.getGroupDescription().getTextEdits())); - } - } - fCopier= new TextEditCopier(fEdit); - TextEdit copiedEdit= fCopier.perform(); - if (copiedEdit != null) { - editor.add(copiedEdit); - editor.setIncludes(mapEdits( - (TextEdit[])includes.toArray(new TextEdit[includes.size()]), - fCopier)); - } - if (!fKeepExecutedTextEdits) - fCopier= null; - } - - private TextEdit[] mapEdits(TextEdit[] edits, TextEditCopier copier) { - if (edits == null) - return null; - for (int i= 0; i < edits.length; i++) { - edits[i]= copier.getCopy(edits[i]); - } - return edits; - } - - private String getContent(EditChange change, int surroundingLines, boolean preview) throws CoreException { - Assert.isTrue(change.getTextChange() == this); - TextBuffer buffer= createTextBuffer(); - IRegion range= null; - if (preview) { - LocalTextEditProcessor editor= new LocalTextEditProcessor(buffer); - boolean keepEdits= fKeepExecutedTextEdits; - setKeepExecutedTextEdits(true); - addTextEdits(editor, new EditChange[] { change }); - editor.performEdits(new NullProgressMonitor()); - range= getNewTextRange(change); - setKeepExecutedTextEdits(keepEdits); - } else { - range= change.getTextRange(); - } - int startLine= Math.max(buffer.getLineOfOffset(range.getOffset()) - surroundingLines, 0); - int endLine= Math.min( - buffer.getLineOfOffset(range.getOffset() + range.getLength() - 1) + surroundingLines, - buffer.getNumberOfLines() - 1); - int offset= buffer.getLineInformation(startLine).getOffset(); - TextRegion region= buffer.getLineInformation(endLine); - int length = region.getOffset() + region.getLength() - offset; - return buffer.getContent(offset, length); - } - - private static void insert(TextEdit parent, TextEdit edit) { - if (!parent.hasChildren()) { - parent.addChild(edit); - return; - } - TextEdit[] children= parent.getChildren(); - // First dive down to find the right parent. - for (int i= 0; i < children.length; i++) { - TextEdit child= children[i]; - if (covers(child, edit)) { - insert(child, edit); - return; - } - } - // We have the right parent. Now check if some of the children have to - // be moved under the new edit since it is covering it. - for (int i= children.length - 1; i >= 0; i--) { - TextEdit child= children[i]; - if (covers(edit, child)) { - parent.removeChild(i); - edit.addChild(child); - } - } - parent.addChild(edit); - } - - private static boolean covers(TextEdit thisEdit, TextEdit otherEdit) { - if (thisEdit.getLength() == 0) // an insertion point can't cover anything - return false; - - int thisOffset= thisEdit.getOffset(); - int thisEnd= thisEdit.getExclusiveEnd(); - if (otherEdit.getLength() == 0) { - int otherOffset= otherEdit.getOffset(); - return thisOffset < otherOffset && otherOffset < thisEnd; - } else { - int otherOffset= otherEdit.getOffset(); - int otherEnd= otherEdit.getExclusiveEnd(); - return thisOffset <= otherOffset && otherEnd <= thisEnd; - } - } -} - diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/changes/TextFileChange.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/changes/TextFileChange.java deleted file mode 100644 index a1824fac34a..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/changes/TextFileChange.java +++ /dev/null @@ -1,239 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.corext.refactoring.changes; - -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.NullProgressMonitor; -import org.eclipse.core.runtime.SubProgressMonitor; - -import org.eclipse.core.resources.IFile; - -import org.eclipse.cdt.core.model.CModelException; - -import org.eclipse.text.edits.UndoEdit; -import org.eclipse.cdt.internal.corext.Assert; -import org.eclipse.cdt.internal.corext.refactoring.Checks; -import org.eclipse.cdt.internal.corext.refactoring.base.ChangeAbortException; -import org.eclipse.cdt.internal.corext.refactoring.base.ChangeContext; -import org.eclipse.cdt.internal.corext.refactoring.base.IChange; -import org.eclipse.cdt.internal.corext.refactoring.base.RefactoringStatus; -import org.eclipse.cdt.internal.corext.textmanipulation.TextBuffer; - -public class TextFileChange extends TextChange { - - protected static class UndoTextFileChange extends UndoTextChange { - private IFile fFile; - private TextBuffer fAcquiredTextBuffer; - private int fAcquireCounter; - public UndoTextFileChange(String name, IFile file, int changeKind, UndoEdit undo) { - super(name, changeKind, undo); - fFile= file; - } - public Object getModifiedLanguageElement(){ - return fFile; - } - protected TextBuffer acquireTextBuffer() throws CoreException { - TextBuffer result= TextBuffer.acquire(fFile); - if (fAcquiredTextBuffer == null || result == fAcquiredTextBuffer) { - fAcquiredTextBuffer= result; - fAcquireCounter++; - } - return result; - } - protected void releaseTextBuffer(TextBuffer textBuffer) { - TextBuffer.release(textBuffer); - if (textBuffer == fAcquiredTextBuffer) { - if (--fAcquireCounter == 0) - fAcquiredTextBuffer= null; - } - } - protected TextBuffer createTextBuffer() throws CoreException { - return TextBuffer.create(fFile); - } - protected IChange createReverseChange(UndoEdit undo, int changeKind) { - return new UndoTextFileChange(getName(), fFile, changeKind, undo); - } - public RefactoringStatus aboutToPerform(ChangeContext context, IProgressMonitor pm) { - RefactoringStatus result= Checks.validateModifiesFiles(new IFile[] {fFile}); - if (result.hasFatalError()) - return result; - context.checkUnsavedFile(result, fFile); - return result; - } - public void perform(ChangeContext context, IProgressMonitor pm) throws CModelException, ChangeAbortException { - if (!isActive()) { - super.perform(context, pm); - return; - } - try{ - acquireTextBuffer(); - pm.beginTask("", 10); //$NON-NLS-1$ - super.perform(context, new SubProgressMonitor(pm, 8)); - TextBuffer.aboutToChange(fAcquiredTextBuffer); - TextBuffer.save(fAcquiredTextBuffer, new SubProgressMonitor(pm, 2)); - } catch (Exception e) { - handleException(context, e); - } finally { - pm.done(); - } - } - public void performed() { - // During acquiring of text buffer an exception has occured. In this case - // the pointer is null - if (fAcquiredTextBuffer != null) { - try { - TextBuffer.changed(fAcquiredTextBuffer); - } catch (CoreException e) { - Assert.isTrue(false, "Should not happen since the buffer is acquired through a text buffer manager"); //$NON-NLS-1$ - } finally { - releaseTextBuffer(fAcquiredTextBuffer); - } - } - super.performed(); - } - } - - private IFile fFile; - private TextBuffer fAcquiredTextBuffer; - private int fAcquireCounter; - private boolean fSave= true; - - /** - * Creates a new TextFileChange for the given file. - * - * @param name the change's name mainly used to render the change in the UI - * @param file the file this text change operates on - */ - public TextFileChange(String name, IFile file) { - super(name); - fFile= file; - Assert.isNotNull(fFile); - } - - /** - * Sets the save state. If set to true the change will save the - * content of the file back to disk. - * - * @param save whether or not the changes should be saved to disk - */ - public void setSave(boolean save) { - fSave= save; - } - - /** - * Returns the IFile this change is working on. - * - * @return the file this change is working on - */ - public IFile getFile() { - return fFile; - } - - /* non java-doc - * Method declared in TextChange - */ - protected TextBuffer acquireTextBuffer() throws CoreException { - TextBuffer result= TextBuffer.acquire(fFile); - if (fAcquiredTextBuffer == null || result == fAcquiredTextBuffer) { - fAcquiredTextBuffer= result; - fAcquireCounter++; - } - return result; - } - - /* non java-doc - * Method declared in TextChange - */ - protected void releaseTextBuffer(TextBuffer textBuffer) { - TextBuffer.release(textBuffer); - if (textBuffer == fAcquiredTextBuffer) { - if (--fAcquireCounter == 0) - fAcquiredTextBuffer= null; - } - } - - /* non java-doc - * Method declared in TextChange - */ - protected TextBuffer createTextBuffer() throws CoreException { - return TextBuffer.create(fFile); - } - - /* non java-doc - * Method declared in TextChange - */ - protected IChange createReverseChange(UndoEdit undo, int changeKind) { - return new UndoTextFileChange(getName(), fFile, changeKind, undo); - } - - /* non java-doc - * Method declared in IChange. - */ - public Object getModifiedLanguageElement(){ - return fFile; - } - - /* non java-doc - * Method declared in TextChange - */ - public RefactoringStatus aboutToPerform(ChangeContext context, IProgressMonitor pm) { - if (fSave) { - return Checks.validateModifiesFiles(new IFile[] {fFile}); - } - return new RefactoringStatus(); - } - - /* non java-doc - * Method declared in TextChange - */ - public void perform(ChangeContext context, IProgressMonitor pm) throws CModelException, ChangeAbortException { - if (pm == null) - pm= new NullProgressMonitor(); - if (!isActive()) { - super.perform(context, pm); - return; - } - try{ - acquireTextBuffer(); - pm.beginTask("", 10); //$NON-NLS-1$ - super.perform(context, new SubProgressMonitor(pm, 8)); - if (fSave) { - TextBuffer.aboutToChange(fAcquiredTextBuffer); - TextBuffer.save(fAcquiredTextBuffer, new SubProgressMonitor(pm, 2)); - } - } catch (Exception e) { - handleException(context, e); - } finally { - pm.done(); - } - } - - /* non java-doc - * Method declared in TextChange - */ - public void performed() { - // During acquiring of text buffer an exception has occured. In this case - // the pointer is null - if (fAcquiredTextBuffer != null) { - try { - if (fSave) - TextBuffer.changed(fAcquiredTextBuffer); - } catch (CoreException e) { - Assert.isTrue(false, "Should not happen since the buffer is acquired through a text buffer manager"); //$NON-NLS-1$ - } finally { - releaseTextBuffer(fAcquiredTextBuffer); - } - } - super.performed(); - } -} - diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/changes/TranslationUnitChange.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/changes/TranslationUnitChange.java deleted file mode 100644 index 532f3e72d20..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/changes/TranslationUnitChange.java +++ /dev/null @@ -1,57 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.corext.refactoring.changes; - -import org.eclipse.core.resources.IFile; -import org.eclipse.core.runtime.CoreException; - -import org.eclipse.cdt.core.model.ITranslationUnit; - -import org.eclipse.cdt.internal.corext.Assert; - -public class TranslationUnitChange extends TextFileChange { - - private ITranslationUnit fCUnit; - - /** - * Creates a new TranslationUnitChange. - * - * @param name the change's name mainly used to render the change in the UI - * @param cunit the Translation unit this text change works on - */ - public TranslationUnitChange(String name, ITranslationUnit cunit) throws CoreException { - super(name, getFile(cunit)); - Assert.isNotNull(cunit); - fCUnit= cunit; - setTextType("java"); //$NON-NLS-1$ - } - - private static IFile getFile(ITranslationUnit cunit) throws CoreException { - return (IFile) cunit.getResource(); - } - - /* non java-doc - * Method declared in IChange. - */ - public Object getModifiedLanguageElement(){ - return fCUnit; - } - - /** - * Returns the Translation unit this change works on. - * - * @return the Translation unit this change works on - */ - public ITranslationUnit getTranslationUnit() { - return fCUnit; - } -} - diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/changes/UndoTextChange.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/changes/UndoTextChange.java deleted file mode 100644 index 207a1930923..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/changes/UndoTextChange.java +++ /dev/null @@ -1,30 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.corext.refactoring.changes; - -import org.eclipse.core.runtime.CoreException; - -import org.eclipse.text.edits.UndoEdit; - -abstract class UndoTextChange extends AbstractTextChange { - - private UndoEdit fUndos; - - public UndoTextChange(String name, int changeKind, UndoEdit undos) { - super(name, changeKind); - fUndos= undos; - } - - protected void addTextEdits(LocalTextEditProcessor editor) throws CoreException { - editor.add(fUndos); - } -} - diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/refactoring.properties b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/refactoring.properties deleted file mode 100644 index 5429404c8bf..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/refactoring.properties +++ /dev/null @@ -1,793 +0,0 @@ -############################################################################### -# Copyright (c) 2004 IBM Corporation and others. -# All rights reserved. This program and the accompanying materials -# are made available under the terms of the Eclipse Public License v1.0 -# which accompanies this distribution, and is available at -# http://www.eclipse.org/legal/epl-v10.html -# -# Contributors: -# IBM Rational Software - Initial API and implementation -############################################################################### -# NLS properties for the Refactoring Core - -####################################### -# org.eclipse.jdt.internal.core.refactoring - -Assert.assertion_failed=assertion failed; -Assert.null_argument=null argument; - -Checks.Choose_name=Choose a name -Checks.all_excluded=All resources have been excluded from refactoring. Cannot proceed -Checks.cannot_be_parsed=''{0}'' has syntax errors. Content of that file will not be updated. -Checks.cu_not_created=Translation unit could not be created for this element. -Checks.cu_not_parsed=This refactoring cannot be performed correctly due to syntax errors in the translation unit. To perform this operation you will need to fix the errors. -Checks.cu_has_compile_errors=Code modification may not be accurate as affected resource ''{0}'' has compile errors. -Checks.no_dot=Class name cannot contain a dot (.) -Checks.cu_name_used=translation unit ''{0}.java'' already exists -Checks.method_native=Method {0}::{1} is native. Running the modified program will cause {2}. -Checks.methodName.constructor=New method name has constructor name -Checks.methodName.exists=Method ''{0}'' already exists in type ''{1}'' -Checks.methodName.overrides=New method ''{0}'' overrides existing method in type ''{1}'' -Checks.methodName.returnTypeClash=New method ''{0}'' overrides a method declared in type ''{1}'' that uses a different return type. -Checks.has_main=Type {0} contains a main method - some applications (such as scripts) may not work after refactoring -Checks.constructor_name= If you proceed, the method {0} in ''{1}'' will have a constructor name. -Checks.method_names_lowercase=This name is discouraged. According to convention, names of methods should start with lowercase letters -Checks.error.InvalidClassName=Class name is not valid. {0} -Checks.warning.ClassNameDiscouraged=Class name is discouraged. {0} -Checks.no_files=No files are found. - -####################################### -# org.eclipse.jdt.internal.core.refactoring.base -####################################### - -Change.checking_for=Checking change for: {0} -Change.internal_Error=Internal Error -Change.is_unsaved={0} is unsaved -Change.is_read_only={0} is read only -Change.unexpected_exception=Unexpected exception while executing a change. See log for details. -Change.javaChanges= C changes - - -ChangeAbortException.wrapped=Exception wrapped by {0} - -Refactoring.binary={0} is binary -Refactoring.not_in_model={0} does not exist in the model -Refactoring.read_only={0} is read only -Refactoring.unknown_structure={0} - unknown structure - -####################################### -# org.eclipse.jdt.internal.core.refactoring.changes -####################################### -AbstractRenameChange.Renaming=Renaming... - -RenameResourceChange.rename_resource=rename resource -RenameResourceChange.name=Rename ''{0}'' to: ''{1}'' - -CompositeChange.CompositeChange=CompositeChange> - -DeleteFromClassPathChange.remove=Remove entry from classpath of C project: - -MovePackageChange.move=Move package ''{0}'' to ''{1}'' -MoveResourceChange.move=Move resource ''{0}'' to ''{1}'' - -RenameCProjectChange.rename=Rename C Project ''{0}'' to ''{1}'' -RenameCProjectChange.update=Updating classpaths - -RenameSourceFolderChange.rename=Rename Source Folder ''{0}'' to ''{1}'' - -AbstractCElementRenameChange.checking_change=Checking change for: - -AbstractDeleteChange.deleting=deleting - -CreatePackageChange.Creating_package=Creating package -CreatePackageChange.Create_package=Create package - -AddToClasspathChange.add=Add entry to classpath of C project: - -CopyCompilationUnitChange.copy=Copy ''{0}'' to ''{1}'' - -CopyPackageChange.copy=Copy package ''{0}'' to ''{1}'' - -RenamePackageChange.checking_change=Checking change for: {0} -RenamePackageChange.name=Rename package ''{0}'' to ''{1}'' - -MoveCompilationUnitChange.default_package=(default package) -MoveCompilationUnitChange.name=Move Translation Unit ''{0}'' to ''{1}'' - -RenameCompilationUnitChange.name=Rename translation unit ''{0}'' to ''{1}'' - -####################################### -# org.eclipse.jdt.internal.core.refactoring.code -####################################### - -#-- Extract Method ------------------------------------------- -LocalTypeAnalyzer.local_type_from_outside=Selected block references a local type declared outside the selection. -LocalTypeAnalyzer.local_type_referenced_outside=A local type declared in the selected block is referenced outside the selection. - -FlowAnalyzer.execution_flow=Selected statements contain a return statement but not all possible execution flows end in a return. - -ExtractMethodAnalyzer.assignments_to_local=Ambiguous return value: selected block contains more than one assignment to local variable. -ExtractMethodAnalyzer.only_method_body=Cannot extract new method from selection. Only statements from a method body can be extracted. -ExtractMethodAnalyzer.after_do_keyword=Selection may not start immediately after the \'do\' keyword. -ExtractMethodAnalyzer.super_or_this=Cannot extract super or this call from constructor. -ExtractMethodAnalyzer.cannot_determine_return_type=Cannot determine expression's return type. Using void instead. -ExtractMethodAnalyzer.branch_mismatch=Selection contains branch statement but corresponding branch target is not selected. -ExtractMethodAnalyzer.parent_mismatch=Not all selected statements are enclosed by the same parent statement. -ExtractMethodAnalyzer.cannot_extract_anonymous_type=Cannot extract the body of a anonymous type declaration. Select whole declaration. -ExtractMethodAnalyzer.cannot_extract_variable_declaration_fragment=Cannot extract a variable declaration fragment. Select whole declaration statement. -ExtractMethodAnalyzer.cannot_extract_for_initializer=Cannot extract initialization part of a for statement. -ExtractMethodAnalyzer.cannot_extract_for_updater=Cannot extract increment part of a for statement. -ExtractMethodAnalyzer.cannot_extract_variable_declaration=Cannot extract parts of a variable declaration. Select whole declaration. -ExtractMethodAnalyzer.cannot_extract_type_reference=Cannot extract a single type reference. -ExtractMethodAnalyzer.cannot_extract_name_in_declaration=Cannot extract the name part of a declaration. -ExtractMethodAnalyzer.ambiguous_return_value=Ambiguous return value: expression, access to local or return statement extracted. -ExtractMethodAnalyzer.compile_errors=The method''s body cannot be analyzed because of compilation errors in method ''{0}''. To perform the operation you will need to fix the errors. -ExtractMethodAnalyzer.leftHandSideOfAssignment=Cannot extract the left hand side of an assignment. -ExtractMethodAnalyzer.single_expression_or_set=Can only extract a single expression or a set of statements. -ExtractMethodAnalyzer.cannot_extract_null_type=Cannot extract null expression. - -ExtractMethodRefactoring.name=Extract Method {0} in {1} -ExtractMethodRefactoring.add_method=add new method {0} -ExtractMethodRefactoring.checking_new_name=Checking new method name -ExtractMethodRefactoring.checking_selection=Checking text selection -ExtractMethodRefactoring.no_set_of_statements=Selection does not mark a set of statements. Only statements from a method body can be extracted. -ExtractMethodRefactoring.substitute_with_call=substitute statement(s) with call to {0} -ExtractMethodRefactoring.change_name=extract method {0} from method {1} -ExtractMethodRefactoring.organize_imports=Organize Imports -ExtractMethodRefactoring.duplicates.single=replace duplicate code fragment with call to {0} -ExtractMethodRefactoring.duplicates.multi=replace duplicate code fragments with call to {0} -ExtractMethodRefactoring.error.nameInUse=''{0}'' is already used as a name in the selected code -ExtractMethodRefactoring.error.sameParameter=A parameter ''{0}'' already exists - -#-- Inline Method ------------------------------------------------------ -InlineMethodRefactoring.name= Inline Method Refactoring -InlineMethodRefactoring.searching= Searching for references... -InlineMethodRefactoring.processing= Processing {0} -InlineMethodRefactoring.edit.inline= Inline invocation -InlineMethodRefactoring.edit.delete= Delete method declaration -InlineMethodRefactoring.edit.inlineCall= Inline Call -InlineMethodRefactoring.edit.import= Update import statements -InlineMethodRefactoring.error.classFile= Can\'t inline method since it is declared in a class file -InlineMethodRefactoring.error.noMethodDeclaration= Unable to resolve corresponding method declaration. -InlineMethodRefactoring.checking.overridden= Checking for overridden methods... -# The there keys below are referenced indirectly by passing a string to a helper -# method. So don't remove them even if they are marked as unused. -InlineMethodRefactoring.checking.overridden.error= Type {0} overrides method to be inlined. -InlineMethodRefactoring.checking.overrides.error= Method to be inlined overrides method from class {0}. -InlineMethodRefactoring.checking.implements.error= Method to be inlined implements method from interface {0}. - -InlineMethodRefactoring.SourceAnalyzer.recursive_call=Method declaration contains recursive call. -InlineMethodRefactoring.SourceAnalyzer.declaration_has_errors=The method declaration contains compile errors. To perform the operation you will need to fix the errors. - -InlineMethodRefactoring.SourceAnalyzer.qualified_this_expressions=Cannot inline a method that uses qualified this expressions. -InlineMethodRefactoring.SourceAnalyzer.syntax_errors=The translation unit containing this method declaration has syntax errors. To perform the operation you will need to fix the errors. -InlineMethodRefactoring.SourceAnalyzer.abstract_methods=Cannot inline abstract methods. - -CallInliner.receiver_type=Can\'t determine receiver\'s type. -CallInliner.execution_flow=Can\'t inline method. Return statement in method declaration interrupts execution flow. -CallInliner.multiDeclaration=Can\'t inline method used as an initializer in a multi fragment variable declaration. -CallInliner.simple_functions=Inlining is only possible on simple functions (consisting of a single return statement), or functions used in an assignment. -CallInliner.field_initializer_simple=In field initializers inlining is only supported for simple functions (e.g. functions consisting of a single return statement). -CallInliner.field_initialize_new_local=Can\'t inline field initializer because new local variable is required. -CallInliner.field_initialize_write_parameter=Can\'t inline field initializer because one of the method parameters is used as an assignment target and will require new local variable. -CallInliner.field_initialize_self_reference=Can\'t inline method. Method references the field to be initialized. -CallInliner.constructors=Can\'t inline a constructor invocation that is used as a class instance creation. - -#-- SEF ------------------------------------------------------ -SelfEncapsulateField.AccessAnalyzer.encapsulate_read_access=Encapsulate read access -SelfEncapsulateField.AccessAnalyzer.encapsulate_write_access=Encapsulate write access -SelfEncapsulateField.AccessAnalyzer.encapsulate_prefix_access=Encapsulate prefix access -SelfEncapsulateField.AccessAnalyzer.encapsulate_postfix_access=Encapsulate postfix access -SelfEncapsulateField.AccessAnalyzer.cannot_convert_postfix_expression=Cannot convert postfix expression. It is used inside another expression. - -SelfEncapsulateField.name=Self Encapsulate Field -SelfEncapsulateField.method_exists=A method ''{0}'' already exists in type ''{1}''. -SelfEncapsulateField.compiler_errors_field=Cannot analyze field ''{0}'' due to the following compiler error: {1} -SelfEncapsulateField.compiler_errors_update={0} contains compiler errors. This may affect field access update. -SelfEncapsulateField.type_not_resolveable=The type of the selected field cannot be resolved. An import statement may be missing. -SelfEncapsulateField.cannot_analyze_selected_field=Cannot analyze selected field ''{0}'' -SelfEncapsulateField.checking_preconditions=Checking preconditions.. -SelfEncapsulateField.searching_for_cunits=Searching for affected translation units... -SelfEncapsulateField.analyzing=Analyzing... -SelfEncapsulateField.create_changes=Create changes -SelfEncapsulateField.change_visibility=Change visibility to private -SelfEncapsulateField.add_setter=Add Setter method -SelfEncapsulateField.add_getter=Add Getter method - -#-- inline temp ------------------------------------------------------ -InlineTempRefactoring.name=Inline local variable -InlineTempRefactoring.syntax_errors=This translation unit contains syntax errors. To perform the operation you will need to fix the errors. -InlineTempRefactoring.select_temp=A local variable declaration or reference must be selected to activate this refactoring. -InlineTempRefactoring.method_parameter=Cannot inline method parameters. -InlineTempRefactoring.exceptions_declared=Cannot inline exceptions declared in \'catch\' clauses. -InlineTempRefactoring.not_initialized=Local variable ''{0}'' is not initialized at declaration. -InlineTempRefactoring.assigned_more_once=Local variable ''{0}'' is assigned more than once. -InlineTempRefactoring.preview=Creating preview -InlineTempRefactoring.inline=Inline local variable -InlineTempRefactoring.inline_edit_name=Inline local variable: -InlineTempRefactoring.remove_edit_name=Remove local variable: -InlineTempRefactoring.Array_vars_initialized=Array variables initialized with constants cannot be inlined. -InlineTempRefactoring.for_initializers=Cannot inline variables declared in the initializer list of a \'for\' statement. - -#-- extract temp ------------------------------------------------------ -ExtractTempRefactoring.name=Extract Local Variable -ExtractTempRefactoring.select_expression=An expression must be selected to activate this refactoring. -ExtractTempRefactoring.syntax_error=This file contains syntax errors. To perform this operation you will need to fix the errors. -ExtractTempRefactoring.explicit_constructor=Code from explicit constructor calls cannot be extracted to a variable. -ExtractTempRefactoring.expression_in_method=An expression used in a method must be selected to activate this refactoring. -ExtractTempRefactoring.no_void=Cannot extract an expression of type \'void\'. -ExtractTempRefactoring.null_literals=Cannot extract single null literals. -ExtractTempRefactoring.array_initializer=Operation not applicable to an array initializer. -ExtractTempRefactoring.assignment=Cannot extract assignment that is part of another expression. -ExtractTempRefactoring.single_conditional_expression=Currently no support to extract a single conditional expression. -ExtractTempRefactoring.convention=This name is discouraged. According to convention, names of local variables should start with lowercase letters. -ExtractTempRefactoring.checking_preconditions=Checking preconditions... -ExtractTempRefactoring.preview=Preparing preview -ExtractTempRefactoring.extract_temp=Extract Temp -ExtractTempRefactoring.update_imports=Update imports -ExtractTempRefactoring.declare_local_variable=Declare local variable -ExtractTempRefactoring.replace=Replace expression with a local variable reference -ExtractTempRefactoring.name_in_new=Cannot extract this name - try selecting the whole instance creation expression. -ExtractTempRefactoring.names_in_declarations=An expression has to be selected to activate this refactoring. Names used in declarations are not expressions. -ExtractTempRefactoring.assigned_to=The selected expression is assigned. Extracting may change the program\'s semantics. -ExtractTempRefactoring.refers_to_for_variable=Cannot extract expression, since it refers to a variable declared in the initializer of the enclosing \'for\' statement. -ExtractTempRefactoring.for_initializer_updater=Cannot extract \'for\' initializer or updater. - -#-- extract constant -------------------------------------------------- -ExtractConstantRefactoring.name=Extract Constant -ExtractConstantRefactoring.select_expression=An expression must be selected to activate this refactoring. -ExtractConstantRefactoring.syntax_error=This file contains syntax errors. To perform this operation you will need to fix the errors. -ExtractConstantRefactoring.declare_constant=Declare constant -ExtractConstantRefactoring.update_imports=Update imports -ExtractConstantRefactoring.replace=Replace expression with a constant reference -ExtractConstantRefactoring.preview=Preparing preview -ExtractConstantRefactoring.field_exists=Field ''{0}'' already exists. -ExtractConstantRefactoring.no_void=Cannot extract an expression of type \'void\'. -ExtractConstantRefactoring.null_literals=Cannot extract single null literals. -ExtractConstantRefactoring.not_load_time_constant=Cannot extract this expression - it is not a valid static constant. -ExtractConstantRefactoring.extract_constant=Extract Constant -ExtractConstantRefactoring.convention=This name is discouraged. According to convention, names of class constants do not contain lowercase letters. -ExtractConstantRefactoring.checking_preconditions=Checking preconditions... -ExtractConstantRefactoring.rename=Rename Constant - -#-- introduce parameter -------------------------------------------------- -IntroduceParameterRefactoring.name=Introduce Parameter -IntroduceParameterRefactoring.introduce_parameter=Introduce Parameter -IntroduceParameterRefactoring.syntax_error=This translation unit contains syntax errors. To perform the operation you will need to fix the errors. -IntroduceParameterRefactoring.select=An expression must be selected to activate this refactoring. -IntroduceParameterRefactoring.expression_in_method=An expression used in a method must be selected to activate this refactoring. -IntroduceParameterRefactoring.no_void=Cannot introduce a parameter from an expression of type \'void\'. -IntroduceParameterRefactoring.duplicate_name=A parameter or local variable with this name already exists. -IntroduceParameterRefactoring.preview=Preparing preview - -IntroduceParameterRefactoring.add_parameter=Add parameter -IntroduceParameterRefactoring.replace=Replace expression with a parameter reference -IntroduceParameterRefactoring.add_argument=Add actual argument expression - - -####################################### -# org.eclipse.jdt.internal.core.refactoring.rename -####################################### -RenameCompilationUnitRefactoring.name=Rename ''{0}'' to ''{1}'' -RenameCompilationUnitRefactoring.not_parsed={0} has syntax errors. No references will be updated if you proceed -RenameCompilationUnitRefactoring.not_parsed_1={0} has syntax errors. -RenameCompilationUnitRefactoring.same_name=The same name chosen - -RenameFieldRefactoring.name=Rename field ''{0}'' to ''{1}'' -RenameFieldRefactoring.hiding=After renaming, the field ''{0}'' will be hidden in the scope of the field ''{1}'' declared in type ''{2}'' -RenameFieldRefactoring.hiding2=After renaming, the field named ''{0}'' declared in type ''{1}'' will be hidden in the scope of the field ''{2}'' -RenameFieldRefactoring.another_name=Choose another name. -RenameFieldRefactoring.checking=Checking preconditions... -RenameFieldRefactoring.field_already_defined=Field with this name is already defined. -RenameFieldRefactoring.searching=Searching for references... -RenameFieldRefactoring.deleted=The selected field has been deleted from ''{0}'' -RenameFieldRefactoring.already_exists=Method ''{0}'' already exists in ''{1}'' -RenameFieldRefactoring.overridden=Method ''{0}'' is overridden or overrides another method -RenameFieldRefactoring.overridden_or_overrides=Method ''{0}'' is overridden or overrides another method -RenameFieldRefactoring.Update_getter_occurrence=Update getter occurrence -RenameFieldRefactoring.Update_setter_occurrence=Update setter occurrence -RenameFieldRefactoring.searching_for_text_matches=searching for text matches -RenameFieldRefactoring.Update_field_declaration=Update field declaration -RenameFieldRefactoring.Update_field_reference=Update field reference -RenameFieldRefactoring.should_start_lowercase=This name is discouraged. According to convention, C instance field names should start with lowercase letters -RenameFieldRefactoring.declared_in_supertype=Cannot be renamed because it is declared in a supertype - -RenamePackageRefactoring.another_name=Choose another name. -RenamePackageRefactoring.checking=Checking preconditions... -RenamePackageRefactoring.creating_change=Preparing preview... -RenamePackageRefactoring.package_exists=Package already exists -RenamePackageRefactoring.searching=Searching for references... -RenamePackageRefactoring.update_reference=update package reference -RenamePackageRefactoring.name=Rename package ''{0}'' to ''{1}'' -RenamePackageRefactoring.aleady_exists=Package ''{0}'' already exists in this project in folder ''{1}'' - -RenameMethodInInterfaceRefactoring.already_defined=A related type declares a method with the new name (and same number of parameters) -RenameMethodInInterfaceRefactoring.special_case=Cannot rename this method because it is a special case (see the language specification section 9.2 for details) - -RenameMethodRefactoring.name=Rename method ''{0}'' to ''{1}'' -RenameMethodRefactoring.no_binary=Related method ''{0}'' (declared in ''{1}'') is binary. Refactoring cannot be performed. -RenameMethodRefactoring.no_native=Renaming native methods will cause an unsatisfied link error on runtime. -RenameMethodRefactoring.no_native_1=Related method ''{0}'' (declared in ''{1}'') is native. Renaming will cause an UnsatisfiedLinkError on runtime. -RenameMethodRefactoring.no_read_only=Related method ''{0}'' (declared in ''{1}'') is read-only. Refactoring cannot be performed. -RenameMethodRefactoring.not_in_model=Related method ''{0}'' (declared in ''{1}'') does not exist in the model. -RenameMethodRefactoring.same_name=This name already exists. - -RenamePrivateMethodRefactoring.hierarchy_defines=''{0}'' or a type in its hierarchy defines a method ''{1}'' with the same number of parameters and same parameter type names. -RenamePrivateMethodRefactoring.hierarchy_defines2=''{0}'' or a type in its hierarchy defines a method ''{1}'' with the same number of parameters, but different parameter type names. -RenamePrivateMethodRefactoring.update=Update method reference - -RenameVirtualMethodRefactoring.requieres_renaming_native=Renaming ''{0}'' requires renaming a native method. Renaming will cause {1} on runtime. -RenameVirtualMethodRefactoring.hierarchy_declares1=Hierarchy declares a method ''{0}'' with the same number of parameters, but different parameter type names. -RenameVirtualMethodRefactoring.hierarchy_declares2=Hierarchy declares a method ''{0}'' with the same number of parameters and same parameter type names. - -RenameMethodRefactoring.update_occurrence=Update method occurrence -RenameMethodRefactoring.update_declaration=Update method declaration -RenameMethodRefactoring.deleted=The selected method has been deleted from ''{0}'' - -RenameTypeRefactoring.checking=Checking preconditions... -RenameTypeRefactoring.choose_another_name=Please choose another name. -RenameTypeRefactoring.creating_change=Preparing preview... -RenameTypeRefactoring.rename_constructor=rename constructor -RenameTypeRefactoring.searching=Searching for references... -RenameTypeRefactoring.update_reference=update element reference -RenameTypeRefactoring.name=Rename ''{0}'' to ''{1}'' -RenameTypeRefactoring.enclosed=Element ''{0}'' is enclosed in a type named ''{1}'' -RenameTypeRefactoring.encloses=Element ''{0}'' encloses a type named ''{1}'' -RenameTypeRefactoring.exists=Type named ''{0}'' already exists in package ''{1}'' -RenameTypeRefactoring.imported=Type named ''{0}'' is imported (single-type-import) in ''{1}'' (a translation unit must not import and declare a type with the same name) -RenameTypeRefactoring.member_type_exists=Another element named ''{0}'' already exists in ''{1}'' -RenameTypeRefactoring.global_member_type_exists=Another element named ''{0}'' already exists in the same element domain. This change might result in compilation errors. -RenameTypeRefactoring.enclosed_type_native=An element enclosed in type ''{0}'' declares a native method. Renaming will cause an unsatisfied link error on runtime. -RenameTypeRefactoring.name_conflict1=Name conflict with element ''{0}'' in ''{1}'' -RenameTypeRefactoring.searching_text=searching for text matches -RenameTypeRefactoring.update=Type declaration update -RenameTypeRefactoring.does_not_exist=Element ''{0}'' does not exist in the saved version of ''{1}'' -RenameTypeRefactoring.will_not_rename=Translation unit will not be renamed -RenameTypeRefactoring.local_type=Local Type declared inside ''{0}'' is named {1} -RenameTypeRefactoring.member_type=Member Type declared inside ''{0}'' is named {1} -RenameTypeRefactoring.another_type=Another type named ''{0} is referenced in ''{1}'' -RenameTypeRefactoring.wrong_element=Rename refactoring does not handle this type of element. -RenameTypeRefactoring.virtual_method=Renaming a virtual method. Consider renaming the base and derived class methods (if any). - - - -TextMatchFinder.comment=text reference update in a comment -TextMatchFinder.string=text reference update in a string literal -TextMatchFinder.searching=searching for text matches in: - -RippleMethodFinder.analizing_hierarchy=analyzing hierarchy - -RefactoringAnalyzeUtil.name_collision=Name collision with name ''{0}'' - -RenameTempRefactoring.must_select_local=A local variable declaration or reference must be selected to activate this refactoring -RenameTempRefactoring.only_in_methods_and_initializers=Only local variables declared in methods and initializers can be renamed -RenameTempRefactoring.lowercase=This name is discouraged. According to convention, local variable names should start with lowercase letters. -RenameTempRefactoring.rename=Rename Local Variable -RenameTempRefactoring.changeName=Rename local variable:''{0}'' to: ''{1}'' - -MethodChecks.overrides=The selected method overrides method ''{0}'' declared in type ''{1}''. -MethodChecks.implements=The selected method is an implementation of method ''{0}'' declared in type ''{1}'' - -RenameCProjectRefactoring.rename=Rename C project ''{0}'' to:''{1}'' -RenameCProjectRefactoring.already_exists=A project with that name already exists -RenameCProjectRefactoring.read_only=Project ''{0}'' is marked as read-only - -RenamePackageRefactoring.searching_text=searching for text matches -RenamePackageRefactoring.Packagered_only=Package ''{0}'' is read-only. -RenamePackageRefactoring.resource_read_only=Resource corresponding to package ''{0}'' is read only. Click ''Continue'' if still you want to rename it. -RenamePackageRefactoring.contains_type=Package ''{0}'' already contains a type named ''{1}'' - -RenameResourceRefactoring.Internal_Error=Internal Error -RenameResourceRefactoring.alread_exists=A file or folder with this name already exists -RenameResourceRefactoring.invalidName=This is an invalid name for a file or folder - -RenameSourceFolderRefactoring.blank=Name must not start or end with a blank -RenameSourceFolderRefactoring.invalid_name=This is an invalid name for a file or folder -RenameSourceFolderRefactoring.already_exists=An element with this name already exists -RenameSourceFolderRefactoring.alread_exists=An element with this name already exists -RenameSourceFolderRefactoring.rename=Rename Source Folder ''{0}'' to ''{1}'' - -################ Rename Processors ######################################### - -RenameResourceProcessor.name=Rename resource ''{0}'' to ''{1}'' - -####################################### -# org.eclipse.jdt.internal.core.refactoring.reorg -####################################### -MoveRefactoring.reorganize_elements=Reorganize elements - -DeleteRefactoring.delete_package_fragment_root= Deleting a package fragment root - -MoveCuUpdateCreator.update_imports=update imports -MoveCuUpdateCreator.searching=Searching for references to types in ''{0}'' -MoveCuUpdateCreator.update_references=update references - -CopyRefactoring.cu.copyOf1=CopyOf{0} -CopyRefactoring.cu.copyOfMore=Copy_{0}_of_{1} -CopyRefactoring.resource.copyOf1=Copy of {0} -CopyRefactoring.resource.copyOfMore=Copy ({0}) of {1} -CopyRefactoring.package.copyOf1={0}.copy -CopyRefactoring.package.copyOfMore={1}.copy{0} - -####################################### -# org.eclipse.jdt.internal.core.refactoring.structure -####################################### -PullUpRefactoring.Pull_Up=Pull Up -PullUpRefactoring.no_interface_members=Pull up is not allowed on interface members -PullUpRefactoring.no_java.lang.Object=Pull up is not allowed on elements declared in java.lang.Object -PullUpRefactoring.no_binary_types=Pull up is not allowed on elements declared in binary types -PullUpRefactoring.no_read_only_types=Pull up is not allowed on elements declared in read-only types -PullUpRefactoring.not_this_type=Pull up is not allowed on elements declared in this type -PullUpRefactoring.final_fields=Pulling up final fields will result in compilation errors if they are not initialized on creation or in constructors -PullUpRefactoring.checking_referenced_elements=Checking referenced elements -PullUpRefactoring.does_not_exist=Element {0} does not exist in the saved version of the file -PullUpRefactoring.type_not_accessible=Type ''{0}'' referenced in one of the pulled elements is not accessible from type ''{1}'' -PullUpRefactoring.field_not_accessible=Field ''{0}'' referenced in one of the pulled elements is not accessible from type ''{1}'' -PullUpRefactoring.method_not_accessible=Method ''{0}'' referenced in one of the pulled elements is not accessible from type ''{1}'' -PullUpRefactoring.different_method_return_type=Method ''{0}'' declared in type''{1}'' has a different return type than its pulled up counterpart, which will result in compile errors if you proceed -PullUpRefactoring.different_field_type=Field ''{0}'' declared in type ''{1}'' has a different type than its pulled up counterpart -PullUpRefactoring.static_method=Method ''{0}'' declared in type ''{1}'' is \'static\', which will result in compile errors if you proceed -PullUpRefactoring.lower_visibility=Method ''{0}'' declared in type ''{1}'' has visibility lower than \'protected\', which will result in compile errors if you proceed -PullUpRefactoring.preview=Preparing preview -PullUpRefactoring.calculating_required=Calculating required members -PullUpRefactoring.gets_instantiated=Class ''{0}'' cannot be made abstract because it gets instantiated -PullUpRefactoring.Field_declared_in_class=Field ''{0}'' is declared in class ''{1}''. Pulling it up may result in changed program semantics. -PullUpRefactoring.methodis_declared_in_class=Method ''{0}'' is declared in class ''{1}''. Pulling it up may result in changed program semantics. -PullUpRefactoring.field_cannot_be_accessed=Field ''{0}'' cannot be accessed from ''{1}'' -PullUpRefactoring.method_cannot_be_accessed=Method ''{0}'' cannot be accessed from ''{1}'' -PullUpRefactoring.Type_declared_in_class=Type ''{0}'' is declared in class ''{1}''. Pulling it up may result in changed program semantics. - -MemberCheckUtil.signature_exists=Method ''{0}'' (with the same signature) already exists in type ''{1}'', which will result in compile errors if you proceed -MemberCheckUtil.same_param_count=Method ''{0}'' (with the same number of parameters) already exists in type ''{1}'' -MemberCheckUtil.field_exists=Field ''{0}'' already exists in type ''{1}'', which will result in compile errors if you proceed -MemberCheckUtil.type_name_conflict0=Nested type ''{0}'' already exists in type ''{1}'', which will result in compile errors if you proceed -MemberCheckUtil.type_name_conflict1=Destination type has the same simple name as ''{0}'', which will result in compile errors if you proceed -MemberCheckUtil.type_name_conflict2=Destination type is enclosed in a type that has same simple name as ''{0}'', which will result in compile errors if you proceed -MemberCheckUtil.type_name_conflict3=Destination type has the same simple name as ''{0}'' (enclosed in ''{1}''), which will result in compile errors if you proceed -MemberCheckUtil.type_name_conflict4=Destination type is enclosed in a type that has same simple name as ''{0}'' (enclosed in ''{1}''), which will result in compile errors if you proceed - -ChangeSignatureRefactoring.modify_Parameters=Change Method Signature -ChangeSignatureRefactoring.restructure_parameters=Restructure parameters -ChangeSignatureRefactoring.checking_preconditions=Checking preconditions... -ChangeSignatureRefactoring.method_deleted=The selected method has been deleted from ''{0}'' -ChangeSignatureRefactoring.native=Method ''{0}'' declared in type ''{1}'' is native. Reordering parameters will cause UnsatisfiedLinkError on runtime if you do not update your native libraries -ChangeSignatureRefactoring.duplicate_name=Duplicate parameter name: {0} - -MoveMembersRefactoring.Move_Members=Move Members -MoveMembersRefactoring.compile_errors=Operation can't be performed due to compile errors in ''{0}''. Please fix errors first. -MoveMembersRefactoring.deleteMembers= delete members -MoveMembersRefactoring.addMembers= add members -MoveMembersRefactoring.referenceUpdate= update reference to moved member -MoveMembersRefactoring.Checking_preconditions=Checking preconditions... -MoveMembersRefactoring.static_declaration=Static members can be declared only in top level or static types. -MoveMembersRefactoring.multi_var_fields=Currently, only field declarations with single variable declaration fragments can be moved. -MoveMembersRefactoring.only_public_static_final=Only ''public static final'' fields with variable initializers can be moved to an interface. -MoveMembersRefactoring.Object=Move is not allowed on members declared in 'java.lang.Object'. -MoveMembersRefactoring.binary=Pull up is not allowed on members of binary types. -MoveMembersRefactoring.read_only=Pull up is not allowed on members of read-only types. -MoveMembersRefactoring.move_members=Move members -MoveMembersRefactoring.not_found=Destination type ''{0}'' not be found -MoveMembersRefactoring.same=Destination and source types are the same (''{0}'') -MoveMembersRefactoring.inside=Destination type ''{1}'' is inside moved member''{0}''. -MoveMembersRefactoring.not_exist=Destination type ''{0}'' does not exist -MoveMembersRefactoring.dest_binary=Destination type ''{0}'' is binary -MoveMembersRefactoring.native=Moved method ''{0}'' is native. You will need to update native libraries. -MoveMembersRefactoring.moved_field=In ''{2}'', moved field ''{0}'' will not be visible from ''{1}'' -MoveMembersRefactoring.accessed_field=Accessed field ''{0}'' will not be visible from ''{1}'' -MoveMembersRefactoring.moved_method=In ''{2}'', moved method ''{0}'' will not be visible from ''{2}'' -MoveMembersRefactoring.accessed_method=Accessed method ''{0}'' will not be visible from ''{1}'' -MoveMembersRefactoring.moved_type=In ''{2}'', moved type ''{0}'' will not be visible from ''{2}'' -MoveMembersRefactoring.accessed_type=Accessed type ''{0}'' will not be visible from ''{1}'' - -MoveRefactoring.scanning_qualified_names=Scanning for qualified names in non C files... - -QualifiedNameFinder.update_name=Update fully qualified name - -####################################### -# org.eclipse.jdt.internal.core.refactoring.surround -####################################### - -SurroundWithTryCatchRefactoring.name=Surround with try/catch Block -SurroundWithTryCatchAnalyzer.doesNotCover=Selection does not cover a set of statements. Extend selection to a valid range using the "Expand Selection With" actions from the Edit menu. -SurroundWithTryCatchAnalyzer.doesNotContain=Selection does not contain statements from a method body or static initializer. -SurroundWithTryCatchAnalyzer.noUncaughtExceptions=No uncaught exceptions are thrown by the selected code. -SurroundWithTryCatchAnalyzer.onlyStatements=Only statements can be surrounded with try/catch blocks. -SurroundWithTryCatchAnalyzer.cannotHandleSuper=Cannot surround a super constructor call. -SurroundWithTryCatchAnalyzer.cannotHandleThis=Cannot surround a constructor invocation. -SurroundWithTryCatchAnalyzer.compile_errors=The selected code cannot be analyzed because of compilation errors. To perform this operation you will need to fix the errors. - -####################################### -# org.eclipse.jdt.internal.core.refactoring.util -####################################### - -CommentAnalyzer.internal_error=Internal error during precondition checking. -CommentAnalyzer.ends_inside_comment=Selection ends inside a comment. -CommentAnalyzer.starts_inside_comment=Selection starts inside a comment. - -StatementAnalyzer.doesNotCover= The selection does not cover a set of statements or an expression. Extend selection to a valid range using the "Expand Selection With" actions from the Edit menu. -StatementAnalyzer.beginning_of_selection=The beginning of the selection contains characters that do not belong to a statement. -StatementAnalyzer.end_of_selection=The end of the selection contains characters that do not belong to a statement. -StatementAnalyzer.do_body_expression=Operation not applicable to a do statement's body and expression. -StatementAnalyzer.for_initializer_expression=Operation not applicable to a for statement's initializer and expression part. -StatementAnalyzer.for_expression_updater=Operation not applicable to a for statement's expression and updater part. -StatementAnalyzer.for_updater_body=Operation not applicable to a for statement's updater and body part. -StatementAnalyzer.catch_argument=Operation is not applicable to a catch block's argument declaration. -StatementAnalyzer.while_expression_body=Operation not applicable to a while statement's expression and body. -StatementAnalyzer.try_statement=Selection must either cover whole try statement or parts of try, catch, or finally block. -StatementAnalyzer.switch_statement=Selection must either cover whole switch statement or parts of a single case block. -StatementAnalyzer.synchronized_statement=Selection must either cover whole synchronized statement or parts of the synchronized block. - -CodeAnalyzer.array_initializer=Operation not applicable to an array initializer. -CElementUtil.initializer=initializer - -####################################### -# other -####################################### -CopyResourceString.copy=Copy resource ''{0}'' to ''{1}'' - -RenameAnalyzeUtil.shadows=Problem in ''{0}''. Another name shadows access to the renamed element -CopyRefactoring.update_ref=Update Type Reference -CopyRefactoring.searching=Searching -CompositeChange.performingChangesTask.name=Performing changes... -CodeRefactoringUtil.error.message=The body of the method ''{0}'' cannot be analyzed because of compilation errors in that method. To perform the operation you will need to fix the errors. -InlineTemRefactoring.error.message.nulLiteralsCannotBeInlined=Null literals cannot be inlined -InlineTemRefactoring.error.message.fieldsCannotBeInlined=Cannot inline fields -RenameMethodRefactoring.taskName.checkingPreconditions=Checking preconditions... -RenameMethodRefactoring.taskName.searchingForReferences=Searching for references... - -PushDownRefactoring.name=Push Down -PushDownRefactoring.no_subclasses=Class ''{0}'' does not have any modifiable non-anonymous subclasses to which members could be pushed down -PushDownRefactoring.not_in_saved=One of the selected members does not exist in the saved version of the file -PushDownRefactoring.interface_members=Pushing down interface members is not supported -PushDownRefactoring.members_of_binary=Pushing down members declared in binary types is not supported -PushDownRefactoring.members_of_read-only=Pushing down members declared in read-only types is not supported -PushDownRefactoring.calculating=Calculating required members -PushDownRefactoring.referenced=Pushed down member ''{0}'' is referenced by ''{1}'' -PushDownRefactoring.checking=Checking referenced elements -PushDownRefactoring.type_not_accessible=Type ''{0}'' referenced in one of the pushed elements is not accessible from type ''{1}'' -PushDownRefactoring.field_not_accessible=Field ''{0}'' referenced in one of the pulled elements is not accessible from type ''{1}'' -PushDownRefactoring.method_not_accessible=Method ''{0}'' referenced in one of the pulled elements is not accessible from type ''{1}'' -PushDownRefactoring.gets_instantiated=Class ''{0}'' cannot be made abstract because it gets instantiated -PushDownRefactoring.preview=Creating preview... -PushDownRefactoring.initializer=initializer -PushDownRefactoring.creating_preview=Creating preview... - -ChangeSignatureRefactoring.invalid_return_type=''{0}'' is not a valid return type name -ChangeSignatureRefactoring.default_value=Enter the default value for parameter ''{0}'' -ChangeSignatureRefactoring.invalid_expression=''{0}'' is not a valid expression -ChangeSignatureRefactoring.parameter_type=Enter the type for parameter ''{0}'' -ChangeSignatureRefactoring.invalid_type_name=''{0}'' is not a valid parameter type name -ChangeSignatureRefactoring.unchanged=Method signature and return type are unchanged. -ChangeSignatureRefactoring.parameter_used=Parameter ''{0}'' is used in method ''{1}'' declared in type ''{2}'' -ChangeSignatureRefactoring.anonymous_subclass=anonymous subclass of ''{0}'' -ChangeSignatureRefactoring.non-virtual=Changing visibility to \'private\' will make this method non-virtual, which may affect the program\'s behavior -ChangeSignatureRefactoring.already_has=Method ''{0}'' already has a parameter named ''{1}'' -ChangeSignatureRefactoring.preview=Preparing preview -ChangeSignatureRefactoring.modify_parameters=Modify parameters -ChangeSignatureRefactoring.not_unique=Parameter type name ''{0}'' cannot be uniquely resolved or is not a valid type name. -ChangeSignatureRefactoring.ambiguous=Parameter type name ''{0}'' is ambiguous. There are {1} types with that name. - -MoveInnerToTopRefactoring.names_start_lowercase=This name is discouraged. According to convention, names of instance fields and local variables start with lowercase letters. -MoveInnerToTopRefactoring.already_declared=A field named ''{0}'' is already declared in type ''{1}'' -MoveInnerToTopRefactoring.deleted=The selected type has been deleted from ''{0}'' -MoveInnerToTopRefactoring.compilation_Unit_exists=Compilation Unit named ''{0}'' already exists in package ''{1}'' -MoveInnerToTopRefactoring.name_used=Name ''{0}'' is used as a parameter name in one of the constructors of type ''{1}'' -MoveInnerToTopRefactoring.name=Move Member Type to New File -MoveInnerToTopRefactoring.creating_preview=Creating change -MoveInnerToTopRefactoring.move_to_Top=Move Member Type to New File -MoveInnerToTopRefactoring.type_exists=Type named ''{0}'' already exists in package ''{1}'' - -InstanceMethodMover.move_method=Move instance method -InstanceMethodMover.replace_with_delegation=Replace method body with delegation. -InstanceMethodMover.create_in_receiver=Create method in new receiver\'s class. -InstanceMethodMover.add_imports=Add needed imports for created method -InstanceMethodMover.to_local_localunsupported=Moving to within local classes is currently unsupported. -InstanceMethodMover.parameter_name_used=Parameter name ''{0}'' is already used -InstanceMethodMover.no_static_methods=This refactoring cannot be used to move static methods. -InstanceMethodMover.single_implementation=Select a single method implementation to move. -InstanceMethodMover.no_native_methods=This refactoring cannot be used to move native methods. -InstanceMethodMover.no_synchronized_methods=This refactoring cannot be used to move synchronized methods. -InstanceMethodMover.no_constructors=This refactoring cannot be used to move a constructor. -InstanceMethodMover.uses_super=The method cannot be moved, since it uses the \"super\" keyword. -InstanceMethodMover.refers_enclosing_instances=The method cannot be moved, since it refers to enclosing instances (i.e. .this). -InstanceMethodMover.potentially_recursive=This refactoring cannot be used to move potentially recursive methods. -InstanceMethodMover.cannot_be_moved=This method cannot be moved, since no possible new receivers were found. An instance method can be moved to source classes that are used as types of its parameters or types of fields declared in the same class as the method. - -ExtractInterfaceUtil.update_reference=Update type reference -ExtractInterfaceUtil.update_imports=Update imports - -ExtractInterfaceRefactoring.deleted=The selected type has been deleted from ''{0}'' -ExtractInterfaceRefactoring.no_Throwable=Extract Interface refactoring is not available on \"java.lang.Throwable\" and its subclasses. -ExtractInterfaceRefactoring.type_exists=Type named ''{0}'' already exists in package ''{1}'' -ExtractInterfaceRefactoring.compilation_Unit_exists=Compilation Unit named ''{0}'' already exists in package ''{1}'' -ExtractInterfaceRefactoring.internal_Error=Internal Error. Please see log for details. -ExtractInterfaceRefactoring.name=Extract Interface -ExtractInterfaceRefactoring.analyzing...=Analyzing... -ExtractInterfaceRefactoring.update_reference=Update type reference -ExtractInterfaceRefactoring.update_type_declaration=Update type declaration - -UseSupertypeWherePossibleRefactoring.deleted=The selected type has been deleted from ''{0}'' -UseSupertypeWherePossibleRefactoring.unavailable_on_Throwable=Use Supertype Where Possible refactoring is not available on \"java.lang.Throwable\" and its subclasses. -UseSupertypeWherePossibleRefactoring.name=Use Supertype Where Possible -UseSupertypeWherePossibleRefactoring.analyzing...=Analyzing... - -MoveInstanceMethodRefactoring.method_declaration=A method declaration must be selected in order to activate this refactoring. -MoveInstanceMethodRefactoring.name=Move Instance Method - -CopyPackageFragmentRootChange.copy=Copy Package Fragment Root ''{0}'' to project ''{1}'' - -DeletePackageFragmentRootChange.delete=Delete package fragment root ''{0}'' - -MovePackageFragmentRootChange.move=Move Package Fragment Root ''{0}'' to project ''{1}'' - -PromoteTempToFieldRefactoring.name=Promote Local Variable to Field -PromoteTempToFieldRefactoring.select_declaration=Select a declaration or a reference to a local variable. -PromoteTempToFieldRefactoring.only_declared_in_methods=Currently, only local variables declared in methods can be converted to fields. -PromoteTempToFieldRefactoring.method_parameters=Cannot convert method parameters to fields. -PromoteTempToFieldRefactoring.exceptions=Cannot convert exceptions declared in catch clauses to fields. -PromoteTempToFieldRefactoring.uses_types_declared_locally=Cannot promote this local variable to a field because it uses types or variables declared locally in the method. -PromoteTempToFieldRefactoring.cannot_promote=Cannot promote this local variable to a field. -PromoteTempToFieldRefactoring.uses_type_declared_locally=Cannot promote this local variable to a field because it uses a type declared locally in the method. -PromoteTempToFieldRefactoring.Name_conflict=Name conflict with name ''{0}'' used in ''{1}'' -PromoteTempToFieldRefactoring.Name_conflict_with_field=Name conflict with existing field -PromoteTempToFieldRefactoring.editName=Promote local variable to field - -ConvertAnonymousToNestedRefactoring.name=Convert Anonymous to Inner -ConvertAnonymousToNestedRefactoring.place_caret=Place the caret inside an anonymous inner class. -ConvertAnonymousToNestedRefactoring.type_exists=Nested type with that name already exists. -ConvertAnonymousToNestedRefactoring.another_name=Choose another name. -ConvertAnonymousToNestedRefactoring.name_hides=Class name hides an enclosing type name. -ConvertAnonymousToNestedRefactoring.edit_name=Convert anonymous inner class to a nested class - -InlineConstantRefactoring.members_declared_in_anonymous=Cannot inline since the initializer to be inlined refers to members declared in an anonymous class scope (currently unsupported). -InlineConstantRefactoring.Inline=Inline Constant -InlineConstantRefactoring.syntax_errors=This file contains syntax errors. To perform this operation you will need to fix the errors. -InlineConstantRefactoring.local_anonymous_unsupported=Inlining of constants defined in local or anonymous classes is currently not supported. -InlineConstantRefactoring.static_final_field=A static final field must be selected. -InlineConstantRefactoring.blank_finals=Inline Constant cannot inline blank finals. -InlineConstantRefactoring.binary_file=Cannot inline this constant, since it is declared in a binary file. -InlineConstantRefactoring.preview=Generating preview ... -InlineConstantRefactoring.inline=Inline Constant -InlineConstantRefactoring.remove_declaration=Remove constant declaration -InlineConstantRefactoring.name=Inline Constant -InlineConstantRefactoring.source_code_unavailable=References in ''{0}'' cannot be inlined since source code is not available - -DeleteFileChange.1=Delete file ''{0}'' - -DeleteFolderChange.0=Delete folder ''{0}'' - -DeleteSourceManipulationChange.0=Delete ''{0}'' -DeleteSourceManipulationChange.1=(default package) - -CopyRefactoring.0=Copy - -MoveRefactoring.0=Move - -OverwriteHelper.0=Confirm overwritting -OverwriteHelper.1=''{0}'' exists in the selected destination. Do you want to overwrite? - -ReadOnlyResourceFinder.0=Confirm Delete of Read Only Elements -ReadOnlyResourceFinder.1=The selected elements contain read-only resources. Do you still want to delete them? -ReadOnlyResourceFinder.2=Confirm Move of Read Only Elements -ReadOnlyResourceFinder.3=The selected elements contain read-only resources. Do you still want to move them? - -ChangeSignatureRefactoring.new_parameter=Enter the type for the new parameter - -MoveInnerToTopRefactoring.29=Creating preview -MoveInnerToTopRefactoring.30=convert nested type to top level -MoveInstanceMethodRefactoring.2=The selected method cannot be moved - -PullUpRefactoring.42=Pull up - -PushDownRefactoring.25=Push down - -ReorgPolicyFactory.doesnotexist0=The selected element cannot be the destination of this operation -ReorgPolicyFactory.readonly=The selected destination is read-only -ReorgPolicyFactory.structure=The structure of the selected destination is not known -ReorgPolicyFactory.inconsistent=The selected destination is not consistent with its underlying resource or buffer -ReorgPolicyFactory.archive=The selected destination is an archive -ReorgPolicyFactory.external=The selected destination is external to the workbench -ReorgPolicyFactory.subCu=Elements inside translation units cannot be used as destinations for copying files, folders or translation units -ReorgPolicyFactory.phantom=The selected destination does not exist or is a phantom resource -ReorgPolicyFactory.inaccessible=The selected destination is not accessible -ReorgPolicyFactory.not_this_resource=The selected resource cannot be used as a destination -ReorgPolicyFactory.linked=Linked resources can only be copied to projects -ReorgPolicyFactory.no_resource=A resource cannot be the destination for the selected elements. -ReorgPolicyFactory.copy=Copy -ReorgPolicyFactory.doesnotexist1=The selected element cannot be the destination for this operation -ReorgPolicyFactory.cannot_modify=The selected destination element cannot be modified -ReorgPolicyFactory.cannot=The selected element cannot be the destination for this operation -ReorgPolicyFactory.package_decl=Package declarations are not available as destinations -ReorgPolicyFactory.src2proj=Source folders can only be copied to C projects -ReorgPolicyFactory.jmodel=The C Model cannot be the destination of this operation -ReorgPolicyFactory.src2writable=Source folders cannot be copied to read-only elements -ReorgPolicyFactory.src2nosrc=Source folders cannot be copied or moved to projects that contain no source folders -ReorgPolicyFactory.packages=Packages can only be moved or copied to source folders or C projects that do not have source folders -ReorgPolicyFactory.cannot1=The selected element cannot be the destination of this operation -ReorgPolicyFactory.noCopying=Copying is not available -ReorgPolicyFactory.element2parent=Elements cannot be moved to their own parents. -ReorgPolicyFactory.package2parent=A package cannot be moved to its own parent. -ReorgPolicyFactory.parent=A file or folder cannot be moved to its own parent. -ReorgPolicyFactory.noMoving=Moving is not available - -ReorgUtils.0=file ''{0}'' -ReorgUtils.1=folder ''{0}'' -ReorgUtils.2=project ''{0}'' -ReorgUtils.3=class file ''{0}'' -ReorgUtils.4=file ''{0}'' -ReorgUtils.5=field ''{0}'' -ReorgUtils.6=the import container -ReorgUtils.7=import declaration ''{0}'' -ReorgUtils.8=the initializer -ReorgUtils.9=C project ''{0}'' -ReorgUtils.10=constructor ''{0}'' -ReorgUtils.11=method ''{0}'' -ReorgUtils.12=package declaration ''{0}'' -ReorgUtils.13=the default package -ReorgUtils.14=package ''{0}'' -ReorgUtils.15=source folder ''{0}'' -ReorgUtils.16=class folder ''{0}'' -ReorgUtils.17=package fragment root ''{0}'' -ReorgUtils.18=type ''{0}'' -ReorgUtils.19=new {0}() '{...'} -ReorgUtils.20=anonymous type ''{0}'' -DeleteChangeCreator.1=Delete elements -DeleteRefactoring.1=Analyzing... -DeleteRefactoring.2=Confirm Referenced Archive Delete -DeleteRefactoring.3=Archive file ''{0}'' is referenced by the following project(s). Do you still want to delete it? -DeleteRefactoring.4=Confirm Folder Delete -DeleteRefactoring.5=Folder ''{0}'' contains a C source folder. Deleting it will delete the source folder as well. Do you still wish to delete it? -DeleteRefactoring.7=Delete -DeleteRefactoring.8=Confirm Delete of Getters/Setters -DeleteRefactoring.9=Do you also want to delete getter/setter methods for field ''{0}''? -MoveStaticMemberAnalyzer.nonStatic=Replacing non-static access to static member with static access - -# -# Introduce Factory -IntroduceFactory.name=Introduce Factory -IntroduceFactory.checkingActivation=Checking activation of IntroduceFactory -IntroduceFactory.syntax_error=Introduce Factory cannot be performed due to syntax errors. -IntroduceFactory.checking_preconditions=Checking preconditions for Introduce Factory... -IntroduceFactory.examiningSelection=Examining selection... -IntroduceFactory.notAConstructorInvocation=Selected entity is not a constructor invocation or definition. -# -IntroduceFactory.noASTNodeForConstructorSearchHit=Can\'t find AST node for constructor search hit @ [''{0}'', ''{1}'']: <''{2}''> in translation unit ''{3}'' -IntroduceFactory.unexpectedInitializerNodeType=Unexpected AST node type for initializer when searching for constructor call: \'''{0}''\' in translation unit ''{1}'' -IntroduceFactory.noConstructorCallNodeInsideFoundVarbleDecl=Couldn\'t find AST node for constructor call inside ''{0}'' -IntroduceFactory.unexpectedASTNodeTypeForConstructorSearchHit=Unexpected AST node type for constructor search hit: ''{0}'' in translation unit ''{1}'' -IntroduceFactory.noBindingForSelectedConstructor=Couldn\'t resolve binding of selected constructor; perhaps a reference to an unknown type. -# -IntroduceFactory.addFactoryMethod=Add factory method -IntroduceFactory.replaceCalls=Replace constructor calls with calls to factory method -IntroduceFactory.protectConstructor=Protect constructor -# -IntroduceFactory.unsupportedNestedTypes=Introduce Factory does not support constructors on nested types. -IntroduceFactory.duplicateMethodName=Duplicate method name: -IntroduceFactory.createChanges=Creating changes for IntroduceFactory -IntroduceFactory.topLevelChangeLabel=Changes to introduce factory for -IntroduceFactory.constructorInBinaryClass=Introduce Factory is not supported when the constructor is in a binary class. -IntroduceFactory.unableToResolveConstructorBinding=Unable to resolve call target; perhaps there are compilation errors? -IntroduceFactory.callSitesInBinaryClass=Constructor call sites in binary classes can not be replaced by factory method calls. -# -# Generalize Type -ChangeTypeRefactoring.Generalize_Type=Generalize Type -ChangeTypeRefactoring.checking_preconditions=Checking preconditions... -ChangeTypeRefactoring.changes=Computing changes -ChangeTypeRefactoring.name=Generalize Type -ChangeTypeRefactoring.cantDoIt=Type of selected declaration cannot be changed -ChangeTypeRefactoring.notSupportedOnNodeType=Generalize Type is only supported on declarations of variables, parameters, and fields, and on method return types. -ChangeTypeRefactoring.notSupportedOnBinary=Generalize Type is not allowed on return types and parameters of methods that override binary methods. -ChangeTypeRefactoring.invalidSelection=Invalid selection for Generalize Type. -ChangeTypeRefactoring.multiDeclarationsNotSupported=Multi-declarations currently not handled. -ChangeTypeRefactoring.noMatchingConstraintVariable=No constraint variable matches the selected ASTNode. -ChangeTypeRefactoring.unhandledSearchException=exception occurred during search: -ChangeTypeRefactoring.failedToSelectType=failed to select type: -ChangeTypeMessages.CreateChangesForChangeType=Creating changes for Generalize Type... -ChangeTypeRefactoring.javaLangObject=java.lang.Object -ChangeTypeRefactoring.arraysNotSupported=Generalize Type is currently not supported on array types. -ChangeTypeRefactoring.localTypesNotSupported=Generalize Type is currently not supported on local types. -ChangeTypeRefactoring.primitivesNotSupported=Generalize Type is not supported on primitive types. -ChangeTypeRefactoring.typeChange=change declared type from -ChangeTypeRefactoring.allChanges=All changes needed for Generalize Type -ChangeTypeRefactoring.to=\ to -ChangeTypeRefactoring.analyzingMessage=Analyzing... diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/rename/RenameElementProcessor.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/rename/RenameElementProcessor.java deleted file mode 100644 index 2daa7e21d88..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/corext/refactoring/rename/RenameElementProcessor.java +++ /dev/null @@ -1,754 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.corext.refactoring.rename; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Set; - -import org.eclipse.cdt.core.model.CModelException; -import org.eclipse.cdt.core.model.CoreModel; -import org.eclipse.cdt.core.model.ICContainer; -import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.cdt.core.model.IEnumeration; -import org.eclipse.cdt.core.model.IEnumerator; -import org.eclipse.cdt.core.model.IField; -import org.eclipse.cdt.core.model.IFunction; -import org.eclipse.cdt.core.model.IFunctionDeclaration; -import org.eclipse.cdt.core.model.IInclude; -import org.eclipse.cdt.core.model.IMacro; -import org.eclipse.cdt.core.model.IMethod; -import org.eclipse.cdt.core.model.IMethodDeclaration; -import org.eclipse.cdt.core.model.INamespace; -import org.eclipse.cdt.core.model.IParent; -import org.eclipse.cdt.core.model.ISourceManipulation; -import org.eclipse.cdt.core.model.ISourceRange; -import org.eclipse.cdt.core.model.ISourceReference; -import org.eclipse.cdt.core.model.IStructure; -import org.eclipse.cdt.core.model.ITranslationUnit; -import org.eclipse.cdt.core.model.IVariable; -import org.eclipse.cdt.core.search.BasicSearchMatch; -import org.eclipse.cdt.core.search.ICSearchConstants; -import org.eclipse.cdt.core.search.ICSearchScope; -import org.eclipse.cdt.core.search.ILineLocatable; -import org.eclipse.cdt.core.search.IMatchLocatable; -import org.eclipse.cdt.core.search.IOffsetLocatable; -import org.eclipse.cdt.core.search.OrPattern; -import org.eclipse.cdt.core.search.SearchEngine; -import org.eclipse.cdt.internal.corext.Assert; -import org.eclipse.cdt.internal.corext.refactoring.Checks; -import org.eclipse.cdt.internal.corext.refactoring.CompositeChange; -import org.eclipse.cdt.internal.corext.refactoring.IReferenceUpdating; -import org.eclipse.cdt.internal.corext.refactoring.RefactoringCoreMessages; -import org.eclipse.cdt.internal.corext.refactoring.RefactoringSearchEngine; -import org.eclipse.cdt.internal.corext.refactoring.RenameProcessor; -import org.eclipse.cdt.internal.corext.refactoring.ResourceUtil; -import org.eclipse.cdt.internal.corext.refactoring.SearchResultGroup; -import org.eclipse.cdt.internal.corext.refactoring.TextChangeManager; -import org.eclipse.cdt.internal.corext.refactoring.base.IChange; -import org.eclipse.cdt.internal.corext.refactoring.base.RefactoringStatus; -import org.eclipse.cdt.internal.corext.util.CModelUtil; -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.OperationCanceledException; -import org.eclipse.core.runtime.SubProgressMonitor; -import org.eclipse.text.edits.ReplaceEdit; - -public class RenameElementProcessor extends RenameProcessor implements IReferenceUpdating{ - private ICElement fCElement = null; - private SearchResultGroup[] fReferences; - private TextChangeManager fChangeManager; - private final String QUALIFIER = "::"; //$NON-NLS-1$ - private final String TELTA = "~"; //$NON-NLS-1$ - - private boolean fUpdateReferences; - - public ICElement getCElement() { - return fCElement; - } - - //---- IRefactoringProcessor --------------------------------------------------- - - /* (non-Javadoc) - * @see org.eclipse.cdt.internal.corext.refactoring.IRefactoringProcessor#initialize(java.lang.Object[]) - */ - public void initialize(Object[] elements) throws CoreException { - Assert.isTrue(elements != null && elements.length == 1); - Object element= elements[0]; - if(element == null) - return; - if (!(element instanceof ISourceReference)) - return; - fCElement= (ICElement)element; - setNewElementName(fCElement.getElementName()); - fUpdateReferences= true; //default is yes - - } - - /* (non-Javadoc) - * @see org.eclipse.cdt.internal.corext.refactoring.IRefactoringProcessor#isAvailable() - */ - public boolean isAvailable() throws CoreException { - if (fCElement == null) - return false; - if (!(fCElement instanceof ISourceReference)) - return false; - if (! Checks.isAvailable(fCElement)) - return false; - return true; - } - /* (non-Javadoc) - * @see org.eclipse.cdt.internal.corext.refactoring.IRefactoringProcessor#getProcessorName() - */ - public String getProcessorName() { - return RefactoringCoreMessages.getFormattedString( - "RenameTypeRefactoring.name", //$NON-NLS-1$ - new String[]{fCElement.getElementName(), fNewElementName}); - } - /* (non-Javadoc) - * @see org.eclipse.cdt.internal.corext.refactoring.IRefactoringProcessor#getElements() - */ - public Object[] getElements() { - return new Object[] {fCElement}; - } - - //---- IRenameProcessor ---------------------------------------------- - /* (non-Javadoc) - * @see org.eclipse.cdt.internal.corext.refactoring.IRenameProcessor#getCurrentElementName() - */ - public String getCurrentElementName() { - if(fCElement == null) - return ""; //$NON-NLS-1$ - String name = fCElement.getElementName(); - if (name.indexOf(QUALIFIER) != -1){ - return (name.substring(name.lastIndexOf(QUALIFIER) + 2, name.length())); - } - return name; - } - - private int getCurrentElementNameLength() { - if(fCElement == null) - return 0; - String name = fCElement.getElementName(); - if (name.indexOf(QUALIFIER) != -1){ - String unQualifiedName =name.substring(name.lastIndexOf(QUALIFIER) + 2, name.length()); - return (unQualifiedName.length()); - } - return name.length(); - } - - private int getCurrentElementNameStartPos() { - if (fCElement == null) - return 0; - try { - String name = fCElement.getElementName(); - ISourceReference sourceRef = (ISourceReference)fCElement; - ISourceRange range = sourceRef.getSourceRange(); - if (name.indexOf(QUALIFIER) != -1) { - return range.getIdStartPos() + name.lastIndexOf(QUALIFIER) + 2; - } - return range.getIdStartPos(); - } catch (CModelException e) { - // - } - return 0; - } - - private String getElementQualifiedName(ICElement element) throws CModelException{ - if(!eligibleForRefactoring(element)){ - return ""; //$NON-NLS-1$ - } else { - StringBuffer name = new StringBuffer(); - if(element instanceof IFunctionDeclaration){ - IFunctionDeclaration function = (IFunctionDeclaration)element; - if((element instanceof IMethodDeclaration) && ( ((IMethodDeclaration)element).isFriend() )){ - // go up until you hit a namespace or a translation unit. - ICElement parent = (ICElement) element.getParent(); - while (!(parent instanceof INamespace) && (!(parent instanceof ITranslationUnit) )){ - parent = parent.getParent(); - } - name.append(getElementQualifiedName(parent)); - }else { - // add the whole signature - name.append(getElementQualifiedName(element.getParent())); - } - name.append("::"); //$NON-NLS-1$ - name.append(function.getSignature()); - } else { - if (element instanceof IEnumerator) { - IEnumeration enum1 = (IEnumeration) element.getParent(); - name.append(getElementQualifiedName(enum1.getParent())); - }else { - name.append(getElementQualifiedName(element.getParent())); - } - name.append("::"); //$NON-NLS-1$ - name.append(element.getElementName()); - } - return name.toString(); - } - } - public RefactoringStatus checkNewElementName(String newName) throws CModelException{ - if (!eligibleForRefactoring(fCElement)) { - return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.getString("RenameTypeRefactoring.wrong_element")); //$NON-NLS-1$ - } - - Assert.isNotNull(newName, "new name"); //$NON-NLS-1$ - - RefactoringStatus result= null; - if (fCElement instanceof IStructure){ - result= Checks.checkClassName(newName); - } - else if ((fCElement instanceof IMethodDeclaration) || (fCElement instanceof IFunctionDeclaration)){ - result= Checks.checkMethodName(newName); - } - else if (fCElement instanceof IField){ - result= Checks.checkFieldName(newName); - } - else { - result = Checks.checkIdentifier(newName); - } - - if (!(fCElement instanceof IFunctionDeclaration)){ - if(checkSiblingsCollision(true).hasError()){ - String msg= RefactoringCoreMessages.getFormattedString("RenameTypeRefactoring.member_type_exists", //$NON-NLS-1$ - new String[]{fNewElementName, fCElement.getParent().getElementName()}); - result.addFatalError(msg); - } - } - - if( fCElement instanceof IMethodDeclaration){ - IMethodDeclaration method = (IMethodDeclaration)fCElement; - if (method.isVirtual()){ - String msg= RefactoringCoreMessages.getFormattedString("RenameTypeRefactoring.virtual_method", //$NON-NLS-1$ - new String[]{fNewElementName, fCElement.getParent().getElementName()}); - result.addWarning(msg); - } - } - - if (Checks.isAlreadyNamed(fCElement, newName)) - result.addFatalError(RefactoringCoreMessages.getString("RenameTypeRefactoring.choose_another_name")); //$NON-NLS-1$ - - return result; - } - //---- IReferenceUpdating -------------------------------------- - - /* (non-Javadoc) - * @see org.eclipse.cdt.internal.corext.refactoring.IReferenceUpdating#canEnableUpdateReferences() - */ - public boolean canEnableUpdateReferences() { - return true; - } - - /* (non-Javadoc) - * @see org.eclipse.cdt.internal.corext.refactoring.IReferenceUpdating#getUpdateReferences() - */ - public boolean getUpdateReferences() { - return fUpdateReferences; - } - - /* (non-Javadoc) - * @see org.eclipse.cdt.internal.corext.refactoring.IReferenceUpdating#setUpdateReferences(boolean) - */ - public void setUpdateReferences(boolean update){ - fUpdateReferences= update; - } - //------------------------------------------ - - /* (non-Javadoc) - * @see org.eclipse.cdt.internal.corext.refactoring.ITextUpdating#canEnableTextUpdating() - */ - public boolean canEnableTextUpdating() { - return false; - } - - - - /* (non-Javadoc) - * @see org.eclipse.cdt.internal.corext.refactoring.IRefactoringProcessor#checkActivation() - */ - public RefactoringStatus checkActivation() throws CoreException { - //RefactoringStatus result= null; - if (!eligibleForRefactoring(fCElement)) { - return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.getString("RenameTypeRefactoring.wrong_element")); //$NON-NLS-1$ - } - return Checks.checkIfTuBroken(fCElement); - - } - - /* (non-Javadoc) - * @see org.eclipse.cdt.internal.corext.refactoring.IRefactoringProcessor#checkInput(org.eclipse.core.runtime.IProgressMonitor) - */ - public RefactoringStatus checkInput(IProgressMonitor pm) - throws CoreException { - Assert.isNotNull(fCElement, "type"); //$NON-NLS-1$ - Assert.isNotNull(fNewElementName, "newName"); //$NON-NLS-1$ - RefactoringStatus result= new RefactoringStatus(); - try{ - pm.beginTask("", 20); //$NON-NLS-1$ - pm.setTaskName(RefactoringCoreMessages.getString("RenameTypeRefactoring.checking"));//$NON-NLS-1$ - result.merge(checkNewElementName(fNewElementName)); - - if (result.hasFatalError()) - return result; - pm.worked(5); - - result.merge(Checks.checkIfTuBroken(fCElement)); - if (result.hasFatalError()) - return result; - pm.worked(1); - - result.merge(checkEnclosingElements()); - pm.worked(1); - - result.merge(checkEnclosedElements()); - pm.worked(1); - - result.merge(checkSiblingsCollision(false)); - pm.worked(1); - - if (result.hasFatalError()) - return result; - - fReferences= null; - pm.setTaskName(RefactoringCoreMessages.getString("RenameTypeRefactoring.searching")); //$NON-NLS-1$ - fReferences= getReferences(getElementQualifiedName(fCElement), new SubProgressMonitor(pm, 35), fUpdateReferences); - pm.worked(6); - - result.merge(analyzeAffectedTranslationUnits()); - - pm.setTaskName(RefactoringCoreMessages.getString("RenameTypeRefactoring.checking")); //$NON-NLS-1$ - if (pm.isCanceled()) - throw new OperationCanceledException(); - - if (result.hasFatalError()) - return result; - - // more checks go here - fChangeManager= createChangeManager(new SubProgressMonitor(pm, 35)); - pm.worked(5); - - return result; - } finally { - pm.done(); - } - } - - /* (non-Javadoc) - * @see org.eclipse.cdt.internal.corext.refactoring.IRefactoringProcessor#createChange(org.eclipse.core.runtime.IProgressMonitor) - */ - public IChange createChange(IProgressMonitor pm) throws CoreException { - pm.beginTask(RefactoringCoreMessages.getString("RenameTypeRefactoring.creating_change"), 4); //$NON-NLS-1$ - CompositeChange builder= new CompositeChange( - RefactoringCoreMessages.getString("Change.javaChanges")); //$NON-NLS-1$ - builder.addAll(fChangeManager.getAllChanges()); - pm.worked(1); - return builder; - } - - private IFile[] getAllFilesToModify() throws CoreException { - List result= new ArrayList(); - result.addAll(Arrays.asList(ResourceUtil.getFiles(fChangeManager.getAllTranslationUnits()))); - return (IFile[]) result.toArray(new IFile[result.size()]); - } - - private TextChangeManager createChangeManager(IProgressMonitor pm) throws CoreException { - try{ - pm.beginTask("", 7); //$NON-NLS-1$ - TextChangeManager manager= new TextChangeManager(); - - addReferenceUpdates(manager, new SubProgressMonitor(pm, 3)); - - pm.worked(1); - - // now both declarations and references are searched for in references - //addTypeDeclarationUpdate(manager); - pm.worked(1); - - return manager; - } finally{ - pm.done(); - } - } - - private void addReferenceUpdates(TextChangeManager manager, IProgressMonitor pm) throws CoreException { - pm.beginTask("", fReferences.length); //$NON-NLS-1$ - for (int i= 0; i < fReferences.length; i++){ - IResource res= fReferences[i].getResultGroupResource(); - if (res == null) - continue; - ITranslationUnit cu= (ITranslationUnit) CoreModel.getDefault().create(res); - if (cu == null) - continue; - - ITranslationUnit tu = CModelUtil.toWorkingCopy(cu); - - if(tu == null) - return; - ITranslationUnit wc = tu; - String name= RefactoringCoreMessages.getString("RenameTypeRefactoring.update_reference"); //$NON-NLS-1$ - BasicSearchMatch[] results= fReferences[i].getSearchResults(); - - for (int j= 0; j < results.length; j++){ - BasicSearchMatch searchResult= results[j]; - int oldNameLength = getCurrentElementNameLength(); - IMatchLocatable locatable =searchResult.getLocatable(); - //Refactoring will only work with offsets, so any matches - //returning lines shall be skipped - int endOffset=0; - if (locatable instanceof IOffsetLocatable){ - endOffset=((IOffsetLocatable)locatable).getNameEndOffset(); - } else if (locatable instanceof ILineLocatable){ - endOffset=((ILineLocatable)locatable).getEndLine(); - } - - int offset= endOffset - oldNameLength; - manager.get(wc).addTextEdit(name, - new ReplaceEdit(offset, oldNameLength, fNewElementName)); - } - pm.worked(1); - } - } - - private void addTypeDeclarationUpdate(TextChangeManager manager) throws CoreException { - String name= RefactoringCoreMessages.getString("RenameTypeRefactoring.update"); //$NON-NLS-1$ - if(fCElement instanceof ISourceReference){ - ITranslationUnit cu= ((ISourceReference)fCElement).getTranslationUnit(); // WorkingCopyUtil.getWorkingCopyIfExists(fCElement.getTranslationUnit()); - manager.get(cu).addTextEdit(name, new ReplaceEdit(getCurrentElementNameStartPos(), getCurrentElementNameLength(), fNewElementName)); - } - } - - private SearchResultGroup[] getReferences(String searchPrefix, IProgressMonitor pm, boolean updateReferences) throws CoreException { - return RefactoringSearchEngine.search(pm, createRefactoringScope(), createSearchPattern(searchPrefix, updateReferences)); - } - - private ICSearchScope createRefactoringScope() throws CoreException { - ICElement[] projectScopeElement = new ICElement[1]; - projectScopeElement[0] = fCElement.getCProject(); - ICSearchScope scope = SearchEngine.createCSearchScope(projectScopeElement, true); - return scope; - } - - private OrPattern createSearchPattern(String searchPrefix, boolean updateReferences) throws CoreException { - OrPattern orPattern = new OrPattern(); - if(fCElement instanceof IStructure){ - if(updateReferences){ - orPattern.addPattern(SearchEngine.createSearchPattern( searchPrefix, - ICSearchConstants.TYPE, ICSearchConstants.ALL_OCCURRENCES, false )); - }else { - orPattern.addPattern(SearchEngine.createSearchPattern( searchPrefix, - ICSearchConstants.TYPE, ICSearchConstants.DECLARATIONS, false )); - orPattern.addPattern(SearchEngine.createSearchPattern( searchPrefix, - ICSearchConstants.TYPE, ICSearchConstants.DEFINITIONS, false )); - } - IStructure structure = (IStructure) fCElement; - orPattern.addPattern(SearchEngine.createSearchPattern( searchPrefix + QUALIFIER + structure.getElementName(), - ICSearchConstants.METHOD, ICSearchConstants.ALL_OCCURRENCES, false )); - orPattern.addPattern(SearchEngine.createSearchPattern( searchPrefix + QUALIFIER + TELTA + structure.getElementName(), - ICSearchConstants.METHOD, ICSearchConstants.ALL_OCCURRENCES, false )); - } - else if(fCElement instanceof IMethod){ - if(updateReferences){ - orPattern.addPattern(SearchEngine.createSearchPattern( searchPrefix, - ICSearchConstants.METHOD, ICSearchConstants.ALL_OCCURRENCES, false )); - }else { - orPattern.addPattern(SearchEngine.createSearchPattern( searchPrefix, - ICSearchConstants.METHOD, ICSearchConstants.DEFINITIONS, false )); - - // The inline declaration is the same as the definition - // we don't need to search for the definition if it is inline -/* ICElement parent = fCElement.getParent(); - if( (!(((IMethod)fCElement).isInline())) && (!(parent instanceof IStructure )) ) { - orPattern.addPattern(SearchEngine.createSearchPattern( searchPrefix, - ICSearchConstants.METHOD, ICSearchConstants.DECLARATIONS, false )); - } - orPattern.addPattern(SearchEngine.createSearchPattern( searchPrefix, - ICSearchConstants.METHOD, ICSearchConstants.REFERENCES, false )); -*/ } - - } - else if(fCElement instanceof IMethodDeclaration){ - if(updateReferences){ - orPattern.addPattern(SearchEngine.createSearchPattern( searchPrefix, - ICSearchConstants.METHOD, ICSearchConstants.ALL_OCCURRENCES, false )); - }else { - orPattern.addPattern(SearchEngine.createSearchPattern( searchPrefix, - ICSearchConstants.METHOD, ICSearchConstants.DECLARATIONS, false )); - } - } - else if(fCElement instanceof IFunction){ - if(updateReferences){ - orPattern.addPattern(SearchEngine.createSearchPattern( searchPrefix, - ICSearchConstants.FUNCTION, ICSearchConstants.ALL_OCCURRENCES, false )); - orPattern.addPattern(SearchEngine.createSearchPattern( searchPrefix, - ICSearchConstants.METHOD, ICSearchConstants.ALL_OCCURRENCES, false )); - }else { - orPattern.addPattern(SearchEngine.createSearchPattern( searchPrefix, - ICSearchConstants.FUNCTION, ICSearchConstants.DECLARATIONS_DEFINITIONS, false )); - } - } - else if(fCElement instanceof IFunctionDeclaration){ - if(updateReferences){ - orPattern.addPattern(SearchEngine.createSearchPattern( searchPrefix, - ICSearchConstants.FUNCTION, ICSearchConstants.ALL_OCCURRENCES, false )); - }else { - orPattern.addPattern(SearchEngine.createSearchPattern( searchPrefix, - ICSearchConstants.FUNCTION, ICSearchConstants.DECLARATIONS, false )); - } - } - else if(fCElement instanceof IEnumeration){ - if(updateReferences){ - orPattern.addPattern(SearchEngine.createSearchPattern( searchPrefix, - ICSearchConstants.ENUM, ICSearchConstants.ALL_OCCURRENCES, false )); - }else { - orPattern.addPattern(SearchEngine.createSearchPattern( searchPrefix, - ICSearchConstants.ENUM, ICSearchConstants.DECLARATIONS_DEFINITIONS, false )); - } - } - else if(fCElement instanceof IEnumerator){ - if(updateReferences){ - orPattern.addPattern(SearchEngine.createSearchPattern( searchPrefix, - ICSearchConstants.ENUMTOR, ICSearchConstants.ALL_OCCURRENCES, false )); - }else { - orPattern.addPattern(SearchEngine.createSearchPattern( searchPrefix, - ICSearchConstants.ENUMTOR, ICSearchConstants.DECLARATIONS_DEFINITIONS, false )); - } - } - else if(fCElement instanceof IField){ - if(updateReferences){ - orPattern.addPattern(SearchEngine.createSearchPattern( searchPrefix, - ICSearchConstants.FIELD, ICSearchConstants.ALL_OCCURRENCES, false )); - }else { - orPattern.addPattern(SearchEngine.createSearchPattern( searchPrefix, - ICSearchConstants.FIELD, ICSearchConstants.DECLARATIONS_DEFINITIONS, false )); - } - } - else if(fCElement instanceof IVariable){ - if(updateReferences){ - orPattern.addPattern(SearchEngine.createSearchPattern( searchPrefix, - ICSearchConstants.VAR, ICSearchConstants.ALL_OCCURRENCES, false )); - }else { - orPattern.addPattern(SearchEngine.createSearchPattern( searchPrefix, - ICSearchConstants.VAR, ICSearchConstants.DECLARATIONS_DEFINITIONS, false )); - } - } - else if(fCElement instanceof INamespace){ - if(updateReferences){ - orPattern.addPattern(SearchEngine.createSearchPattern( searchPrefix, - ICSearchConstants.NAMESPACE, ICSearchConstants.ALL_OCCURRENCES, false )); - }else { - orPattern.addPattern(SearchEngine.createSearchPattern( searchPrefix, - ICSearchConstants.NAMESPACE, ICSearchConstants.DECLARATIONS_DEFINITIONS, false )); - } - } - else { - if(updateReferences){ - orPattern.addPattern(SearchEngine.createSearchPattern( searchPrefix, - ICSearchConstants.UNKNOWN_SEARCH_FOR, ICSearchConstants.ALL_OCCURRENCES, false )); - }else { - orPattern.addPattern(SearchEngine.createSearchPattern( searchPrefix, - ICSearchConstants.UNKNOWN_SEARCH_FOR, ICSearchConstants.DECLARATIONS, false )); - - } - } - return orPattern; - } - - private RefactoringStatus checkEnclosedElements() throws CoreException { - ICElement enclosedElement= findEnclosedElements(fCElement, fNewElementName); - if (enclosedElement == null) - return null; - String msg= RefactoringCoreMessages.getFormattedString("RenameTypeRefactoring.encloses", //$NON-NLS-1$ - new String[]{fCElement.getElementName(), fNewElementName}); - return RefactoringStatus.createErrorStatus(msg); - } - - private RefactoringStatus checkEnclosingElements() throws CoreException { - ICElement enclosingElement= findEnclosingElements(fCElement, fNewElementName); - if (enclosingElement == null) - return null; - - String msg= RefactoringCoreMessages.getFormattedString("RenameTypeRefactoring.enclosed",//$NON-NLS-1$ - new String[]{fCElement.getElementName(), fNewElementName}); - return RefactoringStatus.createErrorStatus(msg); - } - - private static ICElement findEnclosedElements(ICElement element, String newName) throws CoreException { - if(element instanceof IParent){ - ICElement[] enclosedTypes= ((IParent)element).getChildren(); - for (int i= 0; i < enclosedTypes.length; i++){ - if (newName.equals(enclosedTypes[i].getElementName()) || findEnclosedElements(enclosedTypes[i], newName) != null) - return enclosedTypes[i]; - } - } - return null; - } - - private static ICElement findEnclosingElements(ICElement element, String newName) { - ICElement enclosing= element.getParent(); - while ((enclosing != null) && (!(enclosing instanceof ITranslationUnit))){ - if (newName.equals(enclosing.getElementName())) - return enclosing; - else - enclosing= enclosing.getParent(); - } - return null; - } - - private boolean isTopLevelStructure(ICElement element){ - if(element instanceof IStructure){ - ICElement parent = element.getParent(); - while (!(parent instanceof ITranslationUnit)){ - if(parent instanceof IStructure) - return false; - parent = parent.getParent(); - } - return true; - } - return false; - } - - private ICElement[] getSiblings(ICElement element, boolean localSiblings) throws CModelException{ - // only for top level structures - if ((localSiblings) || (!isTopLevelStructure(element))){ - ICElement[] siblings= ((IParent)fCElement.getParent()).getChildren(); - return siblings; - } - else { - Set siblingsSet = new HashSet(); - - ICElement parent = element.getParent(); - int level = 1; - boolean folderIsFound = false; - while (!folderIsFound) { - if (parent instanceof ICContainer){ - folderIsFound = true; - break; - } - parent = parent.getParent(); - level++; - } - // now we are at the first folder or project container - // get siblings at level = level - Set parentsSet = new HashSet(); - Set childrenSet = new HashSet(); - ICElement[] pr =((IParent)parent).getChildren(); - // add all translation unit children but not subfolders - for (int i =0; i < pr.length; i++){ - if(!(pr[i] instanceof ICContainer)) - parentsSet.add(pr[i]); - } - // compare to elements in added translation units. - int currentLevel = 1; - while (currentLevel < level) { - Iterator itr = parentsSet.iterator(); - while (itr.hasNext()){ - Object o = itr.next(); - if(o instanceof ISourceManipulation) { - ICElement p = (ICElement)o; - if(p instanceof IParent){ - ICElement[] ch = ((IParent)p).getChildren(); - for (int i = 0; i < ch.length; i++){ - childrenSet.add(ch[i]); - } - } - } - } - currentLevel++; - if (currentLevel < level){ - parentsSet.clear(); - parentsSet.addAll(childrenSet); - childrenSet.clear(); - } - } - return (ICElement[])childrenSet.toArray(new ICElement[childrenSet.size()]); - } - } - - private RefactoringStatus checkSiblingsCollision(boolean localSiblings) { - RefactoringStatus result= new RefactoringStatus(); - try { - // get the siblings of the CElement and check if it has the same name - ICElement[] siblings = getSiblings(fCElement, localSiblings); - for (int i = 0; i IChangeExceptionHandler
      which - * always aborts an change if an exception is caught. - */ -public class AbortChangeExceptionHandler implements IChangeExceptionHandler { - - public void handle(ChangeContext context, IChange change, Exception e) { - CUIPlugin.getDefault().log(e); - throw new ChangeAbortException(e); - } -} diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/ChangeElement.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/ChangeElement.java deleted file mode 100644 index a5bdaec9234..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/ChangeElement.java +++ /dev/null @@ -1,94 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.refactoring; - -import org.eclipse.core.runtime.CoreException; - -/** - * Instances of ChangeElement are used to present - * IChange object as nodes in a tree. - */ -abstract class ChangeElement { - - /** Flag indicating that the change element isn't active */ - public final static int INACTIVE= 0; - /** Flag indicating that the change element is partly active (some children are inactive) */ - public final static int PARTLY_ACTIVE= 1; - /** Flage indicating that the change element is active */ - public final static int ACTIVE= 2; - - protected final static int[][] ACTIVATION_TABLE= new int[][] { - /*INACTIVE*/ /*PARTLY_ACTIVE */ /*ACTIVE */ - /* INACTIVE */ { INACTIVE, PARTLY_ACTIVE, PARTLY_ACTIVE }, - /* PARTLY_ACTIVE*/{ PARTLY_ACTIVE, PARTLY_ACTIVE, PARTLY_ACTIVE }, - /* ACTIVE */ { PARTLY_ACTIVE, PARTLY_ACTIVE, ACTIVE} - }; - - protected static final ChangeElement[] EMPTY_CHILDREN= new ChangeElement[0]; - - private ChangeElement fParent; - - /** - * Creates a new ChangeElement with the - * given parent - * - * @param parent the change element's parent or null - * if the change element doesn't have a parent - */ - public ChangeElement(ChangeElement parent) { - fParent= parent; - } - - /** - * Returns the change element's parent. - * - * @return the change element's parent - */ - public ChangeElement getParent() { - return fParent; - } - - /** - * Returns the viewer used to present a preview of this change element - * - * @return the viewer suitable to present a preview of this change or - * null if no previewer is configured. - */ -// public abstract ChangePreviewViewerDescriptor getChangePreviewViewer() throws CoreException; - - public abstract void feedInput(IChangePreviewViewer viewer) throws CoreException; - - /** - * Sets the activation status for this ChangeElement. When a - * change element is not active, then executing it is expected to do nothing. - * - * @param active the activation status for this change element - */ - public abstract void setActive(boolean active); - - /** - * Returns the activation status of this ChangeElement. - * Returns one of the following values: IChange.ACTIVE - * if the node and all its children are active, IChange.INACTIVE - * if all children and the node itself is inactive, and IChange.PARTLy_ACTIVE - * otherwise. - * - * @return the change element's activation status. - */ - public abstract int getActive(); - - /** - * Returns the change element's children. - * - * @return the change element's children. - */ - public abstract ChangeElement[] getChildren(); -} diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/ChangeElementContentProvider.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/ChangeElementContentProvider.java deleted file mode 100644 index 8ba5a44ea1b..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/ChangeElementContentProvider.java +++ /dev/null @@ -1,231 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.refactoring; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.List; -import java.util.Map; - -import org.eclipse.cdt.core.model.CModelException; -import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.cdt.core.model.IParent; -import org.eclipse.cdt.core.model.ISourceRange; -import org.eclipse.cdt.core.model.ISourceReference; -import org.eclipse.cdt.core.model.ITranslationUnit; -import org.eclipse.cdt.internal.corext.refactoring.base.IChange; -import org.eclipse.cdt.internal.corext.refactoring.base.ICompositeChange; -import org.eclipse.cdt.internal.corext.refactoring.changes.TextChange; -import org.eclipse.cdt.internal.corext.refactoring.changes.TextChange.EditChange; -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.Region; -import org.eclipse.jface.viewers.ITreeContentProvider; -import org.eclipse.jface.viewers.Viewer; - -/** - * A default content provider to present a hierarchy of IChange - * objects in a tree viewer. - */ -class ChangeElementContentProvider implements ITreeContentProvider { - - private static final ChangeElement[] EMPTY_CHILDREN= new ChangeElement[0]; - - private static class OffsetComparator implements Comparator { - public int compare(Object o1, Object o2) { - EditChange c1= (EditChange)o1; - EditChange c2= (EditChange)o2; - int p1= getOffset(c1); - int p2= getOffset(c2); - if (p1 < p2) - return -1; - if (p1 > p2) - return 1; - // same offset - return 0; - } - private int getOffset(EditChange edit) { - return edit.getTextRange().getOffset(); - } - } - - /* non Java-doc - * @see ITreeContentProvider#inputChanged - */ - public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { - // do nothing - } - - /* non Java-doc - * @see ITreeContentProvider#getChildren - */ - public Object[] getChildren(Object o) { - ChangeElement element= (ChangeElement)o; - ChangeElement[] children= element.getChildren(); - if (children == null) { - children= createChildren(element); - } - return children; - } - - /* non Java-doc - * @see ITreeContentProvider#getParent - */ - public Object getParent(Object element){ - return ((ChangeElement)element).getParent(); - } - - /* non Java-doc - * @see ITreeContentProvider#hasChildren - */ - public boolean hasChildren(Object element){ - Object[] children= getChildren(element); - return children != null && children.length > 0; - } - - /* non Java-doc - * @see ITreeContentProvider#dispose - */ - public void dispose(){ - } - - /* non Java-doc - * @see ITreeContentProvider#getElements - */ - public Object[] getElements(Object element){ - return getChildren(element); - } - - private ChangeElement[] createChildren(ChangeElement object) { - ChangeElement[] result= EMPTY_CHILDREN; - if (!(object instanceof DefaultChangeElement)) - return result; - - DefaultChangeElement changeElement= (DefaultChangeElement)object; - IChange change= changeElement.getChange(); - if (change instanceof ICompositeChange) { - IChange[] children= ((ICompositeChange)change).getChildren(); - result= new ChangeElement[children.length]; - for (int i= 0; i < children.length; i++) { - result[i]= new DefaultChangeElement(changeElement, children[i]); - } - } -//////////////// -// else if (change instanceof TranslationUnitChange) { -// List children= new ArrayList(5); -// TranslationUnitChange cunitChange= (TranslationUnitChange)change; -// ITranslationUnit cunit= cunitChange.getTranslationUnit(); -// Map map= new HashMap(20); -// EditChange[] changes=getSortedTextEditChanges(cunitChange); -// for (int i= 0; i < changes.length; i++) { -// EditChange tec= changes[i]; -// try { -// ICElement element= getModifiedCElement(tec, cunit); -// if (element.equals(cunit)) { -// children.add(new TextEditChangeElement(changeElement, tec)); -// } else { -// PseudoCChangeElement pjce= getChangeElement(map, element, children, changeElement); -// pjce.addChild(new TextEditChangeElement(pjce, tec)); -// } -// } catch (CModelException e) { -// children.add(new TextEditChangeElement(changeElement, tec)); -// } -// } -// result= (ChangeElement[]) children.toArray(new ChangeElement[children.size()]); -// } -// else if (change instanceof TextChange) { -// EditChange[] changes= getSortedTextEditChanges((TextChange)change); -// result= new ChangeElement[changes.length]; -// for (int i= 0; i < changes.length; i++) { -// result[i]= new TextEditChangeElement(changeElement, changes[i]); -// } -// } -/////////// - changeElement.setChildren(result); - return result; - } - - private EditChange[] getSortedTextEditChanges(TextChange change) { - EditChange[] edits= change.getTextEditChanges(); - List result= new ArrayList(edits.length); - for (int i= 0; i < edits.length; i++) { - if (!edits[i].isEmpty()) - result.add(edits[i]); - } - Comparator comparator= new OffsetComparator(); - Collections.sort(result, comparator); - return (EditChange[])result.toArray(new EditChange[result.size()]); - } - - private PseudoCChangeElement getChangeElement(Map map, ICElement element, List children, ChangeElement cunitChange) { - PseudoCChangeElement result= (PseudoCChangeElement)map.get(element); - if (result != null) - return result; - ICElement parent= element.getParent(); - if (parent instanceof ITranslationUnit) { - result= new PseudoCChangeElement(cunitChange, element); - children.add(result); - map.put(element, result); - } else { - PseudoCChangeElement parentChange= getChangeElement(map, parent, children, cunitChange); - result= new PseudoCChangeElement(parentChange, element); - parentChange.addChild(result); - map.put(element, result); - } - return result; - } - - private ICElement getModifiedCElement(EditChange edit, ITranslationUnit cunit) throws CModelException { - IRegion range= edit.getTextRange(); - if (range.getOffset() == 0 && range.getLength() == 0) - return cunit; - ICElement result= getElementAt(cunit, range.getOffset()); - if (result == null) - return cunit; - - try { - while(true) { - ISourceReference ref= (ISourceReference)result; - IRegion sRange= new Region(ref.getSourceRange().getStartPos(), ref.getSourceRange().getLength()); - if (result.getElementType() == ICElement.C_UNIT || result.getParent() == null || edit.coveredBy(sRange)) - break; - result= result.getParent(); - } - } catch(CModelException e) { - // Do nothing, use old value. - } catch(ClassCastException e) { - // Do nothing, use old value. - } - return result; - } - - protected ICElement getElementAt(IParent unit, int position) throws CModelException { - if (unit instanceof ISourceReference) { - ICElement[] children = unit.getChildren(); - for (int i = 0; i < children.length; i++) { - ICElement aChild = children[i]; - if (aChild instanceof ISourceReference) { - ISourceReference child = (ISourceReference) children[i]; - ISourceRange range = child.getSourceRange(); - if (position < range.getStartPos() + range.getLength() && position >= range.getStartPos()) { - if (child instanceof IParent) { - return getElementAt((IParent)child, position); - } else { - return ((ICElement)child); - } - } - } - } - } - return null; - } -} - diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/ChangeElementLabelProvider.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/ChangeElementLabelProvider.java deleted file mode 100644 index c91ed6a16dc..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/ChangeElementLabelProvider.java +++ /dev/null @@ -1,152 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.refactoring; - -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; - -import org.eclipse.cdt.internal.corext.refactoring.base.IChange; -import org.eclipse.cdt.internal.corext.refactoring.base.ICompositeChange; -import org.eclipse.cdt.internal.corext.refactoring.changes.TextFileChange; -import org.eclipse.cdt.internal.corext.refactoring.changes.TranslationUnitChange; -import org.eclipse.cdt.internal.ui.CPluginImages; -import org.eclipse.cdt.ui.CElementLabelProvider; -import org.eclipse.core.resources.IFile; -import org.eclipse.jface.resource.ImageDescriptor; -import org.eclipse.jface.viewers.LabelProvider; -import org.eclipse.jface.viewers.LabelProviderChangedEvent; -import org.eclipse.swt.graphics.Image; - -class ChangeElementLabelProvider extends LabelProvider { - - private int fCElementFlags; - private CElementLabelProvider fCElementLabelProvider; - private Map fDescriptorImageMap= new HashMap(); - private boolean fShowQualification= true; - - public ChangeElementLabelProvider(int CElementFlags) { - fCElementFlags= CElementFlags; - fCElementLabelProvider= new CElementLabelProvider(CElementFlags); - } - - public void setShowQualification(boolean showQualification) { - fShowQualification= showQualification; - LabelProviderChangedEvent event= new LabelProviderChangedEvent(this, null); - fireLabelProviderChanged(event); - } - - public Image getImage(Object object) { - if (object instanceof DefaultChangeElement) { - Object element= ((DefaultChangeElement)object).getChange(); - return doGetImage(element); - } - else if (object instanceof TextEditChangeElement) { - Object element= ((TextEditChangeElement)object).getTextEditChange(); - return doGetImage(element); - } - else if (object instanceof PseudoCChangeElement) { - PseudoCChangeElement element= (PseudoCChangeElement)object; - return fCElementLabelProvider.getImage(element.getCElement()); - } - return super.getImage(object); - } - - public String getText(Object object) { - if (object instanceof DefaultChangeElement) { - IChange change= ((DefaultChangeElement)object).getChange(); - if (!fShowQualification) - return change.getName(); - - if (change instanceof TextFileChange) { - IFile file= ((TextFileChange)change).getFile(); - return RefactoringMessages.getFormattedString( - "PreviewWizardPage.changeElementLabelProvider.textFormat", //$NON-NLS-1$ - new String[] {file.getName(), getPath(file)}); - } else { - return change.getName(); - } - } - else if (object instanceof TextEditChangeElement) { - TextEditChangeElement element= (TextEditChangeElement)object; - String result= element.getTextEditChange().getName(); - if ((fCElementFlags & CElementLabelProvider.SHOW_POST_QUALIFIED) != 0) { - ChangeElement parent= getParent(element); - if (parent != null) - result= RefactoringMessages.getFormattedString( - "PreviewWizardPage.changeElementLabelProvider.textFormatEdit", //$NON-NLS-1$ - new String[] {getText(parent), result}); - } - return result; - } - else if (object instanceof PseudoCChangeElement) { - PseudoCChangeElement element= (PseudoCChangeElement)object; - return fCElementLabelProvider.getText(element.getCElement()); - } - return super.getText(object); - } - - public void dispose() { - for (Iterator iter= fDescriptorImageMap.values().iterator(); iter.hasNext(); ) { - Image image= (Image)iter.next(); - image.dispose(); - } - super.dispose(); - } - - private Image doGetImage(Object element) { - ImageDescriptor descriptor= null; - if (descriptor == null) { - if (element instanceof ICompositeChange) { - descriptor= CPluginImages.DESC_OBJS_COMPOSITE_CHANGE; - } - else if (element instanceof TextEditChangeElement) { - descriptor= CPluginImages.DESC_OBJS_TEXT_EDIT; - } - else if (element instanceof TranslationUnitChange) { - descriptor= CPluginImages.DESC_OBJS_CU_CHANGE; - } - else if (element instanceof TextFileChange) { - descriptor= CPluginImages.DESC_OBJS_FILE_CHANGE; - } - else { - descriptor= CPluginImages.DESC_OBJS_DEFAULT_CHANGE; - } - } - Image image= (Image)fDescriptorImageMap.get(descriptor); - if (image == null) { - image= descriptor.createImage(); - fDescriptorImageMap.put(descriptor, image); - } - return image; - } - - private String getPath(IFile file) { - StringBuffer result= new StringBuffer(file.getProject().getName()); - String projectRelativePath= file.getParent().getProjectRelativePath().toString(); - if (projectRelativePath.length() > 0) { - result.append('/'); - result.append(projectRelativePath); - } - return result.toString(); - } - - private ChangeElement getParent(TextEditChangeElement element) { - ChangeElement parent= element.getParent(); - while (parent != null - && !(parent instanceof PseudoCChangeElement) - && !(parent instanceof DefaultChangeElement)) { - parent= parent.getParent(); - } - return parent; - } -} - diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/ChangeElementTreeViewer.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/ChangeElementTreeViewer.java deleted file mode 100644 index c9ab85f8f0a..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/ChangeElementTreeViewer.java +++ /dev/null @@ -1,175 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.refactoring; - -import org.eclipse.jface.viewers.CheckStateChangedEvent; -import org.eclipse.jface.viewers.CheckboxTreeViewer; -import org.eclipse.jface.viewers.ICheckStateListener; -import org.eclipse.jface.viewers.IStructuredSelection; -import org.eclipse.jface.viewers.StructuredSelection; -import org.eclipse.swt.SWT; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Item; -import org.eclipse.swt.widgets.TreeItem; -import org.eclipse.swt.widgets.Widget; - -class ChangeElementTreeViewer extends CheckboxTreeViewer { - - public ChangeElementTreeViewer(Composite parentComposite) { - super(parentComposite, SWT.NONE); - addCheckStateListener(new ICheckStateListener() { - public void checkStateChanged(CheckStateChangedEvent event){ - ChangeElement element= (ChangeElement)event.getElement(); - boolean checked= event.getChecked(); - - element.setActive(checked); - setSubtreeChecked(element, checked); - setSubtreeGrayed(element, false); - ChangeElement parent= element.getParent(); - while(parent != null) { - int active= parent.getActive(); - boolean grayed= (active == ChangeElement.PARTLY_ACTIVE); - setChecked(parent, checked ? true : grayed); - setGrayed(parent, grayed); - parent= parent.getParent(); - } - } - }); - } - - protected void inputChanged(Object input, Object oldInput) { - super.inputChanged(input, oldInput); - // XXX workaround for http://bugs.eclipse.org/bugs/show_bug.cgi?id=9390 - initializeChildren((ChangeElement)input); - } - - protected void doUpdateItem(Item item, Object element) { - super.doUpdateItem(item, element); - TreeItem treeItem= (TreeItem)item; - ChangeElement ce= (ChangeElement)element; - int state= ce.getActive(); - boolean checked= state == ChangeElement.INACTIVE ? false : true; - treeItem.setChecked(checked); - boolean grayed= state == ChangeElement.PARTLY_ACTIVE ? true : false; - treeItem.setGrayed(grayed); - } - - protected void revealNext() { - revealElement(true); - } - - protected void revealPrevious() { - revealElement(false); - } - - private void initializeChildren(ChangeElement element) { - if (element == null) - return; - ChangeElement[] children= element.getChildren(); - if (children == null) - return; - for (int i= 0; i < children.length; i++) { - ChangeElement child= children[i]; - int state= child.getActive(); - boolean checked= state == ChangeElement.INACTIVE ? false : true; - if (checked) - setChecked(child, checked); - boolean grayed= state == ChangeElement.PARTLY_ACTIVE ? true : false; - if (grayed) - setGrayed(child, grayed); - } - } - - private void setSubtreeGrayed(Object element, boolean grayed) { - Widget widget= findItem(element); - if (widget instanceof TreeItem) { - TreeItem item= (TreeItem)widget; - if (item.getGrayed() != grayed) { - item.setGrayed(grayed); - grayChildren(getChildren(item), grayed); - } - } - } - - private void grayChildren(Item[] items, boolean grayed) { - for (int i= 0; i < items.length; i++) { - Item element= items[i]; - if (element instanceof TreeItem) { - TreeItem item= (TreeItem)element; - if (item.getGrayed() != grayed) { - item.setGrayed(grayed); - grayChildren(getChildren(item), grayed); - } - } - } - } - - private void revealElement(boolean next) { - ChangeElement current= (ChangeElement)getInput(); - IStructuredSelection selection= (IStructuredSelection)getSelection(); - if (!selection.isEmpty()) - current= (ChangeElement)selection.iterator().next(); - - ChangeElement candidate= getLeaf(current, next); - if (candidate == null) { - candidate= getElement(current, next); - if (candidate != null) { - ChangeElement leaf= getLeaf(candidate, next); - if (leaf != null) - candidate= leaf; - } - } - if (candidate != null) - setSelection(new StructuredSelection(candidate), true); - else - getControl().getDisplay().beep(); - } - - private ChangeElement getLeaf(ChangeElement element, boolean first) { - ChangeElement result= null; - ChangeElement[] children= element.getChildren(); - while(children != null && children.length > 0) { - result= children[first ? 0 : children.length - 1]; - children= result.getChildren(); - } - return result; - } - - private ChangeElement getElement(ChangeElement element, boolean next) { - while(true) { - ChangeElement parent= element.getParent(); - if (parent == null) - return null; - ChangeElement candidate= getSibling(parent.getChildren(), element, next); - if (candidate != null) - return candidate; - element= parent; - } - } - - private ChangeElement getSibling(ChangeElement[] children, ChangeElement element, boolean next) { - for (int i= 0; i < children.length; i++) { - if (children[i] == element) { - if (next) - if (i < children.length - 1) - return children[i + 1]; - else - return null; - else - if (i > 0) - return children[i - 1]; - else - return null; - } - } - return null; - } -} diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/ChangeExceptionHandler.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/ChangeExceptionHandler.java deleted file mode 100644 index 4d10ac4b458..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/ChangeExceptionHandler.java +++ /dev/null @@ -1,107 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.cdt.internal.ui.refactoring; - -import org.eclipse.swt.SWT; -import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.widgets.Button; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Control; -import org.eclipse.swt.widgets.Label; -import org.eclipse.swt.widgets.Shell; - -import org.eclipse.jface.dialogs.ErrorDialog; -import org.eclipse.jface.dialogs.IDialogConstants; -import org.eclipse.jface.util.Assert; - -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.Status; - -import org.eclipse.cdt.internal.corext.refactoring.base.ChangeAbortException; -import org.eclipse.cdt.internal.corext.refactoring.base.ChangeContext; -import org.eclipse.cdt.internal.corext.refactoring.base.IChange; -import org.eclipse.cdt.internal.corext.refactoring.base.IChangeExceptionHandler; - -import org.eclipse.cdt.ui.CUIPlugin; -import org.eclipse.cdt.internal.ui.refactoring.RefactoringMessages; - -/** - * An implementation of IChangeExceptionHandler which pops up a dialog - * box asking the user if the refactoring is to be aborted without further actions or - * if the refactoring engine should try to undo all successfully executed changes. - */ -public class ChangeExceptionHandler implements IChangeExceptionHandler { - - private Shell fParent; - - private static class RefactorErrorDialog extends ErrorDialog { - public RefactorErrorDialog(Shell parentShell, String dialogTitle, String message, IStatus status, int displayMask) { - super(parentShell, dialogTitle, message, status, displayMask); - } - protected void createButtonsForButtonBar(Composite parent) { - super.createButtonsForButtonBar(parent); - Button ok= getButton(IDialogConstants.OK_ID); - ok.setText( RefactoringMessages.getString("ChangeExceptionHandler.undo")); //$NON-NLS-1$ - Button abort= createButton(parent, IDialogConstants.CANCEL_ID, RefactoringMessages.getString("ChangeExceptionHandler.abort"), true); //$NON-NLS-1$ - abort.moveBelow(ok); - abort.setFocus(); - } - protected Control createMessageArea (Composite parent) { - Control result= super.createMessageArea(parent); - new Label(parent, SWT.NONE); // filler - Label label= new Label(parent, SWT.NONE); - label.setText(RefactoringMessages.getString("ChangeExceptionHandler.button_explanation")); //$NON-NLS-1$ - label.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); - applyDialogFont(result); - return result; - } - } - - public ChangeExceptionHandler(Shell parent) { - Assert.isNotNull(parent); - fParent= parent; - } - - public void handle(ChangeContext context, IChange change, Exception e) { - CUIPlugin.getDefault().log(e); - IStatus status= null; - if (e instanceof CoreException) { - status= ((CoreException)e).getStatus(); - } else { - if (e.getMessage() == null) - status= new Status(IStatus.ERROR, CUIPlugin.getPluginId(), IStatus.ERROR, - RefactoringMessages.getString("ChangeExceptionHandler.no_details"), e); //$NON-NLS-1$ - else - status= new Status(IStatus.ERROR, CUIPlugin.getPluginId(), IStatus.ERROR, e.getMessage(), e); - } - final ErrorDialog dialog= new RefactorErrorDialog(fParent, - RefactoringMessages.getString("ChangeExceptionHandler.refactoring"), //$NON-NLS-1$ - RefactoringMessages.getFormattedString("ChangeExceptionHandler.unexpected_exception", new String[] {change.getName()}), //$NON-NLS-1$ - status, IStatus.OK | IStatus.INFO | IStatus.WARNING | IStatus.ERROR); - - final int[] result= new int[1]; - Runnable runnable= new Runnable() { - public void run() { - result[0]= dialog.open(); - } - }; - fParent.getDisplay().syncExec(runnable); - switch(result[0]) { - case IDialogConstants.OK_ID: - context.setTryToUndo(); - // Fall through - case IDialogConstants.CANCEL_ID: - throw new ChangeAbortException(e); - } - } -} diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/CheckConditionsOperation.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/CheckConditionsOperation.java deleted file mode 100644 index 48f9575e1e0..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/CheckConditionsOperation.java +++ /dev/null @@ -1,89 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.refactoring; - -import java.lang.reflect.InvocationTargetException; - -import org.eclipse.core.runtime.IProgressMonitor; - -import org.eclipse.jface.operation.IRunnableWithProgress; -import org.eclipse.jface.util.Assert; - -import org.eclipse.cdt.core.model.CModelException; - -import org.eclipse.cdt.internal.corext.refactoring.base.Refactoring; -import org.eclipse.cdt.internal.corext.refactoring.base.RefactoringStatus; - -/** - * Operation that, when run, check proceconditions of an Refactoring passed - * on creation. - */ -public class CheckConditionsOperation implements IRunnableWithProgress { - private Refactoring fRefactoring; - private int fStyle; - private RefactoringStatus fStatus; - - public final static int NONE= 0; - public final static int ACTIVATION= 1 << 1; - public final static int INPUT= 1 << 2; - public final static int PRECONDITIONS= ACTIVATION | INPUT; - final static int LAST= 1 << 3; - - /** - * Creates a new CheckConditionsOperation. - * - * @param refactoring the refactoring. Parameter must not be null. - * @param style style to define which conditions to check. - */ - public CheckConditionsOperation(Refactoring refactoring, int style) { - Assert.isNotNull(refactoring); - fRefactoring= refactoring; - fStyle= style; - Assert.isTrue(checkStyle(fStyle)); - } - - /* - * (Non-Javadoc) - * Method defined int IRunnableWithProgress - */ - public void run(IProgressMonitor pm) throws InvocationTargetException { - try { - fStatus= null; - if ((fStyle & PRECONDITIONS) == PRECONDITIONS) - fStatus= fRefactoring.checkPreconditions(pm); - else if ((fStyle & ACTIVATION) == ACTIVATION) - fStatus= fRefactoring.checkActivation(pm); - else if ((fStyle & INPUT) == INPUT) - fStatus= fRefactoring.checkInput(pm); - } catch (CModelException e) { - throw new InvocationTargetException(e); - } finally { - pm.done(); - } - } - - /** - * Returns the outcome of the operation or null if an exception - * has occured when performing the operation. - * - * @return the RefactoringStatus returned from - * IRefactoring.checkPreconditions. - * @see org.eclipse.jdt.internal.corext.refactoring.base.IRefactoring#checkPreconditions(IProgressMonitor) - */ - public RefactoringStatus getStatus() { - return fStatus; - } - - private boolean checkStyle(int style) { - return style < LAST; - } - -} diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/CreateChangeOperation.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/CreateChangeOperation.java deleted file mode 100644 index 90feb2274fb..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/CreateChangeOperation.java +++ /dev/null @@ -1,156 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.cdt.internal.ui.refactoring; - -import java.lang.reflect.InvocationTargetException; - -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.SubProgressMonitor; - -import org.eclipse.jface.operation.IRunnableWithProgress; -import org.eclipse.jface.util.Assert; - -import org.eclipse.cdt.core.model.CModelException; - -import org.eclipse.cdt.internal.corext.refactoring.base.IChange; -import org.eclipse.cdt.internal.corext.refactoring.base.Refactoring; -import org.eclipse.cdt.internal.corext.refactoring.base.RefactoringStatus; - -/** - * Operation that, when performed, creates an IChange object for the refactoring - * passed as a constructor parameter. - */ -public class CreateChangeOperation implements IRunnableWithProgress { - - private Refactoring fRefactoring; - private int fStyle; - private int fCheckPassedSeverity; - private IChange fChange; - private RefactoringStatus fStatus; - - public static final int CHECK_NONE= CheckConditionsOperation.NONE; - public static final int CHECK_ACTIVATION= CheckConditionsOperation.ACTIVATION; - public static final int CHECK_INPUT= CheckConditionsOperation.INPUT; - public static final int CHECK_PRECONDITION= CheckConditionsOperation.PRECONDITIONS; - private static final int LAST= CheckConditionsOperation.LAST; - - /** - * Creates a new instance with the given refactoring. - * - * @param refactoring the refactoring. Parameter must not be null - * @param style style to define which conditions to check - */ - public CreateChangeOperation(Refactoring refactoring, int style) { - Assert.isNotNull(refactoring); - fRefactoring= refactoring; - fStyle= style; - Assert.isTrue(checkStyle(fStyle)); - fCheckPassedSeverity= RefactoringStatus.ERROR; - } - - /** - * Creates a new instance with the given refactoring. - * - * @param refactoring the refactoring. Parameter must not be null - * @param style style to define which conditions to check - * @param checkPassedSeverity the severity below which the check is considered - * to be passed - * @see #setCheckPassedSeverity(int) - */ - public CreateChangeOperation(Refactoring refactoring, int style, int checkPassedSeverity) { - Assert.isNotNull(refactoring); - fRefactoring= refactoring; - fStyle= style; - Assert.isTrue(checkStyle(fStyle)); - setCheckPassedSeverity(checkPassedSeverity); - } - - /** - * Sets the check passed severity value. This value is used to deceide whether the - * condition check is interpreted as passed or not. The condition check is considered - * to be passed if the refactoring status's severity is less or equal the given severity. - * The given value must be smaller than RefactoringStatus.FATAL. - */ - public void setCheckPassedSeverity(int severity) { - fCheckPassedSeverity= severity; - Assert.isTrue (fCheckPassedSeverity < RefactoringStatus.FATAL); - } - - /* (Non=Javadoc) - * Method declared in IRunnableWithProgress - */ - public void run(IProgressMonitor pm) throws InvocationTargetException { - fChange= null; - fStatus= null; - try { - fChange= null; - if (fStyle != CHECK_NONE) { - pm.beginTask("", 5); //$NON-NLS-1$ - pm.subTask(""); //$NON-NLS-1$ - CheckConditionsOperation op= new CheckConditionsOperation(fRefactoring, fStyle); - op.run(new SubProgressMonitor(pm, 4, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK)); - fStatus= op.getStatus(); - if (fStatus != null && fStatus.getSeverity() <= fCheckPassedSeverity) { - fChange= fRefactoring.createChange( - new SubProgressMonitor(pm, 1, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK)); - } else { - pm.worked(1); - } - } else { - fChange= fRefactoring.createChange(pm); - } - } catch (CModelException e) { - throw new InvocationTargetException(e); - } finally { - pm.done(); - } - } - - /** - * Returns the outcome of the operation or null if an exception - * occured when performing the operation. - * - * @return the outcome of the operation - */ - public IChange getChange() { - return fChange; - } - - /** - * Returns the status of the condition cheking. Returns null if an - * exception occured when performing the operation. - * - * @return the condition checking's status - */ - public RefactoringStatus getStatus() { - return fStatus; - } - - /** - * Returns the checking style. - * - * @return the style used for precondition checking. Is one of NONE, - * ACTIVATION, INPUT, or PRECONDITION. - */ - public int getConditionCheckingStyle() { - return fStyle; - } - - public void setConditionCheckingStyle(int style) { - Assert.isTrue(checkStyle(style)); - fStyle= style; - } - - private boolean checkStyle(int style) { - return style < LAST; - } -} diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/DefaultChangeElement.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/DefaultChangeElement.java deleted file mode 100644 index 7f974183a7a..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/DefaultChangeElement.java +++ /dev/null @@ -1,123 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.refactoring; - -import org.eclipse.cdt.internal.corext.refactoring.base.IChange; -import org.eclipse.cdt.internal.corext.refactoring.base.ICompositeChange; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.jface.util.Assert; -//import org.eclipse.jdt.internal.corext.refactoring.changes.CompilationUnitChange; -//import org.eclipse.jdt.internal.corext.refactoring.changes.TextChange; - -class DefaultChangeElement extends ChangeElement { - - private IChange fChange; - private ChangeElement[] fChildren; - - /** - * Creates a new ChangeElement for the given - * change. - * - * @param parent the change element's parent or null - * if the change element doesn't have a parent - * @param change the actual change. Argument must not be - * null - */ - public DefaultChangeElement(ChangeElement parent, IChange change) { - super(parent); - fChange= change; - Assert.isNotNull(fChange); - } - - /** - * Returns the underlying IChange object. - * - * @return the underlying change - */ - public IChange getChange() { - return fChange; - } - - /* (non-Javadoc) - * @see org.eclipse.jdt.internal.ui.refactoring.ChangeElement#getChangePreviewViewer() - */ -// public ChangePreviewViewerDescriptor getChangePreviewViewer() throws CoreException { -// return ChangePreviewViewerDescriptor.get(fChange); -// } - - /* (non-Javadoc) - * @see org.eclipse.jdt.internal.ui.refactoring.ChangeElement#feedInput(org.eclipse.jdt.internal.ui.refactoring.IChangePreviewViewer) - */ - public void feedInput(IChangePreviewViewer viewer) throws CoreException { - viewer.setInput(fChange); - } - - /* non Java-doc - * @see ChangeElement#setActive - */ - public void setActive(boolean active) { - fChange.setActive(active); - } - - /* non Java-doc - * @see ChangeElement.getActive - */ - public int getActive() { - if (fChange instanceof ICompositeChange /*|| fChange instanceof CompilationUnitChange || fChange instanceof TextChange*/) - return getCompositeChangeActive(); - else - return getDefaultChangeActive(); - } - - /* non Java-doc - * @see ChangeElement.getChildren - */ - public ChangeElement[] getChildren() { - return fChildren; - } - - /** - * Sets the children. - * - * @param the children of this node. Must not be null - */ - public void setChildren(ChangeElement[] children) { - Assert.isNotNull(children); - fChildren= children; - } - - private int getDefaultChangeActive() { - int result= fChange.isActive() ? ACTIVE : INACTIVE; - if (fChildren != null) { - for (int i= 0; i < fChildren.length; i++) { - result= ACTIVATION_TABLE[fChildren[i].getActive()][result]; - if (result == PARTLY_ACTIVE) - break; - } - } - return result; - } - - private int getCompositeChangeActive() { - if (fChildren != null && fChildren.length > 0) { - int result= fChildren[0].getActive(); - for (int i= 1; i < fChildren.length; i++) { - result= ACTIVATION_TABLE[fChildren[i].getActive()][result]; - if (result == PARTLY_ACTIVE) - break; - } - return result; - } else { - return ACTIVE; - } - } -} - diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/ErrorWizardPage.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/ErrorWizardPage.java deleted file mode 100644 index b03290ba34f..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/ErrorWizardPage.java +++ /dev/null @@ -1,141 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.cdt.internal.ui.refactoring; - -import org.eclipse.swt.SWT; -import org.eclipse.swt.widgets.Composite; - -import org.eclipse.jface.dialogs.Dialog; -import org.eclipse.jface.wizard.IWizardPage; - -import org.eclipse.ui.help.WorkbenchHelp; - -import org.eclipse.cdt.internal.ui.ICHelpContextIds; - -import org.eclipse.cdt.internal.corext.refactoring.base.IChange; -import org.eclipse.cdt.internal.corext.refactoring.base.RefactoringStatus; - -/** - * Presents the list of failed preconditions to the user - */ -class ErrorWizardPage extends RefactoringWizardPage { - - public static final String PAGE_NAME= "ErrorPage"; //$NON-NLS-1$ - - private RefactoringStatus fStatus; - private RefactoringStatusViewer fViewer; - - public ErrorWizardPage() { - super(PAGE_NAME); - } - - /** - * Sets the page's refactoring status to the given value. - * @param status the refactoring status. - */ - public void setStatus(RefactoringStatus status) { - fStatus= status; - if (fStatus != null) { - setPageComplete(isRefactoringPossible()); - int severity= fStatus.getSeverity(); - if (severity >= RefactoringStatus.FATAL) { - setDescription(RefactoringMessages.getString("ErrorWizardPage.cannot_proceed")); //$NON-NLS-1$ - } else if (severity >= RefactoringStatus.INFO) { - setDescription(RefactoringMessages.getString("ErrorWizardPage.confirm")); //$NON-NLS-1$ - } else { - setDescription(""); //$NON-NLS-1$ - } - } else { - setPageComplete(true); - setDescription(""); //$NON-NLS-1$ - } - } - - public RefactoringStatus getStatus() { - return fStatus; - } - - //---- UI creation ---------------------------------------------------------------------- - - /* (non-Javadoc) - * Method declared in IWizardPage. - */ - public void createControl(Composite parent) { - initializeDialogUnits(parent); - setControl(fViewer= new RefactoringStatusViewer(parent, SWT.NONE)); - Dialog.applyDialogFont(fViewer); - WorkbenchHelp.setHelp(getControl(), ICHelpContextIds.REFACTORING_ERROR_WIZARD_PAGE); - } - - //---- Reimplementation of WizardPage methods ------------------------------------------ - - /* (non-Javadoc) - * Method declared on IDialog. - */ - public void setVisible(boolean visible) { - if (visible) { - fViewer.setStatus(fStatus); - } - super.setVisible(visible); - } - - /* (non-Javadoc) - * Method declared in IWizardPage. - */ - public boolean canFlipToNextPage() { - // We have to call super.getNextPage since computing the next - // page is expensive. So we avoid it as long as possible. - return fStatus != null && isRefactoringPossible() && - isPageComplete() && super.getNextPage() != null; - } - - /* (non-Javadoc) - * Method declared in IWizardPage. - */ - public IWizardPage getNextPage() { - RefactoringWizard wizard= getRefactoringWizard(); - IChange change= wizard.getChange(); - if (change == null) { - change= wizard.createChange(CreateChangeOperation.CHECK_NONE, RefactoringStatus.ERROR, false); - wizard.setChange(change); - } - if (change == null) - return this; - - return super.getNextPage(); - } - - /* (non-JavaDoc) - * Method defined in RefactoringWizardPage - */ - protected boolean performFinish() { - RefactoringWizard wizard= getRefactoringWizard(); - IChange change= wizard.getChange(); - PerformChangeOperation op= null; - if (change != null) { - op= new PerformChangeOperation(change); - } else { - CreateChangeOperation ccop= new CreateChangeOperation(getRefactoring(), CreateChangeOperation.CHECK_NONE); - ccop.setCheckPassedSeverity(RefactoringStatus.ERROR); - - op= new PerformChangeOperation(ccop); - op.setCheckPassedSeverity(RefactoringStatus.ERROR); - } - return wizard.performFinish(op); - } - - //---- Helpers ---------------------------------------------------------------------------------------- - - private boolean isRefactoringPossible() { - return fStatus.getSeverity() < RefactoringStatus.FATAL; - } -} diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/IChangePreviewViewer.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/IChangePreviewViewer.java deleted file mode 100644 index ad3828ae3fe..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/IChangePreviewViewer.java +++ /dev/null @@ -1,53 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.refactoring; - -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Control; - -import org.eclipse.core.runtime.CoreException; - -/** - * Presents a preview of a ChangeElement - */ -public interface IChangePreviewViewer { - - /** - * Creates the preview viewer's widget hierarchy. This method - * should only be called once. Method getControl() - * should be use retrieve the widget hierarchy. - * - * @param parent the parent for the widget hierarchy - * - * @see #getControl() - */ - public void createControl(Composite parent); - - /** - * Returns the preview viewer's SWT control. - * - * @return the preview viewer's SWT control - */ - public Control getControl(); - - /** - * Sets the preview viewer's input element. - * - * @param input the input element - */ - public void setInput(Object input) throws CoreException; - - /** - * Refreshes the preview viewer. - */ - public void refresh(); -} - diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/IPreviewWizardPage.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/IPreviewWizardPage.java deleted file mode 100644 index f3a864185e8..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/IPreviewWizardPage.java +++ /dev/null @@ -1,29 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.refactoring; - -import org.eclipse.jface.wizard.IWizardPage; - -import org.eclipse.cdt.internal.corext.refactoring.base.IChange; - -public interface IPreviewWizardPage extends IWizardPage { - - /** The page's name */ - public static final String PAGE_NAME= "PreviewPage"; //$NON-NLS-1$ - - /** - * Sets that change for which the page is supposed to display a preview. - * - * @param change the new change. - */ - public void setChange(IChange change); -} - diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/IStatusContextViewer.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/IStatusContextViewer.java deleted file mode 100644 index 18b3636316b..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/IStatusContextViewer.java +++ /dev/null @@ -1,48 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.refactoring; - -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Control; - -import org.eclipse.cdt.internal.corext.refactoring.base.Context; - -/** - * A special viewer to present a context for a RefactoringStatusEntry. - */ -public interface IStatusContextViewer { - - /** - * Creates the status viewer's widget hierarchy. This method - * should only be called once. Method getControl() - * should be used to retrieve the widget hierarchy. - * - * @param parent the parent for the widget hierarchy - * - * @see #getControl() - */ - public void createControl(Composite parent); - - /** - * Returns the status context viewer's SWT control. - * - * @return the status context viewer's SWT control - */ - public Control getControl(); - - /** - * Sets the status context viewer's input element. - * - * @param input the input element - */ - public void setInput(Context input); -} - diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/ListDialog.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/ListDialog.java deleted file mode 100644 index 65e13ac5e8a..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/ListDialog.java +++ /dev/null @@ -1,95 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.refactoring; - -import org.eclipse.swt.SWT; -import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Control; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.swt.widgets.Table; - -import org.eclipse.jface.dialogs.IDialogConstants; -import org.eclipse.jface.viewers.ILabelProvider; -import org.eclipse.jface.viewers.IStructuredContentProvider; -import org.eclipse.jface.viewers.TableViewer; - -import org.eclipse.ui.dialogs.SelectionDialog; - -public class ListDialog extends SelectionDialog { - - private IStructuredContentProvider fContentProvider; - private ILabelProvider fLabelProvider; - private Object fInput; - private TableViewer fTableViewer; - private boolean fAddCancelButton; - - public ListDialog(Shell parent) { - super(parent); - fAddCancelButton= false; - } - - public void setInput(Object input) { - fInput= input; - } - - public void setContentProvider(IStructuredContentProvider sp){ - fContentProvider= sp; - } - - public void setLabelProvider(ILabelProvider lp){ - fLabelProvider= lp; - } - - public void setAddCancelButton(boolean addCancelButton) { - fAddCancelButton= addCancelButton; - } - - public TableViewer getTableViewer(){ - return fTableViewer; - } - - public boolean hasFilters(){ - return fTableViewer.getFilters() != null && fTableViewer.getFilters().length != 0; - } - - public void create() { - setShellStyle(SWT.DIALOG_TRIM | SWT.RESIZE); - super.create(); - } - - protected void createButtonsForButtonBar(Composite parent) { - if (! fAddCancelButton) - createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true); - else - super.createButtonsForButtonBar(parent); - } - - protected Control createDialogArea(Composite container) { - Composite parent= (Composite) super.createDialogArea(container); - createMessageArea(parent); - fTableViewer= new TableViewer(parent, getTableStyle()); - fTableViewer.setContentProvider(fContentProvider); - Table table= fTableViewer.getTable(); - fTableViewer.setLabelProvider(fLabelProvider); - fTableViewer.setInput(fInput); - GridData gd= new GridData(GridData.FILL_BOTH); - gd.heightHint= convertHeightInCharsToPixels(15); - gd.widthHint= convertWidthInCharsToPixels(55); - table.setLayoutData(gd); - applyDialogFont(parent); - return parent; - } - - protected int getTableStyle() { - return SWT.SINGLE | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER; - } -} diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/PerformChangeOperation.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/PerformChangeOperation.java deleted file mode 100644 index 25780316f93..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/PerformChangeOperation.java +++ /dev/null @@ -1,219 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.refactoring; - -import java.lang.reflect.InvocationTargetException; -import java.util.ArrayList; -import java.util.List; - -import org.eclipse.jface.operation.IRunnableWithProgress; -import org.eclipse.jface.text.IRewriteTarget; -import org.eclipse.jface.util.Assert; - -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.NullProgressMonitor; -import org.eclipse.core.runtime.Status; -import org.eclipse.core.runtime.SubProgressMonitor; - -import org.eclipse.core.resources.IWorkspaceRunnable; - -import org.eclipse.ui.IEditorPart; - -import org.eclipse.cdt.core.model.CoreModel; - -import org.eclipse.cdt.internal.corext.refactoring.base.ChangeAbortException; -import org.eclipse.cdt.internal.corext.refactoring.base.ChangeContext; -import org.eclipse.cdt.internal.corext.refactoring.base.IChange; -import org.eclipse.cdt.internal.corext.refactoring.base.RefactoringStatus; - -import org.eclipse.cdt.internal.ui.ICStatusConstants; -import org.eclipse.cdt.ui.CUIPlugin; - -/** - * Operation that, when performed, performes a change to the workbench. - */ -public class PerformChangeOperation implements IRunnableWithProgress { - - private IChange fChange; - private ChangeContext fChangeContext; - private CreateChangeOperation fCreateChangeOperation; - private int fCheckPassedSeverity; - private boolean fChangeExecuted; - - /** - * Creates a new perform change operation instance for the given change. - * - * @param change the change to be applied to the workbench - */ - public PerformChangeOperation(IChange change) { - fChange= change; - Assert.isNotNull(fChange); - } - - /** - * Creates a new perform change operation for the given create change operation. - * When executed, a new change is created using the passed instance. - * - * @param op the CreateChangeOperation used to create a new - * change object - */ - public PerformChangeOperation(CreateChangeOperation op) { - fCreateChangeOperation= op; - Assert.isNotNull(fCreateChangeOperation); - fCheckPassedSeverity= RefactoringStatus.INFO; - } - - /** - * Returns true if the change has been executed. Otherwise false - * is returned. - * - * @return true if the change has been executed, otherwise - * false - */ - public boolean changeExecuted() { - return fChangeExecuted; - } - - /** - * Returns the change used by this operation. This is either the change passed to - * the constructor or the one create by the CreateChangeOperation. - * Method returns null if the create operation did not create - * the change. - * - * @return the change used by this operation or null if no change - * has been created - */ - public IChange getChange() { - return fChange; - } - - public RefactoringStatus getStatus() { - return fCreateChangeOperation != null ? fCreateChangeOperation.getStatus() : null; - } - - /** - * Sets the check passed severity value. This value is used to deceide whether the - * condition check, executed if a change is to be created, is interpreted as passed - * or not. The condition check is considered to be passed if the refactoring status's - * severity is less or equal the given severity. The given value must be smaller - * than RefactoringStatus.FATAL. - * - * @param severity the severity value considered to be "ok". - */ - public void setCheckPassedSeverity(int severity) { - fCheckPassedSeverity= severity; - Assert.isTrue (fCheckPassedSeverity < RefactoringStatus.FATAL); - } - - /** - * Sets the change context used to execute the change. The given context is passed - * to the method IChange.perform. - * - * @param context the change context to use - * @see IChange#perform(ChangeContext, IProgressMonitor) - */ - public void setChangeContext(ChangeContext context) { - fChangeContext= context; - Assert.isNotNull(fChangeContext); - } - - /* (non-Javadoc) - * Method declard in IRunnableWithProgress - */ - public void run(IProgressMonitor pm) throws InvocationTargetException, InterruptedException { - try{ - fChangeExecuted= false; - if (createChange()) { - pm.beginTask("", 2); //$NON-NLS-1$ - fCreateChangeOperation.run(new SubProgressMonitor(pm, 1, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK)); - fChange= fCreateChangeOperation.getChange(); - RefactoringStatus status= fCreateChangeOperation.getStatus(); - int conditionCheckingStyle= fCreateChangeOperation.getConditionCheckingStyle(); - if (fChange != null && - (conditionCheckingStyle == CreateChangeOperation.CHECK_NONE || - status != null && status.getSeverity() <= fCheckPassedSeverity)) { - executeChange(new SubProgressMonitor(pm, 1, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK)); - fChangeExecuted= true; - } else { - pm.worked(1); - } - } else { - executeChange(pm); - fChangeExecuted= true; - } - } catch (CoreException e) { - throw new InvocationTargetException(e); - } finally{ - pm.done(); - } - } - - private void executeChange(IProgressMonitor pm) throws CoreException { - Assert.isNotNull(fChangeContext); - IRewriteTarget[] targets= null; - try { - targets= getRewriteTargets(); - beginCompoundChange(targets); - // Since we have done precondition checking this check should be fast. No PM. - // PR: 1GEWDUH: ITPJCORE:WINNT - Refactoring - Unable to undo refactor change - fChange.aboutToPerform(fChangeContext, new NullProgressMonitor()); - IWorkspaceRunnable runnable= new IWorkspaceRunnable() { - public void run(IProgressMonitor monitor) throws CoreException { - try { - fChange.perform(fChangeContext, monitor); - } catch (ChangeAbortException e) { - throw new CoreException( - new Status( - IStatus.ERROR, - CUIPlugin.getPluginId(), ICStatusConstants.CHANGE_ABORTED, - RefactoringMessages.getString("PerformChangeOperation.unrecoverable_error"), e)); //$NON-NLS-1$ - } - } - }; - CoreModel.run(runnable, pm); - } finally { - fChange.performed(); - if (targets != null) - endCompoundChange(targets); - } - } - - private boolean createChange() { - return fCreateChangeOperation != null; - } - - private static void beginCompoundChange(IRewriteTarget[] targets) { - for (int i= 0; i < targets.length; i++) { - targets[i].beginCompoundChange(); - } - } - - private static void endCompoundChange(IRewriteTarget[] targets) { - for (int i= 0; i < targets.length; i++) { - targets[i].endCompoundChange(); - } - } - - private static IRewriteTarget[] getRewriteTargets() { - IEditorPart[] editors= CUIPlugin.getInstanciatedEditors(); - List result= new ArrayList(editors.length); - for (int i= 0; i < editors.length; i++) { - IRewriteTarget target= (IRewriteTarget)editors[i].getAdapter(IRewriteTarget.class); - if (target != null) { - result.add(target); - } - } - return (IRewriteTarget[]) result.toArray(new IRewriteTarget[result.size()]); - } -} - diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/PerformRefactoringUtil.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/PerformRefactoringUtil.java deleted file mode 100644 index d56aec0ec22..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/PerformRefactoringUtil.java +++ /dev/null @@ -1,128 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.refactoring; - -import java.lang.reflect.InvocationTargetException; - -import org.eclipse.swt.widgets.Shell; - -import org.eclipse.jface.operation.IRunnableContext; -import org.eclipse.jface.operation.IRunnableWithProgress; - -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.NullProgressMonitor; - -import org.eclipse.core.resources.IWorkspaceRunnable; - -import org.eclipse.cdt.core.model.CoreModel; - -import org.eclipse.cdt.internal.corext.refactoring.base.ChangeAbortException; -import org.eclipse.cdt.internal.corext.refactoring.base.ChangeContext; -import org.eclipse.cdt.internal.corext.refactoring.base.IChange; -import org.eclipse.cdt.internal.corext.refactoring.base.IUndoManager; -import org.eclipse.cdt.internal.corext.refactoring.base.Refactoring; - -import org.eclipse.cdt.internal.ui.ICStatusConstants; -import org.eclipse.cdt.internal.ui.util.ExceptionHandler; - -public class PerformRefactoringUtil { - - //no instances - private PerformRefactoringUtil(){ - } - - public static boolean performRefactoring(PerformChangeOperation op, Refactoring refactoring, IRunnableContext execContext, Shell parent) { - ChangeContext context= new ChangeContext(new ChangeExceptionHandler(parent)); - boolean success= false; - IUndoManager undoManager= Refactoring.getUndoManager(); - try{ - op.setChangeContext(context); - undoManager.aboutToPerformRefactoring(); - execContext.run(false, false, op); - if (op.changeExecuted()) { - if (! op.getChange().isUndoable()){ - success= false; - } else { - undoManager.addUndo(refactoring.getName(), op.getChange().getUndoChange()); - success= true; - } - } - } catch (InvocationTargetException e) { - Throwable t= e.getTargetException(); - if (t instanceof CoreException) { - IStatus status= ((CoreException)t).getStatus(); - if (status != null && status.getCode() == ICStatusConstants.CHANGE_ABORTED && status.getPlugin().equals(status.getPlugin())) { - success= handleChangeAbortException(execContext, context); - return true; - } - } - handleUnexpectedException(e); - return false; - } catch (InterruptedException e) { - return false; - } finally { - context.clearPerformedChanges(); - undoManager.refactoringPerformed(success); - } - - return true; - } - - private static boolean handleChangeAbortException(IRunnableContext execContext, final ChangeContext context) { - if (!context.getTryToUndo()) - return false; // Return false since we handle an unexpected exception and we don't have any - // idea in which state the workbench is. - - IRunnableWithProgress op= new IRunnableWithProgress() { - public void run(IProgressMonitor monitor) throws InterruptedException, InvocationTargetException { - try { - CoreModel.run(new IWorkspaceRunnable() { - public void run(IProgressMonitor pm) throws CoreException { - ChangeContext undoContext= new ChangeContext(new AbortChangeExceptionHandler()); - IChange[] changes= context.getPerformedChanges(); - pm.beginTask(RefactoringMessages.getString("RefactoringWizard.undoing"), changes.length); //$NON-NLS-1$ - IProgressMonitor sub= new NullProgressMonitor(); - for (int i= changes.length - 1; i >= 0; i--) { - IChange change= changes[i]; - pm.subTask(change.getName()); - change.getUndoChange().perform(undoContext, sub); - pm.worked(1); - } - } - }, monitor); - } catch (ChangeAbortException e) { - throw new InvocationTargetException(e.getThrowable()); - } catch (CoreException e) { - throw new InvocationTargetException(e); - } finally { - monitor.done(); - } - } - }; - - try { - execContext.run(false, false, op); - } catch (InvocationTargetException e) { - handleUnexpectedException(e); - return false; - } catch (InterruptedException e) { - // not possible. Operation not cancelable. - } - - return true; - } - - private static void handleUnexpectedException(InvocationTargetException e) { - ExceptionHandler.handle(e, RefactoringMessages.getString("RefactoringWizard.refactoring"), RefactoringMessages.getString("RefactoringWizard.unexpected_exception_1")); //$NON-NLS-2$ //$NON-NLS-1$ - } -} diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/PreviewWizardPage.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/PreviewWizardPage.java deleted file mode 100644 index 40cc181d1da..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/PreviewWizardPage.java +++ /dev/null @@ -1,368 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.refactoring; - -import org.eclipse.cdt.internal.corext.refactoring.base.Change; -import org.eclipse.cdt.internal.corext.refactoring.base.ChangeContext; -import org.eclipse.cdt.internal.corext.refactoring.base.IChange; -import org.eclipse.cdt.internal.corext.refactoring.base.ICompositeChange; -import org.eclipse.cdt.internal.corext.refactoring.changes.TextChange; -import org.eclipse.cdt.internal.ui.ICHelpContextIds; -import org.eclipse.cdt.internal.ui.util.ViewerPane; -import org.eclipse.cdt.ui.CElementLabelProvider; -import org.eclipse.compare.CompareUI; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.jface.action.Action; -import org.eclipse.jface.action.ToolBarManager; -import org.eclipse.jface.dialogs.Dialog; -import org.eclipse.jface.dialogs.IDialogConstants; -import org.eclipse.jface.viewers.CheckStateChangedEvent; -import org.eclipse.jface.viewers.ICheckStateListener; -import org.eclipse.jface.viewers.ILabelProvider; -import org.eclipse.jface.viewers.ISelectionChangedListener; -import org.eclipse.jface.viewers.IStructuredSelection; -import org.eclipse.jface.viewers.ITreeContentProvider; -import org.eclipse.jface.viewers.SelectionChangedEvent; -import org.eclipse.jface.viewers.StructuredSelection; -import org.eclipse.swt.SWT; -import org.eclipse.swt.custom.SashForm; -import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.layout.GridLayout; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Control; -import org.eclipse.swt.widgets.Label; -import org.eclipse.ui.help.WorkbenchHelp; -import org.eclipse.ui.part.PageBook; - -/** - * Presents the changes made by the refactoring. - * Consists of a tree of changes and a compare viewer that shows the differences. - */ -public class PreviewWizardPage extends RefactoringWizardPage implements IPreviewWizardPage { - // Dummy root node if input element isn't a composite change. - private static class DummyRootNode extends Change implements ICompositeChange { - private IChange[] fChildren; - - public DummyRootNode(IChange change) { - fChildren= new IChange[] { change }; - } - public IChange[] getChildren() { - return fChildren; - } - public String getName() { - return null; - } - public Object getModifiedLanguageElement() { - return null; - } - public IChange getUndoChange() { - return null; - } - public void perform(ChangeContext context, IProgressMonitor pm) { - } - } - - private static class NullPreviewer implements IChangePreviewViewer { - private Label fLabel; - public void createControl(Composite parent) { - fLabel= new Label(parent, SWT.CENTER | SWT.FLAT); - fLabel.setText(RefactoringMessages.getString("PreviewWizardPage.no_preview")); //$NON-NLS-1$ - } - public void refresh() { - } - public Control getControl() { - return fLabel; - } - public void setInput(Object input) throws CoreException { - } - } - - private class NextChange extends Action { - public NextChange() { - setImageDescriptor(CompareUI.DESC_ETOOL_NEXT); - setDisabledImageDescriptor(CompareUI.DESC_DTOOL_NEXT); - setHoverImageDescriptor(CompareUI.DESC_CTOOL_NEXT); - setToolTipText(RefactoringMessages.getString("PreviewWizardPage.next_Change")); //$NON-NLS-1$ - WorkbenchHelp.setHelp(this, ICHelpContextIds.NEXT_CHANGE_ACTION); - } - public void run() { - fTreeViewer.revealNext(); - } - } - - private class PreviousChange extends Action { - public PreviousChange() { - setImageDescriptor(CompareUI.DESC_ETOOL_PREV); - setDisabledImageDescriptor(CompareUI.DESC_DTOOL_PREV); - setHoverImageDescriptor(CompareUI.DESC_CTOOL_PREV); - setToolTipText(RefactoringMessages.getString("PreviewWizardPage.previous_Change")); //$NON-NLS-1$ - WorkbenchHelp.setHelp(this, ICHelpContextIds.PREVIOUS_CHANGE_ACTION); - } - public void run() { - fTreeViewer.revealPrevious(); - } - } - - private IChange fChange; - private ChangeElement fCurrentSelection; - private PageBook fPageContainer; - private Control fStandardPage; - private Control fNullPage; - private ChangeElementTreeViewer fTreeViewer; -////// -// private PageBook fPreviewContainer; -// private ChangePreviewViewerDescriptor fCurrentDescriptor; -// private IChangePreviewViewer fCurrentPreviewViewer; -// private IChangePreviewViewer fNullPreviewer; -////// - public PreviewWizardPage() { - super(PAGE_NAME); - setDescription(RefactoringMessages.getString("PreviewWizardPage.description")); //$NON-NLS-1$ - } - - public void setChange(IChange change) { - if (fChange == change) - return; - - fChange= change; - setTreeViewerInput(); - } - - protected ChangeElementTreeViewer createTreeViewer(Composite parent) { - return new ChangeElementTreeViewer(parent); - } - - protected ITreeContentProvider createTreeContentProvider() { - return new ChangeElementContentProvider(); - } - - protected ILabelProvider createTreeLabelProvider() { - return new ChangeElementLabelProvider(CElementLabelProvider.SHOW_DEFAULT | CElementLabelProvider.SHOW_SMALL_ICONS); - } - - protected boolean performFinish() { - return getRefactoringWizard().performFinish(new PerformChangeOperation(fChange)); - } - - public boolean canFlipToNextPage() { - return false; - } - - public void createControl(Composite parent) { - initializeDialogUnits(parent); - fPageContainer= new PageBook(parent, SWT.NONE); - fStandardPage= createStandardPreviewPage(fPageContainer); - fNullPage= createNullPage(fPageContainer); - setControl(fPageContainer); - WorkbenchHelp.setHelp(getControl(), ICHelpContextIds.REFACTORING_PREVIEW_WIZARD_PAGE); - } - - private Composite createStandardPreviewPage(Composite parent) { - // XXX The composite is needed to limit the width of the SashForm. See http://bugs.eclipse.org/bugs/show_bug.cgi?id=6854 - Composite result= new Composite(parent, SWT.NONE); - GridLayout layout= new GridLayout(); - layout.marginHeight= 0; layout.marginWidth= 0; - result.setLayout(layout); - - SashForm sashForm= new SashForm(result, SWT.HORIZONTAL); - - ViewerPane pane= new ViewerPane(sashForm, SWT.BORDER | SWT.FLAT); - pane.setText(RefactoringMessages.getString("PreviewWizardPage.changes")); //$NON-NLS-1$ - ToolBarManager tbm= pane.getToolBarManager(); - tbm.add(new NextChange()); - tbm.add(new PreviousChange()); - tbm.update(true); - - fTreeViewer= createTreeViewer(pane); - fTreeViewer.setContentProvider(createTreeContentProvider()); - fTreeViewer.setLabelProvider(createTreeLabelProvider()); - fTreeViewer.addSelectionChangedListener(createSelectionChangedListener()); - fTreeViewer.addCheckStateListener(createCheckStateListener()); - pane.setContent(fTreeViewer.getControl()); - setTreeViewerInput(); -//////// -// fPreviewContainer= new PageBook(sashForm, SWT.NONE); -// fNullPreviewer= new NullPreviewer(); -// fNullPreviewer.createControl(fPreviewContainer); -// fPreviewContainer.showPage(fNullPreviewer.getControl()); -// fCurrentPreviewViewer= fNullPreviewer; -// fCurrentDescriptor= null; -// sashForm.setWeights(new int[]{33, 67}); -//////// - GridData gd= new GridData(GridData.FILL_BOTH); - gd.widthHint= convertWidthInCharsToPixels(80); - sashForm.setLayoutData(gd); - Dialog.applyDialogFont(result); - return result; - } - - private Control createNullPage(Composite parent) { - Composite result= new Composite(parent, SWT.NONE); - GridLayout layout= new GridLayout(); - layout.marginWidth = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN); - layout.marginHeight = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN); - result.setLayout(layout); - Label label= new Label(result, SWT.CENTER); - label.setText(RefactoringMessages.getString("PreviewWizardPage.no_source_code_change")); //$NON-NLS-1$ - label.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); - Dialog.applyDialogFont(result); - return result; - } - - public void setVisible(boolean visible) { - fCurrentSelection= null; - if (hasChanges()) { - fPageContainer.showPage(fStandardPage); - ChangeElement treeViewerInput= (ChangeElement)fTreeViewer.getInput(); - if (visible && treeViewerInput != null) { - IStructuredSelection selection= (IStructuredSelection)fTreeViewer.getSelection(); - if (selection.isEmpty()) { - ITreeContentProvider provider= (ITreeContentProvider)fTreeViewer.getContentProvider(); - Object[] elements= provider.getElements(treeViewerInput); - if (elements != null && elements.length > 0) { - Object element= elements[0]; - if (getRefactoringWizard().getExpandFirstNode()) { - Object[] subElements= provider.getElements(element); - if (subElements != null && subElements.length > 0) { - fTreeViewer.expandToLevel(element, 999); - } - } - fTreeViewer.setSelection(new StructuredSelection(element)); - } - } - } - super.setVisible(visible); - fTreeViewer.getControl().setFocus(); - } else { - fPageContainer.showPage(fNullPage); - super.setVisible(visible); - } - getRefactoringWizard().setPreviewShown(visible); - } - - private void setTreeViewerInput() { - ChangeElement input; - IChange change= computeChangeInput(); - if (change == null) { - input= null; - } else if (change instanceof ICompositeChange && !(change instanceof TextChange)) { - input= new DefaultChangeElement(null, change); - } else { - input= new DefaultChangeElement(null, new DummyRootNode(change)); - } - if (fTreeViewer != null) { - fTreeViewer.setInput(input); - } - } - - private IChange computeChangeInput() { - IChange result= fChange; - if (result == null) - return result; - while (true) { - if (result instanceof ICompositeChange) { - IChange[] children= ((ICompositeChange)result).getChildren(); - if (children.length == 1) { - result= children[0]; - } else { - return result; - } - } else { - return result; - } - } - } - - private ICheckStateListener createCheckStateListener() { - return new ICheckStateListener() { - public void checkStateChanged(CheckStateChangedEvent event){ - ChangeElement element= (ChangeElement)event.getElement(); - if (isChild(fCurrentSelection, element) || isChild(element, fCurrentSelection)) { - showPreview(fCurrentSelection); - } - } - private boolean isChild(ChangeElement element, ChangeElement child) { - while (child != null) { - if (child == element) - return true; - child= child.getParent(); - } - return false; - } - }; - } - - private ISelectionChangedListener createSelectionChangedListener() { - return new ISelectionChangedListener(){ - public void selectionChanged(SelectionChangedEvent event) { - IStructuredSelection sel= (IStructuredSelection) event.getSelection(); - if (sel.size() == 1) { - ChangeElement newSelection= (ChangeElement)sel.getFirstElement(); - if (newSelection != fCurrentSelection) { - fCurrentSelection= newSelection; - showPreview(newSelection); - } - } else { - showPreview(null); - } - } - }; - } - - private void showPreview(ChangeElement element) { -///////////// -// try { -// if (element == null) { - showNullPreviewer(); -// } else { -// ChangePreviewViewerDescriptor descriptor= element.getChangePreviewViewer(); -// if (fCurrentDescriptor != descriptor) { -// IChangePreviewViewer newViewer; -// if (descriptor != null) { -// newViewer= descriptor.createViewer(); -// newViewer.createControl(fPreviewContainer); -// } else { -// newViewer= fNullPreviewer; -// } -// fCurrentDescriptor= descriptor; -// element.feedInput(newViewer); -// if (fCurrentPreviewViewer != null && fCurrentPreviewViewer != fNullPreviewer) -// fCurrentPreviewViewer.getControl().dispose(); -// fCurrentPreviewViewer= newViewer; -// fPreviewContainer.showPage(fCurrentPreviewViewer.getControl()); -// } else { -// element.feedInput(fCurrentPreviewViewer); -// } -// } -// } catch (CoreException e) { -// showNullPreviewer(); -// } -/////////// - } - - private void showNullPreviewer() { -///////// -// fCurrentDescriptor= null; -// fCurrentPreviewViewer= fNullPreviewer; -// fPreviewContainer.showPage(fCurrentPreviewViewer.getControl()); -///////// - } - - public boolean hasChanges() { - if (fChange == null) - return false; - if (fChange instanceof ICompositeChange) - return ((ICompositeChange)fChange).getChildren().length > 0; - return true; - } - -} diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/PseudoCChangeElement.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/PseudoCChangeElement.java deleted file mode 100644 index 4cb417cbf02..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/PseudoCChangeElement.java +++ /dev/null @@ -1,163 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.refactoring; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.cdt.core.model.ISourceRange; -import org.eclipse.cdt.core.model.ISourceReference; -import org.eclipse.cdt.internal.corext.refactoring.base.IChange; -import org.eclipse.cdt.internal.corext.refactoring.changes.TextChange; -import org.eclipse.cdt.internal.corext.refactoring.changes.TextChange.EditChange; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.Region; -import org.eclipse.jface.util.Assert; - -/* package */ class PseudoCChangeElement extends ChangeElement { - - private ICElement fCElement; - private List fChildren; - - public PseudoCChangeElement(ChangeElement parent, ICElement element) { - super(parent); - fCElement= element; - Assert.isNotNull(fCElement); - } - - /** - * Returns the C element. - * - * @return the C element managed by this node - */ - public ICElement getCElement() { - return fCElement; - } - - /* (non-Cdoc) - * @see org.eclipse.jdt.internal.ui.refactoring.ChangeElement#getChangePreviewViewer() - */ -// public ChangePreviewViewerDescriptor getChangePreviewViewer() throws CoreException { -// DefaultChangeElement element= getStandardChangeElement(); -// if (element == null) -// return null; -// return element.getChangePreviewViewer(); -// } - - /* (non-Javadoc) - * @see org.eclipse.jdt.internal.ui.refactoring.ChangeElement#feedInput(org.eclipse.jdt.internal.ui.refactoring.IChangePreviewViewer) - */ - public void feedInput(IChangePreviewViewer viewer) throws CoreException { - DefaultChangeElement element= getStandardChangeElement(); - if (element != null) { - IChange change= element.getChange(); - if (change instanceof TextChange) { - List edits= collectTextEditChanges(); - viewer.setInput(TextChangePreviewViewer.createInput( - (EditChange[])edits.toArray(new EditChange[edits.size()]), - getTextRange())); - } - } else { - viewer.setInput(null); - } - } - - /* non Java-doc - * @see ChangeElement#setActive - */ - public void setActive(boolean active) { - for (Iterator iter= fChildren.iterator(); iter.hasNext();) { - ChangeElement element= (ChangeElement)iter.next(); - element.setActive(active); - } - } - - /* non Java-doc - * @see ChangeElement.getActive - */ - public int getActive() { - Assert.isTrue(fChildren.size() > 0); - int result= ((ChangeElement)fChildren.get(0)).getActive(); - for (int i= 1; i < fChildren.size(); i++) { - ChangeElement element= (ChangeElement)fChildren.get(i); - result= ACTIVATION_TABLE[element.getActive()][result]; - if (result == PARTLY_ACTIVE) - break; - } - return result; - } - - /* non Java-doc - * @see ChangeElement.getChildren - */ - public ChangeElement[] getChildren() { - if (fChildren == null) - return EMPTY_CHILDREN; - return (ChangeElement[]) fChildren.toArray(new ChangeElement[fChildren.size()]); - } - - /** - * Adds the given TextEditChangeElement as a child to this - * PseudoCChangeElement - * - * @param child the child to be added - */ - public void addChild(TextEditChangeElement child) { - doAddChild(child); - } - - /** - * Adds the given PseudoCChangeElement as a child to this - * PseudoCChangeElement - * - * @param child the child to be added - */ - public void addChild(PseudoCChangeElement child) { - doAddChild(child); - } - - private void doAddChild(ChangeElement child) { - if (fChildren == null) - fChildren= new ArrayList(2); - fChildren.add(child); - } - - private DefaultChangeElement getStandardChangeElement() { - ChangeElement element= getParent(); - while(!(element instanceof DefaultChangeElement) && element != null) { - element= element.getParent(); - } - return (DefaultChangeElement)element; - } - - private List collectTextEditChanges() { - List result= new ArrayList(10); - ChangeElement[] children= getChildren(); - for (int i= 0; i < children.length; i++) { - ChangeElement child= children[i]; - if (child instanceof TextEditChangeElement) { - result.add(((TextEditChangeElement)child).getTextEditChange()); - } else if (child instanceof PseudoCChangeElement) { - result.addAll(((PseudoCChangeElement)child).collectTextEditChanges()); - } - } - return result; - } - - public IRegion getTextRange() throws CoreException { - ISourceRange range= ((ISourceReference)fCElement).getSourceRange(); - return new Region(range.getStartPos(), range.getLength()); - } -} - diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/RefactoringErrorDialogUtil.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/RefactoringErrorDialogUtil.java deleted file mode 100644 index ce8e27ce3f6..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/RefactoringErrorDialogUtil.java +++ /dev/null @@ -1,60 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.refactoring; - -import org.eclipse.swt.widgets.Shell; - -import org.eclipse.jface.dialogs.MessageDialog; - -import org.eclipse.cdt.internal.ui.refactoring.RefactoringMessages; -import org.eclipse.cdt.internal.ui.refactoring.RefactoringStatusContentProvider; -import org.eclipse.cdt.internal.ui.refactoring.RefactoringStatusEntryLabelProvider; - -import org.eclipse.cdt.internal.corext.refactoring.base.RefactoringStatus; -import org.eclipse.cdt.internal.corext.refactoring.base.RefactoringStatusCodes; -import org.eclipse.cdt.internal.corext.refactoring.base.RefactoringStatusEntry; - -public class RefactoringErrorDialogUtil { - - private RefactoringErrorDialogUtil() { - // no instance. - } - - public static Object open(String dialogTitle, RefactoringStatus status, Shell parentShell) { - if (status.getEntries().size() == 1) { - RefactoringStatusEntry entry= (RefactoringStatusEntry)status.getEntries().get(0); - String message= status.getFirstMessage(RefactoringStatus.FATAL); - - if ( entry.getCode() != RefactoringStatusCodes.OVERRIDES_ANOTHER_METHOD - && entry.getCode() != RefactoringStatusCodes.METHOD_DECLARED_IN_INTERFACE){ - MessageDialog.openInformation(parentShell, dialogTitle, message); - return null; - } - message= message + RefactoringMessages.getString("RefactoringErrorDialogUtil.okToPerformQuestion"); //$NON-NLS-1$ - if (MessageDialog.openQuestion(parentShell, dialogTitle, message)) - return entry.getData(); - return null; - } else { - openListDialog(dialogTitle, status, parentShell); - return null; - } - } - - private static void openListDialog(String dialogTitle, RefactoringStatus status, Shell parentShell) { - ListDialog dialog= new ListDialog(parentShell); - dialog.setInput(status); - dialog.setTitle(dialogTitle); - dialog.setMessage(RefactoringMessages.getString("RefactoringErrorDialogUtil.cannot_perform")); //$NON-NLS-1$ - dialog.setContentProvider(new RefactoringStatusContentProvider()); - dialog.setLabelProvider(new RefactoringStatusEntryLabelProvider()); - dialog.open(); - } -} diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/RefactoringExecutionHelper.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/RefactoringExecutionHelper.java deleted file mode 100644 index 875d58a0dcf..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/RefactoringExecutionHelper.java +++ /dev/null @@ -1,223 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.refactoring; - -import java.lang.reflect.InvocationTargetException; -import java.util.ArrayList; -import java.util.List; - -import org.eclipse.swt.widgets.Shell; - -import org.eclipse.jface.dialogs.IDialogConstants; -import org.eclipse.jface.operation.IRunnableContext; -import org.eclipse.jface.operation.IRunnableWithProgress; -import org.eclipse.jface.text.Assert; -import org.eclipse.jface.text.IRewriteTarget; - -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.NullProgressMonitor; -import org.eclipse.core.runtime.SubProgressMonitor; - -import org.eclipse.core.resources.IWorkspaceRunnable; - -import org.eclipse.ui.IEditorPart; - -import org.eclipse.cdt.core.model.CoreModel; - -import org.eclipse.cdt.internal.corext.refactoring.base.ChangeAbortException; -import org.eclipse.cdt.internal.corext.refactoring.base.ChangeContext; -import org.eclipse.cdt.internal.corext.refactoring.base.IChange; -import org.eclipse.cdt.internal.corext.refactoring.base.IRefactoring; -import org.eclipse.cdt.internal.corext.refactoring.base.IUndoManager; -import org.eclipse.cdt.internal.corext.refactoring.base.Refactoring; -import org.eclipse.cdt.internal.corext.refactoring.base.RefactoringStatus; - -import org.eclipse.cdt.ui.CUIPlugin; -import org.eclipse.cdt.internal.ui.refactoring.AbortChangeExceptionHandler; -import org.eclipse.cdt.internal.ui.refactoring.ChangeExceptionHandler; -import org.eclipse.cdt.internal.ui.util.ExceptionHandler; - -/** - * A helper class to execute a refactoring. The class takes care of pushing the - * undo change onto the undo stack and folding editor edits into one editor - * undo object. - */ -public class RefactoringExecutionHelper { - - private final IRefactoring fRefactoring; - private final Shell fParent; - private final IRunnableContext fExecContext; - private final int fStopSeverity; - private final boolean fNeedsSavedEditors; - private ChangeContext fContext; - - private class Operation implements IRunnableWithProgress { - public IChange fChange; - public void run(IProgressMonitor pm) throws InvocationTargetException, InterruptedException { - try { - pm.beginTask("", 10); //$NON-NLS-1$ - pm.subTask(""); //$NON-NLS-1$ - RefactoringStatus status= fRefactoring.checkPreconditions(new SubProgressMonitor(pm, 4, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK)); - if (status.getSeverity() >= fStopSeverity) { - RefactoringStatusDialog dialog= new RefactoringStatusDialog(fParent, status, fRefactoring.getName(), false); - if(dialog.open() == IDialogConstants.CANCEL_ID) { - throw new InterruptedException(); - } - } - fChange= fRefactoring.createChange(new SubProgressMonitor(pm, 2, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK)); - try { - fChange.aboutToPerform(fContext, new NullProgressMonitor()); - CoreModel.run(new IWorkspaceRunnable() { - public void run(IProgressMonitor monitor) throws CoreException { - fChange.perform(fContext, monitor); - } - }, new SubProgressMonitor(pm, 4, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK)); - } finally { - fChange.performed(); - } - } catch (ChangeAbortException e) { - throw new InvocationTargetException(e); - } catch (CoreException e) { - throw new InvocationTargetException(e); - } finally { - pm.done(); - } - } - public boolean isExecuted() { - return fChange != null; - } - public boolean isUndoable() { - return fChange.isUndoable(); - } - public IChange getUndoChange() { - return fChange.getUndoChange(); - } - } - - public RefactoringExecutionHelper(IRefactoring refactoring, int stopSevertity, boolean needsSavedEditors, Shell parent, IRunnableContext context) { - super(); - Assert.isNotNull(refactoring); - Assert.isNotNull(parent); - Assert.isNotNull(context); - fRefactoring= refactoring; - fStopSeverity= stopSevertity; - fParent= parent; - fExecContext= context; - fNeedsSavedEditors= needsSavedEditors; - } - - public void perform() throws InterruptedException, InvocationTargetException { - RefactoringSaveHelper saveHelper= new RefactoringSaveHelper(); - if (fNeedsSavedEditors && !saveHelper.saveEditors(fParent)) - throw new InterruptedException(); - fContext= new ChangeContext(new ChangeExceptionHandler(fParent)); - boolean success= false; - IUndoManager undoManager= Refactoring.getUndoManager(); - Operation op= new Operation(); - IRewriteTarget[] targets= null; - try{ - targets= getRewriteTargets(); - beginCompoundChange(targets); - undoManager.aboutToPerformRefactoring(); - fExecContext.run(false, false, op); - if (op.isExecuted()) { - if (!op.isUndoable()) { - success= false; - } else { - undoManager.addUndo(fRefactoring.getName(), op.getUndoChange()); - success= true; - } - } - } catch (InvocationTargetException e) { - Throwable t= e.getTargetException(); - if (t instanceof ChangeAbortException) { - handleChangeAbortException((ChangeAbortException)t); - } else { - throw e; - } - } finally { - fContext.clearPerformedChanges(); - undoManager.refactoringPerformed(success); - saveHelper.triggerBuild(); - if (targets != null) - endCompoundChange(targets); - } - } - - private void handleChangeAbortException(ChangeAbortException exception) { - if (!fContext.getTryToUndo()) - return; - - IRunnableWithProgress op= new IRunnableWithProgress() { - public void run(IProgressMonitor monitor) throws InterruptedException, InvocationTargetException { - try { - CoreModel.run(new IWorkspaceRunnable() { - public void run(IProgressMonitor pm) throws CoreException { - ChangeContext undoContext= new ChangeContext(new AbortChangeExceptionHandler()); - IChange[] changes= fContext.getPerformedChanges(); - pm.beginTask(RefactoringMessages.getString("RefactoringWizard.undoing"), changes.length); //$NON-NLS-1$ - IProgressMonitor sub= new NullProgressMonitor(); - for (int i= changes.length - 1; i >= 0; i--) { - IChange change= changes[i]; - pm.subTask(change.getName()); - change.getUndoChange().perform(undoContext, sub); - pm.worked(1); - } - } - }, monitor); - } catch (ChangeAbortException e) { - throw new InvocationTargetException(e.getThrowable()); - } catch (CoreException e) { - throw new InvocationTargetException(e); - } finally { - monitor.done(); - } - } - }; - - try { - fExecContext.run(false, false, op); - } catch (InvocationTargetException e) { - handleUnexpectedException(e); - } catch (InterruptedException e) { - // not possible. Operation not cancelable. - } - } - - private void handleUnexpectedException(InvocationTargetException e) { - ExceptionHandler.handle(e, RefactoringMessages.getString("RefactoringWizard.refactoring"), RefactoringMessages.getString("RefactoringWizard.unexpected_exception_1")); //$NON-NLS-2$ //$NON-NLS-1$ - } - - private static void beginCompoundChange(IRewriteTarget[] targets) { - for (int i= 0; i < targets.length; i++) { - targets[i].beginCompoundChange(); - } - } - - private static void endCompoundChange(IRewriteTarget[] targets) { - for (int i= 0; i < targets.length; i++) { - targets[i].endCompoundChange(); - } - } - - private static IRewriteTarget[] getRewriteTargets() { - IEditorPart[] editors= CUIPlugin.getInstanciatedEditors(); - List result= new ArrayList(editors.length); - for (int i= 0; i < editors.length; i++) { - IRewriteTarget target= (IRewriteTarget)editors[i].getAdapter(IRewriteTarget.class); - if (target != null) { - result.add(target); - } - } - return (IRewriteTarget[]) result.toArray(new IRewriteTarget[result.size()]); - } -} diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/RefactoringMessages.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/RefactoringMessages.java deleted file mode 100644 index 99a7dcd5694..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/RefactoringMessages.java +++ /dev/null @@ -1,49 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.refactoring; - -import java.text.MessageFormat; -import java.util.MissingResourceException; -import java.util.ResourceBundle; - -public class RefactoringMessages { - - private static final String RESOURCE_BUNDLE= "org.eclipse.cdt.internal.ui.refactoring.refactoringui";//$NON-NLS-1$ - - private static ResourceBundle fgResourceBundle= ResourceBundle.getBundle(RESOURCE_BUNDLE); - - private RefactoringMessages() { - } - - public static String getString(String key) { - try { - return fgResourceBundle.getString(key); - } catch (MissingResourceException e) { - return "!" + key + "!";//$NON-NLS-2$ //$NON-NLS-1$ - } - } - - public static String[] getStrings(String keys[]) { - String[] result= new String[keys.length]; - for (int i= 0; i < keys.length; i++) { - result[i]= getString(keys[i]); - } - return result; - } - - public static String getFormattedString(String key, Object arg) { - return getFormattedString(key, new Object[] { arg }); - } - - public static String getFormattedString(String key, Object[] args) { - return MessageFormat.format(getString(key), args); - } -} diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/RefactoringPreferences.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/RefactoringPreferences.java deleted file mode 100644 index 330009e63b4..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/RefactoringPreferences.java +++ /dev/null @@ -1,56 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.cdt.internal.ui.refactoring; - -import org.eclipse.jface.preference.IPreferenceStore; - -import org.eclipse.cdt.ui.PreferenceConstants; - -import org.eclipse.cdt.internal.corext.refactoring.base.RefactoringStatus; -import org.eclipse.cdt.ui.CUIPlugin; - -public class RefactoringPreferences { - - public static final String PREF_ERROR_PAGE_SEVERITY_THRESHOLD= PreferenceConstants.REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD; - public static final String PREF_SAVE_ALL_EDITORS= PreferenceConstants.REFACTOR_SAVE_ALL_EDITORS; - - public static int getCheckPassedSeverity() { - String value= CUIPlugin.getDefault().getPreferenceStore().getString(PREF_ERROR_PAGE_SEVERITY_THRESHOLD); - try { - return Integer.valueOf(value).intValue() - 1; - } catch (NumberFormatException e) { - return RefactoringStatus.ERROR; - } - } - - public static int getStopSeverity() { - switch (getCheckPassedSeverity()) { - case RefactoringStatus.OK: - return RefactoringStatus.INFO; - case RefactoringStatus.INFO: - return RefactoringStatus.WARNING; - case RefactoringStatus.WARNING: - return RefactoringStatus.ERROR; - } - return RefactoringStatus.FATAL; - } - - public static boolean getSaveAllEditors() { - IPreferenceStore store= CUIPlugin.getDefault().getPreferenceStore(); - return store.getBoolean(PREF_SAVE_ALL_EDITORS); - } - - public static void setSaveAllEditors(boolean save) { - IPreferenceStore store= CUIPlugin.getDefault().getPreferenceStore(); - store.setValue(RefactoringPreferences.PREF_SAVE_ALL_EDITORS, save); - } -} diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/RefactoringSaveHelper.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/RefactoringSaveHelper.java deleted file mode 100644 index 8efa0726057..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/RefactoringSaveHelper.java +++ /dev/null @@ -1,121 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.refactoring; - -import java.util.Arrays; - -import org.eclipse.core.resources.IWorkspace; -import org.eclipse.core.resources.IWorkspaceDescription; -import org.eclipse.core.resources.IncrementalProjectBuilder; -import org.eclipse.core.resources.ResourcesPlugin; -import org.eclipse.core.runtime.CoreException; - -import org.eclipse.swt.SWT; -import org.eclipse.swt.events.SelectionAdapter; -import org.eclipse.swt.events.SelectionEvent; -import org.eclipse.swt.graphics.Image; -import org.eclipse.swt.widgets.Button; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Control; -import org.eclipse.swt.widgets.Shell; - -import org.eclipse.jface.viewers.ILabelProvider; -import org.eclipse.jface.viewers.LabelProvider; -import org.eclipse.jface.window.Window; - -import org.eclipse.ui.IEditorPart; -import org.eclipse.ui.actions.GlobalBuildAction; - -import org.eclipse.cdt.ui.CUIPlugin; -import org.eclipse.cdt.internal.ui.refactoring.ListDialog; -import org.eclipse.cdt.internal.ui.util.ExceptionHandler; -import org.eclipse.cdt.internal.ui.viewsupport.ListContentProvider; - -public class RefactoringSaveHelper { - - private boolean fFilesSaved; - - public RefactoringSaveHelper() { - super(); - } - - public boolean saveEditors(Shell shell) { - IEditorPart[] dirtyEditors= CUIPlugin.getDirtyEditors(); - if (dirtyEditors.length == 0) - return true; - if (! saveAllDirtyEditors(shell)) - return false; - try { - // Save isn't cancelable. - IWorkspace workspace= ResourcesPlugin.getWorkspace(); - IWorkspaceDescription description= workspace.getDescription(); - boolean autoBuild= description.isAutoBuilding(); - description.setAutoBuilding(false); - workspace.setDescription(description); - try { - CUIPlugin.getActiveWorkbenchWindow().getWorkbench().saveAllEditors(false); - fFilesSaved= true; - } finally { - description.setAutoBuilding(autoBuild); - workspace.setDescription(description); - } - return true; - } catch (CoreException e) { - ExceptionHandler.handle(e, shell, - RefactoringMessages.getString("RefactoringStarter.saving"), RefactoringMessages.getString("RefactoringStarter.unexpected_exception")); //$NON-NLS-1$ //$NON-NLS-2$ - return false; - } - } - - public void triggerBuild() { - if (fFilesSaved && ResourcesPlugin.getWorkspace().getDescription().isAutoBuilding()) { - new GlobalBuildAction(CUIPlugin.getActiveWorkbenchWindow(), IncrementalProjectBuilder.INCREMENTAL_BUILD).run(); - } - } - - private boolean saveAllDirtyEditors(Shell shell) { - if (RefactoringPreferences.getSaveAllEditors()) //must save everything - return true; - ListDialog dialog= new ListDialog(shell) { - protected Control createDialogArea(Composite parent) { - Composite result= (Composite) super.createDialogArea(parent); - final Button check= new Button(result, SWT.CHECK); - check.setText(RefactoringMessages.getString("RefactoringStarter.always_save")); //$NON-NLS-1$ - check.setSelection(RefactoringPreferences.getSaveAllEditors()); - check.addSelectionListener(new SelectionAdapter() { - public void widgetSelected(SelectionEvent e) { - RefactoringPreferences.setSaveAllEditors(check.getSelection()); - } - }); - applyDialogFont(result); - return result; - } - }; - dialog.setTitle(RefactoringMessages.getString("RefactoringStarter.save_all_resources")); //$NON-NLS-1$ - dialog.setAddCancelButton(true); - dialog.setLabelProvider(createDialogLabelProvider()); - dialog.setMessage(RefactoringMessages.getString("RefactoringStarter.must_save")); //$NON-NLS-1$ - dialog.setContentProvider(new ListContentProvider()); - dialog.setInput(Arrays.asList(CUIPlugin.getDirtyEditors())); - return dialog.open() == Window.OK; - } - - private ILabelProvider createDialogLabelProvider() { - return new LabelProvider() { - public Image getImage(Object element) { - return ((IEditorPart) element).getTitleImage(); - } - public String getText(Object element) { - return ((IEditorPart) element).getTitle(); - } - }; - } -} diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/RefactoringStarter.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/RefactoringStarter.java deleted file mode 100644 index 86c3515dc69..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/RefactoringStarter.java +++ /dev/null @@ -1,83 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.refactoring; - - -import java.lang.reflect.InvocationTargetException; - -import org.eclipse.swt.widgets.Shell; - -import org.eclipse.jface.dialogs.Dialog; -import org.eclipse.jface.operation.IRunnableContext; -import org.eclipse.jface.util.Assert; -import org.eclipse.jface.window.Window; - -import org.eclipse.cdt.core.model.CModelException; - -import org.eclipse.cdt.internal.ui.refactoring.CheckConditionsOperation; -import org.eclipse.cdt.internal.ui.refactoring.RefactoringMessages; -import org.eclipse.cdt.internal.ui.refactoring.RefactoringSaveHelper; -import org.eclipse.cdt.internal.ui.refactoring.RefactoringWizard; -import org.eclipse.cdt.internal.ui.refactoring.RefactoringWizardDialog; -import org.eclipse.cdt.internal.ui.refactoring.RefactoringWizardDialog2; -import org.eclipse.cdt.internal.ui.util.BusyIndicatorRunnableContext; -import org.eclipse.cdt.internal.ui.util.ExceptionHandler; - -import org.eclipse.cdt.internal.corext.refactoring.base.Refactoring; -import org.eclipse.cdt.internal.corext.refactoring.base.RefactoringStatus; - -/** - * A helper class to activate the UI of a refactoring - */ -public class RefactoringStarter { - - private RefactoringSaveHelper fSaveHelper= new RefactoringSaveHelper(); - - public Object activate(Refactoring refactoring, RefactoringWizard wizard, Shell parent, String dialogTitle, boolean mustSaveEditors) throws CModelException { - if (! canActivate(mustSaveEditors, parent)) - return null; - RefactoringStatus activationStatus= checkActivation(refactoring); - if (activationStatus.hasFatalError()){ - return RefactoringErrorDialogUtil.open(dialogTitle, activationStatus, parent); - } else { - wizard.setActivationStatus(activationStatus); - Dialog dialog; - if (wizard.hasMultiPageUserInput()){ - dialog= new RefactoringWizardDialog(parent, wizard); - } - else { - dialog= new RefactoringWizardDialog2(parent, wizard); - } - if (dialog.open() == Window.CANCEL) - fSaveHelper.triggerBuild(); - return null; - } - } - - private RefactoringStatus checkActivation(Refactoring refactoring){ - try { - CheckConditionsOperation cco= new CheckConditionsOperation(refactoring, CheckConditionsOperation.ACTIVATION); - IRunnableContext context= new BusyIndicatorRunnableContext(); - context.run(false, false, cco); - return cco.getStatus(); - } catch (InvocationTargetException e) { - ExceptionHandler.handle(e, "Error", RefactoringMessages.getString("RefactoringStarter.unexpected_exception"));//$NON-NLS-1$ //$NON-NLS-2$ - return RefactoringStatus.createFatalErrorStatus(RefactoringMessages.getString("RefactoringStarter.unexpected_exception"));//$NON-NLS-1$ - } catch (InterruptedException e) { - Assert.isTrue(false); - return null; - } - } - - private boolean canActivate(boolean mustSaveEditors, Shell shell) { - return ! mustSaveEditors || fSaveHelper.saveEditors(shell); - } -} diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/RefactoringStatusContentProvider.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/RefactoringStatusContentProvider.java deleted file mode 100644 index fd5f21633db..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/RefactoringStatusContentProvider.java +++ /dev/null @@ -1,30 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.refactoring; - -import org.eclipse.jface.viewers.IStructuredContentProvider; -import org.eclipse.jface.viewers.Viewer; - -import org.eclipse.cdt.internal.corext.refactoring.base.RefactoringStatus; - -public class RefactoringStatusContentProvider implements IStructuredContentProvider{ - - public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { - } - - public void dispose() { - } - - public Object[] getElements(Object obj) { - return ((RefactoringStatus)obj).getEntries().toArray(); - } -} - diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/RefactoringStatusDialog.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/RefactoringStatusDialog.java deleted file mode 100644 index 602bb8a6059..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/RefactoringStatusDialog.java +++ /dev/null @@ -1,104 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.refactoring; - -import org.eclipse.swt.SWT; -import org.eclipse.swt.custom.ViewForm; -import org.eclipse.swt.graphics.Color; -import org.eclipse.swt.graphics.Rectangle; -import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.layout.GridLayout; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Control; -import org.eclipse.swt.widgets.Label; -import org.eclipse.swt.widgets.Shell; - -import org.eclipse.jface.dialogs.Dialog; -import org.eclipse.jface.dialogs.IDialogConstants; - -import org.eclipse.cdt.internal.corext.refactoring.base.RefactoringStatus; - -class RefactoringStatusDialog extends Dialog { - - private RefactoringStatus fStatus; - private String fWindowTitle; - private boolean fBackButton; - - public RefactoringStatusDialog(Shell parent, RefactoringStatus status, String windowTitle, boolean backButton) { - super(parent); - fStatus= status; - fWindowTitle= windowTitle; - fBackButton= backButton; - setShellStyle(getShellStyle() | SWT.RESIZE); - } - - public RefactoringStatusDialog(Shell parent, ErrorWizardPage page, boolean backButton) { - this(parent, page.getStatus(), parent.getText(), backButton); - } - - protected void configureShell(Shell newShell) { - super.configureShell(newShell); - newShell.setText(fWindowTitle); - } - protected Control createDialogArea(Composite parent) { - Composite result= new Composite(parent, SWT.NONE); - initializeDialogUnits(result); - GridLayout layout= new GridLayout(); - result.setLayout(layout); - GridData gd= new GridData(GridData.FILL_BOTH); - gd.widthHint= 600; - gd.heightHint= 400; - result.setLayoutData(gd); - Color background= parent.getDisplay().getSystemColor(SWT.COLOR_INFO_BACKGROUND); - ViewForm messagePane= new ViewForm(result, SWT.BORDER | SWT.FLAT); - messagePane.marginWidth= layout.marginWidth; - messagePane.marginHeight= layout.marginHeight; - gd= new GridData(GridData.FILL_HORIZONTAL); - // XXX http://bugs.eclipse.org/bugs/show_bug.cgi?id=27572 - Rectangle rect= messagePane.computeTrim(0, 0, 0, convertHeightInCharsToPixels(2) + messagePane.marginHeight * 2); - gd.heightHint= rect.height; - messagePane.setLayoutData(gd); - messagePane.setBackground(background); - Label label= new Label(messagePane, SWT.LEFT | SWT.WRAP); - if (fStatus.hasFatalError()) - label.setText(RefactoringMessages.getString("RefactoringStatusDialog.Cannot_proceed")); //$NON-NLS-1$ - else - label.setText(RefactoringMessages.getString("RefactoringStatusDialog.Please_look")); //$NON-NLS-1$ - label.setBackground(background); - messagePane.setContent(label); - RefactoringStatusViewer viewer= new RefactoringStatusViewer(result, SWT.NONE); - viewer.setLayoutData(new GridData(GridData.FILL_BOTH)); - viewer.setStatus(fStatus); - applyDialogFont(result); - return result; - } - protected void buttonPressed(int buttonId) { - if (buttonId == IDialogConstants.BACK_ID) { - setReturnCode(IDialogConstants.BACK_ID); - close(); - } else { - super.buttonPressed(buttonId); - } - } - - protected void createButtonsForButtonBar(Composite parent) { - if (!fStatus.hasFatalError()) { - if (fBackButton) - createButton(parent, IDialogConstants.BACK_ID, IDialogConstants.BACK_LABEL, false); //$NON-NLS-1$ - createButton(parent, IDialogConstants.OK_ID, RefactoringMessages.getString("RefactoringStatusDialog.Continue"), true); //$NON-NLS-1$ - createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false); - } else { - if (fBackButton) - createButton(parent, IDialogConstants.BACK_ID, IDialogConstants.BACK_LABEL, true); //$NON-NLS-1$ - createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false); - } - } -} diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/RefactoringStatusEntryLabelProvider.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/RefactoringStatusEntryLabelProvider.java deleted file mode 100644 index 7b958b23ff1..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/RefactoringStatusEntryLabelProvider.java +++ /dev/null @@ -1,36 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.refactoring; - -import org.eclipse.swt.graphics.Image; - -import org.eclipse.jface.viewers.LabelProvider; - -import org.eclipse.cdt.internal.corext.refactoring.base.RefactoringStatusEntry; -import org.eclipse.cdt.internal.ui.util.Strings; -import org.eclipse.cdt.internal.ui.CPluginImages; - -public class RefactoringStatusEntryLabelProvider extends LabelProvider{ - public String getText(Object element){ - return Strings.removeNewLine(((RefactoringStatusEntry)element).getMessage()); - } - public Image getImage(Object element){ - RefactoringStatusEntry entry= (RefactoringStatusEntry)element; - if (entry.isFatalError()) - return CPluginImages.get(CPluginImages.IMG_OBJS_REFACTORING_FATAL); - else if (entry.isError()) - return CPluginImages.get(CPluginImages.IMG_OBJS_REFACTORING_ERROR); - else if (entry.isWarning()) - return CPluginImages.get(CPluginImages.IMG_OBJS_REFACTORING_WARNING); - else - return CPluginImages.get(CPluginImages.IMG_OBJS_REFACTORING_INFO); - } -} diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/RefactoringStatusViewer.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/RefactoringStatusViewer.java deleted file mode 100644 index cb61dc7ca86..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/RefactoringStatusViewer.java +++ /dev/null @@ -1,346 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.refactoring; - -import java.util.List; - -import org.eclipse.cdt.internal.corext.refactoring.base.Context; -import org.eclipse.cdt.internal.corext.refactoring.base.RefactoringStatus; -import org.eclipse.cdt.internal.corext.refactoring.base.RefactoringStatusEntry; -import org.eclipse.cdt.internal.ui.ICHelpContextIds; -import org.eclipse.cdt.internal.ui.util.PixelConverter; -import org.eclipse.cdt.internal.ui.util.ViewerPane; -import org.eclipse.compare.CompareUI; -import org.eclipse.core.runtime.IAdaptable; -import org.eclipse.jface.action.Action; -import org.eclipse.jface.action.ToolBarManager; -import org.eclipse.jface.resource.ImageDescriptor; -import org.eclipse.jface.viewers.ISelection; -import org.eclipse.jface.viewers.ISelectionChangedListener; -import org.eclipse.jface.viewers.IStructuredSelection; -import org.eclipse.jface.viewers.SelectionChangedEvent; -import org.eclipse.jface.viewers.StructuredSelection; -import org.eclipse.jface.viewers.TableViewer; -import org.eclipse.jface.viewers.Viewer; -import org.eclipse.jface.viewers.ViewerSorter; -import org.eclipse.swt.SWT; -import org.eclipse.swt.custom.SashForm; -import org.eclipse.swt.events.DisposeEvent; -import org.eclipse.swt.events.DisposeListener; -import org.eclipse.swt.graphics.Image; -import org.eclipse.swt.graphics.Point; -import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.layout.GridLayout; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Control; -import org.eclipse.swt.widgets.Label; -import org.eclipse.swt.widgets.Table; -import org.eclipse.swt.widgets.TableColumn; -import org.eclipse.ui.help.WorkbenchHelp; -import org.eclipse.ui.model.IWorkbenchAdapter; -import org.eclipse.ui.part.PageBook; - -class RefactoringStatusViewer extends SashForm { - - private static class NullContextViewer implements IStatusContextViewer { - private Label fLabel; - public NullContextViewer() { - } - public void createControl(Composite parent) { - fLabel= new Label(parent, SWT.CENTER | SWT.FLAT); - fLabel.setText(RefactoringMessages.getString("ErrorWizardPage.no_context_information_available")); //$NON-NLS-1$ - } - public void setInput(Context input) { - // do nothing - } - public Control getControl() { - return fLabel; - } - } - - private class NextProblem extends Action { - public NextProblem() { - setImageDescriptor(CompareUI.DESC_ETOOL_NEXT); - setDisabledImageDescriptor(CompareUI.DESC_DTOOL_NEXT); - setHoverImageDescriptor(CompareUI.DESC_CTOOL_NEXT); - setToolTipText(RefactoringMessages.getString("ErrorWizardPage.next_Change")); //$NON-NLS-1$ - WorkbenchHelp.setHelp(this, ICHelpContextIds.NEXT_PROBLEM_ACTION); - } - public void run() { - revealElement(true); - } - public void update() { - boolean enabled= false; - List entries= null; - if (fStatus != null && !(entries= fStatus.getEntries()).isEmpty()) { - int index= fTableViewer.getTable().getSelectionIndex(); - enabled= index == -1 || index < entries.size() - 1; - } - setEnabled(enabled); - } - } - - private class PreviousProblem extends Action { - public PreviousProblem() { - setImageDescriptor(CompareUI.DESC_ETOOL_PREV); - setDisabledImageDescriptor(CompareUI.DESC_DTOOL_PREV); - setHoverImageDescriptor(CompareUI.DESC_CTOOL_PREV); - setToolTipText(RefactoringMessages.getString("ErrorWizardPage.previous_Change")); //$NON-NLS-1$ - WorkbenchHelp.setHelp(this, ICHelpContextIds.PREVIOUS_PROBLEM_ACTION); - } - public void run() { - revealElement(false); - } - public void update() { - boolean enabled= false; - if (fStatus != null && !fStatus.getEntries().isEmpty()) { - int index= fTableViewer.getTable().getSelectionIndex(); - enabled= index == -1 || index > 0; - } - setEnabled(enabled); - } - } - - private static class RefactoringStatusSorter extends ViewerSorter { - public int compare(Viewer viewer, Object e1, Object e2) { - int r1= ((RefactoringStatusEntry)e1).getSeverity(); - int r2= ((RefactoringStatusEntry)e2).getSeverity(); - if (r1 < r2) - return 1; - if (r2 < r1) - return -1; - return 0; - } - - } - - private RefactoringStatus fStatus; - private TableViewer fTableViewer; - private PageBook fContextViewerContainer; - private ViewerPane fContextViewerPane; - private Image fPaneImage; - private StatusContextViewerDescriptor fCurrentDescriptor; - private IStatusContextViewer fCurrentContextViewer; - private NullContextViewer fNullContextViewer; - - private NextProblem fNextProblem; - private PreviousProblem fPreviousProblem; - - public RefactoringStatusViewer(Composite parent, int style) { - super(parent, style | SWT.VERTICAL); - createContents(); - } - - /** - * Sets the refactoring status. - * @param the refactoring status. - */ - public void setStatus(RefactoringStatus status){ - fStatus= status; - if (fTableViewer.getInput() != fStatus) { - fTableViewer.setInput(fStatus); - fTableViewer.getTable().getColumn(0).pack(); - ISelection selection= fTableViewer.getSelection(); - if (selection.isEmpty()) { - RefactoringStatusEntry entry= getFirstEntry(); - if (entry != null) { - fTableViewer.setSelection(new StructuredSelection(entry)); - showContextViewer(entry); - fTableViewer.getControl().setFocus(); - } - } - fNextProblem.update(); - fPreviousProblem.update(); - } - } - - /** - * Returns the currently used RefactoringStatus. - * @return the RefactoringStatus - */ - public RefactoringStatus getStatus() { - return fStatus; - } - - //---- UI creation ---------------------------------------------------------------------- - - public Point computeSize (int wHint, int hHint, boolean changed) { - PixelConverter converter= new PixelConverter(this); - return new Point(converter.convertWidthInCharsToPixels(90), converter.convertHeightInCharsToPixels(25)); - } - - private void createContents() { - GridLayout layout= new GridLayout(); - layout.numColumns= 1; layout.marginWidth= 0; layout.marginHeight= 0; - setLayout(layout); - - ViewerPane contextPane= new ViewerPane(this, SWT.BORDER | SWT.FLAT); - contextPane.setText(RefactoringMessages.getString("RefactoringStatusViewer.Found_problems")); //$NON-NLS-1$ - ToolBarManager tbm= contextPane.getToolBarManager(); - tbm.add(fNextProblem= new NextProblem()); - tbm.add(fPreviousProblem= new PreviousProblem()); - tbm.update(true); - createTableViewer(contextPane); - contextPane.setContent(fTableViewer.getControl()); - - fContextViewerPane= new ViewerPane(this, SWT.BORDER | SWT.FLAT); - fContextViewerContainer= new PageBook(fContextViewerPane, SWT.NONE); - fNullContextViewer= new NullContextViewer(); - fNullContextViewer.createControl(fContextViewerContainer); - fContextViewerContainer.showPage(fNullContextViewer.getControl()); - fCurrentContextViewer= fNullContextViewer; - fContextViewerPane.setContent(fContextViewerContainer); - fCurrentContextViewer= fNullContextViewer; - fCurrentDescriptor= null; - - setWeights(new int[]{35, 65}); - - addDisposeListener(new DisposeListener() { - public void widgetDisposed(DisposeEvent e) { - if (fPaneImage != null) { - fPaneImage.dispose(); - fPaneImage= null; - } - } - }); - } - - private void createTableViewer(Composite parent) { - fTableViewer= new TableViewer(new Table(parent, SWT.SINGLE | SWT.H_SCROLL)); - fTableViewer.setLabelProvider(new RefactoringStatusEntryLabelProvider()); - fTableViewer.setContentProvider(new RefactoringStatusContentProvider()); - fTableViewer.addSelectionChangedListener(new ISelectionChangedListener() { - public void selectionChanged(SelectionChangedEvent event) { - entrySelected(event.getSelection()); - fNextProblem.update(); - fPreviousProblem.update(); - } - }); - fTableViewer.setSorter(new RefactoringStatusSorter()); - Table tableControl= fTableViewer.getTable(); - GridData gd= new GridData(GridData.FILL_BOTH); - tableControl.setLayoutData(gd); - // Add a column so that we can pack it in setVisible. - TableColumn tc= new TableColumn(tableControl, SWT.NONE); - tc.setResizable(false); - } - - //---- Feed status entry into context viewer --------------------------------------------------------- - - private void entrySelected(ISelection s) { - if (!(s instanceof IStructuredSelection)) - return; - Object first= ((IStructuredSelection) s).getFirstElement(); - if (! (first instanceof RefactoringStatusEntry)) - return; - - RefactoringStatusEntry entry= (RefactoringStatusEntry)first; - updateTitle(entry); - showContextViewer(entry); - } - - private void updateTitle(RefactoringStatusEntry first) { - IAdaptable element= getCorrespondingElement(first); - String title= null; - ImageDescriptor imageDescriptor= null; - if (element != null) { - IWorkbenchAdapter adapter= (IWorkbenchAdapter)element.getAdapter(IWorkbenchAdapter.class); - if (adapter != null) { - title= adapter.getLabel(element); - imageDescriptor= adapter.getImageDescriptor(element); - } - } - if (title == null || title.length() == 0) - title= RefactoringMessages.getString("RefactoringStatusViewer.Problem_context"); //$NON-NLS-1$ - fContextViewerPane.setText(title); - if (imageDescriptor != null) { - if (fPaneImage != null) { - fPaneImage.dispose(); - fPaneImage= null; - } - fPaneImage= imageDescriptor.createImage(fContextViewerPane.getDisplay()); - fContextViewerPane.setImage(fPaneImage); - } - } - - private static IAdaptable getCorrespondingElement(RefactoringStatusEntry first){ - if (first.getContext() == null) - return null; - else - return first.getContext().getCorrespondingElement(); - } - - private void showContextViewer(RefactoringStatusEntry entry) { -/* Context context= entry.getContext(); - if (context == null) { - showNullContextViewer(); - } else { - try { - StatusContextViewerDescriptor descriptor= StatusContextViewerDescriptor.get(context); - if (fCurrentDescriptor != descriptor) { - IStatusContextViewer newViewer; - if (descriptor != null) { - newViewer= descriptor.createViewer(); - newViewer.createControl(fContextViewerContainer); - } else { - newViewer= fNullContextViewer; - } - fCurrentDescriptor= descriptor; - newViewer.setInput(context); - if (fCurrentContextViewer != null && fCurrentContextViewer != fNullContextViewer) - fCurrentContextViewer.getControl().dispose(); - fCurrentContextViewer= newViewer; - fContextViewerContainer.showPage(fCurrentContextViewer.getControl()); - } else { - fCurrentContextViewer.setInput(context); - } - } catch (CoreException e) { - showNullContextViewer(); - } - } -*/ } - - private void showNullContextViewer() { - fCurrentContextViewer= fNullContextViewer; - fCurrentDescriptor= null; - fContextViewerContainer.showPage(fCurrentContextViewer.getControl()); - } - - //---- Helpers ---------------------------------------------------------------------------------------- - - private RefactoringStatusEntry getFirstEntry(){ - if (fStatus == null || fStatus.getEntries().isEmpty()) - return null; - return (RefactoringStatusEntry)fStatus.getEntries().get(0); - } - - private void revealElement(boolean next) { - List entries= fStatus.getEntries(); - if (entries.isEmpty()) { - return; - } - int index= fTableViewer.getTable().getSelectionIndex(); - int last= entries.size() - 1; - boolean doIt= true; - if (index == -1) { - index= 0; - } else if (next && index < last) { - index++; - } else if (!next && index > 0) { - index--; - } else { - doIt= false; - } - if (doIt) - fTableViewer.setSelection(new StructuredSelection(entries.get(index))); - } - -} diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/RefactoringWizard.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/RefactoringWizard.java deleted file mode 100644 index 7fa9f6d3f8b..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/RefactoringWizard.java +++ /dev/null @@ -1,510 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.cdt.internal.ui.refactoring; - -import java.lang.reflect.InvocationTargetException; - -import org.eclipse.cdt.internal.corext.Assert; -import org.eclipse.cdt.internal.corext.refactoring.base.IChange; -import org.eclipse.cdt.internal.corext.refactoring.base.Refactoring; -import org.eclipse.cdt.internal.corext.refactoring.base.RefactoringStatus; -import org.eclipse.cdt.internal.ui.util.BusyIndicatorRunnableContext; -import org.eclipse.cdt.internal.ui.util.ExceptionHandler; -import org.eclipse.cdt.ui.CUIPlugin; -import org.eclipse.jface.operation.IRunnableContext; -import org.eclipse.jface.wizard.IWizardPage; -import org.eclipse.jface.wizard.Wizard; -import org.eclipse.ui.PlatformUI; - -public class RefactoringWizard extends Wizard { - - private String fDefaultPageTitle; - private Refactoring fRefactoring; - private IChange fChange; - private RefactoringStatus fActivationStatus= new RefactoringStatus(); - private RefactoringStatus fStatus; - private boolean fHasUserInputPages; - private boolean fExpandFirstNode; - private boolean fIsChangeCreationCancelable; - private boolean fPreviewReview; - private boolean fPreviewShown; - - public RefactoringWizard(Refactoring refactoring) { - this(); - Assert.isNotNull(refactoring); - fRefactoring= refactoring; - } - - public RefactoringWizard(Refactoring refactoring, String defaultPageTitle) { - this(refactoring); - Assert.isNotNull(defaultPageTitle); - fDefaultPageTitle= defaultPageTitle; - } - - - /** - * Creates a new refactoring wizard without initializing its - * state. This constructor should only be used to create a - * refactoring spcified via a plugin manifest file. Clients - * that us this API must make sure that the initialize - * method gets called. - * - * @see #initialize(Refactoring) - */ - public RefactoringWizard() { - setNeedsProgressMonitor(true); - setChangeCreationCancelable(true); - setWindowTitle(RefactoringMessages.getString("RefactoringWizard.title")); //$NON-NLS-1$ -// setDefaultPageImageDescriptor(CPluginImages.DESC_WIZBAN_REFACTOR); - } - - /** - * Initializes the refactoring with the given refactoring. This - * method should be called right after the wizard has been created - * using the default constructor. - * - * @param refactoring the refactoring this wizard is working - * on - * @see #RefactoringWizard() - */ - public void initialize(Refactoring refactoring) { - Assert.isNotNull(refactoring); - fRefactoring= refactoring; - } - - /** - * Sets the default page title to the given value. This value is used - * as a page title for wizard page's which don't provide their own - * page title. Setting this value has only an effect as long as the - * user interface hasn't been created yet. - * - * @param defaultPageTitle the default page title. - * @see Wizard#setDefaultPageImageDescriptor(org.eclipse.jface.resource.ImageDescriptor) - */ - public void setDefaultPageTitle(String defaultPageTitle) { - fDefaultPageTitle= defaultPageTitle; - } - - public void setChangeCreationCancelable(boolean isChangeCreationCancelable){ - fIsChangeCreationCancelable= isChangeCreationCancelable; - } - - //---- Hooks to overide --------------------------------------------------------------- - - /** - * Some refactorings do activation checking when the wizard is going to be opened. - * They do this since activation checking is expensive and can't be performed on - * opening a corresponding menu. Wizards that need activation checking on opening - * should reimplement this method and should return true. This default - * implementation returns false. - * - * @return true if activation checking should be performed on opening; - * otherwise false is returned - */ - protected boolean checkActivationOnOpen() { - return false; - } - - /** - * Hook to add user input pages to the wizard. This default implementation - * adds nothing. - */ - protected void addUserInputPages(){ - } - - /** - * Hook to add the error page to the wizard. This default implementation - * adds an ErrorWizardPage to the wizard. - */ - protected void addErrorPage(){ - addPage(new ErrorWizardPage()); - } - - /** - * Hook to add the page the gives a prefix of the changes to be performed. This default - * implementation adds a PreviewWizardPage to the wizard. - */ - protected void addPreviewPage(){ - addPage(new PreviewWizardPage()); - } - - /** - * Hook to determine if the wizard has more than one user input page without - * actually creating the pages. - * - * @return boolean true if multi page user input exists. - * Otherwise false is returned - */ - public boolean hasMultiPageUserInput() { - return false; - } - - protected int getMessageLineWidthInChars() { - return 80; - } - - protected boolean hasUserInputPages() { - return fHasUserInputPages; - } - - protected boolean hasPreviewPage() { - return true; - } - - protected boolean yesNoStyle() { - return false; - } - - //---- Setter and Getters ------------------------------------------------------------ - - /** - * Returns the refactoring this wizard is using. - */ - public Refactoring getRefactoring(){ - return fRefactoring; - } - - /** - * Sets the change object. - */ - public void setChange(IChange change){ - IPreviewWizardPage page= (IPreviewWizardPage)getPage(IPreviewWizardPage.PAGE_NAME); - if (page != null) - page.setChange(change); - fChange= change; - } - - /** - * Returns the current change object. - */ - public IChange getChange() { - return fChange; - } - - /** - * Sets the refactoring status. - * - * @param status the refactoring status to set. - */ - public void setStatus(RefactoringStatus status) { - ErrorWizardPage page= (ErrorWizardPage)getPage(ErrorWizardPage.PAGE_NAME); - if (page != null) - page.setStatus(status); - fStatus= status; - } - - /** - * Returns the current refactoring status. - */ - public RefactoringStatus getStatus() { - return fStatus; - } - - /** - * Sets the refactoring status returned from input checking. Any previously - * computed activation status is merged into the given status before it is set - * to the error page. - * - * @param status the input status to set. - * @see #getActivationStatus() - */ - public void setInputStatus(RefactoringStatus status) { - RefactoringStatus newStatus= new RefactoringStatus(); - if (fActivationStatus != null) - newStatus.merge(fActivationStatus); - newStatus.merge(status); - setStatus(newStatus); - } - - /** - * Sets the refactoring status returned from activation checking. - * - * @param status the activation status to be set. - */ - public void setActivationStatus(RefactoringStatus status) { - fActivationStatus= status; - setStatus(status); - } - - /** - * Returns the activation status computed during the start up off this - * wizard. This methdod returns null if no activation - * checking has been performed during startup. - * - * @return the activation status computed during startup. - */ - public RefactoringStatus getActivationStatus() { - return fActivationStatus; - } - - /** - * Returns the default page title used for pages that don't - * provide their own page title. - * - * @return the default page title. - */ - public String getDefaultPageTitle() { - return fDefaultPageTitle; - } - - /** - * Defines whether the frist node in the preview page is supposed to be expanded. - * - * @param expand true if the first node is to be expanded. Otherwise - * false - */ - public void setExpandFirstNode(boolean expand) { - fExpandFirstNode= true; - } - - /** - * Returns true if the first node in the preview page is supposed to be - * expanded. Otherwise false is returned. - * - * @return true if the first node in the preview page is supposed to be - * expanded; otherwise false - */ - public boolean getExpandFirstNode() { - return fExpandFirstNode; - } - - /** - * Computes the wizard page that should follow the user input page. This is - * either the error page or the proposed changes page, depending on the - * result of the condition checking. - * - * @return the wizard page that should be shown after the last user input - * page - */ - public IWizardPage computeUserInputSuccessorPage(IWizardPage caller) { - return computeUserInputSuccessorPage(caller, getContainer()); - } - - private IWizardPage computeUserInputSuccessorPage(IWizardPage caller, IRunnableContext context) { - IChange change= createChange(CheckConditionsOperation.INPUT, RefactoringStatus.OK, true, context); - // Status has been updated since we have passed true - RefactoringStatus status= getStatus(); - - // Creating the change has been canceled - if (change == null && status == null) { - setChange(change); - return caller; - } - - // Set change if we don't have fatal errors. - if (!status.hasFatalError()) - setChange(change); - - if (status.isOK()) { - return getPage(IPreviewWizardPage.PAGE_NAME); - } else { - return getPage(ErrorWizardPage.PAGE_NAME); - } - } - - /** - * Initialize all pages with the managed page title. - */ - private void initializeDefaultPageTitles() { - if (fDefaultPageTitle == null) - return; - - IWizardPage[] pages= getPages(); - for (int i= 0; i < pages.length; i++) { - IWizardPage page= pages[i]; - if (page.getTitle() == null) - page.setTitle(fDefaultPageTitle); - } - } - - /** - * Forces the visiting of the preview page. The OK/Finish button will be - * disabled until the user has reached the preview page. - */ - public void setPreviewReview(boolean review) { - fPreviewReview= review; - getContainer().updateButtons(); - } - - public void setPreviewShown(boolean shown) { - fPreviewShown= shown; - getContainer().updateButtons(); - } - - public boolean canFinish() { - if (fPreviewReview && !fPreviewShown) - return false; - return super.canFinish(); - } - - - //---- Change management ------------------------------------------------------------- - - /** - * Creates a new change object for the refactoring. Method returns - * null if the change cannot be created. - * - * @param style the conditions to check before creating the change. - * @param checkPassedSeverity the severity below which the conditions check - * is treated as 'passed' - * @param updateStatus if true the wizard's status is updated - * with the status returned from the CreateChangeOperation. - * if false no status updating is performed. - */ - IChange createChange(int style, int checkPassedSeverity, boolean updateStatus) { - return createChange(style, checkPassedSeverity, updateStatus, getContainer()); - } - - private IChange createChange(int style, int checkPassedSeverity, boolean updateStatus, IRunnableContext context){ - CreateChangeOperation op= new CreateChangeOperation(fRefactoring, style); - op.setCheckPassedSeverity(checkPassedSeverity); - - InvocationTargetException exception= null; - try { - context.run(true, fIsChangeCreationCancelable, op); - } catch (InterruptedException e) { - setStatus(null); - return null; - } catch (InvocationTargetException e) { - exception= e; - } - - if (updateStatus) { - RefactoringStatus status= null; - if (exception != null) { - status= new RefactoringStatus(); - String msg= exception.getMessage(); - if (msg != null) { - status.addFatalError(RefactoringMessages.getFormattedString("RefactoringWizard.see_log", msg)); //$NON-NLS-1$ - } else { - status.addFatalError(RefactoringMessages.getString("RefactoringWizard.Internal_error")); //$NON-NLS-1$ - } - CUIPlugin.getDefault().log(exception); - } else { - status= op.getStatus(); - } - setStatus(status, style); - } else { - if (exception != null) - ExceptionHandler.handle(exception, RefactoringMessages.getString("RefactoringWizard.refactoring"), RefactoringMessages.getString("RefactoringWizard.unexpected_exception")); //$NON-NLS-2$ //$NON-NLS-1$ - } - IChange change= op.getChange(); - return change; - } - - public boolean performFinish(PerformChangeOperation op) { - return PerformRefactoringUtil.performRefactoring(op, fRefactoring, getContainer(), getContainer().getShell()); - } - - //---- Condition checking ------------------------------------------------------------ - - public RefactoringStatus checkInput() { - return internalCheckCondition(getContainer(), CheckConditionsOperation.INPUT); - } - - /** - * Checks the condition for the given style. - * @param style the conditions to check. - * @return the result of the condition check. - * @see CheckConditionsOperation - */ - protected RefactoringStatus internalCheckCondition(IRunnableContext context, int style) { - - CheckConditionsOperation op= new CheckConditionsOperation(fRefactoring, style); - - Exception exception= null; - try { - context.run(true, true, op); - } catch (InterruptedException e) { - exception= e; - } catch (InvocationTargetException e) { - exception= e; - } - RefactoringStatus status= null; - if (exception != null) { - CUIPlugin.getDefault().log(exception); - status= new RefactoringStatus(); - status.addFatalError(RefactoringMessages.getString("RefactoringWizard.internal_error_1")); //$NON-NLS-1$ - } else { - status= op.getStatus(); - } - setStatus(status, style); - return status; - } - - /** - * Sets the status according to the given style flag. - * - * @param status the refactoring status to set. - * @param style a flag indicating if the status is a activation, input checking, or - * precondition checking status. - * @see CheckConditionsOperation - */ - protected void setStatus(RefactoringStatus status, int style) { - if ((style & CheckConditionsOperation.PRECONDITIONS) == CheckConditionsOperation.PRECONDITIONS) - setStatus(status); - else if ((style & CheckConditionsOperation.ACTIVATION) == CheckConditionsOperation.ACTIVATION) - setActivationStatus(status); - else if ((style & CheckConditionsOperation.INPUT) == CheckConditionsOperation.INPUT) - setInputStatus(status); - } - - - //---- Reimplementation of Wizard methods -------------------------------------------- - - public boolean performFinish() { - Assert.isNotNull(fRefactoring); - - RefactoringWizardPage page= (RefactoringWizardPage)getContainer().getCurrentPage(); - return page.performFinish(); - } - - public IWizardPage getPreviousPage(IWizardPage page) { - if (fHasUserInputPages) - return super.getPreviousPage(page); - if (! page.getName().equals(ErrorWizardPage.PAGE_NAME)){ - if (fStatus.isOK()) - return null; - } - return super.getPreviousPage(page); - } - - public IWizardPage getStartingPage() { - if (fHasUserInputPages) - return super.getStartingPage(); - return computeUserInputSuccessorPage(null, PlatformUI.getWorkbench().getActiveWorkbenchWindow()); - } - - public void addPages() { - if (checkActivationOnOpen()) { - internalCheckCondition(new BusyIndicatorRunnableContext(), CheckConditionsOperation.ACTIVATION); - } - if (fActivationStatus.hasFatalError()) { - addErrorPage(); - // Set the status since we added the error page - setStatus(getStatus()); - } else { - Assert.isTrue(getPageCount() == 0); - addUserInputPages(); - if (getPageCount() > 0) - fHasUserInputPages= true; - addErrorPage(); - addPreviewPage(); - } - initializeDefaultPageTitles(); - } - - public void addPage(IWizardPage page) { - Assert.isTrue(page instanceof RefactoringWizardPage); - super.addPage(page); - } -} diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/RefactoringWizardDialog.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/RefactoringWizardDialog.java deleted file mode 100644 index 6e8305e4eda..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/RefactoringWizardDialog.java +++ /dev/null @@ -1,101 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.cdt.internal.ui.refactoring; - -import org.eclipse.swt.SWT; -import org.eclipse.swt.graphics.Point; -import org.eclipse.swt.widgets.Button; -import org.eclipse.swt.widgets.Control; -import org.eclipse.swt.widgets.Shell; - -import org.eclipse.jface.dialogs.DialogSettings; -import org.eclipse.jface.dialogs.IDialogConstants; -import org.eclipse.jface.dialogs.IDialogSettings; -import org.eclipse.jface.wizard.IWizardPage; -import org.eclipse.jface.wizard.WizardDialog; - -import org.eclipse.cdt.ui.CUIPlugin; - -/** - * A dialog to host refactoring wizards. - */ -public class RefactoringWizardDialog extends WizardDialog { - - private static final String DIALOG_SETTINGS= "RefactoringWizard"; //$NON-NLS-1$ - private static final String WIDTH= "width"; //$NON-NLS-1$ - private static final String HEIGHT= "height"; //$NON-NLS-1$ - - private IDialogSettings fSettings; - - /* - * note: this field must not be initialized - setter is called in the call to super - * and java initializes fields 'after' the call to super is made. so initializing would override setting. - */ - private boolean fMakeNextButtonDefault; - - /** - * Creates a new refactoring wizard dialag with the given wizard. - */ - public RefactoringWizardDialog(Shell parent, RefactoringWizard wizard) { - super(parent, wizard); - setShellStyle(getShellStyle() | SWT.RESIZE); - IDialogSettings settings= CUIPlugin.getDefault().getDialogSettings(); - wizard.setDialogSettings(settings); - fSettings= settings.getSection(DIALOG_SETTINGS); - if (fSettings == null) { - fSettings= new DialogSettings(DIALOG_SETTINGS); - settings.addSection(fSettings); - fSettings.put(WIDTH, 600); - fSettings.put(HEIGHT, 400); - } - int width= 600; - int height= 400; - try { - width= fSettings.getInt(WIDTH); - height= fSettings.getInt(HEIGHT); - } catch (NumberFormatException e) { - } - setMinimumPageSize(width, height); - } - - /* - * @see WizardDialog#finishPressed() - */ - protected void finishPressed() { - IWizardPage page= getCurrentPage(); - Control control= page.getControl().getParent(); - Point size = control.getSize(); - fSettings.put(WIDTH, size.x); - fSettings.put(HEIGHT, size.y); - super.finishPressed(); - } - - /* - * @see IWizardContainer#updateButtons() - */ - public void updateButtons() { - super.updateButtons(); - if (! fMakeNextButtonDefault) - return; - if (getShell() == null) - return; - Button next= getButton(IDialogConstants.NEXT_ID); - if (next.isEnabled()) - getShell().setDefaultButton(next); - } - - /* usually called in the IWizard#setContainer(IWizardContainer) method - */ - public void setMakeNextButtonDefault(boolean makeNextButtonDefault) { - fMakeNextButtonDefault= makeNextButtonDefault; - } -} diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/RefactoringWizardDialog2.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/RefactoringWizardDialog2.java deleted file mode 100644 index 4133ab5de74..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/RefactoringWizardDialog2.java +++ /dev/null @@ -1,578 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.refactoring; - -import java.lang.reflect.InvocationTargetException; -import java.util.HashMap; -import java.util.Map; - -import org.eclipse.cdt.internal.ui.CPluginImages; -import org.eclipse.cdt.ui.CUIPlugin; -import org.eclipse.core.runtime.NullProgressMonitor; -import org.eclipse.jface.dialogs.ControlEnableState; -import org.eclipse.jface.dialogs.Dialog; -import org.eclipse.jface.dialogs.DialogSettings; -import org.eclipse.jface.dialogs.IDialogConstants; -import org.eclipse.jface.dialogs.IDialogSettings; -import org.eclipse.jface.dialogs.IMessageProvider; -import org.eclipse.jface.operation.IRunnableWithProgress; -import org.eclipse.jface.operation.ModalContext; -import org.eclipse.jface.util.Assert; -import org.eclipse.jface.wizard.IWizardContainer; -import org.eclipse.jface.wizard.IWizardPage; -import org.eclipse.jface.wizard.ProgressMonitorPart; -import org.eclipse.swt.SWT; -import org.eclipse.swt.custom.StackLayout; -import org.eclipse.swt.events.SelectionAdapter; -import org.eclipse.swt.events.SelectionEvent; -import org.eclipse.swt.graphics.Cursor; -import org.eclipse.swt.graphics.Image; -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.Button; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Control; -import org.eclipse.swt.widgets.Display; -import org.eclipse.swt.widgets.Label; -import org.eclipse.swt.widgets.Shell; - -public class RefactoringWizardDialog2 extends Dialog implements IWizardContainer { - - private RefactoringWizard fWizard; - private IWizardPage fCurrentPage; - private IWizardPage fVisiblePage; - - private PageBook fPageContainer; - private PageBook fStatusContainer; - private MessageBox fMessageBox; - private ProgressMonitorPart fProgressMonitorPart; - private int fActiveRunningOperations; - private Cursor fWaitCursor; - private Cursor fArrowCursor; - - private static final int PREVIEW_ID= IDialogConstants.CLIENT_ID + 1; - - private int fPreviewWidth; - private int fPreviewHeight; - private IDialogSettings fSettings; - private static final String DIALOG_SETTINGS= "RefactoringWizard.preview"; //$NON-NLS-1$ - private static final String WIDTH= "width"; //$NON-NLS-1$ - private static final String HEIGHT= "height"; //$NON-NLS-1$ - - private static final Image INFO= CPluginImages.get(CPluginImages.IMG_OBJS_REFACTORING_INFO); - private static final Image WARNING= CPluginImages.get(CPluginImages.IMG_OBJS_REFACTORING_WARNING); - private static final Image ERROR= CPluginImages.get(CPluginImages.IMG_OBJS_REFACTORING_ERROR); - - private static class MessageBox extends Composite { - private Label fImage; - private Label fText; - public MessageBox(Composite parent, int style) { - super(parent, style); - GridLayout layout= new GridLayout(); - layout.numColumns= 2; - setLayout(layout); - fImage= new Label(this, SWT.NONE); - fImage.setImage(INFO); - Point size= fImage.computeSize(SWT.DEFAULT, SWT.DEFAULT); - GridData gd= new GridData(); - gd.verticalAlignment= SWT.TOP; - gd.widthHint= size.x; - gd.heightHint= size.y; - fImage.setLayoutData(gd); - fImage.setImage(null); - fText= new Label(this, SWT.WRAP); - fText.setText(" \n "); //$NON-NLS-1$ - size= fText.computeSize(SWT.DEFAULT, SWT.DEFAULT); - gd= new GridData(GridData.FILL_HORIZONTAL); - gd.heightHint= size.y; - gd.verticalAlignment= SWT.TOP; - fText.setLayoutData(gd); - } - public void setMessage(IWizardPage page) { - String msg= page.getErrorMessage(); - int type= IMessageProvider.ERROR; - if (msg == null || msg.length() == 0) { - msg= page.getMessage(); - type= IMessageProvider.NONE; - if (msg != null && page instanceof IMessageProvider) - type = ((IMessageProvider)page).getMessageType(); - } - Image image= null; - switch (type) { - case IMessageProvider.INFORMATION: - image= INFO; - break; - case IMessageProvider.WARNING: - image= WARNING; - break; - case IMessageProvider.ERROR: - image= ERROR; - break; - } - if (msg == null) - msg= ""; //$NON-NLS-1$ - fText.setText(msg); - if (image == null && msg.length() > 0) - image= INFO; - fImage.setImage(image); - } - } - - private static class PageBook extends Composite { - private StackLayout fLayout; - public PageBook(Composite parent, int style) { - super(parent, style); - fLayout= new StackLayout(); - setLayout(fLayout); - fLayout.marginWidth= 5; fLayout.marginHeight= 5; - } - public void showPage(Control page) { - fLayout.topControl= page; - layout(); - } - public Control getTopPage() { - return fLayout.topControl; - } - } - - public RefactoringWizardDialog2(Shell shell, RefactoringWizard wizard) { - super(shell); - Assert.isNotNull(wizard); - setShellStyle(getShellStyle() | SWT.RESIZE); - wizard.setDialogSettings(CUIPlugin.getDefault().getDialogSettings()); - fWizard= wizard; - fWizard.setContainer(this); - fWizard.addPages(); - initSize(); - } - - private void initSize() { - IDialogSettings settings= CUIPlugin.getDefault().getDialogSettings(); - fSettings= settings.getSection(DIALOG_SETTINGS); - if (fSettings == null) { - fSettings= new DialogSettings(DIALOG_SETTINGS); - settings.addSection(fSettings); - fSettings.put(WIDTH, 600); - fSettings.put(HEIGHT, 100); - } - fPreviewWidth= 600; - fPreviewHeight= 100; - try { - fPreviewWidth= fSettings.getInt(WIDTH); - fPreviewHeight= fSettings.getInt(HEIGHT); - } catch (NumberFormatException e) { - } - } - - private void saveSize() { - if (fCurrentPage instanceof PreviewWizardPage) { - Control control= fCurrentPage.getControl().getParent(); - Point size = control.getSize(); - fSettings.put(WIDTH, size.x); - fSettings.put(HEIGHT, size.y); - } - } - - //---- IWizardContainer -------------------------------------------- - - /* (non-Javadoc) - * Method declared on IWizardContainer. - */ - public void showPage(IWizardPage page) { - fCurrentPage= page; - } - - /* (non-Javadoc) - * Method declared on IWizardContainer. - */ - public void updateButtons() { - boolean previewPage= isPreviewPageActive(); - boolean ok= fWizard.canFinish(); - boolean canFlip= fCurrentPage.canFlipToNextPage(); - Button previewButton= getButton(PREVIEW_ID); - Button defaultButton= null; - if (previewButton != null && !previewButton.isDisposed()) { - previewButton.setEnabled(!previewPage); - if (!previewPage) - previewButton.setEnabled(canFlip); - if (previewButton.isEnabled()) - defaultButton= previewButton; - } - Button okButton= getButton(IDialogConstants.OK_ID); - if (okButton != null && !okButton.isDisposed()) { - okButton.setEnabled(ok); - if (ok) - defaultButton= okButton; - } - if (defaultButton != null) { - defaultButton.getShell().setDefaultButton(defaultButton); - } - } - - /* (non-Javadoc) - * Method declared on IWizardContainer. - */ - public void updateMessage() { - if (fStatusContainer == null || fStatusContainer.isDisposed()) - return; - fStatusContainer.showPage(fMessageBox); - fMessageBox.setMessage(fCurrentPage); - } - - /* (non-Javadoc) - * Method declared on IWizardContainer. - */ - public void updateTitleBar() { - // we don't have a title bar. - } - - /* (non-Javadoc) - * Method declared on IWizardContainer. - */ - public void updateWindowTitle() { - getShell().setText(fWizard.getWindowTitle()); - } - - /* (non-Javadoc) - * Method declared on IWizardContainer. - */ - public IWizardPage getCurrentPage() { - return fCurrentPage; - } - - //---- IRunnableContext -------------------------------------------- - - /* (non-Javadoc) - * Method declared on IRunnableContext - */ - public void run(boolean fork, boolean cancelable, IRunnableWithProgress runnable) throws InvocationTargetException, InterruptedException { - if (fProgressMonitorPart == null) { - ModalContext.run(runnable, false, new NullProgressMonitor(), getShell().getDisplay()); - } else { - Object state = null; - if(fActiveRunningOperations == 0) - state = aboutToStart(fork && cancelable); - - fActiveRunningOperations++; - try { - ModalContext.run(runnable, fork, fProgressMonitorPart, getShell().getDisplay()); - } finally { - fActiveRunningOperations--; - //Stop if this is the last one - if(state!= null) - stopped(state); - } - } - } - - private Object aboutToStart(boolean cancelable) { - Map savedState = null; - Shell shell= getShell(); - if (shell != null) { - // Save focus control - Control focusControl = getShell().getDisplay().getFocusControl(); - if (focusControl != null && focusControl.getShell() != getShell()) - focusControl = null; - - Button cancelButton= getButton(IDialogConstants.CANCEL_ID); - // Set the busy cursor to all shells. - Display d = getShell().getDisplay(); - fWaitCursor = new Cursor(d, SWT.CURSOR_WAIT); - setDisplayCursor(d, fWaitCursor); - - // Set the arrow cursor to the cancel component. - fArrowCursor= new Cursor(d, SWT.CURSOR_ARROW); - cancelButton.setCursor(fArrowCursor); - - boolean hasProgressMonitor= fProgressMonitorPart != null; - - // Deactivate shell - savedState= saveUIState(hasProgressMonitor && cancelable); - if (focusControl != null) - savedState.put("focus", focusControl); //$NON-NLS-1$ - - if (hasProgressMonitor) { - fProgressMonitorPart.attachToCancelComponent(cancelButton); - fStatusContainer.showPage(fProgressMonitorPart); - } - // Update the status container since we are blocking the event loop right now. - fStatusContainer.update(); - } - return savedState; - } - - private Map saveUIState(boolean keepCancelEnabled) { - Map savedState= new HashMap(10); - saveEnableStateAndSet(getButton(PREVIEW_ID), savedState, "preview", false); //$NON-NLS-1$ - saveEnableStateAndSet(getButton(IDialogConstants.OK_ID), savedState, "ok", false); //$NON-NLS-1$ - saveEnableStateAndSet(getButton(IDialogConstants.CANCEL_ID), savedState, "cancel", keepCancelEnabled); //$NON-NLS-1$ - savedState.put("page", ControlEnableState.disable(fVisiblePage.getControl())); //$NON-NLS-1$ - return savedState; - } - - private void saveEnableStateAndSet(Control w, Map h, String key, boolean enabled) { - if (w != null) { - h.put(key, new Boolean(w.getEnabled())); - w.setEnabled(enabled); - } - } - - private void setDisplayCursor(Display d, Cursor c) { - Shell[] shells= d.getShells(); - for (int i= 0; i < shells.length; i++) - shells[i].setCursor(c); - } - - private void stopped(Object savedState) { - Shell shell= getShell(); - if (shell != null) { - Button cancelButton= getButton(IDialogConstants.CANCEL_ID); - - if (fProgressMonitorPart != null) - fProgressMonitorPart.removeFromCancelComponent(cancelButton); - - fStatusContainer.showPage(fMessageBox); - Map state = (Map)savedState; - restoreUIState(state); - - setDisplayCursor(shell.getDisplay(), null); - cancelButton.setCursor(null); - fWaitCursor.dispose(); - fWaitCursor = null; - fArrowCursor.dispose(); - fArrowCursor = null; - Control focusControl = (Control)state.get("focus"); //$NON-NLS-1$ - if (focusControl != null) - focusControl.setFocus(); - } - } - - private void restoreUIState(Map state) { - restoreEnableState(getButton(PREVIEW_ID), state, "preview");//$NON-NLS-1$ - restoreEnableState(getButton(IDialogConstants.OK_ID), state, "ok");//$NON-NLS-1$ - restoreEnableState(getButton(IDialogConstants.CANCEL_ID), state, "cancel");//$NON-NLS-1$ - ControlEnableState pageState = (ControlEnableState) state.get("page");//$NON-NLS-1$ - pageState.restore(); - } - - private void restoreEnableState(Control w, Map h, String key) { - if (w != null) { - Boolean b = (Boolean) h.get(key); - if (b != null) - w.setEnabled(b.booleanValue()); - } - } - - //---- Dialog ----------------------------------------------------------- - - public boolean close() { - fWizard.dispose(); - return super.close(); - } - - protected void cancelPressed() { - if (fActiveRunningOperations == 0) { - if (fWizard.performCancel()) - super.cancelPressed(); - } - } - - protected void okPressed() { - IWizardPage current= fCurrentPage; - if (fWizard.performFinish()) { - saveSize(); - super.okPressed(); - return; - } - if (fCurrentPage == current) - return; - Assert.isTrue(ErrorWizardPage.PAGE_NAME.equals(fCurrentPage.getName())); - if (showErrorDialog((ErrorWizardPage)fCurrentPage)) { - if (fWizard.performFinish()) { - super.okPressed(); - return; - } - } - fCurrentPage= current; - } - - private boolean isPreviewPageActive() { - return IPreviewWizardPage.PAGE_NAME.equals(fCurrentPage.getName()); - } - - private void previewPressed() { - IWizardPage current= fCurrentPage; - fCurrentPage= fCurrentPage.getNextPage(); - if (current == fCurrentPage) - return; - String pageName= fCurrentPage.getName(); - if (ErrorWizardPage.PAGE_NAME.equals(pageName)) { - if (showErrorDialog((ErrorWizardPage)fCurrentPage)) { - fCurrentPage= fCurrentPage.getNextPage(); - pageName= fCurrentPage.getName(); - } else { - return; - } - } - if (IPreviewWizardPage.PAGE_NAME.equals(pageName)) { - fCurrentPage.createControl(fPageContainer); - makeVisible(fCurrentPage); - updateButtons(); - if (((PreviewWizardPage)fCurrentPage).hasChanges()) - resize(); - else - getButton(IDialogConstants.OK_ID).setEnabled(false); - } else { - fCurrentPage= current; - } - } - - private boolean showErrorDialog(ErrorWizardPage page) { - RefactoringStatusDialog dialog= new RefactoringStatusDialog(getShell(), page, true); - switch (dialog.open()) { - case IDialogConstants.OK_ID: - return true; - case IDialogConstants.BACK_ID: - fCurrentPage= fCurrentPage.getPreviousPage(); - break; - case IDialogConstants.CANCEL_ID: - super.cancelPressed(); - } - return false; - } - - private void resize() { - Control control= fPageContainer.getTopPage(); - Point size= control.getSize(); - int dw= Math.max(0, fPreviewWidth - size.x); - int dh= Math.max(0, fPreviewHeight - size.y); - int dx = dw / 2; - int dy= dh / 2; - Shell shell= getShell(); - Rectangle rect= shell.getBounds(); - Rectangle display= shell.getDisplay().getClientArea(); - rect.x= Math.max(0, rect.x - dx); - rect.y= Math.max(0, rect.y - dy); - rect.width= Math.min(rect.width + dw, display.width); - rect.height= Math.min(rect.height + dh, display.height); - int xe= rect.x + rect.width; - if (xe > display.width) { - rect.x-= xe - display.width; - } - int ye= rect.y + rect.height; - if (ye > display.height) { - rect.y-= ye - display.height; - } - shell.setBounds(rect); - } - - //---- UI construction --------------------------------------------------- - - protected void configureShell(Shell newShell) { - super.configureShell(newShell); - newShell.setText(fWizard.getDefaultPageTitle()); - } - - protected Control createContents(Composite parent) { - Composite result= new Composite(parent, SWT.NONE); - GridLayout layout= new GridLayout(); - layout.marginHeight= 0; layout.marginWidth= 0; - layout.verticalSpacing= 0; layout.horizontalSpacing= 0; - result.setLayout(layout); - result.setLayoutData(new GridData(GridData.FILL_BOTH)); - - // initialize the dialog units - initializeDialogUnits(result); - - fPageContainer= new PageBook(result, SWT.NONE); - GridData gd= new GridData(GridData.FILL_BOTH); - fPageContainer.setLayoutData(gd); - fCurrentPage= fWizard.getStartingPage(); - dialogArea= fPageContainer; - if (fCurrentPage instanceof PreviewWizardPage) { - gd.widthHint= fPreviewWidth; - gd.heightHint= fPreviewHeight; - } - - fStatusContainer= new PageBook(result, SWT.NONE); - gd= new GridData(GridData.FILL_HORIZONTAL); - gd.widthHint= convertWidthInCharsToPixels(fWizard.getMessageLineWidthInChars()); - fStatusContainer.setLayoutData(gd); - if (fWizard.needsProgressMonitor()) - createProgressMonitorPart(); - createMessageBox(); - fStatusContainer.showPage(fMessageBox); - - buttonBar= createButtonBar(result); - - fCurrentPage.createControl(fPageContainer); - makeVisible(fCurrentPage); - - updateMessage(); - updateButtons(); - applyDialogFont(result); - return result; - } - - private void createProgressMonitorPart() { - // Insert a progress monitor - GridLayout pmlayout= new GridLayout(); - pmlayout.numColumns= 1; - pmlayout.marginHeight= 0; - fProgressMonitorPart= new ProgressMonitorPart(fStatusContainer, pmlayout); - } - - private void createMessageBox() { - fMessageBox= new MessageBox(fStatusContainer, SWT.NONE); - } - - protected void createButtonsForButtonBar(Composite parent) { - if (! (fCurrentPage instanceof PreviewWizardPage) && fWizard.hasPreviewPage()) { - Button preview= createButton(parent, PREVIEW_ID, RefactoringMessages.getString("RefactoringWizardDialog2.buttons.preview.label"), false); //$NON-NLS-1$ - preview.addSelectionListener(new SelectionAdapter() { - public void widgetSelected(SelectionEvent e) { - previewPressed(); - } - }); - } - - String OK_LABEL= IDialogConstants.OK_LABEL; - String CANCEL_LABEL= IDialogConstants.CANCEL_LABEL; - if (fWizard.yesNoStyle()) { - OK_LABEL= IDialogConstants.YES_LABEL; - CANCEL_LABEL= IDialogConstants.NO_LABEL; - } - createButton( - parent, - IDialogConstants.OK_ID, - OK_LABEL, - true); - createButton( - parent, - IDialogConstants.CANCEL_ID, - CANCEL_LABEL, - false); - Button okButton= getButton(IDialogConstants.OK_ID); - okButton.setFocus(); - } - - private void makeVisible(IWizardPage page) { - if (fVisiblePage == page) - return; - if (fVisiblePage != null) - fVisiblePage.setVisible(false); - fVisiblePage= page; - fPageContainer.showPage(page.getControl()); - fVisiblePage.setVisible(true); - } -} diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/RefactoringWizardPage.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/RefactoringWizardPage.java deleted file mode 100644 index 1bba3a11190..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/RefactoringWizardPage.java +++ /dev/null @@ -1,98 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.refactoring; - -import org.eclipse.jface.dialogs.DialogSettings; -import org.eclipse.jface.dialogs.IDialogSettings; -import org.eclipse.jface.util.Assert; -import org.eclipse.jface.wizard.IWizard; -import org.eclipse.jface.wizard.WizardPage; - -import org.eclipse.cdt.internal.corext.refactoring.base.Refactoring; - -/** - * An abstract superclass for all wizard pages added to a refactoring wizard. The - * class provides access to the refactoring and the refactoring wizard. - * - * @see RefactoringWizard - */ -public abstract class RefactoringWizardPage extends WizardPage { - - public static final String REFACTORING_SETTINGS= "org.eclipse.cdt.ui.refactoring"; //$NON-NLS-1$ - - /** - * Creates a new refactoring wizard page. - * - * @param name the page's name. - * @see org.eclipse.jface.wizard.IWizardPage#getName() - */ - protected RefactoringWizardPage(String name) { - super(name); - } - - /* (non-Javadoc) - * Method declared on IWizardPage. - */ - public void setWizard(IWizard newWizard) { - Assert.isTrue(newWizard instanceof RefactoringWizard); - super.setWizard(newWizard); - } - - /** - * Returns the refactoring used by the wizard to which this page belongs. - * Returns null if the page isn't added to any wizard yet. - * - * @return the refactoring associated with this refactoring wizard page - */ - protected Refactoring getRefactoring() { - RefactoringWizard wizard= getRefactoringWizard(); - if (wizard == null) - return null; - return wizard.getRefactoring(); - } - - /** - * Returns the page's refactoring wizard. - * - * @return the page's refactoring wizard - */ - protected RefactoringWizard getRefactoringWizard() { - return (RefactoringWizard)getWizard(); - } - - /** - * The user has pressed the finish button. Perform the page specific finish - * action. - * - * @return true if finish operation ended without errors. - * Otherwise false is returned. - */ - protected boolean performFinish() { - return true; - } - - /** - * Returns the refactoring dialog settings. - * - * @return the refactoring dialog settings. - */ - protected IDialogSettings getRefactoringSettings() { - IDialogSettings settings= getDialogSettings(); - if (settings == null) - return null; - IDialogSettings result= settings.getSection(REFACTORING_SETTINGS); - if (result == null) { - result= new DialogSettings(REFACTORING_SETTINGS); - settings.addSection(result); - } - return result; - } -} diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/RenameElementWizard.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/RenameElementWizard.java deleted file mode 100644 index 48b0c962c1e..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/RenameElementWizard.java +++ /dev/null @@ -1,25 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.refactoring; - -import org.eclipse.cdt.internal.ui.ICHelpContextIds; -import org.eclipse.cdt.internal.ui.CPluginImages; -import org.eclipse.cdt.internal.ui.refactoring.RefactoringMessages; - -public class RenameElementWizard extends RenameRefactoringWizard { - public RenameElementWizard() { - super( - RefactoringMessages.getString("RenameTypeWizard.defaultPageTitle"), //$NON-NLS-1$ - RefactoringMessages.getString("RenameTypeWizard.inputPage.description"), //$NON-NLS-1$ - CPluginImages.DESC_WIZBAN_REFACTOR_TYPE, - ICHelpContextIds.RENAME_TYPE_WIZARD_PAGE); - } -} diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/RenameInputWizardPage.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/RenameInputWizardPage.java deleted file mode 100644 index 986ede6d579..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/RenameInputWizardPage.java +++ /dev/null @@ -1,201 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.refactoring; - -import org.eclipse.cdt.internal.corext.refactoring.IReferenceUpdating; -import org.eclipse.cdt.internal.corext.refactoring.ITextUpdating; -import org.eclipse.cdt.internal.corext.refactoring.base.Refactoring; -import org.eclipse.cdt.internal.ui.util.RowLayouter; -import org.eclipse.jface.dialogs.Dialog; -import org.eclipse.jface.dialogs.IDialogConstants; -import org.eclipse.swt.SWT; -import org.eclipse.swt.events.SelectionAdapter; -import org.eclipse.swt.events.SelectionEvent; -import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.layout.GridLayout; -import org.eclipse.swt.widgets.Button; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Label; -import org.eclipse.swt.widgets.Text; -import org.eclipse.ui.help.WorkbenchHelp; - -abstract class RenameInputWizardPage extends TextInputWizardPage { - - private String fHelpContextID; - private Button fUpdateReferences; - private Button fUpdateComments; - private Button fUpdateStrings; - private Button fUpdateQualifiedNames; - private static final String UPDATE_REFERENCES= "updateReferences"; //$NON-NLS-1$ - private static final String UPDATE_COMMENTS= "updateComments"; //$NON-NLS-1$ - private static final String UPDATE_STRINGS= "updateStrings"; //$NON-NLS-1$ - private static final String UPDATE_QUALIFIED_NAMES= "updateQualifiedNames"; //$NON-NLS-1$ - - /** - * Creates a new text input page. - * @param isLastUserPage true if this page is the wizard's last - * user input page. Otherwise false. - * @param initialSetting the initialSetting. - */ - public RenameInputWizardPage(String description, String contextHelpId, boolean isLastUserPage, String initialValue) { - super(description, isLastUserPage, initialValue); - fHelpContextID= contextHelpId; - } - - /* non java-doc - * @see DialogPage#createControl(org.eclipse.swt.widgets.Composite) - */ - public void createControl(Composite parent) { - Composite superComposite= new Composite(parent, SWT.NONE); - setControl(superComposite); - initializeDialogUnits(superComposite); - - superComposite.setLayout(new GridLayout()); - Composite composite= new Composite(superComposite, SWT.NONE); - composite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); - - GridLayout layout= new GridLayout(); - layout.numColumns= 2; - layout.verticalSpacing= 8; - composite.setLayout(layout); - RowLayouter layouter= new RowLayouter(2); - - Label oldNameLabel= new Label(composite, SWT.NONE); - oldNameLabel.setText(getOldNameLabelText()); - - Label oldName= new Label(composite, SWT.NONE); - oldName.setText(fInitialValue); - - Label label= new Label(composite, SWT.NONE); - label.setText(getLabelText()); - - Text text= createTextInputField(composite); - text.selectAll(); - GridData gd= new GridData(GridData.FILL_HORIZONTAL); - gd.widthHint= convertWidthInCharsToPixels(25); - text.setLayoutData(gd); - - - layouter.perform(label, text, 1); - - addOptionalUpdateReferencesCheckbox(composite, layouter); - - Dialog.applyDialogFont(superComposite); - WorkbenchHelp.setHelp(getControl(), fHelpContextID); - - } - - protected boolean saveSettings() { - if (getContainer() instanceof Dialog) - return ((Dialog)getContainer()).getReturnCode() == IDialogConstants.OK_ID; - return true; - } - - public void dispose() { - if (saveSettings()) { - saveBooleanSetting(UPDATE_REFERENCES, fUpdateReferences); - saveBooleanSetting(UPDATE_COMMENTS, fUpdateComments); - saveBooleanSetting(UPDATE_STRINGS, fUpdateStrings); - saveBooleanSetting(UPDATE_QUALIFIED_NAMES, fUpdateQualifiedNames); - } - super.dispose(); - } - - private void addOptionalUpdateReferencesCheckbox(Composite result, RowLayouter layouter) { - final IReferenceUpdating ref= (IReferenceUpdating)getRefactoring().getAdapter(IReferenceUpdating.class); - if (ref == null || !ref.canEnableUpdateReferences()) - return; - String title= RefactoringMessages.getString("RenameInputWizardPage.update_references"); //$NON-NLS-1$ - boolean defaultValue= getBooleanSetting(UPDATE_REFERENCES, ref.getUpdateReferences()); - fUpdateReferences= createCheckbox(result, title, defaultValue, layouter); - ref.setUpdateReferences(fUpdateReferences.getSelection()); - fUpdateReferences.addSelectionListener(new SelectionAdapter(){ - public void widgetSelected(SelectionEvent e) { - ref.setUpdateReferences(fUpdateReferences.getSelection()); - } - }); - } - - private void addOptionalUpdateCommentsAndStringCheckboxes(Composite result, RowLayouter layouter) { - ITextUpdating refactoring= (ITextUpdating)getRefactoring().getAdapter(ITextUpdating.class); - - if (refactoring == null || !refactoring.canEnableTextUpdating()) - return; - - addUpdateCommentsCheckbox(result, layouter, refactoring); - addUpdateStringsCheckbox(result, layouter, refactoring); - } - - private void addUpdateCommentsCheckbox(Composite result, RowLayouter layouter, final ITextUpdating refactoring) { - String title= RefactoringMessages.getString("RenameInputWizardPage.update_comment_references"); //$NON-NLS-1$ - boolean defaultValue= getBooleanSetting(UPDATE_COMMENTS, refactoring.getUpdateComments()); - fUpdateComments= createCheckbox(result, title, defaultValue, layouter); - refactoring.setUpdateComments(fUpdateComments.getSelection()); - fUpdateComments.addSelectionListener(new SelectionAdapter(){ - public void widgetSelected(SelectionEvent e) { - refactoring.setUpdateComments(fUpdateComments.getSelection()); - updateForcePreview(); - } - }); - } - - private void addUpdateStringsCheckbox(Composite result, RowLayouter layouter, final ITextUpdating refactoring) { - String title= RefactoringMessages.getString("RenameInputWizardPage.ppdate_string_references"); //$NON-NLS-1$ - boolean defaultValue= getBooleanSetting(UPDATE_STRINGS, refactoring.getUpdateStrings()); - fUpdateStrings= createCheckbox(result, title, defaultValue, layouter); - refactoring.setUpdateStrings(fUpdateStrings.getSelection()); - fUpdateStrings.addSelectionListener(new SelectionAdapter(){ - public void widgetSelected(SelectionEvent e) { - refactoring.setUpdateStrings(fUpdateStrings.getSelection()); - updateForcePreview(); - } - }); - } - - protected String getLabelText() { - return RefactoringMessages.getString("RenameInputWizardPage.enter_name"); //$NON-NLS-1$ - } - - protected String getOldNameLabelText() { - return RefactoringMessages.getString("RenameInputWizardPage.old_name"); //$NON-NLS-1$ - } - - protected boolean getBooleanSetting(String key, boolean defaultValue) { - String update= getRefactoringSettings().get(key); - if (update != null) - return Boolean.valueOf(update).booleanValue(); - else - return defaultValue; - } - - protected void saveBooleanSetting(String key, Button checkBox) { - if (checkBox != null) - getRefactoringSettings().put(key, checkBox.getSelection()); - } - - private static Button createCheckbox(Composite parent, String title, boolean value, RowLayouter layouter) { - Button checkBox= new Button(parent, SWT.CHECK); - checkBox.setText(title); - checkBox.setSelection(value); - layouter.perform(checkBox); - return checkBox; - } - - private void updateForcePreview() { - boolean forcePreview= false; - Refactoring refactoring= getRefactoring(); - ITextUpdating tu= (ITextUpdating)refactoring.getAdapter(ITextUpdating.class); - if (tu != null) { - forcePreview= tu.getUpdateComments() || tu.getUpdateJavaDoc() || tu.getUpdateStrings(); - } - getRefactoringWizard().setPreviewReview(forcePreview); - } -} diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/RenameRefactoringWizard.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/RenameRefactoringWizard.java deleted file mode 100644 index 8149adb882b..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/RenameRefactoringWizard.java +++ /dev/null @@ -1,83 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.cdt.internal.ui.refactoring; - -import org.eclipse.core.runtime.CoreException; - -import org.eclipse.jface.resource.ImageDescriptor; - -import org.eclipse.cdt.internal.corext.refactoring.RefactoringStyles; -import org.eclipse.cdt.internal.corext.refactoring.RenameRefactoring; -import org.eclipse.cdt.internal.corext.refactoring.IRenameRefactoring; -import org.eclipse.cdt.internal.corext.refactoring.base.Refactoring; -import org.eclipse.cdt.internal.corext.refactoring.base.RefactoringStatus; - -import org.eclipse.cdt.internal.ui.refactoring.RefactoringMessages; -import org.eclipse.cdt.internal.ui.refactoring.RefactoringWizard; - -public class RenameRefactoringWizard extends RefactoringWizard { - - private final String fInputPageDescription; - private final String fPageContextHelpId; - private final ImageDescriptor fInputPageImageDescriptor; - - public RenameRefactoringWizard(String defaultPageTitle, String inputPageDescription, - ImageDescriptor inputPageImageDescriptor, String pageContextHelpId) { - super(); - setDefaultPageTitle(defaultPageTitle); - fInputPageDescription= inputPageDescription; - fInputPageImageDescriptor= inputPageImageDescriptor; - fPageContextHelpId= pageContextHelpId; - } - - protected boolean hasPreviewPage() { - Refactoring refactoring= getRefactoring(); - if (refactoring instanceof RenameRefactoring) { - return (((RenameRefactoring)refactoring).getStyle() & RefactoringStyles.NEEDS_PREVIEW) != 0; - } - return super.hasPreviewPage(); - } - - /* non java-doc - * @see RefactoringWizard#addUserInputPages - */ - protected void addUserInputPages() { - String initialSetting= getRenameRefactoring().getCurrentName(); - RenameInputWizardPage inputPage= createInputPage(fInputPageDescription, initialSetting); - inputPage.setImageDescriptor(fInputPageImageDescriptor); - addPage(inputPage); - } - - private IRenameRefactoring getRenameRefactoring() { - return (IRenameRefactoring)getRefactoring(); - } - - protected RenameInputWizardPage createInputPage(String message, String initialSetting) { - return new RenameInputWizardPage(message, fPageContextHelpId, true, initialSetting) { - protected RefactoringStatus validateTextField(String text) { - return validateNewName(text); - } - }; - } - - protected RefactoringStatus validateNewName(String newName) { - IRenameRefactoring ref= getRenameRefactoring(); - ref.setNewName(newName); - try{ - return ref.checkNewName(newName); - } catch (CoreException e){ - //XXX: should log the exception - String msg= e.getMessage() == null ? "": e.getMessage(); //$NON-NLS-1$ - return RefactoringStatus.createFatalErrorStatus(RefactoringMessages.getFormattedString("RenameRefactoringWizard.internal_error", msg));//$NON-NLS-1$ - } - } -} diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/StatusContextViewerDescriptor.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/StatusContextViewerDescriptor.java deleted file mode 100644 index b3ee51cbb47..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/StatusContextViewerDescriptor.java +++ /dev/null @@ -1,35 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.refactoring; - -public class StatusContextViewerDescriptor /*extends AbstractDescriptor */{ - - private static final String EXT_ID= "statusContextViewers"; //$NON-NLS-1$ -/* - private static DescriptorManager fgDescriptions= new DescriptorManager(EXT_ID) { - protected AbstractDescriptor createDescriptor(IConfigurationElement element) { - return new StatusContextViewerDescriptor(element); - } - }; - - public static StatusContextViewerDescriptor get(Object element) throws CoreException { - return (StatusContextViewerDescriptor)fgDescriptions.getDescriptor(element); - } - - public StatusContextViewerDescriptor(IConfigurationElement element) { - super(element); - } - - public IStatusContextViewer createViewer() throws CoreException { - return (IStatusContextViewer)fConfigurationElement.createExecutableExtension(CLASS); - } - */ -} diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/TextChangePreviewViewer.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/TextChangePreviewViewer.java deleted file mode 100644 index d55ba8d404f..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/TextChangePreviewViewer.java +++ /dev/null @@ -1,191 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.refactoring; - -import java.io.ByteArrayInputStream; -import java.io.InputStream; -import java.io.UnsupportedEncodingException; - -import org.eclipse.compare.CompareConfiguration; -import org.eclipse.compare.CompareUI; -import org.eclipse.compare.CompareViewerSwitchingPane; -import org.eclipse.compare.IStreamContentAccessor; -import org.eclipse.compare.ITypedElement; -import org.eclipse.compare.structuremergeviewer.DiffNode; -import org.eclipse.compare.structuremergeviewer.ICompareInput; - -import org.eclipse.core.runtime.CoreException; - -import org.eclipse.core.resources.ResourcesPlugin; - -import org.eclipse.swt.SWT; -import org.eclipse.swt.graphics.Image; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Control; - -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.viewers.Viewer; - -import org.eclipse.cdt.internal.corext.refactoring.changes.TextChange; -import org.eclipse.cdt.internal.corext.refactoring.changes.TextChange.EditChange; - -public class TextChangePreviewViewer implements IChangePreviewViewer { - - private ComparePreviewer fViewer; - - private static class TextEditChangeInput { - EditChange change; - int surroundingLines; - - EditChange[] changes; - IRegion range; - } - - private static class ComparePreviewer extends CompareViewerSwitchingPane { - private CompareConfiguration fCompareConfiguration; - public ComparePreviewer(Composite parent) { - super(parent, SWT.BORDER | SWT.FLAT, true); - fCompareConfiguration= new CompareConfiguration(); - fCompareConfiguration.setLeftEditable(false); - fCompareConfiguration.setLeftLabel(RefactoringMessages.getString("ComparePreviewer.original_source")); //$NON-NLS-1$ - fCompareConfiguration.setRightEditable(false); - fCompareConfiguration.setRightLabel(RefactoringMessages.getString("ComparePreviewer.refactored_source")); //$NON-NLS-1$ - } - protected Viewer getViewer(Viewer oldViewer, Object input) { - return CompareUI.findContentViewer(oldViewer, (ICompareInput)input, this, fCompareConfiguration); - } - public void setText(String text) { - /* - Object input= getInput(); - if (input instanceof CompareInput) { - CompareInput cInput= (CompareInput)input; - setImage(fLabelProvider.getImage(cInput.getChangeElement())); - super.setText(fLabelProvider.getText(cInput.getChangeElement())); - } else { - super.setText(text); - setImage(null); - } - */ - super.setText(text); - } - } - - private static class CompareElement implements ITypedElement, IStreamContentAccessor { - private InputStream fContent; - private String fType; - public CompareElement(String content, String type) { - fContent= createInputStream(content); - fType= type; - } - public String getName() { - return RefactoringMessages.getString("ComparePreviewer.element_name"); //$NON-NLS-1$ - } - public Image getImage() { - return null; - } - public String getType() { - return fType; - } - public InputStream getContents() throws CoreException { - return fContent; - } - private static InputStream createInputStream(String s) { - try { - return new ByteArrayInputStream(s.getBytes(ResourcesPlugin.getEncoding())); - } catch (UnsupportedEncodingException e) { - return new ByteArrayInputStream(s.getBytes()); - } - } - } - - public static Object createInput(TextChange change) { - return change; - } - - public static Object createInput(EditChange change, int surroundingLines) { - TextEditChangeInput result= new TextEditChangeInput(); - result.change= change; - result.surroundingLines= surroundingLines; - return result; - } - - public static Object createInput(EditChange[] changes, IRegion range) { - TextEditChangeInput result= new TextEditChangeInput(); - result.changes= changes; - result.range= range; - return result; - } - - - /* (non-Javadoc) - * @see org.eclipse.jdt.internal.ui.refactoring.IChangePreviewViewer#createControl(org.eclipse.swt.widgets.Composite) - */ - public void createControl(Composite parent) { - fViewer= new ComparePreviewer(parent); - } - - /* (non-Javadoc) - * @see org.eclipse.jdt.internal.ui.refactoring.IChangePreviewViewer#getControl() - */ - public Control getControl() { - return fViewer; - } - - /* (non-Javadoc) - * @see org.eclipse.jdt.internal.ui.refactoring.IChangePreviewViewer#setInput(org.eclipse.jdt.internal.ui.refactoring.ChangeElement) - */ - public void setInput(Object input) throws CoreException { - if (input instanceof TextChange) { - TextChange change= (TextChange)input; - setInput(change.getCurrentContent(), change.getPreviewContent(), change.getTextType()); - return; - } else if (input instanceof TextEditChangeInput) { - TextEditChangeInput edi= (TextEditChangeInput)input; - if (edi.change != null && edi.surroundingLines >= 0) { - TextChange.EditChange editChange= edi.change; - TextChange change= editChange.getTextChange(); - setInput(change.getCurrentContent(editChange, 2), - change.getPreviewContent(editChange, 2), - change.getTextType()); - return; - } else if (edi.changes != null && edi.changes.length > 0 && edi.range != null) { - TextChange change= edi.changes[0].getTextChange(); - setInput(change.getCurrentContent(edi.range), - change.getPreviewContent(edi.changes, edi.range), - change.getTextType()); - return; - } - } else { - fViewer.setInput(null); - } - /* - } else if (change instanceof CreateTextFileChange){ - CreateTextFileChange ctfc= (CreateTextFileChange)change; - String type= ctfc.isJavaFile() ? JAVA_TYPE: TEXT_TYPE; - setInput(input, ctfc.getCurrentContent(), ctfc.getPreview(), type); - return; - } - */ - } - - /* (non-Javadoc) - * @see org.eclipse.jdt.internal.ui.refactoring.IChangePreviewViewer#refresh() - */ - public void refresh() { - fViewer.getViewer().refresh(); - } - - private void setInput(String left, String right, String type) { - fViewer.setInput(new DiffNode( - new CompareElement(left, type), - new CompareElement(right, type))); - } -} diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/TextEditChangeElement.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/TextEditChangeElement.java deleted file mode 100644 index 96dcfc9b886..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/TextEditChangeElement.java +++ /dev/null @@ -1,116 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.refactoring; - -import org.eclipse.core.runtime.CoreException; - -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.util.Assert; - -import org.eclipse.cdt.internal.corext.refactoring.base.IChange; -import org.eclipse.cdt.internal.corext.refactoring.changes.TextChange; -import org.eclipse.cdt.internal.corext.refactoring.changes.TextChange.EditChange; - -/* package */ class TextEditChangeElement extends ChangeElement { - - private static final ChangeElement[] fgChildren= new ChangeElement[0]; - - private EditChange fChange; - - public TextEditChangeElement(ChangeElement parent, EditChange change) { - super(parent); - fChange= change; - Assert.isNotNull(fChange); - } - - /** - * Returns the TextEditChange managed by this node. - * - * @return the TextEditChange - */ - public EditChange getTextEditChange() { - return fChange; - } - - /* (non-Javadoc) - * @see org.eclipse.jdt.internal.ui.refactoring.ChangeElement#getChangePreviewViewer() - */ -// public ChangePreviewViewerDescriptor getChangePreviewViewer() throws CoreException { -// DefaultChangeElement element= getStandardChangeElement(); -// if (element == null) -// return null; -// return element.getChangePreviewViewer(); -// } - - /* (non-Javadoc) - * @see org.eclipse.jdt.internal.ui.refactoring.ChangeElement#feedInput(org.eclipse.jdt.internal.ui.refactoring.IChangePreviewViewer) - */ - public void feedInput(IChangePreviewViewer viewer) throws CoreException { - DefaultChangeElement element= getStandardChangeElement(); - if (element != null) { - IChange change= element.getChange(); - if (change instanceof TextChange) { - IRegion range= getTextRange(this); - Object input= null; - if (range != null) { - input= TextChangePreviewViewer.createInput(new EditChange[] {fChange}, range); - } else { - input= TextChangePreviewViewer.createInput(fChange, 2); - } - viewer.setInput(input); - } - } else { - viewer.setInput(null); - } - } - - /* non Java-doc - * @see ChangeElement#setActive - */ - public void setActive(boolean active) { - fChange.setActive(active); - } - - /* non Java-doc - * @see ChangeElement.getActive - */ - public int getActive() { - return fChange.isActive() ? ACTIVE : INACTIVE; - } - - /* non Java-doc - * @see ChangeElement.getChildren - */ - public ChangeElement[] getChildren() { - return fgChildren; - } - - private DefaultChangeElement getStandardChangeElement() { - ChangeElement element= getParent(); - while(!(element instanceof DefaultChangeElement) && element != null) { - element= element.getParent(); - } - return (DefaultChangeElement)element; - } - - private static IRegion getTextRange(ChangeElement element) throws CoreException { - if (element == null) - return null; - if (element instanceof PseudoCChangeElement) { - return ((PseudoCChangeElement)element).getTextRange(); - } else - if (element instanceof DefaultChangeElement) { - return null; - } - return getTextRange(element.getParent()); - } -} - diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/TextInputWizardPage.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/TextInputWizardPage.java deleted file mode 100644 index d1bbfd0da22..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/TextInputWizardPage.java +++ /dev/null @@ -1,170 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.cdt.internal.ui.refactoring; - -import org.eclipse.swt.SWT; -import org.eclipse.swt.events.ModifyEvent; -import org.eclipse.swt.events.ModifyListener; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Text; - -import org.eclipse.jface.util.Assert; - -import org.eclipse.cdt.internal.corext.refactoring.base.RefactoringStatus; - -public abstract class TextInputWizardPage extends UserInputWizardPage{ - - protected String fInitialValue; - protected Text fTextField; - - public static final String PAGE_NAME= "TextInputPage";//$NON-NLS-1$ - - /** - * Creates a new text input page. - * @param isLastUserPage true if this page is the wizard's last - * user input page. Otherwise false. - */ - public TextInputWizardPage(String description, boolean isLastUserPage) { - this(description, isLastUserPage, ""); //$NON-NLS-1$ - } - - /** - * Creates a new text input page. - * @param isLastUserPage true if this page is the wizard's last - * user input page. Otherwise false. - * @param initialSetting the initialSetting. - */ - public TextInputWizardPage(String description, boolean isLastUserPage, String initialValue) { - super(PAGE_NAME, isLastUserPage); - Assert.isNotNull(initialValue); - setDescription(description); - fInitialValue= initialValue; - } - - /** - * Returns whether the initial input is valid. Typically it is not, because the - * user is required to provide some information e.g. a new type name etc. - * - * @return true iff the input provided at initialization is valid - */ - protected boolean isInitialInputValid(){ - return false; - } - - /** - * Returns whether an empty string is a valid input. Typically it is not, because - * the user is required to provide some information e.g. a new type name etc. - * - * @return true iff an empty string is valid - */ - protected boolean isEmptyInputValid(){ - return false; - } - - /** - * Returns the content of the text input field. - * - * @return the content of the text input field. Returns null if - * not text input field has been created - */ - protected String getText() { - if (fTextField == null) - return null; - return fTextField.getText(); - } - - /** - * Sets the new text for the text field. Does nothing if the text field has not been created. - * @param text the new value - */ - protected void setText(String text) { - if (fTextField == null) - return; - fTextField.setText(text); - } - - /** - * Performs input validation. Returns a RefactoringStatus which - * describes the result of input validation. Null is interpreted - * as no error. - */ - protected RefactoringStatus validateTextField(String text){ - return null; - } - - protected Text createTextInputField(Composite parent) { - return createTextInputField(parent, SWT.BORDER); - } - - protected Text createTextInputField(Composite parent, int style) { - fTextField= new Text(parent, style); - fTextField.addModifyListener(new ModifyListener() { - public void modifyText(ModifyEvent e) { - textModified(getText()); - } - }); - fTextField.setText(fInitialValue); - return fTextField; - } - - /** - * Checks the page's state and issues a corresponding error message. The page validation - * is computed by calling validatePage. - */ - protected void textModified(String text) { - if (! isEmptyInputValid() && text.equals("")){ //$NON-NLS-1$ - setPageComplete(false); - setErrorMessage(null); - restoreMessage(); - return; - } - if ((! isInitialInputValid()) && text.equals(fInitialValue)){ - setPageComplete(false); - setErrorMessage(null); - //setErrorMessage(RefactoringMessages.getString("RenameInputWizardPage.no_undo")); //$NON-NLS-1$ - restoreMessage(); - return; - } - - setPageComplete(validateTextField(text)); - } - - /** - * Subclasses can override if they want to restore the message differently. - * This implementation calls setMessage(null), which clears the message - * thus exposing the description. - */ - protected void restoreMessage(){ - setMessage(null); - } - - /* (non-Javadoc) - * Method declared in IDialogPage - */ - public void dispose() { - fTextField= null; - } - - /* (non-Javadoc) - * Method declared in WizardPage - */ - public void setVisible(boolean visible) { - if (visible) { - textModified(getText()); - } - super.setVisible(visible); - if (visible && fTextField != null) { - fTextField.setFocus(); - } - } -} - diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/UserInputWizardPage.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/UserInputWizardPage.java deleted file mode 100644 index f3eb84a1cc4..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/UserInputWizardPage.java +++ /dev/null @@ -1,153 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.cdt.internal.ui.refactoring; - -import org.eclipse.cdt.internal.corext.refactoring.base.Refactoring; -import org.eclipse.cdt.internal.corext.refactoring.base.RefactoringStatus; -import org.eclipse.cdt.internal.ui.CPluginImages; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.jface.wizard.IWizardPage; - -/** - * An abstract wizard page that can be used to implement user input pages for - * refactoring wizards. Usually user input pages are pages shown at the beginning - * of a wizard. As soon as the "last" user input page is left a corresponding - * precondition check is executed. - */ -public abstract class UserInputWizardPage extends RefactoringWizardPage { - - private final boolean fIsLastUserPage; - - /** - * Creates a new user input page. - * @param name the page's name. - * @param isLastUserPage true if this page is the wizard's last - * user input page. Otherwise false. - */ - public UserInputWizardPage(String name, boolean isLastUserPage) { - super(name); - fIsLastUserPage= isLastUserPage; - } - - /** - * Sets the page's complete status depending on the given - * ReactoringStatus. - * - * @param status the RefactoringStatus - */ - public void setPageComplete(RefactoringStatus status) { - getRefactoringWizard().setStatus(status); - - int severity= status.getSeverity(); - if (severity == RefactoringStatus.FATAL){ - setPageComplete(false); - setErrorMessage(status.getFirstMessage(severity)); - setImageDescriptor(CPluginImages.DESC_OBJS_DEFAULT_CHANGE); - } else { - setPageComplete(true); - setErrorMessage(null); - //setErrorMessage(RefactoringMessages.getString("RenameInputWizardPage.no_undo")); //$NON-NLS-1$ - if (severity == RefactoringStatus.OK) - setMessage(null, NONE); - else { - setMessage(status.getFirstMessage(severity), getCorrespondingIStatusSeverity(severity)); - setImageDescriptor(CPluginImages.DESC_OBJS_DEFAULT_CHANGE); - } - } - } - - /* (non-Javadoc) - * Method declared in WizardPage - */ - public void setVisible(boolean visible) { - if (visible) - getRefactoringWizard().setChange(null); - super.setVisible(visible); - } - - /* (non-JavaDoc) - * Method declared in IWizardPage. - */ - public IWizardPage getNextPage() { - if (fIsLastUserPage) - return getRefactoringWizard().computeUserInputSuccessorPage(this); - else - return super.getNextPage(); - } - - /* (non-JavaDoc) - * Method declared in IWizardPage. - */ - public boolean canFlipToNextPage() { - if (fIsLastUserPage) { - // we can't call getNextPage to determine if flipping is allowed since computing - // the next page is quite expensive (checking preconditions and creating a - // change). So we say yes if the page is complete. - return isPageComplete(); - } else { - return super.canFlipToNextPage(); - } - } - - /* (non-JavaDoc) - * Method defined in RefactoringWizardPage - */ - protected boolean performFinish() { - RefactoringWizard wizard= getRefactoringWizard(); - int threshold= RefactoringPreferences.getCheckPassedSeverity(); - RefactoringStatus activationStatus= wizard.getActivationStatus(); - RefactoringStatus inputStatus= null; - RefactoringStatus status= new RefactoringStatus(); - Refactoring refactoring= getRefactoring(); - boolean result= false; - - if (activationStatus != null && activationStatus.getSeverity() > threshold) { - inputStatus= wizard.checkInput(); - } else { - CreateChangeOperation create= new CreateChangeOperation(refactoring, CreateChangeOperation.CHECK_INPUT); - create.setCheckPassedSeverity(threshold); - - PerformChangeOperation perform= new PerformChangeOperation(create); - perform.setCheckPassedSeverity(threshold); - - result= wizard.performFinish(perform); - wizard.setChange(create.getChange()); - if (!result) - return false; - inputStatus= create.getStatus(); - } - - status.merge(activationStatus); - status.merge(inputStatus); - - if (status.getSeverity() > threshold) { - wizard.setStatus(status); - IWizardPage nextPage= wizard.getPage(ErrorWizardPage.PAGE_NAME); - wizard.getContainer().showPage(nextPage); - return false; - } - - return result; - } - - private static int getCorrespondingIStatusSeverity(int severity) { - if (severity == RefactoringStatus.FATAL) - return IStatus.ERROR; - if (severity == RefactoringStatus.ERROR) - return IStatus.WARNING; - if (severity == RefactoringStatus.WARNING) - return IStatus.WARNING; - if (severity == RefactoringStatus.INFO) - return IStatus.INFO; - return IStatus.OK; - } -} diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/UserInterfaceStarter.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/UserInterfaceStarter.java deleted file mode 100644 index fb9ec0d0e5a..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/UserInterfaceStarter.java +++ /dev/null @@ -1,82 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.refactoring; - - -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IConfigurationElement; - -import org.eclipse.swt.widgets.Shell; - -import org.eclipse.jface.dialogs.MessageDialog; -import org.eclipse.jface.util.Assert; - -import org.eclipse.cdt.internal.corext.refactoring.IRefactoringProcessor; -import org.eclipse.cdt.internal.corext.refactoring.base.Refactoring; - -import org.eclipse.cdt.internal.ui.refactoring.RefactoringStarter; - -/** - * Opens the user interface for a given refactoring. - */ -public class UserInterfaceStarter { - - protected static final String WIZARD= "wizard"; //$NON-NLS-1$ - - private IConfigurationElement fConfigElement; - - /** - * Opens the user interface for the given refactoring. The provided - * shell should be used as a parent shell. - * - * @param refactoring the refactoring for which the user interface - * should be opened - * @param parent the parent shell to be used - * - * @exception CoreException if the user interface can't be activated - */ - public static void run(Refactoring refactoring, Shell parent) throws CoreException { - run(refactoring, parent, true); - } - - /** - * Opens the user interface for the given refactoring. The provided - * shell should be used as a parent shell. - * - * @param refactoring the refactoring for which the user interface - * should be opened - * @param parent the parent shell to be used - * @param forceSave true if saving is needed before - * executing the refactoring - * - * @exception CoreException if the user interface can't be activated - */ - public static void run(Refactoring refactoring, Shell parent, boolean forceSave) throws CoreException { - IRefactoringProcessor processor= (IRefactoringProcessor)refactoring.getAdapter(IRefactoringProcessor.class); - // TODO this should change. Either IRefactoring models Refactoring API. - Assert.isNotNull(processor); - UserInterfaceStarter starter= new UserInterfaceStarter(); - if(starter != null) { - starter.activate(refactoring, parent, forceSave); - } else - { - MessageDialog.openInformation(parent, - refactoring.getName(), - RefactoringMessages.getString("UserInterfaceStarter.No_ui_found")); //$NON-NLS-1$ - } - } - - protected void activate(Refactoring refactoring, Shell parent, boolean save) throws CoreException { - RenameElementWizard wizard= new RenameElementWizard(); - wizard.initialize(refactoring); - new RefactoringStarter().activate(refactoring, wizard, parent, wizard.getDefaultPageTitle(), save); - } -} diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/actions/RedoRefactoringAction.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/actions/RedoRefactoringAction.java deleted file mode 100644 index 76b89757d52..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/actions/RedoRefactoringAction.java +++ /dev/null @@ -1,123 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.cdt.internal.ui.refactoring.actions; - -import java.lang.reflect.InvocationTargetException; - -import org.eclipse.cdt.core.model.CModelException; -import org.eclipse.cdt.internal.corext.refactoring.base.ChangeAbortException; -import org.eclipse.cdt.internal.corext.refactoring.base.ChangeContext; -import org.eclipse.cdt.internal.corext.refactoring.base.IUndoManager; -import org.eclipse.cdt.internal.corext.refactoring.base.Refactoring; -import org.eclipse.cdt.internal.corext.refactoring.base.UndoManagerAdapter; -import org.eclipse.cdt.internal.ui.editor.CEditor; -import org.eclipse.cdt.internal.ui.refactoring.RefactoringMessages; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.jface.action.IAction; -import org.eclipse.jface.operation.IRunnableWithProgress; -import org.eclipse.jface.viewers.ISelection; -import org.eclipse.ui.IWorkbenchSite; - -public class RedoRefactoringAction extends UndoManagerAction { - - private int fPatternLength; - private CEditor fEditor; - - public RedoRefactoringAction(CEditor editor) { - this(editor.getEditorSite()); - fEditor= editor; - } - - public RedoRefactoringAction(IWorkbenchSite site) { - super(site); - init(site.getWorkbenchWindow()); - } - - /* (non-Javadoc) - * Method declared in UndoManagerAction - */ - protected String getName() { - // PR: 1GEWDUH: ITPJCORE:WINNT - Refactoring - Unable to undo refactor change - return RefactoringMessages.getString("RedoRefactoringAction.name"); //$NON-NLS-1$ - } - - /* (non-Javadoc) - * Method declared in UndoManagerAction - */ - protected IRunnableWithProgress createOperation(final ChangeContext context) { - // PR: 1GEWDUH: ITPJCORE:WINNT - Refactoring - Unable to undo refactor change - return new IRunnableWithProgress(){ - public void run(IProgressMonitor pm) throws InvocationTargetException { - try { - setPreflightStatus(Refactoring.getUndoManager().performRedo(context, pm)); - } catch (CModelException e) { - throw new InvocationTargetException(e); - } catch (ChangeAbortException e) { - throw new InvocationTargetException(e); - } - } - - }; - } - - /* (non-Javadoc) - * Method declared in UndoManagerAction - */ - protected UndoManagerAdapter createUndoManagerListener() { - return new UndoManagerAdapter() { - public void redoStackChanged(IUndoManager manager) { - IAction action= getAction(); - if (action == null) - return; - boolean enabled= false; - String text= null; - if (manager.anythingToRedo()) { - enabled= true; - text= getActionText(); - } else { - text= RefactoringMessages.getString("RedoRefactoringAction.label"); //$NON-NLS-1$ - } - action.setEnabled(enabled); - action.setText(text); - } - }; - } - - /* (non-Javadoc) - */ - public void selectionChanged(ISelection s) { - selectionChanged(this, s); - } - - /* (non-Javadoc) - */ - public void selectionChanged(IAction action, ISelection s) { - if (!isHooked()) { - hookListener(action); - } - fPatternLength= RefactoringMessages.getString("RedoRefactoringAction.extendedLabel").length(); //$NON-NLS-1$ - IUndoManager undoManager = Refactoring.getUndoManager(); - if (undoManager.anythingToRedo()) { - if (undoManager.peekRedoName() != null) - action.setText(getActionText()); - action.setEnabled(true); - } else { - action.setEnabled(false); - } - } - - private String getActionText() { - return shortenText(RefactoringMessages.getFormattedString( - "RedoRefactoringAction.extendedLabel", //$NON-NLS-1$ - Refactoring.getUndoManager().peekRedoName()), fPatternLength); - } -} diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/actions/RenameRefactoringAction.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/actions/RenameRefactoringAction.java deleted file mode 100644 index 6ee031a1868..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/actions/RenameRefactoringAction.java +++ /dev/null @@ -1,133 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.refactoring.actions; - - -import org.eclipse.cdt.core.model.CModelException; -import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.cdt.core.model.ISourceRange; -import org.eclipse.cdt.core.model.ISourceReference; -import org.eclipse.cdt.core.model.ITranslationUnit; -import org.eclipse.cdt.internal.corext.refactoring.RenameRefactoring; -import org.eclipse.cdt.internal.ui.actions.SelectionConverter; -import org.eclipse.cdt.internal.ui.editor.CEditor; -import org.eclipse.cdt.internal.ui.refactoring.RefactoringMessages; -import org.eclipse.cdt.internal.ui.refactoring.UserInterfaceStarter; -import org.eclipse.cdt.internal.ui.util.ExceptionHandler; -import org.eclipse.cdt.ui.CUIPlugin; -import org.eclipse.cdt.ui.IWorkingCopyManager; -import org.eclipse.cdt.ui.actions.SelectionDispatchAction; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.jface.action.IAction; -import org.eclipse.jface.dialogs.MessageDialog; -import org.eclipse.jface.text.ITextSelection; -import org.eclipse.jface.viewers.ISelection; -import org.eclipse.jface.viewers.IStructuredSelection; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.ui.IWorkbenchSite; - - -public class RenameRefactoringAction extends SelectionDispatchAction { - - private CEditor fEditor; - - public RenameRefactoringAction(CEditor editor) { - this(editor.getEditorSite()); - fEditor= editor; - } - - public RenameRefactoringAction(IWorkbenchSite site) { - super(site); - setText(RefactoringMessages.getString("RenameRefactoringAction.text"));//$NON-NLS-1$ - } - - /* (non-Javadoc) - * @see org.eclipse.jdt.ui.actions.SelectionDispatchAction#selectionChanged(org.eclipse.jface.viewers.IStructuredSelection) - */ - public void selectionChanged(IStructuredSelection selection) { - setEnabled(selection.size() == 1); - } - - public void selectionChanged(ITextSelection selection) { - boolean enable = true; - IWorkingCopyManager manager = CUIPlugin.getDefault().getWorkingCopyManager(); - ICElement element = manager.getWorkingCopy(fEditor.getEditorInput()); - if((element == null) || (element instanceof ITranslationUnit)){ - setEnabled(false); - return; - } - ITextSelection textSelection= (ITextSelection)fEditor.getSelectionProvider().getSelection(); - - if (textSelection == null) { - setEnabled(false); - return; - } - if (element instanceof ISourceReference) { - try { - ISourceReference sourceRef = (ISourceReference)element; - ISourceRange range = sourceRef.getSourceRange(); - if( (range.getIdStartPos() != textSelection.getOffset()) - || (range.getIdLength() != textSelection.getLength())) { - enable = false; - } - } catch (CModelException e) { - // - } - } - setEnabled(enable); - } - - public void run(ITextSelection selection) { - try { - Object element= SelectionConverter.getElementAtOffset(fEditor); - RenameRefactoring refactoring= new RenameRefactoring(element); - run(refactoring, getShell()); - } catch (CoreException e) { - ExceptionHandler.handle(e, getShell(), RefactoringMessages.getString("RenameRefactoringAction.label"), //$NON-NLS-1$ - RefactoringMessages.getString("RenameRefactoringAction.unexpected_exception"));//$NON-NLS-1$ - } - } - - /* (non-Javadoc) - * @see org.eclipse.jdt.ui.actions.SelectionDispatchAction#run(org.eclipse.jface.viewers.IStructuredSelection) - */ - public void run(IStructuredSelection selection) { - Object element= selection.getFirstElement(); - try { - RenameRefactoring refactoring= new RenameRefactoring(element); - run(refactoring, getShell()); - } catch (CoreException e) { - ExceptionHandler.handle(e, getShell(), RefactoringMessages.getString("RenameRefactoringAction.label"), //$NON-NLS-1$ - RefactoringMessages.getString("RenameRefactoringAction.unexpected_exception"));//$NON-NLS-1$ - } - } - - /* (non-Javadoc) - * @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction) - */ - public void run(IAction action) { - run(); - } - - public void selectionChanged(IAction action, ISelection selection) { - action.setEnabled(true); - } - - public static void run(RenameRefactoring refactoring, Shell parent) throws CoreException { - if (refactoring.isAvailable()) { - UserInterfaceStarter.run(refactoring, parent); - } else { - MessageDialog.openInformation(parent, RefactoringMessages.getString("RenameRefactoringAction.label"), //$NON-NLS-1$ - RefactoringMessages.getString("RenameRefactoringAction.no_refactoring_available")//$NON-NLS-1$ - ); - } - } -} diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/actions/UndoManagerAction.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/actions/UndoManagerAction.java deleted file mode 100644 index c17d4d42ad9..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/actions/UndoManagerAction.java +++ /dev/null @@ -1,187 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.cdt.internal.ui.refactoring.actions; - -import java.lang.reflect.InvocationTargetException; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import org.eclipse.cdt.internal.corext.refactoring.base.ChangeContext; -import org.eclipse.cdt.internal.corext.refactoring.base.Refactoring; -import org.eclipse.cdt.internal.corext.refactoring.base.RefactoringStatus; -import org.eclipse.cdt.internal.corext.refactoring.base.RefactoringStatusEntry; -import org.eclipse.cdt.internal.corext.refactoring.base.UndoManagerAdapter; -import org.eclipse.cdt.internal.ui.refactoring.AbortChangeExceptionHandler; -import org.eclipse.cdt.internal.ui.refactoring.RefactoringMessages; -import org.eclipse.cdt.internal.ui.util.ExceptionHandler; -import org.eclipse.cdt.ui.CUIPlugin; -import org.eclipse.cdt.ui.actions.SelectionDispatchAction; -import org.eclipse.core.resources.IFile; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.MultiStatus; -import org.eclipse.core.runtime.Status; -import org.eclipse.jface.action.IAction; -import org.eclipse.jface.dialogs.ErrorDialog; -import org.eclipse.jface.dialogs.IDialogConstants; -import org.eclipse.jface.operation.IRunnableWithProgress; -import org.eclipse.jface.viewers.IStructuredSelection; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.ui.IEditorInput; -import org.eclipse.ui.IEditorPart; -import org.eclipse.ui.IFileEditorInput; -import org.eclipse.ui.IWorkbenchSite; -import org.eclipse.ui.IWorkbenchWindow; -import org.eclipse.ui.PlatformUI; - -abstract class UndoManagerAction extends SelectionDispatchAction { - - private static final int MAX_LENGTH= 30; - - private RefactoringStatus fPreflightStatus; - private IAction fAction; - private IWorkbenchWindow fWorkbenchWindow; - private UndoManagerAdapter fUndoManagerListener; - - public UndoManagerAction(IWorkbenchSite site) { - super(site); - } - - protected abstract IRunnableWithProgress createOperation(ChangeContext context); - - protected abstract UndoManagerAdapter createUndoManagerListener(); - - protected abstract String getName(); - - protected IWorkbenchWindow getWorkbenchWindow() { - return fWorkbenchWindow; - } - - protected IAction getAction() { - return fAction; - } - - protected boolean isHooked() { - return fAction != null; - } - - protected void hookListener(IAction action) { - if (isHooked()) - return; - fAction= action; - fUndoManagerListener= createUndoManagerListener(); - Refactoring.getUndoManager().addListener(fUndoManagerListener); - } - - protected String shortenText(String text, int patternLength) { - int length= text.length(); - final int finalLength = MAX_LENGTH + patternLength; - if (text.length() <= finalLength) - return text; - StringBuffer result= new StringBuffer(); - int mid= finalLength / 2; - result.append(text.substring(0, mid)); - result.append("..."); //$NON-NLS-1$ - result.append(text.substring(length - mid)); - return result.toString(); - } - - /* (non-Javadoc) - * Method declared in IActionDelegate - */ - public void dispose() { - if (fUndoManagerListener != null) - Refactoring.getUndoManager().removeListener(fUndoManagerListener); - fWorkbenchWindow= null; - fAction= null; - fUndoManagerListener= null; - } - - /* (non-Javadoc) - */ - public void init(IWorkbenchWindow window) { - fWorkbenchWindow= window; - } - public void run(IStructuredSelection selection) { - run(); - } - public void run(IAction action) { - run(); - } - /* (non-Javadoc) - */ - public void run() { - Shell parent= fWorkbenchWindow.getShell(); - ChangeContext context= new ChangeContext(new AbortChangeExceptionHandler(), getUnsavedFiles()); - IRunnableWithProgress op= createOperation(context); - try { - // Don't execute in separate thread since it updates the UI. - PlatformUI.getWorkbench().getActiveWorkbenchWindow().run(false, false, op); - } catch (InvocationTargetException e) { - Refactoring.getUndoManager().flush(); - ExceptionHandler.handle(e, RefactoringMessages.getString("UndoManagerAction.error"), RefactoringMessages.getString("UndoManagerAction.internal_error")); //$NON-NLS-2$ //$NON-NLS-1$ - } catch (InterruptedException e) { - // Opertation isn't cancelable. - } finally { - context.clearPerformedChanges(); - } - - if (fPreflightStatus != null && fPreflightStatus.hasError()) { - String name= getName(); - MultiStatus status = createMultiStatus(); - String message= RefactoringMessages.getFormattedString("UndoManagerAction.cannot_be_executed", name); //$NON-NLS-1$ - ErrorDialog error= new ErrorDialog(parent, name, message, status, IStatus.ERROR) { - public void create() { - super.create(); - buttonPressed(IDialogConstants.DETAILS_ID); - } - }; - error.open(); - } - fPreflightStatus= null; - } - - /* package */ void setPreflightStatus(RefactoringStatus status) { - fPreflightStatus= status; - } - - private MultiStatus createMultiStatus() { - MultiStatus status= new MultiStatus( - CUIPlugin.getPluginId(), - IStatus.ERROR, - RefactoringMessages.getString("UndoManagerAction.unsaved_filed"), //$NON-NLS-1$ - null); - String id= CUIPlugin.getPluginId(); - for (Iterator iter= fPreflightStatus.getEntries().iterator(); iter.hasNext(); ) { - RefactoringStatusEntry entry= (RefactoringStatusEntry)iter.next(); - status.merge(new Status( - IStatus.ERROR, - id, - IStatus.ERROR, - entry.getMessage(), - null)); - } - return status; - } - - private IFile[] getUnsavedFiles() { - IEditorPart[] parts= CUIPlugin.getDirtyEditors(); - List result= new ArrayList(parts.length); - for (int i= 0; i < parts.length; i++) { - IEditorInput input= parts[i].getEditorInput(); - if (input instanceof IFileEditorInput) { - result.add(((IFileEditorInput)input).getFile()); - } - } - return (IFile[])result.toArray(new IFile[result.size()]); - } -} diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/actions/UndoRefactoringAction.java b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/actions/UndoRefactoringAction.java deleted file mode 100644 index 11d802346cd..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/actions/UndoRefactoringAction.java +++ /dev/null @@ -1,121 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ - -package org.eclipse.cdt.internal.ui.refactoring.actions; - -import java.lang.reflect.InvocationTargetException; - -import org.eclipse.cdt.core.model.CModelException; -import org.eclipse.cdt.internal.corext.refactoring.base.ChangeAbortException; -import org.eclipse.cdt.internal.corext.refactoring.base.ChangeContext; -import org.eclipse.cdt.internal.corext.refactoring.base.IUndoManager; -import org.eclipse.cdt.internal.corext.refactoring.base.Refactoring; -import org.eclipse.cdt.internal.corext.refactoring.base.UndoManagerAdapter; -import org.eclipse.cdt.internal.ui.editor.CEditor; -import org.eclipse.cdt.internal.ui.refactoring.RefactoringMessages; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.jface.action.IAction; -import org.eclipse.jface.operation.IRunnableWithProgress; -import org.eclipse.jface.viewers.ISelection; -import org.eclipse.ui.IWorkbenchSite; - -public class UndoRefactoringAction extends UndoManagerAction { - - private int fPatternLength; - private CEditor fEditor; - - public UndoRefactoringAction(CEditor editor) { - this(editor.getEditorSite()); - fEditor= editor; - } - - public UndoRefactoringAction(IWorkbenchSite site) { - super(site); - init(site.getWorkbenchWindow()); - } - - /* (non-Javadoc) - * Method declared in UndoManagerAction - */ - protected String getName() { - // PR: 1GEWDUH: ITPJCORE:WINNT - Refactoring - Unable to undo refactor change - return RefactoringMessages.getString("UndoRefactoringAction.name"); //$NON-NLS-1$ - } - - /* (non-Javadoc) - * Method declared in UndoManagerAction - */ - protected IRunnableWithProgress createOperation(final ChangeContext context) { - // PR: 1GEWDUH: ITPJCORE:WINNT - Refactoring - Unable to undo refactor change - return new IRunnableWithProgress(){ - public void run(IProgressMonitor pm) throws InvocationTargetException { - try { - setPreflightStatus(Refactoring.getUndoManager().performUndo(context, pm)); - } catch (CModelException e) { - throw new InvocationTargetException(e); - } catch (ChangeAbortException e) { - throw new InvocationTargetException(e); - } - } - - }; - } - - /* (non-Javadoc) - * Method declared in UndoManagerAction - */ - protected UndoManagerAdapter createUndoManagerListener() { - return new UndoManagerAdapter() { - public void undoStackChanged(IUndoManager manager) { - IAction action= getAction(); - if (action == null) - return; - boolean enabled= false; - String text= null; - if (manager.anythingToUndo()) { - enabled= true; - text= getActionText(); - } else { - text= RefactoringMessages.getString("UndoRefactoringAction.label"); //$NON-NLS-1$ - } - action.setEnabled(enabled); - action.setText(text); - } - }; - } - /* (non-Javadoc) - */ - public void selectionChanged(ISelection s) { - selectionChanged(this, s); - } - /* (non-Javadoc) - */ - public void selectionChanged(IAction action, ISelection s) { - if (!isHooked()) { - hookListener(this); - } - fPatternLength= RefactoringMessages.getString("UndoRefactoringAction.extendedLabel").length(); //$NON-NLS-1$ - IUndoManager undoManager = Refactoring.getUndoManager(); - if (undoManager.anythingToUndo()) { - if (undoManager.peekUndoName() != null) - action.setText(getActionText()); - action.setEnabled(true); - } else { - action.setEnabled(false); - } - } - - private String getActionText() { - return shortenText(RefactoringMessages.getFormattedString( - "UndoRefactoringAction.extendedLabel", //$NON-NLS-1$ - Refactoring.getUndoManager().peekUndoName()), fPatternLength); - } -} diff --git a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/refactoringui.properties b/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/refactoringui.properties deleted file mode 100644 index cdf897a0fe6..00000000000 --- a/core/org.eclipse.cdt.ui/refactor/org/eclipse/cdt/internal/ui/refactoring/refactoringui.properties +++ /dev/null @@ -1,585 +0,0 @@ -############################################################################### -# Copyright (c) 2004 IBM Corporation and others. -# All rights reserved. This program and the accompanying materials -# are made available under the terms of the Eclipse Public License v1.0 -# which accompanies this distribution, and is available at -# http://www.eclipse.org/legal/epl-v10.html -# -# Contributors: -# IBM Rational Software - Initial API and implementation -############################################################################### -####################################### -# org.eclipse.jdt.internal.ui.refactoring -####################################### - -RefactorActionGroup.no_refactoring_available= - -ErrorWizardPage.no_context_information_available= No context information available -ErrorWizardPage.cannot_proceed= Cannot proceed due to the following problems. -ErrorWizardPage.confirm= Review the information provided in the list below. Click 'Next' to view the next item or 'Finish'. -ErrorWizardPage.next_Change=Next Problem -ErrorWizardPage.previous_Change=Previous Problem - -PreviewWizardPage.no_preview= No preview available -PreviewWizardPage.next_Change= Select Next Change -PreviewWizardPage.previous_Change= Select Previous Change -PreviewWizardPage.changes= Changes to be performed - -ComparePreviewer.element_name= Compare element name -ComparePreviewer.original_source= Original Source -ComparePreviewer.refactored_source= Refactored Source - -PreviewWizardPage.description= The following changes are necessary to perform the refactoring. -PreviewWizardPage.changeElementLabelProvider.textFormat= {0} - {1} -PreviewWizardPage.changeElementLabelProvider.textFormatEdit= {0}: {1} - -RefactoringPreferencePage.description= Refactoring settings: -RefactoringPreferencePage.auto_save= &Save all modified resources automatically prior to refactoring -RefactoringPreferencePage.error= \ &Errors would be present in the workspace after performing the refactoring -RefactoringPreferencePage.fatal_error= \ &Problems occur that prevent the refactoring from being performed -RefactoringPreferencePage.info= \ &Information is generated by the precondition checking -RefactoringPreferencePage.show_error_page= Confirm the execution of the refactoring if -RefactoringPreferencePage.warning= \ &Warnings would be present in the workspace after performing the refactoring - -RefactoringWizard.Internal_error= Internal error while creating a change object. See log for details. -RefactoringWizard.internal_error_1= Internal error during precondition checking. See log for detailed error description -RefactoringWizard.refactoring= Refactoring -RefactoringWizard.see_log= {0}. See log for details. -RefactoringWizard.title= Refactoring -RefactoringWizard.undoing= Undoing changes: -RefactoringWizard.unexpected_exception= Unexpected exception while creating a change object. See log for a detailed error description. -RefactoringWizard.unexpected_exception_1= Unexpected exception while performing the refactoring. See log for a detailed error description. - -RenameInputWizardPage.enter_name= &Enter new name: -RenameInputWizardPage.old_name= Renaming: -RenameInputWizardPage.no_undo=This operation can not be undone! - -RenameRefactoringWizard.internal_error= Internal error during name checking: {0} - -PerformChangeOperation.unrecoverable_error= Unrecoverable error occurred while performing the refactoring. - -####################################### -# org.eclipse.jdt.internal.ui.actions -####################################### - -OpenRefactoringWizardAction.refactoring=Refactoring -OpenRefactoringWizardAction.exception=Unexpected exception occurred. See log for details - -ExtractMethodAction.label=&Extract Method... -ExtractMethodAction.dialog.title=Extract Method - -SurroundWithTryCatchAction.label=Surround with &try/catch Block -SurroundWithTryCatchAction.dialog.title=Surround with try/catch -SurroundWithTryCatchAction.exception=Unexpected exception occurred. See log for details -SurroundWithTryCatchAction.no_exceptions=No uncaught exceptions are thrown by the selected code. Catch java.lang.RuntimeException ? - -RefactoringGroup.rename_method_message=Enter the new name for this method. -RefactoringGroup.rename_method_title=Rename Method -RefactoringGroup.rename_type_message=Enter the new name for this type. -RefactoringGroup.rename_type_title=Rename Element -RefactoringGroup.modify_Parameters_label=Change Method Si&gnature... -RefactoringGroup.pull_Up_label=Pu&ll Up... -RefactoringGroup.move_label=&Move... -RefactoringGroup.rename_resource_message=Enter the new name for this resource. -RefactoringGroup.rename_resource_title=Rename Resource -RefactoringGroup.rename_java_project_message=Enter the new name for this C project. -RefactoringGroup.rename_java_project_title=Rename C Project -RefactoringGroup.rename_source_folder_message=Enter the new name for this source folder. -RefactoringGroup.rename_source_folder_title=Rename Source Folder - -RefactoringErrorDialogUtil.cannot_perform=This operation cannot be performed. - -RefactoringStarter.unexpected_exception=Unexpected exception. See log for details -RefactoringStarter.saving=Saving Resources -RefactoringStarter.always_save=&Always save all modified resources automatically prior to refactoring -RefactoringStarter.save_all_resources=Save all modified resources -RefactoringStarter.must_save=All modified resources have to be saved before this operation.\n Click 'OK' to confirm or click 'Cancel' - -####################################### -# org.eclipse.jdt.internal.ui.changes -####################################### - -ChangeExceptionHandler.abort=Abort -ChangeExceptionHandler.refactoring=Refactoring -ChangeExceptionHandler.undo=Undo -ChangeExceptionHandler.unexpected_exception=An exception has been caught while processing the change ''{0}''. -ChangeExceptionHandler.button_explanation= \n Click \"Undo\" to undo all successfully executed changes.\n Click \"Abort\" to abort the refactoring. -ChangeExceptionHandler.no_details= Exception does not provide a detail message - -####################################### -# org.eclipse.jdt.internal.ui.code -####################################### - -ExtractMethodWizard.extract_method=Extract Method - -ExtractMethodInputPage.access_Modifiers=Access modifier: -ExtractMethodInputPage.public=&public -ExtractMethodInputPage.default=de&fault -ExtractMethodInputPage.protected=pro&tected -ExtractMethodInputPage.private=pri&vate -ExtractMethodInputPage.signature_preview=Signature preview: -ExtractMethodInputPage.description=Enter new method name and specify the method's visibility -ExtractMethodInputPage.label_text=&Method name: -ExtractMethodInputPage.parameters=Pa&rameters: -ExtractMethodInputPage.throwRuntimeExceptions=&Add thrown runtime exceptions to method signature -ExtractMethodInputPage.validation.emptyMethodName=Provide a method name -ExtractMethodInputPage.validation.emptyParameterName=Parameter names cannot be empty -ExtractMethodInputPage.duplicates.none=Repla&ce duplicate code fragments -ExtractMethodInputPage.duplicates.single=Repla&ce 1 duplicate code fragment -ExtractMethodInputPage.duplicates.multi=Repla&ce {0} duplicate code fragments - -InlineMethodWizard.page_title=Inline Method - -####################################### -# org.eclipse.jdt.internal.ui.sef -####################################### - -SelfEncapsulateField.sef=Self Encapsulate Field - -SelfEncapsulateFieldInputPage.description=Create getting and setting methods for the field and use only those to access the field -SelfEncapsulateFieldInputPage.getter_name=&Getter name: -SelfEncapsulateFieldInputPage.setter_name=&Setter name: -SelfEncapsulateFieldInputPage.insert_after=&Insert new methods after: -SelfEncapsulateFieldInputPage.first_method=As first method -SelfEncapsulateFieldInputPage.access_Modifiers=Access modifier: -SelfEncapsulateFieldInputPage.public=&public -SelfEncapsulateFieldInputPage.default=defa&ult -SelfEncapsulateFieldInputPage.protected=pro&tected -SelfEncapsulateFieldInputPage.private=pri&vate -SelfEncapsulateField.field_access=Field access in declaring class: -SelfEncapsulateField.use_setter_getter=us&e setter and getter -SelfEncapsulateField.keep_references=&keep field reference - -####################################### -# org.eclipse.jdt.internal.ui.undo -####################################### - -UndoManagerAction.cannot_be_executed={0} cannot be executed. -UndoManagerAction.error=Error -UndoManagerAction.internal_error=Internal Error in Undo Manager -UndoManagerAction.unsaved_filed=Some of the affected resources are unsaved or read only. Please revert unsaved files and make read only resources writeable. - -UndoRefactoringAction.label=&Undo -UndoRefactoringAction.extendedLabel=Undo - {0} -UndoRefactoringAction.name=Undo - -RedoRefactoringAction.label=&Redo -RedoRefactoringAction.extendedLabel=Redo - {0} -RedoRefactoringAction.name=Redo - -RenameRefactoringAction.label=Rename Refactoring -RenameRefactoringAction.text=Rename... -RenameRefactoringAction.no_refactoring_available=No refactoring available to process the selected element. -RenameRefactoringAction.unexpected_exception=Unexpected Exception occured. - -####################################### -# Misc -####################################### - -ExtractTempWizard.defaultPageTitle=Extract Local Variable -ExtractTempInputPage.enter_name=Enter a name for the new local variable -ExtractTempInputPage.variable_name=&Variable name: -ExtractTempInputPage.replace_all=&Replace all occurrences of the selected expression with references to the local variable -ExtractTempInputPage.declare_final=&Declare the local variable as \'final\' -ExtractTempInputPage.signature_preview=Signature Preview: -ExtractTempInputPage.extract_local=Extract local variable -ExtractTempInputPage.exception=Unexpected exception. See log for details - -ExtractConstantInputPage.enter_name=Enter a name for the new constant -ExtractConstantInputPage.constant_name=&Constant name: -ExtractConstantInputPage.replace_all=&Replace all occurrences of the selected expression with references to the constant -ExtractConstantInputPage.qualify_constant_references_with_class_name=&Qualify constant references with class name -ExtractConstantInputPage.signature_preview=Signature Preview: -ExtractConstantInputPage.exception=Unexpected exception. See log for details -ExtractConstantInputPage.access_modifiers=Access modifier: -ExtractConstantInputPage.selection_refers_to_nonfinal_fields=The selected expression refers to non-final or non-static fields - -PromoteTempInputPage.description=Select visibility and name for the new field - -MoveMembersWizard.page_title=Move Static Member(s) - -RenameInputWizardPage.update_references=&Update references to the renamed element -RenameInputWizardPage.ppdate_string_references=U&pdate references in string literals -RenameInputWizardPage.update_comment_references=Up&date references in regular comments -RenameInputWizardPage.update_qualified_names=Update fully &qualified name in non C files (forces preview) - -RefactoringSupportFactory.rename=Rename -RefactoringSupportFactory.rename_Package=Rename Package -RefactoringSupportFactory.package_name=Enter the new name for this package. -RefactoringSupportFactory.rename_Cu=Rename Translation Unit -RefactoringSupportFactory.translation_unit=Enter the new name for this translation unit. - -PullUpInputPage.select_methods=Select the methods to be removed in subtypes after pull up. -PullUpInputPage.pull_Up=Pull Up -PullUpInputPage.pull_up1=Pull Up Methods -PullUpInputPage.exception=Unexpected exception. See log for details - -ExtractTempAction.label=Extract Local &Variable... -ExtractTempAction.extract_temp=Extract Local Variable - -ConvertLocalToField.label=Conv&ert Local Variable to Field... -ConvertLocalToField.title=Convert Local Variable to Field - -ExtractConstantAction.label=Extr&act Constant... -ExtractConstantAction.extract_constant=Extract Constant - -InlineTempAction.inline_temp=Inline Local Variable -InlineTempAction.label=&Inline Local Variable... - -RenameAction.rename=Rename -RenameAction.unavailable=Operation unavailable on the current selection.\nSelect a C/C++ project, source folder, resource or a translation unit, or a non binary type, field, method, parameter or a local variable. -RenameAction.text=Re&name... - -UndoAction.rename=Undo Action -UndoAction.unavailable=Operation unavailable. -UndoAction.text=&Undo... - -RedoAction.rename=Redo Action -RedoAction.unavailable=Operation unavailable. -RedoAction.text=&Redo... - - -RenameInputDialog.update_references=&Update references to the renamed element - -RenameTempAction.rename_Local_Variable=Rename Local Variable -RenameTempAction.choose_new_name=Choose a new name for the local variable - -NewTextRefactoringAction.exception=Unexpected exception occurred. See log for details - -RenameFieldWizard.defaultPageTitle=Rename Field -RenameFieldWizard.inputPage.description=Enter the new name for this field. -RenameFieldInputWizardPage.rename_getter=Rename &getter -RenameFieldInputWizardPage.rename_getter_to=Rename &getter: ''{0}'' to ''{1}'' -RenameFieldInputWizardPage.rename_setter=Rename &setter -RenameFieldInputWizardPage.rename_setter_to=Rename &setter: ''{0}'' to ''{1}'' -RenameFieldInputWizardPage.setter_label={0} ({1}) -RenameFieldInputWizardPage.getter_label={0} ({1}) - -MoveMembersInputPage.descriptionKey={0} member(s) from ''{1}'' -MoveMembersInputPage.destination_single=&Destination type for ''{0}'': -MoveMembersInputPage.destination_multi=&Destination type for {0} selected elements: -MoveMembersInputPage.browse=&Browse... -MoveMembersInputPage.move_Member=Move Member -MoveMembersInputPage.exception=Unexpected exception. See log for details -MoveMembersInputPage.choose_Type=Choose Type -MoveMembersInputPage.dialogMessage=&Choose a type (? = any character, * = any string): -MoveMembersInputPage.upperListLabel=&Matching types: -MoveMembersInputPage.lowerListLabel=&Qualifier: -MoveMembersInputPage.not_found=Destination type does not exist (fully qualified type name expected) -MoveMembersInputPage.invalid_name=Invalid Type Name -MoveMembersInputPage.Invalid_selection=Invalid selection -MoveMembersInputPage.no_binary=Cannot move members to binary types -MoveMembersInputPage.internal_error=Internal error. See log for details. -MoveMembersInputPage.move=Move Members - -RenameCElementAction.exception=Unexpected exception occurred. See log for details -RenameCElementAction.not_available=Operation unavailable on the current selection.\nSelect a java project, source folder, resource, package, translation unit, type, field, method, parameter or a local variable -RenameCElementAction.name=Rename - -MoveAction.text=Mo&ve... - -QualifiedNameComponent.patterns.label= &File name patterns: -QualifiedNameComponent.patterns.description= The patterns are separated by comma (* = any string, ? = any character) - -## Pull Up -PullUpInputPage.hierarchyLabal=Select the methods to be removed in subtypes after pull up.\n{0} method(s) selected. -PullUpInputPage.see_log=See log - -##Change Signature -ChangeSignatureInputPage.change=Change the signature of the selected method and all its overriding methods. -ChangeSignatureInputPage.parameters=Pa&rameters -ChangeSignatureInputPage.exceptions=E&xceptions -ChangeSignatureInputPage.method_Signature_Preview=Method Signature Preview: -ChangeSignatureInputPage.exception=Unexpected exception. See log for details -ChangeSignatureRefactoring.modify_Parameters=Change Method Signature - -RenameTempAction.exception=Unexpected Exception. See log for details -ModifyParametersAction.unavailable=To activate this refactoring, please select the name of a method -OpenRefactoringWizardAction.unavailable=Operation Unavailable -PullUpAction.unavailable=To activate this refactoring, please select the name of an instance method or field -MoveMembersAction.unavailable=To activate this refactoring, please select the name of a static method or field -PullUpInputPage.subtypes=&Subtypes of type ''{0}'' - -RefactoringSupportFactory.error.title=Rename -RefactoringSupportFactory.error.message=Renaming not possible. -MoveMembersAction.error.title=Refactoring -MoveMembersAction.error.message=Operation not possible. -RefactoringErrorDialogUtil.okToPerformQuestion=\n\nOK to perform the operation on this method? - -ChangeParametersControl.table.type=Type -ChangeParametersControl.table.name=Name -ChangeParametersControl.table.defaultValue=Default value -ChangeParametersControl.buttons.move_up=&Up -ChangeParametersControl.buttons.move_down=&Down -ChangeParametersControl.buttons.edit=Ed&it... -ChangeParametersControl.buttons.add=&Add -ChangeParametersControl.buttons.remove=Re&move - -ChangeExceptionsControl.buttons.add=&Add... -ChangeExceptionsControl.buttons.remove=Re&move -ChangeExceptionsControl.choose.title=Add Exception -ChangeExceptionsControl.choose.message=&Choose an Exception (? = any character, * = any string): -ChangeExceptionsControl.not_exception=Not an Exception - -ParameterEditDialog.title=Method Parameter -ParameterEditDialog.message.new=Declaration of Parameter: -ParameterEditDialog.message=Declaration of Parameter ''{0}'': - -ParameterEditDialog.type=&Type: -ParameterEditDialog.type.error= The empty string is not a valid type name. -ParameterEditDialog.name=&Name: -ParameterEditDialog.name.error= Parameter name must not be empty. -ParameterEditDialog.defaultValue=&Default value: -ParameterEditDialog.defaultValue.error= Default value must not be empty. - -InlineTempWizard.defaultPageTitle= Inline Local Variable -InlineTempInputPage.message.one= Inline 1 occurrence of local variable {0} ? -InlineTempInputPage.message.multi= Inline {0} occurrences of local variable {1} ? - -RefactoringWizardDialog2.buttons.preview.label=Previe&w > - -ChangeSignatureInputPage.Change_Signature=Change Signature -ChangeSignatureInputPage.return_type=Re&turn type: - -ConvertAnonymousToNestedInputPage.description=Select the name and modifiers for the new nested class -ConvertAnonymousToNestedInputPage.class_name=&Class name: -ConvertAnonymousToNestedInputPage.declare_final=Decla&re class as \'final\' - -ExtractConstantWizard.defaultPageTitle=Extract Constant -ExtractConstantInputPage.Internal_Error=Internal Error: please see log. - -ExtractInterfaceInputPage.description=Select the name for the new interface and select the members that will be declared in the interface. -ExtractInterfaceInputPage.Interface_name=&Interface name: -ExtractInterfaceInputPage.Members=&Members to declare in the interface: -ExtractInterfaceInputPage.Extract_Interface=Extract Interface -ExtractInterfaceInputPage.Internal_Error=Internal Error. See log for details -ExtractInterfaceInputPage.Select_All=&Select All -ExtractInterfaceInputPage.Deselect_All=&Deselect All -ExtractInterfaceInputPage.change_references=&Change references to the class ''{0}'' into references to the interface (where possible) -ExtractInterfaceWizard.Extract_Interface=Extract Interface - -InlineConstantInputPage.Inline=Inline -InlineConstantInputPage.All_references=&All references -InlineConstantInputPage.Delete_constant=&Delete constant declaration -InlineConstantInputPage.Only_selected=&Only the selected reference -InlineConstantWizard.message=Specify where to inline references to the constant. -InlineConstantWizard.Inline_Constant=Inline Constant -InlineConstantWizard.initializer_refers_to_fields=This constant\'s initializer refers to non-final or non-static fields - -MoveInnerToTopWizard.Move_Inner=Move Member Type to New File -MoveInnerToToplnputPage.description=Specify a name for the field that will be used to access the enclosing instance -MoveInnerToToplnputPage.create_field=&Create field for the enclosing instance -MoveInnerToToplnputPage.instance_final=&Mark the enclosing instance field as \'final\' -MoveInnerToToplnputPage.enter_name=Field &name: - -MoveInstanceMethodInputPage.Original_parameter=&Original receiver parameter name: -MoveInstanceMethodInputPage.New_name=New &method name: -MoveInstanceMethodInputPage.New_receiver=&New receiver for ''{0}'': -MoveInstanceMethodInputPage.Name=Name -MoveInstanceMethodInputPage.Type_Name=Type Name -MoveInstanceMethodWizard.Move_Method=Move Method - -PreviewWizardPage.no_source_code_change=The refactoring does not change any source code. - -PromoteTempInputPage.Field_declaration=Field decla&ration -PromoteTempInputPage.Current_method=&Current method -PromoteTempInputPage.constructors=C&lass constructor(s) -PromoteTempInputPage.Field_name=F&ield name: -PromoteTempInputPage.Initialize=Initialize in -PromoteTempInputPage.declare_static=D&eclare field as \'static\' -PromoteTempInputPage.declare_final=Decl&are field as \'final\' - -RefactoringStatusDialog.Cannot_proceed=Cannot proceed due to the following problems. -RefactoringStatusDialog.Please_look=Review the information provided in the list below. If you want to proceed, please click \'Continue\'. -RefactoringStatusDialog.Continue=Con&tinue -RefactoringStatusViewer.Found_problems=Found problems -RefactoringStatusViewer.Problem_context=Problem context - -UseSupertypeInputPage.Select_supertype=Select the supertype to use -UseSupertypeInputPage.Use_in_instanceof=&Use the selected supertype in \'instanceof\' expressions -UseSupertypeInputPage.Select_supertype_to_use=&Select the supertype to use: -UseSupertypeInputPage.No_updates=No updates possible for the selected supertype -UseSupertypeInputPage.Use_Supertype=Use Supertype -UseSupertypeInputPage.Internal_Error=Internal Error. See log for details -UseSupertypeInputPage.no_possible_updates={0} - no possible updates found -UseSupertypeInputPage.updates_possible_in_file={0} - updates possible in 1 file -UseSupertypeInputPage.updates_possible_in_files={0} - updates possible in {1} files -UseSupertypeWizard.Use_Super_Type_Where_Possible=Use Super Type Where Possible - -VisibilityControlUtil.Access_modifier=Access modifier -VisibilityControlUtil.defa&ult_4=d&efault -VisibilityControlUtil.final=&final -VisibilityControlUtil.synchronized=s&ynchronized - -PullUpWizard.defaultPageTitle=Pull up -PullUpInputPage1.pull_up=pull up -PullUpInputPage1.declare_abstract=declare abstract in destination -PullUpInputPage1.Create_stubs=&Create necessary methods stubs in non-abstract subclasses of the destination class -PullUpInputPage1.Select_destination=&Select destination class: -PullUpInputPage1.Specify_actions=&Specify actions for members: -PullUpInputPage1.Edit=&Edit... -PullUpInputPage1.Add_Required=&Add Required -PullUpInputPage1.Edit_members=Edit Members -PullUpInputPage1.Mark_selected_members=&Mark selected member(s) as: -PullUpInputPage1.Member=Member -PullUpInputPage1.Action=Action -PullUpInputPage1.Select_members_to_pull_up=No members selected to pull up or declare abstract -PullUpInputPage1.page_message=Select the members to pull up and their new declaring class.\n If you select methods, then click 'Next' to specify which matching methods you want to delete. -PullUpInputPage1.status_line={0} member(s) selected. - -PullUpInputPage2.Select=Restore &Defaults -PullUpInputPage2.Source=Source - -PushDownWizard.defaultPageTitle= Push Down -PushDownInputPage.leave_abstract=leave abstract declaration -PushDownInputPage.push_down=push down -PushDownInputPage.Specify_actions=&Specify actions for members: -PushDownInputPage.Member=Member -PushDownInputPage.Action=Action -PushDownInputPage.Edit=&Edit... -PushDownInputPage.Add_Required=&Add Required -PushDownInputPage.Push_Down=Push Down -PushDownInputPage.Internal_Error=Internal Error. See log for details. -PushDownInputPage.Edit_members=Edit Members -PushDownInputPage.Mark_selected_members=&Mark selected member(s) as: -PushDownInputPage.Select_members_to_push_down=No members selected to push down or declare abstract -PushDownInputPage.status_line={0} member(s) selected. - -ChangeSignatureInputPage.Internal_Error=Internal Error. See log for details. - -MoveInstanceMethodAction.dialog_title=Move Method -MoveInstanceMethodAction.Move_Method=Move Method... -MoveInstanceMethodAction.unexpected_exception=Unexpected exception during operation -MoveInstanceMethodAction.No_reference_or_declaration=No method reference or declaration selected. - -InlineConstantAction.dialog_title=Inline Constant -InlineConstantAction.inline_Constant=Inline &Constant... -InlineConstantAction.unexpected_exception=Unexpected exception during operation -InlineConstantAction.no_constant_reference_or_declaration=No constant reference or declaration selected. - -InlineMethodInputPage.description=Specify where to inline the method invocation. -InlineMethodInputPage.inline=Inline -InlineMethodInputPage.all_invocations=All invocations -InlineMethodInputPage.delete_declaration=Delete method declaration -InlineMethodInputPage.only_selected=Only the selected invocation - -InlineMethodAction.dialog_title=Inline Method -InlineMethodAction.inline_Method=I&nline Method... -InlineMethodAction.unexpected_exception=Unexpected exception during operation -InlineMethodAction.no_method_invocation_or_declaration_selected=No method invocation or declaration selected. - -UseSupertypeAction.use_Supertype=Use Supertype &Where Possible... -UseSupertypeAction.to_activate=To activate this refactoring, please select the name of a type -UseSupertypeAction.Refactoring=Refactoring -UseSupertypeAction.not_possible=Operation not possible. - -PushDownAction.Push_Down=Push &Down... -PushDownAction.To_activate=To activate this refactoring, please select the name of an instance method or field -PushDownAction.Refactoring=Refactoring -PushDownAction.not_possible=Operation not possible. - -MoveAction.Move=Move -MoveAction.select=Select a static method, a static field or an instance method that can be moved to a component (parameter or field). - -InlineAction.Inline=&Inline... -InlineAction.dialog_title=Inline -InlineAction.select=Select a method declaration, a method invocation, a static final field or a local variable that you want to inline. - -ExtractInterfaceAction.Extract_Interface=Ex&tract Interface... -ExtractInterfaceAction.To_activate=To activate this refactoring, please select the name of a top level class. -ExtractInterfaceAction.Refactoring=Refactoring -ExtractInterfaceAction.not_possible=Operation not possible. - -ConvertNestedToTopAction.Convert=Move M&ember Type to New File... -ConvertNestedToTopAction.To_activate=To activate this refactoring, please select the name of a nested type. -ConvertNestedToTopAction.Refactoring=Refactoring -ConvertNestedToTopAction.not_possible=Operation not possible. - -ConvertAnonymousToNestedAction.dialog_title=Convert Anonymous Class to Nested Class -ConvertAnonymousToNestedAction.Convert_Anonymous=Convert &Anonymous Class to Nested... -ConvertAnonymousToNestedAction.wizard_title=Convert Anonymous Class to Nested Class - -###################### Temporary Participant Keys ################################# -RenameResourceWizard.defaultPageTitle=Rename Resource -RenameResourceWizard.inputPage.description=Enter the new name for this resource. - -RenameCProject.defaultPageTitle=Rename C Project -RenameCProject.inputPage.description=Enter the new name for this C project. - -RenameSourceFolder.defaultPageTitle=Rename Source Folder -RenameSourceFolder.nputPage.description=Enter the new name for this source folder. - -RenamePackageWizard.defaultPageTitle=Rename Package -RenamePackageWizard.inputPage.description=Enter the new name for this package. - -RenameCuWizard.defaultPageTitle= Rename Translation Unit -RenameCuWizard.inputPage.description= Enter the new name for this translation unit. - -RenameTypeWizard.defaultPageTitle= Rename Element -RenameTypeWizard.inputPage.description= Enter the new name for this element. - -RenameMethodWizard.defaultPageTitle=Rename Method -RenameMethodWizard.inputPage.description= Enter the new name for this method. - -ExtractInterfaceWizard.12=Declare interface methods as ''{0}'' - -ParameterEditDialog.9=''{0}'' is not a valid parameter type name - -UseSupertypeWizard.10=No updates are possible for any of the supertypes - -DeleteWizard.1=Confirm Delete -DeleteWizard.2=Internal error. See log for details. -DeleteWizard.3=Are you sure you want to delete linked resource ''{0}''?\nOnly the workspace link will be deleted. Link target will remain unchanged. -DeleteWizard.4=Are you sure you want to delete {0}? -DeleteWizard.5=Are you sure you want to delete linked resource ''{0}''?\nOnly the workspace link will be deleted. Link target will remain unchanged. -DeleteWizard.6=Are you sure you want to delete linked resource ''{0}''?\nOnly the workspace link will be deleted. Link target will remain unchanged.\n\nNote that all subelements of the selected linked packages and package fragment roots will be removed from the workspace as well. -DeleteWizard.7=Are you sure you want to delete linked resource ''{0}''?\nOnly the workspace link will be deleted. Link target will remain unchanged. -DeleteWizard.8=Are you sure you want to delete {0}? -DeleteWizard.9=Are you sure you want to delete these {0} elements? -DeleteWizard.10=Are you sure you want to delete these {0} elements?\n\nSelection contains linked resources.\nOnly the workspace links will be deleted. Link targets will remain unchanged. -DeleteWizard.11=Are you sure you want to delete these {0} elements?\n\nSelection contains linked packages.\nOnly the workspace links will be deleted. Link targets will remain unchanged.\n\nNote that all subelements of linked packages and package fragment roots will be removed from the workspace as well. -DeleteWizard.12=The selected element(s) do not exist anymore and cannot be deleted. - - -####################################### -# IntroduceParameter -####################################### -IntroduceParameterAction.label=Introduce &Parameter... -IntroduceParameterAction.dialog_title=Introduce Parameter - -IntroduceParameterWizard.defaultPageTitle=Introduce Parameter -IntroduceParameterInputPage.description=Enter the name for the new parameter. -IntroduceParameterInputPage.parameter_name=Parameter Name: - -####################################### -# Introduce Factory -####################################### -IntroduceFactoryAction.label=Introduce &Factory... -IntroduceFactoryAction.dialog_title=Introduce Factory -IntroduceFactoryAction.tooltipText=Introduce a factory to encapsulate object instantiation -IntroduceFactoryAction.description=Creates a factory to encapsulate calls to the selected constructor -IntroduceFactoryAction.use_factory=Introduce Factory -IntroduceFactoryAction.exception=Unknown exception occurred during attempt to Introduce Factory -IntroduceFactoryInputPage.name_factory=Factory options -IntroduceFactoryInputPage.method_name=Factory method name: -IntroduceFactoryInputPage.protectConstructorLabel=Make constructor private - -####################################### -# Generalize Type -####################################### -ChangeTypeAction.label=Generalize Type... -ChangeTypeAction.tooltipText=Generalize variable\'s declared type -ChangeTypeAction.description=Change variable\'s declared type to more general type consistent with usage -ChangeTypeAction.exception=An internal error occurred while attempting to Generalize Type. - -ChangeTypeWizard.title=Generalize Type -ChangeTypeWizard.declCannotBeChanged=Type of selected declaration cannot be changed -ChangeTypeWizard.pleaseChooseType= &Choose new type (types shown in gray cannot be selected): -ChangeTypeWizard.analyzing=Analyzing... -ChangeTypeWizard.internalError=Internal error during computation of valid types -ChangeTypeWizard.computationInterrupted=Computation of valid types was interrupted -ChangeTypeWizard.grayed_types= Type ''{0}'' cannot be used as a replacement for type ''{1}'' -ChangeTypeWizard.with_itself= Cannot replace type ''{0}'' with itself -ChangeTypeInputPage.Select_Type=Press "Compute" to determine allowable supertypes - -UserInterfaceStarter.No_ui_found=No user interface found diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/corext/Assert.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/corext/Assert.java deleted file mode 100644 index c6dff112bdd..00000000000 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/corext/Assert.java +++ /dev/null @@ -1,145 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.corext; - -import org.eclipse.cdt.internal.corext.refactoring.RefactoringCoreMessages; - -/** - * Assert is useful for for embedding runtime sanity checks - * in code. The static predicate methods all test a condition and throw some - * type of unchecked exception if the condition does not hold. - *

      - * Assertion failure exceptions, like most runtime exceptions, are - * thrown when something is misbehaving. Assertion failures are invariably - * unspecified behavior; consequently, clients should never rely on - * these being thrown (or not thrown). If you find yourself in the - * position where you need to catch an assertion failure, you have most - * certainly written your program incorrectly. - *

      - *

      - * Note that an assert statement is slated to be added to the - * Java language in JDK 1.4, rending this class obsolete. - *

      - */ -public final class Assert { - - /** - * AssertionFailedException is a runtime exception thrown - * by some of the methods in Assert. - *

      - * This class is not declared public to prevent some misuses; programs that catch - * or otherwise depend on assertion failures are susceptible to unexpected - * breakage when assertions in the code are added or removed. - *

      - */ - private static class AssertionFailedException extends RuntimeException { - - /** - * Comment for serialVersionUID - */ - private static final long serialVersionUID = 1L; - - /** - * Constructs a new exception. - */ - public AssertionFailedException() { - } - - /** - * Constructs a new exception with the given message. - */ - public AssertionFailedException(String detail) { - super(detail); - } - } - - /* This class is not intended to be instantiated. */ - private Assert() { - } - - /** - * Asserts that the given object is not null. If this - * is not the case, some kind of unchecked exception is thrown. - *

      - * As a general rule, parameters passed to API methods must not be - * null unless explicitly allowed in the method's - * specification. Similarly, results returned from API methods are never - * null unless explicitly allowed in the method's - * specification. Implementations are encouraged to make regular use of - * Assert.isNotNull to ensure that null - * parameters are detected as early as possible. - *

      - * - * @param object the value to test - */ - public static void isNotNull(Object object) { - // succeed as quickly as possible - if (object != null) { - return; - } - isNotNull(object, ""); //$NON-NLS-1$ - } - - /** - * Asserts that the given object is not null. If this - * is not the case, some kind of unchecked exception is thrown. - * The given message is included in that exception, to aid debugging. - *

      - * As a general rule, parameters passed to API methods must not be - * null unless explicitly allowed in the method's - * specification. Similarly, results returned from API methods are never - * null unless explicitly allowed in the method's - * specification. Implementations are encouraged to make regular use of - * Assert.isNotNull to ensure that null - * parameters are detected as early as possible. - *

      - * - * @param object the value to test - * @param message the message to include in the exception - */ - public static void isNotNull(Object object, String message) { - if (object == null) - throw new AssertionFailedException(RefactoringCoreMessages.getString("Assert.null_argument") + message); //$NON-NLS-1$ - } - - /** - * Asserts that the given boolean is true. If this - * is not the case, some kind of unchecked exception is thrown. - * - * @param expression the outcome of the check - * @return true if the check passes (does not return - * if the check fails) - */ - public static boolean isTrue(boolean expression) { - // succeed as quickly as possible - if (expression) { - return true; - } - return isTrue(expression, ""); //$NON-NLS-1$ - } - - /** - * Asserts that the given boolean is true. If this - * is not the case, some kind of unchecked exception is thrown. - * The given message is included in that exception, to aid debugging. - * - * @param expression the outcome of the check - * @param message the message to include in the exception - * @return true if the check passes (does not return - * if the check fails) - */ - public static boolean isTrue(boolean expression, String message) { - if (!expression) - throw new AssertionFailedException(RefactoringCoreMessages.getString("Assert.assertion_failed") + message); //$NON-NLS-1$ - return expression; - } - -} diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/corext/textmanipulation/GroupDescription.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/corext/textmanipulation/GroupDescription.java index 8b7e89fc521..ebf724315a8 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/corext/textmanipulation/GroupDescription.java +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/corext/textmanipulation/GroupDescription.java @@ -14,10 +14,9 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import org.eclipse.core.runtime.Assert; import org.eclipse.jface.text.IRegion; - import org.eclipse.text.edits.TextEdit; -import org.eclipse.cdt.internal.corext.Assert; public class GroupDescription { diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/corext/util/CodeFormatterUtil.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/corext/util/CodeFormatterUtil.java index b974e080006..892ba0bcff5 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/corext/util/CodeFormatterUtil.java +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/corext/util/CodeFormatterUtil.java @@ -14,8 +14,8 @@ import java.util.Map; import org.eclipse.cdt.core.ToolFactory; import org.eclipse.cdt.core.formatter.CodeFormatter; -import org.eclipse.cdt.internal.corext.Assert; import org.eclipse.cdt.ui.CUIPlugin; +import org.eclipse.core.runtime.Assert; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.BadPositionCategoryException; diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/cview/MainActionGroup.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/cview/MainActionGroup.java index 95bf90826e4..1f26b62c86e 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/cview/MainActionGroup.java +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/cview/MainActionGroup.java @@ -17,7 +17,6 @@ import org.eclipse.cdt.internal.ui.actions.SelectionConverter; import org.eclipse.cdt.internal.ui.editor.OpenIncludeAction; import org.eclipse.cdt.internal.ui.search.actions.SelectionSearchGroup; import org.eclipse.cdt.ui.actions.CustomFiltersActionGroup; -import org.eclipse.cdt.ui.actions.RefactoringActionGroup; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.IAdaptable; @@ -78,7 +77,6 @@ public class MainActionGroup extends CViewActionGroup { CustomFiltersActionGroup fCustomFiltersActionGroup; SelectionSearchGroup selectionSearchGroup; - RefactoringActionGroup refactoringActionGroup; private NewWizardMenu newWizardMenu; @@ -161,8 +159,6 @@ public class MainActionGroup extends CViewActionGroup { // toggleLinkingAction.setHoverImageDescriptor(getImageDescriptor("clcl16/synced.gif"));//$NON-NLS-1$ selectionSearchGroup = new SelectionSearchGroup(getCView().getSite()); - refactoringActionGroup = new RefactoringActionGroup(getCView().getSite(), null); - } /** @@ -177,8 +173,6 @@ public class MainActionGroup extends CViewActionGroup { if (resources.isEmpty()) { menu.add(new Separator(IContextMenuConstants.GROUP_REORGANIZE)); - refactoringActionGroup.fillContextMenu(menu); - menu.add(new Separator()); importAction.selectionChanged(resources); menu.add(importAction); exportAction.selectionChanged(resources); diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/dialogs/cpaths/SourceAttachmentBlock.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/dialogs/cpaths/SourceAttachmentBlock.java index 4239eeec8af..eeb7fd8d59b 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/dialogs/cpaths/SourceAttachmentBlock.java +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/dialogs/cpaths/SourceAttachmentBlock.java @@ -20,7 +20,6 @@ import org.eclipse.cdt.core.model.CoreModel; import org.eclipse.cdt.core.model.ICProject; import org.eclipse.cdt.core.model.ILibraryEntry; import org.eclipse.cdt.core.model.IPathEntry; -import org.eclipse.cdt.internal.corext.Assert; import org.eclipse.cdt.internal.ui.dialogs.IStatusChangeListener; import org.eclipse.cdt.internal.ui.dialogs.StatusInfo; import org.eclipse.cdt.internal.ui.dialogs.StatusUtil; @@ -38,6 +37,7 @@ import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.ResourcesPlugin; +import org.eclipse.core.runtime.Assert; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/editor/AddIncludeOnSelectionAction.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/editor/AddIncludeOnSelectionAction.java index 9200567fe7b..320ba233c42 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/editor/AddIncludeOnSelectionAction.java +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/editor/AddIncludeOnSelectionAction.java @@ -13,40 +13,19 @@ package org.eclipse.cdt.internal.ui.editor; import java.lang.reflect.InvocationTargetException; -import java.util.ArrayList; -import java.util.List; -import java.util.Set; -import org.eclipse.cdt.core.browser.AllTypesCache; -import org.eclipse.cdt.core.browser.ITypeInfo; -import org.eclipse.cdt.core.browser.ITypeReference; -import org.eclipse.cdt.core.browser.ITypeSearchScope; -import org.eclipse.cdt.core.browser.QualifiedTypeName; -import org.eclipse.cdt.core.browser.TypeSearchScope; -import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.cdt.core.model.ICProject; import org.eclipse.cdt.core.model.ITranslationUnit; -import org.eclipse.cdt.core.search.BasicSearchResultCollector; -import org.eclipse.cdt.core.search.ICSearchConstants; -import org.eclipse.cdt.core.search.ICSearchScope; -import org.eclipse.cdt.core.search.IMatch; -import org.eclipse.cdt.core.search.OrPattern; -import org.eclipse.cdt.core.search.SearchEngine; import org.eclipse.cdt.internal.ui.CHelpProviderManager; import org.eclipse.cdt.internal.ui.ICHelpContextIds; import org.eclipse.cdt.internal.ui.actions.WorkbenchRunnableAdapter; import org.eclipse.cdt.internal.ui.codemanipulation.AddIncludesOperation; import org.eclipse.cdt.internal.ui.text.CWordFinder; import org.eclipse.cdt.internal.ui.util.ExceptionHandler; -import org.eclipse.cdt.ui.CSearchResultLabelProvider; import org.eclipse.cdt.ui.CUIPlugin; import org.eclipse.cdt.ui.IFunctionSummary; import org.eclipse.cdt.ui.IRequiredInclude; -import org.eclipse.cdt.ui.browser.typeinfo.TypeInfoLabelProvider; import org.eclipse.cdt.ui.text.ICHelpInvocationContext; -import org.eclipse.cdt.utils.PathUtil; import org.eclipse.core.resources.IProject; -import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jface.action.Action; import org.eclipse.jface.dialogs.MessageDialog; @@ -56,15 +35,13 @@ import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITextSelection; import org.eclipse.jface.viewers.ISelection; -import org.eclipse.jface.window.Window; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.PlatformUI; -import org.eclipse.ui.dialogs.ElementListSelectionDialog; import org.eclipse.ui.texteditor.ITextEditor; import org.eclipse.ui.texteditor.IUpdate; - +// TODO this is a big TODO. public class AddIncludeOnSelectionAction extends Action implements IUpdate { private ITextEditor fEditor; @@ -189,18 +166,10 @@ public class AddIncludeOnSelectionAction extends Action implements IUpdate { // Try the type caching. if (fRequiredIncludes == null && fUsings == null) { - ITypeInfo[] typeInfos= findTypeInfos(name); - if (typeInfos != null && typeInfos.length > 0) { - selectResult(typeInfos, name, getShell()); - } } // Do a full search if (fRequiredIncludes == null && fUsings == null) { - IMatch[] matches = findMatches(name); - if (matches != null && matches.length > 0) { - selectResult(matches, name, getShell()); - } } } catch (BadLocationException e) { MessageDialog.openError(getShell(), CEditorMessages.getString("AddIncludeOnSelection.error.message3"), CEditorMessages.getString("AddIncludeOnSelection.error.message4") + e.getMessage()); //$NON-NLS-2$ //$NON-NLS-1$ @@ -240,223 +209,6 @@ public class AddIncludeOnSelectionAction extends Action implements IUpdate { return fs[0]; } - /** - * Finds a type by the simple name. - */ - private ITypeInfo[] findTypeInfos(final String name) { - final ITypeInfo[][] infos = new ITypeInfo[1][]; - IRunnableWithProgress op = new IRunnableWithProgress() { - public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { - ITranslationUnit unit = getTranslationUnit(); - int[] types= {ICElement.C_CLASS, ICElement.C_UNION, ICElement.C_STRUCT, ICElement.C_ENUMERATION, ICElement.C_TYPEDEF}; - ITypeSearchScope scope = new TypeSearchScope(); - scope.add(unit.getCProject().getProject()); - if (!AllTypesCache.isCacheUpToDate(scope)) { - AllTypesCache.updateCache(scope, monitor); - } - ITypeInfo[] results = null; - if (!monitor.isCanceled()) { - results = AllTypesCache.getTypes(scope, new QualifiedTypeName(name), types, true); - if (!monitor.isCanceled()) { - for (int i = 0; i < results.length; ++i) { - ITypeInfo info = results[i]; - AllTypesCache.resolveTypeLocation(info, monitor); - if (monitor.isCanceled()) - break; - } - } - } - infos[0] = results; - } - }; - try { - PlatformUI.getWorkbench().getProgressService().busyCursorWhile(op); - } catch (InvocationTargetException e) { - ExceptionHandler.handle(e, getShell(), CEditorMessages.getString("AddIncludeOnSelection.error.message1"), null); //$NON-NLS-1$ - } catch (InterruptedException e) { - // Do nothing. Operation has been canceled. - } - return infos[0]; - } - - private IMatch[] findMatches(final String name) { - final BasicSearchResultCollector searchResultCollector = new BasicSearchResultCollector(); - IRunnableWithProgress op = new IRunnableWithProgress() { - public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { - ICProject cproject = getTranslationUnit().getCProject(); - ICSearchScope scope = SearchEngine.createCSearchScope(new ICElement[]{cproject}, true); - OrPattern orPattern = new OrPattern(); - orPattern.addPattern(SearchEngine.createSearchPattern( - name, ICSearchConstants.TYPE, ICSearchConstants.DECLARATIONS, false)); - orPattern.addPattern(SearchEngine.createSearchPattern( - name, ICSearchConstants.TYPE, ICSearchConstants.DEFINITIONS, false)); - orPattern.addPattern(SearchEngine.createSearchPattern( - name, ICSearchConstants.ENUM, ICSearchConstants.DECLARATIONS, false)); - orPattern.addPattern(SearchEngine.createSearchPattern( - name, ICSearchConstants.MACRO, ICSearchConstants.DECLARATIONS, false)); - orPattern.addPattern(SearchEngine.createSearchPattern( - name, ICSearchConstants.VAR, ICSearchConstants.DECLARATIONS, false)); - orPattern.addPattern(SearchEngine.createSearchPattern( - name, ICSearchConstants.FUNCTION, ICSearchConstants.DECLARATIONS, false)); - - SearchEngine searchEngine = new SearchEngine(); - searchEngine.setWaitingPolicy(ICSearchConstants.FORCE_IMMEDIATE_SEARCH); - searchEngine.search(CUIPlugin.getWorkspace(), orPattern, scope, searchResultCollector, true); - } - }; - try { - PlatformUI.getWorkbench().getProgressService().busyCursorWhile(op); - } catch (InvocationTargetException e) { - ExceptionHandler.handle(e, getShell(), CEditorMessages.getString("AddIncludeOnSelection.error.message1"), null); //$NON-NLS-1$ - } catch (InterruptedException e) { - // Do nothing. Operation has been canceled. - } - - Set set = searchResultCollector.getSearchResults(); - if (set != null) { - IMatch[] matches = new IMatch[set.size()]; - set.toArray(matches); - return matches; - } - return null; - } - - private void selectResult(ITypeInfo[] results, String name, Shell shell) { - int nResults= results.length; - ITranslationUnit unit = getTranslationUnit(); - if (nResults == 0) { - return; // bail out - } - - int occurences = 0; - int index = 0; - for (int i = 0; i < results.length; i++) { - if (name.equals(results[i].getName())) { - occurences++; - index = i; - } - } - - // if only one - if (occurences == 1 || results.length == 1) { - ITypeInfo curr= results[index]; - IRequiredInclude include = getRequiredInclude(curr, unit); - if (include != null) { - fRequiredIncludes = new IRequiredInclude[] { include }; - } - if (curr.hasEnclosedTypes()) { - ITypeInfo[] ns = curr.getEnclosedTypes(); - fUsings = new String[ns.length]; - for (int j = 0; j < fUsings.length; j++) { - fUsings[j] = ns[j].getName(); - } - } - return; - } - - ElementListSelectionDialog dialog= new ElementListSelectionDialog(getShell(), new TypeInfoLabelProvider(TypeInfoLabelProvider.SHOW_TYPE_ONLY)); - dialog.setElements(results); - dialog.setTitle(CEditorMessages.getString("AddIncludeOnSelection.label")); //$NON-NLS-1$ - dialog.setMessage(CEditorMessages.getString("AddIncludeOnSelection.description")); //$NON-NLS-1$ - if (dialog.open() == Window.OK) { - ITypeInfo[] selects = (ITypeInfo[])dialog.getResult(); - fRequiredIncludes = new IRequiredInclude[selects.length]; - List usings = new ArrayList(selects.length); - for (int i = 0; i < fRequiredIncludes.length; i++) { - IRequiredInclude include = getRequiredInclude(selects[i], unit); - if (include != null) { - fRequiredIncludes[i] = include; - if (selects[i].hasEnclosedTypes()) { - ITypeInfo[] ns = results[0].getEnclosedTypes(); - for (int j = 0; j < ns.length; j++) { - usings.add(ns[j].getName()); - } - } - } else { - fRequiredIncludes[i] = new RequiredIncludes(""); //$NON-NLS-1$ - } - } - if (!usings.isEmpty()) { - fUsings = new String[usings.size()]; - usings.toArray(fUsings); - } - } - } - - private IRequiredInclude getRequiredInclude(ITypeInfo curr, ITranslationUnit tu) { - ITypeReference ref = curr.getResolvedReference(); - if (ref != null) { - IPath typeLocation = ref.getLocation(); - IProject project = tu.getCProject().getProject(); - IPath projectLocation = project.getLocation(); - IPath headerLocation = tu.getResource().getLocation(); - boolean isSystemIncludePath = false; - - IPath includePath = PathUtil.makeRelativePathToProjectIncludes(typeLocation, project); - if (includePath != null && !projectLocation.isPrefixOf(typeLocation)) { - isSystemIncludePath = true; - } else if (projectLocation.isPrefixOf(typeLocation) - && projectLocation.isPrefixOf(headerLocation)) { - includePath = PathUtil.makeRelativePath(typeLocation, headerLocation.removeLastSegments(1)); - } - if (includePath == null) - includePath = typeLocation; - return new RequiredIncludes(includePath.toString(), isSystemIncludePath); - } - return null; - } - - private void selectResult(IMatch[] results, String name, Shell shell) { - int nResults = results.length; - if (nResults == 0) { - return; - } - - int occurences = 0; - int index = 0; - for (int i= 0; i < results.length; i++) { - IMatch curr= results[i]; - if (curr.getName().startsWith(name)) { - occurences++; - index = i; - } - } - - // if only one - if (occurences == 1 || results.length == 1) { - IMatch curr = results[index]; - fRequiredIncludes = new IRequiredInclude[1]; - fRequiredIncludes[0] = new RequiredIncludes(curr.getLocation().lastSegment()); - String parentName = curr.getParentName(); - if (parentName != null && parentName.length() > 0) { - fUsings = new String[] {parentName}; - } - return; - } - - // Make them choose - ElementListSelectionDialog dialog= new ElementListSelectionDialog(getShell(), new CSearchResultLabelProvider(null)); - dialog.setElements(results); - dialog.setTitle(CEditorMessages.getString("AddIncludeOnSelection.label")); //$NON-NLS-1$ - dialog.setMessage(CEditorMessages.getString("AddIncludeOnSelection.description")); //$NON-NLS-1$ - if (dialog.open() == Window.OK) { - IMatch[] selects = (IMatch[])dialog.getResult(); - fRequiredIncludes = new IRequiredInclude[selects.length]; - List usings = new ArrayList(selects.length); - for (int i = 0; i < fRequiredIncludes.length; i++) { - fRequiredIncludes[i] = new RequiredIncludes(selects[i].getLocation().lastSegment()); - String parentName = selects[i].getParentName(); - if (parentName != null && parentName.length() > 0) { - usings.add(parentName); - } - } - if (!usings.isEmpty()) { - fUsings = new String [usings.size()]; - usings.toArray(fUsings); - } - } - } - public void setContentEditor(ITextEditor editor) { fEditor= editor; } diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/editor/CContentOutlinePage.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/editor/CContentOutlinePage.java index 5955561abac..a7133ba02d4 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/editor/CContentOutlinePage.java +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/editor/CContentOutlinePage.java @@ -35,7 +35,6 @@ import org.eclipse.cdt.ui.PreferenceConstants; import org.eclipse.cdt.ui.actions.CustomFiltersActionGroup; import org.eclipse.cdt.ui.actions.MemberFilterActionGroup; import org.eclipse.cdt.ui.actions.OpenViewActionGroup; -import org.eclipse.cdt.ui.actions.RefactoringActionGroup; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IMenuListener; import org.eclipse.jface.action.IMenuManager; @@ -84,7 +83,6 @@ public class CContentOutlinePage extends Page implements IContentOutlinePage, IS private MemberFilterActionGroup fMemberFilterActionGroup; private ActionGroup fSelectionSearchGroup; - private ActionGroup fRefactoringActionGroup; private ActionGroup fOpenViewActionGroup; /** * Custom filter action group. @@ -245,8 +243,6 @@ public class CContentOutlinePage extends Page implements IContentOutlinePage, IS fSelectionSearchGroup.fillContextMenu(menu); menu.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS)); } - - fRefactoringActionGroup.fillContextMenu(menu); } protected CContentOutlinerProvider createContentProvider(TreeViewer viewer) { @@ -300,7 +296,6 @@ public class CContentOutlinePage extends Page implements IContentOutlinePage, IS bars.setGlobalActionHandler(ITextEditorActionDefinitionIds.TOGGLE_SHOW_SELECTED_ELEMENT_ONLY, fTogglePresentation); fSelectionSearchGroup = new SelectionSearchGroup(this); - fRefactoringActionGroup = new RefactoringActionGroup(this, null); fOpenViewActionGroup = new OpenViewActionGroup(this); // Custom filter group fCustomFiltersActionGroup= new CustomFiltersActionGroup("org.eclipse.cdt.ui.COutlinePage", getTreeViewer()); //$NON-NLS-1$ @@ -327,10 +322,6 @@ public class CContentOutlinePage extends Page implements IContentOutlinePage, IS fMemberFilterActionGroup= null; } - if (fRefactoringActionGroup != null) { - fRefactoringActionGroup.dispose(); - fRefactoringActionGroup= null; - } if (fOpenViewActionGroup != null) { fOpenViewActionGroup.dispose(); fOpenViewActionGroup= null; diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/editor/CEditor.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/editor/CEditor.java index b39561fdb16..6aa710a1d85 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/editor/CEditor.java +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/editor/CEditor.java @@ -31,7 +31,6 @@ import org.eclipse.cdt.internal.ui.actions.FoldingActionGroup; import org.eclipse.cdt.internal.ui.actions.GoToNextPreviousMemberAction; import org.eclipse.cdt.internal.ui.actions.JoinLinesAction; import org.eclipse.cdt.internal.ui.actions.RemoveBlockCommentAction; -import org.eclipse.cdt.internal.ui.browser.typehierarchy.OpenTypeHierarchyAction; import org.eclipse.cdt.internal.ui.search.actions.OpenDeclarationsAction; import org.eclipse.cdt.internal.ui.search.actions.OpenDefinitionAction; import org.eclipse.cdt.internal.ui.search.actions.SelectionSearchGroup; @@ -43,7 +42,6 @@ import org.eclipse.cdt.internal.ui.util.CUIHelp; import org.eclipse.cdt.ui.CUIPlugin; import org.eclipse.cdt.ui.IWorkingCopyManager; import org.eclipse.cdt.ui.PreferenceConstants; -import org.eclipse.cdt.ui.actions.RefactoringActionGroup; import org.eclipse.cdt.ui.actions.ShowInCViewAction; import org.eclipse.cdt.ui.text.folding.ICFoldingStructureProvider; import org.eclipse.core.resources.IFile; @@ -153,8 +151,6 @@ public class CEditor extends TextEditor implements ISelectionChangedListener, IS /** Search actions **/ private ActionGroup fSelectionSearchGroup; - /** Groups refactoring actions. */ - private ActionGroup fRefactoringActionGroup; /** Action which shows selected element in CView. */ private ShowInCViewAction fShowInCViewAction; @@ -573,7 +569,6 @@ public class CEditor extends TextEditor implements ISelectionChangedListener, IS fCEditorErrorTickUpdater = null; } - final CSourceViewer sourceViewer = (CSourceViewer) getSourceViewer(); if (fSelectionUpdateListener != null) { getSelectionProvider().addSelectionChangedListener(fSelectionUpdateListener); fSelectionUpdateListener = null; @@ -600,11 +595,6 @@ public class CEditor extends TextEditor implements ISelectionChangedListener, IS fShowInCViewAction = null; } - if (fRefactoringActionGroup != null) { - fRefactoringActionGroup.dispose(); - fRefactoringActionGroup = null; - } - if (fSelectionSearchGroup != null) { fSelectionSearchGroup.dispose(); fSelectionSearchGroup = null; @@ -744,7 +734,6 @@ public class CEditor extends TextEditor implements ISelectionChangedListener, IS //Assorted action groupings fSelectionSearchGroup = new SelectionSearchGroup(this); - fRefactoringActionGroup = new RefactoringActionGroup(this, null); } /** @@ -776,9 +765,7 @@ public class CEditor extends TextEditor implements ISelectionChangedListener, IS addAction(menu, IContextMenuConstants.GROUP_GENERATE, "ShowInCView"); //$NON-NLS-1$ - fRefactoringActionGroup.fillContextMenu(menu); fSelectionSearchGroup.fillContextMenu(menu); - } /** diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/editor/ExternalSearchDocumentProvider.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/editor/ExternalSearchDocumentProvider.java index b5652fde336..7bb85607486 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/editor/ExternalSearchDocumentProvider.java +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/editor/ExternalSearchDocumentProvider.java @@ -16,6 +16,7 @@ import org.eclipse.cdt.internal.ui.util.ExternalEditorInput; import org.eclipse.cdt.ui.CUIPlugin; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; +import org.eclipse.core.resources.IStorage; import org.eclipse.core.runtime.CoreException; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.source.IAnnotationModel; @@ -51,18 +52,11 @@ public class ExternalSearchDocumentProvider extends FileDocumentProvider { */ private IAnnotationModel createExternalSearchAnnotationModel(ExternalEditorInput externalInput) { - Object storage = externalInput.getStorage(); - ExternalSearchFile externalSearchFile = null; - if (storage instanceof ExternalSearchFile){ - externalSearchFile = (ExternalSearchFile) storage; - } - - if (externalSearchFile == null) - return null; + IStorage storage = externalInput.getStorage(); IProject projectToUseForMarker = null; - IFile resourceFile = CUIPlugin.getWorkspace().getRoot().getFileForLocation(externalSearchFile.searchMatch.getReferringElement()); + IFile resourceFile = CUIPlugin.getWorkspace().getRoot().getFileForLocation(storage.getFullPath()); if (resourceFile == null){ IProject[] proj = CUIPlugin.getWorkspace().getRoot().getProjects(); diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/editor/ExternalSearchFile.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/editor/ExternalSearchFile.java deleted file mode 100644 index 2847af1c223..00000000000 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/editor/ExternalSearchFile.java +++ /dev/null @@ -1,28 +0,0 @@ -/********************************************************************** - * Copyright (c) 2002, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.editor; - -import org.eclipse.cdt.core.resources.FileStorage; -import org.eclipse.cdt.core.search.BasicSearchMatch; -import org.eclipse.core.runtime.IPath; - -public class ExternalSearchFile extends FileStorage { - - IPath referringElement; - BasicSearchMatch searchMatch; - /** - * @param path - */ - public ExternalSearchFile(IPath path, BasicSearchMatch searchMatch) { - super(path); - this.searchMatch = searchMatch; - } -} diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/indexview/FindDeclarationsAction.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/indexview/FindDeclarationsAction.java index 01196951793..2d4e3237e53 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/indexview/FindDeclarationsAction.java +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/indexview/FindDeclarationsAction.java @@ -11,6 +11,8 @@ package org.eclipse.cdt.internal.ui.indexview; +import org.eclipse.cdt.core.model.ICElement; +import org.eclipse.cdt.core.model.ICProject; import org.eclipse.cdt.internal.core.pdom.dom.PDOMBinding; import org.eclipse.cdt.internal.ui.search.PDOMSearchBindingQuery; import org.eclipse.cdt.ui.CUIPlugin; @@ -39,7 +41,11 @@ public class FindDeclarationsAction extends IndexAction { } public void run() { - PDOMSearchBindingQuery query = new PDOMSearchBindingQuery(getBinding(), + PDOMBinding binding = getBinding(); + ICProject project = binding.getPDOM().getProject(); + PDOMSearchBindingQuery query = new PDOMSearchBindingQuery( + new ICElement[] { project }, + getBinding(), PDOMSearchBindingQuery.FIND_DECLARATIONS | PDOMSearchBindingQuery.FIND_DEFINITIONS); NewSearchUI.activateSearchResultView(); diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/indexview/FindReferencesAction.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/indexview/FindReferencesAction.java index 9a0f1a8dbef..d8ecd501b53 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/indexview/FindReferencesAction.java +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/indexview/FindReferencesAction.java @@ -11,6 +11,8 @@ package org.eclipse.cdt.internal.ui.indexview; +import org.eclipse.cdt.core.model.ICElement; +import org.eclipse.cdt.core.model.ICProject; import org.eclipse.cdt.internal.core.pdom.dom.PDOMBinding; import org.eclipse.cdt.internal.ui.search.PDOMSearchBindingQuery; import org.eclipse.cdt.ui.CUIPlugin; @@ -39,7 +41,12 @@ public class FindReferencesAction extends IndexAction { } public void run() { - PDOMSearchBindingQuery query = new PDOMSearchBindingQuery(getBinding(), PDOMSearchBindingQuery.FIND_REFERENCES); + PDOMBinding binding = getBinding(); + ICProject project = binding.getPDOM().getProject(); + PDOMSearchBindingQuery query = new PDOMSearchBindingQuery( + new ICElement[] { project }, + getBinding(), + PDOMSearchBindingQuery.FIND_REFERENCES); NewSearchUI.activateSearchResultView(); diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/CSearchContentProvider.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/CSearchContentProvider.java deleted file mode 100644 index 2311f4fcc49..00000000000 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/CSearchContentProvider.java +++ /dev/null @@ -1,40 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corp. - Rational Software - initial implementation - *******************************************************************************/ - -package org.eclipse.cdt.internal.ui.search; - -import org.eclipse.jface.viewers.IStructuredContentProvider; -import org.eclipse.jface.viewers.Viewer; - -public abstract class CSearchContentProvider implements IStructuredContentProvider { - protected CSearchResult _result; - protected final Object[] EMPTY_ARR= new Object[0]; - - public Object[] getElements(Object inputElement) { - // TODO Auto-generated method stub - return null; - } - - public void dispose() { - // TODO Auto-generated method stub - } - - public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { - initialize((CSearchResult) newInput); - } - - protected void initialize(CSearchResult result) { - _result= result; - } - - public abstract void elementsChanged(Object[] updatedElements); - public abstract void clear(); -} diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/CSearchMatch.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/CSearchMatch.java deleted file mode 100644 index 6f32c3f4357..00000000000 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/CSearchMatch.java +++ /dev/null @@ -1,49 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005 QNX Software Systems and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * QNX Software Systems - initial API and implementation - *******************************************************************************/ -/* - * Created on Jun 27, 2004 - * - * TODO To change the template for this generated file go to - * Window - Preferences - Java - Code Style - Code Templates - */ -package org.eclipse.cdt.internal.ui.search; - -import org.eclipse.cdt.core.search.BasicSearchMatch; -import org.eclipse.cdt.core.search.IMatch; -import org.eclipse.search.ui.text.Match; - -/** - * @author bgheorgh - * - * TODO To change the template for this generated type comment go to - * Window - Preferences - Java - Code Style - Code Templates - */ -public class CSearchMatch extends Match { - - private BasicSearchMatch searchMatch; - /** - * @param element - * @param offset - * @param length - */ - public CSearchMatch(Object element, int offset, int length, IMatch match) { - super(element, offset, length); - if (match instanceof BasicSearchMatch) - searchMatch = (BasicSearchMatch)match; - } - - /** - * @return Returns the searchMatch. - */ - public BasicSearchMatch getSearchMatch() { - return searchMatch; - } -} diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/CSearchQuery.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/CSearchQuery.java deleted file mode 100644 index b27fab154c8..00000000000 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/CSearchQuery.java +++ /dev/null @@ -1,208 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corp. - Rational Software - initial implementation - *******************************************************************************/ -/* - * Created on Mar 26, 2004 - */ -package org.eclipse.cdt.internal.ui.search; - -import java.util.Iterator; -import java.util.List; - -import org.eclipse.cdt.core.search.ICSearchConstants; -import org.eclipse.cdt.core.search.ICSearchPattern; -import org.eclipse.cdt.core.search.ICSearchScope; -import org.eclipse.cdt.core.search.LimitTo; -import org.eclipse.cdt.core.search.OrPattern; -import org.eclipse.cdt.core.search.SearchEngine; -import org.eclipse.cdt.core.search.SearchFor; -import org.eclipse.cdt.internal.ui.CPluginImages; -import org.eclipse.cdt.ui.CUIPlugin; -import org.eclipse.core.resources.IWorkspace; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.Status; -import org.eclipse.core.runtime.SubProgressMonitor; -import org.eclipse.jface.resource.ImageDescriptor; -import org.eclipse.search.ui.ISearchQuery; -import org.eclipse.search.ui.ISearchResult; -/** - * @author bog - */ -public class CSearchQuery implements ISearchQuery, ICSearchConstants { - - private IWorkspace _workspace; - private ICSearchScope _scope; - private String _stringPattern; - private String _scopeDescription; - private boolean _caseSensitive; - private LimitTo _limitTo; - private List _searchFor; - private CSearchResult _result; - - public CSearchQuery(IWorkspace workspace, String pattern, boolean caseSensitive, List searchFor, LimitTo limitTo, ICSearchScope scope, String scopeDescription) { - this( workspace, limitTo, scope, scopeDescription ); - _stringPattern = pattern; - _caseSensitive = caseSensitive; - _searchFor = searchFor; - } - - public CSearchQuery(IWorkspace workspace, LimitTo limitTo, ICSearchScope scope, String scopeDescription){ - _workspace = workspace; - _limitTo = limitTo; - _scope = scope; - _scopeDescription = scopeDescription; - } - - /** - * @return - */ - public String getSingularLabel() { - String desc = null; - - //if( _elementPattern != null ){ - // desc = _elementPattern.getElementName(); - //} else { - desc = _stringPattern; - //} - - String [] args = new String [] { desc, _scopeDescription }; - - if( _limitTo == DECLARATIONS ){ - return CSearchMessages.getFormattedString( "CSearchOperation.singularDeclarationsPostfix", args ); //$NON_NLS-1$ //$NON-NLS-1$ - } else if( _limitTo == REFERENCES ){ - return CSearchMessages.getFormattedString( "CSearchOperation.singularReferencesPostfix", args ); //$NON_NLS-1$ //$NON-NLS-1$ - } else { - return CSearchMessages.getFormattedString( "CSearchOperation.singularOccurrencesPostfix", args ); //$NON_NLS-1$ //$NON-NLS-1$ - } - } - - /** - * @return - */ - public String getPluralLabelPattern() { - String desc = null; - - // if( _elementPattern != null ){ - // desc = _elementPattern.getElementName(); - // } else { - desc = _stringPattern; - // } - - String [] args = new String [] { desc, "{0}", _scopeDescription }; //$NON-NLS-1$ - if( _limitTo == DECLARATIONS ){ - return CSearchMessages.getFormattedString( "CSearchOperation.pluralDeclarationsPostfix", args ); //$NON_NLS-1$ //$NON-NLS-1$ - } else if ( _limitTo == REFERENCES ){ - return CSearchMessages.getFormattedString( "CSearchOperation.pluralReferencesPostfix", args ); //$NON_NLS-1$ //$NON-NLS-1$ - } else { - return CSearchMessages.getFormattedString( "CSearchOperation.pluralOccurrencesPostfix", args ); //$NON_NLS-1$ //$NON-NLS-1$ - } - } - - /** - * @return - */ - public ImageDescriptor getImageDescriptor() { - if( _limitTo == ICSearchConstants.DECLARATIONS ){ - return CPluginImages.DESC_OBJS_SEARCH_DECL; - } else { - return CPluginImages.DESC_OBJS_SEARCH_REF; - } - } - - /* (non-Javadoc) - * @see org.eclipse.search.ui.ISearchQuery#run(org.eclipse.core.runtime.IProgressMonitor) - */ - public IStatus run(IProgressMonitor monitor) { - - final CSearchResult textResult= (CSearchResult) getSearchResult(); - textResult.removeAll(); - - SearchEngine engine = new SearchEngine( CUIPlugin.getSharedWorkingCopies() ); - - int totalTicks= 1000; - - monitor.beginTask("", totalTicks); //$NON-NLS-1$ - IProgressMonitor mainSearchPM= new SubProgressMonitor(monitor, 1000); - - NewSearchResultCollector finalCollector= new NewSearchResultCollector(textResult, mainSearchPM); - - ICSearchPattern pattern = null; - if( _searchFor.size() > 0 ){ - if( _searchFor.size() > 1 ){ - OrPattern orPattern = new OrPattern(); - for (Iterator iter = _searchFor.iterator(); iter.hasNext();) { - SearchFor element = (SearchFor)iter.next(); - orPattern.addPattern( SearchEngine.createSearchPattern( _stringPattern, element, _limitTo, _caseSensitive ) ); - } - - pattern = orPattern; - - } else { - Iterator iter = _searchFor.iterator(); - pattern = SearchEngine.createSearchPattern( _stringPattern, (SearchFor)iter.next(), _limitTo, _caseSensitive ); - } - - try { - engine.search( _workspace, pattern, _scope, finalCollector, false ); - } catch (InterruptedException e) { - } - } - monitor.done(); - - return new Status(IStatus.OK, CUIPlugin.getPluginId(), 0,"", null); //$NON-NLS-1$ - } - - /* (non-Javadoc) - * @see org.eclipse.search.ui.ISearchQuery#getLabel() - */ - public String getLabel() { - String label; - if (_limitTo == REFERENCES) - label = CSearchMessages.getString("CSearchQuery.searchfor_references"); //$NON-NLS-1$ - else if (_limitTo == DECLARATIONS) - label = CSearchMessages.getString("CSearchQuery.searchfor_declarations"); //$NON-NLS-1$ - else if (_limitTo == DEFINITIONS) - label = CSearchMessages.getString("CSearchQuery.searchfor_definitions"); //$NON-NLS-1$ - else if (_limitTo == ALL_OCCURRENCES) - label = CSearchMessages.getString("CSearchQuery.searchfor_all"); //$NON-NLS-1$ - else - label = CSearchMessages.getString("CSearchQuery.search_label"); //$NON-NLS-1$; - - label += " \""; //$NON-NLS-1$ - label += _stringPattern; - label += '"'; - return label; - } - - /* (non-Javadoc) - * @see org.eclipse.search.ui.ISearchQuery#canRerun() - */ - public boolean canRerun() { - return true; - } - - /* (non-Javadoc) - * @see org.eclipse.search.ui.ISearchQuery#canRunInBackground() - */ - public boolean canRunInBackground() { - return true; - } - - /* (non-Javadoc) - * @see org.eclipse.search.ui.ISearchQuery#getSearchResult() - */ - public ISearchResult getSearchResult() { - if (_result == null) - _result= new CSearchResult(this); - return _result; - } - -} diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/CSearchResult.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/CSearchResult.java deleted file mode 100644 index d7d0bea8392..00000000000 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/CSearchResult.java +++ /dev/null @@ -1,297 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -/* - * Created on Mar 26, 2004 - * - * To change the template for this generated file go to - * Window - Preferences - Java - Code Generation - Code and Comments - */ -package org.eclipse.cdt.internal.ui.search; - -import java.text.MessageFormat; -import java.util.HashSet; -import java.util.Set; - -import org.eclipse.cdt.core.CCorePlugin; -import org.eclipse.cdt.core.model.CModelException; -import org.eclipse.cdt.core.model.CoreModel; -import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.cdt.core.model.ICProject; -import org.eclipse.cdt.core.model.IParent; -import org.eclipse.cdt.core.model.ITranslationUnit; -import org.eclipse.cdt.core.search.BasicSearchMatch; -import org.eclipse.cdt.internal.ui.util.ExternalEditorInput; -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IResource; -import org.eclipse.jface.resource.ImageDescriptor; -import org.eclipse.search.ui.ISearchQuery; -import org.eclipse.search.ui.text.AbstractTextSearchResult; -import org.eclipse.search.ui.text.IEditorMatchAdapter; -import org.eclipse.search.ui.text.IFileMatchAdapter; -import org.eclipse.search.ui.text.Match; -import org.eclipse.ui.IEditorInput; -import org.eclipse.ui.IEditorPart; -import org.eclipse.ui.IFileEditorInput; -/** - * @author bog - * - * To change the template for this generated type comment go to - * Window - Preferences - Java - Code Generation - Code and Comments - */ -public class CSearchResult extends AbstractTextSearchResult implements IEditorMatchAdapter, IFileMatchAdapter { - CSearchQuery cQuery; - private static final Match[] NO_MATCHES= new Match[0]; - - public CSearchResult(CSearchQuery query){ - cQuery = query; - } - - /* (non-Javadoc) - * @see org.eclipse.search.ui.text.AbstractTextSearchResult#findContainedMatches(org.eclipse.core.resources.IFile) - */ - public Match[] findContainedMatches(IFile file) { - ICElement cElement= create(file); - Set matches= new HashSet(); - collectMatches(matches, cElement); - return (Match[]) matches.toArray(new Match[matches.size()]); - } - - private ICElement create(IFile file){ - IProject project = file.getProject(); - ICProject cProject = CCorePlugin.getDefault().getCoreModel().create(project); - return cProject; - } - - private void collectMatches(Set matches, ICElement element) { - Match[] m= getMatches(element); - if (m.length != 0) { - for (int i= 0; i < m.length; i++) { - matches.add(m[i]); - } - } - if (element instanceof IParent) { - IParent parent= (IParent) element; - try { - ICElement[] children= parent.getChildren(); - for (int i= 0; i < children.length; i++) { - collectMatches(matches, children[i]); - } - } catch (CModelException e) { - // we will not be tracking these results - } - - } - } - /* (non-Javadoc) - * @see org.eclipse.search.ui.text.AbstractTextSearchResult#getFile(java.lang.Object) - */ - public IFile getFile(Object element) { - if (element instanceof ICElement) { - ICElement cElement= (ICElement) element; - element= cElement.getUnderlyingResource(); - } - if (element instanceof IFile) - return (IFile)element; - return null; - } - /* (non-Javadoc) - * @see org.eclipse.search.ui.text.AbstractTextSearchResult#isShownInEditor(org.eclipse.search.ui.text.Match, org.eclipse.ui.IEditorPart) - */ - public boolean isShownInEditor(Match match, IEditorPart editor) { - IEditorInput editorInput= editor.getEditorInput(); - if (match.getElement() instanceof BasicSearchMatch) { - BasicSearchMatch searchMatch = (BasicSearchMatch) match.getElement(); - if (editorInput instanceof IFileEditorInput){ - IFile inputFile= ((IFileEditorInput)editorInput).getFile(); - IResource matchFile = searchMatch.getResource(); - if (matchFile != null) - return inputFile.equals(matchFile); - else - return false; - } - } else if (match instanceof CSearchMatch) { - BasicSearchMatch searchMatch = ((CSearchMatch) match).getSearchMatch(); - if (editorInput instanceof IFileEditorInput){ - IFile inputFile= ((IFileEditorInput)editorInput).getFile(); - IResource matchFile = searchMatch.getResource(); - if (matchFile != null) - return inputFile.equals(matchFile); - else - return false; - } - else if (editorInput instanceof ExternalEditorInput){ - String externalPath = ((ExternalEditorInput) editorInput).getFullPath(); - String searchMatchPath = searchMatch.getLocation().toString(); - if (searchMatchPath != null) - return externalPath.equals(searchMatchPath); - else - return false; - - } - } else if (match.getElement() instanceof IFile) { - if (editorInput instanceof IFileEditorInput) { - return ((IFileEditorInput)editorInput).getFile().equals(match.getElement()); - } - } - return false; - } - /* (non-Javadoc) - * @see org.eclipse.search.ui.text.AbstractTextSearchResult#findContainedMatches(org.eclipse.ui.IEditorPart) - */ - public Match[] findContainedMatches(IEditorPart editor) { - IEditorInput editorInput= editor.getEditorInput(); - if (editorInput instanceof IFileEditorInput) { - IFileEditorInput fileEditorInput= (IFileEditorInput) editorInput; - return findContainedMatches(fileEditorInput.getFile()); - } - - return null; - } - /* (non-Javadoc) - * @see org.eclipse.search.ui.ISearchResult#getText() - */ - public String getText() { - int matchCount= getMatchCount(); - String format= null; - if (matchCount == 1) - format= cQuery.getSingularLabel(); - else - format= cQuery.getPluralLabelPattern(); - return MessageFormat.format(format, new Object[] { new Integer(matchCount) }); - } - /* (non-Javadoc) - * @see org.eclipse.search.ui.ISearchResult#getTooltip() - */ - public String getTooltip() { - // TODO Auto-generated method stub - return getText(); - } - /* (non-Javadoc) - * @see org.eclipse.search.ui.ISearchResult#getImageDescriptor() - */ - public ImageDescriptor getImageDescriptor() { - return cQuery.getImageDescriptor(); - } - /* (non-Javadoc) - * @see org.eclipse.search.ui.ISearchResult#getQuery() - */ - public ISearchQuery getQuery() { - return cQuery; - } - - /* (non-Javadoc) - * @see org.eclipse.search.ui.ISearchResult#getLabel() - */ - public String getLabel() { - int matches = getMatchCount(); - String label = null; - if (matches == 1) - return cQuery.getSingularLabel(); - else - label = cQuery.getPluralLabelPattern(); - - return MessageFormat.format(label, new Object[]{new Integer(matches)}); - } - - /* (non-Javadoc) - * @see org.eclipse.search.ui.text.AbstractTextSearchResult#getEditorMatchAdapter() - */ - public IEditorMatchAdapter getEditorMatchAdapter() { - // TODO Auto-generated method stub - return this; - } - - /* (non-Javadoc) - * @see org.eclipse.search.ui.text.AbstractTextSearchResult#getFileMatchAdapter() - */ - public IFileMatchAdapter getFileMatchAdapter() { - // TODO Auto-generated method stub - return this; - } - - /* (non-Javadoc) - * @see org.eclipse.search.ui.text.IEditorMatchAdapter#computeContainedMatches(org.eclipse.search.ui.text.AbstractTextSearchResult, org.eclipse.ui.IEditorPart) - */ - public Match[] computeContainedMatches(AbstractTextSearchResult result, IEditorPart editor) { - IEditorInput editorInput= editor.getEditorInput(); - if (editorInput instanceof IFileEditorInput) { - IFileEditorInput fileEditorInput= (IFileEditorInput) editorInput; - return computeContainedMatches(result, fileEditorInput.getFile()); - } - else if (editorInput instanceof ExternalEditorInput){ - ExternalEditorInput externalInput=(ExternalEditorInput) editorInput; - return computerContainedMatches(result,externalInput.getFullPath()); - } - return null; - } - - /** - * @param result - * @param fullPath - * @return - */ - private Match[] computerContainedMatches(AbstractTextSearchResult result, String fullPath) { - Set matches= new HashSet(); - Object[] test=result.getElements(); - collectMatches(matches, test, fullPath); - return (Match[]) matches.toArray(new Match[matches.size()]); - } - - /** - * @param matches - * @param test - * @param fullPath - */ - private void collectMatches(Set matches, Object[] test, String fullPath) { - for (int i=0; i 0){ - for (int i=0; i0 && tempendLine > tempstartLine){ - int endOffset; - try { - //See NOTE above - endOffset = doc.getLineOffset(tempendLine-1); - length = endOffset - startOffset; - } catch (BadLocationException e) {} - - } - } - textEditor.selectAndReveal(startOffset,length); - } - - //TODO: Put in once we have marker support for External Translation Units - /* //Get all the CProjects off the model - ICProject[] cprojects = CoreModel.getDefault().getCModel().getCProjects(); - - ICProject containingProject=null; - ICElement celem = null; - //Find the CProject that the element belongs to - for (int i=0; i 0) - originalFile = matches[0]; - } - return originalFile; - } - -} diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/CSearchScopeFactory.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/CSearchScopeFactory.java deleted file mode 100644 index f1754f8d1ed..00000000000 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/CSearchScopeFactory.java +++ /dev/null @@ -1,185 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2003, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corp. - Rational Software - initial implementation - *******************************************************************************/ -/* - * Created on Jun 12, 2003 - */ -package org.eclipse.cdt.internal.ui.search; - -import java.util.HashSet; -import java.util.Iterator; -import java.util.Set; - -import org.eclipse.cdt.core.CCorePlugin; -import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.cdt.core.model.ICProject; -import org.eclipse.cdt.core.search.BasicSearchMatch; -import org.eclipse.cdt.core.search.ICSearchScope; -import org.eclipse.cdt.core.search.SearchEngine; -import org.eclipse.cdt.ui.CUIPlugin; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.runtime.IAdaptable; -import org.eclipse.jface.viewers.IStructuredSelection; -import org.eclipse.jface.window.Window; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.ui.IWorkingSet; -import org.eclipse.ui.PlatformUI; -import org.eclipse.ui.dialogs.IWorkingSetSelectionDialog; - -/** - * @author aniefer - * - * To change the template for this generated type comment go to - * Window>Preferences>Java>Code Generation>Code and Comments - */ -public class CSearchScopeFactory { - private static CSearchScopeFactory fgInstance; - private static ICSearchScope EMPTY_SCOPE= SearchEngine.createCSearchScope(new ICElement[]{}); - /** - * - */ - public CSearchScopeFactory() { - super(); - } - - public static CSearchScopeFactory getInstance() { - if (fgInstance == null) - fgInstance = new CSearchScopeFactory(); - return fgInstance; - } - /** - * @param sets - * @return - */ - public ICSearchScope createCSearchScope(IWorkingSet[] sets) { - if (sets == null || sets.length < 1) - return EMPTY_SCOPE; - - Set cElements= new HashSet(sets.length * 10); - for (int i= 0; i < sets.length; i++) - addCElements(cElements, sets[i]); - return createCSearchScope(cElements); - } - /** - * @param cElements - * @return - */ - private ICSearchScope createCSearchScope(Set cElements) { - return SearchEngine.createCSearchScope((ICElement[])cElements.toArray(new ICElement[cElements.size()])); - } - /** - * @param cElements - * @param set - */ - private void addCElements(Set cElements, IWorkingSet set) { - if (set == null) - return; - - IAdaptable[] elements= set.getElements(); - for (int i= 0; i < elements.length; i++) { - if (elements[i] instanceof ICElement) - addCElements(cElements, (ICElement)elements[i]); - else - addCElements(cElements, elements[i]); - } - } - /** - * @param cElements - * @param adaptable - */ - private void addCElements(Set cElements, IAdaptable resource) { - ICElement cElement= (ICElement)resource.getAdapter(ICElement.class); - if (cElement == null) - // not an ICElement resource - return; - - addCElements(cElements, cElement); - } - /** - * @param cElements - * @param element - */ - private void addCElements(Set cElements, ICElement element) { - cElements.add(element); - } - - /** - * @param fStructuredSelection - * @return - */ - public ICSearchScope createCSearchScope(IStructuredSelection fStructuredSelection) { - Set cElements = new HashSet( fStructuredSelection.size() ); - - Iterator iter = fStructuredSelection.iterator(); - while( iter.hasNext() ){ - Object tempObj = iter.next(); - if ( tempObj instanceof ICElement){ - addCElements( cElements, (ICElement)tempObj ); - } - else if (tempObj instanceof BasicSearchMatch){ - addCElements( cElements, (BasicSearchMatch)tempObj ); - } - else if (tempObj instanceof IResource){ - addCElements(cElements, (IResource) tempObj); - } - } - - return createCSearchScope( cElements ); - } - - /** - * @param fStructuredSelection - * @return - */ - public ICSearchScope createEnclosingProjectScope(IStructuredSelection fStructuredSelection) { - Set cElements = new HashSet( fStructuredSelection.size() ); - - Iterator iter = fStructuredSelection.iterator(); - while( iter.hasNext() ){ - Object tempObj = iter.next(); - if ( tempObj instanceof ICElement){ - ICProject cproject = ((ICElement) tempObj).getCProject(); - if (cproject != null) - cElements.add(cproject); - } - - } - - return createCSearchScope( cElements ); - } - - - /** - * @param elements - * @param match - */ - private void addCElements(Set elements, BasicSearchMatch match) { - IResource tempResource=match.getResource(); - if (tempResource!=null ){ - ICElement cTransUnit = CCorePlugin.getDefault().getCoreModel().create(tempResource); - if (cTransUnit != null) - elements.add(cTransUnit); - } - } - - public IWorkingSet[] queryWorkingSets() { - Shell shell= CUIPlugin.getActiveWorkbenchShell(); - if (shell == null) - return null; - IWorkingSetSelectionDialog dialog= PlatformUI.getWorkbench().getWorkingSetManager().createWorkingSetSelectionDialog(shell, true); - if (dialog.open() == Window.OK) { - IWorkingSet[] workingSets= dialog.getSelection(); - if (workingSets.length > 0) - return workingSets; - } - return null; - } - -} diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/CSearchTableContentProvider.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/CSearchTableContentProvider.java deleted file mode 100644 index a3d7a3bedc8..00000000000 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/CSearchTableContentProvider.java +++ /dev/null @@ -1,53 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corp. - Rational Software - initial implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.search; - -import org.eclipse.jface.viewers.IStructuredContentProvider; -import org.eclipse.jface.viewers.TableViewer; - -public class CSearchTableContentProvider extends CSearchContentProvider implements IStructuredContentProvider { - - private TableViewer _tableViewer; - - public CSearchTableContentProvider(TableViewer viewer) { - _tableViewer= viewer; - } - public Object[] getElements(Object inputElement) { - if (inputElement instanceof CSearchResult) - return ((CSearchResult)inputElement).getElements(); - return EMPTY_ARR; - } - - public void elementsChanged(Object[] updatedElements) { - if (_result == null) - return; - - int addCount= 0; - int removeCount= 0; - for (int i= 0; i < updatedElements.length; i++) { - if (_result.getMatchCount(updatedElements[i]) > 0) { - if (_tableViewer.testFindItem(updatedElements[i]) != null) - _tableViewer.refresh(updatedElements[i]); - else - _tableViewer.add(updatedElements[i]); - addCount++; - } else { - _tableViewer.remove(updatedElements[i]); - removeCount++; - } - } - } - - public void clear() { - _tableViewer.refresh(); - } - -} diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/CSearchUtil.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/CSearchUtil.java index 104e546a351..402fc3bca01 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/CSearchUtil.java +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/CSearchUtil.java @@ -14,19 +14,6 @@ package org.eclipse.cdt.internal.ui.search; import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.cdt.core.parser.ast.ASTClassKind; -import org.eclipse.cdt.core.parser.ast.IASTClassSpecifier; -import org.eclipse.cdt.core.parser.ast.IASTEnumerationSpecifier; -import org.eclipse.cdt.core.parser.ast.IASTEnumerator; -import org.eclipse.cdt.core.parser.ast.IASTField; -import org.eclipse.cdt.core.parser.ast.IASTFunction; -import org.eclipse.cdt.core.parser.ast.IASTMethod; -import org.eclipse.cdt.core.parser.ast.IASTNamespaceDefinition; -import org.eclipse.cdt.core.parser.ast.IASTOffsetableNamedElement; -import org.eclipse.cdt.core.parser.ast.IASTTypedefDeclaration; -import org.eclipse.cdt.core.parser.ast.IASTVariable; -import org.eclipse.cdt.core.search.ICSearchConstants; -import org.eclipse.cdt.core.search.SearchFor; import org.eclipse.core.resources.IMarker; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.IWorkingSet; @@ -103,88 +90,4 @@ public class CSearchUtil { // TODO Auto-generated method stub return null; } - - static public SearchFor getSearchForFromElement( ICElement element ) { - if( element == null ) - return null; - - SearchFor searchFor = null; - //outline view will confuse methods with functions, so if the - //name contains a "::", treat it as a method - String pattern = element.getElementName(); - boolean forceMethod = ( pattern.indexOf("::") != -1 ); //$NON-NLS-1$ - - switch ( element.getElementType() ){ - case ICElement.C_TEMPLATE_FUNCTION: /*fall through to function */ - case ICElement.C_FUNCTION_DECLARATION: /*fall through to function */ - case ICElement.C_FUNCTION: if( forceMethod ) searchFor = ICSearchConstants.METHOD; - else searchFor = ICSearchConstants.FUNCTION; - break; - - case ICElement.C_VARIABLE: searchFor = ICSearchConstants.VAR; break; - - case ICElement.C_TEMPLATE_CLASS:/* fall through to CLASS */ - case ICElement.C_STRUCT: /* fall through to CLASS */ - case ICElement.C_CLASS: searchFor = ICSearchConstants.CLASS_STRUCT; break; - - case ICElement.C_UNION: searchFor = ICSearchConstants.UNION; break; - - case ICElement.C_ENUMERATOR: - searchFor = ICSearchConstants.ENUMTOR; break; - case ICElement.C_FIELD: searchFor = ICSearchConstants.FIELD; break; - - case ICElement.C_TEMPLATE_METHOD : /*fall through to METHOD */ - case ICElement.C_METHOD_DECLARATION : /*fall through to METHOD */ - case ICElement.C_METHOD: searchFor = ICSearchConstants.METHOD; break; - - case ICElement.C_NAMESPACE: searchFor = ICSearchConstants.NAMESPACE; break; - - case ICElement.C_ENUMERATION: searchFor = ICSearchConstants.ENUM; break; - - default: searchFor = ICSearchConstants.UNKNOWN_SEARCH_FOR; break; - } - return searchFor; - } - - static public SearchFor getSearchForFromNode(IASTOffsetableNamedElement node){ - SearchFor searchFor = null; - - if (node instanceof IASTClassSpecifier){ - //Find out if class, struct, union - IASTClassSpecifier tempNode = (IASTClassSpecifier) node; - if(tempNode.getClassKind().equals(ASTClassKind.CLASS)){ - searchFor = ICSearchConstants.CLASS; - } - else if (tempNode.getClassKind().equals(ASTClassKind.STRUCT)){ - searchFor = ICSearchConstants.STRUCT; - } - else if (tempNode.getClassKind().equals(ASTClassKind.UNION)){ - searchFor = ICSearchConstants.UNION; - } - } - else if (node instanceof IASTMethod){ - searchFor = ICSearchConstants.METHOD; - } - else if (node instanceof IASTFunction){ - searchFor = ICSearchConstants.FUNCTION; - } - else if (node instanceof IASTField){ - searchFor = ICSearchConstants.FIELD; - } - else if (node instanceof IASTVariable){ - searchFor = ICSearchConstants.VAR; - } - else if (node instanceof IASTEnumerationSpecifier){ - searchFor = ICSearchConstants.ENUM; - } - else if (node instanceof IASTNamespaceDefinition){ - searchFor = ICSearchConstants.NAMESPACE; - } - else if( node instanceof IASTTypedefDeclaration) - searchFor = ICSearchConstants.TYPEDEF; - else if( node instanceof IASTEnumerator ) - searchFor = ICSearchConstants.ENUMTOR; - - return searchFor; - } } diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/DOMQuery.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/DOMQuery.java deleted file mode 100644 index 5a58eb346cf..00000000000 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/DOMQuery.java +++ /dev/null @@ -1,330 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.search; - -import java.util.Iterator; -import java.util.Set; - -import org.eclipse.cdt.core.dom.ast.ASTTypeUtil; -import org.eclipse.cdt.core.dom.ast.DOMException; -import org.eclipse.cdt.core.dom.ast.IASTCompoundStatement; -import org.eclipse.cdt.core.dom.ast.IASTFileLocation; -import org.eclipse.cdt.core.dom.ast.IASTName; -import org.eclipse.cdt.core.dom.ast.IASTNode; -import org.eclipse.cdt.core.dom.ast.IASTProblem; -import org.eclipse.cdt.core.dom.ast.IBinding; -import org.eclipse.cdt.core.dom.ast.ICompositeType; -import org.eclipse.cdt.core.dom.ast.IEnumeration; -import org.eclipse.cdt.core.dom.ast.IEnumerator; -import org.eclipse.cdt.core.dom.ast.IField; -import org.eclipse.cdt.core.dom.ast.IFunction; -import org.eclipse.cdt.core.dom.ast.IMacroBinding; -import org.eclipse.cdt.core.dom.ast.IScope; -import org.eclipse.cdt.core.dom.ast.ITypedef; -import org.eclipse.cdt.core.dom.ast.IVariable; -import org.eclipse.cdt.core.dom.ast.c.ICFunctionScope; -import org.eclipse.cdt.core.dom.ast.cpp.ICPPBinding; -import org.eclipse.cdt.core.dom.ast.cpp.ICPPClassType; -import org.eclipse.cdt.core.dom.ast.cpp.ICPPMember; -import org.eclipse.cdt.core.dom.ast.cpp.ICPPMethod; -import org.eclipse.cdt.core.dom.ast.cpp.ICPPNamespace; -import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.cdt.core.parser.ParserUtil; -import org.eclipse.cdt.core.search.BasicSearchMatch; -import org.eclipse.cdt.core.search.DOMSearchUtil; -import org.eclipse.cdt.core.search.ICSearchScope; -import org.eclipse.cdt.core.search.IMatch; -import org.eclipse.cdt.core.search.LimitTo; -import org.eclipse.cdt.core.search.OffsetLocatable; -import org.eclipse.cdt.ui.CUIPlugin; -import org.eclipse.cdt.utils.PathUtil; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.OperationCanceledException; -import org.eclipse.core.runtime.Path; -import org.eclipse.core.runtime.Status; -import org.eclipse.core.runtime.SubProgressMonitor; -import org.eclipse.search.ui.ISearchQuery; -import org.eclipse.search.ui.ISearchResult; - -/** - * This is used to search the DOM for IASTNames and populate the Search View with the results. - * - * @author dsteffle - */ -public class DOMQuery extends CSearchQuery implements ISearchQuery { - private static final String BLANK_STRING = ""; //$NON-NLS-1$ - - private CSearchResult _result; - - // attributes required for the search - private IASTName searchName=null; - private LimitTo limitTo=null; - private ICSearchScope scope=null; - private String searchPattern=null; - - public DOMQuery(String displaySearchPattern, IASTName name, LimitTo limitTo, ICSearchScope scope, String searchPattern) { - super(CUIPlugin.getWorkspace(), displaySearchPattern, false, null, null, null, displaySearchPattern); - this.searchName = name; - this.limitTo = limitTo; - this.scope = scope; - this.searchPattern = searchPattern; - } - - /* (non-Javadoc) - * @see org.eclipse.search.ui.ISearchQuery#run(org.eclipse.core.runtime.IProgressMonitor) - */ - public IStatus run(IProgressMonitor monitor) - throws OperationCanceledException { - final CSearchResult textResult= (CSearchResult) getSearchResult(); - IProgressMonitor mainSearchPM= new SubProgressMonitor(monitor, 1000); - NewSearchResultCollector collector = new NewSearchResultCollector(textResult, mainSearchPM); - collector.aboutToStart(); - - // fix for 43128 - Set matches=null; - IASTName[] foundNames=null; - if (searchName != null) { - if (!isLocal()) - matches = DOMSearchUtil.getMatchesFromSearchEngine(scope, searchName, limitTo); - - if (matches != null && matches.size() > 0) { - Iterator itr = matches.iterator(); - while(itr.hasNext()) { - Object next = itr.next(); - if (next instanceof IMatch) { - try { - collector.acceptMatch((IMatch)next); - } catch (CoreException e) { - // don't do anything if the match wasn't accepted - } - } - } - } else { // only search against the DOM if the index failed to get results... i.e. don't want duplicates - foundNames = DOMSearchUtil.getNamesFromDOM(searchName, limitTo); - - for (int i=0; iPreferences>Java>Code Generation>Code and Comments - */ -public class ElementNameSorter extends ViewerSorter { - - public int compare(Viewer viewer, Object e1, Object e2) { - String property1= getProperty(e1); - String property2= getProperty(e2); - return collator.compare(property1, property2); - } - - protected String getProperty(Object element) { - if (element instanceof ICElement) - return ((ICElement)element).getElementName(); - if (element instanceof IResource) - return ((IResource)element).getName(); - if (element instanceof BasicSearchMatch) - return ((BasicSearchMatch) element).getName(); - return ""; //$NON-NLS-1$ - } - - public boolean isSorterProperty(Object element, String property) { - return true; - } - -} diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/LevelTreeContentProvider.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/LevelTreeContentProvider.java deleted file mode 100644 index 1e255ddbe65..00000000000 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/LevelTreeContentProvider.java +++ /dev/null @@ -1,274 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corp. - Rational Software - initial implementation - *******************************************************************************/ - -package org.eclipse.cdt.internal.ui.search; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -import org.eclipse.cdt.core.CCorePlugin; -import org.eclipse.cdt.core.model.CModelException; -import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.cdt.core.model.ITranslationUnit; -import org.eclipse.cdt.core.search.BasicSearchMatch; -import org.eclipse.cdt.core.search.ILineLocatable; -import org.eclipse.cdt.core.search.IMatchLocatable; -import org.eclipse.cdt.core.search.IOffsetLocatable; -import org.eclipse.cdt.ui.CElementContentProvider; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.runtime.IPath; -import org.eclipse.jface.viewers.AbstractTreeViewer; -import org.eclipse.jface.viewers.ITreeContentProvider; -import org.eclipse.search.ui.text.Match; -import org.eclipse.swt.widgets.Control; - -public class LevelTreeContentProvider extends CSearchContentProvider implements ITreeContentProvider { - private AbstractTreeViewer fTreeViewer; - private Map fChildrenMap; - private CElementContentProvider fContentProvider; - - private static int[][] C_ELEMENT_TYPES= { - {ICElement.C_CLASS}, - {ICElement.C_UNIT, ICElement.C_NAMESPACE}, - {ICElement.C_CCONTAINER}, - {ICElement.C_PROJECT}, - {ICElement.C_MODEL}}; - - private static int[][] RESOURCE_TYPES= { - {}, - {IResource.FILE}, - {IResource.FOLDER}, - {IResource.PROJECT}, - {IResource.ROOT}}; - - private static final int MAX_LEVEL= C_ELEMENT_TYPES.length - 1; - private int fCurrentLevel; - - public static final int LEVEL_CLASS= 1; - public static final int LEVEL_FILE= 2; - public static final int LEVEL_FOLDER= 3; - public static final int LEVEL_PROJECT= 4; - - - public LevelTreeContentProvider(AbstractTreeViewer viewer, int level) { - fTreeViewer= viewer; - fCurrentLevel= level; - fContentProvider= new CElementContentProvider(); - } - - public Object getParent(Object child) { - Object possibleParent= null; - - if (child instanceof CSearchMatch){ - BasicSearchMatch tempMatch = ((CSearchMatch) child).getSearchMatch(); - IMatchLocatable locatable = tempMatch.getLocatable(); - int startOffset =0; - if (locatable instanceof IOffsetLocatable){ - startOffset = ((IOffsetLocatable)locatable).getNameStartOffset(); - } else if (locatable instanceof ILineLocatable){ - startOffset = ((ILineLocatable)locatable).getStartLine(); - } - - ICElement cTransUnit = CCorePlugin.getDefault().getCoreModel().create(tempMatch.getResource()); - - if (cTransUnit instanceof ITranslationUnit){ - try { - child = ((ITranslationUnit) cTransUnit).getElementAtOffset(startOffset); - } catch (CModelException e) {} - } - if( child == null ){ - possibleParent = cTransUnit; - } - } - - if( child != null ) - possibleParent = internalGetParent(child); - - if (possibleParent instanceof ICElement) { - ICElement cElement= (ICElement) possibleParent; - for (int j= fCurrentLevel; j < MAX_LEVEL + 1; j++) { - for (int i= 0; i < C_ELEMENT_TYPES[j].length; i++) { - if (cElement.getElementType() == C_ELEMENT_TYPES[j][i]) { - return null; - } - } - } - } else if (possibleParent instanceof IResource) { - IResource resource= (IResource) possibleParent; - for (int j= fCurrentLevel; j < MAX_LEVEL + 1; j++) { - for (int i= 0; i < RESOURCE_TYPES[j].length; i++) { - if (resource.getType() == RESOURCE_TYPES[j][i]) { - return null; - } - } - } - } - - return possibleParent; - } - - private Object internalGetParent(Object child) { - Object parent = fContentProvider.getParent(child); - - if (parent == null){ - //Could be an external file - if (child instanceof CSearchMatch){ - BasicSearchMatch match = ((CSearchMatch) child).getSearchMatch(); - IPath location=match.getLocation(); - return location; - } - } - - return parent; - } - - - public Object[] getElements(Object inputElement) { - return getChildren(inputElement); - } - - protected synchronized void initialize(CSearchResult result) { - super.initialize(result); - fChildrenMap= new HashMap(); - if (result != null) { - Object[] elements= result.getElements(); - for (int i= 0; i < elements.length; i++) { - insert(elements[i], false); - } - } - } - - protected void insert(Object child, boolean refreshViewer) { - Object parent= getMatchParent(child); - while (parent != null) { - if (insertChild(parent, child)) { - if (refreshViewer) - fTreeViewer.add(parent, child); - } else { - if (refreshViewer) - fTreeViewer.refresh(parent); - return; - } - child= parent; - parent= getParent(child); - } - - if (insertChild(_result, child)) { - if (refreshViewer) - fTreeViewer.add(_result, child); - } - } - - /** - * @param child - * @return - */ - private Object getMatchParent(Object child) { - Match[]m=null; - if (child instanceof String){ - m=this._result.getMatches(child); - } - - if (m.length > 0) - return getParent(m[0]); - - return null; - } - - /** - * returns true if the child already was a child of parent. - * - * @param parent - * @param child - * @return - */ - private boolean insertChild(Object parent, Object child) { - Set children= (Set) fChildrenMap.get(parent); - if (children == null) { - children= new HashSet(); - fChildrenMap.put(parent, children); - } - return children.add(child); - } - - protected void remove(Object element, boolean refreshViewer) { - // precondition here: _result.getMatchCount(child) <= 0 - - if (hasChildren(element)) { - if (refreshViewer) - fTreeViewer.refresh(element); - } else { - if (_result.getMatchCount(element) == 0) { - fChildrenMap.remove(element); - Object parent= getParent(element); - if (parent != null) { - removeFromSiblings(element, parent); - remove(parent, refreshViewer); - } else { - removeFromSiblings(element, _result); - if (refreshViewer) - fTreeViewer.refresh(); - } - } else { - if (refreshViewer) { - fTreeViewer.refresh(element); - } - } - } - } - - private void removeFromSiblings(Object element, Object parent) { - Set siblings= (Set) fChildrenMap.get(parent); - if (siblings != null) { - siblings.remove(element); - } - } - - public Object[] getChildren(Object parentElement) { - Set children= (Set) fChildrenMap.get(parentElement); - if (children == null) - return EMPTY_ARR; - return children.toArray(); - } - - public boolean hasChildren(Object element) { - return getChildren(element).length > 0; - } - - public synchronized void elementsChanged(Object[] updatedElements) { - if (_result == null) - return; - for (int i= 0; i < updatedElements.length; i++) { - if (_result.getMatchCount(updatedElements[i]) > 0) - insert(updatedElements[i], true); - else - remove(updatedElements[i], true); - } - } - - public void clear() { - initialize(_result); - fTreeViewer.refresh(); - } - - public void setLevel(int level) { - fCurrentLevel= level; - Control control= fTreeViewer.getControl(); - if (control != null) - control.setRedraw(false); - initialize(_result); - fTreeViewer.refresh(); - if (control != null) - control.setRedraw(true); - } -} diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/NewSearchResultCollector.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/NewSearchResultCollector.java deleted file mode 100644 index 8267bc2bd78..00000000000 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/NewSearchResultCollector.java +++ /dev/null @@ -1,174 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corp. - Rational Software - initial implementation - *******************************************************************************/ - -package org.eclipse.cdt.internal.ui.search; - -import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.cdt.core.search.BasicSearchMatch; -import org.eclipse.cdt.core.search.BasicSearchResultCollector; -import org.eclipse.cdt.core.search.ICSearchConstants; -import org.eclipse.cdt.core.search.ILineLocatable; -import org.eclipse.cdt.core.search.IMatch; -import org.eclipse.cdt.core.search.IMatchLocatable; -import org.eclipse.cdt.core.search.IOffsetLocatable; -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.search.ui.text.Match; - -public class NewSearchResultCollector extends BasicSearchResultCollector { - public static final int PARENT_LENGTH = 7; - public static final String PARENT = "PARENT:"; //$NON-NLS-1$ - - public static final int NAME_LENGTH = 5; - public static final String NAME = "NAME:"; //$NON-NLS-1$ - - public static final int LOCATION_LENGTH = 9; - public static final String LOCATION = "LOCATION:"; //$NON-NLS-1$ - - public static final int ELEMENTTYPE_LENGTH = 12; - public static final String ELEMENTTYPE = "ELEMENTTYPE:"; //$NON-NLS-1$ - - public static final int VISIBILITY_LENGTH = 11; - public static final String VISIBILITY = "VISIBILITY:"; //$NON-NLS-1$ - - private CSearchResult fSearch; - private IProgressMonitor fProgressMonitor; - private int fMatchCount; - - - public NewSearchResultCollector(CSearchResult search, IProgressMonitor monitor) { - super(); - fSearch= search; - fProgressMonitor= monitor; - fMatchCount = 0; - } - - - public void accept(IResource resource, int start, int end, ICElement enclosingElement, int accuracy) { - fMatchCount++; - fSearch.addMatch(new Match(enclosingElement, start, end-start)); - } - - - public void done() { - } - - public IProgressMonitor getProgressMonitor() { - return fProgressMonitor; - } - - public int getMatchCount() { - return fMatchCount; - } - - - /* (non-Javadoc) - * @see org.eclipse.cdt.core.search.ICSearchResultCollector#acceptMatch(org.eclipse.cdt.core.search.IMatch) - */ - public boolean acceptMatch(IMatch match) throws CoreException { - - BasicSearchMatch searchMatch = (BasicSearchMatch) match; - - if( !super.acceptMatch( match ) ) - return false; - - if( searchMatch.getResource() == null && - searchMatch.getPath() == null) - return false; - - if (searchMatch.getResource() != null){ - fMatchCount++; - int start =0; - int end = 0; - - IMatchLocatable locatable = match.getLocatable(); - if (locatable instanceof IOffsetLocatable){ - start = ((IOffsetLocatable)locatable).getNameStartOffset(); - end = ((IOffsetLocatable)locatable).getNameEndOffset(); - } else if (locatable instanceof ILineLocatable){ - start = ((ILineLocatable)locatable).getStartLine(); - //Not all line based indexers can provide an ending line; check - //to see if there is a value stored here - int tempEnd = ((ILineLocatable)locatable).getEndLine(); - if (tempEnd > 0 && tempEnd > start){ - end = tempEnd; - } - } - - String classifier = PARENT + match.getParentName() + NAME + match.getName() + LOCATION + match.getLocation().toOSString() + ELEMENTTYPE + match.getElementType() + VISIBILITY + match.getVisibility(); - fSearch.addMatch(new CSearchMatch(classifier,start,end-start, match)); - - return true; - } - else { - fMatchCount++; - int start =0; - int end = 0; - - IMatchLocatable locatable = match.getLocatable(); - if (locatable instanceof IOffsetLocatable){ - start = ((IOffsetLocatable)locatable).getNameStartOffset(); - end = ((IOffsetLocatable)locatable).getNameEndOffset(); - } else if (locatable instanceof ILineLocatable){ - start = ((ILineLocatable)locatable).getStartLine(); - //Not all line based indexers can provide an ending line; check - //to see if there is a value stored here - int tempEnd = ((ILineLocatable)locatable).getEndLine(); - if (tempEnd > 0 && tempEnd > start){ - end = tempEnd; - } - } - - String classifier = PARENT + match.getParentName() + NAME + match.getName() + LOCATION + match.getLocation().toOSString() + ELEMENTTYPE + match.getElementType() + VISIBILITY + match.getVisibility(); - fSearch.addMatch(new CSearchMatch(classifier,start,end-start, match)); - - return true; - } - } - - - /** - * @param externalMatchLocation - * @param refProject - * @return - */ - private IFile getUniqueFile(IPath externalMatchLocation, IProject refProject) { - IFile file = null; - String fileName = ""; //$NON-NLS-1$ - //Total number of segments in file name - int segments = externalMatchLocation.segmentCount() - 1; - for (int linkNumber=0; linkNumberPreferences>Java>Code Generation>Code and Comments - */ -public class ParentNameSorter extends ElementNameSorter { - - public int compare(Viewer viewer, Object e1, Object e2) { - String leftParent= getParentName(e1); - String rightParent= getParentName(e2); - return collator.compare(leftParent, rightParent); - } - - private String getParentName(Object element) { - if (element instanceof ICElement) { - ICElement parent= ((ICElement)element).getParent(); - - if (parent != null) - return parent.getElementName(); - } - if (element instanceof IResource) { - IResource parent= ((IResource)element).getParent(); - if (parent != null) - return parent.getName(); - } - if (element instanceof BasicSearchMatch){ - return ((BasicSearchMatch) element).getParentName(); - } - return ""; //$NON-NLS-1$ - } -} diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/PathNameSorter.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/PathNameSorter.java deleted file mode 100644 index bbf38c13c43..00000000000 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/PathNameSorter.java +++ /dev/null @@ -1,60 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2003, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corp. - Rational Software - initial implementation - *******************************************************************************/ -/* - * Created on Jun 24, 2003 - */ -package org.eclipse.cdt.internal.ui.search; - -import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.cdt.core.search.BasicSearchMatch; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.Path; -import org.eclipse.jface.viewers.Viewer; - -/** - * @author aniefer - * - * To change the template for this generated type comment go to - * Window>Preferences>Java>Code Generation>Code and Comments - */ -public class PathNameSorter extends ElementNameSorter { - - public int compare(Viewer viewer, Object e1, Object e2) { - IPath path1= getPath(e1); - IPath path2=getPath(e2); - return compare(path1, path2); - } - - /** - * @param e1 - * @return - */ - private IPath getPath(Object element) { - if (element instanceof ICElement) - return ((ICElement)element).getPath(); - if (element instanceof IResource) - return ((IResource)element).getFullPath(); - if (element instanceof BasicSearchMatch) - return ((BasicSearchMatch) element).getLocation(); - return new Path(""); //$NON-NLS-1$ - } - - protected int compare(IPath path1, IPath path2) { - int segmentCount= Math.min(path1.segmentCount(), path2.segmentCount()); - for (int i= 0; i < segmentCount; i++) { - int value= collator.compare(path1.segment(i), path2.segment(i)); - if (value != 0) - return value; - } - return path1.segmentCount() - path2.segmentCount(); - } -} diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/actions/AddToIndexAction.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/actions/AddToIndexAction.java deleted file mode 100644 index 6c58b408f37..00000000000 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/actions/AddToIndexAction.java +++ /dev/null @@ -1,94 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.search.actions; - -import java.util.Iterator; - -import org.eclipse.cdt.core.CCorePlugin; -import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.cdt.internal.ui.editor.CEditor; -import org.eclipse.cdt.internal.ui.search.CSearchMessages; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IResource; -import org.eclipse.jface.action.Action; -import org.eclipse.jface.viewers.IStructuredSelection; -import org.eclipse.ui.IWorkbenchSite; - -public class AddToIndexAction extends Action { - - protected IWorkbenchSite fSite; - protected CEditor fEditor; - - - public AddToIndexAction(CEditor editor, String label, String tooltip){ - fEditor = editor; - setText(label); //$NON-NLS-1$ - setToolTipText(tooltip); //$NON-NLS-1$ - } - - public AddToIndexAction(CEditor editor){ - this(editor, - CSearchMessages.getString("ActionDefinition.addToIndex.name"), //$NON-NLS-1$ - CSearchMessages.getString("ActionDefinition.addToIndex.description")); //$NON-NLS-1$ - } - - public AddToIndexAction(IWorkbenchSite site){ - this(site, - CSearchMessages.getString("ActionDefinition.addToIndex.name"), //$NON-NLS-1$ - CSearchMessages.getString("ActionDefinition.addToIndex.description")); //$NON-NLS-1$ - } - - public AddToIndexAction(IWorkbenchSite site, String label, String tooltip) { - fSite = site; - setText(label); - setToolTipText(tooltip); - } - - public void run() { - if (fEditor != null){ - ICElement celement= fEditor.getInputCElement(); - IResource resource = celement.getUnderlyingResource(); - if (resource != null){ - IProject project = resource.getProject(); - if (project != null) - CCorePlugin.getDefault().getCoreModel().getIndexManager().addResource(project,resource); - } - } else if ( fSite != null) { - if (fSite.getSelectionProvider() != null ){ - IStructuredSelection sel = (IStructuredSelection) fSite.getSelectionProvider().getSelection(); - Iterator iter = sel.iterator(); - while (iter.hasNext()){ - Object element = iter.next(); - if (element instanceof ICElement){ - ICElement cel = (ICElement) element; - IProject proj = cel.getCProject().getProject(); - IResource resource =cel.getResource(); - if (proj!= null && - resource != null){ - CCorePlugin.getDefault().getCoreModel().getIndexManager().addResource(proj,resource); - } - } - //Can be added to deal with external files -> but need indexer addResourceByPath support - /*else if (element instanceof ITranslationUnit){ - ITranslationUnit trans = (ITranslationUnit) element; - IProject proj = trans.getCProject().getProject(); - IPath path=trans.getPath(); - CCorePlugin.getDefault().getCoreModel().getIndexManager().addResourceByPath(proj,path, ICDTIndexer.COMPILATION_UNIT); - }*/ - - } - - } - } - } - - -} diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/actions/FindAction.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/actions/FindAction.java index b039b8c14f7..083a4415b56 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/actions/FindAction.java +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/actions/FindAction.java @@ -11,44 +11,16 @@ package org.eclipse.cdt.internal.ui.search.actions; -import java.lang.reflect.InvocationTargetException; -import java.util.LinkedList; -import java.util.List; - -import org.eclipse.cdt.core.CCorePlugin; -import org.eclipse.cdt.core.ICLogConstants; -import org.eclipse.cdt.core.dom.CDOM; -import org.eclipse.cdt.core.dom.IASTServiceProvider; -import org.eclipse.cdt.core.dom.IASTServiceProvider.UnsupportedDialectException; -import org.eclipse.cdt.core.dom.ast.ASTVisitor; -import org.eclipse.cdt.core.dom.ast.IASTName; -import org.eclipse.cdt.core.dom.ast.IASTNode; -import org.eclipse.cdt.core.dom.ast.IASTTranslationUnit; -import org.eclipse.cdt.core.dom.ast.ILabel; import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.cdt.core.model.ICProject; import org.eclipse.cdt.core.model.ISourceReference; -import org.eclipse.cdt.core.parser.ParseError; -import org.eclipse.cdt.core.parser.ParserLanguage; -import org.eclipse.cdt.core.search.DOMSearchUtil; -import org.eclipse.cdt.core.search.ICSearchScope; -import org.eclipse.cdt.core.search.LimitTo; -import org.eclipse.cdt.core.search.SearchFor; +import org.eclipse.cdt.core.model.ITranslationUnit; import org.eclipse.cdt.internal.ui.editor.CEditor; -import org.eclipse.cdt.internal.ui.search.CSearchQuery; -import org.eclipse.cdt.internal.ui.search.CSearchUtil; -import org.eclipse.cdt.internal.ui.search.DOMQuery; -import org.eclipse.cdt.internal.ui.util.ExternalEditorInput; -import org.eclipse.cdt.internal.ui.util.ProblemTreeViewer; -import org.eclipse.core.resources.IFile; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.jface.dialogs.ProgressMonitorDialog; -import org.eclipse.jface.operation.IRunnableWithProgress; -import org.eclipse.jface.text.IDocument; +import org.eclipse.cdt.internal.ui.search.PDOMSearchElementQuery; +import org.eclipse.cdt.internal.ui.search.PDOMSearchTextSelectionQuery; import org.eclipse.jface.text.ITextSelection; -import org.eclipse.jface.text.TextSelection; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.search.ui.ISearchQuery; import org.eclipse.search.ui.NewSearchUI; import org.eclipse.ui.IWorkbenchSite; @@ -62,295 +34,43 @@ public abstract class FindAction extends SelectionParseAction { super( site ); } - /** - * This is used to create a DOMSearchQuery based on an IASTName, LimitTo, ICSearchScope and an ICSearchCollector if - * one should be used. - * - * This is a convenience method to setup the title of the DOMSearchQuery as the rest of the parameters are passed directly - * to the DOMSearchQuery constructor: - * - * return new DOMQuery(buffer.toString(), name, limitTo, scope, collector); - * - * @param name - * @param limitTo - * @param scope - * @param collector - * @return - */ - public CSearchQuery createDOMSearchQueryForName( IASTName name, LimitTo limitTo, ICSearchScope scope, String searchPattern){ - return new DOMQuery(DOMSearchUtil.getSearchPattern(name), name, limitTo, scope, searchPattern); - } - - - /** - * This is a convenience method and is the same as invoking: - * createDOMSearchQueryForName( name, limitTo, scope, null ); - * - * @param name - * @param limitTo - * @param scope - * @return - */ - public CSearchQuery createSearchQueryForName( IASTName name, LimitTo limitTo, ICSearchScope scope, String searchPattern ){ - return createDOMSearchQueryForName( name, limitTo, scope, searchPattern ); - } - public void run() { - ISelection sel = getSelection(); - - if (sel instanceof IStructuredSelection) { - Object obj = ((IStructuredSelection)sel).getFirstElement(); - - // if possible, try to perform a full blown DOM query before the Index query, if this fails, then perform an Index query - if (obj instanceof ISourceReference && fSite.getSelectionProvider() instanceof ProblemTreeViewer) { - try { - fEditor = ((ProblemTreeViewer)fSite.getSelectionProvider()).getEditor(); - if (fEditor != null){ - IDocument doc = fEditor.getDocumentProvider().getDocument(fEditor.getEditorInput()); - ISourceReference ref = (ISourceReference)obj; - - TextSelection selection = new TextSelection(doc, ref.getSourceRange().getIdStartPos(), ref.getSourceRange().getIdLength()); - run(selection); - return; - } - } catch (Exception e) { - } - } - - run((IStructuredSelection) sel); - } else if (sel instanceof ITextSelection) { - run((ITextSelection) sel); + ISearchQuery searchJob = null; + + ISelection selection = getSelection(); + if (selection instanceof IStructuredSelection) { + Object object = ((IStructuredSelection)selection).getFirstElement(); + if (object instanceof ISourceReference) + searchJob = new PDOMSearchElementQuery(getScope(), (ISourceReference)object, getLimitTo()); + } else if (selection instanceof ITextSelection) { + ICElement element = fEditor.getInputCElement(); + while (element != null && !(element instanceof ITranslationUnit)) + element = element.getParent(); + if (element != null) { + searchJob = new PDOMSearchTextSelectionQuery( + getScope(), + (ITranslationUnit)element, + (ITextSelection)selection, + getLimitTo()); + } } - } - - public void run(IStructuredSelection sel){ - Object obj = sel.getFirstElement(); - if( obj == null || !(obj instanceof ICElement ) ){ + + if (searchJob == null) { operationNotAvailable(CSEARCH_OPERATION_OPERATION_UNAVAILABLE_MESSAGE); return; } clearStatusLine(); - - ICElement element = (ICElement) obj; - - CSearchQuery job = createSearchQuery( getFullyQualifiedName(element), CSearchUtil.getSearchForFromElement(element)); - - if (job == null) - return; NewSearchUI.activateSearchResultView(); - NewSearchUI.runQueryInBackground(job); + NewSearchUI.runQueryInBackground(searchJob); } - /** - * @param node - */ - protected CSearchQuery createSearchQuery(String pattern, SearchFor searchFor) { - CSearchQuery op = null; - ICSearchScope scope = getScope(); - - if (scope == null) - return null; - - String scopeDescription = getScopeDescription(); - - //Create a case sensitive search operation - limited by the node - List search = new LinkedList(); - search.add(searchFor); - - LimitTo limitTo = getLimitTo(); - - op = new CSearchQuery(CCorePlugin.getWorkspace(), pattern,true,search,limitTo,scope,scopeDescription); - return op; - - } - - public void run(ITextSelection sel){ - if(sel == null) { - return; - } - - SelSearchNode selNode = getSelection( sel ); - - IASTNode foundNode = null; - IASTTranslationUnit tu = null; - ParserLanguage lang = null; - String file = null; - - ParseWithProgress runnable = new ParseWithProgress(); - ProgressMonitorDialog progressMonitor = new ProgressMonitorDialog(fEditor.getSite().getShell()); - try { - progressMonitor.run(true, true, runnable); - tu = runnable.getTu(); - file = runnable.getFile(); - lang = runnable.getLang(); - } catch (InvocationTargetException e1) { - operationNotAvailable(CSEARCH_OPERATION_OPERATION_UNAVAILABLE_MESSAGE); - return; - } catch (InterruptedException e1) { - operationNotAvailable(CSEARCH_OPERATION_OPERATION_UNAVAILABLE_MESSAGE); - return; - } - - try{ - foundNode = tu.selectNodeForLocation(file, selNode.selStart, selNode.selEnd - selNode.selStart); - } - catch (ParseError er){} - catch (Exception ex){} - catch ( VirtualMachineError vmErr){ - if (vmErr instanceof OutOfMemoryError){ - org.eclipse.cdt.internal.core.model.Util.log(null, "Selection Search Out Of Memory error: " + vmErr.getMessage() + " on File: " + file, ICLogConstants.CDT); //$NON-NLS-1$ //$NON-NLS-2$ - } - } - - IASTName foundName = null; - if (foundNode instanceof IASTName) { - foundName = (IASTName)foundNode; - } else { - ASTVisitor collector = null; - if (lang == ParserLanguage.CPP) { - collector = new DOMSearchUtil.CPPNameCollector(); - } else { - collector = new DOMSearchUtil.CNameCollector(); - } - - if (foundNode != null) { // nothing found - foundNode.accept( collector ); - - List names = null; - if (collector instanceof DOMSearchUtil.CPPNameCollector) { - names = ((DOMSearchUtil.CPPNameCollector)collector).nameList; - } else { - names = ((DOMSearchUtil.CNameCollector)collector).nameList; - } - - if (names.size() == 1) { // just right - clearStatusLine(); - } else if (names.size() == 0) { // no names selected - operationNotAvailable(CSEARCH_OPERATION_NO_NAMES_SELECTED_MESSAGE); - return; - } - - foundName = (IASTName)names.get(0); - } - } - - //Don't allow searches for labels since i)there is no corresponding ICElement - //and thus no label provider and ii) it doesn't make sense to do a global search - //for a local element - if (foundName != null && foundName.resolveBinding() instanceof ILabel) { - operationNotAvailable(CSEARCH_OPERATION_OPERATION_UNAVAILABLE_MESSAGE); - return; - } - - LimitTo limitTo = getLimitTo(); - ICSearchScope searchScope = null; - searchScope = getScope(); - - if (searchScope == null) - return; - - CSearchQuery job = createSearchQueryForName(foundName, limitTo, searchScope, selNode.selText); - - if (job == null) - return; - - NewSearchUI.activateSearchResultView(); - - NewSearchUI.runQueryInBackground(job); - } - - private class ParseWithProgress implements IRunnableWithProgress - { - private IASTTranslationUnit tu = null; - private String file=null; - private ParserLanguage lang=null; - - public ParseWithProgress() {} - - public void run(IProgressMonitor monitor) { - if (fEditor.getEditorInput() instanceof ExternalEditorInput) { - ExternalEditorInput input = (ExternalEditorInput)fEditor.getEditorInput(); - try { - // get the project for the external editor input's translation unit - ICElement project = input.getTranslationUnit(); - while (!(project instanceof ICProject) && project != null) { - project = project.getParent(); - } - - if (project instanceof ICProject) { - tu = CDOM.getInstance().getASTService().getTranslationUnit(input.getStorage(), ((ICProject)project).getProject()); - lang = DOMSearchUtil.getLanguage(input.getStorage().getFullPath(), ((ICProject)project).getProject()); - } - } catch (UnsupportedDialectException e) { - operationNotAvailable(CSEARCH_OPERATION_OPERATION_UNAVAILABLE_MESSAGE); - return; - } - - file = input.getStorage().getFullPath().toOSString(); - } else { - IFile resourceFile = null; - resourceFile = fEditor.getInputFile(); - - try { - tu = CDOM.getInstance().getASTService().getTranslationUnit( - resourceFile, - CDOM.getInstance().getCodeReaderFactory( - CDOM.PARSE_WORKING_COPY_WHENEVER_POSSIBLE)); - } catch (IASTServiceProvider.UnsupportedDialectException e) { - operationNotAvailable(CSEARCH_OPERATION_OPERATION_UNAVAILABLE_MESSAGE); - return; - } - - file = resourceFile.getLocation().toOSString(); - lang = DOMSearchUtil.getLanguageFromFile(resourceFile); - } - } - - public IASTTranslationUnit getTu() { - return tu; - } - - public String getFile() { - return file; - } - - public ParserLanguage getLang() { - return lang; - } - }; - - - private String getFullyQualifiedName(ICElement element){ - - StringBuffer fullName = new StringBuffer(element.getElementName()); - - while (element.getElementType() != 0){ - element = element.getParent(); - //Keep going up CModel until we hit Translation Unit - //or Working Copy (both represented by C_UNIT) or hit a null - if (element.getElementType() == ICElement.C_UNIT || - element == null){ -// fullName.insert(0,"::"); //$NON-NLS-1$ // fix for PR 104128 - break; - } - else if (element.getElementType() != ICElement.C_ENUMERATION){ - //get the parent name as long as it is not an enumeration - enumerators - //don't use the enumeration name as part of the fully qualified name - fullName.insert(0,"::"); //$NON-NLS-1$ - fullName.insert(0,element.getElementName()); - } - } - - return fullName.toString(); - } - abstract protected String getScopeDescription(); - abstract protected ICSearchScope getScope(); + abstract protected ICElement[] getScope(); - abstract protected LimitTo getLimitTo(); + abstract protected int getLimitTo(); } diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/actions/FindDeclarationsAction.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/actions/FindDeclarationsAction.java index 527646abd0d..a19f73cceb9 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/actions/FindDeclarationsAction.java +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/actions/FindDeclarationsAction.java @@ -11,12 +11,10 @@ package org.eclipse.cdt.internal.ui.search.actions; -import org.eclipse.cdt.core.search.ICSearchConstants; -import org.eclipse.cdt.core.search.ICSearchScope; -import org.eclipse.cdt.core.search.LimitTo; -import org.eclipse.cdt.core.search.SearchEngine; +import org.eclipse.cdt.core.model.ICElement; import org.eclipse.cdt.internal.ui.editor.CEditor; import org.eclipse.cdt.internal.ui.search.CSearchMessages; +import org.eclipse.cdt.internal.ui.search.PDOMSearchQuery; import org.eclipse.ui.IWorkbenchSite; @@ -39,35 +37,22 @@ public class FindDeclarationsAction extends FindAction { CSearchMessages.getString("CSearch.FindDeclarationAction.label"), //$NON-NLS-1$ CSearchMessages.getString("CSearch.FindDeclarationAction.tooltip")); //$NON-NLS-1$ } - /** - * @param site - * @param string - * @param string2 - * @param string3 - */ + public FindDeclarationsAction(IWorkbenchSite site, String label, String tooltip) { super(site); setText(label); setToolTipText(tooltip); } - /* (non-Javadoc) - * @see org.eclipse.cdt.internal.ui.editor.selsearch.FindAction#getScope(org.eclipse.core.resources.IProject) - */ - protected ICSearchScope getScope() { - return SearchEngine.createWorkspaceScope(); + + protected ICElement[] getScope() { + return null; } - /* (non-Javadoc) - * @see org.eclipse.cdt.internal.ui.editor.selsearch.FindAction#getScopeDescription() - */ + protected String getScopeDescription() { - // TODO Auto-generated method stub return CSearchMessages.getString("WorkspaceScope"); //$NON-NLS-1$ } - /* (non-Javadoc) - * @see org.eclipse.cdt.internal.ui.editor.selsearch.FindAction#getLimitTo() - */ - protected LimitTo getLimitTo() { - // TODO Auto-generated method stub - return ICSearchConstants.DECLARATIONS_DEFINITIONS; + + protected int getLimitTo() { + return PDOMSearchQuery.FIND_DECLARATIONS_DEFINITIONS; } } diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/actions/FindDeclarationsInWorkingSetAction.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/actions/FindDeclarationsInWorkingSetAction.java index 12442780cb8..e63dded00c5 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/actions/FindDeclarationsInWorkingSetAction.java +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/actions/FindDeclarationsInWorkingSetAction.java @@ -10,13 +10,15 @@ *******************************************************************************/ package org.eclipse.cdt.internal.ui.search.actions; -import org.eclipse.cdt.core.search.ICSearchConstants; -import org.eclipse.cdt.core.search.ICSearchScope; -import org.eclipse.cdt.core.search.LimitTo; +import java.util.ArrayList; +import java.util.List; + +import org.eclipse.cdt.core.model.ICElement; import org.eclipse.cdt.internal.ui.editor.CEditor; import org.eclipse.cdt.internal.ui.search.CSearchMessages; -import org.eclipse.cdt.internal.ui.search.CSearchScopeFactory; import org.eclipse.cdt.internal.ui.search.CSearchUtil; +import org.eclipse.cdt.internal.ui.search.PDOMSearchQuery; +import org.eclipse.core.runtime.IAdaptable; import org.eclipse.ui.IWorkbenchSite; import org.eclipse.ui.IWorkingSet; @@ -24,9 +26,7 @@ public class FindDeclarationsInWorkingSetAction extends FindAction { private IWorkingSet[] fWorkingSet; private String scopeDescription = ""; //$NON-NLS-1$ - /** - * @param site - */ + public FindDeclarationsInWorkingSetAction(IWorkbenchSite site, IWorkingSet[] wset) { this(site, CSearchMessages.getString("CSearch.FindDeclarationsInWorkingSetAction.label"), //$NON-NLS-1$ @@ -36,9 +36,6 @@ public class FindDeclarationsInWorkingSetAction extends FindAction { fWorkingSet = wset; } - /** - * @param editor - */ public FindDeclarationsInWorkingSetAction(CEditor editor, IWorkingSet[] wset) { this(editor, CSearchMessages.getString("CSearch.FindDeclarationsInWorkingSetAction.label"), //$NON-NLS-1$ @@ -53,47 +50,35 @@ public class FindDeclarationsInWorkingSetAction extends FindAction { setText(label); //$NON-NLS-1$ setToolTipText(tooltip); //$NON-NLS-1$ } - /** - * @param site - * @param string - * @param string2 - * @param string3 - */ + public FindDeclarationsInWorkingSetAction(IWorkbenchSite site,String label, String tooltip){ super(site); setText(label); //$NON-NLS-1$ setToolTipText(tooltip); //$NON-NLS-1$ } - /* (non-Javadoc) - * @see org.eclipse.cdt.internal.ui.editor.selsearch.FindAction#getScopeDescription() - */ + protected String getScopeDescription() { return scopeDescription; } - /* (non-Javadoc) - * @see org.eclipse.cdt.internal.ui.editor.selsearch.FindAction#getScope(org.eclipse.core.resources.IProject) - */ - protected ICSearchScope getScope() { - IWorkingSet[] workingSets= null; - if (fWorkingSet == null) { - workingSets= CSearchScopeFactory.getInstance().queryWorkingSets(); - if (workingSets == null) - return null; - } - else { - workingSets = fWorkingSet; - } - ICSearchScope scope= CSearchScopeFactory.getInstance().createCSearchScope(workingSets); - scopeDescription = CSearchMessages.getFormattedString("WorkingSetScope", new String[] {CSearchUtil.toString(workingSets)}); //$NON-NLS-1$ - CSearchUtil.updateLRUWorkingSets(workingSets); + + protected ICElement[] getScope() { + List resources = new ArrayList(); - return scope; + for (int i = 0; i < fWorkingSet.length; ++i) { + IAdaptable[] elements = fWorkingSet[i].getElements(); + for (int j = 0; j < elements.length; ++j) { + ICElement resource = (ICElement)elements[j].getAdapter(ICElement.class); + if (resource != null) + resources.add(resource); + } + } + + scopeDescription = CSearchMessages.getFormattedString("WorkingSetScope", new String[] {CSearchUtil.toString(fWorkingSet)}); //$NON-NLS-1$ + return (ICElement[])resources.toArray(new ICElement[resources.size()]); } - /* (non-Javadoc) - * @see org.eclipse.cdt.internal.ui.editor.selsearch.FindAction#getLimitTo() - */ - protected LimitTo getLimitTo() { - return ICSearchConstants.DECLARATIONS_DEFINITIONS; + + protected int getLimitTo() { + return PDOMSearchQuery.FIND_DECLARATIONS_DEFINITIONS; } } diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/actions/FindDeclarationsProjectAction.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/actions/FindDeclarationsProjectAction.java index 09f373f0b84..cabb9534f4b 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/actions/FindDeclarationsProjectAction.java +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/actions/FindDeclarationsProjectAction.java @@ -10,15 +10,14 @@ *******************************************************************************/ package org.eclipse.cdt.internal.ui.search.actions; +import org.eclipse.cdt.core.model.CoreModel; import org.eclipse.cdt.core.model.ICElement; import org.eclipse.cdt.core.model.ICProject; -import org.eclipse.cdt.core.search.ICSearchConstants; -import org.eclipse.cdt.core.search.ICSearchScope; -import org.eclipse.cdt.core.search.LimitTo; -import org.eclipse.cdt.core.search.SearchEngine; import org.eclipse.cdt.internal.ui.editor.CEditor; import org.eclipse.cdt.internal.ui.search.CSearchMessages; -import org.eclipse.cdt.internal.ui.search.CSearchScopeFactory; +import org.eclipse.cdt.internal.ui.search.PDOMSearchQuery; +import org.eclipse.core.resources.IResource; +import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.ui.IWorkbenchSite; @@ -41,47 +40,37 @@ public class FindDeclarationsProjectAction extends FindAction { CSearchMessages.getString("CSearch.FindDeclarationsProjectAction.label"), //$NON-NLS-1$ CSearchMessages.getString("CSearch.FindDeclarationsProjectAction.tooltip")); //$NON-NLS-1$ } - /** - * @param site - * @param string - * @param string2 - * @param string3 - */ + public FindDeclarationsProjectAction(IWorkbenchSite site, String label, String tooltip) { super(site); setText(label); setToolTipText(tooltip); } - /* (non-Javadoc) - * @see org.eclipse.cdt.internal.ui.editor.selsearch.FindAction#getScope(org.eclipse.core.resources.IProject) - */ - protected ICSearchScope getScope() { - - ICProject proj = null; - if (fEditor != null){ - proj= fEditor.getInputCElement().getCProject(); + + protected ICElement[] getScope() { + ICProject project = null; + if (fEditor != null) { + project = fEditor.getInputCElement().getCProject(); } else if (fSite != null){ - IStructuredSelection sel = (IStructuredSelection) getSelection(); - return CSearchScopeFactory.getInstance().createEnclosingProjectScope(sel); + ISelection selection = getSelection(); + if (selection instanceof IStructuredSelection) { + Object element = ((IStructuredSelection)selection).getFirstElement(); + if (element instanceof IResource) + project = CoreModel.getDefault().create(((IResource)element).getProject()); + else if (element instanceof ICElement) + project = ((ICElement)element).getCProject(); + } } - ICElement[] element = new ICElement[1]; - element[0]=proj; - return SearchEngine.createCSearchScope(element); + return project != null ? new ICElement[] { project } : null; } - /* (non-Javadoc) - * @see org.eclipse.cdt.internal.ui.editor.selsearch.FindAction#getScopeDescription() - */ + protected String getScopeDescription() { - // TODO Auto-generated method stub return CSearchMessages.getString("ProjectScope"); //$NON-NLS-1$ } - /* (non-Javadoc) - * @see org.eclipse.cdt.internal.ui.editor.selsearch.FindAction#getLimitTo() - */ - protected LimitTo getLimitTo() { - // TODO Auto-generated method stub - return ICSearchConstants.DECLARATIONS_DEFINITIONS; + + protected int getLimitTo() { + return PDOMSearchQuery.FIND_DECLARATIONS_DEFINITIONS; } } diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/actions/FindRefsAction.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/actions/FindRefsAction.java index 25340d6b49e..ef66d5e96e5 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/actions/FindRefsAction.java +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/actions/FindRefsAction.java @@ -10,19 +10,14 @@ *******************************************************************************/ package org.eclipse.cdt.internal.ui.search.actions; -import org.eclipse.cdt.core.search.ICSearchConstants; -import org.eclipse.cdt.core.search.ICSearchScope; -import org.eclipse.cdt.core.search.LimitTo; -import org.eclipse.cdt.core.search.SearchEngine; +import org.eclipse.cdt.core.model.ICElement; import org.eclipse.cdt.internal.ui.editor.CEditor; import org.eclipse.cdt.internal.ui.search.CSearchMessages; +import org.eclipse.cdt.internal.ui.search.PDOMSearchQuery; import org.eclipse.ui.IWorkbenchSite; - public class FindRefsAction extends FindAction { - /** - * @param editor - */ + public FindRefsAction(CEditor editor) { this(editor, CSearchMessages.getString("CSearch.FindReferencesAction.label"), //$NON-NLS-1$ @@ -34,45 +29,28 @@ public class FindRefsAction extends FindAction { CSearchMessages.getString("CSearch.FindReferencesAction.label"), //$NON-NLS-1$ CSearchMessages.getString("CSearch.FindReferencesAction.tooltip")); //$NON-NLS-1$ } - /** - * @param editor - * @param string - * @param string2 - * @param string3 - */ + public FindRefsAction(CEditor editor, String label, String tooltip) { super(editor); setText(label); //$NON-NLS-1$ setToolTipText(tooltip); //$NON-NLS-1$ } - /** - * @param site - * @param string - * @param string2 - * @param string3 - */ + public FindRefsAction(IWorkbenchSite site, String label, String tooltip) { super(site); setText(label); setToolTipText(tooltip); } - /* (non-Javadoc) - * @see org.eclipse.cdt.internal.ui.editor.selsearch.FindAction#getScopeDescription() - */ protected String getScopeDescription() { return CSearchMessages.getString("WorkspaceScope"); //$NON-NLS-1$ } - /* (non-Javadoc) - * @see org.eclipse.cdt.internal.ui.editor.selsearch.FindAction#getScope(org.eclipse.core.resources.IProject) - */ - protected ICSearchScope getScope() { - return SearchEngine.createWorkspaceScope(); + + protected ICElement[] getScope() { + return null; } - /* (non-Javadoc) - * @see org.eclipse.cdt.internal.ui.editor.selsearch.FindAction#getLimitTo() - */ - protected LimitTo getLimitTo() { - return ICSearchConstants.REFERENCES; + + protected int getLimitTo() { + return PDOMSearchQuery.FIND_REFERENCES; } } diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/actions/FindRefsInWorkingSetAction.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/actions/FindRefsInWorkingSetAction.java index 5c1b74faaf6..7adc2a8e7fe 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/actions/FindRefsInWorkingSetAction.java +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/actions/FindRefsInWorkingSetAction.java @@ -10,13 +10,16 @@ *******************************************************************************/ package org.eclipse.cdt.internal.ui.search.actions; -import org.eclipse.cdt.core.search.ICSearchConstants; -import org.eclipse.cdt.core.search.ICSearchScope; -import org.eclipse.cdt.core.search.LimitTo; +import java.util.ArrayList; +import java.util.List; + +import org.eclipse.cdt.core.model.ICElement; import org.eclipse.cdt.internal.ui.editor.CEditor; import org.eclipse.cdt.internal.ui.search.CSearchMessages; -import org.eclipse.cdt.internal.ui.search.CSearchScopeFactory; import org.eclipse.cdt.internal.ui.search.CSearchUtil; +import org.eclipse.cdt.internal.ui.search.PDOMSearchQuery; +import org.eclipse.core.resources.IResource; +import org.eclipse.core.runtime.IAdaptable; import org.eclipse.ui.IWorkbenchSite; import org.eclipse.ui.IWorkingSet; @@ -42,59 +45,41 @@ public class FindRefsInWorkingSetAction extends FindAction { if (workingSets != null) fWorkingSet= workingSets; } - /** - * @param editor - * @param string - * @param string2 - * @param string3 - */ + public FindRefsInWorkingSetAction(CEditor editor, String label, String tooltip) { super(editor); setText(label); //$NON-NLS-1$ setToolTipText(tooltip); //$NON-NLS-1$ } - /** - * @param site - * @param string - * @param string2 - * @param string3 - */ + public FindRefsInWorkingSetAction(IWorkbenchSite site, String label, String tooltip) { super(site); setText(label); //$NON-NLS-1$ setToolTipText(tooltip); //$NON-NLS-1 } - /* (non-Javadoc) - * @see org.eclipse.cdt.internal.ui.editor.selsearch.FindAction#getLimitTo() - */ - protected LimitTo getLimitTo() { - return ICSearchConstants.REFERENCES; + + protected int getLimitTo() { + return PDOMSearchQuery.FIND_REFERENCES; } - /* (non-Javadoc) - * @see org.eclipse.cdt.internal.ui.editor.selsearch.FindAction#getScopeDescription() - */ + protected String getScopeDescription() { return scopeDescription; } - /* (non-Javadoc) - * @see org.eclipse.cdt.internal.ui.editor.selsearch.FindAction#getScope(org.eclipse.core.resources.IProject) - */ - protected ICSearchScope getScope() { - IWorkingSet[] workingSets= null; - if (fWorkingSet == null) { - workingSets= CSearchScopeFactory.getInstance().queryWorkingSets(); - if (workingSets == null) - return null; - } - else { - workingSets = fWorkingSet; + + protected ICElement[] getScope() { + List scope = new ArrayList(); + + for (int i = 0; i < fWorkingSet.length; ++i) { + IAdaptable[] elements = fWorkingSet[i].getElements(); + for (int j = 0; j < elements.length; ++j) { + ICElement element = (ICElement)elements[j].getAdapter(IResource.class); + if (element != null) + scope.add(element); + } } - ICSearchScope scope= CSearchScopeFactory.getInstance().createCSearchScope(workingSets); - scopeDescription = CSearchMessages.getFormattedString("WorkingSetScope", new String[] {CSearchUtil.toString(workingSets)}); //$NON-NLS-1$ - CSearchUtil.updateLRUWorkingSets(workingSets); - - return scope; + scopeDescription = CSearchMessages.getFormattedString("WorkingSetScope", new String[] {CSearchUtil.toString(fWorkingSet)}); //$NON-NLS-1$ + return (ICElement[])scope.toArray(new ICElement[scope.size()]); } - + } diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/actions/FindRefsProjectAction.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/actions/FindRefsProjectAction.java index 22f8791ba92..8af66c7faa3 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/actions/FindRefsProjectAction.java +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/actions/FindRefsProjectAction.java @@ -10,15 +10,14 @@ *******************************************************************************/ package org.eclipse.cdt.internal.ui.search.actions; +import org.eclipse.cdt.core.model.CoreModel; import org.eclipse.cdt.core.model.ICElement; import org.eclipse.cdt.core.model.ICProject; -import org.eclipse.cdt.core.search.ICSearchConstants; -import org.eclipse.cdt.core.search.ICSearchScope; -import org.eclipse.cdt.core.search.LimitTo; -import org.eclipse.cdt.core.search.SearchEngine; import org.eclipse.cdt.internal.ui.editor.CEditor; import org.eclipse.cdt.internal.ui.search.CSearchMessages; -import org.eclipse.cdt.internal.ui.search.CSearchScopeFactory; +import org.eclipse.cdt.internal.ui.search.PDOMSearchQuery; +import org.eclipse.core.resources.IResource; +import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.ui.IWorkbenchSite; @@ -41,46 +40,37 @@ public class FindRefsProjectAction extends FindAction { CSearchMessages.getString("CSearch.FindReferencesProjectAction.label"), //$NON-NLS-1$ CSearchMessages.getString("CSearch.FindReferencesProjectAction.tooltip")); //$NON-NLS-1$ } - /** - * @param site - * @param string - * @param string2 - * @param string3 - */ + public FindRefsProjectAction(IWorkbenchSite site, String label, String tooltip) { super(site); setText(label); setToolTipText(tooltip); } - /* (non-Javadoc) - * @see org.eclipse.cdt.internal.ui.editor.selsearch.FindAction#getScope(org.eclipse.core.resources.IProject) - */ - protected ICSearchScope getScope() { - - ICProject proj = null; - if (fEditor != null){ - proj= fEditor.getInputCElement().getCProject(); + + protected ICElement[] getScope() { + ICProject project = null; + if (fEditor != null) { + project = fEditor.getInputCElement().getCProject(); } else if (fSite != null){ - IStructuredSelection sel = (IStructuredSelection) getSelection(); - return CSearchScopeFactory.getInstance().createEnclosingProjectScope(sel); + ISelection selection = getSelection(); + if (selection instanceof IStructuredSelection) { + Object element = ((IStructuredSelection)selection).getFirstElement(); + if (element instanceof IResource) + project = CoreModel.getDefault().create(((IResource)element).getProject()); + else if (element instanceof ICElement) + project = ((ICElement)element).getCProject(); + } } - ICElement[] element = new ICElement[1]; - element[0]=proj; - return SearchEngine.createCSearchScope(element); + return project != null ? new ICElement[] { project } : null; } - /* (non-Javadoc) - * @see org.eclipse.cdt.internal.ui.editor.selsearch.FindAction#getScopeDescription() - */ + protected String getScopeDescription() { return CSearchMessages.getString("ProjectScope"); //$NON-NLS-1$ } - /* (non-Javadoc) - * @see org.eclipse.cdt.internal.ui.editor.selsearch.FindAction#getLimitTo() - */ - protected LimitTo getLimitTo() { - return ICSearchConstants.REFERENCES; + + protected int getLimitTo() { + return PDOMSearchQuery.FIND_REFERENCES; } - } diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/actions/GroupAction.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/actions/GroupAction.java deleted file mode 100644 index 0e51f3d519f..00000000000 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/actions/GroupAction.java +++ /dev/null @@ -1,40 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -/* - * Created on May 15, 2004 - * - * TODO To change the template for this generated file go to - * Window - Preferences - Java - Code Style - Code Templates - */ -package org.eclipse.cdt.internal.ui.search.actions; - -import org.eclipse.cdt.internal.ui.search.CSearchResultPage; -import org.eclipse.jface.action.Action; - -public class GroupAction extends Action { - private int _grouping; - private CSearchResultPage _page; - - public GroupAction(String label, String tooltip, CSearchResultPage page, int grouping) { - super(label); - setToolTipText(tooltip); - _page= page; - _grouping= grouping; - } - - public void run() { - _page.setGrouping(_grouping); - } - - public int getGrouping() { - return _grouping; - } -} diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/actions/OpenDeclarationsAction.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/actions/OpenDeclarationsAction.java index efa1d7e0b8a..b3ef4982e92 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/actions/OpenDeclarationsAction.java +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/actions/OpenDeclarationsAction.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2005 IBM Corporation and others. + * Copyright (c) 2000, 2006 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -11,47 +11,24 @@ package org.eclipse.cdt.internal.ui.search.actions; -import java.util.Iterator; -import java.util.Set; - -import org.eclipse.cdt.core.CCorePlugin; -import org.eclipse.cdt.core.dom.CDOM; -import org.eclipse.cdt.core.dom.IASTServiceProvider; -import org.eclipse.cdt.core.dom.IPDOM; -import org.eclipse.cdt.core.dom.IASTServiceProvider.UnsupportedDialectException; -import org.eclipse.cdt.core.dom.ast.IASTFileLocation; import org.eclipse.cdt.core.dom.ast.IASTName; import org.eclipse.cdt.core.dom.ast.IASTTranslationUnit; -import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.cdt.core.model.ICProject; +import org.eclipse.cdt.core.dom.ast.IBinding; import org.eclipse.cdt.core.model.ILanguage; import org.eclipse.cdt.core.model.IWorkingCopy; -import org.eclipse.cdt.core.parser.ParserLanguage; -import org.eclipse.cdt.core.parser.ParserUtil; -import org.eclipse.cdt.core.parser.util.ArrayUtil; -import org.eclipse.cdt.core.search.DOMSearchUtil; -import org.eclipse.cdt.core.search.ICSearchConstants; -import org.eclipse.cdt.core.search.IMatch; -import org.eclipse.cdt.core.search.OffsetLocatable; -import org.eclipse.cdt.core.search.SearchEngine; -import org.eclipse.cdt.internal.core.model.CProject; import org.eclipse.cdt.internal.ui.editor.CEditor; import org.eclipse.cdt.internal.ui.editor.CEditorMessages; -import org.eclipse.cdt.internal.ui.util.ExternalEditorInput; import org.eclipse.cdt.ui.CUIPlugin; -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.jface.dialogs.ProgressMonitorDialog; -import org.eclipse.jface.operation.IRunnableWithProgress; -import org.eclipse.ui.texteditor.IUpdate; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.Status; +import org.eclipse.core.runtime.jobs.Job; +import org.eclipse.swt.widgets.Display; -public class OpenDeclarationsAction extends SelectionParseAction implements IUpdate { +public class OpenDeclarationsAction extends SelectionParseAction { public static final IASTName[] BLANK_NAME_ARRAY = new IASTName[0]; - //private String fDialogTitle; - //private String fDialogMessage; - SearchEngine searchEngine = null; + SelSearchNode selNode; /** * Creates a new action with the given editor @@ -61,206 +38,57 @@ public class OpenDeclarationsAction extends SelectionParseAction implements IUpd setText(CEditorMessages.getString("OpenDeclarations.label")); //$NON-NLS-1$ setToolTipText(CEditorMessages.getString("OpenDeclarations.tooltip")); //$NON-NLS-1$ setDescription(CEditorMessages.getString("OpenDeclarations.description")); //$NON-NLS-1$ -// setDialogTitle(CEditorMessages.getString("OpenDeclarations.dialog.title")); //$NON-NLS-1$ -// setDialogMessage(CEditorMessages.getString("OpenDeclarations.dialog.message")); //$NON-NLS-1$ - - searchEngine = new SearchEngine(); } - /* (non-Javadoc) - * @see org.eclipse.jface.action.IAction#run() - */ - public void run() { - final SelSearchNode selNode = getSelectedStringFromEditor(); - - if(selNode == null) { - return; + private class Runner extends Job { + Runner() { + super(CEditorMessages.getString("OpenDeclarations.label")); //$NON-NLS-1$ } - - final Storage storage = new Storage(); - - IRunnableWithProgress runnable = new IRunnableWithProgress() - { - // steps: - // 1- parse and get the best selected name based on the offset/length into that TU - // 2- based on the IASTName selected, find the best declaration of it in the TU - // 3- if no IASTName is found for a declaration, then search the Index - public void run(IProgressMonitor monitor) { + + protected IStatus run(IProgressMonitor monitor) { + try { int selectionStart = selNode.selStart; int selectionLength = selNode.selEnd - selNode.selStart; - - IASTName[] selectedNames = BLANK_NAME_ARRAY; - IASTTranslationUnit tu=null; - ParserLanguage lang=null; - ICElement project=null; - - if (fEditor.getEditorInput() instanceof ExternalEditorInput) { - ExternalEditorInput input = (ExternalEditorInput)fEditor.getEditorInput(); - try { - // get the project for the external editor input's translation unit - project = input.getTranslationUnit(); - while (!(project instanceof ICProject) && project != null) { - project = project.getParent(); - } - - if (project instanceof ICProject) { - IProject p = ((ICProject)project).getProject(); - IPDOM pdom = null; //PDOM.getPDOM(p); - if (pdom != null) - tu = CDOM.getInstance().getASTService().getTranslationUnit( - input.getStorage(), - p, - pdom.getCodeReaderFactory()); - else - tu = CDOM.getInstance().getASTService().getTranslationUnit( - input.getStorage(), - p); - lang = DOMSearchUtil.getLanguage(input.getStorage().getFullPath(), ((ICProject)project).getProject()); - projectName = ((ICProject)project).getElementName(); - } - } catch (UnsupportedDialectException e) { - operationNotAvailable(CSEARCH_OPERATION_OPERATION_UNAVAILABLE_MESSAGE); - return; - } - } else { - // an awful lot of casts goingo on here... - IWorkingCopy workingCopy = (IWorkingCopy)fEditor.getInputCElement(); - IFile resourceFile = (IFile)workingCopy.getResource(); - project = new CProject(null, resourceFile.getProject()); - IPDOM pdom = CCorePlugin.getPDOMManager().getPDOM(workingCopy.getCProject()); - try { - if (pdom != null) { - try { - ILanguage language = workingCopy.getLanguage(); - tu = language.getASTTranslationUnit(workingCopy, - ILanguage.AST_USE_INDEX | - ILanguage.AST_SKIP_INDEXED_HEADERS); - } catch (CoreException e) { - CUIPlugin.getDefault().log(e); - operationNotAvailable(CSEARCH_OPERATION_OPERATION_UNAVAILABLE_MESSAGE); - return; - } - } else - tu = CDOM.getInstance().getASTService().getTranslationUnit( - resourceFile); - } catch (IASTServiceProvider.UnsupportedDialectException e) { - operationNotAvailable(CSEARCH_OPERATION_OPERATION_UNAVAILABLE_MESSAGE); - return; - } - lang = DOMSearchUtil.getLanguageFromFile(resourceFile); - projectName = resourceFile.getProject().getName(); - } - - // step 1 starts here - selectedNames = DOMSearchUtil.getSelectedNamesFrom(tu, selectionStart, selectionLength, lang); - - try { - if (selectedNames.length > 0 && selectedNames[0] != null) { // just right, only one name selected - IASTName searchName = selectedNames[0]; - // step 2 starts here - IASTName[] domNames = DOMSearchUtil.getNamesFromDOM(searchName, ICSearchConstants.DECLARATIONS_DEFINITIONS); - - // make sure the names are clean (fix for 95202) - boolean modified=false; - for(int i=0; i 0 && domNames[0] != null) { - String fileName=null; - int start=0; - int end=0; - - if ( domNames[0].getTranslationUnit() != null ) { - IASTFileLocation location = domNames[0].getFileLocation(); - if( location != null ) - { - fileName = location.getFileName(); - start = location.getNodeOffset(); - end = location.getNodeOffset() + location.getNodeLength(); - } - } - - if (fileName != null) { - storage.setFileName(fileName); - storage.setLocatable(new OffsetLocatable(start,end)); - storage.setResource(ParserUtil.getResourceForFilename( fileName )); - return; - } - } else { - // step 3 starts here - ICElement[] scope = new ICElement[1]; - scope[0] = project; - Set matches = DOMSearchUtil.getMatchesFromSearchEngine(SearchEngine.createCSearchScope(scope), searchName, ICSearchConstants.DECLARATIONS_DEFINITIONS); - - if (matches != null && matches.size() > 0) { - Iterator itr = matches.iterator(); - while(itr.hasNext()) { - Object match = itr.next(); - if (match instanceof IMatch) { - IMatch theMatch = (IMatch)match; - storage.setFileName(theMatch.getLocation().toOSString()); - storage.setLocatable(theMatch.getLocatable()); - storage.setResource(ParserUtil.getResourceForFilename(theMatch.getLocation().toOSString())); - break; + + IWorkingCopy workingCopy = CUIPlugin.getDefault().getWorkingCopyManager().getWorkingCopy(fEditor.getEditorInput()); + if (workingCopy == null) + return Status.CANCEL_STATUS; + + IASTTranslationUnit ast = workingCopy.getLanguage().getASTTranslationUnit(workingCopy, ILanguage.AST_SKIP_ALL_HEADERS | ILanguage.AST_USE_INDEX); + IASTName[] selectedNames = workingCopy.getLanguage().getSelectedNames(ast, selectionStart, selectionLength); + + if (selectedNames.length > 0 && selectedNames[0] != null) { // just right, only one name selected + IASTName searchName = selectedNames[0]; + + IBinding binding = searchName.resolveBinding(); + if (binding != null) { + final IASTName[] declNames = ast.getDeclarations(binding); + if (declNames.length > 0) { + Display.getDefault().asyncExec(new Runnable() { + public void run() { + try { + open(declNames[0]); + } catch (CoreException e) { + CUIPlugin.getDefault().log(e); } - } - return; - } + }; + }); } } - } catch(Exception e) {} // catch all exceptions from DOM so the indexer can still be tried - - // last try: search the index for the selected string, even if no name was found for that selection - ICElement[] scope = new ICElement[1]; - scope[0] = project; - Set matches = DOMSearchUtil.getMatchesFromSearchEngine( SearchEngine.createCSearchScope(scope), selNode.selText, ICSearchConstants.DECLARATIONS_DEFINITIONS ); - - if (matches != null && matches.size() > 0) { - Iterator itr = matches.iterator(); - while(itr.hasNext()) { - Object match = itr.next(); - if (match instanceof IMatch) { - IMatch theMatch = (IMatch)match; - storage.setFileName(theMatch.getLocation().toOSString()); - storage.setLocatable(theMatch.getLocatable()); - storage.setResource(ParserUtil.getResourceForFilename(theMatch.getLocation().toOSString())); - break; - } - } - } else { - operationNotAvailable(CSEARCH_OPERATION_NO_DECLARATION_MESSAGE); - return; } + + return Status.OK_STATUS; + } catch (CoreException e) { + return e.getStatus(); } - }; - - try { - ProgressMonitorDialog progressMonitor = new ProgressMonitorDialog(getShell()); - progressMonitor.run(true, true, runnable); - - if( storage.getResource() != null ) - { - clearStatusLine(); - open( storage.getResource(), storage.getLocatable() ); - return; - } - String fileName = storage.getFileName(); - - if (fileName != null){ - clearStatusLine(); - open( fileName, storage.getLocatable()); - } - - } catch(Exception x) { - CUIPlugin.getDefault().log(x); } } - + + public void run() { + selNode = getSelectedStringFromEditor(); + if (selNode != null) { + new Runner().schedule(); + } + } } diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/actions/OpenDefinitionAction.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/actions/OpenDefinitionAction.java index e5e0366957b..c155809fe0d 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/actions/OpenDefinitionAction.java +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/actions/OpenDefinitionAction.java @@ -10,48 +10,30 @@ *******************************************************************************/ package org.eclipse.cdt.internal.ui.search.actions; -import java.util.Iterator; -import java.util.Set; - -import org.eclipse.cdt.core.dom.CDOM; -import org.eclipse.cdt.core.dom.IASTServiceProvider; -import org.eclipse.cdt.core.dom.IASTServiceProvider.UnsupportedDialectException; -import org.eclipse.cdt.core.dom.ast.IASTFileLocation; import org.eclipse.cdt.core.dom.ast.IASTName; import org.eclipse.cdt.core.dom.ast.IASTTranslationUnit; -import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.cdt.core.model.ICProject; -import org.eclipse.cdt.core.parser.ParserLanguage; -import org.eclipse.cdt.core.parser.ParserUtil; -import org.eclipse.cdt.core.parser.util.ArrayUtil; -import org.eclipse.cdt.core.search.DOMSearchUtil; -import org.eclipse.cdt.core.search.ICSearchConstants; -import org.eclipse.cdt.core.search.IMatch; -import org.eclipse.cdt.core.search.OffsetLocatable; -import org.eclipse.cdt.core.search.SearchEngine; -import org.eclipse.cdt.internal.core.model.CProject; +import org.eclipse.cdt.core.dom.ast.IBinding; +import org.eclipse.cdt.core.model.ILanguage; +import org.eclipse.cdt.core.model.IWorkingCopy; import org.eclipse.cdt.internal.ui.editor.CEditor; import org.eclipse.cdt.internal.ui.editor.CEditorMessages; -import org.eclipse.cdt.internal.ui.util.ExternalEditorInput; import org.eclipse.cdt.ui.CUIPlugin; -import org.eclipse.core.resources.IFile; +import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.jface.dialogs.ProgressMonitorDialog; -import org.eclipse.jface.operation.IRunnableWithProgress; -import org.eclipse.ui.texteditor.IUpdate; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.Status; +import org.eclipse.core.runtime.jobs.Job; +import org.eclipse.swt.widgets.Display; /** * Open Definition Action (Ctrl+F3). * * @author dsteffle */ -public class OpenDefinitionAction extends SelectionParseAction implements - IUpdate { +public class OpenDefinitionAction extends SelectionParseAction { public static final IASTName[] BLANK_NAME_ARRAY = new IASTName[0]; - //private String fDialogTitle; - //private String fDialogMessage; - SearchEngine searchEngine = null; + SelSearchNode selNode; /** * Creates a new action with the given editor @@ -61,189 +43,57 @@ public class OpenDefinitionAction extends SelectionParseAction implements setText(CEditorMessages.getString("OpenDefinition.label")); //$NON-NLS-1$ setToolTipText(CEditorMessages.getString("OpenDefinition.tooltip")); //$NON-NLS-1$ setDescription(CEditorMessages.getString("OpenDefinition.description")); //$NON-NLS-1$ - - searchEngine = new SearchEngine(); } -// protected void setDialogTitle(String title) { -// fDialogTitle= title; -// } -// -// protected void setDialogMessage(String message) { -// fDialogMessage= message; -// } + private class Runner extends Job { + Runner() { + super(CEditorMessages.getString("OpenDeclarations.label")); //$NON-NLS-1$ + } + + protected IStatus run(IProgressMonitor monitor) { + try { + int selectionStart = selNode.selStart; + int selectionLength = selNode.selEnd - selNode.selStart; + + IWorkingCopy workingCopy = CUIPlugin.getDefault().getWorkingCopyManager().getWorkingCopy(fEditor.getEditorInput()); + if (workingCopy == null) + return Status.CANCEL_STATUS; + + IASTTranslationUnit ast = workingCopy.getLanguage().getASTTranslationUnit(workingCopy, ILanguage.AST_SKIP_ALL_HEADERS | ILanguage.AST_USE_INDEX); + IASTName[] selectedNames = workingCopy.getLanguage().getSelectedNames(ast, selectionStart, selectionLength); + + if (selectedNames.length > 0 && selectedNames[0] != null) { // just right, only one name selected + IASTName searchName = selectedNames[0]; + + IBinding binding = searchName.resolveBinding(); + if (binding != null) { + final IASTName[] declNames = ast.getDefinitions(binding); + if (declNames.length > 0) { + Display.getDefault().asyncExec(new Runnable() { + public void run() { + try { + open(declNames[0]); + } catch (CoreException e) { + CUIPlugin.getDefault().log(e); + } + }; + }); + } + } + } + + return Status.OK_STATUS; + } catch (CoreException e) { + return e.getStatus(); + } + } + } + + public void run() { + selNode = getSelectedStringFromEditor(); + if (selNode != null) { + new Runner().schedule(); + } + } - /* (non-Javadoc) - * @see org.eclipse.jface.action.IAction#run() - */ - public void run() { - final SelSearchNode selNode = getSelectedStringFromEditor(); - - if(selNode == null) { - return; - } - - final Storage storage = new Storage(); - - IRunnableWithProgress runnable = new IRunnableWithProgress() - { - // steps: - // 1- parse and get the best selected name based on the offset/length into that TU - // 2- based on the IASTName selected, find the best definition of it in the TU - // 3- if no IASTName is found for a definition, then search the Index - public void run(IProgressMonitor monitor) { - int selectionStart = selNode.selStart; - int selectionLength = selNode.selEnd - selNode.selStart; - - IASTName[] selectedNames = BLANK_NAME_ARRAY; - IASTTranslationUnit tu=null; - ParserLanguage lang=null; - ICElement project=null; - - if (fEditor.getEditorInput() instanceof ExternalEditorInput) { - ExternalEditorInput input = (ExternalEditorInput)fEditor.getEditorInput(); - try { - // get the project for the external editor input's translation unit - project = input.getTranslationUnit(); - while (!(project instanceof ICProject) && project != null) { - project = project.getParent(); - } - - if (project instanceof ICProject) { - tu = CDOM.getInstance().getASTService().getTranslationUnit(input.getStorage(), ((ICProject)project).getProject()); - lang = DOMSearchUtil.getLanguage(input.getStorage().getFullPath(), ((ICProject)project).getProject()); - projectName = ((ICProject)project).getElementName(); - } - } catch (UnsupportedDialectException e) { - operationNotAvailable(CSEARCH_OPERATION_OPERATION_UNAVAILABLE_MESSAGE); - return; - } - } else { - IFile resourceFile = null; - resourceFile = fEditor.getInputFile(); - project = new CProject(null, resourceFile.getProject()); - - try { - tu = CDOM.getInstance().getASTService().getTranslationUnit( - resourceFile, - CDOM.getInstance().getCodeReaderFactory( - CDOM.PARSE_WORKING_COPY_WHENEVER_POSSIBLE)); - } catch (IASTServiceProvider.UnsupportedDialectException e) { - operationNotAvailable(CSEARCH_OPERATION_OPERATION_UNAVAILABLE_MESSAGE); - return; - } - lang = DOMSearchUtil.getLanguageFromFile(resourceFile); - projectName = resourceFile.getProject().getName(); - } - - // step 1 starts here - selectedNames = DOMSearchUtil.getSelectedNamesFrom(tu, selectionStart, selectionLength, lang); - - try { - if (selectedNames.length > 0 && selectedNames[0] != null) { - IASTName searchName = selectedNames[0]; - // step 2 starts here - IASTName[] domNames = DOMSearchUtil.getNamesFromDOM(searchName, ICSearchConstants.DEFINITIONS); - - // make sure the names are clean (fix for 95202) - boolean modified=false; - for(int i=0; i 0 && domNames[0] != null) { - String fileName=null; - int start=0; - int end=0; - - if ( domNames[0].getTranslationUnit() != null ) { - IASTFileLocation location = domNames[0].getFileLocation(); - if (location != null) - { - fileName = location.getFileName(); - start = location.getNodeOffset(); - end = location.getNodeOffset() + location.getNodeLength(); - } - } - - if (fileName != null) { - storage.setFileName(fileName); - storage.setLocatable(new OffsetLocatable(start,end)); - storage.setResource(ParserUtil.getResourceForFilename( fileName )); - return; - } - } else { - // step 3 starts here - ICElement[] scope = new ICElement[1]; - scope[0] = project; - Set matches = DOMSearchUtil.getMatchesFromSearchEngine(SearchEngine.createCSearchScope(scope), searchName, ICSearchConstants.DEFINITIONS); - - if (matches != null && matches.size() > 0) { - Iterator itr = matches.iterator(); - while(itr.hasNext()) { - Object match = itr.next(); - if (match instanceof IMatch) { - IMatch theMatch = (IMatch)match; - storage.setFileName(theMatch.getLocation().toOSString()); - storage.setLocatable(theMatch.getLocatable()); - storage.setResource(ParserUtil.getResourceForFilename(theMatch.getLocation().toOSString())); - break; - } - } - return; - } - } - } - } catch (Exception e) {} // catch all exceptions from DOM so the indexer can still be tried - - // last try: search the index for the selected string, even if no name was found for that selection - ICElement[] scope = new ICElement[1]; - scope[0] = project; - Set matches = DOMSearchUtil.getMatchesFromSearchEngine( SearchEngine.createCSearchScope(scope), selNode.selText, ICSearchConstants.DEFINITIONS ); - - if (matches != null && matches.size() > 0) { - Iterator itr = matches.iterator(); - while(itr.hasNext()) { - Object match = itr.next(); - if (match instanceof IMatch) { - IMatch theMatch = (IMatch)match; - storage.setFileName(theMatch.getLocation().toOSString()); - storage.setLocatable(theMatch.getLocatable()); - storage.setResource(ParserUtil.getResourceForFilename(theMatch.getLocation().toOSString())); - break; - } - } - } else { - operationNotAvailable(CSEARCH_OPERATION_NO_DEFINITION_MESSAGE); - return; - } - } - }; - - try { - ProgressMonitorDialog progressMonitor = new ProgressMonitorDialog(getShell()); - progressMonitor.run(true, true, runnable); - - if( storage.getResource() != null ) - { - clearStatusLine(); - open( storage.getResource(), storage.getLocatable() ); - return; - } - String fileName = storage.getFileName(); - - if (fileName != null){ - clearStatusLine(); - open( fileName, storage.getLocatable() ); - } - } catch(Exception x) { - CUIPlugin.getDefault().log(x); - } - } - } diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/actions/SelectionParseAction.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/actions/SelectionParseAction.java index 272124a923e..cf74218858c 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/actions/SelectionParseAction.java +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/actions/SelectionParseAction.java @@ -14,10 +14,9 @@ package org.eclipse.cdt.internal.ui.search.actions; import java.io.IOException; import org.eclipse.cdt.core.CCorePlugin; -import org.eclipse.cdt.core.model.CModelException; +import org.eclipse.cdt.core.dom.ast.IASTFileLocation; +import org.eclipse.cdt.core.dom.ast.IASTName; import org.eclipse.cdt.core.model.CoreModel; -import org.eclipse.cdt.core.model.ICProject; -import org.eclipse.cdt.core.model.ITranslationUnit; import org.eclipse.cdt.core.model.IWorkingCopy; import org.eclipse.cdt.core.parser.CodeReader; import org.eclipse.cdt.core.parser.IParser; @@ -32,16 +31,14 @@ import org.eclipse.cdt.core.parser.ParserMode; import org.eclipse.cdt.core.parser.ParserUtil; import org.eclipse.cdt.core.parser.ScannerInfo; import org.eclipse.cdt.core.resources.FileStorage; -import org.eclipse.cdt.core.search.ILineLocatable; -import org.eclipse.cdt.core.search.IMatchLocatable; -import org.eclipse.cdt.core.search.IOffsetLocatable; import org.eclipse.cdt.internal.ui.editor.CEditor; +import org.eclipse.cdt.internal.ui.editor.ExternalSearchEditor; import org.eclipse.cdt.internal.ui.search.CSearchMessages; -import org.eclipse.cdt.internal.ui.util.EditorUtility; +import org.eclipse.cdt.internal.ui.util.ExternalEditorInput; import org.eclipse.cdt.ui.CUIPlugin; import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; @@ -52,16 +49,16 @@ import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.ITextSelection; import org.eclipse.jface.viewers.ISelection; -import org.eclipse.swt.widgets.Shell; +import org.eclipse.search.ui.NewSearchUI; +import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IEditorSite; import org.eclipse.ui.IFileEditorInput; import org.eclipse.ui.IViewSite; import org.eclipse.ui.IWorkbenchSite; -import org.eclipse.ui.PartInitException; -import org.eclipse.ui.PlatformUI; -import org.eclipse.ui.texteditor.AbstractTextEditor; +import org.eclipse.ui.ide.IDE; import org.eclipse.ui.texteditor.IDocumentProvider; +import org.eclipse.ui.texteditor.ITextEditor; /** * @author aniefer @@ -551,165 +548,43 @@ public class SelectionParseAction extends Action { return getSelection( (ITextSelection)selection ); } - String projectName = ""; //$NON-NLS-1$ - protected static class Storage - { - private IResource resource; - private String fileName; - private IMatchLocatable locatable; - - public final String getFileName() { - return fileName; - } - public Storage() { - } - public final IResource getResource() { - return resource; - } - public final IMatchLocatable getLocatable() { - return locatable; - } - public void setFileName(String fileName) { - this.fileName = fileName; - } - public void setLocatable(IMatchLocatable locatable) { - this.locatable = locatable; - } - public void setResource(IResource resource) { - this.resource = resource; - } - - } - /** - * @param string - * @param i + * Open the editor on the given name. + * + * @param name */ - protected boolean open(String filename, IMatchLocatable locatable) throws PartInitException, CModelException { - IPath path = new Path( filename ); - IFile file = ResourcesPlugin.getWorkspace().getRoot().getFileForLocation(path); - if( file != null ) - { - open( file, locatable ); - return true; - } - - ICProject cproject = CoreModel.getDefault().getCModel().getCProject( projectName ); - ITranslationUnit unit = CoreModel.getDefault().createTranslationUnitFrom(cproject, path); - if (unit != null) { - setSelectionAtOffset( EditorUtility.openInEditor(unit), locatable ); - return true; - } - - // check the IWorkspaceRoot to see if it knows of any IFiles that are open for the corresponding filename (i.e. linked resources) - IFile[] files = ResourcesPlugin.getWorkspace().getRoot().findFilesForLocation(path); - for(int i=0; i0 && tempendOffset>tempstartOffset){ - try { - //See NOTE above - int endOffset = doc.getLineOffset(tempendOffset-1); - length=endOffset - startOffset; - } catch (BadLocationException e) {} - } - + protected void open(IASTName name) throws CoreException { + IASTFileLocation fileloc = name.getFileLocation(); + int currentOffset = fileloc.getNodeOffset(); + int currentLength = fileloc.getNodeLength(); + + IPath path = new Path(fileloc.getFileName()); + IFile[] files = ResourcesPlugin.getWorkspace().getRoot().findFilesForLocation(path); + if (files.length > 0) { + IEditorPart editor = IDE.openEditor(CUIPlugin.getActivePage(), files[0]); + try { + IMarker marker = files[0].createMarker(NewSearchUI.SEARCH_MARKER); + marker.setAttribute(IMarker.CHAR_START, currentOffset); + marker.setAttribute(IMarker.CHAR_END, currentOffset + currentLength); + IDE.gotoMarker(editor, marker); + marker.delete(); + } catch (CoreException e) { + CUIPlugin.getDefault().log(e); } - try { - ((AbstractTextEditor) part).selectAndReveal(startOffset, length); - } catch (Exception e) {} - } - } -// /** -// * Shows a dialog for resolving an ambigous C element. -// * Utility method that can be called by subclassers. -// */ -// protected IMatch selectCElement(List elements, Shell shell, String title, String message) { -// -// int nResults= elements.size(); -// -// if (nResults == 0) -// return null; -// -// if (nResults == 1) -// return (IMatch) elements.get(0); -// -// -// ElementListSelectionDialog dialog= new ElementListSelectionDialog(shell, new CSearchResultLabelProvider(), false, false); -// dialog.setTitle(title); -// dialog.setMessage(message); -// dialog.setElements(elements); -// -// if (dialog.open() == Window.OK) { -// Object[] selection= dialog.getResult(); -// if (selection != null && selection.length > 0) { -// nResults= selection.length; -// for (int i= 0; i < nResults; i++) { -// Object current= selection[i]; -// if (current instanceof IMatch) -// return (IMatch) current; -// } -// } -// } -// return null; -// } - + } else { + // external file + IEditorInput input = new ExternalEditorInput(new FileStorage(path)); + IEditorPart editor = CUIPlugin.getActivePage().openEditor(input, ExternalSearchEditor.EDITOR_ID); + if (editor instanceof ITextEditor) { + ITextEditor textEditor = (ITextEditor)editor; + textEditor.selectAndReveal(currentOffset, currentLength); + } + } + + } + + public void update() { + setEnabled(getSelectedStringFromEditor() != null); + } - /* (non-Javadoc) - * @see org.eclipse.ui.texteditor.IUpdate#update() - */ - public void update() { - setEnabled(getSelectedStringFromEditor() != null); - } - } diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/actions/SortAction.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/actions/SortAction.java deleted file mode 100644 index 5e7631eb0d3..00000000000 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/actions/SortAction.java +++ /dev/null @@ -1,41 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -/* - * Created on May 14, 2004 - * - * TODO To change the template for this generated file go to - * Window - Preferences - Java - Code Style - Code Templates - */ -package org.eclipse.cdt.internal.ui.search.actions; - -import org.eclipse.cdt.internal.ui.search.CSearchResultPage; -import org.eclipse.jface.action.Action; - -public class SortAction extends Action { - - private int fSortOrder; - private CSearchResultPage fPage; - - public SortAction(String label, CSearchResultPage page, int sortOrder) { - super(label); - fPage= page; - fSortOrder= sortOrder; - } - - public void run() { - fPage.setSortOrder(fSortOrder); - } - - public int getSortOrder() { - return fSortOrder; - } - -} diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/actions/WorkingSetFindAction.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/actions/WorkingSetFindAction.java index 030f3c33aad..3793826322b 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/actions/WorkingSetFindAction.java +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/search/actions/WorkingSetFindAction.java @@ -16,12 +16,8 @@ */ package org.eclipse.cdt.internal.ui.search.actions; -import org.eclipse.cdt.core.search.ICSearchScope; -import org.eclipse.cdt.core.search.LimitTo; +import org.eclipse.cdt.core.model.ICElement; import org.eclipse.cdt.internal.ui.editor.CEditor; -import org.eclipse.jface.text.ITextSelection; -import org.eclipse.jface.viewers.ISelection; -import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.ui.IWorkbenchSite; public class WorkingSetFindAction extends FindAction { @@ -34,49 +30,26 @@ public class WorkingSetFindAction extends FindAction { setText(string); //$NON-NLS-1$ } - /** - * @param site - * @param action - * @param string - */ public WorkingSetFindAction(IWorkbenchSite site,FindAction action, String string) { super(site); this.findAction = action; setText(string); //$NON-NLS-1$ } - /* (non-Javadoc) - * @see org.eclipse.cdt.internal.ui.search.actions.FindAction#getScopeDescription() - */ protected String getScopeDescription() { return findAction.getScopeDescription(); } - /* (non-Javadoc) - * @see org.eclipse.cdt.internal.ui.search.actions.FindAction#getScope(org.eclipse.core.resources.IProject) - */ - protected ICSearchScope getScope() { - // TODO Auto-generated method stub + protected ICElement[] getScope() { return findAction.getScope(); } - /* (non-Javadoc) - * @see org.eclipse.cdt.internal.ui.search.actions.FindAction#getLimitTo() - */ - protected LimitTo getLimitTo() { + protected int getLimitTo() { return findAction.getLimitTo(); } public void run() { - ISelection sel = getSelection(); - - if (sel instanceof IStructuredSelection){ - findAction.run((IStructuredSelection) sel); - } - else if (sel instanceof ITextSelection){ - findAction.run((ITextSelection) sel); - } - + findAction.run(); } } diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/text/c/hover/CSourceHover.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/text/c/hover/CSourceHover.java index ad711b28079..5614d168d50 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/text/c/hover/CSourceHover.java +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/text/c/hover/CSourceHover.java @@ -12,34 +12,20 @@ package org.eclipse.cdt.internal.ui.text.c.hover; import java.io.IOException; -import java.util.Iterator; import java.util.Set; import org.eclipse.cdt.core.model.CModelException; -import org.eclipse.cdt.core.model.CoreModel; import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.cdt.core.model.ICProject; import org.eclipse.cdt.core.model.ISourceReference; -import org.eclipse.cdt.core.model.ITranslationUnit; import org.eclipse.cdt.core.model.IWorkingCopy; import org.eclipse.cdt.core.parser.KeywordSetKey; import org.eclipse.cdt.core.parser.ParserFactory; import org.eclipse.cdt.core.parser.ParserLanguage; -import org.eclipse.cdt.core.search.BasicSearchResultCollector; -import org.eclipse.cdt.core.search.ICSearchConstants; -import org.eclipse.cdt.core.search.ICSearchScope; -import org.eclipse.cdt.core.search.ILineLocatable; -import org.eclipse.cdt.core.search.IMatch; -import org.eclipse.cdt.core.search.IMatchLocatable; -import org.eclipse.cdt.core.search.IOffsetLocatable; -import org.eclipse.cdt.core.search.OrPattern; -import org.eclipse.cdt.core.search.SearchEngine; import org.eclipse.cdt.internal.ui.codemanipulation.StubUtility; import org.eclipse.cdt.internal.ui.text.CCodeReader; import org.eclipse.cdt.internal.ui.util.Strings; import org.eclipse.cdt.ui.CUIPlugin; import org.eclipse.cdt.ui.IWorkingCopyManager; -import org.eclipse.core.resources.IResource; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.Document; import org.eclipse.jface.text.IDocument; @@ -172,75 +158,7 @@ public class CSourceHover extends AbstractCEditorTextHover implements ITextHover return null; if (copy != null) { - try { - BasicSearchResultCollector searchResultCollector = new BasicSearchResultCollector(); - ICProject cproject = copy.getCProject(); - ICSearchScope scope = SearchEngine.createCSearchScope(new ICElement[]{cproject}, true); - OrPattern orPattern = new OrPattern(); - orPattern.addPattern(SearchEngine.createSearchPattern( - name, ICSearchConstants.TYPE, ICSearchConstants.DECLARATIONS, false)); - orPattern.addPattern(SearchEngine.createSearchPattern( - name, ICSearchConstants.TYPE, ICSearchConstants.DEFINITIONS, false)); - orPattern.addPattern(SearchEngine.createSearchPattern( - name, ICSearchConstants.ENUM, ICSearchConstants.DECLARATIONS, false)); - orPattern.addPattern(SearchEngine.createSearchPattern( - name, ICSearchConstants.MACRO, ICSearchConstants.DECLARATIONS, false)); - orPattern.addPattern(SearchEngine.createSearchPattern( - name, ICSearchConstants.VAR, ICSearchConstants.DECLARATIONS, false)); - orPattern.addPattern(SearchEngine.createSearchPattern( - name, ICSearchConstants.FUNCTION, ICSearchConstants.DECLARATIONS, false)); - - SearchEngine searchEngine = new SearchEngine(); - searchEngine.setWaitingPolicy(ICSearchConstants.FORCE_IMMEDIATE_SEARCH); - searchEngine.search(CUIPlugin.getWorkspace(), orPattern, scope, searchResultCollector, true); - - Set set = searchResultCollector.getSearchResults(); - if (set != null && set.size() > 0 ) { - IMatch[] matches = new IMatch[set.size()]; - set.toArray(matches); - IResource resource = matches[0].getResource(); - if (resource != null) { - ICElement celement = CoreModel.getDefault().create(resource); - if (celement instanceof ITranslationUnit) { - ITranslationUnit unit = (ITranslationUnit)celement; - //Check offset type - IMatchLocatable searchLocatable = matches[0].getLocatable(); - int startOffset=0; - int length=0; - if (searchLocatable instanceof IOffsetLocatable){ - startOffset = ((IOffsetLocatable)searchLocatable).getNameStartOffset(); - length = ((IOffsetLocatable)searchLocatable).getNameEndOffset() - startOffset; - } else if (searchLocatable instanceof ILineLocatable){ - int tempstartOffset = ((ILineLocatable)searchLocatable).getStartLine(); - IDocument doc =textViewer.getDocument(); - try { - //NOTE: Subtract 1 from the passed in line number because, even though the editor is 1 based, the line - //resolver doesn't take this into account and is still 0 based - startOffset = doc.getLineOffset(tempstartOffset-1); - length=doc.getLineLength(tempstartOffset-1); - } catch (BadLocationException e) {} - catch (NullPointerException e) {return null;} - - //Check to see if an end offset is provided - int tempendOffset = ((ILineLocatable)searchLocatable).getEndLine(); - //Make sure that there is a real value for the end line - if (tempendOffset>0 && tempendOffset>tempstartOffset){ - try { - //See NOTE above - int endOffset = doc.getLineOffset(tempendOffset-1); - length=endOffset - startOffset; - } catch (BadLocationException e) {} - catch (NullPointerException e) {return null;} - } - - } - - return unit.getBuffer().getText(startOffset, length); - } - } - } - }catch (InterruptedException e) {} - catch (CModelException e) {} + // TODO actually find some matches... } } return null; diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/text/contentassist/CCompletionProcessor.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/text/contentassist/CCompletionProcessor.java deleted file mode 100644 index 9d7fa5cbd63..00000000000 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/text/contentassist/CCompletionProcessor.java +++ /dev/null @@ -1,659 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.internal.ui.text.contentassist; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.Vector; - -import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.cdt.core.model.ITranslationUnit; -import org.eclipse.cdt.core.model.IWorkingCopy; -import org.eclipse.cdt.core.parser.ast.ASTAccessVisibility; -import org.eclipse.cdt.core.parser.ast.IASTCompletionNode; -import org.eclipse.cdt.core.search.BasicSearchMatch; -import org.eclipse.cdt.core.search.BasicSearchResultCollector; -import org.eclipse.cdt.core.search.ICSearchConstants; -import org.eclipse.cdt.core.search.ICSearchScope; -import org.eclipse.cdt.core.search.OrPattern; -import org.eclipse.cdt.core.search.SearchEngine; -import org.eclipse.cdt.internal.corext.template.c.CContextType; -import org.eclipse.cdt.internal.ui.CHelpProviderManager; -import org.eclipse.cdt.internal.ui.CPluginImages; -import org.eclipse.cdt.internal.ui.CUIMessages; -import org.eclipse.cdt.internal.ui.editor.CEditor; -import org.eclipse.cdt.internal.ui.text.CParameterListValidator; -import org.eclipse.cdt.internal.ui.text.template.TemplateEngine; -import org.eclipse.cdt.ui.CUIPlugin; -import org.eclipse.cdt.ui.IFunctionSummary; -import org.eclipse.cdt.ui.IWorkingCopyManager; -import org.eclipse.cdt.ui.text.ICCompletionProposal; -import org.eclipse.cdt.ui.text.ICHelpInvocationContext; -import org.eclipse.core.resources.IProject; -import org.eclipse.jface.preference.IPreferenceStore; -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.ITextViewer; -import org.eclipse.jface.text.contentassist.ContextInformation; -import org.eclipse.jface.text.contentassist.ICompletionProposal; -import org.eclipse.jface.text.contentassist.IContentAssistProcessor; -import org.eclipse.jface.text.contentassist.IContextInformation; -import org.eclipse.jface.text.contentassist.IContextInformationExtension; -import org.eclipse.jface.text.contentassist.IContextInformationValidator; -import org.eclipse.jface.text.templates.TemplateContextType; -import org.eclipse.swt.graphics.Image; -import org.eclipse.ui.IEditorPart; - -/** - * C completion processor. - * @deprecated - */ -public class CCompletionProcessor implements IContentAssistProcessor { - - private static class ContextInformationWrapper implements IContextInformation, IContextInformationExtension { - - private final IContextInformation fContextInformation; - private int fPosition; - - public ContextInformationWrapper(IContextInformation contextInformation) { - fContextInformation= contextInformation; - } - - /* - * @see IContextInformation#getContextDisplayString() - */ - public String getContextDisplayString() { - return fContextInformation.getContextDisplayString(); - } - - /* - * @see IContextInformation#getImage() - */ - public Image getImage() { - return fContextInformation.getImage(); - } - - /* - * @see IContextInformation#getInformationDisplayString() - */ - public String getInformationDisplayString() { - return fContextInformation.getInformationDisplayString(); - } - - /* - * @see IContextInformationExtension#getContextInformationPosition() - */ - public int getContextInformationPosition() { - return fPosition; - } - - public void setContextInformationPosition(int position) { - fPosition= position; - } - } - - protected IWorkingCopyManager fManager; - private CEditor fEditor; - private char[] fProposalAutoActivationSet; - private CCompletionProposalComparator fComparator; - private IContextInformationValidator fValidator; - - private TemplateEngine fTemplateEngine; - - //private boolean fRestrictToMatchingCase; - private boolean fAllowAddIncludes; - - private BasicSearchResultCollector searchResultCollector = null; - private ResultCollector resultCollector = null; - private CompletionEngine completionEngine = null; - - private SearchEngine searchEngine = null; - - IWorkingCopy fCurrentSourceUnit = null; - - private int fCurrentOffset = 0; - private IASTCompletionNode fCurrentCompletionNode = null; - private int fNumberOfComputedResults= 0; - private ITextViewer fTextViewer; - - public CCompletionProcessor(IEditorPart editor) { - fEditor = (CEditor) editor; - fManager= CUIPlugin.getDefault().getWorkingCopyManager(); - // Needed for search - searchResultCollector = new BasicSearchResultCollector (); - resultCollector = new ResultCollector(); - completionEngine = new CompletionEngine(resultCollector); - searchEngine = new SearchEngine(); - searchEngine.setWaitingPolicy( ICSearchConstants.FORCE_IMMEDIATE_SEARCH ); - setupTemplateEngine(); - - //fRestrictToMatchingCase = false; - fAllowAddIncludes = true; - - fComparator = new CCompletionProposalComparator(); - } - - private void setupTemplateEngine() { - TemplateContextType contextType = CUIPlugin.getDefault().getTemplateContextRegistry().getContextType(CContextType.CCONTEXT_TYPE); - if (contextType == null) { - contextType= new CContextType(); - CUIPlugin.getDefault().getTemplateContextRegistry().addContextType(contextType); - } - if (contextType != null) { - fTemplateEngine = new TemplateEngine(contextType); - } - - } - /** - * Tells this processor to order the proposals alphabetically. - * - * @param order true if proposals should be ordered. - */ - public void orderProposalsAlphabetically(boolean order) { - fComparator.setOrderAlphabetically(order); - } - - /** - * @see IContentAssistProcessor#getErrorMessage() - */ - public String getErrorMessage() { - if (fNumberOfComputedResults == 0) { - String errorMsg= resultCollector.getErrorMessage(); - if (errorMsg == null || errorMsg.length() == 0) - errorMsg= CUIMessages.getString("CEditor.contentassist.noCompletions"); //$NON-NLS-1$ - return errorMsg; - } - - return resultCollector.getErrorMessage(); - } - - /** - * @see IContentAssistProcessor#getContextInformationValidator() - */ - public IContextInformationValidator getContextInformationValidator() { - if(fValidator == null) { - fValidator = new CParameterListValidator(); - } - return fValidator; - } - - /** - * @see IContentAssistProcessor#getContextInformationAutoActivationCharacters() - */ - public char[] getContextInformationAutoActivationCharacters() { - return null; - } - - /** - * @see IContentAssistProcessor#computeContextInformation(ITextViewer, int) - */ - public IContextInformation[] computeContextInformation(ITextViewer viewer, int offset) { - List result= addContextInformations(viewer, offset); - return (IContextInformation[]) result.toArray(new IContextInformation[result.size()]); - } - - private List addContextInformations(ITextViewer viewer, int offset) { - ICompletionProposal[] proposals= internalComputeCompletionProposals(viewer, offset); - - List result= new ArrayList(); - for (int i= 0; i < proposals.length; i++) { - IContextInformation contextInformation= proposals[i].getContextInformation(); - if (contextInformation != null) { - ContextInformationWrapper wrapper= new ContextInformationWrapper(contextInformation); - wrapper.setContextInformationPosition(offset); - result.add(wrapper); - } - } - return result; - } - - /** - * @see IContentAssistProcessor#getCompletionProposalAutoActivationCharacters() - */ - public char[] getCompletionProposalAutoActivationCharacters() { - return fProposalAutoActivationSet; - } - - /** - * Sets this processor's set of characters triggering the activation of the - * completion proposal computation. - * - * @param activationSet the activation set - */ - public void setCompletionProposalAutoActivationCharacters(char[] activationSet) { - fProposalAutoActivationSet = activationSet; - } - - /** - * Tells this processor to restrict is proposals to those - * starting with matching cases. - * - * @param restrict true if proposals should be restricted - */ - public void restrictProposalsToMatchingCases(boolean restrict) { - // not yet supported - } - - /** - * Tells this processor to add include statement for proposals that have - * a fully qualified type name - * - * @param restrict true if import can be added - */ - public void allowAddingIncludes(boolean allowAddingIncludes) { - fAllowAddIncludes = allowAddingIncludes; - } - - /** - * @see IContentAssistProcessor#computeCompletionProposals(ITextViewer, int) - */ - public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int offset) { - return internalComputeCompletionProposals(viewer, offset); - } - - private ICompletionProposal[] internalComputeCompletionProposals(ITextViewer viewer, int offset) { - IWorkingCopy unit = fManager.getWorkingCopy(fEditor.getEditorInput()); - - IDocument document = viewer.getDocument(); - - // check for :: and -> - int pos = offset -1; - if(pos >= 0){ - try{ - if ((document.getChar(pos) == ':') && (document.getChar(pos -1) != ':')) { - // ignore this request - return null; - } else if ((document.getChar(pos) == '>') && (document.getChar(pos - 1) != '-')) { - // ignore this request - return null; - } - } catch ( BadLocationException ex ){ - // ignore this request - return null; - } - } - - ICCompletionProposal[] results = null; - try { - results = evalProposals(document, offset, unit, viewer); - } catch (Exception e) { - CUIPlugin.getDefault().log(e); - } - - fNumberOfComputedResults= (results == null ? 0 : results.length); - - if (results == null) - results = new ICCompletionProposal[0]; - - /* - * Order here and not in result collector to make sure that the order - * applies to all proposals and not just those of the compilation unit. - */ - order(results); - return results; - } - /** - * Order the given proposals. - */ - private ICCompletionProposal[] order(ICCompletionProposal[] proposals) { - if(proposals != null) - Arrays.sort(proposals, fComparator); - return proposals; - } - - /** - * Evaluate the actual proposals for C - */ - public ICCompletionProposal[] evalProposals(IDocument document, int documentOffset, IWorkingCopy unit, ITextViewer viewer) { - // setup the global variables - fCurrentOffset = documentOffset; - fCurrentSourceUnit = unit; - fTextViewer = viewer; - - final List completions = new Vector(); - - if (fCurrentSourceUnit == null) - return null; - - // clear the completion list at the result collector - resultCollector.reset(viewer); - - fCurrentCompletionNode = addProposalsFromModel(completions); - if (fCurrentCompletionNode != null) { - addProposalsFromSearch(fCurrentCompletionNode, completions); - addProposalsFromCompletionContributors(fCurrentCompletionNode, completions); - addProposalsFromTemplates(viewer, fCurrentCompletionNode, completions); - removeRepeatedProposals(completions); - return order( (ICCompletionProposal[]) completions.toArray(new ICCompletionProposal[0])); - } - return null; - } - - /** - * Removes duplicated proposals. - * @param completions Completions to check. - */ - private void removeRepeatedProposals(List completions) { - final int size = completions.size(); - final ICompletionProposal[] proposalsToCheck = (ICCompletionProposal[]) completions.toArray(new ICCompletionProposal[size]); - for (int i = 0; i < size; i++) { - for (int j = i + 1; j < size; j++) { - if (proposalsToCheck[i].equals(proposalsToCheck[j])) { - completions.remove(proposalsToCheck[j]); - break; - } - } - } - } - - private void addProposalsFromTemplates(ITextViewer viewer, IASTCompletionNode completionNode, List completions){ - if (completionNode == null) - return; - - if (viewer == null) - return; - - IASTCompletionNode.CompletionKind kind = completionNode.getCompletionKind(); - - -// if ((kind == IASTCompletionNode.CompletionKind.VARIABLE_TYPE) || -// (kind == IASTCompletionNode.CompletionKind.CLASS_REFERENCE) -// || (kind == IASTCompletionNode.CompletionKind.SINGLE_NAME_REFERENCE)) { - addProposalsFromTemplateEngine(viewer, fTemplateEngine, completions); -// } - } - - private void addProposalsFromTemplateEngine(ITextViewer viewer, TemplateEngine fTemplateEngine, List completions){ - if (fTemplateEngine != null) { - try { - fTemplateEngine.reset(); - fTemplateEngine.complete(viewer, fCurrentOffset, fCurrentSourceUnit); - } catch (Exception x) { - CUIPlugin.getDefault().log(x); - } - completions.addAll(fTemplateEngine.getResults()); - } - } - - private void addProposalsFromCompletionContributors(IASTCompletionNode completionNode, List completions) { - if(completionNode == null) - return; - String prefix = completionNode.getCompletionPrefix(); - int offset = fCurrentOffset - prefix.length(); - int length = prefix.length(); - - // calling functions should happen only within the context of a code body - if (completionNode.getCompletionContext() != null) - return; - - IFunctionSummary[] summary; - - ICHelpInvocationContext context = new ICHelpInvocationContext() { - - public IProject getProject() { - return fCurrentSourceUnit.getCProject().getProject(); - } - - public ITranslationUnit getTranslationUnit() { - return fCurrentSourceUnit; - } - }; - summary = CHelpProviderManager.getDefault().getMatchingFunctions(context, prefix); - if(summary == null) { - return; - } - - for (int i = 0; i < summary.length; i++) { - String fname = summary[i].getName() + "()"; //$NON-NLS-1$ - String fdesc = summary[i].getDescription(); - IFunctionSummary.IFunctionPrototypeSummary fproto = summary[i].getPrototype(); - String fargs = fproto.getArguments(); - - CCompletionProposal proposal; - proposal = new CCompletionProposal(fname, - offset, - length, - CPluginImages.get(CPluginImages.IMG_OBJS_FUNCTION), - fproto.getPrototypeString(true), - 2, - fTextViewer); - - if(fdesc != null) { - proposal.setAdditionalProposalInfo(fdesc); - } - - if(fargs != null && fargs.length() > 0) { - proposal.setContextInformation(new ContextInformation(fname, fargs)); - // set the cursor before the closing bracket - proposal.setCursorPosition(fname.length() - 1); - } - - completions.add(proposal); - } - } - -// private FunctionPrototypeSummary getPrototype (BasicSearchMatch match) { -// switch(match.getElementType()){ -// case ICElement.C_FUNCTION: -// case ICElement.C_FUNCTION_DECLARATION: -// case ICElement.C_METHOD: -// case ICElement.C_METHOD_DECLARATION: -// { -// return (new FunctionPrototypeSummary ( match.getReturnType() + " " + match.getName() )); //$NON-NLS-1$ -// } -// default: -// return null; -// } -// } - - - private IASTCompletionNode addProposalsFromModel(List completions){ - //invoke the completion engine - IASTCompletionNode completionNode = completionEngine.complete(fCurrentSourceUnit, fCurrentOffset); - return completionNode; - } - - private void addProposalsFromSearch (IASTCompletionNode completionNode, List completions) { - if(completionNode == null) - return; - String prefix = completionNode.getCompletionPrefix(); - int offset = fCurrentOffset - prefix.length(); - int length = prefix.length(); - - String searchPrefix = prefix + "*"; //$NON-NLS-1$ - - // figure out the search scope - IPreferenceStore store = CUIPlugin.getDefault().getPreferenceStore(); - //boolean fileScope = store.getBoolean(ContentAssistPreference.CURRENT_FILE_SEARCH_SCOPE); - boolean projectScope = store.getBoolean(ContentAssistPreference.PROJECT_SEARCH_SCOPE); - ICSearchScope scope = null; - - if ( (projectScope) - && ( (completionNode.getCompletionKind() == IASTCompletionNode.CompletionKind.SINGLE_NAME_REFERENCE) - || (completionNode.getCompletionKind() == IASTCompletionNode.CompletionKind.SINGLE_NAME_REFERENCE) - || (completionNode.getCompletionKind() == IASTCompletionNode.CompletionKind.VARIABLE_TYPE) - || (completionNode.getCompletionKind() == IASTCompletionNode.CompletionKind.FIELD_TYPE) ) - && (prefix.length() > 0)){ - List elementsFound = new LinkedList(); - - ICElement[] projectScopeElement = new ICElement[1]; - projectScopeElement[0] = fCurrentSourceUnit.getCProject(); - scope = SearchEngine.createCSearchScope(projectScopeElement, true); - - // search for global variables, functions, classes, structs, unions, enums, macros, and namespaces - OrPattern orPattern = new OrPattern(); - orPattern.addPattern(SearchEngine.createSearchPattern( - searchPrefix, ICSearchConstants.TYPE, ICSearchConstants.DECLARATIONS, false )); - orPattern.addPattern(SearchEngine.createSearchPattern( - searchPrefix, ICSearchConstants.ENUM, ICSearchConstants.DECLARATIONS, false )); - orPattern.addPattern(SearchEngine.createSearchPattern( - searchPrefix, ICSearchConstants.MACRO, ICSearchConstants.DECLARATIONS, false )); - orPattern.addPattern(SearchEngine.createSearchPattern( - searchPrefix, ICSearchConstants.NAMESPACE, ICSearchConstants.DEFINITIONS, false )); - - if( (completionNode.getCompletionKind() == IASTCompletionNode.CompletionKind.SINGLE_NAME_REFERENCE) - || (completionNode.getCompletionKind() == IASTCompletionNode.CompletionKind.SINGLE_NAME_REFERENCE)){ - orPattern.addPattern(SearchEngine.createSearchPattern( - searchPrefix, ICSearchConstants.VAR, ICSearchConstants.DECLARATIONS, false )); - orPattern.addPattern(SearchEngine.createSearchPattern( - searchPrefix, ICSearchConstants.FUNCTION, ICSearchConstants.DEFINITIONS, false )); - orPattern.addPattern(SearchEngine.createSearchPattern( - searchPrefix, ICSearchConstants.FUNCTION, ICSearchConstants.DECLARATIONS, false )); - } - try { - searchEngine.search(CUIPlugin.getWorkspace(), orPattern, scope, searchResultCollector, true); - } catch (InterruptedException e) { - } - elementsFound.addAll(searchResultCollector.getSearchResults()); - - sendResultsToCollector(elementsFound.iterator(), offset, length, prefix ); - } - - completions.addAll(resultCollector.getCompletions()); - - } - - private void sendResultsToCollector(Iterator results , int completionStart, int completionLength, String prefix){ - while (results.hasNext()){ - ASTAccessVisibility visibility; - - BasicSearchMatch match = (BasicSearchMatch)results.next(); - int type = match.getElementType(); - int relevance = completionEngine.computeRelevance(type, prefix, match.getName()); - switch (type){ - case ICElement.C_FIELD: - switch (match.getVisibility()){ - case ICElement.CPP_PUBLIC: - visibility = ASTAccessVisibility.PUBLIC; - break; - case ICElement.CPP_PROTECTED: - visibility = ASTAccessVisibility.PROTECTED; - break; - default: - visibility = ASTAccessVisibility.PRIVATE; - break; - } - resultCollector.acceptField( - match.getName(), - match.getReturnType(), - visibility, - completionStart, - completionLength, - relevance); - break; - - case ICElement.C_VARIABLE: - case ICElement.C_VARIABLE_DECLARATION: - resultCollector.acceptVariable( - match.getName(), - match.getReturnType(), - completionStart, - completionLength, - relevance); - break; - case ICElement.C_METHOD: - case ICElement.C_METHOD_DECLARATION: - switch (match.getVisibility()){ - case ICElement.CPP_PUBLIC: - visibility = ASTAccessVisibility.PUBLIC; - break; - case ICElement.CPP_PROTECTED: - visibility = ASTAccessVisibility.PROTECTED; - break; - default: - visibility = ASTAccessVisibility.PRIVATE; - break; - } - resultCollector.acceptMethod( - match.getName(), - null, - match.getReturnType(), - visibility, - completionStart, - completionLength, - relevance, true, completionStart); - break; - case ICElement.C_FUNCTION: - case ICElement.C_FUNCTION_DECLARATION: - resultCollector.acceptFunction( - match.getName(), - null, - match.getReturnType(), - completionStart, - completionLength, - relevance, true, completionStart); - break; - case ICElement.C_CLASS: - resultCollector.acceptClass( - match.getName(), - completionStart, - completionLength, - relevance); - break; - case ICElement.C_STRUCT: - resultCollector.acceptStruct( - match.getName(), - completionStart, - completionLength, - relevance); - break; - case ICElement.C_UNION: - resultCollector.acceptUnion( - match.getName(), - completionStart, - completionLength, - relevance); - break; - case ICElement.C_NAMESPACE: - resultCollector.acceptNamespace( - match.getName(), - completionStart, - completionLength, - relevance); - break; - case ICElement.C_MACRO: - resultCollector.acceptMacro( - match.getName(), - completionStart, - completionLength, - relevance, completionStart); - break; - case ICElement.C_ENUMERATION: - resultCollector.acceptEnumeration( - match.getName(), - completionStart, - completionLength, - relevance); - break; - case ICElement.C_ENUMERATOR: - resultCollector.acceptEnumerator( - match.getName(), - completionStart, - completionLength, - relevance); - break; - default : - break; - } // end switch - } // end while - } - /** - * @return Returns the fCurrentCompletionNode. - * This method is added for JUnit tests. - */ - public IASTCompletionNode getCurrentCompletionNode() { - return fCurrentCompletionNode; - } - -} diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/viewsupport/ProblemsLabelDecorator.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/viewsupport/ProblemsLabelDecorator.java index d51151845c1..7d9e4acee51 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/viewsupport/ProblemsLabelDecorator.java +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/viewsupport/ProblemsLabelDecorator.java @@ -15,12 +15,12 @@ import org.eclipse.cdt.core.model.ICElement; import org.eclipse.cdt.core.model.ISourceRange; import org.eclipse.cdt.core.model.ISourceReference; import org.eclipse.cdt.core.model.ITranslationUnit; -import org.eclipse.cdt.internal.corext.refactoring.ListenerList; import org.eclipse.cdt.internal.ui.CPluginImages; import org.eclipse.cdt.internal.ui.util.IProblemChangedListener; import org.eclipse.cdt.internal.ui.util.ImageDescriptorRegistry; import org.eclipse.cdt.ui.CElementImageDescriptor; import org.eclipse.cdt.ui.CUIPlugin; +import org.eclipse.core.internal.runtime.ListenerList; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IResource; diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/viewsupport/StatusBarUpdater.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/viewsupport/StatusBarUpdater.java index 5b34ba3b991..2691a302c85 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/viewsupport/StatusBarUpdater.java +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/viewsupport/StatusBarUpdater.java @@ -11,13 +11,10 @@ package org.eclipse.cdt.internal.ui.viewsupport; -import org.eclipse.cdt.core.browser.ITypeInfo; import org.eclipse.cdt.core.model.ICElement; import org.eclipse.cdt.internal.ui.CUIMessages; -import org.eclipse.cdt.ui.browser.typeinfo.TypeInfoLabelProvider; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IResource; - import org.eclipse.jface.action.IStatusLineManager; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; @@ -34,8 +31,6 @@ public class StatusBarUpdater implements ISelectionChangedListener { CElementLabels.M_PARAMETER_TYPES | CElementLabels.M_PARAMETER_NAMES | CElementLabels.M_APP_RETURNTYPE | CElementLabels.M_EXCEPTIONS | CElementLabels.F_APP_TYPE_SIGNATURE; - private final TypeInfoLabelProvider fTypeInfoLabelProvider = new TypeInfoLabelProvider(TypeInfoLabelProvider.SHOW_FULLY_QUALIFIED + TypeInfoLabelProvider.SHOW_PATH); - private IStatusLineManager fStatusLineManager; public StatusBarUpdater(IStatusLineManager statusLineManager) { @@ -62,8 +57,6 @@ public class StatusBarUpdater implements ISelectionChangedListener { Object elem= selection.getFirstElement(); if (elem instanceof ICElement) { return formatCElementMessage((ICElement) elem); - } else if (elem instanceof ITypeInfo) { - return formatTypeInfoMessage((ITypeInfo) elem); } else if (elem instanceof IResource) { return formatResourceMessage((IResource) elem); } @@ -75,10 +68,6 @@ public class StatusBarUpdater implements ISelectionChangedListener { return CElementLabels.getElementLabel(element, LABEL_FLAGS); } - private String formatTypeInfoMessage(ITypeInfo info) { - return fTypeInfoLabelProvider.getText(info); - } - private String formatResourceMessage(IResource element) { IContainer parent= element.getParent(); if (parent != null && parent.getType() != IResource.ROOT) diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/wizards/classwizard/BaseClassInfo.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/wizards/classwizard/BaseClassInfo.java index 38f3c76259a..f7611e94afe 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/wizards/classwizard/BaseClassInfo.java +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/wizards/classwizard/BaseClassInfo.java @@ -10,26 +10,19 @@ *******************************************************************************/ package org.eclipse.cdt.internal.ui.wizards.classwizard; -import org.eclipse.cdt.core.browser.ITypeInfo; import org.eclipse.cdt.core.parser.ast.ASTAccessVisibility; public class BaseClassInfo implements IBaseClassInfo { - private ITypeInfo fType; private ASTAccessVisibility fAccess; private boolean fIsVirtual; - public BaseClassInfo(ITypeInfo type, ASTAccessVisibility access, boolean isVirtual) { - fType = type; + public BaseClassInfo(ASTAccessVisibility access, boolean isVirtual) { fAccess = access; fIsVirtual = isVirtual; } - public ITypeInfo getType() { - return fType; - } - public ASTAccessVisibility getAccess() { return fAccess; } diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/wizards/classwizard/BaseClassesLabelProvider.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/wizards/classwizard/BaseClassesLabelProvider.java index 030f72c6411..f75ff8879bd 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/wizards/classwizard/BaseClassesLabelProvider.java +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/wizards/classwizard/BaseClassesLabelProvider.java @@ -11,7 +11,6 @@ package org.eclipse.cdt.internal.ui.wizards.classwizard; import org.eclipse.cdt.core.parser.ast.ASTAccessVisibility; -import org.eclipse.cdt.ui.browser.typeinfo.TypeInfoLabelProvider; import org.eclipse.jface.viewers.ILabelProviderListener; import org.eclipse.jface.viewers.ITableLabelProvider; import org.eclipse.swt.graphics.Image; @@ -37,8 +36,6 @@ public final class BaseClassesLabelProvider implements ITableLabelProvider { return ACCESS_PUBLIC; } - private static TypeInfoLabelProvider fTypeInfoLabelProvider = new TypeInfoLabelProvider(TypeInfoLabelProvider.SHOW_FULLY_QUALIFIED); - /* * @see ITableLabelProvider#getColumnImage(Object, int) */ @@ -47,7 +44,7 @@ public final class BaseClassesLabelProvider implements ITableLabelProvider { return null; IBaseClassInfo info = (IBaseClassInfo) element; - return fTypeInfoLabelProvider.getImage(info.getType()); + return null; //fTypeInfoLabelProvider.getImage(info.getType()); } /* @@ -58,7 +55,7 @@ public final class BaseClassesLabelProvider implements ITableLabelProvider { switch (columnIndex) { case 0: - return fTypeInfoLabelProvider.getText(info.getType()); + return null; //fTypeInfoLabelProvider.getText(info.getType()); case 1: return getAccessText(info.getAccess()); case 2: diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/wizards/classwizard/IBaseClassInfo.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/wizards/classwizard/IBaseClassInfo.java index 8c80b88ddb9..ee658e6874b 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/wizards/classwizard/IBaseClassInfo.java +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/wizards/classwizard/IBaseClassInfo.java @@ -10,12 +10,10 @@ *******************************************************************************/ package org.eclipse.cdt.internal.ui.wizards.classwizard; -import org.eclipse.cdt.core.browser.ITypeInfo; import org.eclipse.cdt.core.parser.ast.ASTAccessVisibility; public interface IBaseClassInfo { - public ITypeInfo getType(); public ASTAccessVisibility getAccess(); public boolean isVirtual(); diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/wizards/classwizard/NewBaseClassSelectionDialog.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/wizards/classwizard/NewBaseClassSelectionDialog.java index 4e648bf5d92..15b3a3f7e3d 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/wizards/classwizard/NewBaseClassSelectionDialog.java +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/wizards/classwizard/NewBaseClassSelectionDialog.java @@ -11,19 +11,13 @@ package org.eclipse.cdt.internal.ui.wizards.classwizard; import java.util.ArrayList; -import java.util.Iterator; import java.util.List; -import org.eclipse.cdt.core.browser.ITypeInfo; import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.cdt.internal.ui.dialogs.StatusInfo; import org.eclipse.cdt.ui.browser.typeinfo.TypeSelectionDialog; -import org.eclipse.core.runtime.IStatus; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Shell; -import org.eclipse.ui.PlatformUI; -import org.eclipse.ui.progress.IProgressService; public class NewBaseClassSelectionDialog extends TypeSelectionDialog { @@ -34,7 +28,6 @@ public class NewBaseClassSelectionDialog extends TypeSelectionDialog { private List fTypeListeners; public interface ITypeSelectionListener { - void typeAdded(ITypeInfo baseClass); } public NewBaseClassSelectionDialog(Shell parent) { @@ -58,19 +51,6 @@ public class NewBaseClassSelectionDialog extends TypeSelectionDialog { fTypeListeners.remove(listener); } - private void notifyTypeAddedListeners(ITypeInfo type) { - // first copy listeners in case one calls removeListener - List list = new ArrayList(fTypeListeners); - for (Iterator i = list.iterator(); i.hasNext(); ) { - ITypeSelectionListener listener = (ITypeSelectionListener) i.next(); - listener.typeAdded(type); - } - } - - public ITypeInfo[] getAddedTypes() { - return (ITypeInfo[])fTypeList.toArray(new ITypeInfo[fTypeList.size()]); - } - /* * @see Dialog#createButtonsForButtonBar */ @@ -98,61 +78,6 @@ public class NewBaseClassSelectionDialog extends TypeSelectionDialog { } private void addType(Object elem) { - if (elem instanceof ITypeInfo) { - ITypeInfo type = (ITypeInfo)elem; - if (fTypeList.contains(type)) { - String qualifiedName = type.getQualifiedTypeName().getFullyQualifiedName(); - String message = NewClassWizardMessages.getFormattedString("NewBaseClassSelectionDialog.classalreadyadded.info", qualifiedName); //$NON-NLS-1$ - updateStatus(new StatusInfo(IStatus.INFO, message)); - } else { - String qualifiedName = type.getQualifiedTypeName().getFullyQualifiedName(); - String message = NewClassWizardMessages.getFormattedString("NewBaseClassSelectionDialog.addingclass.info", qualifiedName); //$NON-NLS-1$ - updateStatus(new StatusInfo(IStatus.INFO, message)); - - boolean canAdd = true; - if (verifyBaseClasses()) { - IProgressService service = PlatformUI.getWorkbench().getProgressService(); - NewClassWizardUtil.resolveClassLocation(type, service); - canAdd = (type.getResolvedReference() != null); - } - -// // resolve location of base class -// if (type.getResolvedReference() == null) { -// final ITypeInfo[] typesToResolve = new ITypeInfo[] { type }; -// IRunnableWithProgress runnable = new IRunnableWithProgress() { -// public void run(IProgressMonitor progressMonitor) throws InvocationTargetException, InterruptedException { -// AllTypesCache.resolveTypeLocation(typesToResolve[0], progressMonitor); -// if (progressMonitor.isCanceled()) { -// throw new InterruptedException(); -// } -// } -// }; -// -// IProgressService service = PlatformUI.getWorkbench().getProgressService(); -// try { -// service.busyCursorWhile(runnable); -// } catch (InvocationTargetException e) { -// String title= NewClassWizardMessages.getString("NewBaseClassSelectionDialog.getClasses.exception.title"); //$NON-NLS-1$ -// String errorMessage= NewClassWizardMessages.getString("NewBaseClassSelectionDialog.getClasses.exception.message"); //$NON-NLS-1$ -// ExceptionHandler.handle(e, title, errorMessage); -// } catch (InterruptedException e) { -// // cancelled by user -// } -// } - - if (canAdd) { - fTypeList.add(type); - - message = NewClassWizardMessages.getFormattedString("NewBaseClassSelectionDialog.classadded.info", qualifiedName); //$NON-NLS-1$ - updateStatus(new StatusInfo(IStatus.INFO, message)); - - notifyTypeAddedListeners(type); - } else { - message = NewClassWizardMessages.getFormattedString("NewBaseClassSelectionDialog.error.classnotadded", qualifiedName); //$NON-NLS-1$ - updateStatus(new StatusInfo(IStatus.ERROR, message)); - } - } - } } /** diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/wizards/classwizard/NewClassCodeGenerator.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/wizards/classwizard/NewClassCodeGenerator.java index e864b3987c1..a643b05c76b 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/wizards/classwizard/NewClassCodeGenerator.java +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/wizards/classwizard/NewClassCodeGenerator.java @@ -15,9 +15,6 @@ import java.util.Iterator; import java.util.List; import org.eclipse.cdt.core.CCorePlugin; -import org.eclipse.cdt.core.browser.IQualifiedTypeName; -import org.eclipse.cdt.core.browser.ITypeReference; -import org.eclipse.cdt.core.browser.QualifiedTypeName; import org.eclipse.cdt.core.model.CModelException; import org.eclipse.cdt.core.model.CoreModel; import org.eclipse.cdt.core.model.ICContainer; @@ -27,6 +24,8 @@ import org.eclipse.cdt.core.model.IIncludeEntry; import org.eclipse.cdt.core.model.IPathEntry; import org.eclipse.cdt.core.model.ITranslationUnit; import org.eclipse.cdt.core.model.IWorkingCopy; +import org.eclipse.cdt.core.model.util.IQualifiedTypeName; +import org.eclipse.cdt.core.model.util.QualifiedTypeName; import org.eclipse.cdt.core.parser.IScannerInfo; import org.eclipse.cdt.core.parser.IScannerInfoProvider; import org.eclipse.cdt.core.parser.ast.ASTAccessVisibility; @@ -386,22 +385,22 @@ public class NewClassCodeGenerator { if (fBaseClasses != null && fBaseClasses.length > 0) { text.append(" : "); //$NON-NLS-1$ for (int i = 0; i < fBaseClasses.length; ++i) { - IBaseClassInfo baseClass = fBaseClasses[i]; - String baseClassName = baseClass.getType().getQualifiedTypeName().getFullyQualifiedName(); - if (i > 0) - text.append(", "); //$NON-NLS-1$ - if (baseClass.getAccess() == ASTAccessVisibility.PRIVATE) - text.append("private"); //$NON-NLS-1$ - else if (baseClass.getAccess() == ASTAccessVisibility.PROTECTED) - text.append("private"); //$NON-NLS-1$ - else - text.append("public"); //$NON-NLS-1$ - text.append(' '); - - if (baseClass.isVirtual()) - text.append("virtual "); //$NON-NLS-1$ - - text.append(baseClassName); +// IBaseClassInfo baseClass = fBaseClasses[i]; +// String baseClassName = baseClass.getType().getQualifiedTypeName().getFullyQualifiedName(); +// if (i > 0) +// text.append(", "); //$NON-NLS-1$ +// if (baseClass.getAccess() == ASTAccessVisibility.PRIVATE) +// text.append("private"); //$NON-NLS-1$ +// else if (baseClass.getAccess() == ASTAccessVisibility.PROTECTED) +// text.append("private"); //$NON-NLS-1$ +// else +// text.append("public"); //$NON-NLS-1$ +// text.append(' '); +// +// if (baseClass.isVirtual()) +// text.append("virtual "); //$NON-NLS-1$ +// +// text.append(baseClassName); } } } @@ -624,20 +623,20 @@ public class NewClassCodeGenerator { private List getBaseClassPaths(boolean verifyLocation) throws CodeGeneratorException { List list = new ArrayList(); for (int i = 0; i < fBaseClasses.length; ++i) { - IBaseClassInfo baseClass = fBaseClasses[i]; - ITypeReference ref = baseClass.getType().getResolvedReference(); - IPath baseClassLocation = null; - if (ref != null) { - baseClassLocation = ref.getLocation(); - } - - if (baseClassLocation == null) { - if (verifyLocation) { - throw new CodeGeneratorException("Could not find base class " + baseClass.toString()); //$NON-NLS-1$ - } - } else if (!list.contains(baseClassLocation)) { - list.add(baseClassLocation); - } +// IBaseClassInfo baseClass = fBaseClasses[i]; +// ITypeReference ref = baseClass.getType().getResolvedReference(); +// IPath baseClassLocation = null; +// if (ref != null) { +// baseClassLocation = ref.getLocation(); +// } +// +// if (baseClassLocation == null) { +// if (verifyLocation) { +// throw new CodeGeneratorException("Could not find base class " + baseClass.toString()); //$NON-NLS-1$ +// } +// } else if (!list.contains(baseClassLocation)) { +// list.add(baseClassLocation); +// } } return list; } diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/wizards/classwizard/NewClassWizardUtil.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/wizards/classwizard/NewClassWizardUtil.java index 3e65de0cff8..7eaaf1780ef 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/wizards/classwizard/NewClassWizardUtil.java +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/wizards/classwizard/NewClassWizardUtil.java @@ -10,40 +10,22 @@ *******************************************************************************/ package org.eclipse.cdt.internal.ui.wizards.classwizard; -import java.lang.reflect.InvocationTargetException; -import java.util.ArrayList; -import java.util.List; - -import org.eclipse.cdt.core.CCorePlugin; -import org.eclipse.cdt.core.browser.AllTypesCache; -import org.eclipse.cdt.core.browser.ITypeInfo; -import org.eclipse.cdt.core.browser.ITypeReference; -import org.eclipse.cdt.core.browser.ITypeSearchScope; -import org.eclipse.cdt.core.browser.TypeSearchScope; import org.eclipse.cdt.core.model.CModelException; import org.eclipse.cdt.core.model.CoreModel; import org.eclipse.cdt.core.model.ICContainer; import org.eclipse.cdt.core.model.ICElement; import org.eclipse.cdt.core.model.ICProject; import org.eclipse.cdt.core.model.ISourceRoot; -import org.eclipse.cdt.core.parser.IScannerInfo; -import org.eclipse.cdt.core.parser.IScannerInfoProvider; import org.eclipse.cdt.internal.ui.editor.CEditor; -import org.eclipse.cdt.internal.ui.util.ExceptionHandler; import org.eclipse.cdt.internal.ui.viewsupport.IViewPartInputProvider; import org.eclipse.cdt.internal.ui.wizards.filewizard.NewSourceFileGenerator; import org.eclipse.cdt.ui.CUIPlugin; import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.Path; -import org.eclipse.jface.operation.IRunnableContext; -import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IEditorPart; @@ -270,136 +252,5 @@ public class NewClassWizardUtil { public static IWorkspaceRoot getWorkspaceRoot() { return ResourcesPlugin.getWorkspace().getRoot(); } - - /** - * Ensures the type cache is up to date. - * - * @param context the runnable context - */ - public static void prepareTypeCache(IRunnableContext context) { - final ITypeSearchScope scope = new TypeSearchScope(true); - if (!AllTypesCache.isCacheUpToDate(scope)) { - IRunnableWithProgress runnable = new IRunnableWithProgress() { - public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { - AllTypesCache.updateCache(scope, monitor); - if (monitor.isCanceled()) { - throw new InterruptedException(); - } - } - }; - - try { - context.run(true, true, runnable); - } catch (InvocationTargetException e) { - String title = NewClassWizardMessages.getString("NewClassCreationWizardPage.getTypes.exception.title"); //$NON-NLS-1$ - String message = NewClassWizardMessages.getString("NewClassCreationWizardPage.getTypes.exception.message"); //$NON-NLS-1$ - ExceptionHandler.handle(e, title, message); - } catch (InterruptedException e) { - // cancelled by user - } - } - } - /** - * Resolve the location of the given class. - * - * @param type the class to resolve - * @param context the runnable context - * @return the class location, or null if not found - */ - public static ITypeReference resolveClassLocation(ITypeInfo type, IRunnableContext context) { - prepareTypeCache(context); - - // resolve location of base class - if (type.getResolvedReference() == null) { - final ITypeInfo[] typesToResolve = new ITypeInfo[] { type }; - IRunnableWithProgress runnable = new IRunnableWithProgress() { - public void run(IProgressMonitor progressMonitor) throws InvocationTargetException, InterruptedException { - AllTypesCache.resolveTypeLocation(typesToResolve[0], progressMonitor); - if (progressMonitor.isCanceled()) { - throw new InterruptedException(); - } - } - }; - - try { - context.run(true, true, runnable); - } catch (InvocationTargetException e) { - String title = NewClassWizardMessages.getString("NewClassCreationWizardPage.getTypes.exception.title"); //$NON-NLS-1$ - String message = NewClassWizardMessages.getString("NewClassCreationWizardPage.getTypes.exception.message"); //$NON-NLS-1$ - ExceptionHandler.handle(e, title, message); - return null; - } catch (InterruptedException e) { - // cancelled by user - return null; - } - } - return type.getResolvedReference(); - } - - private static final int[] CLASS_TYPES = { ICElement.C_CLASS, ICElement.C_STRUCT }; - - /** - * Returns all classes/structs which are accessible from the include - * paths of the given project. - * - * @param project the given project - * @return array of classes/structs - */ - public static ITypeInfo[] getReachableClasses(IProject project) { - ITypeInfo[] elements = AllTypesCache.getTypes(new TypeSearchScope(true), CLASS_TYPES); - if (elements != null && elements.length > 0) { - if (project != null) { - IScannerInfoProvider provider = CCorePlugin.getDefault().getScannerInfoProvider(project); - if (provider != null) { - //TODO get the scanner info for the actual source folder - IScannerInfo info = provider.getScannerInformation(project); - if (info != null) { - String[] includePaths = info.getIncludePaths(); - List filteredTypes = new ArrayList(); - for (int i = 0; i < elements.length; ++i) { - ITypeInfo baseType = elements[i]; - if (isTypeReachable(baseType, project, includePaths)) { - filteredTypes.add(baseType); - } - } - return (ITypeInfo[]) filteredTypes.toArray(new ITypeInfo[filteredTypes.size()]); - } - } - } - } - return elements; - } - - /** - * Checks whether the given type can be found in the given project or the - * given include paths. - * - * @param type the type - * @param project the project - * @param includePaths the include paths - * @return true if the given type is found - */ - public static boolean isTypeReachable(ITypeInfo type, IProject project, String[] includePaths) { - IProject baseProject = type.getEnclosingProject(); - if (baseProject != null) { - if (baseProject.equals(project)) { - return true; - } - ITypeReference ref = type.getResolvedReference(); - for (int i = 0; i < includePaths.length; ++i) { - IPath includePath = new Path(includePaths[i]); - if (ref != null) { - if (includePath.isPrefixOf(ref.getLocation())) - return true; - } else { - // we don't have the real location, so just check the project path - if (baseProject.getLocation().isPrefixOf(includePath)) - return true; - } - } - } - return false; - } - } diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/ui/CSearchResultLabelProvider.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/ui/CSearchResultLabelProvider.java deleted file mode 100644 index 9e0351184f5..00000000000 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/ui/CSearchResultLabelProvider.java +++ /dev/null @@ -1,265 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2003, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corp. - Rational Software - initial implementation - *******************************************************************************/ -/* - * Created on Jun 18, 2003 - */ -package org.eclipse.cdt.ui; - -import org.eclipse.cdt.core.model.ICElement; -import org.eclipse.cdt.core.search.IMatch; -import org.eclipse.cdt.internal.ui.CPluginImages; -import org.eclipse.cdt.internal.ui.search.CSearchMessages; -import org.eclipse.cdt.internal.ui.search.CSearchResultPage; -import org.eclipse.cdt.internal.ui.search.NewSearchResultCollector; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.runtime.IPath; -import org.eclipse.jface.resource.ImageDescriptor; -import org.eclipse.jface.viewers.LabelProvider; -import org.eclipse.swt.graphics.Image; -import org.eclipse.swt.graphics.Point; - -/** - * @author aniefer - * - * To change the template for this generated type comment go to - * Window>Preferences>Java>Code Generation>Code and Comments - */ -public class CSearchResultLabelProvider extends LabelProvider { - - public static final int SHOW_NAME_ONLY = 0; - public static final int SHOW_ELEMENT_CONTAINER = 1; - public static final int SHOW_CONTAINER_ELEMENT = 2; - public static final int SHOW_PATH = 3;//default - - public static final String POTENTIAL_MATCH = CSearchMessages.getString("CSearchResultLabelProvider.potentialMatch"); //$NON-NLS-1$ - - public CSearchResultLabelProvider(){ - _sortOrder = SHOW_PATH; - } - - /** - * @param page - */ - public CSearchResultLabelProvider(CSearchResultPage page) { - - // TODO Auto-generated constructor stub - } - - public Image getImage( Object element ) { - IMatch match = null; - int elementType = -1; - int visibility = -1; - - if ( element instanceof IMatch ){ - match = (IMatch) element; - if( match == null ) - return null; - elementType = match.getElementType(); - visibility = match.getVisibility(); - } else if (element instanceof ICElement){ - elementType = ((ICElement) element).getElementType(); - } else if (element instanceof String){ - String eleString = (String) element; - int elIndex = eleString.indexOf(NewSearchResultCollector.ELEMENTTYPE); - int vizIndex = eleString.indexOf(NewSearchResultCollector.VISIBILITY); - - String elType = eleString.substring(elIndex+NewSearchResultCollector.ELEMENTTYPE_LENGTH,vizIndex); - String elViz = eleString.substring(vizIndex+NewSearchResultCollector.VISIBILITY_LENGTH,eleString.length()); - - elementType = new Integer(elType).intValue(); - visibility = new Integer(elViz).intValue(); - } else if (element instanceof IPath){ - //External File; use Translation Unit - elementType = ICElement.C_UNIT; - } - - - int flags = 0; - ImageDescriptor imageDescriptor = null; - - switch( elementType ){ - case ICElement.C_PROJECT: imageDescriptor = CPluginImages.DESC_OBJS_SEARCHHIERPROJECT; break; - case ICElement.C_CCONTAINER: imageDescriptor = CPluginImages.DESC_OBJS_SEARCHHIERFODLER; break; - case ICElement.C_CLASS: imageDescriptor = CPluginImages.DESC_OBJS_CLASS; break; - case ICElement.C_STRUCT: imageDescriptor = CPluginImages.DESC_OBJS_STRUCT; break; - case ICElement.C_UNION: imageDescriptor = CPluginImages.DESC_OBJS_UNION; break; - case ICElement.C_NAMESPACE: imageDescriptor = CPluginImages.DESC_OBJS_NAMESPACE; break; - case ICElement.C_ENUMERATION: imageDescriptor = CPluginImages.DESC_OBJS_ENUMERATION; break; - case ICElement.C_MACRO: imageDescriptor = CPluginImages.DESC_OBJS_MACRO; break; - case ICElement.C_FUNCTION: imageDescriptor = CPluginImages.DESC_OBJS_FUNCTION; break; - case ICElement.C_VARIABLE: imageDescriptor = CPluginImages.DESC_OBJS_VARIABLE; break; - case ICElement.C_ENUMERATOR: imageDescriptor = CPluginImages.DESC_OBJS_ENUMERATOR; break; - case ICElement.C_TYPEDEF: imageDescriptor = CPluginImages.DESC_OBJS_TYPEDEF; break; - case ICElement.C_UNIT: imageDescriptor = CPluginImages.DESC_OBJS_TUNIT; break; - case ICElement.C_FIELD: - { - switch( visibility ){ - case ICElement.CPP_PUBLIC: imageDescriptor = CPluginImages.DESC_OBJS_PUBLIC_FIELD; break; - case ICElement.CPP_PRIVATE: imageDescriptor = CPluginImages.DESC_OBJS_PRIVATE_FIELD; break; - default: imageDescriptor = CPluginImages.DESC_OBJS_PROTECTED_FIELD; break; - } - break; - } - case ICElement.C_METHOD: - { - switch( visibility ){ - case ICElement.CPP_PUBLIC: imageDescriptor = CPluginImages.DESC_OBJS_PUBLIC_METHOD; break; - case ICElement.CPP_PRIVATE: imageDescriptor = CPluginImages.DESC_OBJS_PRIVATE_METHOD; break; - default: imageDescriptor = CPluginImages.DESC_OBJS_PROTECTED_METHOD; break; - } - break; - } - - case ICElement.C_TEMPLATE_CLASS:{ - imageDescriptor = CPluginImages.DESC_OBJS_CLASS; - flags |= CElementImageDescriptor.TEMPLATE; - break; - } - - default: - imageDescriptor = CPluginImages.DESC_OBJS_UNKNOWN; - break; - } - - - - if (match != null){ - if( match.isStatic() ) flags |= CElementImageDescriptor.STATIC; - if( match.isConst() ) flags |= CElementImageDescriptor.CONSTANT; - if( match.isVolatile() ) flags |= CElementImageDescriptor.VOLATILE; - } - - imageDescriptor = new CElementImageDescriptor( imageDescriptor, flags, SMALL_SIZE ); - - Image image = CUIPlugin.getImageDescriptorRegistry().get( imageDescriptor ); - - return image; - } - - public String getText( Object element ) { - IMatch match = null; - - if( element instanceof IMatch ){ - match = (IMatch) element; - } else if ( element instanceof ICElement){ - return getElementText((ICElement) element); - } else if (element instanceof String){ - String elString = (String) element; - - int parentIndex = elString.indexOf(NewSearchResultCollector.PARENT); - int nameIndex = elString.indexOf(NewSearchResultCollector.NAME); - int locationIndex = elString.indexOf(NewSearchResultCollector.LOCATION); - int elementIndex = elString.indexOf(NewSearchResultCollector.ELEMENTTYPE); - - String elParent = elString.substring(parentIndex+NewSearchResultCollector.PARENT_LENGTH,nameIndex); - String elName = elString.substring(nameIndex+NewSearchResultCollector.NAME_LENGTH,locationIndex); - String elPath = elString.substring(locationIndex+NewSearchResultCollector.LOCATION_LENGTH, elementIndex); - - return getCSearchSortElementText(elParent, elName, elPath); - } - else if (element instanceof IPath){ - return ((IPath) element).toOSString(); - } - - if( match == null ) - return ""; //$NON-NLS-1$ - - IResource resource = match.getResource(); - - String result = ""; //$NON-NLS-1$ - String path = ""; //$NON-NLS-1$ - if (resource != null){ - if (resource.isLinked()){ - path = match.getLocation().toOSString(); - } - else{ - path = resource.getFullPath().toOSString(); - } - } - - switch( getOrder() ){ - case SHOW_NAME_ONLY: - result = match.getName(); - case SHOW_ELEMENT_CONTAINER: - if( !match.getParentName().equals("") ) //$NON-NLS-1$ - result = match.getName() + " - " + match.getParentName() + " ( " + path + " )"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - else - result = match.getName() + " ( " + path + " )"; //$NON-NLS-1$ //$NON-NLS-2$ - - break; - case SHOW_PATH: - result = path + " - " + match.getParentName()+ "::" + match.getName(); //$NON-NLS-1$ //$NON-NLS-2$ - break; - case SHOW_CONTAINER_ELEMENT: - result = match.getParentName() + "::" + match.getName() + " ( " + path + " )"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - break; - } - - return result; - } - - /** - * @param element - * @return - */ - private String getCSearchSortElementText(String parentName, String name, String path) { - String result = ""; //$NON-NLS-1$ - - switch( getOrder() ){ - case SHOW_NAME_ONLY: - result = name; - case SHOW_ELEMENT_CONTAINER: - if( !parentName.equals("") ) //$NON-NLS-1$ - result = name + " - " + parentName + " ( " + path + " )"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - else - result = name+ " ( " + path + " )"; //$NON-NLS-1$ //$NON-NLS-2$ - - break; - case SHOW_PATH: - result = path + " - " + parentName + "::" + name; //$NON-NLS-1$ //$NON-NLS-2$ - break; - case SHOW_CONTAINER_ELEMENT: - result = parentName + "::" + name + " ( " + path + " )"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - break; - } - - return result; - } - - private String getElementText(ICElement element){ - - String result=""; //$NON-NLS-1$ - String path=""; //$NON-NLS-1$ - ICElement parent=element.getParent(); - - - result = element.getElementName() + " ( " + element.getPath() + " )"; //$NON-NLS-1$ //$NON-NLS-2$ - - - - return result; - } - - public int getOrder(){ - return _sortOrder; - } - public void setOrder(int orderFlag) { - _sortOrder = orderFlag; - } - - private int _sortOrder; - private int _textFlags; - private int _imageFlags; - - private static final Point SMALL_SIZE= new Point(16, 16); - - -} diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/ui/CUIPlugin.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/ui/CUIPlugin.java index 6960a028716..52e411a4bf9 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/ui/CUIPlugin.java +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/ui/CUIPlugin.java @@ -21,13 +21,11 @@ import java.util.ResourceBundle; import java.util.Set; import org.eclipse.cdt.core.CCorePlugin; -import org.eclipse.cdt.core.browser.AllTypesCache; import org.eclipse.cdt.core.model.CoreModel; import org.eclipse.cdt.core.model.ICElement; import org.eclipse.cdt.core.model.IWorkingCopy; import org.eclipse.cdt.core.model.IWorkingCopyProvider; import org.eclipse.cdt.internal.core.model.IBufferFactory; -import org.eclipse.cdt.internal.corext.refactoring.base.Refactoring; import org.eclipse.cdt.internal.corext.template.c.CContextType; import org.eclipse.cdt.internal.ui.CElementAdapterFactory; import org.eclipse.cdt.internal.ui.ICStatusConstants; @@ -433,17 +431,13 @@ public class CUIPlugin extends AbstractUIPlugin { return CUIPlugin.getSharedWorkingCopies(); } }; - AllTypesCache.initialize(workingCopyProvider); CCorePlugin.getDefault().getDOM().setWorkingCopyProvider(workingCopyProvider); - } /* (non-Javadoc) * @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext) */ public void stop(BundleContext context) throws Exception { - AllTypesCache.terminate(); - if (fTextTools != null) { fTextTools.dispose(); } @@ -465,7 +459,6 @@ public class CUIPlugin extends AbstractUIPlugin { fDocumentProvider.shutdown(); fDocumentProvider= null; } - Refactoring.getUndoManager().shutdown(); // Do this last. super.stop(context); diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/ui/actions/RefactoringActionGroup.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/ui/actions/RefactoringActionGroup.java deleted file mode 100644 index 2d0763d9e27..00000000000 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/ui/actions/RefactoringActionGroup.java +++ /dev/null @@ -1,290 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Rational Software - Initial API and implementation - *******************************************************************************/ -package org.eclipse.cdt.ui.actions; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import org.eclipse.cdt.internal.ui.IContextMenuConstants; -import org.eclipse.cdt.internal.ui.actions.ActionMessages; -import org.eclipse.cdt.internal.ui.editor.CEditor; -import org.eclipse.cdt.internal.ui.refactoring.RefactoringMessages; -import org.eclipse.cdt.internal.ui.refactoring.actions.RedoRefactoringAction; -import org.eclipse.cdt.internal.ui.refactoring.actions.RenameRefactoringAction; -import org.eclipse.cdt.internal.ui.refactoring.actions.UndoRefactoringAction; -import org.eclipse.core.runtime.Platform; -import org.eclipse.jface.action.Action; -import org.eclipse.jface.action.IAction; -import org.eclipse.jface.action.IMenuManager; -import org.eclipse.jface.action.MenuManager; -import org.eclipse.jface.action.Separator; -import org.eclipse.jface.text.ITextSelection; -import org.eclipse.jface.viewers.ISelection; -import org.eclipse.jface.viewers.ISelectionChangedListener; -import org.eclipse.jface.viewers.ISelectionProvider; -import org.eclipse.ui.IActionBars; -import org.eclipse.ui.IViewPart; -import org.eclipse.ui.IWorkbenchSite; -import org.eclipse.ui.actions.ActionGroup; -import org.eclipse.ui.part.Page; - -/** - * Action group that adds refactor actions (for example Rename..., Move..., etc) - * to a context menu and the global menu bar. - * - *

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

      - * - * @since 2.0 - */ -public class RefactoringActionGroup extends ActionGroup { - - /** - * Pop-up menu: id of the refactor sub menu (value org.eclipse.cdt.ui.refactoring.menu). - * - * @since 2.1 - */ - public static final String MENU_ID= "org.eclipse.cdt.ui.refactoring.menu"; //$NON-NLS-1$ - - /** - * Pop-up menu: id of the reorg group of the refactor sub menu (value - * reorgGroup). - * - * @since 2.1 - */ - public static final String GROUP_REORG= "reorgGroup"; //$NON-NLS-1$ - - /** - * Pop-up menu: id of the type group of the refactor sub menu (value - * typeGroup). - * - * @since 2.1 - */ - public static final String GROUP_TYPE= "typeGroup"; //$NON-NLS-1$ - - /** - * Pop-up menu: id of the coding group of the refactor sub menu (value - * codingGroup). - * - * @since 2.1 - */ - public static final String GROUP_CODING= "codingGroup"; //$NON-NLS-1$ - - /** - * Refactor menu: name of standard Rename Element global action - * (value "org.eclipse.cdt.ui.actions.refactor.Rename"). - */ - public static final String REFACTOR_RENAME= "org.eclipse.cdt.ui.actions.refactor.RenameAction"; //$NON-NLS-1$ - /** - * Refactor menu: name of standard Undo global action - * (value "org.eclipse.cdt.ui.actions.refactor.undo"). - */ - public static final String REFACTOR_UNDO= "org.eclipse.cdt.ui.actions.refactor.UndoAction"; //$NON-NLS-1$ - /** - * Refactor menu: name of standard Redo global action - * (value "org.eclipse.cdt.ui.actions.refactor.redo"). - */ - public static final String REFACTOR_REDO= "org.eclipse.cdt.ui.actions.refactor.RedoAction"; //$NON-NLS-1$ - - private IWorkbenchSite fSite; - private CEditor fEditor; - private String fGroupName= IContextMenuConstants.GROUP_REORGANIZE; - - private RenameRefactoringAction fRenameAction; - private RedoRefactoringAction fRedoAction; - private UndoRefactoringAction fUndoAction; - private List fEditorActions; - - private static class NoActionAvailable extends Action { - public NoActionAvailable() { - setEnabled(false); - setText(RefactoringMessages.getString("RefactorActionGroup.no_refactoring_available")); //$NON-NLS-1$ - } - } - private Action fNoActionAvailable= new NoActionAvailable(); - - /** - * Creates a new RefactorActionGroup. The group requires - * that the selection provided by the part's selection provider is of type - * org.eclipse.jface.viewers.IStructuredSelection. - * - * @param part the view part that owns this action group - */ - public RefactoringActionGroup(IViewPart part, String groupName) { - this(part.getSite(), groupName); - } - - /** - * Creates a new RefactorActionGroup. The action requires - * that the selection provided by the page's selection provider is of type - * org.eclipse.jface.viewers.IStructuredSelection. - * - * @param page the page that owns this action group - */ - public RefactoringActionGroup(Page page, String groupName) { - this(page.getSite(), groupName); - } - - /** - * Note: This constructor is for internal use only. Clients should not call this constructor. - */ - public RefactoringActionGroup(CEditor editor, String groupName) { - if (!isRefactoringPluginLoaded()) { - fSite= editor.getEditorSite(); - fEditor= editor; - if((groupName != null) && (groupName.length() > 0)) - fGroupName= groupName; - - ISelectionProvider provider= editor.getSelectionProvider(); - ISelection selection= provider.getSelection(); - fEditorActions= new ArrayList(3); - - fRenameAction= new RenameRefactoringAction(editor); - fRenameAction.update(selection); - editor.setAction("RenameElement", fRenameAction); //$NON-NLS-1$ - fEditorActions.add(fRenameAction); - - fUndoAction= new UndoRefactoringAction(editor); - fUndoAction.update(selection); - editor.setAction("UndoAction", fUndoAction); //$NON-NLS-1$ - fEditorActions.add(fUndoAction); - - fRedoAction= new RedoRefactoringAction(editor); - fRedoAction.update(selection); - editor.setAction("RedoAction", fRedoAction); //$NON-NLS-1$ - fEditorActions.add(fRedoAction); - } - } - - public RefactoringActionGroup(IWorkbenchSite site, String groupName) { - if (!isRefactoringPluginLoaded()) { - fSite= site; - if((groupName != null) && (groupName.length() > 0)) - fGroupName= groupName; - ISelectionProvider provider= fSite.getSelectionProvider(); - ISelection selection= provider.getSelection(); - - fRenameAction= new RenameRefactoringAction(site); - initAction(fRenameAction, provider, selection); - - fUndoAction= new UndoRefactoringAction(site); - initAction(fUndoAction, provider, selection); - - fRedoAction= new RedoRefactoringAction(site); - initAction(fRedoAction, provider, selection); - } - } - - private boolean isRefactoringPluginLoaded() { - return Platform.getBundle("org.eclipse.cdt.refactoring") != null; //$NON-NLS-1$ - } - - private static void initAction(SelectionDispatchAction action, ISelectionProvider provider, ISelection selection){ - action.update(selection); - provider.addSelectionChangedListener(action); - } - - /* (non-Javadoc) - * Method declared in ActionGroup - */ - public void fillActionBars(IActionBars actionBars) { - super.fillActionBars(actionBars); - if (fSite != null) { - actionBars.setGlobalActionHandler(REFACTOR_RENAME, fRenameAction); - actionBars.setGlobalActionHandler(REFACTOR_UNDO, fUndoAction); - actionBars.setGlobalActionHandler(REFACTOR_REDO, fRedoAction); - } - } - - /* (non-Javadoc) - * Method declared in ActionGroup - */ - public void fillContextMenu(IMenuManager menu) { - super.fillContextMenu(menu); - if (fSite != null) { - addRefactorSubmenu(menu); - } - } - - /* - * @see ActionGroup#dispose() - */ - public void dispose() { - if (fSite != null) { - ISelectionProvider provider= fSite.getSelectionProvider(); - - if (fRenameAction != null) { - disposeAction(fRenameAction, provider); - fRenameAction= null; - } - - if (fUndoAction != null) { - disposeAction(fUndoAction, provider); - fUndoAction.dispose(); - fUndoAction= null; - } - - if (fRedoAction != null) { - disposeAction(fRedoAction, provider); - fRedoAction.dispose(); - fRedoAction= null; - } - - if (fEditorActions != null) { - fEditorActions.clear(); - fEditorActions= null; - } - } - super.dispose(); - } - - private void disposeAction(ISelectionChangedListener action, ISelectionProvider provider) { - provider.removeSelectionChangedListener(action); - } - - private void addRefactorSubmenu(IMenuManager menu) { - IMenuManager refactorSubmenu= new MenuManager(ActionMessages.getString("RefactorMenu.label"), MENU_ID); //$NON-NLS-1$ - if (fEditor != null) { - ITextSelection textSelection= (ITextSelection)fEditor.getSelectionProvider().getSelection(); - for (Iterator iter= fEditorActions.iterator(); iter.hasNext(); ) { - SelectionDispatchAction action= (SelectionDispatchAction)iter.next(); - action.update(textSelection); - } - refactorSubmenu.removeAll(); - if (fillRefactorMenu(refactorSubmenu) == 0) - refactorSubmenu.add(fNoActionAvailable); - menu.appendToGroup(fGroupName, refactorSubmenu); - } else { - if (fillRefactorMenu(refactorSubmenu) > 0){ - menu.appendToGroup(fGroupName, refactorSubmenu); - } - } - } - - private int fillRefactorMenu(IMenuManager refactorSubmenu) { - int added= 0; - refactorSubmenu.add(new Separator(GROUP_REORG)); - added+= addAction(refactorSubmenu, fRenameAction); - added+= addAction(refactorSubmenu, fUndoAction); - added+= addAction(refactorSubmenu, fRedoAction); - return added; - } - - private int addAction(IMenuManager menu, IAction action) { - if (action != null && action.isEnabled()) { - menu.add(action); - return 1; - } - return 0; - } -} diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/ui/dialogs/CTagsIndexerBlock.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/ui/dialogs/CTagsIndexerBlock.java index f56918cbf43..abe4fb5b904 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/ui/dialogs/CTagsIndexerBlock.java +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/ui/dialogs/CTagsIndexerBlock.java @@ -14,7 +14,6 @@ import org.eclipse.cdt.core.CCorePlugin; import org.eclipse.cdt.core.ICDescriptor; import org.eclipse.cdt.core.ICExtensionReference; import org.eclipse.cdt.core.model.ICProject; -import org.eclipse.cdt.internal.core.index.ctagsindexer.CTagsIndexer; import org.eclipse.cdt.internal.ui.CUIMessages; import org.eclipse.cdt.internal.ui.util.SWTUtil; import org.eclipse.cdt.ui.CUIPlugin; @@ -82,26 +81,26 @@ public class CTagsIndexerBlock extends AbstractIndexerPage { monitor.beginTask(CUIMessages.getString("IndexerOptiosn.task.savingAttributes "), 1); //$NON-NLS-1$ ICOptionContainer container = getContainer(); IProject proj = null; - String internalExternalCTagsString = internalTagsFile ? CTagsIndexer.CTAGS_INTERNAL : CTagsIndexer.CTAGS_EXTERNAL; + String internalExternalCTagsString = ""; //internalTagsFile ? CTagsIndexer.CTAGS_INTERNAL : CTagsIndexer.CTAGS_EXTERNAL; String cTagsFileLocation = ""; //$NON-NLS-1$ if (!internalTagsFile) cTagsFileLocation = cTagsFile.getText(); String indexIncludeFiles = new Boolean(indexIncludePaths.getSelection()).toString(); - String cTagsLocationType = useDefaultCTags ? CTagsIndexer.CTAGS_PATH_DEFAULT : CTagsIndexer.CTAGS_PATH_SPECIFIED; + String cTagsLocationType = ""; //useDefaultCTags ? CTagsIndexer.CTAGS_PATH_DEFAULT : CTagsIndexer.CTAGS_PATH_SPECIFIED; String cTagsLocation = ""; //$NON-NLS-1$ if (!useDefaultCTags) cTagsLocation=cTagsExecutable.getText(); //if external has been chosen, ensure that there is a cTagsFileLocation selected; otherwise default //to internal file - if (internalExternalCTagsString.equals(CTagsIndexer.CTAGS_EXTERNAL) && cTagsFileLocation.equals("")) //$NON-NLS-1$ - internalExternalCTagsString=CTagsIndexer.CTAGS_INTERNAL; +// if (internalExternalCTagsString.equals(CTagsIndexer.CTAGS_EXTERNAL) && cTagsFileLocation.equals("")) //$NON-NLS-1$ +// internalExternalCTagsString=CTagsIndexer.CTAGS_INTERNAL; //if an external CPaths has been selected but no path has been provided, switch back to default setting - if (cTagsLocationType.equals(CTagsIndexer.CTAGS_PATH_SPECIFIED) && cTagsLocation.equals("")) //$NON-NLS-1$ - cTagsLocationType=CTagsIndexer.CTAGS_PATH_DEFAULT; +// if (cTagsLocationType.equals(CTagsIndexer.CTAGS_PATH_SPECIFIED) && cTagsLocation.equals("")) //$NON-NLS-1$ +// cTagsLocationType=CTagsIndexer.CTAGS_PATH_DEFAULT; if (container != null){ proj = container.getProject(); @@ -127,7 +126,7 @@ public class CTagsIndexerBlock extends AbstractIndexerPage { if (orig == null || !orig.equals(indexIncludeFiles)) { cext[i].setExtensionData("ctagsindexincludes", indexIncludeFiles); //$NON-NLS-1$ if (indexIncludeFiles.equals( "true")){ //$NON-NLS-1$ - CCorePlugin.getDefault().getCoreModel().getIndexManager().addResource(proj,proj); +// CCorePlugin.getDefault().getCoreModel().getIndexManager().addResource(proj,proj); } } orig = cext[i].getExtensionData("ctagslocationtype"); //$NON-NLS-1$ @@ -188,10 +187,10 @@ public class CTagsIndexerBlock extends AbstractIndexerPage { useSpecifiedCTagsExecutable = useCTagsExecutable.getSelection(); if (useDefaultCTags){ - setButtonState(CTagsIndexer.CTAGS_PATH_DEFAULT); +// setButtonState(CTagsIndexer.CTAGS_PATH_DEFAULT); } if (useSpecifiedCTagsExecutable){ - setButtonState(CTagsIndexer.CTAGS_PATH_SPECIFIED); +// setButtonState(CTagsIndexer.CTAGS_PATH_SPECIFIED); } } }; @@ -246,10 +245,10 @@ public class CTagsIndexerBlock extends AbstractIndexerPage { externalTagsFile = externalCTagsFile.getSelection(); if (externalTagsFile){ - setButtonState(CTagsIndexer.CTAGS_EXTERNAL); +// setButtonState(CTagsIndexer.CTAGS_EXTERNAL); } if (internalTagsFile){ - setButtonState(CTagsIndexer.CTAGS_INTERNAL); +// setButtonState(CTagsIndexer.CTAGS_INTERNAL); } } }; @@ -335,31 +334,31 @@ public class CTagsIndexerBlock extends AbstractIndexerPage { } private void setButtonState(String orig){ - if (orig.equals(CTagsIndexer.CTAGS_INTERNAL)){ - internalTagsFile=true; - externalTagsFile=false; - internalCTagsFile.setSelection(true); - externalCTagsFile.setSelection(false); - browseButton.setEnabled(false); - } else if (orig.equals(CTagsIndexer.CTAGS_EXTERNAL)){ - externalTagsFile=true; - internalTagsFile=false; - externalCTagsFile.setSelection(true); - internalCTagsFile.setSelection(false); - browseButton.setEnabled(true); - } else if(orig.equals(CTagsIndexer.CTAGS_PATH_DEFAULT)){ - useDefaultCTags=true; - useSpecifiedCTagsExecutable=false; - useCTagsPath.setSelection(true); - useCTagsExecutable.setSelection(false); - browseButtonCTagsExec.setEnabled(false); - } else if(orig.equals(CTagsIndexer.CTAGS_PATH_SPECIFIED)){ - useDefaultCTags=false; - useSpecifiedCTagsExecutable=true; - useCTagsPath.setSelection(false); - useCTagsExecutable.setSelection(true); - browseButtonCTagsExec.setEnabled(true); - } +// if (orig.equals(CTagsIndexer.CTAGS_INTERNAL)){ +// internalTagsFile=true; +// externalTagsFile=false; +// internalCTagsFile.setSelection(true); +// externalCTagsFile.setSelection(false); +// browseButton.setEnabled(false); +// } else if (orig.equals(CTagsIndexer.CTAGS_EXTERNAL)){ +// externalTagsFile=true; +// internalTagsFile=false; +// externalCTagsFile.setSelection(true); +// internalCTagsFile.setSelection(false); +// browseButton.setEnabled(true); +// } else if(orig.equals(CTagsIndexer.CTAGS_PATH_DEFAULT)){ +// useDefaultCTags=true; +// useSpecifiedCTagsExecutable=false; +// useCTagsPath.setSelection(true); +// useCTagsExecutable.setSelection(false); +// browseButtonCTagsExec.setEnabled(false); +// } else if(orig.equals(CTagsIndexer.CTAGS_PATH_SPECIFIED)){ +// useDefaultCTags=false; +// useSpecifiedCTagsExecutable=true; +// useCTagsPath.setSelection(false); +// useCTagsExecutable.setSelection(true); +// browseButtonCTagsExec.setEnabled(true); +// } } public void loadPreferences() { diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/ui/dialogs/DOMSourceIndexerBlock.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/ui/dialogs/DOMSourceIndexerBlock.java index e640a7a5e72..38ea3478757 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/ui/dialogs/DOMSourceIndexerBlock.java +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/ui/dialogs/DOMSourceIndexerBlock.java @@ -14,9 +14,7 @@ package org.eclipse.cdt.ui.dialogs; import org.eclipse.cdt.core.CCorePlugin; import org.eclipse.cdt.core.ICDescriptor; import org.eclipse.cdt.core.ICExtensionReference; -import org.eclipse.cdt.core.index.ICDTIndexer; import org.eclipse.cdt.core.model.ICProject; -import org.eclipse.cdt.internal.core.index.domsourceindexer.DOMSourceIndexer; import org.eclipse.cdt.internal.ui.CUIMessages; import org.eclipse.cdt.ui.CUIPlugin; import org.eclipse.cdt.ui.index.AbstractIndexerPage; @@ -59,7 +57,7 @@ public class DOMSourceIndexerBlock extends AbstractIndexerPage { monitor.beginTask(CUIMessages.getString("IndexerOptiosn.task.savingAttributes "), 1); //$NON-NLS-1$ ICOptionContainer container = getContainer(); IProject proj = null; - String indexMarkers = getIndexerProblemsValuesString(); +// String indexMarkers = getIndexerProblemsValuesString(); if (container != null){ proj = container.getProject(); @@ -75,16 +73,16 @@ public class DOMSourceIndexerBlock extends AbstractIndexerPage { for (int i = 0; i < cext.length; i++) { String id = cext[i].getID(); String orig = cext[i].getExtensionData("indexmarkers"); //$NON-NLS-1$ - String indexProblems = getIndexerProblemsValuesString(); - if (orig == null || !orig.equals(indexProblems)) { - cext[i].setExtensionData("indexmarkers", indexProblems); //$NON-NLS-1$ - } +// String indexProblems = getIndexerProblemsValuesString(); +// if (orig == null || !orig.equals(indexProblems)) { +// cext[i].setExtensionData("indexmarkers", indexProblems); //$NON-NLS-1$ +// } } } } else { if (prefStore != null) { - prefStore.setValue(PREF_INDEX_MARKERS, indexMarkers); +// prefStore.setValue(PREF_INDEX_MARKERS, indexMarkers); } } @@ -92,14 +90,6 @@ public class DOMSourceIndexerBlock extends AbstractIndexerPage { //an indexAll as one will come through the DeltaProcessor if (currentProject == null) return; - - ICDTIndexer indexer = CCorePlugin.getDefault().getCoreModel().getIndexManager().getIndexerForProject(currentProject.getProject()); - - int indexMarkersInt = Integer.parseInt(indexMarkers); - if (indexMarkersInt != oldIndexerProblemsValue && indexMarkersInt == 0) - if (indexer instanceof DOMSourceIndexer) - ((DOMSourceIndexer) indexer).removeIndexerProblems(currentProject.getProject()); - } /* (non-Javadoc) * @see org.eclipse.cdt.ui.dialogs.ICOptionPage#performDefaults() @@ -129,16 +119,16 @@ public class DOMSourceIndexerBlock extends AbstractIndexerPage { } - public String getIndexerProblemsValuesString(){ - int result = 0; - result |= preprocessorProblemsEnabled.getSelection() ? DOMSourceIndexer.PREPROCESSOR_PROBLEMS_BIT : 0; - if( syntacticProblemsEnabled != null ) - result |= syntacticProblemsEnabled.getSelection() ? DOMSourceIndexer.SYNTACTIC_PROBLEMS_BIT : 0; - result |= semanticProblemsEnabled.getSelection() ? DOMSourceIndexer.SEMANTIC_PROBLEMS_BIT : 0; - Integer tempInt = new Integer(result); - - return tempInt.toString(); - } +// public String getIndexerProblemsValuesString(){ +// int result = 0; +// result |= preprocessorProblemsEnabled.getSelection() ? DOMSourceIndexer.PREPROCESSOR_PROBLEMS_BIT : 0; +// if( syntacticProblemsEnabled != null ) +// result |= syntacticProblemsEnabled.getSelection() ? DOMSourceIndexer.SYNTACTIC_PROBLEMS_BIT : 0; +// result |= semanticProblemsEnabled.getSelection() ? DOMSourceIndexer.SEMANTIC_PROBLEMS_BIT : 0; +// Integer tempInt = new Integer(result); +// +// return tempInt.toString(); +// } /* (non-Javadoc) * @see org.eclipse.cdt.ui.index2.AbstractIndexerPage#initialize(org.eclipse.core.resources.IProject) @@ -151,7 +141,7 @@ public class DOMSourceIndexerBlock extends AbstractIndexerPage { } catch (CoreException e) {} //Set the IProblem checkboxes - setIndexerProblemValues(oldIndexerProblemsValue); +// setIndexerProblemValues(oldIndexerProblemsValue); } public void loadPersistedValues(IProject project) throws CoreException { @@ -172,18 +162,18 @@ public class DOMSourceIndexerBlock extends AbstractIndexerPage { } - public void setIndexerProblemValues( int value ){ - preprocessorProblemsEnabled.setSelection( (value & DOMSourceIndexer.PREPROCESSOR_PROBLEMS_BIT) != 0 ); - if( syntacticProblemsEnabled != null ) - syntacticProblemsEnabled.setSelection( (value & DOMSourceIndexer.SYNTACTIC_PROBLEMS_BIT) != 0 ); - semanticProblemsEnabled.setSelection( (value & DOMSourceIndexer.SEMANTIC_PROBLEMS_BIT) != 0 ); - } +// public void setIndexerProblemValues( int value ){ +// preprocessorProblemsEnabled.setSelection( (value & DOMSourceIndexer.PREPROCESSOR_PROBLEMS_BIT) != 0 ); +// if( syntacticProblemsEnabled != null ) +// syntacticProblemsEnabled.setSelection( (value & DOMSourceIndexer.SYNTACTIC_PROBLEMS_BIT) != 0 ); +// semanticProblemsEnabled.setSelection( (value & DOMSourceIndexer.SEMANTIC_PROBLEMS_BIT) != 0 ); +// } public void loadPreferences() { String indexerId=prefStore.getString(PREF_INDEX_MARKERS); if (!indexerId.equals("")) { //$NON-NLS-1$ oldIndexerProblemsValue = (new Integer(indexerId)).intValue(); - setIndexerProblemValues(oldIndexerProblemsValue); +// setIndexerProblemValues(oldIndexerProblemsValue); } } diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/ui/dialogs/IndexerBlock.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/ui/dialogs/IndexerBlock.java index edecd4fa29f..7e1a4358d14 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/ui/dialogs/IndexerBlock.java +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/ui/dialogs/IndexerBlock.java @@ -18,7 +18,6 @@ import java.util.List; import org.eclipse.cdt.core.CCorePlugin; import org.eclipse.cdt.core.model.CoreModel; import org.eclipse.cdt.core.model.ICProject; -import org.eclipse.cdt.internal.core.index.nullindexer.NullIndexer; import org.eclipse.cdt.internal.ui.CUIMessages; import org.eclipse.cdt.ui.CUIPlugin; import org.eclipse.cdt.ui.index.AbstractIndexerPage; @@ -64,8 +63,6 @@ public class IndexerBlock extends AbstractCOptionPage { private Composite parentComposite; private ICOptionPage currentPage; - int nullIndexerIndex; - String initialSelected; public IndexerBlock(){ @@ -241,8 +238,6 @@ public class IndexerBlock extends AbstractCOptionPage { for (int i = 0; i < infos.length; i++) { if (infos[i].getName().equals("indexerUI")) { //$NON-NLS-1$ String id = infos[i].getAttribute("indexerID"); //$NON-NLS-1$ - if (NullIndexer.ID.equals(id)) - nullIndexerIndex = i; indexerPageMap.put(id, new IndexerPageConfiguration(infos[i])); indexerPageList.add(id); } @@ -347,10 +342,6 @@ public class IndexerBlock extends AbstractCOptionPage { if (currentPage != null && currentPage.getControl() != null) { currentPage.performApply(new SubProgressMonitor(monitor, 1)); } - //Only send out an index changed notification if the indexer has actually changed - if (initialSelected == null || !selected.equals(initialSelected)) { - CCorePlugin.getDefault().getCoreModel().getIndexManager().indexerChangeNotification(project); - } } else { if (initialSelected == null || !selected.equals(initialSelected)) { diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/ui/wizards/NewClassCreationWizardPage.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/ui/wizards/NewClassCreationWizardPage.java index cc72c4654a7..29148d39b44 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/ui/wizards/NewClassCreationWizardPage.java +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/ui/wizards/NewClassCreationWizardPage.java @@ -10,47 +10,37 @@ *******************************************************************************/ package org.eclipse.cdt.ui.wizards; -import java.util.Iterator; import java.util.List; import org.eclipse.cdt.core.CConventions; import org.eclipse.cdt.core.CCorePlugin; -import org.eclipse.cdt.core.browser.AllTypesCache; -import org.eclipse.cdt.core.browser.IQualifiedTypeName; -import org.eclipse.cdt.core.browser.ITypeInfo; -import org.eclipse.cdt.core.browser.ITypeSearchScope; -import org.eclipse.cdt.core.browser.QualifiedTypeName; -import org.eclipse.cdt.core.browser.TypeSearchScope; -import org.eclipse.cdt.core.browser.TypeUtil; import org.eclipse.cdt.core.model.CModelException; import org.eclipse.cdt.core.model.CoreModel; import org.eclipse.cdt.core.model.ICContainer; import org.eclipse.cdt.core.model.ICElement; import org.eclipse.cdt.core.model.ICProject; import org.eclipse.cdt.core.model.ISourceRoot; +import org.eclipse.cdt.core.model.util.IQualifiedTypeName; +import org.eclipse.cdt.core.model.util.QualifiedTypeName; +import org.eclipse.cdt.core.model.util.TypeUtil; import org.eclipse.cdt.core.parser.IScannerInfo; import org.eclipse.cdt.core.parser.IScannerInfoProvider; -import org.eclipse.cdt.core.parser.ast.ASTAccessVisibility; import org.eclipse.cdt.internal.ui.dialogs.StatusInfo; import org.eclipse.cdt.internal.ui.dialogs.StatusUtil; import org.eclipse.cdt.internal.ui.util.SWTUtil; import org.eclipse.cdt.internal.ui.wizards.NewElementWizardPage; import org.eclipse.cdt.internal.ui.wizards.SourceFolderSelectionDialog; -import org.eclipse.cdt.internal.ui.wizards.classwizard.BaseClassInfo; import org.eclipse.cdt.internal.ui.wizards.classwizard.BaseClassesListDialogField; import org.eclipse.cdt.internal.ui.wizards.classwizard.ConstructorMethodStub; import org.eclipse.cdt.internal.ui.wizards.classwizard.DestructorMethodStub; import org.eclipse.cdt.internal.ui.wizards.classwizard.IBaseClassInfo; import org.eclipse.cdt.internal.ui.wizards.classwizard.IMethodStub; import org.eclipse.cdt.internal.ui.wizards.classwizard.MethodStubsListDialogField; -import org.eclipse.cdt.internal.ui.wizards.classwizard.NamespaceSelectionDialog; -import org.eclipse.cdt.internal.ui.wizards.classwizard.NewBaseClassSelectionDialog; import org.eclipse.cdt.internal.ui.wizards.classwizard.NewClassCodeGenerator; import org.eclipse.cdt.internal.ui.wizards.classwizard.NewClassWizardMessages; import org.eclipse.cdt.internal.ui.wizards.classwizard.NewClassWizardPrefs; -import org.eclipse.cdt.internal.ui.wizards.classwizard.SourceFileSelectionDialog; import org.eclipse.cdt.internal.ui.wizards.classwizard.NewClassWizardUtil; -import org.eclipse.cdt.internal.ui.wizards.classwizard.NewBaseClassSelectionDialog.ITypeSelectionListener; +import org.eclipse.cdt.internal.ui.wizards.classwizard.SourceFileSelectionDialog; import org.eclipse.cdt.internal.ui.wizards.dialogfields.DialogField; import org.eclipse.cdt.internal.ui.wizards.dialogfields.IDialogFieldListener; import org.eclipse.cdt.internal.ui.wizards.dialogfields.IListAdapter; @@ -73,8 +63,6 @@ import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.MultiStatus; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Status; -import org.eclipse.jface.dialogs.IDialogConstants; -import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.text.ITextSelection; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionProvider; @@ -689,25 +677,25 @@ public class NewClassCreationWizardPage extends NewElementWizardPage { * @param access the access visibility (public/private/protected) * @param isVirtual true if the inheritance is virtual */ - protected void addBaseClass(ITypeInfo newBaseClass, ASTAccessVisibility access, boolean isVirtual) { - // check if already exists - List baseClasses = fBaseClassesDialogField.getElements(); - if (baseClasses != null) { - for (Iterator i = baseClasses.iterator(); i.hasNext(); ) { - BaseClassInfo info = (BaseClassInfo) i.next(); - if (info.getType().equals(newBaseClass)) { - // already added - return; - } - } - } - - if (verifyBaseClasses()) { - NewClassWizardUtil.resolveClassLocation(newBaseClass, getContainer()); - } - - fBaseClassesDialogField.addBaseClass(new BaseClassInfo(newBaseClass, access, isVirtual)); - } +// protected void addBaseClass(ITypeInfo newBaseClass, ASTAccessVisibility access, boolean isVirtual) { +// // check if already exists +// List baseClasses = fBaseClassesDialogField.getElements(); +// if (baseClasses != null) { +// for (Iterator i = baseClasses.iterator(); i.hasNext(); ) { +// BaseClassInfo info = (BaseClassInfo) i.next(); +// if (info.getType().equals(newBaseClass)) { +// // already added +// return; +// } +// } +// } +// +// if (verifyBaseClasses()) { +// NewClassWizardUtil.resolveClassLocation(newBaseClass, getContainer()); +// } +// +// fBaseClassesDialogField.addBaseClass(new BaseClassInfo(newBaseClass, access, isVirtual)); +// } /** * Returns the selection state of the file group checkbox. @@ -975,34 +963,6 @@ public class NewClassCreationWizardPage extends NewElementWizardPage { */ private final class NamespaceFieldAdapter implements IStringButtonAdapter, IDialogFieldListener { public void changeControlPressed(DialogField field) { - ITypeInfo ns = chooseNamespace(); - if (ns != null) { - int changedFields = NAMESPACE_ID|CLASS_NAME_ID; - IPath oldFolderPath = getSourceFolderFullPath(); - if (oldFolderPath == null) { - IPath headerPath = getHeaderFileFullPath(); - IPath sourcePath = getSourceFileFullPath(); - IPath newFolderPath = updateSourceFolderFromPath(ns.getEnclosingProject().getFullPath()); - if (newFolderPath != null) { - changedFields |= SOURCE_FOLDER_ID | HEADER_FILE_ID | SOURCE_FILE_ID; - // adjust the relative paths - if (oldFolderPath != null && oldFolderPath.matchingFirstSegments(newFolderPath) == 0) { - if (headerPath != null) { - headerPath = newFolderPath.append(headerPath.lastSegment()); - } - if (sourcePath != null) { - sourcePath = newFolderPath.append(sourcePath.lastSegment()); - } - } - setSourceFolderFullPath(newFolderPath, false); - // adjust the relative paths - setHeaderFileFullPath(headerPath, false); - setSourceFileFullPath(sourcePath, false); - } - } - setNamespaceText(ns.getQualifiedTypeName().toString(), false); - handleFieldChanged(changedFields); - } } public void dialogFieldChanged(DialogField field) { @@ -1028,35 +988,6 @@ public class NewClassCreationWizardPage extends NewElementWizardPage { return null; } - private ITypeInfo chooseNamespace() { - ITypeSearchScope scope; - IProject project = getCurrentProject(); - if (project != null) { - scope = new TypeSearchScope(project); - } else { - scope = new TypeSearchScope(true); - } - - NewClassWizardUtil.prepareTypeCache(getContainer()); - - ITypeInfo[] elements = AllTypesCache.getNamespaces(scope, false); - if (elements == null || elements.length == 0) { - String title = NewClassWizardMessages.getString("NewClassCreationWizardPage.getTypes.noNamespaces.title"); //$NON-NLS-1$ - String message = NewClassWizardMessages.getString("NewClassCreationWizardPage.getTypes.noNamespaces.message"); //$NON-NLS-1$ - MessageDialog.openInformation(getShell(), title, message); - return null; - } - - NamespaceSelectionDialog dialog = new NamespaceSelectionDialog(getShell()); - dialog.setElements(elements); - int result = dialog.open(); - if (result == IDialogConstants.OK_ID) { - return (ITypeInfo) dialog.getFirstResult(); - } - - return null; - } - /** * handles changes to the class name field */ @@ -1090,29 +1021,6 @@ public class NewClassCreationWizardPage extends NewElementWizardPage { } private void chooseBaseClasses() { - NewClassWizardUtil.prepareTypeCache(getContainer()); - - ITypeInfo[] elements = NewClassWizardUtil.getReachableClasses(getCurrentProject()); - if (elements == null || elements.length == 0) { - String title = NewClassWizardMessages.getString("NewClassCreationWizardPage.getTypes.noClasses.title"); //$NON-NLS-1$ - String message = NewClassWizardMessages.getString("NewClassCreationWizardPage.getTypes.noClasses.message"); //$NON-NLS-1$ - MessageDialog.openInformation(getShell(), title, message); - return; - } - - List oldContents = fBaseClassesDialogField.getElements(); - NewBaseClassSelectionDialog dialog = new NewBaseClassSelectionDialog(getShell()); - dialog.addListener(new ITypeSelectionListener() { - public void typeAdded(ITypeInfo newBaseClass) { - addBaseClass(newBaseClass, ASTAccessVisibility.PUBLIC, false); - } - }); - dialog.setElements(elements); - int result = dialog.open(); - if (result != IDialogConstants.OK_ID) { - // restore the old contents - fBaseClassesDialogField.setElements(oldContents); - } } /** @@ -1486,62 +1394,12 @@ public class NewClassCreationWizardPage extends NewElementWizardPage { IQualifiedTypeName typeName = new QualifiedTypeName(namespace); IProject project = getCurrentProject(); if (project != null) { - NewClassWizardUtil.prepareTypeCache(getContainer()); - if (typeName.isQualified()) { // make sure enclosing namespace exists - ITypeInfo parentNamespace = AllTypesCache.getType(project, ICElement.C_NAMESPACE, typeName.getEnclosingTypeName()); - if (parentNamespace == null) { - status.setError(NewClassWizardMessages.getString("NewClassCreationWizardPage.error.EnclosingNamespaceNotExists")); //$NON-NLS-1$ - return status; - } } - ITypeInfo[] types = AllTypesCache.getTypes(project, typeName, false, true); - if (types.length > 0) { // look for namespace - boolean foundNamespace = false; - boolean exactMatch = false; - for (int i = 0; i < types.length; ++i) { - ITypeInfo currType = types[i]; - if (currType.getCElementType() == ICElement.C_NAMESPACE) { - foundNamespace = true; - exactMatch = currType.getQualifiedTypeName().equals(typeName); - if (exactMatch) { - // found a matching namespace - break; - } - } - } - if (foundNamespace) { - if (exactMatch) { - // we're good to go - status.setOK(); - } else { - status.setError(NewClassWizardMessages.getString("NewClassCreationWizardPage.error.NamespaceExistsDifferentCase")); //$NON-NLS-1$ - } - return status; - } // look for other types - exactMatch = false; - for (int i = 0; i < types.length; ++i) { - ITypeInfo currType = types[i]; - if (currType.getCElementType() != ICElement.C_NAMESPACE) { - exactMatch = currType.getQualifiedTypeName().equals(typeName); - if (exactMatch) { - // found a matching type - break; - } - } - } - if (exactMatch) { - status.setWarning(NewClassWizardMessages.getString("NewClassCreationWizardPage.error.TypeMatchingNamespaceExists")); //$NON-NLS-1$ - } else { - status.setWarning(NewClassWizardMessages.getString("NewClassCreationWizardPage.error.TypeMatchingNamespaceExistsDifferentCase")); //$NON-NLS-1$ - } - } else { - status.setWarning(NewClassWizardMessages.getString("NewClassCreationWizardPage.warning.NamespaceNotExists")); //$NON-NLS-1$ - } } val = CConventions.validateNamespaceName(typeName.lastSegment()); @@ -1586,8 +1444,6 @@ public class NewClassCreationWizardPage extends NewElementWizardPage { IProject project = getCurrentProject(); if (project != null) { - NewClassWizardUtil.prepareTypeCache(getContainer()); - IQualifiedTypeName fullyQualifiedName = typeName; if (isNamespaceSelected()) { String namespace = getNamespaceText(); @@ -1596,51 +1452,8 @@ public class NewClassCreationWizardPage extends NewElementWizardPage { } } - ITypeInfo[] types = AllTypesCache.getTypes(project, fullyQualifiedName, false, true); - if (types.length > 0) { // look for class - boolean foundClass = false; - boolean exactMatch = false; - for (int i = 0; i < types.length; ++i) { - ITypeInfo currType = types[i]; - if (currType.getCElementType() == ICElement.C_CLASS - || currType.getCElementType() == ICElement.C_STRUCT) { - foundClass = true; - exactMatch = currType.getQualifiedTypeName().equals(fullyQualifiedName); - if (exactMatch) { - // found a matching class - break; - } - } - } - if (foundClass) { - if (exactMatch) { - status.setError(NewClassWizardMessages.getString("NewClassCreationWizardPage.error.ClassNameExists")); //$NON-NLS-1$ - } else { - status.setError(NewClassWizardMessages.getString("NewClassCreationWizardPage.error.ClassNameExistsDifferentCase")); //$NON-NLS-1$ - } - return status; - } // look for other types - exactMatch = false; - for (int i = 0; i < types.length; ++i) { - ITypeInfo currType = types[i]; - if (currType.getCElementType() != ICElement.C_CLASS - && currType.getCElementType() != ICElement.C_STRUCT) { - exactMatch = currType.getQualifiedTypeName().equals(fullyQualifiedName); - if (exactMatch) { - // found a matching type - break; - } - } - } - if (exactMatch) { - status.setError(NewClassWizardMessages.getString("NewClassCreationWizardPage.error.TypeMatchingClassExists")); //$NON-NLS-1$ - } else { - status.setError(NewClassWizardMessages.getString("NewClassCreationWizardPage.error.TypeMatchingClassExistsDifferentCase")); //$NON-NLS-1$ - } - return status; - } } return status; } @@ -1691,11 +1504,7 @@ public class NewClassCreationWizardPage extends NewElementWizardPage { String[] includePaths = info.getIncludePaths(); for (int i = 0; i < baseClasses.length; ++i) { IBaseClassInfo baseClass = baseClasses[i]; - ITypeInfo baseType = baseClass.getType(); StatusInfo baseClassStatus = new StatusInfo(); - if (!NewClassWizardUtil.isTypeReachable(baseType, project, includePaths)) { - baseClassStatus.setError(NewClassWizardMessages.getFormattedString("NewClassCreationWizardPage.error.BaseClassNotExistsInProject", baseType.getQualifiedTypeName().toString())); //$NON-NLS-1$ - } status.add(baseClassStatus); } }