private static boolean fitsLayeredPane(
      JLayeredPane pane, JComponent component, RelativePoint desiredLocation, HintHint hintHint) {
    if (hintHint.isAwtTooltip()) {
      Dimension size = component.getPreferredSize();
      Dimension paneSize = pane.getSize();

      Point target = desiredLocation.getPointOn(pane).getPoint();
      Balloon.Position pos = hintHint.getPreferredPosition();
      int pointer = BalloonImpl.getPointerLength(pos, false) + BalloonImpl.getNormalInset();
      if (pos == Balloon.Position.above || pos == Balloon.Position.below) {
        boolean heightFit =
            target.y - size.height - pointer > 0
                || target.y + size.height + pointer < paneSize.height;
        return heightFit && size.width + pointer < paneSize.width;
      } else {
        boolean widthFit =
            target.x - size.width - pointer > 0 || target.x + size.width + pointer < paneSize.width;
        return widthFit && size.height + pointer < paneSize.height;
      }
    } else {
      final Rectangle lpRect =
          new Rectangle(
              pane.getLocationOnScreen().x,
              pane.getLocationOnScreen().y,
              pane.getWidth(),
              pane.getHeight());
      Rectangle componentRect =
          new Rectangle(
              desiredLocation.getScreenPoint().x,
              desiredLocation.getScreenPoint().y,
              component.getPreferredSize().width,
              component.getPreferredSize().height);
      return lpRect.contains(componentRect);
    }
  }
  private void setHeaderComponent(JComponent c) {
    boolean doRevalidate = false;
    if (myHeaderComponent != null) {
      myHeaderPanel.remove(myHeaderComponent);
      myHeaderPanel.add(myCaption, BorderLayout.NORTH);
      myHeaderComponent = null;
      doRevalidate = true;
    }

    if (c != null) {
      myHeaderPanel.remove(myCaption);
      myHeaderPanel.add(c, BorderLayout.NORTH);
      myHeaderComponent = c;

      final Dimension size = myContent.getSize();
      if (size.height < c.getPreferredSize().height * 2) {
        size.height += c.getPreferredSize().height;
        setSize(size);
      }

      doRevalidate = true;
    }

    if (doRevalidate) myContent.revalidate();
  }
Exemple #3
0
    /**
     * Instructs the layout manager to perform the layout for the specified container.
     *
     * @param the Container for which this layout manager is being used
     */
    public void layoutContainer(Container parent) {
      JRootPane root = (JRootPane) parent;
      Rectangle b = root.getBounds();
      Insets i = root.getInsets();
      int nextY = 0;
      int w = b.width - i.right - i.left;
      int h = b.height - i.top - i.bottom;

      if (root.getLayeredPane() != null) {
        root.getLayeredPane().setBounds(i.left, i.top, w, h);
      }
      if (root.getGlassPane() != null) {
        root.getGlassPane().setBounds(i.left, i.top, w, h);
      }
      // Note: This is laying out the children in the layeredPane,
      // technically, these are not our children.
      if (root.getWindowDecorationStyle() != JRootPane.NONE
          && (root.getUI() instanceof RootPaneUI)) {
        JComponent titlePane = ((RootPaneUI) root.getUI()).getTitlePane();
        if (titlePane != null) {
          Dimension tpd = titlePane.getPreferredSize();
          if (tpd != null) {
            int tpHeight = tpd.height;
            titlePane.setBounds(0, 0, w, tpHeight);
            nextY += tpHeight;
          }
        }
      }

      if (root.getContentPane() != null) {

        root.getContentPane().setBounds(0, nextY, w, h < nextY ? 0 : h - nextY);
      }
    }
Exemple #4
0
    /**
     * Returns the amount of space the layout would like to have.
     *
     * @param the Container for which this layout manager is being used
     * @return a Dimension object containing the layout's preferred size
     */
    public Dimension preferredLayoutSize(Container parent) {
      Dimension cpd, tpd;
      int cpWidth = 0;
      int cpHeight = 0;
      int mbWidth = 0;
      int mbHeight = 0;
      int tpWidth = 0;
      Insets i = parent.getInsets();
      JRootPane root = (JRootPane) parent;

      if (root.getContentPane() != null) {
        cpd = root.getContentPane().getPreferredSize();
      } else {
        cpd = root.getSize();
      }
      if (cpd != null) {
        cpWidth = cpd.width;
        cpHeight = cpd.height;
      }

      if (root.getWindowDecorationStyle() != JRootPane.NONE
          && (root.getUI() instanceof RootPaneUI)) {
        JComponent titlePane = ((RootPaneUI) root.getUI()).getTitlePane();
        if (titlePane != null) {
          tpd = titlePane.getPreferredSize();
          if (tpd != null) {
            tpWidth = tpd.width;
          }
        }
      }

      return new Dimension(
          Math.max(Math.max(cpWidth, mbWidth), tpWidth) + i.left + i.right,
          cpHeight + mbHeight + tpWidth + i.top + i.bottom);
    }
Exemple #5
0
    QuickDocInfoPane(
        @NotNull PsiElement documentationAnchor,
        @NotNull PsiElement elementUnderMouse,
        @NotNull JComponent baseDocControl) {
      myBaseDocControl = baseDocControl;

      PresentationFactory presentationFactory = new PresentationFactory();
      for (AbstractDocumentationTooltipAction action : ourTooltipActions) {
        Icon icon = action.getTemplatePresentation().getIcon();
        Dimension minSize = new Dimension(icon.getIconWidth(), icon.getIconHeight());
        myButtons.add(
            new ActionButton(
                action,
                presentationFactory.getPresentation(action),
                IdeTooltipManager.IDE_TOOLTIP_PLACE,
                minSize));
        action.setDocInfo(documentationAnchor, elementUnderMouse);
      }
      Collections.reverse(myButtons);

      setPreferredSize(baseDocControl.getPreferredSize());
      setMaximumSize(baseDocControl.getMaximumSize());
      setMinimumSize(baseDocControl.getMinimumSize());
      setBackground(baseDocControl.getBackground());

      add(baseDocControl, Integer.valueOf(0));
      int minWidth = 0;
      int minHeight = 0;
      int buttonWidth = 0;
      for (JComponent button : myButtons) {
        button.setBorder(null);
        button.setBackground(baseDocControl.getBackground());
        add(button, Integer.valueOf(1));
        button.setVisible(false);
        Dimension preferredSize = button.getPreferredSize();
        minWidth += preferredSize.width;
        minHeight = Math.max(minHeight, preferredSize.height);
        buttonWidth = Math.max(buttonWidth, preferredSize.width);
      }
      myButtonWidth = buttonWidth;

      int margin = 2;
      myMinWidth = minWidth + margin * 2 + (myButtons.size() - 1) * BUTTON_HGAP;
      myMinHeight = minHeight + margin * 2;
    }
Exemple #6
0
 private void updateLabelSizes() {
   Dictionary labelTable = getLabelTable();
   if (labelTable != null) {
     Enumeration labels = labelTable.elements();
     while (labels.hasMoreElements()) {
       JComponent component = (JComponent) labels.nextElement();
       component.setSize(component.getPreferredSize());
     }
   }
 }
  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());
  }
  /*
   *  Create a BufferedImage for Swing components.
   *  The entire component will be captured to an image.
   *
   *  @param	 component Swing component to create image from
   *  @param	 fileName name of file to be created or null
   *  @return	image the image for the given region
   *  @exception IOException if an error occurs during writing
   */
  public static BufferedImage createImage(JComponent component, String fileName)
      throws IOException {
    Dimension d = component.getSize();

    if (d.width == 0) {
      d = component.getPreferredSize();
      component.setSize(d);
    }

    Rectangle region = new Rectangle(0, 0, d.width, d.height);
    return ScreenCapture.createImage(component, region, fileName);
  }
 private void addRow(String label, JComponent component) {
   JLabel l = new JLabel(label);
   l.setFont(Theme.SMALL_BOLD_FONT);
   l.setBounds(18, y, 400, 18);
   add(l);
   y += 18;
   int componentHeight = (int) component.getPreferredSize().getHeight();
   component.setBounds(16, y, 400, componentHeight);
   y += componentHeight;
   y += 2; // vertical gap
   add(component);
 }
Exemple #10
0
  /**
   * Updates the UIs for the labels in the label table by calling {@code updateUI} on each label.
   * The UIs are updated from the current look and feel. The labels are also set to their preferred
   * size.
   *
   * @see #setLabelTable
   * @see JComponent#updateUI
   */
  protected void updateLabelUIs() {
    Dictionary labelTable = getLabelTable();

    if (labelTable == null) {
      return;
    }
    Enumeration labels = labelTable.keys();
    while (labels.hasMoreElements()) {
      JComponent component = (JComponent) labelTable.get(labels.nextElement());
      component.updateUI();
      component.setSize(component.getPreferredSize());
    }
  }
Exemple #11
0
    @Override
    public void doLayout() {
      Rectangle bounds = getBounds();
      myBaseDocControl.setBounds(new Rectangle(0, 0, bounds.width, bounds.height));

      int x = bounds.width;
      for (JComponent button : myButtons) {
        Dimension buttonSize = button.getPreferredSize();
        x -= buttonSize.width;
        button.setBounds(x, 0, buttonSize.width, buttonSize.height);
        x -= BUTTON_HGAP;
      }
    }
  /**
   * Create the GUI and show it. For thread safety, this method should be invoked from the
   * event-dispatching thread.
   */
  private static void createAndShowGUI() {
    // Create and set up the window.
    JFrame frame = new JFrame("ListDataEventDemo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    // Create and set up the content pane.
    JComponent newContentPane = new ListDataEventDemo();
    newContentPane.setOpaque(true); // content panes must be opaque
    frame.setContentPane(newContentPane);

    // Don't let the content pane get too small.
    // (Works if the Java look and feel provides
    // the window decorations.)
    newContentPane.setMinimumSize(new Dimension(newContentPane.getPreferredSize().width, 100));

    // Display the window.
    frame.pack();
    frame.setVisible(true);
  }
  private void doHandleSelectionChange(@NotNull KeyType selected, boolean processIfUnfocused) {
    if (!isHandleSelectionEnabled(selected, processIfUnfocused)) {
      hideHint();
      return;
    }

    myKey = selected;

    Point location = createToolTipImage(myKey);

    if (location == null) {
      hideHint();
    } else {
      Rectangle bounds = new Rectangle(location, myTipComponent.getPreferredSize());
      myPopup.setBounds(bounds);
      myPopup.setVisible(noIntersections(bounds));
      repaintKeyItem();
    }
  }
Exemple #14
0
  void test(JComponent c) {
    c.setEnabled(false);
    c.setOpaque(true);
    c.setBackground(TEST_COLOR);
    c.setBorder(null);
    Dimension size = c.getPreferredSize();
    c.setBounds(0, 0, size.width, size.height);

    BufferedImage image = new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_ARGB);
    c.paint(image.getGraphics());

    int rgb = TEST_COLOR.getRGB();
    for (int i = 0; i < size.height; i++) {
      for (int j = 0; j < size.width; j++) {
        if (image.getRGB(j, i) != rgb) {
          throw new RuntimeException(String.format("Color mismatch at [%d, %d]", j, i));
        }
      }
    }
  }
  private void checkResult(@TestDataFile String expectedResultFileName) throws IOException {
    myEditor.getSettings().setAdditionalLinesCount(0);
    myEditor.getSettings().setAdditionalColumnsCount(1);
    JComponent editorComponent = myEditor.getContentComponent();
    Dimension size = editorComponent.getPreferredSize();
    editorComponent.setSize(size);
    //noinspection UndesirableClassUsage
    BufferedImage image = new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_ARGB);
    BitmapFont bitmapFont = BitmapFont.loadFromFile(getFontFile());
    MyGraphics graphics = new MyGraphics(image.createGraphics(), bitmapFont);
    try {
      editorComponent.paint(graphics);
    } finally {
      graphics.dispose();
    }

    File fileWithExpectedResult = getTestDataFile(expectedResultFileName);
    if (OVERWRITE_TESTDATA) {
      ImageIO.write(image, "png", fileWithExpectedResult);
      System.out.println("File " + fileWithExpectedResult.getPath() + " created.");
    }
    if (fileWithExpectedResult.exists()) {
      BufferedImage expectedResult = ImageIO.read(fileWithExpectedResult);
      if (expectedResult.getWidth() != image.getWidth()) {
        fail("Unexpected image width", fileWithExpectedResult, image);
      }
      if (expectedResult.getHeight() != image.getHeight()) {
        fail("Unexpected image height", fileWithExpectedResult, image);
      }
      for (int i = 0; i < expectedResult.getWidth(); i++) {
        for (int j = 0; j < expectedResult.getHeight(); j++) {
          if (expectedResult.getRGB(i, j) != image.getRGB(i, j)) {
            fail("Unexpected image contents", fileWithExpectedResult, image);
          }
        }
      }
    } else {
      ImageIO.write(image, "png", fileWithExpectedResult);
      fail("Missing test data created: " + fileWithExpectedResult.getPath());
    }
  }
Exemple #16
0
  /**
   * Creates preview for the (video) device in the video container.
   *
   * @param device the device
   * @param videoContainer the video container
   * @throws IOException a problem accessing the device
   * @throws MediaException a problem getting preview
   */
  private static void createVideoPreview(CaptureDeviceInfo device, JComponent videoContainer)
      throws IOException, MediaException {
    videoContainer.removeAll();

    videoContainer.revalidate();
    videoContainer.repaint();

    if (device == null) return;

    for (MediaDevice mediaDevice : mediaService.getDevices(MediaType.VIDEO, MediaUseCase.ANY)) {
      if (((MediaDeviceImpl) mediaDevice).getCaptureDeviceInfo().equals(device)) {
        Dimension videoContainerSize = videoContainer.getPreferredSize();
        Component preview =
            (Component)
                mediaService.getVideoPreviewComponent(
                    mediaDevice, videoContainerSize.width, videoContainerSize.height);

        if (preview != null) videoContainer.add(preview);
        break;
      }
    }
  }
  private void fixActualPoint(Point actualPoint) {
    if (!isAwtTooltip()) return;
    if (!myIsRealPopup) return;

    Dimension size = myComponent.getPreferredSize();
    Balloon.Position position = myHintHint.getPreferredPosition();
    int shift = BalloonImpl.getPointerLength(position, false);
    switch (position) {
      case below:
        actualPoint.y += shift;
        break;
      case above:
        actualPoint.y -= (shift + size.height);
        break;
      case atLeft:
        actualPoint.x -= (shift + size.width);
        break;
      case atRight:
        actualPoint.y += shift;
        break;
    }
  }
    /**
     * Paints the border for the specified component with the specified position and size.
     *
     * @param c the component for which this border is being painted
     * @param g the paint graphics
     * @param x the x position of the painted border
     * @param y the y position of the painted border
     * @param width the width of the painted border
     * @param height the height of the painted border
     */
    public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {

      Border border = getBorder();

      if (label == null) {
        if (border != null) {
          border.paintBorder(c, g, x, y, width, height);
        }
        return;
      }

      Rectangle grooveRect =
          new Rectangle(
              x + EDGE_SPACING,
              y + EDGE_SPACING,
              width - (EDGE_SPACING * 2),
              height - (EDGE_SPACING * 2));

      Dimension labelDim = label.getPreferredSize();
      int baseline = label.getBaseline(labelDim.width, labelDim.height);
      int ascent = Math.max(0, baseline);
      int descent = labelDim.height - ascent;
      int diff;
      Insets insets;

      if (border != null) {
        insets = border.getBorderInsets(c);
      } else {
        insets = new Insets(0, 0, 0, 0);
      }

      diff = Math.max(0, ascent / 2 + TEXT_SPACING - EDGE_SPACING);
      grooveRect.y += diff;
      grooveRect.height -= diff;
      compLoc.y = grooveRect.y + insets.top / 2 - (ascent + descent) / 2 - 1;

      int justification;
      if (c.getComponentOrientation().isLeftToRight()) {
        justification = LEFT;
      } else {
        justification = RIGHT;
      }

      switch (justification) {
        case LEFT:
          compLoc.x = grooveRect.x + TEXT_INSET_H + insets.left;
          break;
        case RIGHT:
          compLoc.x =
              (grooveRect.x + grooveRect.width - (labelDim.width + TEXT_INSET_H + insets.right));
          break;
      }

      // If title is positioned in middle of border AND its fontsize
      // is greater than the border's thickness, we'll need to paint
      // the border in sections to leave space for the component's background
      // to show through the title.
      //
      if (border != null) {
        if (grooveRect.y > compLoc.y - ascent) {
          Rectangle clipRect = new Rectangle();

          // save original clip
          Rectangle saveClip = g.getClipBounds();

          // paint strip left of text
          clipRect.setBounds(saveClip);
          if (computeIntersection(clipRect, x, y, compLoc.x - 1 - x, height)) {
            g.setClip(clipRect);
            border.paintBorder(
                c, g, grooveRect.x, grooveRect.y, grooveRect.width, grooveRect.height);
          }

          // paint strip right of text
          clipRect.setBounds(saveClip);
          if (computeIntersection(
              clipRect,
              compLoc.x + labelDim.width + 1,
              y,
              x + width - (compLoc.x + labelDim.width + 1),
              height)) {
            g.setClip(clipRect);
            border.paintBorder(
                c, g, grooveRect.x, grooveRect.y, grooveRect.width, grooveRect.height);
          }

          // paint strip below text
          clipRect.setBounds(saveClip);
          if (computeIntersection(
              clipRect,
              compLoc.x - 1,
              compLoc.y + ascent + descent,
              labelDim.width + 2,
              y + height - compLoc.y - ascent - descent)) {
            g.setClip(clipRect);
            border.paintBorder(
                c, g, grooveRect.x, grooveRect.y, grooveRect.width, grooveRect.height);
          }

          // restore clip
          g.setClip(saveClip);

        } else {
          border.paintBorder(c, g, grooveRect.x, grooveRect.y, grooveRect.width, grooveRect.height);
        }

        label.setLocation(compLoc);
        label.setSize(labelDim);
      }
    }
Exemple #19
0
  @Override
  public ActionCallback navigateTo(@Nullable final Place place, final boolean requestFocus) {
    final Configurable toSelect = (Configurable) place.getPath(CATEGORY);

    JComponent detailsContent = myDetails.getTargetComponent();

    if (mySelectedConfigurable != toSelect) {
      if (mySelectedConfigurable instanceof BaseStructureConfigurable) {
        ((BaseStructureConfigurable) mySelectedConfigurable).onStructureUnselected();
      }
      saveSideProportion();
      removeSelected();

      if (toSelect != null) {
        detailsContent = toSelect.createComponent();
        myDetails.setContent(detailsContent);
      }

      mySelectedConfigurable = toSelect;
      if (mySelectedConfigurable != null) {
        myUiState.lastEditedConfigurable = mySelectedConfigurable.getDisplayName();
      }

      if (toSelect instanceof MasterDetailsComponent) {
        final MasterDetailsComponent masterDetails = (MasterDetailsComponent) toSelect;
        if (myUiState.sideProportion > 0) {
          masterDetails.getSplitter().setProportion(myUiState.sideProportion);
        }
        masterDetails.setHistory(myHistory);
      }

      if (toSelect instanceof DetailsComponent.Facade) {
        ((DetailsComponent.Facade) toSelect)
            .getDetailsComponent()
            .setBannerMinHeight(myToolbarComponent.getPreferredSize().height);
      }

      if (toSelect instanceof BaseStructureConfigurable) {
        ((BaseStructureConfigurable) toSelect).onStructureSelected();
      }
    }

    if (detailsContent != null) {
      JComponent toFocus = IdeFocusTraversalPolicy.getPreferredFocusedComponent(detailsContent);
      if (toFocus == null) {
        toFocus = detailsContent;
      }
      if (requestFocus) {
        myToFocus = toFocus;
        UIUtil.requestFocus(toFocus);
      }
    }

    final ActionCallback result = new ActionCallback();
    Place.goFurther(toSelect, place, requestFocus).notifyWhenDone(result);

    myDetails.revalidate();
    myDetails.repaint();

    if (toSelect != null) {
      mySidePanel.select(createPlaceFor(toSelect));
    }

    if (!myHistory.isNavigatingNow() && mySelectedConfigurable != null) {
      myHistory.pushQueryPlace();
    }

    return result;
  }
Exemple #20
0
 @Override
 public Dimension getPreferredSize() {
   return expandIfNecessary(myBaseDocControl.getPreferredSize());
 }
 @Override
 public Dimension getPreferredSize() {
   return myAnchor == null || myAnchor == this
       ? super.getPreferredSize()
       : myAnchor.getPreferredSize();
 }
  public static void main(String args[]) {
    JComponent ch = new JComponent() {};
    ch.getAccessibleContext();
    ch.isFocusTraversable();
    ch.setEnabled(false);
    ch.setEnabled(true);
    ch.requestFocus();
    ch.requestFocusInWindow();
    ch.getPreferredSize();
    ch.getMaximumSize();
    ch.getMinimumSize();
    ch.contains(1, 2);
    Component c1 = ch.add(new Component() {});
    Component c2 = ch.add(new Component() {});
    Component c3 = ch.add(new Component() {});
    Insets ins = ch.getInsets();
    ch.getAlignmentY();
    ch.getAlignmentX();
    ch.getGraphics();
    ch.setVisible(false);
    ch.setVisible(true);
    ch.setForeground(Color.red);
    ch.setBackground(Color.red);
    for (String font : Toolkit.getDefaultToolkit().getFontList()) {
      for (int j = 8; j < 17; j++) {
        Font f1 = new Font(font, Font.PLAIN, j);
        Font f2 = new Font(font, Font.BOLD, j);
        Font f3 = new Font(font, Font.ITALIC, j);
        Font f4 = new Font(font, Font.BOLD | Font.ITALIC, j);

        ch.setFont(f1);
        ch.setFont(f2);
        ch.setFont(f3);
        ch.setFont(f4);

        ch.getFontMetrics(f1);
        ch.getFontMetrics(f2);
        ch.getFontMetrics(f3);
        ch.getFontMetrics(f4);
      }
    }
    ch.enable();
    ch.disable();
    ch.reshape(10, 10, 10, 10);
    ch.getBounds(new Rectangle(1, 1, 1, 1));
    ch.getSize(new Dimension(1, 2));
    ch.getLocation(new Point(1, 2));
    ch.getX();
    ch.getY();
    ch.getWidth();
    ch.getHeight();
    ch.isOpaque();
    ch.isValidateRoot();
    ch.isOptimizedDrawingEnabled();
    ch.isDoubleBuffered();
    ch.getComponentCount();
    ch.countComponents();
    ch.getComponent(1);
    ch.getComponent(2);
    Component[] cs = ch.getComponents();
    ch.getLayout();
    ch.setLayout(new FlowLayout());
    ch.doLayout();
    ch.layout();
    ch.invalidate();
    ch.validate();
    ch.remove(0);
    ch.remove(c2);
    ch.removeAll();
    ch.preferredSize();
    ch.minimumSize();
    ch.getComponentAt(1, 2);
    ch.locate(1, 2);
    ch.getComponentAt(new Point(1, 2));
    ch.isFocusCycleRoot(new Container());
    ch.transferFocusBackward();
    ch.setName("goober");
    ch.getName();
    ch.getParent();
    ch.getGraphicsConfiguration();
    ch.getTreeLock();
    ch.getToolkit();
    ch.isValid();
    ch.isDisplayable();
    ch.isVisible();
    ch.isShowing();
    ch.isEnabled();
    ch.enable(false);
    ch.enable(true);
    ch.enableInputMethods(false);
    ch.enableInputMethods(true);
    ch.show();
    ch.show(false);
    ch.show(true);
    ch.hide();
    ch.getForeground();
    ch.isForegroundSet();
    ch.getBackground();
    ch.isBackgroundSet();
    ch.getFont();
    ch.isFontSet();
    Container c = new Container();
    c.add(ch);
    ch.getLocale();
    for (Locale locale : Locale.getAvailableLocales()) ch.setLocale(locale);

    ch.getColorModel();
    ch.getLocation();

    boolean exceptions = false;
    try {
      ch.getLocationOnScreen();
    } catch (IllegalComponentStateException e) {
      exceptions = true;
    }
    if (!exceptions)
      throw new RuntimeException("IllegalComponentStateException did not occur when expected");

    ch.location();
    ch.setLocation(1, 2);
    ch.move(1, 2);
    ch.setLocation(new Point(1, 2));
    ch.getSize();
    ch.size();
    ch.setSize(1, 32);
    ch.resize(1, 32);
    ch.setSize(new Dimension(1, 32));
    ch.resize(new Dimension(1, 32));
    ch.getBounds();
    ch.bounds();
    ch.setBounds(10, 10, 10, 10);
    ch.setBounds(new Rectangle(10, 10, 10, 10));
    ch.isLightweight();
    ch.setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR));
    ch.getCursor();
    ch.isCursorSet();
    ch.inside(1, 2);
    ch.contains(new Point(1, 2));
    ch.isFocusable();
    ch.setFocusable(true);
    ch.setFocusable(false);
    ch.transferFocus();
    ch.getFocusCycleRootAncestor();
    ch.nextFocus();
    ch.transferFocusUpCycle();
    ch.hasFocus();
    ch.isFocusOwner();
    ch.toString();
    ch.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
    ch.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
    ch.setComponentOrientation(ComponentOrientation.UNKNOWN);
    ch.getComponentOrientation();
  }
Exemple #23
0
 /**
  * Returns the baseline for the specified component, or -1 if the baseline can not be determined.
  * The baseline is measured from the top of the component. This method returns the baseline based
  * on the preferred size.
  *
  * @param component JComponent to calculate baseline for
  * @return baseline for the specified component
  */
 public static int getBaseline(JComponent component) {
   Dimension pref = component.getPreferredSize();
   return getBaseline(component, pref.width, pref.height);
 }
 @Override
 public void updateBounds(int x, int y) {
   setSize(myComponent.getPreferredSize());
   updateLocation(x, y);
 }
 @Override
 public void pack() {
   setSize(myComponent.getPreferredSize());
 }
 private void fixComponentSize(JComponent comp) {
   comp.setMaximumSize(comp.getPreferredSize());
 }
  /**
   * Shows the hint in the layered pane. Coordinates <code>x</code> and <code>y</code> are in <code>
   * parentComponent</code> coordinate system. Note that the component appears on 250 layer.
   */
  @Override
  public void show(
      @NotNull final JComponent parentComponent,
      final int x,
      final int y,
      final JComponent focusBackComponent,
      @NotNull final HintHint hintHint) {
    myParentComponent = parentComponent;
    myHintHint = hintHint;

    myFocusBackComponent = focusBackComponent;

    LOG.assertTrue(myParentComponent.isShowing());
    myEscListener = new MyEscListener();
    myComponent.registerKeyboardAction(
        myEscListener,
        KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0),
        JComponent.WHEN_IN_FOCUSED_WINDOW);
    myComponent.registerKeyboardAction(
        myEscListener, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_FOCUSED);
    final JLayeredPane layeredPane = parentComponent.getRootPane().getLayeredPane();

    myComponent.validate();

    if (!myForceShowAsPopup
        && (myForceLightweightPopup
            || fitsLayeredPane(
                layeredPane,
                myComponent,
                new RelativePoint(parentComponent, new Point(x, y)),
                hintHint))) {
      beforeShow();
      final Dimension preferredSize = myComponent.getPreferredSize();

      if (hintHint.isAwtTooltip()) {
        IdeTooltip tooltip =
            new IdeTooltip(
                hintHint.getOriginalComponent(),
                hintHint.getOriginalPoint(),
                myComponent,
                hintHint,
                myComponent) {
              @Override
              protected boolean canAutohideOn(TooltipEvent event) {
                if (event.getInputEvent() instanceof MouseEvent) {
                  return !(hintHint.isContentActive() && event.isIsEventInsideBalloon());
                } else if (event.getAction() != null) {
                  return false;
                } else {
                  return true;
                }
              }

              @Override
              protected void onHidden() {
                fireHintHidden();
                TooltipController.getInstance().resetCurrent();
              }

              @Override
              public boolean canBeDismissedOnTimeout() {
                return false;
              }
            }.setToCenterIfSmall(hintHint.isMayCenterTooltip())
                .setPreferredPosition(hintHint.getPreferredPosition())
                .setHighlighterType(hintHint.isHighlighterType())
                .setTextForeground(hintHint.getTextForeground())
                .setTextBackground(hintHint.getTextBackground())
                .setBorderColor(hintHint.getBorderColor())
                .setBorderInsets(hintHint.getBorderInsets())
                .setFont(hintHint.getTextFont())
                .setCalloutShift(hintHint.getCalloutShift())
                .setPositionChangeShift(
                    hintHint.getPositionChangeX(), hintHint.getPositionChangeY())
                .setExplicitClose(hintHint.isExplicitClose())
                .setHint(true);
        myComponent.validate();
        myCurrentIdeTooltip =
            IdeTooltipManager.getInstance()
                .show(tooltip, hintHint.isShowImmediately(), hintHint.isAnimationEnabled());
      } else {
        final Point layeredPanePoint =
            SwingUtilities.convertPoint(parentComponent, x, y, layeredPane);
        myComponent.setBounds(
            layeredPanePoint.x, layeredPanePoint.y, preferredSize.width, preferredSize.height);
        layeredPane.add(myComponent, JLayeredPane.POPUP_LAYER);

        myComponent.validate();
        myComponent.repaint();
      }
    } else {
      myIsRealPopup = true;
      Point actualPoint = new Point(x, y);
      JComponent actualComponent = new OpaquePanel(new BorderLayout());
      actualComponent.add(myComponent, BorderLayout.CENTER);
      if (isAwtTooltip()) {
        fixActualPoint(actualPoint);

        int inset = BalloonImpl.getNormalInset();
        actualComponent.setBorder(new LineBorder(hintHint.getTextBackground(), inset));
        actualComponent.setBackground(hintHint.getTextBackground());
        actualComponent.validate();
      }

      myPopup =
          JBPopupFactory.getInstance()
              .createComponentPopupBuilder(actualComponent, myFocusRequestor)
              .setRequestFocus(myFocusRequestor != null)
              .setFocusable(myFocusRequestor != null)
              .setResizable(myResizable)
              .setMovable(myTitle != null)
              .setTitle(myTitle)
              .setModalContext(false)
              .setShowShadow(isRealPopup() && !isForceHideShadow())
              .setCancelKeyEnabled(false)
              .setCancelOnClickOutside(myCancelOnClickOutside)
              .setCancelCallback(
                  new Computable<Boolean>() {
                    @Override
                    public Boolean compute() {
                      onPopupCancel();
                      return true;
                    }
                  })
              .setCancelOnOtherWindowOpen(myCancelOnOtherWindowOpen)
              .createPopup();

      beforeShow();
      myPopup.show(new RelativePoint(myParentComponent, new Point(actualPoint.x, actualPoint.y)));
    }
  }
  public void ellipsifyValues(int width) {
    int maxKeyWidth = 0;
    int[] maxAdditionalColumnsWidth = new int[additionalColumns];

    for (JComponent keyComp : keyKeyComponentMap.values()) {
      maxKeyWidth = Math.max(maxKeyWidth, keyComp.getPreferredSize().width);
    }

    for (String k : keyValueComponentMap.keySet()) {
      for (int i = 0; i < additionalColumns; i++) {
        JComponent extraComp = getAdditionalColumn(k, i);
        if (extraComp != null) {
          maxAdditionalColumnsWidth[i] =
              Math.max(maxAdditionalColumnsWidth[i], extraComp.getPreferredSize().width);
        }
      }
    }

    width -= maxKeyWidth;
    for (int i : maxAdditionalColumnsWidth) {
      width -= i;
    }

    for (String k : keyValueComponentMap.keySet()) {
      JComponent comp = getComponent(k);
      if (comp != null) {
        int avail = width;
        /*for (int i = 0; i < additionalColumns; i++) {
        JComponent extraComp = getAdditionalColumn(k, i);
        if (extraComp != null) {
        avail -= extraComp.getPreferredSize().width;
        }
        }*/

        if (comp instanceof JLabel) {

          while (avail < comp.getPreferredSize().width) {
            String text = ((JLabel) comp).getText();
            if (text.endsWith("…")) {
              if (text.length() > 2) {
                // Already truncated.
                text = text.substring(0, text.length() - 2);
              } else {
                break; // As short as we can get.  Can't truncate any more.
              }
            } else {
              // Reasonable first truncation is to trim off the last word.
              int spacePos = text.lastIndexOf(' ');
              if (spacePos > 0) {
                text = text.substring(0, spacePos);
              } else {
                FontMetrics fm = comp.getFontMetrics(comp.getFont());

                while (fm.stringWidth(text + "…") > avail) {
                  // causes StringIndexOutOfBoundsException if text is empty.
                  if (text == null || text.length() < 2) {
                    LOG.info("Text is null or empty in KeyValuePairPanel");
                    break;
                  }
                  text = text.substring(0, text.length() - 2);
                }
                // text = text + "…";

                // text = text.substring(0, text.length() - 1);
              }
            }
            ((JLabel) comp).setText(text + "…");
          }
        } else {
          // Can't truncate, but we can force the preferred size.
          comp.setMaximumSize(new Dimension(avail, comp.getPreferredSize().height));
        }
      }
    }
  }
  @NotNull
  private JBPopup createUsagePopup(
      @NotNull final List<Usage> usages,
      @NotNull final UsageInfoToUsageConverter.TargetElementsDescriptor descriptor,
      @NotNull Set<UsageNode> visibleNodes,
      @NotNull final FindUsagesHandler handler,
      final Editor editor,
      @NotNull final RelativePoint popupPosition,
      final int maxUsages,
      @NotNull final UsageViewImpl usageView,
      @NotNull final FindUsagesOptions options,
      @NotNull final JTable table,
      @NotNull final UsageViewPresentation presentation,
      @NotNull final AsyncProcessIcon processIcon,
      boolean hadMoreSeparator) {
    table.setRowHeight(PlatformIcons.CLASS_ICON.getIconHeight() + 2);
    table.setShowGrid(false);
    table.setShowVerticalLines(false);
    table.setShowHorizontalLines(false);
    table.setTableHeader(null);
    table.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN);
    table.setIntercellSpacing(new Dimension(0, 0));

    PopupChooserBuilder builder = new PopupChooserBuilder(table);
    final String title = presentation.getTabText();
    if (title != null) {
      String result = getFullTitle(usages, title, hadMoreSeparator, visibleNodes.size() - 1, true);
      builder.setTitle(result);
      builder.setAdText(getSecondInvocationTitle(options, handler));
    }

    builder.setMovable(true).setResizable(true);
    builder.setItemChoosenCallback(
        new Runnable() {
          @Override
          public void run() {
            int[] selected = table.getSelectedRows();
            for (int i : selected) {
              Object value = table.getValueAt(i, 0);
              if (value instanceof UsageNode) {
                Usage usage = ((UsageNode) value).getUsage();
                if (usage == MORE_USAGES_SEPARATOR) {
                  appendMoreUsages(editor, popupPosition, handler, maxUsages);
                  return;
                }
                navigateAndHint(usage, null, handler, popupPosition, maxUsages, options);
              }
            }
          }
        });
    final JBPopup[] popup = new JBPopup[1];

    KeyboardShortcut shortcut = UsageViewImpl.getShowUsagesWithSettingsShortcut();
    if (shortcut != null) {
      new DumbAwareAction() {
        @Override
        public void actionPerformed(AnActionEvent e) {
          popup[0].cancel();
          showDialogAndFindUsages(handler, popupPosition, editor, maxUsages);
        }
      }.registerCustomShortcutSet(new CustomShortcutSet(shortcut.getFirstKeyStroke()), table);
    }
    shortcut = getShowUsagesShortcut();
    if (shortcut != null) {
      new DumbAwareAction() {
        @Override
        public void actionPerformed(AnActionEvent e) {
          popup[0].cancel();
          searchEverywhere(options, handler, editor, popupPosition, maxUsages);
        }
      }.registerCustomShortcutSet(new CustomShortcutSet(shortcut.getFirstKeyStroke()), table);
    }

    InplaceButton settingsButton =
        createSettingsButton(
            handler,
            popupPosition,
            editor,
            maxUsages,
            new Runnable() {
              @Override
              public void run() {
                popup[0].cancel();
              }
            });

    ActiveComponent spinningProgress =
        new ActiveComponent() {
          @Override
          public void setActive(boolean active) {}

          @Override
          public JComponent getComponent() {
            return processIcon;
          }
        };
    builder.setCommandButton(new CompositeActiveComponent(spinningProgress, settingsButton));

    DefaultActionGroup toolbar = new DefaultActionGroup();
    usageView.addFilteringActions(toolbar);

    toolbar.add(UsageGroupingRuleProviderImpl.createGroupByFileStructureAction(usageView));
    toolbar.add(
        new AnAction(
            "Open Find Usages Toolwindow",
            "Show all usages in a separate toolwindow",
            AllIcons.Toolwindows.ToolWindowFind) {
          {
            AnAction action = ActionManager.getInstance().getAction(IdeActions.ACTION_FIND_USAGES);
            setShortcutSet(action.getShortcutSet());
          }

          @Override
          public void actionPerformed(AnActionEvent e) {
            hideHints();
            popup[0].cancel();
            FindUsagesManager findUsagesManager =
                ((FindManagerImpl) FindManager.getInstance(usageView.getProject()))
                    .getFindUsagesManager();

            findUsagesManager.findUsages(
                handler.getPrimaryElements(),
                handler.getSecondaryElements(),
                handler,
                options,
                FindSettings.getInstance().isSkipResultsWithOneUsage());
          }
        });

    ActionToolbar actionToolbar =
        ActionManager.getInstance()
            .createActionToolbar(ActionPlaces.USAGE_VIEW_TOOLBAR, toolbar, true);
    actionToolbar.setReservePlaceAutoPopupIcon(false);
    final JComponent toolBar = actionToolbar.getComponent();
    toolBar.setOpaque(false);
    builder.setSettingButton(toolBar);

    popup[0] = builder.createPopup();
    JComponent content = popup[0].getContent();

    myWidth =
        (int)
            (toolBar.getPreferredSize().getWidth()
                + new JLabel(
                        getFullTitle(
                            usages, title, hadMoreSeparator, visibleNodes.size() - 1, true))
                    .getPreferredSize()
                    .getWidth()
                + settingsButton.getPreferredSize().getWidth());
    myWidth = -1;
    for (AnAction action : toolbar.getChildren(null)) {
      action.unregisterCustomShortcutSet(usageView.getComponent());
      action.registerCustomShortcutSet(action.getShortcutSet(), content);
    }

    return popup[0];
  }
  private void addToken(@NotNull CompositeArrangementSettingsToken rowToken) {
    List<CompositeArrangementSettingsToken> tokens = ArrangementUtil.flatten(rowToken);
    GridBag labelConstraints =
        new GridBag()
            .anchor(GridBagConstraints.NORTHWEST)
            .insets(ArrangementConstants.VERTICAL_PADDING, 0, 0, 0);
    MultiRowFlowPanel panel =
        new MultiRowFlowPanel(
            FlowLayout.LEFT,
            ArrangementConstants.HORIZONTAL_GAP,
            ArrangementConstants.VERTICAL_GAP);
    List<ArrangementSettingsToken> prevTokens = ContainerUtilRt.newArrayList();
    StdArrangementTokenUiRole prevRole = null;
    ArrangementUiComponent component;
    JComponent uiComponent;
    for (CompositeArrangementSettingsToken token : tokens) {
      StdArrangementTokenUiRole role = token.getRole();
      if (role != prevRole && !prevTokens.isEmpty()) {
        component =
            ArrangementUtil.buildUiComponent(role, prevTokens, myColorsProvider, mySettingsManager);
        component.setListener(this);
        for (ArrangementSettingsToken prevToken : prevTokens) {
          myComponents.put(prevToken, component);
        }
        panel.add(component.getUiComponent());
        panel = addRowIfNecessary(panel);
        prevRole = null;
        prevTokens.clear();
      }
      component =
          ArrangementUtil.buildUiComponent(
              role,
              Collections.singletonList(token.getToken()),
              myColorsProvider,
              mySettingsManager);
      component.setListener(this);
      uiComponent = component.getUiComponent();
      switch (role) {
        case LABEL:
          panel = addRowIfNecessary(panel);
          add(uiComponent, labelConstraints);
          myLabelWidth = Math.max(myLabelWidth, uiComponent.getPreferredSize().width);
          prevRole = null;
          break;
        case TEXT_FIELD:
          panel = addRowIfNecessary(panel);

          ArrangementUiComponent textLabel =
              ArrangementUtil.buildUiComponent(
                  StdArrangementTokenUiRole.LABEL,
                  Collections.singletonList(token.getToken()),
                  myColorsProvider,
                  mySettingsManager);
          JComponent textLabelComponent = textLabel.getUiComponent();
          add(textLabelComponent, labelConstraints);
          myLabelWidth = Math.max(myLabelWidth, textLabelComponent.getPreferredSize().width);

          panel.add(uiComponent);
          panel = addRowIfNecessary(panel);
          prevRole = null;

          myComponents.put(token.getToken(), component);

          if (myDefaultFocusRequestor == null) {
            myDefaultFocusRequestor = uiComponent;
          }
          break;
        default:
          if (role == StdArrangementTokenUiRole.COMBO_BOX) {
            prevTokens.add(token.getToken());
            prevRole = role;
            break;
          }

          panel.add(uiComponent);
          myComponents.put(token.getToken(), component);
      }
    }

    if (prevRole != null && !prevTokens.isEmpty()) {
      component =
          ArrangementUtil.buildUiComponent(
              prevRole, prevTokens, myColorsProvider, mySettingsManager);
      panel.add(component.getUiComponent());
      component.setListener(this);
      for (ArrangementSettingsToken prevToken : prevTokens) {
        myComponents.put(prevToken, component);
      }
    }
    addRowIfNecessary(panel);
  }