下面列出了怎么用org.eclipse.jface.viewers.StyledString的API类实例代码及写法,或者点击链接到github查看源代码。
void applyTo(StyledString styled, String otherText, Site site, ActionType action) {
String text = styled.getString();
if (text.isEmpty())
return;
styled.setStyle(0, text.length(), defaultStyler);
LinkedList<Diff> diffs = getDiffs(text, otherText, site, action);
boolean showDelete = doShowDelete(site, action);
boolean showInsert = doShowInsert(site, action);
int index = 0;
for (Diff diff : diffs) {
if (showDelete && diff.operation == Operation.DELETE) {
styled.setStyle(index, diff.text.length(), deleteStyler);
index += diff.text.length();
} else if (showInsert && diff.operation == Operation.INSERT) {
styled.setStyle(index, diff.text.length(), insertStyler);
index += diff.text.length();
} else if (diff.operation == Operation.EQUAL) {
index += diff.text.length();
}
}
}
public StyledStringVisitor(CloneStructureNode node, CloneDiffSide position) {
this.styledString = new StyledString();
List<ASTNodeDifference> differences = node.getMapping().getNodeDifferences();
//TextStyle Experiment
keywordStyle = initializeKeywordStyle();
stringStyle = initializeStringStyle();
ordinaryStyle = initializeOrdinaryStyle();
differenceStyle = initializeDifferenceStyle();
namedConstantStyle = initializeNamedConstantStyle();
nonStaticFieldStyle = initializeNonStaticFieldStyle();
staticMethodCallStyle = initializeStaticMethodCallStyle();
if(node.isElseIf()) {
styledString.append("else", new StyledStringStyler(keywordStyle));
appendSpace();
}
//Use the List of ASTNodeDifferences to recover actual ASTNodes and place them into a new list
astNodesThatAreDifferences = new ArrayList<ASTNode>();
generateDifferenceASTNodes(differences, position);
}
/**
* Creates a new completion proposal. All fields are initialized based on the provided information.
*
* @param replacementString the actual string to be inserted into the document
* @param replacementOffset the offset of the text to be replaced
* @param replacementLength the length of the text to be replaced
* @param cursorPosition the position of the cursor following the insert relative to replacementOffset
* @param image the image to display for this proposal
* @param displayString the string to be displayed for the proposal
* @param contextInformation the context information associated with this proposal
* @param additionalProposalInfo the additional information associated with this proposal
*/
public ModulaContextualCompletionProposal(String replacementString, int replacementOffset, int replacementLength,
int cursorPosition, Image image, StyledString displaySString, IContextInformation contextInformation, String additionalProposalInfo) {
Assert.isNotNull(replacementString);
Assert.isTrue(replacementOffset >= 0);
Assert.isTrue(replacementLength >= 0);
Assert.isTrue(cursorPosition >= 0);
fReplacementString= replacementString;
fReplacementOffset= replacementOffset;
fReplacementLength= replacementLength;
fCursorPosition= cursorPosition;
fImage= image;
fDisplaySString= displaySString;
fContextInformation= contextInformation;
fAdditionalProposalInfo= additionalProposalInfo;
}
@Override
public void completeAOPMember_Guard(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) {
if (model instanceof SarlBehaviorUnit) {
final SarlBehaviorUnit behaviorUnit = (SarlBehaviorUnit) model;
final XExpression guardExpr = behaviorUnit.getGuard();
if (guardExpr != null) {
// Generate the proposals by considering the guard expression as an anchor.
createLocalVariableAndImplicitProposals(guardExpr, IExpressionScope.Anchor.BEFORE, context, acceptor);
return;
}
final XExpression body = behaviorUnit.getExpression();
if (body != null) {
// Generate the proposals by considering that all elements that accessible from the body are accessible from the guard to.
// "it" is missed => it is manually added.
final ICompletionProposal itProposal = createCompletionProposal(
this.keywords.getItKeyword(),
new StyledString(this.keywords.getItKeyword()),
this.imageHelper.getImage(this.images.forLocalVariable(0)),
SARLContentProposalPriorities.CONTEXTUAL_KEYWORD_PRIORITY,
context.getPrefix(), context);
acceptor.accept(itProposal);
createLocalVariableAndImplicitProposals(body, context, acceptor);
}
}
}
/**
* Adds special marks so that that the given styled string is readable in a BiDi environment.
*
* @param styledString the styled string
* @return the processed styled string
* @since 3.4
*/
public static StyledString markLTR(StyledString styledString) {
/*
* NOTE: For performance reasons we do not call markLTR(styledString, null)
*/
if (!USE_TEXT_PROCESSOR)
return styledString;
String inputString= styledString.getString();
String string= TextProcessor.process(inputString);
if (string != inputString)
insertMarks(styledString, inputString, string);
return styledString;
}
@Override
public StyledString getStyledText(Object element) {
String text= getText(element);
StyledString string= new StyledString(text);
if (element instanceof ListItem) {
ListItem li = (ListItem)element;
if (li.isDelimiter()) {
string.setStyle(0, text.length(), StyledString.QUALIFIER_STYLER);
} else {
int concatPos = text.indexOf(CONCAT_STRING);
String modName = concatPos == -1 ? text : text.substring(0, concatPos);
if (sourceFileItemsFilter != null) {
ArrayList<Integer> ints = sourceFileItemsFilter.getMatchedIntervals(modName);
markMatchingRegions(string, ints, boldStyler);
}
if (concatPos != -1) {
string.setStyle(concatPos, text.length() - concatPos, StyledString.QUALIFIER_STYLER);
}
}
}
return string;
}
@Override
public void update(ViewerCell cell) {
if (cell.getElement() instanceof DiagramFileStore) {
DiagramFileStore filseStore = (DiagramFileStore) cell.getElement();
StyledString styledString = new StyledString();
styledString.append(fileStoreLabelProvider.getText(filseStore), null);
if(filseStore.hasMigrationReport()){
styledString.append(" -- ",StyledString.DECORATIONS_STYLER) ;
styledString.append( Messages.migrationOngoing ,StyledString.COUNTER_STYLER) ;
}
cell.setText(styledString.getString());
cell.setImage(fileStoreLabelProvider.getImage(filseStore)) ;
cell.setStyleRanges(styledString.getStyleRanges());
}
super.update(cell);
}
/** Replies the text for the given element.
*
* @param element the element.
* @return the text.
*/
protected StyledString text(SarlBehaviorUnit element) {
final StyledString text = new StyledString("on ", StyledString.DECORATIONS_STYLER); //$NON-NLS-1$
text.append(getHumanReadableName(element.getName()));
if (element.getGuard() != null) {
String txt = null;
final ICompositeNode node = NodeModelUtils.getNode(element.getGuard());
if (node != null) {
txt = node.getText().trim();
}
if (Strings.isNullOrEmpty(txt)) {
txt = "[" + Messages.SARLLabelProvider_2 + "]"; //$NON-NLS-1$//$NON-NLS-2$
} else {
assert txt != null;
final String dots = "..."; //$NON-NLS-1$
if (txt.length() > BEHAVIOR_UNIT_TEXT_LENGTH + dots.length()) {
txt = "[" + txt.substring(0, BEHAVIOR_UNIT_TEXT_LENGTH) + dots + "]"; //$NON-NLS-1$//$NON-NLS-2$
} else {
txt = "[" + txt + "]"; //$NON-NLS-1$//$NON-NLS-2$
}
}
text.append(" "); //$NON-NLS-1$
text.append(txt, StyledString.DECORATIONS_STYLER);
}
return text;
}
public void completeNestedKeyword(Keyword keyword, ContentAssistContext contentAssistContext, ICompletionProposalAcceptor acceptor, TemplateData data) {
String keywordValue = keyword.getValue();
String escapedKeywordValue = keywordValue.replace("$", "$$");
StyledString displayString = new StyledString(keywordValue);
if (!keywordValue.equals(escapedKeywordValue)) {
displayString = new StyledString(escapedKeywordValue)
.append(" - ", StyledString.QUALIFIER_STYLER)
.append(keywordValue, StyledString.COUNTER_STYLER)
.append(" - Keyword", StyledString.QUALIFIER_STYLER);
} else {
displayString = displayString.append(" - Keyword", StyledString.QUALIFIER_STYLER);
}
ConfigurableCompletionProposal proposal = (ConfigurableCompletionProposal) createCompletionProposal(escapedKeywordValue,
displayString,
getImage(keyword),
contentAssistContext);
getPriorityHelper().adjustKeywordPriority(proposal, contentAssistContext.getPrefix());
if (proposal != null)
proposal.setPriority(proposal.getPriority() * 2);
acceptor.accept(proposal);
}
protected void createRuleNode(IOutlineNode parentNode, AbstractRule rule, boolean isShowGrammar, boolean isLocalRule) {
StyledString text = (StyledString) textDispatcher.invoke(rule);
if (isShowGrammar) {
EObject grammar = rule.eContainer();
if (grammar instanceof Grammar)
text.append(new StyledString(" (" + ((Grammar) grammar).getName() + ")", StyledString.COUNTER_STYLER));
}
Image image = imageDispatcher.invoke(rule);
RuleNode ruleNode = new RuleNode(rule, parentNode, image, text, isLeafDispatcher.invoke(rule));
ruleNode.setFullText(new StyledString().append(text).append(getReturnTypeText(rule)));
if (isLocalRule) {
ICompositeNode parserNode = NodeModelUtils.getNode(rule);
if (parserNode != null)
ruleNode.setTextRegion(parserNode.getTextRegion());
ruleNode.setShortTextRegion(locationInFileProvider.getSignificantTextRegion(rule));
}
}
@Override
public void completeParameter_Name(final EObject model, Assignment assignment, final ContentAssistContext context,
final ICompletionProposalAcceptor acceptor) {
if (model instanceof XtendParameter) {
final List<XtendParameter> siblings = EcoreUtil2.getSiblingsOfType(model, XtendParameter.class);
Set<String> alreadyTaken = Sets.newHashSet();
for(XtendParameter sibling: siblings) {
alreadyTaken.add(sibling.getName());
}
alreadyTaken.addAll(getAllKeywords());
completions.getVariableProposals(model, XtendPackage.Literals.XTEND_PARAMETER__PARAMETER_TYPE,
VariableType.PARAMETER, alreadyTaken, new JdtVariableCompletions.CompletionDataAcceptor() {
@Override
public void accept(String replaceText, StyledString label, Image img) {
acceptor.accept(createCompletionProposal(replaceText, label, img, context));
}
});
} else {
super.completeParameter_Name(model, assignment, context, acceptor);
}
}
/**
* Appends the parameter list to <code>buffer</code>.
*
* @param buffer the buffer to append to
* @param methodProposal the method proposal
* @return the modified <code>buffer</code>
*/
private StyledString appendUnboundedParameterList(StyledString buffer, CompletionProposal methodProposal) {
// TODO remove once https://bugs.eclipse.org/bugs/show_bug.cgi?id=85293
// gets fixed.
char[] signature= SignatureUtil.fix83600(methodProposal.getSignature());
char[][] parameterNames= methodProposal.findParameterNames(null);
char[][] parameterTypes= Signature.getParameterTypes(signature);
for (int i= 0; i < parameterTypes.length; i++)
parameterTypes[i]= createTypeDisplayName(SignatureUtil.getLowerBound(parameterTypes[i]));
if (Flags.isVarargs(methodProposal.getFlags())) {
int index= parameterTypes.length - 1;
parameterTypes[index]= convertToVararg(parameterTypes[index]);
}
return appendParameterSignature(buffer, parameterTypes, parameterNames);
}
@Override
public IJavaCompletionProposal[] getAssists(IInvocationContext context, IProblemLocation[] locations)
throws CoreException {
return new IJavaCompletionProposal[] { new AbstractJavaCompletionProposal() {
public org.eclipse.jface.viewers.StyledString getStyledDisplayString() {
ICompilationUnit compilationUnit = context.getCompilationUnit();
return new StyledString(
"Generate Getter and setter for " + compilationUnit.findPrimaryType().getElementName());
}
protected int getPatternMatchRule(String pattern, String string) {
// override the match rule since we do not work with a pattern, but just want to open the "Generate Getters and Setters..." dialog
return -1;
};
public void apply(org.eclipse.jface.text.ITextViewer viewer, char trigger, int stateMask, int offset) {
if(context instanceof AssistContext) {
AssistContext assistContext = (AssistContext) context;
AddGetterSetterAction addGetterSetterAction = new AddGetterSetterAction((CompilationUnitEditor)assistContext.getEditor());
addGetterSetterAction.run();
}
}
} };
}
private StyledString getStyledString( ILaunchConfiguration launchConfig ) {
StyledString result;
if( labelMode == LIST ) {
result = getListStyledString( launchConfig );
} else {
result = getDetailStyledString( launchConfig );
}
return result;
}
/**
* Returns the styled label of a classpath container.
* The returned label is BiDi-processed with {@link TextProcessor#process(String, String)}.
*
* @param containerPath the path of the container
* @param project the project the container is resolved in
* @return the label of the classpath container
*
* @since 3.4
*/
public static StyledString getStyledContainerEntryLabel(IPath containerPath, IJavaProject project) {
try {
IClasspathContainer container= JavaCore.getClasspathContainer(containerPath, project);
String description= null;
if (container != null) {
description= container.getDescription();
}
if (description == null) {
ClasspathContainerInitializer initializer= JavaCore.getClasspathContainerInitializer(containerPath.segment(0));
if (initializer != null) {
description= initializer.getDescription(containerPath, project);
}
}
if (description != null) {
StyledString str= new StyledString(description);
if (containerPath.segmentCount() > 0 && JavaRuntime.JRE_CONTAINER.equals(containerPath.segment(0))) {
int index= description.indexOf('[');
if (index != -1) {
str.setStyle(index, description.length() - index, DECORATIONS_STYLE);
}
}
return Strings.markLTR(str);
}
} catch (JavaModelException e) {
// ignore
}
return new StyledString(BasicElementLabels.getPathLabel(containerPath, false));
}
@Override
public StyledString getStyledText(final Object element) {
if (element instanceof FileURI) {
return getCategoryText((FileURI) element);
} else if (element instanceof IN4JSProject) {
return projectExplorerhelper.getStyledTextForExternalProject((IN4JSProject) element, null);
}
return new StyledString("unknown");
}
@Override
public StyledString getStyledDisplayString() {
if(styledDisplayString == null) {
StyledString styledString = new StyledString(proposal.getLabel());
getStyledDisplayString_TypeLabel(styledString);
getStyledDisplayString_ModuleName(styledString);
styledDisplayString = styledString;
}
return styledDisplayString;
}
/** Replies the styled parameters.
*
* @param element the element from which the parameters are extracted.
* @return the styled parameters
* @since 0.6
*/
public StyledString styledParameters(JvmIdentifiableElement element) {
final StyledString str = new StyledString();
if (element instanceof JvmExecutable) {
final JvmExecutable executable = (JvmExecutable) element;
str.append(this.keywords.getLeftParenthesisKeyword());
str.append(parametersToStyledString(
executable.getParameters(),
executable.isVarArgs(),
false));
str.append(this.keywords.getRightParenthesisKeyword());
}
return str;
}
private StyledString getStyledText(Object element,
IStyledLabelProvider provider) {
StyledString string = provider.getStyledText(element);
if (selectionDecorator != null && isSelected(element)) {
String decorated = selectionDecorator.decorateText(string
.getString(), element);
return StyledCellLabelProvider.styleDecoratedString(decorated, null, string);
// no need to add colors when element is selected
}
return string;
}
private StyledString getLineElementLabel(LineElement lineElement) {
int lineNumber= lineElement.getLine();
String lineNumberString= Messages.format(SearchMessages.FileLabelProvider_line_number, new Integer(lineNumber));
StyledString str= new StyledString(lineNumberString, StyledString.QUALIFIER_STYLER);
Match[] matches= lineElement.getMatches(fPage.getInput());
Arrays.sort(matches, fMatchComparator);
String content= lineElement.getContents();
int pos= evaluateLineStart(matches, content, lineElement.getOffset());
int length= content.length();
int charsToCut= getCharsToCut(length, matches); // number of characters to leave away if the line is too long
for (int i= 0; i < matches.length; i++) {
TypeScriptMatch match= (TypeScriptMatch) matches[i];
int start= Math.max(match.getOriginalOffset() - lineElement.getOffset(), 0);
// append gap between last match and the new one
if (pos < start) {
if (charsToCut > 0) {
charsToCut= appendShortenedGap(content, pos, start, charsToCut, i == 0, str);
} else {
str.append(content.substring(pos, start));
}
}
// append match
int end= Math.min(match.getOriginalOffset() + match.getOriginalLength() - lineElement.getOffset(), lineElement.getLength());
str.append(content.substring(start, end), DecoratingTypeScriptSearchLabelProvider.HIGHLIGHT_STYLE);
pos= end;
}
// append rest of the line
if (charsToCut > 0) {
appendShortenedGap(content, pos, length, charsToCut, false, str);
} else {
str.append(content.substring(pos));
}
return str;
}
@Override
// CHECKSTYLE:OFF
public void completeConfiguredParameter_NewValue(final EObject model, final Assignment assignment, final ContentAssistContext context, final ICompletionProposalAcceptor acceptor) {
// CHECKSTYLE:ON
// TODO filter depending on type of linked parameter
FormalParameter parameter = ((ConfiguredParameter) model).getParameter();
ICheckCfgPropertySpecification propertySpecification = null;
String[] validValues = null;
if (parameter != null) {
propertySpecification = CheckCfgUtil.getPropertySpecification(parameter.getName());
if (propertySpecification != null) {
validValues = propertySpecification.getExpectedValues();
}
}
if (validValues != null && validValues.length > 0) {
String info = propertySpecification.getInfo();
for (String validValue : validValues) {
ICompletionProposal proposal = createCompletionProposal(String.format("\"%s\"", validValue), new StyledString(validValue), getImage(model), 0, context.getPrefix(), context);
if (proposal instanceof ConfigurableCompletionProposal) {
((ConfigurableCompletionProposal) proposal).setAdditionalProposalInfo(info);
}
acceptor.accept(proposal);
}
return;
}
super.completeConfiguredParameter_NewValue(model, assignment, context, acceptor);
}
@Override
protected Object text(final JvmField element) {
String _simpleName = element.getSimpleName();
StyledString _styledString = new StyledString(_simpleName);
String _simpleName_1 = element.getType().getSimpleName();
String _plus = (" : " + _simpleName_1);
StyledString _styledString_1 = new StyledString(_plus, StyledString.DECORATIONS_STYLER);
return _styledString.append(_styledString_1);
}
@Override
public StyledString getStyledText(Object element) {
if (element instanceof ExampleData) {
return new StyledString(((ExampleData) element).getTitle());
} else if (element instanceof ExampleCategory) {
return new StyledString(((ExampleCategory) element).getTitle());
}
return null;
}
public DatabaseDriversLabelProvider(){
super();
boldgreen = new StyledString.Styler(){
@Override
public void applyStyles(TextStyle textStyle) {
textStyle.font = BonitaStudioFontRegistry.getActiveFont();
textStyle.foreground = Display.getCurrent().getSystemColor(SWT.COLOR_DARK_GREEN);
}
};
}
@Override
public void update(ViewerCell cell) {
StyledString styledString = new StyledString();
DiffNode node = (DiffNode)cell.getElement();
if (node.getLeft()!=null){
styledString.append(getText(cell.getElement()),boldgreen);
} else {
styledString.append(getText(cell.getElement()));
}
cell.setText(styledString.getString());
cell.setImage(getImage(cell.getElement())) ;
cell.setStyleRanges(styledString.getStyleRanges());
}
/** Compute the text for the given JVM constructor, which is usually a inherited constructor.
*
* @param modelElement the model
* @return the text.
*/
protected CharSequence _text(JvmConstructor modelElement) {
if (this.labelProvider instanceof IStyledLabelProvider) {
final StyledString str = ((IStyledLabelProvider) this.labelProvider).getStyledText(modelElement);
str.setStyle(0, str.length(), ColoringLabelProvider.INHERITED_STYLER);
return str;
}
return this.labelProvider.getText(modelElement);
}
public StyledString getStyledLabel() {
StyledString result = new StyledString("App Engine");
result.append(" [", StyledString.QUALIFIER_STYLER);
result.append(getEnvironmentType(), StyledString.QUALIFIER_STYLER);
result.append(": ", StyledString.QUALIFIER_STYLER);
result.append(getRuntime(), StyledString.QUALIFIER_STYLER);
result.append("]", StyledString.QUALIFIER_STYLER);
result.append(" - " + descriptorFile.getName(), StyledString.DECORATIONS_STYLER);
return result;
}
private IJavaCompletionProposal createLabelProposal(CompletionProposal proposal) {
String completion= String.valueOf(proposal.getCompletion());
int start= proposal.getReplaceStart();
int length= getLength(proposal);
StyledString label= fLabelProvider.createSimpleLabel(proposal);
int relevance= computeRelevance(proposal);
return new JavaCompletionProposal(completion, start, length, null, label, relevance);
}
private StyledString getStyledString(Object element) {
StyledString styledString = new StyledString();
if (element instanceof SimpleField) {
appendTypeLabel(((SimpleField) element).getType(), styledString);
} else if (element instanceof FieldType) {
appendTypeLabel((FieldType) element, styledString);
} else if (element instanceof RelationField && ((RelationField) element).getReference() != null) {
styledString.append(((RelationField) element).getReference().getSimpleName());
} else if (element instanceof BusinessObject) {
styledString.append(((BusinessObject) element).getSimpleName());
}
return styledString;
}
@Test public void testGetStyledTextFallbackText() throws Exception {
DefaultEObjectLabelProvider defaultLabelProvider = new DefaultEObjectLabelProvider();
ParserRule parserRule = XtextFactory.eINSTANCE.createParserRule();
parserRule.setName("testCreateStyledString");
StyledString styledText = defaultLabelProvider.getStyledText(parserRule);
assertEquals("testCreateStyledString", styledText.getString());
}