@Override
  public boolean canHandle(RunConfiguration configuration, Project project) {
    if (!(configuration instanceof JUnitConfiguration)) {
      return false;
    } else {
      JUnitConfiguration.Data data = ((JUnitConfiguration) configuration).getPersistentData();

      String mainClassName = data.getMainClassName();
      String methodName = data.getMethodName();

      JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project);
      PsiClass referencedClass =
          psiFacade.findClass(mainClassName, GlobalSearchScope.allScope(project));
      PsiFile containingFile = referencedClass.getContainingFile();

      FileEditorManager fileEditorManager = FileEditorManager.getInstance(project);
      if (methodName == null) {
        fileEditorManager.openFile(containingFile.getVirtualFile(), true);
      } else {
        PsiMethod[] methodsByName = referencedClass.findMethodsByName(methodName, false);

        fileEditorManager.openEditor(
            new OpenFileDescriptor(
                project, containingFile.getVirtualFile(), methodsByName[0].getTextOffset()),
            true);
      }
      return true;
    }
  }
  /**
   * 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);
    }
  }
Example #3
0
  /**
   * Returns the currently selected file, based on which VcsBranch or StatusBar components will
   * identify the current repository root.
   */
  @Nullable
  public static VirtualFile getSelectedFile(@NotNull Project project) {
    StatusBar statusBar = WindowManager.getInstance().getStatusBar(project);
    final FileEditor fileEditor = StatusBarUtil.getCurrentFileEditor(project, statusBar);
    VirtualFile result = null;
    if (fileEditor != null) {
      if (fileEditor instanceof TextEditor) {
        Document document = ((TextEditor) fileEditor).getEditor().getDocument();
        result = FileDocumentManager.getInstance().getFile(document);
      } else if (fileEditor instanceof ImageFileEditor) {
        result = ((ImageFileEditor) fileEditor).getImageEditor().getFile();
      }
    }

    if (result == null) {
      final FileEditorManager manager = FileEditorManager.getInstance(project);
      if (manager != null) {
        Editor editor = manager.getSelectedTextEditor();
        if (editor != null) {
          result = FileDocumentManager.getInstance().getFile(editor.getDocument());
        }
      }
    }
    return result;
  }
  private static void reinitBreadcrumbsComponent(
      @NotNull final FileEditorManager fileEditorManager, @NotNull VirtualFile file) {
    if (isSuitable(fileEditorManager.getProject(), file)) {
      FileEditor[] fileEditors = fileEditorManager.getAllEditors(file);
      for (final FileEditor fileEditor : fileEditors) {
        if (fileEditor instanceof TextEditor) {
          Editor editor = ((TextEditor) fileEditor).getEditor();
          if (BreadcrumbsXmlWrapper.getBreadcrumbsComponent(editor) != null) {
            continue;
          }
          final BreadcrumbsXmlWrapper wrapper = new BreadcrumbsXmlWrapper(editor);
          final JComponent c = wrapper.getComponent();
          fileEditorManager.addTopComponent(fileEditor, c);

          Disposer.register(
              fileEditor,
              new Disposable() {
                @Override
                public void dispose() {
                  disposeWrapper(fileEditorManager, fileEditor, wrapper);
                }
              });
        }
      }
    } else {
      removeBreadcrumbs(fileEditorManager, file);
    }
  }
  public void hideCoverageData() {
    if (myEditor == null) return;
    final FileEditorManager fileEditorManager = FileEditorManager.getInstance(myProject);
    final List<RangeHighlighter> highlighters = myEditor.getUserData(COVERAGE_HIGHLIGHTERS);
    if (highlighters != null) {
      for (final RangeHighlighter highlighter : highlighters) {
        ApplicationManager.getApplication().invokeLater(() -> highlighter.dispose());
      }
      myEditor.putUserData(COVERAGE_HIGHLIGHTERS, null);
    }

    final Map<FileEditor, EditorNotificationPanel> map =
        myFile.getCopyableUserData(NOTIFICATION_PANELS);
    if (map != null) {
      final VirtualFile vFile = myFile.getVirtualFile();
      LOG.assertTrue(vFile != null);
      boolean freeAll = !fileEditorManager.isFileOpen(vFile);
      myFile.putCopyableUserData(NOTIFICATION_PANELS, null);
      for (FileEditor fileEditor : map.keySet()) {
        if (!freeAll && !isCurrentEditor(fileEditor)) {
          continue;
        }
        fileEditorManager.removeTopComponent(fileEditor, map.get(fileEditor));
      }
    }

    final DocumentListener documentListener = myEditor.getUserData(COVERAGE_DOCUMENT_LISTENER);
    if (documentListener != null) {
      myDocument.removeDocumentListener(documentListener);
      myEditor.putUserData(COVERAGE_DOCUMENT_LISTENER, null);
    }
  }
  private void showEditorWarningMessage(final String message) {
    ApplicationManager.getApplication()
        .invokeLater(
            () -> {
              if (myEditor == null) return;
              final FileEditorManager fileEditorManager = FileEditorManager.getInstance(myProject);
              final VirtualFile vFile = myFile.getVirtualFile();
              assert vFile != null;
              Map<FileEditor, EditorNotificationPanel> map =
                  myFile.getCopyableUserData(NOTIFICATION_PANELS);
              if (map == null) {
                map = new HashMap<FileEditor, EditorNotificationPanel>();
                myFile.putCopyableUserData(NOTIFICATION_PANELS, map);
              }

              final FileEditor[] editors = fileEditorManager.getAllEditors(vFile);
              for (final FileEditor editor : editors) {
                if (isCurrentEditor(editor)) {
                  final EditorNotificationPanel panel =
                      new EditorNotificationPanel() {
                        {
                          myLabel.setIcon(AllIcons.General.ExclMark);
                          myLabel.setText(message);
                        }
                      };
                  panel.createActionLabel(
                      "Close", () -> fileEditorManager.removeTopComponent(editor, panel));
                  map.put(editor, panel);
                  fileEditorManager.addTopComponent(editor, panel);
                  break;
                }
              }
            });
  }
 private void renewInformationInEditors() {
   final FileEditorManager fileEditorManager = FileEditorManager.getInstance(myProject);
   final VirtualFile[] openFiles = fileEditorManager.getOpenFiles();
   for (VirtualFile openFile : openFiles) {
     final FileEditor[] allEditors = fileEditorManager.getAllEditors(openFile);
     applyInformationToEditor(allEditors, openFile);
   }
 }
 private static void updateModifiedProperty(@NotNull VirtualFile file) {
   for (Project project : ProjectManager.getInstance().getOpenProjects()) {
     FileEditorManager fileEditorManager = FileEditorManager.getInstance(project);
     for (FileEditor editor : fileEditorManager.getAllEditors(file)) {
       if (editor instanceof TextEditorImpl) {
         ((TextEditorImpl) editor).updateModifiedProperty();
       }
     }
   }
 }
 @Override
 public void propertyChanged(@NotNull VirtualFilePropertyEvent event) {
   if (VirtualFile.PROP_NAME.equals(event.getPropertyName())) {
     FileEditorManager fileEditorManager = FileEditorManager.getInstance(myProject);
     VirtualFile file = event.getFile();
     if (fileEditorManager.isFileOpen(file)) {
       reinitBreadcrumbsComponent(fileEditorManager, file);
     }
   }
 }
  public void dispose() {
    final EditorFactory editorFactory = EditorFactory.getInstance();
    editorFactory.releaseEditor(myConsoleEditor);
    editorFactory.releaseEditor(myHistoryViewer);

    final FileEditorManager editorManager = FileEditorManager.getInstance(getProject());
    final boolean isOpen = editorManager.isFileOpen(myVirtualFile);
    if (isOpen) {
      editorManager.closeFile(myVirtualFile);
    }
  }
 private void removeAnathema() {
   if (!myAnathemaThrown) return;
   myAnathemaThrown = false;
   final FileEditor[] editors = myFileEditorManager.getEditors(myVirtualFile);
   for (FileEditor editor : editors) {
     final CanNotCalculateDiffPanel panel = editor.getUserData(PANEL_KEY);
     if (panel != null) {
       myFileEditorManager.removeTopComponent(editor, panel);
       editor.putUserData(PANEL_KEY, null);
     }
   }
 }
 private void installAnathema() {
   myAnathemaThrown = true;
   final FileEditor[] editors = myFileEditorManager.getAllEditors(myVirtualFile);
   for (FileEditor editor : editors) {
     CanNotCalculateDiffPanel panel = editor.getUserData(PANEL_KEY);
     if (panel == null) {
       final CanNotCalculateDiffPanel newPanel = new CanNotCalculateDiffPanel();
       editor.putUserData(PANEL_KEY, newPanel);
       myFileEditorManager.addTopComponent(editor, newPanel);
     }
   }
 }
 @Override
 protected void tearDown() throws Exception {
   FileEditorManager editorManager = FileEditorManager.getInstance(getProject());
   VirtualFile[] openFiles = editorManager.getOpenFiles();
   for (VirtualFile openFile : openFiles) {
     editorManager.closeFile(openFile);
   }
   deleteVFile();
   myEditor = null;
   myFile = null;
   myVFile = null;
   super.tearDown();
 }
 private void openFilesInEditor(final List<FilePath> allCommittedFilePathsInSelection) {
   FileEditorManager fileEditorManager = FileEditorManager.getInstance(project);
   boolean areTabsAllowed =
       UISettings.getInstance().EDITOR_TAB_LIMIT >= allCommittedFilePathsInSelection.size();
   if (areTabsAllowed)
     allCommittedFilePathsInSelection
         .stream()
         .filter(filePath -> filePath != null)
         .forEach(filepath -> fileEditorManager.openFile(filepath.getVirtualFile(), true));
   else
     displayErrorMessage(
         "Tab limit reached",
         "Please increase Tab Limit for the editor in\nFile -> Settings -> Editor -> General -> Editor Tabs");
 }
  private static void highlightElement(@NotNull PsiElement element) {
    final Project project = element.getProject();
    final FileEditorManager editorManager = FileEditorManager.getInstance(project);
    final HighlightManager highlightManager = HighlightManager.getInstance(project);
    final EditorColorsManager editorColorsManager = EditorColorsManager.getInstance();
    final Editor editor = editorManager.getSelectedTextEditor();
    final EditorColorsScheme globalScheme = editorColorsManager.getGlobalScheme();
    final TextAttributes textattributes =
        globalScheme.getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES);
    final PsiElement[] elements = new PsiElement[] {element};
    highlightManager.addOccurrenceHighlights(editor, elements, textattributes, true, null);

    StatusBar.Info.set(
        IntentionPowerPackBundle.message("status.bar.escape.highlighting.message"), project);
  }
  private void installEditorFactoryListener() {
    final FileEditorManagerAdapter fileEditorListener =
        new FileEditorManagerAdapter() {
          @Override
          public void fileOpened(FileEditorManager source, VirtualFile file) {
            if (!Comparing.equal(file, myVirtualFile) || myConsoleEditor == null) return;
            Editor selectedTextEditor = source.getSelectedTextEditor();
            for (FileEditor fileEditor : source.getAllEditors(file)) {
              if (!(fileEditor instanceof TextEditor)) continue;
              final EditorEx editor = (EditorEx) ((TextEditor) fileEditor).getEditor();
              editor.addFocusListener(myFocusListener);
              if (selectedTextEditor == editor) { // already focused
                myCurrentEditor = editor;
              }
              EmptyAction.registerActionShortcuts(
                  editor.getComponent(), myConsoleEditor.getComponent());
              editor
                  .getCaretModel()
                  .addCaretListener(
                      new CaretListener() {
                        public void caretPositionChanged(CaretEvent e) {
                          queueUiUpdate(false);
                        }
                      });
            }
            queueUiUpdate(false);
          }

          @Override
          public void fileClosed(FileEditorManager source, VirtualFile file) {
            if (!Comparing.equal(file, myVirtualFile)) return;
            if (myUiUpdateRunnable != null
                && !Boolean.TRUE.equals(
                    file.getUserData(FileEditorManagerImpl.CLOSING_TO_REOPEN))) {
              if (myCurrentEditor != null && myCurrentEditor.isDisposed()) myCurrentEditor = null;
              ApplicationManager.getApplication().runReadAction(myUiUpdateRunnable);
            }
          }
        };
    myProject
        .getMessageBus()
        .connect(this)
        .subscribe(FileEditorManagerListener.FILE_EDITOR_MANAGER, fileEditorListener);
    FileEditorManager editorManager = FileEditorManager.getInstance(getProject());
    if (editorManager.isFileOpen(myVirtualFile)) {
      fileEditorListener.fileOpened(editorManager, myVirtualFile);
    }
  }
  private static PsiDirectory[] suggestMostAppropriateDirectories(PsiPackage psiPackage) {
    final Project project = psiPackage.getProject();
    PsiDirectory[] directories = null;
    final Editor editor = FileEditorManager.getInstance(project).getSelectedTextEditor();
    if (editor != null) {
      final Document document = editor.getDocument();
      final PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(document);
      if (psiFile != null) {
        final Module module = ModuleUtil.findModuleForPsiElement(psiFile);
        if (module != null) {
          directories =
              psiPackage.getDirectories(GlobalSearchScope.moduleWithDependenciesScope(module));
        } else {
          directories =
              psiPackage.getDirectories(
                  GlobalSearchScope.notScope(GlobalSearchScope.projectScope(project)));
        }
      }
    }

    if (directories == null || directories.length == 0) {
      directories = psiPackage.getDirectories();
    }
    return directories;
  }
 private static void disposeWrapper(
     @NotNull FileEditorManager fileEditorManager,
     @NotNull FileEditor fileEditor,
     @NotNull BreadcrumbsXmlWrapper wrapper) {
   fileEditorManager.removeTopComponent(fileEditor, wrapper.getComponent());
   Disposer.dispose(wrapper);
 }
Example #19
0
  private void highlightSearch(final boolean noSmartCase) {
    Project[] projects = ProjectManager.getInstance().getOpenProjects();
    for (Project project : projects) {
      Editor current = FileEditorManager.getInstance(project).getSelectedTextEditor();
      Editor[] editors =
          current == null
              ? null
              : EditorFactory.getInstance().getEditors(current.getDocument(), project);
      if (editors == null) {
        continue;
      }

      for (final Editor editor : editors) {
        String els = EditorData.getLastSearch(editor);
        if (!showSearchHighlight) {
          removeSearchHighlight(editor);

          continue;
        } else if (lastSearch != null && lastSearch.equals(els)) {
          continue;
        } else if (lastSearch == null) {
          continue;
        }

        removeSearchHighlight(editor);
        highlightSearchLines(editor, lastSearch, 0, -1, shouldIgnoreCase(lastSearch, noSmartCase));

        EditorData.setLastSearch(editor, lastSearch);
      }
    }
  }
Example #20
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 void setSelected(AnActionEvent e, boolean state) {
    VcsContext context = VcsContextFactory.SERVICE.getInstance().createContextOn(e);
    Editor editor = context.getEditor();
    if (!state) {
      if (editor != null) {
        editor.getGutter().closeAllAnnotations();
      }
    } else {
      if (editor == null) {
        VirtualFile selectedFile = context.getSelectedFile();
        if (selectedFile == null) {
          return;
        }

        FileEditor[] fileEditors =
            FileEditorManager.getInstance(context.getProject()).openFile(selectedFile, false);
        for (FileEditor fileEditor : fileEditors) {
          if (fileEditor instanceof TextEditor) {
            editor = ((TextEditor) fileEditor).getEditor();
          }
        }
      }

      LOGGER.assertTrue(editor != null);

      doAnnotate(editor, context.getProject());
    }
  }
 @Override
 protected void revertStateOnFinish() {
   final Editor editor = InjectedLanguageUtil.getTopLevelEditor(myEditor);
   if (editor == FileEditorManager.getInstance(myProject).getSelectedTextEditor()) {
     ((EditorImpl) editor).startDumb();
   }
   revertState();
 }
Example #23
0
  private void replaceWarningPanels(MPSFileNodeEditor editor, List<WarningPanel> newPanels) {
    Collection<WarningPanel> oldPanels = myWarnings.get(editor);
    List<WarningPanel> toRemove = new ArrayList<WarningPanel>(oldPanels);
    toRemove.removeAll(newPanels);
    List<WarningPanel> toAdd = new ArrayList<WarningPanel>(newPanels);
    toAdd.removeAll(oldPanels);

    for (WarningPanel panel : toRemove) {
      myFileEditorManager.removeTopComponent(editor, panel);
      myWarnings.removeValue(editor, panel);
    }

    for (WarningPanel panel : toAdd) {
      myFileEditorManager.addTopComponent(editor, panel);
      myWarnings.putValue(editor, panel);
    }
  }
 private static DataContext getCorrectContext(DataContext dataContext) {
   if (PlatformDataKeys.FILE_EDITOR.getData(dataContext) != null) {
     return dataContext;
   }
   Project project = PlatformDataKeys.PROJECT.getData(dataContext);
   if (project == null) {
     return dataContext;
   }
   FileEditorManager editorManager = FileEditorManager.getInstance(project);
   VirtualFile[] files = editorManager.getSelectedFiles();
   if (files.length == 0) {
     return dataContext;
   }
   FileEditor fileEditor = editorManager.getSelectedEditor(files[0]);
   return fileEditor == null
       ? dataContext
       : DataManager.getInstance().getDataContext(fileEditor.getComponent());
 }
  @SuppressWarnings("DialogTitleCapitalization")
  @Nullable
  public static PsiFile createFileFromTemplate(
      @SuppressWarnings("NullableProblems") @NotNull String name,
      @NotNull FileTemplate template,
      @NotNull PsiDirectory dir,
      @Nullable String defaultTemplateProperty) {
    // TODO: Do we *have* to hack the IntelliJ source?
    // This is a roughly a copy/paste then slight adaptation from the IntelliJ definition of this
    // method.
    // We can't override it directly, and more importantly we can't override its call to
    // FileTemplateUtil.createFromTemplate()
    List<String> pathItems = FileUtil.getPathFromSourceRoot(dir.getProject(), dir.getVirtualFile());
    // modulePrefix is the empty string if the module is either in the top
    // level directory or one of the subdirectories start with a lower-case
    // letter.
    final String modulePrefix =
        pathItems == null || invalidPathItems(pathItems) ? "" : StringUtil.join(pathItems, ".");

    // Adapted from super definition.
    CreateFileAction.MkDirs mkdirs = new CreateFileAction.MkDirs(name, dir);
    name = mkdirs.newName;
    dir = mkdirs.directory;
    PsiElement element;
    Project project = dir.getProject();
    try {
      // Patch props with custom property.
      Properties props = FileTemplateManager.getInstance().getDefaultProperties(project);
      props.setProperty(
          "HASKELL_MODULE_NAME", modulePrefix.isEmpty() ? name : modulePrefix + '.' + name);
      element = FileTemplateUtil.createFromTemplate(template, name, props, dir);

      final PsiFile psiFile = element.getContainingFile();

      final VirtualFile virtualFile = psiFile.getVirtualFile();
      if (virtualFile != null) {
        FileEditorManager.getInstance(project).openFile(virtualFile, true);
        if (defaultTemplateProperty != null) {
          PropertiesComponent.getInstance(project)
              .setValue(defaultTemplateProperty, template.getName());
        }
        return psiFile;
      }
    } catch (ParseException e) {
      Messages.showErrorDialog(
          project,
          "Error parsing Velocity template: " + e.getMessage(),
          "Create File from Template");
      return null;
    } catch (IncorrectOperationException e) {
      throw e;
    } catch (Exception e) {
      LOG.error(e);
    }

    return null;
  }
 @Override
 public boolean openFile(File file) {
   VirtualFile floorc = LocalFileSystem.getInstance().findFileByIoFile(file);
   if (floorc == null) {
     return false;
   }
   FileEditorManager.getInstance(context.project).openFile(floorc, true);
   return true;
 }
Example #27
0
 private static Editor getEditor(Project project, PsiElement element) {
   FileEditor[] editors =
       FileEditorManager.getInstance(project)
           .getEditors(element.getContainingFile().getVirtualFile());
   for (FileEditor fileEditor : editors) {
     if (fileEditor instanceof TextEditor) return ((TextEditor) fileEditor).getEditor();
   }
   return null;
 }
Example #28
0
  public static Editor positionCursor(
      final Project project, PsiFile targetFile, PsiElement element) {
    TextRange range = element.getTextRange();
    int textOffset = range.getStartOffset();

    OpenFileDescriptor descriptor =
        new OpenFileDescriptor(project, targetFile.getVirtualFile(), textOffset);
    return FileEditorManager.getInstance(project).openTextEditor(descriptor, true);
  }
Example #29
0
 @Override
 public void run() {
   final Editor editor =
       FileEditorManager.getInstance(myProject).getSelectedTextEditor();
   if (editor != null) {
     editor.getContentComponent().revalidate();
     editor.getContentComponent().repaint();
   }
 }
 private void fileChanged(VirtualFile newFile) {
   FileEditor fileEditor =
       newFile == null
           ? null
           : FileEditorManager.getInstance(getProject()).getSelectedEditor(newFile);
   Editor editor = fileEditor instanceof TextEditor ? ((TextEditor) fileEditor).getEditor() : null;
   myEditor = new WeakReference<Editor>(editor);
   update();
 }