Example usage for com.intellij.openapi.ui.popup JBPopupListener beforeShown

List of usage examples for com.intellij.openapi.ui.popup JBPopupListener beforeShown

Introduction

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

Prototype

default void beforeShown(@NotNull LightweightWindowEvent event) 

Source Link

Usage

From source file:com.intellij.ui.BalloonImpl.java

License:Apache License

private void show(PositionTracker<Balloon> tracker, AbstractPosition position) {
    assert !myDisposed : "Balloon is already disposed";

    if (isVisible())
        return;//from  w  w  w.j  av a  2s.  co  m
    final Component comp = tracker.getComponent();
    if (!comp.isShowing())
        return;

    myTracker = tracker;
    myTracker.init(this);

    JRootPane root = null;
    JDialog dialog = IJSwingUtilities.findParentOfType(comp, JDialog.class);
    if (dialog != null) {
        root = dialog.getRootPane();
    } else {
        JWindow jwindow = IJSwingUtilities.findParentOfType(comp, JWindow.class);
        if (jwindow != null) {
            root = jwindow.getRootPane();
        } else {
            JFrame frame = IJSwingUtilities.findParentOfType(comp, JFrame.class);
            if (frame != null) {
                root = frame.getRootPane();
            } else {
                assert false;
            }
        }
    }

    myVisible = true;

    myLayeredPane = root.getLayeredPane();
    myPosition = position;
    UIUtil.setFutureRootPane(myContent, root);

    myFocusManager = IdeFocusManager.findInstanceByComponent(myLayeredPane);
    final Ref<Component> originalFocusOwner = new Ref<Component>();
    final Ref<FocusRequestor> focusRequestor = new Ref<FocusRequestor>();
    final Ref<ActionCallback> proxyFocusRequest = new Ref<ActionCallback>(new 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());
                myFocusManager.requestFocus(glassPane.getProxyComponent(), true)
                        .notify(proxyFocusRequest.get());
                focusRequestor.set(myFocusManager.getFurtherRequestor());
            }
        });
    }

    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.
            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(new Runnable() {
            @Override
            public void run() {
                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) {
        final Ref<JEditorPane> ref = Ref.create(null);
        new AwtVisitor(myContent) {
            @Override
            public boolean visit(Component component) {
                if (component instanceof JEditorPane) {
                    ref.set((JEditorPane) component);
                    return true;
                }
                return false;
            }
        };
        if (!ref.isNull()) {
            ref.get().addHyperlinkListener(new HyperlinkAdapter() {
                @Override
                protected void hyperlinkActivated(HyperlinkEvent e) {
                    hide();
                }
            });
        }
    }
}

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

License:Apache License

public void show(Component owner, int aScreenX, int aScreenY, final boolean considerForcedXY) {
    if (ApplicationManagerEx.getApplicationEx() != null
            && ApplicationManager.getApplication().isHeadlessEnvironment())
        return;//  w  w w.j a va 2 s. c  o m
    if (isDisposed()) {
        throw new IllegalStateException("Popup was already disposed. Recreate a new instance to show again");
    }

    assert ApplicationManager.getApplication().isDispatchThread();
    assert myState == State.INIT : "Popup was already shown. Recreate a new instance to show again.";

    debugState("show popup", State.INIT);
    myState = State.SHOWING;

    installWindowHook(this);
    installProjectDisposer();
    addActivity();

    final Component prevOwner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();

    final boolean shouldShow = beforeShow();
    if (!shouldShow) {
        removeActivity();
        debugState("rejected to show popup", State.SHOWING);
        myState = State.INIT;
        return;
    }

    prepareToShow();

    if (myInStack) {
        myFocusTrackback = new FocusTrackback(this, owner, true);
        myFocusTrackback.setMustBeShown(true);
    }

    Dimension sizeToSet = null;

    if (myDimensionServiceKey != null) {
        sizeToSet = DimensionService.getInstance().getSize(myDimensionServiceKey, myProject);
    }

    if (myForcedSize != null) {
        sizeToSet = myForcedSize;
    }

    if (sizeToSet != null) {
        sizeToSet.width = Math.max(sizeToSet.width, myContent.getMinimumSize().width);
        sizeToSet.height = Math.max(sizeToSet.height, myContent.getMinimumSize().height);

        myContent.setSize(sizeToSet);
        myContent.setPreferredSize(sizeToSet);
    }

    Point xy = new Point(aScreenX, aScreenY);
    boolean adjustXY = true;
    if (myUseDimServiceForXYLocation && myDimensionServiceKey != null) {
        final Point storedLocation = DimensionService.getInstance().getLocation(myDimensionServiceKey,
                myProject);
        if (storedLocation != null) {
            xy = storedLocation;
            adjustXY = false;
        }
    }

    if (adjustXY) {
        final Insets insets = myContent.getInsets();
        if (insets != null) {
            xy.x -= insets.left;
            xy.y -= insets.top;
        }
    }

    if (considerForcedXY && myForcedLocation != null) {
        xy = myForcedLocation;
    }

    if (myLocateByContent) {
        final Dimension captionSize = myHeaderPanel.getPreferredSize();
        xy.y -= captionSize.height;
    }

    Rectangle targetBounds = new Rectangle(xy, myContent.getPreferredSize());
    Rectangle original = new Rectangle(targetBounds);
    if (myLocateWithinScreen) {
        ScreenUtil.moveToFit(targetBounds, ScreenUtil.getScreenRectangle(aScreenX, aScreenY), null);
    }

    if (myMouseOutCanceller != null) {
        myMouseOutCanceller.myEverEntered = targetBounds.equals(original);
    }

    myOwner = getFrameOrDialog(owner); // use correct popup owner for non-modal dialogs too
    if (myOwner == null) {
        myOwner = owner;
    }

    myRequestorComponent = owner;

    boolean forcedDialog = myMayBeParent
            || SystemInfo.isMac && !(myOwner instanceof IdeFrame) && myOwner != null && myOwner.isShowing();

    PopupComponent.Factory factory = getFactory(myForcedHeavyweight || myResizable, forcedDialog);
    myNativePopup = factory.isNativePopup();
    Component popupOwner = myOwner;
    if (popupOwner instanceof RootPaneContainer
            && !(popupOwner instanceof IdeFrame && !Registry.is("popup.fix.ide.frame.owner"))) {
        // JDK uses cached heavyweight popup for a window ancestor
        RootPaneContainer root = (RootPaneContainer) popupOwner;
        popupOwner = root.getRootPane();
        LOG.debug("popup owner fixed for JDK cache");
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("expected preferred size: " + myContent.getPreferredSize());
    }
    myPopup = factory.getPopup(popupOwner, myContent, targetBounds.x, targetBounds.y, this);
    if (LOG.isDebugEnabled()) {
        LOG.debug("  actual preferred size: " + myContent.getPreferredSize());
    }
    if ((targetBounds.width != myContent.getWidth()) || (targetBounds.height != myContent.getHeight())) {
        // JDK uses cached heavyweight popup that is not initialized properly
        LOG.debug("the expected size is not equal to the actual size");
        Window popup = myPopup.getWindow();
        if (popup != null) {
            popup.setSize(targetBounds.width, targetBounds.height);
            if (myContent.getParent().getComponentCount() != 1) {
                LOG.debug("unexpected count of components in heavy-weight popup");
            }
        } else {
            LOG.debug("cannot fix size for non-heavy-weight popup");
        }
    }

    if (myResizable) {
        final JRootPane root = myContent.getRootPane();
        final IdeGlassPaneImpl glass = new IdeGlassPaneImpl(root);
        root.setGlassPane(glass);

        int i = Registry.intValue("ide.popup.resizable.border.sensitivity", 4);
        WindowResizeListener resizeListener = new WindowResizeListener(myContent,
                myMovable ? new Insets(i, i, i, i) : new Insets(0, 0, i, i),
                isToDrawMacCorner() ? AllIcons.General.MacCorner : null) {
            private Cursor myCursor;

            @Override
            protected void setCursor(Component content, Cursor cursor) {
                if (myCursor != cursor || myCursor != Cursor.getDefaultCursor()) {
                    glass.setCursor(cursor, this);
                    myCursor = cursor;
                }
            }
        };
        glass.addMousePreprocessor(resizeListener, this);
        glass.addMouseMotionPreprocessor(resizeListener, this);
        myResizeListener = resizeListener;
    }

    if (myCaption != null && myMovable) {
        final WindowMoveListener moveListener = new WindowMoveListener(myCaption) {
            @Override
            public void mousePressed(final MouseEvent e) {
                if (e.isConsumed())
                    return;
                if (UIUtil.isCloseClick(e) && myCaption.isWithinPanel(e)) {
                    cancel();
                } else {
                    super.mousePressed(e);
                }
            }
        };
        myCaption.addMouseListener(moveListener);
        myCaption.addMouseMotionListener(moveListener);
        final MyContentPanel saved = myContent;
        Disposer.register(this, new Disposable() {
            @Override
            public void dispose() {
                ListenerUtil.removeMouseListener(saved, moveListener);
                ListenerUtil.removeMouseMotionListener(saved, moveListener);
            }
        });
        myMoveListener = moveListener;
    }

    for (JBPopupListener listener : myListeners) {
        listener.beforeShown(new LightweightWindowEvent(this));
    }

    myPopup.setRequestFocus(myRequestFocus);
    myPopup.show();

    final Window window = getContentWindow(myContent);

    myWindow = window;

    myWindowListener = new MyWindowListener();
    window.addWindowListener(myWindowListener);

    if (myFocusable) {
        window.setFocusableWindowState(true);
        window.setFocusable(true);
    }

    if (myWindow != null) {
        // dialogwrapper-based popups do this internally through peer,
        // for other popups like jdialog-based we should exclude them manually, but
        // we still have to be able to use IdeFrame as parent
        if (!myMayBeParent && !(myWindow instanceof Frame)) {
            WindowManager.getInstance().doNotSuggestAsParent(myWindow);
        }
    }

    setMinimumSize(myMinSize);

    final Runnable afterShow = new Runnable() {
        @Override
        public void run() {
            if (myPreferredFocusedComponent != null && myInStack && myFocusable) {
                myFocusTrackback.registerFocusComponent(myPreferredFocusedComponent);
                if (myPreferredFocusedComponent instanceof JTextComponent) {
                    IJSwingUtilities.moveMousePointerOn(myPreferredFocusedComponent);
                }
            }

            removeActivity();

            afterShow();

        }
    };

    if (myRequestFocus) {
        getFocusManager().requestFocus(new FocusCommand() {
            @NotNull
            @Override
            public ActionCallback run() {
                if (isDisposed()) {
                    removeActivity();
                    return ActionCallback.DONE;
                }

                _requestFocus();

                final ActionCallback result = new ActionCallback();

                final Runnable afterShowRunnable = new Runnable() {
                    @Override
                    public void run() {
                        afterShow.run();
                        result.setDone();
                    }
                };
                if (myNativePopup) {
                    final FocusRequestor furtherRequestor = getFocusManager().getFurtherRequestor();
                    //noinspection SSBasedInspection
                    SwingUtilities.invokeLater(new Runnable() {
                        @Override
                        public void run() {
                            if (isDisposed()) {
                                result.setRejected();
                                return;
                            }

                            furtherRequestor.requestFocus(new FocusCommand() {
                                @NotNull
                                @Override
                                public ActionCallback run() {
                                    if (isDisposed()) {
                                        return ActionCallback.REJECTED;
                                    }

                                    _requestFocus();

                                    afterShowRunnable.run();

                                    return ActionCallback.DONE;
                                }
                            }, true).notify(result).doWhenProcessed(new Runnable() {
                                @Override
                                public void run() {
                                    removeActivity();
                                }
                            });
                        }
                    });
                } else {
                    afterShowRunnable.run();
                }

                return result;
            }
        }, true).doWhenRejected(new Runnable() {
            @Override
            public void run() {
                afterShow.run();
            }
        });
    } else {
        //noinspection SSBasedInspection
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                if (isDisposed()) {
                    removeActivity();
                    return;
                }

                if (X_WINDOW_FOCUS_BUG && !myRequestFocus && prevOwner != null
                        && Registry.is("actionSystem.xWindow.remove.focus.from.nonFocusable.popups")) {
                    new Alarm().addRequest(new Runnable() {
                        @Override
                        public void run() {
                            if (isFocused()) {
                                IdeFocusManager.getInstance(myProject).requestFocus(prevOwner, false);
                            }
                        }
                    }, Registry.intValue("actionSystem.xWindow.remove.focus.from.nonFocusable.popups.delay"));
                }

                afterShow.run();
            }
        });
    }
    debugState("popup shown", State.SHOWING);
    myState = State.SHOWN;
}