Example usage for com.intellij.openapi.fileEditor FileEditorManager openFile

List of usage examples for com.intellij.openapi.fileEditor FileEditorManager openFile

Introduction

In this page you can find the example usage for com.intellij.openapi.fileEditor FileEditorManager openFile.

Prototype

public abstract FileEditor @NotNull [] openFile(@NotNull VirtualFile file, boolean focusEditor);

Source Link

Usage

From source file:com.android.tools.idea.tests.gui.framework.fixture.EditorFixture.java

License:Apache License

/**
 * Opens up a different file. This will run through the "Open File..." dialog to
 * find and select the given file./*  w w w . j av a  2s  .  c  o  m*/
 *
 * @param file the file to open
 * @param tab which tab to open initially, if there are multiple editors
 */
public EditorFixture open(@NotNull final VirtualFile file, @NotNull final Tab tab) {
    execute(new GuiTask() {
        @Override
        protected void executeInEDT() throws Throwable {
            // TODO: Use UI to navigate to the file instead
            Project project = myFrame.getProject();
            FileEditorManager manager = FileEditorManager.getInstance(project);
            if (tab == Tab.EDITOR) {
                manager.openTextEditor(new OpenFileDescriptor(project, file), true);
            } else {
                manager.openFile(file, true);
            }
        }
    });

    selectEditorTab(tab);

    Wait.seconds(5).expecting("file " + quote(file.getPath()) + " to be opened and loaded").until(() -> {
        if (!file.equals(getCurrentFile())) {
            return false;
        }

        FileEditor fileEditor = FileEditorManager.getInstance(myFrame.getProject()).getSelectedEditor(file);
        JComponent editorComponent = fileEditor.getComponent();
        if (editorComponent instanceof JBLoadingPanel) {
            return !((JBLoadingPanel) editorComponent).isLoading();
        }
        return true;
    });

    myFrame.requestFocusIfLost();
    robot.waitForIdle();

    return this;
}

From source file:com.facebook.buck.intellij.ideabuck.fixup.MoveResourceFiles.java

License:Apache License

private void moveTo(Project project, VirtualFile selection, String newFile, String selectedTarget) {
    String repo = getRepositoryPath(project, selection);
    if (repo != null) {
        int colon = selectedTarget.lastIndexOf(':');
        selectedTarget = colon < 0 ? selectedTarget : selectedTarget.substring(0, colon);

        String basePath = project.getBasePath();
        String newFileSuffix = newFile.substring(basePath.length());
        Path newTarget = Paths.get(repo, selectedTarget, newFileSuffix);

        String targetSuffix = selectedTarget.substring("//android_res/".length());
        String mangledPath = targetSuffix.replace('/', '_');

        String dirnameNewFile = PathUtil.getParentPath(newFile);
        String basenameNewFile = PathUtil.getFileName(newFile);
        Path mangledTarget = Paths.get(dirnameNewFile, mangledPath + "_" + basenameNewFile);

        // Move newFile to newTarget, create symlink mangledTarget -> newTarget
        Path newFilePath = Paths.get(newFile);

        // mv newFilePath to newTarget
        boolean moved = move(newFilePath, newTarget);
        if (!moved) {
            ErrorDialog.showErrorDialog(project, "Error moving file", "New file is still at %s", newFile);
        } else {/*from   ww w  .jav  a2 s . c o  m*/
            // ln -s newTarget mangledTarget
            boolean linked = createSymbolicLink(mangledTarget, newTarget);
            if (linked) {
                // Open mangledTarget in editor
                VirtualFileManager virtualFileManager = VirtualFileManager.getInstance();
                virtualFileManager.asyncRefresh(() -> {
                    VirtualFile virtualFile = virtualFileManager
                            .findFileByUrl("file://" + mangledTarget.toString());
                    if (virtualFile != null) {
                        FileEditorManager fileEditorManager = FileEditorManager.getInstance(project);
                        fileEditorManager.openFile(virtualFile, /*focusEditor=*/ true);
                    } else {
                        ErrorDialog.showErrorDialog(project, "Can't reopen resource file", "Could not find %s",
                                mangledTarget);
                    }
                });
            } else {
                move(newTarget, newFilePath); // move back
                ErrorDialog.showErrorDialog(project, "Error creating symlink", "New file is still at %s",
                        newFile);
            }
        }
    } else {
        ErrorDialog.showErrorDialog(project, "Can't find repo", "New file is still at %s", newFile);
    }
}

From source file:com.google.idea.blaze.android.project.BlazeBuildSystemService.java

License:Open Source License

@Override
public void addDependency(Module module, String artifact) {
    Project project = module.getProject();
    BlazeProjectData blazeProjectData = BlazeProjectDataManager.getInstance(project).getBlazeProjectData();
    if (blazeProjectData == null) {
        return;/*from w  w w .  ja va2 s.  c om*/
    }
    AndroidResourceModuleRegistry registry = AndroidResourceModuleRegistry.getInstance(project);
    TargetIdeInfo targetIdeInfo = blazeProjectData.targetMap.get(registry.getTargetKey(module));
    if (targetIdeInfo == null || targetIdeInfo.buildFile == 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.key.label);
    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.
        File buildIoFile = blazeProjectData.artifactLocationDecoder.decode(targetIdeInfo.buildFile);
        VirtualFile buildVirtualFile = findFileByIoFile(buildIoFile);
        if (buildVirtualFile != null) {
            fileEditorManager.openFile(buildVirtualFile, true);
        }
    }
}

From source file:com.intellij.codeInsight.daemon.quickFix.CreateFileFix.java

License:Apache License

private void invoke(@NotNull Project project, PsiDirectory myDirectory) throws IncorrectOperationException {
    myIsAvailableTimeStamp = 0; // to revalidate applicability

    try {//from w ww. j a va  2  s.c om
        if (myIsDirectory) {
            myDirectory.createSubdirectory(myNewFileName);
        } else {
            String newFileName = myNewFileName;
            String newDirectories = null;
            if (myNewFileName.contains("/")) {
                int pos = myNewFileName.lastIndexOf("/");
                newFileName = myNewFileName.substring(pos + 1);
                newDirectories = myNewFileName.substring(0, pos);
            }
            PsiDirectory directory = myDirectory;
            if (newDirectories != null) {
                try {
                    VfsUtil.createDirectoryIfMissing(myDirectory.getVirtualFile(), newDirectories);
                    VirtualFile vfsDir = VfsUtil.findRelativeFile(myDirectory.getVirtualFile(),
                            ArrayUtil.toStringArray(StringUtil.split(newDirectories, "/")));
                    directory = new PsiDirectoryImpl((PsiManagerImpl) myDirectory.getManager(), vfsDir);
                } catch (IOException e) {
                    throw new IncorrectOperationException(e.getMessage());
                }
            }
            final PsiFile newFile = directory.createFile(newFileName);
            String text = getFileText();

            if (text != null) {
                final FileType type = FileTypeRegistry.getInstance().getFileTypeByFileName(newFileName);
                final PsiFile psiFile = PsiFileFactory.getInstance(project)
                        .createFileFromText("_" + newFileName, type, text);
                final PsiElement psiElement = CodeStyleManager.getInstance(project).reformat(psiFile);
                text = psiElement.getText();
            }

            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;
                    }
                }
            }
        }
    } catch (IncorrectOperationException e) {
        myIsAvailable = false;
    }
}

From source file:com.intellij.ide.navigationToolbar.NavBarListener.java

License:Apache License

@Override
public void fileOpened(@NotNull final FileEditorManager manager, @NotNull final VirtualFile file) {
    ApplicationManager.getApplication().invokeLater(new Runnable() {
        @Override/*from  w  ww .  j  a v a 2s. c  o m*/
        public void run() {
            if (myPanel.hasFocus()) {
                manager.openFile(file, true);
            }
        }
    });
}

From source file:com.intellij.projectView.JavaTreeStructureTest.java

License:Open Source License

private void dotest(CheckAction checkAction) throws Exception {
    final PsiClass psiClass = JavaDirectoryService.getInstance()
            .getClasses(getPackageDirectory("com/package1"))[0];
    final VirtualFile virtualFile = psiClass.getContainingFile().getVirtualFile();
    final FileEditorManager fileEditorManager = FileEditorManager.getInstance(myProject);
    FileEditor[] fileEditors = fileEditorManager.openFile(virtualFile, false);
    final FileEditor fileEditor = fileEditors[0];
    try {/* www.  j  av  a 2 s  .c  o m*/
        final StructureViewComponent structureViewComponent = (StructureViewComponent) fileEditor
                .getStructureViewBuilder().createStructureView(fileEditor, myProject);

        checkAction.testClassStructure(structureViewComponent);
        Disposer.dispose(structureViewComponent);

    } finally {
        fileEditorManager.closeFile(virtualFile);
    }
}

From source file:com.intellij.projectView.StructureViewUpdatingTest.java

License:Open Source License

public void testJavaClassStructure() throws Exception {
    final PsiClass psiClass = JavaDirectoryService.getInstance()
            .getClasses(getPackageDirectory("com/package1"))[0];
    final VirtualFile virtualFile = psiClass.getContainingFile().getVirtualFile();
    final FileEditorManager fileEditorManager = FileEditorManager.getInstance(myProject);
    FileEditor[] fileEditors = fileEditorManager.openFile(virtualFile, false);
    final FileEditor fileEditor = fileEditors[0];
    try {/*  www . j a v  a  2  s  .c  o m*/
        final StructureViewComponent structureViewComponent = (StructureViewComponent) fileEditor
                .getStructureViewBuilder().createStructureView(fileEditor, myProject);
        final Document document = PsiDocumentManager.getInstance(myProject)
                .getDocument(psiClass.getContainingFile());
        structureViewComponent.setActionActive(InheritedMembersNodeProvider.ID, true);
        PlatformTestUtil.assertTreeEqual(structureViewComponent.getTree(),
                "-Class1.java\n" + " -Class1\n" + "  getValue(): int\n"
                        + "  getClass(): Class<? extends Object>\n" + "  hashCode(): int\n"
                        + "  equals(Object): boolean\n" + "  clone(): Object\n" + "  toString(): String\n"
                        + "  notify(): void\n" + "  notifyAll(): void\n" + "  wait(long): void\n"
                        + "  wait(long, int): void\n" + "  wait(): void\n" + "  finalize(): void\n"
                        + "  myField1: boolean\n" + "  myField2: boolean\n");

        new WriteCommandAction.Simple(getProject()) {
            @Override
            protected void run() throws Throwable {
                final int offset = document.getLineStartOffset(5);
                document.insertString(offset, "    boolean myNewField = false;\n");
            }
        }.execute().throwException();

        PsiDocumentManager.getInstance(myProject).commitDocument(document);

        PlatformTestUtil.waitForAlarm(600);

        //TreeUtil.expand(structureViewComponent.getTree(), 3);

        PlatformTestUtil.assertTreeEqual(structureViewComponent.getTree(), "-Class1.java\n" + " -Class1\n"
                + "  getValue(): int\n" + "  getClass(): Class<? extends Object>\n" + "  hashCode(): int\n"
                + "  equals(Object): boolean\n" + "  clone(): Object\n" + "  toString(): String\n"
                + "  notify(): void\n" + "  notifyAll(): void\n" + "  wait(long): void\n"
                + "  wait(long, int): void\n" + "  wait(): void\n" + "  finalize(): void\n"
                + "  myField1: boolean\n" + "  myField2: boolean\n" + "  myNewField: boolean = false\n");

        Disposer.dispose(structureViewComponent);

    } finally {
        fileEditorManager.closeFile(virtualFile);
    }
}

From source file:com.intellij.projectView.StructureViewUpdatingTest.java

License:Open Source License

public void testShowClassMembers() throws Exception {
    final PsiClass psiClass = JavaDirectoryService.getInstance()
            .getClasses(getPackageDirectory("com/package1"))[0];
    final VirtualFile virtualFile = psiClass.getContainingFile().getVirtualFile();
    final FileEditorManager fileEditorManager = FileEditorManager.getInstance(myProject);
    FileEditor[] fileEditors = fileEditorManager.openFile(virtualFile, false);
    final FileEditor fileEditor = fileEditors[0];
    final StructureViewComponent structureViewComponent = (StructureViewComponent) fileEditor
            .getStructureViewBuilder().createStructureView(fileEditor, myProject);
    try {/*from   w  w w .j  a v a2s . c  o  m*/
        PlatformTestUtil.assertTreeEqual(structureViewComponent.getTree(),
                "-Class2.java\n" + " -Class2\n" + "  +InnerClass1\n" + "  +InnerClass2\n"
                        + "  getValue(): int\n" + "  myField1: boolean\n" + "  myField2: boolean\n"
                        + "  myField3: boolean\n" + "  myField4: boolean\n");

        final PsiField innerClassField = psiClass.getInnerClasses()[0].getFields()[0];

        structureViewComponent.select(innerClassField, true);

        PlatformTestUtil.assertTreeEqual(structureViewComponent.getTree(),
                "-Class2.java\n" + " -Class2\n" + "  -InnerClass1\n" + "   +InnerClass12\n"
                        + "   myInnerClassField: int\n" + "  +InnerClass2\n" + "  getValue(): int\n"
                        + "  myField1: boolean\n" + "  myField2: boolean\n" + "  myField3: boolean\n"
                        + "  myField4: boolean\n");

        CommandProcessor.getInstance().executeCommand(myProject, new Runnable() {
            @Override
            public void run() {

                ApplicationManager.getApplication().runWriteAction(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            innerClassField.delete();
                        } catch (IncorrectOperationException e) {
                            fail(e.getLocalizedMessage());
                        }
                    }
                });
            }
        }, null, null);

        PlatformTestUtil.waitForAlarm(600);

        PlatformTestUtil.assertTreeEqual(structureViewComponent.getTree(),
                "-Class2.java\n" + " -Class2\n" + "  -InnerClass1\n" + "   +InnerClass12\n" + "  +InnerClass2\n"
                        + "  getValue(): int\n" + "  myField1: boolean\n" + "  myField2: boolean\n"
                        + "  myField3: boolean\n" + "  myField4: boolean\n");

    } finally {
        Disposer.dispose(structureViewComponent);
        fileEditorManager.closeFile(virtualFile);
    }
}

From source file:com.intellij.projectView.StructureViewUpdatingTest.java

License:Open Source License

public void testExpandElementWithExitingName() throws InterruptedException {

    final VirtualFile xmlVirtualFile = getContentRoot().findFileByRelativePath("test.xml");
    final FileEditorManager fileEditorManager = FileEditorManager.getInstance(myProject);
    FileEditor[] fileEditors = fileEditorManager.openFile(xmlVirtualFile, false);
    final FileEditor fileEditor = fileEditors[0];
    try {// w  w w. ja v  a2 s .  c o m
        final StructureViewComponent structureViewComponent = (StructureViewComponent) fileEditor
                .getStructureViewBuilder().createStructureView(fileEditor, myProject);

        final JTree tree = structureViewComponent.getTree();
        PlatformTestUtil.assertTreeEqual(tree,
                "-test.xml\n" + " -test\n" + "  +level1\n" + "  +level1\n" + "  +level1\n" + "  +level1\n");

        tree.expandPath(tree.getPathForRow(3));

        PlatformTestUtil.waitForAlarm(600);

        PlatformTestUtil.assertTreeEqual(tree, "-test.xml\n" + " -test\n" + "  +level1\n" + "  -level1\n"
                + "   +level2\n" + "  +level1\n" + "  +level1\n");

        Disposer.dispose(structureViewComponent);
    } finally {
        fileEditorManager.closeFile(xmlVirtualFile);
    }

}

From source file:com.maddyhome.idea.vim.group.FileGroup.java

License:Open Source License

public boolean openFile(@NotNull String filename, @NotNull DataContext context) {
    if (logger.isDebugEnabled()) {
        logger.debug("openFile(" + filename + ")");
    }/* w  w  w .j av  a  2  s  . co m*/
    Project proj = PlatformDataKeys.PROJECT.getData(context); // API change - don't merge

    VirtualFile found = findFile(filename, proj);

    if (found != null) {
        if (logger.isDebugEnabled()) {
            logger.debug("found file: " + found);
        }
        // Can't open a file unless it has a known file type. The next call will return the known type.
        // If unknown, IDEA will prompt the user to pick a type.
        FileType type = FileTypeManager.getInstance().getKnownFileTypeOrAssociate(found);
        if (type != null) {
            FileEditorManager fem = FileEditorManager.getInstance(proj);
            fem.openFile(found, true);

            return true;
        } else {
            // There was no type and user didn't pick one. Don't open the file
            // Return true here because we found the file but the user canceled by not picking a type.
            return true;
        }
    } else {
        VimPlugin.showMessage("Unable to find " + filename);

        return false;
    }
}