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

The following are top voted examples for showing how to use com.intellij.openapi.actionSystem.DataContext. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: AppleScript-IDEA   File: AppleScriptNamesValidator.java   Source Code and License 6 votes vote down vote up
private boolean isRenamingHandlerWithValidName(@NotNull String name, Project project) {
  PsiElement elementToRename;
  String oldName;
  Editor editor = FileEditorManager.getInstance(project).getSelectedTextEditor();
  if (editor != null) {
    DataContext dataContext = DataManager.getInstance().getDataContext(editor.getComponent());
    elementToRename = PsiElementRenameHandler.getElement(dataContext);
    if (elementToRename instanceof AppleScriptHandler) {
      oldName = ((AppleScriptHandler) elementToRename).getName();
      final String[] newParts = name.split(":");
      final String[] oldParts = oldName != null ? oldName.split(":") : null;
      if (oldParts == null || oldParts.length != newParts.length) {
        return false;
      }
      for (String part : newParts) {
        if (!isIdentifier(part)) {
          return false;
        }
      }
      return true;
    } else
      return false;
  } else
    return false;
}
 
Example 2
Project: SmartQQ4IntelliJ   File: ReviewHandler.java   Source Code and License 6 votes vote down vote up
@Override
protected void doExecute(Editor editor, @Nullable Caret caret, DataContext dataContext) {
    super.doExecute(editor, caret, dataContext);
    VirtualFile vf = (CommonDataKeys.VIRTUAL_FILE.getData(dataContext));

    if (IMWindowFactory.getDefault() == null) {
        return;
    }
    String path = VFSUtils.getPath(vf);
    if (!TextUtils.isEmpty(path)) {
        String text = editor.getSelectionModel().getSelectedText();
        int line = EditorUtils.getEditorLine(editor);
        ReviewDialog dialog = new ReviewDialog();
        dialog.pack();
        dialog.setLocationRelativeTo(null);
        dialog.setData(path, line, text);
        dialog.setVisible(true);
        dialog.dispose();
    }
}
 
Example 3
Project: idea-php-typo3-plugin   File: ExtensionUtility.java   Source Code and 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 4
Project: bamboo-soy   File: ClosingTagHandler.java   Source Code and License 6 votes vote down vote up
public void execute(@NotNull Editor editor, char charTyped, @NotNull DataContext dataContext) {
  myOriginalHandler.execute(editor, charTyped, dataContext);
  if (isMatchForClosingTag(editor, charTyped)) {
    int offset = editor.getCaretModel().getOffset();
    PsiFile file = dataContext.getData(LangDataKeys.PSI_FILE);
    if (file == null) {
      return;
    }
    PsiElement el = file.findElementAt(offset - 1);
    TagBlockElement block = (TagBlockElement) PsiTreeUtil
        .findFirstParent(el,
            parent -> parent instanceof TagBlockElement && !(parent instanceof SoyChoiceClause));
    if (block == null) {
      return;
    }
    String closingTag = block.getOpeningTag().generateClosingTag();
    insertClosingTag(editor, offset, closingTag);
    if (editor.getProject() != null) {
      PsiDocumentManager.getInstance(editor.getProject()).commitDocument(editor.getDocument());
      CodeStyleManager.getInstance(editor.getProject()).reformat(block);
    }
  }
}
 
Example 5
Project: bamboo-soy   File: EnterHandler.java   Source Code and License 6 votes vote down vote up
@Override
public Result preprocessEnter(
    @NotNull PsiFile psiFile,
    @NotNull Editor editor,
    @NotNull Ref<Integer> caretOffset,
    @NotNull Ref<Integer> caretOffsetChange,
    @NotNull DataContext dataContext,
    @Nullable EditorActionHandler originalHandler) {
  if (psiFile instanceof SoyFile && isBetweenSiblingTags(psiFile, caretOffset.get())) {
    if (originalHandler != null) {
      originalHandler.execute(editor, dataContext);
    }
    return Result.Default;
  }
  return Result.Continue;
}
 
Example 6
Project: bamboo-soy   File: EnterHandler.java   Source Code and License 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 7
Project: Riho   File: IdeActionListener.java   Source Code and License 6 votes vote down vote up
@Override
public void beforeEditorTyping(char c, DataContext dataContext) {
    Instant now = Instant.now();
    Duration between = Duration.between(lastInputTime, now);
    lastInputTime = now;

    if (between.getSeconds() < comboCoolTimeSec) {
        comboCount++;
    } else {
        comboCount = 0;
        return;
    }

    RihoReactionNotifier publisher = project.getMessageBus().syncPublisher(RihoReactionNotifier.REACTION_NOTIFIER);
    switch (comboCount) {
        case 5: publisher.reaction(Reaction.of(FacePattern.SMILE1, Duration.ofSeconds(3))); break;
        case 10: publisher.reaction(Reaction.of(FacePattern.SMILE2, Duration.ofSeconds(3))); break;
        case 15: publisher.reaction(Reaction.of(FacePattern.SURPRISE, Duration.ofSeconds(5))); break;
        case 20:
        case 30: publisher.reaction(Reaction.of(FacePattern.AWAWA, Duration.ofSeconds(3))); break;
    }
}
 
Example 8
Project: educational-plugin   File: CCDeleteAllAnswerPlaceholdersAction.java   Source Code and License 6 votes vote down vote up
@Override
public void update(AnActionEvent e) {
  Presentation presentation = e.getPresentation();
  presentation.setEnabledAndVisible(false);

  Project project = e.getProject();
  if (project == null) {
    return;
  }
  if (!CCUtils.isCourseCreator(project)) {
    return;
  }
  DataContext context = e.getDataContext();
  VirtualFile file = CommonDataKeys.VIRTUAL_FILE.getData(context);
  if (file == null ) {
    return;
  }
  TaskFile taskFile = StudyUtils.getTaskFile(project, file);
  if (taskFile == null || taskFile.getAnswerPlaceholders().isEmpty()) {
    return;
  }
  presentation.setEnabledAndVisible(true);
}
 
Example 9
Project: educational-plugin   File: CCNewSubtaskAction.java   Source Code and License 6 votes vote down vote up
@Override
public void actionPerformed(AnActionEvent e) {
  DataContext dataContext = e.getDataContext();
  VirtualFile virtualFile = CommonDataKeys.VIRTUAL_FILE.getData(dataContext);
  Editor editor = CommonDataKeys.EDITOR.getData(dataContext);
  Project project = CommonDataKeys.PROJECT.getData(dataContext);
  if (virtualFile == null || project == null || editor == null) {
    return;
  }
  Task task = StudyUtils.getTaskForFile(project, virtualFile);
  if (task == null) return;
  if (!(task instanceof TaskWithSubtasks)) {
    task = convertToTaskWithSubtasks(task, project);
  }
  addSubtask((TaskWithSubtasks)task, project);
}
 
Example 10
Project: educational-plugin   File: CCNewSubtaskAction.java   Source Code and License 6 votes vote down vote up
@Override
public void update(AnActionEvent e) {
  DataContext dataContext = e.getDataContext();
  Presentation presentation = e.getPresentation();
  presentation.setEnabledAndVisible(false);
  VirtualFile virtualFile = CommonDataKeys.VIRTUAL_FILE.getData(dataContext);
  Project project = CommonDataKeys.PROJECT.getData(dataContext);
  if (virtualFile == null || project == null) {
    return;
  }
  if (!CCUtils.isCourseCreator(project)) {
    return;
  }
  if (StudyUtils.getTaskForFile(project, virtualFile) != null || StudyUtils.getTask(project, virtualFile) != null) {
    presentation.setEnabledAndVisible(true);
  }
}
 
Example 11
Project: educational-plugin   File: CCRenameHandler.java   Source Code and License 6 votes vote down vote up
@Override
public void invoke(@NotNull Project project, Editor editor, PsiFile file, DataContext dataContext) {
  PsiElement element = CommonDataKeys.PSI_ELEMENT.getData(dataContext);
  assert element != null;
  PsiDirectory directory = (PsiDirectory)element;
  Course course = StudyTaskManager.getInstance(project).getCourse();
  if (course == null) {
    return;
  }
  rename(project, course, directory);
  ProjectView.getInstance(project).refresh();
  FileEditorManagerEx managerEx = FileEditorManagerEx.getInstanceEx(project);
  for (VirtualFile virtualFile : managerEx.getOpenFiles()) {
    managerEx.updateFilePresentation(virtualFile);
  }
}
 
Example 12
Project: educational-plugin   File: CCLessonMoveHandlerDelegate.java   Source Code and License 6 votes vote down vote up
@Override
public boolean canMove(DataContext dataContext) {
  if (CommonDataKeys.PSI_FILE.getData(dataContext) != null) {
    return false;
  }
  IdeView view = LangDataKeys.IDE_VIEW.getData(dataContext);
  if (view == null) {
    return false;
  }

  final PsiDirectory[] directories = view.getDirectories();
  if (directories.length == 0 || directories.length > 1) {
    return false;
  }

  final PsiDirectory sourceDirectory = directories[0];
  return CCUtils.isLessonDir(sourceDirectory);
}
 
Example 13
Project: educational-plugin   File: CCTaskMoveHandlerDelegate.java   Source Code and License 6 votes vote down vote up
@Override
public boolean canMove(DataContext dataContext) {
  if (CommonDataKeys.PSI_FILE.getData(dataContext) != null) {
    return false;
  }
  IdeView view = LangDataKeys.IDE_VIEW.getData(dataContext);
  if (view == null) {
    return false;
  }
  final PsiDirectory[] directories = view.getDirectories();
  if (directories.length == 0 || directories.length > 1) {
    return false;
  }

  final PsiDirectory sourceDirectory = directories[0];
  return isTaskDir(sourceDirectory);
}
 
Example 14
Project: RIBs   File: GenerateAction.java   Source Code and License 6 votes vote down vote up
/**
 * Checked whether or not this action can be enabled.
 *
 * <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 15
Project: intellij-ce-playground   File: NavigateToTestDataAction.java   Source Code and License 6 votes vote down vote up
@Override
public void actionPerformed(AnActionEvent e) {
  final DataContext dataContext = e.getDataContext();
  final Project project = CommonDataKeys.PROJECT.getData(dataContext);
  List<String> fileNames = findTestDataFiles(dataContext);
  if (fileNames == null || fileNames.isEmpty()) {
    String testData = guessTestData(dataContext);
    if (testData == null) {
      String message = "Cannot find testdata files for class";
      final Notification notification = new Notification("testdata", "Found no testdata files", message, NotificationType.INFORMATION);
      Notifications.Bus.notify(notification, project);
      return;
    }
    fileNames = Collections.singletonList(testData);
  }

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

  TestDataNavigationHandler.navigate(point, fileNames, project);
}
 
Example 16
Project: intellij-ce-playground   File: ChangeTypeSignatureHandler.java   Source Code and License 6 votes vote down vote up
public void invoke(@NotNull Project project, Editor editor, PsiFile file, DataContext dataContext) {
  editor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE);
  final int offset = TargetElementUtil.adjustOffset(file, editor.getDocument(), editor.getCaretModel().getOffset());
  final PsiElement element = file.findElementAt(offset);
  PsiTypeElement typeElement = PsiTreeUtil.getParentOfType(element, PsiTypeElement.class);
  while (typeElement != null) {
    final PsiElement parent = typeElement.getParent();
    if (parent instanceof PsiVariable || (parent instanceof PsiMember && !(parent instanceof PsiClass)) || isClassArgument(parent)) {
      invoke(project, parent, null, editor);
      return;
    }
    typeElement = PsiTreeUtil.getParentOfType(parent, PsiTypeElement.class, false);
  }
  CommonRefactoringUtil.showErrorHint(project, editor,
                                      "The caret should be positioned on type of field, variable, method or method parameter to be refactored",
                                      REFACTORING_NAME, "refactoring.migrateType");
}
 
Example 17
Project: intellij-ce-playground   File: AndroidRenameHandler.java   Source Code and License 6 votes vote down vote up
@Override
public boolean isAvailableOnDataContext(DataContext dataContext) {
  final Editor editor = CommonDataKeys.EDITOR.getData(dataContext);
  if (editor == null) {
    return false;
  }

  final PsiFile file = CommonDataKeys.PSI_FILE.getData(dataContext);
  if (file == null) {
    return false;
  }

  if (AndroidUsagesTargetProvider.findValueResourceTagInContext(editor, file) != null) {
    return true;
  }
  final Project project = CommonDataKeys.PROJECT.getData(dataContext);

  if (project == null) {
    return false;
  }
  final PsiElement element = CommonDataKeys.PSI_ELEMENT.getData(dataContext);
  return element != null && isPackageAttributeInManifest(project, element);
}
 
Example 18
Project: intellij-ce-playground   File: GroovyExtractMethodHandler.java   Source Code and License 6 votes vote down vote up
@Override
public void invoke(@NotNull final Project project, final Editor editor, final PsiFile file, @Nullable DataContext dataContext) {
  editor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE);
  final SelectionModel model = editor.getSelectionModel();
  if (model.hasSelection()) {
    invokeImpl(project, editor, file, model.getSelectionStart(), model.getSelectionEnd());
  }
  else {
    final List<GrExpression> expressions = GrIntroduceHandlerBase.collectExpressions(file, editor, editor.getCaretModel().getOffset(), true);
    final Pass<GrExpression> callback = new Callback(project, editor, file);
    if (expressions.size() == 1) {
      callback.pass(expressions.get(0));
    }
    else if (expressions.isEmpty()) {
      model.selectLineAtCaret();
      invokeImpl(project, editor, file, model.getSelectionStart(), model.getSelectionEnd());
    }
    else {
      IntroduceTargetChooser.showChooser(editor, expressions, callback, GrIntroduceHandlerBase.GR_EXPRESSION_RENDERER);
    }
  }
}
 
Example 19
Project: intellij-ce-playground   File: LazyUiDisposable.java   Source Code and License 6 votes vote down vote up
private static AsyncResult<Disposable> findDisposable(Disposable defaultValue, final DataKey<? extends Disposable> key) {
  if (defaultValue == null) {
    if (ApplicationManager.getApplication() != null) {
      final AsyncResult<Disposable> result = new AsyncResult<Disposable>();
      DataManager.getInstance().getDataContextFromFocus().doWhenDone(new Consumer<DataContext>() {
        public void consume(DataContext context) {
          Disposable disposable = key.getData(context);
          if (disposable == null) {
            disposable = Disposer.get("ui");
          }
          result.setDone(disposable);
        }
      });
      return result;
    }
    else {
      return null;
    }
  }
  else {
    return new AsyncResult.Done<Disposable>(defaultValue);
  }
}
 
Example 20
Project: intellij-ce-playground   File: IpnbMoveCellUpAction.java   Source Code and License 6 votes vote down vote up
@Override
public void actionPerformed(@NotNull AnActionEvent event) {
  final DataContext context = event.getDataContext();
  final FileEditor editor = PlatformDataKeys.FILE_EDITOR.getData(context);
  if (editor instanceof IpnbFileEditor) {
    final IpnbFilePanel ipnbFilePanel = ((IpnbFileEditor)editor).getIpnbFilePanel();
    CommandProcessor.getInstance().executeCommand(ipnbFilePanel.getProject(), new Runnable() {
      public void run() {
        ApplicationManager.getApplication().runWriteAction(new Runnable() {
          public void run() {
            ipnbFilePanel.moveCell(false);
          }
        });
      }
    }, "Ipnb.moveCell", new Object());

  }
}
 
Example 21
Project: MissingInActions   File: SwapLastSelectionTextAction.java   Source Code and License 6 votes vote down vote up
@Override
protected void doExecute(final Editor editor, @Nullable final Caret caret, final DataContext dataContext) {
    LineSelectionManager manager = LineSelectionManager.getInstance(editor);
    RangeMarker previousSelection = manager.getDummyRangeMarker();
    manager.recallLastSelection(0, true, false, true);
    RangeMarker rangeMarker = manager.getDummyRangeMarker();
    boolean handled = false;

    if (rangeMarker != null && previousSelection != null) {
        final Range range1 = new Range(rangeMarker.getStartOffset(), rangeMarker.getEndOffset());
        final Range range2 = new Range(previousSelection.getStartOffset(), previousSelection.getEndOffset());

        handled = EditHelpers.swapRangeText(editor, range1, range2);
    }

    if (!handled && previousSelection != null) {
        manager.pushSelection(true, false, false);
        editor.getSelectionModel().setSelection(previousSelection.getStartOffset(), previousSelection.getEndOffset());
        manager.recallLastSelection(0, true, true, true);
    }
}
 
Example 22
Project: intellij-ce-playground   File: GotoTestRelatedProvider.java   Source Code and License 6 votes vote down vote up
@NotNull
@Override
public List<? extends GotoRelatedItem> getItems(@NotNull DataContext context) {
  final PsiFile file = CommonDataKeys.PSI_FILE.getData(context);
  if (file == null) return Collections.emptyList();

  Collection<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 Collections.emptyList();
}
 
Example 23
Project: intellij-ce-playground   File: LegacyNewAndroidComponentAction.java   Source Code and License 6 votes vote down vote up
private static boolean isAvailable(DataContext dataContext) {
  final Module module = LangDataKeys.MODULE.getData(dataContext);
  final IdeView view = LangDataKeys.IDE_VIEW.getData(dataContext);

  if (module == null ||
      view == null ||
      view.getDirectories().length == 0) {
    return false;
  }
  final AndroidFacet facet = AndroidFacet.getInstance(module);

  if (facet == null || facet.isGradleProject()) {
    return false;
  }
  final ProjectFileIndex projectIndex = ProjectRootManager.getInstance(module.getProject()).getFileIndex();
  final JavaDirectoryService dirService = JavaDirectoryService.getInstance();

  for (PsiDirectory dir : view.getDirectories()) {
    if (projectIndex.isUnderSourceRootOfType(dir.getVirtualFile(), JavaModuleSourceRootTypes.SOURCES) &&
        dirService.getPackage(dir) != null) {
      return true;
    }
  }
  return false;
}
 
Example 24
Project: intellij-ce-playground   File: JavaPullUpHandler.java   Source Code and License 6 votes vote down vote up
@Override
public void invoke(@NotNull final Project project, @NotNull PsiElement[] elements, DataContext dataContext) {
  if (elements.length != 1) return;
  myProject = project;

  PsiElement element = elements[0];
  PsiClass aClass;
  PsiElement aMember = null;

  if (element instanceof PsiClass) {
    aClass = (PsiClass)element;
  }
  else if (element instanceof PsiMethod) {
    aClass = ((PsiMethod)element).getContainingClass();
    aMember = element;
  }
  else if (element instanceof PsiField) {
    aClass = ((PsiField)element).getContainingClass();
    aMember = element;
  }
  else {
    return;
  }

  invoke(project, dataContext, aClass, aMember);
}
 
Example 25
Project: intellij-ce-playground   File: ProjectUtil.java   Source Code and License 6 votes vote down vote up
@NotNull
public static Project guessCurrentProject(@Nullable JComponent component) {
  Project project = null;
  if (component != null) {
    project = CommonDataKeys.PROJECT.getData(DataManager.getInstance().getDataContext(component));
  }
  if (project == null) {
    Project[] openProjects = ProjectManager.getInstance().getOpenProjects();
    if (openProjects.length > 0) project = openProjects[0];
    if (project == null) {
      DataContext dataContext = DataManager.getInstance().getDataContext();
      project = CommonDataKeys.PROJECT.getData(dataContext);
    }
    if (project == null) {
      project = ProjectManager.getInstance().getDefaultProject();
    }
  }
  return project;
}
 
Example 26
Project: intellij-ce-playground   File: ShowMessageHistoryAction.java   Source Code and License 6 votes vote down vote up
public void update(AnActionEvent e) {
  super.update(e);

  final DataContext dc = e.getDataContext();
  final Project project = CommonDataKeys.PROJECT.getData(dc);
  Object panel = CheckinProjectPanel.PANEL_KEY.getData(dc);
  if (! (panel instanceof CommitMessageI)) {
    panel = VcsDataKeys.COMMIT_MESSAGE_CONTROL.getData(dc);
  }

  if (project == null || panel == null) {
    e.getPresentation().setVisible(false);
    e.getPresentation().setEnabled(false);
  }
  else {
    e.getPresentation().setVisible(true);
    final ArrayList<String> recentMessages = VcsConfiguration.getInstance(project).getRecentMessages();
    e.getPresentation().setEnabled(!recentMessages.isEmpty());
  }
}
 
Example 27
Project: intellij-ce-playground   File: TestCaseAsRelatedFileProvider.java   Source Code and License 6 votes vote down vote up
@NotNull
@Override
public List<? extends GotoRelatedItem> getItems(@NotNull DataContext context) {
  final Editor editor = CommonDataKeys.EDITOR.getData(context);
  final Project project = CommonDataKeys.PROJECT.getData(context);
  final VirtualFile file = CommonDataKeys.VIRTUAL_FILE.getData(context);
  if (editor == null || file == null || project == null) {
    return Collections.emptyList();
  }

  final List<Location> locations = TestLocationDataRule.collectRelativeLocations(project, file);
  if (locations.isEmpty()) {
    return Collections.emptyList();
  }
  
  return ContainerUtil.map(locations, new Function<Location, GotoRelatedItem>() {
    @Override
    public GotoRelatedItem fun(Location location) {
      return new GotoRelatedItem(location.getPsiElement());
    }
  });
}
 
Example 28
Project: intellij-ce-playground   File: PyTestCase.java   Source Code and License 6 votes vote down vote up
/**
 * Creates run configuration from right click menu
 *
 * @param fixture       test fixture
 * @param expectedClass expected class of run configuration
 * @param <C>           expected class of run configuration
 * @return configuration (if created) or null (otherwise)
 */
@Nullable
public static <C extends RunConfiguration> C createRunConfigurationFromContext(
  @NotNull final CodeInsightTestFixture fixture,
  @NotNull final Class<C> expectedClass) {
  final DataContext context = DataManager.getInstance().getDataContext(fixture.getEditor().getComponent());
  for (final RunConfigurationProducer<?> producer : RunConfigurationProducer.EP_NAME.getExtensions()) {
    final ConfigurationFromContext fromContext = producer.createConfigurationFromContext(ConfigurationContext.getFromContext(context));
    if (fromContext == null) {
      continue;
    }
    final C result = PyUtil.as(fromContext.getConfiguration(), expectedClass);
    if (result != null) {
      return result;
    }
  }
  return null;
}
 
Example 29
Project: intellij-ce-playground   File: ChooseItemAction.java   Source Code and License 6 votes vote down vote up
@Override
public void execute(@NotNull final Editor editor, final DataContext dataContext) {
  final LookupImpl lookup = (LookupImpl)LookupManager.getActiveLookup(editor);
  if (lookup == null) {
    throw new AssertionError("The last lookup disposed at: " + LookupImpl.getLastLookupDisposeTrace() + "\n-----------------------\n");
  }
  
  if (finishingChar == Lookup.NORMAL_SELECT_CHAR) {
    if (!lookup.isFocused()) {
      FeatureUsageTracker.getInstance().triggerFeatureUsed(CodeCompletionFeatures.EDITING_COMPLETION_CONTROL_ENTER);
    }
  } else if (finishingChar == Lookup.COMPLETE_STATEMENT_SELECT_CHAR) {
    FeatureUsageTracker.getInstance().triggerFeatureUsed(CodeCompletionFeatures.EDITING_COMPLETION_FINISH_BY_SMART_ENTER);
  } else if (finishingChar == Lookup.REPLACE_SELECT_CHAR) {
    FeatureUsageTracker.getInstance().triggerFeatureUsed(CodeCompletionFeatures.EDITING_COMPLETION_REPLACE);
  } else if (finishingChar == '.')  {
    FeatureUsageTracker.getInstance().triggerFeatureUsed(CodeCompletionFeatures.EDITING_COMPLETION_FINISH_BY_CONTROL_DOT);
  }

  lookup.finishLookup(finishingChar);
}
 
Example 30
Project: intellij-ce-playground   File: bigFile.java   Source Code and License 6 votes vote down vote up
private boolean processKeyTyped(char c) {
  // [vova] This is patch for Mac OS X. Under Mac "input methods"
  // is handled before our EventQueue consume upcoming KeyEvents.
  IdeEventQueue queue = IdeEventQueue.getInstance();
  if (queue.shouldNotTypeInEditor() || ProgressManager.getInstance().hasModalProgressIndicator()) {
    return false;
  }
  FileDocumentManager manager = FileDocumentManager.getInstance();
  final VirtualFile file = manager.getFile(myDocument);
  if (file != null && !file.isValid()) {
    return false;
  }

  ActionManagerEx actionManager = ActionManagerEx.getInstanceEx();
  DataContext dataContext = getDataContext();
  actionManager.fireBeforeEditorTyping(c, dataContext);
  MacUIUtil.hideCursor();
  EditorActionManager.getInstance().getTypedAction().actionPerformed(this, c, dataContext);

  return true;
}
 
Example 31
Project: intellij-ce-playground   File: StaticMethodOnlyUsedInOneClassInspection.java   Source Code and License 6 votes vote down vote up
@Override
protected void doFix(@NotNull final Project project, ProblemDescriptor descriptor) throws IncorrectOperationException {
  final PsiElement location = descriptor.getPsiElement();
  final PsiMethod method = (PsiMethod)location.getParent();
  final RefactoringActionHandler moveHandler = RefactoringActionHandlerFactory.getInstance().createMoveHandler();
  final AsyncResult<DataContext> result = DataManager.getInstance().getDataContextFromFocus();
  result.doWhenDone(new Consumer<DataContext>() {
    @Override
    public void consume(final DataContext originalContext) {
      final DataContext dataContext = new DataContext() {
        @Override
        public Object getData(@NonNls String name) {
          if (LangDataKeys.TARGET_PSI_ELEMENT.is(name)) {
            return usageClass.getElement();
          }
          return originalContext.getData(name);
        }
      };
      moveHandler.invoke(project, new PsiElement[]{method}, dataContext);
    }
  });
}
 
Example 32
Project: intellij-ce-playground   File: JavaPullUpHandler.java   Source Code and License 6 votes vote down vote up
@Override
public void invoke(@NotNull 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 || element instanceof PsiFile) {
      String message = RefactoringBundle
        .getCannotRefactorMessage(RefactoringBundle.message("the.caret.should.be.positioned.inside.a.class.to.pull.members.from"));
      CommonRefactoringUtil.showErrorHint(project, editor, message, REFACTORING_NAME, HelpID.MEMBERS_PULL_UP);
      return;
    }

    if (!CommonRefactoringUtil.checkReadOnlyStatus(project, element)) return;

    if (element instanceof PsiClass || element instanceof PsiField || element instanceof PsiMethod) {
      invoke(project, new PsiElement[]{element}, dataContext);
      return;
    }
    element = element.getParent();
  }
}
 
Example 33
Project: IdeaCurrency   File: IdeaCurrencyConfigUI.java   Source Code and License 5 votes vote down vote up
private void triggerConfigChange() {
    DataContext dataContext = DataManager.getInstance().getDataContextFromFocus().getResult();
    Project project = DataKeys.PROJECT.getData(dataContext);
    if (project != null) {
        MessageBus messageBus = project.getMessageBus();
        messageBus.connect();
        ConfigChangeNotifier configChangeNotifier = messageBus.syncPublisher(ConfigChangeNotifier.CONFIG_TOPIC);
        configChangeNotifier.configChanged(activeCheckBox.isSelected());
    }
}
 
Example 34
Project: CodeGenerate   File: CodeMakerUtil.java   Source Code and License 5 votes vote down vote up
/**
 * Gets the javafile that's currently selected in the editor. Returns null if it's not a java file.
 *
 * @param dataContext data context.
 * @return The current javafile. Null if not a javafile.
 */
public static PsiJavaFile getSelectedJavaFile(DataContext dataContext) {
    final PsiFile psiFile = (PsiFile) dataContext.getData("psi.File");

    if (!(psiFile instanceof PsiJavaFile)) {
        return null;
    } else {
        return (PsiJavaFile) psiFile;
    }
}
 
Example 35
Project: CodeGenerate   File: CreateFileAction.java   Source Code and License 5 votes vote down vote up
public CreateFileAction(String outputFile, String content, DataContext dataContext) {
    this.outputFile = outputFile;
    try {
        this.content = new String(content.getBytes("UTF-8"));
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    this.dataContext = dataContext;
}
 
Example 36
Project: mybatis-log-plugin   File: GoogleTranslateAction.java   Source Code and License 5 votes vote down vote up
public void actionPerformed(AnActionEvent var1) {
    DataContext var2 = var1.getDataContext();
    CopyProvider var3 = (CopyProvider) PlatformDataKeys.COPY_PROVIDER.getData(var2);
    if (var3 != null) {
        var3.performCopy(var2);
        String var4 = (String) CopyPasteManager.getInstance().getContents(DataFlavor.stringFlavor);
        if (StringUtil.isNotEmpty(var4)) {
            BrowserUtil.browse("https://translate.google.com/#en/zh-CN/" + URLEncoder.encode(var4));
        }
    }
}
 
Example 37
Project: mybatis-log-plugin   File: GoogleTranslateAction.java   Source Code and License 5 votes vote down vote up
public void update(AnActionEvent var1) {
    Presentation var2 = var1.getPresentation();
    DataContext var3 = var1.getDataContext();
    CopyProvider var4 = (CopyProvider) PlatformDataKeys.COPY_PROVIDER.getData(var3);
    boolean var5 = var4 != null && var4.isCopyEnabled(var3) && var4.isCopyVisible(var3);
    var2.setEnabled(var5);
    var2.setVisible(var5);
}
 
Example 38
Project: mybatis-log-plugin   File: BaiduSearchAction.java   Source Code and License 5 votes vote down vote up
public void actionPerformed(AnActionEvent var1) {
    DataContext var2 = var1.getDataContext();
    CopyProvider var3 = (CopyProvider) PlatformDataKeys.COPY_PROVIDER.getData(var2);
    if (var3 != null) {
        var3.performCopy(var2);
        String var4 = (String) CopyPasteManager.getInstance().getContents(DataFlavor.stringFlavor);
        if (StringUtil.isNotEmpty(var4)) {
            BrowserUtil.browse("https://www.baidu.com/s?wd=" + URLEncoder.encode(var4));
        }
    }
}
 
Example 39
Project: mybatis-log-plugin   File: BaiduSearchAction.java   Source Code and License 5 votes vote down vote up
public void update(AnActionEvent var1) {
    Presentation var2 = var1.getPresentation();
    DataContext var3 = var1.getDataContext();
    CopyProvider var4 = (CopyProvider) PlatformDataKeys.COPY_PROVIDER.getData(var3);
    boolean var5 = var4 != null && var4.isCopyEnabled(var3) && var4.isCopyVisible(var3);
    var2.setEnabled(var5);
    var2.setVisible(var5);
}
 
Example 40
Project: idea-php-typo3-plugin   File: ActionUtil.java   Source Code and 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();
}