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

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

Introduction

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

Prototype

@NotNull
    public static IdeFocusManager getGlobalInstance() 

Source Link

Usage

From source file:com.intellij.internal.focus.FocusTracesAction.java

License:Apache License

@Override
public void actionPerformed(AnActionEvent e) {
    final Project project = e.getData(CommonDataKeys.PROJECT);
    final IdeFocusManager manager = IdeFocusManager.getGlobalInstance();
    if (!(manager instanceof FocusManagerImpl))
        return;//from   w  ww  .ja  v a 2 s. c  om
    final FocusManagerImpl focusManager = (FocusManagerImpl) manager;

    myActive = !myActive;
    if (myActive) {
        myFocusTracker = new AWTEventListener() {
            @Override
            public void eventDispatched(AWTEvent event) {
                if (event instanceof FocusEvent && event.getID() == FocusEvent.FOCUS_GAINED) {
                    focusManager.getRequests().add(
                            new FocusRequestInfo(((FocusEvent) event).getComponent(), new Throwable(), false));
                }
            }
        };
        Toolkit.getDefaultToolkit().addAWTEventListener(myFocusTracker, AWTEvent.FOCUS_EVENT_MASK);
    }

    if (!myActive) {
        final List<FocusRequestInfo> requests = focusManager.getRequests();
        new FocusTracesDialog(project, new ArrayList<FocusRequestInfo>(requests)).show();
        Toolkit.getDefaultToolkit().removeAWTEventListener(myFocusTracker);
        myFocusTracker = null;
        requests.clear();
    }
}

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

License:Apache License

public FocusTrackback(@NotNull Object requestor, Window parent, boolean mustBeShown) {
    myRequestor = new WeakReference<Object>(requestor);
    myRequestorName = requestor.toString();
    myParentWindow = parent;/*from  ww  w  .  j a v  a2  s.  co  m*/
    myMustBeShown = mustBeShown;

    final Application app = ApplicationManager.getApplication();
    if (app == null || app.isUnitTestMode() || wrongOS())
        return;

    register(parent);

    final List<FocusTrackback> stack = getStackForRoot(myRoot);
    final int index = stack.indexOf(this);

    //todo [kirillk] diagnostics for IDEADEV-28766
    assert index >= 0 : myRequestorName;

    final KeyboardFocusManager manager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
    setLocalFocusOwner(manager.getPermanentFocusOwner());

    final IdeFocusManager fm = IdeFocusManager.getGlobalInstance();
    if (myLocalFocusOwner == null && fm.isFocusBeingTransferred()) {
        if (index > 0) {
            int eachIndex = index - 1;
            while (eachIndex > 0) {
                final FocusTrackback each = stack.get(eachIndex);
                if (!each.isConsumed() && each.myLocalFocusOwner != null) {
                    setLocalFocusOwner(each.myLocalFocusOwner);
                    break;
                }
                eachIndex--;
            }
        }
    }

    if (index == 0) {
        setFocusOwner(manager.getPermanentFocusOwner());
        if (getFocusOwner() == null) {
            final Window window = manager.getActiveWindow();
            if (window instanceof Provider) {
                final FocusTrackback other = ((Provider) window).getFocusTrackback();
                if (other != null) {
                    setFocusOwner(other.getFocusOwner());
                }
            }
        }
    } else {
        setFocusOwner(stack.get(0).getFocusOwner());
    }

    if (stack.size() == 1 && getFocusOwner() == null) {
        setFocusOwner(getFocusFor(myRoot));
    } else if (index == 0 && getFocusOwner() != null) {
        setFocusFor(myRoot, getFocusOwner());
    }
}

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

License:Apache License

public void swipe(@NotNull final Container parent, @NotNull final String name,
        @NotNull SwipeDirection direction, final @Nullable Runnable onDone) {
    stopSwipeIfNeed();//from   www.j  a v  a2 s .co m
    mySwipeFrom = findVisible(parent);
    mySwipeTo = myMap.get(name);
    if (mySwipeTo == null)
        return;
    if (mySwipeFrom == null || mySwipeFrom == mySwipeTo) {
        super.show(parent, name);
        if (onDone != null) {
            onDone.run();
        }
        return;
    }
    final boolean isForward;
    if (direction == SwipeDirection.AUTO) {
        boolean b = true;
        for (Component component : myMap.values()) {
            if (component == mySwipeFrom || component == mySwipeTo) {
                b = component == mySwipeFrom;
                break;
            }
        }
        isForward = b;
    } else {
        isForward = direction == SwipeDirection.FORWARD;
    }
    final double[] linearProgress = new double[1];
    linearProgress[0] = 0;
    final long startTime = System.currentTimeMillis();
    ActionListener listener = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            long timePassed = System.currentTimeMillis() - startTime;
            if (timePassed >= mySwipeTime) {
                Component currentFocusComponent = IdeFocusManager.getGlobalInstance()
                        .getFocusedDescendantFor(parent);
                show(parent, name);
                if (currentFocusComponent != null)
                    currentFocusComponent.requestFocusInWindow();
                if (onDone != null) {
                    onDone.run();
                }
                return;
            }
            linearProgress[0] = Math.min(1, Math.max(0, (float) timePassed / mySwipeTime));
            double naturalProgress = (1 - Math.cos(Math.PI * linearProgress[0])) / 2;
            Rectangle bounds = parent.getBounds();
            Insets insets = parent.getInsets();
            bounds.setLocation(insets.left, insets.top);
            bounds.width -= insets.left + insets.right;
            bounds.height -= insets.top + insets.bottom;
            Rectangle r = new Rectangle(bounds);
            int x = (int) ((naturalProgress * r.width));
            r.translate(isForward ? -x : x, 0);
            mySwipeFrom.setBounds(r);
            Rectangle r2 = new Rectangle(bounds);
            r2.translate(isForward ? r2.width - x : x - r2.width, 0);
            mySwipeTo.setVisible(true);
            mySwipeTo.setBounds(r2);
            parent.repaint();
        }
    };
    for (ActionListener actionListener : myTimer.getActionListeners()) {
        myTimer.removeActionListener(actionListener);
    }
    myTimer.addActionListener(listener);
    myTimer.start();
}

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

License:Apache License

private static Window showDialog(@Nullable Window window, final String methodName,
        final DialogParamsWrapper paramsWrapper) {

    final Window foremostWindow = getForemostWindow(window);

    final Window documentRoot = getDocumentRootFromWindow(foremostWindow);

    final ID nativeFocusedWindow = MacUtil.findWindowFromJavaWindow(foremostWindow);

    paramsWrapper.setNativeWindow(nativeFocusedWindow);

    final ID paramsArray = paramsWrapper.getParamsAsID();

    foremostWindow.addWindowListener(new WindowAdapter() {
        @Override/*from ww  w .ja v a 2  s.c o  m*/
        public void windowClosed(WindowEvent e) {
            super.windowClosed(e);
            //if (blockedDocumentRoots.get(documentRoot) != null) {
            //   LOG.assertTrue(blockedDocumentRoots.get(documentRoot) < 2);
            //}
            queuesFromDocumentRoot.remove(documentRoot);
            if (blockedDocumentRoots.remove(documentRoot) != null) {
                throw new MacMessageException("Owner window has been removed");
            }
        }
    });

    final ID delegate = invoke(invoke(getObjcClass("NSAlertDelegate_"), "alloc"), "init");

    IdeFocusManager.getGlobalInstance().setTypeaheadEnabled(false);

    runOrPostponeForWindow(documentRoot, new Runnable() {
        @Override
        public void run() {
            invoke(delegate, "performSelectorOnMainThread:withObject:waitUntilDone:",
                    createSelector(methodName), paramsArray, false);
        }
    });

    startModal(documentRoot, nativeFocusedWindow);

    IdeFocusManager.getGlobalInstance().setTypeaheadEnabled(true);
    return documentRoot;
}

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

License:Apache License

private static Window getForemostWindow(final Window window) {
    Window _window = null;//from   w w w  .j a  va  2 s  .co m
    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.switcher.SwitchManager.java

License:Apache License

public ActionCallback applySwitch() {
    final ActionCallback result = new ActionCallback();
    if (isSessionActive()) {
        final boolean showSpots = mySession.isShowspots();
        mySession.finish(false).doWhenDone(new Consumer<SwitchTarget>() {
            @Override//www . j a v a  2 s  .c o m
            public void consume(final SwitchTarget switchTarget) {
                mySession = null;
                IdeFocusManager.getGlobalInstance().doWhenFocusSettlesDown(new Runnable() {
                    public void run() {
                        tryToInitSessionFromFocus(switchTarget, showSpots)
                                .doWhenProcessed(result.createSetDoneRunnable());
                    }
                });
            }
        });
    } else {
        result.setDone();
    }

    return result;
}

From source file:com.microsoft.alm.plugin.idea.common.utils.IdeaHelper.java

License:Open Source License

/**
 * Find the project that is associated with the current open frame
 * Got this method from how Git gets the current project
 *
 * @return project based on repo//ww w .  ja  v  a2  s  .  c  o m
 */
public static Project getCurrentProject() {
    final IdeFrame frame = IdeFocusManager.getGlobalInstance().getLastFocusedFrame();
    return frame == null || frame.getProject() == null ? ProjectManager.getInstance().getDefaultProject()
            : frame.getProject();
}

From source file:io.flutter.project.FlutterProjectCreator.java

License:Open Source License

public void createProject() {
    IdeFrame frame = IdeFocusManager.getGlobalInstance().getLastFocusedFrame();
    final Project projectToClose = frame != null ? frame.getProject() : null;

    final File location = new File(FileUtil.toSystemDependentName(myModel.projectLocation().get()));
    if (!location.exists() && !location.mkdirs()) {
        String message = ActionsBundle.message("action.NewDirectoryProject.cannot.create.dir",
                location.getAbsolutePath());
        Messages.showErrorDialog(projectToClose, message,
                ActionsBundle.message("action.NewDirectoryProject.title"));
        return;//from   w  ww .jav a 2 s. co m
    }
    final File baseFile = new File(location, myModel.projectName().get());
    //noinspection ResultOfMethodCallIgnored
    baseFile.mkdirs();
    final VirtualFile baseDir = ApplicationManager.getApplication().runWriteAction(
            (Computable<VirtualFile>) () -> LocalFileSystem.getInstance().refreshAndFindFileByIoFile(baseFile));
    if (baseDir == null) {
        LOG.error("Couldn't find '" + location + "' in VFS");
        return;
    }
    VfsUtil.markDirtyAndRefresh(false, true, true, baseDir);

    RecentProjectsManager.getInstance().setLastProjectCreationLocation(location.getPath());

    ProjectOpenedCallback callback = (project, module) -> ProgressManager.getInstance()
            .run(new Task.Modal(null, "Creating Flutter Project", false) {
                @Override
                public void run(@NotNull ProgressIndicator indicator) {
                    indicator.setIndeterminate(true);

                    // The IDE has already created some files. Flutter won't overwrite them, but we want the versions provided by Flutter.
                    deleteDirectoryContents(baseFile);

                    // Add an Android facet if needed by the project type.
                    if (myModel.projectType().getValue() != FlutterProjectType.PACKAGE) {
                        ModifiableFacetModel model = FacetManager.getInstance(module).createModifiableModel();
                        AndroidFacetType facetType = AndroidFacet.getFacetType();
                        AndroidFacet facet = facetType.createFacet(module, AndroidFacet.NAME,
                                facetType.createDefaultConfiguration(), null);
                        model.addFacet(facet);
                        configureFacet(facet, baseFile, "android");
                        File appLocation = new File(baseFile, "android");
                        //noinspection ResultOfMethodCallIgnored
                        appLocation.mkdirs();
                        AndroidFacet appFacet = facetType.createFacet(module, AndroidFacet.NAME,
                                facetType.createDefaultConfiguration(), null);
                        model.addFacet(appFacet);
                        configureFacet(appFacet, appLocation, "app");
                    }

                    FlutterSmallIDEProjectGenerator.generateProject(project, baseDir,
                            myModel.flutterSdk().get(), module, makeAdditionalSettings());

                    // Reload the project to use the configuration written by Flutter.
                    VfsUtil.markDirtyAndRefresh(false, true, true, baseDir);
                    ConversionService.getInstance().convertSilently(baseDir.getPath(),
                            new MyConversionListener());
                    VfsUtil.markDirtyAndRefresh(false, true, true, baseDir);
                    reloadProjectNow(project);
                }
            });

    EnumSet<PlatformProjectOpenProcessor.Option> options = EnumSet
            .noneOf(PlatformProjectOpenProcessor.Option.class);
    PlatformProjectOpenProcessor.doOpenProject(baseDir, projectToClose, -1, callback, options);
    // The project was reloaded by the callback. Find the new Project object.
    Project newProject = FlutterUtils.findProject(baseDir.getPath());
    if (newProject != null) {
        StartupManager.getInstance(newProject)
                .registerPostStartupActivity(() -> ApplicationManager.getApplication().invokeLater(() -> {
                    disableUserConfig(newProject);
                    // We want to show the Project view, not the Android view since it doesn't make the Dart code visible.
                    ProjectView.getInstance(newProject).changeView(ProjectViewPane.ID);
                    //ProjectManager.getInstance().reloadProject(newProject);
                }, ModalityState.NON_MODAL));
    }
}

From source file:jetbrains.communicator.util.MultipleSelectionListUI.java

License:Apache License

protected MouseInputListener createMouseInputListener() {
    return new MouseInputListener() {
        public void mouseClicked(MouseEvent e) {
        }//from w  w  w.  j av a 2s .  c o  m

        public void mouseEntered(MouseEvent e) {
        }

        public void mouseExited(MouseEvent e) {
        }

        public void mousePressed(MouseEvent e) {
            if (e.isConsumed()) {
                selectedOnPress = false;
                return;
            }
            selectedOnPress = true;
            adjustFocusAndSelection(e);
        }

        void adjustFocusAndSelection(MouseEvent e) {
            if (!SwingUtilities.isLeftMouseButton(e)) {
                return;
            }

            if (!list.isEnabled()) {
                return;
            }

            /* Request focus before updating the list selection.  This implies
             * that the current focus owner will see a focusLost() event
             * before the lists selection is updated IF requestFocus() is
             * synchronous (it is on Windows).  See bug 4122345
             */
            if (!list.hasFocus() && list.isRequestFocusEnabled()) {
                IdeFocusManager.getGlobalInstance().doWhenFocusSettlesDown(() -> {
                    IdeFocusManager.getGlobalInstance().requestFocus(list, true);
                });
            }

            int row = locationToIndex(list, e.getPoint());
            if (row != -1) {
                myLastPressedRow = row;
                boolean adjusting = (e.getID() == MouseEvent.MOUSE_PRESSED) ? true : false;
                list.setValueIsAdjusting(adjusting);
                int anchorIndex = list.getAnchorSelectionIndex();
                if (e.isShiftDown() && (anchorIndex != -1)) {
                    list.setSelectionInterval(anchorIndex, row);
                } else {
                    toggleSelection(row);
                }
            }
        }

        public void mouseDragged(MouseEvent e) {
            if (e.isConsumed()) {
                return;
            }
            if (!SwingUtilities.isLeftMouseButton(e)) {
                return;
            }
            if (!list.isEnabled()) {
                return;
            }
            if (e.isShiftDown() || e.isControlDown()) {
                return;
            }

            int row = locationToIndex(list, e.getPoint());
            if (row != -1 && row != myLastDraggedRow && row != myLastPressedRow) {
                myLastDraggedRow = row;
                Rectangle cellBounds = getCellBounds(list, row, row);
                if (cellBounds != null) {
                    list.scrollRectToVisible(cellBounds);
                    toggleSelection(row);
                    //list.setSelectionInterval(row, row);
                }
            }
            if (row == -1) {
                list.clearSelection();
            }
        }

        public void mouseMoved(MouseEvent e) {
        }

        public void mouseReleased(MouseEvent e) {
            if (selectedOnPress) {
                if (!SwingUtilities.isLeftMouseButton(e)) {
                    return;
                }

                list.setValueIsAdjusting(false);
            } else {
                adjustFocusAndSelection(e);
            }
        }

        private boolean selectedOnPress;

    };
}

From source file:org.intellij.lang.regexp.intention.CheckRegExpForm.java

License:Apache License

private void createUIComponents() {
    PsiFile file = myParams.first;/* w  w w . j  a v a2s. c o  m*/
    myProject = file.getProject();
    myRef = myParams.second;
    Document document = PsiDocumentManager.getInstance(myProject).getDocument(file);

    myRegExp = new EditorTextField(document, myProject, RegExpLanguage.INSTANCE.getAssociatedFileType());
    final String sampleText = PropertiesComponent.getInstance(myProject).getValue(LAST_EDITED_REGEXP,
            "Sample Text");
    mySampleText = new EditorTextField(sampleText, myProject, PlainTextFileType.INSTANCE);
    myRootPanel = new JPanel(new BorderLayout()) {
        @Override
        public void addNotify() {
            super.addNotify();
            IdeFocusManager.getGlobalInstance().requestFocus(mySampleText, true);

            final KeyAdapter escaper = new KeyAdapter() {
                @Override
                public void keyPressed(KeyEvent e) {
                    if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
                        if (!myRef.get().isDisposed()) {
                            myRef.get().hide();
                        }
                    }
                }
            };

            final Editor fieldEditor = myRegExp.getEditor();
            final Editor textEditor = mySampleText.getEditor();

            assert fieldEditor != null && textEditor != null;

            fieldEditor.getContentComponent().addKeyListener(escaper);
            textEditor.getContentComponent().addKeyListener(escaper);

            myRef.get().addListener(new JBPopupAdapter() {
                @Override
                public void onClosed(LightweightWindowEvent event) {
                    PropertiesComponent.getInstance(myProject).setValue(LAST_EDITED_REGEXP,
                            mySampleText.getText());
                }
            });

            final Alarm updater = new Alarm(Alarm.ThreadToUse.SWING_THREAD, myRef.get());
            final DocumentAdapter documentListener = new DocumentAdapter() {
                @Override
                public void documentChanged(DocumentEvent e) {
                    updater.cancelAllRequests();
                    if (!updater.isDisposed()) {
                        updater.addRequest(new Runnable() {
                            @Override
                            public void run() {
                                updateBalloon();
                            }
                        }, 200);
                    }
                }
            };
            myRegExp.addDocumentListener(documentListener);
            mySampleText.addDocumentListener(documentListener);

            updateBalloon();
            mySampleText.selectAll();
        }
    };
}