protected Editor createIdeaEditor(String text) {
   Document doc = EditorFactory.getInstance().createDocument(text);
   Editor editor = EditorFactory.getInstance().createViewer(doc, myProject);
   editor.getSettings().setFoldingOutlineShown(false);
   editor.getSettings().setLineNumbersShown(false);
   editor.getSettings().setLineMarkerAreaShown(false);
   editor.getSettings().setIndentGuidesShown(false);
   return editor;
 }
  /**
   * Configures given editor to wrap at given width, assuming characters are of given width
   *
   * @return whether any actual wraps of editor contents were created as a result of turning on soft
   *     wraps
   */
  @TestOnly
  public static boolean configureSoftWraps(
      Editor editor, final int visibleWidth, final int charWidthInPixels) {
    editor.getSettings().setUseSoftWraps(true);
    SoftWrapModelImpl model = (SoftWrapModelImpl) editor.getSoftWrapModel();
    model.setSoftWrapPainter(
        new SoftWrapPainter() {
          @Override
          public int paint(
              @NotNull Graphics g,
              @NotNull SoftWrapDrawingType drawingType,
              int x,
              int y,
              int lineHeight) {
            return charWidthInPixels;
          }

          @Override
          public int getDrawingHorizontalOffset(
              @NotNull Graphics g,
              @NotNull SoftWrapDrawingType drawingType,
              int x,
              int y,
              int lineHeight) {
            return charWidthInPixels;
          }

          @Override
          public int getMinDrawingWidth(@NotNull SoftWrapDrawingType drawingType) {
            return charWidthInPixels;
          }

          @Override
          public boolean canUse() {
            return true;
          }

          @Override
          public void reinit() {}
        });
    model.reinitSettings();

    SoftWrapApplianceManager applianceManager = model.getApplianceManager();
    applianceManager.setWidthProvider(
        new SoftWrapApplianceManager.VisibleAreaWidthProvider() {
          @Override
          public int getVisibleAreaWidth() {
            return visibleWidth;
          }
        });
    model.setEditorTextRepresentationHelper(
        new DefaultEditorTextRepresentationHelper(editor) {
          @Override
          public int charWidth(char c, int fontType) {
            return charWidthInPixels;
          }
        });
    applianceManager.registerSoftWrapIfNecessary();
    return !model.getRegisteredSoftWraps().isEmpty();
  }
  private Content getOrCreateConsoleContent(final ContentManager contentManager) {
    final String displayName = VcsBundle.message("vcs.console.toolwindow.display.name");
    Content content = contentManager.findContent(displayName);
    if (content == null) {
      releaseEditor();
      final EditorFactory editorFactory = EditorFactory.getInstance();
      final Editor editor = editorFactory.createViewer(editorFactory.createDocument(""), myProject);
      EditorSettings editorSettings = editor.getSettings();
      editorSettings.setLineMarkerAreaShown(false);
      editorSettings.setIndentGuidesShown(false);
      editorSettings.setLineNumbersShown(false);
      editorSettings.setFoldingOutlineShown(false);

      ((EditorEx) editor).getScrollPane().setBorder(null);
      myEditorAdapter = new EditorAdapter(editor, myProject, false);
      final JPanel panel = new JPanel(new BorderLayout());
      panel.add(editor.getComponent(), BorderLayout.CENTER);

      content = ContentFactory.SERVICE.getInstance().createContent(panel, displayName, true);
      contentManager.addContent(content);

      for (Pair<String, TextAttributes> pair : myPendingOutput) {
        myEditorAdapter.appendString(pair.first, pair.second);
      }
      myPendingOutput.clear();
    }
    return content;
  }
  @Override
  protected boolean isAvailable(PsiElement element, Editor editor, PsiFile file) {

    return editor.getSettings().isVariableInplaceRenameEnabled()
        && element instanceof PsiNameIdentifierOwner
        && element.getUseScope() instanceof LocalSearchScope
        && element.getLanguage() == PerlLanguage.INSTANCE
        && ((PsiNameIdentifierOwner) element).getNameIdentifier() instanceof PerlString
        && element.getContainingFile().getViewProvider().getAllFiles().size() < 2;
  }
 @Override
 public List<TextRange> select(
     PsiElement e, CharSequence editorText, int cursorOffset, Editor editor) {
   List<TextRange> ranges;
   if (canSelect(e)) {
     ranges = super.select(e, editorText, cursorOffset, editor);
   } else {
     ranges = ContainerUtil.newArrayList();
   }
   SelectWordUtil.addWordOrLexemeSelection(
       editor.getSettings().isCamelWords(), editor, cursorOffset, ranges);
   return ranges;
 }
  @NotNull
  private static Editor createView(Project project) {
    EditorFactory editorFactory = EditorFactory.getInstance();
    Document document = editorFactory.createDocument("");
    Editor result = editorFactory.createViewer(document, project);

    EditorSettings editorSettings = result.getSettings();
    editorSettings.setLineMarkerAreaShown(false);
    editorSettings.setLineNumbersShown(false);
    editorSettings.setIndentGuidesShown(false);
    editorSettings.setFoldingOutlineShown(false);
    return result;
  }
 @Override
 protected boolean isAvailable(PsiElement element, Editor editor, PsiFile file) {
   final PsiElement nameSuggestionContext = file.findElementAt(editor.getCaretModel().getOffset());
   if (element == null && LookupManager.getActiveLookup(editor) != null) {
     element = PsiTreeUtil.getParentOfType(nameSuggestionContext, PsiNamedElement.class);
   }
   final RefactoringSupportProvider supportProvider =
       element != null
           ? LanguageRefactoringSupport.INSTANCE.forLanguage(element.getLanguage())
           : null;
   return editor.getSettings().isVariableInplaceRenameEnabled()
       && supportProvider != null
       && supportProvider.isMemberInplaceRenameAvailable(element, nameSuggestionContext);
 }
Ejemplo n.º 8
0
  public static Editor createEditor(boolean isReadOnly, final CharSequence text) {
    EditorFactory editorFactory = EditorFactory.getInstance();
    Document doc = editorFactory.createDocument(text);
    Editor editor =
        (isReadOnly ? editorFactory.createViewer(doc) : editorFactory.createEditor(doc));

    EditorSettings editorSettings = editor.getSettings();
    editorSettings.setVirtualSpace(false);
    editorSettings.setLineMarkerAreaShown(false);
    editorSettings.setIndentGuidesShown(false);
    editorSettings.setLineNumbersShown(false);
    editorSettings.setFoldingOutlineShown(false);

    EditorColorsScheme scheme = editor.getColorsScheme();
    scheme.setColor(EditorColors.CARET_ROW_COLOR, null);

    return editor;
  }
 protected void performActionOnElementOccurrences(final IntroduceOperation operation) {
   final Editor editor = operation.getEditor();
   if (editor.getSettings().isVariableInplaceRenameEnabled()) {
     ensureName(operation);
     if (operation.isReplaceAll() != null) {
       performInplaceIntroduce(operation);
     } else {
       OccurrencesChooser.simpleChooser(editor)
           .showChooser(
               operation.getElement(),
               operation.getOccurrences(),
               new Pass<OccurrencesChooser.ReplaceChoice>() {
                 @Override
                 public void pass(OccurrencesChooser.ReplaceChoice replaceChoice) {
                   operation.setReplaceAll(replaceChoice == OccurrencesChooser.ReplaceChoice.ALL);
                   performInplaceIntroduce(operation);
                 }
               });
     }
   } else {
     performIntroduceWithDialog(operation);
   }
 }
  private Editor createEditor() {
    EditorFactory editorFactory = EditorFactory.getInstance();
    Document doc =
        myFile == null
            ? editorFactory.createDocument(myTemplate == null ? "" : myTemplate.getText())
            : PsiDocumentManager.getInstance(myFile.getProject()).getDocument(myFile);
    Editor editor =
        myProject == null
            ? editorFactory.createEditor(doc)
            : editorFactory.createEditor(doc, myProject);

    EditorSettings editorSettings = editor.getSettings();
    editorSettings.setVirtualSpace(false);
    editorSettings.setLineMarkerAreaShown(false);
    editorSettings.setIndentGuidesShown(false);
    editorSettings.setLineNumbersShown(false);
    editorSettings.setFoldingOutlineShown(false);
    editorSettings.setAdditionalColumnsCount(3);
    editorSettings.setAdditionalLinesCount(3);

    EditorColorsScheme scheme = editor.getColorsScheme();
    scheme.setColor(EditorColors.CARET_ROW_COLOR, null);

    editor
        .getDocument()
        .addDocumentListener(
            new DocumentAdapter() {
              @Override
              public void documentChanged(DocumentEvent e) {
                onTextChanged();
              }
            });

    ((EditorEx) editor).setHighlighter(createHighlighter());
    mySplitter.setFirstComponent(editor.getComponent());
    return editor;
  }
  public ImplementationViewComponent(PsiElement[] elements, final int index) {
    super(new BorderLayout());

    final Project project = elements.length > 0 ? elements[0].getProject() : null;
    EditorFactory factory = EditorFactory.getInstance();
    Document doc = factory.createDocument("");
    doc.setReadOnly(true);
    myEditor = factory.createEditor(doc, project);
    ((EditorEx) myEditor).setBackgroundColor(EditorFragmentComponent.getBackgroundColor(myEditor));

    final EditorSettings settings = myEditor.getSettings();
    settings.setAdditionalLinesCount(1);
    settings.setAdditionalColumnsCount(1);
    settings.setLineMarkerAreaShown(false);
    settings.setIndentGuidesShown(false);
    settings.setLineNumbersShown(false);
    settings.setFoldingOutlineShown(false);

    myBinarySwitch = new CardLayout();
    myViewingPanel = new JPanel(myBinarySwitch);
    myEditor.setBorder(null);
    ((EditorEx) myEditor).getScrollPane().setViewportBorder(JBScrollPane.createIndentBorder());
    myViewingPanel.add(myEditor.getComponent(), TEXT_PAGE_KEY);

    myBinaryPanel = new JPanel(new BorderLayout());
    myViewingPanel.add(myBinaryPanel, BINARY_PAGE_KEY);

    add(myViewingPanel, BorderLayout.CENTER);

    myToolbar = createToolbar();
    myLocationLabel = new JLabel();
    myCountLabel = new JLabel();

    final JPanel header = new JPanel(new BorderLayout(2, 0));
    header.setBorder(
        BorderFactory.createCompoundBorder(
            IdeBorderFactory.createBorder(SideBorder.BOTTOM),
            IdeBorderFactory.createEmptyBorder(0, 0, 0, 5)));
    final JPanel toolbarPanel = new JPanel(new GridBagLayout());
    final GridBagConstraints gc =
        new GridBagConstraints(
            GridBagConstraints.RELATIVE,
            0,
            1,
            1,
            0,
            0,
            GridBagConstraints.WEST,
            GridBagConstraints.NONE,
            new Insets(0, 2, 0, 0),
            0,
            0);
    toolbarPanel.add(myToolbar.getComponent(), gc);

    setPreferredSize(new Dimension(600, 400));

    update(
        elements,
        new PairFunction<PsiElement[], List<FileDescriptor>, Boolean>() {
          @Override
          public Boolean fun(
              final PsiElement[] psiElements, final List<FileDescriptor> fileDescriptors) {
            if (psiElements.length == 0) return false;
            myElements = psiElements;

            myIndex = index < myElements.length ? index : 0;
            PsiFile psiFile = getContainingFile(myElements[myIndex]);

            VirtualFile virtualFile = psiFile.getVirtualFile();
            EditorHighlighter highlighter;
            if (virtualFile != null)
              highlighter = HighlighterFactory.createHighlighter(project, virtualFile);
            else {
              String fileName = psiFile.getName(); // some artificial psi file, lets do best we can
              highlighter = HighlighterFactory.createHighlighter(project, fileName);
            }

            ((EditorEx) myEditor).setHighlighter(highlighter);

            gc.fill = GridBagConstraints.HORIZONTAL;
            gc.weightx = 1;
            if (myElements.length > 1) {
              myFileChooser =
                  new ComboBox(
                      fileDescriptors.toArray(new FileDescriptor[fileDescriptors.size()]), 250);
              updateRenderer(project);

              myFileChooser.addActionListener(
                  new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                      int index = myFileChooser.getSelectedIndex();
                      if (myIndex != index) {
                        myIndex = index;
                        updateControls();
                      }
                    }
                  });

              myLabel = new JLabel();
              myLabel.setVisible(false);
              toolbarPanel.add(myFileChooser, gc);
            } else {
              myFileChooser = new ComboBox();
              myFileChooser.setVisible(false);
              myCountLabel.setVisible(false);

              myLabel = new JLabel();
              VirtualFile file = psiFile.getVirtualFile();
              if (file != null) {
                myLabel.setIcon(getIconForFile(psiFile));
                myLabel.setForeground(
                    FileStatusManager.getInstance(project).getStatus(file).getColor());
                myLabel.setText(file.getPresentableName());
                myLabel.setBorder(
                    new CompoundBorder(
                        IdeBorderFactory.createRoundedBorder(),
                        IdeBorderFactory.createEmptyBorder(0, 0, 0, 5)));
              }
              toolbarPanel.add(myLabel, gc);
            }

            gc.fill = GridBagConstraints.NONE;
            gc.weightx = 0;
            toolbarPanel.add(myCountLabel, gc);

            header.add(toolbarPanel, BorderLayout.CENTER);
            header.add(myLocationLabel, BorderLayout.EAST);

            add(header, BorderLayout.NORTH);

            updateControls();
            return true;
          }
        });
  }
  protected Settings showRefactoringDialog(
      Project project,
      final Editor editor,
      PsiClass parentClass,
      PsiExpression expr,
      PsiType type,
      PsiExpression[] occurrences,
      PsiElement anchorElement,
      PsiElement anchorElementIfAll) {
    final PsiMethod containingMethod =
        PsiTreeUtil.getParentOfType(expr != null ? expr : anchorElement, PsiMethod.class);

    PsiLocalVariable localVariable = null;
    if (expr instanceof PsiReferenceExpression) {
      PsiElement ref = ((PsiReferenceExpression) expr).resolve();
      if (ref instanceof PsiLocalVariable) {
        localVariable = (PsiLocalVariable) ref;
      }
    } else if (anchorElement instanceof PsiLocalVariable) {
      localVariable = (PsiLocalVariable) anchorElement;
    }

    String enteredName = null;
    boolean replaceAllOccurrences = true;

    final AbstractInplaceIntroducer activeIntroducer =
        AbstractInplaceIntroducer.getActiveIntroducer(editor);
    if (activeIntroducer != null) {
      activeIntroducer.stopIntroduce(editor);
      expr = (PsiExpression) activeIntroducer.getExpr();
      localVariable = (PsiLocalVariable) activeIntroducer.getLocalVariable();
      occurrences = (PsiExpression[]) activeIntroducer.getOccurrences();
      enteredName = activeIntroducer.getInputName();
      replaceAllOccurrences = activeIntroducer.isReplaceAllOccurrences();
      type = ((InplaceIntroduceConstantPopup) activeIntroducer).getType();
    }

    for (PsiExpression occurrence : occurrences) {
      if (RefactoringUtil.isAssignmentLHS(occurrence)) {
        String message =
            RefactoringBundle.getCannotRefactorMessage("Selected expression is used for write");
        CommonRefactoringUtil.showErrorHint(
            project, editor, message, REFACTORING_NAME, getHelpID());
        highlightError(project, editor, occurrence);
        return null;
      }
    }

    if (localVariable == null) {
      final PsiElement errorElement = isStaticFinalInitializer(expr);
      if (errorElement != null) {
        String message =
            RefactoringBundle.getCannotRefactorMessage(
                RefactoringBundle.message("selected.expression.cannot.be.a.constant.initializer"));
        CommonRefactoringUtil.showErrorHint(
            project, editor, message, REFACTORING_NAME, getHelpID());
        highlightError(project, editor, errorElement);
        return null;
      }
    } else {
      final PsiExpression initializer = localVariable.getInitializer();
      if (initializer == null) {
        String message =
            RefactoringBundle.getCannotRefactorMessage(
                RefactoringBundle.message(
                    "variable.does.not.have.an.initializer", localVariable.getName()));
        CommonRefactoringUtil.showErrorHint(
            project, editor, message, REFACTORING_NAME, getHelpID());
        return null;
      }
      final PsiElement errorElement = isStaticFinalInitializer(initializer);
      if (errorElement != null) {
        String message =
            RefactoringBundle.getCannotRefactorMessage(
                RefactoringBundle.message(
                    "initializer.for.variable.cannot.be.a.constant.initializer",
                    localVariable.getName()));
        CommonRefactoringUtil.showErrorHint(
            project, editor, message, REFACTORING_NAME, getHelpID());
        highlightError(project, editor, errorElement);
        return null;
      }
    }

    final TypeSelectorManagerImpl typeSelectorManager =
        new TypeSelectorManagerImpl(project, type, containingMethod, expr, occurrences);
    if (editor != null
        && editor.getSettings().isVariableInplaceRenameEnabled()
        && (expr == null || expr.isPhysical())
        && activeIntroducer == null) {
      myInplaceIntroduceConstantPopup =
          new InplaceIntroduceConstantPopup(
              project,
              editor,
              parentClass,
              expr,
              localVariable,
              occurrences,
              typeSelectorManager,
              anchorElement,
              anchorElementIfAll,
              expr != null ? createOccurrenceManager(expr, parentClass) : null);
      if (myInplaceIntroduceConstantPopup.startInplaceIntroduceTemplate()) {
        return null;
      }
    }

    final IntroduceConstantDialog dialog =
        new IntroduceConstantDialog(
            project,
            parentClass,
            expr,
            localVariable,
            localVariable != null,
            occurrences,
            getParentClass(),
            typeSelectorManager,
            enteredName);
    dialog.setReplaceAllOccurrences(replaceAllOccurrences);
    if (!dialog.showAndGet()) {
      if (occurrences.length > 1) {
        WindowManager.getInstance()
            .getStatusBar(project)
            .setInfo(RefactoringBundle.message("press.escape.to.remove.the.highlighting"));
      }
      return null;
    }
    return new Settings(
        dialog.getEnteredName(),
        expr,
        occurrences,
        dialog.isReplaceAllOccurrences(),
        true,
        true,
        InitializationPlace.IN_FIELD_DECLARATION,
        dialog.getFieldVisibility(),
        localVariable,
        dialog.getSelectedType(),
        dialog.isDeleteVariable(),
        dialog.getDestinationClass(),
        dialog.isAnnotateAsNonNls(),
        dialog.introduceEnumConstant());
  }
  public void performAction(IntroduceOperation operation) {
    final PsiFile file = operation.getFile();
    if (!CommonRefactoringUtil.checkReadOnlyStatus(file)) {
      return;
    }
    final Editor editor = operation.getEditor();
    if (editor.getSettings().isVariableInplaceRenameEnabled()) {
      final TemplateState templateState =
          TemplateManagerImpl.getTemplateState(operation.getEditor());
      if (templateState != null && !templateState.isFinished()) {
        return;
      }
    }

    PsiElement element1 = null;
    PsiElement element2 = null;
    final SelectionModel selectionModel = editor.getSelectionModel();
    boolean singleElementSelection = false;
    if (selectionModel.hasSelection()) {
      element1 = file.findElementAt(selectionModel.getSelectionStart());
      element2 = file.findElementAt(selectionModel.getSelectionEnd() - 1);
      if (element1 instanceof PsiWhiteSpace) {
        int startOffset = element1.getTextRange().getEndOffset();
        element1 = file.findElementAt(startOffset);
      }
      if (element2 instanceof PsiWhiteSpace) {
        int endOffset = element2.getTextRange().getStartOffset();
        element2 = file.findElementAt(endOffset - 1);
      }
      if (element1 == element2) {
        singleElementSelection = true;
      }
    } else {
      if (smartIntroduce(operation)) {
        return;
      }
      final CaretModel caretModel = editor.getCaretModel();
      final Document document = editor.getDocument();
      int lineNumber = document.getLineNumber(caretModel.getOffset());
      if ((lineNumber >= 0) && (lineNumber < document.getLineCount())) {
        element1 = file.findElementAt(document.getLineStartOffset(lineNumber));
        element2 = file.findElementAt(document.getLineEndOffset(lineNumber) - 1);
      }
    }
    final Project project = operation.getProject();
    if (element1 == null || element2 == null) {
      showCannotPerformError(project, editor);
      return;
    }

    element1 = PyRefactoringUtil.getSelectedExpression(project, file, element1, element2);
    if (element1 == null) {
      showCannotPerformError(project, editor);
      return;
    }

    if (singleElementSelection && element1 instanceof PyStringLiteralExpression) {
      final PyStringLiteralExpression literal = (PyStringLiteralExpression) element1;
      // Currently introduce for substrings of a multi-part string literals is not supported
      if (literal.getStringNodes().size() > 1) {
        showCannotPerformError(project, editor);
        return;
      }
      final int offset = element1.getTextOffset();
      final TextRange selectionRange =
          TextRange.create(selectionModel.getSelectionStart(), selectionModel.getSelectionEnd());
      final TextRange elementRange = element1.getTextRange();
      if (!elementRange.equals(selectionRange) && elementRange.contains(selectionRange)) {
        final TextRange innerRange = literal.getStringValueTextRange();
        final TextRange intersection = selectionRange.shiftRight(-offset).intersection(innerRange);
        final TextRange finalRange = intersection != null ? intersection : selectionRange;
        final String text = literal.getText();
        if (getFormatValueExpression(literal) != null && breaksStringFormatting(text, finalRange)
            || getNewStyleFormatValueExpression(literal) != null
                && breaksNewStyleStringFormatting(text, finalRange)
            || breaksStringEscaping(text, finalRange)) {
          showCannotPerformError(project, editor);
          return;
        }
        element1.putUserData(
            PyReplaceExpressionUtil.SELECTION_BREAKS_AST_NODE, Pair.create(element1, finalRange));
      }
    }

    if (!checkIntroduceContext(file, editor, element1)) {
      return;
    }
    operation.setElement(element1);
    performActionOnElement(operation);
  }