com.intellij.openapi.fileEditor.FileEditorManager Java Examples

The following examples show how to use com.intellij.openapi.fileEditor.FileEditorManager. 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: DaemonCodeAnalyzerImpl.java    From consulo with 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 #2
Source File: FileUtilsTest.java    From lsp4intellij with 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 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 #4
Source File: AbstractRefactoringPanel.java    From IntelliJDeodorant with 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 #5
Source File: EditSourceUtil.java    From consulo with 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 #6
Source File: EditorEventManager.java    From lsp4intellij with 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 #7
Source File: Switcher.java    From consulo with 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 #8
Source File: InjectedLanguageUtil.java    From consulo with 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 #9
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 #10
Source File: StatusBarUpdater.java    From consulo with 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 #11
Source File: ClearOneAction.java    From leetcode-editor with 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 #12
Source File: FormattingProgressTask.java    From consulo with 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 #13
Source File: XDebuggerInlayUtil.java    From consulo with 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 #14
Source File: AbstractEditAction.java    From leetcode-editor with 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 #15
Source File: CopyHandler.java    From consulo with 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 File: GoToBuckFile.java    From buck with 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 #17
Source File: DesktopSaveAndSyncHandlerImpl.java    From consulo with 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 #18
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 #19
Source File: InferredTypesService.java    From reasonml-idea-plugin with 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 #20
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 #21
Source File: AutoSwitcher.java    From JHelper with 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 #22
Source File: RenameFileFix.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void applyFix(@Nonnull final Project project, @Nonnull ProblemDescriptor descriptor) {
  final PsiFile file = descriptor.getPsiElement().getContainingFile();
  if (isAvailable(project, null, file)) {
    new WriteCommandAction(project) {
      @Override
      protected void run(Result result) throws Throwable {
        invoke(project, FileEditorManager.getInstance(project).getSelectedTextEditor(), file);
      }
    }.execute();
  }
}
 
Example #23
Source File: PackageDependenciesNode.java    From consulo with 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 File: GraphQLSchemaEndpointsListNode.java    From js-graphql-intellij-plugin with MIT License 5 votes vote down vote up
@Override
public void handleDoubleClickOrEnter(SimpleTree tree, InputEvent inputEvent) {

    final String introspect = "Get GraphQL Schema from Endpoint (introspection)";
    final String createScratch = "New GraphQL Scratch File (for query, mutation testing)";
    ListPopup listPopup = JBPopupFactory.getInstance().createListPopup(new BaseListPopupStep<String>("Choose Endpoint Action", introspect, createScratch) {

        @Override
        public PopupStep onChosen(String selectedValue, boolean finalChoice) {
            return doFinalStep(() -> {
                if (introspect.equals(selectedValue)) {
                    GraphQLIntrospectionHelper.getService(myProject).performIntrospectionQueryAndUpdateSchemaPathFile(myProject, endpoint);
                } else if (createScratch.equals(selectedValue)) {
                    final String configBaseDir = endpoint.configPackageSet.getConfigBaseDir().getPresentableUrl();
                    final String text = "# " + GRAPHQLCONFIG_COMMENT + configBaseDir + "!" + Optional.ofNullable(projectKey).orElse("") + "\n\nquery ScratchQuery {\n\n}";
                    final VirtualFile scratchFile = ScratchRootType.getInstance().createScratchFile(myProject, "scratch.graphql", GraphQLLanguage.INSTANCE, text);
                    if (scratchFile != null) {
                        FileEditor[] fileEditors = FileEditorManager.getInstance(myProject).openFile(scratchFile, true);
                        for (FileEditor editor : fileEditors) {
                            if (editor instanceof TextEditor) {
                                final JSGraphQLEndpointsModel endpointsModel = ((TextEditor) editor).getEditor().getUserData(JS_GRAPH_QL_ENDPOINTS_MODEL);
                                if (endpointsModel != null) {
                                    endpointsModel.setSelectedItem(endpoint);
                                }
                            }
                        }
                    }
                }
            });
        }
    });
    if (inputEvent instanceof KeyEvent) {
        listPopup.showInFocusCenter();
    } else if (inputEvent instanceof MouseEvent) {
        listPopup.show(new RelativePoint((MouseEvent) inputEvent));
    }
}
 
Example #25
Source File: LightToolWindowManager.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void fileClosed(@Nonnull FileEditorManager source, @Nonnull VirtualFile file) {
  ApplicationManager.getApplication().invokeLater(new Runnable() {
    @Override
    public void run() {
      bindToDesigner(getActiveDesigner());
    }
  });
}
 
Example #26
Source File: VcsAnnotateUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
public static List<Editor> getEditors(@Nonnull Project project, @Nonnull VirtualFile file) {
  FileEditor[] editors = FileEditorManager.getInstance(project).getEditors(file);
  return ContainerUtil.mapNotNull(editors, new Function<FileEditor, Editor>() {
    @Override
    public Editor fun(FileEditor fileEditor) {
      return fileEditor instanceof TextEditor ? ((TextEditor)fileEditor).getEditor() : null;
    }
  });
}
 
Example #27
Source File: GraphQLIntrospectionHelper.java    From js-graphql-intellij-plugin with MIT License 5 votes vote down vote up
void createOrUpdateIntrospectionOutputFile(String schemaText, IntrospectionOutputFormat format, VirtualFile introspectionSourceFile, String outputFileName) {
    ApplicationManager.getApplication().runWriteAction(() -> {
        try {
            final String header;
            switch (format) {
                case SDL:
                    header = "# This file was generated based on \"" + introspectionSourceFile.getName() + "\". Do not edit manually.\n\n";
                    break;
                case JSON:
                    header = "";
                    break;
                default:
                    throw new IllegalArgumentException("unsupported output format: " + format);
            }
            String relativeOutputFileName = StringUtils.replaceChars(outputFileName, '\\', '/');
            VirtualFile outputFile = introspectionSourceFile.getParent().findFileByRelativePath(relativeOutputFileName);
            if (outputFile == null) {
                PsiDirectory directory = PsiDirectoryFactory.getInstance(myProject).createDirectory(introspectionSourceFile.getParent());
                CreateFileAction.MkDirs dirs = new CreateFileAction.MkDirs(relativeOutputFileName, directory);
                outputFile = dirs.directory.getVirtualFile().createChildData(introspectionSourceFile, dirs.newName);
            }
            outputFile.putUserData(GraphQLSchemaKeys.IS_GRAPHQL_INTROSPECTION_JSON, true);
            final FileEditor[] fileEditors = FileEditorManager.getInstance(myProject).openFile(outputFile, true, true);
            if (fileEditors.length > 0) {
                final FileEditor fileEditor = fileEditors[0];
                setEditorTextAndFormatLines(header + schemaText, fileEditor);
            } else {
                Notifications.Bus.notify(new Notification("GraphQL", "GraphQL Error", "Unable to open an editor for '" + outputFile.getPath() + "'", NotificationType.ERROR));
            }
        } catch (IOException ioe) {
            Notifications.Bus.notify(new Notification("GraphQL", "GraphQL IO Error", "Unable to create file '" + outputFileName + "' in directory '" + introspectionSourceFile.getParent().getPath() + "': " + ioe.getMessage(), NotificationType.ERROR));
        }
    });
}
 
Example #28
Source File: ProjectAPI.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Opens an editor for the given file in the UI thread.
 *
 * @param project the project in which to open the editor
 * @param virtualFile file for which to open an editor
 * @param activate activate editor after opening
 * @return text editor managing the passed file or <code>null</code> if the opened editor is not a
 *     text editor
 */
@Nullable
public static Editor openEditor(
    @NotNull Project project, @NotNull VirtualFile virtualFile, final boolean activate) {

  FileEditorManager fileEditorManager = getFileEditorManager(project);

  return EDTExecutor.invokeAndWait(
      () ->
          fileEditorManager.openTextEditor(
              new OpenFileDescriptor(project, virtualFile), activate));
}
 
Example #29
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 #30
Source File: CreateUnresolvedElementFix.java    From consulo-csharp with Apache License 2.0 5 votes vote down vote up
@Nullable
protected static Editor openEditor(@Nonnull PsiElement anchor, int offset)
{
	PsiFile containingFile = anchor.getContainingFile();
	if(containingFile == null)
	{
		return null;
	}
	VirtualFile virtualFile = containingFile.getVirtualFile();
	if(virtualFile == null)
	{
		return null;
	}

	Project project = containingFile.getProject();
	FileEditorProviderManager editorProviderManager = FileEditorProviderManager.getInstance();
	if(editorProviderManager.getProviders(project, virtualFile).length == 0)
	{
		Messages.showMessageDialog(project, IdeBundle.message("error.files.of.this.type.cannot.be.opened", ApplicationNamesInfo.getInstance()
				.getProductName()), IdeBundle.message("title.cannot.open.file"), Messages.getErrorIcon());
		return null;
	}

	OpenFileDescriptor descriptor = new OpenFileDescriptor(project, virtualFile);
	Editor editor = FileEditorManager.getInstance(project).openTextEditor(descriptor, true);
	if(editor != null)
	{
		editor.getCaretModel().moveToOffset(offset);
		editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
		return editor;
	}
	return null;
}