Java Code Examples for com.intellij.openapi.actionSystem.AnActionEvent#getDataContext()

The following examples show how to use com.intellij.openapi.actionSystem.AnActionEvent#getDataContext() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
    Project project = e.getProject();
    if (project != null) {
        DataContext dataContext = e.getDataContext();
        List<String> fileNames = findRelatedFiles(project, dataContext);
        if (fileNames.isEmpty()) {
            Notifications.Bus.notify(new ORNotification("testdata", "Found no testdata files", "Cannot find related files", INFORMATION, null), project);
            return;
        }

        Editor editor = e.getData(CommonDataKeys.EDITOR);
        JBPopupFactory popupFactory = JBPopupFactory.getInstance();
        RelativePoint point = editor == null ? popupFactory.guessBestPopupLocation(dataContext) : popupFactory.guessBestPopupLocation(editor);

        TestDataNavigationHandler.navigate(point, fileNames, project);
    }
}
 
Example 2
Source Project: idea-php-typo3-plugin   File: ExtensionUtility.java    License: MIT License 6 votes vote down vote up
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]);
}
 
Example 3
Source Project: consulo   File: SendToFavoritesAction.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void actionPerformed(AnActionEvent e) {
  final DataContext dataContext = e.getDataContext();
  Project project = e.getProject();
  final FavoritesManager favoritesManager = FavoritesManager.getInstance(project);

  FavoritesTreeNodeDescriptor[] roots = dataContext.getData(FavoritesTreeViewPanel.CONTEXT_FAVORITES_ROOTS_DATA_KEY);
  if (roots == null) return;

  for (FavoritesTreeNodeDescriptor root : roots) {
    FavoritesTreeNodeDescriptor listNode = root.getFavoritesRoot();
    if (listNode != null && listNode !=root && listNode.getElement() instanceof FavoritesListNode) {
      doSend(favoritesManager, new FavoritesTreeNodeDescriptor[]{root}, listNode.getElement().getName());
    }
  }
}
 
Example 4
Source Project: CppTools   File: BuildCppAction.java    License: Apache License 2.0 6 votes vote down vote up
public void update(AnActionEvent e) {
  super.update(e);

  final DataContext dataContext = e.getDataContext();
  final Project project = (Project) dataContext.getData(DataConstants.PROJECT);
  final VirtualFile file = (VirtualFile) dataContext.getData(DataConstants.VIRTUAL_FILE);

  BaseBuildHandler buildHandler = null;

  if (project != null && file != null &&
      !file.isDirectory()
     ) {
     buildHandler = BaseBuildHandler.getBuildHandler(project, file);
  }
  final boolean enabled = buildHandler != null;
  
  e.getPresentation().setEnabled(enabled);
  e.getPresentation().setVisible(enabled);

  final String s = "Do &build for " + (buildHandler != null ? file.getName():"makefile/dsp/dsw file");
  e.getPresentation().setText(s);
  e.getPresentation().setDescription(s);
}
 
Example 5
@Override
public void actionPerformed(AnActionEvent anActionEvent) {
    final DataContext dc = anActionEvent.getDataContext();
    final Project project = CommonDataKeys.PROJECT.getData(dc);
    final Refreshable panel = CheckinProjectPanel.PANEL_KEY.getData(dc);
    final CommitMessageI commitMessageI = (panel instanceof CommitMessageI) ? (CommitMessageI) panel : VcsDataKeys.COMMIT_MESSAGE_CONTROL.getData(dc);

    if (commitMessageI != null && project != null) {
        String commitMessage = "";
        // Attempt to append the message instead of overwriting it
        if (commitMessageI instanceof CommitChangeListDialog) {
            commitMessage = ((CommitChangeListDialog) commitMessageI).getCommitMessage();
        }

        SelectWorkItemsDialog dialog = new SelectWorkItemsDialog(project);
        if (dialog.showAndGet()) {
            if (StringUtils.isNotEmpty(commitMessage)) {
                commitMessage += "\n" + dialog.getComment();
            } else {
                commitMessage = dialog.getComment();
            }

            commitMessageI.setCommitMessage(commitMessage);
        }
    }
}
 
Example 6
Source Project: consulo   File: RenameProjectAction.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void actionPerformed(AnActionEvent e) {
  final DataContext dataContext = e.getDataContext();
  final Project project = dataContext.getData(CommonDataKeys.PROJECT);
  LOG.assertTrue(project instanceof ProjectEx);
  Module module;
  Module[] modules = ModuleManager.getInstance(project).getModules();
  if (modules.length == 1 && project.getName().equals(modules[0].getName())) {
    module = modules[0];
  }
  else {
    module = null;
  }
  Messages.showInputDialog(project, RefactoringBundle.message("enter.new.project.name"), RefactoringBundle.message("rename.project"),
                           Messages.getQuestionIcon(),
                           project.getName(),
                           new RenameProjectHandler.MyInputValidator((ProjectEx)project, module));
}
 
Example 7
Source Project: consulo   File: MergeFilesAction.java    License: Apache License 2.0 5 votes vote down vote up
public void actionPerformed(AnActionEvent e) {
  DataContext context = e.getDataContext();
  VirtualFile[] files = e.getData(CommonDataKeys.VIRTUAL_FILE_ARRAY);
  if (files == null || files.length != 3){
    return;
  }

  DiffRequestFactory diffRequestFactory = DiffRequestFactory.getInstance();

  try {
    Project project = e.getData(CommonDataKeys.PROJECT);

    String title = DiffBundle.message("merge.files.dialog.title");
    List<String> titles = ContainerUtil.list(files[0].getPresentableUrl(),
                                             files[1].getPresentableUrl(),
                                             files[2].getPresentableUrl());

    VirtualFile outputFile = files[1];
    List<VirtualFile> contents = ContainerUtil.list(files[0], files[1], files[2]);

    MergeRequest request = diffRequestFactory.createMergeRequestFromFiles(project, outputFile, contents, title, titles, null);
    request.putUserData(DiffUserDataKeys.HELP_ID, "cvs.merge");

    DiffManager.getInstance().showMerge(project, request);
  }
  catch (InvalidDiffRequestException err) {
    Messages.showErrorDialog(err.getLocalizedMessage(), DiffBundle.message("merge.files.dialog.title"));
  }
}
 
Example 8
@RequiredUIAccess
@Override
public final void actionPerformed(@Nonnull AnActionEvent e) {
  DataContext dataContext = e.getDataContext();
  IdeView view = dataContext.getData(LangDataKeys.IDE_VIEW);
  if (view == null) return;
  PsiDirectory dir = getTargetDirectory(dataContext, view);
  if (dir == null) return;
  Project project = dir.getProject();

  FileTemplate selectedTemplate = getTemplate(project, dir);
  if (selectedTemplate != null) {
    AnAction action = getReplacedAction(selectedTemplate);
    if (action != null) {
      action.actionPerformed(e);
    }
    else {
      FileTemplateManager.getInstance(project).addRecentName(selectedTemplate.getName());
      AttributesDefaults defaults = getAttributesDefaults(dataContext);
      Map<String, Object> properties = defaults != null ? defaults.getDefaultProperties() : null;
      CreateFromTemplateDialog dialog = new CreateFromTemplateDialog(dir, selectedTemplate, defaults, properties);
      PsiElement createdElement = dialog.create();
      if (createdElement != null) {
        elementCreated(dialog, createdElement);
        view.selectElement(createdElement);
        if (selectedTemplate.isLiveTemplateEnabled() && createdElement instanceof PsiFile) {
          Map<String, String> defaultValues = getLiveTemplateDefaults(dataContext, ((PsiFile)createdElement));
          startLiveTemplate((PsiFile)createdElement, notNull(defaultValues, Collections.emptyMap()));
        }
      }
    }
  }
}
 
Example 9
Source Project: idea-php-typo3-plugin   File: ActionUtil.java    License: MIT License 5 votes vote down vote up
/**
 * Finds the directories on which an action was performed on.
 *
 * @param actionEvent The source action event
 * @return an array of directories the action was performed on
 */
public static PsiDirectory[] findDirectoryFromActionEvent(AnActionEvent actionEvent) {

    DataContext dataContext = actionEvent.getDataContext();
    IdeView data = LangDataKeys.IDE_VIEW.getData(dataContext);

    if (data == null) {
        return new PsiDirectory[]{};
    }

    return data.getDirectories();
}
 
Example 10
/**
 * @param event Carries information on the invocation place
 */
@Override
public void actionPerformed(@NotNull AnActionEvent event) {
    final Project project = getEventProject(event);
    if (project == null) {
        this.setStatus(event, false);
        return;
    }

    DataContext dataContext = event.getDataContext();

    final Editor editor = CommonDataKeys.EDITOR.getData(dataContext);
    final PsiFile file = CommonDataKeys.PSI_FILE.getData(dataContext);
    final PhpClass targetClass = editor == null || file == null ? null : PhpCodeEditUtil.findClassAtCaret(editor, file);

    if (targetClass == null) {
        JOptionPane.showMessageDialog(null, "Could not find containing class");
        return;
    }

    String actionName = Messages.showInputDialog(project, "New action name:", "New Extbase ActionController Action", TYPO3CMSIcons.TYPO3_ICON);

    if (StringUtils.isBlank(actionName)) {
        return;
    }

    actionName = Character.toLowerCase(actionName.charAt(0)) + actionName.substring(1);

    if (!actionName.endsWith("Action")) {
        actionName += "Action";
    }

    if (!PhpNameUtil.isValidMethodName(actionName)) {
        JOptionPane.showMessageDialog(null, "Invalid method name");
        return;
    }

    write(project, targetClass, actionName);
}
 
Example 11
Source Project: patcher   File: ClassesExportAction.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void actionPerformed(AnActionEvent e) {
    try {
        com.intellij.openapi.actionSystem.DataContext dataContext = e.getDataContext();
        PsiJavaFile javaFile = (PsiJavaFile) ((PsiFile) DataKeys.PSI_FILE.getData(dataContext)).getContainingFile();
        String sourceName = javaFile.getName();
        Module module = (Module) DataKeys.MODULE.getData(dataContext);
        String compileRoot = CompilerModuleExtension.getInstance(module).getCompilerOutputPath().getPath();
        getVirtualFile(sourceName, CompilerModuleExtension.getInstance(module).getCompilerOutputPath().getChildren(), compileRoot);
        VirtualFileManager.getInstance().syncRefresh();
    } catch (Exception ex) {
        ex.printStackTrace();
        Messages.showErrorDialog("Please build your module or project!!!", "error");
    }
}
 
Example 12
Source Project: consulo   File: ApplyNonConflicts.java    License: Apache License 2.0 5 votes vote down vote up
public void actionPerformed(AnActionEvent e) {
  DataContext dataContext = e.getDataContext();
  List<Change> notConflicts = ContainerUtil.collect(getNotConflicts(dataContext));
  for (Change change : notConflicts) {
    Change.apply(change, MergeList.BRANCH_SIDE);
  }
  if (myDiffPanel != null) {
    myDiffPanel.requestScrollEditors();
  }
}
 
Example 13
Source Project: CppTools   File: BaseEditorAction.java    License: Apache License 2.0 5 votes vote down vote up
public void update(AnActionEvent anActionEvent) {
  final DataContext dataContext = anActionEvent.getDataContext();
  final PsiFile psiFile = findFileFromDataContext(dataContext);
  Editor editor = findEditorFromDataContext(dataContext);

  anActionEvent.getPresentation().setVisible(
    psiFile instanceof CppFile &&
    editor != null &&
    acceptableState(editor, psiFile) &&
    Communicator.getInstance(psiFile.getProject()).isServerUpAndRunning()
  );
}
 
Example 14
@Override
public void actionPerformed(AnActionEvent e) {
	final DataContext context = e.getDataContext();
	MavenProjectsManager projectsManager = MavenActionUtil.getProjectsManager(context);
	if (projectsManager != null) {
		perform(projectsManager, Arrays.asList(mavenProject.mavenProject), e);
	}
}
 
Example 15
Source Project: Crucible4IDEA   File: AddCommentAction.java    License: MIT License 5 votes vote down vote up
public void actionPerformed(AnActionEvent e) {
  final DataContext dataContext = e.getDataContext();
  final Project project = e.getData(PlatformDataKeys.PROJECT);
  if (project == null) return;
  final ToolWindow toolWindow = e.getData(PlatformDataKeys.TOOL_WINDOW);
  if (toolWindow != null) {
    addGeneralComment(project, dataContext);
  }
  else {
    addVersionedComment(project);
  }
}
 
Example 16
public void update(AnActionEvent event) {
    Project project = event.getProject();
    DataContext dataContext = event.getDataContext();
    event.getPresentation().setEnabled(
        project != null &&
        isEnabled(project, dataContext) &&
        !isLocked(project)
    );
}
 
Example 17
Source Project: dbunit-extractor   File: CopyToDbUnit.java    License: MIT License 5 votes vote down vote up
public void actionPerformed(@NotNull AnActionEvent e) {
    DataContext dataContext = e.getDataContext();
    DataGrid dataGrid = DatabaseDataKeys.DATA_GRID_KEY.getData(dataContext);
    ExtractorProperties extractorProperties = ProjectSettings.getExtractorProperties(dataContext);
    XmlOutput xmlOutput = actionPerformed(extractorProperties, dataGrid, dataContext);
    copyOutput(xmlOutput);
    showPopup(dataContext, xmlOutput);
}
 
Example 18
Source Project: CppTools   File: BaseEditorAction.java    License: Apache License 2.0 4 votes vote down vote up
public void actionPerformed(AnActionEvent e) {
  final DataContext dataContext = e.getDataContext();
  final Editor editor = findEditorFromDataContext(dataContext);
  PsiFile file = findFileFromDataContext(dataContext);
  execute(editor, file, (Project) dataContext.getData(DataConstants.PROJECT));
}
 
Example 19
public static void buildFile(AnActionEvent event, final Project project, String templatePath, String fileName) {
    DataContext dataContext = event.getDataContext();
    IdeView view = LangDataKeys.IDE_VIEW.getData(dataContext);
    if (view == null) {
        return;
    }

    PsiDirectory[] directories = view.getDirectories();
    if(directories.length == 0) {
        return;
    }

    final PsiDirectory initialBaseDir = directories[0];
    if (initialBaseDir == null) {
        return;
    }

    if(initialBaseDir.findFile(fileName) != null) {
        Messages.showInfoMessage("File exists", "Error");
        return;
    }

    String content;
    try {
        content = StreamUtil.readText(ServiceActionUtil.class.getResourceAsStream(templatePath), "UTF-8");
    } catch (IOException e) {
        e.printStackTrace();
        return;
    }

    final PsiFileFactory factory = PsiFileFactory.getInstance(project);

    final PsiFile file = factory.createFileFromText(fileName, XmlFileType.INSTANCE, content);

    ApplicationManager.getApplication().runWriteAction(() -> {
        CodeStyleManager.getInstance(project).reformat(file);
        initialBaseDir.add(file);
    });

    PsiFile psiFile = initialBaseDir.findFile(fileName);
    if(psiFile != null) {
        view.selectElement(psiFile);
    }

}
 
Example 20
public static void buildFile(AnActionEvent event, final Project project, String templatePath) {
    String extension = (templatePath.endsWith(".yml") || templatePath.endsWith(".yaml")) ? "yml" : "xml" ;

    String fileName = Messages.showInputDialog(project, "File name (without extension)", String.format("Create %s Service", extension), Symfony2Icons.SYMFONY);
    if(fileName == null || StringUtils.isBlank(fileName)) {
        return;
    }

    FileType fileType = (templatePath.endsWith(".yml") || templatePath.endsWith(".yaml")) ? YAMLFileType.YML : XmlFileType.INSTANCE ;

    if(!fileName.endsWith("." + extension)) {
        fileName = fileName.concat("." + extension);
    }

    DataContext dataContext = event.getDataContext();
    IdeView view = LangDataKeys.IDE_VIEW.getData(dataContext);
    if (view == null) {
        return;
    }

    PsiDirectory[] directories = view.getDirectories();
    if(directories.length == 0) {
        return;
    }

    final PsiDirectory initialBaseDir = directories[0];
    if (initialBaseDir == null) {
        return;
    }

    if(initialBaseDir.findFile(fileName) != null) {
        Messages.showInfoMessage("File exists", "Error");
        return;
    }

    String content;
    try {
        content = StreamUtil.readText(ServiceActionUtil.class.getResourceAsStream(templatePath), "UTF-8").replace("\r\n", "\n");
    } catch (IOException e) {
        e.printStackTrace();
        return;
    }

    final PsiFileFactory factory = PsiFileFactory.getInstance(project);

    String bundleName = "Acme\\DemoBundle";

    SymfonyBundleUtil symfonyBundleUtil = new SymfonyBundleUtil(project);
    SymfonyBundle symfonyBundle = symfonyBundleUtil.getContainingBundle(initialBaseDir);

    if(symfonyBundle != null) {
        bundleName = StringUtils.strip(symfonyBundle.getNamespaceName(), "\\");
    }

    String underscoreBundle = bundleName.replace("\\", ".").toLowerCase();
    if(underscoreBundle.endsWith("bundle")) {
        underscoreBundle = underscoreBundle.substring(0, underscoreBundle.length() - 6);
    }

    content = content.replace("{{ BundleName }}", bundleName).replace("{{ BundleNameUnderscore }}", underscoreBundle);

    final PsiFile file = factory.createFileFromText(fileName, fileType, content);

    ApplicationManager.getApplication().runWriteAction(() -> {
        CodeStyleManager.getInstance(project).reformat(file);
        initialBaseDir.add(file);
    });

    PsiFile psiFile = initialBaseDir.findFile(fileName);
    if(psiFile != null) {
        view.selectElement(psiFile);
    }

}