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

The following examples show how to use com.intellij.openapi.actionSystem.AnActionEvent#getRequiredData() . 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
Source File: CommitMessageTemplateAction.java    From intellij-commit-message-template-plugin with MIT License 6 votes vote down vote up
public void actionPerformed(AnActionEvent e) {
    final CommitMessageI checkinPanel = getCheckinPanel(e);
    if (checkinPanel == null) {
        return;
    }

    Project project = e.getRequiredData(CommonDataKeys.PROJECT);
    CommitMessageTemplateConfig config = CommitMessageTemplateConfig.getInstance(project);

    if (config != null) {
        String commitMessage = config.getCommitMessage();
        if (!commitMessage.isEmpty()) {
            checkinPanel.setCommitMessage(commitMessage);
        }
    }
}
 
Example 2
Source File: GoToHashOrRefAction.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void actionPerformed(AnActionEvent e) {
  VcsLogUtil.triggerUsage(e);

  Project project = e.getRequiredData(CommonDataKeys.PROJECT);
  final VcsLog log = e.getRequiredData(VcsLogDataKeys.VCS_LOG);
  final VcsLogUiImpl logUi = (VcsLogUiImpl)e.getRequiredData(VcsLogDataKeys.VCS_LOG_UI);

  Set<VirtualFile> visibleRoots = VcsLogUtil.getVisibleRoots(logUi);
  GoToHashOrRefPopup popup =
    new GoToHashOrRefPopup(project, logUi.getDataPack().getRefs(), visibleRoots, text -> log.jumpToReference(text),
                                                    vcsRef -> logUi.jumpToCommit(vcsRef.getCommitHash(), vcsRef.getRoot()),
                           logUi.getColorManager(),
                           new VcsGoToRefComparator(logUi.getDataPack().getLogProviders()));
  popup.show(logUi.getTable());
}
 
Example 3
Source File: CompareFilesAction.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nullable
@Override
protected DiffRequest getDiffRequest(@Nonnull AnActionEvent e) {
  Project project = e.getProject();
  DiffRequest diffRequest = e.getData(DIFF_REQUEST);
  if (diffRequest != null) {
    return diffRequest;
  }

  VirtualFile[] data = e.getRequiredData(CommonDataKeys.VIRTUAL_FILE_ARRAY);
  if (data.length == 1) {
    VirtualFile otherFile = getOtherFile(project, data[0]);
    if (otherFile == null) return null;
    if (!hasContent(data[0])) return null;
    return DiffRequestFactory.getInstance().createFromFiles(project, data[0], otherFile);
  }
  else {
    return DiffRequestFactory.getInstance().createFromFiles(project, data[0], data[1]);
  }
}
 
Example 4
Source File: VcsShowToolWindowTabAction.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void actionPerformed(@Nonnull AnActionEvent e) {
  final Project project = e.getRequiredData(CommonDataKeys.PROJECT);
  ToolWindow toolWindow = assertNotNull(getToolWindow(project));
  final ChangesViewContentManager changesViewContentManager = (ChangesViewContentManager)ChangesViewContentManager.getInstance(project);
  final String tabName = getTabName();

  boolean contentAlreadySelected = changesViewContentManager.isContentSelected(tabName);
  if (toolWindow.isActive() && contentAlreadySelected) {
    toolWindow.hide(null);
  }
  else {
    Runnable runnable = contentAlreadySelected ? null : new Runnable() {
      @Override
      public void run() {
        changesViewContentManager.selectContent(tabName, true);
      }
    };
    toolWindow.activate(runnable, true, true);
  }
}
 
Example 5
Source File: CleanUnshelvedAction.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void actionPerformed(AnActionEvent e) {
  final Project project = e.getRequiredData(CommonDataKeys.PROJECT);
  CleanUnshelvedFilterDialog dialog = new CleanUnshelvedFilterDialog(project);
  dialog.show();
  if (dialog.isOK()) {
    if (dialog.isUnshelvedWithFilterSelected()) {
      ShelveChangesManager.getInstance(project).cleanUnshelved(false, dialog.getTimeLimitInMillis());
    }
    else if (dialog.isAllUnshelvedSelected()) {
      ShelveChangesManager.getInstance(project).clearRecycled();
    }
    else {
      ShelveChangesManager.getInstance(project).cleanUnshelved(true, System.currentTimeMillis());
    }
  }
}
 
Example 6
Source File: EditorIllustrationAction.java    From intellij-sdk-docs with Apache License 2.0 6 votes vote down vote up
/**
 * Replaces the run of text selected by the primary caret with a fixed string.
 * @param e  Event related to this action
 */
@Override
public void actionPerformed(@NotNull final AnActionEvent e) {
  // Get all the required data from data keys
  // Editor and Project were verified in update(), so they are not null.
  final Editor editor = e.getRequiredData(CommonDataKeys.EDITOR);
  final Project project = e.getRequiredData(CommonDataKeys.PROJECT);
  final Document document = editor.getDocument();
  // Work off of the primary caret to get the selection info
  Caret primaryCaret = editor.getCaretModel().getPrimaryCaret();
  int start = primaryCaret.getSelectionStart();
  int end = primaryCaret.getSelectionEnd();
  // Replace the selection with a fixed string.
  // Must do this document change in a write action context.
  WriteCommandAction.runWriteCommandAction(project, () ->
      document.replaceString(start, end, "editor_basics")
  );
  // De-select the text range that was just replaced
  primaryCaret.removeSelection();
}
 
Example 7
Source File: OpenCommitInBrowserAction.java    From azure-devops-intellij with MIT License 6 votes vote down vote up
@Override
public void actionPerformed(@NotNull final AnActionEvent anActionEvent) {
    final Project project = anActionEvent.getRequiredData(CommonDataKeys.PROJECT);
    final VcsFullCommitDetails commit = anActionEvent.getRequiredData(VcsLogDataKeys.VCS_LOG).getSelectedDetails().get(0);

    final GitRepository gitRepository = GitUtil.getRepositoryManager(project).getRepositoryForRootQuick(commit.getRoot());
    if (gitRepository == null)
        return;

    final GitRemote remote = TfGitHelper.getTfGitRemote(gitRepository);

    // guard for null so findbugs doesn't complain
    if (remote == null) {
        return;
    }

    final String remoteUrl = remote.getFirstUrl();
    if (remoteUrl == null) {
        return;
    }

    final URI urlToBrowseTo = UrlHelper.getCommitURI(remoteUrl, commit.getId().toString());
    logger.info("Browsing to url " + urlToBrowseTo.getPath());
    BrowserUtil.browse(urlToBrowseTo);
}
 
Example 8
Source File: SearchAction.java    From tutorials with MIT License 5 votes vote down vote up
/**
 * Convert selected text to a URL friendly string.
 * @param e
 */
@Override
public void actionPerformed(AnActionEvent e)
{
   final Editor editor = e.getRequiredData(CommonDataKeys.EDITOR);
   CaretModel caretModel = editor.getCaretModel();

   // For searches from the editor, we should also get file type information
   // to help add scope to the search using the Stack overflow search syntax.
   //
   // https://stackoverflow.com/help/searching

   String languageTag = "";
   PsiFile file = e.getData(CommonDataKeys.PSI_FILE);
   if(file != null)
   {
      Language lang = e.getData(CommonDataKeys.PSI_FILE).getLanguage();
      languageTag = "+[" + lang.getDisplayName().toLowerCase() + "]";
   }

   // The update method below is only called periodically so need
   // to be careful to check for selected text
   if(caretModel.getCurrentCaret().hasSelection())
   {
      String query = caretModel.getCurrentCaret().getSelectedText().replace(' ', '+') + languageTag;
      BrowserUtil.browse("https://stackoverflow.com/search?q=" + query);
   }
}
 
Example 9
Source File: SearchAction.java    From tutorials with MIT License 5 votes vote down vote up
/**
 * Only make this action visible when text is selected.
 * @param e
 */
@Override
public void update(AnActionEvent e)
{
   final Editor editor = e.getRequiredData(CommonDataKeys.EDITOR);
   CaretModel caretModel = editor.getCaretModel();
   e.getPresentation().setEnabledAndVisible(caretModel.getCurrentCaret().hasSelection());
}
 
Example 10
Source File: IgnoreUnversionedAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
public void actionPerformed(@Nonnull AnActionEvent e) {
  Project project = e.getRequiredData(CommonDataKeys.PROJECT);

  if (!ChangeListManager.getInstance(project).isFreezedWithNotification(null)) {
    List<VirtualFile> files = e.getRequiredData(UNVERSIONED_FILES_DATA_KEY).collect(Collectors.toList());
    ChangesBrowserBase<?> browser = e.getData(ChangesBrowserBase.DATA_KEY);
    Runnable callback = browser == null ? null : () -> {
      browser.rebuildList();
      //noinspection unchecked
      browser.getViewer().excludeChanges((List)files);
    };

    IgnoreUnversionedDialog.ignoreSelectedFiles(project, files, callback);
  }
}
 
Example 11
Source File: OpenFileInBrowserAction.java    From azure-devops-intellij with MIT License 5 votes vote down vote up
@Override
public void actionPerformed(final AnActionEvent anActionEvent) {
    final Project project = anActionEvent.getRequiredData(CommonDataKeys.PROJECT);
    final VirtualFile virtualFile = anActionEvent.getRequiredData(CommonDataKeys.VIRTUAL_FILE);

    final GitRepositoryManager manager = GitUtil.getRepositoryManager(project);
    final GitRepository gitRepository = manager.getRepositoryForFileQuick(virtualFile);
    if (gitRepository == null)
        return;

    final GitRemote gitRemote = TfGitHelper.getTfGitRemote(gitRepository);

    // guard for null so findbugs doesn't complain
    if (gitRemote == null || gitRepository.getRoot() == null) {
        return;
    }

    final String rootPath = gitRepository.getRoot().getPath();
    final String path = virtualFile.getPath();
    final String relativePath = path.substring(rootPath.length());

    String gitRemoteBranchName = StringUtils.EMPTY;
    final GitLocalBranch gitLocalBranch = gitRepository.getCurrentBranch();
    if (gitLocalBranch != null) {
        final GitRemoteBranch gitRemoteBranch = gitLocalBranch.findTrackedBranch(gitRepository);
        if (gitRemoteBranch != null) {
            gitRemoteBranchName = gitRemoteBranch.getNameForRemoteOperations();
        }
    }

    final URI urlToBrowseTo = UrlHelper.getFileURI(gitRemote.getFirstUrl(), encodeVirtualFilePath(relativePath), gitRemoteBranchName);
    logger.info("Browsing to url " + urlToBrowseTo.getPath());
    BrowserUtil.browse(urlToBrowseTo);
}
 
Example 12
Source File: ShowDiffWithLocalAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void actionPerformed(@Nonnull AnActionEvent e) {
  Project project = e.getRequiredData(CommonDataKeys.PROJECT);
  if (ChangeListManager.getInstance(project).isFreezedWithNotification(null)) return;

  VcsRevisionNumber currentRevisionNumber = e.getRequiredData(VcsDataKeys.HISTORY_SESSION).getCurrentRevisionNumber();
  VcsFileRevision selectedRevision = e.getRequiredData(VcsDataKeys.VCS_FILE_REVISIONS)[0];
  FilePath filePath = e.getRequiredData(VcsDataKeys.FILE_PATH);

  if (currentRevisionNumber != null && selectedRevision != null) {
    DiffFromHistoryHandler diffHandler =
            ObjectUtil.notNull(e.getRequiredData(VcsDataKeys.HISTORY_PROVIDER).getHistoryDiffHandler(), new StandardDiffFromHistoryHandler());
    diffHandler.showDiffForTwo(project, filePath, selectedRevision, new CurrentRevision(filePath.getVirtualFile(), currentRevisionNumber));
  }
}
 
Example 13
Source File: CollapseOrExpandGraphAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void actionPerformed(@Nonnull AnActionEvent e) {
  VcsLogUtil.triggerUsage(e);

  VcsLogUi ui = e.getRequiredData(VcsLogDataKeys.VCS_LOG_UI);
  executeAction((VcsLogUiImpl)ui);
}
 
Example 14
Source File: SwitchToFind.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void actionPerformed(AnActionEvent e) {
  if (KeymapUtil.isEmacsKeymap()) {
    // Emacs users are accustomed to the editor that executes 'find next' on subsequent pressing of shortcut that
    // activates 'incremental search'. Hence, we do the similar hack here for them.
    ActionManager.getInstance().getAction(IdeActions.ACTION_FIND_NEXT).actionPerformed(e);
    return;
  }

  EditorSearchSession search = e.getRequiredData(EditorSearchSession.SESSION_KEY);
  final FindModel findModel = search.getFindModel();
  FindUtil.configureFindModel(false, e.getDataContext().getData(EDITOR), findModel, false);
  search.getComponent().getSearchTextComponent().selectAll();
}
 
Example 15
Source File: CloseProjectAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
@RequiredUIAccess
@Override
public void actionPerformed(@Nonnull AnActionEvent event) {
  Project project = event.getRequiredData(CommonDataKeys.PROJECT);

  myProjectManager.closeAndDisposeAsync(project, UIAccess.current()).doWhenDone(() -> {
    myRecentProjectsManager.updateLastProjectPath();
    myWelcomeFrameManager.showIfNoProjectOpened();
  });
}
 
Example 16
Source File: VcsPushAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void actionPerformed(@Nonnull AnActionEvent e) {
  Project project = e.getRequiredData(CommonDataKeys.PROJECT);
  VcsRepositoryManager manager = ServiceManager.getService(project, VcsRepositoryManager.class);
  Collection<Repository> repositories = e.getData(CommonDataKeys.EDITOR) != null
                                        ? ContainerUtil.<Repository>emptyList()
                                        : collectRepositories(manager, e.getData(CommonDataKeys.VIRTUAL_FILE_ARRAY));
  VirtualFile selectedFile = DvcsUtil.getSelectedFile(project);
  new VcsPushDialog(project, DvcsUtil.sortRepositories(repositories), selectedFile != null ? manager.getRepositoryForFile(selectedFile) : null).show();
}
 
Example 17
Source File: VcsCherryPickAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void actionPerformed(AnActionEvent e) {
  FileDocumentManager.getInstance().saveAllDocuments();

  Project project = e.getRequiredData(CommonDataKeys.PROJECT);
  VcsLog log = e.getRequiredData(VcsLogDataKeys.VCS_LOG);

  VcsCherryPickManager.getInstance(project).cherryPick(log);
}
 
Example 18
Source File: NewFileAction.java    From idea-gitignore with MIT License 4 votes vote down vote up
/**
 * Creates new Gitignore file if it does not exist or uses an existing one and opens {@link GeneratorDialog}.
 *
 * @param e action event
 */
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
    final Project project = e.getRequiredData(CommonDataKeys.PROJECT);
    final IdeView view = e.getRequiredData(LangDataKeys.IDE_VIEW);

    VirtualFile fixedDirectory = fileType.getIgnoreLanguage().getFixedDirectory(project);
    PsiDirectory directory;

    if (fixedDirectory != null) {
        directory = PsiManager.getInstance(project).findDirectory(fixedDirectory);
    } else {
        directory = view.getOrChooseDirectory();
    }

    if (directory == null) {
        return;
    }

    GeneratorDialog dialog;
    String filename = fileType.getIgnoreLanguage().getFilename();
    PsiFile file = directory.findFile(filename);
    VirtualFile virtualFile = file == null ? directory.getVirtualFile().findChild(filename) : file.getVirtualFile();

    if (file == null && virtualFile == null) {
        CreateFileCommandAction action = new CreateFileCommandAction(project, directory, fileType);
        dialog = new GeneratorDialog(project, action);
    } else {
        Notifications.Bus.notify(new Notification(
                fileType.getLanguageName(),
                IgnoreBundle.message("action.newFile.exists", fileType.getLanguageName()),
                IgnoreBundle.message("action.newFile.exists.in", virtualFile.getPath()),
                NotificationType.INFORMATION
        ), project);

        if (file == null) {
            file = Utils.getPsiFile(project, virtualFile);
        }

        dialog = new GeneratorDialog(project, file);
    }

    dialog.show();
    file = dialog.getFile();

    if (file != null) {
        Utils.openFile(project, file);
    }
}
 
Example 19
Source File: IgnoreFileAction.java    From idea-gitignore with MIT License 4 votes vote down vote up
/**
 * Adds currently selected {@link VirtualFile} to the {@link #ignoreFile}.
 * If {@link #ignoreFile} is null, default project's Gitignore file will be used.
 * Files that cannot be covered with Gitignore file produces error notification.
 * When action is performed, Gitignore file is opened with additional content added
 * using {@link AppendFileCommandAction}.
 *
 * @param e action event
 */
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
    final VirtualFile[] files = e.getRequiredData(CommonDataKeys.VIRTUAL_FILE_ARRAY);
    final Project project = e.getRequiredData(CommonDataKeys.PROJECT);

    PsiFile ignore = null;
    if (ignoreFile != null) {
        ignore = Utils.getPsiFile(project, ignoreFile);
    }
    if (ignore == null && fileType != null) {
        ignore = Utils.getIgnoreFile(project, fileType, null, true);
    }

    if (ignore != null) {
        Set<String> paths = new HashSet<>();
        for (VirtualFile file : files) {
            final String path = getPath(ignore.getVirtualFile().getParent(), file);
            if (path.isEmpty()) {
                final VirtualFile baseDir = Utils.getModuleRootForFile(file, project);
                if (baseDir != null) {
                    Notify.show(
                            project,
                            IgnoreBundle.message(
                                    "action.ignoreFile.addError",
                                    Utils.getRelativePath(baseDir, file)
                            ),
                            IgnoreBundle.message(
                                    "action.ignoreFile.addError.to",
                                    Utils.getRelativePath(baseDir, ignore.getVirtualFile())
                            ),
                            NotificationType.ERROR
                    );
                }
            } else {
                paths.add(path);
            }
        }
        Utils.openFile(project, ignore);
        try {
            new AppendFileCommandAction(project, ignore, paths, false, false).execute();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
    }
}
 
Example 20
Source File: AnnotateVcsVirtualFileAction.java    From consulo with Apache License 2.0 4 votes vote down vote up
private static boolean isSuspended(AnActionEvent e) {
  VirtualFile file = e.getRequiredData(CommonDataKeys.VIRTUAL_FILE_ARRAY)[0];
  return VcsAnnotateUtil.getBackgroundableLock(e.getRequiredData(CommonDataKeys.PROJECT), file).isLocked();
}