javax.swing.text.Segment Java Examples

The following examples show how to use javax.swing.text.Segment. 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: WrapEditorKit.java    From PacketProxy with Apache License 2.0 6 votes vote down vote up
@Override
public void write(Writer out, Document doc, int pos, int len) throws IOException, BadLocationException {
	if ((pos < 0) || ((pos + len) > doc.getLength())) {
		throw new BadLocationException("DefaultEditorKit.write", pos);
	}

	Segment data = new Segment();
	int nleft = len;
	int offs = pos;

	while (nleft > 0) {
		int n = Math.min(nleft, 4096);
		doc.getText(offs, n, data);
		out.write(data.array, data.offset, data.count);
		offs += n;
		nleft -= n;
	}
}
 
Example #2
Source File: SyntaxDocument.java    From jpexs-decompiler with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Parse the entire document and return list of tokens that do not already
 * exist in the tokens list. There may be overlaps, and replacements, which
 * we will cleanup later.
 *
 * @return list of tokens that do not exist in the tokens field
 */
private void parse() {
    // if we have no lexer, then we must have no tokens...
    if (lexer == null) {
        tokens = null;
        return;
    }
    int len = getLength();
    List<Token> toks = new ArrayList<Token>(len / 10);
    long ts = System.nanoTime();
    try {
        Segment seg = new Segment();
        getText(0, len, seg);
        lexer.parse(seg, 0, toks);
    } catch (BadLocationException ex) {
        log.log(Level.SEVERE, null, ex);
    } finally {
        if (log.isLoggable(Level.FINEST)) {
            log.finest(String.format("Parsed %d in %d ms, giving %d tokens\n",
                    len, (System.nanoTime() - ts) / 1000000, toks.size()));
        }
        tokens = toks;
    }
}
 
Example #3
Source File: ThreadDumpWindow.java    From visualvm with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void getText(int offset, int length, Segment txt) throws BadLocationException {
    if (lastOffset == offset && lastLength == length) {
        txt.array = segArray;
        txt.offset = segOffset;
        txt.count = segCount;
        txt.setPartialReturn(segPartialReturn);
        return;
    }
    super.getText(offset, length, txt);
    if (length > CACHE_BOUNDARY || lastLength <= CACHE_BOUNDARY) {
        segArray = txt.array;
        segOffset = txt.offset;
        segCount = txt.count;
        segPartialReturn = txt.isPartialReturn();
        lastOffset = offset;
        lastLength = length;
    }
}
 
Example #4
Source File: ThreadDumpView.java    From visualvm with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void getText(int offset, int length, Segment txt) throws BadLocationException {
    if (lastOffset == offset && lastLength == length) {
        txt.array = segArray;
        txt.offset = segOffset;
        txt.count = segCount;
        txt.setPartialReturn(segPartialReturn);
        return;
    }
    super.getText(offset, length, txt);
    if (length > CACHE_BOUNDARY || lastLength <= CACHE_BOUNDARY) {
        segArray = txt.array;
        segOffset = txt.offset;
        segCount = txt.count;
        segPartialReturn = txt.isPartialReturn();
        lastOffset = offset;
        lastLength = length;
    }
}
 
Example #5
Source File: SyntaxDocument.java    From visualvm with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Find the next position that matches <code>pattern</code> in the document.
 * returns -1 if the pattern is not found.
 * @param pattern the regex pattern to find
 * @param start The beginning index of search
 * @return
 * @deprecated use {@link getMatcher} instead
 */
@Deprecated
public int getIndexOf(Pattern pattern, int start) {
    int ndx = -1;
    if (pattern == null || getLength() == 0) {
        return -1;
    }
    try {
        Segment segment = new Segment();
        getText(start, getLength() - start, segment);
        Matcher m = pattern.matcher(segment);
        if (m.find()) {
            // remember that the index is relative to the document, so
            // always add the start position to it
            ndx = m.start() + start;
        }
    } catch (BadLocationException ex) {
        log.log(Level.SEVERE, null, ex);
    }
    return ndx;
}
 
Example #6
Source File: OverviewControllerUI.java    From visualvm with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void getText(int offset, int length, Segment txt) throws BadLocationException {
    if (lastOffset == offset && lastLength == length) {
        txt.array = segArray;
        txt.offset = segOffset;
        txt.count = segCount;
        txt.setPartialReturn(segPartialReturn);
        return;
    }
    super.getText(offset, length, txt);
    if (length > CACHE_BOUNDARY || lastLength <= CACHE_BOUNDARY) {
        segArray = txt.array;
        segOffset = txt.offset;
        segCount = txt.count;
        segPartialReturn = txt.isPartialReturn();
        lastOffset = offset;
        lastLength = length;
    }
}
 
Example #7
Source File: HTMLTextComponent.java    From visualvm with GNU General Public License v2.0 6 votes vote down vote up
public void getText(int offset, int length, Segment txt) throws BadLocationException {
    if (lastOffset == offset && lastLength == length) {
        txt.array = segArray;
        txt.offset = segOffset;
        txt.count = segCount;
        txt.setPartialReturn(segPartialReturn);
        return;
    }
    super.getText(offset, length, txt);
    if (length > CACHE_BOUNDARY || lastLength <= CACHE_BOUNDARY) {
        segArray = txt.array;
        segOffset = txt.offset;
        segCount = txt.count;
        segPartialReturn = txt.isPartialReturn();
        lastOffset = offset;
        lastLength = length;
    }
}
 
Example #8
Source File: SyntaxStyle.java    From visualvm with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Draw text.  This can directly call the Utilities.drawTabbedText.
 * Sub-classes can override this method to provide any other decorations.
 * @param  segment - the source of the text
 * @param  x - the X origin >= 0
 * @param  y - the Y origin >= 0
 * @param  graphics - the graphics context
 * @param e - how to expand the tabs. If this value is null, tabs will be 
 * expanded as a space character.
 * @param startOffset - starting offset of the text in the document >= 0 
 * @return
 */
public int drawText(Segment segment, int x, int y,
        Graphics graphics, TabExpander e, int startOffset) {
    graphics.setFont(graphics.getFont().deriveFont(getFontStyle()));
    FontMetrics fontMetrics = graphics.getFontMetrics();
    int a = fontMetrics.getAscent();
    int h = a + fontMetrics.getDescent();
    int w = Utilities.getTabbedTextWidth(segment, fontMetrics, 0, e, startOffset);
    int rX = x - 1;
    int rY = y - a;
    int rW = w + 2;
    int rH = h;
    if ((getFontStyle() & 0x10) != 0) {
        graphics.setColor(Color.decode("#EEEEEE"));
        graphics.fillRect(rX, rY, rW, rH);
    }
    graphics.setColor(getColor());
    x = Utilities.drawTabbedText(segment, x, y, graphics, e, startOffset);
    if ((getFontStyle() & 0x8) != 0) {
        graphics.setColor(Color.RED);
        graphics.drawRect(rX, rY, rW, rH);
    }
    return x;
}
 
Example #9
Source File: SyntaxDocument.java    From jpexs-decompiler with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Return a matcher that matches the given pattern in the part of the
 * document starting at offset start and ending at start + length. Note that
 * the matcher will have offset starting from <code>start</code>
 *
 * @param pattern
 * @param start
 * @param length
 * @return matcher that <b>MUST</b> be offset by start to get the proper
 * location within the document
 */
public Matcher getMatcher(Pattern pattern, int start, int length) {
    Matcher matcher = null;
    if (getLength() == 0) {
        return null;
    }
    if (start >= getLength()) {
        return null;
    }
    try {
        if (start < 0) {
            start = 0;
        }
        if (start + length > getLength()) {
            length = getLength() - start;
        }
        Segment seg = new Segment();
        getText(start, length, seg);
        matcher = pattern.matcher(seg);
    } catch (BadLocationException ex) {
        log.log(Level.SEVERE, "Requested offset: " + ex.offsetRequested(), ex);
    }
    return matcher;
}
 
Example #10
Source File: SerpentTokenMaker.java    From ethereumj with MIT License 6 votes vote down vote up
/**
    * Checks the token to give it the exact ID it deserves before
    * being passed up to the super method.
    *
    * @param segment <code>Segment</code> to get text from.
    * @param start Start offset in <code>segment</code> of token.
    * @param end End offset in <code>segment</code> of token.
    * @param tokenType The token's type.
    * @param startOffset The offset in the document at which the token occurs.
    */
   @Override
public void addToken(Segment segment, int start, int end, int tokenType, int startOffset) {

       switch (tokenType) {
           // Since reserved words, functions, and data types are all passed
           // into here as "identifiers," we have to see what the token
           // really is...
           case Token.IDENTIFIER:
               int value = wordsToHighlight.get(segment, start,end);
               if (value!=-1)
                   tokenType = value;
               break;

           case Token.ANNOTATION:
               value = wordsToHighlight.get(segment, start,end);
               if (value!=-1)
                   tokenType = value;
               break;
       }
       super.addToken(segment, start, end, tokenType, startOffset);
   }
 
Example #11
Source File: RLangKeywordMap.java    From Processing.R with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Looks up a key.
 * 
 * @param text The text segment
 * @param offset The offset of the substring within the text segment
 * @param length The length of the substring
 */
public byte lookup(final Segment text, final int offset, final int length) {
  if (length == 0) {
    return Token.NULL;
  }
  Keyword k = map[getSegmentMapKey(text, offset, length)];
  while (k != null) {
    if (length != k.keyword.length) {
      k = k.next;
      continue;
    }
    if (SyntaxUtilities.regionMatches(text, offset, k.keyword)) {
      return k.id;
    }
    k = k.next;
  }
  return Token.NULL;
}
 
Example #12
Source File: ThreadDumpWindow.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public void getText(int offset, int length, Segment txt) throws BadLocationException {
    if (lastOffset == offset && lastLength == length) {
        txt.array = segArray;
        txt.offset = segOffset;
        txt.count = segCount;
        txt.setPartialReturn(segPartialReturn);
        return;
    }
    super.getText(offset, length, txt);
    if (length > CACHE_BOUNDARY || lastLength <= CACHE_BOUNDARY) {
        segArray = txt.array;
        segOffset = txt.offset;
        segCount = txt.count;
        segPartialReturn = txt.isPartialReturn();
        lastOffset = offset;
        lastLength = length;
    }
}
 
Example #13
Source File: ConsoleTextArea.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
synchronized void returnPressed() {
    Document doc = getDocument();
    int len = doc.getLength();
    Segment segment = new Segment();
    try {
        doc.getText(outputMark, len - outputMark, segment);
    } catch(javax.swing.text.BadLocationException ignored) {
        ignored.printStackTrace();
    }
    if(segment.count > 0) {
        history.add(segment.toString());
    }
    historyIndex = history.size();
    inPipe.write(segment.array, segment.offset, segment.count);
    append("\n");
    outputMark = doc.getLength();
    inPipe.write("\n");
    inPipe.flush();
    console1.flush();
}
 
Example #14
Source File: UniTools.java    From jpexs-decompiler with GNU General Public License v3.0 6 votes vote down vote up
public static int getTabbedTextOffset(Segment segment, FontMetrics metrics, int tabBase,int x,TabExpander e, int startOffset){
    List<Segment> segments=new ArrayList<Segment>();
    List<Boolean> unis=new ArrayList<Boolean>();
    
    Font origFont=metrics.getFont();
    getSegments(origFont, segment, segments, unis);
    Graphics g=new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB).getGraphics();
    Font uniFont = defaultUniFont.deriveFont(origFont.getStyle(),origFont.getSize2D());       
    int ofs=0;
    int totalto = 0;
    for(int i=0;i<segments.size();i++){
        Segment seg=segments.get(i);
        FontMetrics fm=unis.get(i)?g.getFontMetrics(uniFont):metrics;
        int to = Utilities.getTabbedTextOffset(seg, fm, tabBase+ofs,x, e, startOffset);
        totalto += to;
        ofs+=fm.stringWidth(seg.toString());
        if(to<seg.length()){
            break;
        }            
    }        
    return totalto;
}
 
Example #15
Source File: KeywordMap.java    From rapidminer-studio with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Looks up a key.
 * 
 * @param text
 *            The text segment
 * @param offset
 *            The offset of the substring within the text segment
 * @param length
 *            The length of the substring
 */
public byte lookup(Segment text, int offset, int length) {
	if (length == 0) {
		return Token.NULL;
	}
	Keyword k = map[getSegmentMapKey(text, offset, length)];
	while (k != null) {
		if (length != k.keyword.length) {
			k = k.next;
			continue;
		}
		if (SyntaxUtilities.regionMatches(ignoreCase, text, offset, k.keyword)) {
			return k.id;
		}
		k = k.next;
	}
	return Token.NULL;
}
 
Example #16
Source File: UniTools.java    From jpexs-decompiler with GNU General Public License v3.0 6 votes vote down vote up
public static int drawTabbedText(Segment segment, int x, int y, Graphics g, TabExpander e, int startOffset){
    
    List<Segment> segments=new ArrayList<Segment>();
    List<Boolean> unis=new ArrayList<Boolean>();
    getSegments(g.getFont(), segment, segments, unis);
    Font origFont=g.getFont();
    Font uniFont = defaultUniFont.deriveFont(origFont.getStyle(),origFont.getSize2D());
    int ret=x;
    int pos=0;
    for(int i=0;i<segments.size();i++){
        Segment seg=segments.get(i);
        if(unis.get(i)){
            g.setFont(uniFont);
        }else{
            g.setFont(origFont);
        }
        ret = Utilities.drawTabbedText(seg, ret, y, g, e, startOffset+pos);   
        pos += seg.length();
    }
    g.setFont(origFont);
    return ret;         
}
 
Example #17
Source File: KStreamsTopologyTokenMaker.java    From netbeans-mmd-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the first token in the linked list of tokens generated
 * from <code>text</code>.  This method must be implemented by
 * subclasses so they can correctly implement syntax highlighting.
 *
 * @param text             The text from which to get tokens.
 * @param initialTokenType The token type we should start with.
 * @param startOffset      The offset into the document at which
 *                         <code>text</code> starts.
 * @return The first <code>Token</code> in a linked list representing
 * the syntax highlighted text.
 */
public Token getTokenList(Segment text, int initialTokenType, int startOffset) {

  resetTokenList();
  this.offsetShift = -text.offset + startOffset;

  // Start off in the proper state.
  int state = Token.NULL;
  switch (initialTokenType) {
    /* No multi-line comments */
    /* No documentation comments */
    default:
      state = Token.NULL;
  }

  s = text;
  try {
    yyreset(zzReader);
    yybegin(state);
    return yylex();
  } catch (IOException ioe) {
    ioe.printStackTrace();
    return new TokenImpl();
  }

}
 
Example #18
Source File: BDDTokenMaker.java    From Cognizant-Intelligent-Test-Scripter with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the first token in the linked list of tokens generated
 * from <code>text</code>.  This method must be implemented by
 * subclasses so they can correctly implement syntax highlighting.
 *
 * @param text The text from which to get tokens.
 * @param initialTokenType The token type we should start with.
 * @param startOffset The offset into the document at which
 *        <code>text</code> starts.
 * @return The first <code>Token</code> in a linked list representing
 *         the syntax highlighted text.
 */
public Token getTokenList(Segment text, int initialTokenType, int startOffset) {

	resetTokenList();
	this.offsetShift = -text.offset + startOffset;

	// Start off in the proper state.
	s = text;
	try {
		yyreset(zzReader);
		yybegin(YYINITIAL);
		return yylex();
	} catch (IOException ioe) {
		ioe.printStackTrace();
		return new TokenImpl();
	}

}
 
Example #19
Source File: SyntaxUtilities.java    From rapidminer-studio with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Checks if a subregion of a <code>Segment</code> is equal to a string.
 * 
 * @param ignoreCase
 *            True if case should be ignored, false otherwise
 * @param text
 *            The segment
 * @param offset
 *            The offset into the segment
 * @param match
 *            The string to match
 */
public static boolean regionMatches(boolean ignoreCase, Segment text, int offset, String match) {
	int length = offset + match.length();
	char[] textArray = text.array;
	if (length > text.offset + text.count) {
		return false;
	}
	for (int i = offset, j = 0; i < length; i++, j++) {
		char c1 = textArray[i];
		char c2 = match.charAt(j);
		if (ignoreCase) {
			c1 = Character.toUpperCase(c1);
			c2 = Character.toUpperCase(c2);
		}
		if (c1 != c2) {
			return false;
		}
	}
	return true;
}
 
Example #20
Source File: DocumentUtilities.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Copy portion of the document into target character array.
 * 
 * @param srcDoc document from which to copy.
 * @param srcStartOffset offset of the first character to copy.
 * @param srcEndOffset offset that follows the last character to copy.
 * @param dst destination character array into which the data will be copied.
 * @param dstOffset offset in the destination array at which the putting
 *  of the characters starts.
 * 
 * @throws javax.swing.text.BadLocationException 
 */
public static void copyText(Document srcDoc, int srcStartOffset,
int srcEndOffset, char[] dst, int dstOffset) throws BadLocationException {
    Segment text = new Segment();
    int gapStart = getGapStart(srcDoc);
    if (gapStart != -1 && srcStartOffset < gapStart && gapStart < srcEndOffset) {
        // Get part below gap
        srcDoc.getText(srcStartOffset, gapStart - srcStartOffset, text);
        System.arraycopy(text.array, text.offset, dst, dstOffset, text.count);
        dstOffset += text.count;
        srcStartOffset = gapStart;
    }

    srcDoc.getText(srcStartOffset, srcEndOffset - srcStartOffset, text);
    System.arraycopy(text.array, text.offset, dst, dstOffset, srcEndOffset - srcStartOffset);
}
 
Example #21
Source File: SyntaxUtilities.java    From Processing.R with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Checks if a subregion of a <code>Segment</code> is equal to a character array.
 * 
 * @param text The segment
 * @param offset The offset into the segment
 * @param match The character array to match
 */
public static boolean regionMatches(final Segment text, final int offset, final char[] match) {
  final int length = offset + match.length;
  final char[] textArray = text.array;
  if (length > text.offset + text.count) {
    return false;
  }
  for (int i = offset, j = 0; i < length; i++, j++) {
    if (textArray[i] != match[j]) {
      return false;
    }
  }
  return true;
}
 
Example #22
Source File: LineMarkedEditorPane.java    From jpexs-decompiler with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void paint(Graphics g, int offs0, int offs1, Shape bounds, JTextComponent c) {
    try {
        // --- determine locations ---
        TextUI mapper = c.getUI();

        Segment seg = new Segment();
        ((SyntaxDocument) c.getDocument()).getText(offs0, offs1 - offs0, seg);

        Rectangle r = mapper.modelToView(c, offs0, Position.Bias.Forward);
        FontMetrics fm = g.getFontMetrics();
        //int fh = fm.getHeight();
        fgStyle.drawText(seg, r.x, r.y + fm.getAscent(), g, null, offs0);
        /*for (int i = offs0; i < offs1; i++) {

         Rectangle r = mapper.modelToView(c, i, Position.Bias.Forward);
         Rectangle r1 = mapper.modelToView(c, i + 1, Position.Bias.Forward);
         if (r1.y == r.y) {
         ((SyntaxDocument) c.getDocument()).getText(i, 1, seg);
         fgStyle.drawText(seg, r.x, r.y, g, null, i);
         //g.drawLine(r.x, r.y + r.height - 3, r1.x, r.y + r.height - 3);
         }
         }*/

    } catch (BadLocationException e) {
        // can't render
    }
}
 
Example #23
Source File: PHPTokenMarker.java    From rapidminer-studio with GNU Affero General Public License v3.0 5 votes vote down vote up
private boolean doKeyword(Segment line, int i, char c) {
	int i1 = i + 1;

	int len = i - lastKeyword;
	byte id = keywords.lookup(line, lastKeyword, len);
	if (id != Token.NULL) {
		if (lastKeyword != lastOffset) {
			addToken(lastKeyword - lastOffset, Token.KEYWORD3);
		}
		addToken(len, id);
		lastOffset = i;
	}
	lastKeyword = i1;
	return false;
}
 
Example #24
Source File: ImageView.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
public Segment getText(int p0, int p1) {
    if (p0 < 0 || p1 > segment.array.length) {
        throw new RuntimeException("ImageLabelView: Stale view");
    }
    segment.offset = p0;
    segment.count = p1 - p0;
    return segment;
}
 
Example #25
Source File: DocumentCharacterIterator.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
DocumentCharacterIterator(Document doc) {
    this.doc = doc;
    text = new Segment();
    text.setPartialReturn(true);

    try {
        doc.getText(0, doc.getLength(), text);
    } catch (BadLocationException e) {
        throw new RuntimeException(e);
    }
    segmentEnd = text.count;
}
 
Example #26
Source File: PerlTokenMarker.java    From rapidminer-studio with GNU Affero General Public License v3.0 5 votes vote down vote up
private boolean doKeyword(Segment line, int i, char c) {
	int i1 = i + 1;

	if (token == S_END) {
		addToken(i - lastOffset, Token.LITERAL2);
		token = Token.NULL;
		lastOffset = i;
		lastKeyword = i1;
		return false;
	}

	int len = i - lastKeyword;
	byte id = keywords.lookup(line, lastKeyword, len);
	if (id == S_ONE || id == S_TWO) {
		if (lastKeyword != lastOffset) {
			addToken(lastKeyword - lastOffset, Token.NULL);
		}
		addToken(len, Token.LITERAL2);
		lastOffset = i;
		lastKeyword = i1;
		if (Character.isWhitespace(c)) {
			matchChar = '\0';
		} else {
			matchChar = c;
		}
		matchSpacesAllowed = true;
		token = id;
		return true;
	} else if (id != Token.NULL) {
		if (lastKeyword != lastOffset) {
			addToken(lastKeyword - lastOffset, Token.NULL);
		}
		addToken(len, id);
		lastOffset = i;
	}
	lastKeyword = i1;
	return false;
}
 
Example #27
Source File: TextAreaPainter.java    From rapidminer-studio with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Creates a new repaint manager. This should be not be called directly.
 */
public TextAreaPainter(JEditTextArea textArea, TextAreaDefaults defaults) {
	this.textArea = textArea;

	setAutoscrolls(true);
	setDoubleBuffered(true);
	setOpaque(true);

	ToolTipManager.sharedInstance().registerComponent(this);

	currentLine = new Segment();
	currentLineIndex = -1;

	setCursor(Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR));

	setFont(FontTools.getFont(Font.MONOSPACED, Font.PLAIN, 14));
	setForeground(Color.black);
	setBackground(Color.white);

	blockCaret = defaults.blockCaret;
	styles = defaults.styles;
	cols = defaults.cols;
	rows = defaults.rows;
	caretColor = defaults.caretColor;
	selectionColor = defaults.selectionColor;
	lineHighlightColor = defaults.lineHighlightColor;
	lineHighlight = defaults.lineHighlight;
	bracketHighlightColor = defaults.bracketHighlightColor;
	bracketHighlight = defaults.bracketHighlight;
	paintInvalid = defaults.paintInvalid;
	eolMarkerColor = defaults.eolMarkerColor;
	eolMarkers = defaults.eolMarkers;
}
 
Example #28
Source File: SyntaxUtilities.java    From rapidminer-studio with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Paints the specified line onto the graphics context. Note that this method munges the offset
 * and count values of the segment.
 * 
 * @param line
 *            The line segment
 * @param tokens
 *            The token list for the line
 * @param styles
 *            The syntax style list
 * @param expander
 *            The tab expander used to determine tab stops. May be null
 * @param gfx
 *            The graphics context
 * @param x
 *            The x co-ordinate
 * @param y
 *            The y co-ordinate
 * @return The x co-ordinate, plus the width of the painted string
 */
public static int paintSyntaxLine(Segment line, Token tokens, SyntaxStyle[] styles, TabExpander expander, Graphics gfx,
		int x, int y) {
	Font defaultFont = gfx.getFont();
	Color defaultColor = gfx.getColor();

	for (;;) {
		byte id = tokens.id;
		if (id == Token.END) {
			break;
		}

		int length = tokens.length;
		if (id == Token.NULL) {
			if (!defaultColor.equals(gfx.getColor())) {
				gfx.setColor(defaultColor);
			}
			if (!defaultFont.equals(gfx.getFont())) {
				gfx.setFont(defaultFont);
			}
		} else {
			styles[id].setGraphicsFlags(gfx, defaultFont);
		}

		line.count = length;
		x = Utilities.drawTabbedText(line, x, y, gfx, expander, 0);
		line.offset += length;

		tokens = tokens.next;
	}

	return x;
}
 
Example #29
Source File: MainPanel.java    From java-swing-tips with MIT License 5 votes vote down vote up
/**
 * Returns a <code>Segment</code>. When done, the <code>Segment</code>
 * should be recycled by invoking <code>releaseSegment</code>.
 */
public Segment getSegment() {
  synchronized (this) {
    int size = segments.size();
    if (size > 0) {
      return segments.remove(size - 1);
    }
  }
  return new CachedSegment();
}
 
Example #30
Source File: BytecodeTokenizer.java    From java-disassembler with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Returns the first token in the linked list of tokens generated
 * from <code>text</code>.  This method must be implemented by
 * subclasses so they can correctly implement syntax highlighting.
 *
 * @param text The text from which to get tokens.
 * @param initialTokenType The token type we should start with.
 * @param startOffset The offset into the document at which
 *        <code>text</code> starts.
 * @return The first <code>Token</code> in a linked list representing
 *         the syntax highlighted text.
 */
public Token getTokenList(Segment text, int initialTokenType, int startOffset) {

	resetTokenList();
	this.offsetShift = startOffset;

	// Start off in the proper state.
	int state = Token.NULL;
	switch (initialTokenType) {
		case Token.COMMENT_MULTILINE:
			state = MLC;
			start = 0;
			break;
		case Token.COMMENT_DOCUMENTATION:
			state = DOCCOMMENT;
			start = 0;
			break;
		default:
			state = Token.NULL;
	}

	s = text;
	try {
		reset(text, 0, text.count, state);
		return yylex();
	} catch (IOException ioe) {
		ioe.printStackTrace();
		return new TokenImpl();
	}

}