Java Code Examples for com.intellij.psi.util.PsiUtilBase#getPsiFileInEditor()

The following examples show how to use com.intellij.psi.util.PsiUtilBase#getPsiFileInEditor() . 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: CodeCompletionHandlerBase.java    From consulo with Apache License 2.0 6 votes vote down vote up
private static WatchingInsertionContext callHandleInsert(CompletionProgressIndicator indicator, LookupElement item, char completionChar) {
  final Editor editor = indicator.getEditor();

  final int caretOffset = indicator.getCaret().getOffset();
  final int idEndOffset = calcIdEndOffset(indicator);
  PsiFile psiFile = PsiUtilBase.getPsiFileInEditor(editor, indicator.getProject());

  WatchingInsertionContext context = createInsertionContext(indicator.getLookup(), item, completionChar, editor, psiFile, caretOffset, idEndOffset, indicator.getOffsetMap());
  try {
    item.handleInsert(context);
  }
  finally {
    context.stopWatching();
  }
  return context;
}
 
Example 2
Source File: AbstractActivityViewAction.java    From idea-android-studio-plugin with GNU General Public License v2.0 6 votes vote down vote up
@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);
}
 
Example 3
Source File: AbstractInflateViewAction.java    From idea-android-studio-plugin with GNU General Public License v2.0 6 votes vote down vote up
@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);
}
 
Example 4
Source File: IntentionListStep.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void applyAction(@Nonnull IntentionActionWithTextCaching cachedAction) {
  myFinalRunnable = () -> {
    HintManager.getInstance().hideAllHints();
    if (myProject.isDisposed()) return;
    if (myEditor != null && (myEditor.isDisposed() || (!myEditor.getComponent().isShowing() && !ApplicationManager.getApplication().isUnitTestMode()))) return;

    if (DumbService.isDumb(myProject) && !DumbService.isDumbAware(cachedAction)) {
      DumbService.getInstance(myProject).showDumbModeNotification(cachedAction.getText() + " is not available during indexing");
      return;
    }

    PsiDocumentManager.getInstance(myProject).commitAllDocuments();

    PsiFile file = myEditor != null ? PsiUtilBase.getPsiFileInEditor(myEditor, myProject) : myFile;
    if (file == null) {
      return;
    }

    ShowIntentionActionsHandler.chooseActionAndInvoke(file, myEditor, cachedAction.getAction(), cachedAction.getText(), myProject);
  };
}
 
Example 5
Source File: CodeInsightAction.java    From consulo with Apache License 2.0 6 votes vote down vote up
@RequiredUIAccess
@Override
public void update(@Nonnull 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, true);
  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());
}
 
Example 6
Source File: ServiceGenerateAction.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
private boolean invokePhpClass(Project project, Editor editor) {

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

        int offset = editor.getCaretModel().getOffset();
        if(offset <= 0) {
            return false;
        }

        PsiElement psiElement = file.findElementAt(offset);
        if(psiElement == null) {
            return false;
        }

        PhpClass phpClass = PsiTreeUtil.getParentOfType(psiElement, PhpClass.class);
        if(phpClass == null) {
            return false;
        }

        invokeServiceGenerator(project, file, phpClass, editor);

        return true;
    }
 
Example 7
Source File: InjectAction.java    From android-butterknife-zelezny with Apache License 2.0 6 votes vote down vote up
public void onConfirm(Project project, Editor editor, ArrayList<Element> elements, String fieldNamePrefix, boolean createHolder, boolean splitOnclickMethods) {
    PsiFile file = PsiUtilBase.getPsiFileInEditor(editor, project);
    if (file == null) {
        return;
    }
    PsiFile layout = Utils.getLayoutFileFromCaret(editor, file);

    closeDialog();


    if (Utils.getInjectCount(elements) > 0 || Utils.getClickCount(elements) > 0) { // generate injections
        new InjectWriter(file, getTargetClass(editor, file), "Generate Injections", elements, layout.getName(), fieldNamePrefix, createHolder, splitOnclickMethods).execute();
    } else { // just notify user about no element selected
        Utils.showInfoNotification(project, "No injection was selected");
    }

}
 
Example 8
Source File: NoPolAction.java    From nopol with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void actionPerformed(ActionEvent e) {
	Project project = event.getData(PlatformDataKeys.PROJECT);
	Editor editor = event.getData(PlatformDataKeys.EDITOR);
	PsiFile currentFile = PsiUtilBase.getPsiFileInEditor(editor, project);

	if (JavaFileType.INSTANCE != currentFile.getFileType())
		return;

	try {
		File outputZip = File.createTempFile(project.getName(), ".zip");
		VirtualFile file = buildTestProject(project, editor, currentFile);
		Module module = ProjectRootManager.getInstance(project).getFileIndex().getModuleForFile(file);
		Ziper ziper = new Ziper(outputZip.getAbsolutePath(), project);

		//sources folder
		buildSources(ziper, module);

		//Classpath
		buildClasspath(ziper, module);

		ProgressManager.getInstance().run(new NoPolTask(project, "NoPol is Fixing", outputZip.getAbsolutePath()));
		ziper.close();
		this.parent.close(0);
	} catch (IOException e1) {
		throw new RuntimeException(e1);
	}
}
 
Example 9
Source File: CodeCompletionHandlerBase.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static WatchingInsertionContext insertItemHonorBlockSelection(CompletionProcessEx indicator, LookupElement item, char completionChar, StatisticsUpdate update) {
  final Editor editor = indicator.getEditor();

  final int caretOffset = indicator.getCaret().getOffset();
  final int idEndOffset = calcIdEndOffset(indicator);
  final int idEndOffsetDelta = idEndOffset - caretOffset;

  WatchingInsertionContext context;
  if (editor.getCaretModel().supportsMultipleCarets()) {
    Ref<WatchingInsertionContext> lastContext = Ref.create();
    Editor hostEditor = InjectedLanguageUtil.getTopLevelEditor(editor);
    boolean wasInjected = hostEditor != editor;
    OffsetsInFile topLevelOffsets = indicator.getHostOffsets();
    hostEditor.getCaretModel().runForEachCaret(caret -> {
      OffsetsInFile targetOffsets = findInjectedOffsetsIfAny(caret, wasInjected, topLevelOffsets, hostEditor);
      PsiFile targetFile = targetOffsets.getFile();
      Editor targetEditor = InjectedLanguageUtil.getInjectedEditorForInjectedFile(hostEditor, targetFile);
      int targetCaretOffset = targetEditor.getCaretModel().getOffset();
      int idEnd = targetCaretOffset + idEndOffsetDelta;
      if (idEnd > targetEditor.getDocument().getTextLength()) {
        idEnd = targetCaretOffset; // no replacement by Tab when offsets gone wrong for some reason
      }
      WatchingInsertionContext currentContext = insertItem(indicator.getLookup(), item, completionChar, update, targetEditor, targetFile, targetCaretOffset, idEnd, targetOffsets.getOffsets());
      lastContext.set(currentContext);
    });
    context = lastContext.get();
  }
  else {
    PsiFile psiFile = PsiUtilBase.getPsiFileInEditor(editor, indicator.getProject());
    context = insertItem(indicator.getLookup(), item, completionChar, update, editor, psiFile, caretOffset, idEndOffset, indicator.getOffsetMap());
  }
  if (context.shouldAddCompletionChar()) {
    WriteAction.run(() -> addCompletionChar(context, item));
  }
  checkPsiTextConsistency(indicator);

  return context;
}
 
Example 10
Source File: GotoTestOrCodeAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
@RequiredUIAccess
@Override
public void update(AnActionEvent event) {
  Presentation p = event.getPresentation();
  if (TestFinderHelper.getFinders().length == 0) {
    p.setVisible(false);
    return;
  }
  p.setEnabled(false);
  Project project = event.getData(CommonDataKeys.PROJECT);
  Editor editor = event.getData(PlatformDataKeys.EDITOR);
  if (editor == null || project == null) return;

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

  PsiElement element = GotoTestOrCodeHandler.getSelectedElement(editor, psiFile);

  if (TestFinderHelper.findSourceElement(element) == null) return;

  p.setEnabled(true);
  if (TestFinderHelper.isTest(element)) {
    p.setText(ActionsBundle.message("action.GotoTestSubject.text"));
    p.setDescription(ActionsBundle.message("action.GotoTestSubject.description"));
  } else {
    p.setText(ActionsBundle.message("action.GotoTest.text"));
    p.setDescription(ActionsBundle.message("action.GotoTest.description"));
  }
}
 
Example 11
Source File: LookupTypedHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(@Nonnull Editor originalEditor, char charTyped, @Nonnull DataContext dataContext) {
  final Project project = dataContext.getData(CommonDataKeys.PROJECT);
  PsiFile file = project == null ? null : PsiUtilBase.getPsiFileInEditor(originalEditor, project);

  if (file == null) {
    if (myOriginalHandler != null) {
      myOriginalHandler.execute(originalEditor, charTyped, dataContext);
    }
    return;
  }

  if (!EditorModificationUtil.checkModificationAllowed(originalEditor)) {
    return;
  }

  CompletionPhase oldPhase = CompletionServiceImpl.getCompletionPhase();
  if (oldPhase instanceof CompletionPhase.CommittingDocuments && oldPhase.indicator != null) {
    oldPhase.indicator.scheduleRestart();
  }

  Editor editor = TypedHandler.injectedEditorIfCharTypedIsSignificant(charTyped, originalEditor, file);
  if (editor != originalEditor) {
    file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
  }

  if (originalEditor.isInsertMode() && beforeCharTyped(charTyped, project, originalEditor, editor, file)) {
    return;
  }

  if (myOriginalHandler != null) {
    myOriginalHandler.execute(originalEditor, charTyped, dataContext);
  }
}
 
Example 12
Source File: PsiFileUtil.java    From needsmoredojo with Apache License 2.0 5 votes vote down vote up
public static PsiFile getPsiFileInCurrentEditor(Project project)
{
    Editor editor = FileEditorManager.getInstance(project).getSelectedTextEditor();

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

    PsiFile psiFile = PsiUtilBase.getPsiFileInEditor(editor, editor.getProject());

    return psiFile;
}
 
Example 13
Source File: ServiceGenerateAction.java    From idea-php-symfony2-plugin with MIT License 5 votes vote down vote up
private boolean invokeFile(Project project, Editor editor) {

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

        SymfonyCreateService.create(editor.getComponent(), project, file, editor);

        return true;
    }
 
Example 14
Source File: AbstractDelombokAction.java    From lombok-intellij-plugin with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void actionPerformed(@NotNull AnActionEvent event) {
  final Project project = event.getProject();
  if (project == null) {
    return;
  }

  PsiDocumentManager psiDocumentManager = PsiDocumentManager.getInstance(project);
  if (psiDocumentManager.hasUncommitedDocuments()) {
    psiDocumentManager.commitAllDocuments();
  }

  final DataContext dataContext = event.getDataContext();
  final Editor editor = PlatformDataKeys.EDITOR.getData(dataContext);

  if (null != editor) {
    final PsiFile psiFile = PsiUtilBase.getPsiFileInEditor(editor, project);
    if (null != psiFile) {
      final PsiClass targetClass = getTargetClass(editor, psiFile);
      if (null != targetClass) {
        process(project, psiFile, targetClass);
      }
    }
  } else {
    final VirtualFile[] files = PlatformDataKeys.VIRTUAL_FILE_ARRAY.getData(dataContext);
    if (null != files) {
      for (VirtualFile file : files) {
        if (file.isDirectory()) {
          processDirectory(project, file);
        } else {
          processFile(project, file);
        }
      }
    }
  }
}
 
Example 15
Source File: CodeCompletionHandlerBase.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static void checkPsiTextConsistency(CompletionProcessEx indicator) {
  PsiFile psiFile = PsiUtilBase.getPsiFileInEditor(InjectedLanguageUtil.getTopLevelEditor(indicator.getEditor()), indicator.getProject());
  if (psiFile != null) {
    if (Registry.is("ide.check.stub.text.consistency") || ApplicationManager.getApplication().isUnitTestMode() && !ApplicationInfoImpl.isInPerformanceTest()) {
      StubTextInconsistencyException.checkStubTextConsistency(psiFile);
      if (PsiDocumentManager.getInstance(psiFile.getProject()).hasUncommitedDocuments()) {
        PsiDocumentManager.getInstance(psiFile.getProject()).commitAllDocuments();
        StubTextInconsistencyException.checkStubTextConsistency(psiFile);
      }
    }
  }
}
 
Example 16
Source File: MainAction.java    From GsonFormat with Apache License 2.0 5 votes vote down vote up
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);
    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);

}
 
Example 17
Source File: ActionKit.java    From LayoutMaster with Apache License 2.0 5 votes vote down vote up
public static PsiFile getCurrentEditFile(AnActionEvent anActionEvent) {
  PsiFile psiFile = anActionEvent.getData(CommonDataKeys.PSI_FILE);
  if (psiFile != null) {
    return psiFile;
  }

  Project project = anActionEvent.getProject();
  Editor editor = anActionEvent.getData(CommonDataKeys.EDITOR_EVEN_IF_INACTIVE);

  if (editor == null || project == null) {
    return null;
  }

  return PsiUtilBase.getPsiFileInEditor(editor, project);
}
 
Example 18
Source File: BraceHighlightingHandler.java    From consulo with Apache License 2.0 4 votes vote down vote up
static void lookForInjectedAndMatchBracesInOtherThread(@Nonnull final Editor editor,
                                                       @Nonnull final Alarm alarm,
                                                       @Nonnull final Processor<BraceHighlightingHandler> processor) {
  ApplicationEx application = (ApplicationEx)Application.get();
  application.assertIsDispatchThread();
  if (!isValidEditor(editor)) return;
  if (!PROCESSED_EDITORS.add(editor)) {
    // Skip processing if that is not really necessary.
    // Assuming to be in EDT here.
    return;
  }
  final int offset = editor.getCaretModel().getOffset();
  final Project project = editor.getProject();
  final PsiFile psiFile = PsiUtilBase.getPsiFileInEditor(editor, project);
  if (!isValidFile(psiFile)) return;
  application.executeOnPooledThread(() -> {
    if (!application.tryRunReadAction(() -> {
      final PsiFile injected;
      try {
        if (psiFile instanceof PsiBinaryFile || !isValidEditor(editor) || !isValidFile(psiFile)) {
          injected = null;
        }
        else {
          injected = getInjectedFileIfAny(editor, project, offset, psiFile, alarm);
        }
      }
      catch (RuntimeException e) {
        // Reset processing flag in case of unexpected exception.
        application.invokeLater(new DumbAwareRunnable() {
          @Override
          public void run() {
            PROCESSED_EDITORS.remove(editor);
          }
        });
        throw e;
      }
      application.invokeLater(new DumbAwareRunnable() {
        @Override
        public void run() {
          try {
            if (isValidEditor(editor) && isValidFile(injected)) {
              Editor newEditor = InjectedLanguageUtil.getInjectedEditorForInjectedFile(editor, injected);
              BraceHighlightingHandler handler = new BraceHighlightingHandler(project, newEditor, alarm, injected);
              processor.process(handler);
            }
          }
          finally {
            PROCESSED_EDITORS.remove(editor);
          }
        }
      }, ModalityState.stateForComponent(editor.getComponent()));
    })) {
      // write action is queued in AWT. restart after it's finished
      application.invokeLater(() -> {
        PROCESSED_EDITORS.remove(editor);
        lookForInjectedAndMatchBracesInOtherThread(editor, alarm, processor);
      }, ModalityState.stateForComponent(editor.getComponent()));
    }
  });
}
 
Example 19
Source File: InjectAction.java    From android-butterknife-zelezny with Apache License 2.0 4 votes vote down vote up
protected void showDialog(Project project, Editor editor, ArrayList<Element> elements) {
    PsiFile file = PsiUtilBase.getPsiFileInEditor(editor, project);
    if (file == null) {
        return;
    }
    PsiClass clazz = getTargetClass(editor, file);

    final IButterKnife butterKnife = ButterKnifeFactory.findButterKnifeForPsiElement(project, file);
    if (clazz == null || butterKnife == null) {
        return;
    }

    // get parent classes and check if it's an adapter
    boolean createHolder = false;
    PsiReferenceList list = clazz.getExtendsList();
    if (list != null) {
        for (PsiJavaCodeReferenceElement element : list.getReferenceElements()) {
            if (Definitions.adapters.contains(element.getQualifiedName())) {
                createHolder = true;
            }
        }
    }

    // get already generated injections
    ArrayList<String> ids = new ArrayList<String>();
    PsiField[] fields = clazz.getAllFields();
    String[] annotations;
    String id;

    for (PsiField field : fields) {
        annotations = field.getFirstChild().getText().split(" ");

        for (String annotation : annotations) {
            id = Utils.getInjectionID(butterKnife, annotation.trim());
            if (!Utils.isEmptyString(id)) {
                ids.add(id);
            }
        }
    }

    EntryList panel = new EntryList(project, editor, elements, ids, createHolder, this, this);

    mDialog = new JFrame();
    mDialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
    mDialog.getRootPane().setDefaultButton(panel.getConfirmButton());
    mDialog.getContentPane().add(panel);
    mDialog.pack();
    mDialog.setLocationRelativeTo(null);
    mDialog.setVisible(true);
}
 
Example 20
Source File: ParameterInfoController.java    From consulo with Apache License 2.0 4 votes vote down vote up
public void updateComponent() {
  if (!myKeepOnHintHidden && !myHint.isVisible() && !ApplicationManager.getApplication().isHeadlessEnvironment() || myEditor instanceof EditorWindow && !((EditorWindow)myEditor).isValid()) {
    Disposer.dispose(this);
    return;
  }

  final PsiFile file = PsiUtilBase.getPsiFileInEditor(myEditor, myProject);
  int caretOffset = myEditor.getCaretModel().getOffset();
  final int offset = getCurrentOffset();
  final MyUpdateParameterInfoContext context = new MyUpdateParameterInfoContext(offset, file);
  executeFindElementForUpdatingParameterInfo(context, elementForUpdating -> {
    myHandler.processFoundElementForUpdatingParameterInfo(elementForUpdating, context);
    if (elementForUpdating != null) {
      executeUpdateParameterInfo(elementForUpdating, context, () -> {
        boolean knownParameter = (myComponent.getObjects().length == 1 || myComponent.getHighlighted() != null) && myComponent.getCurrentParameterIndex() != -1;
        if (mySingleParameterInfo && !knownParameter && myHint.isVisible()) {
          hideHint();
        }
        if (myKeepOnHintHidden && knownParameter && !myHint.isVisible()) {
          AutoPopupController.getInstance(myProject).autoPopupParameterInfo(myEditor, null);
        }
        if (!myDisposed &&
            (myHint.isVisible() && !myEditor.isDisposed() && (myEditor.getComponent().getRootPane() != null || ApplicationManager.getApplication().isUnitTestMode()) ||
             ApplicationManager.getApplication().isHeadlessEnvironment())) {
          Model result = myComponent.update(mySingleParameterInfo);
          result.project = myProject;
          result.range = myComponent.getParameterOwner().getTextRange();
          result.editor = myEditor;
          //for (ParameterInfoListener listener : ParameterInfoListener.EP_NAME.getExtensionList()) {
          //  listener.hintUpdated(result);
          //}
          if (ApplicationManager.getApplication().isHeadlessEnvironment()) return;
          IdeTooltip tooltip = myHint.getCurrentIdeTooltip();
          short position = tooltip != null ? toShort(tooltip.getPreferredPosition()) : HintManager.ABOVE;
          Pair<Point, Short> pos = myProvider.getBestPointPosition(myHint, elementForUpdating, caretOffset, myEditor.getCaretModel().getVisualPosition(), position);
          HintManagerImpl.adjustEditorHintPosition(myHint, myEditor, pos.getFirst(), pos.getSecond());
        }
      });
    }
    else {
      hideHint();
      if (!myKeepOnHintHidden) {
        Disposer.dispose(this);
      }
    }
  });
}