下面列出了com.intellij.psi.search.EverythingGlobalScope#com.intellij.openapi.fileEditor.OpenFileDescriptor 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public boolean processSelectedItem(@Nonnull Object selected, int modifiers, @Nonnull String searchText) {
if (selected instanceof PsiFile) {
VirtualFile file = ((PsiFile)selected).getVirtualFile();
if (file != null && myProject != null) {
Pair<Integer, Integer> pos = getLineAndColumn(searchText);
OpenFileDescriptor descriptor = new OpenFileDescriptor(myProject, file, pos.first, pos.second);
descriptor.setUseCurrentWindow(openInCurrentWindow(modifiers));
if (descriptor.canNavigate()) {
descriptor.navigate(true);
return true;
}
}
}
return super.processSelectedItem(selected, modifiers, searchText);
}
public static void navigate(PsiElement psiElement, Project project) {
ApplicationManager.getApplication().invokeLater(
() -> {
ApplicationManager.getApplication().assertIsDispatchThread();
Navigatable n = (Navigatable) psiElement;
//this is for better cursor position
if (psiElement instanceof PsiFile) {
VirtualFile file = ((PsiFile) psiElement).getVirtualFile();
if (file == null) return;
OpenFileDescriptor descriptor = new OpenFileDescriptor(project, file, 0, 0);
n = descriptor.setUseCurrentWindow(true);
}
if (n.canNavigate()) {
n.navigate(true);
}
}
);
}
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;
}
@Override
public void actionPerformed(AnActionEvent e) {
Project project = e.getProject();
if (project == null) {
return;
}
VirtualFile buckFile = findBuckFile(project);
if (buckFile != null) {
final OpenFileDescriptor descriptor = new OpenFileDescriptor(e.getProject(), buckFile);
// This is for better cursor position.
final Navigatable n = descriptor.setUseCurrentWindow(false);
if (!n.canNavigate()) {
return;
}
n.navigate(true);
}
}
private static void handleClickOnError(BuckErrorItemNode node) {
TreeNode parentNode = node.getParent();
if (parentNode instanceof BuckFileErrorNode) {
BuckFileErrorNode buckParentNode = (BuckFileErrorNode) parentNode;
DataContext dataContext = DataManager.getInstance().getDataContext();
Project project = DataKeys.PROJECT.getData(dataContext);
String relativePath = buckParentNode.getText().replace(project.getBasePath(), "");
VirtualFile virtualFile = project.getBaseDir().findFileByRelativePath(relativePath);
if (virtualFile != null) {
OpenFileDescriptor openFileDescriptor =
new OpenFileDescriptor(project, virtualFile, node.getLine() - 1, node.getColumn() - 1);
openFileDescriptor.navigate(true);
}
}
}
@javax.annotation.Nullable
@Deprecated
protected Navigatable findSuitableNavigatableForLine(@Nonnull Project project, @Nonnull VirtualFile file, int line) {
// lets find first non-ws psi element
final Document doc = FileDocumentManager.getInstance().getDocument(file);
final PsiFile psi = doc == null ? null : PsiDocumentManager.getInstance(project).getPsiFile(doc);
if (psi == null) {
return null;
}
int offset = doc.getLineStartOffset(line);
int endOffset = doc.getLineEndOffset(line);
for (int i = offset + 1; i < endOffset; i++) {
PsiElement el = psi.findElementAt(i);
if (el != null && !(el instanceof PsiWhiteSpace)) {
offset = el.getTextOffset();
break;
}
}
return new OpenFileDescriptor(project, file, offset);
}
public void navigate(boolean requestFocus) {
Editor editor = FileUtils.editorFromPsiFile(getContainingFile());
if (editor == null) {
OpenFileDescriptor descriptor = new OpenFileDescriptor(getProject(), getContainingFile().getVirtualFile(),
getTextOffset());
ApplicationUtils.invokeLater(() -> ApplicationUtils
.writeAction(() -> FileEditorManager.getInstance(getProject()).openTextEditor(descriptor, false)));
}
}
/**
* 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;
}
public static void openFileEditor(File file, Project project){
ApplicationManager.getApplication().invokeAndWait(()->{
VirtualFile vf = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(file);
OpenFileDescriptor descriptor = new OpenFileDescriptor(project, vf);
FileEditorManager.getInstance(project).openTextEditor(descriptor, false);
});
}
public static void openFile(final VirtualFile virtualFile, final Project project) {
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;
}
NonProjectFileWritingAccessProvider.allowWriting(virtualFile);
OpenFileDescriptor descriptor = new OpenFileDescriptor(project, virtualFile);
FileEditorManager.getInstance(project).openTextEditor(descriptor, true);
}
static void handleSubMemberNavigation(ChooseByNamePopup popup, Object element) {
if (element instanceof PsiElement && ((PsiElement)element).isValid()) {
PsiElement psiElement = getElement(((PsiElement)element), popup);
psiElement = psiElement.getNavigationElement();
VirtualFile file = PsiUtilCore.getVirtualFile(psiElement);
if (file != null && popup.getLinePosition() != -1) {
OpenFileDescriptor descriptor = new OpenFileDescriptor(psiElement.getProject(), file, popup.getLinePosition(), popup.getColumnPosition());
Navigatable n = descriptor.setUseCurrentWindow(popup.isOpenInCurrentWindowRequested());
if (n.canNavigate()) {
n.navigate(true);
return;
}
}
if (file != null && popup.getMemberPattern() != null) {
NavigationUtil.activateFileWithPsiElement(psiElement, !popup.isOpenInCurrentWindowRequested());
Navigatable member = findMember(popup.getMemberPattern(), popup.getTrimmedText(), psiElement, file);
if (member != null) {
member.navigate(true);
}
}
NavigationUtil.activateFileWithPsiElement(psiElement, !popup.isOpenInCurrentWindowRequested());
}
else {
EditSourceUtil.navigate(((NavigationItem)element), true, popup.isOpenInCurrentWindowRequested());
}
}
@Override
public Object getData(@Nonnull Key<?> dataId) {
if (myTreeBrowser != null && myTreeBrowser.isVisible()) {
return null;
}
if (CommonDataKeys.NAVIGATABLE == dataId) {
if (mySelectedFile == null || !mySelectedFile.isValid()) return null;
return new OpenFileDescriptor(myProject, mySelectedFile);
}
else if (CommonDataKeys.VIRTUAL_FILE_ARRAY == dataId) {
return getVirtualFileArray();
}
else if (VcsDataKeys.IO_FILE_ARRAY == dataId) {
return getFileArray();
}
else if (PlatformDataKeys.TREE_EXPANDER == dataId) {
if (myGroupByChangeList) {
return myTreeBrowser != null ? myTreeBrowser.getTreeExpander() : null;
}
else {
return myTreeExpander;
}
}
else if (VcsDataKeys.UPDATE_VIEW_SELECTED_PATH == dataId) {
return mySelectedUrl;
}
else if (VcsDataKeys.UPDATE_VIEW_FILES_ITERABLE == dataId) {
return myTreeIterable;
}
else if (VcsDataKeys.LABEL_BEFORE == dataId) {
return myBefore;
}
else if (VcsDataKeys.LABEL_AFTER == dataId) {
return myAfter;
}
return super.getData(dataId);
}
private static void addDirectoryToProjectView(
Project project, File projectViewFile, ArtifactLocation generatedResDir) {
ProjectViewEdit edit =
ProjectViewEdit.editLocalProjectView(
project,
builder -> {
ListSection<GenfilesPath> existingSection =
builder.getLast(GeneratedAndroidResourcesSection.KEY);
ListSection.Builder<GenfilesPath> directoryBuilder =
ListSection.update(GeneratedAndroidResourcesSection.KEY, existingSection);
directoryBuilder.add(new GenfilesPath(generatedResDir.getRelativePath()));
builder.replace(existingSection, directoryBuilder);
return true;
});
if (edit == null) {
Messages.showErrorDialog(
"Could not modify project view. Check for errors in your project view and try again",
"Error");
return;
}
edit.apply();
VirtualFile projectView = VfsUtil.findFileByIoFile(projectViewFile, false);
if (projectView != null) {
FileEditorManager.getInstance(project)
.openEditor(new OpenFileDescriptor(project, projectView), true);
}
}
@Override
public void showSource(@Nonnull OpenFileDescriptor descriptor, @Nonnull DiffPanelImpl diffPanel) {
Window window = diffPanel.getOwnerWindow();
if (window == null) {
return;
}
else if (window instanceof Frame) {
OPEN_EDITOR.showSource(descriptor, diffPanel);
}
else {
OPEN_EDITOR_AND_CLOSE_DIFF.showSource(descriptor, diffPanel);
}
}
@Nullable
private static HyperlinkInfo getHyperlinkInfo(IssueOutput issue) {
Navigatable navigatable = issue.getNavigatable();
if (navigatable != null) {
return project -> navigatable.navigate(true);
}
VirtualFile vf = resolveVirtualFile(issue.getFile());
return vf != null
? project ->
new OpenFileDescriptor(project, vf, issue.getLine() - 1, issue.getColumn() - 1)
.navigate(true)
: null;
}
@Override
public void navigate(final Project project) {
ApplicationManager.getApplication().runReadAction(() -> {
OpenFileDescriptor descriptor = getDescriptor();
if (descriptor != null) {
FileEditorManager.getInstance(project).openTextEditor(descriptor, true);
}
});
}
private void openFile(String fileNameOrPath, int line, boolean requestFocus) {
VirtualFile vf = findFile(fileNameOrPath);
if (vf == null) {
return;
}
new OpenFileDescriptor(project, vf, line - 1, -1).navigate(requestFocus);
}
@Nullable
public OpenFileDescriptor getOpenFileDescriptor() {
VirtualFile virtualFile = getVirtualFile();
if (virtualFile == null) {
return null;
}
return new OpenFileDescriptor(getProject(), virtualFile, getPsiElement().getTextOffset());
}
@Override
public void handleDoubleClickOrEnter(SimpleTree tree, InputEvent inputEvent) {
final SourceLocation location = getLocation();
if (location != null && location.getSourceName() != null) {
GraphQLTreeNodeNavigationUtil.openSourceLocation(myProject, location, false);
} else if (error instanceof GraphQLInternalSchemaError) {
String stackTrace = ExceptionUtil.getThrowableText(((GraphQLInternalSchemaError) error).getException());
PsiFile file = PsiFileFactory.getInstance(myProject).createFileFromText("graphql-error.txt", PlainTextLanguage.INSTANCE, stackTrace);
new OpenFileDescriptor(myProject, file.getVirtualFile()).navigate(true);
}
}
@Nullable
private static OpenFileDescriptor getOpenFileDescriptor(final RefElement refElement) {
final VirtualFile[] file = new VirtualFile[1];
final int[] offset = new int[1];
ApplicationManager.getApplication().runReadAction(new Runnable() {
@Override
public void run() {
PsiElement psiElement = refElement.getElement();
if (psiElement != null) {
final PsiFile containingFile = psiElement.getContainingFile();
if (containingFile != null) {
file[0] = containingFile.getVirtualFile();
offset[0] = psiElement.getTextOffset();
}
}
else {
file[0] = null;
}
}
});
if (file[0] != null && file[0].isValid()) {
return new OpenFileDescriptor(refElement.getRefManager().getProject(), file[0], offset[0]);
}
return null;
}
public void doExecute() {
try {
int index = fileName.lastIndexOf('.');
File tempFile = File.createTempFile(
fileName.substring(fileName.lastIndexOf(File.separatorChar) + 1, index != -1 ? index:fileName.length()),
index != -1 ? fileName.substring(index):""
);
String s = "// + Preprocessed Text for " + fileName + " ("+start + "," + end + "), selection follows below:\n";
StringTokenizer tokenizer = new StringTokenizer(editor.getDocument().getCharsSequence().subSequence(start, end).toString(), "\n");
while (tokenizer.hasMoreElements()) {
s += "// " + tokenizer.nextToken() + "\n";
}
s += myText;
FileUtil.writeToFile(tempFile, s.getBytes());
VirtualFile virtualFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(tempFile);
if (virtualFile != null) {
Project project = editor.getProject();
OpenFileDescriptor descriptor = new OpenFileDescriptor(project, virtualFile);
FileEditorManager.getInstance(project).openTextEditor(descriptor, true);
} else {
Logger.getInstance(getClass().getName()).error(
"Unexpected problem finding virtual file for "+tempFile.getPath());
}
} catch (IOException ex) {
Logger.getInstance(getClass().getName()).error(ex);
}
}
@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;
}
@Override
public boolean handleLink(@Nonnull final String refSuffix, @Nonnull final Editor editor) {
final int pos = refSuffix.lastIndexOf(':');
if (pos <= 0 || pos == refSuffix.length() - 1) {
LOG.error("Malformed suffix: " + refSuffix);
return true;
}
final String path = refSuffix.substring(0, pos);
final VirtualFile vFile = LocalFileSystem.getInstance().findFileByPath(path);
if (vFile == null) {
LOG.error("Unknown file: " + path);
return true;
}
final int offset;
try {
offset = Integer.parseInt(refSuffix.substring(pos + 1));
}
catch (NumberFormatException e) {
LOG.error("Malformed suffix: " + refSuffix);
return true;
}
new OpenFileDescriptor(editor.getProject(), vFile, offset).navigate(true);
return true;
}
@Nullable
public OpenFileDescriptor getCurrentOpenFileDescriptor() {
final EditorEx editor = myEditorSource.getEditor();
final DiffContent content = myEditorSource.getContent();
if (content == null || editor == null) {
return null;
}
return content.getOpenFileDescriptor(editor.getCaretModel().getOffset());
}
public static void navigate(@Nullable final PsiElement psiElement) {
if (psiElement != null && psiElement.isValid()) {
final PsiElement navigationElement = psiElement.getNavigationElement();
final int offset = navigationElement instanceof PsiFile ? -1 : navigationElement.getTextOffset();
final VirtualFile virtualFile = navigationElement.getContainingFile().getVirtualFile();
if (virtualFile != null && virtualFile.isValid()) {
new OpenFileDescriptor(navigationElement.getProject(), virtualFile, offset).navigate(true);
}
}
}
@Override
protected void write(@NotNull final Project project, @NotNull final PhpClass phpClass, @NotNull final String className) {
new WriteCommandAction(project) {
@Override
protected void run(@NotNull Result result) throws Throwable {
String fileTemplate = "form_type_defaults";
if(PhpElementsUtil.getClassMethod(project, "\\Symfony\\Component\\Form\\AbstractType", "configureOptions") != null) {
fileTemplate = "form_type_configure";
}
PsiElement bundleFile = null;
try {
bundleFile = PhpBundleFileFactory.createBundleFile(phpClass, fileTemplate, "Form\\" + className, new HashMap<String, String>() {{
put("name", fr.adrienbrault.idea.symfony2plugin.util.StringUtils.underscore(phpClass.getName() + className));
}});
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Error:" + e.getMessage());
return;
}
if(bundleFile != null) {
new OpenFileDescriptor(getProject(), bundleFile.getContainingFile().getVirtualFile(), 0).navigate(true);
}
}
@Override
public String getGroupID() {
return "Create FormType";
}
}.execute();
}
@Override
public void actionPerformed(@NotNull AnActionEvent event) {
Project project = getEventProject(event);
if(project == null) {
this.setStatus(event, false);
return;
}
PsiDirectory bundleDirContext = BundleClassGeneratorUtil.getBundleDirContext(event);
if(bundleDirContext == null) {
return;
}
final PhpClass phpClass = BundleClassGeneratorUtil.getBundleClassInDirectory(bundleDirContext);
if(phpClass == null) {
return;
}
new WriteCommandAction(project) {
@Override
protected void run(@NotNull Result result) throws Throwable {
PsiElement psiFile = PhpBundleFileFactory.invokeCreateCompilerPass(phpClass, null);
if(psiFile != null) {
new OpenFileDescriptor(getProject(), psiFile.getContainingFile().getVirtualFile(), 0).navigate(true);
}
}
@Override
public String getGroupID() {
return "Create CompilerClass";
}
}.execute();
}
@Nullable
protected Navigatable createExtendedNavigatable(PsiElement psi, String searchText, int modifiers) {
VirtualFile file = PsiUtilCore.getVirtualFile(psi);
Pair<Integer, Integer> position = getLineAndColumn(searchText);
boolean positionSpecified = position.first >= 0 || position.second >= 0;
if (file != null && positionSpecified) {
OpenFileDescriptor descriptor = new OpenFileDescriptor(psi.getProject(), file, position.first, position.second);
return descriptor.setUseCurrentWindow(openInCurrentWindow(modifiers));
}
return null;
}
@Override
public void run() {
VirtualFile relativeDirectory = VfsUtil.findRelativeFile(targetPathRelative, project.getBaseDir());
if(relativeDirectory != null) {
PsiDirectory directory = PsiManager.getInstance(project).findDirectory(relativeDirectory);
if(directory != null) {
PsiFile virtualFile = createFile(directory, fileName, this.content);
if(virtualFile != null) {
new OpenFileDescriptor(project, virtualFile.getVirtualFile(), 0).navigate(true);
}
}
}
}
public void actionPerformed(AnActionEvent actionEvent) {
Project project = actionEvent.getProject();
FloobitsPlugin floobitsPlugin = FloobitsPlugin.getInstance(project);
ContextImpl context = floobitsPlugin.context;
File file = new File(Settings.floorcJsonPath);
if (!file.exists()) {
boolean created;
try {
created = file.createNewFile();
} catch (IOException e) {
context.errorMessage("Can't create ~/.floorc.json");
Flog.error(e);
return;
}
if (!created) {
context.errorMessage("Can't create ~/.floorc.json");
return;
}
}
VirtualFile virtualFile = LocalFileSystem.getInstance().refreshAndFindFileByPath(Settings.floorcJsonPath);
if (virtualFile == null) {
context.errorMessage("No virtual file");
return;
}
if (project == null) {
context.errorMessage("Can't open ~/.floorc.json");
return;
}
OpenFileDescriptor openFileDescriptor = new OpenFileDescriptor(project, virtualFile);
FileEditorManager.getInstance(project).openTextEditor(openFileDescriptor, true);
}