com.intellij.openapi.actionSystem.LangDataKeys Java Examples

The following examples show how to use com.intellij.openapi.actionSystem.LangDataKeys. 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: RunAnythingUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
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;
    }
  }
}
 
Example #2
Source File: GotoTestRelatedProvider.java    From consulo with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #3
Source File: NavBarModel.java    From consulo with Apache License 2.0 6 votes vote down vote up
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));
}
 
Example #4
Source File: BundleClassGeneratorUtil.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
@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]);
}
 
Example #5
Source File: MyActionUtils.java    From intellij-plugin-v4 with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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;
}
 
Example #6
Source File: AddReplAction.java    From BashSupport with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #7
Source File: SearchAction.java    From tutorials with MIT License 6 votes vote down vote up
@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);
}
 
Example #8
Source File: BuckTestAtCursorAction.java    From buck with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example #9
Source File: BaseHaxeGenerateAction.java    From intellij-haxe with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example #10
Source File: CSharpBaseGroupingRule.java    From consulo-csharp with Apache License 2.0 6 votes vote down vote up
@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));
	}
}
 
Example #11
Source File: GenerateAction.java    From RIBs with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #12
Source File: DeleteHandler.java    From consulo with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #13
Source File: PopupPositionManager.java    From consulo with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #14
Source File: NewClassAction.java    From json2java4idea with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example #15
Source File: EOFAction.java    From consulo with Apache License 2.0 6 votes vote down vote up
@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) {
  }
}
 
Example #16
Source File: MoveFilesOrDirectoriesHandler.java    From consulo with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #17
Source File: MacroAwareTextBrowseFolderListener.java    From consulo with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #18
Source File: ExtensionUtility.java    From idea-php-typo3-plugin with 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 #19
Source File: CreateElementActionBase.java    From consulo with Apache License 2.0 6 votes vote down vote up
@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);
    }
  });
}
 
Example #20
Source File: InlineRefactoringActionHandler.java    From consulo with Apache License 2.0 6 votes vote down vote up
@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);
  }
}
 
Example #21
Source File: MarkRootAction.java    From consulo with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #22
Source File: AbstractUploadCloudActionTest.java    From markdown-image-kit with MIT License 6 votes vote down vote up
/**
 * 获取 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();
}
 
Example #23
Source File: RenameLibraryHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void invoke(@Nonnull final Project project, @Nonnull PsiElement[] elements, @Nonnull DataContext dataContext) {
  final Library library = dataContext.getData(LangDataKeys.LIBRARY);
  LOG.assertTrue(library != null);
  Messages.showInputDialog(project,
                           IdeBundle.message("prompt.enter.new.library.name"),
                           IdeBundle.message("title.rename.library"),
                           Messages.getQuestionIcon(),
                           library.getName(),
                           new MyInputValidator(project, library));
}
 
Example #24
Source File: RerunFailedTestsAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static boolean getAction(@Nonnull AnActionEvent e, boolean execute) {
  Project project = e.getProject();
  if (project == null) {
    return false;
  }

  RunContentDescriptor contentDescriptor = ExecutionManager.getInstance(project).getContentManager().getSelectedContent();
  if (contentDescriptor == null) {
    return false;
  }

  JComponent component = contentDescriptor.getComponent();
  if (component == null) {
    return false;
  }

  ExecutionEnvironment environment = DataManager.getInstance().getDataContext(component).getData(LangDataKeys.EXECUTION_ENVIRONMENT);
  if (environment == null) {
    return false;
  }

  AnAction[] actions = contentDescriptor.getRestartActions();
  if (actions.length == 0) {
    return false;
  }

  for (AnAction action : actions) {
    if (action instanceof AbstractRerunFailedTestsAction) {
      if (execute) {
        ((AbstractRerunFailedTestsAction)action).execute(e, environment);
      }
      return true;
    }
  }
  return false;
}
 
Example #25
Source File: CSharpCreateFileAction.java    From consulo-csharp with Apache License 2.0 5 votes vote down vote up
@Override
@RequiredUIAccess
protected boolean isAvailable(DataContext dataContext)
{
	Module module = findModule(dataContext);
	if(module != null)
	{
		DotNetModuleExtension extension = ModuleUtilCore.getExtension(module, DotNetModuleExtension.class);
		if(extension != null && extension.isAllowSourceRoots())
		{
			final IdeView view = dataContext.getData(LangDataKeys.IDE_VIEW);
			if(view == null)
			{
				return false;
			}

			PsiDirectory orChooseDirectory = view.getOrChooseDirectory();
			if(orChooseDirectory == null)
			{
				return false;
			}
			PsiPackage aPackage = PsiPackageManager.getInstance(module.getProject()).findPackage(orChooseDirectory, DotNetModuleExtension.class);

			if(aPackage == null)
			{
				return false;
			}
		}
	}
	return module != null && ModuleUtilCore.getExtension(module, CSharpSimpleModuleExtension.class) != null;
}
 
Example #26
Source File: ChooserBasedAttachRootButtonDescriptor.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public VirtualFile[] selectFiles(final @Nonnull JComponent parent, @Nullable VirtualFile initialSelection,
                                 final @Nullable Module contextModule, @Nonnull LibraryEditor libraryEditor) {
  final FileChooserDescriptor chooserDescriptor = createChooserDescriptor();
  chooserDescriptor.setTitle(getChooserTitle(libraryEditor.getName()));
  chooserDescriptor.setDescription(getChooserDescription());
  if (contextModule != null) {
    chooserDescriptor.putUserData(LangDataKeys.MODULE_CONTEXT, contextModule);
  }
  return FileChooser.chooseFiles(chooserDescriptor, parent, contextModule != null ? contextModule.getProject() : null, initialSelection);
}
 
Example #27
Source File: OpenModuleSettingsAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static boolean isModuleInContext(@Nonnull AnActionEvent e) {
  final Project project = getEventProject(e);
  final Module module = e.getData(LangDataKeys.MODULE);
  if (project != null && module != null) {
    final VirtualFile moduleFolder = e.getData(CommonDataKeys.VIRTUAL_FILE);
    if (moduleFolder == null) {
      return false;
    }
    if (ProjectRootsUtil.isModuleContentRoot(moduleFolder, project) || ProjectRootsUtil.isModuleSourceRoot(moduleFolder, project)) {
      return true;
    }
  }
  return false;
}
 
Example #28
Source File: SqlGeneratorAction.java    From idea-sql-generator-tool with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void update(AnActionEvent e) {
    PsiElement psiElement = e.getData(LangDataKeys.PSI_ELEMENT);
    if (psiElement == null) {
        return;
    }

    e.getPresentation().setEnabledAndVisible(psiElement instanceof DbTable);
    super.update(e);
}
 
Example #29
Source File: ParcelablePleaseAction.java    From ParcelablePlease with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example #30
Source File: FoldLinesLikeThis.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void update(AnActionEvent e) {
  final Editor editor = e.getData(PlatformDataKeys.EDITOR);

  final boolean enabled = e.getData(LangDataKeys.CONSOLE_VIEW) != null &&  editor != null && getSingleLineSelection(editor) != null;
  e.getPresentation().setEnabled(enabled);
  e.getPresentation().setVisible(enabled);
}