Java Code Examples for com.intellij.openapi.fileEditor.FileEditorManager

The following examples show how to use com.intellij.openapi.fileEditor.FileEditorManager. These examples are extracted from open source projects. 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 Project: lsp4intellij   Source File: EditorEventManager.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Applies the given edits to the document
 *
 * @param version    The version of the edits (will be discarded if older than current version)
 * @param edits      The edits to apply
 * @param name       The name of the edits (Rename, for example)
 * @param closeAfter will close the file after edits if set to true
 * @return True if the edits were applied, false otherwise
 */
boolean applyEdit(int version, List<TextEdit> edits, String name, boolean closeAfter, boolean setCaret) {
    Runnable runnable = getEditsRunnable(version, edits, name, setCaret);
    writeAction(() -> {
        if (runnable != null) {
            CommandProcessor.getInstance()
                    .executeCommand(project, runnable, name, "LSPPlugin", editor.getDocument());
        }
        if (closeAfter) {
            PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
            if (file != null) {
                FileEditorManager.getInstance(project).closeFile(file.getVirtualFile());
            }
        }
    });
    return runnable != null;
}
 
Example 2
Source Project: lsp4intellij   Source File: FileUtilsTest.java    License: Apache License 2.0 6 votes vote down vote up
@PrepareForTest(FileEditorManager.class)
@Test
public void testEditorFromVirtualFile() {
  VirtualFile file = PowerMockito.mock(VirtualFile.class);
  Project project = PowerMockito.mock(Project.class);

  Editor editor = PowerMockito.mock(Editor.class);
  TextEditor textEditor = PowerMockito.mock(TextEditor.class);
  PowerMockito.when(textEditor.getEditor()).thenReturn(editor);

  FileEditorManagerEx fileEditorManagerEx = PowerMockito.mock(FileEditorManagerEx.class);
  PowerMockito.mockStatic(FileEditorManager.class);
  PowerMockito.when(fileEditorManagerEx.getAllEditors(file))
      .thenReturn(new FileEditor[]{textEditor})
      .thenReturn(new FileEditor[0]);
  PowerMockito.when(FileEditorManager.getInstance(project)).thenReturn(fileEditorManagerEx);

  Assert.assertEquals(editor, FileUtils.editorFromVirtualFile(file, project));

  Assert.assertNull(FileUtils.editorFromVirtualFile(file, project));
}
 
Example 3
Source Project: IntelliJDeodorant   Source File: AbstractRefactoringPanel.java    License: MIT License 6 votes vote down vote up
private static void highlightPsiElement(PsiElement psiElement, boolean openInEditor) {
    if (openInEditor) {
        EditorHelper.openInEditor(psiElement);
    }

    Editor editor = FileEditorManager.getInstance(psiElement.getProject()).getSelectedTextEditor();
    if (editor == null) {
        return;
    }

    TextAttributes attributes = EditorColorsManager.getInstance().getGlobalScheme().getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES);
    editor.getMarkupModel().addRangeHighlighter(
            psiElement.getTextRange().getStartOffset(),
            psiElement.getTextRange().getEndOffset(),
            HighlighterLayer.SELECTION,
            attributes,
            HighlighterTargetArea.EXACT_RANGE
    );
}
 
Example 4
Source Project: consulo   Source File: InjectedLanguageUtil.java    License: Apache License 2.0 6 votes vote down vote up
public static Editor openEditorFor(@Nonnull PsiFile file, @Nonnull Project project) {
  Document document = PsiDocumentManager.getInstance(project).getDocument(file);
  // may return editor injected in current selection in the host editor, not for the file passed as argument
  VirtualFile virtualFile = file.getVirtualFile();
  if (virtualFile == null) {
    return null;
  }
  if (virtualFile instanceof VirtualFileWindow) {
    virtualFile = ((VirtualFileWindow)virtualFile).getDelegate();
  }
  Editor editor = FileEditorManager.getInstance(project).openTextEditor(new OpenFileDescriptor(project, virtualFile, -1), false);
  if (editor == null || editor instanceof EditorWindow || editor.isDisposed()) return editor;
  if (document instanceof DocumentWindowImpl) {
    return EditorWindowImpl.create((DocumentWindowImpl)document, (DesktopEditorImpl)editor, file);
  }
  return editor;
}
 
Example 5
Source Project: leetcode-editor   Source File: ClearOneAction.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void actionPerformed(AnActionEvent anActionEvent, Config config, JTree tree, Question question) {

    String codeType = config.getCodeType();
    CodeTypeEnum codeTypeEnum = CodeTypeEnum.getCodeTypeEnum(codeType);
    if (codeTypeEnum == null) {
        MessageUtils.getInstance(anActionEvent.getProject()).showWarnMsg("info", PropertiesUtils.getInfo("config.code"));
        return;
    }

    String filePath = PersistentConfig.getInstance().getTempFilePath() + VelocityUtils.convert(config.getCustomFileName(), question) + codeTypeEnum.getSuffix();

    File file = new File(filePath);
    if (file.exists()) {
        ApplicationManager.getApplication().invokeAndWait(() -> {
            VirtualFile vf = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(file);
            if (FileEditorManager.getInstance(anActionEvent.getProject()).isFileOpen(vf)) {
                FileEditorManager.getInstance(anActionEvent.getProject()).closeFile(vf);
            }
            file.delete();
        });
    }
    MessageUtils.getInstance(anActionEvent.getProject()).showInfoMsg(question.getFormTitle(), PropertiesUtils.getInfo("clear.success"));

}
 
Example 6
Source Project: consulo   Source File: FormattingProgressTask.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
  FORMATTING_CANCELLED_FLAG.set(true);
  VirtualFile file = myFile.get();
  Document document = myDocument.get();
  if (file == null || document == null || myDocumentModificationStampBefore < 0) {
    return;
  }
  FileEditor editor = FileEditorManager.getInstance(myProject).getSelectedEditor(file);
  if (editor == null) {
    return;
  }

  UndoManager manager = UndoManager.getInstance(myProject);
  while (manager.isUndoAvailable(editor) && document.getModificationStamp() != myDocumentModificationStampBefore) {
    manager.undo(editor);
  }
}
 
Example 7
Source Project: consulo   Source File: XDebuggerInlayUtil.java    License: Apache License 2.0 6 votes vote down vote up
public static void clearInlays(@Nonnull Project project) {
  UIUtil.invokeLaterIfNeeded(() -> {
    FileEditor[] editors = FileEditorManager.getInstance(project).getAllEditors();
    for (FileEditor editor : editors) {
      if (editor instanceof TextEditor) {
        Editor e = ((TextEditor)editor).getEditor();
        List<Inlay> existing = e.getInlayModel().getInlineElementsInRange(0, e.getDocument().getTextLength());
        for (Inlay inlay : existing) {
          if (inlay.getRenderer() instanceof MyRenderer) {
            Disposer.dispose(inlay);
          }
        }
      }
    }
  });
}
 
Example 8
Source Project: leetcode-editor   Source File: AbstractEditAction.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void actionPerformed(AnActionEvent anActionEvent, Config config) {
    VirtualFile vf = ArrayUtil.getFirstElement(FileEditorManager.getInstance(anActionEvent.getProject()).getSelectedFiles());
    if(vf == null){
        return;
    }
    LeetcodeEditor leetcodeEditor = ProjectConfig.getInstance(anActionEvent.getProject()).getEditor(vf.getPath());
    if (leetcodeEditor == null) {
        return;
    }
    Question question = ViewManager.getQuestionById(leetcodeEditor.getQuestionId(), anActionEvent.getProject());
    if (question == null) {
        MessageUtils.getInstance(anActionEvent.getProject()).showInfoMsg("info", PropertiesUtils.getInfo("tree.null"));
        return;
    }

    actionPerformed(anActionEvent, config, question);

}
 
Example 9
Source Project: buck   Source File: GoToBuckFile.java    License: Apache License 2.0 6 votes vote down vote up
private VirtualFile findBuckFile(Project project) {
  if (project == null || project.isDefault()) {
    return null;
  }
  Editor currentEditor = FileEditorManager.getInstance(project).getSelectedTextEditor();
  if (currentEditor == null) {
    return null;
  }
  VirtualFile currentFile =
      FileDocumentManager.getInstance().getFile(currentEditor.getDocument());
  if (currentFile == null) {
    return null;
  }
  VirtualFile buckFile =
      BuckTargetLocator.getInstance(project).findBuckFileForVirtualFile(currentFile).orElse(null);
  if (buckFile == null || buckFile.equals(currentFile)) {
    return null;
  }
  return buckFile;
}
 
Example 10
Source Project: consulo   Source File: DesktopSaveAndSyncHandlerImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void refreshOpenFiles() {
  List<VirtualFile> files = ContainerUtil.newArrayList();

  for (Project project : ProjectManager.getInstance().getOpenProjects()) {
    for (VirtualFile file : FileEditorManager.getInstance(project).getSelectedFiles()) {
      if (file instanceof NewVirtualFile) {
        files.add(file);
      }
    }
  }

  if (!files.isEmpty()) {
    // refresh open files synchronously so it doesn't wait for potentially longish refresh request in the queue to finish
    RefreshQueue.getInstance().refresh(false, false, null, files);
  }
}
 
Example 11
Source Project: consulo   Source File: DaemonCodeAnalyzerImpl.java    License: 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 12
Source Project: reasonml-idea-plugin   Source File: InferredTypesService.java    License: MIT License 6 votes vote down vote up
public static void annotatePsiFile(@NotNull Project project, @NotNull Language lang, @Nullable VirtualFile sourceFile, @Nullable InferredTypes types) {
    if (types == null || sourceFile == null) {
        return;
    }

    if (FileHelper.isInterface(sourceFile.getFileType())) {
        return;
    }

    LOG.debug("Updating signatures in user data cache for file", sourceFile);

    TextEditor selectedEditor = (TextEditor) FileEditorManager.getInstance(project).getSelectedEditor(sourceFile);
    if (selectedEditor != null) {
        CodeLensView.CodeLensInfo userData = getCodeLensData(project);
        userData.putAll(sourceFile, types.signaturesByLines(lang));
    }

    PsiFile psiFile = PsiManager.getInstance(project).findFile(sourceFile);
    if (psiFile != null && !FileHelper.isInterface(psiFile.getFileType())) {
        String[] lines = psiFile.getText().split("\n");
        psiFile.putUserData(SignatureProvider.SIGNATURE_CONTEXT, new SignatureProvider.InferredTypesWithLines(types, lines));
    }
}
 
Example 13
Source Project: JHelper   Source File: AutoSwitcher.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
private void addSelectedConfigurationListener() {
	RunManagerImpl.getInstanceImpl(project).addRunManagerListener(new RunManagerListener() {
		@Override
		public void runConfigurationSelected(RunnerAndConfigurationSettings selectedConfiguration) {
			if (selectedConfiguration == null) {
				return;
			}
			RunConfiguration configuration = selectedConfiguration.getConfiguration();
			if (busy || !(configuration instanceof TaskConfiguration)) {
				return;
			}
			busy = true;
			String pathToClassFile = ((TaskConfiguration) configuration).getCppPath();
			VirtualFile toOpen = project.getBaseDir().findFileByRelativePath(pathToClassFile);
			if (toOpen != null) {
				TransactionGuard.getInstance().submitTransactionAndWait(() -> FileEditorManager.getInstance(project).openFile(
						toOpen,
						true
				));
			}
			busy = false;
		}
	});
}
 
Example 14
Source Project: consulo   Source File: EditorNotificationActions.java    License: 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 15
Source Project: consulo   Source File: CopyHandler.java    License: Apache License 2.0 6 votes vote down vote up
public static void updateSelectionInActiveProjectView(PsiElement newElement, Project project, boolean selectInActivePanel) {
  String id = ToolWindowManager.getInstance(project).getActiveToolWindowId();
  if (id != null) {
    ToolWindow window = ToolWindowManager.getInstance(project).getToolWindow(id);
    Content selectedContent = window.getContentManager().getSelectedContent();
    if (selectedContent != null) {
      JComponent component = selectedContent.getComponent();
      if (component instanceof TwoPaneIdeView) {
        ((TwoPaneIdeView) component).selectElement(newElement, selectInActivePanel);
        return;
      }
    }
  }
  if (ToolWindowId.PROJECT_VIEW.equals(id)) {
    ProjectView.getInstance(project).selectPsiElement(newElement, true);
  }
  else if (ToolWindowId.STRUCTURE_VIEW.equals(id)) {
    VirtualFile virtualFile = newElement.getContainingFile().getVirtualFile();
    FileEditor editor = FileEditorManager.getInstance(newElement.getProject()).getSelectedEditor(virtualFile);
    StructureViewFactoryEx.getInstanceEx(project).getStructureViewWrapper().selectCurrentElement(editor, virtualFile, true);
  }
}
 
Example 16
Source Project: consulo   Source File: DaemonCodeAnalyzerImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void cleanFileLevelHighlights(@Nonnull Project project, final int group, PsiFile psiFile) {
  if (psiFile == null) return;
  FileViewProvider provider = psiFile.getViewProvider();
  VirtualFile vFile = provider.getVirtualFile();
  final FileEditorManager manager = FileEditorManager.getInstance(project);
  for (FileEditor fileEditor : manager.getEditors(vFile)) {
    final List<HighlightInfo> infos = fileEditor.getUserData(FILE_LEVEL_HIGHLIGHTS);
    if (infos == null) continue;
    List<HighlightInfo> infosToRemove = new ArrayList<>();
    for (HighlightInfo info : infos) {
      if (info.getGroup() == group) {
        manager.removeTopComponent(fileEditor, info.fileLevelComponent);
        infosToRemove.add(info);
      }
    }
    infos.removeAll(infosToRemove);
  }
}
 
Example 17
Source Project: consulo   Source File: StatusBarUpdater.java    License: Apache License 2.0 6 votes vote down vote up
private void updateStatus() {
  if (myProject.isDisposed()) {
    return;
  }

  Editor editor = FileEditorManager.getInstance(myProject).getSelectedTextEditor();
  if (editor == null || !editor.getContentComponent().hasFocus()) {
    return;
  }

  final Document document = editor.getDocument();
  if (document instanceof DocumentEx && ((DocumentEx)document).isInBulkUpdate()) return;

  int offset = editor.getCaretModel().getOffset();
  DaemonCodeAnalyzer codeAnalyzer = DaemonCodeAnalyzer.getInstance(myProject);
  HighlightInfo info = ((DaemonCodeAnalyzerImpl)codeAnalyzer).findHighlightByOffset(document, offset, false, HighlightSeverity.WARNING);
  String text = info != null && info.getDescription() != null ? info.getDescription() : "";

  StatusBar statusBar = WindowManager.getInstance().getStatusBar(editor.getContentComponent(), myProject);
  if (statusBar instanceof StatusBarEx) {
    StatusBarEx barEx = (StatusBarEx)statusBar;
    if (!text.equals(barEx.getInfo())) {
      statusBar.setInfo(text, "updater");
    }
  }
}
 
Example 18
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 19
Source Project: consulo   Source File: Switcher.java    License: Apache License 2.0 6 votes vote down vote up
@Nonnull
private static List<VirtualFile> getRecentFiles(@Nonnull Project project) {
  List<VirtualFile> recentFiles = EditorHistoryManager.getInstance(project).getFileList();
  VirtualFile[] openFiles = FileEditorManager.getInstance(project).getOpenFiles();

  Set<VirtualFile> recentFilesSet = new HashSet<>(recentFiles);
  Set<VirtualFile> openFilesSet = ContainerUtil.newHashSet(openFiles);

  // Add missing FileEditor tabs right after the last one, that is available via "Recent Files"
  int index = 0;
  for (int i = 0; i < recentFiles.size(); i++) {
    if (openFilesSet.contains(recentFiles.get(i))) {
      index = i;
      break;
    }
  }

  List<VirtualFile> result = new ArrayList<>(recentFiles);
  result.addAll(index, ContainerUtil.filter(openFiles, it -> !recentFilesSet.contains(it)));
  return result;
}
 
Example 20
Source Project: consulo   Source File: CreateFileFix.java    License: 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 21
Source Project: consulo   Source File: EditSourceUtil.java    License: Apache License 2.0 6 votes vote down vote up
@Nullable
public static Navigatable getDescriptor(final PsiElement element) {
  if (!canNavigate(element)) {
    return null;
  }
  if (element instanceof PomTargetPsiElement) {
    return ((PomTargetPsiElement)element).getTarget();
  }
  final PsiElement navigationElement = element.getNavigationElement();
  if (navigationElement instanceof PomTargetPsiElement) {
    return ((PomTargetPsiElement)navigationElement).getTarget();
  }
  final int offset = navigationElement instanceof PsiFile ? -1 : navigationElement.getTextOffset();
  final VirtualFile virtualFile = PsiUtilCore.getVirtualFile(navigationElement);
  if (virtualFile == null || !virtualFile.isValid()) {
    return null;
  }
  OpenFileDescriptor desc = new OpenFileDescriptor(navigationElement.getProject(), virtualFile, offset);
  desc.setUseCurrentWindow(FileEditorManager.USE_CURRENT_WINDOW.isIn(navigationElement));
  return desc;
}
 
Example 22
Source Project: KodeBeagle   Source File: EditorDocOps.java    License: Apache License 2.0 5 votes vote down vote up
public final void addHighlighting(final List<Integer> linesForHighlighting,
                                  final Document document) {
    TextAttributes attributes = new TextAttributes();
    JBColor color = JBColor.GREEN;
    attributes.setEffectColor(color);
    attributes.setEffectType(EffectType.SEARCH_MATCH);
    attributes.setBackgroundColor(HIGHLIGHTING_COLOR);
    Editor projectEditor =
            FileEditorManager.getInstance(windowObjects.getProject()).getSelectedTextEditor();
    if (projectEditor != null) {
        PsiFile psiFile =
                PsiDocumentManager.getInstance(windowObjects.getProject()).
                        getPsiFile(projectEditor.getDocument());
        MarkupModel markupModel = projectEditor.getMarkupModel();
        if (markupModel != null) {
            markupModel.removeAllHighlighters();

            for (int line : linesForHighlighting) {
                line = line - 1;
                if (line < document.getLineCount()) {
                    int startOffset = document.getLineStartOffset(line);
                    int endOffset = document.getLineEndOffset(line);
                    String lineText =
                            document.getCharsSequence().
                                    subSequence(startOffset, endOffset).toString();
                    int lineStartOffset =
                            startOffset + lineText.length() - lineText.trim().length();
                    markupModel.addRangeHighlighter(lineStartOffset, endOffset,
                            HighlighterLayer.ERROR, attributes,
                            HighlighterTargetArea.EXACT_RANGE);
                    if (psiFile != null && psiFile.findElementAt(lineStartOffset) != null) {
                        HighlightUsagesHandler.doHighlightElements(projectEditor,
                                new PsiElement[]{psiFile.findElementAt(lineStartOffset)},
                                attributes, false);
                    }
                }
            }
        }
    }
}
 
Example 23
Source Project: consulo   Source File: PackageDependenciesNode.java    License: Apache License 2.0 5 votes vote down vote up
@Nullable
private Editor openTextEditor(boolean focus) {
  final OpenFileDescriptor descriptor = getDescriptor();
  if (descriptor != null) {
    return FileEditorManager.getInstance(getProject()).openTextEditor(descriptor, focus);
  }
  return null;
}
 
Example 24
Source Project: lsp4intellij   Source File: LanguageServerWrapper.java    License: Apache License 2.0 5 votes vote down vote up
private void connect(String uri) {
    FileEditor[] fileEditors = FileEditorManager.getInstance(project)
            .getAllEditors(Objects.requireNonNull(FileUtils.URIToVFS(uri)));

    List<Editor> editors = new ArrayList<>();
    for (FileEditor ed : fileEditors) {
        if (ed instanceof TextEditor) {
            editors.add(((TextEditor) ed).getEditor());
        }
    }
    if (!editors.isEmpty()) {
        connect(editors.get(0));
    }
}
 
Example 25
Source Project: consulo   Source File: CodeInsightTestFixtureImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Nullable
private Editor createEditor(VirtualFile file) {
  final Project project = getProject();
  final FileEditorManager instance = FileEditorManager.getInstance(project);
  if (file.getFileType().isBinary()) {
    return null;
  }
  return instance.openTextEditor(new OpenFileDescriptor(project, file, 0), false);
}
 
Example 26
Source Project: lsp4intellij   Source File: LSPFileEventManager.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Called when a file is moved. Notifies the server if this file was watched.
 *
 * @param event The file move event
 */
static void fileMoved(VirtualFileMoveEvent event) {
    try {
        VirtualFile file = event.getFile();
        if (!FileUtils.isFileSupported(file)) {
            return;
        }

        String newFileUri = FileUtils.VFSToURI(file);
        String oldParentUri = FileUtils.VFSToURI(event.getOldParent());
        if (newFileUri == null || oldParentUri == null) {
            return;
        }
        String oldFileUri = String.format("%s/%s", oldParentUri, event.getFileName());

        ApplicationUtils.invokeAfterPsiEvents(() -> {
            // Notifies the language server.
            FileUtils.findProjectsFor(file).forEach(p -> changedConfiguration(oldFileUri,
                FileUtils.projectToUri(p), FileChangeType.Deleted));
            FileUtils.findProjectsFor(file).forEach(p -> changedConfiguration(newFileUri,
                FileUtils.projectToUri(p), FileChangeType.Created));

            FileUtils.findProjectsFor(file).forEach(p -> {
                // Detaches old file from the wrappers.
                Set<LanguageServerWrapper> wrappers = IntellijLanguageClient.getAllServerWrappersFor(FileUtils.projectToUri(p));
                if (wrappers != null) {
                    wrappers.forEach(wrapper -> wrapper.disconnect(oldFileUri, FileUtils.projectToUri(p)));
                }
                // Re-open file to so that the new editor will be connected to the language server.
                FileEditorManager fileEditorManager = FileEditorManager.getInstance(p);
                ApplicationUtils.invokeLater(() -> {
                    fileEditorManager.closeFile(file);
                    fileEditorManager.openFile(file, true);
                });
            });
        });
    } catch (Exception e) {
        LOG.warn("LSP file move event failed due to :", e);
    }
}
 
Example 27
Source Project: lsp4intellij   Source File: WorkspaceEditHandler.java    License: 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 28
Source Project: IntelliJDeodorant   Source File: AbstractRefactoringPanel.java    License: MIT License 5 votes vote down vote up
/**
 * Refreshes the panel with suggestions.
 */
private void refreshPanel() {
    Editor editor = FileEditorManager.getInstance(scope.getProject()).getSelectedTextEditor();
    if (editor != null) {
        editor.getMarkupModel().removeAllHighlighters();
    }
    if (scopeChooserCombo.getScope() != null) {
        showEmptyPanel();
        calculateRefactorings();
    }
}
 
Example 29
Source Project: consulo   Source File: OutdatedVersionNotifier.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void fileOpened(@Nonnull FileEditorManager source, @Nonnull VirtualFile file) {
  if (myCache.getCachedIncomingChanges() == null) {
    requestLoadIncomingChanges();
  }
  else {
    final Pair<CommittedChangeList, Change> pair = myCache.getIncomingChangeList(file);
    if (pair != null) {
      final FileEditor[] fileEditors = source.getEditors(file);
      for(FileEditor editor: fileEditors) {
        initPanel(pair.first, pair.second, editor);
      }
    }
  }
}
 
Example 30
Source Project: consulo   Source File: DvcsUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns the currently selected file, based on which VcsBranch or StatusBar components will identify the current repository root.
 */
@javax.annotation.Nullable
public static VirtualFile getSelectedFile(@Nonnull 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 {
      result = fileEditor.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;
}