Java Code Examples for com.intellij.openapi.fileEditor.FileEditorManager#getInstance()

The following examples show how to use com.intellij.openapi.fileEditor.FileEditorManager#getInstance() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CreateFileFix.java    From consulo with Apache License 2.0 6 votes vote down vote up
protected void openFile(@Nonnull Project project, PsiDirectory directory, PsiFile newFile, String text) {
  final FileEditorManager editorManager = FileEditorManager.getInstance(directory.getProject());
  final FileEditor[] fileEditors = editorManager.openFile(newFile.getVirtualFile(), true);

  if (text != null) {
    for (FileEditor fileEditor : fileEditors) {
      if (fileEditor instanceof TextEditor) { // JSP is not safe to edit via Psi
        final Document document = ((TextEditor)fileEditor).getEditor().getDocument();
        document.setText(text);

        if (ApplicationManager.getApplication().isUnitTestMode()) {
          FileDocumentManager.getInstance().saveDocument(document);
        }
        PsiDocumentManager.getInstance(project).commitDocument(document);
        break;
      }
    }
  }
}
 
Example 2
Source File: OpenFilesActivity.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void runActivity(@Nonnull UIAccess uiAccess, @Nonnull Project project) {
  final FileEditorManager fileEditorManager = FileEditorManager.getInstance(project);
  if (!(fileEditorManager instanceof FileEditorManagerImpl)) {
    return;
  }

  ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
  if (indicator != null) {
    indicator.setText("Reopening files...");
  }

  final FileEditorManagerImpl manager = (FileEditorManagerImpl)fileEditorManager;
  manager.getMainSplitters().openFiles(uiAccess);
  manager.initDockableContentFactory();
}
 
Example 3
Source File: DaemonCodeAnalyzerImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void addFileLevelHighlight(@Nonnull final Project project, final int group, @Nonnull final HighlightInfo info, @Nonnull final PsiFile psiFile) {
  VirtualFile vFile = psiFile.getViewProvider().getVirtualFile();
  final FileEditorManager manager = FileEditorManager.getInstance(project);
  for (FileEditor fileEditor : manager.getEditors(vFile)) {
    if (fileEditor instanceof TextEditor) {
      FileLevelIntentionComponent component = new FileLevelIntentionComponent(info.getDescription(), info.getSeverity(), info.getGutterIconRenderer(), info.quickFixActionRanges, project, psiFile,
                                                                              ((TextEditor)fileEditor).getEditor(), info.getToolTip());
      manager.addTopComponent(fileEditor, component);
      List<HighlightInfo> fileLevelInfos = fileEditor.getUserData(FILE_LEVEL_HIGHLIGHTS);
      if (fileLevelInfos == null) {
        fileLevelInfos = new ArrayList<>();
        fileEditor.putUserData(FILE_LEVEL_HIGHLIGHTS, fileLevelInfos);
      }
      info.fileLevelComponent = component;
      info.setGroup(group);
      fileLevelInfos.add(info);
    }
  }
}
 
Example 4
Source File: DetectedIndentOptionsNotificationProvider.java    From consulo with Apache License 2.0 6 votes vote down vote up
public static void updateIndentNotification(@Nonnull PsiFile file, boolean enforce) {
  VirtualFile vFile = file.getVirtualFile();
  if (vFile == null) return;

  if (!ApplicationManager.getApplication().isHeadlessEnvironment()
      || ApplicationManager.getApplication().isUnitTestMode() && myShowNotificationInTest)
  {
    Project project = file.getProject();
    FileEditorManager fileEditorManager = FileEditorManager.getInstance(project);
    if (fileEditorManager == null) return;
    FileEditor fileEditor = fileEditorManager.getSelectedEditor(vFile);
    if (fileEditor != null) {
      Boolean notifiedFlag = fileEditor.getUserData(NOTIFIED_FLAG);
      if (notifiedFlag == null || enforce) {
        fileEditor.putUserData(NOTIFIED_FLAG, Boolean.TRUE);
        EditorNotifications.getInstance(project).updateNotifications(vFile);
      }
    }
  }
}
 
Example 5
Source File: EditorNotificationActions.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void collectActions(@Nonnull Editor hostEditor, @Nonnull PsiFile hostFile, @Nonnull ShowIntentionsPass.IntentionsInfo intentions, int passIdToShowIntentionsFor, int offset) {
  Project project = hostEditor.getProject();
  if (project == null) return;
  FileEditorManager fileEditorManager = FileEditorManager.getInstance(project);
  if (!(fileEditorManager instanceof FileEditorManagerImpl)) return;
  TextEditor fileEditor = TextEditorProvider.getInstance().getTextEditor(hostEditor);
  List<JComponent> components = ((FileEditorManagerImpl)fileEditorManager).getTopComponents(fileEditor);
  for (JComponent component : components) {
    if (component instanceof IntentionActionProvider) {
      IntentionActionWithOptions action = ((IntentionActionProvider)component).getIntentionAction();
      if (action != null) {
        intentions.notificationActionsToShow.add(new HighlightInfo.IntentionActionDescriptor(action, action.getOptions(), null));
      }
    }
  }
}
 
Example 6
Source File: PantsHighlightingIntegrationTest.java    From intellij-pants-plugin with Apache License 2.0 5 votes vote down vote up
@Override
public void tearDown() throws Exception {
  final FileEditorManager fileEditorManager = FileEditorManager.getInstance(myProject);
  for (VirtualFile openFile : fileEditorManager.getOpenFiles()) {
    fileEditorManager.closeFile(openFile);
  }

  super.tearDown();
}
 
Example 7
Source File: AddAllOpenFilesToFavorites.java    From consulo with Apache License 2.0 5 votes vote down vote up
static ArrayList<PsiFile> getFilesToAdd(Project project) {
  ArrayList<PsiFile> result = new ArrayList<PsiFile>();
  final FileEditorManager editorManager = FileEditorManager.getInstance(project);
  final PsiManager psiManager = PsiManager.getInstance(project);
  final VirtualFile[] openFiles = editorManager.getOpenFiles();
  for (VirtualFile openFile : openFiles) {
    if (!openFile.isValid()) continue;
    final PsiFile psiFile = psiManager.findFile(openFile);
    if (psiFile != null) {
      result.add(psiFile);
    }
  }
  return result;
}
 
Example 8
Source File: TypeInfoUtil.java    From intellij-haskforce with Apache License 2.0 5 votes vote down vote up
@Nullable
public static String getTypeInfo(Project project) {
    FileEditorManager fileEditorManager = FileEditorManager.getInstance(
            project);
    if (fileEditorManager == null){
        return null;
    }
    Editor textEditor = fileEditorManager.getSelectedTextEditor();
    if (textEditor == null){
        return null;
    }

    VisualPosition blockStart = correctFor0BasedVS1Based(textEditor.getSelectionModel().getSelectionStartPosition());
    VisualPosition blockEnd = correctFor0BasedVS1Based(textEditor.getSelectionModel().getSelectionEndPosition());
    if (blockStart == null || blockEnd == null){
        return null;
    }

    PsiFile psiFileInEditor = PsiUtilBase.getPsiFileInEditor(textEditor, project);
    if(psiFileInEditor == null){
        return "no psi file found";
    }
    VirtualFile projectFile = psiFileInEditor.getVirtualFile();
    if (projectFile == null){
        return "project file is null";
    }
    Module module = ModuleUtilCore.findModuleForFile(projectFile, project);

    return getTypeInfo(module, blockStart, blockEnd, projectFile);
}
 
Example 9
Source File: NavigationUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static boolean activatePsiElementIfOpen(@Nonnull PsiElement elt, boolean searchForOpen, boolean requestFocus) {
  if (!elt.isValid()) return false;
  elt = elt.getNavigationElement();
  final PsiFile file = elt.getContainingFile();
  if (file == null || !file.isValid()) return false;

  VirtualFile vFile = file.getVirtualFile();
  if (vFile == null) return false;

  if (!EditorHistoryManager.getInstance(elt.getProject()).hasBeenOpen(vFile)) return false;

  final FileEditorManager fem = FileEditorManager.getInstance(elt.getProject());
  if (!fem.isFileOpen(vFile)) {
    fem.openFile(vFile, requestFocus, searchForOpen);
  }

  final TextRange range = elt.getTextRange();
  if (range == null) return false;

  final FileEditor[] editors = fem.getEditors(vFile);
  for (FileEditor editor : editors) {
    if (editor instanceof TextEditor) {
      final Editor text = ((TextEditor)editor).getEditor();
      final int offset = text.getCaretModel().getOffset();

      if (range.containsOffset(offset)) {
        // select the file
        fem.openFile(vFile, requestFocus, searchForOpen);
        return true;
      }
    }
  }

  return false;
}
 
Example 10
Source File: BreadcrumbsInitializingActivity.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static void reinitBreadcrumbsInAllEditors(@Nonnull Project project) {
  if (project.isDisposed()) return;
  FileEditorManager fileEditorManager = FileEditorManager.getInstance(project);
  for (VirtualFile virtualFile : fileEditorManager.getOpenFiles()) {
    reinitBreadcrumbsComponent(fileEditorManager, virtualFile);
  }
}
 
Example 11
Source File: SrcFileAnnotator.java    From consulo with Apache License 2.0 5 votes vote down vote up
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(new Runnable() {
        @Override
        public void run() {
          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);
  }
}
 
Example 12
Source File: CoverageDataManagerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
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);
  }
}
 
Example 13
Source File: FoldingTestCase.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
private String getFoldingDescription(@Nonnull String content, @Nonnull String fileName, boolean doCheckCollapseStatus) {
  FileType fileTypeByFileName = FileTypeManager.getInstance().getFileTypeByFileName(fileName);

  PsiFile file = createFile(fileName, fileTypeByFileName, content);

  final FileEditorManager fileEditorManager = FileEditorManager.getInstance(myProject);

  Editor editor = fileEditorManager.openTextEditor(new OpenFileDescriptor(myProject, file.getVirtualFile()), false);

  CodeFoldingManager.getInstance(myProject).buildInitialFoldings(editor);

  final FoldingModel model = editor.getFoldingModel();
  final FoldRegion[] foldingRegions = model.getAllFoldRegions();
  final List<Border> borders = new LinkedList<Border>();

  for (FoldRegion region : foldingRegions) {
    borders.add(new Border(Border.LEFT, region.getStartOffset(), region.getPlaceholderText(), region.isExpanded()));
    borders.add(new Border(Border.RIGHT, region.getEndOffset(), "", region.isExpanded()));
  }
  Collections.sort(borders);

  StringBuilder result = new StringBuilder(editor.getDocument().getText());
  for (Border border : borders) {
    result.insert(border.getOffset(), border.isSide() == Border.LEFT ? "<fold text=\'" + border.getText() + "\'" +
                                                                       (doCheckCollapseStatus ? " expand=\'" +
                                                                                                border.isExpanded() +
                                                                                                "\'" : "") +
                                                                       ">" : END_FOLD);
  }

  return result.toString();
}
 
Example 14
Source File: LanguageConsoleImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
protected void closeFile() {
  if (getProject().isOpen()) {
    FileEditorManager editorManager = FileEditorManager.getInstance(getProject());
    if (editorManager.isFileOpen(getVirtualFile())) {
      editorManager.closeFile(getVirtualFile());
    }
  }
}
 
Example 15
Source File: LightPlatformCodeInsightTestCase.java    From consulo with Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example 16
Source File: BreadcrumbsInitializingActivity.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void propertyChanged(@Nonnull VirtualFilePropertyEvent event) {
  if (VirtualFile.PROP_NAME.equals(event.getPropertyName()) && !myProject.isDisposed()) {
    FileEditorManager fileEditorManager = FileEditorManager.getInstance(myProject);
    VirtualFile file = event.getFile();
    if (fileEditorManager.isFileOpen(file)) {
      reinitBreadcrumbsComponent(fileEditorManager, file);
    }
  }
}
 
Example 17
Source File: WorkspaceEditHandler.java    From lsp4intellij with Apache License 2.0 5 votes vote down vote up
/**
 * Opens an editor when needed and gets the Runnable
 *
 * @param edits         The text edits
 * @param uri           The uri of the file
 * @param version       The version of the file
 * @param openedEditors
 * @param curProject
 * @param name
 * @return The runnable containing the edits
 */
private static Runnable manageUnopenedEditor(List<TextEdit> edits, String uri, int version,
                                             List<VirtualFile> openedEditors, Project[] curProject, String name) {
    Project[] projects = ProjectManager.getInstance().getOpenProjects();
    //Infer the project from the uri
    Project project = Stream.of(projects)
            .map(p -> new ImmutablePair<>(FileUtils.VFSToURI(ProjectUtil.guessProjectDir(p)), p))
            .filter(p -> uri.startsWith(p.getLeft())).sorted(Collections.reverseOrder())
            .map(ImmutablePair::getRight).findFirst().orElse(projects[0]);
    VirtualFile file = null;
    try {
        file = LocalFileSystem.getInstance().findFileByIoFile(new File(new URI(FileUtils.sanitizeURI(uri))));
    } catch (URISyntaxException e) {
        LOG.warn(e);
    }
    FileEditorManager fileEditorManager = FileEditorManager.getInstance(project);
    OpenFileDescriptor descriptor = new OpenFileDescriptor(project, file);
    Editor editor = ApplicationUtils
            .computableWriteAction(() -> fileEditorManager.openTextEditor(descriptor, false));
    openedEditors.add(file);
    curProject[0] = editor.getProject();
    Runnable runnable = null;
    EditorEventManager manager = EditorEventManagerBase.forEditor(editor);
    if (manager != null) {
        runnable = manager.getEditsRunnable(version, edits, name, true);
    }
    return runnable;
}
 
Example 18
Source File: BlazeModuleSystem.java    From intellij with Apache License 2.0 4 votes vote down vote up
@Override
public void registerDependency(GradleCoordinate coordinate, DependencyType type) {
  if (type != DependencyType.IMPLEMENTATION) {
    throw new UnsupportedOperationException("Unsupported dependency type in Blaze: " + type);
  }
  BlazeProjectData blazeProjectData =
      BlazeProjectDataManager.getInstance(project).getBlazeProjectData();
  if (blazeProjectData == null) {
    return;
  }
  AndroidResourceModuleRegistry registry = AndroidResourceModuleRegistry.getInstance(project);
  TargetIdeInfo targetIdeInfo =
      blazeProjectData.getTargetMap().get(registry.getTargetKey(module));
  if (targetIdeInfo == null || targetIdeInfo.getBuildFile() == null) {
    return;
  }

  // TODO: automagically edit deps instead of just opening the BUILD file?
  // Need to translate Gradle coordinates into blaze targets.
  // Will probably need to hardcode for each dependency.
  FileEditorManager fileEditorManager = FileEditorManager.getInstance(project);
  PsiElement buildTargetPsi =
      BuildReferenceManager.getInstance(project).resolveLabel(targetIdeInfo.getKey().getLabel());
  if (buildTargetPsi != null) {
    // If we can find a PSI for the target,
    // then we can jump straight to the target in the build file.
    fileEditorManager.openTextEditor(
        new OpenFileDescriptor(
            project,
            buildTargetPsi.getContainingFile().getVirtualFile(),
            buildTargetPsi.getTextOffset()),
        true);
  } else {
    // If not, just the build file is good enough.
    ArtifactLocation buildFile = targetIdeInfo.getBuildFile();
    File buildIoFile =
        Preconditions.checkNotNull(
            OutputArtifactResolver.resolve(
                project, blazeProjectData.getArtifactLocationDecoder(), buildFile),
            "Fail to find file %s",
            buildFile.getRelativePath());
    VirtualFile buildVirtualFile =
        VfsUtils.resolveVirtualFile(buildIoFile, /* refreshIfNeeded= */ true);
    if (buildVirtualFile != null) {
      fileEditorManager.openFile(buildVirtualFile, true);
    }
  }
}
 
Example 19
Source File: NoSqlDatabaseFileSystem.java    From nosql4idea with Apache License 2.0 4 votes vote down vote up
public void openEditor(final NoSqlDatabaseObjectFile databaseObjectFile) {
    FileEditorManager fileEditorManager = FileEditorManager.getInstance(databaseObjectFile.getProject());
    fileEditorManager.openFile(databaseObjectFile, true);
}
 
Example 20
Source File: EditSourceInNewWindowAction.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
public void actionPerformed(AnActionEvent e) {
  final FileEditorManager manager = FileEditorManager.getInstance(getEventProject(e));
  ((FileEditorManagerImpl)manager).openFileInNewWindow(getVirtualFiles(e)[0]);
}