protected void doOKAction() {
    final LogicalPosition currentPosition = myEditor.getCaretModel().getLogicalPosition();
    int lineNumber = getLineNumber(currentPosition.line + 1);
    if (isInternal() && myOffsetField.getText().length() > 0) {
      try {
        final int offset = Integer.parseInt(myOffsetField.getText());
        if (offset < myEditor.getDocument().getTextLength()) {
          myEditor.getCaretModel().removeSecondaryCarets();
          myEditor.getCaretModel().moveToOffset(offset);
          myEditor.getScrollingModel().scrollToCaret(ScrollType.CENTER);
          myEditor.getSelectionModel().removeSelection();
          IdeFocusManager.getGlobalInstance().requestFocus(myEditor.getContentComponent(), true);
          super.doOKAction();
        }
        return;
      } catch (NumberFormatException e) {
        return;
      }
    }

    if (lineNumber < 0) return;

    int columnNumber = getColumnNumber(currentPosition.column);
    myEditor.getCaretModel().removeSecondaryCarets();
    myEditor
        .getCaretModel()
        .moveToLogicalPosition(
            new LogicalPosition(Math.max(0, lineNumber - 1), Math.max(0, columnNumber - 1)));
    myEditor.getScrollingModel().scrollToCaret(ScrollType.CENTER);
    myEditor.getSelectionModel().removeSelection();
    IdeFocusManager.getGlobalInstance().requestFocus(myEditor.getContentComponent(), true);
    super.doOKAction();
  }
    private void recalculateMaxValues() {
      myIdxLeft = widestEditor(myLeftEditors);
      final Editor leftEditor = myLeftEditors.get(myIdxLeft);
      final int wholeWidth = leftEditor.getContentComponent().getWidth();
      final Rectangle va = leftEditor.getScrollingModel().getVisibleArea();
      final int visibleLeft = leftEditor.xyToVisualPosition(new Point(va.width, 0)).column;

      myMaxColumnsLeft = (int) (visibleLeft * ((double) wholeWidth / va.getWidth()));

      myIdxRight = widestEditor(myRightEditors);
      final Editor rightEditor = myRightEditors.get(myIdxRight);
      final int wholeWidthRight = rightEditor.getContentComponent().getWidth();
      final Rectangle vaRight = rightEditor.getScrollingModel().getVisibleArea();
      final int visibleRight = rightEditor.xyToVisualPosition(new Point(va.width, 0)).column;

      myMaxColumnsRight = (int) (visibleRight * ((double) wholeWidthRight / vaRight.getWidth()));

      myByLeft = !(myMaxColumnsLeft <= visibleLeft);
      if (!myByLeft) {
        // check right editor
        if (myLeftScroll.getVisibleAmount() != visibleRight) {
          myLeftScroll.setVisibleAmount(visibleRight);
        }
        myLeftScroll.setMaximum(myMaxColumnsRight);
      } else {
        if (myLeftScroll.getVisibleAmount() != visibleLeft) {
          myLeftScroll.setVisibleAmount(visibleLeft);
        }
        myLeftScroll.setMaximum(myMaxColumnsLeft);
      }
    }
  private BeforeAfter<Integer> getEditorLines() {
    final Editor editor = ((DiffPanelImpl) getCurrentPanel()).getEditor1();
    Rectangle visibleArea = editor.getScrollingModel().getVisibleArea();
    final int offset = editor.getScrollingModel().getVerticalScrollOffset();

    int leftPixels = offset % editor.getLineHeight();

    final Point start = visibleArea.getLocation();
    final LogicalPosition startLp = editor.xyToLogicalPosition(start);
    final Point location = new Point(start.x + visibleArea.width, start.y + visibleArea.height);
    final LogicalPosition lp = editor.xyToLogicalPosition(location);

    int curStartLine =
        startLp.line == (editor.getDocument().getLineCount() - 1)
            ? startLp.line
            : (startLp.line + 1);
    int cutEndLine = lp.line == 0 ? 0 : lp.line - 1;

    boolean commonPartOk = leftPixels == 0 || startLp.line == lp.line;
    return new BeforeAfter<Integer>(
        commonPartOk && startLp.softWrapLinesOnCurrentLogicalLine == 0
            ? startLp.line
            : curStartLine,
        commonPartOk && lp.softWrapLinesOnCurrentLogicalLine == 0 ? lp.line : cutEndLine);
    /*if (leftPixels == 0 || startLp.line == lp.line) {
      return new BeforeAfter<Integer>(startLp.line, lp.line);
    } else {
      return new BeforeAfter<Integer>(curStartLine, cutEndLine);
    }*/
  }
  private void updateCursorHighlighting(boolean scroll) {
    hideBalloon();

    if (myCursorHighlighter != null) {
      HighlightManager.getInstance(mySearchResults.getProject())
          .removeSegmentHighlighter(mySearchResults.getEditor(), myCursorHighlighter);
      myCursorHighlighter = null;
    }

    final FindResult cursor = mySearchResults.getCursor();
    Editor editor = mySearchResults.getEditor();
    SelectionModel selection = editor.getSelectionModel();
    if (cursor != null) {
      Set<RangeHighlighter> dummy = new HashSet<RangeHighlighter>();
      highlightRange(
          cursor, new TextAttributes(null, null, Color.BLACK, EffectType.ROUNDED_BOX, 0), dummy);
      if (!dummy.isEmpty()) {
        myCursorHighlighter = dummy.iterator().next();
      }

      if (scroll) {
        if (mySearchResults.getFindModel().isGlobal()) {
          FoldingModel foldingModel = editor.getFoldingModel();
          final FoldRegion[] allRegions = editor.getFoldingModel().getAllFoldRegions();

          foldingModel.runBatchFoldingOperation(
              new Runnable() {
                @Override
                public void run() {
                  for (FoldRegion region : allRegions) {
                    if (!region.isValid()) continue;
                    if (cursor.intersects(TextRange.create(region))) {
                      region.setExpanded(true);
                    }
                  }
                }
              });
          selection.setSelection(cursor.getStartOffset(), cursor.getEndOffset());

          editor.getCaretModel().moveToOffset(cursor.getEndOffset());
          editor.getScrollingModel().scrollToCaret(ScrollType.CENTER);
        } else {
          if (!SearchResults.insideVisibleArea(editor, cursor)) {
            LogicalPosition pos = editor.offsetToLogicalPosition(cursor.getStartOffset());
            editor.getScrollingModel().scrollTo(pos, ScrollType.CENTER);
          }
        }
      }
      editor
          .getScrollingModel()
          .runActionOnScrollingFinished(
              new Runnable() {
                @Override
                public void run() {
                  showReplacementPreview();
                }
              });
    }
  }
 private void restoreOriginalLocation() {
   for (Map.Entry<Editor, Integer> e : myCaretRelativeVerticalPositions.entrySet()) {
     Editor editor = e.getKey();
     int relativePosition = e.getValue();
     Point caretLocation = editor.visualPositionToXY(editor.getCaretModel().getVisualPosition());
     int scrollOffset = caretLocation.y - relativePosition;
     editor.getScrollingModel().disableAnimation();
     editor.getScrollingModel().scrollVertically(scrollOffset);
     editor.getScrollingModel().enableAnimation();
   }
 }
  /**
   * Scroll to the error specified by the given tree path, or do nothing if no error is specified.
   *
   * @param treePath the tree path to scroll to.
   */
  private void scrollToError(final TreePath treePath) {
    final DefaultMutableTreeNode treeNode =
        (DefaultMutableTreeNode) treePath.getLastPathComponent();
    if (treeNode == null || !(treeNode.getUserObject() instanceof ResultTreeNode)) {
      return;
    }

    final ResultTreeNode nodeInfo = (ResultTreeNode) treeNode.getUserObject();
    if (nodeInfo.getFile() == null || nodeInfo.getProblem() == null) {
      return; // no problem here :-)
    }

    final VirtualFile virtualFile = nodeInfo.getFile().getVirtualFile();
    if (virtualFile == null || !virtualFile.exists()) {
      return;
    }

    final FileEditorManager fileEditorManager = FileEditorManager.getInstance(project);
    final FileEditor[] editor = fileEditorManager.openFile(virtualFile, true);

    if (editor.length > 0 && editor[0] instanceof TextEditor) {
      final LogicalPosition problemPos =
          new LogicalPosition(Math.max(lineFor(nodeInfo) - 1, 0), Math.max(columnFor(nodeInfo), 0));

      final Editor textEditor = ((TextEditor) editor[0]).getEditor();
      textEditor.getCaretModel().moveToLogicalPosition(problemPos);
      textEditor.getScrollingModel().scrollToCaret(ScrollType.CENTER);
    }
  }
 public void invoke(
     @NotNull Project project, Editor editor, PsiFile file, DataContext dataContext) {
   editor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE);
   final int offset =
       TargetElementUtil.adjustOffset(
           file, editor.getDocument(), editor.getCaretModel().getOffset());
   final PsiElement element = file.findElementAt(offset);
   PsiTypeElement typeElement = PsiTreeUtil.getParentOfType(element, PsiTypeElement.class);
   while (typeElement != null) {
     final PsiElement parent = typeElement.getParent();
     PsiElement[] toMigrate = null;
     if (parent instanceof PsiVariable) {
       toMigrate = extractReferencedVariables(typeElement);
     } else if ((parent instanceof PsiMember && !(parent instanceof PsiClass))
         || isClassArgument(parent)) {
       toMigrate = new PsiElement[] {parent};
     }
     if (toMigrate != null && toMigrate.length > 0) {
       invoke(project, toMigrate, null, null, editor);
       return;
     }
     typeElement = PsiTreeUtil.getParentOfType(parent, PsiTypeElement.class, false);
   }
   CommonRefactoringUtil.showErrorHint(
       project,
       editor,
       "The caret should be positioned on type of field, variable, method or method parameter to be refactored",
       REFACTORING_NAME,
       "refactoring.migrateType");
 }
Esempio n. 8
0
  public static void showInfoTooltip(
      @NotNull final HighlightInfo info,
      final Editor editor,
      final int defaultOffset,
      final int currentWidth) {
    if (info.toolTip == null || info.getSeverity() == HighlightSeverity.INFORMATION) return;
    Rectangle visibleArea = editor.getScrollingModel().getVisibleArea();
    int endOffset = info.highlighter.getEndOffset();
    int startOffset = info.highlighter.getStartOffset();

    Point top = editor.logicalPositionToXY(editor.offsetToLogicalPosition(startOffset));
    Point bottom = editor.logicalPositionToXY(editor.offsetToLogicalPosition(endOffset));

    Point bestPoint = new Point(top.x, bottom.y + editor.getLineHeight());

    if (!visibleArea.contains(bestPoint)) {
      bestPoint = editor.logicalPositionToXY(editor.offsetToLogicalPosition(defaultOffset));
    }

    Point p =
        SwingUtilities.convertPoint(
            editor.getContentComponent(),
            bestPoint,
            editor.getComponent().getRootPane().getLayeredPane());
    TooltipController.getInstance()
        .showTooltip(editor, p, info.toolTip, currentWidth, false, DAEMON_INFO_GROUP);
  }
  public void invoke(
      @NotNull Project project, Editor editor, PsiFile file, DataContext dataContext) {
    int offset = editor.getCaretModel().getOffset();
    editor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE);
    PsiElement element = file.findElementAt(offset);

    while (true) {
      if (element == null || element instanceof PsiFile) {
        String message =
            RefactoringBundle.getCannotRefactorMessage(
                RefactoringBundle.message(
                    "the.caret.should.be.positioned.inside.a.class.to.push.members.from"));
        CommonRefactoringUtil.showErrorHint(
            project, editor, message, REFACTORING_NAME, HelpID.MEMBERS_PUSH_DOWN);
        return;
      }

      if (element instanceof PsiClass
          || element instanceof PsiField
          || element instanceof PsiMethod) {
        if (element instanceof JspClass) {
          RefactoringMessageUtil.showNotSupportedForJspClassesError(
              project, editor, REFACTORING_NAME, HelpID.MEMBERS_PUSH_DOWN);
          return;
        }
        invoke(project, new PsiElement[] {element}, dataContext);
        return;
      }
      element = element.getParent();
    }
  }
Esempio n. 10
0
  public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
    PsiElement element = descriptor.getPsiElement();
    PsiStatement anchorStatement = PsiTreeUtil.getParentOfType(element, PsiStatement.class);
    LOG.assertTrue(anchorStatement != null);
    Editor editor = getEditor(project, element);
    if (editor == null) return;
    PsiFile file = element.getContainingFile();
    PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
    Document document = documentManager.getDocument(file);
    if (!CodeInsightUtilBase.prepareFileForWrite(file)) return;
    PsiElement[] elements = {anchorStatement};
    PsiElement prev = PsiTreeUtil.skipSiblingsBackward(anchorStatement, PsiWhiteSpace.class);
    if (prev instanceof PsiComment
        && SuppressManager.getInstance().getSuppressedInspectionIdsIn(prev) != null) {
      elements = new PsiElement[] {prev, anchorStatement};
    }
    try {
      TextRange textRange = new JavaWithIfSurrounder().surroundElements(project, editor, elements);
      if (textRange == null) return;

      @NonNls String newText = myText + " != null";
      document.replaceString(textRange.getStartOffset(), textRange.getEndOffset(), newText);
      editor.getCaretModel().moveToOffset(textRange.getEndOffset() + newText.length());
      editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);

    } catch (IncorrectOperationException e) {
      LOG.error(e);
    }
  }
 public void startTemplateWithPrefix(
     final Editor editor,
     final TemplateImpl template,
     final int templateStart,
     @Nullable final PairProcessor<String, String> processor,
     @Nullable final String argument) {
   final int caretOffset = editor.getCaretModel().getOffset();
   final TemplateState templateState = initTemplateState(editor);
   CommandProcessor commandProcessor = CommandProcessor.getInstance();
   commandProcessor.executeCommand(
       myProject,
       () -> {
         editor.getDocument().deleteString(templateStart, caretOffset);
         editor.getCaretModel().moveToOffset(templateStart);
         editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
         editor.getSelectionModel().removeSelection();
         Map<String, String> predefinedVarValues = null;
         if (argument != null) {
           predefinedVarValues = new HashMap<String, String>();
           predefinedVarValues.put(TemplateImpl.ARG, argument);
         }
         templateState.start(template, processor, predefinedVarValues);
       },
       CodeInsightBundle.message("insert.code.template.command"),
       null);
 }
Esempio n. 12
0
  private HighlightersSet installHighlighterSet(Info info, Editor editor) {
    final JComponent internalComponent = editor.getContentComponent();
    internalComponent.addKeyListener(myEditorKeyListener);
    editor.getScrollingModel().addVisibleAreaListener(myVisibleAreaListener);
    final Cursor cursor = internalComponent.getCursor();
    internalComponent.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
    myFileEditorManager.addFileEditorManagerListener(myFileEditorManagerListener);

    List<RangeHighlighter> highlighters = new ArrayList<RangeHighlighter>();
    TextAttributes attributes =
        myEditorColorsManager
            .getGlobalScheme()
            .getAttributes(EditorColors.REFERENCE_HYPERLINK_COLOR);
    for (TextRange range : info.getRanges()) {
      TextAttributes attr = patchAttributesColor(attributes, range, editor);
      final RangeHighlighter highlighter =
          editor
              .getMarkupModel()
              .addRangeHighlighter(
                  range.getStartOffset(),
                  range.getEndOffset(),
                  HighlighterLayer.SELECTION + 1,
                  attr,
                  HighlighterTargetArea.EXACT_RANGE);
      highlighters.add(highlighter);
    }

    return new HighlightersSet(highlighters, editor, cursor, info);
  }
 public TextRange surroundExpression(
     final Project project, final Editor editor, PsiExpression expr)
     throws IncorrectOperationException {
   assert expr.isValid();
   PsiType[] types = GuessManager.getInstance(project).guessTypeToCast(expr);
   final boolean parenthesesNeeded =
       expr instanceof PsiPolyadicExpression
           || expr instanceof PsiConditionalExpression
           || expr instanceof PsiAssignmentExpression;
   String exprText = parenthesesNeeded ? "(" + expr.getText() + ")" : expr.getText();
   final Template template = generateTemplate(project, exprText, types);
   TextRange range;
   if (expr.isPhysical()) {
     range = expr.getTextRange();
   } else {
     final RangeMarker rangeMarker = expr.getUserData(ElementToWorkOn.TEXT_RANGE);
     if (rangeMarker == null) return null;
     range = new TextRange(rangeMarker.getStartOffset(), rangeMarker.getEndOffset());
   }
   editor.getDocument().deleteString(range.getStartOffset(), range.getEndOffset());
   editor.getCaretModel().moveToOffset(range.getStartOffset());
   editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
   TemplateManager.getInstance(project).startTemplate(editor, template);
   return null;
 }
Esempio n. 14
0
  private void removeFromEditor() {
    Editor editor = mySearchResults.getEditor();
    if (myReplacementBalloon != null) {
      myReplacementBalloon.hide();
    }

    if (editor != null) {

      for (VisibleAreaListener visibleAreaListener : myVisibleAreaListenersToRemove) {
        editor.getScrollingModel().removeVisibleAreaListener(visibleAreaListener);
      }
      myVisibleAreaListenersToRemove.clear();
      Project project = mySearchResults.getProject();
      if (project != null && !project.isDisposed()) {
        for (RangeHighlighter h : myHighlighters) {
          HighlightManager.getInstance(project).removeSegmentHighlighter(editor, h);
        }
        if (myCursorHighlighter != null) {
          HighlightManager.getInstance(project)
              .removeSegmentHighlighter(editor, myCursorHighlighter);
          myCursorHighlighter = null;
        }
      }
      myHighlighters.clear();
      if (myListeningSelection) {
        editor.getSelectionModel().removeSelectionListener(this);
        myListeningSelection = false;
      }
    }
  }
  private void altCommitToOriginal(@NotNull DocumentEvent e) {
    final PsiFile origPsiFile =
        PsiDocumentManager.getInstance(myProject).getPsiFile(myOrigDocument);
    String newText = myNewDocument.getText();
    // prepare guarded blocks
    LinkedHashMap<String, String> replacementMap = new LinkedHashMap<String, String>();
    int count = 0;
    for (RangeMarker o : ContainerUtil.reverse(((DocumentEx) myNewDocument).getGuardedBlocks())) {
      String replacement = o.getUserData(REPLACEMENT_KEY);
      String tempText = "REPLACE" + (count++) + Long.toHexString(StringHash.calc(replacement));
      newText =
          newText.substring(0, o.getStartOffset()) + tempText + newText.substring(o.getEndOffset());
      replacementMap.put(tempText, replacement);
    }
    // run preformat processors
    final int hostStartOffset = myAltFullRange.getStartOffset();
    myEditor.getCaretModel().moveToOffset(hostStartOffset);
    for (CopyPastePreProcessor preProcessor :
        Extensions.getExtensions(CopyPastePreProcessor.EP_NAME)) {
      newText = preProcessor.preprocessOnPaste(myProject, origPsiFile, myEditor, newText, null);
    }
    myOrigDocument.replaceString(hostStartOffset, myAltFullRange.getEndOffset(), newText);
    // replace temp strings for guarded blocks
    for (String tempText : replacementMap.keySet()) {
      int idx =
          CharArrayUtil.indexOf(
              myOrigDocument.getCharsSequence(),
              tempText,
              hostStartOffset,
              myAltFullRange.getEndOffset());
      myOrigDocument.replaceString(idx, idx + tempText.length(), replacementMap.get(tempText));
    }
    // JAVA: fix occasional char literal concatenation
    fixDocumentQuotes(myOrigDocument, hostStartOffset - 1);
    fixDocumentQuotes(myOrigDocument, myAltFullRange.getEndOffset());

    // reformat
    PsiDocumentManager.getInstance(myProject).commitDocument(myOrigDocument);
    Runnable task =
        () -> {
          try {
            CodeStyleManager.getInstance(myProject)
                .reformatRange(origPsiFile, hostStartOffset, myAltFullRange.getEndOffset(), true);
          } catch (IncorrectOperationException e1) {
            // LOG.error(e);
          }
        };
    DocumentUtil.executeInBulk(myOrigDocument, true, task);

    PsiElement newInjected =
        InjectedLanguageManager.getInstance(myProject)
            .findInjectedElementAt(origPsiFile, hostStartOffset);
    DocumentWindow documentWindow =
        newInjected == null ? null : InjectedLanguageUtil.getDocumentWindow(newInjected);
    if (documentWindow != null) {
      myEditor.getCaretModel().moveToOffset(documentWindow.injectedToHost(e.getOffset()));
      myEditor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE);
    }
  }
 public void nextPanel(final BeforeAfter<ShiftedSimpleContent> diff, final DiffPanel diffPanel) {
   final Editor editor1 = ((DiffPanelImpl) diffPanel).getEditor1();
   myLeftModels.add(editor1.getScrollingModel());
   final Editor editor2 = ((DiffPanelImpl) diffPanel).getEditor2();
   myRightModels.add(editor2.getScrollingModel());
   if (myEditor == null) {
     myEditor = editor1;
   }
   myLeftEditors.add(editor1);
   myRightEditors.add(editor2);
   ((EditorEx) editor1).setHorizontalScrollbarVisible(false);
   ((EditorEx) editor1).setVerticalScrollbarVisible(false);
   ((EditorEx) editor1).getScrollPane().setWheelScrollingEnabled(false);
   ((EditorEx) editor2).setHorizontalScrollbarVisible(false);
   ((EditorEx) editor2).setVerticalScrollbarVisible(false);
   ((EditorEx) editor2).getScrollPane().setWheelScrollingEnabled(false);
 }
 public void invoke(
     @NotNull Project project, Editor editor, PsiFile file, DataContext dataContext) {
   editor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE);
   PsiElement element = findTargetMember(file, editor);
   if (element == null) {
     element = LangDataKeys.PSI_ELEMENT.getData(dataContext);
   }
   invokeOnElement(project, editor, element);
 }
Esempio n. 18
0
  static void selectReturnValueInEditor(
      final PsiReturnStatement returnStatement, final Editor editor) {
    TextRange range = returnStatement.getReturnValue().getTextRange();
    int offset = range.getStartOffset();

    editor.getCaretModel().moveToOffset(offset);
    editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
    editor.getSelectionModel().setSelection(range.getEndOffset(), range.getStartOffset());
  }
  private void moveToParameterAtOffset(int offset) {
    PsiFile file = PsiDocumentManager.getInstance(myProject).getPsiFile(myEditor.getDocument());
    PsiElement argsList = findArgumentList(file, offset, -1);
    if (argsList == null) return;

    myEditor.getCaretModel().moveToOffset(offset);
    myEditor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
    myEditor.getSelectionModel().removeSelection();
    myHandler.updateParameterInfo(argsList, new MyUpdateParameterInfoContext(offset, file));
  }
  @Override
  public void commandStarted(CommandEvent event) {
    for (Editor editor : EditorFactory.getInstance().getAllEditors()) {
      if (editor.getComponent().isShowing()) {
        myEditorsVisibleOnCommandStart.add(editor);
      }

      ((ScrollingModelImpl) editor.getScrollingModel()).finishAnimation();
      myCurrentCommandStart = System.currentTimeMillis();
    }
  }
    private CaretVisualPositionKeeper(@Nullable Document document) {
      if (document == null) return;

      Editor[] editors = EditorFactory.getInstance().getEditors(document);
      for (Editor editor : editors) {
        Rectangle visibleArea = editor.getScrollingModel().getVisibleArea();
        Point pos = editor.visualPositionToXY(editor.getCaretModel().getVisualPosition());
        int relativePosition = pos.y - visibleArea.y;
        myCaretRelativeVerticalPositions.put(editor, relativePosition);
      }
    }
Esempio n. 22
0
    public void uninstall() {
      for (RangeHighlighter highlighter : myHighlighters) {
        highlighter.dispose();
      }

      Component internalComponent = myHighlighterView.getContentComponent();
      internalComponent.setCursor(myStoredCursor);
      internalComponent.removeKeyListener(myEditorKeyListener);
      myHighlighterView.getScrollingModel().removeVisibleAreaListener(myVisibleAreaListener);
      myFileEditorManager.removeFileEditorManagerListener(myFileEditorManagerListener);
    }
  private static boolean isDeclarationVisible(PsiElement container, Editor editor) {
    Rectangle viewRect = editor.getScrollingModel().getVisibleArea();
    final TextRange range = DeclarationRangeUtil.getPossibleDeclarationAtRange(container);
    if (range == null) {
      return false;
    }

    LogicalPosition pos = editor.offsetToLogicalPosition(range.getStartOffset());
    Point loc = editor.logicalPositionToXY(pos);
    return loc.y >= viewRect.y;
  }
 @NotNull
 @Override
 public RelativePoint guessBestPopupLocation(@NotNull Editor editor) {
   Point p = getVisibleBestPopupLocation(editor);
   if (p == null) {
     final Rectangle visibleArea = editor.getScrollingModel().getVisibleArea();
     p =
         new Point(
             (visibleArea.x + visibleArea.width) / 2, (visibleArea.y + visibleArea.height) / 2);
   }
   return new RelativePoint(editor.getContentComponent(), p);
 }
 private static void highlightInEditor(
     final Project project, final IncludeDuplicate pair, final Editor editor) {
   final HighlightManager highlightManager = HighlightManager.getInstance(project);
   EditorColorsManager colorsManager = EditorColorsManager.getInstance();
   TextAttributes attributes =
       colorsManager.getGlobalScheme().getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES);
   final int startOffset = pair.getStart().getTextRange().getStartOffset();
   final int endOffset = pair.getEnd().getTextRange().getEndOffset();
   highlightManager.addRangeHighlight(editor, startOffset, endOffset, attributes, true, null);
   final LogicalPosition logicalPosition = editor.offsetToLogicalPosition(startOffset);
   editor.getScrollingModel().scrollTo(logicalPosition, ScrollType.MAKE_VISIBLE);
 }
  public static void run(
      @NotNull final Project project,
      @NotNull final Editor editor,
      @NotNull final ExtractMethodObjectProcessor processor,
      @NotNull final ExtractMethodObjectProcessor.MyExtractMethodProcessor extractProcessor) {
    final int offset = editor.getCaretModel().getOffset();
    final RangeMarker marker =
        editor.getDocument().createRangeMarker(new TextRange(offset, offset));
    CommandProcessor.getInstance()
        .executeCommand(
            project,
            new Runnable() {
              public void run() {
                ApplicationManager.getApplication()
                    .runWriteAction(
                        new Runnable() {
                          @Override
                          public void run() {
                            extractProcessor.doRefactoring();
                          }
                        });

                processor.run();
                processor.runChangeSignature();
                PsiDocumentManager.getInstance(project).commitAllDocuments();
                if (processor.isCreateInnerClass()) {
                  processor.moveUsedMethodsToInner();
                  PsiDocumentManager.getInstance(project).commitAllDocuments();
                  DuplicatesImpl.processDuplicates(extractProcessor, project, editor);
                }
                ApplicationManager.getApplication()
                    .runWriteAction(
                        new Runnable() {
                          @Override
                          public void run() {
                            if (processor.isCreateInnerClass()) {
                              processor.changeInstanceAccess(project);
                            }
                            final PsiElement method = processor.getMethod();
                            LOG.assertTrue(method != null);
                            method.delete();
                          }
                        });
              }
            },
            ExtractMethodObjectProcessor.REFACTORING_NAME,
            ExtractMethodObjectProcessor.REFACTORING_NAME);
    editor.getCaretModel().moveToOffset(marker.getStartOffset());
    marker.dispose();
    editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
  }
Esempio n. 27
0
  private void paintVisibleWindow(Graphics2D g) {
    Rectangle visibleArea = editor.getScrollingModel().getVisibleArea();
    int firstVisibleLine = getMapYFromEditorY((int) visibleArea.getMinY());
    int height =
        coords.linesToPixels(
            (int) ((visibleArea.getMaxY() - visibleArea.getMinY()) / editor.getLineHeight()));

    // Draw the current viewport
    g.setColor(viewportColor);
    g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.50f));
    g.drawRect(0, firstVisibleLine, getWidth(), height);
    g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.20f));
    g.fillRect(0, firstVisibleLine, getWidth(), height);
  }
  @Override
  public void addOccurrenceHighlights(
      @NotNull Editor editor,
      @NotNull PsiReference[] occurrences,
      @NotNull TextAttributes attributes,
      boolean hideByTextChange,
      Collection<RangeHighlighter> outHighlighters) {
    if (occurrences.length == 0) return;
    int flags = HIDE_BY_ESCAPE;
    if (hideByTextChange) {
      flags |= HIDE_BY_TEXT_CHANGE;
    }
    Color scrollmarkColor = getScrollMarkColor(attributes);

    int oldOffset = editor.getCaretModel().getOffset();
    int horizontalScrollOffset = editor.getScrollingModel().getHorizontalScrollOffset();
    int verticalScrollOffset = editor.getScrollingModel().getVerticalScrollOffset();
    for (PsiReference occurrence : occurrences) {
      PsiElement element = occurrence.getElement();
      int startOffset = element.getTextRange().getStartOffset();
      int start = startOffset + occurrence.getRangeInElement().getStartOffset();
      int end = startOffset + occurrence.getRangeInElement().getEndOffset();
      PsiFile containingFile = element.getContainingFile();
      Project project = element.getProject();
      // each reference can reside in its own injected editor
      Editor textEditor = InjectedLanguageUtil.openEditorFor(containingFile, project);
      if (textEditor != null) {
        addOccurrenceHighlight(
            textEditor, start, end, attributes, flags, outHighlighters, scrollmarkColor);
      }
    }
    editor.getCaretModel().moveToOffset(oldOffset);
    editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
    editor.getScrollingModel().scrollHorizontally(horizontalScrollOffset);
    editor.getScrollingModel().scrollVertically(verticalScrollOffset);
  }
Esempio n. 29
0
  public void onClose() {
    container.removeComponentListener(componentListener);
    editor.getDocument().removeDocumentListener(documentListener);
    configService.remove(configChangeListener);
    editor.getScrollingModel().removeVisibleAreaListener(this);
    editor.getSelectionModel().removeSelectionListener(selectionListener);
    removeMouseWheelListener(mouseWheelListener);
    removeMouseListener(mouseListener);
    removeMouseMotionListener(mouseListener);

    componentListener = null;
    documentListener = null;
    configChangeListener = null;
    mouseListener = null;
  }
Esempio n. 30
0
  @Override
  public void paint(Graphics gfx) {
    Graphics2D g = (Graphics2D) gfx;
    g.setColor(editor.getColorsScheme().getDefaultBackground());
    g.fillRect(0, 0, getWidth(), getHeight());

    logger.debug(String.format("Rendering to buffer: %d", activeBuffer));
    if (activeBuffer >= 0) {
      paintSelection(g);

      Minimap minimap = minimaps[activeBuffer];

      Rectangle visibleArea = editor.getScrollingModel().getVisibleArea();

      double documentEndY =
          editor
              .logicalPositionToXY(
                  editor.offsetToLogicalPosition(editor.getDocument().getTextLength() - 1))
              .getY();

      coords
          .setMinimap(minimap)
          .setPanelHeight(getHeight())
          .setPanelWidth(getWidth())
          .setPercentageComplete(
              visibleArea.getMinY()
                  / (documentEndY - (visibleArea.getMaxY() - visibleArea.getMinY())))
          .setHidpiScale(getHidpiScale());

      Rectangle src = coords.getImageSource();
      Rectangle dest = coords.getImageDestination();

      // Draw the image and scale it to stretch vertically.
      g.drawImage(
          minimap.img, // source image
          dest.x,
          dest.y,
          dest.width,
          dest.height,
          src.x,
          src.y,
          src.width,
          src.height,
          null);

      paintVisibleWindow(g);
    }
  }