public static boolean isFocused(@Nullable Component[] components) {
    if (components == null) return false;

    Component owner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();

    if (owner == null) return false;

    Window wnd;
    if (owner instanceof Window) {
      wnd = (Window) owner;
    } else {
      wnd = SwingUtilities.getWindowAncestor(owner);
    }

    for (Component each : components) {
      if (each != null && SwingUtilities.isDescendingFrom(owner, each)) {
        Window eachWindow =
            each instanceof Window ? (Window) each : SwingUtilities.getWindowAncestor(each);
        if (eachWindow == wnd) {
          return true;
        }
      }
    }

    return false;
  }
示例#2
0
  public final void runBare() throws Throwable {
    final Throwable[] throwables = new Throwable[1];

    SwingUtilities.invokeAndWait(
        new Runnable() {
          public void run() {
            try {
              ourTestThread = Thread.currentThread();
              startRunAndTear();
            } catch (Throwable throwable) {
              throwables[0] = throwable;
            } finally {
              ourTestThread = null;
              try {
                cleanupApplicationCaches();
              } catch (Throwable e) {
                e.printStackTrace();
              }
            }
          }
        });

    if (throwables[0] != null) {
      throw throwables[0];
    }

    // just to make sure all deffered Runnable's to finish
    SwingUtilities.invokeAndWait(EmptyRunnable.getInstance());

    if (IdeaLogger.ourErrorsOccurred != null) {
      throw IdeaLogger.ourErrorsOccurred;
    }
  }
 @Override
 public void documentChanged(DocumentEvent e) {
   UndoManager undoManager = UndoManager.getInstance(myProject);
   boolean undoOrRedo = undoManager.isUndoInProgress() || undoManager.isRedoInProgress();
   if (undoOrRedo) {
     // allow undo/redo up until 'creation stamp' back in time
     // and check it after action is completed
     if (e.getDocument() == myOrigDocument) {
       //noinspection SSBasedInspection
       SwingUtilities.invokeLater(
           () -> {
             if (myOrigCreationStamp > myOrigDocument.getModificationStamp()) {
               closeEditor();
             }
           });
     }
   } else if (e.getDocument() == myNewDocument) {
     commitToOriginal(e);
     if (!isValid()) {
       ApplicationManager.getApplication()
           .invokeLater(() -> closeEditor(), myProject.getDisposed());
     }
   } else if (e.getDocument() == myOrigDocument) {
     if (myCommittingToOriginal || myAltFullRange != null && myAltFullRange.isValid()) return;
     ApplicationManager.getApplication().invokeLater(() -> closeEditor(), myProject.getDisposed());
   }
 }
 public void fireBreakpointChanged(Breakpoint breakpoint) {
   breakpoint.reload();
   breakpoint.updateUI();
   RequestManagerImpl.updateRequests(breakpoint);
   if (myAllowMulticasting) {
     // can be invoked from non-AWT thread
     myAlarm.cancelAllRequests();
     final Runnable runnable =
         new Runnable() {
           @Override
           public void run() {
             myAlarm.addRequest(
                 new Runnable() {
                   @Override
                   public void run() {
                     myDispatcher.getMulticaster().breakpointsChanged();
                   }
                 },
                 100);
           }
         };
     if (ApplicationManager.getApplication().isDispatchThread()) {
       runnable.run();
     } else {
       SwingUtilities.invokeLater(runnable);
     }
   }
 }
 public boolean isFocused() {
   if (myComponent != null
       && isFocused(new Component[] {SwingUtilities.getWindowAncestor(myComponent)})) {
     return true;
   }
   return isFocused(myFocusOwners);
 }
 /**
  * @param component component
  * @return whether the component in Swing tree or not. This method is more weak then {@link
  *     Component#isShowing() }
  */
 private boolean isInTree(final Component component) {
   if (component instanceof Window) {
     return component.isShowing();
   } else {
     Window windowAncestor = SwingUtilities.getWindowAncestor(component);
     return windowAncestor != null && windowAncestor.isShowing();
   }
 }
    private boolean withinPopup(final AWTEvent event) {
      if (!myContent.isShowing()) return false;

      final MouseEvent mouse = (MouseEvent) event;
      final Point point = mouse.getPoint();
      SwingUtilities.convertPointToScreen(point, mouse.getComponent());
      return new Rectangle(myContent.getLocationOnScreen(), myContent.getSize()).contains(point);
    }
 @Override
 public Dimension getSize() {
   if (myPopup != null) {
     final Window popupWindow = SwingUtilities.windowForComponent(myContent);
     return popupWindow.getSize();
   } else {
     return myForcedSize;
   }
 }
 public static Window moveTo(
     JComponent content, Point screenPoint, final Dimension headerCorrectionSize) {
   setDefaultCursor(content);
   final Window wnd = SwingUtilities.getWindowAncestor(content);
   if (headerCorrectionSize != null) {
     screenPoint.y -= headerCorrectionSize.height;
   }
   wnd.setLocation(screenPoint);
   return wnd;
 }
  public static Point getCenterOf(final Component aContainer, final JComponent content) {
    final JComponent component = getTargetComponent(aContainer);

    Point containerScreenPoint = component.getVisibleRect().getLocation();
    SwingUtilities.convertPointToScreen(containerScreenPoint, aContainer);

    return UIUtil.getCenterPoint(
        new Rectangle(containerScreenPoint, component.getVisibleRect().getSize()),
        content.getPreferredSize());
  }
 @Nullable
 private EditorWindow findWindowWith(final Component component) {
   if (component != null) {
     for (final EditorWindow window : myWindows) {
       if (SwingUtilities.isDescendingFrom(component, window.myPanel)) {
         return window;
       }
     }
   }
   return null;
 }
  @Override
  public void moveToFitScreen() {
    if (myPopup == null) return;

    final Window popupWindow = SwingUtilities.windowForComponent(myContent);
    Rectangle bounds = popupWindow.getBounds();

    ScreenUtil.moveRectangleToFitTheScreen(bounds);
    setLocation(bounds.getLocation());
    setSize(bounds.getSize(), false);
  }
  @Nullable
  JBTabs getTabsAt(RelativePoint point) {
    Point thisPoint = point.getPoint(this);
    Component c = SwingUtilities.getDeepestComponentAt(this, thisPoint.x, thisPoint.y);
    while (c != null) {
      if (c instanceof JBTabs) {
        return (JBTabs) c;
      }
      c = c.getParent();
    }

    return null;
  }
 public static Window setSize(JComponent content, final Dimension size) {
   final Window popupWindow = SwingUtilities.windowForComponent(content);
   final Point location = popupWindow.getLocation();
   popupWindow.setLocation(location.x, location.y);
   Insets insets = content.getInsets();
   if (insets != null) {
     size.width += insets.left + insets.right;
     size.height += insets.top + insets.bottom;
   }
   content.setPreferredSize(size);
   popupWindow.pack();
   return popupWindow;
 }
  private boolean isProjectViewVisible() {
    final Window frame = SwingUtilities.getWindowAncestor(this);
    if (frame instanceof IdeFrameImpl) {
      final Project project = ((IdeFrameImpl) frame).getProject();
      if (project != null) {
        if (!project.isInitialized()) return true;
        ToolWindow toolWindow =
            ToolWindowManager.getInstance(project).getToolWindow(ToolWindowId.PROJECT_VIEW);
        return toolWindow != null && toolWindow.isVisible();
      }
    }

    return false;
  }
示例#16
0
      @Override
      public void windowActivated(final WindowEvent e) {
        SwingUtilities.invokeLater(
            new Runnable() {
              @Override
              public void run() {
                final DialogWrapper wrapper = getActiveWrapper();
                if (wrapper == null && !myFocusedCallback.isProcessed()) {
                  myFocusedCallback.setRejected();
                  myTypeAheadDone.setRejected();
                  return;
                }

                if (myActivated) {
                  return;
                }
                myActivated = true;
                JComponent toFocus =
                    wrapper == null ? null : wrapper.getPreferredFocusedComponent();
                if (toFocus == null) {
                  toFocus = getRootPane().getDefaultButton();
                }

                moveMousePointerOnButton(getRootPane().getDefaultButton());
                setupSelectionOnPreferredComponent(toFocus);

                if (toFocus != null) {
                  final JComponent toRequest = toFocus;
                  SwingUtilities.invokeLater(
                      new Runnable() {
                        @Override
                        public void run() {
                          if (isShowing() && isActive()) {
                            getFocusManager().requestFocus(toRequest, true);
                            notifyFocused(wrapper);
                          }
                        }
                      });
                } else {
                  if (isShowing()) {
                    notifyFocused(wrapper);
                  }
                }
                if (myTypeAheadCallback != null) {
                  myTypeAheadCallback.setDone();
                }
              }
            });
      }
示例#17
0
  public BalloonHandler notifyByBalloon(
      MessageType type,
      String htmlBody,
      @Nullable Icon icon,
      @Nullable HyperlinkListener listener) {
    final Balloon balloon =
        JBPopupFactory.getInstance()
            .createHtmlTextBalloonBuilder(
                htmlBody.replace("\n", "<br>"),
                icon != null ? icon : type.getDefaultIcon(),
                type.getPopupBackground(),
                listener)
            .createBalloon();

    SwingUtilities.invokeLater(
        new Runnable() {
          @Override
          public void run() {
            Component comp = InfoAndProgressPanel.this;
            if (comp.isShowing()) {
              int offset = comp.getHeight() / 2;
              Point point = new Point(comp.getWidth() - offset, comp.getHeight() - offset);
              balloon.show(new RelativePoint(comp, point), Balloon.Position.above);
            } else {
              final JRootPane rootPane = SwingUtilities.getRootPane(comp);
              if (rootPane != null && rootPane.isShowing()) {
                final Container contentPane = rootPane.getContentPane();
                final Rectangle bounds = contentPane.getBounds();
                final Point target = UIUtil.getCenterPoint(bounds, new Dimension(1, 1));
                target.y = bounds.height - 3;
                balloon.show(new RelativePoint(contentPane, target), Balloon.Position.above);
              }
            }
          }
        });

    return new BalloonHandler() {
      @Override
      public void hide() {
        SwingUtilities.invokeLater(
            new Runnable() {
              @Override
              public void run() {
                balloon.hide();
              }
            });
      }
    };
  }
示例#18
0
 @Override
 public void windowOpened(WindowEvent e) {
   SwingUtilities.invokeLater(
       new Runnable() {
         @Override
         public void run() {
           myOpened = true;
           final DialogWrapper activeWrapper = getActiveWrapper();
           if (activeWrapper == null) {
             myFocusedCallback.setRejected();
             myTypeAheadDone.setRejected();
           }
         }
       });
 }
    @Override
    public void propertyChange(PropertyChangeEvent e) {
      boolean queueForDispose = getParent() == null;

      String name = e.getPropertyName();
      if (mySynchronized.contains(name)) return;

      mySynchronized.add(name);

      try {
        if (Presentation.PROP_VISIBLE.equals(name)) {
          final boolean visible = myPresentation.isVisible();
          if (!visible && SystemInfo.isMacSystemMenu && myPlace.equals(ActionPlaces.MAIN_MENU)) {
            setEnabled(false);
          } else {
            setVisible(visible);
          }
        } else if (Presentation.PROP_ENABLED.equals(name)) {
          setEnabled(myPresentation.isEnabled());
          updateIcon(myAction.getAction());
        } else if (Presentation.PROP_MNEMONIC_KEY.equals(name)) {
          setMnemonic(myPresentation.getMnemonic());
        } else if (Presentation.PROP_MNEMONIC_INDEX.equals(name)) {
          setDisplayedMnemonicIndex(myPresentation.getDisplayedMnemonicIndex());
        } else if (Presentation.PROP_TEXT.equals(name)) {
          setText(myPresentation.getText());
        } else if (Presentation.PROP_ICON.equals(name)
            || Presentation.PROP_DISABLED_ICON.equals(name)
            || SELECTED.equals(name)) {
          updateIcon(myAction.getAction());
        }
      } finally {
        mySynchronized.remove(name);
        if (queueForDispose) {
          // later since we cannot remove property listeners inside event processing
          //noinspection SSBasedInspection
          SwingUtilities.invokeLater(
              new Runnable() {
                @Override
                public void run() {
                  if (getParent() == null) {
                    uninstallSynchronizer();
                  }
                }
              });
        }
      }
    }
 public void enableBreakpoints(final DebugProcessImpl debugProcess) {
   final List<Breakpoint> breakpoints = getBreakpoints();
   if (!breakpoints.isEmpty()) {
     for (Breakpoint breakpoint : breakpoints) {
       breakpoint.markVerified(false); // clean cached state
       breakpoint.createRequest(debugProcess);
     }
     SwingUtilities.invokeLater(
         new Runnable() {
           @Override
           public void run() {
             updateBreakpointsUI();
           }
         });
   }
 }
 // interaction with RequestManagerImpl
 public void disableBreakpoints(@NotNull final DebugProcessImpl debugProcess) {
   final List<Breakpoint> breakpoints = getBreakpoints();
   if (!breakpoints.isEmpty()) {
     final RequestManagerImpl requestManager = debugProcess.getRequestsManager();
     for (Breakpoint breakpoint : breakpoints) {
       breakpoint.markVerified(requestManager.isVerified(breakpoint));
       requestManager.deleteRequest(breakpoint);
     }
     SwingUtilities.invokeLater(
         new Runnable() {
           @Override
           public void run() {
             updateBreakpointsUI();
           }
         });
   }
 }
 private RelativePoint relativePointWithDominantRectangle(
     final JLayeredPane layeredPane, final Rectangle bounds) {
   Dimension preferredSize = getComponent().getPreferredSize();
   if (myDimensionServiceKey != null) {
     final Dimension dimension =
         DimensionService.getInstance().getSize(myDimensionServiceKey, myProject);
     if (dimension != null) {
       preferredSize = dimension;
     }
   }
   final Point leftTopCorner = new Point(bounds.x + bounds.width, bounds.y);
   final Point leftTopCornerScreen = (Point) leftTopCorner.clone();
   SwingUtilities.convertPointToScreen(leftTopCornerScreen, layeredPane);
   final RelativePoint relativePoint;
   if (!ScreenUtil.isOutsideOnTheRightOFScreen(
       new Rectangle(
           leftTopCornerScreen.x,
           leftTopCornerScreen.y,
           preferredSize.width,
           preferredSize.height))) {
     relativePoint = new RelativePoint(layeredPane, leftTopCorner);
   } else {
     if (bounds.x > preferredSize.width) {
       relativePoint =
           new RelativePoint(layeredPane, new Point(bounds.x - preferredSize.width, bounds.y));
     } else {
       setDimensionServiceKey(null); // going to cut width
       Rectangle screen =
           ScreenUtil.getScreenRectangle(leftTopCornerScreen.x, leftTopCornerScreen.y);
       final int spaceOnTheLeft = bounds.x;
       final int spaceOnTheRight = (screen.x + screen.width) - leftTopCornerScreen.x;
       if (spaceOnTheLeft > spaceOnTheRight) {
         relativePoint = new RelativePoint(layeredPane, new Point(0, bounds.y));
         myComponent.setPreferredSize(
             new Dimension(spaceOnTheLeft, Math.max(preferredSize.height, 200)));
       } else {
         relativePoint = new RelativePoint(layeredPane, leftTopCorner);
         myComponent.setPreferredSize(
             new Dimension(spaceOnTheRight, Math.max(preferredSize.height, 200)));
       }
     }
   }
   return relativePoint;
 }
 @Override
 public void mousePressed(final MouseEvent e) {
   if (UIUtil.isActionClick(e)) {
     if (e.getClickCount() == 1) {
       myActionClickCount = 0;
     }
     // clicks on the close window button don't count in determining whether we have a
     // double-click on tab (IDEA-70403)
     final Component deepestComponent =
         SwingUtilities.getDeepestComponentAt(e.getComponent(), e.getX(), e.getY());
     if (!(deepestComponent instanceof InplaceButton)) {
       myActionClickCount++;
     }
     if (myActionClickCount == 2 && !isFloating()) {
       final ActionManager mgr = ActionManager.getInstance();
       mgr.tryToExecute(mgr.getAction("HideAllWindows"), e, null, ActionPlaces.UNKNOWN, true);
     }
   }
 }
  @Override
  public void pack(boolean width, boolean height) {
    if (!isVisible() || (!width && !height)) return;

    Dimension size = getSize();
    Dimension prefSize = myContent.computePreferredSize();

    if (width) {
      size.width = prefSize.width;
    }

    if (height) {
      size.height = prefSize.height;
    }

    size = computeWindowSize(size);

    final Window window = SwingUtilities.getWindowAncestor(myContent);
    window.setSize(size);
  }
示例#25
0
  /**
   * @param parent parent component which is used to calculate heavy weight window ancestor. <code>
   *     parent</code> cannot be <code>null</code> and must be showing.
   */
  protected DialogWrapperPeerImpl(
      @NotNull DialogWrapper wrapper, @NotNull Component parent, boolean canBeParent) {
    myWrapper = wrapper;
    if (!parent.isShowing() && parent != JOptionPane.getRootFrame()) {
      throw new IllegalArgumentException("parent must be showing: " + parent);
    }
    myWindowManager = null;
    Application application = ApplicationManager.getApplication();
    if (application != null && application.hasComponent(WindowManager.class)) {
      myWindowManager = (WindowManagerEx) WindowManager.getInstance();
    }

    Window owner =
        parent instanceof Window
            ? (Window) parent
            : (Window) SwingUtilities.getAncestorOfClass(Window.class, parent);
    if (!(owner instanceof Dialog) && !(owner instanceof Frame)) {
      owner = JOptionPane.getRootFrame();
    }
    createDialog(owner, canBeParent);
  }
示例#26
0
    private void disposeFocusTrackbackIfNoChildWindowFocused(
        @Nullable IdeFocusManager focusManager) {
      if (myFocusTrackback == null) return;

      final DialogWrapper wrapper = myDialogWrapper.get();
      if (wrapper == null || !wrapper.isShowing()) {
        myFocusTrackback.dispose();
        return;
      }

      if (focusManager != null) {
        final Component c = focusManager.getFocusedDescendantFor(wrapper.getContentPane());
        if (c == null) {
          myFocusTrackback.dispose();
        }
      } else {
        final Component owner =
            KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
        if (owner == null || !SwingUtilities.isDescendingFrom(owner, wrapper.getContentPane())) {
          myFocusTrackback.dispose();
        }
      }
    }
  private RelativePoint relativePointByQuickSearch(final DataContext dataContext) {
    Rectangle dominantArea = PlatformDataKeys.DOMINANT_HINT_AREA_RECTANGLE.getData(dataContext);

    if (dominantArea != null) {
      final Component focusedComponent = getWndManager().getFocusedComponent(myProject);
      Window window = SwingUtilities.windowForComponent(focusedComponent);
      JLayeredPane layeredPane;
      if (window instanceof JFrame) {
        layeredPane = ((JFrame) window).getLayeredPane();
      } else if (window instanceof JDialog) {
        layeredPane = ((JDialog) window).getLayeredPane();
      } else if (window instanceof JWindow) {
        layeredPane = ((JWindow) window).getLayeredPane();
      } else {
        throw new IllegalStateException(
            "cannot find parent window: project=" + myProject + "; window=" + window);
      }

      return relativePointWithDominantRectangle(layeredPane, dominantArea);
    }

    return JBPopupFactory.getInstance().guessBestPopupLocation(dataContext);
  }
示例#28
0
  @Override
  @SuppressWarnings("SSBasedInspection")
  protected void dispose() {
    LOG.assertTrue(
        EventQueue.isDispatchThread(), "Access is allowed from event dispatch thread only");
    for (Runnable runnable : myDisposeActions) {
      runnable.run();
    }
    myDisposeActions.clear();
    final JRootPane root = myDialog.getRootPane();

    Runnable disposer =
        new Runnable() {
          @Override
          public void run() {
            myDialog.dispose();
            myProject = null;

            SwingUtilities.invokeLater(
                new Runnable() {
                  @Override
                  public void run() {
                    if (myDialog != null && root != null) {
                      myDialog.remove(root);
                    }
                  }
                });
          }
        };

    if (EventQueue.isDispatchThread()) {
      disposer.run();
    } else {
      SwingUtilities.invokeLater(disposer);
    }
  }
示例#29
0
 @NotNull
 public ModalityState getModalityStateForComponent(@NotNull Component c) {
   Window window = c instanceof Window ? (Window) c : SwingUtilities.windowForComponent(c);
   if (window == null) return getNoneModalityState(); // ?
   return LaterInvocator.modalityStateForWindow(window);
 }
示例#30
0
  public boolean runProcessWithProgressSynchronously(
      @NotNull final Runnable process,
      @NotNull final String progressTitle,
      final boolean canBeCanceled,
      @Nullable final Project project,
      final JComponent parentComponent,
      final String cancelText) {
    assertIsDispatchThread();

    if (myExceptionalThreadWithReadAccessRunnable != null
        || ApplicationManager.getApplication().isUnitTestMode()
        || ApplicationManager.getApplication().isHeadlessEnvironment()) {
      try {
        ProgressManager.getInstance().runProcess(process, new EmptyProgressIndicator());
      } catch (ProcessCanceledException e) {
        // ok to ignore.
        return false;
      }
      return true;
    }

    final ProgressWindow progress =
        new ProgressWindow(canBeCanceled, false, project, parentComponent, cancelText);
    progress.setTitle(progressTitle);

    try {
      myExceptionalThreadWithReadAccessRunnable = process;
      final boolean[] threadStarted = {false};
      SwingUtilities.invokeLater(
          new Runnable() {
            public void run() {
              if (myExceptionalThreadWithReadAccessRunnable != process) {
                LOG.error(
                    "myExceptionalThreadWithReadAccessRunnable != process, process = "
                        + myExceptionalThreadWithReadAccessRunnable);
              }

              executeOnPooledThread(
                  new Runnable() {
                    public void run() {
                      if (myExceptionalThreadWithReadAccessRunnable != process) {
                        LOG.error(
                            "myExceptionalThreadWithReadAccessRunnable != process, process = "
                                + myExceptionalThreadWithReadAccessRunnable);
                      }

                      final boolean old = setExceptionalThreadWithReadAccessFlag(true);
                      LOG.assertTrue(isReadAccessAllowed());
                      try {
                        ProgressManager.getInstance().runProcess(process, progress);
                      } catch (ProcessCanceledException e) {
                        progress.cancel();
                        // ok to ignore.
                      } catch (RuntimeException e) {
                        progress.cancel();
                        throw e;
                      } finally {
                        setExceptionalThreadWithReadAccessFlag(old);
                        makeChangesVisibleToEDT();
                      }
                    }
                  });
              threadStarted[0] = true;
            }
          });

      progress.startBlocking();

      LOG.assertTrue(threadStarted[0]);
      LOG.assertTrue(!progress.isRunning());
    } finally {
      myExceptionalThreadWithReadAccessRunnable = null;
      makeChangesVisibleToEDT();
    }

    return !progress.isCanceled();
  }