下面列出了com.intellij.psi.impl.compiled.ClsClassImpl#com.intellij.openapi.actionSystem.LangDataKeys 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static void executeMatched(@Nonnull DataContext dataContext, @Nonnull String pattern) {
List<String> commands = RunAnythingCache.getInstance(fetchProject(dataContext)).getState().getCommands();
Module module = dataContext.getData(LangDataKeys.MODULE);
if (module == null) {
LOG.info("RunAnything: module hasn't been found, command will be executed in context of 'null' module.");
}
for (RunAnythingProvider provider : RunAnythingProvider.EP_NAME.getExtensions()) {
Object value = provider.findMatchingValue(dataContext, pattern);
if (value != null) {
//noinspection unchecked
provider.execute(dataContext, value);
commands.remove(pattern);
commands.add(pattern);
break;
}
}
}
/**
* 获取 PSI 的几种方式
*
* @param e the e
*/
private void getPsiFile(AnActionEvent e) {
// 从 action 中获取
PsiFile psiFileFromAction = e.getData(LangDataKeys.PSI_FILE);
Project project = e.getProject();
if (project != null) {
VirtualFile virtualFile = e.getData(PlatformDataKeys.VIRTUAL_FILE);
if (virtualFile != null) {
// 从 VirtualFile 获取
PsiFile psiFileFromVirtualFile = PsiManager.getInstance(project).findFile(virtualFile);
// 从 document
Document documentFromEditor = Objects.requireNonNull(e.getData(PlatformDataKeys.EDITOR)).getDocument();
PsiFile psiFileFromDocument = PsiDocumentManager.getInstance(project).getPsiFile(documentFromEditor);
// 在 project 范围内查找特定 PsiFile
FilenameIndex.getFilesByName(project, "fileName", GlobalSearchScope.projectScope(project));
}
}
// 找到特定 PSI 元素的使用位置
// ReferencesSearch.search();
}
public boolean canMark(AnActionEvent e) {
Module module = e.getData(LangDataKeys.MODULE);
VirtualFile[] vFiles = e.getData(CommonDataKeys.VIRTUAL_FILE_ARRAY);
if (module == null || vFiles == null) {
return false;
}
ModuleRootManager moduleRootManager = ModuleRootManager.getInstance(module);
final ContentEntry[] contentEntries = moduleRootManager.getContentEntries();
for (VirtualFile vFile : vFiles) {
if (!vFile.isDirectory()) {
return false;
}
for (ContentEntry contentEntry : contentEntries) {
for (ContentFolder contentFolder : contentEntry.getFolders(ContentFolderScopes.all())) {
if (Comparing.equal(contentFolder.getFile(), vFile)) {
if (contentFolder.getType() == myContentFolderType) {
return false;
}
}
}
}
}
return true;
}
@Override
public void invoke(@Nonnull final Project project, Editor editor, PsiFile file, DataContext dataContext) {
editor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE);
PsiElement element = dataContext.getData(LangDataKeys.PSI_ELEMENT);
if (element == null) {
element = BaseRefactoringAction.getElementAtCaret(editor, file);
}
if (element != null) {
for(InlineActionHandler handler: Extensions.getExtensions(InlineActionHandler.EP_NAME)) {
if (handler.canInlineElementInEditor(element, editor)) {
handler.inlineElement(project, editor, element);
return;
}
}
if (invokeInliner(editor, element)) return;
String message = RefactoringBundle.getCannotRefactorMessage(RefactoringBundle.message("error.wrong.caret.position.method.or.local.name"));
CommonRefactoringUtil.showErrorHint(project, editor, message, REFACTORING_NAME, null);
}
}
public static PsiDirectory getExtensionDirectory(@NotNull AnActionEvent event) {
Project project = event.getData(PlatformDataKeys.PROJECT);
if (project == null) {
return null;
}
DataContext dataContext = event.getDataContext();
IdeView view = LangDataKeys.IDE_VIEW.getData(dataContext);
if (view == null) {
return null;
}
PsiDirectory[] directories = view.getDirectories();
if (directories.length == 0) {
return null;
}
return FilesystemUtil.findParentExtensionDirectory(directories[0]);
}
@Nonnull
@Override
protected String expandPath(@Nonnull String path) {
Project project = getProject();
if (project != null) {
path = PathMacroManager.getInstance(project).expandPath(path);
}
Module module = myFileChooserDescriptor.getUserData(LangDataKeys.MODULE_CONTEXT);
if (module == null) {
module = myFileChooserDescriptor.getUserData(LangDataKeys.MODULE);
}
if (module != null) {
path = PathMacroManager.getInstance(module).expandPath(path);
}
return super.expandPath(path);
}
@RequiredUIAccess
@Override
public void actionPerformed(@Nonnull AnActionEvent e) {
RunContentDescriptor descriptor = StopAction.getRecentlyStartedContentDescriptor(e.getDataContext());
ProcessHandler activeProcessHandler = descriptor != null ? descriptor.getProcessHandler() : null;
if (activeProcessHandler == null || activeProcessHandler.isProcessTerminated()) return;
try {
OutputStream input = activeProcessHandler.getProcessInput();
if (input != null) {
ConsoleView console = e.getData(LangDataKeys.CONSOLE_VIEW);
if (console != null) {
console.print("^D\n", ConsoleViewContentType.SYSTEM_OUTPUT);
}
input.close();
}
}
catch (IOException ignored) {
}
}
@CheckReturnValue
@VisibleForTesting
@SuppressWarnings("WeakerAccess")
static boolean isAvailable(@Nonnull AnActionEvent event) {
final Project project = event.getProject();
if (project == null) {
return false;
}
final IdeView view = event.getData(LangDataKeys.IDE_VIEW);
if (view == null) {
return false;
}
final ProjectRootManager rootManager = ProjectRootManager.getInstance(project);
final ProjectFileIndex fileIndex = rootManager.getFileIndex();
final Optional<PsiDirectory> sourceDirectory = Stream.of(view.getDirectories())
.filter(directory -> {
final VirtualFile virtualFile = directory.getVirtualFile();
return fileIndex.isUnderSourceRootOfType(virtualFile, JavaModuleSourceRootTypes.SOURCES);
})
.findFirst();
return sourceDirectory.isPresent();
}
@Nullable
private static PsiElement[] getPsiElements(DataContext dataContext) {
PsiElement[] elements = dataContext.getData(LangDataKeys.PSI_ELEMENT_ARRAY);
if (elements == null) {
final Object data = dataContext.getData(CommonDataKeys.PSI_ELEMENT);
if (data != null) {
elements = new PsiElement[]{(PsiElement)data};
}
else {
final Object data1 = dataContext.getData(CommonDataKeys.PSI_FILE);
if (data1 != null) {
elements = new PsiElement[]{(PsiFile)data1};
}
}
}
return elements;
}
/**
* Checked whether or not this action can be enabled.
* <p>
* <p>Requirements to be enabled: * User must be in a Java source folder.
*
* @param dataContext to figure out where the user is.
* @return {@code true} when the action is available, {@code false} when the action is not
* available.
*/
private boolean isAvailable(DataContext dataContext) {
final Project project = CommonDataKeys.PROJECT.getData(dataContext);
if (project == null) {
return false;
}
final IdeView view = LangDataKeys.IDE_VIEW.getData(dataContext);
if (view == null || view.getDirectories().length == 0) {
return false;
}
ProjectFileIndex projectFileIndex = ProjectRootManager.getInstance(project).getFileIndex();
for (PsiDirectory dir : view.getDirectories()) {
if (projectFileIndex.isUnderSourceRootOfType(
dir.getVirtualFile(), JavaModuleSourceRootTypes.SOURCES)
&& checkPackageExists(dir)) {
return true;
}
}
return false;
}
private Object calculateRoot(DataContext dataContext) {
// Narrow down the root element to the first interesting one
Module root = dataContext.getData(LangDataKeys.MODULE);
Project project = dataContext.getData(CommonDataKeys.PROJECT);
if (project == null) return null;
Object projectChild;
Object projectGrandChild = null;
CommonProcessors.FindFirstAndOnlyProcessor<Object> processor = new CommonProcessors.FindFirstAndOnlyProcessor<>();
processChildren(project, processor);
projectChild = processor.reset();
if (projectChild != null) {
processChildren(projectChild, processor);
projectGrandChild = processor.reset();
}
return ObjectUtils.chooseNotNull(projectGrandChild, ObjectUtils.chooseNotNull(projectChild, project));
}
@Nullable
private static Module getModule(AnActionEvent e) {
Module module = e.getData(LangDataKeys.MODULE);
if (module == null) {
Project project = e.getData(LangDataKeys.PROJECT);
if (project == null) {
return null;
}
final Module[] modules = ModuleManager.getInstance(project).getModules();
if (modules.length == 1) {
module = modules[0];
}
}
return module;
}
@Override
public boolean tryToMove(final PsiElement element, final Project project, final DataContext dataContext, final PsiReference reference,
final Editor editor) {
if ((element instanceof PsiFile && ((PsiFile)element).getVirtualFile() != null)
|| element instanceof PsiDirectory) {
doMove(project, new PsiElement[]{element}, dataContext.getData(LangDataKeys.TARGET_PSI_ELEMENT), null);
return true;
}
if (element instanceof PsiPlainText) {
PsiFile file = element.getContainingFile();
if (file != null) {
doMove(project, new PsiElement[]{file}, null, null);
}
return true;
}
return false;
}
@RequiredUIAccess
@Override
public final void actionPerformed(@Nonnull final AnActionEvent e) {
final IdeView view = e.getData(LangDataKeys.IDE_VIEW);
if (view == null) {
return;
}
final Project project = e.getProject();
final PsiDirectory dir = view.getOrChooseDirectory();
if (dir == null) return;
invokeDialog(project, dir, elements -> {
for (PsiElement createdElement : elements) {
view.selectElement(createdElement);
}
});
}
@Override
public void calcData(final Key<?> key, final DataSink sink)
{
T element = myPointer.getElement();
if(element == null)
{
return;
}
if(LangDataKeys.PSI_ELEMENT == key)
{
sink.put(LangDataKeys.PSI_ELEMENT, element);
}
if(UsageView.USAGE_INFO_KEY == key)
{
sink.put(UsageView.USAGE_INFO_KEY, new UsageInfo(element));
}
}
private static Pair<Editor, PsiFile> getEditorAndPsiFile(final AnActionEvent e) {
final Project project = e.getData(PlatformDataKeys.PROJECT);
if (project == null) return Pair.create(null, null);
Editor editor = e.getData(PlatformDataKeys.EDITOR);
PsiFile psiFile = e.getData(LangDataKeys.PSI_FILE);
return Pair.create(editor, psiFile);
}
@Nullable
public static PsiDirectory getBundleDirContext(@NotNull AnActionEvent event) {
Project project = event.getData(PlatformDataKeys.PROJECT);
if (project == null) {
return null;
}
DataContext dataContext = event.getDataContext();
IdeView view = LangDataKeys.IDE_VIEW.getData(dataContext);
if (view == null) {
return null;
}
PsiDirectory[] directories = view.getDirectories();
if(directories.length == 0) {
return null;
}
return FilesystemUtil.findParentBundleFolder(directories[0]);
}
@Nonnull
@Override
public List<? extends GotoRelatedItem> getItems(@Nonnull DataContext context) {
final PsiFile file = context.getData(LangDataKeys.PSI_FILE);
List<PsiElement> result;
final boolean isTest = TestFinderHelper.isTest(file);
if (isTest) {
result = TestFinderHelper.findClassesForTest(file);
} else {
result = TestFinderHelper.findTestsForClass(file);
}
if (!result.isEmpty()) {
final List<GotoRelatedItem> items = new ArrayList<GotoRelatedItem>();
for (PsiElement element : result) {
items.add(new GotoRelatedItem(element, isTest ? "Tests" : "Testee classes"));
}
return items;
}
return super.getItems(context);
}
public static PsiElement getSelectedPsiElement(AnActionEvent e) {
Editor editor = e.getData(PlatformDataKeys.EDITOR);
if ( editor==null ) { // not in editor
PsiElement selectedNavElement = e.getData(LangDataKeys.PSI_ELEMENT);
// in nav bar?
if ( selectedNavElement==null || !(selectedNavElement instanceof ParserRuleRefNode) ) {
return null;
}
return selectedNavElement;
}
// in editor
PsiFile file = e.getData(LangDataKeys.PSI_FILE);
if ( file==null ) {
return null;
}
int offset = editor.getCaretModel().getOffset();
PsiElement el = file.findElementAt(offset);
return el;
}
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
Optional<PsiFile> psiFile = Optional.ofNullable(e.getData(LangDataKeys.PSI_FILE));
String languageTag = psiFile
.map(PsiFile::getLanguage)
.map(Language::getDisplayName)
.map(String::toLowerCase)
.map(lang -> "[" + lang + "]")
.orElse("");
Editor editor = e.getRequiredData(CommonDataKeys.EDITOR);
CaretModel caretModel = editor.getCaretModel();
String selectedText = caretModel.getCurrentCaret().getSelectedText();
BrowserUtil.browse("https://stackoverflow.com/search?q=" + languageTag + selectedText);
}
private void findTestAndDo(AnActionEvent anActionEvent, BiConsumer<PsiClass, PsiMethod> action) {
PsiElement psiElement = anActionEvent.getData(CommonDataKeys.PSI_ELEMENT);
PsiFile psiFile = anActionEvent.getData(LangDataKeys.PSI_FILE);
if (psiElement == null) {
Editor editor = anActionEvent.getData(CommonDataKeys.EDITOR);
if (editor != null && psiFile != null) {
psiElement = psiFile.findElementAt(editor.getCaretModel().getOffset());
}
}
if (psiFile == null && psiElement != null) {
psiFile = psiElement.getContainingFile();
}
if (psiElement != null) {
PsiElement testElement = findNearestTestElement(psiFile, psiElement);
if (testElement instanceof PsiClass) {
PsiClass psiClass = (PsiClass) testElement;
action.accept(psiClass, null);
return;
} else if (testElement instanceof PsiMethod) {
PsiMethod psiMethod = (PsiMethod) testElement;
action.accept(psiMethod.getContainingClass(), psiMethod);
return;
}
}
action.accept(null, null);
}
@Nullable
private static PositionAdjuster createPositionAdjuster(JBPopup hint) {
final Component focusOwner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
if (focusOwner == null) return null;
JBPopup popup = PopupUtil.getPopupContainerFor(focusOwner);
if (popup != null && popup != hint && !popup.isDisposed()) {
return new PositionAdjuster(popup.getContent());
}
final Component existing = discoverPopup(LangDataKeys.POSITION_ADJUSTER_POPUP, focusOwner);
if (existing != null) {
return new PositionAdjuster2(existing, discoverPopup(LangDataKeys.PARENT_POPUP, focusOwner));
}
return null;
}
@Override
public void actionPerformed(AnActionEvent anActionEvent) {
LogicUtils.getLogic().conOrEnd(anActionEvent.getData(LangDataKeys.PSI_FILE), file -> Objects.nonNull(file) && StringUtils.containsAny(file.getLanguage().getID(), STYLE_SHEET_LANGUAGE_ID, LESS_LANGUAGE_ID, SASS_LANGUAGE_ID, HTML_LANGUAGE_ID, SCSS_LANGUAGE_ID, STYLUS_LANGUAGE_ID), file ->
Optional.ofNullable(ActionPerformer.getActionPerformer(anActionEvent.getRequiredData(CommonDataKeys.PROJECT), anActionEvent.getRequiredData(CommonDataKeys.EDITOR))).ifPresent(ap ->
Optional.of(FormatTools.getFormatTools(ap.getConstValue())).ifPresent(formatTools ->
formatTools.rollbackStyle(ap, ap.getDocument().getLineNumber(ap.getCaretModel().getOffset()))
)
)
);
}
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
PsiFile psiFile = e.getData(LangDataKeys.PSI_FILE);
Project project = e.getProject();
Editor editor = e.getData(PlatformDataKeys.EDITOR);
TypePickDialog dialog = new TypePickDialog();
dialog.setListener(type -> {build(type, psiFile, project, editor);});
dialog.pack();
dialog.setVisible(true);
}
private PsiClass getPsiClassFromContext(AnActionEvent e) {
PsiFile psiFile = e.getData(LangDataKeys.PSI_FILE);
Editor editor = e.getData(PlatformDataKeys.EDITOR);
// psiFile.getViewProvider().getVirtualFile()
if (psiFile == null || editor == null) {
return null;
}
int offset = editor.getCaretModel().getOffset();
PsiElement element = psiFile.findElementAt(offset);
return PsiTreeUtil.getParentOfType(element, PsiClass.class);
}
private PsiClass getPsiClassFromContext(AnActionEvent e) {
PsiFile psiFile = e.getData(LangDataKeys.PSI_FILE);
Editor editor = e.getData(PlatformDataKeys.EDITOR);
if (psiFile == null || editor == null) {
return null;
}
int offset = editor.getCaretModel().getOffset();
PsiElement element = psiFile.findElementAt(offset);
return PsiTreeUtil.getParentOfType(element, PsiClass.class);
}
/**
* 获取当前焦点下的类
* @param anActionEvent
* @return
*/
public static PsiClass getPsiClass(AnActionEvent anActionEvent) {
PsiFile psiFile = anActionEvent.getData(LangDataKeys.PSI_FILE);
Editor editor = anActionEvent.getData(PlatformDataKeys.EDITOR);
if (psiFile == null || editor == null) {
return null;
}
int offset = editor.getCaretModel().getOffset();
PsiElement element = psiFile.findElementAt(offset);
return PsiTreeUtil.getParentOfType(element, PsiClass.class);
}
private static void restart(@Nullable JComponent component) {
if (component != null) {
ExecutionEnvironment environment = DataManager.getInstance().getDataContext(component).getData(LangDataKeys.EXECUTION_ENVIRONMENT);
if (environment != null) {
restart(environment);
}
}
}
/**
* called by an Action in AtomicAction
*/
@Override
public void invoke(@Nonnull Project project, @Nonnull PsiElement[] elements, DataContext dataContext) {
final PsiElement targetContainer = dataContext == null ? null : dataContext.getData(LangDataKeys.TARGET_PSI_ELEMENT);
final Set<PsiElement> filesOrDirs = new HashSet<PsiElement>();
for(MoveHandlerDelegate delegate: Extensions.getExtensions(MoveHandlerDelegate.EP_NAME)) {
if (delegate.canMove(dataContext) && delegate.isValidTarget(targetContainer, elements)) {
delegate.collectFilesOrDirsFromContext(dataContext, filesOrDirs);
}
}
if (!filesOrDirs.isEmpty()) {
for (PsiElement element : elements) {
if (element instanceof PsiDirectory) {
filesOrDirs.add(element);
}
else {
final PsiFile containingFile = element.getContainingFile();
if (containingFile != null) {
filesOrDirs.add(containingFile);
}
}
}
MoveFilesOrDirectoriesUtil
.doMove(project, PsiUtilBase.toPsiElementArray(filesOrDirs), new PsiElement[]{targetContainer}, null);
return;
}
doMove(project, elements, targetContainer, dataContext, null);
}
private boolean isEnabled(AnActionEvent event) {
Project project = event.getProject();
IdeView view = event.getData(LangDataKeys.IDE_VIEW);
if (project == null || view == null) {
return false;
}
return view.getDirectories().length != 0;
}