com.intellij.openapi.actionSystem.DataContext Java Examples

The following examples show how to use com.intellij.openapi.actionSystem.DataContext. 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: EnterHandler.java    From bamboo-soy with Apache License 2.0 6 votes vote down vote up
@Override
public Result postProcessEnter(
    @NotNull PsiFile file, @NotNull Editor editor, @NotNull DataContext dataContext) {
  if (file.getFileType() != SoyFileType.INSTANCE) {
    return Result.Continue;
  }

  int caretOffset = editor.getCaretModel().getOffset();
  PsiElement element = file.findElementAt(caretOffset);
  Document document = editor.getDocument();

  int lineNumber = document.getLineNumber(caretOffset) - 1;
  int lineStartOffset = document.getLineStartOffset(lineNumber);
  String lineTextBeforeCaret = document.getText(new TextRange(lineStartOffset, caretOffset));

  if (element instanceof PsiComment && element.getTextOffset() < caretOffset) {
    handleEnterInComment(element, file, editor);
  } else if (lineTextBeforeCaret.startsWith("/*")) {
    insertText(file, editor, " * \n ", 3);
  }

  return Result.Continue;
}
 
Example #2
Source File: XDebuggerTreeActionBase.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
public static List<XValueNodeImpl> getSelectedNodes(DataContext dataContext) {
  XDebuggerTree tree = XDebuggerTree.getTree(dataContext);
  if (tree == null) return Collections.emptyList();

  TreePath[] paths = tree.getSelectionPaths();
  if (paths == null || paths.length == 0) {
    return Collections.emptyList();
  }
  List<XValueNodeImpl> result = new ArrayList<>();
  for (TreePath path : paths) {
    Object lastPathComponent = path.getLastPathComponent();
    if(lastPathComponent instanceof XValueNodeImpl) {
      result.add((XValueNodeImpl)lastPathComponent);
    }
  }
  return result;
}
 
Example #3
Source File: AbstractStringManipAction.java    From StringManipulation with Apache License 2.0 6 votes vote down vote up
protected String transformSelection(Editor editor, Map<String, Object> actionContext, DataContext dataContext, String selectedText, T additionalParam) {
	String[] textParts = selectedText.split("\n");

	for (int i = 0; i < textParts.length; i++) {
		if (!StringUtils.isBlank(textParts[i])) {
			textParts[i] = transformByLine(actionContext, textParts[i]);
		}
	}

	String join = StringUtils.join(textParts, '\n');

	if (selectedText.endsWith("\n")) {
		return join + "\n";
	}
	return join;
}
 
Example #4
Source File: ImportFromServerAction.java    From aem-ide-tooling-4-intellij with Apache License 2.0 6 votes vote down vote up
@Override
protected void execute(@NotNull Project project, @NotNull DataContext dataContext, final ProgressHandler progressHandler) {
    VirtualFile[] virtualFiles = CommonDataKeys.VIRTUAL_FILE_ARRAY.getData(dataContext);
    if(virtualFiles != null) {
        switch(virtualFiles.length) {
            case 0:
                //AS TODO: Alert User about unselected folder
                break;
            case 1:
                doImport(project, virtualFiles[0]);
                break;
            default:
                //AS TODO: Alert user about too many selected folders
        }
    }
}
 
Example #5
Source File: AbstractStringManipAction.java    From StringManipulation with Apache License 2.0 6 votes vote down vote up
protected void executeMyWriteActionPerCaret(Editor editor, Caret caret, Map<String, Object> actionContext, DataContext dataContext, T additionalParam) {
final SelectionModel selectionModel = editor.getSelectionModel();
String selectedText = selectionModel.getSelectedText();

if (selectedText == null) {
	selectSomethingUnderCaret(editor, dataContext, selectionModel);
	selectedText = selectionModel.getSelectedText();

	if (selectedText == null) {
		return;
	}
}

String s = transformSelection(editor, actionContext, dataContext, selectedText, additionalParam);
s = s.replace("\r\n", "\n");
s = s.replace("\r", "\n");
      editor.getDocument().replaceString(selectionModel.getSelectionStart(), selectionModel.getSelectionEnd(), s);
  }
 
Example #6
Source File: SelectWorkItemsAction.java    From azure-devops-intellij with MIT License 6 votes vote down vote up
@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 #7
Source File: TreeMouseAdapter.java    From jetbrains-plugin-graph-database-support with Apache License 2.0 6 votes vote down vote up
@Override
public void mouseClicked(MouseEvent e) {
    Tree tree = (Tree) e.getComponent();
    TreePath pathForLocation = tree.getPathForLocation(e.getX(), e.getY());

    if (SwingUtilities.isLeftMouseButton(e)) {
        Optional.ofNullable(pathForLocation)
                .flatMap(p -> cast(p.getLastPathComponent(), PatchedDefaultMutableTreeNode.class))
                .flatMap(n -> cast(n.getUserObject(), LinkLabel.class))
                .ifPresent(LinkLabel::doClick);
    } else if (SwingUtilities.isRightMouseButton(e)) {
        DataContext dataContext = DataManager.getInstance().getDataContext(tree);
        contextMenuService.getContextMenu(pathForLocation)
                .ifPresent(dto -> dto.showPopup(dataContext));
    }
}
 
Example #8
Source File: XDebuggerUtilImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
public static Collection<XSourcePosition> getAllCaretsPositions(@Nonnull Project project, DataContext context) {
  Editor editor = getEditor(project, context);
  if (editor == null) {
    return Collections.emptyList();
  }

  final Document document = editor.getDocument();
  VirtualFile file = FileDocumentManager.getInstance().getFile(document);
  Collection<XSourcePosition> res = new ArrayList<XSourcePosition>();
  List<Caret> carets = editor.getCaretModel().getAllCarets();
  for (Caret caret : carets) {
    int line = caret.getLogicalPosition().line;
    XSourcePositionImpl position = XSourcePositionImpl.create(file, line);
    if (position != null) {
      res.add(position);
    }
  }
  return res;
}
 
Example #9
Source File: KillRingSaveAction.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void execute(final Editor editor, final DataContext dataContext) {
  SelectionModel selectionModel = editor.getSelectionModel();
  if (!selectionModel.hasSelection()) {
    return;
  }

  final int start = selectionModel.getSelectionStart();
  final int end = selectionModel.getSelectionEnd();
  if (start >= end) {
    return;
  }
  KillRingUtil.copyToKillRing(editor, start, end, false);
  if (myRemove) {
    ApplicationManager.getApplication().runWriteAction(new DocumentRunnable(editor.getDocument(),editor.getProject()) {
      @Override
      public void run() {
        editor.getDocument().deleteString(start, end);
      }
    });
  } 
}
 
Example #10
Source File: GenerateDeployableJarTaskProvider.java    From intellij with Apache License 2.0 6 votes vote down vote up
@Override
public boolean executeTask(
    DataContext context, RunConfiguration configuration, ExecutionEnvironment env, Task task) {
  Label target = getTarget(configuration);
  if (target == null) {
    return false;
  }

  try {
    File outputJar = getDeployableJar(configuration, env, target);
    LocalFileSystem.getInstance().refreshIoFiles(ImmutableList.of(outputJar));
    ((ApplicationConfiguration) configuration).setVMParameters("-cp " + outputJar.getPath());
    return true;
  } catch (ExecutionException e) {
    ExecutionUtil.handleExecutionError(
        env.getProject(), env.getExecutor().getToolWindowId(), env.getRunProfile(), e);
  }
  return false;
}
 
Example #11
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 #12
Source File: FilePathRelativeToSourcepathMacro.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public String expand(final DataContext dataContext) {
  final Project project = dataContext.getData(CommonDataKeys.PROJECT);
  if (project == null) {
    return null;
  }
  VirtualFile file = dataContext.getData(PlatformDataKeys.VIRTUAL_FILE);
  if (file == null) {
    return null;
  }
  final VirtualFile sourceRoot = ProjectRootManager.getInstance(project).getFileIndex().getSourceRootForFile(file);
  if (sourceRoot == null) {
    return null;
  }
  return FileUtil.getRelativePath(getIOFile(sourceRoot), getIOFile(file));
}
 
Example #13
Source File: ServerConnectionManager.java    From aem-ide-tooling-4-intellij with Apache License 2.0 5 votes vote down vote up
@Nullable
private ProcessHandler getHandler(@NotNull DataContext dataContext) {
    final RunContentDescriptor contentDescriptor = LangDataKeys.RUN_CONTENT_DESCRIPTOR.getData(dataContext);
    if(contentDescriptor != null) {
        // toolwindow case
        return contentDescriptor.getProcessHandler();
    } else {
        // main menu toolbar
        final Project project = CommonDataKeys.PROJECT.getData(dataContext);
        final RunContentDescriptor selectedContent =
            project == null ? null : ExecutionManager.getInstance(project).getContentManager().getSelectedContent();
        return selectedContent == null ? null : selectedContent.getProcessHandler();
    }
}
 
Example #14
Source File: BlazeRenderErrorContributor.java    From intellij with Apache License 2.0 5 votes vote down vote up
@Override
public RenderErrorContributor getContributor(
    @Nullable EditorDesignSurface surface,
    RenderResult result,
    @Nullable DataContext dataContext) {
  return new BlazeRenderErrorContributor(surface, result, dataContext);
}
 
Example #15
Source File: XAddToWatchesFromEditorActionHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
protected void perform(@Nonnull XDebugSession session, DataContext dataContext) {
  final String text = getTextToEvaluate(dataContext, session);
  if (text == null) return;

  ((XDebugSessionImpl)session).getSessionTab().getWatchesView().addWatchExpression(XExpressionImpl.fromText(text), -1, true);
}
 
Example #16
Source File: RTMergerTreeStructureProvider.java    From react-templates-plugin with MIT License 5 votes vote down vote up
@Override
public void performPaste(@NotNull DataContext dataContext) {
    RTFile[] rtFiles = RTFile.DATA_KEY.getData(dataContext);
    if (rtFiles != null) {
        System.out.println(rtFiles.length);
    }
}
 
Example #17
Source File: SaveAsAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void update(AnActionEvent e) {
  final DataContext dataContext = e.getDataContext();
  final Project project = dataContext.getData(CommonDataKeys.PROJECT);
  final VirtualFile virtualFile = dataContext.getData(PlatformDataKeys.VIRTUAL_FILE);
  e.getPresentation().setEnabled(project!=null && virtualFile!=null);
}
 
Example #18
Source File: VcsDataWrapper.java    From consulo with Apache License 2.0 5 votes vote down vote up
VcsDataWrapper(final AnActionEvent e) {
  final DataContext dataContext = e.getDataContext();
  myProject = dataContext.getData(CommonDataKeys.PROJECT);
  if (myProject == null || myProject.isDefault()) {
    myManager = null;
    myVcses = null;
    return;
  }
  myManager = ProjectLevelVcsManager.getInstance(myProject);
}
 
Example #19
Source File: InspectorTreeActionBase.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static DefaultMutableTreeNode getSelectedNode(final DataContext dataContext) {
  final Tree tree = InspectorPanel.getTree(dataContext);
  if (tree == null) return null;

  final TreePath path = tree.getSelectionPath();
  if (path == null) return null;

  return (DefaultMutableTreeNode)path.getLastPathComponent();
}
 
Example #20
Source File: InspectorTreeActionBase.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static DiagnosticsNode getSelectedValue(DataContext dataContext) {
  final DefaultMutableTreeNode node = getSelectedNode(dataContext);
  if (node == null) {
    return null;
  }
  final Object userObject = node.getUserObject();
  return userObject instanceof DiagnosticsNode ? (DiagnosticsNode)userObject : null;
}
 
Example #21
Source File: RefactoringQuickFix.java    From consulo with Apache License 2.0 5 votes vote down vote up
default void doFix(@Nonnull PsiElement element) {
  final PsiElement elementToRefactor = getElementToRefactor(element);
  if (elementToRefactor == null) {
    return;
  }
  final Consumer<DataContext> consumer = dataContext -> {
    dataContext = enhanceDataContext(dataContext);
    final RefactoringActionHandler handler = getHandler();
    handler.invoke(element.getProject(), new PsiElement[] {elementToRefactor}, dataContext);
  };
  DataManager.getInstance().getDataContextFromFocus().doWhenDone(consumer);
}
 
Example #22
Source File: ObjectFinder.java    From tmc-intellij with MIT License 5 votes vote down vote up
public Project findCurrentProject() {
    logger.info("Trying to findCurrentProject. @ObjectFinder");
    DataContext dataContext = DataManager.getInstance().getDataContextFromFocus().getResult();

    if (dataContext == null) {
        Project[] projects = ProjectManager.getInstance().getOpenProjects();

        if (projects.length > 0) {
            return projects[projects.length - 1];
        }
        return null;
    }
    return DataKeys.PROJECT.getData(dataContext);
}
 
Example #23
Source File: EditorActionHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
/**
 * Implementations can override this method to define whether handler is enabled for a specific caret in a given editor.
 */
protected boolean isEnabledForCaret(@Nonnull Editor editor, @Nonnull Caret caret, DataContext dataContext) {
  if (inCheck) {
    return true;
  }
  inCheck = true;
  try {
    //noinspection deprecation
    return isEnabled(editor, dataContext);
  }
  finally {
    inCheck = false;
  }
}
 
Example #24
Source File: SelectWordAtCaretAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void doExecute(Editor editor, @Nullable Caret caret, DataContext dataContext) {
  SelectionModel selectionModel = editor.getSelectionModel();
  Document document = editor.getDocument();

  if (EditorUtil.isPasswordEditor(editor)) {
    selectionModel.setSelection(0, document.getTextLength());
    return;
  }

  int lineNumber = editor.getCaretModel().getLogicalPosition().line;
  int caretOffset = editor.getCaretModel().getOffset();
  if (lineNumber >= document.getLineCount()) {
    return;
  }

  boolean camel = editor.getSettings().isCamelWords();
  List<TextRange> ranges = new ArrayList<TextRange>();

  int textLength = document.getTextLength();
  if (caretOffset == textLength) caretOffset--;
  if (caretOffset < 0) return;

  SelectWordUtil.addWordOrLexemeSelection(camel, editor, caretOffset, ranges);

  if (ranges.isEmpty()) return;

  final TextRange selectionRange = new TextRange(selectionModel.getSelectionStart(), selectionModel.getSelectionEnd());

  TextRange minimumRange = new TextRange(0, document.getTextLength());
  for (TextRange range : ranges) {
    if (range.contains(selectionRange) && !range.equals(selectionRange)) {
      if (minimumRange.contains(range)) {
        minimumRange = range;
      }
    }
  }

  selectionModel.setSelection(minimumRange.getStartOffset(), minimumRange.getEndOffset());
}
 
Example #25
Source File: DefaultRawTypedHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void beforeExecute(@Nonnull Editor editor, char c, @Nonnull DataContext context, @Nonnull ActionPlan plan) {
  if (editor.isViewer() || !editor.getDocument().isWritable()) return;

  TypedActionHandler handler = myAction.getHandler();

  if (handler instanceof TypedActionHandlerEx) {
    ((TypedActionHandlerEx)handler).beforeExecute(editor, c, context, plan);
  }
}
 
Example #26
Source File: BuckCommandBeforeRunTaskProvider.java    From buck with Apache License 2.0 5 votes vote down vote up
@Override
public Promise<Boolean> configureTask(
    @NotNull DataContext context,
    @NotNull RunConfiguration configuration,
    @NotNull BuckCommandBeforeRunTask task) {
  Project project = configuration.getProject();
  final BuckCommandToolEditorDialog dialog = new BuckCommandToolEditorDialog(project);
  dialog.setArguments(task.getArguments());
  if (dialog.showAndGet()) {
    task.setArguments(dialog.getArguments());
    Promises.resolvedPromise(true);
  }
  return Promises.resolvedPromise(false);
}
 
Example #27
Source File: ExecutionManagerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private void runBeforeTask(@Nonnull List<BeforeRunTask> beforeRunTasks,
                           int index,
                           long executionSessionId,
                           @Nonnull ExecutionEnvironment environment,
                           @Nonnull UIAccess uiAccess,
                           @Nonnull DataContext dataContext,
                           @Nonnull RunConfiguration runConfiguration,
                           @Nonnull AsyncResult<Void> finishResult) {
  if (beforeRunTasks.size() == index) {
    finishResult.setDone();
    return;
  }

  if (myProject.isDisposed()) {
    return;
  }

  BeforeRunTask task = beforeRunTasks.get(index);

  BeforeRunTaskProvider<BeforeRunTask> provider = BeforeRunTaskProvider.getProvider(myProject, task.getProviderId());
  if (provider == null) {
    LOG.warn("Cannot find BeforeRunTaskProvider for id='" + task.getProviderId() + "'");
    runBeforeTask(beforeRunTasks, index + 1, executionSessionId, environment, uiAccess, dataContext, runConfiguration, finishResult);
    return;
  }

  myApplication.executeOnPooledThread(() -> {
    ExecutionEnvironment taskEnvironment = new ExecutionEnvironmentBuilder(environment).contentToReuse(null).build();
    taskEnvironment.setExecutionId(executionSessionId);
    taskEnvironment.putUserData(EXECUTION_SESSION_ID_KEY, executionSessionId);

    AsyncResult<Void> result = provider.executeTaskAsync(uiAccess, dataContext, runConfiguration, taskEnvironment, task);
    result.doWhenDone(() -> runBeforeTask(beforeRunTasks, index + 1, executionSessionId, environment, uiAccess, dataContext, runConfiguration, finishResult));
    result.doWhenRejected((Runnable)finishResult::setRejected);
  });
}
 
Example #28
Source File: EditorWriteActionHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
/**
 * @deprecated Use/override
 * {@link #executeWriteAction(Editor, Caret, DataContext)}
 * instead.
 */
@RequiredWriteAction
public void executeWriteAction(Editor editor, DataContext dataContext) {
  if (inExecution) {
    return;
  }
  try {
    inExecution = true;
    executeWriteAction(editor, editor.getCaretModel().getCurrentCaret(), dataContext);
  }
  finally {
    inExecution = false;
  }
}
 
Example #29
Source File: CommitCompletionContributor.java    From consulo with Apache License 2.0 5 votes vote down vote up
@RequiredReadAction
@Override
public void fillCompletionVariants(CompletionParameters parameters, CompletionResultSet result) {
  PsiFile file = parameters.getOriginalFile();
  Document document = PsiDocumentManager.getInstance(file.getProject()).getDocument(file);
  if (document != null) {
    DataContext dataContext = document.getUserData(CommitMessage.DATA_CONTEXT_KEY);
    if (dataContext != null) {
      result.stopHere();
      if (parameters.getInvocationCount() > 0) {
        ChangeList[] lists = dataContext.getData(VcsDataKeys.CHANGE_LISTS);
        if (lists != null) {
          String prefix = TextFieldWithAutoCompletionListProvider.getCompletionPrefix(parameters);
          CompletionResultSet insensitive = result.caseInsensitive().withPrefixMatcher(new CamelHumpMatcher(prefix));
          for (ChangeList list : lists) {
            for (Change change : list.getChanges()) {
              VirtualFile virtualFile = change.getVirtualFile();
              if (virtualFile != null) {
                LookupElementBuilder element = LookupElementBuilder.create(virtualFile.getName()).
                  withIcon(VirtualFilePresentation.getAWTIcon(virtualFile));
                insensitive.addElement(element);
              }
            }
          }
        }
      }
    }
  }
}
 
Example #30
Source File: MoveHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
/**
 * called by an Action in AtomicAction when refactoring is invoked from Editor
 */
@Override
public void invoke(@Nonnull Project project, Editor editor, PsiFile file, DataContext dataContext) {
  int offset = editor.getCaretModel().getOffset();
  editor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE);
  PsiElement element = file.findElementAt(offset);
  while(true){
    if (element == null) {
      String message = RefactoringBundle.getCannotRefactorMessage(RefactoringBundle.message("the.caret.should.be.positioned.at.the.class.method.or.field.to.be.refactored"));
      CommonRefactoringUtil.showErrorHint(project, editor, message, REFACTORING_NAME, null);
      return;
    }

    if (tryToMoveElement(element, project, dataContext, null, editor)) {
      return;
    }
    final TextRange range = element.getTextRange();
    if (range != null) {
      int relative = offset - range.getStartOffset();
      final PsiReference reference = element.findReferenceAt(relative);
      if (reference != null) {
        final PsiElement refElement = reference.resolve();
        if (refElement != null && tryToMoveElement(refElement, project, dataContext, reference, editor)) return;
      }
    }

    element = element.getParent();
  }
}