예제 #1
0
 // ------------------------------
 public void
     scrollToCaret() { // not called - fixed with putting visible scrollbars on JScrollPane
   //
   Rectangle rect1 = scroller1.getViewport().getViewRect();
   double x1 = rect1.getX();
   double y1 = rect1.getY();
   double r1height = rect1.getHeight();
   double r1width = rect1.getWidth();
   Caret caret1 = editor1.getCaret();
   Point pt2 = caret1.getMagicCaretPosition(); // the end of the string
   double x2 = pt2.getX();
   double y2 = pt2.getY();
   if (((x2 > x1) && (x2 < (x1 + r1width))) && ((y2 > y1) && (y2 < (y1 + r1height)))) {
     // inview
   } else {
     double newheight = r1height / 2;
     double newwidth = r1width / 2;
     double x3 = pt2.getX() - newwidth;
     double y3 = pt2.getY() - newheight;
     if (x3 < 0) x3 = 0;
     if (y3 < 0) y3 = 0;
     Rectangle rect3 = new Rectangle((int) x3, (int) y3, (int) newwidth, (int) newheight);
     editor1.scrollRectToVisible(rect3);
   }
 } // end scrollToCaret
예제 #2
0
 /**
  * Replaces the currently selected content with new content represented by the given StyledText.
  * If there is no selection this amounts to an insert of the given text. If there is no
  * replacement text this amounts to a removal of the current selection. The replacement text will
  * have the attributes currently defined for input at the point of insertion. If the document is
  * not editable, beep and return
  *
  * @param content the content to replace the selection with
  * @see StyledText#insert
  */
 public static void replaceSelection(Word word, StyledText content) {
   Document doc = word.workspace.getDocument();
   String text;
   Caret caret = word.workspace.getCaret();
   int insertPos = 0;
   int i;
   int contentSize;
   if (doc != null) {
     try {
       int p0 = Math.min(caret.getDot(), caret.getMark());
       int p1 = Math.max(caret.getDot(), caret.getMark());
       // if there is any selection
       if (p0 != p1) {
         doc.remove(p0, p1 - p0);
       }
       // insert the content
       if (content != null) {
         content.insert(doc, p0);
       }
     } catch (BadLocationException ble) {
       javax.swing.UIManager.getLookAndFeel().provideErrorFeedback(word.workspace);
       return;
     }
   }
 }
예제 #3
0
  static void updateStyle(JTextComponent comp, SynthContext context, String prefix) {
    SynthStyle style = context.getStyle();

    Color color = comp.getCaretColor();
    if (color == null || color instanceof UIResource) {
      comp.setCaretColor((Color) style.get(context, prefix + ".caretForeground"));
    }

    Color fg = comp.getForeground();
    if (fg == null || fg instanceof UIResource) {
      fg = style.getColorForState(context, ColorType.TEXT_FOREGROUND);
      if (fg != null) {
        comp.setForeground(fg);
      }
    }

    Object ar = style.get(context, prefix + ".caretAspectRatio");
    if (ar instanceof Number) {
      comp.putClientProperty("caretAspectRatio", ar);
    }

    context.setComponentState(SELECTED | FOCUSED);

    Color s = comp.getSelectionColor();
    if (s == null || s instanceof UIResource) {
      comp.setSelectionColor(style.getColor(context, ColorType.TEXT_BACKGROUND));
    }

    Color sfg = comp.getSelectedTextColor();
    if (sfg == null || sfg instanceof UIResource) {
      comp.setSelectedTextColor(style.getColor(context, ColorType.TEXT_FOREGROUND));
    }

    context.setComponentState(DISABLED);

    Color dfg = comp.getDisabledTextColor();
    if (dfg == null || dfg instanceof UIResource) {
      comp.setDisabledTextColor(style.getColor(context, ColorType.TEXT_FOREGROUND));
    }

    Insets margin = comp.getMargin();
    if (margin == null || margin instanceof UIResource) {
      margin = (Insets) style.get(context, prefix + ".margin");

      if (margin == null) {
        // Some places assume margins are non-null.
        margin = SynthLookAndFeel.EMPTY_UIRESOURCE_INSETS;
      }
      comp.setMargin(margin);
    }

    Caret caret = comp.getCaret();
    if (caret instanceof UIResource) {
      Object o = style.get(context, prefix + ".caretBlinkRate");
      if (o != null && o instanceof Integer) {
        Integer rate = (Integer) o;
        caret.setBlinkRate(rate.intValue());
      }
    }
  }
 private static Caret getNextCaretToProcess(@NotNull Editor editor) {
   for (Caret caret : editor.getCaretModel().getAllCarets()) {
     if (caret.getUserData(CARET_PROCESSED) == null) {
       return caret;
     }
   }
   return null;
 }
  public void commentRange(
      int startOffset,
      int endOffset,
      String commentPrefix,
      String commentSuffix,
      Commenter commenter) {
    final CharSequence chars = myDocument.getCharsSequence();
    LogicalPosition caretPosition = myCaret.getLogicalPosition();

    if (startOffset == 0 || chars.charAt(startOffset - 1) == '\n') {
      if (endOffset == myDocument.getTextLength()
          || endOffset > 0 && chars.charAt(endOffset - 1) == '\n') {
        CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(myProject);
        CommonCodeStyleSettings settings =
            CodeStyleSettingsManager.getSettings(myProject).getCommonSettings(myFile.getLanguage());
        String space;
        if (!settings.BLOCK_COMMENT_AT_FIRST_COLUMN) {
          final FileType fileType = myFile.getFileType();
          int line1 = myEditor.offsetToLogicalPosition(startOffset).line;
          int line2 = myEditor.offsetToLogicalPosition(endOffset - 1).line;
          Indent minIndent =
              CommentUtil.getMinLineIndent(myProject, myDocument, line1, line2, fileType);
          if (minIndent == null) {
            minIndent = codeStyleManager.zeroIndent();
          }
          space = codeStyleManager.fillIndent(minIndent, fileType);
        } else {
          space = "";
        }
        final StringBuilder nestingPrefix = new StringBuilder(space).append(commentPrefix);
        if (!commentPrefix.endsWith("\n")) {
          nestingPrefix.append("\n");
        }
        final StringBuilder nestingSuffix = new StringBuilder(space);
        nestingSuffix.append(
            commentSuffix.startsWith("\n") ? commentSuffix.substring(1) : commentSuffix);
        nestingSuffix.append("\n");
        TextRange range =
            insertNestedComments(
                startOffset,
                endOffset,
                nestingPrefix.toString(),
                nestingSuffix.toString(),
                commenter);
        myCaret.setSelection(range.getStartOffset(), range.getEndOffset());
        LogicalPosition pos = new LogicalPosition(caretPosition.line + 1, caretPosition.column);
        myCaret.moveToLogicalPosition(pos);
        return;
      }
    }

    TextRange range =
        insertNestedComments(startOffset, endOffset, commentPrefix, commentSuffix, commenter);
    myCaret.setSelection(range.getStartOffset(), range.getEndOffset());
    LogicalPosition pos =
        new LogicalPosition(caretPosition.line, caretPosition.column + commentPrefix.length());
    myCaret.moveToLogicalPosition(pos);
  }
  private void paintCaret(Graphics2D g_) {
    EditorImpl.CaretRectangle[] locations = myEditor.getCaretLocations(true);
    if (locations == null) return;

    Graphics2D g = IdeBackgroundUtil.getOriginalGraphics(g_);
    int lineHeight = myView.getLineHeight();
    EditorSettings settings = myEditor.getSettings();
    Color caretColor = myEditor.getColorsScheme().getColor(EditorColors.CARET_COLOR);
    if (caretColor == null) caretColor = new JBColor(CARET_DARK, CARET_LIGHT);
    g.setColor(caretColor);
    for (EditorImpl.CaretRectangle location : locations) {
      int x = location.myPoint.x;
      int y = location.myPoint.y;
      Caret caret = location.myCaret;
      boolean isRtl = location.myIsRtl;
      if (myEditor.isInsertMode() != settings.isBlockCursor()) {
        int lineWidth = JBUI.scale(settings.getLineCursorWidth());
        g.fillRect(x, y, lineWidth, lineHeight);
        if (myDocument.getTextLength() > 0
            && caret != null
            && !myView.getLineLayout(caret.getLogicalPosition().line).isLtr()) {
          g.fillPolygon(
              new int[] {
                isRtl ? x + lineWidth : x,
                isRtl ? x + lineWidth - CARET_DIRECTION_MARK_SIZE : x + CARET_DIRECTION_MARK_SIZE,
                isRtl ? x + lineWidth : x
              },
              new int[] {y, y, y + CARET_DIRECTION_MARK_SIZE},
              3);
        }
      } else {
        int width = location.myWidth;
        int startX = Math.max(0, isRtl ? x - width : x);
        g.fillRect(startX, y, width, lineHeight - 1);
        if (myDocument.getTextLength() > 0 && caret != null) {
          int targetVisualColumn = caret.getVisualPosition().column;
          for (VisualLineFragmentsIterator.Fragment fragment :
              VisualLineFragmentsIterator.create(myView, caret.getVisualLineStart(), false)) {
            int startVisualColumn = fragment.getStartVisualColumn();
            int endVisualColumn = fragment.getEndVisualColumn();
            if (startVisualColumn < targetVisualColumn && endVisualColumn > targetVisualColumn
                || startVisualColumn == targetVisualColumn && !isRtl
                || endVisualColumn == targetVisualColumn && isRtl) {
              g.setColor(ColorUtil.isDark(caretColor) ? CARET_LIGHT : CARET_DARK);
              fragment.draw(
                  g,
                  startX,
                  y + myView.getAscent(),
                  targetVisualColumn - startVisualColumn - (isRtl ? 1 : 0),
                  targetVisualColumn - startVisualColumn + (isRtl ? 0 : 1));
              break;
            }
          }
        }
      }
    }
  }
예제 #7
0
  private void initializePane() {
    mode = INSERT;
    addKeyListener(
        new KeyAdapter() {

          public void keyPressed(KeyEvent e) {
            if (e.getKeyCode() == KeyEvent.VK_INSERT) {
              toggleTypingMode();
            }
          }
        });

    // all editors display another caret when in overwrite mode
    // replace it
    setFont(new Font("Monospaced", Font.PLAIN, 12));
    Caret c =
        new DefaultCaret() {

          public void paint(Graphics g) {
            if (mode == INSERT) {
              super.paint(g);
              return;
            }
            JTextComponent comp = getComponent();

            int dot = getDot();
            Rectangle r = null;
            char c;
            try {
              r = comp.modelToView(dot);
              if (r == null) return;
              c = comp.getText(dot, 1).charAt(0);
            } catch (BadLocationException e) {
              return;
            }

            // erase provious caret
            if ((x != r.x) || (y != r.y)) {
              repaint();
              x = r.x;
              y = r.y;
              height = r.height;
            }

            g.setColor(comp.getCaretColor());
            g.setXORMode(comp.getBackground());

            width = g.getFontMetrics().charWidth(c);
            if (c == '\t' || c == '\n') width = g.getFontMetrics().charWidth(' ');
            if (isVisible()) {
              g.fillRect(r.x, r.y, width, r.height);
            }
          }
        };
    c.setBlinkRate(500); // default rate
    setCaret(c);
  }
예제 #8
0
  /**
   * Provides a way to determine the next visually represented model location at which one might
   * place a caret. Some views may not be visible, they might not be in the same order found in the
   * model, or they just might not allow access to some of the locations in the model.
   *
   * @param pos the position to convert >= 0
   * @param a the allocated region in which to render
   * @param direction the direction from the current position that can be thought of as the arrow
   *     keys typically found on a keyboard. This will be one of the following values:
   *     <ul>
   *       <li>SwingConstants.WEST
   *       <li>SwingConstants.EAST
   *       <li>SwingConstants.NORTH
   *       <li>SwingConstants.SOUTH
   *     </ul>
   *
   * @return the location within the model that best represents the next location visual position
   * @exception BadLocationException
   * @exception IllegalArgumentException if <code>direction</code> doesn't have one of the legal
   *     values above
   */
  public int getNextVisualPositionFrom(
      int pos, Position.Bias b, Shape a, int direction, Position.Bias[] biasRet)
      throws BadLocationException {

    biasRet[0] = Position.Bias.Forward;
    switch (direction) {
      case NORTH:
      case SOUTH:
        {
          if (pos == -1) {
            pos = (direction == NORTH) ? Math.max(0, getEndOffset() - 1) : getStartOffset();
            break;
          }
          JTextComponent target = (JTextComponent) getContainer();
          Caret c = (target != null) ? target.getCaret() : null;
          // YECK! Ideally, the x location from the magic caret position
          // would be passed in.
          Point mcp;
          if (c != null) {
            mcp = c.getMagicCaretPosition();
          } else {
            mcp = null;
          }
          int x;
          if (mcp == null) {
            Rectangle loc = target.modelToView(pos);
            x = (loc == null) ? 0 : loc.x;
          } else {
            x = mcp.x;
          }
          if (direction == NORTH) {
            pos = Utilities.getPositionAbove(target, pos, x);
          } else {
            pos = Utilities.getPositionBelow(target, pos, x);
          }
        }
        break;
      case WEST:
        if (pos == -1) {
          pos = Math.max(0, getEndOffset() - 1);
        } else {
          pos = Math.max(0, pos - 1);
        }
        break;
      case EAST:
        if (pos == -1) {
          pos = getStartOffset();
        } else {
          pos = Math.min(pos + 1, getDocument().getLength());
        }
        break;
      default:
        throw new IllegalArgumentException("Bad direction: " + direction);
    }
    return pos;
  }
예제 #9
0
 public void delete() {
   long p0 = caret.getMark();
   long p1 = caret.getDot();
   if (p0 < 0 || p1 < 0) return;
   if (p0 > p1) {
     long t = p0;
     p0 = p1;
     p1 = t;
   }
   model.fill(p0, p1 - p0 + 1, 0);
 }
예제 #10
0
 @Override
 public void deselect(Canvas canvas) {
   if (caret != null) {
     caret.stopEditing();
     caret = null;
   }
 }
예제 #11
0
  // HDC WINAPI BeginPaint( HWND hwnd, PAINTSTRUCT *lps )
  public static int BeginPaint(int hwnd, int lps) {
    WinWindow win = WinWindow.get(hwnd);

    if (lps == 0) return 0;

    Caret.HideCaret(hwnd);

    int rgn = WinRegion.CreateRectRgn(0, 0, win.rectWindow.width(), win.rectWindow.height());
    Message.SendMessageA(hwnd, WM_NCPAINT, rgn, 0);
    GdiObj.DeleteObject(rgn);

    WinDC dc = win.getDC();
    if (win.invalidationRect == null) {
      new WinRect(0, 0, win.rectClient.width(), win.rectClient.height()).write(lps + 8);
    } else {
      dc.clipX = win.invalidationRect.left;
      dc.clipY = win.invalidationRect.top;
      dc.clipCx = win.invalidationRect.width();
      dc.clipCy = win.invalidationRect.height();
      win.invalidationRect.write(lps + 8);
    }
    int hdc = dc.handle;
    writed(lps, hdc);
    writed(lps + 4, Message.SendMessageA(hwnd, WM_ERASEBKGND, hdc, 0));
    return readd(lps);
  }
 @Nullable
 private TextRange getSelectedComments(CharSequence text, String prefix, String suffix) {
   TextRange commentedRange = null;
   if (myCaret.hasSelection()) {
     int selectionStart = myCaret.getSelectionStart();
     selectionStart = CharArrayUtil.shiftForward(text, selectionStart, " \t\n");
     int selectionEnd = myCaret.getSelectionEnd() - 1;
     selectionEnd = CharArrayUtil.shiftBackward(text, selectionEnd, " \t\n") + 1;
     if (selectionEnd - selectionStart >= prefix.length() + suffix.length()
         && CharArrayUtil.regionMatches(text, selectionStart, prefix)
         && CharArrayUtil.regionMatches(text, selectionEnd - suffix.length(), suffix)) {
       commentedRange = new TextRange(selectionStart, selectionEnd);
     }
   }
   return commentedRange;
 }
예제 #13
0
 @Override
 public void setPosition(int position) {
   super.setPosition(position);
   if (CARET != null) {
     CARET.setVisible(true);
   }
 }
예제 #14
0
 @Override
 public void keyTyped(Canvas canvas, KeyEvent e) {
   if (caret != null) {
     caret.keyTyped(e);
     canvas.getProject().repaintCanvas();
   }
 }
 private Map<Integer, Couple<Integer>> createVirtualSelectionMap(
     int startVisualLine, int endVisualLine) {
   HashMap<Integer, Couple<Integer>> map = new HashMap<Integer, Couple<Integer>>();
   for (Caret caret : myEditor.getCaretModel().getAllCarets()) {
     if (caret.hasSelection()) {
       VisualPosition selectionStart = caret.getSelectionStartPosition();
       VisualPosition selectionEnd = caret.getSelectionEndPosition();
       if (selectionStart.line == selectionEnd.line) {
         int line = selectionStart.line;
         if (line >= startVisualLine && line <= endVisualLine) {
           map.put(line, Couple.of(selectionStart.column, selectionEnd.column));
         }
       }
     }
   }
   return map;
 }
예제 #16
0
 Dimension getPreferredSize() {
   int widthWithoutCaret = getPreferredWidth();
   int width = widthWithoutCaret;
   if (!myDocument.isInBulkUpdate()) {
     for (Caret caret : myEditor.getCaretModel().getAllCarets()) {
       if (caret.isUpToDate()) {
         int caretX = myView.visualPositionToXY(caret.getVisualPosition()).x;
         width = Math.max(caretX, width);
       }
     }
   }
   if (shouldRespectAdditionalColumns(widthWithoutCaret)) {
     width += myEditor.getSettings().getAdditionalColumnsCount() * myView.getPlainSpaceWidth();
   }
   Insets insets = myView.getInsets();
   return new Dimension(width + insets.left + insets.right, getPreferredHeight());
 }
예제 #17
0
 // BOOL EndPaint(HWND hWnd, const PAINTSTRUCT *lpPaint)
 public static int EndPaint(int hWnd, int lpPaint) {
   WinDC dc = WinDC.get(readd(lpPaint));
   if (dc != null) dc.close();
   Caret.ShowCaret(hWnd);
   Main.drawImage(StaticData.screen.getImage());
   WinWindow.get(hWnd).validate();
   return TRUE;
 }
예제 #18
0
 public void setModel(HexModel value) {
   if (model == value) return;
   if (model != null) model.removeHexModelListener(listener);
   model = value;
   highlighter.clear();
   caret.setDot(-1, false);
   if (model != null) model.addHexModelListener(listener);
   measures.recompute();
 }
  @Nullable
  private PsiElement findCommentAtCaret() {
    int offset = myCaret.getOffset();
    TextRange range = new TextRange(myCaret.getSelectionStart(), myCaret.getSelectionEnd());
    if (offset == range.getEndOffset()) {
      offset--;
    }
    if (offset <= range.getStartOffset()) {
      offset++;
    }
    PsiElement elt = myFile.getViewProvider().findElementAt(offset);
    if (elt == null) return null;
    PsiElement comment = PsiTreeUtil.getParentOfType(elt, PsiComment.class, false);
    if (comment == null || myCaret.hasSelection() && !range.contains(comment.getTextRange())) {
      return null;
    }

    return comment;
  }
 private boolean testSelectionForNonComments() {
   if (!myCaret.hasSelection()) {
     return true;
   }
   TextRange range = new TextRange(myCaret.getSelectionStart(), myCaret.getSelectionEnd() - 1);
   for (PsiElement element = myFile.findElementAt(range.getStartOffset());
       element != null && range.intersects(element.getTextRange());
       element = element.getNextSibling()) {
     if (element instanceof OuterLanguageElement) {
       if (!isInjectedWhiteSpace(range, (OuterLanguageElement) element)) {
         return false;
       }
     } else {
       if (!isWhiteSpaceOrComment(element, range)) {
         return false;
       }
     }
   }
   return true;
 }
 /*     */ public void paint(Graphics paramGraphics, Shape paramShape) /*     */ {
   /* 356 */ Rectangle localRectangle = (Rectangle) paramShape;
   /* 357 */ this.tabBase = localRectangle.x;
   /* 358 */ JTextComponent localJTextComponent = (JTextComponent) getContainer();
   /* 359 */ this.sel0 = localJTextComponent.getSelectionStart();
   /* 360 */ this.sel1 = localJTextComponent.getSelectionEnd();
   /* 361 */ this.unselected =
       (localJTextComponent.isEnabled()
           ? localJTextComponent.getForeground()
           : localJTextComponent.getDisabledTextColor());
   /*     */
   /* 363 */ Caret localCaret = localJTextComponent.getCaret();
   /* 364 */ this.selected =
       ((localCaret.isSelectionVisible()) && (localJTextComponent.getHighlighter() != null)
           ? localJTextComponent.getSelectedTextColor()
           : this.unselected);
   /*     */
   /* 366 */ paramGraphics.setFont(localJTextComponent.getFont());
   /*     */
   /* 369 */ super.paint(paramGraphics, paramShape);
   /*     */ }
  public void collapseFoldRegion(FoldRegion region) {
    assertIsDispatchThreadForEditor();
    if (!region.isExpanded()) return;

    if (!myIsBatchFoldingProcessing) {
      LOG.error("Fold regions must be collapsed or expanded inside batchFoldProcessing() only.");
    }

    List<Caret> carets = myEditor.getCaretModel().getAllCarets();
    for (Caret caret : carets) {
      LogicalPosition caretPosition = caret.getLogicalPosition();
      int caretOffset = myEditor.logicalPositionToOffset(caretPosition);

      if (FoldRegionsTree.contains(region, caretOffset)) {
        if (myDoNotCollapseCaret) return;
      }
    }
    for (Caret caret : carets) {
      LogicalPosition caretPosition = caret.getLogicalPosition();
      int caretOffset = myEditor.logicalPositionToOffset(caretPosition);

      if (FoldRegionsTree.contains(region, caretOffset)) {
        if (caret.getUserData(SAVED_CARET_POSITION) == null) {
          caret.putUserData(SAVED_CARET_POSITION, caretPosition.withoutVisualPositionInfo());
        }
      }
    }

    myFoldRegionsProcessed = true;
    ((FoldRegionImpl) region).setExpandedInternal(false);
    notifyListenersOnFoldRegionStateChange(region);
  }
예제 #23
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);
        }
      }
    }
예제 #24
0
  @Override
  protected void paintComponent(Graphics g) {
    measures.ensureComputed(g);

    Rectangle clip = g.getClipBounds();
    if (isOpaque()) {
      g.setColor(getBackground());
      g.fillRect(clip.x, clip.y, clip.width, clip.height);
    }

    long addr0 = model.getFirstOffset();
    long addr1 = model.getLastOffset();

    long xaddr0 = measures.toAddress(0, clip.y);
    if (xaddr0 == addr0) xaddr0 = measures.getBaseAddress(model);
    long xaddr1 = measures.toAddress(getWidth(), clip.y + clip.height) + 1;
    highlighter.paint(g, xaddr0, xaddr1);

    g.setColor(getForeground());
    Font baseFont = g.getFont();
    FontMetrics baseFm = g.getFontMetrics(baseFont);
    Font labelFont = baseFont.deriveFont(Font.ITALIC);
    FontMetrics labelFm = g.getFontMetrics(labelFont);
    int cols = measures.getColumnCount();
    int baseX = measures.getBaseX();
    int baseY = measures.toY(xaddr0) + baseFm.getAscent() + baseFm.getLeading() / 2;
    int dy = measures.getCellHeight();
    int labelWidth = measures.getLabelWidth();
    int labelChars = measures.getLabelChars();
    int cellWidth = measures.getCellWidth();
    int cellChars = measures.getCellChars();
    for (long a = xaddr0; a < xaddr1; a += cols, baseY += dy) {
      String label = toHex(a, labelChars);
      g.setFont(labelFont);
      g.drawString(
          label, baseX - labelWidth + (labelWidth - labelFm.stringWidth(label)) / 2, baseY);
      g.setFont(baseFont);
      long b = a;
      for (int j = 0; j < cols; j++, b++) {
        if (b >= addr0 && b <= addr1) {
          String val = toHex(model.get(b), cellChars);
          int x = measures.toX(b) + (cellWidth - baseFm.stringWidth(val)) / 2;
          g.drawString(val, x, baseY);
        }
      }
    }

    caret.paintForeground(g, xaddr0, xaddr1);
  }
  public void expandFoldRegion(FoldRegion region) {
    assertIsDispatchThreadForEditor();
    if (region.isExpanded() || region.shouldNeverExpand()) return;

    if (!myIsBatchFoldingProcessing) {
      LOG.error("Fold regions must be collapsed or expanded inside batchFoldProcessing() only.");
    }

    for (Caret caret : myEditor.getCaretModel().getAllCarets()) {
      LogicalPosition savedPosition = caret.getUserData(SAVED_CARET_POSITION);
      if (savedPosition != null) {
        int savedOffset = myEditor.logicalPositionToOffset(savedPosition);

        FoldRegion[] allCollapsed = myFoldTree.fetchCollapsedAt(savedOffset);
        if (allCollapsed.length == 1 && allCollapsed[0] == region) {
          caret.moveToLogicalPosition(savedPosition);
        }
      }
    }

    myFoldRegionsProcessed = true;
    ((FoldRegionImpl) region).setExpandedInternal(true);
    notifyListenersOnFoldRegionStateChange(region);
  }
예제 #26
0
    public void actionPerformed(JTextComponent text) {
      indentationLogic = ((EditorPane) text).getIndentationLogic();
      boolean indentError = false;
      Document doc = text.getDocument();
      Element map = doc.getDefaultRootElement();
      String tabWhitespace = PreferencesUser.getInstance().getTabWhitespace();
      Caret c = text.getCaret();
      int dot = c.getDot();
      int mark = c.getMark();
      int dotLine = map.getElementIndex(dot);
      int markLine = map.getElementIndex(mark);

      if (dotLine != markLine) {
        int first = Math.min(dotLine, markLine);
        int last = Math.max(dotLine, markLine);
        Element elem;
        int start;
        try {
          for (int i = first; i < last; i++) {
            elem = map.getElement(i);
            start = elem.getStartOffset();
            doc.insertString(start, tabWhitespace, null);
          }
          elem = map.getElement(last);
          start = elem.getStartOffset();
          if (Math.max(c.getDot(), c.getMark()) != start) {
            doc.insertString(start, tabWhitespace, null);
          }
        } catch (BadLocationException ble) {
          Debug.error(me + "Problem while indenting line\n%s", ble.getMessage());
          UIManager.getLookAndFeel().provideErrorFeedback(text);
        }
      } else {
        text.replaceSelection(tabWhitespace);
      }
    }
예제 #27
0
 public void setCaretPosition(int position) {
   Caret c = textView.getCaret();
   // move the caret
   c.setDot(position);
 }
예제 #28
0
 public int getCaretPosition() {
   Caret c = textView.getCaret();
   return c.getDot();
 }
 public void flushCaretPosition() {
   for (Caret caret : myEditor.getCaretModel().getAllCarets()) {
     caret.putUserData(SAVED_CARET_POSITION, null);
   }
 }
  private void notifyBatchFoldingProcessingDone(final boolean moveCaretFromCollapsedRegion) {
    rebuild();

    for (FoldingListener listener : myListeners) {
      listener.onFoldProcessingEnd();
    }

    myEditor.updateCaretCursor();
    myEditor.recalculateSizeAndRepaint();
    myEditor.getGutterComponentEx().updateSize();
    myEditor.getGutterComponentEx().repaint();

    for (Caret caret : myEditor.getCaretModel().getAllCarets()) {
      // There is a possible case that caret position is already visual position aware. But visual
      // position depends on number of folded
      // logical lines as well, hence, we can't be sure that target logical position defines correct
      // visual position because fold
      // regions have just changed. Hence, we use 'raw' logical position instead.
      LogicalPosition caretPosition = caret.getLogicalPosition().withoutVisualPositionInfo();
      int caretOffset = myEditor.logicalPositionToOffset(caretPosition);
      int selectionStart = caret.getSelectionStart();
      int selectionEnd = caret.getSelectionEnd();

      LogicalPosition positionToUse = null;
      int offsetToUse = -1;

      FoldRegion collapsed = myFoldTree.fetchOutermost(caretOffset);
      LogicalPosition savedPosition = caret.getUserData(SAVED_CARET_POSITION);
      if (savedPosition != null) {
        int savedOffset = myEditor.logicalPositionToOffset(savedPosition);
        FoldRegion collapsedAtSaved = myFoldTree.fetchOutermost(savedOffset);
        if (collapsedAtSaved == null) {
          positionToUse = savedPosition;
        } else {
          offsetToUse = collapsedAtSaved.getStartOffset();
        }
      }

      if (collapsed != null && positionToUse == null) {
        positionToUse = myEditor.offsetToLogicalPosition(collapsed.getStartOffset());
      }

      if (moveCaretFromCollapsedRegion && caret.isUpToDate()) {
        if (offsetToUse >= 0) {
          caret.moveToOffset(offsetToUse);
        } else if (positionToUse != null) {
          caret.moveToLogicalPosition(positionToUse);
        } else {
          caret.moveToLogicalPosition(caretPosition);
        }
      }

      caret.putUserData(SAVED_CARET_POSITION, savedPosition);

      if (isOffsetInsideCollapsedRegion(selectionStart)
          || isOffsetInsideCollapsedRegion(selectionEnd)) {
        caret.removeSelection();
      } else if (selectionStart < myEditor.getDocument().getTextLength()) {
        caret.setSelection(selectionStart, selectionEnd);
      }
    }

    if (mySavedCaretShift > 0) {
      final ScrollingModel scrollingModel = myEditor.getScrollingModel();
      scrollingModel.disableAnimation();
      scrollingModel.scrollVertically(
          myEditor.visibleLineToY(myEditor.getCaretModel().getVisualPosition().line)
              - mySavedCaretShift);
      scrollingModel.enableAnimation();
    }
  }