Java 类com.intellij.psi.util.PsiUtilBase 实例源码

项目:CodeGenerate    文件:MainAction.java   
public void actionPerformed(AnActionEvent event) {
        Project project = event.getData(PlatformDataKeys.PROJECT);
        Editor editor = event.getData(PlatformDataKeys.EDITOR);
        PsiFile mFile = PsiUtilBase.getPsiFileInEditor(editor, project);
        PsiClass psiClass = getTargetClass(editor, mFile);
        GridMain gridMain = new GridMain(psiClass,mFile,project);
        //DBConn dbConn = new DBConn(psiClass,mFile,project);
//        JsonDialog jsonD = new JsonDialog(psiClass, mFile, project);
//        jsonD.setClass(psiClass);
//        jsonD.setFile(mFile);
//        jsonD.setProject(project);
//        jsonD.setSize(600, 400);
//        jsonD.setLocationRelativeTo(null);
//        jsonD.setVisible(true);

    }
项目:hybris-integration-intellij-idea-plugin    文件:DefaultImpexColumnHighlighterService.java   
@Override
@Contract
public void highlightCurrentColumn(@NotNull final Editor editor) {
    Validate.notNull(editor);

    final Project project = editor.getProject();

    if (null == project) {
        return;
    }

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

    final Language languageInEditor = PsiUtilBase.getLanguageInEditor(editor, project);

    if (languageInEditor instanceof ImpexLanguage) {
        this.highlightColumnOfValueUnderCaret(editor);
    }
}
项目:hybris-integration-intellij-idea-plugin    文件:ImpexHeaderHighlighterComponent.java   
private void highlightHeader(final PsiTreeChangeEvent psiTreeChangeEvent) {
    final PsiFile file = psiTreeChangeEvent.getFile();

    if (null == file) {
        return;
    }

    final Editor editor = PsiUtilBase.findEditor(file);

    if (null == editor) {
        return;
    }

    impexHeaderNameHighlighterService.highlightCurrentHeader(editor);
    impexColumnHighlighterService.highlightCurrentColumn(editor);
}
项目:hybris-integration-intellij-idea-plugin    文件:DefaultImpexHeaderNameHighlighterService.java   
@Override
@Contract(pure = false)
public void highlightCurrentHeader(@NotNull final Editor editor) {
    Validate.notNull(editor);

    final Project project = editor.getProject();

    if (null == project) {
        return;
    }

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

    final Language languageInEditor = PsiUtilBase.getLanguageInEditor(editor, project);

    if (languageInEditor instanceof ImpexLanguage) {
        this.highlightHeaderOfValueUnderCaret(editor);
    }
}
项目:hybris-integration-intellij-idea-plugin    文件:ImpexPsiUtils.java   
public static PsiElement getHeaderOfValueGroupUnderCaret(@NotNull final Editor editor) {
    Validate.notNull(editor);

    final PsiElement psiElementUnderCaret = PsiUtilBase.getElementAtCaret(editor);
    if (null == psiElementUnderCaret) {
        return null;
    }

    final ImpexValueGroup valueGroup = ImpexPsiUtils.getClosestSelectedValueGroupFromTheSameLine(
        psiElementUnderCaret);
    if (null != valueGroup) {

        final PsiElement header = ImpexPsiUtils.getHeaderForValueGroup(valueGroup);
        if (null != header) {

            return header;
        }
    }

    return null;
}
项目:AndroidStudioPlugin    文件:CreateDialogAction.java   
@Override
public void actionPerformed(AnActionEvent e) {

    // 获取编辑器中的文件
    Project project = e.getData(PlatformDataKeys.PROJECT);
    Editor editor = e.getData(PlatformDataKeys.EDITOR);
    PsiFile file = PsiUtilBase.getPsiFileInEditor(editor, project);

    // 获取当前类
    PsiClass targetClass = getTargetClass(editor, file);
    // 获取元素操作的工厂类
    PsiElementFactory factory = JavaPsiFacade.getElementFactory(project);

    // 生成代码
    new LayoutCreator(project, targetClass, factory, file).execute();
}
项目:intellij-ce-playground    文件:GenerateCreateUIHandler.java   
@Override
public void invoke(@NotNull Project project, @NotNull Editor editor, @NotNull PsiFile file) {
  final PsiElement element = PsiUtilBase.getElementAtCaret(editor);
  final PsiClass psiClass = PsiTreeUtil.getParentOfType(element, PsiClass.class);
  if (psiClass == null) return;

  final PsiElementFactory factory = JavaPsiFacade.getElementFactory(project);
  String annotation = "";
  if (PsiUtil.getLanguageLevel(file).isAtLeast(LanguageLevel.JDK_1_5)) {
    annotation = "@SuppressWarnings({\"MethodOverridesStaticMethodOfSuperclass\", \"UnusedDeclaration\"})";
  }
  final PsiMethod createUI = factory.createMethodFromText(annotation +
                                                          "\npublic static javax.swing.plaf.ComponentUI createUI(javax.swing.JComponent c) {" +
                                                      "\n  return new " + psiClass.getName() + "();\n}", psiClass);
  final PsiMethod newMethod = (PsiMethod)psiClass.add(CodeStyleManager.getInstance(project).reformat(createUI));
  JavaCodeStyleManager.getInstance(project).shortenClassReferences(newMethod);
  final PsiReturnStatement returnStatement = PsiTreeUtil.findChildOfType(newMethod, PsiReturnStatement.class);
  if (returnStatement != null) {
    final int offset = returnStatement.getTextRange().getEndOffset();
    editor.getCaretModel().moveToOffset(offset - 2);
  }
}
项目:intellij-ce-playground    文件:CodeBlockReformattingProcessor.java   
@Override
public void processText(Project project,
                        Template template,
                        Document document,
                        RangeMarker templateRange,
                        Editor editor) {
  if (!template.isToReformat()) return;

  PsiDocumentManager.getInstance(project).commitDocument(document);
  PsiFile file = PsiUtilBase.getPsiFileInEditor(editor, project);
  if (!(file instanceof PsiJavaFile)) return;

  CharSequence text = document.getImmutableCharSequence();
  int prevChar = CharArrayUtil.shiftBackward(text, templateRange.getStartOffset() - 1, " \t");
  int nextChar = CharArrayUtil.shiftForward(text, templateRange.getEndOffset(), " \t");
  if (prevChar > 0 && text.charAt(prevChar) == '{' && nextChar < text.length() && text.charAt(nextChar) == '}') {
    PsiCodeBlock codeBlock = PsiTreeUtil.findElementOfClassAtOffset(file, prevChar, PsiCodeBlock.class, false);
    if (codeBlock != null && codeBlock.getTextRange().getStartOffset() == prevChar) {
      PsiJavaToken rBrace = codeBlock.getRBrace();
      if (rBrace != null && rBrace.getTextRange().getStartOffset() == nextChar) {
        CodeEditUtil.markToReformat(rBrace.getNode(), true);
      }
    }
  }
}
项目:intellij-ce-playground    文件:CodeInsightAction.java   
public void actionPerformedImpl(@NotNull final Project project, final Editor editor) {
  if (editor == null) return;
  //final PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
  final PsiFile psiFile = PsiUtilBase.getPsiFileInEditor(editor, project);
  if (psiFile == null) return;
  CommandProcessor.getInstance().executeCommand(project, new Runnable() {
    @Override
    public void run() {
      final CodeInsightActionHandler handler = getHandler();
      final Runnable action = new Runnable() {
        @Override
        public void run() {
          if (!ApplicationManager.getApplication().isUnitTestMode() && !editor.getContentComponent().isShowing()) return;
          handler.invoke(project, editor, psiFile);
        }
      };
      if (handler.startInWriteAction()) {
        ApplicationManager.getApplication().runWriteAction(action);
      }
      else {
        action.run();
      }
    }
  }, getCommandName(), DocCommandGroupId.noneGroupId(editor.getDocument()));
}
项目:intellij-ce-playground    文件:CodeInsightAction.java   
@Override
public void update(AnActionEvent e) {
  Presentation presentation = e.getPresentation();

  Project project = e.getProject();
  if (project == null) {
    presentation.setEnabled(false);
    return;
  }

  final DataContext dataContext = e.getDataContext();
  Editor editor = getEditor(dataContext, project);
  if (editor == null) {
    presentation.setEnabled(false);
    return;
  }

  final PsiFile file = PsiUtilBase.getPsiFileInEditor(editor, project);
  if (file == null) {
    presentation.setEnabled(false);
    return;
  }

  update(presentation, project, editor, file, dataContext, e.getPlace());
}
项目:intellij-ce-playground    文件:BaseCodeCompletionAction.java   
@Override
public void update(AnActionEvent e) {
  DataContext dataContext = e.getDataContext();
  e.getPresentation().setEnabled(false);
  Project project = CommonDataKeys.PROJECT.getData(dataContext);
  if (project == null) return;

  Editor editor = CommonDataKeys.EDITOR.getData(dataContext);
  if (editor == null) return;

  final PsiFile psiFile = PsiUtilBase.getPsiFileInEditor(editor, project);
  if (psiFile == null) return;

  if (!ApplicationManager.getApplication().isUnitTestMode() && !editor.getContentComponent().isShowing()) return;
  e.getPresentation().setEnabled(true);
}
项目:intellij-ce-playground    文件:CodeCompletionHandlerBase.java   
private static void addCompletionChar(Project project,
                                      CompletionAssertions.WatchingInsertionContext context,
                                      LookupElement item,
                                      Editor editor, CompletionProgressIndicator indicator, char completionChar) {
  int tailOffset = context.getTailOffset();
  if (tailOffset < 0) {
    LOG.info("tailOffset<0 after inserting " + item + " of " + item.getClass() + "; invalidated at: " + context.invalidateTrace + "\n--------");
  }
  else {
    editor.getCaretModel().moveToOffset(tailOffset);
  }
  if (context.getCompletionChar() == Lookup.COMPLETE_STATEMENT_SELECT_CHAR) {
    final Language language = PsiUtilBase.getLanguageInEditor(editor, project);
    if (language != null) {
      for (SmartEnterProcessor processor : SmartEnterProcessors.INSTANCE.forKey(language)) {
        if (processor.processAfterCompletion(editor, indicator.getParameters().getOriginalFile())) break;
      }
    }
  }
  else if (!editor.getCaretModel().supportsMultipleCarets()) { // this will be done outside of runForEach caret context
    DataContext dataContext = DataManager.getInstance().getDataContext(editor.getContentComponent());
    EditorActionManager.getInstance().getTypedAction().getHandler().execute(editor, completionChar, dataContext);
  }
}
项目:intellij-ce-playground    文件:DefaultHighlightInfoProcessor.java   
private void repaintTrafficIcon(@NotNull final PsiFile file, final Editor editor, double progress) {
  if (ApplicationManager.getApplication().isCommandLine()) return;

  if (repaintIconAlarm.isEmpty() || progress >= 1) {
    repaintIconAlarm.addRequest(new Runnable() {
      @Override
      public void run() {
        Project myProject = file.getProject();
        if (myProject.isDisposed()) return;
        Editor myeditor = editor;
        if (myeditor == null) {
          myeditor = PsiUtilBase.findEditor(file);
        }
        if (myeditor == null || myeditor.isDisposed()) return;
        EditorMarkupModelImpl markup = (EditorMarkupModelImpl)myeditor.getMarkupModel();
        markup.repaintTrafficLightIcon();
        DaemonListeners.repaintErrorStripeRenderer(myeditor, myProject);
      }
    }, 50, null);
  }
}
项目:intellij-ce-playground    文件:HighlightingSettingsPerFile.java   
public void setHighlightingSettingForRoot(@NotNull PsiElement root, @NotNull FileHighlightingSetting setting) {
  final PsiFile containingFile = root.getContainingFile();
  final VirtualFile virtualFile = containingFile.getVirtualFile();
  if (virtualFile == null) return;
  FileHighlightingSetting[] defaults = myHighlightSettings.get(virtualFile);
  int rootIndex = PsiUtilBase.getRootIndex(root);
  if (defaults != null && rootIndex >= defaults.length) defaults = null;
  if (defaults == null) defaults = getDefaults(containingFile);
  defaults[rootIndex] = setting;
  boolean toRemove = true;
  for (FileHighlightingSetting aDefault : defaults) {
    if (aDefault != FileHighlightingSetting.NONE) toRemove = false;
  }
  if (toRemove) {
    myHighlightSettings.remove(virtualFile);
  }
  else {
    myHighlightSettings.put(virtualFile, defaults);
  }
}
项目:intellij-ce-playground    文件:MultiCaretCodeInsightAction.java   
private static void iterateOverCarets(@NotNull final Project project,
                               @NotNull final Editor hostEditor,
                               @NotNull final MultiCaretCodeInsightActionHandler handler) {
  PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
  final PsiFile psiFile = documentManager.getCachedPsiFile(hostEditor.getDocument());
  documentManager.commitAllDocuments();

  hostEditor.getCaretModel().runForEachCaret(new CaretAction() {
    @Override
    public void perform(Caret caret) {
      Editor editor = hostEditor;
      if (psiFile != null) {
        Caret injectedCaret = InjectedLanguageUtil.getCaretForInjectedLanguageNoCommit(caret, psiFile);
        if (injectedCaret != null) {
          caret = injectedCaret;
          editor = caret.getEditor();
        }
      }
      final PsiFile file = PsiUtilBase.getPsiFileInEditor(caret, project);
      if (file != null) {
        handler.invoke(project, editor, caret, file);
      }
    }
  });
}
项目:intellij-ce-playground    文件:BaseMoveHandler.java   
@Nullable
private static PsiFile getRoot(final PsiFile file, final Editor editor) {
  if (file == null) return null;
  int offset = editor.getCaretModel().getOffset();
  if (offset == editor.getDocument().getTextLength()) offset--;
  if (offset<0) return null;
  PsiElement leafElement = file.findElementAt(offset);
  if (leafElement == null) return null;
  if (leafElement.getLanguage() instanceof DependentLanguage) {
    leafElement = file.getViewProvider().findElementAt(offset, file.getViewProvider().getBaseLanguage());
    if (leafElement == null) return null;
  }
  ASTNode node = leafElement.getNode();
  if (node == null) return null;
  return (PsiFile)PsiUtilBase.getRoot(node).getPsi();
}
项目:intellij-ce-playground    文件:IntentionListStep.java   
private void applyAction(final IntentionActionWithTextCaching cachedAction) {
  myFinalRunnable = new Runnable() {
    @Override
    public void run() {
      HintManager.getInstance().hideAllHints();
      ApplicationManager.getApplication().invokeLater(new Runnable() {
        @Override
        public void run() {
          if (myProject.isDisposed()) return;
          if (DumbService.isDumb(myProject) && !DumbService.isDumbAware(cachedAction)) {
            DumbService.getInstance(myProject).showDumbModeNotification(cachedAction.getText() + " is not available during indexing");
            return;
          }

          PsiDocumentManager.getInstance(myProject).commitAllDocuments();
          final PsiFile file = PsiUtilBase.getPsiFileInEditor(myEditor, myProject);
          if (file == null) {
            return;
          }

          ShowIntentionActionsHandler.chooseActionAndInvoke(file, myEditor, cachedAction.getAction(), cachedAction.getText());
        }
      });
    }
  };
}
项目:intellij-ce-playground    文件:FindUsagesInFileAction.java   
private static boolean isEnabled(DataContext dataContext) {
  Project project = CommonDataKeys.PROJECT.getData(dataContext);
  if (project == null) {
    return false;
  }

  Editor editor = CommonDataKeys.EDITOR.getData(dataContext);
  if (editor == null) {
    UsageTarget[] target = UsageView.USAGE_TARGETS_KEY.getData(dataContext);
    return target != null && target.length > 0;
  }
  else {
    PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
    if (file == null) {
      return false;
    }

    Language language = PsiUtilBase.getLanguageInEditor(editor, project);
    if (language == null) {
      language = file.getLanguage();
    }
    return !(LanguageFindUsages.INSTANCE.forLanguage(language) instanceof EmptyFindUsagesProvider);
  }
}
项目:intellij-ce-playground    文件:FavoritesViewSelectInTarget.java   
@Override
protected void select(PsiElement element, boolean requestFocus) {
  PsiElement toSelect = null;
  if (element instanceof PsiFile || element instanceof PsiDirectory) {
    toSelect = element;
  }
  else {
    final PsiFile containingFile = element.getContainingFile();
    if (containingFile == null) return;
    final FileViewProvider viewProvider = containingFile.getViewProvider();
    toSelect = viewProvider.getPsi(viewProvider.getBaseLanguage());
  }
  if (toSelect == null) return;
  PsiElement originalElement = toSelect.getOriginalElement();
  final VirtualFile virtualFile = PsiUtilBase.getVirtualFile(originalElement);
  select(originalElement, virtualFile, requestFocus);
}
项目:intellij-ce-playground    文件:FavoritesProjectViewPane.java   
@Override
public void select(Object object, VirtualFile file, boolean requestFocus) {
  if (!(object instanceof PsiElement)) return;
  /*PsiElement element = (PsiElement)object;
  PsiFile psiFile = element.getContainingFile();
  if (psiFile != null) {
    element = psiFile;
  }

  if (element instanceof PsiJavaFile) {
    final PsiClass[] classes = ((PsiJavaFile)element).getClasses();
    if (classes.length > 0) {
      element = classes[0];
    }
  }

  final PsiElement originalElement = element.getOriginalElement();*/
  final VirtualFile virtualFile = PsiUtilBase.getVirtualFile((PsiElement)object);
  final String list = FavoritesViewSelectInTarget.findSuitableFavoritesList(virtualFile, myProject, getSubId());
  if (list == null) return;
  if (!list.equals(getSubId())) {
    ProjectView.getInstance(myProject).changeView(ID, list);
  }
  myViewPanel.selectElement(object, virtualFile, requestFocus);
}
项目:intellij-ce-playground    文件:DeleteTypeDescriptionLocation.java   
@Override
public String getElementDescription(@NotNull final PsiElement element, @NotNull final ElementDescriptionLocation location) {
  if (location instanceof DeleteTypeDescriptionLocation) {
    final boolean plural = ((DeleteTypeDescriptionLocation)location).isPlural();
    final int count = plural ? 2 : 1;
    if (element instanceof PsiFileSystemItem && PsiUtilBase.isSymLink((PsiFileSystemItem)element)) {
      return IdeBundle.message("prompt.delete.symlink", count);
    }
    if (element instanceof PsiFile) {
      return IdeBundle.message("prompt.delete.file", count);
    }
    if (element instanceof PsiDirectory) {
      return IdeBundle.message("prompt.delete.directory", count);
    }
    if (!plural) {
      return LanguageFindUsages.INSTANCE.forLanguage(element.getLanguage()).getType(element);
    }
    return "elements";
  }
  return null;
}
项目:intellij-ce-playground    文件:AndroidInlineLayoutHandler.java   
@Nullable
private static LayoutUsageData getLayoutUsageDataFromContext(Editor editor) {
  if (editor == null) {
    return null;
  }
  final PsiElement element = PsiUtilBase.getElementAtCaret(editor);

  if (!(element instanceof XmlToken) ||
      AndroidFacet.getInstance(element) == null) {
    return null;
  }
  final XmlTag tag = PsiTreeUtil.getParentOfType(element, XmlTag.class);
  return tag != null
         ? AndroidInlineUtil.getLayoutUsageData(tag)
         : null;
}
项目:intellij-ce-playground    文件:CommanderSelectInTarget.java   
protected void select(PsiElement element, boolean requestFocus) {
  while (true) {
    if (element instanceof PsiFile || element instanceof PsiDirectory) {
      break;
    }
    if (element instanceof PsiClass && element.getParent() instanceof PsiFile) {
      break;
    }
    element = element.getParent();
  }

  if (element instanceof PsiJavaFile) {
    final PsiClass[] classes = ((PsiJavaFile)element).getClasses();
    if (classes.length > 0) {
      element = classes[0];
    }
  }

  final PsiElement _element = element.getOriginalElement();

  selectElementInCommander(new Runnable() {
    public void run() {
      Commander.getInstance(myProject).selectElementInLeftPanel(_element, PsiUtilBase.getVirtualFile(_element));
    }
  }, requestFocus);
}
项目:intellij-ce-playground    文件:ShowByteCodeAction.java   
@Nullable
private static PsiElement getPsiElement(DataContext dataContext, Project project, Editor editor) {
  PsiElement psiElement = null;
  if (editor == null) {
    psiElement = CommonDataKeys.PSI_ELEMENT.getData(dataContext);
  } else {
    final PsiFile file = PsiUtilBase.getPsiFileInEditor(editor, project);
    final Editor injectedEditor = InjectedLanguageUtil.getEditorForInjectedLanguageNoCommit(editor, file);
    if (injectedEditor != null) {
      PsiFile psiFile = PsiUtilBase.getPsiFileInEditor(injectedEditor, project);
      psiElement = psiFile != null ? psiFile.findElementAt(injectedEditor.getCaretModel().getOffset()) : null;
    }

    if (file != null && psiElement == null) {
      psiElement = file.findElementAt(editor.getCaretModel().getOffset());
    }
  }

  return psiElement;
}
项目:intellij-ce-playground    文件:GroovyShortenFQNamesProcessor.java   
@Override
public void processText(final Project project,
                        final Template template,
                        final Document document,
                        final RangeMarker templateRange,
                        final Editor editor) {
  if (!template.isToShortenLongNames()) return;

  try {
    PsiDocumentManager.getInstance(project).commitDocument(document);
    final PsiFile file = PsiUtilBase.getPsiFileInEditor(editor, project);
    if (file instanceof GroovyFile) {
      JavaCodeStyleManager.getInstance(project).shortenClassReferences(file, templateRange.getStartOffset(),templateRange.getEndOffset());
    }
    PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(document);
  }
  catch (IncorrectOperationException e) {
    LOG.error(e);
  }
}
项目:jnihelper    文件:JavahAction.java   
@Override
public void actionPerformedImpl(Project project, Editor editor) {
    PsiFile file = PsiUtilBase.getPsiFileInEditor(editor, project);
    PsiClass sourceClass = getTargetClass(editor, file);

    boolean hasNativeMethod = Utils.hasNativeMethod(sourceClass);
    if(!hasNativeMethod){
        Utils.showErrorNotification(project,"This file has no native method.");
        return;
    }

    ProjectRootManager rootManager = ProjectRootManager.getInstance(project);
    final ProjectFileIndex fileIndex = rootManager.getFileIndex();
    VirtualFile sourceRootFile = fileIndex.getSourceRootForFile(file.getVirtualFile()); // 默认包的路径 /XXX/src/main/java

    createJavahFile(project, sourceRootFile, sourceClass);
}
项目:google-cloud-intellij    文件:ApiNameInspection.java   
@Override
public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
  PsiElement element = descriptor.getPsiElement();
  if (element == null) {
    return;
  }

  Editor editor = PsiUtilBase.findEditor(element);
  if (editor == null) {
    return;
  }

  TextRange textRange = ((ProblemDescriptorBase) descriptor).getTextRange();
  editor.getSelectionModel().setSelection(textRange.getStartOffset(), textRange.getEndOffset());

  String wordWithQuotes = editor.getSelectionModel().getSelectedText();
  String word = EndpointUtilities.removeBeginningAndEndingQuotes(wordWithQuotes);

  if (word == null || StringUtil.isEmpty(word)) {
    return;
  }

  String variant = "\"" + getNameSuggestions(word) + "\"";
  LookupManager lookupManager = LookupManager.getInstance(project);
  lookupManager.showLookup(editor, LookupElementBuilder.create(variant));
}
项目:eZ-completion    文件:Completion.java   
@Override
public void handleInsert(InsertionContext context)
{
    if (keepQuotes) {
        return;
    }

    PsiElement rightSingleQuote = PsiUtilBase.getElementAtCaret(context.getEditor());
    if (rightSingleQuote == null || isNotQuote(rightSingleQuote)) {
        return;
    }

    PsiElement previousSibling = rightSingleQuote.getPrevSibling();
    if (previousSibling == null) {
        return;
    }

    PsiElement leftSingleQuote = previousSibling.getPrevSibling();
    if (leftSingleQuote == null || isNotQuote(leftSingleQuote)) {
        return;
    }

    leftSingleQuote.delete();
    rightSingleQuote.delete();
}
项目:idea-android-studio-plugin    文件:AbstractActivityViewAction.java   
@Override
public void actionPerformedImpl(@NotNull final Project project, final Editor editor) {
    PsiFile file = PsiUtilBase.getPsiFileInEditor(editor, project);
    if(file == null) {
        return;
    }

    int offset = editor.getCaretModel().getOffset();
    PsiElement psiElement = file.findElementAt(offset);
    if(psiElement == null) {
        return;
    }

    PsiMethodCallExpression psiMethodCallExpression = PsiTreeUtil.getParentOfType(psiElement, PsiMethodCallExpression.class);
    if(psiMethodCallExpression == null) {
        return;
    }

    PsiFile xmlFile = matchInflate(psiMethodCallExpression);
    generate(psiMethodCallExpression, xmlFile, editor, file);
}
项目:idea-android-studio-plugin    文件:AbstractInflateViewAction.java   
@Override
public void actionPerformedImpl(@NotNull final Project project, final Editor editor) {
    PsiFile file = PsiUtilBase.getPsiFileInEditor(editor, project);
    if(file == null) {
        return;
    }

    int offset = editor.getCaretModel().getOffset();
    PsiElement psiElement = file.findElementAt(offset);
    if(psiElement == null) {
        return;
    }

    PsiLocalVariable psiLocalVariable = PsiTreeUtil.getParentOfType(psiElement, PsiLocalVariable.class);
    InflateViewAnnotator.InflateContainer inflateContainer = InflateViewAnnotator.matchInflate(psiLocalVariable);
    if(inflateContainer == null) {
        return;
    }

    generate(inflateContainer, editor, file);
}
项目:android-viewbyid-generator    文件:GenerateViewByIds.java   
@Override
public void actionPerformedImpl(@NotNull Project project, Editor editor) {
    PsiFile file = PsiUtilBase.getPsiFileInEditor(editor, project);
    PsiFile layout = Utils.getLayoutFileFromCaret(editor, file);

    if (layout == null) {
        Utils.showErrorNotification(project, "No layout found - Please place the caret in the layout name");
        return;
    }

    ArrayList<Element> elements = Utils.getIDsFromLayout(layout);
    if (elements.size() > 0) {

        showDialog(project, editor, elements);

    } else {
        Utils.showErrorNotification(project, "No IDs found in the selected layout");
    }
}
项目:android-viewbyid-generator    文件:GenerateViewByIds.java   
@Override
public void onConfirm(Project project, Editor editor, ArrayList<Element> elements, String fieldNamePrefix) {
    PsiFile file = PsiUtilBase.getPsiFileInEditor(editor, project);
    PsiFile layout = Utils.getLayoutFileFromCaret(editor, file);

    closeDialog();

    int cnt = 0;
    for (Element element : elements) {
        if (element.used) {
            cnt++;
        }
    }

    if (cnt > 0) { // generate injections
        new ViewByIdWriter(file, getTargetClass(editor, file), "Generate Injections", elements, fieldNamePrefix, layout.getName()).execute();

        if (cnt == 1) {
            Utils.showInfoNotification(project, "One injection added to " + file.getName());
        } else {
            Utils.showInfoNotification(project, String.valueOf(cnt) + " injections added to " + file.getName());
        }
    } else { // just notify user about no element selected
        Utils.showInfoNotification(project, "No injection was selected");
    }
}
项目:tools-idea    文件:GenerateCreateUIHandler.java   
@Override
public void invoke(@NotNull Project project, @NotNull Editor editor, @NotNull PsiFile file) {
  final PsiElement element = PsiUtilBase.getElementAtCaret(editor);
  final PsiClass psiClass = PsiTreeUtil.getParentOfType(element, PsiClass.class);
  if (psiClass == null) return;

  final PsiElementFactory factory = JavaPsiFacade.getElementFactory(project);
  String annotation = "";
  if (PsiUtil.getLanguageLevel(file).isAtLeast(LanguageLevel.JDK_1_5)) {
    annotation = "@SuppressWarnings({\"MethodOverridesStaticMethodOfSuperclass\", \"UnusedDeclaration\"})";
  }
  final PsiMethod createUI = factory.createMethodFromText(annotation +
                                                          "\npublic static javax.swing.plaf.ComponentUI createUI(javax.swing.JComponent c) {" +
                                                      "\n  return new " + psiClass.getName() + "();\n}", psiClass);
  final PsiMethod newMethod = (PsiMethod)psiClass.add(CodeStyleManager.getInstance(project).reformat(createUI));
  JavaCodeStyleManager.getInstance(project).shortenClassReferences(newMethod);
  final PsiReturnStatement returnStatement = PsiTreeUtil.findChildOfType(newMethod, PsiReturnStatement.class);
  if (returnStatement != null) {
    final int offset = returnStatement.getTextRange().getEndOffset();
    editor.getCaretModel().moveToOffset(offset - 2);
  }
}
项目:tools-idea    文件:CodeInsightAction.java   
public void actionPerformedImpl(@NotNull final Project project, final Editor editor) {
  if (editor == null) return;
  //final PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
  final PsiFile psiFile = PsiUtilBase.getPsiFileInEditor(editor, project);
  if (psiFile == null) return;
  CommandProcessor.getInstance().executeCommand(project, new Runnable() {
    @Override
    public void run() {
      final CodeInsightActionHandler handler = getHandler();
      final Runnable action = new Runnable() {
        @Override
        public void run() {
          if (!ApplicationManager.getApplication().isUnitTestMode() && !editor.getContentComponent().isShowing()) return;
          handler.invoke(project, editor, psiFile);
        }
      };
      if (handler.startInWriteAction()) {
        ApplicationManager.getApplication().runWriteAction(action);
      }
      else {
        action.run();
      }
    }
  }, getCommandName(), DocCommandGroupId.noneGroupId(editor.getDocument()));
}
项目:tools-idea    文件:CodeInsightAction.java   
@Override
public void update(AnActionEvent event) {
  Presentation presentation = event.getPresentation();
  DataContext dataContext = event.getDataContext();

  Project project = PlatformDataKeys.PROJECT.getData(dataContext);
  if (project == null) {
    presentation.setEnabled(false);
    return;
  }

  Editor editor = getEditor(dataContext, project);
  if (editor == null) {
    presentation.setEnabled(false);
    return;
  }

  final PsiFile file = PsiUtilBase.getPsiFileInEditor(editor, project);
  presentation.setEnabled(file != null && isValidForFile(project, editor, file));
}
项目:tools-idea    文件:ParameterInfoController.java   
@Nullable
public static <E extends PsiElement> E findArgumentList(PsiFile file, int offset, int lbraceOffset){
  if (file == null) return null;
  ParameterInfoHandler[] handlers = ShowParameterInfoHandler.getHandlers(file.getProject(), PsiUtilBase.getLanguageAtOffset(file, offset), file.getViewProvider().getBaseLanguage());

  if (handlers != null) {
    for(ParameterInfoHandler handler:handlers) {
      if (handler instanceof ParameterInfoHandlerWithTabActionSupport) {
        final ParameterInfoHandlerWithTabActionSupport parameterInfoHandler2 = (ParameterInfoHandlerWithTabActionSupport)handler;

        final E e = (E)ParameterInfoUtils.findArgumentList(file, offset, lbraceOffset, parameterInfoHandler2);
        if (e != null) return e;
      }
    }
  }

  return null;
}
项目:tools-idea    文件:BaseCodeCompletionAction.java   
@Override
public void update(AnActionEvent e) {
  DataContext dataContext = e.getDataContext();
  e.getPresentation().setEnabled(false);
  Project project = PlatformDataKeys.PROJECT.getData(dataContext);
  if (project == null) return;

  Editor editor = PlatformDataKeys.EDITOR.getData(dataContext);
  if (editor == null) return;

  final PsiFile psiFile = PsiUtilBase.getPsiFileInEditor(editor, project);
  if (psiFile == null) return;

  if (!ApplicationManager.getApplication().isUnitTestMode() && !editor.getContentComponent().isShowing()) return;
  e.getPresentation().setEnabled(true);
}
项目:tools-idea    文件:CodeCompletionHandlerBase.java   
private static boolean shouldSkipAutoPopup(Editor editor, PsiFile psiFile) {
  int offset = editor.getCaretModel().getOffset();
  int psiOffset = Math.max(0, offset - 1);

  PsiElement elementAt = InjectedLanguageUtil.findInjectedElementNoCommit(psiFile, psiOffset);
  if (elementAt == null) {
    elementAt = psiFile.findElementAt(psiOffset);
  }
  if (elementAt == null) return true;

  Language language = PsiUtilBase.findLanguageFromElement(elementAt);

  for (CompletionConfidence confidence : CompletionConfidenceEP.forLanguage(language)) {
    final ThreeState result = confidence.shouldSkipAutopopup(elementAt, psiFile, offset);
    if (result != ThreeState.UNSURE) {
      LOG.debug(confidence + " has returned shouldSkipAutopopup=" + result);
      return result == ThreeState.YES;
    }
  }
  return false;
}
项目:tools-idea    文件:CodeCompletionHandlerBase.java   
private static void addCompletionChar(Project project,
                                      CompletionAssertions.WatchingInsertionContext context,
                                      LookupElement item,
                                      Editor editor, CompletionProgressIndicator indicator, char completionChar) {
  int tailOffset = context.getTailOffset();
  if (tailOffset < 0) {
    LOG.info("tailOffset<0 after inserting " + item + " of " + item.getClass() + "; invalidated at: " + context.invalidateTrace + "\n--------");
  }
  else {
    editor.getCaretModel().moveToOffset(tailOffset);
  }
  if (context.getCompletionChar() == Lookup.COMPLETE_STATEMENT_SELECT_CHAR) {
    final Language language = PsiUtilBase.getLanguageInEditor(editor, project);
    final List<SmartEnterProcessor> processors = SmartEnterProcessors.INSTANCE.forKey(language);
    if (processors.size() > 0) {
      for (SmartEnterProcessor processor : processors) {
        processor.process(project, editor, indicator.getParameters().getOriginalFile());
      }
    }
  }
  else {
    DataContext dataContext = DataManager.getInstance().getDataContext(editor.getContentComponent());
    EditorActionManager.getInstance().getTypedAction().getHandler().execute(editor, completionChar, dataContext);
  }
}
项目:tools-idea    文件:CompletionProgressIndicator.java   
private static boolean shouldPreselectFirstSuggestion(CompletionParameters parameters) {
  if (!ApplicationManager.getApplication().isUnitTestMode()) {
    return true;
  }

  switch (CodeInsightSettings.getInstance().AUTOPOPUP_FOCUS_POLICY) {
    case CodeInsightSettings.ALWAYS:
      return true;
    case CodeInsightSettings.NEVER:
      return false;
  }

  final Language language = PsiUtilBase.getLanguageAtOffset(parameters.getPosition().getContainingFile(), parameters.getOffset());
  for (CompletionConfidence confidence : CompletionConfidenceEP.forLanguage(language)) {
    final ThreeState result = confidence.shouldFocusLookup(parameters);
    if (result != ThreeState.UNSURE) {
      LOG.debug(confidence + " has returned shouldFocusLookup=" + result);
      return result == ThreeState.YES;
    }
  }
  return false;
}