Пример #1
0
 /**
  * We know that there are problems with incremental soft wraps cache update at the moment. Hence,
  * we may implement full cache reconstruction when the problem is encountered in order to avoid
  * customer annoyance.
  *
  * <p>However, the problems still should be fixed, hence, we report them only if dedicated flag is
  * set.
  *
  * <p>Current method encapsulates the logic mentioned above.
  *
  * @param task command object that which execution may trigger incremental update of update soft
  *     wraps cache
  */
 @SuppressWarnings({"UseOfArchaicSystemPropertyAccessors"})
 private void executeSafely(SoftWrapAwareTask task) {
   try {
     task.run(true);
   } catch (Throwable e) {
     if (Boolean.getBoolean(DEBUG_PROPERTY_NAME)) {
       LOG.error(
           String.format(
               "Unexpected exception occurred during performing '%s'. Current soft wraps cache: %n"
                   + "%s%nFold regions: %s",
               task, myDataMapper, Arrays.toString(myEditor.getFoldingModel().fetchTopLevel())),
           e);
     }
     myEditor.getFoldingModel().rebuild();
     myDataMapper.release();
     myApplianceManager.reset();
     myStorage.removeAll();
     try {
       task.run(true);
     } catch (Throwable e1) {
       LOG.error(
           String.format(
               "Can't perform %s even with complete soft wraps cache re-parsing. Current soft wraps cache: %n"
                   + "%s. Document:%n%s%nFold regions: %s",
               task,
               myDataMapper,
               myEditor.getDocument().getText(),
               Arrays.toString(myEditor.getFoldingModel().fetchTopLevel())),
           e1);
       myEditor.getSettings().setUseSoftWraps(false);
       task.run(false);
     }
   }
 }
  public List<HighlightInfo> getHighlights() {
    clearLineMarkers(myEditor);

    final int count = myPairsToHighlight.size();
    final List<HighlightInfo> highlightInfos = new ArrayList<HighlightInfo>(count * 2);
    final MarkupModel markupModel = myEditor.getMarkupModel();

    final Color[] baseColors = XmlTagTreeHighlightingUtil.getBaseColors();
    final Color[] colorsForEditor =
        count > 1
            ? toColorsForEditor(baseColors)
            : new Color[] {
              myEditor
                  .getColorsScheme()
                  .getAttributes(CodeInsightColors.MATCHED_BRACE_ATTRIBUTES)
                  .getBackgroundColor()
            };
    final Color[] colorsForLineMarkers = toColorsForLineMarkers(baseColors);

    final List<RangeHighlighter> newHighlighters = new ArrayList<RangeHighlighter>();

    assert colorsForEditor.length > 0;

    for (int i = 0; i < count && i < baseColors.length; i++) {
      Pair<TextRange, TextRange> pair = myPairsToHighlight.get(i);

      if (pair.first == null && pair.second == null) {
        continue;
      }

      Color color = colorsForEditor[i];

      if (color == null) {
        continue;
      }

      if (pair.first != null && !pair.first.isEmpty()) {
        highlightInfos.add(createHighlightInfo(color, pair.first));
      }

      if (pair.second != null && !pair.second.isEmpty()) {
        highlightInfos.add(createHighlightInfo(color, pair.second));
      }

      final int start =
          pair.first != null ? pair.first.getStartOffset() : pair.second.getStartOffset();
      final int end = pair.second != null ? pair.second.getEndOffset() : pair.first.getEndOffset();

      final Color lineMarkerColor = colorsForLineMarkers[i];
      if (count > 1 && lineMarkerColor != null && start != end) {
        final RangeHighlighter highlighter =
            createHighlighter(markupModel, new TextRange(start, end), lineMarkerColor);
        newHighlighters.add(highlighter);
      }
    }

    myEditor.putUserData(TAG_TREE_HIGHLIGHTERS_IN_EDITOR_KEY, newHighlighters);

    return highlightInfos;
  }
 private void scrollHistoryToEnd() {
   final int lineCount = myHistoryViewer.getDocument().getLineCount();
   if (lineCount == 0) return;
   myHistoryViewer
       .getCaretModel()
       .moveToOffset(myHistoryViewer.getDocument().getLineStartOffset(lineCount - 1), false);
   myHistoryViewer.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE);
 }
 @NotNull
 protected Runnable loadEditorInBackground() {
   EditorColorsScheme scheme = EditorColorsManager.getInstance().getGlobalScheme();
   EditorHighlighter highlighter =
       EditorHighlighterFactory.getInstance().createEditorHighlighter(myFile, scheme, myProject);
   EditorEx editor = (EditorEx) getEditor();
   highlighter.setText(editor.getDocument().getImmutableCharSequence());
   return () -> editor.setHighlighter(highlighter);
 }
 protected final void setPreviewText(final String text) {
   if (myPreview == null) return; // already disposed
   ApplicationManager.getApplication()
       .runWriteAction(
           () ->
               myPreview
                   .getDocument()
                   .replaceString(0, myPreview.getDocument().getTextLength(), text));
 }
 public void update(final AnActionEvent e) {
   final EditorEx editor = myLanguageConsole.getConsoleEditor();
   final Lookup lookup = LookupManager.getActiveLookup(editor);
   e.getPresentation()
       .setEnabled(
           !editor.isRendererMode()
               && !myProcessHandler.isProcessTerminated()
               && (lookup == null || !(lookup.isCompletion() && lookup.isFocused())));
 }
 /**
  * Enables/disables left border {@link #BORDER_SIZE_PX} width for certain editors.
  *
  * @param editors editors to enable/disable border
  * @param enable whether border should be enabled
  */
 private static void configureLeftBorder(
     final boolean enable, @NotNull final EditorEx... editors) {
   for (final EditorEx editor : editors) {
     final Color backgroundColor =
         editor.getBackgroundColor(); // Border have the same color console background has
     final int thickness = enable ? BORDER_SIZE_PX : 0;
     final Border border = BorderFactory.createMatteBorder(0, thickness, 0, 0, backgroundColor);
     editor.getComponent().setBorder(border);
   }
 }
  @Override
  protected EditorEx createEditor() {
    final EditorEx ex = super.createEditor();

    if (myLanguage != null) {
      final FileType fileType = myLanguage.getAssociatedFileType();
      ex.setHighlighter(HighlighterFactory.createHighlighter(myProject, fileType));
    }
    ex.setEmbeddedIntoDialogWrapper(true);

    return ex;
  }
Пример #9
0
 public static EditorEx createEditor(Document document, Project project, boolean isViewer) {
   EditorFactory factory = EditorFactory.getInstance();
   EditorEx editor =
       (EditorEx)
           (isViewer
               ? factory.createViewer(document, project)
               : factory.createEditor(document, project));
   editor.putUserData(DiffManagerImpl.EDITOR_IS_DIFF_KEY, Boolean.TRUE);
   editor.setSoftWrapAppliancePlace(SoftWrapAppliancePlaces.VCS_DIFF);
   editor.getGutterComponentEx().revalidateMarkup();
   return editor;
 }
  private static void setupEditorDefault(EditorEx editor) {
    ConsoleViewUtil.setupConsoleEditor(editor, false, false);
    editor.getContentComponent().setFocusCycleRoot(false);
    editor.setHorizontalScrollbarVisible(false);
    editor.setVerticalScrollbarVisible(true);
    editor.setBorder(null);

    final EditorSettings editorSettings = editor.getSettings();
    editorSettings.setAdditionalLinesCount(0);
    editorSettings.setAdditionalColumnsCount(1);
    editorSettings.setRightMarginShown(false);
  }
  private static void noScrolling(EditorEx editor) {
    editor.getScrollPane().setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER);
    editor
        .getScrollPane()
        .setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    editor.getScrollPane().setWheelScrollingEnabled(false);

    List<MouseWheelListener> listeners =
        Lists.newArrayList(editor.getScrollPane().getMouseWheelListeners());
    for (MouseWheelListener l : listeners) {
      editor.getScrollPane().removeMouseWheelListener(l);
    }
  }
  public static EditorFragmentComponent createEditorFragmentComponent(
      Editor editor, int startLine, int endLine, boolean showFolding, boolean showGutter) {
    final EditorEx editorEx = (EditorEx) editor;
    final Color old = editorEx.getBackgroundColor();
    Color backColor = getBackgroundColor(editor);
    editorEx.setBackgroundColor(backColor);
    EditorFragmentComponent fragmentComponent =
        new EditorFragmentComponent(editorEx, startLine, endLine, showFolding, showGutter);
    fragmentComponent.setBackground(backColor);

    editorEx.setBackgroundColor(old);
    return fragmentComponent;
  }
Пример #13
0
 @Nullable
 private Color getBgColorForFragmentContainingInlines(@NotNull EditorEx editor) {
   TextAttributes originalAttrs = getTextAttributes(editor.getColorsScheme());
   if (originalAttrs == null) {
     return null;
   }
   Color fg = originalAttrs.getBackgroundColor();
   if (fg == null) {
     return null;
   }
   Color bg = editor.getBackgroundColor();
   return getMiddleColor(fg, bg, MIDDLE_COLOR_FACTOR);
 }
Пример #14
0
 /**
  * Called on editor settings change. Current model is expected to drop all cached information
  * about the settings if any.
  */
 public void reinitSettings() {
   boolean softWrapsUsedBefore = myUseSoftWraps;
   EditorSettings settings = myEditor.getSettings();
   myUseSoftWraps = settings.isUseSoftWraps();
   if (myUseSoftWraps && (!softWrapsUsedBefore || settings.getAdditionalColumnsCount() > 0)) {
     myApplianceManager.reset();
     myDeferredFoldRegions.clear();
     myAdditionalColumnsCount = settings.getAdditionalColumnsCount();
     settings.setAdditionalColumnsCount(0);
     myEditor.getScrollingModel().scrollToCaret(ScrollType.CENTER);
   } else if (!myUseSoftWraps && softWrapsUsedBefore) {
     settings.setAdditionalColumnsCount(myAdditionalColumnsCount);
     myEditor.getScrollingModel().scrollToCaret(ScrollType.CENTER);
   }
 }
 @NotNull
 private MyGutterOperation createOperation(@NotNull Side side) {
   int offset = side.getStartOffset(myFragment);
   EditorEx editor = myViewer.getEditor(side);
   RangeHighlighter highlighter =
       editor
           .getMarkupModel()
           .addRangeHighlighter(
               offset,
               offset,
               HighlighterLayer.ADDITIONAL_SYNTAX,
               null,
               HighlighterTargetArea.LINES_IN_RANGE);
   return new MyGutterOperation(side, highlighter);
 }
 public RendererComponent(
     Project project, @Nullable FileType fileType, boolean inheritFontFromLaF) {
   Pair<EditorTextField, EditorEx> pair = createEditor(project, fileType, inheritFontFromLaF);
   myTextField = pair.first;
   myEditor = pair.second;
   add(myEditor.getContentComponent());
 }
  public AbstractInplaceIntroducer(
      Project project,
      Editor editor,
      @Nullable E expr,
      @Nullable V localVariable,
      E[] occurrences,
      String title,
      final FileType languageFileType) {
    super(null, editor, project, title, occurrences, expr);
    myLocalVariable = localVariable;
    if (localVariable != null) {
      final PsiElement nameIdentifier = localVariable.getNameIdentifier();
      if (nameIdentifier != null) {
        myLocalMarker = createMarker(nameIdentifier);
      }
    } else {
      myLocalMarker = null;
    }
    myExprText = getExpressionText(expr);
    myLocalName = localVariable != null ? localVariable.getName() : null;

    myPreview = createPreviewComponent(project, languageFileType);
    myPreviewComponent = new JPanel(new BorderLayout());
    myPreviewComponent.add(myPreview.getComponent(), BorderLayout.CENTER);
    myPreviewComponent.setBorder(new EmptyBorder(2, 2, 6, 2));

    myWholePanel = new JPanel(new GridBagLayout());
    myWholePanel.setBorder(null);

    showDialogAdvertisement(getActionName());
  }
 public void testPrefixWithEmptyText() throws Exception {
   initText("");
   ((EditorEx) myEditor)
       .setPrefixTextAndAttributes(
           ">", new TextAttributes(Color.blue, Color.gray, null, null, Font.PLAIN));
   checkResult();
 }
  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
  public void doCollectInformation(@NotNull ProgressIndicator progress) {
    if (ApplicationManager.getApplication().isUnitTestMode()) {
      return;
    }

    if (!WebEditorOptions.getInstance().isTagTreeHighlightingEnabled()) {
      return;
    }

    final PsiElement[] elements =
        BreadcrumbsXmlWrapper.getLinePsiElements(
            myEditor.getCaretModel().getOffset(),
            myFile.getVirtualFile(),
            myProject,
            myInfoProvider);

    if (elements == null || elements.length == 0) {
      return;
    }

    if (!XmlTagTreeHighlightingUtil.containsTagsWithSameName(elements)) {
      return;
    }

    for (int i = elements.length - 1; i >= 0; i--) {
      if (elements[i] instanceof XmlTag) {
        myPairsToHighlight.add(getTagRanges((XmlTag) elements[i]));
      }
    }
  }
 /**
  * Updates editors' highlighters. This should be done when the opened file changes its file type.
  */
 private void updateHighlighters() {
   if (!myProject.isDisposed()) {
     final EditorHighlighter highlighter =
         EditorHighlighterFactory.getInstance().createEditorHighlighter(myProject, myFile);
     ((EditorEx) myEditor).setHighlighter(highlighter);
   }
 }
 public XmlTagTreeHighlightingPass(@NotNull PsiFile file, @NotNull EditorEx editor) {
   super(file.getProject(), editor.getDocument(), true);
   myFile = file;
   myEditor = editor;
   final FileViewProvider viewProvider = file.getManager().findViewProvider(file.getVirtualFile());
   myInfoProvider = BreadcrumbsXmlWrapper.findInfoProvider(viewProvider);
 }
  public LanguageConsoleImpl(
      Project project, String title, LightVirtualFile lightFile, boolean initComponents) {
    myProject = project;
    myTitle = title;
    myVirtualFile = lightFile;
    EditorFactory editorFactory = EditorFactory.getInstance();
    myHistoryFile = new LightVirtualFile(getTitle() + ".history.txt", FileTypes.PLAIN_TEXT, "");
    myEditorDocument = FileDocumentManager.getInstance().getDocument(lightFile);
    reparsePsiFile();
    assert myEditorDocument != null;
    myConsoleEditor = (EditorEx) editorFactory.createEditor(myEditorDocument, myProject);
    myConsoleEditor.addFocusListener(myFocusListener);
    myCurrentEditor = myConsoleEditor;
    myHistoryViewer =
        (EditorEx)
            editorFactory.createViewer(
                ((EditorFactoryImpl) editorFactory).createDocument(true), myProject);
    myUpdateQueue = new MergingUpdateQueue("ConsoleUpdateQueue", 300, true, null);
    Disposer.register(this, myUpdateQueue);

    // action shortcuts are not yet registered
    ApplicationManager.getApplication()
        .invokeLater(
            new Runnable() {
              @Override
              public void run() {
                installEditorFactoryListener();
              }
            });

    if (initComponents) {
      initComponents();
    }
  }
 public static void setEditorVisibleSize(Editor editor, int widthInChars, int heightInChars) {
   Dimension size =
       new Dimension(
           widthInChars * EditorUtil.getSpaceWidth(Font.PLAIN, editor),
           heightInChars * editor.getLineHeight());
   ((EditorEx) editor).getScrollPane().getViewport().setExtentSize(size);
 }
  public void testColumnModeBlockSelectionWithGaps() {
    String text =
        "public class TestClass {\n"
            + "\n"
            + "    int field;\n"
            + "\n"
            + "    int otherField;\n"
            + "}";
    init(text);

    int blockSelectionStartOffset = text.indexOf("int");
    Editor editor = myFixture.getEditor();
    ((EditorEx) editor).setColumnMode(true);
    LogicalPosition blockSelectionStartPosition =
        editor.offsetToLogicalPosition(blockSelectionStartOffset);
    LogicalPosition blockSelectionEndPosition =
        new LogicalPosition(
            blockSelectionStartPosition.line + 2, blockSelectionStartPosition.column + 16);
    editor
        .getSelectionModel()
        .setBlockSelection(blockSelectionStartPosition, blockSelectionEndPosition);

    verifySyntaxInfo(
        "foreground=java.awt.Color[r=0,g=0,b=128],fontStyle=1,text=int \n"
            + "foreground=java.awt.Color[r=102,g=14,b=122],text=field\n"
            + "foreground=java.awt.Color[r=0,g=0,b=0],fontStyle=0,text=;\n"
            + "text=\n"
            + "\n"
            + "text=\n"
            + "\n"
            + "foreground=java.awt.Color[r=0,g=0,b=128],fontStyle=1,text=int \n"
            + "foreground=java.awt.Color[r=102,g=14,b=122],text=otherField\n"
            + "foreground=java.awt.Color[r=0,g=0,b=0],fontStyle=0,text=;\n");
  }
 public void testAddingMultipleSelectionsUsingMouseInColumnSelectionMode() throws Exception {
   initText("s<selection>om<caret></selection>e text\nother text");
   setEditorVisibleSize(1000, 1000);
   ((EditorEx) myEditor).setColumnMode(true);
   mouse().alt().shift().pressAt(0, 5).dragTo(1, 2).release();
   checkResultByText(
       "s<selection>om<caret></selection>e <selection>text\not<caret></selection>her text");
 }
 public void testCaretRowWinsOverSyntaxEvenInPresenceOfHighlighter() throws Exception {
   initText("foo");
   ((EditorEx) myEditor)
       .setHighlighter(
           new UniformHighlighter(new TextAttributes(null, Color.red, null, null, Font.PLAIN)));
   addRangeHighlighter(0, 3, 0, null, Color.blue);
   checkResult();
 }
 @Override
 public void setBackground(Color bg) {
   // allows for striped tables
   if (myEditor != null) {
     myEditor.setBackgroundColor(bg);
   }
   super.setBackground(bg);
 }
  public void setConsoleEditorEnabled(boolean consoleEditorEnabled) {
    if (isConsoleEditorEnabled() == consoleEditorEnabled) return;
    final FileEditorManagerEx fileManager = FileEditorManagerEx.getInstanceEx(getProject());
    if (consoleEditorEnabled) {
      fileManager.closeFile(myVirtualFile);
      myPanel.removeAll();
      myPanel.add(myHistoryViewer.getComponent());
      myPanel.add(myConsoleEditor.getComponent());

      myHistoryViewer.setHorizontalScrollbarVisible(false);
      myCurrentEditor = myConsoleEditor;
    } else {
      myPanel.removeAll();
      myPanel.add(myHistoryViewer.getComponent(), BorderLayout.CENTER);
      myHistoryViewer.setHorizontalScrollbarVisible(true);
    }
  }
  private static void reinitSettings(final EditorEx editor) {
    EditorColorsScheme scheme = EditorColorsManager.getInstance().getGlobalScheme();
    editor.setColorsScheme(scheme);
    EditorSettings settings = editor.getSettings();
    settings.setLineNumbersShown(false);
    settings.setWhitespacesShown(false);
    settings.setLineMarkerAreaShown(false);
    settings.setIndentGuidesShown(false);
    settings.setFoldingOutlineShown(false);
    settings.setAdditionalColumnsCount(0);
    settings.setAdditionalLinesCount(0);
    settings.setRightMarginShown(true);
    settings.setRightMargin(60);
    settings.setVirtualSpace(false);

    editor.setHighlighter(new LexerEditorHighlighter(new PropertiesValueHighlighter(), scheme));
    editor.setVerticalScrollbarVisible(true);
  }