Java Code Examples for com.intellij.openapi.editor.ex.util.EditorUtil#getSpaceWidth()

The following examples show how to use com.intellij.openapi.editor.ex.util.EditorUtil#getSpaceWidth() . 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: EditorGutterComponentImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void calcAnnotationExtraSize() {
  myTextAnnotationExtraSize = 0;
  if (!myEditor.isInDistractionFreeMode() || isMirrored()) return;

  Window frame = SwingUtilities.getWindowAncestor(myEditor.getComponent());
  if (frame == null) return;

  EditorSettings settings = myEditor.getSettings();
  int rightMargin = settings.getRightMargin(myEditor.getProject());
  if (rightMargin <= 0) return;

  JComponent editorComponent = myEditor.getComponent();
  RelativePoint point = new RelativePoint(editorComponent, new Point(0, 0));
  Point editorLocationInWindow = point.getPoint(frame);

  int editorLocationX = (int)editorLocationInWindow.getX();
  int rightMarginX = rightMargin * EditorUtil.getSpaceWidth(Font.PLAIN, myEditor) + editorLocationX;

  int width = editorLocationX + editorComponent.getWidth();
  if (rightMarginX < width && editorLocationX < width - rightMarginX) {
    int centeredSize = (width - rightMarginX - editorLocationX) / 2 - (getLineMarkerAreaWidth() + getLineNumberAreaWidth() + getFoldingAreaWidth() + 2 * getGapBetweenAreas());
    myTextAnnotationExtraSize = Math.max(0, centeredSize - myTextAnnotationGuttersSize);
  }
}
 
Example 2
Source File: ConsoleGutterComponent.java    From consulo with Apache License 2.0 6 votes vote down vote up
public ConsoleGutterComponent(@Nonnull Editor editor, @Nonnull GutterContentProvider gutterContentProvider, boolean atLineStart) {
  this.editor = (DesktopEditorImpl)editor;
  this.gutterContentProvider = gutterContentProvider;
  this.atLineStart = atLineStart;

  if (atLineStart) {
    setOpaque(gutterContentProvider.getLineStartGutterOverlap(editor) == 0);
  }
  else {
    addListeners();
    setOpaque(false);
  }

  int spaceWidth = EditorUtil.getSpaceWidth(Font.PLAIN, editor);
  // at line start: icon/one-char symbol + space
  gap = atLineStart ? spaceWidth * GutterContentProvider.MAX_LINE_END_GUTTER_WIDTH_IN_CHAR : spaceWidth;
  maxContentWidth = atLineStart ? gap : 0;
}
 
Example 3
Source File: DesktopEditorImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void mouseReleased(@Nonnull MouseEvent e) {
  myMousePressArea = null;
  myLastMousePressedLocation = null;
  runMouseReleasedCommand(e);
  if (!e.isConsumed() && myMousePressedEvent != null && !myMousePressedEvent.isConsumed() &&
      Math.abs(e.getX() - myMousePressedEvent.getX()) < EditorUtil.getSpaceWidth(Font.PLAIN, DesktopEditorImpl.this) &&
      Math.abs(e.getY() - myMousePressedEvent.getY()) < getLineHeight()) {
    runMouseClickedCommand(e);
  }
}
 
Example 4
Source File: EditorSizeAdjustmentStrategy.java    From consulo with Apache License 2.0 5 votes vote down vote up
/**
 * Asks to adjust new preferred size appliance if necessary.
 *
 * @param newPreferredSize newly calculated preferred size that differs from the old preferred size
 * @param oldPreferredSize old preferred size (if any)
 * @param editor           target editor
 * @return preferred size to use (given 'new preferred size' may be adjusted)
 */
@Nonnull
Dimension adjust(@Nonnull Dimension newPreferredSize, @Nullable Dimension oldPreferredSize, @Nonnull DesktopEditorImpl editor) {
  if (oldPreferredSize == null || myInsideValidation) {
    return newPreferredSize;
  }
  // Process only width change.
  if (newPreferredSize.height != oldPreferredSize.height) {
    return newPreferredSize;
  }

  stripTimings();
  myTimings.add(System.currentTimeMillis());
  if (myTimings.size() < FREQUENT_SIZE_CHANGES_NUMBER) {
    return newPreferredSize;
  }

  boolean increaseWidth = newPreferredSize.width > oldPreferredSize.width;
  Dimension result;
  if (increaseWidth) {
    final int spaceWidth = EditorUtil.getSpaceWidth(Font.PLAIN, editor);
    newPreferredSize.width += myReserveColumns * spaceWidth;
    myReserveColumns += 3;
    result = newPreferredSize;
  }
  else {
    // Don't reduce preferred size on frequent reduce of the longest document line.
    result = oldPreferredSize;
  }

  scheduleSizeUpdate(editor);
  return result;
}
 
Example 5
Source File: EditorComponentImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) {
  if (orientation == SwingConstants.VERTICAL) {
    return myEditor.getLineHeight();
  }
  // if orientation == SwingConstants.HORIZONTAL
  return EditorUtil.getSpaceWidth(Font.PLAIN, myEditor);
}
 
Example 6
Source File: EditorFragmentComponent.java    From consulo with Apache License 2.0 4 votes vote down vote up
private void doInit(Component anchorComponent, EditorEx editor, int startLine, int endLine, boolean showFolding, boolean showGutter) {
  boolean newRendering = editor instanceof DesktopEditorImpl;
  int savedScrollOffset = newRendering ? 0 : editor.getScrollingModel().getHorizontalScrollOffset();

  FoldingModelEx foldingModel = editor.getFoldingModel();
  boolean isFoldingEnabled = foldingModel.isFoldingEnabled();
  if (!showFolding) {
    foldingModel.setFoldingEnabled(false);
  }
  int textImageWidth;
  int markersImageWidth;
  int textImageHeight;
  BufferedImage textImage;
  BufferedImage markersImage;
  JComponent rowHeader;
  try {
    Document doc = editor.getDocument();
    int endOffset = endLine < doc.getLineCount() ? doc.getLineEndOffset(Math.max(0, endLine - 1)) : doc.getTextLength();
    int widthAdjustment = newRendering ? EditorUtil.getSpaceWidth(Font.PLAIN, editor) : 0;
    textImageWidth = Math.min(editor.getMaxWidthInRange(doc.getLineStartOffset(startLine), endOffset) + widthAdjustment, getWidthLimit(editor));

    Point p1 = editor.logicalPositionToXY(new LogicalPosition(startLine, 0));
    Point p2 = editor.logicalPositionToXY(new LogicalPosition(Math.max(endLine, startLine + 1), 0));
    int y1 = p1.y;
    int y2 = p2.y;
    textImageHeight = y2 - y1 == 0 ? editor.getLineHeight() : y2 - y1;
    LOG.assertTrue(textImageHeight > 0, "Height: " + textImageHeight + "; startLine:" + startLine + "; endLine:" + endLine + "; p1:" + p1 + "; p2:" + p2);

    if (savedScrollOffset > 0) {
      editor.getScrollingModel().scrollHorizontally(0);
    }

    textImage = UIUtil.createImage(anchorComponent == null ? editor.getContentComponent() : anchorComponent, textImageWidth, textImageHeight, BufferedImage.TYPE_INT_RGB);
    Graphics textGraphics = textImage.getGraphics();
    EditorUIUtil.setupAntialiasing(textGraphics);

    if (showGutter) {
      rowHeader = editor.getGutterComponentEx();
      markersImageWidth = Math.max(1, rowHeader.getWidth());

      markersImage = UIUtil.createImage(editor.getComponent(), markersImageWidth, textImageHeight, BufferedImage.TYPE_INT_RGB);
      Graphics markerGraphics = markersImage.getGraphics();
      EditorUIUtil.setupAntialiasing(markerGraphics);

      markerGraphics.translate(0, -y1);
      markerGraphics.setClip(0, y1, rowHeader.getWidth(), textImageHeight);
      markerGraphics.setColor(getBackgroundColor(editor));
      markerGraphics.fillRect(0, y1, rowHeader.getWidth(), textImageHeight);
      rowHeader.paint(markerGraphics);
    }
    else {
      markersImageWidth = 0;
      rowHeader = null;
      markersImage = null;
    }

    textGraphics.translate(0, -y1);
    textGraphics.setClip(0, y1, textImageWidth, textImageHeight);
    boolean wasVisible = editor.setCaretVisible(false);
    editor.getContentComponent().paint(textGraphics);
    if (wasVisible) {
      editor.setCaretVisible(true);
    }
  }
  finally {
    if (!showFolding) {
      foldingModel.setFoldingEnabled(isFoldingEnabled);
    }
  }

  if (savedScrollOffset > 0) {
    editor.getScrollingModel().scrollHorizontally(savedScrollOffset);
  }

  JComponent component = new JComponent() {
    @Override
    public Dimension getPreferredSize() {
      return new Dimension(textImageWidth + markersImageWidth, textImageHeight);
    }

    @Override
    protected void paintComponent(Graphics graphics) {
      if (markersImage != null) {
        UIUtil.drawImage(graphics, markersImage, 0, 0, null);
        UIUtil.drawImage(graphics, textImage, rowHeader.getWidth(), 0, null);
      }
      else {
        UIUtil.drawImage(graphics, textImage, 0, 0, null);
      }
    }
  };

  setLayout(new BorderLayout());
  add(component);

  setBorder(createEditorFragmentBorder(editor));
}
 
Example 7
Source File: ScrollingModelImpl.java    From consulo with Apache License 2.0 4 votes vote down vote up
private Point calcOffsetsToScroll(Point targetLocation, ScrollType scrollType, Rectangle viewRect) {
  if (myEditor.getSettings().isRefrainFromScrolling() && viewRect.contains(targetLocation)) {
    if (scrollType == ScrollType.CENTER ||
        scrollType == ScrollType.CENTER_DOWN ||
        scrollType == ScrollType.CENTER_UP) {
      scrollType = ScrollType.RELATIVE;
    }
  }

  int spaceWidth = EditorUtil.getSpaceWidth(Font.PLAIN, myEditor);
  int xInsets = myEditor.getSettings().getAdditionalColumnsCount() * spaceWidth;

  int hOffset = scrollType == ScrollType.CENTER ||
                scrollType == ScrollType.CENTER_DOWN ||
                scrollType == ScrollType.CENTER_UP ? 0 : viewRect.x;
  if (targetLocation.x < hOffset) {
    int inset = 4 * spaceWidth;
    if (scrollType == ScrollType.MAKE_VISIBLE && targetLocation.x < viewRect.width - inset) {
      // if we need to scroll to the left to make target position visible,
      // let's scroll to the leftmost position (if that will make caret visible)
      hOffset = 0;
    }
    else {
      hOffset = Math.max(0, targetLocation.x - inset);
    }
  }
  else if (viewRect.width > 0 && targetLocation.x >= hOffset + viewRect.width) {
    hOffset = targetLocation.x - Math.max(0, viewRect.width - xInsets);
  }

  // the following code tries to keeps 1 line above and 1 line below if available in viewRect
  int lineHeight = myEditor.getLineHeight();
  // to avoid 'hysteresis', minAcceptableY should be always less or equal to maxAcceptableY
  int minAcceptableY = viewRect.y + Math.max(0, Math.min(lineHeight, viewRect.height - 3 * lineHeight));
  int maxAcceptableY = viewRect.y + (viewRect.height <= lineHeight ? 0 :
                                     (viewRect.height - (viewRect.height <= 2 * lineHeight ? lineHeight : 2 * lineHeight)));
  int scrollUpBy = minAcceptableY - targetLocation.y;
  int scrollDownBy = targetLocation.y - maxAcceptableY;
  int centerPosition = targetLocation.y - viewRect.height / 3;

  int vOffset = viewRect.y;
  if (scrollType == ScrollType.CENTER) {
    vOffset = centerPosition;
  }
  else if (scrollType == ScrollType.CENTER_UP) {
    if (scrollUpBy > 0 || scrollDownBy > 0 || vOffset > centerPosition) {
      vOffset = centerPosition;
    }
  }
  else if (scrollType == ScrollType.CENTER_DOWN) {
    if (scrollUpBy > 0 || scrollDownBy > 0 || vOffset < centerPosition) {
      vOffset = centerPosition;
    }
  }
  else if (scrollType == ScrollType.RELATIVE) {
    if (scrollUpBy > 0) {
      vOffset = viewRect.y - scrollUpBy;
    }
    else if (scrollDownBy > 0) {
      vOffset = viewRect.y + scrollDownBy;
    }
  }
  else if (scrollType == ScrollType.MAKE_VISIBLE) {
    if (scrollUpBy > 0 || scrollDownBy > 0) {
      vOffset = centerPosition;
    }
  }

  JScrollPane scrollPane = myEditor.getScrollPane();
  hOffset = Math.max(0, hOffset);
  vOffset = Math.max(0, vOffset);
  hOffset = Math.min(scrollPane.getHorizontalScrollBar().getMaximum() - getExtent(scrollPane.getHorizontalScrollBar()), hOffset);
  vOffset = Math.min(scrollPane.getVerticalScrollBar().getMaximum() - getExtent(scrollPane.getVerticalScrollBar()), vOffset);

  return new Point(hOffset, vOffset);
}
 
Example 8
Source File: SoftWrapApplianceManager.java    From consulo with Apache License 2.0 4 votes vote down vote up
private void doRecalculateSoftWraps(IncrementalCacheUpdateEvent event, int endOffsetUpperEstimate) {
  // Preparation.
  myContext.reset();
  myOffset2fontType.clear();
  myOffset2widthInPixels.clear();
  EditorTextRepresentationHelper editorTextRepresentationHelper = SoftWrapModelImpl.getEditorTextRepresentationHelper(myEditor);
  if (editorTextRepresentationHelper instanceof DefaultEditorTextRepresentationHelper) {
    ((DefaultEditorTextRepresentationHelper)editorTextRepresentationHelper).updateContext();
  }

  // Define start of the visual line that holds target range start.
  final int start = event.getStartOffset();
  final LogicalPosition logical = event.getStartLogicalPosition();

  Document document = myEditor.getDocument();
  myContext.text = document.getCharsSequence();
  myContext.tokenStartOffset = start;
  IterationState iterationState = new IterationState(myEditor, start, document.getTextLength(), null, false, false, true, false);
  TextAttributes attributes = iterationState.getMergedAttributes();
  myContext.fontType = normalizeFontType(attributes.getFontType());
  myContext.rangeEndOffset = event.getMandatoryEndOffset();

  EditorPosition position = new EditorPosition(logical, start, myEditor);
  position.x = start == 0 ? myEditor.getPrefixTextWidthInPixels() : 0;
  int spaceWidth = EditorUtil.getSpaceWidth(myContext.fontType, myEditor);
  int plainSpaceWidth = EditorUtil.getSpaceWidth(Font.PLAIN, myEditor);

  myContext.logicalLineData.update(logical.line, spaceWidth, plainSpaceWidth);

  myContext.currentPosition = position;
  myContext.lineStartPosition = position.clone();
  myContext.fontType2spaceWidth.put(myContext.fontType, spaceWidth);
  myContext.softWrapStartOffset = position.offset;

  myContext.reservedWidthInPixels = myPainter.getMinDrawingWidth(SoftWrapDrawingType.BEFORE_SOFT_WRAP_LINE_FEED);

  SoftWrap softWrapAtStartPosition = myStorage.getSoftWrap(start);
  if (softWrapAtStartPosition != null) {
    myContext.currentPosition.x = softWrapAtStartPosition.getIndentInPixels();
    myContext.softWrapStartOffset++;
  }

  myContext.inlineInlays = myEditor.getInlayModel().getInlineElementsInRange(start, endOffsetUpperEstimate);
  myContext.afterLineEndInlays = myEditor.getInlayModel().getAfterLineEndElementsInRange(DocumentUtil.getLineStartOffset(start, document), endOffsetUpperEstimate);

  // Perform soft wraps calculation.
  while (!iterationState.atEnd()) {
    FoldRegion currentFold = iterationState.getCurrentFold();
    if (currentFold == null) {
      myContext.tokenEndOffset = iterationState.getEndOffset();
      myContext.nextIsFoldRegion = iterationState.nextIsFoldRegion();
      if (processNonFoldToken()) {
        break;
      }
    }
    else {
      if (processCollapsedFoldRegion(currentFold)) {
        break;
      }

      // 'myOffset2widthInPixels' contains information necessary to processing soft wraps that lay before the current offset.
      // We do know that soft wraps are not allowed to go backward after processed collapsed fold region, hence, we drop
      // information about processed symbols width.
      myOffset2widthInPixels.clear();
    }

    iterationState.advance();
    attributes = iterationState.getMergedAttributes();
    myContext.fontType = normalizeFontType(attributes.getFontType());
    myContext.tokenStartOffset = iterationState.getStartOffset();
    myOffset2fontType.fill(myContext.tokenStartOffset, iterationState.getEndOffset(), myContext.fontType);
  }
  if (myContext.delayedSoftWrap != null) {
    myStorage.remove(myContext.delayedSoftWrap);
  }
  event.setActualEndOffset(myContext.currentPosition.offset);
}
 
Example 9
Source File: ArrowSoftWrapPainter.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
public Integer compute() {
  return EditorUtil.getSpaceWidth(Font.PLAIN, myEditor);
}
 
Example 10
Source File: CodeStyleAbstractPanel.java    From consulo with Apache License 2.0 4 votes vote down vote up
private void blinkHighlighters() {
  MarkupModel markupModel = myEditor.getMarkupModel();
  if (myShowsPreviewHighlighters) {
    Rectangle visibleArea = myEditor.getScrollingModel().getVisibleArea();
    VisualPosition visualStart = myEditor.xyToVisualPosition(visibleArea.getLocation());
    VisualPosition visualEnd = myEditor.xyToVisualPosition(new Point(visibleArea.x + visibleArea.width, visibleArea.y + visibleArea.height));

    // There is a possible case that viewport is located at its most bottom position and last document symbol
    // is located at the start of the line, hence, resulting visual end column has a small value and doesn't actually
    // indicates target visible rectangle. Hence, we need to correct that if necessary.
    int endColumnCandidate = visibleArea.width / EditorUtil.getSpaceWidth(Font.PLAIN, myEditor) + visualStart.column;
    if (endColumnCandidate > visualEnd.column) {
      visualEnd = new VisualPosition(visualEnd.line, endColumnCandidate);
    }
    int offsetToScroll = -1;
    CharSequence text = myEditor.getDocument().getCharsSequence();
    TextAttributes backgroundAttributes = myEditor.getColorsScheme().getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES);
    TextAttributes borderAttributes = new TextAttributes(
            null, null, backgroundAttributes.getBackgroundColor(), EffectType.BOXED, Font.PLAIN
    );
    boolean scrollToChange = true;
    for (TextRange range : myPreviewRangesToHighlight) {
      if (scrollToChange) {
        boolean rangeVisible = isWithinBounds(myEditor.offsetToVisualPosition(range.getStartOffset()), visualStart, visualEnd)
                               || isWithinBounds(myEditor.offsetToVisualPosition(range.getEndOffset()), visualStart, visualEnd);
        scrollToChange = !rangeVisible;
        if (offsetToScroll < 0) {
          if (offsetToScroll < 0) {
            if (text.charAt(range.getStartOffset()) != '\n') {
              offsetToScroll = range.getStartOffset();
            }
            else if (range.getEndOffset() > 0 && text.charAt(range.getEndOffset() - 1) != '\n') {
              offsetToScroll = range.getEndOffset() - 1;
            }
          }
        }
      }

      TextAttributes attributesToUse = range.getLength() > 0 ? backgroundAttributes : borderAttributes;
      markupModel.addRangeHighlighter(
              range.getStartOffset(), range.getEndOffset(), HighlighterLayer.SELECTION, attributesToUse, HighlighterTargetArea.EXACT_RANGE
      );
    }

    if (scrollToChange) {
      if (offsetToScroll < 0 && !myPreviewRangesToHighlight.isEmpty()) {
        offsetToScroll = myPreviewRangesToHighlight.get(0).getStartOffset();
      }
      if (offsetToScroll >= 0 && offsetToScroll < text.length() - 1 && text.charAt(offsetToScroll) != '\n') {
        // There is a possible case that target offset is located too close to the right edge. However, our point is to show
        // highlighted region at target offset, hence, we need to scroll to the visual symbol end. Hence, we're trying to ensure
        // that by scrolling to the symbol's end over than its start.
        offsetToScroll++;
      }
      if (offsetToScroll >= 0 && offsetToScroll < myEditor.getDocument().getTextLength()) {
        myEditor.getScrollingModel().scrollTo(
                myEditor.offsetToLogicalPosition(offsetToScroll), ScrollType.RELATIVE
        );
      }
    }
  }
  else {
    markupModel.removeAllHighlighters();
  }
  myShowsPreviewHighlighters = !myShowsPreviewHighlighters;
}
 
Example 11
Source File: CodeFormatterFacade.java    From consulo with Apache License 2.0 4 votes vote down vote up
public void doWrapLongLinesIfNecessary(@Nonnull final Editor editor, @Nonnull final Project project, @Nonnull Document document,
                                       int startOffset, int endOffset, List<? extends TextRange> enabledRanges) {
  // Normalization.
  int startOffsetToUse = Math.min(document.getTextLength(), Math.max(0, startOffset));
  int endOffsetToUse = Math.min(document.getTextLength(), Math.max(0, endOffset));

  LineWrapPositionStrategy strategy = LanguageLineWrapPositionStrategy.INSTANCE.forEditor(editor);
  CharSequence text = document.getCharsSequence();
  int startLine = document.getLineNumber(startOffsetToUse);
  int endLine = document.getLineNumber(Math.max(0, endOffsetToUse - 1));
  int maxLine = Math.min(document.getLineCount(), endLine + 1);
  int tabSize = EditorUtil.getTabSize(editor);
  if (tabSize <= 0) {
    tabSize = 1;
  }
  int spaceSize = EditorUtil.getSpaceWidth(Font.PLAIN, editor);
  int[] shifts = new int[2];
  // shifts[0] - lines shift.
  // shift[1] - offset shift.
  int cumulativeShift = 0;

  for (int line = startLine; line < maxLine; line++) {
    int startLineOffset = document.getLineStartOffset(line);
    int endLineOffset = document.getLineEndOffset(line);
    if (!canWrapLine(Math.max(startOffsetToUse, startLineOffset), Math.min(endOffsetToUse, endLineOffset), cumulativeShift, enabledRanges)) {
      continue;
    }

    final int preferredWrapPosition = calculatePreferredWrapPosition(editor, text, tabSize, spaceSize, startLineOffset, endLineOffset, endOffsetToUse);

    if (preferredWrapPosition < 0 || preferredWrapPosition >= endLineOffset) {
      continue;
    }
    if (preferredWrapPosition >= endOffsetToUse) {
      return;
    }

    // We know that current line exceeds right margin if control flow reaches this place, so, wrap it.
    int wrapOffset =
            strategy.calculateWrapPosition(document, editor.getProject(), Math.max(startLineOffset, startOffsetToUse), Math.min(endLineOffset, endOffsetToUse), preferredWrapPosition, false, false);
    if (wrapOffset < 0 // No appropriate wrap position is found.
        // No point in splitting line when its left part contains only white spaces, example:
        //    line start -> |                   | <- right margin
        //                  |   aaaaaaaaaaaaaaaa|aaaaaaaaaaaaaaaaaaaa() <- don't want to wrap this line even if it exceeds right margin
        || CharArrayUtil.shiftBackward(text, startLineOffset, wrapOffset - 1, " \t") < startLineOffset) {
      continue;
    }

    // Move caret to the target position and emulate pressing <enter>.
    editor.getCaretModel().moveToOffset(wrapOffset);
    emulateEnter(editor, project, shifts);

    //If number of inserted symbols on new line after wrapping more or equal then symbols left on previous line
    //there was no point to wrapping it, so reverting to before wrapping version
    if (shifts[1] - 1 >= wrapOffset - startLineOffset) {
      document.deleteString(wrapOffset, wrapOffset + shifts[1]);
    }
    else {
      // We know that number of lines is just increased, hence, update the data accordingly.
      maxLine += shifts[0];
      endOffsetToUse += shifts[1];
      cumulativeShift += shifts[1];
    }

  }
}