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

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

Introduction

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

Prototype

void cancel();

Source Link

Document

Cancels the popup as if Esc was pressed or any other "cancel" action.

Usage

From source file:com.android.tools.idea.uibuilder.actions.TogglePanningDialogAction.java

License:Apache License

@Override
public void setSelected(AnActionEvent e, boolean state) {
    if (state) {//from  w ww  .j ava2 s . co  m
        NlUsageTrackerManager.getInstance(mySurface)
                .logAction(LayoutEditorEvent.LayoutEditorEventType.SHOW_PAN_AND_ZOOM);
        myPopupReference = new WeakReference<>(WidgetNavigatorPanel.createPopup(mySurface));
    } else {
        if (myPopupReference != null) {
            JBPopup popup = myPopupReference.get();
            if (popup != null) {
                popup.cancel();
            }
        }
    }
}

From source file:com.antoine.ideaplugin.greenrobot.ShowUsagesAction.java

License:Apache License

private void showElementUsages(@NotNull final FindUsagesHandler handler, final Editor editor,
        @NotNull final RelativePoint popupPosition, final int maxUsages,
        @NotNull final FindUsagesOptions options) {
    ApplicationManager.getApplication().assertIsDispatchThread();
    final UsageViewSettings usageViewSettings = UsageViewSettings.getInstance();
    final UsageViewSettings savedGlobalSettings = new UsageViewSettings();

    savedGlobalSettings.loadState(usageViewSettings);
    usageViewSettings.loadState(myUsageViewSettings);

    final Project project = handler.getProject();
    UsageViewManager manager = UsageViewManager.getInstance(project);
    FindUsagesManager findUsagesManager = ((FindManagerImpl) FindManager.getInstance(project))
            .getFindUsagesManager();//from   w w w  .  j  a  v a2s  .  c o  m
    final UsageViewPresentation presentation = findUsagesManager.createPresentation(handler, options);
    presentation.setDetachedMode(true);
    final UsageViewImpl usageView = (UsageViewImpl) manager.createUsageView(UsageTarget.EMPTY_ARRAY,
            Usage.EMPTY_ARRAY, presentation, null);

    Disposer.register(usageView, new Disposable() {
        @Override
        public void dispose() {
            myUsageViewSettings.loadState(usageViewSettings);
            usageViewSettings.loadState(savedGlobalSettings);
        }
    });

    final List<Usage> usages = new ArrayList<Usage>();
    final Set<UsageNode> visibleNodes = new LinkedHashSet<UsageNode>();
    UsageInfoToUsageConverter.TargetElementsDescriptor descriptor = new UsageInfoToUsageConverter.TargetElementsDescriptor(
            handler.getPrimaryElements(), handler.getSecondaryElements());

    final MyTable table = new MyTable();
    final AsyncProcessIcon processIcon = new AsyncProcessIcon("xxx");
    boolean hadMoreSeparator = visibleNodes.remove(MORE_USAGES_SEPARATOR_NODE);
    if (hadMoreSeparator) {
        usages.add(MORE_USAGES_SEPARATOR);
        visibleNodes.add(MORE_USAGES_SEPARATOR_NODE);
    }

    addUsageNodes(usageView.getRoot(), usageView, new ArrayList<UsageNode>());

    TableScrollingUtil.installActions(table);

    final List<UsageNode> data = collectData(usages, visibleNodes, usageView, presentation);
    setTableModel(table, usageView, data);

    SpeedSearchBase<JTable> speedSearch = new MySpeedSearch(table);
    speedSearch.setComparator(new SpeedSearchComparator(false));

    final JBPopup popup = createUsagePopup(usages, descriptor, visibleNodes, handler, editor, popupPosition,
            maxUsages, usageView, options, table, presentation, processIcon, hadMoreSeparator);

    Disposer.register(popup, usageView);

    // show popup only if find usages takes more than 300ms, otherwise it would flicker needlessly
    Alarm alarm = new Alarm(usageView);
    alarm.addRequest(new Runnable() {
        @Override
        public void run() {
            showPopupIfNeedTo(popup, popupPosition);
        }
    }, 300);

    final PingEDT pingEDT = new PingEDT("Rebuild popup in EDT", new Condition<Object>() {
        @Override
        public boolean value(Object o) {
            return popup.isDisposed();
        }
    }, 100, new Runnable() {
        @Override
        public void run() {
            if (popup.isDisposed())
                return;

            final List<UsageNode> nodes = new ArrayList<UsageNode>();
            List<Usage> copy;
            synchronized (usages) {
                // open up popup as soon as several usages 've been found
                if (!popup.isVisible() && (usages.size() <= 1 || !showPopupIfNeedTo(popup, popupPosition))) {
                    return;
                }
                addUsageNodes(usageView.getRoot(), usageView, nodes);
                copy = new ArrayList<Usage>(usages);
            }

            rebuildPopup(usageView, copy, nodes, table, popup, presentation, popupPosition,
                    !processIcon.isDisposed());
        }
    });

    final MessageBusConnection messageBusConnection = project.getMessageBus().connect(usageView);
    messageBusConnection.subscribe(UsageFilteringRuleProvider.RULES_CHANGED, new Runnable() {
        @Override
        public void run() {
            pingEDT.ping();
        }
    });

    Processor<Usage> collect = new Processor<Usage>() {
        private final UsageTarget[] myUsageTarget = {
                new PsiElement2UsageTargetAdapter(handler.getPsiElement()) };

        @Override
        public boolean process(@NotNull Usage usage) {
            synchronized (usages) {
                if (visibleNodes.size() >= maxUsages)
                    return false;
                if (UsageViewManager.isSelfUsage(usage, myUsageTarget)) {
                    return true;
                }

                Usage usageToAdd = transform(usage);
                if (usageToAdd == null)
                    return true;

                UsageNode node = usageView.doAppendUsage(usageToAdd);
                usages.add(usageToAdd);
                if (node != null) {
                    visibleNodes.add(node);
                    boolean continueSearch = true;
                    if (visibleNodes.size() == maxUsages) {
                        visibleNodes.add(MORE_USAGES_SEPARATOR_NODE);
                        usages.add(MORE_USAGES_SEPARATOR);
                        continueSearch = false;
                    }
                    pingEDT.ping();

                    return continueSearch;
                }
                return true;
            }
        }
    };

    final ProgressIndicator indicator = FindUsagesManager.startProcessUsages(handler,
            handler.getPrimaryElements(), handler.getSecondaryElements(), collect, options, new Runnable() {
                @Override
                public void run() {
                    ApplicationManager.getApplication().invokeLater(new Runnable() {
                        @Override
                        public void run() {
                            Disposer.dispose(processIcon);
                            Container parent = processIcon.getParent();
                            parent.remove(processIcon);
                            parent.repaint();
                            pingEDT.ping(); // repaint title
                            synchronized (usages) {
                                if (visibleNodes.isEmpty()) {
                                    if (usages.isEmpty()) {
                                        String text = UsageViewBundle.message("no.usages.found.in",
                                                searchScopePresentableName(options, project));
                                        showHint(text, editor, popupPosition, handler, maxUsages, options);
                                        popup.cancel();
                                    } else {
                                        // all usages filtered out
                                    }
                                } else if (visibleNodes.size() == 1) {
                                    if (usages.size() == 1) {
                                        //the only usage
                                        Usage usage = visibleNodes.iterator().next().getUsage();
                                        usage.navigate(true);
                                        //String message = UsageViewBundle.message("show.usages.only.usage", searchScopePresentableName(options, project));
                                        //navigateAndHint(usage, message, handler, popupPosition, maxUsages, options);
                                        popup.cancel();
                                    } else {
                                        assert usages.size() > 1 : usages;
                                        // usage view can filter usages down to one
                                        Usage visibleUsage = visibleNodes.iterator().next().getUsage();
                                        if (areAllUsagesInOneLine(visibleUsage, usages)) {
                                            String hint = UsageViewBundle.message("all.usages.are.in.this.line",
                                                    usages.size(),
                                                    searchScopePresentableName(options, project));
                                            navigateAndHint(visibleUsage, hint, handler, popupPosition,
                                                    maxUsages, options);
                                            popup.cancel();
                                        }
                                    }
                                } else {
                                    String title = presentation.getTabText();
                                    boolean shouldShowMoreSeparator = visibleNodes
                                            .contains(MORE_USAGES_SEPARATOR_NODE);
                                    String fullTitle = getFullTitle(usages, title, shouldShowMoreSeparator,
                                            visibleNodes.size() - (shouldShowMoreSeparator ? 1 : 0), false);
                                    ((AbstractPopup) popup).setCaption(fullTitle);
                                }
                            }
                        }
                    }, project.getDisposed());
                }
            });
    Disposer.register(popup, new Disposable() {
        @Override
        public void dispose() {
            indicator.cancel();
        }
    });
}

From source file:com.intellij.byteCodeViewer.ShowByteCodeAction.java

License:Apache License

@Override
public void actionPerformed(AnActionEvent e) {
    final DataContext dataContext = e.getDataContext();
    final Project project = CommonDataKeys.PROJECT.getData(dataContext);
    if (project == null)
        return;//from w w w. j  a va2 s.  c o  m
    final Editor editor = CommonDataKeys.EDITOR.getData(dataContext);

    final PsiElement psiElement = getPsiElement(dataContext, project, editor);
    if (psiElement == null)
        return;

    final String psiElementTitle = ByteCodeViewerManager.getInstance(project).getTitle(psiElement);

    final VirtualFile virtualFile = PsiUtilCore.getVirtualFile(psiElement);
    if (virtualFile == null)
        return;

    final SmartPsiElementPointer element = SmartPointerManager.getInstance(project)
            .createSmartPsiElementPointer(psiElement);
    ProgressManager.getInstance().run(new Task.Backgroundable(project, "Searching byte code...") {
        private String myByteCode;
        private String myErrorMessage;
        private String myErrorTitle;

        @Override
        public void run(@NotNull ProgressIndicator indicator) {
            if (ProjectRootManager.getInstance(project).getFileIndex().isInContent(virtualFile)
                    && TranslatingCompilerFilesMonitor.getInstance().isMarkedForCompilation(project,
                            virtualFile)) {
                myErrorMessage = "Unable to show byte code for '" + psiElementTitle
                        + "'. Class file does not exist or is out-of-date.";
                myErrorTitle = "Class File Out-Of-Date";
            } else {
                myByteCode = ApplicationManager.getApplication().runReadAction(new Computable<String>() {
                    @Override
                    public String compute() {
                        return ByteCodeViewerManager.getByteCode(psiElement);
                    }
                });
            }
        }

        @Override
        public void onSuccess() {
            if (project.isDisposed())
                return;

            if (myErrorMessage != null && myTitle != null) {
                Messages.showWarningDialog(project, myErrorMessage, myErrorTitle);
                return;
            }
            final PsiElement targetElement = element.getElement();
            if (targetElement == null)
                return;

            final ByteCodeViewerManager codeViewerManager = ByteCodeViewerManager.getInstance(project);
            if (codeViewerManager.hasActiveDockedDocWindow()) {
                codeViewerManager.doUpdateComponent(targetElement, myByteCode);
            } else {
                if (myByteCode == null) {
                    Messages.showErrorDialog(project,
                            "Unable to parse class file for '" + psiElementTitle + "'.", "Byte Code not Found");
                    return;
                }
                final ByteCodeViewerComponent component = new ByteCodeViewerComponent(project, null);
                component.setText(myByteCode, targetElement);
                Processor<JBPopup> pinCallback = new Processor<JBPopup>() {
                    @Override
                    public boolean process(JBPopup popup) {
                        codeViewerManager.recreateToolWindow(targetElement, targetElement);
                        popup.cancel();
                        return false;
                    }
                };

                final JBPopup popup = JBPopupFactory.getInstance().createComponentPopupBuilder(component, null)
                        .setRequestFocusCondition(project, NotLookupOrSearchCondition.INSTANCE)
                        .setProject(project)
                        .setDimensionServiceKey(project, DocumentationManager.JAVADOC_LOCATION_AND_SIZE, false)
                        .setResizable(true).setMovable(true)
                        .setRequestFocus(LookupManager.getActiveLookup(editor) == null)
                        .setTitle(psiElementTitle + " Bytecode").setCouldPin(pinCallback).createPopup();
                Disposer.register(popup, component);

                PopupPositionManager.positionPopupInBestPosition(popup, editor, dataContext);
            }
        }
    });
}

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

License:Apache License

public HectorComponent(@NotNull PsiFile file) {
    super(new GridBagLayout());
    setBorder(BorderFactory.createEmptyBorder(0, 0, 7, 0));
    myFile = file;//from w  w  w.  j av a2s .  c o  m
    mySliders = new HashMap<Language, JSlider>();

    final Project project = myFile.getProject();
    final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex();
    final VirtualFile virtualFile = myFile.getContainingFile().getVirtualFile();
    LOG.assertTrue(virtualFile != null);
    final boolean notInLibrary = !fileIndex.isInLibrarySource(virtualFile)
            && !fileIndex.isInLibraryClasses(virtualFile) || fileIndex.isInContent(virtualFile);
    final FileViewProvider viewProvider = myFile.getViewProvider();
    final Set<Language> languages = new TreeSet<Language>(LanguageUtil.LANGUAGE_COMPARATOR);
    languages.addAll(viewProvider.getLanguages());
    for (Language language : languages) {
        @SuppressWarnings("UseOfObsoleteCollectionType")
        final Hashtable<Integer, JLabel> sliderLabels = new Hashtable<Integer, JLabel>();
        sliderLabels.put(1, new JLabel(EditorBundle.message("hector.none.slider.label")));
        sliderLabels.put(2, new JLabel(EditorBundle.message("hector.syntax.slider.label")));
        if (notInLibrary) {
            sliderLabels.put(3, new JLabel(EditorBundle.message("hector.inspections.slider.label")));
        }

        final JSlider slider = new JSlider(SwingConstants.VERTICAL, 1, notInLibrary ? 3 : 2, 1);
        if (UIUtil.isUnderGTKLookAndFeel()) {
            // default GTK+ slider UI is way too ugly
            slider.putClientProperty("Slider.paintThumbArrowShape", true);
            slider.setUI(new BasicSliderUI(slider));
        }
        slider.setLabelTable(sliderLabels);
        UIUtil.setSliderIsFilled(slider, true);
        slider.setPaintLabels(true);
        slider.setSnapToTicks(true);
        slider.addChangeListener(new ChangeListener() {
            @Override
            public void stateChanged(ChangeEvent e) {
                int value = slider.getValue();
                for (Enumeration<Integer> enumeration = sliderLabels.keys(); enumeration.hasMoreElements();) {
                    Integer key = enumeration.nextElement();
                    sliderLabels.get(key).setForeground(key.intValue() <= value ? UIUtil.getLabelForeground()
                            : UIUtil.getLabelDisabledForeground());
                }
            }
        });

        final PsiFile psiRoot = viewProvider.getPsi(language);
        assert psiRoot != null : "No root in " + viewProvider + " for " + language;
        slider.setValue(getValue(HighlightingLevelManager.getInstance(project).shouldHighlight(psiRoot),
                HighlightingLevelManager.getInstance(project).shouldInspect(psiRoot)));
        mySliders.put(language, slider);
    }

    GridBagConstraints gc = new GridBagConstraints(0, GridBagConstraints.RELATIVE, 1, 1, 0, 0,
            GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(0, 5, 0, 0), 0, 0);

    JPanel panel = new JPanel(new GridBagLayout());
    panel.setBorder(IdeBorderFactory.createTitledBorder(EditorBundle.message("hector.highlighting.level.title"),
            false));
    final boolean addLabel = mySliders.size() > 1;
    if (addLabel) {
        layoutVertical(panel);
    } else {
        layoutHorizontal(panel);
    }
    gc.gridx = 0;
    gc.gridy = 0;
    gc.weighty = 1.0;
    gc.fill = GridBagConstraints.BOTH;
    add(panel, gc);

    gc.gridy = GridBagConstraints.RELATIVE;
    gc.weighty = 0;

    final HyperlinkLabel configurator = new HyperlinkLabel("Configure inspections");
    gc.insets.right = 5;
    gc.insets.bottom = 10;
    gc.weightx = 0;
    gc.fill = GridBagConstraints.NONE;
    gc.anchor = GridBagConstraints.EAST;
    add(configurator, gc);
    configurator.addHyperlinkListener(new HyperlinkListener() {
        @Override
        public void hyperlinkUpdate(HyperlinkEvent e) {
            final JBPopup hector = getOldHector();
            if (hector != null) {
                hector.cancel();
            }
            if (!DaemonCodeAnalyzer.getInstance(myFile.getProject()).isHighlightingAvailable(myFile))
                return;
            final Project project = myFile.getProject();
            final ErrorsConfigurable errorsConfigurable = ErrorsConfigurable.SERVICE
                    .createConfigurable(project);
            assert errorsConfigurable != null;
            errorsConfigurable.setFilterLanguages(languages);
            ShowSettingsUtil.getInstance().editConfigurable(project, errorsConfigurable);
        }
    });

    gc.anchor = GridBagConstraints.WEST;
    gc.weightx = 1.0;
    gc.insets.right = 0;
    gc.fill = GridBagConstraints.HORIZONTAL;
    myAdditionalPanels = new ArrayList<HectorComponentPanel>();
    for (HectorComponentPanelsProvider provider : HectorComponentPanelsProvider.EP_NAME
            .getExtensions(project)) {
        final HectorComponentPanel componentPanel = provider.createConfigurable(file);
        if (componentPanel != null) {
            myAdditionalPanels.add(componentPanel);
            add(componentPanel.createComponent(), gc);
            componentPanel.reset();
        }
    }
}

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

License:Apache License

public void showComponent(RelativePoint point) {
    final JBPopup hector = JBPopupFactory.getInstance().createComponentPopupBuilder(this, this)
            .setRequestFocus(true).setMovable(true).setCancelCallback(new Computable<Boolean>() {
                @Override//from   w  w  w .  j  av  a 2s . c o  m
                public Boolean compute() {
                    for (HectorComponentPanel additionalPanel : myAdditionalPanels) {
                        if (!additionalPanel.canClose()) {
                            return Boolean.FALSE;
                        }
                    }
                    onClose();
                    return Boolean.TRUE;
                }
            }).createPopup();
    Disposer.register(myFile.getProject(), new Disposable() {
        @Override
        public void dispose() {
            final JBPopup oldHector = getOldHector();
            if (oldHector != null && !oldHector.isDisposed()) {
                Disposer.dispose(oldHector);
            }
            Disposer.dispose(hector);
        }
    });
    final JBPopup oldHector = getOldHector();
    if (oldHector != null) {
        oldHector.cancel();
    } else {
        myHectorRef = new WeakReference<JBPopup>(hector);
        hector.show(point);
    }
}

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

License:Apache License

@Nullable
public static JBPopup navigateOrCreatePopup(@NotNull final NavigatablePsiElement[] targets, final String title,
        final String findUsagesTitle, final ListCellRenderer listRenderer,
        @Nullable final ListBackgroundUpdaterTask listUpdaterTask, @NotNull final Consumer<Object[]> consumer) {
    if (targets.length == 0)
        return null;
    if (targets.length == 1) {
        consumer.consume(targets);//  www.  jav  a  2  s  .  c o  m
        return null;
    }
    final CollectionListModel<NavigatablePsiElement> model = new CollectionListModel<NavigatablePsiElement>(
            targets);
    final JBListWithHintProvider list = new JBListWithHintProvider(model) {
        @Override
        protected PsiElement getPsiElementForHint(final Object selectedValue) {
            return (PsiElement) selectedValue;
        }
    };

    list.setTransferHandler(new TransferHandler() {
        @Nullable
        @Override
        protected Transferable createTransferable(JComponent c) {
            final Object[] selectedValues = list.getSelectedValues();
            final PsiElement[] copy = new PsiElement[selectedValues.length];
            for (int i = 0; i < selectedValues.length; i++) {
                copy[i] = (PsiElement) selectedValues[i];
            }
            return new PsiCopyPasteManager.MyTransferable(copy);
        }

        @Override
        public int getSourceActions(JComponent c) {
            return COPY;
        }
    });

    list.setCellRenderer(listRenderer);
    list.setFont(ChooseByNameBase.getEditorFont());

    final PopupChooserBuilder builder = new PopupChooserBuilder(list);
    if (listRenderer instanceof PsiElementListCellRenderer) {
        ((PsiElementListCellRenderer) listRenderer).installSpeedSearch(builder);
    }

    PopupChooserBuilder popupChooserBuilder = builder.setTitle(title).setMovable(true).setResizable(true)
            .setItemChoosenCallback(new Runnable() {
                @Override
                public void run() {
                    int[] ids = list.getSelectedIndices();
                    if (ids == null || ids.length == 0)
                        return;
                    Object[] selectedElements = list.getSelectedValues();
                    consumer.consume(selectedElements);
                }
            }).setCancelCallback(new Computable<Boolean>() {
                @Override
                public Boolean compute() {
                    HintUpdateSupply.hideHint(list);
                    return true;
                }
            });
    final Ref<UsageView> usageView = new Ref<UsageView>();
    if (findUsagesTitle != null) {
        popupChooserBuilder = popupChooserBuilder.setCouldPin(new Processor<JBPopup>() {
            @Override
            public boolean process(JBPopup popup) {
                final List<NavigatablePsiElement> items = model.getItems();
                usageView.set(FindUtil.showInUsageView(null, items.toArray(new PsiElement[items.size()]),
                        findUsagesTitle, targets[0].getProject()));
                popup.cancel();
                return false;
            }
        });
    }

    final JBPopup popup = popupChooserBuilder.createPopup();

    builder.getScrollPane().setBorder(null);
    builder.getScrollPane().setViewportBorder(null);

    if (listUpdaterTask != null) {
        listUpdaterTask.init((AbstractPopup) popup, list, usageView);

        ProgressManager.getInstance().run(listUpdaterTask);
    }
    return popup;
}

From source file:com.intellij.codeInsight.documentation.DocumentationManager.java

License:Apache License

public DocumentationManager(final Project project, ActionManagerEx managerEx) {
    super(project);
    myActionManagerEx = managerEx;/* w  ww  . jav a 2s  .c  om*/
    final AnActionListener actionListener = new AnActionListener() {
        @Override
        public void beforeActionPerformed(AnAction action, DataContext dataContext, AnActionEvent event) {
            final JBPopup hint = getDocInfoHint();
            if (hint != null) {
                if (action instanceof HintManagerImpl.ActionToIgnore) {
                    ((AbstractPopup) hint).focusPreferredComponent();
                    return;
                }
                if (action instanceof ListScrollingUtil.ListScrollAction)
                    return;
                if (action == myActionManagerEx.getAction(IdeActions.ACTION_EDITOR_MOVE_CARET_DOWN))
                    return;
                if (action == myActionManagerEx.getAction(IdeActions.ACTION_EDITOR_MOVE_CARET_UP))
                    return;
                if (action == myActionManagerEx.getAction(IdeActions.ACTION_EDITOR_MOVE_CARET_PAGE_DOWN))
                    return;
                if (action == myActionManagerEx.getAction(IdeActions.ACTION_EDITOR_MOVE_CARET_PAGE_UP))
                    return;
                if (action == ActionManagerEx.getInstanceEx().getAction(IdeActions.ACTION_EDITOR_ESCAPE))
                    return;
                if (ActionPlaces.JAVADOC_INPLACE_SETTINGS.equals(event.getPlace()))
                    return;
                if (action instanceof BaseNavigateToSourceAction)
                    return;
                closeDocHint();
            }
        }

        @Override
        public void beforeEditorTyping(char c, DataContext dataContext) {
            final JBPopup hint = getDocInfoHint();
            if (hint != null && LookupManager.getActiveLookup(myEditor) == null) {
                hint.cancel();
            }
        }

        @Override
        public void afterActionPerformed(final AnAction action, final DataContext dataContext,
                AnActionEvent event) {
        }
    };
    myActionManagerEx.addAnActionListener(actionListener, project);
    myUpdateDocAlarm = new Alarm(Alarm.ThreadToUse.POOLED_THREAD, myProject);
}

From source file:com.intellij.codeInsight.documentation.DocumentationManager.java

License:Apache License

private void closeDocHint() {
    JBPopup hint = getDocInfoHint();
    if (hint == null) {
        return;/*from w  ww  . j  av a  2 s .  com*/
    }
    myCloseOnSneeze = false;
    hint.cancel();
    Component toFocus = myPreviouslyFocused;
    hint.cancel();
    if (toFocus != null) {
        IdeFocusManager.getInstance(myProject).requestFocus(toFocus, true);
    }
}

From source file:com.intellij.codeInsight.documentation.DocumentationManager.java

License:Apache License

private void showInPopup(@NotNull final PsiElement element, boolean requestFocus,
        PopupUpdateProcessor updateProcessor, final PsiElement originalElement,
        @Nullable final Runnable closeCallback) {
    final DocumentationComponent component = new DocumentationComponent(this);
    component.setNavigateCallback(new Consumer<PsiElement>() {
        @Override//from  ww w  . ja  v a2s. c  o m
        public void consume(PsiElement psiElement) {
            final AbstractPopup jbPopup = (AbstractPopup) getDocInfoHint();
            if (jbPopup != null) {
                final String title = getTitle(psiElement, false);
                jbPopup.setCaption(title);
            }
        }
    });
    Processor<JBPopup> pinCallback = new Processor<JBPopup>() {
        @Override
        public boolean process(JBPopup popup) {
            createToolWindow(element, originalElement);
            myToolWindow.setAutoHide(false);
            popup.cancel();
            return false;
        }
    };

    ActionListener actionListener = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            createToolWindow(element, originalElement);
            final JBPopup hint = getDocInfoHint();
            if (hint != null && hint.isVisible())
                hint.cancel();
        }
    };
    List<Pair<ActionListener, KeyStroke>> actions = ContainerUtil.newSmartList();
    AnAction quickDocAction = ActionManagerEx.getInstanceEx().getAction(IdeActions.ACTION_QUICK_JAVADOC);
    for (Shortcut shortcut : quickDocAction.getShortcutSet().getShortcuts()) {
        if (!(shortcut instanceof KeyboardShortcut))
            continue;
        actions.add(Pair.create(actionListener, ((KeyboardShortcut) shortcut).getFirstKeyStroke()));
    }

    boolean hasLookup = LookupManager.getActiveLookup(myEditor) != null;
    final JBPopup hint = JBPopupFactory.getInstance().createComponentPopupBuilder(component, component)
            .setProject(element.getProject()).addListener(updateProcessor).addUserData(updateProcessor)
            .setKeyboardActions(actions).setDimensionServiceKey(myProject, JAVADOC_LOCATION_AND_SIZE, false)
            .setResizable(true).setMovable(true).setRequestFocus(requestFocus)
            .setCancelOnClickOutside(!hasLookup) // otherwise selecting lookup items by mouse would close the doc
            .setTitle(getTitle(element, false)).setCouldPin(pinCallback).setModalContext(false)
            .setCancelCallback(new Computable<Boolean>() {
                @Override
                public Boolean compute() {
                    myCloseOnSneeze = false;
                    if (closeCallback != null) {
                        closeCallback.run();
                    }
                    if (fromQuickSearch()) {
                        ((ChooseByNameBase.JPanelProvider) myPreviouslyFocused.getParent()).unregisterHint();
                    }

                    Disposer.dispose(component);
                    myEditor = null;
                    myPreviouslyFocused = null;
                    return Boolean.TRUE;
                }
            }).setKeyEventHandler(new BooleanFunction<KeyEvent>() {
                @Override
                public boolean fun(KeyEvent e) {
                    if (myCloseOnSneeze) {
                        closeDocHint();
                    }
                    if ((AbstractPopup.isCloseRequest(e) && getDocInfoHint() != null)) {
                        closeDocHint();
                        return true;
                    }
                    return false;
                }
            }).createPopup();

    component.setHint(hint);

    if (myEditor == null) {
        // subsequent invocation of javadoc popup from completion will have myEditor == null because of cancel invoked, 
        // so reevaluate the editor for proper popup placement
        Lookup lookup = LookupManager.getInstance(myProject).getActiveLookup();
        myEditor = lookup != null ? lookup.getEditor() : null;
    }
    fetchDocInfo(getDefaultCollector(element, originalElement), component);

    myDocInfoHintRef = new WeakReference<JBPopup>(hint);

    if (fromQuickSearch() && myPreviouslyFocused != null) {
        ((ChooseByNameBase.JPanelProvider) myPreviouslyFocused.getParent()).registerHint(hint);
    }
}

From source file:com.intellij.codeInsight.documentation.QuickDocOnMouseOverManager.java

License:Apache License

private void closeQuickDocIfPossible() {
    myAlarm.cancelAllRequests();//from  ww  w  .j ava2 s .  co m
    DocumentationManager docManager = getDocManager();
    if (docManager == null) {
        return;
    }

    JBPopup hint = docManager.getDocInfoHint();
    if (hint == null) {
        return;
    }

    hint.cancel();
    myDocumentationManager = null;
}