Example #1
1
  private void updateTemplateFromEditor(PrintfTemplate template) {
    ArrayList params = new ArrayList();
    String format = null;
    int text_length = editorPane.getDocument().getLength();
    try {
      format = editorPane.getDocument().getText(0, text_length);
    } catch (BadLocationException ex1) {
    }
    Element section_el = editorPane.getDocument().getDefaultRootElement();
    // Get number of paragraphs.
    int num_para = section_el.getElementCount();
    for (int p_count = 0; p_count < num_para; p_count++) {
      Element para_el = section_el.getElement(p_count);
      // Enumerate the content elements
      int num_cont = para_el.getElementCount();
      for (int c_count = 0; c_count < num_cont; c_count++) {
        Element content_el = para_el.getElement(c_count);
        AttributeSet attr = content_el.getAttributes();
        // Get the name of the style applied to this content element; may be null
        String sn = (String) attr.getAttribute(StyleConstants.NameAttribute);
        // Check if style name match
        if (sn != null && sn.startsWith("Parameter")) {
          // we extract the label.
          JLabel l = (JLabel) StyleConstants.getComponent(attr);
          if (l != null) {
            params.add(l.getName());
          }
        }
      }
    }

    template.setFormat(format);
    template.setTokens(params);
  }
Example #2
1
    // TODO: make this a method of SikuliDocument, no need to pass document as argument
    private void changeIndentation(DefaultStyledDocument doc, int linenum, int columns)
        throws BadLocationException {
      PreferencesUser pref = PreferencesUser.getInstance();
      boolean expandTab = pref.getExpandTab();
      int tabWidth = pref.getTabWidth();

      if (linenum < 0) {
        throw new BadLocationException("Negative line", -1);
      }
      Element map = doc.getDefaultRootElement();
      if (linenum >= map.getElementCount()) {
        throw new BadLocationException("No such line", doc.getLength() + 1);
      }
      if (columns == 0) {
        return;
      }

      Element lineElem = map.getElement(linenum);
      int lineStart = lineElem.getStartOffset();
      int lineLength = lineElem.getEndOffset() - lineStart;
      String line = doc.getText(lineStart, lineLength);

      // determine current indentation and number of whitespace characters
      int wsChars;
      int indentation = 0;
      for (wsChars = 0; wsChars < line.length(); wsChars++) {
        char c = line.charAt(wsChars);
        if (c == ' ') {
          indentation++;
        } else if (c == '\t') {
          indentation += tabWidth;
        } else {
          break;
        }
      }

      int newIndentation = indentation + columns;
      if (newIndentation <= 0) {
        doc.remove(lineStart, wsChars);
        return;
      }

      // build whitespace string for new indentation
      StringBuilder newWs = new StringBuilder(newIndentation / tabWidth + tabWidth - 1);
      int ind = 0;
      if (!expandTab) {
        for (; ind + tabWidth <= newIndentation; ind += tabWidth) {
          newWs.append('\t');
        }
      }
      for (; ind < newIndentation; ind++) {
        newWs.append(' ');
      }
      doc.replace(lineStart, wsChars, newWs.toString(), null);
    }
 /**
  * Inserting text with the same attributes into the beginning of the document.
  *
  * <p>This test is equivalent to <code>doc.insertString(insertOffset, newLine, null)</code>, where
  * <code>insertOffset = 0</code>.
  */
 public void testInsertSameAttrsDocStart() throws Exception {
   insertOffset = 0;
   // doc.insertString(insertOffset, newLine, null);
   content.insertString(insertOffset, newLine);
   event = doc.new DefaultDocumentEvent(insertOffset, newLineLen, EventType.INSERT);
   ElementSpec[] specs = {
     new ElementSpec(null, ElementSpec.ContentType, newLineLen),
     new ElementSpec(null, ElementSpec.EndTagType),
     new ElementSpec(null, ElementSpec.StartTagType)
   };
   specs[0].setDirection(ElementSpec.JoinPreviousDirection);
   specs[2].setDirection(ElementSpec.JoinFractureDirection);
   buf.insert(insertOffset, newLineLen, specs, event);
   List<?> edits = getEdits(event);
   assertEquals(2, edits.size());
   assertChange(edits.get(0), new int[] {0, 6, 6, 10, 10, 16, 16, 17}, new int[] {0, 1});
   assertChange(edits.get(1), new int[] {}, new int[] {1, 17});
   assertChildren(root.getElement(0), new int[] {0, 1}, new AttributeSet[] {null});
   assertChildren(
       root.getElement(1),
       new int[] {1, 6, 6, 10, 10, 16, 16, 17},
       new AttributeSet[] {null, bold, italic, null});
   assertEquals("\n", getText(doc.getCharacterElement(insertOffset)));
   assertEquals("plain", getText(doc.getCharacterElement(insertOffset + newLineLen)));
 }
Example #4
0
  /**
   * Highlight lines to start or end delimiter.
   *
   * @param content the content to parse
   * @param line the line number
   * @throws BadLocationException if offsets are wrong
   */
  protected void highlightLinesAfter(String content, int line) throws BadLocationException {
    int offset = m_RootElement.getElement(line).getEndOffset();

    // Start/End delimiter not found, nothing to do

    int startDelimiter = -1;
    int endDelimiter = -1;
    if (getMultiLineComment()) {
      startDelimiter = indexOf(content, getMultiLineCommentStart(), offset);
      endDelimiter = indexOf(content, getMultiLineCommentEnd(), offset);
    }

    if (startDelimiter < 0) startDelimiter = content.length();

    if (endDelimiter < 0) endDelimiter = content.length();

    int delimiter = Math.min(startDelimiter, endDelimiter);

    if (delimiter < offset) return;

    // Start/End delimiter found, reapply highlighting

    int endLine = m_RootElement.getElementIndex(delimiter);

    for (int i = line + 1; i < endLine; i++) {
      Element branch = m_RootElement.getElement(i);
      Element leaf = m_Self.getCharacterElement(branch.getStartOffset());
      AttributeSet as = leaf.getAttributes();

      if (as.isEqual(DEFAULT_COMMENT)) applyHighlighting(content, i);
    }
  }
 /**
  * Inserting text into the start of a paragraph with different attributes.
  *
  * <p>This test is equivalent to <code>doc.insertString(insertOffset, newLine, italic)</code>,
  * where <code>insertOffset = paragraph.getEndOffset()</code>.
  */
 public void testInsertDiffAttrsParStart() throws Exception {
   insertOffset = paragraph.getEndOffset();
   // doc.insertString(insertOffset, newLine, italic);
   content.insertString(insertOffset, newLine);
   event = doc.new DefaultDocumentEvent(insertOffset, newLineLen, EventType.INSERT);
   ElementSpec[] specs = {
     new ElementSpec(null, ElementSpec.EndTagType),
     new ElementSpec(null, ElementSpec.StartTagType),
     new ElementSpec(italic, ElementSpec.ContentType, newLineLen),
     new ElementSpec(null, ElementSpec.EndTagType),
     new ElementSpec(null, ElementSpec.StartTagType)
   };
   specs[4].setDirection(ElementSpec.JoinNextDirection);
   buf.insert(insertOffset, newLineLen, specs, event);
   List<?> edits = getEdits(event);
   assertEquals(3, edits.size());
   assertChange(edits.get(0), new int[] {15, 17}, new int[] {15, 16});
   assertChange(edits.get(1), new int[] {}, new int[] {16, 17});
   assertChange(edits.get(2), new int[] {}, new int[] {16, 17});
   assertChildren(
       root.getElement(0),
       new int[] {0, 5, 5, 9, 9, 15, 15, 16},
       new AttributeSet[] {null, bold, italic, null});
   assertChildren(root.getElement(1), new int[] {16, 17}, new AttributeSet[] {italic});
   assertChildren(root.getElement(2), new int[] {17, 22}, new AttributeSet[] {null});
   assertEquals("\n", getText(doc.getCharacterElement(insertOffset)));
   assertEquals("text\n", getText(doc.getCharacterElement(insertOffset + newLineLen)));
 }
 /**
  * Inserting text into end of the an element with the same attributes; the following element has
  * different attributes.
  *
  * <p>This test is equivalent to <code>doc.insertString(insertOffset, newLine, bold)</code>, where
  * 2 is added to default value of <code>insertOffset</code>.
  */
 public void testInsertSameAttrsEnd() throws Exception {
   insertOffset += 2;
   // doc.insertString(insertOffset, newLine, bold);
   content.insertString(insertOffset, newLine);
   event = doc.new DefaultDocumentEvent(insertOffset, newLineLen, EventType.INSERT);
   ElementSpec[] specs = {
     new ElementSpec(null, ElementSpec.ContentType, newLineLen),
     new ElementSpec(null, ElementSpec.EndTagType),
     new ElementSpec(null, ElementSpec.StartTagType)
   };
   specs[0].setDirection(ElementSpec.JoinPreviousDirection);
   specs[2].setDirection(ElementSpec.JoinFractureDirection);
   // Spec [0] has wrong attributes (should be bold) but everything works
   // the way it supposed to.
   buf.insert(insertOffset, newLineLen, specs, event);
   List<?> edits = getEdits(event);
   assertEquals(2, edits.size());
   assertChange(edits.get(0), new int[] {10, 16, 16, 17}, new int[] {});
   assertChange(edits.get(1), new int[] {}, new int[] {10, 17});
   assertChildren(root.getElement(0), new int[] {0, 5, 5, 10}, new AttributeSet[] {null, bold});
   assertChildren(
       root.getElement(1), new int[] {10, 16, 16, 17}, new AttributeSet[] {italic, null});
   assertEquals("bold\n", getText(doc.getCharacterElement(insertOffset)));
   assertEquals("italic", getText(doc.getCharacterElement(insertOffset + newLineLen)));
 }
Example #7
0
  /**
   * Repaint the region of change covered by the given document event. Damages the line that begins
   * the range to cover the case when the insert/remove is only on one line. If lines are added or
   * removed, damages the whole view. The longest line is checked to see if it has changed.
   */
  protected void updateDamage(DocumentEvent changes, Shape a, ViewFactory f) {
    Component host = getContainer();
    updateMetrics();
    Element elem = getElement();
    DocumentEvent.ElementChange ec = changes.getChange(elem);
    Element[] added = (ec != null) ? ec.getChildrenAdded() : null;
    Element[] removed = (ec != null) ? ec.getChildrenRemoved() : null;
    if (((added != null) && (added.length > 0)) || ((removed != null) && (removed.length > 0))) {
      // lines were added or removed...
      if (added != null) {
        int addedAt = ec.getIndex(); // FIXME: Is this correct?????
        for (int i = 0; i < added.length; i++) possiblyUpdateLongLine(added[i], addedAt + i);
      }
      if (removed != null) {
        for (int i = 0; i < removed.length; i++) {
          if (removed[i] == longLine) {
            longLineWidth = -1; // Must do this!!
            calculateLongestLine();
            break;
          }
        }
      }
      preferenceChanged(null, true, true);
      host.repaint();
    }

    // This occurs when syntax highlighting only changes on lines
    // (i.e. beginning a multiline comment).
    else if (changes.getType() == DocumentEvent.EventType.CHANGE) {
      // System.err.println("Updating the damage due to a CHANGE event...");
      int startLine = changes.getOffset();
      int endLine = changes.getLength();
      damageLineRange(startLine, endLine, a, host);
    } else {
      Element map = getElement();
      int line = map.getElementIndex(changes.getOffset());
      damageLineRange(line, line, a, host);
      if (changes.getType() == DocumentEvent.EventType.INSERT) {
        // check to see if the line is longer than current
        // longest line.
        Element e = map.getElement(line);
        if (e == longLine) {
          // We must recalculate longest line's width here
          // because it has gotten longer.
          longLineWidth = getLineWidth(line);
          preferenceChanged(null, true, false);
        } else {
          // If long line gets updated, update the status bars too.
          if (possiblyUpdateLongLine(e, line)) preferenceChanged(null, true, false);
        }
      } else if (changes.getType() == DocumentEvent.EventType.REMOVE) {
        if (map.getElement(line) == longLine) {
          // removed from longest line... recalc
          longLineWidth = -1; // Must do this!
          calculateLongestLine();
          preferenceChanged(null, true, false);
        }
      }
    }
  }
 /*     */ protected void drawLine(
     int paramInt1, int paramInt2, Graphics paramGraphics, int paramInt3, int paramInt4)
       /*     */ {
   /* 105 */ Element localElement1 = getElement();
   /* 106 */ Element localElement2 =
       localElement1.getElement(localElement1.getElementIndex(paramInt1));
   /*     */ try
   /*     */ {
     /* 110 */ if (localElement2.isLeaf()) {
       /* 111 */ drawText(
           localElement2, paramInt1, paramInt2, paramGraphics, paramInt3, paramInt4);
       /*     */ }
     /*     */ else {
       /* 114 */ int i = localElement2.getElementIndex(paramInt1);
       /* 115 */ int j = localElement2.getElementIndex(paramInt2);
       /* 116 */ for (; i <= j; i++) {
         /* 117 */ Element localElement3 = localElement2.getElement(i);
         /* 118 */ int k = Math.max(localElement3.getStartOffset(), paramInt1);
         /* 119 */ int m = Math.min(localElement3.getEndOffset(), paramInt2);
         /* 120 */ paramInt3 = drawText(localElement3, k, m, paramGraphics, paramInt3, paramInt4);
         /*     */ }
       /*     */ }
     /*     */ } catch (BadLocationException localBadLocationException) {
     /* 124 */ throw new StateInvariantError("Can't render: " + paramInt1 + "," + paramInt2);
     /*     */ }
   /*     */ }
Example #9
0
 public Element getLineAtCaret(int caretPosition) {
   Element root = getDocument().getDefaultRootElement();
   if (caretPosition == -1) {
     return root.getElement(root.getElementIndex(getCaretPosition()));
   } else {
     return root.getElement(root.getElementIndex(root.getElementIndex(caretPosition)));
   }
 }
Example #10
0
  /** Returns the offset where the selection ends on the specified line. */
  public int getSelectionEnd(int line) {
    if (line == selectionEndLine) return selectionEnd;
    else if (rectSelect) {
      Element map = document.getDefaultRootElement();
      int end = selectionEnd - map.getElement(selectionEndLine).getStartOffset();

      Element lineElement = map.getElement(line);
      int lineStart = lineElement.getStartOffset();
      int lineEnd = lineElement.getEndOffset() - 1;
      return Math.min(lineEnd, lineStart + end);
    } else return getLineEndOffset(line) - 1;
  }
 @Override
 protected void setUp() throws Exception {
   super.setUp();
   doc = new DefaultStyledDocument();
   root = doc.getDefaultRootElement();
   buf = new DefStyledDoc_Helpers.ElementBufferWithLogging(doc, root);
   doc.buffer = buf;
   paragraph = root.getElement(0);
   content = doc.getContent();
   content.insertString(0, "plainbolditalic\ntext");
   // Create the structure equivalent to this sequence:
   // doc.insertString(doc.getLength(), "plain", null);    // 5 chars
   // doc.insertString(doc.getLength(), "bold", bold);     // 4 chars
   // doc.insertString(doc.getLength(), "italic", italic); // 6 chars
   // doc.insertString(doc.getLength(), "\ntext", null);   // 5 chars
   doc.writeLock(); // Write lock needed to modify document structure
   Element[] leaves = new Element[4];
   leaves[0] = doc.createLeafElement(paragraph, null, 0, 5);
   leaves[1] = doc.createLeafElement(paragraph, bold, 5, 9);
   leaves[2] = doc.createLeafElement(paragraph, italic, 9, 15);
   leaves[3] = doc.createLeafElement(paragraph, null, 15, 16);
   ((BranchElement) paragraph).replace(0, 1, leaves);
   BranchElement branch = (BranchElement) doc.createBranchElement(root, null);
   leaves = new Element[1];
   leaves[0] = doc.createLeafElement(branch, null, 16, 21);
   branch.replace(0, 0, leaves);
   // Add this branch to the root
   ((BranchElement) root).replace(1, 0, new Element[] {branch});
   insertOffset = 5 + 2;
 }
Example #12
0
 /**
  * Returns the line.
  *
  * @param content the content
  * @param offset the offset to start at
  * @return the line
  */
 protected String getLine(String content, int offset) {
   int line = m_RootElement.getElementIndex(offset);
   Element lineElement = m_RootElement.getElement(line);
   int start = lineElement.getStartOffset();
   int end = lineElement.getEndOffset();
   return content.substring(start, end - 1);
 }
  /**
   * Paints the word-wrapped text.
   *
   * @param g The graphics context in which to paint.
   * @param a The shape (usually a rectangle) in which to paint.
   */
  public void paint(Graphics g, Shape a) {

    Rectangle alloc = (a instanceof Rectangle) ? (Rectangle) a : a.getBounds();
    tabBase = alloc.x;

    Graphics2D g2d = (Graphics2D) g;
    host = (RSyntaxTextArea) getContainer();
    int ascent = host.getMaxAscent();
    int fontHeight = host.getLineHeight();
    FoldManager fm = host.getFoldManager();
    TokenPainter painter = host.getTokenPainter();
    Element root = getElement();

    // Whether token styles should always be painted, even in selections
    int selStart = host.getSelectionStart();
    int selEnd = host.getSelectionEnd();
    boolean useSelectedTextColor = host.getUseSelectedTextColor();

    int n = getViewCount(); // Number of lines.
    int x = alloc.x + getLeftInset();
    tempRect.y = alloc.y + getTopInset();
    Rectangle clip = g.getClipBounds();
    for (int i = 0; i < n; i++) {

      tempRect.x = x + getOffset(X_AXIS, i);
      // tempRect.y = y + getOffset(Y_AXIS, i);
      tempRect.width = getSpan(X_AXIS, i);
      tempRect.height = getSpan(Y_AXIS, i);
      // System.err.println("For line " + i + ": tempRect==" + tempRect);

      if (tempRect.intersects(clip)) {
        Element lineElement = root.getElement(i);
        int startOffset = lineElement.getStartOffset();
        int endOffset = lineElement.getEndOffset() - 1; // Why always "-1"?
        View view = getView(i);
        if (!useSelectedTextColor
            || selStart == selEnd
            || (startOffset >= selEnd || endOffset < selStart)) {
          drawView(painter, g2d, alloc, view, fontHeight, tempRect.y + ascent);
        } else {
          // System.out.println("Drawing line with selection: " + i);
          drawViewWithSelection(
              painter, g2d, alloc, view, fontHeight, tempRect.y + ascent, selStart, selEnd);
        }
      }

      tempRect.y += tempRect.height;

      Fold possibleFold = fm.getFoldForLine(i);
      if (possibleFold != null && possibleFold.isCollapsed()) {
        i += possibleFold.getCollapsedLineCount();
        // Visible indicator of collapsed lines
        Color c = RSyntaxUtilities.getFoldedLineBottomColor(host);
        if (c != null) {
          g.setColor(c);
          g.drawLine(x, tempRect.y - 1, alloc.width, tempRect.y - 1);
        }
      }
    }
  }
Example #14
0
 private void analyseDocument(Document document, int lineNum, PythonIndentation indentationLogic)
     throws BadLocationException {
   Element map = document.getDefaultRootElement();
   int endPos = map.getElement(lineNum).getEndOffset();
   indentationLogic.reset();
   indentationLogic.addText(document.getText(0, endPos));
 }
Example #15
0
  /**
   * Adds the matching block end.
   *
   * @param offset the offset
   * @return the string after adding the matching block end
   * @throws BadLocationException if the offset is invalid
   */
  protected String addMatchingBlockEnd(int offset) throws BadLocationException {
    StringBuffer result;
    StringBuffer whiteSpace = new StringBuffer();
    int line = m_RootElement.getElementIndex(offset);
    int i = m_RootElement.getElement(line).getStartOffset();

    while (true) {
      String temp = m_Self.getText(i, 1);

      if (temp.equals(" ") || temp.equals("\t")) {
        whiteSpace.append(temp);
        i++;
      } else {
        break;
      }
    }

    // assemble string
    result = new StringBuffer();
    result.append(m_BlockStart);
    result.append("\n");
    result.append(whiteSpace.toString());
    if (m_UseBlanks) result.append(m_Indentation);
    else result.append("\t");
    result.append("\n");
    result.append(whiteSpace.toString());
    result.append(m_BlockEnd);

    return result.toString();
  }
Example #16
0
  /*
   *	Get the line number to be drawn. The empty string will be returned
   *  when a line of text has wrapped.
   */
  protected String getTextLineNumber(int rowStartOffset) {
    Element root = component.getDocument().getDefaultRootElement();
    int index = root.getElementIndex(rowStartOffset);
    Element line = root.getElement(index);

    if (line.getStartOffset() == rowStartOffset) return String.valueOf(index + 1);
    else return "";
  }
 /**
  * Loads all of the children to initialize the view. This is called by the <code>setParent</code>
  * method. Subclasses can re-implement this to initialize their child views in a different manner.
  * The default implementation creates a child view for each child element.
  *
  * @param f the view factory
  */
 protected void loadChildren(ViewFactory f) {
   Element e = getElement();
   int n = e.getElementCount();
   if (n > 0) {
     View[] added = new View[n];
     for (int i = 0; i < n; i++) added[i] = new WrappedLine(e.getElement(i));
     replace(0, 0, added);
   }
 }
  /**
   * Provides a mapping from the view coordinate space to the logical coordinate space of the model.
   *
   * @param fx the X coordinate &gt;= 0
   * @param fy the Y coordinate &gt;= 0
   * @param a the allocated region to render into
   * @return the location within the model that best represents the given point in the view &gt;= 0
   */
  @Override
  public int viewToModel(float fx, float fy, Shape a, Position.Bias[] bias) {

    bias[0] = Position.Bias.Forward;

    Rectangle alloc = a.getBounds();
    RSyntaxDocument doc = (RSyntaxDocument) getDocument();
    int x = (int) fx;
    int y = (int) fy;

    // If they're asking about a view position above the area covered by
    // this view, then the position is assumed to be the starting position
    // of this view.
    if (y < alloc.y) {
      return getStartOffset();
    }

    // If they're asking about a position below this view, the position
    // is assumed to be the ending position of this view.
    else if (y > alloc.y + alloc.height) {
      return host.getLastVisibleOffset();
    }

    // They're asking about a position within the coverage of this view
    // vertically.  So, we figure out which line the point corresponds to.
    // If the line is greater than the number of lines contained, then
    // simply use the last line as it represents the last possible place
    // we can position to.
    else {

      Element map = doc.getDefaultRootElement();
      int lineIndex = Math.abs((y - alloc.y) / lineHeight); // metrics.getHeight() );
      FoldManager fm = host.getFoldManager();
      // System.out.print("--- " + lineIndex);
      lineIndex += fm.getHiddenLineCountAbove(lineIndex, true);
      // System.out.println(" => " + lineIndex);
      if (lineIndex >= map.getElementCount()) {
        return host.getLastVisibleOffset();
      }

      Element line = map.getElement(lineIndex);

      // If the point is to the left of the line...
      if (x < alloc.x) {
        return line.getStartOffset();
      } else if (x > alloc.x + alloc.width) {
        return line.getEndOffset() - 1;
      } else {
        // Determine the offset into the text
        int p0 = line.getStartOffset();
        Token tokenList = doc.getTokenListForLine(lineIndex);
        tabBase = alloc.x;
        int offs = tokenList.getListOffset((RSyntaxTextArea) getContainer(), this, tabBase, x);
        return offs != -1 ? offs : p0;
      }
    } // End of else.
  }
Example #19
0
  /*
   *  Determine the Y offset for the current row
   */
  private int getOffsetY(int rowStartOffset, FontMetrics fontMetrics) throws BadLocationException {
    //  Get the bounding rectangle of the row

    Rectangle r = component.modelToView(rowStartOffset);
    int lineHeight = fontMetrics.getHeight();
    int y = r.y + r.height;
    int descent = 0;

    //  The text needs to be positioned above the bottom of the bounding
    //  rectangle based on the descent of the font(s) contained on the row.
    if (r.height == lineHeight) {
      // default font is being used
      descent = fontMetrics.getDescent();
    } else {
      // We need to check all the attributes for font changes
      if (fonts == null) {
        fonts = new HashMap<String, FontMetrics>();
      }

      Element root = component.getDocument().getDefaultRootElement();
      int index = root.getElementIndex(rowStartOffset);
      Element line = root.getElement(index);

      for (int i = 0; i < line.getElementCount(); i++) {
        Element child = line.getElement(i);
        AttributeSet as = child.getAttributes();
        String fontFamily = (String) as.getAttribute(StyleConstants.FontFamily);
        Integer fontSize = (Integer) as.getAttribute(StyleConstants.FontSize);
        String key = fontFamily + fontSize;

        FontMetrics fm = fonts.get(key);

        if (fm == null) {
          Font font = new Font(fontFamily, Font.PLAIN, fontSize);
          fm = component.getFontMetrics(font);
          fonts.put(key, fm);
        }

        descent = Math.max(descent, fm.getDescent());
      }
    }

    return y - descent;
  }
 /**
  * Returns the last child of <code>parent</code> that is a leaf. If the last child is a not a
  * leaf, this method is called with the last child.
  */
 private Element getDeepestLeaf(Element parent) {
   if (parent.isLeaf()) {
     return parent;
   }
   int childCount = parent.getElementCount();
   if (childCount == 0) {
     return parent;
   }
   return getDeepestLeaf(parent.getElement(childCount - 1));
 }
 public void appendToEnd(String text) {
   Element root = document.getDefaultRootElement();
   try {
     document.insertAfterEnd(root.getElement(root.getElementCount() - 1), text);
   } catch (BadLocationException e) {
     logger.error("Insert in the HTMLDocument failed.", e);
   } catch (IOException e) {
     logger.error("Insert in the HTMLDocument failed.", e);
   }
 }
 /*     */ protected void loadChildren(ViewFactory paramViewFactory) /*     */ {
   /* 261 */ Element localElement = getElement();
   /* 262 */ int i = localElement.getElementCount();
   /* 263 */ if (i > 0) {
     /* 264 */ View[] arrayOfView = new View[i];
     /* 265 */ for (int j = 0; j < i; j++) {
       /* 266 */ arrayOfView[j] = new WrappedLine(localElement.getElement(j));
       /*     */ }
     /* 268 */ replace(0, 0, arrayOfView);
     /*     */ }
   /*     */ }
  public void insertAfterStart(String text) {
    Element root = this.document.getDefaultRootElement();

    try {
      this.document.insertBeforeStart(root.getElement(0), text);
    } catch (BadLocationException e) {
      logger.error("Insert in the HTMLDocument failed.", e);
    } catch (IOException e) {
      logger.error("Insert in the HTMLDocument failed.", e);
    }
  }
  /**
   * Fetches the previous Element. If howver the current element is the last element, or the current
   * element is null, then null is returned.
   *
   * @return previous <code>Element</code> if available
   */
  public Element previous() {

    int stackSize;
    if (elementStack == null || (stackSize = elementStack.size()) == 0) {
      return null;
    }

    // get a handle to the element on top of the stack
    //
    StackItem item = (StackItem) elementStack.peek();
    Element elem = item.getElement();
    int index = item.getIndex();

    if (index > 0) {
      /* return child at previous index. */
      return getDeepestLeaf(elem.getElement(--index));
    } else if (index == 0) {
      /* this implies that current is the element's
      first child, therefore previous is the
      element itself. */
      return elem;
    } else if (index == -1) {
      if (stackSize == 1) {
        // current is the root, nothing before it.
        return null;
      }
      /* We need to return either the item
      below the top item or one of the
      former's children. */
      Object top = elementStack.pop();
      item = (StackItem) elementStack.peek();

      // restore the top item.
      elementStack.push(top);
      elem = item.getElement();
      index = item.getIndex();
      return ((index == -1) ? elem : getDeepestLeaf(elem.getElement(index)));
    }
    // should never get here.
    return null;
  }
Example #25
0
  /** Returns the selected text, or null if no selection is active. */
  public final String getSelectedText() {
    if (selectionStart == selectionEnd) return null;

    if (rectSelect) {
      // Return each row of the selection on a new line

      Element map = document.getDefaultRootElement();

      int start = selectionStart - map.getElement(selectionStartLine).getStartOffset();
      int end = selectionEnd - map.getElement(selectionEndLine).getStartOffset();

      // Certain rectangles satisfy this condition...
      if (end < start) {
        int tmp = end;
        end = start;
        start = tmp;
      }

      StringBuffer buf = new StringBuffer();
      Segment seg = new Segment();

      for (int i = selectionStartLine; i <= selectionEndLine; i++) {
        Element lineElement = map.getElement(i);
        int lineStart = lineElement.getStartOffset();
        int lineEnd = lineElement.getEndOffset() - 1;
        int lineLen = lineEnd - lineStart;

        lineStart = Math.min(lineStart + start, lineEnd);
        lineLen = Math.min(end - start, lineEnd - lineStart);

        getText(lineStart, lineLen, seg);
        buf.append(seg.array, seg.offset, seg.count);

        if (i != selectionEndLine) buf.append('\n');
      }

      return buf.toString();
    } else {
      return getText(selectionStart, selectionEnd - selectionStart);
    }
  }
Example #26
0
 public boolean reparseCheckContent() {
   Element e = this.getDocument().getDefaultRootElement();
   String txt;
   if (e.getElementCount() > 2) {
     return false;
   } else if (e.getElement(1).getEndOffset() - e.getElement(1).getStartOffset() > 1) {
     return false;
   } else {
     int is = e.getElement(0).getStartOffset();
     int ie = e.getElement(0).getEndOffset();
     try {
       txt = e.getElement(0).getDocument().getText(is, ie - 1);
       if (txt.endsWith(Settings.TypeCommentToken)) {
         return true;
       }
     } catch (BadLocationException ex) {
       return false;
     }
   }
   return false;
 }
Example #27
0
 public Element getLineAtPoint(MouseEvent me) {
   Point p = me.getLocationOnScreen();
   Point pp = getLocationOnScreen();
   p.translate(-pp.x, -pp.y);
   int pos = viewToModel(p);
   Element root = getDocument().getDefaultRootElement();
   int e = root.getElementIndex(pos);
   if (e == -1) {
     return null;
   }
   return root.getElement(e);
 }
Example #28
0
 public int getLineStartOffset(int line) throws BadLocationException {
   // line starting from 0
   Element map = getDocument().getDefaultRootElement();
   if (line < 0) {
     throw new BadLocationException("Negative line", -1);
   } else if (line >= map.getElementCount()) {
     throw new BadLocationException("No such line", getDocument().getLength() + 1);
   } else {
     Element lineElem = map.getElement(line);
     return lineElem.getStartOffset();
   }
 }
Example #29
0
  /**
   * Parse the line to determine the appropriate highlighting.
   *
   * @param content the content to parse
   * @param line the line number
   * @throws BadLocationException if offsets are invalid
   */
  protected void applyHighlighting(String content, int line) throws BadLocationException {
    int startOffset = m_RootElement.getElement(line).getStartOffset();
    int endOffset = m_RootElement.getElement(line).getEndOffset() - 1;

    int lineLength = endOffset - startOffset;
    int contentLength = content.length();

    if (endOffset >= contentLength) endOffset = contentLength - 1;

    // check for multi line comments
    // (always set the comment attribute for the entire line)

    if (getMultiLineComment()) {
      if (endingMultiLineComment(content, startOffset, endOffset)
          || isMultiLineComment()
          || startingMultiLineComment(content, startOffset, endOffset)) {
        m_Self.setCharacterAttributes(
            startOffset, endOffset - startOffset + 1, DEFAULT_COMMENT, false);
        return;
      }
    }

    // set normal attributes for the line

    m_Self.setCharacterAttributes(startOffset, lineLength, DEFAULT_NORMAL, true);

    // check for single line comment

    int index = content.indexOf(getSingleLineCommentStart(), startOffset);

    if ((index > -1) && (index < endOffset)) {
      m_Self.setCharacterAttributes(index, endOffset - index + 1, DEFAULT_COMMENT, false);
      endOffset = index - 1;
    }

    // check for tokens

    checkForTokens(content, startOffset, endOffset);
  }
Example #30
0
    public void actionPerformed(JTextComponent text) {
      indentationLogic = ((EditorPane) text).getIndentationLogic();
      StyledDocument doc = (StyledDocument) text.getDocument();
      Element map = doc.getDefaultRootElement();
      Caret c = text.getCaret();
      int dot = c.getDot();
      int mark = c.getMark();
      int line1 = map.getElementIndex(dot);

      if (dot != mark) {
        int line2 = map.getElementIndex(mark);
        int begin = Math.min(line1, line2);
        int end = Math.max(line1, line2);
        Element elem;
        try {
          for (line1 = begin; line1 < end; line1++) {
            elem = map.getElement(line1);
            handleDecreaseIndent(line1, elem, doc);
          }
          elem = map.getElement(end);
          int start = elem.getStartOffset();
          if (Math.max(c.getDot(), c.getMark()) != start) {
            handleDecreaseIndent(end, elem, doc);
          }
        } catch (BadLocationException ble) {
          Debug.error(me + "Problem while de-indenting line\n%s", ble.getMessage());
          UIManager.getLookAndFeel().provideErrorFeedback(text);
        }
      } else {
        Element elem = map.getElement(line1);
        try {
          handleDecreaseIndent(line1, elem, doc);
        } catch (BadLocationException ble) {
          Debug.error(me + "Problem while de-indenting line\n%s", ble.getMessage());
          UIManager.getLookAndFeel().provideErrorFeedback(text);
        }
      }
    }