コード例 #1
0
      @Override
      public void mouseDragged(MouseEvent e) {
        if (!myDragging) return;
        MouseEvent event = SwingUtilities.convertMouseEvent(e.getComponent(), e, MyDivider.this);
        final ToolWindowAnchor anchor = myInfo.getAnchor();
        final Point point = event.getPoint();
        final Container windowPane = InternalDecorator.this.getParent();
        myLastPoint = SwingUtilities.convertPoint(MyDivider.this, point, windowPane);
        myLastPoint.x = Math.min(Math.max(myLastPoint.x, 0), windowPane.getWidth());
        myLastPoint.y = Math.min(Math.max(myLastPoint.y, 0), windowPane.getHeight());

        final Rectangle bounds = InternalDecorator.this.getBounds();
        if (anchor == ToolWindowAnchor.TOP) {
          InternalDecorator.this.setBounds(0, 0, bounds.width, myLastPoint.y);
        } else if (anchor == ToolWindowAnchor.LEFT) {
          InternalDecorator.this.setBounds(0, 0, myLastPoint.x, bounds.height);
        } else if (anchor == ToolWindowAnchor.BOTTOM) {
          InternalDecorator.this.setBounds(
              0, myLastPoint.y, bounds.width, windowPane.getHeight() - myLastPoint.y);
        } else if (anchor == ToolWindowAnchor.RIGHT) {
          InternalDecorator.this.setBounds(
              myLastPoint.x, 0, windowPane.getWidth() - myLastPoint.x, bounds.height);
        }
        InternalDecorator.this.validate();
        e.consume();
      }
コード例 #2
0
    @Override
    public void layoutContainer(final Container parent) {
      final int componentCount = parent.getComponentCount();
      if (componentCount == 0) return;
      final EditorEx history = myHistoryViewer;
      final EditorEx editor = componentCount == 2 ? myConsoleEditor : null;

      if (editor == null) {
        parent.getComponent(0).setBounds(parent.getBounds());
        return;
      }

      final Dimension panelSize = parent.getSize();
      if (panelSize.getHeight() <= 0) return;
      final Dimension historySize = history.getContentSize();
      final Dimension editorSize = editor.getContentSize();
      final Dimension newEditorSize = new Dimension();

      // deal with width
      final int width = Math.max(editorSize.width, historySize.width);
      newEditorSize.width = width + editor.getScrollPane().getHorizontalScrollBar().getHeight();
      history.getSoftWrapModel().forceAdditionalColumnsUsage();
      editor
          .getSettings()
          .setAdditionalColumnsCount(
              2 + (width - editorSize.width) / EditorUtil.getSpaceWidth(Font.PLAIN, editor));
      history
          .getSettings()
          .setAdditionalColumnsCount(
              2 + (width - historySize.width) / EditorUtil.getSpaceWidth(Font.PLAIN, history));

      // deal with height
      if (historySize.width == 0) historySize.height = 0;
      final int minHistorySize =
          historySize.height > 0
              ? 2 * history.getLineHeight() + (myShowSeparatorLine ? SEPARATOR_THICKNESS : 0)
              : 0;
      final int minEditorSize = editor.isViewer() ? 0 : editor.getLineHeight();
      final int editorPreferred =
          editor.isViewer() ? 0 : Math.max(minEditorSize, editorSize.height);
      final int historyPreferred = Math.max(minHistorySize, historySize.height);
      if (panelSize.height < minEditorSize) {
        newEditorSize.height = panelSize.height;
      } else if (panelSize.height < editorPreferred) {
        newEditorSize.height = panelSize.height - minHistorySize;
      } else if (panelSize.height < editorPreferred + historyPreferred) {
        newEditorSize.height = editorPreferred;
      } else {
        newEditorSize.height = editorPreferred == 0 ? 0 : panelSize.height - historyPreferred;
      }
      final Dimension newHistorySize =
          new Dimension(width, panelSize.height - newEditorSize.height);

      // apply
      editor
          .getComponent()
          .setBounds(0, newHistorySize.height, panelSize.width, newEditorSize.height);
      myForceScrollToEnd.compareAndSet(false, shouldScrollHistoryToEnd());
      history.getComponent().setBounds(0, 0, panelSize.width, newHistorySize.height);
    }
コード例 #3
0
 private void recalculateFoldingAreaWidth() {
   myLeftFoldingAreaWidth =
       myRightToLeft ? MIN_RIGHT_FOLDING_AREA_WIDTH : MIN_LEFT_FOLDING_AREA_WIDTH;
   myRightFoldingAreaWidth =
       myRightToLeft ? MIN_LEFT_FOLDING_AREA_WIDTH : MIN_RIGHT_FOLDING_AREA_WIDTH;
   // Layouting painters
   for (AbstractFoldingAreaPainter painter : myFoldingAreaPainters) {
     myLeftFoldingAreaWidth = Math.max(myLeftFoldingAreaWidth, painter.getLeftAreaWidth());
     myRightFoldingAreaWidth = Math.max(myRightFoldingAreaWidth, painter.getRightAreaWidth());
   }
 }
コード例 #4
0
  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();
  }
コード例 #5
0
 private boolean setColumnPreferredSize() {
   boolean sizeCalculated = false;
   Font tableFont = UIManager.getFont("Table.font");
   for (int i = 0; i < getColumnCount(); i++) {
     TableColumn column = getColumnModel().getColumn(i);
     if (i == GraphTableModel.ROOT_COLUMN) { // thin stripe, or root name, or nothing
       setRootColumnSize(column);
     } else if (i
         == GraphTableModel.COMMIT_COLUMN) { // let commit message occupy as much as possible
       column.setPreferredWidth(Short.MAX_VALUE);
     } else if (i == GraphTableModel.AUTHOR_COLUMN) { // detect author with the longest name
       // to avoid querying the last row (it would lead to full graph loading)
       int maxRowsToCheck =
           Math.min(MAX_ROWS_TO_CALC_WIDTH, getRowCount() - MAX_ROWS_TO_CALC_OFFSET);
       if (maxRowsToCheck < 0) { // but if the log is small, check all of them
         maxRowsToCheck = getRowCount();
       }
       int maxWidth = 0;
       for (int row = 0; row < maxRowsToCheck; row++) {
         String value = getModel().getValueAt(row, i).toString();
         maxWidth = Math.max(getFontMetrics(tableFont).stringWidth(value), maxWidth);
         if (!value.isEmpty()) sizeCalculated = true;
       }
       column.setMinWidth(
           Math.min(maxWidth + UIUtil.DEFAULT_HGAP, MAX_DEFAULT_AUTHOR_COLUMN_WIDTH));
       column.setWidth(column.getMinWidth());
     } else if (i == GraphTableModel.DATE_COLUMN) { // all dates have nearly equal sizes
       column.setMinWidth(
           getFontMetrics(tableFont)
               .stringWidth("mm" + DateFormatUtil.formatDateTime(new Date())));
       column.setWidth(column.getMinWidth());
     }
   }
   return sizeCalculated;
 }
コード例 #6
0
 private static void duplicateHighlighters(
     MarkupModel to, MarkupModel from, int offset, TextRange textRange) {
   for (RangeHighlighter rangeHighlighter : from.getAllHighlighters()) {
     if (!rangeHighlighter.isValid()) continue;
     Object tooltip = rangeHighlighter.getErrorStripeTooltip();
     HighlightInfo highlightInfo =
         tooltip instanceof HighlightInfo ? (HighlightInfo) tooltip : null;
     if (highlightInfo != null) {
       if (highlightInfo.getSeverity() != HighlightSeverity.INFORMATION) continue;
       if (highlightInfo.type.getAttributesKey() == EditorColors.IDENTIFIER_UNDER_CARET_ATTRIBUTES)
         continue;
     }
     final int localOffset = textRange.getStartOffset();
     final int start = Math.max(rangeHighlighter.getStartOffset(), localOffset) - localOffset;
     final int end =
         Math.min(rangeHighlighter.getEndOffset(), textRange.getEndOffset()) - localOffset;
     if (start > end) continue;
     final RangeHighlighter h =
         to.addRangeHighlighter(
             start + offset,
             end + offset,
             rangeHighlighter.getLayer(),
             rangeHighlighter.getTextAttributes(),
             rangeHighlighter.getTargetArea());
     ((RangeHighlighterEx) h)
         .setAfterEndOfLine(((RangeHighlighterEx) rangeHighlighter).isAfterEndOfLine());
   }
 }
コード例 #7
0
 private int calculateMaxRootWidth() {
   int width = 0;
   for (VirtualFile file : myLogDataHolder.getRoots()) {
     Font tableFont = UIManager.getFont("Table.font");
     width = Math.max(getFontMetrics(tableFont).stringWidth(file.getName() + "  "), width);
   }
   return width;
 }
コード例 #8
0
 private static int getScrollAmount(Component c, MouseWheelEvent me, JScrollBar scrollBar) {
   final int scrollBarWidth = scrollBar.getWidth();
   final int ratio =
       Registry.is("ide.smart.horizontal.scrolling") && scrollBarWidth > 0
           ? Math.max((int) Math.pow(c.getWidth() / scrollBarWidth, 2), 10)
           : 10; // do annoying scrolling faster if smart scrolling is on
   return me.getUnitsToScroll() * scrollBar.getUnitIncrement() * ratio;
 }
コード例 #9
0
 private void scrollToRow(Integer row, Integer delta) {
   Rectangle startRect = myTable.getCellRect(row, 0, true);
   myTable.scrollRectToVisible(
       new Rectangle(
           startRect.x,
           Math.max(startRect.y - delta, 0),
           startRect.width,
           myTable.getVisibleRect().height));
 }
コード例 #10
0
 private int calcMaxContentColumnWidth(int columnIndex, int maxRowsToCheck) {
   int maxWidth = 0;
   for (int row = 0; row < maxRowsToCheck; row++) {
     TableCellRenderer renderer = getCellRenderer(row, columnIndex);
     Component comp = prepareRenderer(renderer, row, columnIndex);
     maxWidth = Math.max(comp.getPreferredSize().width, maxWidth);
   }
   return maxWidth + UIUtil.DEFAULT_HGAP;
 }
コード例 #11
0
 private void recalculateTextColumnWidth() {
   int initialOffset = getTextColumnOffset();
   int offset = initialOffset;
   for (AbstractLeftColumn column : myLeftColumns) {
     column.setX(offset);
     column.relayout();
     offset += column.getWidth();
   }
   myTextColumnWidth = Math.max(MIN_LEFT_TEXT_WIDTH, offset - initialOffset);
 }
コード例 #12
0
  private void recalculateIconRenderersWidth() {
    myLineToRenderersMap.clear();
    for (EditorMessageIconRenderer renderer : myIconRenderers) {
      int yCoordinate = getIconCoordinate(renderer);
      if (yCoordinate < 0) {
        continue;
      }
      List<IconRendererLayoutConstraint> renderersForLine = myLineToRenderersMap.get(yCoordinate);
      if (renderersForLine == null) {
        renderersForLine = new SortedList(myIconRenderersComparator);
        myLineToRenderersMap.put(yCoordinate, renderersForLine);
      }
      renderersForLine.add(new IconRendererLayoutConstraint(renderer));
    }

    myIconRenderersWidth = MIN_ICON_RENDERERS_WIDTH;
    myMaxIconHeight = 0;
    int[] sortedYCoordinates = myLineToRenderersMap.keys();
    Arrays.sort(sortedYCoordinates);

    int initialOffset = getIconRenderersOffset();
    for (int y : sortedYCoordinates) {
      List<IconRendererLayoutConstraint> row = myLineToRenderersMap.get(y);
      assert row.size() != 0;
      int maxIconHeight = 0;
      for (IconRendererLayoutConstraint rendererConstraint : row) {
        maxIconHeight =
            Math.max(maxIconHeight, rendererConstraint.getIconRenderer().getIcon().getIconHeight());
      }
      myMaxIconHeight = Math.max(myMaxIconHeight, maxIconHeight);
      int offset = initialOffset + LEFT_GAP;
      for (Iterator<IconRendererLayoutConstraint> it = row.iterator(); it.hasNext(); ) {
        IconRendererLayoutConstraint rendererConstraint = it.next();
        rendererConstraint.setX(offset);
        offset += rendererConstraint.getIconRenderer().getIcon().getIconWidth();
        if (it.hasNext()) {
          offset += GAP_BETWEEN_ICONS;
        }
      }
      myIconRenderersWidth = Math.max(myIconRenderersWidth, offset - initialOffset);
    }
  }
コード例 #13
0
  private static int columnMaxWidth(@NotNull JTable table, int col) {
    TableColumn column = table.getColumnModel().getColumn(col);
    int width = 0;
    for (int row = 0; row < table.getRowCount(); row++) {
      Component component = table.prepareRenderer(column.getCellRenderer(), row, col);

      int rendererWidth = component.getPreferredSize().width;
      width = Math.max(width, rendererWidth + table.getIntercellSpacing().width);
    }
    return width;
  }
コード例 #14
0
 private static Rectangle fitToScreen(
     @NotNull Dimension newDim, @NotNull RelativePoint popupPosition, JTable table) {
   Rectangle rectangle = new Rectangle(popupPosition.getScreenPoint(), newDim);
   ScreenUtil.fitToScreen(rectangle);
   if (rectangle.getHeight() != newDim.getHeight()) {
     int newHeight = (int) rectangle.getHeight();
     int roundedHeight = newHeight - newHeight % table.getRowHeight();
     rectangle.setSize((int) rectangle.getWidth(), Math.max(roundedHeight, table.getRowHeight()));
   }
   return rectangle;
 }
コード例 #15
0
    public static Image createImage(final JTable table, int column) {
      final int height =
          Math.max(20, Math.min(100, table.getSelectedRowCount() * table.getRowHeight()));
      final int width = table.getColumnModel().getColumn(column).getWidth();

      final BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
      Graphics2D g2 = (Graphics2D) image.getGraphics();

      g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.7f));

      drawSelection(table, column, g2, width);
      return image;
    }
コード例 #16
0
  public Dimension getPreferredSize() {
    Dimension basicSize = super.getPreferredSize();

    Icon icon = getIcon();
    FontMetrics fm = getFontMetrics(getFont());
    Rectangle viewRect = new Rectangle(0, 0, Short.MAX_VALUE, Short.MAX_VALUE);
    Insets insets = getInsets();
    int dx = insets.left + insets.right;
    int dy = insets.top + insets.bottom;

    Rectangle iconR = new Rectangle();
    Rectangle textR = new Rectangle();
    SwingUtilities.layoutCompoundLabel(
        this,
        fm,
        getText(),
        icon,
        SwingConstants.CENTER,
        horizontalTextAlignment(),
        SwingConstants.CENTER,
        horizontalTextPosition(),
        viewRect,
        iconR,
        textR,
        iconTextSpace());
    int x1 = Math.min(iconR.x, textR.x);
    int x2 = Math.max(iconR.x + iconR.width, textR.x + textR.width);
    int y1 = Math.min(iconR.y, textR.y);
    int y2 = Math.max(iconR.y + iconR.height, textR.y + textR.height);
    Dimension rv = new Dimension(x2 - x1 + dx, y2 - y1 + dy);

    rv.width += Math.max(basicSize.height - rv.height, 0);

    rv.width = Math.max(rv.width, basicSize.width);
    rv.height = Math.max(rv.height, basicSize.height);
    return rv;
  }
コード例 #17
0
  public static void assertTiming(final String message, final long expectedMs, final long actual) {
    if (COVERAGE_ENABLED_BUILD) return;

    final long expectedOnMyMachine =
        Math.max(1, expectedMs * Timings.MACHINE_TIMING / Timings.ETALON_TIMING);

    // Allow 10% more in case of test machine is busy.
    String logMessage = message;
    if (actual > expectedOnMyMachine) {
      int percentage = (int) (100.0 * (actual - expectedOnMyMachine) / expectedOnMyMachine);
      logMessage += ". Operation took " + percentage + "% longer than expected";
    }
    logMessage +=
        ". Expected on my machine: "
            + expectedOnMyMachine
            + "."
            + " Actual: "
            + actual
            + "."
            + " Expected on Standard machine: "
            + expectedMs
            + ";"
            + " Actual on Standard: "
            + actual * Timings.ETALON_TIMING / Timings.MACHINE_TIMING
            + ";"
            + " Timings: CPU="
            + Timings.CPU_TIMING
            + ", I/O="
            + Timings.IO_TIMING
            + "."
            + " ("
            + (int) (Timings.MACHINE_TIMING * 1.0 / Timings.ETALON_TIMING * 100)
            + "% of the Standard)"
            + ".";
    final double acceptableChangeFactor = 1.1;
    if (actual < expectedOnMyMachine) {
      System.out.println(logMessage);
      TeamCityLogger.info(logMessage);
    } else if (actual < expectedOnMyMachine * acceptableChangeFactor) {
      TeamCityLogger.warning(logMessage, null);
    } else {
      // throw AssertionFailedError to try one more time
      throw new AssertionFailedError(logMessage);
    }
  }
コード例 #18
0
  private static int calcMaxWidth(JTable table) {
    int colsNum = table.getColumnModel().getColumnCount();

    int totalWidth = 0;
    for (int col = 0; col < colsNum - 1; col++) {
      TableColumn column = table.getColumnModel().getColumn(col);
      int preferred = column.getPreferredWidth();
      int width = Math.max(preferred, columnMaxWidth(table, col));
      totalWidth += width;
      column.setMinWidth(width);
      column.setMaxWidth(width);
      column.setWidth(width);
      column.setPreferredWidth(width);
    }

    totalWidth += columnMaxWidth(table, colsNum - 1);

    return totalWidth;
  }
コード例 #19
0
 private void updateButtons() {
   final int[] selectedRows = myEntryTable.getSelectedRows();
   boolean removeButtonEnabled = true;
   int minRow = myEntryTable.getRowCount() + 1;
   int maxRow = -1;
   for (final int selectedRow : selectedRows) {
     minRow = Math.min(minRow, selectedRow);
     maxRow = Math.max(maxRow, selectedRow);
     final ClasspathTableItem<?> item = myModel.getItemAt(selectedRow);
     if (!item.isRemovable()) {
       removeButtonEnabled = false;
     }
   }
   if (myRemoveButton != null) {
     myRemoveButton.setEnabled(removeButtonEnabled && selectedRows.length > 0);
   }
   ClasspathTableItem<?> selectedItem =
       selectedRows.length == 1 ? myModel.getItemAt(selectedRows[0]) : null;
   myEditButton.setEnabled(selectedItem != null && selectedItem.isEditable());
 }
コード例 #20
0
  public JComponent createCenterPanel() {
    List<FileStructureFilter> fileStructureFilters = new ArrayList<FileStructureFilter>();
    List<FileStructureNodeProvider> fileStructureNodeProviders =
        new ArrayList<FileStructureNodeProvider>();
    if (myTreeActionsOwner != null) {
      for (Filter filter : myBaseTreeModel.getFilters()) {
        if (filter instanceof FileStructureFilter) {
          final FileStructureFilter fsFilter = (FileStructureFilter) filter;
          myTreeActionsOwner.setActionIncluded(fsFilter, true);
          fileStructureFilters.add(fsFilter);
        }
      }

      if (myBaseTreeModel instanceof ProvidingTreeModel) {
        for (NodeProvider provider : ((ProvidingTreeModel) myBaseTreeModel).getNodeProviders()) {
          if (provider instanceof FileStructureNodeProvider) {
            fileStructureNodeProviders.add((FileStructureNodeProvider) provider);
          }
        }
      }
    }
    final JPanel panel = new JPanel(new BorderLayout());
    JPanel comboPanel = new JPanel(new GridLayout(0, 2, 0, 0));

    final Shortcut[] F4 =
        ActionManager.getInstance()
            .getAction(IdeActions.ACTION_EDIT_SOURCE)
            .getShortcutSet()
            .getShortcuts();
    final Shortcut[] ENTER = CustomShortcutSet.fromString("ENTER").getShortcuts();
    final CustomShortcutSet shortcutSet = new CustomShortcutSet(ArrayUtil.mergeArrays(F4, ENTER));
    new AnAction() {
      public void actionPerformed(AnActionEvent e) {
        final boolean succeeded = navigateSelectedElement();
        if (succeeded) {
          unregisterCustomShortcutSet(panel);
        }
      }
    }.registerCustomShortcutSet(shortcutSet, panel);

    new AnAction() {
      public void actionPerformed(AnActionEvent e) {
        if (mySpeedSearch != null && mySpeedSearch.isPopupActive()) {
          mySpeedSearch.hidePopup();
        } else {
          myPopup.cancel();
        }
      }
    }.registerCustomShortcutSet(CustomShortcutSet.fromString("ESCAPE"), myTree);

    new ClickListener() {
      @Override
      public boolean onClick(MouseEvent e, int clickCount) {
        navigateSelectedElement();
        return true;
      }
    }.installOn(myTree);

    for (FileStructureFilter filter : fileStructureFilters) {
      addCheckbox(comboPanel, filter);
    }

    for (FileStructureNodeProvider provider : fileStructureNodeProviders) {
      addCheckbox(comboPanel, provider);
    }
    myPreferredWidth = Math.max(comboPanel.getPreferredSize().width, 350);
    panel.add(comboPanel, BorderLayout.NORTH);
    JScrollPane scrollPane = ScrollPaneFactory.createScrollPane(myAbstractTreeBuilder.getTree());
    scrollPane.setBorder(IdeBorderFactory.createBorder(SideBorder.TOP | SideBorder.BOTTOM));
    panel.add(scrollPane, BorderLayout.CENTER);
    panel.add(createSouthPanel(), BorderLayout.SOUTH);
    DataManager.registerDataProvider(
        panel,
        new DataProvider() {
          @Override
          public Object getData(@NonNls String dataId) {
            if (PlatformDataKeys.PROJECT.is(dataId)) {
              return myProject;
            }
            if (LangDataKeys.PSI_ELEMENT.is(dataId)) {
              final Object node =
                  ContainerUtil.getFirstItem(myAbstractTreeBuilder.getSelectedElements());
              if (!(node instanceof FilteringTreeStructure.FilteringNode)) return null;
              return getPsi((FilteringTreeStructure.FilteringNode) node);
            }
            if (LangDataKeys.POSITION_ADJUSTER_POPUP.is(dataId)) {
              return myPopup;
            }
            if (PlatformDataKeys.TREE_EXPANDER.is(dataId)) {
              return myTreeExpander;
            }
            return null;
          }
        });

    return panel;
  }
コード例 #21
0
    @Override
    @SuppressWarnings("deprecation")
    public void show() {
      myFocusTrackback = new FocusTrackback(getDialogWrapper(), getParent(), true);

      final DialogWrapper dialogWrapper = getDialogWrapper();
      boolean isAutoAdjustable = dialogWrapper.isAutoAdjustable();
      Point location = null;
      if (isAutoAdjustable) {
        pack();

        Dimension packedSize = getSize();
        Dimension minSize = getMinimumSize();
        setSize(
            Math.max(packedSize.width, minSize.width), Math.max(packedSize.height, minSize.height));

        setSize(
            (int) (getWidth() * dialogWrapper.getHorizontalStretch()),
            (int) (getHeight() * dialogWrapper.getVerticalStretch()));

        // Restore dialog's size and location

        myDimensionServiceKey = dialogWrapper.getDimensionKey();

        if (myDimensionServiceKey != null) {
          final Project projectGuess =
              CommonDataKeys.PROJECT.getData(DataManager.getInstance().getDataContext(this));
          location =
              DimensionService.getInstance().getLocation(myDimensionServiceKey, projectGuess);
          Dimension size =
              DimensionService.getInstance().getSize(myDimensionServiceKey, projectGuess);
          if (size != null) {
            myInitialSize = new Dimension(size);
            _setSizeForLocation(myInitialSize.width, myInitialSize.height, location);
          }
        }

        if (myInitialSize == null) {
          myInitialSize = getSize();
        }
      }

      if (location == null) {
        location = dialogWrapper.getInitialLocation();
      }

      if (location != null) {
        setLocation(location);
      } else {
        setLocationRelativeTo(getOwner());
      }

      if (isAutoAdjustable) {
        final Rectangle bounds = getBounds();
        ScreenUtil.fitToScreen(bounds);
        setBounds(bounds);
      }
      addWindowListener(
          new WindowAdapter() {
            @Override
            public void windowActivated(WindowEvent e) {
              final DialogWrapper wrapper = getDialogWrapper();
              if (wrapper != null && myFocusTrackback != null) {
                myFocusTrackback.cleanParentWindow();
                myFocusTrackback.registerFocusComponent(
                    new FocusTrackback.ComponentQuery() {
                      @Override
                      public Component getComponent() {
                        return wrapper.getPreferredFocusedComponent();
                      }
                    });
              }
            }

            @Override
            public void windowDeactivated(WindowEvent e) {
              if (!isModal()) {
                final Ref<IdeFocusManager> focusManager = new Ref<IdeFocusManager>(null);
                Project project = getProject();
                if (project != null && !project.isDisposed()) {
                  focusManager.set(getFocusManager());
                  focusManager
                      .get()
                      .doWhenFocusSettlesDown(
                          new Runnable() {
                            @Override
                            public void run() {
                              disposeFocusTrackbackIfNoChildWindowFocused(focusManager.get());
                            }
                          });
                } else {
                  disposeFocusTrackbackIfNoChildWindowFocused(focusManager.get());
                }
              }
            }

            @Override
            public void windowOpened(WindowEvent e) {
              if (!SystemInfo.isMacOSLion) return;
              Window window = e.getWindow();
              if (window instanceof Dialog) {
                ID _native = MacUtil.findWindowForTitle(((Dialog) window).getTitle());
                if (_native != null && _native.intValue() > 0) {
                  // see MacMainFrameDecorator
                  // NSCollectionBehaviorFullScreenAuxiliary = 1 << 8
                  Foundation.invoke(_native, "setCollectionBehavior:", 1 << 8);
                }
              }
            }
          });

      if (Registry.is("actionSystem.fixLostTyping")) {
        final IdeEventQueue queue = IdeEventQueue.getInstance();
        if (queue != null) {
          queue.getKeyEventDispatcher().resetState();
        }

        // if (myProject != null) {
        //   Project project = myProject.get();
        // if (project != null && !project.isDisposed() && project.isInitialized()) {
        // // IdeFocusManager.findInstanceByComponent(this).requestFocus(new
        // MyFocusCommand(dialogWrapper), true);
        // }
        // }
      }

      if (SystemInfo.isMac
          && myProject != null
          && Registry.is("ide.mac.fix.dialog.showing")
          && !dialogWrapper.isModalProgress()) {
        final IdeFrame frame = WindowManager.getInstance().getIdeFrame(myProject.get());
        AppIcon.getInstance().requestFocus(frame);
      }

      setBackground(UIUtil.getPanelBackground());

      final ApplicationEx app = ApplicationManagerEx.getApplicationEx();
      if (app != null && !app.isLoaded() && Splash.BOUNDS != null) {
        final Point loc = getLocation();
        loc.y = Splash.BOUNDS.y + Splash.BOUNDS.height;
        setLocation(loc);
      }
      super.show();
    }
コード例 #22
0
  @NotNull
  @Override
  public RelativePoint guessBestPopupLocation(@NotNull final JComponent component) {
    Point popupMenuPoint = null;
    final Rectangle visibleRect = component.getVisibleRect();
    if (component instanceof JList) { // JList
      JList list = (JList) component;
      int firstVisibleIndex = list.getFirstVisibleIndex();
      int lastVisibleIndex = list.getLastVisibleIndex();
      int[] selectedIndices = list.getSelectedIndices();
      for (int index : selectedIndices) {
        if (firstVisibleIndex <= index && index <= lastVisibleIndex) {
          Rectangle cellBounds = list.getCellBounds(index, index);
          popupMenuPoint =
              new Point(visibleRect.x + visibleRect.width / 4, cellBounds.y + cellBounds.height);
          break;
        }
      }
    } else if (component instanceof JTree) { // JTree
      JTree tree = (JTree) component;
      int[] selectionRows = tree.getSelectionRows();
      if (selectionRows != null) {
        Arrays.sort(selectionRows);
        for (int i = 0; i < selectionRows.length; i++) {
          int row = selectionRows[i];
          Rectangle rowBounds = tree.getRowBounds(row);
          if (visibleRect.contains(rowBounds)) {
            popupMenuPoint = new Point(rowBounds.x + 2, rowBounds.y + rowBounds.height - 1);
            break;
          }
        }
        if (popupMenuPoint == null) { // All selected rows are out of visible rect
          Point visibleCenter =
              new Point(
                  visibleRect.x + visibleRect.width / 2, visibleRect.y + visibleRect.height / 2);
          double minDistance = Double.POSITIVE_INFINITY;
          int bestRow = -1;
          Point rowCenter;
          double distance;
          for (int i = 0; i < selectionRows.length; i++) {
            int row = selectionRows[i];
            Rectangle rowBounds = tree.getRowBounds(row);
            rowCenter =
                new Point(rowBounds.x + rowBounds.width / 2, rowBounds.y + rowBounds.height / 2);
            distance = visibleCenter.distance(rowCenter);
            if (minDistance > distance) {
              minDistance = distance;
              bestRow = row;
            }
          }

          if (bestRow != -1) {
            Rectangle rowBounds = tree.getRowBounds(bestRow);
            tree.scrollRectToVisible(
                new Rectangle(
                    rowBounds.x,
                    rowBounds.y,
                    Math.min(visibleRect.width, rowBounds.width),
                    rowBounds.height));
            popupMenuPoint = new Point(rowBounds.x + 2, rowBounds.y + rowBounds.height - 1);
          }
        }
      }
    } else if (component instanceof JTable) {
      JTable table = (JTable) component;
      int column = table.getColumnModel().getSelectionModel().getLeadSelectionIndex();
      int row =
          Math.max(
              table.getSelectionModel().getLeadSelectionIndex(),
              table.getSelectionModel().getAnchorSelectionIndex());
      Rectangle rect = table.getCellRect(row, column, false);
      if (!visibleRect.intersects(rect)) {
        table.scrollRectToVisible(rect);
      }
      popupMenuPoint = new Point(rect.x, rect.y + rect.height);
    } else if (component instanceof PopupOwner) {
      popupMenuPoint = ((PopupOwner) component).getBestPopupPosition();
    }
    if (popupMenuPoint == null) {
      popupMenuPoint =
          new Point(visibleRect.x + visibleRect.width / 2, visibleRect.y + visibleRect.height / 2);
    }

    return new RelativePoint(component, popupMenuPoint);
  }
コード例 #23
0
  private void paintBackgroundAndFoldingLine(Graphics g, Rectangle clipBounds) {
    Graphics2D g2d = (Graphics2D) g;
    g.setColor(getBackground());
    g.fillRect(
        clipBounds.x,
        clipBounds.y,
        Math.min(clipBounds.width, myFoldingLineX - clipBounds.x),
        clipBounds.height);
    g.setColor(getEditorComponent().getBackground());
    g.fillRect(
        Math.max(clipBounds.x, myFoldingLineX),
        clipBounds.y,
        clipBounds.width - Math.max(0, myFoldingLineX - clipBounds.x),
        clipBounds.height);

    // same as in EditorComponent.paint() method
    EditorCell deepestCell = myEditorComponent.getDeepestSelectedCell();
    if (deepestCell instanceof EditorCell_Label) {
      int selectedCellY = deepestCell.getY();
      int selectedCellHeight =
          deepestCell.getHeight() - deepestCell.getTopInset() - deepestCell.getBottomInset();
      if (g.hitClip(clipBounds.x, selectedCellY, clipBounds.width, selectedCellHeight)) {
        g.setColor(EditorComponent.CARET_ROW_COLOR);
        g.fillRect(clipBounds.x, selectedCellY, clipBounds.width, selectedCellHeight);
        // Drawing folding line
        UIUtil.drawVDottedLine(
            g2d,
            myFoldingLineX,
            clipBounds.y,
            selectedCellY,
            getBackground(),
            EditorColorsManager.getInstance()
                .getGlobalScheme()
                .getColor(EditorColors.TEARLINE_COLOR));
        UIUtil.drawVDottedLine(
            g2d,
            myFoldingLineX,
            selectedCellY,
            selectedCellY + selectedCellHeight,
            EditorComponent.CARET_ROW_COLOR,
            EditorColorsManager.getInstance()
                .getGlobalScheme()
                .getColor(EditorColors.TEARLINE_COLOR));
        UIUtil.drawVDottedLine(
            g2d,
            myFoldingLineX,
            selectedCellY + selectedCellHeight,
            clipBounds.y + clipBounds.height,
            getBackground(),
            EditorColorsManager.getInstance()
                .getGlobalScheme()
                .getColor(EditorColors.TEARLINE_COLOR));
        return;
      }
    }
    // Drawing folding line
    // COLORS: Remove hardcoded color
    UIUtil.drawVDottedLine(
        g2d,
        myFoldingLineX,
        clipBounds.y,
        clipBounds.y + clipBounds.height,
        getBackground(),
        Color.gray);
  }
コード例 #24
0
  /**
   * Generates a comment if possible.
   *
   * <p>It's assumed that this method {@link PsiDocumentManager#commitDocument(Document) syncs} all
   * PSI-document changes during the processing.
   *
   * @param anchor target element for which a comment should be generated
   * @param editor target editor
   * @param commenter commenter to use
   * @param project current project
   */
  private static void generateComment(
      @NotNull PsiElement anchor,
      @NotNull Editor editor,
      @NotNull CodeDocumentationProvider documentationProvider,
      @NotNull CodeDocumentationAwareCommenter commenter,
      @NotNull Project project) {
    Document document = editor.getDocument();
    int commentStartOffset = anchor.getTextRange().getStartOffset();
    int lineStartOffset = document.getLineStartOffset(document.getLineNumber(commentStartOffset));
    if (lineStartOffset > 0 && lineStartOffset < commentStartOffset) {
      // Example:
      //    void test1() {
      //    }
      //    void test2() {
      //       <offset>
      //    }
      // We want to insert the comment at the start of the line where 'test2()' is declared.
      int nonWhiteSpaceOffset =
          CharArrayUtil.shiftBackward(document.getCharsSequence(), commentStartOffset - 1, " \t");
      commentStartOffset = Math.max(nonWhiteSpaceOffset, lineStartOffset);
    }

    int commentBodyRelativeOffset = 0;
    int caretOffsetToSet = -1;
    StringBuilder buffer = new StringBuilder();
    String commentPrefix = commenter.getDocumentationCommentPrefix();
    if (commentPrefix != null) {
      buffer.append(commentPrefix).append("\n");
      commentBodyRelativeOffset += commentPrefix.length() + 1;
    }

    String linePrefix = commenter.getDocumentationCommentLinePrefix();
    if (linePrefix != null) {
      buffer.append(linePrefix);
      commentBodyRelativeOffset += linePrefix.length();
      caretOffsetToSet = commentStartOffset + commentBodyRelativeOffset;
    }
    buffer.append("\n");
    commentBodyRelativeOffset++;

    String commentSuffix = commenter.getDocumentationCommentSuffix();
    if (commentSuffix != null) {
      buffer.append(commentSuffix).append("\n");
    }

    if (buffer.length() <= 0) {
      return;
    }

    document.insertString(commentStartOffset, buffer);
    PsiDocumentManager docManager = PsiDocumentManager.getInstance(project);
    docManager.commitDocument(document);

    Pair<PsiElement, PsiComment> pair = documentationProvider.parseContext(anchor);
    if (pair == null || pair.second == null) {
      return;
    }

    String stub = documentationProvider.generateDocumentationContentStub(pair.second);
    CaretModel caretModel = editor.getCaretModel();
    if (stub != null) {
      int insertionOffset = commentStartOffset + commentBodyRelativeOffset;
      // if (CodeStyleSettingsManager.getSettings(project).JD_ADD_BLANK_AFTER_DESCRIPTION) {
      //  buffer.setLength(0);
      //  if (linePrefix != null) {
      //    buffer.append(linePrefix);
      //  }
      //  buffer.append("\n");
      //  buffer.append(stub);
      //  stub = buffer.toString();
      // }
      document.insertString(insertionOffset, stub);
      docManager.commitDocument(document);
      pair = documentationProvider.parseContext(anchor);
    }

    if (caretOffsetToSet >= 0) {
      caretModel.moveToOffset(caretOffsetToSet);
    }

    if (pair == null || pair.second == null) {
      return;
    }

    int start = Math.min(calcStartReformatOffset(pair.first), calcStartReformatOffset(pair.second));
    int end = pair.second.getTextRange().getEndOffset();

    CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project);
    codeStyleManager.reformatText(anchor.getContainingFile(), start, end);

    int caretOffset = caretModel.getOffset();
    if (caretOffset > 0 && caretOffset <= document.getTextLength()) {
      char c = document.getCharsSequence().charAt(caretOffset - 1);
      if (!StringUtil.isWhiteSpace(c)) {
        document.insertString(caretOffset, " ");
        caretModel.moveToOffset(caretOffset + 1);
      }
    }
  }
コード例 #25
0
  protected String addTextRangeToHistory(
      TextRange textRange, final EditorEx consoleEditor, boolean preserveMarkup) {
    final Document history = myHistoryViewer.getDocument();
    final MarkupModel markupModel = DocumentMarkupModel.forDocument(history, myProject, true);
    if (myPrompt != null) {
      appendToHistoryDocument(history, myPrompt);
    }
    markupModel.addRangeHighlighter(
        history.getTextLength() - StringUtil.length(myPrompt),
        history.getTextLength(),
        HighlighterLayer.SYNTAX,
        ConsoleViewContentType.USER_INPUT.getAttributes(),
        HighlighterTargetArea.EXACT_RANGE);
    final int localStartOffset = textRange.getStartOffset();
    String text;
    EditorHighlighter highlighter;
    if (consoleEditor instanceof EditorWindow) {
      EditorWindow editorWindow = (EditorWindow) consoleEditor;
      EditorColorsScheme scheme = EditorColorsManager.getInstance().getGlobalScheme();
      PsiFile file = editorWindow.getInjectedFile();
      final VirtualFile virtualFile = file.getVirtualFile();
      assert virtualFile != null;
      highlighter = HighlighterFactory.createHighlighter(virtualFile, scheme, getProject());
      String fullText = InjectedLanguageUtil.getUnescapedText(file, null, null);
      highlighter.setText(fullText);
      text = textRange.substring(fullText);
    } else {
      text = consoleEditor.getDocument().getText(textRange);
      highlighter = consoleEditor.getHighlighter();
    }
    // offset can be changed after text trimming after insert due to buffer constraints
    appendToHistoryDocument(history, text);
    int offset = history.getTextLength() - text.length();

    final HighlighterIterator iterator = highlighter.createIterator(localStartOffset);
    final int localEndOffset = textRange.getEndOffset();
    while (!iterator.atEnd()) {
      final int itStart = iterator.getStart();
      if (itStart > localEndOffset) break;
      final int itEnd = iterator.getEnd();
      if (itEnd >= localStartOffset) {
        final int start = Math.max(itStart, localStartOffset) - localStartOffset + offset;
        final int end = Math.min(itEnd, localEndOffset) - localStartOffset + offset;
        markupModel.addRangeHighlighter(
            start,
            end,
            HighlighterLayer.SYNTAX,
            iterator.getTextAttributes(),
            HighlighterTargetArea.EXACT_RANGE);
      }
      iterator.advance();
    }
    if (preserveMarkup) {
      duplicateHighlighters(
          markupModel,
          DocumentMarkupModel.forDocument(consoleEditor.getDocument(), myProject, true),
          offset,
          textRange);
      duplicateHighlighters(markupModel, consoleEditor.getMarkupModel(), offset, textRange);
    }
    if (!text.endsWith("\n")) {
      appendToHistoryDocument(history, "\n");
    }
    return text;
  }
コード例 #26
0
 private static void adjustRows(JTextArea area) {
   area.setRows(Math.max(2, Math.min(3, StringUtil.countChars(area.getText(), '\n') + 1)));
 }