Java Code Examples for org.eclipse.swt.custom.StyledText#setStyleRanges()

The following examples show how to use org.eclipse.swt.custom.StyledText#setStyleRanges() . 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
Source File: HsMultiCellEditor.java    From translationstudio8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 刷新拼写检查中错误单词的样式
 * @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 File: HsMultiCellEditor.java    From tmxeditor8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 刷新拼写检查中错误单词的样式
 * @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 3
Source File: HoverInfoWithText.java    From xds-ide with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void deferredCreateContent(Composite parent,
        HoverInformationControl miControl) {
    this.fParent = parent;
    this.fMIControl = miControl;

    fText = new StyledText(parent, SWT.MULTI | SWT.READ_ONLY
            | fMIControl.getAdditionalTextStyles());
    fText.setForeground(parent.getForeground());
    fText.setBackground(parent.getBackground());
    fText.setFont(JFaceResources.getDialogFont());
    fText.addPaintObjectListener(new PaintObjectListener() {
        public void paintObject(PaintObjectEvent event) {
            StyleRange style = event.style;
            Image image = (Image) style.data;
            if (image != null && !image.isDisposed()) {
                int x = event.x + 2;
                int y = event.y + event.ascent / 2 - style.metrics.ascent
                        / 2 + 2;
                event.gc.drawImage(image, x, y);
            }
        }
    });
    FillLayout layout = new FillLayout();
    layout.marginHeight = 2;
    layout.marginWidth = 2;
    parent.setLayout(layout);

    if (monospace) {
        fText.setFont(JFaceResources.getTextFont());
    } else {
        fText.setFont(JFaceResources.getDialogFont());
    }

    fText.setText(xsString.getText());
    fText.setStyleRanges(xsString.getStyleRanges().toArray(new StyleRange[0]));

    parent.layout(true);
}
 
Example 4
Source File: DiffAttributeEditor.java    From git-appraise-eclipse with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void createControl(final Composite parent, FormToolkit toolkit) {
  Composite composite = new Composite(parent, SWT.NONE);
  GridLayout layout = new GridLayout(1, false);
  composite.setLayout(layout);

  final String filePath =
      getTaskAttribute().getAttribute(AppraiseReviewTaskSchema.DIFF_NEWPATH).getValue();

  Link fileLink = new Link(composite, SWT.BORDER);
  fileLink.setText("<a>View in Workspace</a>");
  fileLink.addListener(SWT.Selection, new Listener() {
    @Override
    public void handleEvent(Event event) {
      AppraiseUiPlugin.openFileInEditor(filePath, getModel().getTaskRepository());
    }
  });

  final String diffText =
      getTaskAttribute().getAttribute(AppraiseReviewTaskSchema.DIFF_TEXT).getValue();

  final StyledText text = new StyledText(composite, SWT.MULTI | SWT.LEFT | SWT.BORDER | SWT.READ_ONLY);
  text.setText(diffText);
  text.setStyleRanges(getStyleRangesForDiffText(diffText));

  GridData diffTextGridData = new GridData();
  diffTextGridData.grabExcessHorizontalSpace = true;
  diffTextGridData.horizontalAlignment = SWT.FILL;
  text.setLayoutData(diffTextGridData);

  composite.pack();
  setControl(composite);
}
 
Example 5
Source File: SpringConfigurationStyledText.java    From tesb-studio-se with Apache License 2.0 5 votes vote down vote up
private void updateStyledRanges(ExtendedModifyEvent event) {
	StyledText st = (StyledText) event.widget;
	int start = event.start;
	int length = event.length;
	String replacedText = event.replacedText;
	String textRange = st.getTextRange(start, length);
	/*
	 * if no real change
	 * then return
	 */
	if ("".equals(textRange.trim()) && "".equals(replacedText.trim())) {
		return;
	}

	List<StyleRange> styles = new ArrayList<StyleRange>();
	scanner.setRange(st.getText());
	int token = scanner.nextToken();
	while (token != EOF) {
		int startOffset = scanner.getStartOffset();
		int tokenLength = scanner.getLength();
		String tokenText = st.getTextRange(startOffset, tokenLength).trim();
		for (String s : fgKeywords) {
			if (s.equals(tokenText)) {
				token = KEY;
				break;
			}
		}

		Color color = getColor(token);
		StyleRange style = new StyleRange(startOffset, tokenLength, color,
				null);
		if (token == KEY) {
			style.fontStyle = SWT.BOLD;
		}
		styles.add(style);
		token = scanner.nextToken();
	}
	st.setStyleRanges(styles.toArray(new StyleRange[0]));
}
 
Example 6
Source File: TextDiffDialog.java    From olca-app with Mozilla Public License 2.0 5 votes vote down vote up
private void createText(Composite parent, String value, String otherValue, Site site) {
	StyledString styled = new StyledString(value);
	new DiffStyle().applyTo(styled, otherValue, site, action);
	StyledText text = new StyledText(parent, SWT.BORDER | SWT.MULTI | SWT.V_SCROLL | SWT.WRAP);
	text.setText(styled.toString());
	text.setStyleRanges(styled.getStyleRanges());
	text.setEditable(false);
	text.setBackground(Colors.white());
	UI.gridData(text, true, true);
}
 
Example 7
Source File: StyledTextDescriptor.java    From n4js with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Creates and returns with a new {@link StyledText styled text} instance hooked up to the given parent composite.
 *
 * @param parent
 *            the parent of the styled text control.
 * @param style
 *            style bits for the new text control.
 * @return a new styled text control initialized from the descriptor.
 */
default StyledText toStyledText(final Composite parent, final int style) {

	final StyledText text = new StyledText(parent, READ_ONLY | style);
	text.setText(getText());
	text.setStyleRanges(getRanges());
	text.setFont(getFont());
	text.setEditable(false);
	text.setEnabled(false);

	final AtomicReference<Color> colorRef = new AtomicReference<>();
	final IPreferenceStore prefStore = EditorsUI.getPreferenceStore();
	if (null == prefStore
			|| prefStore.getBoolean(PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT)) {

		colorRef.set(getDefault().getSystemColor(COLOR_LIST_BACKGROUND));

	} else {

		RGB rgb = null;
		if (prefStore.contains(PREFERENCE_COLOR_BACKGROUND)) {
			if (prefStore.isDefault(PREFERENCE_COLOR_BACKGROUND)) {
				rgb = getDefaultColor(prefStore, PREFERENCE_COLOR_BACKGROUND);
			} else {
				rgb = getColor(prefStore, PREFERENCE_COLOR_BACKGROUND);
			}
			if (rgb != null) {
				colorRef.set(new Color(text.getDisplay(), rgb));
			}
		}

	}

	if (null != colorRef.get()) {
		text.setBackground(colorRef.get());
		text.addDisposeListener(e -> {
			if (!colorRef.get().isDisposed()) {
				colorRef.get().dispose();
			}
		});
	}

	text.pack();
	return text;
}
 
Example 8
Source File: IllegalBinaryStateDialog.java    From n4js with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Creates a control with some message and with link to the Binaries preference page.
 *
 * @param parent
 *            the parent composite.
 * @param dialog
 *            the container dialog that has to be closed.
 * @param binary
 *            the binary with the illegal state.
 *
 * @return a control with error message and link that can be reused in dialogs.
 */
public static Control createCustomAreaWithLink(final Composite parent, final Dialog dialog, final Binary binary) {
	final String binaryLabel = binary.getLabel();
	final String prefix = "The requested operation cannot be performed due to invalid '" + binaryLabel
			+ "' settings. Check your '" + binaryLabel
			+ "' configuration and preferences under the corresponding ";
	final String link = "preference page";
	final String suffix = ".";
	final String text = prefix + link + suffix;

	final Composite control = new Composite(parent, NONE);
	control.setLayout(GridLayoutFactory.fillDefaults().create());
	final GridData gridData = GridDataFactory.fillDefaults().align(LEFT, TOP).grab(true, true).create();
	control.setLayoutData(gridData);

	final StyleRange style = new StyleRange();
	style.underline = true;
	style.underlineStyle = UNDERLINE_LINK;

	final StyledText styledText = new StyledText(control, MULTI | READ_ONLY | WRAP);
	styledText.setWordWrap(true);
	styledText.setJustify(true);
	styledText.setText(text);
	final GridData textGridData = GridDataFactory.fillDefaults().align(FILL, FILL).grab(true, true).create();
	textGridData.widthHint = TEXT_WIDTH_HINT;
	textGridData.heightHint = TEXT_HEIGHT_HINT;
	styledText.setLayoutData(textGridData);

	styledText.setEditable(false);
	styledText.setBackground(UIUtils.getSystemColor(COLOR_WIDGET_BACKGROUND));
	final int[] ranges = { text.indexOf(link), link.length() };
	final StyleRange[] styles = { style };
	styledText.setStyleRanges(ranges, styles);

	styledText.addMouseListener(new MouseAdapter() {

		@Override
		public void mouseDown(final MouseEvent event) {
			try {
				final int offset = styledText.getOffsetAtPoint(new Point(event.x, event.y));
				final StyleRange actualStyle = offset >= 0 ? styledText.getStyleRangeAtOffset(offset) : null;
				if (null != actualStyle && actualStyle.underline
						&& UNDERLINE_LINK == actualStyle.underlineStyle) {

					dialog.close();
					final PreferenceDialog preferenceDialog = createPreferenceDialogOn(
							UIUtils.getShell(),
							BinariesPreferencePage.ID,
							FILTER_IDS,
							null);

					if (null != preferenceDialog) {
						preferenceDialog.open();
					}

				}
			} catch (final IllegalArgumentException e) {
				// We are not over the actual text.
			}
		}

	});

	return control;
}
 
Example 9
Source File: Snippet163old.java    From http4e with Apache License 2.0 4 votes vote down vote up
public static void main(String [] args) {
   Display display = new Display();
   Shell shell = new Shell(display);
   shell.setLayout(new FillLayout());
   StyledText styledText = new StyledText(shell, SWT.WRAP | SWT.BORDER);
   styledText.setText(text);
   FontData data = styledText.getFont().getFontData()[0];
   Font font1 = new Font(display, data.getName(), data.getHeight() * 2, data.getStyle());
   Font font2 = new Font(display, data.getName(), data.getHeight() * 4 / 5, data.getStyle());
   StyleRange[] styles = new StyleRange[8];
   styles[0] = new StyleRange();
   styles[0].font = font1; 
   styles[1] = new StyleRange();
   styles[1].rise = data.getHeight() / 3; 
   styles[2] = new StyleRange();
   styles[2].background = display.getSystemColor(SWT.COLOR_GREEN); 
   styles[3] = new StyleRange();
   styles[3].foreground = display.getSystemColor(SWT.COLOR_MAGENTA); 
   styles[4] = new StyleRange();
   styles[4].font = font2; 
   styles[4].foreground = display.getSystemColor(SWT.COLOR_BLUE);;
   styles[4].underline = true;
   styles[5] = new StyleRange();
   styles[5].rise = -data.getHeight() / 3; 
   styles[5].strikeout = true;
   styles[5].underline = true;
   styles[6] = new StyleRange();
   styles[6].font = font1; 
   styles[6].foreground = display.getSystemColor(SWT.COLOR_YELLOW);
   styles[6].background = display.getSystemColor(SWT.COLOR_BLUE);
   styles[7] = new StyleRange();
   styles[7].rise =  data.getHeight() / 3;
   styles[7].underline = true;
   styles[7].fontStyle = SWT.BOLD;
   styles[7].foreground = display.getSystemColor(SWT.COLOR_RED);
   styles[7].background = display.getSystemColor(SWT.COLOR_BLACK);
   
   int[] ranges = new int[] {16, 4, 61, 13, 107, 10, 122, 10, 134, 3, 143, 6, 160, 7, 168, 7};
   styledText.setStyleRanges(ranges, styles);
   
   shell.setSize(300, 300);
   shell.open();
   while (!shell.isDisposed()) {
      if (!display.readAndDispatch())
         display.sleep();
   }
   font1.dispose();
   font2.dispose();     
   display.dispose();
}
 
Example 10
Source File: ExecutionStatisticsDialog.java    From tlaplus with MIT License 4 votes vote down vote up
@Override
  protected Control createCustomArea(Composite parent) {
final Composite c = new Composite(parent, SWT.BORDER);
c.setLayout(new GridLayout());
c.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));

//NOTE: Take care of ExecutionStatisticsCollector.md when updating!!!
final String txt = String.format("%s"
		+ "* Total number of cores and cores assigned to TLC\n"
		+ "* Heap and off-heap memory allocated to TLC\n"
		+ "* TLC's version (git commit SHA)\n"
		+ "* If breadth-first search, depth-first search or simulation mode is active\n"
		+ "* TLC's implementation for the sets of seen and unseen states\n"
		+ "* If TLC has been launched from the TLA Toolbox\n"
		+ "* Name, version, and architecture of your operating system\n"
		+ "* Vendor, version, and architecture of your Java virtual machine\n"
		+ "* The current date and time\n"
		+ "* An installation identifier which allows us to group execution statistics\n\n"
		+ "The execution statistics do not contain personal information. If you wish to revoke\n"
		+ "your consent to share execution statistics at a later point, please chose \n"
		+ "\"Never Share Execution Statistics\" below by re-opening this dialog via\n"
		+ "Help > Opt In/Out Execution Statistics accessible from the Toolbox's main menu.", prettyPrintSelection2(esc));

final StyledText st = new StyledText(c, SWT.SHADOW_NONE | SWT.WRAP);
st.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));

st.setEnabled(true);
st.setEditable(false);
st.setText(txt);

final StyleRange[] ranges = new StyleRange[3];
ranges[0] = new StyleRange(txt.indexOf("(TLC) execution statistics"), "(TLC) execution statistics".length(), null, null);
ranges[0].underline = true;
ranges[0].underlineStyle = SWT.UNDERLINE_LINK;
ranges[0].data = "https://exec-stats.tlapl.us";

ranges[1] = new StyleRange(txt.indexOf("publicly available"), "publicly available".length(), null, null);
ranges[1].underline = true;
ranges[1].underlineStyle = SWT.UNDERLINE_LINK;
ranges[1].data = "https://exec-stats.tlapl.us/tlaplus.csv";
		
ranges[2] = new StyleRange(txt.indexOf("git commit SHA"), "git commit SHA".length(), null, null);
ranges[2].underline = true;
ranges[2].underlineStyle = SWT.UNDERLINE_LINK;
ranges[2].data = "https://git-scm.com/book/en/v2/Git-Internals-Git-Objects";

st.setStyleRanges(ranges);
st.addMouseListener(new MouseAdapter() {
	@Override
	public void mouseUp(final MouseEvent event) {
              final int offset = st.getOffsetAtPoint(new Point(event.x, event.y));
              if (offset < 0 || offset >= st.getCharCount()) {
              	return;
              }
		final StyleRange style = st.getStyleRangeAtOffset(offset);
              if (style != null && style.underline && style.underlineStyle == SWT.UNDERLINE_LINK && style.data instanceof String) {
                  try {
				PlatformUI.getWorkbench().getBrowserSupport().getExternalBrowser().openURL(new URL((String) style.data));
			} catch (PartInitException | MalformedURLException notExpectedToHappen) {
				notExpectedToHappen.printStackTrace();
			}
              }
	}
});
	
      return c;
  }
 
Example 11
Source File: LineBackgroundPainter.java    From APICloud-Studio with GNU General Public License v3.0 4 votes vote down vote up
private void drawCurrentLine(LineBackgroundEvent event, final IRegion lineRegion)
{
	final StyledText textWidget = fViewer.getTextWidget();
	final int offset = event.lineOffset;
	final RGBa lineHighlight = getCurrentTheme().getLineHighlight();
	event.lineBackground = getColorManager().getColor(lineHighlight.toRGB());

	// In this case, we should be overriding the bg of the style ranges for the line too!
	if (textWidget.isDisposed())
	{
		return;
	}
	// FIXME Only change bg colors of visible ranges!
	int replaceLength = 160;
	if (lineRegion != null)
	{
		replaceLength = Math.min(replaceLength, lineRegion.getLength());
	}

	// be safe about offsets
	int charCount = textWidget.getCharCount();
	if (offset + replaceLength > charCount)
	{
		replaceLength = charCount - offset;
		if (replaceLength < 0)
		{
			// Just playing safe here
			replaceLength = 0;
		}
	}
	final StyleRange[] ranges = textWidget.getStyleRanges(offset, replaceLength, true);
	if (ranges == null || ranges.length == 0)
	{
		return;
	}
	Color background = textWidget.getBackground();
	final int[] positions = new int[ranges.length << 1];
	int x = 0;
	boolean apply = false;
	for (StyleRange range : ranges)
	{
		if (range.background != null)
		{
			if (!range.background.equals(background))
			{
				positions[x] = range.start;
				positions[x + 1] = range.length;
				x += 2;
				continue;
			}
			apply = true;
		}
		range.background = null;
		positions[x] = range.start;
		positions[x + 1] = range.length;
		x += 2;
	}

	if (apply)
	{
		textWidget.setStyleRanges(offset, replaceLength, positions, ranges);
	}
}