Example usage for com.intellij.openapi.ui.popup JBPopup showInBestPositionFor

List of usage examples for com.intellij.openapi.ui.popup JBPopup showInBestPositionFor

Introduction

In this page you can find the example usage for com.intellij.openapi.ui.popup JBPopup showInBestPositionFor.

Prototype

void showInBestPositionFor(@NotNull Editor editor);

Source Link

Document

Shows the popup near the cursor location in the specified editor.

Usage

From source file:com.android.tools.idea.actions.EditMultipleSourcesAction.java

License:Apache License

@Override
public void actionPerformed(AnActionEvent e) {
    Project project = e.getData(CommonDataKeys.PROJECT);
    assert project != null;

    final Navigatable[] files = e.getData(CommonDataKeys.NAVIGATABLE_ARRAY);
    assert files != null && files.length > 0;

    if (files.length > 1) {
        DefaultListModel listModel = new DefaultListModel();
        for (int i = 0; i < files.length; ++i) {
            assert files[i] instanceof PsiClassNavigation;
            //noinspection unchecked
            listModel.add(i, ((PsiClassNavigation) files[i]).getPsiFile());
        }//from   w ww. j a  v a 2  s . co m
        final JBList list = new JBList(listModel);
        int width = WindowManager.getInstance().getFrame(project).getSize().width;
        list.setCellRenderer(new GotoFileCellRenderer(width));

        JBPopup popup = JBPopupFactory.getInstance().createListPopupBuilder(list).setTitle("Choose Target File")
                .setItemChoosenCallback(new Runnable() {
                    @Override
                    public void run() {
                        Object selectedValue = list.getSelectedValue();
                        PsiClassNavigation navigationWrapper = null;
                        for (Navigatable file : files) {
                            if (selectedValue == ((PsiClassNavigation) file).getPsiFile()) {
                                navigationWrapper = (PsiClassNavigation) file;
                                break;
                            }
                        }
                        assert navigationWrapper != null;
                        if (navigationWrapper.canNavigate()) {
                            navigationWrapper.navigate(true);
                        }
                    }
                }).createPopup();

        if (e.getInputEvent().getSource() instanceof ActionButton) {
            popup.showUnderneathOf((ActionButton) e.getInputEvent().getSource());
        } else {
            popup.showInBestPositionFor(e.getDataContext());
        }
    } else {
        assert files[0] instanceof PsiClassNavigation;
        PsiClassNavigation file = (PsiClassNavigation) files[0];
        if (file.canNavigate()) {
            file.navigate(true);
        }
    }
}

From source file:com.android.tools.idea.lint.ShowCustomIssueExplanationFix.java

License:Apache License

@Override
public void apply(@NotNull PsiElement startElement, @NotNull PsiElement endElement,
        @NotNull AndroidQuickfixContexts.Context context) {
    Project project = myElement.getProject();
    DocumentationManager manager = DocumentationManager.getInstance(project);
    DocumentationComponent component = new DocumentationComponent(manager);
    component.setText("<html>" + myIssue.getExplanation(TextFormat.HTML) + "</html>", myElement, false);
    JBPopup popup = JBPopupFactory.getInstance().createComponentPopupBuilder(component, component)
            .setDimensionServiceKey(project, DocumentationManager.JAVADOC_LOCATION_AND_SIZE, false)
            .setResizable(true).setMovable(true).setRequestFocus(true).createPopup();
    component.setHint(popup);// w  w  w.ja  va  2  s . c  o m
    if (context.getType() == AndroidQuickfixContexts.EditorContext.TYPE) {
        popup.showInBestPositionFor(((AndroidQuickfixContexts.EditorContext) context).getEditor());
    } else {
        popup.showCenteredInCurrentWindow(project);
    }
    Disposer.dispose(component);
}

From source file:com.goide.codeInsight.imports.GoImportPackageQuickFix.java

License:Apache License

private void perform(@Nonnull List<String> packagesToImport, @Nonnull PsiFile file, @Nullable Editor editor) {
    LOG.assertTrue(editor != null || packagesToImport.size() == 1,
            "Cannot invoke fix with ambiguous imports on null editor");
    if (packagesToImport.size() > 1 && editor != null) {
        JBList list = new JBList(packagesToImport);
        list.installCellRenderer(o -> {
            JBLabel label = new JBLabel(o.toString(), TargetAWT.to(GoIcons.PACKAGE), SwingConstants.LEFT);
            label.setBorder(IdeBorderFactory.createEmptyBorder(2, 4, 2, 4));
            return label;
        });/*from   www  .j  a  v a  2s.  c  o  m*/
        PopupChooserBuilder builder = JBPopupFactory.getInstance().createListPopupBuilder(list)
                .setRequestFocus(true).setTitle("Package to import").setItemChoosenCallback(() -> {
                    int i = list.getSelectedIndex();
                    if (i < 0)
                        return;
                    perform(file, packagesToImport.get(i));
                }).setFilteringEnabled(o -> o instanceof String ? (String) o : o.toString());
        JBPopup popup = builder.createPopup();
        builder.getScrollPane().setBorder(null);
        builder.getScrollPane().setViewportBorder(null);
        popup.showInBestPositionFor(editor);
    } else if (packagesToImport.size() == 1) {
        perform(file, getFirstItem(packagesToImport));
    } else {
        String packages = StringUtil.join(packagesToImport, ",");
        throw new IncorrectOperationException(
                "Cannot invoke fix with ambiguous imports on editor ()" + editor + ". Packages: " + packages);
    }
}

From source file:com.intellij.codeInsight.daemon.impl.PsiElementListNavigator.java

License:Apache License

public static void openTargets(Editor e, NavigatablePsiElement[] targets, String title,
        final String findUsagesTitle, ListCellRenderer listRenderer) {
    JBPopup popup = navigateOrCreatePopup(targets, title, findUsagesTitle, listRenderer, null);
    if (popup != null)
        popup.showInBestPositionFor(e);
}

From source file:com.intellij.codeInsight.daemon.impl.quickfix.AddModuleDependencyFix.java

License:Apache License

@Override
public void invoke(@NotNull final Project project, @Nullable final Editor editor, PsiFile file) {
    if (myModules.size() == 1) {
        addDependencyOnModule(project, editor, myModules.get(0));
    } else {/* w  w w.  j a  v a  2s.c  o m*/
        final JBList list = new JBList(myModules);
        list.setCellRenderer(new ListCellRendererWrapper<Module>() {
            @Override
            public void customize(JList list, Module module, int index, boolean selected, boolean hasFocus) {
                if (module != null) {
                    setIcon(AllIcons.Nodes.Module);
                    setText(module.getName());
                }
            }
        });
        final JBPopup popup = JBPopupFactory.getInstance().createListPopupBuilder(list)
                .setTitle("Choose Module to Add Dependency on").setMovable(false).setResizable(false)
                .setRequestFocus(true).setItemChoosenCallback(new Runnable() {
                    @Override
                    public void run() {
                        final Object value = list.getSelectedValue();
                        if (value instanceof Module) {
                            addDependencyOnModule(project, editor, (Module) value);
                        }
                    }
                }).createPopup();
        if (editor != null) {
            popup.showInBestPositionFor(editor);
        } else {
            popup.showCenteredInCurrentWindow(project);
        }
    }
}

From source file:com.intellij.codeInsight.navigation.GotoTargetHandler.java

License:Apache License

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;//ww  w. ja va2s. c  o m
    }

    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();
    final 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.setFont(ChooseByNameBase.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 = 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);
                    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(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 Ref<UsageView> usageView = new Ref<UsageView>();
    final JBPopup popup = builder.setTitle(title).setItemChoosenCallback(runnable).setMovable(true)
            .setCancelCallback(new Computable<Boolean>() {
                @Override
                public Boolean compute() {
                    HintUpdateSupply.hideHint(list);
                    return true;
                }
            }).setCouldPin(new Processor<JBPopup>() {
                @Override
                public boolean process(JBPopup popup) {
                    usageView.set(FindUtil.showInUsageView(gotoData.source, gotoData.targets,
                            getFindUsagesTitle(gotoData.source, name, gotoData.targets.length), project));
                    popup.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);
}

From source file:com.intellij.codeInsight.unwrap.UnwrapHandler.java

License:Apache License

private void showPopup(final List<AnAction> options, Editor editor) {
    final ScopeHighlighter highlighter = new ScopeHighlighter(editor);

    DefaultListModel m = new DefaultListModel();
    for (AnAction a : options) {
        m.addElement(((MyUnwrapAction) a).getName());
    }/*w  w  w.j  a va2 s. c  o m*/

    final JList list = new JBList(m);
    list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    list.setVisibleRowCount(options.size());

    list.addListSelectionListener(new ListSelectionListener() {
        @Override
        public void valueChanged(ListSelectionEvent e) {
            int index = list.getSelectedIndex();
            if (index < 0)
                return;

            MyUnwrapAction a = (MyUnwrapAction) options.get(index);

            List<PsiElement> toExtract = new ArrayList<PsiElement>();
            PsiElement wholeRange = a.collectAffectedElements(toExtract);
            highlighter.highlight(wholeRange, toExtract);
        }
    });

    PopupChooserBuilder builder = JBPopupFactory.getInstance().createListPopupBuilder(list);
    builder.setTitle(CodeInsightBundle.message("unwrap.popup.title")).setMovable(false).setResizable(false)
            .setRequestFocus(true).setItemChoosenCallback(new Runnable() {
                @Override
                public void run() {
                    MyUnwrapAction a = (MyUnwrapAction) options.get(list.getSelectedIndex());
                    a.actionPerformed(null);
                }
            }).addListener(new JBPopupAdapter() {
                @Override
                public void onClosed(LightweightWindowEvent event) {
                    highlighter.dropHighlight();
                }
            });

    JBPopup popup = builder.createPopup();
    popup.showInBestPositionFor(editor);
}

From source file:com.intellij.codeInspection.ui.InspectionResultsView.java

License:Apache License

public static void showPopup(AnActionEvent e, JBPopup popup) {
    final InputEvent event = e.getInputEvent();
    if (event instanceof MouseEvent) {
        popup.showUnderneathOf(event.getComponent());
    } else {/*from  w  w w  . ja v a2s  .com*/
        popup.showInBestPositionFor(e.getDataContext());
    }
}

From source file:com.intellij.ui.popup.PopupPositionManager.java

License:Apache License

public static void positionPopupInBestPosition(final JBPopup hint, @Nullable final Editor editor,
        @Nullable DataContext dataContext) {
    final LookupEx lookup = LookupManager.getActiveLookup(editor);
    if (lookup != null && lookup.getCurrentItem() != null) {
        new PositionAdjuster(lookup.getComponent()).adjust(hint);
        lookup.addLookupListener(new LookupAdapter() {
            @Override//www .j a v a 2  s  . co m
            public void lookupCanceled(LookupEvent event) {
                if (hint.isVisible()) {
                    hint.cancel();
                }
            }
        });
        return;
    }

    final PositionAdjuster positionAdjuster = createPositionAdjuster();
    if (positionAdjuster != null) {
        positionAdjuster.adjust(hint);
        return;
    }

    if (editor != null && editor.getComponent().isShowing()) {
        hint.showInBestPositionFor(editor);
        return;
    }

    if (dataContext != null) {
        hint.showInBestPositionFor(dataContext);
    }
}

From source file:com.intellij.xdebugger.impl.ui.DebuggerUIUtil.java

License:Apache License

public static void showValuePopup(@NotNull XFullValueEvaluator evaluator, @NotNull MouseEvent event,
        @NotNull Project project, @Nullable Editor editor) {
    EditorTextField textArea = new TextViewer("Evaluating...", project);
    textArea.setBackground(HintUtil.INFORMATION_COLOR);

    final FullValueEvaluationCallbackImpl callback = new FullValueEvaluationCallbackImpl(textArea);
    evaluator.startEvaluation(callback);

    Dimension size = DimensionService.getInstance().getSize(FULL_VALUE_POPUP_DIMENSION_KEY, project);
    if (size == null) {
        Dimension frameSize = WindowManager.getInstance().getFrame(project).getSize();
        size = new Dimension(frameSize.width / 2, frameSize.height / 2);
    }//from ww  w  .ja va  2s  . c  o  m

    textArea.setPreferredSize(size);

    JBPopup popup = createValuePopup(project, textArea, callback);
    if (editor == null) {
        Rectangle bounds = new Rectangle(event.getLocationOnScreen(), size);
        ScreenUtil.fitToScreenVertical(bounds, 5, 5, true);
        if (size.width != bounds.width || size.height != bounds.height) {
            size = bounds.getSize();
            textArea.setPreferredSize(size);
        }
        popup.showInScreenCoordinates(event.getComponent(), bounds.getLocation());
    } else {
        popup.showInBestPositionFor(editor);
    }
}