Ejemplo n.º 1
1
 /**
  * Event.detail line start offset (input) Event.text line text (input) LineStyleEvent.styles
  * Enumeration of StyleRanges, need to be in order. (output) LineStyleEvent.background line
  * background color (output)
  */
 public void lineGetStyle(LineStyleEvent event) {
   Vector styles = new Vector();
   int token;
   StyleRange lastStyle;
   // If the line is part of a block comment, create one style for the entire line.
   if (inBlockComment(event.lineOffset, event.lineOffset + event.lineText.length())) {
     styles.addElement(
         new StyleRange(event.lineOffset, event.lineText.length(), getColor(COMMENT), null));
     event.styles = new StyleRange[styles.size()];
     styles.copyInto(event.styles);
     return;
   }
   Color defaultFgColor = ((Control) event.widget).getForeground();
   scanner.setRange(event.lineText);
   token = scanner.nextToken();
   while (token != EOF) {
     if (token == OTHER) {
       // do nothing for non-colored tokens
     } else if (token != WHITE) {
       Color color = getColor(token);
       // Only create a style if the token color is different than the
       // widget's default foreground color and the token's style is not
       // bold.  Keywords are bolded.
       if ((!color.equals(defaultFgColor)) || (token == KEY)) {
         StyleRange style =
             new StyleRange(
                 scanner.getStartOffset() + event.lineOffset, scanner.getLength(), color, null);
         if (token == KEY) {
           style.fontStyle = SWT.BOLD;
         }
         if (styles.isEmpty()) {
           styles.addElement(style);
         } else {
           // Merge similar styles.  Doing so will improve performance.
           lastStyle = (StyleRange) styles.lastElement();
           if (lastStyle.similarTo(style) && (lastStyle.start + lastStyle.length == style.start)) {
             lastStyle.length += style.length;
           } else {
             styles.addElement(style);
           }
         }
       }
     } else if ((!styles.isEmpty())
         && ((lastStyle = (StyleRange) styles.lastElement()).fontStyle == SWT.BOLD)) {
       int start = scanner.getStartOffset() + event.lineOffset;
       lastStyle = (StyleRange) styles.lastElement();
       // A font style of SWT.BOLD implies that the last style
       // represents a java keyword.
       if (lastStyle.start + lastStyle.length == start) {
         // Have the white space take on the style before it to
         // minimize the number of style ranges created and the
         // number of font style changes during rendering.
         lastStyle.length += scanner.getLength();
       }
     }
     token = scanner.nextToken();
   }
   event.styles = new StyleRange[styles.size()];
   styles.copyInto(event.styles);
 }
Ejemplo n.º 2
1
  /**
   * Event.detail line start offset (input) Event.text line text (input) LineStyleEvent.styles
   * Enumeration of StyleRanges, need to be in order. (output) LineStyleEvent.background line
   * background color (output)
   */
  public void lineGetStyle(LineStyleEvent event) {
    Vector<StyleRange> styles = new Vector<StyleRange>();
    int token;
    StyleRange lastStyle;

    if (inBlockComment(event.lineOffset, event.lineOffset + event.lineText.length())) {
      styles.addElement(
          new StyleRange(event.lineOffset, event.lineText.length() + 4, colors[2], null));
      event.styles = new StyleRange[styles.size()];
      styles.copyInto(event.styles);
      return;
    }
    scanner.setRange(event.lineText);
    String xs = ((StyledText) event.widget).getText();
    if (xs != null) parseBlockComments(xs);
    token = scanner.nextToken();
    while (token != EOF) {
      if (token == OTHER) {
        // do nothing
      } else if ((token == WHITE) && (!styles.isEmpty())) {
        int start = scanner.getStartOffset() + event.lineOffset;
        lastStyle = (StyleRange) styles.lastElement();
        if (lastStyle.fontStyle != SWT.NORMAL) {
          if (lastStyle.start + lastStyle.length == start) {
            // have the white space take on the style before it to minimize font style
            // changes
            lastStyle.length += scanner.getLength();
          }
        }
      } else {
        Color color = getColor(token);
        if (color != colors[0]) { // hardcoded default foreground color, black
          StyleRange style =
              new StyleRange(
                  scanner.getStartOffset() + event.lineOffset, scanner.getLength(), color, null);
          if (token == KEY) {
            style.fontStyle = SWT.BOLD;
          }
          if (styles.isEmpty()) {
            styles.addElement(style);
          } else {
            lastStyle = (StyleRange) styles.lastElement();
            if (lastStyle.similarTo(style) && (lastStyle.start + lastStyle.length == style.start)) {
              lastStyle.length += style.length;
            } else {
              styles.addElement(style);
            }
          }
        }
      }
      token = scanner.nextToken();
    }
    event.styles = new StyleRange[styles.size()];
    styles.copyInto(event.styles);
  }
Ejemplo n.º 3
0
 public static void main(String[] args) {
   Display display = new Display();
   Shell shell = new Shell(display);
   shell.setText("StyledText with underline and strike through");
   shell.setLayout(new FillLayout());
   StyledText text = new StyledText(shell, SWT.BORDER);
   text.setText("0123456789 ABCDEFGHIJKLM NOPQRSTUVWXYZ");
   // make 0123456789 appear underlined
   StyleRange style1 = new StyleRange();
   style1.start = 0;
   style1.length = 10;
   style1.underline = true;
   text.setStyleRange(style1);
   // make ABCDEFGHIJKLM have a strike through
   StyleRange style2 = new StyleRange();
   style2.start = 11;
   style2.length = 13;
   style2.strikeout = true;
   text.setStyleRange(style2);
   // make NOPQRSTUVWXYZ appear underlined and have a strike through
   StyleRange style3 = new StyleRange();
   style3.start = 25;
   style3.length = 13;
   style3.underline = true;
   style3.strikeout = true;
   text.setStyleRange(style3);
   shell.pack();
   shell.open();
   while (!shell.isDisposed()) {
     if (!display.readAndDispatch()) display.sleep();
   }
   display.dispose();
 }
Ejemplo n.º 4
0
  /**
   * creates the style range of the StyledText for the range of the contained editor
   *
   * <p>XXX problem will occur if there is a newline in the position. Working on this! code folding.
   */
  private StyleRange[] createStyleRange(ContainedEditorManager c, Position p) {
    int offset = p.offset;
    int length = p.length;

    Rectangle rect = c.getControl().getBounds();
    int ascent = rect.height - 4;
    int descent = 4;

    // use two style ranges

    // first style range covers the entire size of the contained editor
    StyleRange first = new StyleRange();
    first.start = offset;
    first.length = Math.min(1, length);
    first.background = this.containingEditor.colorManager.getColor(new RGB(255, 255, 255));
    first.metrics =
        new GlyphMetrics(
            ascent + ContainingEditor.MARGIN,
            descent + ContainingEditor.MARGIN,
            rect.width + 2 * ContainingEditor.MARGIN);

    // this style range is hidden.  the height and width are 0
    StyleRange second = new StyleRange();
    second.start = offset + 1;
    second.length = length - 1;
    second.background = this.containingEditor.colorManager.getColor(new RGB(255, 255, 255));
    second.metrics = new GlyphMetrics(0, 0, 0);
    second.font = TINY_FONT;

    return new StyleRange[] {first, second};
  }
Ejemplo n.º 5
0
  /**
   * Inputs in the view the selected PO whose pretty code is recorded in the Goal class
   *
   * @throws IOException
   */
  public void inputPO() throws IOException {

    // we want to see a context, not the goal
    if (!POMode) {
      return;
    }

    if (ttext > 0) // if we've a title text
    setPartName(IConstants.PO_VIEW_TITLE + " : po " + ttext); // put it in the view
    else setPartName(IConstants.PO_VIEW_TITLE); // else, put the view title only

    // gets the PO pretty text
    String container = "";
    container = Goal.getGoal();

    // if the Goal is empty, we can return
    if (container.equals("")) {
      text.setText(container);
      return;
    }

    // get the style ranges
    Vector<StyleRange> range = Goal.getStyleRanges();
    int w = range.size() - 1;
    // keep the ranges which can be applied in the text area
    while (((StyleRange) range.get(w)).start >= container.length()) {
      w--;
    }

    // put the bar between the goal and the arrow result excerpted from this same goal
    container += "\n_______________________________________________\n\n";
    container += Goal.getResult();
    text.setText(container);

    // apply style ranges to the first part of the goal (before the bar)
    for (int e = 0; e <= w; e++) {
      text.setStyleRange((StyleRange) range.get(e));
    }

    // puts a style range to color the bar in black
    StyleRange srg = new StyleRange();
    srg.start += Goal.getGoal().length();
    srg.length = 50;
    srg.foreground = new Color(null, 0, 0, 0);
    text.setStyleRange(srg);

    // puts a style range to color the end of the goal in blue
    srg = new StyleRange();
    srg.start += Goal.getGoal().length() + 50;
    srg.length = Goal.getResult().length();
    srg.foreground = new Color(null, 0, 0, 255);
    text.setStyleRange(srg);

    // sets the cursor at the end of the code
    text.setSelection(text.getText().length(), text.getText().length());
  }
Ejemplo n.º 6
0
    @Override
    public void run() {
      try {
        String query = queryString.getSelectionText();
        Point queryRange = queryString.getSelectionRange();

        if ("".equals(query)) // $NON-NLS-1$
        {
          query = queryString.getText();
          queryRange = new Point(0, queryString.getCharCount());
        }

        try {
          // force parsing of OQL query
          SnapshotFactory.createQuery(query);
          new OQLJob(OQLPane.this, query, state).schedule();
        } catch (final OQLParseException e) {
          int start = findInText(query, e.getLine(), e.getColumn());

          StyleRange style2 = new StyleRange();
          style2.start = start + queryRange.x;
          style2.length = queryRange.y - start;
          style2.foreground = JFaceResources.getColorRegistry().get(JFacePreferences.ERROR_COLOR);
          style2.underline = true;
          style2.underlineStyle = SWT.UNDERLINE_SQUIGGLE;
          queryString.replaceStyleRanges(0, queryString.getCharCount(), new StyleRange[] {style2});

          createExceptionPane(e, query);
        } catch (Exception e) {
          createExceptionPane(e, query);
        }
      } catch (PartInitException e1) {
        ErrorHelper.logThrowableAndShowMessage(e1, Messages.OQLPane_ErrorExecutingQuery);
      }
    }
Ejemplo n.º 7
0
  protected void adaptTextPresentation(
      final TextPresentation presentation, final int offset, final int insertLength) {

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

    @SuppressWarnings("rawtypes")
    Iterator e = presentation.getAllStyleRangeIterator();
    while (e.hasNext()) {

      StyleRange range = (StyleRange) 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;
      }
    }
  }
Ejemplo n.º 8
0
 public static StyleRange copy(final StyleRange range) {
   final StyleRange result = new StyleRange(range);
   result.start = range.start;
   result.length = range.length;
   result.fontStyle = range.fontStyle;
   return result;
 }
 private StyleRange createStyleRange(int start, int end, Styler style) {
   StyleRange styleRange = new StyleRange();
   styleRange.start = start;
   styleRange.length = end - start;
   style.applyStyles(styleRange);
   return styleRange;
 }
  private void formatIpAddress(int start, int end) {
    StyleRange style = new StyleRange();
    style.start = start;
    style.length = end - start;
    style.font = new Font(sShell.getDisplay(), "Courier New", 9, SWT.BOLD);
    style.foreground = new Color(sShell.getDisplay(), 255, 127, 0); // Orange	

    activeHostsFileStyledText.setStyleRange(style);
  }
  private void formatRemark(int start, int end) {
    StyleRange style = new StyleRange();
    style.start = start;
    style.length = end - start;
    style.font = new Font(sShell.getDisplay(), "Courier New", 9, SWT.NORMAL);
    style.foreground = new Color(sShell.getDisplay(), 0, 128, 0); // Green	

    activeHostsFileStyledText.setStyleRange(style);
  }
  private void formatHostName(int start, int end) {
    StyleRange style = new StyleRange();
    style.start = start;
    style.length = end - start;
    style.font = new Font(sShell.getDisplay(), "Courier New", 9, SWT.BOLD);
    style.foreground = sShell.getDisplay().getSystemColor(SWT.COLOR_BLUE);

    activeHostsFileStyledText.setStyleRange(style);
  }
Ejemplo n.º 13
0
 /**
  * {@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.
  */
 @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;
 }
Ejemplo n.º 14
0
 private org.eclipse.swt.custom.StyleRange getStyleRangeAtPosition(
     org.eclipse.jface.text.Position position) {
   org.eclipse.swt.custom.StyleRange styleRange = null;
   try {
     styleRange = textWidget.getStyleRangeAtOffset(position.offset);
   } catch (IllegalArgumentException iae) {
   }
   if (styleRange == null) {
     styleRange =
         new org.eclipse.swt.custom.StyleRange(position.offset, position.length, black, null);
   } else {
     styleRange.length = position.length;
   }
   return styleRange;
 }
  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;
    }
  }
Ejemplo n.º 16
0
 private void highlight(int start, String search) {
   stylerange.start = start;
   stylerange.length = search.length();
   text.setStyleRange(stylerange);
 }
Ejemplo n.º 17
0
 public static StyleRange newStyleRange(StyleRange from) {
   StyleRange r = new StyleRange(from);
   r.start = from.start;
   r.length = from.length;
   return r;
 }
Ejemplo n.º 18
0
  @SuppressWarnings("unchecked")
  private void updateImage(String imgSrc, ImageData imageData) {
    if (display.isDisposed() || viewer.getTextWidget().isDisposed()) {
      return;
    }
    Image image =
        imageData == null
            ? imageCache.getMissingImage()
            : ImageDescriptor.createFromImageData(imageData).createImage();
    imageCache.putImage(imgSrc, image);

    Set<ImageAnnotation> modifiedAnnotations = new HashSet<>();

    AnnotationModel annotationModel = (AnnotationModel) viewer.getAnnotationModel();
    Object annotationLockObject = annotationModel.getLockObject();
    if (annotationLockObject == null) {
      annotationLockObject = annotationModel;
    }
    synchronized (annotationLockObject) {
      Iterator<Annotation> iterator = annotationModel.getAnnotationIterator();
      while (iterator.hasNext()) {
        Annotation annotation = iterator.next();
        if (annotation instanceof ImageAnnotation) {
          ImageAnnotation imageAnnotation = (ImageAnnotation) annotation;
          if (imgSrc.equals(imageAnnotation.getUrl())) {
            imageAnnotation.setImage(image);
            modifiedAnnotations.add(imageAnnotation);
          }
        }
      }
    }

    if (!modifiedAnnotations.isEmpty()) {
      computingChanges = true;
      try {
        boolean rangesAdjusted = false;
        List<StyleRange> ranges = new ArrayList<>();

        Iterator<?> allStyleRangeIterator = viewer.getTextPresentation().getAllStyleRangeIterator();
        while (allStyleRangeIterator.hasNext()) {
          StyleRange range = (StyleRange) allStyleRangeIterator.next();
          ranges.add((StyleRange) range.clone());
        }

        GC gc = new GC(viewer.getTextWidget());
        try {
          viewer.getTextWidget().setRedraw(false);
          TextPresentation textPresentation = viewer.getTextPresentation();
          //			textPresentation.
          for (ImageAnnotation annotation : modifiedAnnotations) {
            int height = annotation.getImage().getBounds().height;
            Position position = annotationModel.getPosition(annotation);
            String widgetText = viewer.getTextWidget().getText();
            Font font = null;
            if (widgetText.length() > 0 && widgetText.length() > position.offset) {
              StyleRange styleRange = viewer.getTextWidget().getStyleRangeAtOffset(position.offset);
              if (styleRange != null) {
                font = styleRange.font;
              }
            }
            if (font == null) {
              font = viewer.getTextWidget().getFont();
            }
            gc.setFont(font);
            Point extent = gc.textExtent("\n"); // $NON-NLS-1$
            if (extent.y > 0) {
              int numNewlines = (int) Math.ceil(((double) height) / ((double) extent.y));
              final int originalNewlines = numNewlines;
              IDocument document = viewer.getDocument();
              try {
                for (int x = position.offset; x < document.getLength(); ++x) {
                  if (document.getChar(x) == '\n') {
                    if (x != position.offset
                        && Util.annotationsIncludeOffset(viewer.getAnnotationModel(), x)) {
                      break;
                    }
                    --numNewlines;
                  } else {
                    break;
                  }
                }
                if (numNewlines > 0) {
                  String newlines = ""; // $NON-NLS-1$
                  for (int x = 0; x < numNewlines; ++x) {
                    newlines += "\n"; // $NON-NLS-1$
                  }
                  document.replace(position.offset + 1, 0, newlines);
                } else if (numNewlines < 0) {
                  document.replace(position.offset, -numNewlines, ""); // $NON-NLS-1$
                }
                if (numNewlines != 0) {
                  // no need to fixup other annotation positions, since the annotation model is
                  // hooked into the document.

                  // fix up styles
                  for (StyleRange range : ranges) {
                    if (range.start > position.offset) {
                      range.start += numNewlines;
                      rangesAdjusted = true;
                    } else if (range.start + range.length > position.offset) {
                      range.length += numNewlines;
                      rangesAdjusted = true;
                    }
                  }
                }

                // bug# 248643: update the annotation size to reflect the full size of the image
                //              so that it gets repainted when some portion of the image is exposed
                //              as a result of scrolling
                if (position.getLength() != originalNewlines) {
                  annotationModel.modifyAnnotationPosition(
                      annotation, new Position(position.offset, originalNewlines));
                }
              } catch (BadLocationException e) {
                // ignore
              }
            }
          }
          if (rangesAdjusted) {
            TextPresentation presentation = new TextPresentation();
            if (textPresentation.getDefaultStyleRange() != null) {
              StyleRange defaultStyleRange =
                  (StyleRange) textPresentation.getDefaultStyleRange().clone();
              if (viewer.getDocument() != null) {
                if (defaultStyleRange.length < viewer.getDocument().getLength()) {
                  defaultStyleRange.length = viewer.getDocument().getLength();
                }
              }
              presentation.setDefaultStyleRange(defaultStyleRange);
            }
            for (StyleRange range : ranges) {
              presentation.addStyleRange(range);
            }
            viewer.setTextPresentation(presentation);
            viewer.invalidateTextPresentation();
          }
        } finally {
          viewer.getTextWidget().setRedraw(true);
          gc.dispose();
        }
        viewer.getTextWidget().redraw();
      } finally {
        computingChanges = false;
      }
    }
  }
  private boolean prepareTwigRegions(
      Collection<StyleRange> holdResults,
      ITwigScriptRegion region,
      int regionStart,
      int partitionStartOffset,
      int partitionLength) {

    assert (region.getType() == TwigRegionContext.TWIG_CONTENT
        || region.getType() == TwigRegionContext.TWIG_COMMENT);

    StyleRange styleRange = null;
    TextAttribute attr;
    TextAttribute previousAttr = null;

    ITextRegion[] twigTokens = null;
    try {

      int from;
      int length;
      if (partitionStartOffset < regionStart) {
        from = 0;
        length = partitionLength - (regionStart - partitionStartOffset);
      } else {
        from = partitionStartOffset - regionStart;
        length = partitionLength;
      }
      twigTokens = region.getTwigTokens(from, Math.min(length, region.getLength()));
      ITextRegion prevElement = null;
      for (int i = 0; i < twigTokens.length; i++) {

        ITextRegion element = twigTokens[i];
        attr = getAttributeFor(element);
        // Check that the elements are different - otherwise the
        // coloring is not valid
        if (prevElement == element || attr == null) {
          continue;
        }
        if ((styleRange != null)
            && (previousAttr != null)
            && (previousAttr.equals(attr))
            && prevElement != null
            && prevElement.getLength() == prevElement.getLength()) {
          // extends the prev styleRange with the current element
          // length
          styleRange.length += element.getLength();
          if (styleRange.start + styleRange.length > partitionStartOffset + partitionLength) {
            styleRange.length -=
                (styleRange.start + styleRange.length) - (partitionStartOffset + partitionLength);
          }
        } else {
          // create new styleRange
          int styleStart = regionStart + element.getStart();
          int styleLength = element.getLength();
          if (styleStart + styleLength < partitionStartOffset) { // if
            // the
            // range
            // ends
            // before
            // the
            // requested
            // starting
            // position
            // -
            // ignoring
            // it
            continue;
          }
          if (styleStart < partitionStartOffset) { // if the region
            // starts before
            // the requested
            // starting
            // position -
            // adjusting the
            // style start
            // position
            styleLength -= (partitionStartOffset - styleStart);
            styleStart = partitionStartOffset;
          }
          if (styleStart > partitionStartOffset + partitionLength) {
            // if the region ends after the requested end position -
            // making it shorter
            styleLength -= styleStart - (partitionStartOffset + partitionLength);
          }
          if (attr.getBackground() != null && element.getTextEnd() != element.getEnd()) { // in
            // case
            // of
            // background
            // color
            // make
            // sure
            // the
            // highlighting
            // will
            // not
            // paint
            // the
            // whitespaces
            // applying style to the region w/o the whitespace
            styleRange =
                new StyleRange(
                    styleStart,
                    styleLength - (element.getEnd() - element.getTextEnd()),
                    attr.getForeground(),
                    attr.getBackground(),
                    attr.getStyle());
            if ((attr.getStyle() & TextAttribute.UNDERLINE) != 0) {
              styleRange.underline = true;
              styleRange.fontStyle &= ~TextAttribute.UNDERLINE;
            }
            if ((attr.getStyle() & TextAttribute.STRIKETHROUGH) != 0) {
              styleRange.strikeout = true;
              styleRange.fontStyle &= ~TextAttribute.STRIKETHROUGH;
            }
            holdResults.add(styleRange);
            // applying style to the whitespace (important for the
            // refresh of the specific range
            styleRange =
                new StyleRange(
                    regionStart + element.getTextEnd(),
                    element.getEnd() - element.getTextEnd(),
                    attr.getForeground(),
                    null,
                    attr.getStyle());
            holdResults.add(styleRange);
            previousAttr = null;
          } else {
            styleRange =
                new StyleRange(
                    styleStart,
                    styleLength,
                    attr.getForeground(),
                    attr.getBackground(),
                    attr.getStyle());
            if ((attr.getStyle() & TextAttribute.UNDERLINE) != 0) {
              styleRange.underline = true;
              styleRange.fontStyle &= ~TextAttribute.UNDERLINE;
            }
            if ((attr.getStyle() & TextAttribute.STRIKETHROUGH) != 0) {
              styleRange.strikeout = true;
              styleRange.fontStyle &= ~TextAttribute.STRIKETHROUGH;
            }
            holdResults.add(styleRange);
            // technically speaking, we don't need to update
            // previousAttr
            // in the other case, because the other case is when
            // it hasn't changed
            previousAttr = attr;
          }
        }
        prevElement = element;
      }
      return true;
    } catch (BadLocationException e) {
      Logger.logException(e);
      return false;
    }
  }