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

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

Introduction

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

Prototype

@NotNull
    public static IdeFocusManager findInstanceByComponent(@NotNull Component component) 

Source Link

Usage

From source file:com.intellij.execution.testframework.export.ExportTestResultsForm.java

License:Apache License

public ExportTestResultsForm(ExportTestResultsConfiguration config, String defaultFileName,
        String defaultFolder) {//  w w  w  .j av a  2 s.  c o m
    ActionListener listener = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            updateOnFormatChange();
        }
    };
    myXmlRb.addActionListener(listener);
    myBundledTemplateRb.addActionListener(listener);
    myCustomTemplateRb.addActionListener(listener);

    myOutputFolderLabel.setLabelFor(myFolderField.getChildComponent());

    myFileNameField.setText(defaultFileName);

    myCustomTemplateField.addBrowseFolderListener(
            ExecutionBundle.message("export.test.results.custom.template.chooser.title"), null, null,
            new FileChooserDescriptor(true, false, false, false, false, false) {
                public boolean isFileSelectable(VirtualFile file) {
                    return "xsl".equalsIgnoreCase(file.getExtension())
                            || "xslt".equalsIgnoreCase(file.getExtension());
                }
            }, TextComponentAccessor.TEXT_FIELD_WHOLE_TEXT, false);

    myFolderField.addBrowseFolderListener(
            ExecutionBundle.message("export.test.results.output.folder.chooser.title"), null, null,
            FileChooserDescriptorFactory.createSingleFolderDescriptor(),
            TextComponentAccessor.TEXT_FIELD_WHOLE_TEXT, false);

    myFileNameField.getDocument().addDocumentListener(new DocumentAdapter() {
        @Override
        protected void textChanged(DocumentEvent e) {
            updateOpenInLabel();
        }
    });

    UserActivityWatcher watcher = new UserActivityWatcher();
    watcher.register(myContentPane);
    watcher.addUserActivityListener(new UserActivityListener() {
        @Override
        public void stateChanged() {
            myEventDispatcher.getMulticaster().stateChanged(new ChangeEvent(this));
        }
    });

    myMessageLabel.setIcon(UIUtil.getBalloonWarningIcon());
    JRadioButton b;
    if (config.getExportFormat() == ExportTestResultsConfiguration.ExportFormat.Xml) {
        b = myXmlRb;
    } else if (config.getExportFormat() == ExportTestResultsConfiguration.ExportFormat.BundledTemplate) {
        b = myBundledTemplateRb;
    } else {
        b = myCustomTemplateRb;
    }
    b.setSelected(true);
    IdeFocusManager.findInstanceByComponent(myContentPane).requestFocus(b, true);
    myFolderField.setText(defaultFolder);
    myCustomTemplateField
            .setText(FileUtil.toSystemDependentName(StringUtil.notNullize(config.getUserTemplatePath())));
    myOpenExportedFileCb.setSelected(config.isOpenResults());
    updateOnFormatChange();
    updateOpenInLabel();
}

From source file:com.intellij.execution.testframework.export.ExportTestResultsForm.java

License:Apache License

private void updateOnFormatChange() {
    if (getExportFormat() == ExportTestResultsConfiguration.ExportFormat.UserTemplate) {
        myCustomTemplateField.setEnabled(true);
        IdeFocusManager.findInstanceByComponent(myContentPane)
                .requestFocus(myCustomTemplateField.getChildComponent(), true);
    } else {/*  w ww. ja  v  a 2 s .c  o m*/
        myCustomTemplateField.setEnabled(false);
    }
    String filename = myFileNameField.getText();
    if (filename != null && filename.indexOf('.') != -1) {
        myFileNameField.setText(
                filename.substring(0, filename.lastIndexOf('.') + 1) + getExportFormat().getDefaultExtension());
    }
}

From source file:com.intellij.ide.actions.SearchEverywhereAction.java

License:Apache License

private void doNavigate(final int index) {
    final Project project = CommonDataKeys.PROJECT
            .getData(DataManager.getInstance().getDataContext(getField().getTextEditor()));
    final Executor executor = ourShiftIsPressed.get() ? DefaultRunExecutor.getRunExecutorInstance()
            : ExecutorRegistry.getInstance().getExecutorById(ToolWindowId.DEBUG);
    assert project != null;
    final SearchListModel model = getModel();
    if (isMoreItem(index)) {
        final String pattern = myPopupField.getText();
        WidgetID wid = null;//  w  w  w .j  av  a2 s  . c o m
        if (index == model.moreIndex.classes)
            wid = WidgetID.CLASSES;
        else if (index == model.moreIndex.files)
            wid = WidgetID.FILES;
        else if (index == model.moreIndex.settings)
            wid = WidgetID.SETTINGS;
        else if (index == model.moreIndex.actions)
            wid = WidgetID.ACTIONS;
        else if (index == model.moreIndex.symbols)
            wid = WidgetID.SYMBOLS;
        else if (index == model.moreIndex.runConfigurations)
            wid = WidgetID.RUN_CONFIGURATIONS;
        if (wid != null) {
            final WidgetID widgetID = wid;
            myCurrentWorker.doWhenProcessed(new Runnable() {
                @Override
                public void run() {
                    myCalcThread = new CalcThread(project, pattern, true);
                    myPopupActualWidth = 0;
                    myCurrentWorker = myCalcThread.insert(index, widgetID);
                }
            });

            return;
        }
    }
    final String pattern = getField().getText();
    final Object value = myList.getSelectedValue();
    saveHistory(project, pattern, value);
    IdeFocusManager focusManager = IdeFocusManager.findInstanceByComponent(getField().getTextEditor());
    if (myPopup != null && myPopup.isVisible()) {
        myPopup.cancel();
    }

    if (value instanceof BooleanOptionDescription) {
        final BooleanOptionDescription option = (BooleanOptionDescription) value;
        option.setOptionState(!option.isOptionEnabled());
        myList.revalidate();
        myList.repaint();
        getField().requestFocus();
        return;
    }

    if (value instanceof OptionsTopHitProvider) {
        //noinspection SSBasedInspection
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                getField().setText("#" + ((OptionsTopHitProvider) value).getId() + " ");
            }
        });
        return;
    }
    Runnable onDone = null;

    AccessToken token = ApplicationManager.getApplication().acquireReadActionLock();
    try {
        if (value instanceof PsiElement) {
            onDone = new Runnable() {
                @Override
                public void run() {
                    NavigationUtil.activateFileWithPsiElement((PsiElement) value, true);
                }
            };
            return;
        } else if (isVirtualFile(value)) {
            onDone = new Runnable() {
                @Override
                public void run() {
                    OpenSourceUtil.navigate(true, new OpenFileDescriptor(project, (VirtualFile) value));
                }
            };
            return;
        } else if (isActionValue(value) || isSetting(value) || isRunConfiguration(value)) {
            focusManager.requestDefaultFocus(true);
            final Component comp = myContextComponent;
            final AnActionEvent event = myActionEvent;
            IdeFocusManager.getInstance(project).doWhenFocusSettlesDown(new Runnable() {
                @Override
                public void run() {
                    Component c = comp;
                    if (c == null) {
                        c = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
                    }

                    if (isRunConfiguration(value)) {
                        ((ChooseRunConfigurationPopup.ItemWrapper) value).perform(project, executor,
                                DataManager.getInstance().getDataContext(c));
                    } else {
                        GotoActionAction.openOptionOrPerformAction(value, pattern, project, c, event);
                        if (isToolWindowAction(value))
                            return;
                    }
                }
            });
            return;
        } else if (value instanceof Navigatable) {
            onDone = new Runnable() {
                @Override
                public void run() {
                    OpenSourceUtil.navigate(true, (Navigatable) value);
                }
            };
            return;
        }
    } finally {
        token.finish();
        final ActionCallback callback = onFocusLost();
        if (onDone != null) {
            callback.doWhenDone(onDone);
        }
    }
    focusManager.requestDefaultFocus(true);
}

From source file:com.intellij.ide.IdeEventQueue.java

License:Apache License

public void fixStickyFocusedComponents(@Nullable AWTEvent e) {
      if (e != null && !(e instanceof InputEvent))
          return;

      final KeyboardFocusManager mgr = KeyboardFocusManager.getCurrentKeyboardFocusManager();

      if (Registry.is("actionSystem.fixStickyFocusedWindows")) {
          fixStickyWindow(mgr, mgr.getActiveWindow(), "setGlobalActiveWindow");
          fixStickyWindow(mgr, mgr.getFocusedWindow(), "setGlobalFocusedWindow");
      }//  ww  w. j a  v a 2  s  . c o  m

      if (Registry.is("actionSystem.fixNullFocusedComponent")) {
          final Component focusOwner = mgr.getFocusOwner();
          if (focusOwner == null || !focusOwner.isShowing() || focusOwner instanceof JFrame
                  || focusOwner instanceof JDialog) {

              final Application app = ApplicationManager.getApplication();
              if (app instanceof ApplicationEx && !((ApplicationEx) app).isLoaded()) {
                  return;
              }

              boolean mouseEventsAhead = isMouseEventAhead(e);
              boolean focusTransferredNow = IdeFocusManager.getGlobalInstance().isFocusBeingTransferred();

              boolean okToFixFocus = !mouseEventsAhead && !focusTransferredNow;

              if (okToFixFocus) {
                  Window showingWindow = mgr.getActiveWindow();
                  if (showingWindow == null) {
                      Method getNativeFocusOwner = ReflectionUtil.getDeclaredMethod(KeyboardFocusManager.class,
                              "getNativeFocusOwner");
                      if (getNativeFocusOwner != null) {
                          try {
                              Object owner = getNativeFocusOwner.invoke(mgr);
                              if (owner instanceof Component) {
                                  showingWindow = UIUtil.getWindow((Component) owner);
                              }
                          } catch (Exception e1) {
                              LOG.debug(e1);
                          }
                      }
                  }
                  if (showingWindow != null) {
                      final IdeFocusManager fm = IdeFocusManager.findInstanceByComponent(showingWindow);
                      ExpirableRunnable maybeRequestDefaultFocus = new ExpirableRunnable() {
                          @Override
                          public void run() {
                              if (getPopupManager().requestDefaultFocus(false))
                                  return;

                              final Application app = ApplicationManager.getApplication();
                              if (app != null && app.isActive()) {
                                  fm.requestDefaultFocus(false);
                              }
                          }

                          @Override
                          public boolean isExpired() {
                              return !UIUtil.isMeaninglessFocusOwner(mgr.getFocusOwner());
                          }
                      };
                      fm.revalidateFocus(maybeRequestDefaultFocus);
                  }
              }
          }
      }
  }

From source file:com.intellij.ide.IdeEventQueue.java

License:Apache License

private static boolean typeAheadDispatchToFocusManager(AWTEvent e) {
      if (e instanceof KeyEvent) {
          final KeyEvent event = (KeyEvent) e;
          if (!event.isConsumed()) {
              final IdeFocusManager focusManager = IdeFocusManager.findInstanceByComponent(event.getComponent());
              return focusManager.dispatch(event);
          }/*w  w  w .ja  v a 2  s .com*/
      }

      return false;
  }

From source file:com.intellij.ide.impl.DataManagerImpl.java

License:Apache License

@Nullable
private Component getFocusedComponent() {
    if (myWindowManager == null) {
        return null;
    }/*  ww  w .  j ava2 s .c om*/
    Window activeWindow = myWindowManager.getMostRecentFocusedWindow();
    if (activeWindow == null) {
        activeWindow = KeyboardFocusManager.getCurrentKeyboardFocusManager().getActiveWindow();
        if (activeWindow == null) {
            activeWindow = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusedWindow();
            if (activeWindow == null)
                return null;
        }
    }

    if (Registry.is("actionSystem.noContextComponentWhileFocusTransfer")) {
        IdeFocusManager fm = IdeFocusManager.findInstanceByComponent(activeWindow);
        if (fm.isFocusBeingTransferred()) {
            return null;
        }
    }

    // In case we have an active floating toolwindow and some component in another window focused,
    // we want this other component to receive key events.
    // Walking up the window ownership hierarchy from the floating toolwindow would have led us to the main IdeFrame
    // whereas we want to be able to type in other frames as well.
    if (activeWindow instanceof FloatingDecorator) {
        IdeFocusManager ideFocusManager = IdeFocusManager.findInstanceByComponent(activeWindow);
        IdeFrame lastFocusedFrame = ideFocusManager.getLastFocusedFrame();
        JComponent frameComponent = lastFocusedFrame != null ? lastFocusedFrame.getComponent() : null;
        Window lastFocusedWindow = frameComponent != null ? SwingUtilities.getWindowAncestor(frameComponent)
                : null;
        boolean toolWindowIsNotFocused = myWindowManager.getFocusedComponent(activeWindow) == null;
        if (toolWindowIsNotFocused && lastFocusedWindow != null) {
            activeWindow = lastFocusedWindow;
        }
    }

    // try to find first parent window that has focus
    Window window = activeWindow;
    Component focusedComponent = null;
    while (window != null) {
        focusedComponent = myWindowManager.getFocusedComponent(window);
        if (focusedComponent != null) {
            break;
        }
        window = window.getOwner();
    }
    if (focusedComponent == null) {
        focusedComponent = activeWindow;
    }

    return focusedComponent;
}

From source file:com.intellij.ide.wizard.AbstractWizard.java

License:Apache License

private static void requestFocusTo(final JComponent component) {
    UiNotifyConnector.doWhenFirstShown(component, new Runnable() {
        @Override/*from w ww  . j a  v a2s .  co  m*/
        public void run() {
            final IdeFocusManager focusManager = IdeFocusManager.findInstanceByComponent(component);
            focusManager.requestFocus(component, false);
        }
    });
}

From source file:com.intellij.ide.wizard.AbstractWizardEx.java

License:Apache License

protected void updateStep() {
    super.updateStep();
    updateButtons();/*  ww w  . ja v a 2  s  . c o m*/
    final AbstractWizardStepEx step = getCurrentStepObject();
    String stepTitle = step.getTitle();
    setTitle(stepTitle != null ? myTitle + ": " + stepTitle : myTitle);
    final JComponent toFocus = step.getPreferredFocusedComponent();
    if (toFocus != null) {
        IdeFocusManager.findInstanceByComponent(getWindow()).requestFocus(toFocus, true);
    }
}

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;/* www  .  ja v a 2s.c o 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

private IdeFocusManager getFocusManager() {
    if (myProject != null) {
        return IdeFocusManager.getInstance(myProject);
    }/*from   w ww.  ja va2  s.  c o m*/
    if (myOwner != null) {
        return IdeFocusManager.findInstanceByComponent(myOwner);
    }
    return IdeFocusManager.findInstance();
}