1
0
Fork 0
mirror of https://github.com/eclipse-cdt/cdt synced 2025-06-07 17:56:01 +02:00

Cosmetics.

This commit is contained in:
Sergey Prigogin 2014-05-19 12:15:52 -07:00
parent 6b3e138ff5
commit 9a96a017e5
13 changed files with 279 additions and 437 deletions

View file

@ -48,13 +48,11 @@ import org.eclipse.cdt.ui.testplugin.EditorTestHelper;
import org.eclipse.cdt.internal.ui.editor.CEditor; import org.eclipse.cdt.internal.ui.editor.CEditor;
/** /**
* Tests the automatic bracket insertion feature of the CEditor. Also tests * Tests the automatic bracket insertion feature of the CEditor. Also tests
* linked mode along the way. * linked mode along the way.
*/ */
public class BracketInserterTest extends TestCase { public class BracketInserterTest extends TestCase {
private static final String SRC= "src"; private static final String SRC= "src";
private static final String SEP= "/"; private static final String SEP= "/";
private static final String TU_NAME= "smartedit.cpp"; private static final String TU_NAME= "smartedit.cpp";
@ -77,7 +75,7 @@ public class BracketInserterTest extends TestCase {
" char[] t= args[0];" + " char[] t= args[0];" +
"}\n"; "}\n";
// document offsets // Document offsets.
private static final int INCLUDE_OFFSET= 9; private static final int INCLUDE_OFFSET= 9;
private static final int BODY_OFFSET= 212; private static final int BODY_OFFSET= 212;
private static final int ARGS_OFFSET= 184; private static final int ARGS_OFFSET= 184;
@ -173,7 +171,7 @@ public class BracketInserterTest extends TestCase {
assertModel(true); assertModel(true);
} }
public void testDeletingMultipleParenthesisInertion() throws BadLocationException, CModelException, CoreException { public void testDeletingMultipleParenthesisInsertion() throws BadLocationException, CModelException, CoreException {
setCaret(BODY_OFFSET); setCaret(BODY_OFFSET);
type("(((("); type("((((");
@ -477,7 +475,6 @@ public class BracketInserterTest extends TestCase {
return false; return false;
} }
}.waitForCondition(EditorTestHelper.getActiveDisplay(), 200); }.waitForCondition(EditorTestHelper.getActiveDisplay(), 200);
} }
private int getCaret() { private int getCaret() {

View file

@ -8,7 +8,6 @@
* Contributors: * Contributors:
* Markus Schorn - initial API and implementation * Markus Schorn - initial API and implementation
*******************************************************************************/ *******************************************************************************/
package org.eclipse.cdt.ui.tests.text.contentassist; package org.eclipse.cdt.ui.tests.text.contentassist;
import junit.framework.TestSuite; import junit.framework.TestSuite;
@ -22,7 +21,6 @@ public class ContentAssistTestSuite extends TestSuite {
public ContentAssistTestSuite() { public ContentAssistTestSuite() {
super(ContentAssistTestSuite.class.getName()); super(ContentAssistTestSuite.class.getName());
addTest( ContentAssistTests.suite() ); addTest(ContentAssistTests.suite());
} }
} }

View file

@ -13,7 +13,6 @@ package org.eclipse.cdt.ui.tests.text.contentassist;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.InputStream; import java.io.InputStream;
import java.io.StringWriter;
import junit.framework.Test; import junit.framework.Test;
import junit.framework.TestSuite; import junit.framework.TestSuite;
@ -53,7 +52,7 @@ public class ContentAssistTests extends BaseUITestCase {
private final NullProgressMonitor monitor= new NullProgressMonitor(); private final NullProgressMonitor monitor= new NullProgressMonitor();
static IProject project; static IProject project;
static ICProject cproject; static ICProject cproject;
static boolean disabledHelpContributions = false; static boolean disabledHelpContributions;
@Override @Override
public void setUp() throws InterruptedException { public void setUp() throws InterruptedException {
@ -64,60 +63,60 @@ public class ContentAssistTests extends BaseUITestCase {
cproject = CProjectHelper.createCCProject("ContentAssistTestProject", "bin", IPDOMManager.ID_FAST_INDEXER); //$NON-NLS-1$ //$NON-NLS-2$ cproject = CProjectHelper.createCCProject("ContentAssistTestProject", "bin", IPDOMManager.ID_FAST_INDEXER); //$NON-NLS-1$ //$NON-NLS-2$
project = cproject.getProject(); project = cproject.getProject();
waitForIndexer(cproject); waitForIndexer(cproject);
} catch ( CoreException e ) { } catch (CoreException e) {
/*boo*/ /*boo*/
} }
if (project == null) if (project == null)
fail("Unable to create project"); //$NON-NLS-1$ fail("Unable to create project"); //$NON-NLS-1$
} }
} }
public ContentAssistTests()
{ public ContentAssistTests() {
super(); super();
} }
/** /**
* @param name * @param name
*/ */
public ContentAssistTests(String name) public ContentAssistTests(String name) {
{
super(name); super(name);
} }
private void disableContributions (){ private void disableContributions() {
//disable the help books so we don't get proposals we weren't expecting //disable the help books so we don't get proposals we weren't expecting
CHelpBookDescriptor helpBooks[]; CHelpBookDescriptor helpBooks[];
helpBooks = CHelpProviderManager.getDefault().getCHelpBookDescriptors(new ICHelpInvocationContext(){ helpBooks = CHelpProviderManager.getDefault().getCHelpBookDescriptors(new ICHelpInvocationContext() {
@Override @Override
public IProject getProject(){return project;} public IProject getProject() {return project;}
@Override @Override
public ITranslationUnit getTranslationUnit(){return null;} public ITranslationUnit getTranslationUnit() {return null;}
} }
); );
for (CHelpBookDescriptor helpBook : helpBooks) { for (CHelpBookDescriptor helpBook : helpBooks) {
if( helpBook != null ) if (helpBook != null)
helpBook.enable( false ); helpBook.enable(false);
} }
} }
public static Test suite() { public static Test suite() {
TestSuite suite= suite(ContentAssistTests.class, "_"); TestSuite suite= suite(ContentAssistTests.class, "_");
suite.addTest( new ContentAssistTests("cleanupProject") ); //$NON-NLS-1$ suite.addTest(new ContentAssistTests("cleanupProject")); //$NON-NLS-1$
return suite; return suite;
} }
public void cleanupProject() throws Exception { public void cleanupProject() throws Exception {
closeAllEditors(); closeAllEditors();
try{ try {
project.delete( true, false, monitor ); project.delete(true, false, monitor);
project = null; project = null;
} catch( Throwable e ){ } catch (Throwable e) {
/*boo*/ /*boo*/
} }
} }
@Override @Override
protected void tearDown() throws Exception { protected void tearDown() throws Exception {
if( project == null || !project.exists() ) if (project == null || !project.exists())
return; return;
closeAllEditors(); closeAllEditors();
@ -125,45 +124,46 @@ public class ContentAssistTests extends BaseUITestCase {
// wait for indexer before deleting project to avoid errors in the log // wait for indexer before deleting project to avoid errors in the log
waitForIndexer(cproject); waitForIndexer(cproject);
IResource [] members = project.members(); IResource[] members = project.members();
for (IResource member : members) { for (IResource member : members) {
if( member.getName().equals( ".project" ) || member.getName().equals( ".cproject" ) ) //$NON-NLS-1$ //$NON-NLS-2$ if (member.getName().equals(".project") || member.getName().equals(".cproject")) //$NON-NLS-1$ //$NON-NLS-2$
continue; continue;
if (member.getName().equals(".settings")) if (member.getName().equals(".settings"))
continue; continue;
try{ try {
member.delete( false, monitor ); member.delete(false, monitor);
} catch( Throwable e ){ } catch (Throwable e) {
/*boo*/ /*boo*/
} }
} }
} }
protected IFile importFile(String fileName, String contents ) throws Exception{ protected IFile importFile(String fileName, String contents) throws Exception{
//Obtain file handle // Obtain file handle
IFile file = project.getProject().getFile(fileName); IFile file = project.getProject().getFile(fileName);
InputStream stream = new ByteArrayInputStream( contents.getBytes() ); InputStream stream = new ByteArrayInputStream(contents.getBytes());
//Create file input stream // Create file input stream
if( file.exists() ) if (file.exists()) {
file.setContents( stream, false, false, monitor ); file.setContents(stream, false, false, monitor);
else } else {
file.create( stream, false, monitor ); file.create(stream, false, monitor);
}
return file; return file;
} }
protected ICompletionProposal[] getResults( IFile file, int offset ) throws Exception { protected ICompletionProposal[] getResults(IFile file, int offset) throws Exception {
if( !disabledHelpContributions ) if (!disabledHelpContributions)
disableContributions(); disableContributions();
ITranslationUnit tu = (ITranslationUnit)CoreModel.getDefault().create( file ); ITranslationUnit tu = (ITranslationUnit)CoreModel.getDefault().create(file);
String buffer = tu.getBuffer().getContents(); String buffer = tu.getBuffer().getContents();
IWorkingCopy wc = null; IWorkingCopy wc = null;
try{ try{
wc = tu.getWorkingCopy(); wc = tu.getWorkingCopy();
}catch (CModelException e){ } catch (CModelException e) {
fail("Failed to get working copy"); //$NON-NLS-1$ fail("Failed to get working copy"); //$NON-NLS-1$
} }
@ -181,103 +181,103 @@ public class ContentAssistTests extends BaseUITestCase {
} }
public void testBug69334a() throws Exception { public void testBug69334a() throws Exception {
importFile( "test.h", "class Test{ public : Test( int ); }; \n" ); //$NON-NLS-1$//$NON-NLS-2$ importFile("test.h", "class Test{ public : Test( int ); }; \n"); //$NON-NLS-1$//$NON-NLS-2$
StringWriter writer = new StringWriter(); StringBuilder buf = new StringBuilder();
writer.write( "#include \"test.h\" \n"); //$NON-NLS-1$ buf.append("#include \"test.h\" \n"); //$NON-NLS-1$
writer.write( "Test::Test( int i ) { return; } \n"); //$NON-NLS-1$ buf.append("Test::Test( int i ) { return; } \n"); //$NON-NLS-1$
writer.write( "int main() { \n"); //$NON-NLS-1$ buf.append("int main() { \n"); //$NON-NLS-1$
writer.write( " int veryLongName = 1; \n"); //$NON-NLS-1$ buf.append(" int veryLongName = 1; \n"); //$NON-NLS-1$
writer.write( " Test * ptest = new Test( very \n"); //$NON-NLS-1$ buf.append(" Test * ptest = new Test( very \n"); //$NON-NLS-1$
String code = writer.toString(); String code = buf.toString();
IFile cu = importFile( "test.cpp", code ); //$NON-NLS-1$ IFile cu = importFile("test.cpp", code); //$NON-NLS-1$
ICompletionProposal [] results = getResults( cu, code.indexOf( "very " ) + 4 ); //$NON-NLS-1$ ICompletionProposal[] results = getResults(cu, code.indexOf("very ") + 4); //$NON-NLS-1$
assertEquals( 1, results.length ); assertEquals(1, results.length);
assertEquals( "veryLongName : int", results[0].getDisplayString() ); //$NON-NLS-1$ assertEquals("veryLongName : int", results[0].getDisplayString()); //$NON-NLS-1$
} }
public void testBug69334b() throws Exception { public void testBug69334b() throws Exception {
importFile( "test.h", "class Test{ public : Test( int ); }; \n" ); //$NON-NLS-1$//$NON-NLS-2$ importFile("test.h", "class Test{ public : Test( int ); }; \n"); //$NON-NLS-1$//$NON-NLS-2$
StringWriter writer = new StringWriter(); StringBuilder buf = new StringBuilder();
writer.write( "#include \"test.h\" \n"); //$NON-NLS-1$ buf.append("#include \"test.h\" \n"); //$NON-NLS-1$
writer.write( "Test::Test( int i ) { return; } \n"); //$NON-NLS-1$ buf.append("Test::Test( int i ) { return; } \n"); //$NON-NLS-1$
writer.write( "int main() { \n"); //$NON-NLS-1$ buf.append("int main() { \n"); //$NON-NLS-1$
writer.write( " int veryLongName = 1; \n"); //$NON-NLS-1$ buf.append(" int veryLongName = 1; \n"); //$NON-NLS-1$
writer.write( " Test test( very \n"); //$NON-NLS-1$ buf.append(" Test test( very \n"); //$NON-NLS-1$
String code = writer.toString(); String code = buf.toString();
IFile cu = importFile( "test.cpp", code ); //$NON-NLS-1$ IFile cu = importFile("test.cpp", code); //$NON-NLS-1$
ICompletionProposal [] results = getResults( cu, code.indexOf( "very " ) + 4 ); //$NON-NLS-1$ ICompletionProposal[] results = getResults(cu, code.indexOf("very ") + 4); //$NON-NLS-1$
assertEquals( 1, results.length ); assertEquals(1, results.length);
assertEquals( "veryLongName : int", results[0].getDisplayString() ); //$NON-NLS-1$ assertEquals("veryLongName : int", results[0].getDisplayString()); //$NON-NLS-1$
} }
public void testBug72824() throws Exception { public void testBug72824() throws Exception {
StringWriter writer = new StringWriter(); StringBuilder buf = new StringBuilder();
writer.write( "class Strategy { \n"); //$NON-NLS-1$ buf.append("class Strategy { \n"); //$NON-NLS-1$
writer.write( "public : \n"); //$NON-NLS-1$ buf.append("public : \n"); //$NON-NLS-1$
writer.write( " enum _Ability { IDIOT, NORMAL, CHEAT } ; \n"); //$NON-NLS-1$ buf.append(" enum _Ability { IDIOT, NORMAL, CHEAT } ; \n"); //$NON-NLS-1$
writer.write( " Strategy( _Ability a ) { } \n"); //$NON-NLS-1$ buf.append(" Strategy( _Ability a ) { } \n"); //$NON-NLS-1$
writer.write( " _Ability getAbility(); \n"); //$NON-NLS-1$ buf.append(" _Ability getAbility(); \n"); //$NON-NLS-1$
writer.write( "}; \n"); //$NON-NLS-1$ buf.append("}; \n"); //$NON-NLS-1$
writer.write( "int main(){ \n"); //$NON-NLS-1$ buf.append("int main(){ \n"); //$NON-NLS-1$
String code = writer.toString(); String code = buf.toString();
String c2 = code + " Strategy *p[3] = { new Strategy( Str \n"; //$NON-NLS-1$ String c2 = code + " Strategy *p[3] = { new Strategy( Str \n"; //$NON-NLS-1$
IFile cu = importFile( "strategy.cpp", c2 ); //$NON-NLS-1$ IFile cu = importFile("strategy.cpp", c2); //$NON-NLS-1$
ICompletionProposal [] results = getResults( cu, c2.indexOf( "Str " ) + 3 ); //$NON-NLS-1$ ICompletionProposal[] results = getResults(cu, c2.indexOf("Str ") + 3); //$NON-NLS-1$
assertEquals( 1, results.length ); assertEquals(1, results.length);
assertEquals( "Strategy", results[0].getDisplayString() ); //$NON-NLS-1$ assertEquals("Strategy", results[0].getDisplayString()); //$NON-NLS-1$
c2 = code + " Strategy *p[3] = { new Strategy( Strategy:: \n"; //$NON-NLS-1$ c2 = code + " Strategy *p[3] = { new Strategy( Strategy:: \n"; //$NON-NLS-1$
cu = importFile( "strategy.cpp", c2 ); //$NON-NLS-1$ cu = importFile("strategy.cpp", c2); //$NON-NLS-1$
results = getResults( cu, c2.indexOf( "::" ) + 2 ); //$NON-NLS-1$ results = getResults(cu, c2.indexOf("::") + 2); //$NON-NLS-1$
assertEquals( 4, results.length ); assertEquals(4, results.length);
assertEquals( "CHEAT", results[0].getDisplayString() ); //$NON-NLS-1$ assertEquals("CHEAT", results[0].getDisplayString()); //$NON-NLS-1$
assertEquals( "IDIOT", results[1].getDisplayString() ); //$NON-NLS-1$ assertEquals("IDIOT", results[1].getDisplayString()); //$NON-NLS-1$
assertEquals( "NORMAL", results[2].getDisplayString() ); //$NON-NLS-1$ assertEquals("NORMAL", results[2].getDisplayString()); //$NON-NLS-1$
// "_Ability" is here due to fix for bug 199598 // "_Ability" is here due to fix for bug 199598
// Difficult to differentiate between declaration and expression context // Difficult to differentiate between declaration and expression context
assertEquals( "_Ability", results[3].getDisplayString() ); //$NON-NLS-1$ assertEquals("_Ability", results[3].getDisplayString()); //$NON-NLS-1$
// in a method definition context, constructors and methods should be proposed // in a method definition context, constructors and methods should be proposed
c2 = code + "return 0;}\nStrategy::\n"; //$NON-NLS-1$ c2 = code + "return 0;}\nStrategy::\n"; //$NON-NLS-1$
cu = importFile( "strategy.cpp", c2 ); //$NON-NLS-1$ cu = importFile("strategy.cpp", c2); //$NON-NLS-1$
results = getResults( cu, c2.indexOf( "::" ) + 2 ); //$NON-NLS-1$ results = getResults(cu, c2.indexOf("::") + 2); //$NON-NLS-1$
assertEquals( 3, results.length ); assertEquals(3, results.length);
assertEquals( "getAbility(void) : enum _Ability", results[1].getDisplayString() ); //$NON-NLS-1$ assertEquals("getAbility(void) : enum _Ability", results[1].getDisplayString()); //$NON-NLS-1$
assertEquals( "Strategy(enum _Ability a)", results[0].getDisplayString() ); //$NON-NLS-1$ assertEquals("Strategy(enum _Ability a)", results[0].getDisplayString()); //$NON-NLS-1$
assertEquals( "_Ability", results[2].getDisplayString() ); //$NON-NLS-1$ assertEquals("_Ability", results[2].getDisplayString()); //$NON-NLS-1$
} }
public void testBug72559() throws Exception { public void testBug72559() throws Exception {
StringWriter writer = new StringWriter(); StringBuilder buf = new StringBuilder();
writer.write("void foo(){ \n"); //$NON-NLS-1$ buf.append("void foo(){ \n"); //$NON-NLS-1$
writer.write(" int var; \n"); //$NON-NLS-1$ buf.append(" int var; \n"); //$NON-NLS-1$
writer.write(" { \n"); //$NON-NLS-1$ buf.append(" { \n"); //$NON-NLS-1$
writer.write(" float var; \n"); //$NON-NLS-1$ buf.append(" float var; \n"); //$NON-NLS-1$
writer.write(" v \n"); //$NON-NLS-1$ buf.append(" v \n"); //$NON-NLS-1$
writer.write(" } \n"); //$NON-NLS-1$ buf.append(" } \n"); //$NON-NLS-1$
writer.write("} \n"); //$NON-NLS-1$ buf.append("} \n"); //$NON-NLS-1$
String code = writer.toString(); String code = buf.toString();
IFile cu = importFile( "t.cpp", code ); //$NON-NLS-1$ IFile cu = importFile("t.cpp", code); //$NON-NLS-1$
ICompletionProposal [] results = getResults( cu, code.indexOf( "v " ) + 1 ); //$NON-NLS-1$ ICompletionProposal[] results = getResults(cu, code.indexOf("v ") + 1); //$NON-NLS-1$
assertEquals( results.length, 3 ); assertEquals(results.length, 3);
assertEquals( results[0].getDisplayString(), "var : float" ); //$NON-NLS-1$ assertEquals(results[0].getDisplayString(), "var : float"); //$NON-NLS-1$
assertEquals( results[1].getDisplayString(), "virtual" ); //$NON-NLS-1$ assertEquals(results[1].getDisplayString(), "virtual"); //$NON-NLS-1$
assertEquals( results[2].getDisplayString(), "volatile" ); //$NON-NLS-1$ assertEquals(results[2].getDisplayString(), "volatile"); //$NON-NLS-1$
} }
} }

View file

@ -27,7 +27,7 @@ import org.eclipse.cdt.internal.ui.text.contentassist.ContentAssistPreference;
public class ProposalFilterPreferencesTest extends TestCase { public class ProposalFilterPreferencesTest extends TestCase {
public void testPreferences() { public void testPreferences() {
// Check that the test filter is among the filternames // Check that the test filter is among the filter names.
String[] filterNames = ProposalFilterPreferencesUtil.getProposalFilterNames(); String[] filterNames = ProposalFilterPreferencesUtil.getProposalFilterNames();
int index = -1 ; int index = -1 ;
for (int i = 0; i < filterNames.length; i++) { for (int i = 0; i < filterNames.length; i++) {
@ -44,7 +44,7 @@ public class ProposalFilterPreferencesTest extends TestCase {
String filterComboStateString = store.getString(ContentAssistPreference.PROPOSALS_FILTER); String filterComboStateString = store.getString(ContentAssistPreference.PROPOSALS_FILTER);
ProposalFilterPreferencesUtil.ComboState state = ProposalFilterPreferencesUtil.getComboState(filterComboStateString); ProposalFilterPreferencesUtil.ComboState state = ProposalFilterPreferencesUtil.getComboState(filterComboStateString);
StringBuffer newStateText = new StringBuffer(); StringBuffer newStateText = new StringBuffer();
newStateText.append(index+1); // First entry is always the <Default Filter>, index+1 must be selected newStateText.append(index + 1); // First entry is always the <Default Filter>, index+1 must be selected
for (int i = 0; i < state.items.length; i++) { for (int i = 0; i < state.items.length; i++) {
String item = state.items[i]; String item = state.items[i];
newStateText.append(";"); newStateText.append(";");

View file

@ -17,14 +17,11 @@ import org.eclipse.cdt.ui.text.contentassist.IProposalFilter;
* Dummy filter implementation for testing purposes * Dummy filter implementation for testing purposes
*/ */
public class TestProposalFilter implements IProposalFilter { public class TestProposalFilter implements IProposalFilter {
/** /**
* This dummy filter method will return the original proposals unmodified. * This dummy filter method will return the original proposals unmodified.
*/ */
@Override @Override
public ICCompletionProposal[] filterProposals( public ICCompletionProposal[] filterProposals(ICCompletionProposal[] proposals) {
ICCompletionProposal[] proposals) {
return proposals ; return proposals ;
} }
} }

View file

@ -55,7 +55,7 @@ public class ParameterHintTests extends AbstractContentAssistTest {
protected IFile setUpProjectContent(IProject project) throws Exception { protected IFile setUpProjectContent(IProject project) throws Exception {
String headerContent= readTaggedComment(HEADER_FILE_NAME); String headerContent= readTaggedComment(HEADER_FILE_NAME);
StringBuilder sourceContent= getContentsForTest(1)[0]; StringBuilder sourceContent= getContentsForTest(1)[0];
sourceContent.insert(0, "#include \""+HEADER_FILE_NAME+"\"\n"); sourceContent.insert(0, "#include \"" + HEADER_FILE_NAME + "\"\n");
assertNotNull(createFile(project, HEADER_FILE_NAME, headerContent)); assertNotNull(createFile(project, HEADER_FILE_NAME, headerContent));
return createFile(project, SOURCE_FILE_NAME, sourceContent.toString()); return createFile(project, SOURCE_FILE_NAME, sourceContent.toString());
} }

View file

@ -14,9 +14,6 @@ package org.eclipse.cdt.internal.ui.text;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyleRange;
import org.eclipse.core.runtime.Assert; import org.eclipse.core.runtime.Assert;
import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IDocument;
@ -25,13 +22,14 @@ import org.eclipse.jface.text.TextPresentation;
import org.eclipse.jface.text.contentassist.IContextInformation; import org.eclipse.jface.text.contentassist.IContextInformation;
import org.eclipse.jface.text.contentassist.IContextInformationPresenter; import org.eclipse.jface.text.contentassist.IContextInformationPresenter;
import org.eclipse.jface.text.contentassist.IContextInformationValidator; import org.eclipse.jface.text.contentassist.IContextInformationValidator;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyleRange;
/** /**
* This class provides the function parameter parsing for the C/C++ Editor hover * This class provides the function parameter parsing for the C/C++ Editor hover.
* It is based heavily on the Java class JavaParameterListValidator * It is based heavily on the Java class JavaParameterListValidator.
* *
* @author thomasf * @author thomasf
*
*/ */
public class CParameterListValidator implements IContextInformationValidator, IContextInformationPresenter { public class CParameterListValidator implements IContextInformationValidator, IContextInformationPresenter {
private int fPosition; private int fPosition;
@ -49,7 +47,6 @@ public class CParameterListValidator implements IContextInformationValidator, IC
*/ */
@Override @Override
public void install(IContextInformation info, ITextViewer viewer, int documentPosition) { public void install(IContextInformation info, ITextViewer viewer, int documentPosition) {
fPosition= documentPosition; fPosition= documentPosition;
fViewer= viewer; fViewer= viewer;
fInformation= info; fInformation= info;
@ -86,7 +83,6 @@ public class CParameterListValidator implements IContextInformationValidator, IC
private int getCharCount(IDocument document, int start, int end, private int getCharCount(IDocument document, int start, int end,
char increment, char decrement, boolean considerNesting) throws BadLocationException { char increment, char decrement, boolean considerNesting) throws BadLocationException {
Assert.isTrue((increment != 0 || decrement != 0) && increment != decrement); Assert.isTrue((increment != 0 || decrement != 0) && increment != decrement);
int nestingLevel = 0; int nestingLevel = 0;
@ -98,7 +94,7 @@ public class CParameterListValidator implements IContextInformationValidator, IC
if (start < end) { if (start < end) {
char next= document.getChar(start); char next= document.getChar(start);
if (next == '*') { if (next == '*') {
// a comment starts, advance to the comment end // A comment starts, advance to the comment end.
start= getCommentEnd(document, start + 1, end); start= getCommentEnd(document, start + 1, end);
} else if (next == '/') { } else if (next == '/') {
// '//'-comment: nothing to do anymore on this line // '//'-comment: nothing to do anymore on this line
@ -106,28 +102,30 @@ public class CParameterListValidator implements IContextInformationValidator, IC
} }
} }
break; break;
case '*': case '*':
if (start < end) { if (start < end) {
char next= document.getChar(start); char next= document.getChar(start);
if (next == '/') { if (next == '/') {
// we have been in a comment: forget what we read before // We have been in a comment: forget what we read before.
charCount= 0; charCount= 0;
++ start; ++ start;
} }
} }
break; break;
case '"': case '"':
case '\'': case '\'':
start= getStringEnd(document, start, end, curr); start= getStringEnd(document, start, end, curr);
break; break;
default: default:
if (considerNesting) { if (considerNesting) {
if ('(' == curr) {
if ('(' == curr) ++nestingLevel;
++ nestingLevel; } else if (')' == curr) {
else if (')' == curr) --nestingLevel;
-- nestingLevel; }
if (nestingLevel != 0) if (nestingLevel != 0)
break; break;
@ -135,12 +133,12 @@ public class CParameterListValidator implements IContextInformationValidator, IC
if (increment != 0) { if (increment != 0) {
if (curr == increment) if (curr == increment)
++ charCount; ++charCount;
} }
if (decrement != 0) { if (decrement != 0) {
if (curr == decrement) if (curr == decrement)
-- charCount; --charCount;
} }
} }
} }
@ -153,26 +151,19 @@ public class CParameterListValidator implements IContextInformationValidator, IC
*/ */
@Override @Override
public boolean isContextInformationValid(int position) { public boolean isContextInformationValid(int position) {
try { try {
if (position < fPosition) if (position < fPosition)
return false; return false;
IDocument document= fViewer.getDocument(); IDocument document= fViewer.getDocument();
return getCharCount(document, fPosition, position, '(', ')', false) >= 0;
return (getCharCount(document, fPosition, position, '(', ')', false) >= 0);
} catch (BadLocationException x) { } catch (BadLocationException x) {
return false; return false;
} }
} }
/**
* @see IContextInformationPresenter#updatePresentation(int, TextPresentation)
*/
@Override @Override
public boolean updatePresentation(int position, TextPresentation presentation) { public boolean updatePresentation(int position, TextPresentation presentation) {
int currentParameter= -1; int currentParameter= -1;
try { try {
@ -189,7 +180,7 @@ public class CParameterListValidator implements IContextInformationValidator, IC
presentation.clear(); presentation.clear();
fCurrentParameter= currentParameter; fCurrentParameter= currentParameter;
//Don't presume what has been done to the string, rather use as is // Don't presume what has been done to the string, rather use as is.
String s= fInformation.getInformationDisplayString(); String s= fInformation.getInformationDisplayString();
int[] commas= computeCommaPositions(s); int[] commas= computeCommaPositions(s);

View file

@ -9,10 +9,8 @@
* IBM Rational Software - Initial API and implementation * IBM Rational Software - Initial API and implementation
* Jens Elmenthaler - http://bugs.eclipse.org/173458 (camel case completion) * Jens Elmenthaler - http://bugs.eclipse.org/173458 (camel case completion)
*******************************************************************************/ *******************************************************************************/
package org.eclipse.cdt.internal.ui.text.contentassist; package org.eclipse.cdt.internal.ui.text.contentassist;
import org.eclipse.core.runtime.Assert; import org.eclipse.core.runtime.Assert;
import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferenceConverter; import org.eclipse.jface.preference.PreferenceConverter;
@ -59,7 +57,6 @@ import org.eclipse.cdt.internal.ui.text.CTextTools;
public class CCompletionProposal implements ICCompletionProposal, ICompletionProposalExtension, ICompletionProposalExtension2, ICompletionProposalExtension3 { public class CCompletionProposal implements ICCompletionProposal, ICompletionProposalExtension, ICompletionProposalExtension2, ICompletionProposalExtension3 {
private String fDisplayString; private String fDisplayString;
private String fIdString; private String fIdString;
private String fReplacementString; private String fReplacementString;
@ -85,7 +82,7 @@ public class CCompletionProposal implements ICCompletionProposal, ICompletionPro
* @param replacementLength the length of the text to be replaced * @param replacementLength the length of the text to be replaced
* @param image the image to display for this proposal * @param image the image to display for this proposal
* @param displayString the string to be displayed for the proposal * @param displayString the string to be displayed for the proposal
* If set to <code>null</code>, the replacement string will be taken as display string. * If set to {@code null}, the replacement string will be taken as display string.
*/ */
public CCompletionProposal(String replacementString, int replacementOffset, int replacementLength, Image image, String displayString, int relevance) { public CCompletionProposal(String replacementString, int replacementOffset, int replacementLength, Image image, String displayString, int relevance) {
this(replacementString, replacementOffset, replacementLength, image, displayString, null, relevance, null); this(replacementString, replacementOffset, replacementLength, image, displayString, null, relevance, null);
@ -99,8 +96,8 @@ public class CCompletionProposal implements ICCompletionProposal, ICompletionPro
* @param replacementLength the length of the text to be replaced * @param replacementLength the length of the text to be replaced
* @param image the image to display for this proposal * @param image the image to display for this proposal
* @param displayString the string to be displayed for the proposal * @param displayString the string to be displayed for the proposal
* @param viewer the text viewer for which this proposal is computed, may be <code>null</code> * @param viewer the text viewer for which this proposal is computed, may be {@code null}
* If set to <code>null</code>, the replacement string will be taken as display string. * If set to {@code null}, the replacement string will be taken as display string.
*/ */
public CCompletionProposal(String replacementString, int replacementOffset, int replacementLength, Image image, String displayString, int relevance, ITextViewer viewer) { public CCompletionProposal(String replacementString, int replacementOffset, int replacementLength, Image image, String displayString, int relevance, ITextViewer viewer) {
this(replacementString, replacementOffset, replacementLength, image, displayString, null, relevance, viewer); this(replacementString, replacementOffset, replacementLength, image, displayString, null, relevance, viewer);
@ -115,8 +112,8 @@ public class CCompletionProposal implements ICCompletionProposal, ICompletionPro
* @param image the image to display for this proposal * @param image the image to display for this proposal
* @param displayString the string to be displayed for the proposal * @param displayString the string to be displayed for the proposal
* @param idString the string to be uniquely identify this proposal * @param idString the string to be uniquely identify this proposal
* @param viewer the text viewer for which this proposal is computed, may be <code>null</code> * @param viewer the text viewer for which this proposal is computed, may be {@code null}
* If set to <code>null</code>, the replacement string will be taken as display string. * If set to {@code null}, the replacement string will be taken as display string.
*/ */
public CCompletionProposal(String replacementString, int replacementOffset, int replacementLength, Image image, String displayString, String idString, int relevance, ITextViewer viewer) { public CCompletionProposal(String replacementString, int replacementOffset, int replacementLength, Image image, String displayString, String idString, int relevance, ITextViewer viewer) {
Assert.isNotNull(replacementString); Assert.isNotNull(replacementString);
@ -160,7 +157,7 @@ public class CCompletionProposal implements ICCompletionProposal, ICompletionPro
/** /**
* Sets the proposal info. * Sets the proposal info.
* @param proposalInfo The additional information associated with this proposal or <code>null</code> * @param proposalInfo The additional information associated with this proposal or {@code null}
*/ */
public void setAdditionalProposalInfo(String proposalInfo) { public void setAdditionalProposalInfo(String proposalInfo) {
fProposalInfo= proposalInfo; fProposalInfo= proposalInfo;
@ -174,12 +171,9 @@ public class CCompletionProposal implements ICCompletionProposal, ICompletionPro
public void setCursorPosition(int cursorPosition) { public void setCursorPosition(int cursorPosition) {
Assert.isTrue(cursorPosition >= 0); Assert.isTrue(cursorPosition >= 0);
fCursorPosition= cursorPosition; fCursorPosition= cursorPosition;
fContextInformationPosition= (fContextInformation != null ? fCursorPosition : -1); fContextInformationPosition= fContextInformation != null ? fCursorPosition : -1;
} }
/*
* @see ICompletionProposalExtension#apply(IDocument, char, int)
*/
@Override @Override
public void apply(IDocument document, char trigger, int offset) { public void apply(IDocument document, char trigger, int offset) {
try { try {
@ -192,7 +186,7 @@ public class CCompletionProposal implements ICCompletionProposal, ICompletionPro
if (trigger == (char) 0) { if (trigger == (char) 0) {
string= fReplacementString; string= fReplacementString;
} else { } else {
StringBuffer buffer= new StringBuffer(fReplacementString); StringBuilder buffer= new StringBuilder(fReplacementString);
// fix for PR #5533. Assumes that no eating takes place. // fix for PR #5533. Assumes that no eating takes place.
if ((fCursorPosition > 0 && fCursorPosition <= buffer.length() && buffer.charAt(fCursorPosition - 1) != trigger)) { if ((fCursorPosition > 0 && fCursorPosition <= buffer.length() && buffer.charAt(fCursorPosition - 1) != trigger)) {
@ -233,9 +227,8 @@ public class CCompletionProposal implements ICCompletionProposal, ICompletionPro
ui.enter(); ui.enter();
} }
} }
} catch (BadLocationException x) { } catch (BadLocationException x) {
// ignore // Ignore
} }
} }
@ -243,7 +236,6 @@ public class CCompletionProposal implements ICCompletionProposal, ICompletionPro
* A class to simplify tracking a reference position in a document. * A class to simplify tracking a reference position in a document.
*/ */
private static final class ReferenceTracker { private static final class ReferenceTracker {
/** The reference position category name. */ /** The reference position category name. */
private static final String CATEGORY= "reference_position"; //$NON-NLS-1$ private static final String CATEGORY= "reference_position"; //$NON-NLS-1$
/** The position updater of the reference position. */ /** The position updater of the reference position. */
@ -255,7 +247,6 @@ public class CCompletionProposal implements ICCompletionProposal, ICompletionPro
* Called before document changes occur. It must be followed by a call to postReplace(). * Called before document changes occur. It must be followed by a call to postReplace().
* *
* @param document the document on which to track the reference position. * @param document the document on which to track the reference position.
*
*/ */
public void preReplace(IDocument document, int offset) throws BadLocationException { public void preReplace(IDocument document, int offset) throws BadLocationException {
fPosition.setOffset(offset); fPosition.setOffset(offset);
@ -263,9 +254,8 @@ public class CCompletionProposal implements ICCompletionProposal, ICompletionPro
document.addPositionCategory(CATEGORY); document.addPositionCategory(CATEGORY);
document.addPositionUpdater(fPositionUpdater); document.addPositionUpdater(fPositionUpdater);
document.addPosition(CATEGORY, fPosition); document.addPosition(CATEGORY, fPosition);
} catch (BadPositionCategoryException e) { } catch (BadPositionCategoryException e) {
// should not happen // Should not happen
CUIPlugin.log(e); CUIPlugin.log(e);
} }
} }
@ -280,9 +270,8 @@ public class CCompletionProposal implements ICCompletionProposal, ICompletionPro
document.removePosition(CATEGORY, fPosition); document.removePosition(CATEGORY, fPosition);
document.removePositionUpdater(fPositionUpdater); document.removePositionUpdater(fPositionUpdater);
document.removePositionCategory(CATEGORY); document.removePositionCategory(CATEGORY);
} catch (BadPositionCategoryException e) { } catch (BadPositionCategoryException e) {
// should not happen // Should not happen
CUIPlugin.log(e); CUIPlugin.log(e);
} }
return fPosition.getOffset(); return fPosition.getOffset();
@ -290,19 +279,14 @@ public class CCompletionProposal implements ICCompletionProposal, ICompletionPro
} }
protected static class ExitPolicy implements IExitPolicy { protected static class ExitPolicy implements IExitPolicy {
final char fExitCharacter; final char fExitCharacter;
public ExitPolicy(char exitCharacter) { public ExitPolicy(char exitCharacter) {
fExitCharacter= exitCharacter; fExitCharacter= exitCharacter;
} }
/*
* @see org.eclipse.jdt.internal.ui.text.link.LinkedPositionUI.ExitPolicy#doExit(org.eclipse.jdt.internal.ui.text.link.LinkedPositionManager, org.eclipse.swt.events.VerifyEvent, int, int)
*/
@Override @Override
public ExitFlags doExit(LinkedModeModel environment, VerifyEvent event, int offset, int length) { public ExitFlags doExit(LinkedModeModel environment, VerifyEvent event, int offset, int length) {
if (event.character == fExitCharacter) { if (event.character == fExitCharacter) {
if (environment.anyPositionContains(offset)) if (environment.anyPositionContains(offset))
return new ExitFlags(ILinkedModeListener.UPDATE_CARET, false); return new ExitFlags(ILinkedModeListener.UPDATE_CARET, false);
@ -318,7 +302,6 @@ public class CCompletionProposal implements ICCompletionProposal, ICompletionPro
return null; return null;
} }
} }
} }
// #6410 - File unchanged but dirtied by code assist // #6410 - File unchanged but dirtied by code assist
@ -335,33 +318,21 @@ public class CCompletionProposal implements ICCompletionProposal, ICompletionPro
apply(document, (char) 0, fReplacementOffset + fReplacementLength); apply(document, (char) 0, fReplacementOffset + fReplacementLength);
} }
/*
* @see ICompletionProposal#getSelection
*/
@Override @Override
public Point getSelection(IDocument document) { public Point getSelection(IDocument document) {
return new Point(fReplacementOffset + fCursorPosition, 0); return new Point(fReplacementOffset + fCursorPosition, 0);
} }
/*
* @see ICompletionProposal#getContextInformation()
*/
@Override @Override
public IContextInformation getContextInformation() { public IContextInformation getContextInformation() {
return fContextInformation; return fContextInformation;
} }
/*
* @see ICompletionProposal#getImage()
*/
@Override @Override
public Image getImage() { public Image getImage() {
return fImage; return fImage;
} }
/*
* @see ICompletionProposal#getDisplayString()
*/
@Override @Override
public String getDisplayString() { public String getDisplayString() {
return fDisplayString; return fDisplayString;
@ -377,9 +348,6 @@ public class CCompletionProposal implements ICCompletionProposal, ICompletionPro
return fIdString; return fIdString;
} }
/*
* @see ICompletionProposal#getAdditionalProposalInfo()
*/
@Override @Override
public String getAdditionalProposalInfo() { public String getAdditionalProposalInfo() {
if (fProposalInfo != null) { if (fProposalInfo != null) {
@ -388,17 +356,11 @@ public class CCompletionProposal implements ICCompletionProposal, ICompletionPro
return null; return null;
} }
/*
* @see ICompletionProposalExtension#getTriggerCharacters()
*/
@Override @Override
public char[] getTriggerCharacters() { public char[] getTriggerCharacters() {
return fTriggerCharacters; return fTriggerCharacters;
} }
/*
* @see ICompletionProposalExtension#getContextInformationPosition()
*/
@Override @Override
public int getContextInformationPosition() { public int getContextInformationPosition() {
return fReplacementOffset + fContextInformationPosition; return fReplacementOffset + fContextInformationPosition;
@ -412,9 +374,6 @@ public class CCompletionProposal implements ICCompletionProposal, ICompletionPro
return fReplacementOffset; return fReplacementOffset;
} }
/*
* @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension3#getCompletionOffset()
*/
@Override @Override
public int getPrefixCompletionStart(IDocument document, int completionOffset) { public int getPrefixCompletionStart(IDocument document, int completionOffset) {
return getReplacementOffset(); return getReplacementOffset();
@ -454,9 +413,6 @@ public class CCompletionProposal implements ICCompletionProposal, ICompletionPro
return fReplacementString; return fReplacementString;
} }
/*
* @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension3#getReplacementText()
*/
@Override @Override
public CharSequence getPrefixCompletionText(IDocument document, int completionOffset) { public CharSequence getPrefixCompletionText(IDocument document, int completionOffset) {
String string= getReplacementString(); String string= getReplacementString();
@ -482,27 +438,20 @@ public class CCompletionProposal implements ICCompletionProposal, ICompletionPro
fImage= image; fImage= image;
} }
/*
* @see ICompletionProposalExtension#isValidFor(IDocument, int)
*/
@Override @Override
public boolean isValidFor(IDocument document, int offset) { public boolean isValidFor(IDocument document, int offset) {
return validate(document, offset, null); return validate(document, offset, null);
} }
/*
* @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension2#validate(org.eclipse.jface.text.IDocument, int, org.eclipse.jface.text.DocumentEvent)
*/
@Override @Override
public boolean validate(IDocument document, int offset, DocumentEvent event) { public boolean validate(IDocument document, int offset, DocumentEvent event) {
if (offset < fReplacementOffset) if (offset < fReplacementOffset)
return false; return false;
boolean validated= match(document, offset, fReplacementString); boolean validated= match(document, offset, fReplacementString);
if (validated && event != null) { if (validated && event != null) {
// adapt replacement range to document change // Adapt replacement range to document change
int delta= (event.fText == null ? 0 : event.fText.length()) - event.fLength; int delta= (event.fText == null ? 0 : event.fText.length()) - event.fLength;
fReplacementLength += delta; fReplacementLength += delta;
} }
@ -528,8 +477,8 @@ public class CCompletionProposal implements ICCompletionProposal, ICompletionPro
} }
/** /**
* Returns <code>true</code> if a words matches the code completion prefix in the document, * Returns {@code true} if a words matches the code completion prefix in the document,
* <code>false</code> otherwise. * {@code false} otherwise.
*/ */
protected boolean match(IDocument document, int offset, String word) { protected boolean match(IDocument document, int offset, String word) {
if (word == null) if (word == null)
@ -554,15 +503,11 @@ public class CCompletionProposal implements ICCompletionProposal, ICompletionPro
return preference.getBoolean(ContentAssistPreference.AUTOINSERT); return preference.getBoolean(ContentAssistPreference.AUTOINSERT);
} }
/*
* @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension1#apply(org.eclipse.jface.text.ITextViewer, char, int, int)
*/
@Override @Override
public void apply(ITextViewer viewer, char trigger, int stateMask, int offset) { public void apply(ITextViewer viewer, char trigger, int stateMask, int offset) {
IDocument document= viewer.getDocument(); IDocument document= viewer.getDocument();
// don't eat if not in preferences, XOR with modifier key 1 (Ctrl) // Don't eat if not in preferences, XOR with modifier key 1 (Ctrl)
// but: if there is a selection, replace it! // but: if there is a selection, replace it!
Point selection= viewer.getSelectedRange(); Point selection= viewer.getSelectedRange();
fToggleEating= (stateMask & SWT.MOD1) != 0; fToggleEating= (stateMask & SWT.MOD1) != 0;
@ -574,7 +519,6 @@ public class CCompletionProposal implements ICCompletionProposal, ICompletionPro
} }
private static Color getForegroundColor(StyledText text) { private static Color getForegroundColor(StyledText text) {
IPreferenceStore preference= CUIPlugin.getDefault().getPreferenceStore(); IPreferenceStore preference= CUIPlugin.getDefault().getPreferenceStore();
RGB rgb= PreferenceConverter.getColor(preference, ContentAssistPreference.PROPOSALS_FOREGROUND); RGB rgb= PreferenceConverter.getColor(preference, ContentAssistPreference.PROPOSALS_FOREGROUND);
CTextTools textTools= CUIPlugin.getDefault().getTextTools(); CTextTools textTools= CUIPlugin.getDefault().getTextTools();
@ -582,7 +526,6 @@ public class CCompletionProposal implements ICCompletionProposal, ICompletionPro
} }
private static Color getBackgroundColor(StyledText text) { private static Color getBackgroundColor(StyledText text) {
IPreferenceStore preference= CUIPlugin.getDefault().getPreferenceStore(); IPreferenceStore preference= CUIPlugin.getDefault().getPreferenceStore();
RGB rgb= PreferenceConverter.getColor(preference, ContentAssistPreference.PROPOSALS_BACKGROUND); RGB rgb= PreferenceConverter.getColor(preference, ContentAssistPreference.PROPOSALS_BACKGROUND);
CTextTools textTools= CUIPlugin.getDefault().getTextTools(); CTextTools textTools= CUIPlugin.getDefault().getTextTools();
@ -592,27 +535,24 @@ public class CCompletionProposal implements ICCompletionProposal, ICompletionPro
private void repairPresentation(ITextViewer viewer) { private void repairPresentation(ITextViewer viewer) {
if (fRememberedStyleRange != null) { if (fRememberedStyleRange != null) {
if (viewer instanceof ITextViewerExtension2) { if (viewer instanceof ITextViewerExtension2) {
// attempts to reduce the redraw area // Attempts to reduce the redraw area
ITextViewerExtension2 viewer2= (ITextViewerExtension2) viewer; ITextViewerExtension2 viewer2= (ITextViewerExtension2) viewer;
if (viewer instanceof ITextViewerExtension5) { if (viewer instanceof ITextViewerExtension5) {
ITextViewerExtension5 extension= (ITextViewerExtension5) viewer; ITextViewerExtension5 extension= (ITextViewerExtension5) viewer;
IRegion widgetRange= extension.modelRange2WidgetRange(new Region(fRememberedStyleRange.start, fRememberedStyleRange.length)); IRegion widgetRange= extension.modelRange2WidgetRange(new Region(fRememberedStyleRange.start, fRememberedStyleRange.length));
if (widgetRange != null) if (widgetRange != null)
viewer2.invalidateTextPresentation(widgetRange.getOffset(), widgetRange.getLength()); viewer2.invalidateTextPresentation(widgetRange.getOffset(), widgetRange.getLength());
} else { } else {
viewer2.invalidateTextPresentation(fRememberedStyleRange.start + viewer.getVisibleRegion().getOffset(), fRememberedStyleRange.length); viewer2.invalidateTextPresentation(fRememberedStyleRange.start + viewer.getVisibleRegion().getOffset(), fRememberedStyleRange.length);
} }
} else {
} else
viewer.invalidateTextPresentation(); viewer.invalidateTextPresentation();
} }
} }
}
private void updateStyle(ITextViewer viewer) { private void updateStyle(ITextViewer viewer) {
StyledText text= viewer.getTextWidget(); StyledText text= viewer.getTextWidget();
if (text == null || text.isDisposed()) if (text == null || text.isDisposed())
return; return;
@ -649,36 +589,27 @@ public class CCompletionProposal implements ICCompletionProposal, ICompletionPro
try { try {
text.setStyleRange(fRememberedStyleRange); text.setStyleRange(fRememberedStyleRange);
} catch (IllegalArgumentException x) { } catch (IllegalArgumentException x) {
// catching exception as offset + length might be outside of the text widget // Catching exception as offset + length might be outside of the text widget
fRememberedStyleRange= null; fRememberedStyleRange= null;
} }
} }
/*
* @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension2#selected(ITextViewer, boolean)
*/
@Override @Override
public void selected(ITextViewer viewer, boolean smartToggle) { public void selected(ITextViewer viewer, boolean smartToggle) {
if (!insertCompletion() ^ smartToggle) if (!insertCompletion() ^ smartToggle) {
updateStyle(viewer); updateStyle(viewer);
else { } else {
repairPresentation(viewer); repairPresentation(viewer);
fRememberedStyleRange= null; fRememberedStyleRange= null;
} }
} }
/*
* @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension2#unselected(ITextViewer)
*/
@Override @Override
public void unselected(ITextViewer viewer) { public void unselected(ITextViewer viewer) {
repairPresentation(viewer); repairPresentation(viewer);
fRememberedStyleRange= null; fRememberedStyleRange= null;
} }
/*
* @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension3#getInformationControlCreator()
*/
@Override @Override
public IInformationControlCreator getInformationControlCreator() { public IInformationControlCreator getInformationControlCreator() {
return null; return null;
@ -692,22 +623,15 @@ public class CCompletionProposal implements ICCompletionProposal, ICompletionPro
setReplacementLength(length); setReplacementLength(length);
} }
/*
* @see java.lang.Object#hashCode()
*/
@Override @Override
public int hashCode() { public int hashCode() {
return fIdString.hashCode(); return fIdString.hashCode();
} }
/*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override @Override
public boolean equals(Object other) { public boolean equals(Object other) {
if(!(other instanceof ICCompletionProposal)) if(!(other instanceof ICCompletionProposal))
return false; return false;
return fIdString.equalsIgnoreCase(((ICCompletionProposal)other).getIdString()); return fIdString.equalsIgnoreCase(((ICCompletionProposal)other).getIdString());
} }
} }

View file

@ -38,7 +38,6 @@ import org.eclipse.cdt.core.dom.ast.IASTExpression;
import org.eclipse.cdt.core.dom.ast.IASTFieldReference; import org.eclipse.cdt.core.dom.ast.IASTFieldReference;
import org.eclipse.cdt.core.dom.ast.IASTName; import org.eclipse.cdt.core.dom.ast.IASTName;
import org.eclipse.cdt.core.dom.ast.IPointerType; import org.eclipse.cdt.core.dom.ast.IPointerType;
import org.eclipse.cdt.ui.CUIPlugin; import org.eclipse.cdt.ui.CUIPlugin;
import org.eclipse.cdt.ui.text.ICCompletionProposal; import org.eclipse.cdt.ui.text.ICCompletionProposal;
import org.eclipse.cdt.ui.text.contentassist.ContentAssistInvocationContext; import org.eclipse.cdt.ui.text.contentassist.ContentAssistInvocationContext;
@ -55,14 +54,14 @@ import org.eclipse.cdt.internal.ui.text.Symbols;
public class CContentAssistProcessor extends ContentAssistProcessor { public class CContentAssistProcessor extends ContentAssistProcessor {
private static class ActivationSet { private static class ActivationSet {
private final String theSet; private final String set;
ActivationSet(String s) { ActivationSet(String s) {
theSet = s; set = s;
} }
boolean contains(char c) { boolean contains(char c) {
return -1 != theSet.indexOf(c); return -1 != set.indexOf(c);
} }
} }
@ -76,65 +75,41 @@ public class CContentAssistProcessor extends ContentAssistProcessor {
fWrappedProposal= proposal; fWrappedProposal= proposal;
} }
/*
* @see org.eclipse.cdt.ui.text.ICCompletionProposal#getIdString()
*/
@Override @Override
public String getIdString() { public String getIdString() {
return fWrappedProposal.getDisplayString(); return fWrappedProposal.getDisplayString();
} }
/*
* @see org.eclipse.cdt.ui.text.ICCompletionProposal#getRelevance()
*/
@Override @Override
public int getRelevance() { public int getRelevance() {
return RelevanceConstants.CASE_MATCH_RELEVANCE + RelevanceConstants.KEYWORD_TYPE_RELEVANCE; return RelevanceConstants.CASE_MATCH_RELEVANCE + RelevanceConstants.KEYWORD_TYPE_RELEVANCE;
} }
/*
* @see org.eclipse.jface.text.contentassist.ICompletionProposal#apply(org.eclipse.jface.text.IDocument)
*/
@Override @Override
public void apply(IDocument document) { public void apply(IDocument document) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
/*
* @see org.eclipse.jface.text.contentassist.ICompletionProposal#getAdditionalProposalInfo()
*/
@Override @Override
public String getAdditionalProposalInfo() { public String getAdditionalProposalInfo() {
return fWrappedProposal.getAdditionalProposalInfo(); return fWrappedProposal.getAdditionalProposalInfo();
} }
/*
* @see org.eclipse.jface.text.contentassist.ICompletionProposal#getContextInformation()
*/
@Override @Override
public IContextInformation getContextInformation() { public IContextInformation getContextInformation() {
return fWrappedProposal.getContextInformation(); return fWrappedProposal.getContextInformation();
} }
/*
* @see org.eclipse.jface.text.contentassist.ICompletionProposal#getDisplayString()
*/
@Override @Override
public String getDisplayString() { public String getDisplayString() {
return fWrappedProposal.getDisplayString(); return fWrappedProposal.getDisplayString();
} }
/*
* @see org.eclipse.jface.text.contentassist.ICompletionProposal#getImage()
*/
@Override @Override
public Image getImage() { public Image getImage() {
return fWrappedProposal.getImage(); return fWrappedProposal.getImage();
} }
/*
* @see org.eclipse.jface.text.contentassist.ICompletionProposal#getSelection(org.eclipse.jface.text.IDocument)
*/
@Override @Override
public Point getSelection(IDocument document) { public Point getSelection(IDocument document) {
return fWrappedProposal.getSelection(document); return fWrappedProposal.getSelection(document);
@ -158,9 +133,6 @@ public class CContentAssistProcessor extends ContentAssistProcessor {
fEditor= editor; fEditor= editor;
} }
/*
* @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#getContextInformationValidator()
*/
@Override @Override
public IContextInformationValidator getContextInformationValidator() { public IContextInformationValidator getContextInformationValidator() {
if (fValidator == null) { if (fValidator == null) {
@ -169,43 +141,40 @@ public class CContentAssistProcessor extends ContentAssistProcessor {
return fValidator; return fValidator;
} }
/*
* @see org.eclipse.cdt.internal.ui.text.contentassist.ContentAssistProcessor#filterAndSort(List, IProgressMonitor)
*/
@Override @Override
protected List<ICompletionProposal> filterAndSortProposals(List<ICompletionProposal> proposals, protected List<ICompletionProposal> filterAndSortProposals(List<ICompletionProposal> proposals,
IProgressMonitor monitor, ContentAssistInvocationContext context) { IProgressMonitor monitor, ContentAssistInvocationContext context) {
IProposalFilter filter = getCompletionFilter(); IProposalFilter filter = getCompletionFilter();
ICCompletionProposal[] proposalsInput= new ICCompletionProposal[proposals.size()]; ICCompletionProposal[] proposalsInput= new ICCompletionProposal[proposals.size()];
// wrap proposals which are no ICCompletionProposals // Wrap proposals which are no ICCompletionProposals.
boolean wrapped= false; boolean wrapped= false;
int i= 0; int i= 0;
for (ICompletionProposal proposal : proposals) { for (ICompletionProposal proposal : proposals) {
if (proposal instanceof ICCompletionProposal) { if (proposal instanceof ICCompletionProposal) {
proposalsInput[i++]= (ICCompletionProposal)proposal; proposalsInput[i++]= (ICCompletionProposal) proposal;
} else { } else {
wrapped= true; wrapped= true;
proposalsInput[i++]= new CCompletionProposalWrapper(proposal); proposalsInput[i++]= new CCompletionProposalWrapper(proposal);
} }
} }
// filter // Filter.
ICCompletionProposal[] proposalsFiltered = filter.filterProposals(proposalsInput); ICCompletionProposal[] proposalsFiltered = filter.filterProposals(proposalsInput);
// sort // Sort.
boolean sortByAlphabet= CUIPlugin.getDefault().getPreferenceStore().getBoolean(ContentAssistPreference.ORDER_PROPOSALS); boolean sortByAlphabet= CUIPlugin.getDefault().getPreferenceStore().getBoolean(ContentAssistPreference.ORDER_PROPOSALS);
if (sortByAlphabet) { if (sortByAlphabet) {
// already sorted alphabetically by DefaultProposalFilter // Already sorted alphabetically by DefaultProposalFilter
// in case of custom proposal filter, keep ordering applied by filter // in case of custom proposal filter, keep ordering applied by filter.
} else { } else {
// sort by relevance // Sort by relevance.
CCompletionProposalComparator propsComp= new CCompletionProposalComparator(); CCompletionProposalComparator propsComp= new CCompletionProposalComparator();
propsComp.setOrderAlphabetically(sortByAlphabet); propsComp.setOrderAlphabetically(sortByAlphabet);
Arrays.sort(proposalsFiltered, propsComp); Arrays.sort(proposalsFiltered, propsComp);
} }
List<ICompletionProposal> filteredList; List<ICompletionProposal> filteredList;
if (wrapped) { if (wrapped) {
// unwrap again // Unwrap again.
filteredList= new ArrayList<ICompletionProposal>(proposalsFiltered.length); filteredList= new ArrayList<>(proposalsFiltered.length);
for (ICCompletionProposal proposal : proposalsFiltered) { for (ICCompletionProposal proposal : proposalsFiltered) {
if (proposal instanceof CCompletionProposalWrapper) { if (proposal instanceof CCompletionProposalWrapper) {
filteredList.add(((CCompletionProposalWrapper)proposal).unwrap()); filteredList.add(((CCompletionProposalWrapper)proposal).unwrap());
@ -231,15 +200,15 @@ public class CContentAssistProcessor extends ContentAssistProcessor {
} }
} }
} catch (InvalidRegistryObjectException e) { } catch (InvalidRegistryObjectException e) {
// No action required since we will be using the fail-safe default filter // No action required since we will be using the fail-safe default filter.
CUIPlugin.log(e); CUIPlugin.log(e);
} catch (CoreException e) { } catch (CoreException e) {
// No action required since we will be using the fail-safe default filter // No action required since we will be using the fail-safe default filter.
CUIPlugin.log(e); CUIPlugin.log(e);
} }
if (filter == null) { if (filter == null) {
// fail-safe default implementation // Fail-safe default implementation.
filter = new DefaultProposalFilter(); filter = new DefaultProposalFilter();
} }
return filter; return filter;
@ -287,9 +256,6 @@ public class CContentAssistProcessor extends ContentAssistProcessor {
fCContentAutoActivationCharacters= new ActivationSet(activationSet); fCContentAutoActivationCharacters= new ActivationSet(activationSet);
} }
/*
* @see org.eclipse.cdt.internal.ui.text.contentassist.ContentAssistProcessor#createContext(org.eclipse.jface.text.ITextViewer, int)
*/
@Override @Override
protected ContentAssistInvocationContext createContext(ITextViewer viewer, int offset, boolean isCompletion) { protected ContentAssistInvocationContext createContext(ITextViewer viewer, int offset, boolean isCompletion) {
char activationChar = getActivationChar(viewer, offset); char activationChar = getActivationChar(viewer, offset);
@ -309,7 +275,7 @@ public class CContentAssistProcessor extends ContentAssistProcessor {
} }
} }
if (context != null && isAutoActivated() && !fCContentAutoActivationCharacters.contains(activationChar)) { if (context != null && isAutoActivated() && !fCContentAutoActivationCharacters.contains(activationChar)) {
// auto-replace, but not auto-content-assist - bug 344387 // Auto-replace, but not auto-content-assist - bug 344387.
context.dispose(); context.dispose();
context = null; context = null;
} }
@ -325,20 +291,21 @@ public class CContentAssistProcessor extends ContentAssistProcessor {
doc.replace(offset - 1, 1, "->"); //$NON-NLS-1$ doc.replace(offset - 1, 1, "->"); //$NON-NLS-1$
context.dispose(); context.dispose();
context = null; context = null;
// if user turned on activation only for replacement characters, // If user turned on activation only for replacement characters,
// setting the context to null will skip the proposals popup later // setting the context to null will skip the proposals popup later.
if (!isAutoActivated() || fCContentAutoActivationCharacters.contains(activationChar)) { if (!isAutoActivated() || fCContentAutoActivationCharacters.contains(activationChar)) {
context = new CContentAssistInvocationContext(viewer, offset + 1, fEditor, context = new CContentAssistInvocationContext(viewer, offset + 1, fEditor,
isCompletion, isAutoActivated()); isCompletion, isAutoActivated());
} }
} catch (BadLocationException e) { } catch (BadLocationException e) {
// ignore // Ignore
} }
return context; return context;
} }
/** /**
* Get the character preceding the content assist activation offset. * Returns the character preceding the content assist activation offset.
*
* @param viewer * @param viewer
* @param offset * @param offset
* @return the activation character * @return the activation character
@ -358,9 +325,6 @@ public class CContentAssistProcessor extends ContentAssistProcessor {
return 0; return 0;
} }
/*
* @see org.eclipse.cdt.internal.ui.text.contentassist.ContentAssistProcessor#verifyAutoActivation(org.eclipse.jface.text.ITextViewer, int)
*/
@Override @Override
protected boolean verifyAutoActivation(ITextViewer viewer, int offset) { protected boolean verifyAutoActivation(ITextViewer viewer, int offset) {
IDocument doc= viewer.getDocument(); IDocument doc= viewer.getDocument();
@ -378,12 +342,12 @@ public class CContentAssistProcessor extends ContentAssistProcessor {
case '>': case '>':
return offset > 0 && doc.getChar(--offset) == '-'; return offset > 0 && doc.getChar(--offset) == '-';
case '.': case '.':
// avoid completion of float literals // Avoid completion of float literals
CHeuristicScanner scanner= new CHeuristicScanner(doc); CHeuristicScanner scanner= new CHeuristicScanner(doc);
int token= scanner.previousToken(--offset, Math.max(0, offset - 200)); int token= scanner.previousToken(--offset, Math.max(0, offset - 200));
// the scanner reports numbers as identifiers // The scanner reports numbers as identifiers
if (token == Symbols.TokenIDENT && !Character.isJavaIdentifierStart(doc.getChar(scanner.getPosition() + 1))) { if (token == Symbols.TokenIDENT && !Character.isJavaIdentifierStart(doc.getChar(scanner.getPosition() + 1))) {
// not a valid identifier // Not a valid identifier
return false; return false;
} }
return true; return true;

View file

@ -8,9 +8,6 @@
* Contributors: * Contributors:
* IBM Corp. - Rational Software - initial implementation * IBM Corp. - Rational Software - initial implementation
*******************************************************************************/ *******************************************************************************/
/*
* Created on May 6, 2004
*/
package org.eclipse.cdt.internal.ui.text.contentassist; package org.eclipse.cdt.internal.ui.text.contentassist;
import org.eclipse.jface.text.contentassist.IContextInformation; import org.eclipse.jface.text.contentassist.IContextInformation;
@ -55,9 +52,6 @@ public class CProposalContextInformation implements IContextInformation, IContex
fInformationDisplayString= informationDisplayString; fInformationDisplayString= informationDisplayString;
} }
/*
* @see IContextInformation#equals(Object)
*/
@Override @Override
public boolean equals(Object object) { public boolean equals(Object object) {
if (object instanceof IContextInformation) { if (object instanceof IContextInformation) {
@ -70,40 +64,29 @@ public class CProposalContextInformation implements IContextInformation, IContex
return false; return false;
} }
/*
* @see IContextInformation#getInformationDisplayString()
*/
@Override @Override
public String getInformationDisplayString() { public String getInformationDisplayString() {
return fInformationDisplayString; return fInformationDisplayString;
} }
/*
* @see IContextInformation#getImage()
*/
@Override @Override
public Image getImage() { public Image getImage() {
return fImage; return fImage;
} }
/*
* @see IContextInformation#getContextDisplayString()
*/
@Override @Override
public String getContextDisplayString() { public String getContextDisplayString() {
if (fContextDisplayString != null) if (fContextDisplayString != null)
return fContextDisplayString; return fContextDisplayString;
return fInformationDisplayString; return fInformationDisplayString;
} }
/* (non-Javadoc)
* @see org.eclipse.jface.text.contentassist.IContextInformationExtension#getContextInformationPosition()
*/
@Override @Override
public int getContextInformationPosition() { public int getContextInformationPosition() {
return fInformationPosition; return fInformationPosition;
} }
public void setContextInformationPosition( int pos ){ public void setContextInformationPosition(int pos) {
fInformationPosition = pos; fInformationPosition = pos;
} }
} }

View file

@ -48,7 +48,7 @@ public final class CompletionProposalCategory {
private final String fId; private final String fId;
private final String fName; private final String fName;
private final IConfigurationElement fElement; private final IConfigurationElement fElement;
/** The image descriptor for this category, or <code>null</code> if none specified. */ /** The image descriptor for this category, or {@code null} if none specified. */
private final ImageDescriptor fImage; private final ImageDescriptor fImage;
private boolean fIsSeparateCommand= true; private boolean fIsSeparateCommand= true;
@ -57,7 +57,7 @@ public final class CompletionProposalCategory {
private final CompletionProposalComputerRegistry fRegistry; private final CompletionProposalComputerRegistry fRegistry;
private int fSortOrder= 0x10000; private int fSortOrder= 0x10000;
private String fLastError= null; private String fLastError;
CompletionProposalCategory(IConfigurationElement element, CompletionProposalComputerRegistry registry) throws CoreException { CompletionProposalCategory(IConfigurationElement element, CompletionProposalComputerRegistry registry) throws CoreException {
fElement= element; fElement= element;
@ -66,10 +66,11 @@ public final class CompletionProposalCategory {
fId= parent.getUniqueIdentifier(); fId= parent.getUniqueIdentifier();
checkNotNull(fId, "id"); //$NON-NLS-1$ checkNotNull(fId, "id"); //$NON-NLS-1$
String name= parent.getLabel(); String name= parent.getLabel();
if (name == null) if (name == null) {
fName= fId; fName= fId;
else } else {
fName= name; fName= name;
}
String icon= element.getAttribute(ICON); String icon= element.getAttribute(ICON);
ImageDescriptor img= null; ImageDescriptor img= null;
@ -100,11 +101,11 @@ public final class CompletionProposalCategory {
} }
/** /**
* Checks that the given attribute value is not <code>null</code>. * Checks that the given attribute value is not {@code null}.
* *
* @param value the element to be checked * @param value the element to be checked
* @param attribute the attribute * @param attribute the attribute
* @throws CoreException if <code>value</code> is <code>null</code> * @throws CoreException if {@code value} is {@code null}
*/ */
private void checkNotNull(Object obj, String attribute) throws CoreException { private void checkNotNull(Object obj, String attribute) throws CoreException {
if (obj == null) { if (obj == null) {
@ -195,10 +196,10 @@ public final class CompletionProposalCategory {
} }
/** /**
* Returns <code>true</code> if the category contains any computers, <code>false</code> * Returns {@code true} if the category contains any computers, {@code false}
* otherwise. * otherwise.
* *
* @return <code>true</code> if the category contains any computers, <code>false</code> * @return {@code true} if the category contains any computers, {@code false}
* otherwise * otherwise
*/ */
public boolean hasComputers() { public boolean hasComputers() {
@ -211,12 +212,11 @@ public final class CompletionProposalCategory {
} }
/** /**
* Returns <code>true</code> if the category contains any computers in the given partition, <code>false</code> * Returns {@code true} if the category contains any computers in the given partition,
* otherwise. * {@code false} otherwise.
* *
* @param partition the partition * @param partition the partition
* @return <code>true</code> if the category contains any computers, <code>false</code> * @return {@code true} if the category contains any computers, {@code false} otherwise
* otherwise
*/ */
public boolean hasComputers(String partition) { public boolean hasComputers(String partition) {
List<CompletionProposalComputerDescriptor> descriptors= fRegistry.getProposalComputerDescriptors(partition); List<CompletionProposalComputerDescriptor> descriptors= fRegistry.getProposalComputerDescriptors(partition);
@ -254,8 +254,8 @@ public final class CompletionProposalCategory {
*/ */
public List<ICompletionProposal> computeCompletionProposals(ContentAssistInvocationContext context, String partition, SubProgressMonitor monitor) { public List<ICompletionProposal> computeCompletionProposals(ContentAssistInvocationContext context, String partition, SubProgressMonitor monitor) {
fLastError= null; fLastError= null;
List<ICompletionProposal> result= new ArrayList<ICompletionProposal>(); List<ICompletionProposal> result= new ArrayList<>();
List<CompletionProposalComputerDescriptor> descriptors= new ArrayList<CompletionProposalComputerDescriptor>(fRegistry.getProposalComputerDescriptors(partition)); List<CompletionProposalComputerDescriptor> descriptors= new ArrayList<>(fRegistry.getProposalComputerDescriptors(partition));
for (CompletionProposalComputerDescriptor desc : descriptors) { for (CompletionProposalComputerDescriptor desc : descriptors) {
if (desc.getCategory() == this) if (desc.getCategory() == this)
result.addAll(desc.computeCompletionProposals(context, monitor)); result.addAll(desc.computeCompletionProposals(context, monitor));
@ -278,8 +278,8 @@ public final class CompletionProposalCategory {
*/ */
public List<IContextInformation> computeContextInformation(ContentAssistInvocationContext context, String partition, SubProgressMonitor monitor) { public List<IContextInformation> computeContextInformation(ContentAssistInvocationContext context, String partition, SubProgressMonitor monitor) {
fLastError= null; fLastError= null;
List<IContextInformation> result= new ArrayList<IContextInformation>(); List<IContextInformation> result= new ArrayList<>();
List<CompletionProposalComputerDescriptor> descriptors= new ArrayList<CompletionProposalComputerDescriptor>(fRegistry.getProposalComputerDescriptors(partition)); List<CompletionProposalComputerDescriptor> descriptors= new ArrayList<>(fRegistry.getProposalComputerDescriptors(partition));
for (CompletionProposalComputerDescriptor desc : descriptors) { for (CompletionProposalComputerDescriptor desc : descriptors) {
if (desc.getCategory() == this) if (desc.getCategory() == this)
result.addAll(desc.computeContextInformation(context, monitor)); result.addAll(desc.computeContextInformation(context, monitor));
@ -302,7 +302,7 @@ public final class CompletionProposalCategory {
* Notifies the computers in this category of a proposal computation session start. * Notifies the computers in this category of a proposal computation session start.
*/ */
public void sessionStarted() { public void sessionStarted() {
List<CompletionProposalComputerDescriptor> descriptors= new ArrayList<CompletionProposalComputerDescriptor>(fRegistry.getProposalComputerDescriptors()); List<CompletionProposalComputerDescriptor> descriptors= new ArrayList<>(fRegistry.getProposalComputerDescriptors());
for (CompletionProposalComputerDescriptor desc : descriptors) { for (CompletionProposalComputerDescriptor desc : descriptors) {
if (desc.getCategory() == this) if (desc.getCategory() == this)
desc.sessionStarted(); desc.sessionStarted();
@ -315,7 +315,7 @@ public final class CompletionProposalCategory {
* Notifies the computers in this category of a proposal computation session end. * Notifies the computers in this category of a proposal computation session end.
*/ */
public void sessionEnded() { public void sessionEnded() {
List<CompletionProposalComputerDescriptor> descriptors= new ArrayList<CompletionProposalComputerDescriptor>(fRegistry.getProposalComputerDescriptors()); List<CompletionProposalComputerDescriptor> descriptors= new ArrayList<>(fRegistry.getProposalComputerDescriptors());
for (CompletionProposalComputerDescriptor desc : descriptors) { for (CompletionProposalComputerDescriptor desc : descriptors) {
if (desc.getCategory() == this) if (desc.getCategory() == this)
desc.sessionEnded(); desc.sessionEnded();
@ -323,5 +323,4 @@ public final class CompletionProposalCategory {
fLastError= desc.getErrorMessage(); fLastError= desc.getErrorMessage();
} }
} }
} }

View file

@ -66,19 +66,18 @@ import org.eclipse.cdt.internal.ui.util.Messages;
/** /**
* A content assist processor that aggregates the proposals of the * A content assist processor that aggregates the proposals of the
* {@link org.eclipse.cdt.ui.text.contentassist.ICompletionProposalComputer}s contributed via the * {@link org.eclipse.cdt.ui.text.contentassist.ICompletionProposalComputer}s contributed via
* <code>org.eclipse.cdt.ui.completionProposalComputer</code> extension point. * the {@code org.eclipse.cdt.ui.completionProposalComputer} extension point.
* <p> * <p>
* Subclasses may extend: * Subclasses may extend:
* <ul> * <ul>
* <li><code>createContext</code> to provide the context object passed to the computers</li> * <li>{@code createContext} to provide the context object passed to the computers</li>
* <li><code>createProgressMonitor</code> to change the way progress is reported</li> * <li>{@code createProgressMonitor} to change the way progress is reported</li>
* <li><code>filterAndSort</code> to add sorting and filtering</li> * <li>{@code filterAndSort} to add sorting and filtering</li>
* <li><code>getContextInformationValidator</code> to add context validation (needed if any * <li>{@code getContextInformationValidator} to add context validation (needed if any
* contexts are provided)</li> * contexts are provided)</li>
* <li><code>getErrorMessage</code> to change error reporting</li> * <li>{@code getErrorMessage} to change error reporting</li>
* </ul> * </ul>
* </p>
* *
* @since 4.0 * @since 4.0
*/ */
@ -130,7 +129,7 @@ public class ContentAssistProcessor implements IContentAssistProcessor {
fIterationGesture= getIterationGesture(); fIterationGesture= getIterationGesture();
KeySequence binding= getIterationBinding(); KeySequence binding= getIterationBinding();
// this may show the warning dialog if all categories are disabled // This may show the warning dialog if all categories are disabled.
fCategoryIteration= getCategoryIteration(); fCategoryIteration= getCategoryIteration();
for (Object element : fCategories) { for (Object element : fCategories) {
CompletionProposalCategory cat= (CompletionProposalCategory) element; CompletionProposalCategory cat= (CompletionProposalCategory) element;
@ -237,12 +236,11 @@ public class ContentAssistProcessor implements IContentAssistProcessor {
/** /**
* Verifies that auto activation is allowed. * Verifies that auto activation is allowed.
* <p> * <p>
* The default implementation always returns <code>true</code>. * The default implementation always returns {@code true}.
* </p>
* *
* @param viewer the text viewer * @param viewer the text viewer
* @param offset the offset where content assist was invoked on * @param offset the offset where content assist was invoked on
* @return <code>true</code> if auto activation is allowed * @return {@code true} if auto activation is allowed
*/ */
protected boolean verifyAutoActivation(ITextViewer viewer, int offset) { protected boolean verifyAutoActivation(ITextViewer viewer, int offset) {
return true; return true;
@ -254,7 +252,7 @@ public class ContentAssistProcessor implements IContentAssistProcessor {
} }
private List<ICompletionProposal> collectProposals(ITextViewer viewer, int offset, IProgressMonitor monitor, ContentAssistInvocationContext context) { private List<ICompletionProposal> collectProposals(ITextViewer viewer, int offset, IProgressMonitor monitor, ContentAssistInvocationContext context) {
List<ICompletionProposal> proposals= new ArrayList<ICompletionProposal>(); List<ICompletionProposal> proposals= new ArrayList<>();
List<CompletionProposalCategory> providers= getCategories(); List<CompletionProposalCategory> providers= getCategories();
for (CompletionProposalCategory cat : providers) { for (CompletionProposalCategory cat : providers) {
List<ICompletionProposal> computed= cat.computeCompletionProposals(context, fPartition, new SubProgressMonitor(monitor, 1)); List<ICompletionProposal> computed= cat.computeCompletionProposals(context, fPartition, new SubProgressMonitor(monitor, 1));
@ -270,14 +268,14 @@ public class ContentAssistProcessor implements IContentAssistProcessor {
* Filters and sorts the proposals. The passed list may be modified * Filters and sorts the proposals. The passed list may be modified
* and returned, or a new list may be created and returned. * and returned, or a new list may be created and returned.
* *
* @param proposals the list of collected proposals (element type: * @param proposals the list of collected proposals (element type: {@link ICompletionProposal})
* {@link ICompletionProposal})
* @param monitor a progress monitor * @param monitor a progress monitor
* @param context TODO * @param context TODO
* @return the list of filtered and sorted proposals, ready for * @return the list of filtered and sorted proposals, ready for
* display (element type: {@link ICompletionProposal}) * display (element type: {@link ICompletionProposal})
*/ */
protected List<ICompletionProposal> filterAndSortProposals(List<ICompletionProposal> proposals, IProgressMonitor monitor, ContentAssistInvocationContext context) { protected List<ICompletionProposal> filterAndSortProposals(List<ICompletionProposal> proposals,
IProgressMonitor monitor, ContentAssistInvocationContext context) {
return proposals; return proposals;
} }
@ -301,7 +299,7 @@ public class ContentAssistProcessor implements IContentAssistProcessor {
} }
private List<IContextInformation> collectContextInformation(ITextViewer viewer, int offset, IProgressMonitor monitor) { private List<IContextInformation> collectContextInformation(ITextViewer viewer, int offset, IProgressMonitor monitor) {
List<IContextInformation> proposals= new ArrayList<IContextInformation>(); List<IContextInformation> proposals= new ArrayList<>();
ContentAssistInvocationContext context= createContext(viewer, offset, false); ContentAssistInvocationContext context= createContext(viewer, offset, false);
try { try {
@ -320,12 +318,10 @@ public class ContentAssistProcessor implements IContentAssistProcessor {
} }
/** /**
* Filters and sorts the context information objects. The passed * Filters and sorts the context information objects. The passed list may be modified
* list may be modified and returned, or a new list may be created * and returned, or a new list may be created and returned.
* and returned.
* *
* @param contexts the list of collected proposals (element type: * @param contexts the list of collected proposals (element type: {@link IContextInformation})
* {@link IContextInformation})
* @param monitor a progress monitor * @param monitor a progress monitor
* @return the list of filtered and sorted proposals, ready for * @return the list of filtered and sorted proposals, ready for
* display (element type: {@link IContextInformation}) * display (element type: {@link IContextInformation})
@ -371,9 +367,7 @@ public class ContentAssistProcessor implements IContentAssistProcessor {
/** /**
* Creates a progress monitor. * Creates a progress monitor.
* <p> * <p>
* The default implementation creates a * The default implementation creates a {@code NullProgressMonitor}.
* <code>NullProgressMonitor</code>.
* </p>
* *
* @return a progress monitor * @return a progress monitor
*/ */
@ -382,13 +376,12 @@ public class ContentAssistProcessor implements IContentAssistProcessor {
} }
/** /**
* Creates the context that is passed to the completion proposal * Creates the context that is passed to the completion proposal computers.
* computers.
* *
* @param viewer the viewer that content assist is invoked on * @param viewer the viewer that content assist is invoked on
* @param offset the content assist offset * @param offset the content assist offset
* @return the context to be passed to the computers * @return the context to be passed to the computers,
* or <code>null</code> if no completion is possible * or {@code null} if no completion is possible
*/ */
protected ContentAssistInvocationContext createContext(ITextViewer viewer, int offset, boolean isCompletion) { protected ContentAssistInvocationContext createContext(ITextViewer viewer, int offset, boolean isCompletion) {
return new ContentAssistInvocationContext(viewer, offset); return new ContentAssistInvocationContext(viewer, offset);
@ -397,7 +390,7 @@ public class ContentAssistProcessor implements IContentAssistProcessor {
/** /**
* Test whether the current session was auto-activated. * Test whether the current session was auto-activated.
* *
* @return <code>true</code> if the current session was auto-activated. * @return {@code true} if the current session was auto-activated.
*/ */
protected boolean isAutoActivated() { protected boolean isAutoActivated() {
return fIsAutoActivated; return fIsAutoActivated;
@ -418,7 +411,7 @@ public class ContentAssistProcessor implements IContentAssistProcessor {
} }
private List<List<CompletionProposalCategory>> getCategoryIteration() { private List<List<CompletionProposalCategory>> getCategoryIteration() {
List<List<CompletionProposalCategory>> sequence= new ArrayList<List<CompletionProposalCategory>>(); List<List<CompletionProposalCategory>> sequence= new ArrayList<>();
sequence.add(getDefaultCategories()); sequence.add(getDefaultCategories());
for (CompletionProposalCategory cat : getSeparateCategories()) { for (CompletionProposalCategory cat : getSeparateCategories()) {
sequence.add(Collections.singletonList(cat)); sequence.add(Collections.singletonList(cat));
@ -439,7 +432,7 @@ public class ContentAssistProcessor implements IContentAssistProcessor {
} }
private List<CompletionProposalCategory> getDefaultCategoriesUnchecked() { private List<CompletionProposalCategory> getDefaultCategoriesUnchecked() {
List<CompletionProposalCategory> included= new ArrayList<CompletionProposalCategory>(); List<CompletionProposalCategory> included= new ArrayList<>();
for (Object element : fCategories) { for (Object element : fCategories) {
CompletionProposalCategory category= (CompletionProposalCategory) element; CompletionProposalCategory category= (CompletionProposalCategory) element;
if (category.isIncluded() && category.hasComputers(fPartition)) if (category.isIncluded() && category.hasComputers(fPartition))
@ -525,7 +518,7 @@ public class ContentAssistProcessor implements IContentAssistProcessor {
} }
private List<CompletionProposalCategory> getSeparateCategories() { private List<CompletionProposalCategory> getSeparateCategories() {
ArrayList<CompletionProposalCategory> sorted= new ArrayList<CompletionProposalCategory>(); ArrayList<CompletionProposalCategory> sorted= new ArrayList<>();
for (Object element : fCategories) { for (Object element : fCategories) {
CompletionProposalCategory category= (CompletionProposalCategory) element; CompletionProposalCategory category= (CompletionProposalCategory) element;
if (category.isSeparateCommand() && category.hasComputers(fPartition)) if (category.isSeparateCommand() && category.hasComputers(fPartition))

View file

@ -20,50 +20,46 @@ import org.eclipse.cdt.ui.text.contentassist.IProposalFilter;
* their id string. Use CCompletionProposalComparator for sorting. * their id string. Use CCompletionProposalComparator for sorting.
*/ */
public class DefaultProposalFilter implements IProposalFilter { public class DefaultProposalFilter implements IProposalFilter {
@Override @Override
public ICCompletionProposal[] filterProposals( public ICCompletionProposal[] filterProposals(ICCompletionProposal[] proposals) {
ICCompletionProposal[] proposals) {
CCompletionProposalComparator propsComp = new CCompletionProposalComparator(); CCompletionProposalComparator propsComp = new CCompletionProposalComparator();
propsComp.setOrderAlphabetically(true); propsComp.setOrderAlphabetically(true);
Arrays.sort(proposals, propsComp); Arrays.sort(proposals, propsComp);
// remove duplicates but leave the ones with return types // Remove duplicates but leave the ones with return types
int last = 0; int last = 0;
int removed = 0; int removed = 0;
for (int i = 1; i < proposals.length; ++i) { for (int i = 1; i < proposals.length; ++i) {
if (propsComp.compare(proposals[last], proposals[i]) == 0) { if (propsComp.compare(proposals[last], proposals[i]) == 0) {
// We want to leave the one that has the return string if any // We want to leave the one that has the return string if any
boolean lastReturn = proposals[last].getIdString() != proposals[last] boolean lastReturn = proposals[last].getIdString() != proposals[last].getDisplayString();
.getDisplayString(); boolean iReturn = proposals[i].getIdString() != proposals[i].getDisplayString();
boolean iReturn = proposals[i].getIdString() != proposals[i]
.getDisplayString();
if (!lastReturn && iReturn) if (!lastReturn && iReturn) {
// flip i down to last // flip i down to last
proposals[last] = proposals[i]; proposals[last] = proposals[i];
}
// Remove the duplicate // Remove the duplicate
proposals[i] = null; proposals[i] = null;
++removed; ++removed;
} else } else {
// update last // update last
last = i; last = i;
} }
}
if (removed > 0) { if (removed > 0) {
// Strip out the null entries // Strip out the null entries
ICCompletionProposal[] newArray = new ICCompletionProposal[proposals.length ICCompletionProposal[] newArray = new ICCompletionProposal[proposals.length - removed];
- removed];
int j = 0; int j = 0;
for (int i = 0; i < proposals.length; ++i) for (int i = 0; i < proposals.length; ++i) {
if (proposals[i] != null) if (proposals[i] != null)
newArray[j++] = proposals[i]; newArray[j++] = proposals[i];
}
proposals = newArray; proposals = newArray;
} }
return proposals; return proposals;
} }
} }