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;
  }
 public boolean isFocused() {
   if (myComponent != null
       && isFocused(new Component[] {SwingUtilities.getWindowAncestor(myComponent)})) {
     return true;
   }
   return isFocused(myFocusOwners);
 }
    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 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());
  }
 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;
 }
示例#7
0
 private void startEditingAtSelection() {
   myTable.editCellAt(myTable.getSelectedRow(), 2);
   SwingUtilities.invokeLater(
       new Runnable() {
         public void run() {
           if (myTable.isEditing()) {
             myTable.getEditorComponent().requestFocus();
           }
         }
       });
 }
  @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);
  }
  private void keepSelectionState() {
    final Object[] selectedItems = getSelectedRoots();

    SwingUtilities.invokeLater(
        new Runnable() {
          public void run() {
            if (selectedItems != null) {
              setSelectedRoots(selectedItems);
            }
          }
        });
  }
  private void setSizeAndDimensions(
      @NotNull JTable table,
      @NotNull JBPopup popup,
      @NotNull RelativePoint popupPosition,
      @NotNull List<UsageNode> data) {
    JComponent content = popup.getContent();
    Window window = SwingUtilities.windowForComponent(content);
    Dimension d = window.getSize();

    int width = calcMaxWidth(table);
    width = (int) Math.max(d.getWidth(), width);
    Dimension headerSize = ((AbstractPopup) popup).getHeaderPreferredSize();
    width = Math.max((int) headerSize.getWidth(), width);
    width = Math.max(myWidth, width);

    if (myWidth == -1) myWidth = width;
    int newWidth = Math.max(width, d.width + width - myWidth);

    myWidth = newWidth;

    int rowsToShow = Math.min(30, data.size());
    Dimension dimension = new Dimension(newWidth, table.getRowHeight() * rowsToShow);
    Rectangle rectangle = fitToScreen(dimension, popupPosition, table);
    dimension = rectangle.getSize();
    Point location = window.getLocation();
    if (!location.equals(rectangle.getLocation())) {
      window.setLocation(rectangle.getLocation());
    }

    if (!data.isEmpty()) {
      TableScrollingUtil.ensureSelectionExists(table);
    }
    table.setSize(dimension);
    // table.setPreferredSize(dimension);
    // table.setMaximumSize(dimension);
    // table.setPreferredScrollableViewportSize(dimension);

    Dimension footerSize = ((AbstractPopup) popup).getFooterPreferredSize();

    int newHeight =
        (int) (dimension.height + headerSize.getHeight() + footerSize.getHeight())
            + 4 /* invisible borders, margins etc*/;
    Dimension newDim = new Dimension(dimension.width, newHeight);
    window.setSize(newDim);
    window.setMinimumSize(newDim);
    window.setMaximumSize(newDim);

    window.validate();
    window.repaint();
    table.revalidate();
    table.repaint();
  }
 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 void treeSelectionChanged() {
   SwingUtilities.invokeLater(
       new Runnable() {
         @Override
         public void run() {
           if (isDisposed) return;
           List<UsageInfo> infos = getSelectedUsageInfos();
           if (infos != null && myUsagePreviewPanel != null) {
             myUsagePreviewPanel.updateLayout(infos);
           }
         }
       });
 }
 private void setToComponent(final JComponent cmp, final boolean requestFocus) {
   myMatchingCountPanel.removeAll();
   myMatchingCountPanel.add(cmp, BorderLayout.CENTER);
   myMatchingCountPanel.revalidate();
   myMatchingCountPanel.repaint();
   if (requestFocus) {
     SwingUtilities.invokeLater(
         new Runnable() {
           public void run() {
             myPatternField.getTextField().requestFocusInWindow();
           }
         });
   }
 }
示例#14
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();
                }
              }
            });
      }
示例#15
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();
           }
         }
       });
 }
示例#16
0
 @Override
 public Rectangle getCurrentItemBounds() {
   int index = myList.getSelectedIndex();
   if (index < 0) {
     LOG.error("No selected element, size=" + getListModel().getSize() + "; items" + getItems());
   }
   Rectangle itmBounds = myList.getCellBounds(index, index);
   if (itmBounds == null) {
     LOG.error("No bounds for " + index + "; size=" + getListModel().getSize());
     return null;
   }
   Point layeredPanePoint =
       SwingUtilities.convertPoint(myList, itmBounds.x, itmBounds.y, getComponent());
   itmBounds.x = layeredPanePoint.x;
   itmBounds.y = layeredPanePoint.y;
   return itmBounds;
 }
  private void reset() {
    ApplicationManager.getApplication().assertIsDispatchThread();

    myUsageNodes.clear();
    myIsFirstVisibleUsageFound = false;

    myModel.reset();
    if (!myPresentation.isDetachedMode()) {
      SwingUtilities.invokeLater(
          new Runnable() {
            @Override
            public void run() {
              if (isDisposed) return;
              TreeUtil.expand(myTree, 2);
            }
          });
    }
  }
 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 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);
  }
示例#20
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);
  }
  private void selectInTree(VirtualFile[] array, boolean requestFocus, boolean updatePathNeeded) {
    myTreeIsUpdating = true;
    final List<VirtualFile> fileList = Arrays.asList(array);
    if (!Arrays.asList(myFileSystemTree.getSelectedFiles()).containsAll(fileList)) {
      myFileSystemTree.select(
          array,
          () -> {
            if (!myFileSystemTree.areHiddensShown()
                && !Arrays.asList(myFileSystemTree.getSelectedFiles()).containsAll(fileList)) {
              // try to select files in hidden folders
              myFileSystemTree.showHiddens(true);
              selectInTree(array, requestFocus, updatePathNeeded);
              return;
            }
            if (array.length == 1
                && !Arrays.asList(myFileSystemTree.getSelectedFiles()).containsAll(fileList)) {
              // try to select a parent of a missed file
              VirtualFile parent = array[0].getParent();
              if (parent != null && parent.isValid()) {
                selectInTree(new VirtualFile[] {parent}, requestFocus, updatePathNeeded);
                return;
              }
            }

            reportFileNotFound();
            if (updatePathNeeded) {
              updatePathFromTree(fileList, true);
            }
            if (requestFocus) {
              //noinspection SSBasedInspection
              SwingUtilities.invokeLater(() -> myFileSystemTree.getTree().requestFocus());
            }
          });
    } else {
      reportFileNotFound();
      if (updatePathNeeded) {
        updatePathFromTree(fileList, true);
      }
    }
  }
 private void rulesChanged() {
   ApplicationManager.getApplication().assertIsDispatchThread();
   final ArrayList<UsageState> states = new ArrayList<UsageState>();
   captureUsagesExpandState(new TreePath(myTree.getModel().getRoot()), states);
   final List<Usage> allUsages = new ArrayList<Usage>(myUsageNodes.keySet());
   Collections.sort(allUsages, USAGE_COMPARATOR);
   final Set<Usage> excludedUsages = getExcludedUsages();
   reset();
   myBuilder.setGroupingRules(getActiveGroupingRules(myProject));
   myBuilder.setFilteringRules(getActiveFilteringRules(myProject));
   ApplicationManager.getApplication()
       .runReadAction(
           new Runnable() {
             @Override
             public void run() {
               for (Usage usage : allUsages) {
                 if (!usage.isValid()) {
                   continue;
                 }
                 if (usage instanceof MergeableUsage) {
                   ((MergeableUsage) usage).reset();
                 }
                 appendUsage(usage);
               }
             }
           });
   excludeUsages(excludedUsages.toArray(new Usage[excludedUsages.size()]));
   if (myCentralPanel != null) {
     setupCentralPanel();
   }
   SwingUtilities.invokeLater(
       new Runnable() {
         @Override
         public void run() {
           if (isDisposed) return;
           restoreUsageExpandState(states);
           updateImmediately();
         }
       });
 }
 public void actionPerformed(AnActionEvent e) {
   DependenciesToolWindow.getInstance(myProject).closeContent(myContent);
   mySettings.copyToApplicationDependencySettings();
   SwingUtilities.invokeLater(
       new Runnable() {
         public void run() {
           final List<AnalysisScope> scopes = new ArrayList<AnalysisScope>();
           for (DependenciesBuilder builder : myBuilders) {
             final AnalysisScope scope = builder.getScope();
             scope.invalidate();
             scopes.add(scope);
           }
           if (!myForward) {
             new BackwardDependenciesHandler(myProject, scopes, myScopeOfInterest, myExcluded)
                 .analyze();
           } else {
             new AnalyzeDependenciesHandler(myProject, scopes, myTransitiveBorder, myExcluded)
                 .analyze();
           }
         }
       });
 }
示例#24
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);
  }
示例#26
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);
    }
  }
 public static void setDefaultCursor(JComponent content) {
   final Window wnd = SwingUtilities.getWindowAncestor(content);
   if (wnd != null) {
     wnd.setCursor(Cursor.getDefaultCursor());
   }
 }
  public void pack() {
    final Window window = SwingUtilities.getWindowAncestor(myContent);

    window.pack();
  }
  public void show(Component owner, int aScreenX, int aScreenY, final boolean considerForcedXY) {
    if (ApplicationManagerEx.getApplicationEx() != null
        && ApplicationManager.getApplication().isHeadlessEnvironment()) return;
    if (isDisposed()) {
      throw new IllegalStateException(
          "Popup was already disposed. Recreate a new instance to show again");
    }

    assert ApplicationManager.getApplication().isDispatchThread();

    addActivity();

    final boolean shouldShow = beforeShow();
    if (!shouldShow) {
      removeActivity();
      return;
    }

    prepareToShow();

    if (myInStack) {
      myFocusTrackback = new FocusTrackback(this, owner, true);
      myFocusTrackback.setMustBeShown(true);
    }

    Dimension sizeToSet = null;

    if (myDimensionServiceKey != null) {
      sizeToSet = DimensionService.getInstance().getSize(myDimensionServiceKey, myProject);
    }

    if (myForcedSize != null) {
      sizeToSet = myForcedSize;
    }

    if (myMinSize == null) {
      myMinSize = myContent.getMinimumSize();
    }

    if (sizeToSet == null) {
      sizeToSet = myContent.getPreferredSize();
    }

    if (sizeToSet != null) {
      sizeToSet.width = Math.max(sizeToSet.width, myMinSize.width);
      sizeToSet.height = Math.max(sizeToSet.height, myMinSize.height);

      myContent.setSize(sizeToSet);
      myContent.setPreferredSize(sizeToSet);
    }

    Point xy = new Point(aScreenX, aScreenY);
    boolean adjustXY = true;
    if (myDimensionServiceKey != null) {
      final Point storedLocation =
          DimensionService.getInstance().getLocation(myDimensionServiceKey, myProject);
      if (storedLocation != null) {
        xy = storedLocation;
        adjustXY = false;
      }
    }

    if (adjustXY) {
      final Insets insets = myContent.getInsets();
      if (insets != null) {
        xy.x -= insets.left;
        xy.y -= insets.top;
      }
    }

    if (considerForcedXY && myForcedLocation != null) {
      xy = myForcedLocation;
    }

    if (myLocateByContent) {
      final Dimension captionSize = myHeaderPanel.getPreferredSize();
      xy.y -= captionSize.height;
    }

    Rectangle targetBounds = new Rectangle(xy, myContent.getPreferredSize());
    Insets insets = myPopupBorder.getBorderInsets(myContent);
    if (insets != null) {
      targetBounds.x += insets.left;
      targetBounds.y += insets.top;
    }

    Rectangle original = new Rectangle(targetBounds);
    if (myLocateWithinScreen) {
      ScreenUtil.moveRectangleToFitTheScreen(targetBounds);
    }

    if (myMouseOutCanceller != null) {
      myMouseOutCanceller.myEverEntered = targetBounds.equals(original);
    }

    myOwner = IdeFrameImpl.findNearestModalComponent(owner);
    if (myOwner == null) {
      myOwner = owner;
    }

    myRequestorComponent = owner;

    boolean forcedDialog = (SystemInfo.isMac && !(myOwner instanceof IdeFrame)) || myMayBeParent;

    PopupComponent.Factory factory = getFactory(myForcedHeavyweight || myResizable, forcedDialog);
    myNativePopup = factory.isNativePopup();
    myPopup = factory.getPopup(myOwner, myContent, targetBounds.x, targetBounds.y);

    if (myResizable) {
      final JRootPane root = myContent.getRootPane();
      final IdeGlassPaneImpl glass = new IdeGlassPaneImpl(root);
      root.setGlassPane(glass);

      final ResizeComponentListener resizeListener = new ResizeComponentListener(this, glass);
      glass.addMousePreprocessor(resizeListener, this);
      glass.addMouseMotionPreprocessor(resizeListener, this);
    }

    if (myCaption != null && myMovable) {
      final MoveComponentListener moveListener =
          new MoveComponentListener(myCaption) {
            public void mousePressed(final MouseEvent e) {
              super.mousePressed(e);
              if (e.isConsumed()) return;

              if (UIUtil.isCloseClick(e)) {
                if (myCaption.isWithinPanel(e)) {
                  cancel();
                }
              }
            }
          };
      ListenerUtil.addMouseListener(myCaption, moveListener);
      ListenerUtil.addMouseMotionListener(myCaption, moveListener);
      final MyContentPanel saved = myContent;
      Disposer.register(
          this,
          new Disposable() {
            public void dispose() {
              ListenerUtil.removeMouseListener(saved, moveListener);
              ListenerUtil.removeMouseMotionListener(saved, moveListener);
            }
          });
    }

    for (JBPopupListener listener : myListeners) {
      listener.beforeShown(new LightweightWindowEvent(this));
    }

    myPopup.setRequestFocus(myRequestFocus);
    myPopup.show();

    final Window window = SwingUtilities.getWindowAncestor(myContent);

    myWindowListener = new MyWindowListener();
    window.addWindowListener(myWindowListener);

    if (myFocusable) {
      window.setFocusableWindowState(true);
      window.setFocusable(true);
    }

    myWindow = updateMaskAndAlpha(window);

    if (myWindow instanceof JWindow) {
      ((JWindow) myWindow).getRootPane().putClientProperty(KEY, this);
    }

    if (myWindow != null) {
      // dialogwrapper-based popups do this internally through peer,
      // for other popups like jdialog-based we should exclude them manually, but
      // we still have to be able to use IdeFrame as parent
      if (!myMayBeParent && !(myWindow instanceof Frame)) {
        WindowManager.getInstance().doNotSuggestAsParent(myWindow);
      }
    }

    final Runnable afterShow =
        new Runnable() {
          public void run() {
            if (myPreferredFocusedComponent != null && myInStack && myFocusable) {
              myFocusTrackback.registerFocusComponent(myPreferredFocusedComponent);
            }

            removeActivity();

            afterShow();
          }
        };

    if (myRequestFocus) {
      getFocusManager()
          .requestFocus(
              new FocusCommand() {
                @Override
                public ActionCallback run() {
                  if (isDisposed()) {
                    removeActivity();
                    return new ActionCallback.Done();
                  }

                  _requestFocus();

                  final ActionCallback result = new ActionCallback();

                  final Runnable afterShowRunnable =
                      new Runnable() {
                        @Override
                        public void run() {
                          afterShow.run();
                          result.setDone();
                        }
                      };
                  if (myNativePopup) {
                    final FocusRequestor furtherRequestor = getFocusManager().getFurtherRequestor();
                    SwingUtilities.invokeLater(
                        new Runnable() {
                          @Override
                          public void run() {
                            if (isDisposed()) {
                              result.setRejected();
                              return;
                            }

                            furtherRequestor
                                .requestFocus(
                                    new FocusCommand() {
                                      @Override
                                      public ActionCallback run() {
                                        if (isDisposed()) {
                                          return new ActionCallback.Rejected();
                                        }

                                        _requestFocus();

                                        afterShowRunnable.run();

                                        return new ActionCallback.Done();
                                      }
                                    },
                                    true)
                                .notify(result)
                                .doWhenProcessed(
                                    new Runnable() {
                                      @Override
                                      public void run() {
                                        removeActivity();
                                      }
                                    });
                          }
                        });
                  } else {
                    afterShowRunnable.run();
                  }

                  return result;
                }
              },
              true)
          .doWhenRejected(
              new Runnable() {
                @Override
                public void run() {
                  afterShow.run();
                }
              });
    } else {
      SwingUtilities.invokeLater(
          new Runnable() {
            @Override
            public void run() {
              if (isDisposed()) {
                removeActivity();
                return;
              }

              afterShow.run();
            }
          });
    }
  }