@Override public boolean showHint(@NotNull Editor editor) { if (suggestions.isEmpty()) { return false; } final Project project = editor.getProject(); if (project == null) { return false; } if (HintManager.getInstance().hasShownHintsThatWillHideByOtherHint(true)) { return false; } if (!ApplicationManager.getApplication().isUnitTestMode()) { String hintText = ShowAutoImportPass.getMessage( suggestions.size() > 1, suggestions.iterator().next().getFqName()); HintManager.getInstance() .showQuestionHint( editor, hintText, element.getTextOffset(), element.getTextRange().getEndOffset(), createAction(project, editor)); } return true; }
public static void invokeImpl( Project project, Editor editor, final PsiFile file, Injectable injectable) { final PsiLanguageInjectionHost host = findInjectionHost(editor, file); if (host == null) return; if (defaultFunctionalityWorked(host, injectable.getId())) return; try { host.putUserData(FIX_KEY, null); Language language = injectable.toLanguage(); for (LanguageInjectionSupport support : InjectorUtils.getActiveInjectionSupports()) { if (support.isApplicableTo(host) && support.addInjectionInPlace(language, host)) { return; } } if (TemporaryPlacesRegistry.getInstance(project) .getLanguageInjectionSupport() .addInjectionInPlace(language, host)) { final Processor<PsiLanguageInjectionHost> data = host.getUserData(FIX_KEY); String text = StringUtil.escapeXml(language.getDisplayName()) + " was temporarily injected."; if (data != null) { if (!ApplicationManager.getApplication().isUnitTestMode()) { final SmartPsiElementPointer<PsiLanguageInjectionHost> pointer = SmartPointerManager.getInstance(project).createSmartPsiElementPointer(host); final TextRange range = host.getTextRange(); HintManager.getInstance() .showQuestionHint( editor, text + "<br>Do you want to insert annotation? " + KeymapUtil.getFirstKeyboardShortcutText( ActionManager.getInstance() .getAction(IdeActions.ACTION_SHOW_INTENTION_ACTIONS)), range.getStartOffset(), range.getEndOffset(), new QuestionAction() { @Override public boolean execute() { return data.process(pointer.getElement()); } }); } } else { HintManager.getInstance().showInformationHint(editor, text); } } } finally { if (injectable.getLanguage() != null) { // no need for reference injection FileContentUtil.reparseFiles(project, Collections.<VirtualFile>emptyList(), true); } else { ((PsiModificationTrackerImpl) PsiManager.getInstance(project).getModificationTracker()) .incCounter(); DaemonCodeAnalyzer.getInstance(project).restart(); } } }
@Override public void runExecuteAction(@NotNull LanguageConsoleView console) { if (isEnabled()) { if (!canExecuteNow()) { HintManager.getInstance() .showErrorHint(console.getConsole().getConsoleEditor(), getPrevCommandRunningMessage()); } else { doRunExecuteAction(console); } } else { HintManager.getInstance() .showErrorHint(console.getConsole().getConsoleEditor(), getConsoleIsNotEnabledMessage()); } }
protected void performHighlighting() { boolean clearHighlights = HighlightUsagesHandler.isClearHighlights(myEditor); EditorColorsManager manager = EditorColorsManager.getInstance(); TextAttributes attributes = manager.getGlobalScheme().getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES); TextAttributes writeAttributes = manager.getGlobalScheme().getAttributes(EditorColors.WRITE_SEARCH_RESULT_ATTRIBUTES); HighlightUsagesHandler.highlightRanges( HighlightManager.getInstance(myEditor.getProject()), myEditor, attributes, clearHighlights, myReadUsages); HighlightUsagesHandler.highlightRanges( HighlightManager.getInstance(myEditor.getProject()), myEditor, writeAttributes, clearHighlights, myWriteUsages); if (!clearHighlights) { WindowManager.getInstance().getStatusBar(myEditor.getProject()).setInfo(myStatusText); HighlightHandlerBase.setupFindModel(myEditor.getProject()); // enable f3 navigation } if (myHintText != null) { HintManager.getInstance().showInformationHint(myEditor, myHintText); } }
private void disposeHighlighter() { if (myHighlighter != null) { myHighlighter.uninstall(); HintManager.getInstance().hideAllHints(); myHighlighter = null; } }
@Nullable public static PsiElement invokeCreateCompilerPass( @NotNull PhpClass bundleClass, @Nullable Editor editor) { String className = Messages.showInputDialog( "Class name for CompilerPass (no namespace needed): ", "New File", Symfony2Icons.SYMFONY); if (StringUtils.isBlank(className)) { return null; } if (!PhpNameUtil.isValidClassName(className)) { Messages.showMessageDialog( bundleClass.getProject(), "Invalid class name", "Error", Symfony2Icons.SYMFONY); } try { return PhpBundleFileFactory.createCompilerPass(bundleClass, className); } catch (Exception e) { if (editor != null) { HintManager.getInstance().showErrorHint(editor, "Error:" + e.getMessage()); } else { JOptionPane.showMessageDialog(null, "Error:" + e.getMessage()); } } return null; }
@Override public void actionPerformed(AnActionEvent e) { DataContext dataContext = e.getDataContext(); final Project project = CommonDataKeys.PROJECT.getData(dataContext); if (project == null) return; PsiDocumentManager.getInstance(project).commitAllDocuments(); Editor editor = CommonDataKeys.EDITOR.getData(dataContext); UsageTarget[] usageTargets = UsageView.USAGE_TARGETS_KEY.getData(dataContext); if (usageTargets != null) { FileEditor fileEditor = PlatformDataKeys.FILE_EDITOR.getData(dataContext); if (fileEditor != null) { usageTargets[0].findUsagesInEditor(fileEditor); } } else if (editor == null) { Messages.showMessageDialog( project, FindBundle.message("find.no.usages.at.cursor.error"), CommonBundle.getErrorTitle(), Messages.getErrorIcon()); } else { HintManager.getInstance() .showErrorHint(editor, FindBundle.message("find.no.usages.at.cursor.error")); } }
public boolean showHint(@NotNull final Editor editor) { myEditor = editor; final PsiElement element = myReference.getElement(); TextRange range = InjectedLanguageManager.getInstance(element.getProject()) .injectedToHost(element, element.getTextRange()); HintManager.getInstance() .showQuestionHint(editor, getText(), range.getStartOffset(), range.getEndOffset(), this); return true; }
public void setImportHintsEnabled(@NotNull PsiFile file, boolean value) { VirtualFile vFile = file.getVirtualFile(); if (value) { myDisabledHintsFiles.remove(vFile); stopProcess(true); } else { myDisabledHintsFiles.add(vFile); HintManager.getInstance().hideAllHints(); } }
private void showHint( @NotNull String text, @Nullable final Editor editor, @NotNull final RelativePoint popupPosition, @NotNull FindUsagesHandler handler, int maxUsages, @NotNull FindUsagesOptions options) { JComponent label = createHintComponent( text, handler, popupPosition, editor, HIDE_HINTS_ACTION, maxUsages, options); if (editor == null || editor.isDisposed()) { HintManager.getInstance() .showHint( label, popupPosition, HintManager.HIDE_BY_ANY_KEY | HintManager.HIDE_BY_TEXT_CHANGE | HintManager.HIDE_BY_SCROLLING, 0); } else { HintManager.getInstance().showInformationHint(editor, label); } }
private void doGenerate( final Editor editor, final PsiFile file, final PsiClass targetClass, final TestFramework framework) { if (framework instanceof JavaTestFramework && ((JavaTestFramework) framework).isSingleConfig()) { PsiElement alreadyExist = null; switch (myMethodKind) { case SET_UP: alreadyExist = framework.findSetUpMethod(targetClass); break; case TEAR_DOWN: alreadyExist = framework.findTearDownMethod(targetClass); break; default: break; } if (alreadyExist instanceof PsiMethod) { editor.getCaretModel().moveToOffset(alreadyExist.getNavigationElement().getTextOffset()); HintManager.getInstance() .showErrorHint( editor, "Method " + ((PsiMethod) alreadyExist).getName() + " already exists"); return; } } if (!CommonRefactoringUtil.checkReadOnlyStatus(file)) return; WriteCommandAction.runWriteCommandAction( file.getProject(), new Runnable() { @Override public void run() { try { PsiDocumentManager.getInstance(file.getProject()).commitAllDocuments(); PsiMethod method = generateDummyMethod(editor, file); if (method == null) return; TestIntegrationUtils.runTestMethodTemplate( myMethodKind, framework, editor, targetClass, method, "name", false, null); } catch (IncorrectOperationException e) { HintManager.getInstance() .showErrorHint(editor, "Cannot generate method: " + e.getMessage()); LOG.warn(e); } } }); }
private ImportClassFixBase.Result doFix(Editor editor) { if (!CodeInsightSettings.getInstance().ADD_MEMBER_IMPORTS_ON_THE_FLY) { return ImportClassFixBase.Result.POPUP_NOT_SHOWN; } final List<T> candidates = getMembersToImport(true); if (candidates.isEmpty()) { return ImportClassFixBase.Result.POPUP_NOT_SHOWN; } final PsiElement element = getElement(); if (element == null) { return ImportClassFixBase.Result.POPUP_NOT_SHOWN; } final QuestionAction action = createQuestionAction(candidates, element.getProject(), editor); /* PsiFile psiFile = element.getContainingFile(); if (candidates.size() == 1 && ImportClassFixBase.isAddUnambiguousImportsOnTheFlyEnabled(psiFile) && (ApplicationManager.getApplication().isUnitTestMode() || DaemonListeners.canChangeFileSilently(psiFile)) && !LaterInvocator.isInModalContext()) { CommandProcessor.getInstance().runUndoTransparentAction(() -> action.execute()); return ImportClassFixBase.Result.CLASS_AUTO_IMPORTED; } */ String hintText = ShowAutoImportPass.getMessage( candidates.size() > 1, getMemberPresentableText(candidates.get(0))); if (!ApplicationManager.getApplication().isUnitTestMode() && !HintManager.getInstance().hasShownHintsThatWillHideByOtherHint(true)) { final TextRange textRange = element.getTextRange(); HintManager.getInstance() .showQuestionHint( editor, hintText, textRange.getStartOffset(), textRange.getEndOffset(), action); } return ImportClassFixBase.Result.POPUP_SHOWN; }
private static LightweightHint showErrorHint(Project project, Editor editor, String text) { final LightweightHint[] result = {null}; final EditorHintListener listener = new EditorHintListener() { public void hintShown( final Project project, final LightweightHint hint, final int flags) { result[0] = hint; } }; final MessageBusConnection connection = project.getMessageBus().connect(); connection.subscribe(EditorHintListener.TOPIC, listener); assert text != null; HintManager.getInstance().showErrorHint(editor, text, HintManager.UNDER); connection.disconnect(); return result[0]; }
@Override public void invoke(@NotNull Project project, @NotNull Editor editor, @NotNull PsiFile file) { SelectionModel selectionModel = editor.getSelectionModel(); if (!selectionModel.hasSelection()) { selectionModel.selectLineAtCaret(); } ZenCodingTemplate emmetCustomTemplate = CustomLiveTemplate.EP_NAME.findExtension(ZenCodingTemplate.class); if (emmetCustomTemplate != null) { new WrapWithCustomTemplateAction( emmetCustomTemplate, editor, file, ContainerUtil.newHashSet()) .actionPerformed(null); } else if (!ApplicationManager.getApplication().isUnitTestMode()) { HintManager.getInstance() .showErrorHint(editor, "Cannot invoke Surround with Emmet in the current context"); } }
private static void chooseAmbiguousTarget( final Editor editor, int offset, PsiElement[] elements, PsiFile currentFile) { PsiElementProcessor<PsiElement> navigateProcessor = element -> { gotoTargetElement(element, editor, currentFile); return true; }; boolean found = chooseAmbiguousTarget( editor, offset, navigateProcessor, CodeInsightBundle.message("declaration.navigation.title"), elements); if (!found) { HintManager.getInstance().showErrorHint(editor, "Cannot find declaration to go to"); } }
@Override public void invoke( @NotNull final Project project, @NotNull final Editor editor, @NotNull final PsiFile file) { if (!CodeInsightUtilBase.prepareEditorForWrite(editor)) return; try { final XmlTag contextTag = getContextTag(editor, file); if (contextTag == null) { throw new CommonRefactoringUtil.RefactoringErrorHintException( "Caret should be positioned inside a tag"); } XmlElementDescriptor currentTagDescriptor = contextTag.getDescriptor(); assert currentTagDescriptor != null; final XmlElementDescriptor[] descriptors = currentTagDescriptor.getElementsDescriptors(contextTag); Arrays.sort( descriptors, new Comparator<XmlElementDescriptor>() { @Override public int compare(XmlElementDescriptor o1, XmlElementDescriptor o2) { return o1.getName().compareTo(o2.getName()); } }); final JBList list = new JBList(descriptors); list.setCellRenderer(new MyListCellRenderer()); Runnable runnable = new Runnable() { @Override public void run() { final XmlElementDescriptor selected = (XmlElementDescriptor) list.getSelectedValue(); new WriteCommandAction.Simple(project, "Generate XML Tag", file) { @Override protected void run() { if (selected == null) return; XmlTag newTag = createTag(contextTag, selected); PsiElement anchor = getAnchor(contextTag, editor, selected); if (anchor == null) { // insert it in the cursor position int offset = editor.getCaretModel().getOffset(); Document document = editor.getDocument(); document.insertString(offset, newTag.getText()); PsiDocumentManager.getInstance(project).commitDocument(document); newTag = PsiTreeUtil.getParentOfType( file.findElementAt(offset + 1), XmlTag.class, false); } else { newTag = (XmlTag) contextTag.addAfter(newTag, anchor); } if (newTag != null) { generateTag(newTag, editor); } } }.execute(); } }; if (ApplicationManager.getApplication().isUnitTestMode()) { XmlElementDescriptor descriptor = ContainerUtil.find( descriptors, new Condition<XmlElementDescriptor>() { @Override public boolean value(XmlElementDescriptor xmlElementDescriptor) { return xmlElementDescriptor.getName().equals(TEST_THREAD_LOCAL.get()); } }); list.setSelectedValue(descriptor, false); runnable.run(); } else { JBPopupFactory.getInstance() .createListPopupBuilder(list) .setTitle("Choose Tag Name") .setItemChoosenCallback(runnable) .setFilteringEnabled( new Function<Object, String>() { @Override public String fun(Object o) { return ((XmlElementDescriptor) o).getName(); } }) .createPopup() .showInBestPositionFor(editor); } } catch (CommonRefactoringUtil.RefactoringErrorHintException e) { HintManager.getInstance().showErrorHint(editor, e.getMessage()); } }
private void show(Project project, Editor editor, PsiFile file, final GotoData gotoData) { final PsiElement[] targets = gotoData.targets; final List<AdditionalAction> additionalActions = gotoData.additionalActions; if (targets.length == 0 && additionalActions.isEmpty()) { HintManager.getInstance().showErrorHint(editor, getNotFoundMessage(project, editor, file)); return; } if (targets.length == 1 && additionalActions.isEmpty()) { Navigatable descriptor = targets[0] instanceof Navigatable ? (Navigatable) targets[0] : EditSourceUtil.getDescriptor(targets[0]); if (descriptor != null && descriptor.canNavigate()) { navigateToElement(descriptor); } return; } for (PsiElement eachTarget : targets) { gotoData.renderers.put(eachTarget, createRenderer(gotoData, eachTarget)); } String name = ((PsiNamedElement) gotoData.source).getName(); String title = getChooserTitle(gotoData.source, name, targets.length); if (shouldSortTargets()) { Arrays.sort(targets, createComparator(gotoData.renderers, gotoData)); } List<Object> allElements = new ArrayList<Object>(targets.length + additionalActions.size()); Collections.addAll(allElements, targets); allElements.addAll(additionalActions); final JBListWithHintProvider list = new JBListWithHintProvider(new CollectionListModel<Object>(allElements)) { @Override protected PsiElement getPsiElementForHint(final Object selectedValue) { return selectedValue instanceof PsiElement ? (PsiElement) selectedValue : null; } }; list.setCellRenderer( new DefaultListCellRenderer() { @Override public Component getListCellRendererComponent( JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { if (value == null) return super.getListCellRendererComponent( list, value, index, isSelected, cellHasFocus); if (value instanceof AdditionalAction) { return myActionElementRenderer.getListCellRendererComponent( list, value, index, isSelected, cellHasFocus); } PsiElementListCellRenderer renderer = getRenderer(value, gotoData.renderers, gotoData); return renderer.getListCellRendererComponent( list, value, index, isSelected, cellHasFocus); } }); final Runnable runnable = new Runnable() { @Override public void run() { int[] ids = list.getSelectedIndices(); if (ids == null || ids.length == 0) return; Object[] selectedElements = list.getSelectedValues(); for (Object element : selectedElements) { if (element instanceof AdditionalAction) { ((AdditionalAction) element).execute(); } else { Navigatable nav = element instanceof Navigatable ? (Navigatable) element : EditSourceUtil.getDescriptor((PsiElement) element); if (nav != null && nav.canNavigate()) { navigateToElement(nav); } } } } }; final PopupChooserBuilder builder = new PopupChooserBuilder(list); builder.setFilteringEnabled( new Function<Object, String>() { @Override public String fun(Object o) { if (o instanceof AdditionalAction) { return ((AdditionalAction) o).getText(); } return getRenderer(o, gotoData.renderers, gotoData).getElementText((PsiElement) o); } }); final JBPopup popup = builder .setTitle(title) .setItemChoosenCallback(runnable) .setMovable(true) .setCancelCallback( new Computable<Boolean>() { @Override public Boolean compute() { list.hideHint(); return true; } }) .setAdText(getAdText(gotoData.source, targets.length)) .createPopup(); if (gotoData.listUpdaterTask != null) { gotoData.listUpdaterTask.init((AbstractPopup) popup, list); ProgressManager.getInstance().run(gotoData.listUpdaterTask); } popup.showInBestPositionFor(editor); }
private static void hideHints() { HintManager.getInstance().hideHints(HintManager.HIDE_BY_ANY_KEY, false, false); }
private void show( @NotNull final Project project, @NotNull Editor editor, @NotNull PsiFile file, @NotNull final GotoData gotoData) { final PsiElement[] targets = gotoData.targets; final List<AdditionalAction> additionalActions = gotoData.additionalActions; if (targets.length == 0 && additionalActions.isEmpty()) { HintManager.getInstance().showErrorHint(editor, getNotFoundMessage(project, editor, file)); return; } if (targets.length == 1 && additionalActions.isEmpty()) { Navigatable descriptor = targets[0] instanceof Navigatable ? (Navigatable) targets[0] : EditSourceUtil.getDescriptor(targets[0]); if (descriptor != null && descriptor.canNavigate()) { navigateToElement(descriptor); } return; } for (PsiElement eachTarget : targets) { gotoData.renderers.put(eachTarget, createRenderer(gotoData, eachTarget)); } final String name = ((PsiNamedElement) gotoData.source).getName(); boolean finished = gotoData.listUpdaterTask == null || gotoData.listUpdaterTask.isFinished(); final String title = getChooserTitle(gotoData.source, name, targets.length, finished); if (shouldSortTargets()) { Arrays.sort(targets, createComparator(gotoData.renderers, gotoData)); } List<Object> allElements = new ArrayList<Object>(targets.length + additionalActions.size()); Collections.addAll(allElements, targets); allElements.addAll(additionalActions); final JBListWithHintProvider list = new JBListWithHintProvider(new CollectionListModel<Object>(allElements)) { @Override protected PsiElement getPsiElementForHint(final Object selectedValue) { return selectedValue instanceof PsiElement ? (PsiElement) selectedValue : null; } }; list.setFont(EditorUtil.getEditorFont()); list.setCellRenderer( new DefaultListCellRenderer() { @Override public Component getListCellRendererComponent( JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { if (value == null) return super.getListCellRendererComponent( list, value, index, isSelected, cellHasFocus); if (value instanceof AdditionalAction) { return myActionElementRenderer.getListCellRendererComponent( list, value, index, isSelected, cellHasFocus); } PsiElementListCellRenderer renderer = getRenderer(value, gotoData.renderers, gotoData); return renderer.getListCellRendererComponent( list, value, index, isSelected, cellHasFocus); } }); final Runnable runnable = () -> { int[] ids = list.getSelectedIndices(); if (ids == null || ids.length == 0) return; Object[] selectedElements = list.getSelectedValues(); for (Object element : selectedElements) { if (element instanceof AdditionalAction) { ((AdditionalAction) element).execute(); } else { Navigatable nav = element instanceof Navigatable ? (Navigatable) element : EditSourceUtil.getDescriptor((PsiElement) element); try { if (nav != null && nav.canNavigate()) { navigateToElement(nav); } } catch (IndexNotReadyException e) { DumbService.getInstance(project) .showDumbModeNotification("Navigation is not available while indexing"); } } } }; final PopupChooserBuilder builder = new PopupChooserBuilder(list); builder.setFilteringEnabled( o -> { if (o instanceof AdditionalAction) { return ((AdditionalAction) o).getText(); } return getRenderer(o, gotoData.renderers, gotoData).getElementText((PsiElement) o); }); final Ref<UsageView> usageView = new Ref<UsageView>(); final JBPopup popup = builder .setTitle(title) .setItemChoosenCallback(runnable) .setMovable(true) .setCancelCallback( () -> { HintUpdateSupply.hideHint(list); final ListBackgroundUpdaterTask task = gotoData.listUpdaterTask; if (task != null) { task.cancelTask(); } return true; }) .setCouldPin( popup1 -> { usageView.set( FindUtil.showInUsageView( gotoData.source, gotoData.targets, getFindUsagesTitle(gotoData.source, name, gotoData.targets.length), project)); popup1.cancel(); return false; }) .setAdText(getAdText(gotoData.source, targets.length)) .createPopup(); builder.getScrollPane().setBorder(null); builder.getScrollPane().setViewportBorder(null); if (gotoData.listUpdaterTask != null) { gotoData.listUpdaterTask.init((AbstractPopup) popup, list, usageView); ProgressManager.getInstance().run(gotoData.listUpdaterTask); } popup.showInBestPositionFor(editor); }