Example usage for com.intellij.openapi.ui.popup JBPopupAdapter JBPopupAdapter

List of usage examples for com.intellij.openapi.ui.popup JBPopupAdapter JBPopupAdapter

Introduction

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

Prototype

JBPopupAdapter

Source Link

Usage

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

License:Apache License

public void init(@NotNull AbstractPopup popup, T component, Ref<UsageView> usageView) {
    myPopup = popup;/*from   www  . java  2s  .  c om*/
    myComponent = component;
    myUsageView = usageView;

    myPopup.addPopupListener(new JBPopupAdapter() {
        @Override
        public void onClosed(LightweightWindowEvent event) {
            setCanceled();
        }
    });
}

From source file:com.intellij.codeInsight.template.impl.LiveTemplateSettingsEditor.java

License:Apache License

private JPanel createShortContextPanel(final boolean allowNoContexts) {
    JPanel panel = new JPanel(new BorderLayout());

    final JLabel ctxLabel = new JLabel();
    final JLabel change = new JLabel();
    change.setForeground(PlatformColors.BLUE);
    change.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
    panel.add(ctxLabel, BorderLayout.CENTER);
    panel.add(change, BorderLayout.EAST);

    final Runnable updateLabel = new Runnable() {
        @Override//from w w w .  j  ava  2 s  .c  om
        public void run() {
            StringBuilder sb = new StringBuilder();
            String oldPrefix = "";
            for (TemplateContextType type : getApplicableContexts()) {
                final TemplateContextType base = type.getBaseContextType();
                String ownName = UIUtil.removeMnemonic(type.getPresentableName());
                String prefix = "";
                if (base != null && !(base instanceof EverywhereContextType)) {
                    prefix = UIUtil.removeMnemonic(base.getPresentableName()) + ": ";
                    ownName = StringUtil.decapitalize(ownName);
                }
                if (type instanceof EverywhereContextType) {
                    ownName = "Other";
                }
                if (sb.length() > 0) {
                    sb.append(oldPrefix.equals(prefix) ? ", " : "; ");
                }
                if (!oldPrefix.equals(prefix)) {
                    sb.append(prefix);
                    oldPrefix = prefix;
                }
                sb.append(ownName);
            }
            final boolean noContexts = sb.length() == 0;
            ctxLabel.setText((noContexts ? "No applicable contexts" + (allowNoContexts ? "" : " yet")
                    : "Applicable in " + sb.toString()) + ".  ");
            ctxLabel.setForeground(
                    noContexts ? allowNoContexts ? JBColor.GRAY : JBColor.RED : UIUtil.getLabelForeground());
            change.setText(noContexts ? "Define" : "Change");
        }
    };

    new ClickListener() {
        @Override
        public boolean onClick(MouseEvent e, int clickCount) {
            if (disposeContextPopup())
                return false;

            final JPanel content = createPopupContextPanel(updateLabel);
            Dimension prefSize = content.getPreferredSize();
            if (myLastSize != null
                    && (myLastSize.width > prefSize.width || myLastSize.height > prefSize.height)) {
                content.setPreferredSize(new Dimension(Math.max(prefSize.width, myLastSize.width),
                        Math.max(prefSize.height, myLastSize.height)));
            }
            myContextPopup = JBPopupFactory.getInstance().createComponentPopupBuilder(content, null)
                    .setResizable(true).createPopup();
            myContextPopup.show(new RelativePoint(change,
                    new Point(change.getWidth(), -content.getPreferredSize().height - 10)));
            myContextPopup.addListener(new JBPopupAdapter() {
                @Override
                public void onClosed(LightweightWindowEvent event) {
                    myLastSize = content.getSize();
                }
            });
            return true;
        }
    }.installOn(change);

    updateLabel.run();

    return panel;
}

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());
    }/* www  .ja  v a 2 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.notification.impl.NotificationsManagerImpl.java

License:Apache License

private static void showNotification(final Notification notification, @Nullable final Project project) {
    Application application = ApplicationManager.getApplication();
    if (application instanceof ApplicationEx && !((ApplicationEx) application).isLoaded()) {
        application.invokeLater(new Runnable() {
            @Override/*from  ww  w  . j  a va 2  s .c  o  m*/
            public void run() {
                showNotification(notification, project);
            }
        }, ModalityState.current());
        return;
    }

    String groupId = notification.getGroupId();
    final NotificationSettings settings = NotificationsConfigurationImpl.getSettings(groupId);

    NotificationDisplayType type = settings.getDisplayType();
    String toolWindowId = NotificationsConfigurationImpl.getInstanceImpl().getToolWindowId(groupId);
    if (type == NotificationDisplayType.TOOL_WINDOW && (toolWindowId == null || project == null
            || !ToolWindowManager.getInstance(project).canShowNotification(toolWindowId))) {
        type = NotificationDisplayType.BALLOON;
    }

    switch (type) {
    case NONE:
        return;
    //case EXTERNAL:
    //  notifyByExternal(notification);
    //  break;
    case STICKY_BALLOON:
    case BALLOON:
    default:
        Balloon balloon = notifyByBalloon(notification, type, project);
        if (!settings.isShouldLog() || type == NotificationDisplayType.STICKY_BALLOON) {
            if (balloon == null) {
                notification.expire();
            } else {
                balloon.addListener(new JBPopupAdapter() {
                    @Override
                    public void onClosed(LightweightWindowEvent event) {
                        if (!event.isOk()) {
                            notification.expire();
                        }
                    }
                });
            }
        }
        break;
    case TOOL_WINDOW:
        MessageType messageType = notification.getType() == NotificationType.ERROR ? MessageType.ERROR
                : notification.getType() == NotificationType.WARNING ? MessageType.WARNING : MessageType.INFO;
        final NotificationListener notificationListener = notification.getListener();
        HyperlinkListener listener = notificationListener == null ? null : new HyperlinkListener() {
            @Override
            public void hyperlinkUpdate(HyperlinkEvent e) {
                notificationListener.hyperlinkUpdate(notification, e);
            }
        };
        assert toolWindowId != null;
        String msg = notification.getTitle();
        if (StringUtil.isNotEmpty(notification.getContent())) {
            if (StringUtil.isNotEmpty(msg)) {
                msg += "<br>";
            }
            msg += notification.getContent();
        }

        //noinspection SSBasedInspection
        ToolWindowManager.getInstance(project).notifyByBalloon(toolWindowId, messageType, msg,
                notification.getIcon(), listener);
    }
}

From source file:com.intellij.notification.Notification.java

License:Apache License

public void setBalloon(@NotNull final Balloon balloon) {
    hideBalloon();/*from w  ww  .j a  va  2  s  .c o m*/
    myBalloonRef = new WeakReference<Balloon>(balloon);
    balloon.addListener(new JBPopupAdapter() {
        @Override
        public void onClosed(LightweightWindowEvent event) {
            WeakReference<Balloon> ref = myBalloonRef;
            if (ref != null && ref.get() == balloon) {
                myBalloonRef = null;
            }
        }
    });
}

From source file:com.intellij.refactoring.introduce.inplace.OccurrencesChooser.java

License:Apache License

public void showChooser(final Pass<ReplaceChoice> callback, final Map<ReplaceChoice, List<T>> occurrencesMap) {
    if (occurrencesMap.size() == 1) {
        callback.pass(occurrencesMap.keySet().iterator().next());
        return;//w  ww . j av a  2 s  .co m
    }
    final DefaultListModel model = new DefaultListModel();
    for (ReplaceChoice choice : occurrencesMap.keySet()) {
        model.addElement(choice);
    }
    final JList list = new JBList(model);
    list.setCellRenderer(new DefaultListCellRenderer() {
        @Override
        public Component getListCellRendererComponent(final JList list, final Object value, final int index,
                final boolean isSelected, final boolean cellHasFocus) {
            final Component rendererComponent = super.getListCellRendererComponent(list, value, index,
                    isSelected, cellHasFocus);
            final ReplaceChoice choices = (ReplaceChoice) value;
            if (choices != null) {
                String text = choices.getDescription();
                if (choices == ReplaceChoice.ALL) {
                    text = MessageFormat.format(text, occurrencesMap.get(choices).size());
                }
                setText(text);
            }
            return rendererComponent;
        }
    });
    list.addListSelectionListener(new ListSelectionListener() {
        @Override
        public void valueChanged(final ListSelectionEvent e) {
            final ReplaceChoice value = (ReplaceChoice) list.getSelectedValue();
            if (value == null)
                return;
            dropHighlighters();
            final MarkupModel markupModel = myEditor.getMarkupModel();
            final List<T> occurrenceList = occurrencesMap.get(value);
            for (T occurrence : occurrenceList) {
                final TextRange textRange = getOccurrenceRange(occurrence);
                final RangeHighlighter rangeHighlighter = markupModel.addRangeHighlighter(
                        textRange.getStartOffset(), textRange.getEndOffset(), HighlighterLayer.SELECTION - 1,
                        myAttributes, HighlighterTargetArea.EXACT_RANGE);
                myRangeHighlighters.add(rangeHighlighter);
            }
        }
    });

    JBPopupFactory.getInstance().createListPopupBuilder(list).setTitle("Multiple occurrences found")
            .setMovable(false).setResizable(false).setRequestFocus(true).setItemChoosenCallback(new Runnable() {
                @Override
                public void run() {
                    callback.pass((ReplaceChoice) list.getSelectedValue());
                }
            }).addListener(new JBPopupAdapter() {
                @Override
                public void onClosed(LightweightWindowEvent event) {
                    dropHighlighters();
                }
            }).createPopup().showInBestPositionFor(myEditor);
}

From source file:com.intellij.refactoring.introduceParameter.IntroduceParameterHandler.java

License:Apache License

private void chooseMethodToIntroduceParameter(final Editor editor, final List<PsiMethod> validEnclosingMethods,
        final Introducer introducer) {
    final AbstractInplaceIntroducer inplaceIntroducer = AbstractInplaceIntroducer.getActiveIntroducer(editor);
    if (inplaceIntroducer instanceof InplaceIntroduceParameterPopup) {
        final InplaceIntroduceParameterPopup introduceParameterPopup = (InplaceIntroduceParameterPopup) inplaceIntroducer;
        introducer.introduceParameter(introduceParameterPopup.getMethodToIntroduceParameter(),
                introduceParameterPopup.getMethodToSearchFor());
        return;// w w  w  .j a v a 2s  .c  om
    }
    final JPanel panel = new JPanel(new BorderLayout());
    final JCheckBox superMethod = new JCheckBox("Refactor super method", true);
    superMethod.setMnemonic('U');
    panel.add(superMethod, BorderLayout.SOUTH);
    final JBList list = new JBList(validEnclosingMethods.toArray());
    list.setVisibleRowCount(5);
    list.setCellRenderer(new MethodCellRenderer());
    list.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    list.setSelectedIndex(0);
    final List<RangeHighlighter> highlighters = new ArrayList<RangeHighlighter>();
    final TextAttributes attributes = EditorColorsManager.getInstance().getGlobalScheme()
            .getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES);
    list.addListSelectionListener(new ListSelectionListener() {
        public void valueChanged(final ListSelectionEvent e) {
            final PsiMethod selectedMethod = (PsiMethod) list.getSelectedValue();
            if (selectedMethod == null)
                return;
            dropHighlighters(highlighters);
            updateView(selectedMethod, editor, attributes, highlighters, superMethod);
        }
    });
    updateView(validEnclosingMethods.get(0), editor, attributes, highlighters, superMethod);
    final JScrollPane scrollPane = ScrollPaneFactory.createScrollPane(list);
    scrollPane.setBorder(null);
    panel.add(scrollPane, BorderLayout.CENTER);

    final List<Pair<ActionListener, KeyStroke>> keyboardActions = Collections
            .singletonList(Pair.<ActionListener, KeyStroke>create(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    final PsiMethod methodToSearchIn = (PsiMethod) list.getSelectedValue();
                    if (myEnclosingMethodsPopup != null && myEnclosingMethodsPopup.isVisible()) {
                        myEnclosingMethodsPopup.cancel();
                    }

                    final PsiMethod methodToSearchFor = superMethod.isEnabled() && superMethod.isSelected()
                            ? methodToSearchIn.findDeepestSuperMethod()
                            : methodToSearchIn;
                    Runnable runnable = new Runnable() {
                        public void run() {
                            introducer.introduceParameter(methodToSearchIn, methodToSearchFor);
                        }
                    };
                    IdeFocusManager.findInstance().doWhenFocusSettlesDown(runnable);
                }
            }, KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0)));
    myEnclosingMethodsPopup = JBPopupFactory.getInstance().createComponentPopupBuilder(panel, list)
            .setTitle("Introduce parameter to method").setMovable(false).setResizable(false)
            .setRequestFocus(true).setKeyboardActions(keyboardActions).addListener(new JBPopupAdapter() {
                @Override
                public void onClosed(LightweightWindowEvent event) {
                    dropHighlighters(highlighters);
                }
            }).createPopup();
    myEnclosingMethodsPopup.showInBestPositionFor(editor);
}

From source file:com.intellij.refactoring.IntroduceTargetChooser.java

License:Apache License

public static <T extends PsiElement> void showChooser(final Editor editor, final List<T> expressions,
        final Pass<T> callback, final Function<T, String> renderer, String title, int selection,
        NotNullFunction<PsiElement, TextRange> ranger) {
    final ScopeHighlighter highlighter = new ScopeHighlighter(editor, ranger);
    final DefaultListModel model = new DefaultListModel();
    for (T expr : expressions) {
        model.addElement(expr);/*from  w w w. j av a  2s. c  o  m*/
    }
    final JList list = new JBList(model);
    if (selection > -1)
        list.setSelectedIndex(selection);
    list.setCellRenderer(new DefaultListCellRenderer() {

        @Override
        public Component getListCellRendererComponent(final JList list, final Object value, final int index,
                final boolean isSelected, final boolean cellHasFocus) {
            final Component rendererComponent = super.getListCellRendererComponent(list, value, index,
                    isSelected, cellHasFocus);

            final T expr = (T) value;
            if (expr.isValid()) {
                String text = renderer.fun(expr);
                int firstNewLinePos = text.indexOf('\n');
                String trimmedText = text.substring(0,
                        firstNewLinePos != -1 ? firstNewLinePos : Math.min(100, text.length()));
                if (trimmedText.length() != text.length())
                    trimmedText += " ...";
                setText(trimmedText);
            }
            return rendererComponent;
        }
    });

    list.addListSelectionListener(new ListSelectionListener() {
        @Override
        public void valueChanged(final ListSelectionEvent e) {
            highlighter.dropHighlight();
            final int index = list.getSelectedIndex();
            if (index < 0)
                return;
            final T expr = (T) model.get(index);
            final ArrayList<PsiElement> toExtract = new ArrayList<PsiElement>();
            toExtract.add(expr);
            highlighter.highlight(expr, toExtract);
        }
    });

    JBPopupFactory.getInstance().createListPopupBuilder(list).setTitle(title).setMovable(false)
            .setResizable(false).setRequestFocus(true).setItemChoosenCallback(new Runnable() {
                @Override
                public void run() {
                    callback.pass((T) list.getSelectedValue());
                }
            }).addListener(new JBPopupAdapter() {
                @Override
                public void onClosed(LightweightWindowEvent event) {
                    highlighter.dropHighlight();
                }
            }).createPopup().showInBestPositionFor(editor);
}

From source file:com.intellij.refactoring.rename.inplace.RenameChooser.java

License:Apache License

public void showChooser(final Collection<PsiReference> refs,
        final Collection<Pair<PsiElement, TextRange>> stringUsages) {
    if (ApplicationManager.getApplication().isUnitTestMode()) {
        runRenameTemplate(RefactoringSettings.getInstance().RENAME_SEARCH_IN_COMMENTS_FOR_FILE ? stringUsages
                : new ArrayList<Pair<PsiElement, TextRange>>());
        return;/* ww w . j  a va 2 s.c om*/
    }

    final DefaultListModel model = new DefaultListModel();
    model.addElement(CODE_OCCURRENCES);
    model.addElement(ALL_OCCURRENCES);
    final JList list = new JBList(model);

    list.addListSelectionListener(new ListSelectionListener() {
        @Override
        public void valueChanged(final ListSelectionEvent e) {
            final String selectedValue = (String) list.getSelectedValue();
            if (selectedValue == null)
                return;
            dropHighlighters();
            final MarkupModel markupModel = myEditor.getMarkupModel();

            if (selectedValue.equals(ALL_OCCURRENCES)) {
                for (Pair<PsiElement, TextRange> pair : stringUsages) {
                    final TextRange textRange = pair.second.shiftRight(pair.first.getTextOffset());
                    final RangeHighlighter rangeHighlighter = markupModel.addRangeHighlighter(
                            textRange.getStartOffset(), textRange.getEndOffset(),
                            HighlighterLayer.SELECTION - 1, myAttributes, HighlighterTargetArea.EXACT_RANGE);
                    myRangeHighlighters.add(rangeHighlighter);
                }
            }

            for (PsiReference reference : refs) {
                final PsiElement element = reference.getElement();
                if (element == null)
                    continue;
                final TextRange textRange = element.getTextRange();
                final RangeHighlighter rangeHighlighter = markupModel.addRangeHighlighter(
                        textRange.getStartOffset(), textRange.getEndOffset(), HighlighterLayer.SELECTION - 1,
                        myAttributes, HighlighterTargetArea.EXACT_RANGE);
                myRangeHighlighters.add(rangeHighlighter);
            }
        }
    });

    JBPopupFactory.getInstance().createListPopupBuilder(list).setTitle("String occurrences found")
            .setMovable(false).setResizable(false).setRequestFocus(true).setItemChoosenCallback(new Runnable() {
                @Override
                public void run() {
                    runRenameTemplate(ALL_OCCURRENCES.equals(list.getSelectedValue()) ? stringUsages
                            : new ArrayList<Pair<PsiElement, TextRange>>());
                }
            }).addListener(new JBPopupAdapter() {
                @Override
                public void onClosed(LightweightWindowEvent event) {
                    dropHighlighters();
                }
            }).createPopup().showInBestPositionFor(myEditor);
}

From source file:com.intellij.tasks.actions.context.LoadContextAction.java

License:Apache License

@Override
public void actionPerformed(AnActionEvent e) {
    final Project project = getProject(e);
    assert project != null;
    DefaultActionGroup group = new DefaultActionGroup();
    final WorkingContextManager manager = WorkingContextManager.getInstance(project);
    List<ContextInfo> history = manager.getContextHistory();
    List<ContextHolder> infos = new ArrayList<ContextHolder>(
            ContainerUtil.map2List(history, new Function<ContextInfo, ContextHolder>() {
                public ContextHolder fun(final ContextInfo info) {
                    return new ContextHolder() {
                        @Override
                        void load(final boolean clear) {
                            LoadContextUndoableAction undoableAction = LoadContextUndoableAction
                                    .createAction(manager, clear, info.name);
                            UndoableCommand.execute(project, undoableAction, "Load context " + info.comment,
                                    "Context");
                        }//from  ww w  . jav a  2 s  .  c o m

                        @Override
                        void remove() {
                            manager.removeContext(info.name);
                        }

                        @Override
                        Date getDate() {
                            return new Date(info.date);
                        }

                        @Override
                        String getComment() {
                            return info.comment;
                        }

                        @Override
                        Image getIcon() {
                            return TasksIcons.SavedContext;
                        }
                    };
                }
            }));
    final TaskManager taskManager = TaskManager.getManager(project);
    List<LocalTask> tasks = taskManager.getLocalTasks();
    infos.addAll(ContainerUtil.mapNotNull(tasks, new NullableFunction<LocalTask, ContextHolder>() {
        public ContextHolder fun(final LocalTask task) {
            if (task.isActive()) {
                return null;
            }
            return new ContextHolder() {
                @Override
                void load(boolean clear) {
                    LoadContextUndoableAction undoableAction = LoadContextUndoableAction.createAction(manager,
                            clear, task);
                    UndoableCommand.execute(project, undoableAction,
                            "Load context " + TaskUtil.getTrimmedSummary(task), "Context");
                }

                @Override
                void remove() {
                    SwitchTaskAction.removeTask(project, task, taskManager);
                }

                @Override
                Date getDate() {
                    return task.getUpdated();
                }

                @Override
                String getComment() {
                    return TaskUtil.getTrimmedSummary(task);
                }

                @Override
                Image getIcon() {
                    return task.getIcon();
                }
            };
        }
    }));

    Collections.sort(infos, new Comparator<ContextHolder>() {
        public int compare(ContextHolder o1, ContextHolder o2) {
            return o2.getDate().compareTo(o1.getDate());
        }
    });

    final Ref<Boolean> shiftPressed = Ref.create(false);
    boolean today = true;
    Calendar now = Calendar.getInstance();
    for (int i = 0, historySize = Math.min(MAX_ROW_COUNT, infos.size()); i < historySize; i++) {
        final ContextHolder info = infos.get(i);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(info.getDate());
        if (today && (calendar.get(Calendar.YEAR) != now.get(Calendar.YEAR)
                || calendar.get(Calendar.DAY_OF_YEAR) != now.get(Calendar.DAY_OF_YEAR))) {
            group.addSeparator();
            today = false;
        }
        group.add(createItem(info, shiftPressed));
    }

    final ListPopupImpl popup = (ListPopupImpl) JBPopupFactory.getInstance().createActionGroupPopup(
            "Load Context", group, e.getDataContext(), JBPopupFactory.ActionSelectionAid.SPEEDSEARCH, false,
            null, MAX_ROW_COUNT);
    popup.setAdText("Press SHIFT to merge with current context");
    popup.registerAction("shiftPressed", KeyStroke.getKeyStroke("shift pressed SHIFT"), new AbstractAction() {
        public void actionPerformed(ActionEvent e) {
            shiftPressed.set(true);
            popup.setCaption("Merge with Current Context");
        }
    });
    popup.registerAction("shiftReleased", KeyStroke.getKeyStroke("released SHIFT"), new AbstractAction() {
        public void actionPerformed(ActionEvent e) {
            shiftPressed.set(false);
            popup.setCaption("Load Context");
        }
    });
    popup.registerAction("invoke", KeyStroke.getKeyStroke("shift ENTER"), new AbstractAction() {
        public void actionPerformed(ActionEvent e) {
            popup.handleSelect(true);
        }
    });
    popup.addPopupListener(new JBPopupAdapter() {
        @Override
        public void onClosed(LightweightWindowEvent event) {

        }
    });
    popup.showCenteredInCurrentWindow(project);
}