下面列出了org.eclipse.swt.widgets.Layout#org.eclipse.swt.custom.StyledText 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Sets the font for the given viewer sustaining selection and scroll position.
*
* @param font the font
*/
private void applyFont(Font font) {
IDocument doc = getDocument();
if (doc != null && doc.getLength() > 0) {
Point selection = getSelectedRange();
int topIndex = getTopIndex();
StyledText styledText = getTextWidget();
styledText.setRedraw(false);
styledText.setFont(font);
setSelectedRange(selection.x, selection.y);
setTopIndex(topIndex);
styledText.setRedraw(true);
} else {
getTextWidget().setFont(font);
}
}
/**
* @return a styled text that can be used to show code with the colors based on the color cache received.
*/
public StyledText createStyledTextForCodePresentation(Composite parent) {
styledText = new StyledText(parent, SWT.BORDER | SWT.READ_ONLY);
this.backgroundColorCache = new ColorAndStyleCache(new PreferenceStore());
this.colorCache = new ColorAndStyleCache(null);
try {
styledText.setFont(new Font(parent.getDisplay(), FontUtils.getFontData(IFontUsage.STYLED, true)));
} catch (Throwable e) {
//ignore
}
updateBackgroundColor();
PyDevUiPrefs.getChainedPrefStore().addPropertyChangeListener(this);
return styledText;
}
@Override
protected void setupEditMode() {
checkWidget();
StyledText text = viewer.getTextWidget();
if (!close) {
if (editable) {
return;
}
text.removeVerifyKeyListener(readOnly_VerifyKey);
}
editable = true;
text.setEditable(true);
text.addVerifyKeyListener(edit_VerifyKey);
text.addTraverseListener(edit_Traverse);
}
/**
* Draw square of the given rgb.
*
* @param rgb the rgb color
* @param gc the graphic context
* @param textWidget the text widget
* @param x the location y
* @param y the location y
* @return the square width.
*/
private int drawSquare(RGB rgb, GC gc, StyledText textWidget, int x, int y) {
FontMetrics fontMetrics = gc.getFontMetrics();
int size = getSquareSize(fontMetrics);
x += fontMetrics.getLeading();
y += fontMetrics.getDescent();
Rectangle rect = new Rectangle(x, y, size, size);
// Fill square
gc.setBackground(getColor(rgb, textWidget.getDisplay()));
gc.fillRectangle(rect);
// Draw square box
gc.setForeground(textWidget.getForeground());
gc.drawRectangle(rect);
return getSquareWidth(gc.getFontMetrics());
}
/**
* @see org.eclipse.jface.contentassist.IContentAssistSubjectControl#removeVerifyKeyListener(org.eclipse.swt.custom.VerifyKeyListener)
*/
public void removeVerifyKeyListener(VerifyKeyListener verifyKeyListener)
{
if (fContentAssistSubjectControl != null)
{
fContentAssistSubjectControl.removeVerifyKeyListener(verifyKeyListener);
}
else if (fViewer instanceof ITextViewerExtension)
{
ITextViewerExtension extension = (ITextViewerExtension) fViewer;
extension.removeVerifyKeyListener(verifyKeyListener);
}
else
{
StyledText textWidget = fViewer.getTextWidget();
if (Helper.okToUse(textWidget))
{
textWidget.removeVerifyKeyListener(verifyKeyListener);
}
}
}
@Override
public void mouseUp(MouseEvent e) {
Widget w = e.widget;
if (w instanceof StyledText) {
StyledText styledText = (StyledText) w;
int offset = styledText.getCaretOffset();
if (offset >= 0 && offset < styledText.getCharCount()) {
StyleRange styleRangeAtOffset = styledText.getStyleRangeAtOffset(offset);
if (styleRangeAtOffset instanceof StyleRangeWithCustomData) {
StyleRangeWithCustomData styleRangeWithCustomData = (StyleRangeWithCustomData) styleRangeAtOffset;
Object l = styleRangeWithCustomData.customData;
if (l instanceof IHyperlink) {
((IHyperlink) l).linkActivated();
}
}
}
}
}
/**
* @param control control on which the listener will be added
* @return a BaseControlFocus Listener that can be attached to the events
* focusLost, focusGained and controlResized
*/
static BaseFocusControlListener getFocusControlListenerFor(final Control control) {
if (control instanceof Combo) {
return new ComboFocusControlListener((Combo) control);
}
if (control instanceof CCombo) {
return new CComboFocusControlListener((CCombo) control);
}
if (control instanceof Text) {
return new TextFocusControlListener((Text) control);
}
if (control instanceof StyledText) {
return new StyledTextFocusControlListener((StyledText) control);
}
throw new IllegalArgumentException("Control should be a Text, a Combo, a CCombo or a StyledText widget");
}
public void createLogDetail() {
tabFolderLogDetail = new CTabFolder(sashFormLog, SWT.CLOSE | SWT.BORDER);
tabFolderLogDetail.setTabHeight(0);
tabFolderLogDetail.marginHeight = 0;
tabFolderLogDetail.marginWidth = 0;
tabFolderLogDetail.setMaximizeVisible(false);
tabFolderLogDetail.setMinimizeVisible(false);
//tabFolderLogDetail.setSelectionBackground(new Color(display, new RGB(153, 186, 243)));
tabFolderLogDetail.setSimple(false);
tabFolderLogDetail.setUnselectedCloseVisible(true);
CTabItem tabItemLogList = new CTabItem(tabFolderLogDetail, SWT.NONE | SWT.MULTI
| SWT.V_SCROLL);
tabFolderLogDetail.setSelection(tabItemLogList);
//styledTextLog = new List(tabFolderLogDetail, SWT.BORDER);
styledTextLog = new StyledText(tabFolderLogDetail, SWT.BORDER | SWT.MULTI | SWT.H_SCROLL
| SWT.V_SCROLL | SWT.READ_ONLY);
styledTextLog.addLineStyleListener(new LogLineStyleListener(shell));
tabItemLogList.setControl(styledTextLog);
//sTextLog.setFont(new Font(display,"Courier New",10,SWT.NONE));
}
private StyledText buildEditorText( Composite parent){
final SourceViewer sourceViewer = new SourceViewer(parent, null, SWT.BORDER | SWT.MULTI | SWT.V_SCROLL | SWT.H_SCROLL);
final HConfiguration sourceConf = new HConfiguration(HContentAssistProcessor.PARAM_PROCESSOR);
sourceViewer.configure(sourceConf);
sourceViewer.setDocument(DocumentUtils.createDocument1());
sourceViewer.getControl().addKeyListener(new KeyAdapter() {
public void keyPressed( KeyEvent e){
// if ((e.character == ' ') && ((e.stateMask & SWT.CTRL) != 0)) {
if (Utils.isAutoAssistInvoked(e)) {
IContentAssistant ca = sourceConf.getContentAssistant(sourceViewer);
ca.showPossibleCompletions();
}
}
});
return sourceViewer.getTextWidget();
}
private void runFlasher(final int count, final StyledText item) {
if (count > 0) {
Display.getDefault().asyncExec(() -> {
item.setBackground(flash);
item.setVisible(true);
item.redraw();
item.update();
Display.getDefault().asyncExec(() -> {
try {
Thread.sleep(waitTime);
} catch (InterruptedException e) {}
item.setBackground(background);
item.redraw();
item.update();
runFlasher(count -1, item);
});
});
}
}
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
}
}
});
}
protected void initCellEditor() {
committed = false;
// Get the Text Compartments Edit Part
setEditText(getEditPart().getEditText());
IFigure label = getEditPart().getFigure();
Assert.isNotNull(label);
StyledText text = (StyledText) getCellEditor().getControl();
// scale the font accordingly to the zoom level
text.setFont(getScaledFont(label));
// Hook the cell editor's copy/paste actions to the actionBars so that
// they can
// be invoked via keyboard shortcuts.
actionBars = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor()
.getEditorSite().getActionBars();
saveCurrentActions(actionBars);
actionHandler = new CellEditorActionHandler(actionBars);
actionHandler.addCellEditor(getCellEditor());
actionBars.updateActionBars();
}
public int getCaretOffset()
{
ISourceViewer sourceViewer = getSourceViewer();
if (sourceViewer == null)
{
return -1;
}
StyledText styledText = sourceViewer.getTextWidget();
if (styledText == null)
{
return -1;
}
if (sourceViewer instanceof ITextViewerExtension5)
{
ITextViewerExtension5 extension = (ITextViewerExtension5) sourceViewer;
return extension.widgetOffset2ModelOffset(styledText.getCaretOffset());
}
int offset = sourceViewer.getVisibleRegion().getOffset();
return offset + styledText.getCaretOffset();
}
@Override
protected void setupReadOnlyMode() {
checkWidget();
StyledText text = viewer.getTextWidget();
if (!close) {
if (!editable) {
return;
}
text.removeVerifyKeyListener(edit_VerifyKey);
text.removeTraverseListener(edit_Traverse);
}
editable = false;
text.setEditable(false);
text.addVerifyKeyListener(readOnly_VerifyKey);
}
protected void uninstall() {
if (getViewer() == null || !fIsTextDragAndDropInstalled) { return; }
final IDragAndDropService dndService = editor.getSite().getService(IDragAndDropService.class);
if (dndService == null) { return; }
final StyledText st = getStyledText();
dndService.removeMergedDropTarget(st);
final DragSource dragSource = (DragSource) st.getData(DND.DRAG_SOURCE_KEY);
if (dragSource != null) {
dragSource.dispose();
st.setData(DND.DRAG_SOURCE_KEY, null);
}
fIsTextDragAndDropInstalled = false;
}
/**
* (non-Javadoc)
* @see net.heartsome.cat.ts.ui.editors.IXliffEditor#getSelectPureText()
*/
public String getSelectPureText() {
StyledTextCellEditor cellEditor = HsMultiActiveCellEditor.getFocusCellEditor();
String selectionText = null;
if (cellEditor != null && !cellEditor.isClosed()) {
StyledText styledText = cellEditor.getSegmentViewer().getTextWidget();
Point p = styledText.getSelection();
if (p != null) {
if (p.x != p.y) {
selectionText = cellEditor.getSelectedPureText();
} else {
selectionText = "";
}
}
}
if (selectionText != null) {
// 将换行符替换为空
selectionText = selectionText.replaceAll("\n", "");
}
return selectionText;
}
/**
* 初始化默认颜色、字体等
* @param textControl
* ;
*/
private void initStyle(final StyledText textControl, IStyle cellStyle) {
// textControl.setBackground(cellStyle.getAttributeValue(CellStyleAttributes.BACKGROUND_COLOR));
textControl.setBackground(GUIHelper.getColor(210, 210, 240));
textControl.setForeground(cellStyle.getAttributeValue(CellStyleAttributes.FOREGROUND_COLOR));
textControl.setLineSpacing(Constants.SEGMENT_LINE_SPACING);
textControl.setLeftMargin(Constants.SEGMENT_LEFT_MARGIN);
textControl.setRightMargin(Constants.SEGMENT_RIGHT_MARGIN);
textControl.setTopMargin(Constants.SEGMENT_TOP_MARGIN);
textControl.setBottomMargin(Constants.SEGMENT_TOP_MARGIN);
// textControl.setLeftMargin(0);
// textControl.setRightMargin(0);
// textControl.setTopMargin(0);
// textControl.setBottomMargin(0);
textControl.setFont(JFaceResources.getFont(net.heartsome.cat.ts.ui.Constants.XLIFF_EDITOR_TEXT_FONT));
textControl.setIME(new IME(textControl, SWT.NONE));
}
/**
* In the console context, use paste as
* in some consoles (e.g. org.eclipse.debug.internal.ui.views.console.ProcessConsole), updateText
* will not simulate keyboard input
*
* @param event the ExecutionEvent
* @param widget The consoles StyledText widget
*/
protected void paste(ExecutionEvent event, StyledText widget) {
IWorkbenchPart apart = HandlerUtil.getActivePart(event);
if (apart != null) {
try {
IWorkbenchPartSite site = apart.getSite();
if (site != null) {
IHandlerService service = (IHandlerService) site.getService(IHandlerService.class);
if (service != null) {
service.executeCommand(IEmacsPlusCommandDefinitionIds.EMP_PASTE, null);
KillRing.getInstance().setYanked(true);
}
}
} catch (CommandException e) {
}
}
}
/**
* Support exchange for simple mark on TextConsole
*
* @see com.mulgasoft.emacsplus.commands.IConsoleDispatch#consoleDispatch(org.eclipse.ui.console.TextConsoleViewer, org.eclipse.ui.console.IConsoleView, org.eclipse.core.commands.ExecutionEvent)
*/
public Object consoleDispatch(TextConsoleViewer viewer, IConsoleView activePart, ExecutionEvent event) {
int mark = viewer.getMark();
StyledText st = viewer.getTextWidget();
if (mark != -1) {
try {
st.setRedraw(false);
int offset = st.getCaretOffset();
viewer.setMark(offset);
st.setCaretOffset(mark);
int len = offset - mark;
viewer.setSelectedRange(offset, -len);
} finally {
st.setRedraw(true);
}
}
return null;
}
@Test
public void testTMHighlightInGenericEditorEdit() throws IOException, PartInitException {
f = File.createTempFile("test" + System.currentTimeMillis(), ".ts");
FileOutputStream fileOutputStream = new FileOutputStream(f);
fileOutputStream.write("let a = '';".getBytes());
fileOutputStream.close();
f.deleteOnExit();
editor = IDE.openEditor(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(),
f.toURI(), editorDescriptor.getId(), true);
StyledText text = (StyledText)editor.getAdapter(Control.class);
Assert.assertTrue(new DisplayHelper() {
@Override
protected boolean condition() {
return text.getStyleRanges().length > 1;
}
}.waitForCondition(text.getDisplay(), 3000));
int initialNumberOfRanges = text.getStyleRanges().length;
text.setText("let a = '';\nlet b = 10;\nlet c = true;");
Assert.assertTrue("More styles should have been added", new DisplayHelper() {
@Override protected boolean condition() {
return text.getStyleRanges().length > initialNumberOfRanges + 3;
}
}.waitForCondition(text.getDisplay(), 300000));
}
/**
* makes the associated text widget uneditable.
*/
public void setReadOnly() {
ConsolePlugin.getStandardDisplay().asyncExec(new Runnable() {
public void run() {
StyledText text = getTextWidget();
if (text != null && !text.isDisposed()) {
text.setEditable(false);
}
}
});
}
protected void pasteText(XtextEditor editor, String text) throws Exception {
StyledText textWidget = editor.getInternalSourceViewer().getTextWidget();
Point selection = textWidget.getSelection();
Event event = new Event();
event.start = selection.x;
event.end = selection.y;
event.text = text;
event.keyCode = KeyLookupFactory.getDefault().getCtrl();
textWidget.notifyListeners(SWT.KeyDown, event);
Method sendKeyEvent = textWidget.getClass().getDeclaredMethod("sendKeyEvent", Event.class);
sendKeyEvent.setAccessible(true);
sendKeyEvent.invoke(textWidget, event);
}
/**
* 将指定文本添加到光标所在位置。 robert 2011-12-21
* @param canonicalValue
* ;
*/
public void insertCanonicalValue(Object canonicalValue) {
StyledText text = viewer.getTextWidget();
if (text == null || text.isDisposed()) {
return;
}
int offset = text.getCaretOffset();
text.insert(canonicalValue.toString());
text.setCaretOffset(offset + canonicalValue.toString().length());
}
public Rectangle getInsertionBounds(Control control) {
StyledText text = (StyledText) control;
Point caretOrigin = text.getCaret().getLocation();
return new Rectangle(caretOrigin.x + text.getClientArea().x,
caretOrigin.y + text.getClientArea().y + 3, 1,
text.getLineHeight());
}
@Override
public int getCursorOffset() {
ISourceViewer sourceViewer = getSourceViewer();
StyledText styledText = sourceViewer.getTextWidget();
if (styledText == null) {
return 0;
}
if (sourceViewer instanceof ITextViewerExtension5) {
ITextViewerExtension5 extension = (ITextViewerExtension5) sourceViewer;
return extension.widgetOffset2ModelOffset(styledText.getCaretOffset());
} else {
int offset = sourceViewer.getVisibleRegion().getOffset();
return offset + styledText.getCaretOffset();
}
}
/**
* Basic source code viewer...
* @param content
*/
private void createSourceContent(Composite content) {
JavaLineStyler lineStyler = new JavaLineStyler();
StyledText text = new StyledText(content, SWT.BORDER | SWT.MULTI | SWT.V_SCROLL | SWT.H_SCROLL);
GridData spec = new GridData();
spec.horizontalAlignment = GridData.FILL;
spec.grabExcessHorizontalSpace = true;
spec.verticalAlignment = GridData.FILL;
spec.grabExcessVerticalSpace = true;
text.setLayoutData(spec);
text.addLineStyleListener(lineStyler);
// Use a monospaced font, which is not as easy as it might be.
// http://stackoverflow.com/questions/221568/swt-os-agnostic-way-to-get-monospaced-font
text.setFont(JFaceResources.getTextFont());
text.setEditable(false);
// Providing that they run this from a debug session:
try {
File dir = BundleUtils.getBundleLocation("org.eclipse.dawnsci.plotting.examples");
String loc = "/src/"+getClass().getName().replace('.', '/')+".java";
File src = new File(dir, loc);
text.setText(readFile(src).toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* Returns the number of lines in the view port.
*
* @param textWidget the styled text widget
* @return the number of lines visible in the view port <code>-1</code> if there's no client
* area
* @deprecated this method should not be used - it relies on the widget using a uniform line
* height
*/
static int getVisibleLinesInViewport(StyledText textWidget) {
if (textWidget != null) {
Rectangle clArea= textWidget.getClientArea();
if (!clArea.isEmpty()) {
int firstPixel= 0;
int lastPixel= clArea.height - 1; // XXX: what about margins? don't take trims as they include scrollbars
int first= JFaceTextUtil.getLineIndex(textWidget, firstPixel);
int last= JFaceTextUtil.getLineIndex(textWidget, lastPixel);
return last - first;
}
}
return -1;
}
@Override
public Point draw(GC gc, StyledText textWidget, Color color, int x, int y) {
// increment x with 3 spaces width
x += 3 * (int) gc.getFontMetrics().getAverageCharacterWidth();
Point p = super.draw(gc, textWidget, color, x, y);
if (fRgb != null) {
int width = drawSquare(fRgb, gc, textWidget, x + p.x, y);
p.x += width;
}
return p;
}
/**
* Get the selection point from the text widget
*
* @param editor
*
* @return the selection point iff it is a (Styled)Text widget
* x is the offset of the first selected character,
* y is the offset after the last selected character.
*/
public static Point getWidgetSelection(ITextEditor editor) {
Point result = null;
Control text = (Control) editor.getAdapter(Control.class);
if (text instanceof StyledText) {
result = ((StyledText) text).getSelection();
} else if (text instanceof Text) {
result = ((Text) text).getSelection();
}
return result;
}
/**
* @see org.eclipse.nebula.widgets.opal.preferencewindow.widgets.PWWidget#build(org.eclipse.swt.widgets.Composite)
*/
@Override
public Control build(final Composite parent) {
if (getLabel() == null) {
throw new UnsupportedOperationException("You need to set a description for a PWLabel object");
}
labelWidget = new StyledText(parent, SWT.WRAP | SWT.READ_ONLY);
labelWidget.setEnabled(false);
labelWidget.setBackground(parent.getBackground());
labelWidget.setText(getLabel());
SWTGraphicUtil.applyHTMLFormating(labelWidget);
return labelWidget;
}