Java Code Examples for org.eclipse.swt.custom.StyleRange

The following examples show how to use org.eclipse.swt.custom.StyleRange. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
/**
 * 刷新拼写检查中错误单词的样式
 * @param ranges
 */
public void refreshErrorWordsStyle(List<StyleRange> ranges){
	StyledText styledText = cellEditor.viewer.getTextWidget();
	List<StyleRange> oldRangeList = new ArrayList<StyleRange>();
	for(StyleRange oldRange : styledText.getStyleRanges()){
		if (oldRange.underlineStyle != SWT.UNDERLINE_ERROR) {
			oldRangeList.add(oldRange);
		}
	}
	styledText.setStyleRange(null);

	styledText.setStyleRanges(oldRangeList.toArray(new StyleRange[oldRangeList.size()]));
	if (ranges != null) {
		for (StyleRange range : ranges) {
			styledText.setStyleRange(range);
		}
	}
}
 
Example 2
Source Project: tlaplus   Source File: CoverageInformationItem.java    License: MIT License 6 votes vote down vote up
public void style(final TextPresentation textPresentation, final Color c, final Representation rep) {
	if (!isRoot()) {
		final StyleRange rs = new StyleRange();
		rs.start = region.getOffset();
		rs.length = region.getLength();
		rs.background = c;
		if ((rep == Representation.STATES_DISTINCT || rep == Representation.STATES) && !(this instanceof ActionInformationItem)) {
			rs.background = JFaceResources.getColorRegistry().get(ModuleCoverageInformation.GRAY);
			rs.borderStyle = SWT.NONE;
			rs.borderColor = null;
		} else if (rep != Representation.COST && rep.getValue(this, Grouping.INDIVIDUAL) == 0L) {
			rs.background = null;
			rs.borderStyle = SWT.BORDER_SOLID;
			rs.borderColor = JFaceResources.getColorRegistry().get(ModuleCoverageInformation.RED);
		}
		active = false;
		textPresentation.replaceStyleRange(addStlye(rs));
	}
	for (CoverageInformationItem child : childs) {
		child.style(textPresentation, c, rep);
	}
}
 
Example 3
Source Project: pentaho-kettle   Source File: UrlFormatRule.java    License: Apache License 2.0 6 votes vote down vote up
public Format execute( String value ) {
  Format format = new Format();
  Matcher matcher = parse( value );
  List<StyleRange> styleRanges = new ArrayList<>();
  while ( matcher.find() ) {
    StyleRange styleRange = new StyleRange();
    styleRange.start = value.indexOf( matcher.group( 0 ) );
    styleRange.length = matcher.group( 1 ).length();
    styleRange.data = matcher.group( 2 );
    styleRange.underlineStyle = SWT.UNDERLINE_LINK;
    styleRange.underline = true;
    styleRanges.add( styleRange );
    value = value.replace( matcher.group( LINK_TEXT ), matcher.group( LINK_URL ) );
  }
  format.setStyleRanges( styleRanges );
  format.setText( value );
  return format;
}
 
Example 4
Source Project: saros   Source File: ChatLine.java    License: GNU General Public License v2.0 6 votes vote down vote up
private void addHyperLinkListener(final StyledText text) {
  text.addListener(
      SWT.MouseDown,
      new Listener() {
        @Override
        public void handleEvent(Event event) {
          try {

            int offset = text.getOffsetAtLocation(new Point(event.x, event.y));

            StyleRange style = text.getStyleRangeAtOffset(offset);
            if (style != null && style.underline && style.underlineStyle == SWT.UNDERLINE_LINK) {
              String url = (String) style.data;
              SWTUtils.openInternalBrowser(url, url);
            }
          } catch (IllegalArgumentException e) {
            // no character under event.x, event.y
          }
        }
      });
}
 
Example 5
@Override
public void update(ViewerCell cell) {
   Object element = cell.getElement();

   StyledString styledString = getStyledText(element, cell.getColumnIndex());
   String newText = styledString.toString();

   StyleRange[] oldStyleRanges = cell.getStyleRanges();
   StyleRange[] newStyleRanges = isOwnerDrawEnabled() ? styledString.getStyleRanges() : null;

   if (!Arrays.equals(oldStyleRanges, newStyleRanges)) {
      cell.setStyleRanges(newStyleRanges);
   }

   cell.setText(newText);
   cell.setImage(getColumnImage(element, cell.getColumnIndex()));
   cell.setFont(getFont(element, cell.getColumnIndex()));
   cell.setForeground(getForeground(element, cell.getColumnIndex()));
   cell.setBackground(getBackground(element, cell.getColumnIndex()));

   // no super call required. changes on item will trigger the refresh.
}
 
Example 6
Source Project: Pydev   Source File: PyCodeFormatterPage.java    License: Eclipse Public License 1.0 6 votes vote down vote up
private void updateLabelExampleNow(FormatStd formatStd) {

        String str = "" +
                "                                   \n" +
                "                                   \n" +
                "                                   \n" +
                "                                   \n" +
                "class Example(object):             \n" +
                "                                   \n" +
                "    def Call(self, param1=None):   \n" +
                "        '''docstring'''            \n" +
                "        return param1 + 10 * 10    \n" +
                "                                   \n" +
                "                                   \n" +
                "                                   \n" +
                "    def Call2(self): #Comment      \n" +
                "        #Comment                   \n" +
                "        return self.Call(param1=10)" +
                "";
        Tuple<String, StyleRange[]> result = formatAndStyleRangeHelper.formatAndGetStyleRanges(formatStd, str,
                PyDevUiPrefs.getChainedPrefStore(), true);
        labelExample.setText(result.o1);
        labelExample.setStyleRanges(result.o2);
    }
 
Example 7
Source Project: Pydev   Source File: PyInformationPresenter.java    License: Eclipse Public License 1.0 6 votes vote down vote up
protected void adaptTextPresentation(TextPresentation presentation, int offset, int insertLength) {

        int yoursStart = offset;
        int yoursEnd = offset + insertLength - 1;
        yoursEnd = Math.max(yoursStart, yoursEnd);

        Iterator<StyleRange> e = presentation.getAllStyleRangeIterator();
        while (e.hasNext()) {

            StyleRange range = e.next();

            int myStart = range.start;
            int myEnd = range.start + range.length - 1;
            myEnd = Math.max(myStart, myEnd);

            if (myEnd < yoursStart) {
                continue;
            }

            if (myStart < yoursStart) {
                range.length += insertLength;
            } else {
                range.start += insertLength;
            }
        }
    }
 
Example 8
Source Project: statecharts   Source File: StyleRanges.java    License: Eclipse Public License 1.0 6 votes vote down vote up
public List<StyleRange> getRanges(String expression) {
	final List<StyleRange> ranges = Lists.newArrayList();
	DocumentEvent event = new DocumentEvent();
	event.fDocument = new DummyDocument(expression);
	DocumentTokenSource tokenSource = tokenSourceProvider.get();
	tokenSource.updateStructure(event);
	Iterator<ILexerTokenRegion> iterator = tokenSource.getTokenInfos().iterator();
	while (iterator.hasNext()) {
		ILexerTokenRegion next = iterator.next();
		TextAttribute attribute = attributeProvider.getAttribute(tokenTypeMapper.getId(next.getLexerTokenType()));
		StyleRange range = new StyleRange(next.getOffset(), next.getLength(), attribute.getForeground(),
				attribute.getBackground());
		range.font = attribute.getFont();
		range.fontStyle = attribute.getStyle();
		ranges.add(range);
	}
	return merge(ranges);
}
 
Example 9
Source Project: Pydev   Source File: PyInformationPresenterTest.java    License: Eclipse Public License 1.0 6 votes vote down vote up
public void testStyleRanges() throws Exception {
    PyInformationPresenter presenter = new PyInformationPresenter();
    TextPresentation presentation = new TextPresentation();
    String str = "@foo: <pydev_link link=\"itemPointer\">link</pydev_link> <pydev_hint_bold>bold</pydev_hint_bold>";

    Reader reader = presenter.createReader(str, presentation);
    String handled = StringUtils.readAll(reader);
    assertEquals("@foo: link bold", handled);
    Iterator<StyleRange> it = presentation.getAllStyleRangeIterator();
    ArrayList<String> tagsReplaced = new ArrayList<String>();

    ArrayList<String> expected = new ArrayList<String>();
    expected.add("<pydev_link link=\"itemPointer\">");
    expected.add("<pydev_hint_bold>");

    while (it.hasNext()) {
        PyStyleRange next = (PyStyleRange) it.next();
        tagsReplaced.add(next.tagReplaced);
    }
    assertEquals(expected, tagsReplaced);
}
 
Example 10
private void resetViewerBackground(StyleRange[] oldRanges) {

		if (oldRanges == null)
			return;

		if (fInput == null)
			return;

		StyledText text= fInput.fViewer.getTextWidget();
		if (text == null || text.isDisposed())
			return;

		// set the ranges one by one
		for (int i= 0; i < oldRanges.length; i++) {
			text.setStyleRange(oldRanges[i]);
		}
	}
 
Example 11
protected void testHighlighting(StyledText styledText, String text, int fontStyle, int foregroundR, int foregroundG, int foregroundB,
		int backgroundR, int backgroundG, int backgroundB) {
	Color expectedForegroundColor = new Color(null, foregroundR, foregroundG, foregroundB);
	Color expectedBackgroundColor = new Color(null, backgroundR, backgroundG, backgroundB);

	String content = styledText.getText();
	int offset = getStartPosition(content, text);
	assertNotEquals("Cannot locate '" + text + "' in " + content, -1, offset);

	for (int i = 0; i < text.length(); i++) {
		int currentPosition = offset + i;
		String character = styledText.getTextRange(currentPosition, 1);
		StyleRange styleRange = styledText.getStyleRangeAtOffset(currentPosition);
		if (isRelevant(character)) {
			assertFontStyle(styleRange, character, fontStyle);
			assertForegroundColor(styleRange, character, expectedForegroundColor);
			assertBackgroundColor(styleRange, character, expectedBackgroundColor);
		}
	}
}
 
Example 12
@Override
public void replaceStyleRanges(int start, int length, StyleRange[] styles) {
    checkWidget();
    if (isListening(ST.LineGetStyle)) {
        return;
    }
    if (styles == null) {
        SWT.error(SWT.ERROR_NULL_ARGUMENT);
    }
    RangesInfo rangesInfo = createRanges(styles, this.getCharCount());
    int[] newRanges = rangesInfo.newRanges;
    styles = rangesInfo.styles;
    try {
        setStyleRanges(start, length, newRanges, styles);
    } catch (Exception e) {
        Log.log(e);
    }
}
 
Example 13
protected void changeStyles(){
    final StyleRange [] srs = new StyleRange[styleList.size()];
    styleList.toArray(srs);

    getDisplay().asyncExec(new Runnable(){
        public void run(){
            for (int i = 0; i < srs.length; i++){
                try{
                    //System.out.println("Style Range: "+srs[i]);
                    getViewer().getTextWidget().setStyleRange(srs[i]);
                }
                catch(Exception e){
                    System.out.println("Seting Style Range Ex: "+e.getMessage());
                }
            }
        };
    });        
}
 
Example 14
Source Project: e4macs   Source File: BufferDialog.java    License: Eclipse Public License 1.0 6 votes vote down vote up
private Control createBufferTip(Composite parent, IEditorReference ref) {

		Composite result = new Composite(parent, SWT.NO_FOCUS);
		Color bg = parent.getBackground();
		result.setBackground(bg);
		GridLayout gridLayout = new GridLayout();
		gridLayout.numColumns = 1;
		result.setLayout(gridLayout);

		StyledText name = new StyledText(result, SWT.READ_ONLY | SWT.HIDE_SELECTION);
		// italics results in slightly clipped text unless extended
		String text = ref.getTitleToolTip() + ' ';
		name.setText(text);
		name.setBackground(bg);
		name.setCaret(null);
		StyleRange styleIt = new StyleRange(0, text.length(), null, bg);
		styleIt.fontStyle = SWT.ITALIC;
		name.setStyleRange(styleIt);
		
		return result;
	}
 
Example 15
Source Project: tlaplus   Source File: TLCUIHelperTest.java    License: MIT License 6 votes vote down vote up
@Test
public void testTLAandPCalLocations() {
	final String text =
			// PCal
			"Failure of assertion at line " + line	+ ", column " + beginColumn + ".\n" +
			// TLA
			"4. Line " + line+ ", column " + beginColumn + " to line " + line + ", column "	+ endColumn + " in " + module;

	final List<StyleRange> ranges = TLCUIHelper.setTLCLocationHyperlinks(text);

	// check if we get expected amount of locations
	Assert.assertEquals(2, ranges.size());
	
	// check each location individually
	for (final StyleRange range : ranges) {
		if (range.data instanceof Location) {
			final Location location = (Location) range.data;
			Assert.assertEquals(module, location.source());
			Assert.assertEquals(line, location.beginLine());
			Assert.assertEquals(beginColumn, location.beginColumn());
			// ignore end line and endColumn here as the PCal matcher does
			// not know and hence set this information.
		}
	}
}
 
Example 16
Source Project: LogViewer   Source File: DamageRepairer.java    License: Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Adds style information to the given text presentation.
 *
 * @param presentation the text presentation to be extended
 * @param offset the offset of the range to be styled
 * @param length the length of the range to be styled
 * @param attr the attribute describing the style of the range to be styled
 * @param wholeLine the boolean switch to declare that the whole line should be colored
 */
private void addRange(TextPresentation presentation, int offset, int length, TextAttribute attr, boolean wholeLine) {
    if (attr != null) {
        int style= attr.getStyle();
        int fontStyle= style & (SWT.ITALIC | SWT.BOLD | SWT.NORMAL);
        if(wholeLine) {
            try {
                int line = document.getLineOfOffset(offset);
                int start = document.getLineOffset(line);
                length = document.getLineLength(line);
                offset = start;
            } catch (BadLocationException e) {
            }
        }
        StyleRange styleRange = new StyleRange(offset,length,attr.getForeground(),attr.getBackground(),fontStyle);
        styleRange.strikeout = (style & TextAttribute.STRIKETHROUGH) != 0;
        styleRange.underline = (style & TextAttribute.UNDERLINE) != 0;
        presentation.addStyleRange(styleRange);
    }
}
 
Example 17
Source Project: tmxeditor8   Source File: HsMultiCellEditor.java    License: GNU General Public License v2.0 6 votes vote down vote up
public void highlightedTerms(List<String> terms) {
	if (!isValid()) {
		return;
	}
	StyledText styledText = cellEditor.viewer.getTextWidget();
	String text = styledText.getText();
	char[] source = text.toCharArray();
	List<StyleRange> ranges = new ArrayList<StyleRange>();
	TextStyle style = new TextStyle(cellEditor.getSegmentViewer().getTextWidget().getFont(), null,
			ColorConfigBean.getInstance().getHighlightedTermColor());
	for (String term : terms) {
		ranges.addAll(calculateTermsStyleRange(source, term.toCharArray(), style));
	}
	for (StyleRange range : ranges) {
		styledText.setStyleRange(range);
	}
}
 
Example 18
/**
 * 根据传入的相关参数获取错误单词的样式	robert	2013-01-22
 * @param style
 * @param start
 * @param length
 * @return
 */
private StyleRange getErrorWordRange(TextStyle style, int start, int length){
	StyleRange range = new StyleRange(style);
	range.start = start;
	range.length = length;
	range.underline = true;
	range.underlineStyle = SWT.UNDERLINE_ERROR;
	range.underlineColor = ColorConfigBean.getInstance().getErrorWordColor();
	return range;
}
 
Example 19
/**
 * {@inheritDoc}
 * <p>
 * Performance optimization: since we know at this place
 * that none of the clients expects the given range to be
 * untouched we reuse the given range as return value.
 * </p>
 */
@Override
protected StyleRange modelStyleRange2WidgetStyleRange(StyleRange range) {
	IRegion region= modelRange2WidgetRange(new Region(range.start, range.length));
	if (region != null) {
		// don't clone the style range, but simply reuse it.
		range.start= region.getOffset();
		range.length= region.getLength();
		return range;
	}
	return null;
}
 
Example 20
Source Project: nebula   Source File: HTMLStyledTextParser.java    License: Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Constructor
 *
 * @param styledText styled text to analyze
 */
HTMLStyledTextParser(final StyledText styledText) {
	this.styledText = styledText;
	listOfStyles = new ArrayList<StyleRange>();
	stack = new LinkedList<StyleRange>();
	final FontData data = styledText.getFont().getFontData()[0];
	defaultHeight = data.getHeight();
}
 
Example 21
Source Project: nebula   Source File: HTMLStyledTextParser.java    License: Eclipse Public License 2.0 5 votes vote down vote up
private StyleRange[] removeDoublons() {
	final Iterator<StyleRange> mainIt = listOfStyles.iterator();
	while (mainIt.hasNext()) {
		final StyleRange current = mainIt.next();
		final Iterator<StyleRange> it = listOfStyles.iterator();
		while (it.hasNext()) {
			final StyleRange other = it.next();
			if (current == other) {
				continue;
			}
			if (current.start == other.start && current.length == other.length) {
				current.fontStyle = current.fontStyle | other.fontStyle;
				if (current.font == null) {
					current.font = other.font;
				}
				if (current.foreground == null) {
					current.foreground = other.foreground;
				}
				if (current.background == null) {
					current.background = other.background;
				}
				it.remove();
			}
		}
	}

	return listOfStyles.toArray(new StyleRange[listOfStyles.size()]);
}
 
Example 22
Source Project: nebula   Source File: HTMLStyledTextParser.java    License: Eclipse Public License 2.0 5 votes vote down vote up
private void processBeginBold() {
	final StyleRange currentStyleRange = new StyleRange();
	currentStyleRange.start = currentPosition;
	currentStyleRange.length = 0;
	currentStyleRange.fontStyle = SWT.BOLD;
	currentStyleRange.data = "</b>";
	stack.push(currentStyleRange);
}
 
Example 23
Source Project: statecharts   Source File: StyleRanges.java    License: Eclipse Public License 1.0 5 votes vote down vote up
protected List<StyleRange> merge(List<StyleRange> ranges) {
	List<StyleRange> result = new ArrayList<>();
	for (StyleRange styleRange : ranges) {
		if (result.isEmpty()) {
			result.add(styleRange);
			continue;
		}
		StyleRange lastRange = result.get(result.size() - 1);
		if (equal(lastRange, styleRange)) {
			lastRange.length += styleRange.length;
		} else
			result.add(styleRange);
	}
	return result;
}
 
Example 24
Source Project: tlaplus   Source File: TLCUIHelper.java    License: MIT License 5 votes vote down vote up
public static void openTLCLocationHyperlink(StyledText styledText, MouseEvent trigger, Model model, Set<Class<? extends ITextEditor>> blacklist)
{
    try
    {
        int offset = styledText.getOffsetAtLocation(new Point(trigger.x, trigger.y));
        StyleRange range = styledText.getStyleRangeAtOffset(offset);
        if (range != null)
        {
            Object data = range.data;
            if (data instanceof Location)
            {
                boolean jumpToSavedModule = jumpToSavedLocation((Location) data, model, blacklist);
                if (!jumpToSavedModule)
                {
                    UIHelper.jumpToLocation((Location) data, (trigger.stateMask & SWT.MOD1) != 0, null);
                }
            }
        }
    } catch (IllegalArgumentException e)
    {
        /*
         * This type of exception can occur if the mouse event does
         * not correspond to an area of text in the styled text widget.
         * In this case, just do nothing.
         */
    }
}
 
Example 25
Source Project: nebula   Source File: HTMLStyledTextParser.java    License: Eclipse Public License 2.0 5 votes vote down vote up
private void processBeginColor() {
	final StyleRange currentStyleRange = new StyleRange();
	currentStyleRange.start = currentPosition;
	currentStyleRange.length = 0;
	currentStyleRange.fontStyle = SWT.NONE;
	currentStyleRange.foreground = computeColor();
	currentStyleRange.data = "</color>";
	stack.push(currentStyleRange);
}
 
Example 26
Source Project: nebula   Source File: HTMLStyledTextParser.java    License: Eclipse Public License 2.0 5 votes vote down vote up
private void processBeginBackgroundColor() {
	final StyleRange currentStyleRange = new StyleRange();
	currentStyleRange.start = currentPosition;
	currentStyleRange.length = 0;
	currentStyleRange.fontStyle = SWT.NONE;
	currentStyleRange.background = computeColor();
	currentStyleRange.data = "</backgroundcolor>";
	stack.push(currentStyleRange);
}
 
Example 27
public void testWrongRanges2() {
    StyleRange[] styles = new StyleRange[] {
            new StyleRange(2, 2, null, null),
            new StyleRange(0, 2, null, null),
            new StyleRange(5, 5, null, null),
    };
    RangesInfo rangesInfo = StyledTextWithoutVerticalBar.createRanges(styles, 10);
    int[] ranges = rangesInfo.newRanges;
    Assert.assertArrayEquals(new int[] { 2, 2, 5, 5 }, ranges);
    assertEquals(2, rangesInfo.styles.length);
    assertEquals(2, rangesInfo.styles[0].start);
    assertEquals(2, rangesInfo.styles[0].length);
    assertEquals(5, rangesInfo.styles[1].start);
    assertEquals(5, rangesInfo.styles[1].length);
}
 
Example 28
Source Project: ldparteditor   Source File: SyntaxFormatter.java    License: MIT License 5 votes vote down vote up
/**
 * Extends the style range of the text with a warning-underline-style.
 *
 * @param range
 *            the reference to the style range
 */
private void setWarningStyle(StyleRange range) {
    range.underline = true;
    range.underlineStyle = SWT.UNDERLINE_SQUIGGLE;
    range.underlineColor = Colour.line_warning_underline[0];
    range.length = range.length - 1;
}
 
Example 29
Source Project: n4js   Source File: SourceMapView.java    License: Eclipse Public License 1.0 5 votes vote down vote up
private static void doStyleText(StyledText text, Color colorBackground, int start, int end) {
	final int max = text.getCharCount();
	if (end >= max) {
		end = max - 1;
	}
	if (start < 0 || end < 0 || start > end || end - start == 0) {
		return;
	}
	StyleRange styleRange = new StyleRange();
	styleRange.start = start;
	styleRange.length = end - start;
	styleRange.background = colorBackground;
	text.setStyleRange(styleRange);
}
 
Example 30
@Override
protected StyleRange prepareStyleRange(StyleRange styleRange, boolean applyColors) {
    if (!applyColors && styleRange.background != null) {
        styleRange = super.prepareStyleRange(styleRange, applyColors);
        styleRange.borderStyle = SWT.BORDER_DOT;
        return styleRange;
    }
    return super.prepareStyleRange(styleRange, applyColors);
}