下面列出了com.intellij.psi.XmlRecursiveElementVisitor#com.intellij.openapi.actionSystem.PlatformDataKeys 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 获取 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();
}
@Override
public String expand(final DataContext dataContext) {
final Project project = dataContext.getData(CommonDataKeys.PROJECT);
if (project == null) {
return null;
}
VirtualFile file = dataContext.getData(PlatformDataKeys.VIRTUAL_FILE);
if (file == null) {
return null;
}
final VirtualFile sourceRoot = ProjectRootManager.getInstance(project).getFileIndex().getSourceRootForFile(file);
if (sourceRoot == null) {
return null;
}
return FileUtil.getRelativePath(getIOFile(sourceRoot), getIOFile(file));
}
@Override
public Object getData(@Nonnull Key<?> dataId) {
if (FocusDiffSide.DATA_KEY == dataId) {
int index = getFocusedEditorIndex();
if (index < 0) return null;
switch (index) {
case 0:
return new BranchFocusedSide(FragmentSide.SIDE1);
case 1:
return new MergeFocusedSide();
case 2:
return new BranchFocusedSide(FragmentSide.SIDE2);
}
}
else if (PlatformDataKeys.DIFF_VIEWER == dataId) return MergePanel2.this;
return super.getData(dataId);
}
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
Project project = e.getData(PlatformDataKeys.PROJECT);
if (project == null) {
return;
}
ToolWindow tw = ToolWindowManager.getInstance(project).getToolWindow(
MypyToolWindowFactory.MYPY_PLUGIN_ID);
if (!tw.isVisible()) {
tw.show(null);
}
MypyTerminal terminal = MypyToolWindowFactory.getMypyTerminal(project);
if (terminal == null) {
return;
}
if (terminal.getRunner().isRunning()) {
return;
}
terminal.runMypyDaemonUIWrapper();
}
@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]);
}
@Override
public String getData(@Nonnull DataProvider dataProvider) {
final VirtualFile virtualFile = dataProvider.getDataUnchecked(PlatformDataKeys.VIRTUAL_FILE);
if (virtualFile == null) {
return null;
}
final FileType fileType = virtualFile.getFileType();
if (fileType.isBinary() || fileType.isReadOnly()) {
return null;
}
final Project project = dataProvider.getDataUnchecked(CommonDataKeys.PROJECT);
if (project == null) {
return null;
}
final Document document = FileDocumentManager.getInstance().getDocument(virtualFile);
if (document == null) {
return null;
}
return document.getText();
}
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);
}
private void getTranslation(AnActionEvent event) {
Editor editor = event.getData(PlatformDataKeys.EDITOR);
if (editor == null) {
return;
}
SelectionModel model = editor.getSelectionModel();
String selectedText = model.getSelectedText();
if (TextUtils.isEmpty(selectedText)) {
selectedText = getCurrentWords(editor);
if (TextUtils.isEmpty(selectedText)) {
return;
}
}
String queryText = strip(addBlanks(selectedText));
new Thread(new RequestRunnable(mTranslator, editor, queryText)).start();
}
@Override
public void update(AnActionEvent e) {
final Project project = e.getData(PlatformDataKeys.PROJECT);
boolean enabled = project != null;
if (!enabled) {
return;
}
NoSqlConfiguration configuration = NoSqlConfiguration.getInstance(project);
e.getPresentation().setVisible(
configuration != null &&
(StringUtils.isNotBlank(configuration.getShellPath(DatabaseVendor.MONGO)) ||
StringUtils.isNotBlank(configuration.getShellPath(DatabaseVendor.REDIS))
) &&
noSqlExplorerPanel.getConfiguration() != null &&
noSqlExplorerPanel.getConfiguration().isSingleServer()
);
e.getPresentation().setEnabled(
noSqlExplorerPanel.getSelectedMongoDatabase() != null ||
noSqlExplorerPanel.getSelectedRedisDatabase() != null
);
}
@Override
public String expand(final DataContext dataContext) {
final Project project = dataContext.getData(CommonDataKeys.PROJECT);
if (project == null) {
return null;
}
VirtualFile file = dataContext.getData(PlatformDataKeys.VIRTUAL_FILE);
if (file == null) {
return null;
}
final VirtualFile sourceRoot = ProjectRootManager.getInstance(project).getFileIndex().getSourceRootForFile(file);
if (sourceRoot == null) {
return null;
}
return getPath(sourceRoot);
}
private void selectInTargetFile(final VirtualFile targetFile) {
UIUtil.invokeLaterIfNeeded(new Runnable() {
public void run() {
Project project = deviceResult.anActionEvent.getProject();
Editor editor = deviceResult.anActionEvent.getData(PlatformDataKeys.EDITOR);
MySelectInContext selectInContext = new MySelectInContext(targetFile, editor, project);
ProjectViewImpl projectView = (ProjectViewImpl) ProjectView.getInstance(project);
AbstractProjectViewPane currentProjectViewPane = projectView.getCurrentProjectViewPane();
SelectInTarget target = currentProjectViewPane.createSelectInTarget();
if (target != null && target.canSelect(selectInContext)) {
target.selectIn(selectInContext, false);
} else {
selectInContext = new MySelectInContext(targetFile.getParent(), editor, project);
if (target != null && target.canSelect(selectInContext)) {
target.selectIn(selectInContext, false);
}
}
}
});
}
@Override
public void actionPerformed(AnActionEvent e) {
Editor editor = e.getData(PlatformDataKeys.EDITOR);
String actionId = e.getActionManager().getId(this);
String selectorClassName = "org.hunmr.common.selector."
+ actionId.substring("emacsIDEAs.AceJumpAndReplace.".length())
+ "Selector";
try {
Class<? extends Selector> selectorClass = (Class<? extends Selector>) Class.forName(selectorClassName);
EditorUtils.copyRange(selectorClass, editor);
AceJumpAction.getInstance().switchEditorIfNeed(e);
AceJumpAction.getInstance().addCommandAroundJump(new ReplaceAfterJumpCommand(editor, selectorClass));
AceJumpAction.getInstance().performAction(e);
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
}
@Override
public void actionPerformed(AnActionEvent event) {
final Project project = getEventProject(event);
final Editor editor = event.getData(PlatformDataKeys.EDITOR);
XmlSorterDialog dialog = new XmlSorterDialog(project);
PropertiesComponent pc = PropertiesComponent.getInstance();
execute(project,
editor,
pc.getInt(PC_KEY_INPUT_CASE, 0) == 0,
dialog.getPrefixSpacePositionValueAt(pc.getInt(PC_KEY_PREFIX_SPACE_POS, 0)),
pc.getBoolean(PC_KEY_SPACE_BETWEEN_PREFIX, true),
pc.getBoolean(PC_KEY_INSERT_XML_INFO, true),
pc.getBoolean(PC_KEY_DELETE_COMMENT, false),
dialog.getCodeIndentValueAt(pc.getInt(PC_KEY_CODE_INDENT, 1)),
pc.getBoolean(PC_KEY_SEPARATE_NON_TRANSLATABLE, false));
}
@Override
public String expand(final DataContext dataContext) {
final Project project = dataContext.getData(CommonDataKeys.PROJECT);
if (project == null) {
return null;
}
VirtualFile file = dataContext.getData(PlatformDataKeys.VIRTUAL_FILE);
if (file == null) {
return null;
}
if (!file.isDirectory()) {
file = file.getParent();
if (file == null) {
return null;
}
}
final VirtualFile sourceRoot = ProjectRootManager.getInstance(project).getFileIndex().getSourceRootForFile(file);
if (sourceRoot == null) return null;
return FileUtil.getRelativePath(getIOFile(sourceRoot), getIOFile(file));
}
@Override
public final Object getData(@Nonnull Key<?> dataId) {
if (PlatformDataKeys.FILE_EDITOR == dataId) {
return getSelectedEditor();
}
else if (CommonDataKeys.VIRTUAL_FILE == dataId) {
return myFile.isValid() ? myFile : null;
}
else if (CommonDataKeys.VIRTUAL_FILE_ARRAY == dataId) {
return myFile.isValid() ? new VirtualFile[]{myFile} : null;
}
else {
JComponent component = getPreferredFocusedComponent();
if (component instanceof DataProvider && component != this) {
return ((DataProvider)component).getData(dataId);
}
return null;
}
}
@Override
@Nullable
public Object getData(@Nonnull @NonNls Key<?> dataId) {
if (PlatformDataKeys.CONTENT_MANAGER == dataId || PlatformDataKeys.NONEMPTY_CONTENT_MANAGER == dataId && getContentCount() > 1) {
return DesktopContentManagerImpl.this;
}
for (DataProvider dataProvider : myDataProviders) {
Object data = dataProvider.getData(dataId);
if (data != null) {
return data;
}
}
if (myUI instanceof DataProvider) {
return ((DataProvider)myUI).getData(dataId);
}
DataProvider provider = DataManager.getDataProvider(this);
return provider == null ? null : provider.getData(dataId);
}
@Override
public void invoke(@Nonnull Project project, @Nonnull PsiElement[] elements, DataContext dataContext) {
LOG.assertTrue(elements.length == 1);
if (dataContext == null) {
dataContext = DataManager.getInstance().getDataContext();
}
final Editor editor = dataContext.getData(PlatformDataKeys.EDITOR);
for(InlineActionHandler handler: Extensions.getExtensions(InlineActionHandler.EP_NAME)) {
if (handler.canInlineElement(elements[0])) {
handler.inlineElement(project, editor, elements [0]);
return;
}
}
invokeInliner(editor, elements[0]);
}
private static boolean edit(DataContext context, String search, Function<ColorAndFontOptions, SearchableConfigurable> function) {
ColorAndFontOptions options = new ColorAndFontOptions();
SearchableConfigurable page = function.apply(options);
Configurable[] configurables = options.getConfigurables();
try {
if (page != null) {
Runnable runnable = search == null ? null : page.enableSearch(search);
Window window = UIUtil.getWindow(context.getData(PlatformDataKeys.CONTEXT_COMPONENT));
if (window != null) {
ShowSettingsUtil.getInstance().editConfigurable(window, page, runnable);
}
else {
ShowSettingsUtil.getInstance().editConfigurable(context.getData(CommonDataKeys.PROJECT), page, runnable);
}
}
}
finally {
for (Configurable configurable : configurables) configurable.disposeUIResources();
options.disposeUIResources();
}
return page != null;
}
@Override
public PsiElement[] getData(@Nonnull DataProvider dataProvider) {
final Object[] objects = dataProvider.getDataUnchecked(PlatformDataKeys.SELECTED_ITEMS);
if (objects != null) {
final PsiElement[] elements = new PsiElement[objects.length];
for (int i = 0, objectsLength = objects.length; i < objectsLength; i++) {
Object object = objects[i];
if (!(object instanceof PsiElement)) return null;
if (!((PsiElement)object).isValid()) return null;
elements[i] = (PsiElement)object;
}
return elements;
}
return null;
}
public void update(AnActionEvent event) {
Project project = event.getData(PlatformDataKeys.PROJECT);
if (project == null || !Symfony2ProjectComponent.isEnabled(project)) {
this.setStatus(event, false);
return;
}
Pair<PsiFile, PhpClass> pair = findPhpClass(event);
if(pair == null) {
return;
}
PsiFile psiFile = pair.getFirst();
if(!(psiFile instanceof YAMLFile) && !(psiFile instanceof XmlFile) && !(psiFile instanceof PhpFile)) {
this.setStatus(event, false);
}
}
@Nonnull
protected DataContext getContext() {
Editor editor = getEditor();
DataContext parent = DataManager.getInstance().getDataContext((Component)myStatusBar);
VirtualFile selectedFile = getSelectedFile();
return SimpleDataContext.getSimpleContext(ContainerUtil.<Key, Object>immutableMapBuilder().put(CommonDataKeys.VIRTUAL_FILE, selectedFile)
.put(CommonDataKeys.VIRTUAL_FILE_ARRAY, selectedFile == null ? VirtualFile.EMPTY_ARRAY : new VirtualFile[]{selectedFile})
.put(CommonDataKeys.PROJECT, getProject()).put(PlatformDataKeys.CONTEXT_COMPONENT, editor == null ? null : editor.getComponent()).build(),
parent);
}
@Override
public Object getData(@Nonnull Key dataId) {
if (PlatformDataKeys.SELECTED_ITEM == dataId) {
return myList.getSelectedValue();
}
if (PlatformDataKeys.SELECTED_ITEMS == dataId) {
return myList.getSelectedValues();
}
if (PlatformDataKeys.SPEED_SEARCH_COMPONENT == dataId) {
if (mySpeedSearchPatternField != null && mySpeedSearchPatternField.isVisible()) {
return mySpeedSearchPatternField;
}
}
return null;
}
@Override
public void actionPerformed(AnActionEvent actionEvent) {
Project project = actionEvent.getProject();
String apiKey = PropertiesComponent.getInstance().getValue(TINY_PNG_API_KEY);
if (TextUtils.isEmpty(apiKey)) {
apiKey = Messages.showInputDialog(project, "What's your ApiKey?", "ApiKey", Messages.getQuestionIcon());
PropertiesComponent.getInstance().setValue(TINY_PNG_API_KEY, apiKey);
}
VirtualFile[] selectedFiles = PlatformDataKeys.VIRTUAL_FILE_ARRAY.getData(actionEvent.getDataContext());
Tinify.setKey(apiKey);
ProgressDialog dialog = new ProgressDialog();
sExecutorService.submit(() -> {
//writing to file
int i = 1;
successCount = 0;
failCount = 0;
List<VirtualFile> failFileList = new ArrayList<>();
for (VirtualFile file : selectedFiles) {
failFileList.addAll(processFile(dialog, i + "/" + selectedFiles.length, file));
i++;
}
dialog.setLabelMsg("Success :" + successCount + " Fail :" + failCount);
dialog.setButtonOKVisible();
});
dialog.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
runningFlag.set(false);
}
});
dialog.setLabelMsg("processing");
JFrame frame = WindowManager.getInstance().getFrame(project);
dialog.setMinimumSize(new Dimension(frame.getWidth() / 4, frame.getHeight() / 4));
dialog.setLocationRelativeTo(frame);
dialog.pack();
dialog.setVisible(true);
}
@Override
public Object getData(@Nonnull Key<?> dataId) {
if (myEditor.isDisposed() || myEditor.isRendererMode()) return null;
if (CommonDataKeys.EDITOR == dataId) {
return myEditor;
}
if (CommonDataKeys.CARET == dataId) {
return myEditor.getCaretModel().getCurrentCaret();
}
if (PlatformDataKeys.DELETE_ELEMENT_PROVIDER == dataId) {
return myEditor.getDeleteProvider();
}
if (PlatformDataKeys.CUT_PROVIDER == dataId) {
return myEditor.getCutProvider();
}
if (PlatformDataKeys.COPY_PROVIDER == dataId) {
return myEditor.getCopyProvider();
}
if (PlatformDataKeys.PASTE_PROVIDER == dataId) {
return myEditor.getPasteProvider();
}
if (CommonDataKeys.EDITOR_VIRTUAL_SPACE == dataId) {
LogicalPosition location = myEditor.myLastMousePressedLocation;
if (location == null) {
location = myEditor.getCaretModel().getLogicalPosition();
}
return EditorUtil.inVirtualSpace(myEditor, location);
}
return null;
}
/**
* Get the class where currently the curser is
*/
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);
}
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
Project project = e.getData(PlatformDataKeys.PROJECT);
if (project == null) {
return;
}
ToolWindow tw = ToolWindowManager.getInstance(project).getToolWindow(
MypyToolWindowFactory.MYPY_PLUGIN_ID);
if (!tw.isVisible()) {
return;
}
MypyTerminal terminal = MypyToolWindowFactory.getMypyTerminal(project);
if (terminal == null) {
return;
}
if (terminal.getRunner().isRunning()) {
return;
}
MypyError error = terminal.getErrorsList().getSelectedValue();
if (error == null) { // no errors
return;
}
if (error.getLevel() == MypyError.HEADER) {
terminal.toggleExpand(error);
int index = terminal.getErrorsList().getSelectedIndex();
terminal.renderList();
terminal.getErrorsList().setSelectedIndex(index);
}
}
@Override
public void update(AnActionEvent e) {
final DataContext dataContext = e.getDataContext();
final Project project = dataContext.getData(CommonDataKeys.PROJECT);
final VirtualFile virtualFile = dataContext.getData(PlatformDataKeys.VIRTUAL_FILE);
e.getPresentation().setEnabled(project!=null && virtualFile!=null);
}
protected Project getProjectFrom(AnActionEvent e) {
if (e instanceof ChainActionEvent) {
ChainActionEvent chainActionEvent = (ChainActionEvent) e;
Project project = chainActionEvent.getProject();
if (project != null) {
return project;
}
}
return e.getData(PlatformDataKeys.PROJECT);
}
@Override
@Nullable
public Object getData(@Nonnull @NonNls Key dataId) {
if (PlatformDataKeys.SELECTED_ITEM == dataId) {
return myList.getSelectedValue();
}
if (PlatformDataKeys.SELECTED_ITEMS == dataId) {
return myList.getSelectedValues();
}
return null;
}
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);
}