Search in sources :

Example 1 with LightweightWindowEvent

use of com.intellij.openapi.ui.popup.LightweightWindowEvent in project intellij-community by JetBrains.

the class MethodOrClosureScopeChooser method create.

/**
   * @param callback is invoked if any scope was chosen. The first arg is this scope and the second arg is a psielement to search for (super method of chosen method or
   *                 variable if the scope is a closure)
   */
public static JBPopup create(List<? extends GrParametersOwner> scopes, final Editor editor, final JBPopupOwner popupRef, final PairFunction<GrParametersOwner, PsiElement, Object> callback) {
    final JPanel panel = new JPanel(new BorderLayout());
    final JCheckBox superMethod = new JCheckBox(USE_SUPER_METHOD_OF, true);
    superMethod.setMnemonic('U');
    panel.add(superMethod, BorderLayout.SOUTH);
    final JBList list = new JBList(scopes.toArray());
    list.setVisibleRowCount(5);
    list.setCellRenderer(new DefaultListCellRenderer() {

        @Override
        public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
            super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
            final String text;
            if (value instanceof PsiMethod) {
                final PsiMethod method = (PsiMethod) value;
                text = PsiFormatUtil.formatMethod(method, PsiSubstitutor.EMPTY, PsiFormatUtilBase.SHOW_CONTAINING_CLASS | PsiFormatUtilBase.SHOW_NAME | PsiFormatUtilBase.SHOW_PARAMETERS, PsiFormatUtilBase.SHOW_TYPE);
                final int flags = Iconable.ICON_FLAG_VISIBILITY;
                final Icon icon = method.getIcon(flags);
                if (icon != null)
                    setIcon(icon);
            } else {
                LOG.assertTrue(value instanceof GrClosableBlock);
                setIcon(JetgroovyIcons.Groovy.Groovy_16x16);
                text = "{...}";
            }
            setText(text);
            return this;
        }
    });
    list.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    list.setSelectedIndex(0);
    final List<RangeHighlighter> highlighters = new ArrayList<>();
    final TextAttributes attributes = EditorColorsManager.getInstance().getGlobalScheme().getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES);
    list.addListSelectionListener(new ListSelectionListener() {

        @Override
        public void valueChanged(final ListSelectionEvent e) {
            final GrParametersOwner selectedMethod = (GrParametersOwner) list.getSelectedValue();
            if (selectedMethod == null)
                return;
            dropHighlighters(highlighters);
            updateView(selectedMethod, editor, attributes, highlighters, superMethod);
        }
    });
    updateView(scopes.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 GrParametersOwner ToSearchIn = (GrParametersOwner) list.getSelectedValue();
            final JBPopup popup = popupRef.get();
            if (popup != null && popup.isVisible()) {
                popup.cancel();
            }
            final PsiElement toSearchFor;
            if (ToSearchIn instanceof GrMethod) {
                final GrMethod method = (GrMethod) ToSearchIn;
                toSearchFor = superMethod.isEnabled() && superMethod.isSelected() ? method.findDeepestSuperMethod() : method;
            } else {
                toSearchFor = superMethod.isEnabled() && superMethod.isSelected() ? ToSearchIn.getParent() : null;
            }
            IdeFocusManager.findInstance().doWhenFocusSettlesDown(() -> callback.fun(ToSearchIn, toSearchFor), ModalityState.current());
        }
    }, KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0)));
    return JBPopupFactory.getInstance().createComponentPopupBuilder(panel, list).setTitle("Introduce parameter to").setMovable(false).setResizable(false).setRequestFocus(true).setKeyboardActions(keyboardActions).addListener(new JBPopupAdapter() {

        @Override
        public void onClosed(LightweightWindowEvent event) {
            dropHighlighters(highlighters);
        }
    }).createPopup();
}
Also used : PsiMethod(com.intellij.psi.PsiMethod) GrParametersOwner(org.jetbrains.plugins.groovy.lang.psi.api.statements.GrParametersOwner) ActionEvent(java.awt.event.ActionEvent) ArrayList(java.util.ArrayList) ListSelectionEvent(javax.swing.event.ListSelectionEvent) LightweightWindowEvent(com.intellij.openapi.ui.popup.LightweightWindowEvent) JBPopup(com.intellij.openapi.ui.popup.JBPopup) PsiElement(com.intellij.psi.PsiElement) Pair(com.intellij.openapi.util.Pair) GrMethod(org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod) GrClosableBlock(org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock) ListSelectionListener(javax.swing.event.ListSelectionListener) ActionListener(java.awt.event.ActionListener) JBPopupAdapter(com.intellij.openapi.ui.popup.JBPopupAdapter) JBList(com.intellij.ui.components.JBList)

Example 2 with LightweightWindowEvent

use of com.intellij.openapi.ui.popup.LightweightWindowEvent in project intellij-community by JetBrains.

the class EmmetAbbreviationBalloon method show.

public void show(@NotNull final CustomTemplateCallback customTemplateCallback) {
    if (ApplicationManager.getApplication().isUnitTestMode()) {
        if (ourTestingAbbreviation == null) {
            throw new RuntimeException("Testing abbreviation is not set. See EmmetAbbreviationBalloon#setTestingAbbreviation");
        }
        myCallback.onEnter(ourTestingAbbreviation);
        return;
    }
    final TextFieldWithStoredHistory field = new TextFieldWithStoredHistory(myAbbreviationsHistoryKey);
    final Dimension fieldPreferredSize = field.getPreferredSize();
    field.setPreferredSize(new Dimension(Math.max(220, fieldPreferredSize.width), fieldPreferredSize.height));
    field.setHistorySize(10);
    final JBPopupFactory popupFactory = JBPopupFactory.getInstance();
    final BalloonImpl balloon = (BalloonImpl) popupFactory.createDialogBalloonBuilder(field, myTitle).setCloseButtonEnabled(false).setBlockClicksThroughBalloon(true).setAnimationCycle(0).setHideOnKeyOutside(true).setHideOnClickOutside(true).createBalloon();
    final DocumentAdapter documentListener = new DocumentAdapter() {

        @Override
        protected void textChanged(DocumentEvent e) {
            if (!isValid(customTemplateCallback)) {
                balloon.hide();
                return;
            }
            validateTemplateKey(field, balloon, field.getText(), customTemplateCallback);
        }
    };
    field.addDocumentListener(documentListener);
    final KeyAdapter keyListener = new KeyAdapter() {

        @Override
        public void keyPressed(@NotNull KeyEvent e) {
            if (!field.isPopupVisible()) {
                if (!isValid(customTemplateCallback)) {
                    balloon.hide();
                    return;
                }
                switch(e.getKeyCode()) {
                    case KeyEvent.VK_ENTER:
                        final String abbreviation = field.getText();
                        if (validateTemplateKey(field, balloon, abbreviation, customTemplateCallback)) {
                            myCallback.onEnter(abbreviation);
                            PropertiesComponent.getInstance().setValue(myLastAbbreviationKey, abbreviation);
                            field.addCurrentTextToHistory();
                            balloon.hide();
                        }
                        break;
                    case KeyEvent.VK_ESCAPE:
                        balloon.hide(false);
                        break;
                }
            }
        }
    };
    field.addKeyboardListener(keyListener);
    balloon.addListener(new JBPopupListener.Adapter() {

        @Override
        public void beforeShown(LightweightWindowEvent event) {
            field.setText(PropertiesComponent.getInstance().getValue(myLastAbbreviationKey, ""));
        }

        @Override
        public void onClosed(LightweightWindowEvent event) {
            field.removeKeyListener(keyListener);
            field.removeDocumentListener(documentListener);
            super.onClosed(event);
        }
    });
    balloon.show(popupFactory.guessBestPopupLocation(customTemplateCallback.getEditor()), Balloon.Position.below);
    final IdeFocusManager focusManager = IdeFocusManager.getInstance(customTemplateCallback.getProject());
    focusManager.doWhenFocusSettlesDown(() -> {
        focusManager.requestFocus(field, true);
        field.selectText();
    });
}
Also used : KeyAdapter(java.awt.event.KeyAdapter) IdeFocusManager(com.intellij.openapi.wm.IdeFocusManager) DocumentEvent(javax.swing.event.DocumentEvent) NotNull(org.jetbrains.annotations.NotNull) LightweightWindowEvent(com.intellij.openapi.ui.popup.LightweightWindowEvent) KeyEvent(java.awt.event.KeyEvent) JBPopupListener(com.intellij.openapi.ui.popup.JBPopupListener) JBPopupFactory(com.intellij.openapi.ui.popup.JBPopupFactory)

Example 3 with LightweightWindowEvent

use of com.intellij.openapi.ui.popup.LightweightWindowEvent in project intellij-community by JetBrains.

the class PyStudyShowTutorial method projectOpened.

@Override
public void projectOpened() {
    ApplicationManager.getApplication().invokeLater(new DumbAwareRunnable() {

        @Override
        public void run() {
            ApplicationManager.getApplication().runWriteAction(new DumbAwareRunnable() {

                @Override
                public void run() {
                    if (PropertiesComponent.getInstance().getBoolean(ourShowPopup, true)) {
                        final String content = "<html>If you'd like to learn more about PyCharm Edu, " + "click <a href=\"https://www.jetbrains.com/pycharm-edu/quickstart/\">here</a> to watch a tutorial</html>";
                        final Notification notification = new Notification("Watch Tutorials!", "", content, NotificationType.INFORMATION, new NotificationListener.UrlOpeningListener(true));
                        Notifications.Bus.notify(notification);
                        Balloon balloon = notification.getBalloon();
                        if (balloon != null) {
                            balloon.addListener(new JBPopupAdapter() {

                                @Override
                                public void onClosed(LightweightWindowEvent event) {
                                    notification.expire();
                                }
                            });
                        }
                        notification.whenExpired(() -> PropertiesComponent.getInstance().setValue(ourShowPopup, false, true));
                    }
                }
            });
        }
    });
}
Also used : Balloon(com.intellij.openapi.ui.popup.Balloon) JBPopupAdapter(com.intellij.openapi.ui.popup.JBPopupAdapter) DumbAwareRunnable(com.intellij.openapi.project.DumbAwareRunnable) Notification(com.intellij.notification.Notification) NotificationListener(com.intellij.notification.NotificationListener) LightweightWindowEvent(com.intellij.openapi.ui.popup.LightweightWindowEvent)

Example 4 with LightweightWindowEvent

use of com.intellij.openapi.ui.popup.LightweightWindowEvent in project intellij-community by JetBrains.

the class RenameChooser method showChooser.

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<>());
        return;
    }
    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(() -> runRenameTemplate(ALL_OCCURRENCES.equals(list.getSelectedValue()) ? stringUsages : new ArrayList<>())).addListener(new JBPopupAdapter() {

        @Override
        public void onClosed(LightweightWindowEvent event) {
            dropHighlighters();
        }
    }).createPopup().showInBestPositionFor(myEditor);
}
Also used : ListSelectionEvent(javax.swing.event.ListSelectionEvent) PsiReference(com.intellij.psi.PsiReference) TextRange(com.intellij.openapi.util.TextRange) ListSelectionListener(javax.swing.event.ListSelectionListener) LightweightWindowEvent(com.intellij.openapi.ui.popup.LightweightWindowEvent) JBPopupAdapter(com.intellij.openapi.ui.popup.JBPopupAdapter) JBList(com.intellij.ui.components.JBList) PsiElement(com.intellij.psi.PsiElement) Pair(com.intellij.openapi.util.Pair)

Example 5 with LightweightWindowEvent

use of com.intellij.openapi.ui.popup.LightweightWindowEvent in project intellij-community by JetBrains.

the class BalloonImpl method show.

private void show(PositionTracker<Balloon> tracker, AbstractPosition position) {
    assert !myDisposed : "Balloon is already disposed";
    if (isVisible())
        return;
    final Component comp = tracker.getComponent();
    if (!comp.isShowing())
        return;
    myTracker = tracker;
    myTracker.init(this);
    JRootPane root = ObjectUtils.notNull(UIUtil.getRootPane(comp));
    myVisible = true;
    myLayeredPane = root.getLayeredPane();
    myPosition = position;
    UIUtil.setFutureRootPane(myContent, root);
    myFocusManager = IdeFocusManager.findInstanceByComponent(myLayeredPane);
    final Ref<Component> originalFocusOwner = new Ref<>();
    final Ref<FocusRequestor> focusRequestor = new Ref<>();
    final Ref<ActionCallback> proxyFocusRequest = new Ref<>(ActionCallback.DONE);
    boolean mnemonicsFix = myDialogMode && SystemInfo.isMac && Registry.is("ide.mac.inplaceDialogMnemonicsFix");
    if (mnemonicsFix) {
        final IdeGlassPaneEx glassPane = (IdeGlassPaneEx) IdeGlassPaneUtil.find(myLayeredPane);
        assert glassPane != null;
        proxyFocusRequest.set(new ActionCallback());
        myFocusManager.doWhenFocusSettlesDown(new ExpirableRunnable() {

            @Override
            public boolean isExpired() {
                return isDisposed();
            }

            @Override
            public void run() {
                IdeEventQueue.getInstance().disableInputMethods(BalloonImpl.this);
                originalFocusOwner.set(myFocusManager.getFocusOwner());
                focusRequestor.set(myFocusManager.getFurtherRequestor());
            }
        });
    }
    if (myRequestFocus) {
        myFocusManager.doWhenFocusSettlesDown(new ExpirableRunnable() {

            @Override
            public boolean isExpired() {
                return isDisposed();
            }

            @Override
            public void run() {
                myOriginalFocusOwner = myFocusManager.getFocusOwner();
                // Set the accessible parent so that screen readers don't announce
                // a window context change -- the tooltip is "logically" hosted
                // inside the component (e.g. editor) it appears on top of.
                AccessibleContextUtil.setParent(myContent, myOriginalFocusOwner);
                // Set the focus to "myContent"
                myFocusManager.requestFocus(getContentToFocus(), true);
            }
        });
    }
    myLayeredPane.addComponentListener(myComponentListener);
    myTargetPoint = myPosition.getShiftedPoint(myTracker.recalculateLocation(this).getPoint(myLayeredPane), myCalloutShift);
    int positionChangeFix = 0;
    if (myShowPointer) {
        Rectangle rec = getRecForPosition(myPosition, true);
        if (!myPosition.isOkToHavePointer(myTargetPoint, rec, getPointerLength(myPosition), getPointerWidth(myPosition), getArc())) {
            rec = getRecForPosition(myPosition, false);
            Rectangle lp = new Rectangle(new Point(myContainerInsets.left, myContainerInsets.top), myLayeredPane.getSize());
            lp.width -= myContainerInsets.right;
            lp.height -= myContainerInsets.bottom;
            if (!lp.contains(rec)) {
                Rectangle2D currentSquare = lp.createIntersection(rec);
                double maxSquare = currentSquare.getWidth() * currentSquare.getHeight();
                AbstractPosition targetPosition = myPosition;
                for (AbstractPosition eachPosition : myPosition.getOtherPositions()) {
                    Rectangle2D eachIntersection = lp.createIntersection(getRecForPosition(eachPosition, false));
                    double eachSquare = eachIntersection.getWidth() * eachIntersection.getHeight();
                    if (maxSquare < eachSquare) {
                        maxSquare = eachSquare;
                        targetPosition = eachPosition;
                    }
                }
                myPosition = targetPosition;
                positionChangeFix = myPosition.getChangeShift(position, myPositionChangeXShift, myPositionChangeYShift);
            }
        }
    }
    if (myPosition != position) {
        myTargetPoint = myPosition.getShiftedPoint(myTracker.recalculateLocation(this).getPoint(myLayeredPane), myCalloutShift > 0 ? myCalloutShift + positionChangeFix : positionChangeFix);
    }
    createComponent();
    myComp.validate();
    Rectangle rec = myComp.getContentBounds();
    if (myShowPointer && !myPosition.isOkToHavePointer(myTargetPoint, rec, getPointerLength(myPosition), getPointerWidth(myPosition), getArc())) {
        myShowPointer = false;
        myComp.removeAll();
        myLayeredPane.remove(myComp);
        createComponent();
        if (!new Rectangle(myLayeredPane.getSize()).contains(new Rectangle(myComp.getSize()))) {
            // Balloon is bigger than window, don't show it at all.
            myComp.removeAll();
            myLayeredPane.remove(myComp);
            myLayeredPane = null;
            hide();
            return;
        }
    }
    for (JBPopupListener each : myListeners) {
        each.beforeShown(new LightweightWindowEvent(this));
    }
    runAnimation(true, myLayeredPane, null);
    myLayeredPane.revalidate();
    myLayeredPane.repaint();
    if (mnemonicsFix) {
        proxyFocusRequest.get().doWhenDone(() -> myFocusManager.requestFocus(originalFocusOwner.get(), true));
    }
    Toolkit.getDefaultToolkit().addAWTEventListener(myAwtActivityListener, AWTEvent.MOUSE_EVENT_MASK | AWTEvent.MOUSE_MOTION_EVENT_MASK | AWTEvent.KEY_EVENT_MASK);
    if (ApplicationManager.getApplication() != null) {
        ActionManager.getInstance().addAnActionListener(new AnActionListener.Adapter() {

            @Override
            public void beforeActionPerformed(AnAction action, DataContext dataContext, AnActionEvent event) {
                if (myHideOnAction) {
                    hide();
                }
            }
        }, this);
    }
    if (myHideOnLinkClick) {
        JEditorPane editorPane = UIUtil.uiTraverser(myContent).traverse().filter(JEditorPane.class).first();
        if (editorPane != null) {
            editorPane.addHyperlinkListener(new HyperlinkAdapter() {

                @Override
                protected void hyperlinkActivated(HyperlinkEvent e) {
                    hide();
                }
            });
        }
    }
}
Also used : HyperlinkEvent(javax.swing.event.HyperlinkEvent) AnActionEvent(com.intellij.openapi.actionSystem.AnActionEvent) AnAction(com.intellij.openapi.actionSystem.AnAction) LightweightWindowEvent(com.intellij.openapi.ui.popup.LightweightWindowEvent) IdeGlassPaneEx(com.intellij.openapi.wm.impl.IdeGlassPaneEx) JBPopupListener(com.intellij.openapi.ui.popup.JBPopupListener) DataContext(com.intellij.openapi.actionSystem.DataContext) AnActionListener(com.intellij.openapi.actionSystem.ex.AnActionListener) FocusRequestor(com.intellij.openapi.wm.FocusRequestor) Rectangle2D(java.awt.geom.Rectangle2D) RoundRectangle2D(java.awt.geom.RoundRectangle2D) RelativePoint(com.intellij.ui.awt.RelativePoint) RelativePoint(com.intellij.ui.awt.RelativePoint)

Aggregations

LightweightWindowEvent (com.intellij.openapi.ui.popup.LightweightWindowEvent)14 JBPopupAdapter (com.intellij.openapi.ui.popup.JBPopupAdapter)12 JBList (com.intellij.ui.components.JBList)5 RelativePoint (com.intellij.ui.awt.RelativePoint)4 ActionEvent (java.awt.event.ActionEvent)4 ListSelectionEvent (javax.swing.event.ListSelectionEvent)4 ListSelectionListener (javax.swing.event.ListSelectionListener)4 Pair (com.intellij.openapi.util.Pair)3 TextRange (com.intellij.openapi.util.TextRange)3 ActionListener (java.awt.event.ActionListener)3 Balloon (com.intellij.openapi.ui.popup.Balloon)2 JBPopup (com.intellij.openapi.ui.popup.JBPopup)2 JBPopupListener (com.intellij.openapi.ui.popup.JBPopupListener)2 PsiElement (com.intellij.psi.PsiElement)2 ArrayList (java.util.ArrayList)2 List (java.util.List)2 NotNull (org.jetbrains.annotations.NotNull)2 EverywhereContextType (com.intellij.codeInsight.template.EverywhereContextType)1 TemplateContextType (com.intellij.codeInsight.template.TemplateContextType)1 ScopeHighlighter (com.intellij.codeInsight.unwrap.ScopeHighlighter)1