/** * Returns the difference between the baseline of the widget and the baseline as specified by the * font for <code>gc</code>. When drawing line numbers, the returned bias should be added to * obtain text lined up on the correct base line of the text widget. * * @param gc the {@code GC} to get the font metrics from * @param widgetLine the widget line * @return the baseline bias to use when drawing text that is lined up with the text widget. */ private int getBaselineBias(GC gc, int widgetLine) { ITextViewer textViewer = getParentRuler().getTextViewer(); int offset = textViewer.getTextWidget().getOffsetAtLine(widgetLine); int widgetBaseline = textViewer.getTextWidget().getBaseline(offset); FontMetrics fm = gc.getFontMetrics(); int fontBaseline = fm.getAscent() + fm.getLeading(); int baselineBias = widgetBaseline - fontBaseline; return Math.max(0, baselineBias); }
/** * Use hyperlink detectors to find a text viewer's hyperlinks and return the style ranges to * render them. * * @param textViewer * @param hyperlinkDetectors * @return the style ranges to render the detected hyperlinks */ public static StyleRange[] getHyperlinkDetectorStyleRanges( ITextViewer textViewer, IHyperlinkDetector[] hyperlinkDetectors) { List<StyleRange> styleRangeList = new ArrayList<StyleRange>(); if (hyperlinkDetectors != null && hyperlinkDetectors.length > 0) { for (int i = 0; i < textViewer.getTextWidget().getText().length(); i++) { IRegion region = new Region(i, 0); for (IHyperlinkDetector hyperLinkDetector : hyperlinkDetectors) { IHyperlink[] hyperlinks = hyperLinkDetector.detectHyperlinks(textViewer, region, true); if (hyperlinks != null) { for (IHyperlink hyperlink : hyperlinks) { StyleRange hyperlinkStyleRange = new StyleRange( hyperlink.getHyperlinkRegion().getOffset(), hyperlink.getHyperlinkRegion().getLength(), Display.getDefault().getSystemColor(SWT.COLOR_BLUE), Display.getDefault().getSystemColor(SWT.COLOR_WHITE)); hyperlinkStyleRange.underline = true; styleRangeList.add(hyperlinkStyleRange); } } } } } StyleRange[] styleRangeArray = new StyleRange[styleRangeList.size()]; styleRangeList.toArray(styleRangeArray); return styleRangeArray; }
/** * Creates a style range for the text viewer. * * @param viewer the text viewer * @return the new style range for the text viewer or <code>null</code> */ private StyleRange createStyleRange(ITextViewer viewer) { StyledText text = viewer.getTextWidget(); if (text == null || text.isDisposed()) { return null; } int widgetCaret = text.getCaretOffset(); int modelCaret = 0; if (viewer instanceof ITextViewerExtension5) { ITextViewerExtension5 extension = (ITextViewerExtension5) viewer; modelCaret = extension.widgetOffset2ModelOffset(widgetCaret); } else { IRegion visibleRegion = viewer.getVisibleRegion(); modelCaret = widgetCaret + visibleRegion.getOffset(); } if (modelCaret >= getReplacementOffset() + getReplacementLength()) { return null; } int length = getReplacementOffset() + getReplacementLength() - modelCaret; Color foreground = getForegroundColor(); Color background = getBackgroundColor(); return new StyleRange(modelCaret, length, foreground, background); }
/** * Convert mouse screen coordinates to a <code>StyledText</code> offset. * * @param x screen X-coordinate * @param y screen Y-coordinate * @param absolute if <code>true</code>, coordinates are expected to be absolute screen * coordinates * @return text offset * @see StyledText#getOffsetAtLocation() */ private int getOffsetAtLocation(int x, int y, boolean absolute) { StyledText textWidget = fViewer.getTextWidget(); StyledTextContent content = textWidget.getContent(); Point location; if (absolute) { location = textWidget.toControl(x, y); } else { location = new Point(x, y); } int line = (textWidget.getTopPixel() + location.y) / textWidget.getLineHeight(); if (line >= content.getLineCount()) { return content.getCharCount(); } int lineOffset = content.getOffsetAtLine(line); String lineText = content.getLine(line); Point endOfLine = textWidget.getLocationAtOffset(lineOffset + lineText.length()); if (location.x >= endOfLine.x) { return lineOffset + lineText.length(); } try { return textWidget.getOffsetAtLocation(location); } catch (IllegalArgumentException iae) { // we are expecting this return -1; } }
public SpellingHelper(ISpellingSupport support, ITextViewer viewer) { this.support = support; this.viewer = viewer; this.control = viewer.getTextWidget(); this.contentAdapter = new StyledTextContentAdapter(); init(viewer); }
/** * Implementation of the <code>IAction</code> prototype. Checks if the selected lines are all * commented or not and uncomments/comments them respectively. */ @Override public void run() { if (fOperationTarget == null || fDocumentPartitioning == null || fPrefixesMap == null) return; final int operationCode; if (isSelectionCommented(fViewer.getSelectionProvider().getSelection())) operationCode = ITextOperationTarget.STRIP_PREFIX; else operationCode = ITextOperationTarget.PREFIX; Shell shell = fViewer.getTextWidget().getShell(); if (!fOperationTarget.canDoOperation(operationCode)) { if (shell != null) MessageDialog.openError( shell, "An error occured", "ToggleComment_error_message=An error occurred while toggling comments."); //$NON-NLS-1$//$NON-NLS-2$ return; } Display display = null; if (shell != null && !shell.isDisposed()) display = shell.getDisplay(); BusyIndicator.showWhile( display, new Runnable() { public void run() { fOperationTarget.doOperation(operationCode); } }); }
@SuppressWarnings("unchecked") private List<ScriptVariable> getScriptVariables(final ITextViewer viewer) { final List<ScriptVariable> result = new ArrayList<ScriptVariable>(); final List<ScriptVariable> nodes = (List<ScriptVariable>) viewer.getTextWidget().getData(GroovyViewer.PROCESS_VARIABLES_DATA_KEY); if (nodes != null) { result.addAll(nodes); } final List<ScriptVariable> providedScriptVariables = (List<ScriptVariable>) viewer.getTextWidget().getData(GroovyViewer.BONITA_KEYWORDS_DATA_KEY); if (providedScriptVariables != null) { result.addAll(providedScriptVariables); } return result; }
/** * @param textViewer check to see if this viewer is empty * @return <code>true</code> if there is no text or it's all white space, <code>false</code> * otherwise */ public static boolean isViewerEmpty(ITextViewer textViewer) { boolean isEmpty = false; String text = textViewer.getTextWidget().getText(); if ((text == null) || ((text != null) && text.trim().equals(""))) { // $NON-NLS-1$ isEmpty = true; } return isEmpty; }
/** * Creates a new painter for the given text viewer. * * @param textViewer the text viewer the painter should be attached to */ public WhitespaceCharacterPainter(ITextViewer textViewer) { super(); fTextViewer = textViewer; fTextWidget = textViewer.getTextWidget(); GC gc = new GC(fTextWidget); gc.setAdvanced(true); fIsAdvancedGraphicsPresent = gc.getAdvanced(); gc.dispose(); }
/** * Called when Ctrl is selected during the completions * * @see * org.eclipse.jface.text.contentassist.ICompletionProposalExtension2#selected(org.eclipse.jface.text.ITextViewer, * boolean) */ public void selected(ITextViewer viewer, boolean smartToggle) { if (smartToggle) { StyledText text = viewer.getTextWidget(); if (text == null || text.isDisposed()) { return; } int widgetCaret = text.getCaretOffset(); IDocument document = viewer.getDocument(); int finalOffset = widgetCaret; try { if (finalOffset >= document.getLength()) { unselected(viewer); return; } char c; do { c = document.getChar(finalOffset); finalOffset++; } while (isValidChar(c) && finalOffset < document.getLength()); if (c == '(') { fLastIsPar = true; } else { fLastIsPar = false; } if (!isValidChar(c)) { finalOffset--; } this.fLen = finalOffset - widgetCaret; this.getPresentationUpdater().updateStyle(viewer, widgetCaret, this.fLen); } catch (BadLocationException e) { Log.log(e); } } else { unselected(viewer); } }
private void invalidateTextPresentation() { if (fPresentation != null) { fPresentation = null; if (fViewer != null) { Display display = fViewer.getTextWidget().getDisplay(); if (display.getThread() != Thread.currentThread()) { display.asyncExec( new Runnable() { public void run() { if (fViewer != null) { fViewer.invalidateTextPresentation(); } } }); } else { fViewer.invalidateTextPresentation(); } } } }
private void updateStyle(ITextViewer viewer) { StyledText text = viewer.getTextWidget(); int widgetOffset = getWidgetOffset(viewer, fRememberedStyleRange.start); StyleRange range = new StyleRange(fRememberedStyleRange); range.start = widgetOffset; range.length = fRememberedStyleRange.length; StyleRange currentRange = text.getStyleRangeAtOffset(widgetOffset); if (currentRange != null) { range.strikeout = currentRange.strikeout; range.underline = currentRange.underline; range.fontStyle = currentRange.fontStyle; } // http://dev.eclipse.org/bugs/show_bug.cgi?id=34754 try { text.setStyleRange(range); } catch (IllegalArgumentException x) { // catching exception as offset + length might be outside of the text widget fRememberedStyleRange = null; } }
// modified version from TextViewer private int computeOffsetAtLocation(ITextViewer textViewer, int x, int y) { StyledText styledText = textViewer.getTextWidget(); IDocument document = textViewer.getDocument(); if (document == null) return -1; try { int widgetOffset = styledText.getOffsetAtLocation(new Point(x, y)); Point p = styledText.getLocationAtOffset(widgetOffset); if (p.x > x) widgetOffset--; if (textViewer instanceof ITextViewerExtension5) { ITextViewerExtension5 extension = (ITextViewerExtension5) textViewer; return extension.widgetOffset2ModelOffset(widgetOffset); } else { IRegion visibleRegion = textViewer.getVisibleRegion(); return widgetOffset + visibleRegion.getOffset(); } } catch (IllegalArgumentException e) { return -1; } }
public static PeerCharacterCloser install(ITextViewer textViewer, char[] pairs) { PeerCharacterCloser pairMatcher = new PeerCharacterCloser(textViewer, pairs); textViewer.getTextWidget().addVerifyKeyListener(pairMatcher); return pairMatcher; }
/* * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension2#apply(org.eclipse.jface.text.ITextViewer, char, int, int) */ @Override public void apply(ITextViewer viewer, char trigger, int stateMask, int offset) { IDocument document = viewer.getDocument(); try { fContext.setReadOnly(false); int start; TemplateBuffer templateBuffer; try { beginCompoundChange(viewer); int oldReplaceOffset = getReplaceOffset(); try { // this may already modify the document (e.g. add imports) templateBuffer = fContext.evaluate(fTemplate); } catch (TemplateException e1) { fSelectedRegion = fRegion; return; } start = getReplaceOffset(); int shift = start - oldReplaceOffset; int end = Math.max(getReplaceEndOffset(), offset + shift); // insert template string if (end > document.getLength()) end = offset; String templateString = templateBuffer.getString(); document.replace(start, end - start, templateString); } finally { endCompoundChange(viewer); } // translate positions LinkedModeModel model = new LinkedModeModel(); TemplateVariable[] variables = templateBuffer.getVariables(); MultiVariableGuess guess = fContext instanceof CompilationUnitContext ? ((CompilationUnitContext) fContext).getMultiVariableGuess() : null; boolean hasPositions = false; for (int i = 0; i != variables.length; i++) { TemplateVariable variable = variables[i]; if (variable.isUnambiguous()) continue; LinkedPositionGroup group = new LinkedPositionGroup(); int[] offsets = variable.getOffsets(); int length = variable.getLength(); LinkedPosition first; if (guess != null && variable instanceof MultiVariable) { first = new VariablePosition( document, offsets[0] + start, length, guess, (MultiVariable) variable); guess.addSlave((VariablePosition) first); } else { String[] values = variable.getValues(); ICompletionProposal[] proposals = new ICompletionProposal[values.length]; for (int j = 0; j < values.length; j++) { ensurePositionCategoryInstalled(document, model); Position pos = new Position(offsets[0] + start, length); document.addPosition(getCategory(), pos); proposals[j] = new PositionBasedCompletionProposal(values[j], pos, length); } if (proposals.length > 1) first = new ProposalPosition(document, offsets[0] + start, length, proposals); else first = new LinkedPosition(document, offsets[0] + start, length); } for (int j = 0; j != offsets.length; j++) if (j == 0) group.addPosition(first); else group.addPosition(new LinkedPosition(document, offsets[j] + start, length)); model.addGroup(group); hasPositions = true; } if (hasPositions) { model.forceInstall(); JavaEditor editor = getJavaEditor(); if (editor != null) { model.addLinkingListener(new EditorHighlightingSynchronizer(editor)); } LinkedModeUI ui = new EditorLinkedModeUI(model, viewer); ui.setExitPosition(viewer, getCaretOffset(templateBuffer) + start, 0, Integer.MAX_VALUE); ui.enter(); fSelectedRegion = ui.getSelectedRegion(); } else { fSelectedRegion = new Region(getCaretOffset(templateBuffer) + start, 0); } } catch (BadLocationException e) { JavaPlugin.log(e); openErrorDialog(viewer.getTextWidget().getShell(), e); fSelectedRegion = fRegion; } catch (BadPositionCategoryException e) { JavaPlugin.log(e); openErrorDialog(viewer.getTextWidget().getShell(), e); fSelectedRegion = fRegion; } }
public void gotoMatchingBracket() { ITextViewer sourceViewer = langEditor.getSourceViewer_(); IDocument document = sourceViewer.getDocument(); if (document == null) return; IRegion selection = EditorUtils.getSignedSelection(sourceViewer); if (fPreviousSelections == null) initializePreviousSelectionList(); IRegion region = getBracketMatcher().match(document, selection.getOffset(), selection.getLength()); if (region == null) { region = getBracketMatcher() .findEnclosingPeerCharacters(document, selection.getOffset(), selection.getLength()); initializePreviousSelectionList(); fPreviousSelections.add(selection); } else { if (fPreviousSelections.size() == 2) { if (!selection.equals(fPreviousSelections.get(1))) { initializePreviousSelectionList(); } } else if (fPreviousSelections.size() == 3) { if (selection.equals(fPreviousSelections.get(2)) && !selection.equals(fPreviousSelections.get(0))) { IRegion originalSelection = fPreviousSelections.get(0); sourceViewer.setSelectedRange( originalSelection.getOffset(), originalSelection.getLength()); sourceViewer.revealRange(originalSelection.getOffset(), originalSelection.getLength()); initializePreviousSelectionList(); return; } initializePreviousSelectionList(); } } if (region == null) { langEditor.setStatusLineErrorMessage( LangEditorMessages.GotoMatchingBracket_error_noMatchingBracket); sourceViewer.getTextWidget().getDisplay().beep(); return; } int offset = region.getOffset(); int length = region.getLength(); if (length < 1) return; int anchor = getBracketMatcher().getAnchor(); // http://dev.eclipse.org/bugs/show_bug.cgi?id=34195 int targetOffset = (ICharacterPairMatcher.RIGHT == anchor) ? offset + 1 : offset + length - 1; boolean visible = false; if (sourceViewer instanceof ITextViewerExtension5) { ITextViewerExtension5 extension = (ITextViewerExtension5) sourceViewer; visible = (extension.modelOffset2WidgetOffset(targetOffset) > -1); } else { IRegion visibleRegion = sourceViewer.getVisibleRegion(); // http://dev.eclipse.org/bugs/show_bug.cgi?id=34195 visible = (targetOffset >= visibleRegion.getOffset() && targetOffset <= visibleRegion.getOffset() + visibleRegion.getLength()); } if (!visible) { langEditor.setStatusLineErrorMessage( LangEditorMessages.GotoMatchingBracket_error_bracketOutsideSelectedElement); sourceViewer.getTextWidget().getDisplay().beep(); return; } int adjustment = getBracketMatcher() .getOffsetAdjustment( document, selection.getOffset() + selection.getLength(), selection.getLength()); targetOffset += adjustment; int direction = (selection.getLength() == 0) ? 0 : ((selection.getLength() > 0) ? 1 : -1); if (fPreviousSelections.size() == 1 && direction < 0) { targetOffset++; } if (fPreviousSelections.size() > 0) { fPreviousSelections.add(new Region(targetOffset, direction)); } sourceViewer.setSelectedRange(targetOffset, direction); sourceViewer.revealRange(targetOffset, direction); }