Changing AnActionEvent origin?

Answered

Hi,

i have created a tool window with a button. When this button is pressed, then another action is executed (dynamically chosen). This action is in 99% of the time a refactoring action. The problem i have is that these actions require a correct DataContext and the dataContext when clicking on a gui is completely different sometimes.

 

Is there a way to "fake" an action event, so it looks and feels like the action is triggered via shortcut from within an editor and not through a random button in a gui?


For example:

When i click on the tool window button and dynamically the "Enter" action is chosen, then "enter" is pressed/triggered inside the tool window and NOT in the editor

 

2 comments
Comment actions Permalink
DataContext context = DataManager.getInstance().getDataContext(editor.getComponent());

+ com.intellij.openapi.actionSystem.AnActionEvent#withDataContext
1
Comment actions Permalink

Thanks for your answer, i have still some questions. Here is the current code:

    Arrays.stream(ProjectView.getInstance(project)
            .getCurrentProjectViewPane()
            .getSelectedUserObjects())
        .map(x -> (PsiFileNode) x)
        .filter(Objects::nonNull)
        .map(BasePsiNode::getVirtualFile)
        .forEach(virtualFile -> {
          var document = FileDocumentManager.getInstance().getDocument(virtualFile);
          var editor = EditorFactory.getInstance().createEditor(document, project);
          
        var context = DataManager.getInstance().getDataContext(editor.getContentComponent());

          var newActionEvent = e.withDataContext(context);
        var isNull = newActionEvent.getData(CommonDataKeys.EDITOR);
      });

You can see in the last line, that newActionEvent.getData() is always null. I wonder what iam doing wrong.

 

The goal of my code is that the user can select any file in the project view and run actions based on these selected files. 

 

EDIT: i solved it: the problem is that i need to do editor.getContentComponent() instead of editor.getComponent()

EDIT2: i have still a problem: PSI_FILE + VIRTUAL_FILE common data keys are both empty. How can i add them to the datacontext? This is what iam trying:

getDataManager().saveInDataContext(context, Key.create(CommonDataKeys.VIRTUAL_FILE.getName()), virtualFile);
var isNull = context.getData(CommonDataKeys.VIRTUAL_FILE);

EDIT3: I solved the problem. The issue was that i used the wrong method to create the editor. This is the correct way to do it:

FileEditorManager.getInstance(project).openTextEditor(new OpenFileDescriptor(e.getProject(), virtualFile), true);

If you do it this way, then getting the datacontext from this editor is correctly setting the project etc

0

Please sign in to leave a comment.