Example usage for com.intellij.openapi.wm IdeFocusManager findInstance

List of usage examples for com.intellij.openapi.wm IdeFocusManager findInstance

Introduction

In this page you can find the example usage for com.intellij.openapi.wm IdeFocusManager findInstance.

Prototype

@NotNull
    public static IdeFocusManager findInstance() 

Source Link

Usage

From source file:com.intellij.ui.mac.MacMessagesImpl.java

License:Apache License

private static Window getForemostWindow(final Window window) {
    Window _window = null;//from  www. j  a  v  a2  s.c om
    IdeFocusManager ideFocusManager = IdeFocusManager.getGlobalInstance();

    Component focusOwner = IdeFocusManager.findInstance().getFocusOwner();
    // Let's ask for a focused component first
    if (focusOwner != null) {
        _window = SwingUtilities.getWindowAncestor(focusOwner);
    }

    if (_window == null) {
        // Looks like ide lost focus, let's ask about the last focused component
        focusOwner = ideFocusManager.getLastFocusedFor(ideFocusManager.getLastFocusedFrame());
        if (focusOwner != null) {
            _window = SwingUtilities.getWindowAncestor(focusOwner);
        }
    }

    if (_window == null) {
        _window = WindowManager.getInstance().findVisibleFrame();
    }

    if (_window == null && window != null) {
        // It might be we just has not opened a frame yet.
        // So let's ask AWT
        focusOwner = window.getMostRecentFocusOwner();
        if (focusOwner != null) {
            _window = SwingUtilities.getWindowAncestor(focusOwner);
        }
    }

    if (_window != null) {
        // We have successfully found the window
        // Let's check that we have not missed a blocker
        if (ModalityHelper.isModalBlocked(_window)) {
            _window = ModalityHelper.getModalBlockerFor(_window);
        }
    }

    if (SystemInfo.isAppleJvm && MacUtil.getWindowTitle(_window) == null) {
        // With Apple JDK we cannot find a window if it does not have a title
        // Let's show a dialog instead of the message.
        throw new MacMessageException("MacMessage parent does not have a title.");
    }
    while (_window != null && MacUtil.getWindowTitle(_window) == null) {
        _window = _window.getOwner();
        //At least our frame should have a title
    }

    while (Registry.is("skip.untitled.windows.for.mac.messages") && _window != null
            && _window instanceof JDialog && !((JDialog) _window).isModal()) {
        _window = _window.getOwner();
    }

    return _window;
}

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

License:Apache License

private IdeFocusManager getFocusManager() {
    if (myProject != null) {
        return IdeFocusManager.getInstance(myProject);
    }//  w ww . jav  a 2  s.c  om
    if (myOwner != null) {
        return IdeFocusManager.findInstanceByComponent(myOwner);
    }
    return IdeFocusManager.findInstance();
}

From source file:com.intellij.util.net.HttpConfigurable.java

License:Apache License

@Deprecated
public void writeExternal(Element element) throws WriteExternalException {
    XmlSerializer.serializeInto(getState(), element);
    if (USE_PROXY_PAC && USE_HTTP_PROXY && !ApplicationManager.getApplication().isDisposed()) {
        ApplicationManager.getApplication().invokeLater(new Runnable() {
            @Override/*from w  w w  .jav  a  2  s  .  c  o m*/
            public void run() {
                IdeFrame frame = IdeFocusManager.findInstance().getLastFocusedFrame();
                if (frame != null) {
                    USE_PROXY_PAC = false;
                    Messages.showMessageDialog(frame.getComponent(),
                            "Proxy: both 'use proxy' and 'autodetect proxy' settings were set."
                                    + "\nOnly one of these options should be selected.\nPlease re-configure.",
                            "Proxy Setup", Messages.getWarningIcon());
                    editConfigurable(frame.getComponent());
                }
            }
        }, ModalityState.NON_MODAL);
    }
}

From source file:com.intellij.util.net.HTTPProxySettingsPanel.java

License:Apache License

public HTTPProxySettingsPanel(final HttpConfigurable httpConfigurable) {
    final ButtonGroup group = new ButtonGroup();
    group.add(myUseHTTPProxyRb);//from w  w  w  . ja  va  2 s  . c  om
    group.add(myAutoDetectProxyRb);
    group.add(myNoProxyRb);
    myNoProxyRb.setSelected(true);

    final ButtonGroup proxyTypeGroup = new ButtonGroup();
    proxyTypeGroup.add(myHTTP);
    proxyTypeGroup.add(mySocks);
    myHTTP.setSelected(true);

    myProxyExceptions.setBorder(UIUtil.getTextFieldBorder());

    final Boolean property = Boolean.getBoolean(JavaProxyProperty.USE_SYSTEM_PROXY);
    mySystemProxyDefined.setVisible(Boolean.TRUE.equals(property));
    if (Boolean.TRUE.equals(property)) {
        mySystemProxyDefined.setIcon(Messages.getWarningIcon());
        mySystemProxyDefined.setFont(mySystemProxyDefined.getFont().deriveFont(Font.BOLD));
        mySystemProxyDefined.setUI(new MultiLineLabelUI());
    }

    myProxyAuthCheckBox.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            enableProxyAuthentication(myProxyAuthCheckBox.isSelected());
        }
    });

    final ActionListener listener = new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            enableProxy(myUseHTTPProxyRb.isSelected());
        }
    };
    myUseHTTPProxyRb.addActionListener(listener);
    myAutoDetectProxyRb.addActionListener(listener);
    myNoProxyRb.addActionListener(listener);
    myHttpConfigurable = httpConfigurable;

    myClearPasswordsButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            myHttpConfigurable.clearGenericPasswords();
            Messages.showMessageDialog(myMainPanel, "Proxy passwords were cleared.", "Auto-detected proxy",
                    Messages.getInformationIcon());
        }
    });

    if (HttpConfigurable.getInstance() != null) {
        myCheckButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                final String title = "Check Proxy Settings";
                final String answer = Messages.showInputDialog(myMainPanel,
                        "Warning: your settings will be saved.\n\nEnter any URL to check connection to:", title,
                        Messages.getQuestionIcon(), "http://", null);
                if (!StringUtil.isEmptyOrSpaces(answer)) {
                    apply();
                    final HttpConfigurable instance = HttpConfigurable.getInstance();
                    final AtomicReference<IOException> exc = new AtomicReference<IOException>();
                    myCheckButton.setEnabled(false);
                    myCheckButton.setText("Check connection (in progress...)");
                    myConnectionCheckInProgress = true;
                    final Application application = ApplicationManager.getApplication();
                    application.executeOnPooledThread(new Runnable() {
                        @Override
                        public void run() {
                            HttpURLConnection connection = null;
                            try {
                                //already checked for null above
                                //noinspection ConstantConditions
                                connection = instance.openHttpConnection(answer);
                                connection.setReadTimeout(3 * 1000);
                                connection.setConnectTimeout(3 * 1000);
                                connection.connect();
                                final int code = connection.getResponseCode();
                                if (HttpURLConnection.HTTP_OK != code) {
                                    exc.set(new IOException("Error code: " + code));
                                }
                            } catch (IOException e1) {
                                exc.set(e1);
                            } finally {
                                if (connection != null) {
                                    connection.disconnect();
                                }
                            }
                            //noinspection SSBasedInspection
                            SwingUtilities.invokeLater(new Runnable() {
                                @Override
                                public void run() {
                                    myConnectionCheckInProgress = false;
                                    reset(); // since password might have been set
                                    Component parent = null;
                                    if (myMainPanel.isShowing()) {
                                        parent = myMainPanel;
                                        myCheckButton.setText("Check connection");
                                        myCheckButton.setEnabled(canEnableConnectionCheck());
                                    } else {
                                        final IdeFrame frame = IdeFocusManager.findInstance()
                                                .getLastFocusedFrame();
                                        if (frame == null) {
                                            return;
                                        }
                                        parent = frame.getComponent();
                                    }
                                    //noinspection ThrowableResultOfMethodCallIgnored
                                    final IOException exception = exc.get();
                                    if (exception == null) {
                                        Messages.showMessageDialog(parent, "Connection successful", title,
                                                Messages.getInformationIcon());
                                    } else {
                                        final String message = exception.getMessage();
                                        if (instance.USE_HTTP_PROXY) {
                                            instance.LAST_ERROR = message;
                                        }
                                        Messages.showErrorDialog(parent, errorText(message));
                                    }
                                }
                            });
                        }
                    });
                }
            }
        });
    } else {
        myCheckButton.setVisible(false);
    }
}

From source file:com.intellij.util.net.HttpProxySettingsUi.java

License:Apache License

private void configureCheckButton() {
    if (HttpConfigurable.getInstance() == null) {
        myCheckButton.setVisible(false);
        return;/*w w w  .  j av a 2 s  . co m*/
    }

    myCheckButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(@NotNull ActionEvent e) {
            final String title = "Check Proxy Settings";
            final String answer = Messages.showInputDialog(myMainPanel,
                    "Warning: your settings will be saved.\n\nEnter any URL to check connection to:", title,
                    Messages.getQuestionIcon(), "http://", null);
            if (StringUtil.isEmptyOrSpaces(answer)) {
                return;
            }

            final HttpConfigurable settings = HttpConfigurable.getInstance();
            apply(settings);
            final AtomicReference<IOException> exceptionReference = new AtomicReference<IOException>();
            myCheckButton.setEnabled(false);
            myCheckButton.setText("Check connection (in progress...)");
            myConnectionCheckInProgress = true;
            ApplicationManager.getApplication().executeOnPooledThread(new Runnable() {
                @Override
                public void run() {
                    HttpURLConnection connection = null;
                    try {
                        //already checked for null above
                        //noinspection ConstantConditions
                        connection = settings.openHttpConnection(answer);
                        connection.setReadTimeout(3 * 1000);
                        connection.setConnectTimeout(3 * 1000);
                        connection.connect();
                        final int code = connection.getResponseCode();
                        if (HttpURLConnection.HTTP_OK != code) {
                            exceptionReference.set(new IOException("Error code: " + code));
                        }
                    } catch (IOException e) {
                        exceptionReference.set(e);
                    } finally {
                        if (connection != null) {
                            connection.disconnect();
                        }
                    }
                    //noinspection SSBasedInspection
                    SwingUtilities.invokeLater(new Runnable() {
                        @Override
                        public void run() {
                            myConnectionCheckInProgress = false;
                            reset(settings); // since password might have been set
                            Component parent;
                            if (myMainPanel.isShowing()) {
                                parent = myMainPanel;
                                myCheckButton.setText("Check connection");
                                myCheckButton.setEnabled(canEnableConnectionCheck());
                            } else {
                                IdeFrame frame = IdeFocusManager.findInstance().getLastFocusedFrame();
                                if (frame == null) {
                                    return;
                                }
                                parent = frame.getComponent();
                            }
                            //noinspection ThrowableResultOfMethodCallIgnored
                            final IOException exception = exceptionReference.get();
                            if (exception == null) {
                                Messages.showMessageDialog(parent, "Connection successful", title,
                                        Messages.getInformationIcon());
                            } else {
                                final String message = exception.getMessage();
                                if (settings.USE_HTTP_PROXY) {
                                    settings.LAST_ERROR = message;
                                }
                                Messages.showErrorDialog(parent, errorText(message));
                            }
                        }
                    });
                }
            });
        }
    });
}

From source file:com.intellij.xdebugger.impl.breakpoints.ui.XLightBreakpointPropertiesPanel.java

License:Apache License

public XLightBreakpointPropertiesPanel(Project project, XBreakpointManager breakpointManager, B breakpoint,
        boolean showAllOptions) {
    myBreakpoint = breakpoint;//from  w ww  .jav  a  2 s .  c  om
    myShowAllOptions = showAllOptions;
    XBreakpointType<B, ?> breakpointType = XBreakpointUtil.getType(breakpoint);

    mySuspendPolicyPanel.init(project, breakpointManager, breakpoint);
    mySuspendPolicyPanel.setDelegate(this);

    mySubPanels.add(mySuspendPolicyPanel);
    myMasterBreakpointPanel.init(project, breakpointManager, breakpoint);
    mySubPanels.add(myMasterBreakpointPanel);
    XDebuggerEditorsProvider debuggerEditorsProvider = breakpointType.getEditorsProvider(breakpoint, project);

    myActionsPanel.init(project, breakpointManager, breakpoint, debuggerEditorsProvider);
    mySubPanels.add(myActionsPanel);

    myCustomPanels = new ArrayList<XBreakpointCustomPropertiesPanel<B>>();
    if (debuggerEditorsProvider != null) {
        myConditionEnabledCheckbox = new JBCheckBox(XDebuggerBundle.message("xbreakpoints.condition.checkbox"));
        JBLabel conditionEnabledLabel = new JBLabel(XDebuggerBundle.message("xbreakpoints.condition.checkbox"));
        conditionEnabledLabel.setBorder(UIUtil.getTextAlignBorder(myConditionEnabledCheckbox));
        myConditionEnabledPanel.add(myConditionEnabledCheckbox, CONDITION_ENABLED_CHECKBOX);
        myConditionEnabledPanel.add(conditionEnabledLabel, CONDITION_ENABLED_LABEL);
        myConditionComboBox = new XDebuggerExpressionComboBox(project, debuggerEditorsProvider,
                CONDITION_HISTORY_ID, myBreakpoint.getSourcePosition());
        JComponent conditionComponent = myConditionComboBox.getComponent();
        myConditionExpressionPanel.add(conditionComponent, BorderLayout.CENTER);
        myConditionEnabledCheckbox.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                onCheckboxChanged();
            }
        });
        DebuggerUIUtil.focusEditorOnCheck(myConditionEnabledCheckbox, myConditionComboBox.getEditorComponent());
    } else {
        myConditionPanel.setVisible(false);
    }

    myShowMoreOptions = false;
    for (XBreakpointPropertiesSubPanel<B> panel : mySubPanels) {
        if (panel.lightVariant(showAllOptions)) {
            myShowMoreOptions = true;
        }
    }

    XBreakpointCustomPropertiesPanel<B> customPropertiesPanel = breakpointType.createCustomPropertiesPanel();
    if (customPropertiesPanel != null) {
        myCustomPropertiesPanelWrapper.add(customPropertiesPanel.getComponent(), BorderLayout.CENTER);
        myCustomPanels.add(customPropertiesPanel);
    }

    XBreakpointCustomPropertiesPanel<B> customConditionPanel = breakpointType.createCustomConditionsPanel();
    if (customConditionPanel != null) {
        myCustomConditionsPanelWrapper.add(customConditionPanel.getComponent(), BorderLayout.CENTER);
        myCustomPanels.add(customConditionPanel);
    }

    XBreakpointCustomPropertiesPanel<B> customRightConditionPanel = breakpointType
            .createCustomRightPropertiesPanel(project);
    if (customRightConditionPanel != null
            && (showAllOptions || customRightConditionPanel.isVisibleOnPopup(breakpoint))) {
        myCustomRightPropertiesPanelWrapper.add(customRightConditionPanel.getComponent(), BorderLayout.CENTER);
        myCustomPanels.add(customRightConditionPanel);
    } else {
        // see IDEA-125745
        myCustomRightPropertiesPanelWrapper.getParent().remove(myCustomRightPropertiesPanelWrapper);
    }

    XBreakpointCustomPropertiesPanel<B> customTopPropertiesPanel = breakpointType
            .createCustomTopPropertiesPanel(project);
    if (customTopPropertiesPanel != null) {
        myCustomTopPropertiesPanelWrapper.add(customTopPropertiesPanel.getComponent(), BorderLayout.CENTER);
        myCustomPanels.add(customTopPropertiesPanel);
    }

    myMainPanel.addFocusListener(new FocusAdapter() {
        @Override
        public void focusGained(FocusEvent event) {
            if (myConditionComboBox != null) {
                IdeFocusManager.findInstance().requestFocus(myConditionComboBox.getEditorComponent(), false);
            }
        }
    });

    myEnabledCheckbox.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent event) {
            myBreakpoint.setEnabled(myEnabledCheckbox.isSelected());
        }
    });
}

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

License:Apache License

public static void showXBreakpointEditorBalloon(final Project project, @Nullable final Point point,
        final JComponent component, final boolean showAllOptions, final XBreakpoint breakpoint) {
    final XBreakpointManager breakpointManager = XDebuggerManager.getInstance(project).getBreakpointManager();
    final XLightBreakpointPropertiesPanel<XBreakpointBase<?, ?, ?>> propertiesPanel = new XLightBreakpointPropertiesPanel<XBreakpointBase<?, ?, ?>>(
            project, breakpointManager, (XBreakpointBase) breakpoint, showAllOptions);

    final Ref<Balloon> balloonRef = Ref.create(null);
    final Ref<Boolean> isLoading = Ref.create(Boolean.FALSE);
    final Ref<Boolean> moreOptionsRequested = Ref.create(Boolean.FALSE);

    propertiesPanel.setDelegate(new XLightBreakpointPropertiesPanel.Delegate() {
        @Override/*from w  ww  . java2s .c  o  m*/
        public void showMoreOptions() {
            if (!isLoading.get()) {
                propertiesPanel.saveProperties();
            }
            if (!balloonRef.isNull()) {
                balloonRef.get().hide();
            }
            showXBreakpointEditorBalloon(project, point, component, true, breakpoint);
            moreOptionsRequested.set(true);
        }
    });

    isLoading.set(Boolean.TRUE);
    propertiesPanel.loadProperties();
    isLoading.set(Boolean.FALSE);

    if (moreOptionsRequested.get()) {
        return;
    }

    Runnable showMoreOptions = new Runnable() {
        @Override
        public void run() {
            propertiesPanel.saveProperties();
            propertiesPanel.dispose();
            BreakpointsDialogFactory.getInstance(project).showDialog(breakpoint);
        }
    };

    final JComponent mainPanel = propertiesPanel.getMainPanel();
    final Balloon balloon = showBreakpointEditor(project, mainPanel, point, component, showMoreOptions,
            breakpoint);
    balloonRef.set(balloon);

    final XBreakpointListener<XBreakpoint<?>> breakpointListener = new XBreakpointAdapter<XBreakpoint<?>>() {
        @Override
        public void breakpointRemoved(@NotNull XBreakpoint<?> removedBreakpoint) {
            if (removedBreakpoint.equals(breakpoint)) {
                balloon.hide();
            }
        }
    };

    balloon.addListener(new JBPopupListener.Adapter() {
        @Override
        public void onClosed(LightweightWindowEvent event) {
            propertiesPanel.saveProperties();
            propertiesPanel.dispose();
            breakpointManager.removeBreakpointListener(breakpointListener);
        }
    });

    breakpointManager.addBreakpointListener(breakpointListener);
    ApplicationManager.getApplication().invokeLater(new Runnable() {
        @Override
        public void run() {
            IdeFocusManager.findInstance().requestFocus(mainPanel, true);
        }
    });
}

From source file:com.mbeddr.pluginmanager.com.intellij.ide.plugins.PluginHeaderPanel.java

License:Apache License

private void createUIComponents() {
    myInstallButton = new JButton() {
        {//from   w w  w .  jav a 2 s .c  o m
            setOpaque(false);
            setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        }

        @Override
        public Dimension getPreferredSize() {
            final FontMetrics metrics = getFontMetrics(getFont());
            final int textWidth = metrics.stringWidth(getText());
            final int width = 8 + 16 + 4 + textWidth + 8;
            final int height = 2 + Math.max(16, metrics.getHeight()) + 2;
            return new Dimension(width, height);
        }

        @Override
        public void paint(Graphics g2) {
            final Graphics2D g = (Graphics2D) g2;
            final GraphicsConfig config = GraphicsUtil.setupAAPainting(g);
            final int w = g.getClipBounds().width;
            final int h = g.getClipBounds().height;

            g.setPaint(getBackgroundBorderPaint());
            g.fillRoundRect(0, 0, w, h, 7, 7);

            g.setPaint(getBackgroundPaint());
            g.fillRoundRect(1, 1, w - 2, h - 2, 6, 6);
            g.setColor(getButtonForeground());
            int offset = 8;
            g.drawString(getText(), offset + 16 + 4, getBaseline(w, h));
            getIcon().paintIcon(this, g, offset, (getHeight() - getIcon().getIconHeight()) / 2);
            config.restore();
        }

        private Color getButtonForeground() {
            switch (myActionId) {
            case UPDATE:
                return new JBColor(Gray._240, Gray._210);
            case INSTALL:
                return new JBColor(Gray._240, Gray._210);
            case RESTART:
            case UNINSTALL:
                return new JBColor(Gray._0, Gray._210);
            }

            return new JBColor(Gray._80, Gray._60);
        }

        private Paint getBackgroundPaint() {
            switch (myActionId) {
            case UPDATE:
                return new JBGradientPaint(this, new JBColor(new Color(98, 158, 225), new Color(98, 158, 225)),
                        new JBColor(new Color(58, 91, 181), new Color(58, 91, 181)));
            case INSTALL:
                return new JBGradientPaint(this, new JBColor(new Color(96, 204, 105), new Color(81, 149, 87)),
                        new JBColor(new Color(50, 101, 41), new Color(40, 70, 47)));
            case RESTART:
            case UNINSTALL:
                return UIUtil.isUnderDarcula()
                        ? new JBGradientPaint(this, UIManager.getColor("Button.darcula.color1"),
                                UIManager.getColor("Button.darcula.color2"))
                        : Gray._240;
            }
            return Gray._238;
        }

        private Paint getBackgroundBorderPaint() {
            switch (myActionId) {
            case UPDATE:
                return new JBColor(new Color(166, 180, 205), Gray._85);
            case INSTALL:
                return new JBColor(new Color(201, 223, 201), Gray._70);
            case RESTART:
            case UNINSTALL:
                return new JBColor(Gray._220, Gray._100.withAlpha(180));
            }
            return Gray._208;
        }

        @Override
        public String getText() {
            switch (myActionId) {
            case UPDATE:
                return "Update";
            case INSTALL:
                return "Install";
            case UNINSTALL:
                return "Uninstall";
            case RESTART:
                return "Restart " + ApplicationNamesInfo.getInstance().getFullProductName();
            }
            return super.getText();
        }

        @Override
        public Icon getIcon() {
            switch (myActionId) {
            case UPDATE:
                return AllIcons.General.DownloadPlugin;
            case INSTALL:
                return AllIcons.General.DownloadPlugin;
            case UNINSTALL:
                return AllIcons.Actions.Delete;
            case RESTART:
                return AllIcons.Actions.Restart;
            }
            return super.getIcon();

        }
    };
    myInstallButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            switch (myActionId) {
            case UPDATE:
            case INSTALL:
                new InstallPluginAction(myManager.getAvailable(), myManager.getInstalled())
                        .install(new Runnable() {
                            @Override
                            public void run() {
                                setPlugin(myPlugin);
                            }
                        }, true);
                break;
            case UNINSTALL:
                UninstallPluginAction.uninstall(myManager.getInstalled(), true, myPlugin);
                break;
            case RESTART:
                if (myManager != null) {
                    myManager.apply();
                }
                final DialogWrapper dialog = DialogWrapper
                        .findInstance(KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner());
                if (dialog != null && dialog.isModal()) {
                    dialog.close(DialogWrapper.OK_EXIT_CODE);
                }
                //noinspection SSBasedInspection
                SwingUtilities.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        final DialogWrapper settings = DialogWrapper
                                .findInstance(IdeFocusManager.findInstance().getFocusOwner());
                        if (settings instanceof SettingsDialog) {
                            ((SettingsDialog) settings).doOKAction();
                            ApplicationManager.getApplication().restart();
                        } else {
                            ApplicationManager.getApplication().restart();
                        }
                    }
                });
                break;
            }
            setPlugin(myPlugin);
        }
    });
}

From source file:org.jetbrains.plugins.groovy.refactoring.ui.MethodOrClosureScopeChooser.java

License:Apache License

/**
 * @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)
 *///from   w  w w  . j  av  a2 s.com
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 Icon icon = IconDescriptorUpdaters.getIcon(method, Iconable.ICON_FLAG_VISIBILITY);
                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<RangeHighlighter>();
    final TextAttributes attributes = EditorColorsManager.getInstance().getGlobalScheme()
            .getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES);
    list.addListSelectionListener(new ListSelectionListener() {
        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(new Runnable() {
                        public void run() {
                            callback.fun(ToSearchIn, toSearchFor);
                        }
                    });
                }
            }, 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();
}

From source file:org.twodividedbyzero.idea.findbugs.gui.settings.ShareTab.java

License:Open Source License

void requestFocusOnImportFile() {
    IdeFocusManager.findInstance().doWhenFocusSettlesDown(new Runnable() {
        @Override/*from  ww w. j  a v  a2 s  .  c  o m*/
        public void run() {
            IdeFocusManager.findInstance().requestFocus(importPathLabel.getComponent().getTextField(), true);
        }
    });
}