Java Code Examples for com.intellij.openapi.actionSystem.LangDataKeys

The following examples show how to use com.intellij.openapi.actionSystem.LangDataKeys. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: consulo   Source File: RunAnythingUtil.java    License: 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 Project: markdown-image-kit   Source File: AbstractUploadCloudActionTest.java    License: 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 3
Source Project: consulo   Source File: MarkRootAction.java    License: 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 4
Source Project: consulo   Source File: InlineRefactoringActionHandler.java    License: 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 5
Source Project: idea-php-typo3-plugin   Source 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 6
@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 7
Source Project: consulo   Source File: EOFAction.java    License: 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 8
Source Project: json2java4idea   Source File: NewClassAction.java    License: 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 9
Source Project: consulo   Source File: DeleteHandler.java    License: 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 10
Source Project: RIBs   Source File: GenerateAction.java    License: 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 11
Source Project: consulo   Source File: NavBarModel.java    License: 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 12
Source Project: BashSupport   Source File: AddReplAction.java    License: 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 13
Source Project: consulo   Source File: MoveFilesOrDirectoriesHandler.java    License: 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 14
Source Project: consulo   Source File: CreateElementActionBase.java    License: 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 15
Source Project: consulo-csharp   Source File: CSharpBaseGroupingRule.java    License: 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 16
@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 17
Source Project: consulo   Source File: GotoTestRelatedProvider.java    License: 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 18
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 19
Source Project: tutorials   Source File: SearchAction.java    License: 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 20
Source Project: buck   Source File: BuckTestAtCursorAction.java    License: 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 21
Source Project: consulo   Source File: PopupPositionManager.java    License: 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 22
Source Project: px2rwd-intellij-plugin   Source File: ConvertRollback.java    License: MIT License 5 votes vote down vote up
@Override
public void actionPerformed(AnActionEvent anActionEvent) {
    LogicUtils.getLogic().conOrEnd(anActionEvent.getData(LangDataKeys.PSI_FILE), file -> Objects.nonNull(file) && StringUtils.containsAny(file.getLanguage().getID(), STYLE_SHEET_LANGUAGE_ID, LESS_LANGUAGE_ID, SASS_LANGUAGE_ID, HTML_LANGUAGE_ID, SCSS_LANGUAGE_ID, STYLUS_LANGUAGE_ID), file ->
            Optional.ofNullable(ActionPerformer.getActionPerformer(anActionEvent.getRequiredData(CommonDataKeys.PROJECT), anActionEvent.getRequiredData(CommonDataKeys.EDITOR))).ifPresent(ap ->
                    Optional.of(FormatTools.getFormatTools(ap.getConstValue())).ifPresent(formatTools ->
                            formatTools.rollbackStyle(ap, ap.getDocument().getLineNumber(ap.getCaretModel().getOffset()))
                    )
            )
    );
}
 
Example 23
Source Project: OkHttpParamsGet   Source File: GetParamsAction.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
    PsiFile psiFile = e.getData(LangDataKeys.PSI_FILE);
    Project project = e.getProject();
    Editor editor = e.getData(PlatformDataKeys.EDITOR);
    TypePickDialog dialog = new TypePickDialog();
    dialog.setListener(type -> {build(type, psiFile, project, editor);});
    dialog.pack();
    dialog.setVisible(true);
}
 
Example 24
Source Project: data-mediator   Source File: ConvertAction.java    License: Apache License 2.0 5 votes vote down vote up
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);
}
 
Example 25
Source Project: data-mediator   Source File: DataMediatorAction.java    License: Apache License 2.0 5 votes vote down vote up
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 26
Source Project: CodeGen   Source File: PsiUtil.java    License: MIT License 5 votes vote down vote up
/**
 * 获取当前焦点下的类
 * @param anActionEvent
 * @return
 */
public static PsiClass getPsiClass(AnActionEvent anActionEvent) {

    PsiFile psiFile = anActionEvent.getData(LangDataKeys.PSI_FILE);
    Editor editor = anActionEvent.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 27
Source Project: consulo   Source File: ExecutionUtil.java    License: Apache License 2.0 5 votes vote down vote up
private static void restart(@Nullable JComponent component) {
  if (component != null) {
    ExecutionEnvironment environment = DataManager.getInstance().getDataContext(component).getData(LangDataKeys.EXECUTION_ENVIRONMENT);
    if (environment != null) {
      restart(environment);
    }
  }
}
 
Example 28
Source Project: consulo   Source File: MoveHandler.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * called by an Action in AtomicAction
 */
@Override
public void invoke(@Nonnull Project project, @Nonnull PsiElement[] elements, DataContext dataContext) {
  final PsiElement targetContainer = dataContext == null ? null : dataContext.getData(LangDataKeys.TARGET_PSI_ELEMENT);
  final Set<PsiElement> filesOrDirs = new HashSet<PsiElement>();
  for(MoveHandlerDelegate delegate: Extensions.getExtensions(MoveHandlerDelegate.EP_NAME)) {
    if (delegate.canMove(dataContext) && delegate.isValidTarget(targetContainer, elements)) {
      delegate.collectFilesOrDirsFromContext(dataContext, filesOrDirs);
    }
  }
  if (!filesOrDirs.isEmpty()) {
    for (PsiElement element : elements) {
      if (element instanceof PsiDirectory) {
        filesOrDirs.add(element);
      }
      else {
        final PsiFile containingFile = element.getContainingFile();
        if (containingFile != null) {
          filesOrDirs.add(containingFile);
        }
      }
    }
    MoveFilesOrDirectoriesUtil
      .doMove(project, PsiUtilBase.toPsiElementArray(filesOrDirs), new PsiElement[]{targetContainer}, null);
    return;
  }
  doMove(project, elements, targetContainer, dataContext, null);
}
 
Example 29
Source Project: intellij   Source File: NewBlazePackageAction.java    License: Apache License 2.0 5 votes vote down vote up
private boolean isEnabled(AnActionEvent event) {
  Project project = event.getProject();
  IdeView view = event.getData(LangDataKeys.IDE_VIEW);
  if (project == null || view == null) {
    return false;
  }
  return view.getDirectories().length != 0;
}
 
Example 30
protected ConfigurationContext createContextFromPsi(PsiElement element) {
  final MapDataContext dataContext = new MapDataContext();
  dataContext.put(CommonDataKeys.PROJECT, getProject());
  dataContext.put(LangDataKeys.MODULE, ModuleUtil.findModuleForPsiElement(element));
  dataContext.put(Location.DATA_KEY, PsiLocation.fromPsiElement(element));
  return ConfigurationContext.getFromContext(dataContext);
}