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();
  }
  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 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 ActiveComponent createPinButton(
      final UsageInfoToUsageConverter.TargetElementsDescriptor descriptor,
      final UsageViewImpl usageView,
      final FindUsagesOptions options,
      final JBPopup[] popup,
      DefaultActionGroup pinGroup) {
    final AnAction pinAction =
        new AnAction(
            "Open Find Usages Toolwindow",
            "Show all usages in a separate toolwindow",
            AllIcons.General.AutohideOff) {
          {
            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.SearchData data = new FindUsagesManager.SearchData();
            data.myOptions = options;
            List<SmartPsiElementPointer<PsiElement>> plist = descriptor.getAllElementPointers();

            data.myElements = plist.toArray(new SmartPsiElementPointer[plist.size()]);
            findUsagesManager.rerunAndRecallFromHistory(data);
          }
        };
    pinGroup.add(pinAction);
    final ActionToolbar pinToolbar =
        ActionManager.getInstance()
            .createActionToolbar(ActionPlaces.USAGE_VIEW_TOOLBAR, pinGroup, true);
    pinToolbar.setReservePlaceAutoPopupIcon(false);
    final JComponent pinToolBar = pinToolbar.getComponent();
    pinToolBar.setBorder(null);
    pinToolBar.setOpaque(false);

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

      @Override
      public JComponent getComponent() {
        return pinToolBar;
      }
    };
  }
  public boolean isToDrawMacCorner() {
    if (!SystemInfo.isMac || myComponent.getComponentCount() <= 0) {
      return false;
    }

    if (myComponent.getComponentCount() > 0) {
      Component component = myComponent.getComponent(0);
      if (component instanceof JComponent
          && Boolean.TRUE.equals(((JComponent) component).getClientProperty(SUPPRESS_MAC_CORNER))) {
        return false;
      }
    }

    return true;
  }
  private void _requestFocus() {
    if (!myFocusable) return;

    if (myPreferredFocusedComponent != null) {
      myPreferredFocusedComponent.requestFocus();
    }
  }
 private static Component setLabelColors(
     final Component label, final JTable table, final boolean isSelected, final int row) {
   if (label instanceof JComponent) {
     ((JComponent) label).setOpaque(true);
   }
   label.setForeground(isSelected ? table.getSelectionForeground() : table.getForeground());
   label.setBackground(isSelected ? table.getSelectionBackground() : table.getBackground());
   return label;
 }
 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;
 }
 public Component getTableCellRendererComponent(
     JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
   Component component =
       myDelegate.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
   component.setEnabled(ElementsChooser.this.isEnabled());
   if (component instanceof JComponent) {
     ((JComponent) component).setBorder(null);
   }
   return component;
 }
  @NotNull
  private JComponent createHintComponent(
      @NotNull String text,
      @NotNull final FindUsagesHandler handler,
      @NotNull final RelativePoint popupPosition,
      final Editor editor,
      @NotNull final Runnable cancelAction,
      final int maxUsages,
      @NotNull final FindUsagesOptions options) {
    JComponent label =
        HintUtil.createInformationLabel(suggestSecondInvocation(options, handler, text + "&nbsp;"));
    InplaceButton button =
        createSettingsButton(handler, popupPosition, editor, maxUsages, cancelAction);

    JPanel panel =
        new JPanel(new BorderLayout()) {
          @Override
          public void addNotify() {
            mySearchEverywhereRunnable =
                new Runnable() {
                  @Override
                  public void run() {
                    searchEverywhere(options, handler, editor, popupPosition, maxUsages);
                  }
                };
            super.addNotify();
          }

          @Override
          public void removeNotify() {
            mySearchEverywhereRunnable = null;
            super.removeNotify();
          }
        };
    button.setBackground(label.getBackground());
    panel.setBackground(label.getBackground());
    label.setOpaque(false);
    label.setBorder(null);
    panel.setBorder(HintUtil.createHintBorder());
    panel.add(label, BorderLayout.CENTER);
    panel.add(button, BorderLayout.EAST);
    return panel;
  }
  public void cancel(InputEvent e) {
    if (isDisposed()) return;

    if (myPopup != null) {
      if (!canClose()) {
        return;
      }
      storeDimensionSize(myContent.getSize());
      if (myUseDimServiceForXYLocation) {
        final JRootPane root = myComponent.getRootPane();
        if (root != null) {
          final Container popupWindow = root.getParent();
          if (popupWindow != null && popupWindow.isShowing()) {
            storeLocation(popupWindow.getLocationOnScreen());
          }
        }
      }

      if (e instanceof MouseEvent) {
        IdeEventQueue.getInstance().blockNextEvents(((MouseEvent) e));
      }

      myPopup.hide(false);

      if (ApplicationManagerEx.getApplicationEx() != null) {
        StackingPopupDispatcher.getInstance().onPopupHidden(this);
      }

      if (myInStack) {
        myFocusTrackback.setForcedRestore(!myOk && myFocusable);
        myFocusTrackback.restoreFocus();
      }

      disposePopup();

      if (myListeners != null) {
        for (JBPopupListener each : myListeners) {
          each.onClosed(new LightweightWindowEvent(this, myOk));
        }
      }
    }

    Disposer.dispose(this, false);
  }
    private void installFocusable(
        final JComponent comp,
        final AnAction action,
        final int prevKeyCode,
        final int nextKeyCode,
        final boolean focusListOnLeft) {
      comp.setFocusable(true);
      comp.setFocusTraversalKeysEnabled(true);
      comp.addKeyListener(
          new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
              final JList list =
                  UIUtil.findComponentOfType(FlatWelcomeFrame.this.getComponent(), JList.class);
              if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                InputEvent event = e;
                if (e.getComponent() instanceof JComponent) {
                  ActionLink link =
                      UIUtil.findComponentOfType((JComponent) e.getComponent(), ActionLink.class);
                  if (link != null) {
                    event =
                        new MouseEvent(
                            link,
                            MouseEvent.MOUSE_CLICKED,
                            e.getWhen(),
                            e.getModifiers(),
                            0,
                            0,
                            1,
                            false,
                            MouseEvent.BUTTON1);
                  }
                }
                action.actionPerformed(
                    AnActionEvent.createFromAnAction(
                        action,
                        event,
                        ActionPlaces.WELCOME_SCREEN,
                        DataManager.getInstance().getDataContext()));
              } else if (e.getKeyCode() == prevKeyCode) {
                focusPrev(comp);
              } else if (e.getKeyCode() == nextKeyCode) {
                focusNext(comp);
              } else if (e.getKeyCode() == KeyEvent.VK_LEFT) {
                if (focusListOnLeft) {
                  if (list != null) {
                    list.requestFocus();
                  }
                } else {
                  focusPrev(comp);
                }
              } else if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
                focusNext(comp);
              }
            }
          });
      comp.addFocusListener(
          new FocusListener() {
            @Override
            public void focusGained(FocusEvent e) {
              comp.setOpaque(true);
              comp.setBackground(getActionLinkSelectionColor());
            }

            @Override
            public void focusLost(FocusEvent e) {
              comp.setOpaque(false);
              comp.setBackground(getMainBackground());
            }
          });
    }
  protected JComponent createCenterPanel() {
    JPanel panel = new MyPanel();

    myUiUpdater = new MergingUpdateQueue("FileChooserUpdater", 200, false, panel);
    Disposer.register(myDisposable, myUiUpdater);
    new UiNotifyConnector(panel, myUiUpdater);

    panel.setBorder(JBUI.Borders.empty());

    createTree();

    final DefaultActionGroup group = createActionGroup();
    ActionToolbar toolBar =
        ActionManager.getInstance().createActionToolbar(ActionPlaces.UNKNOWN, group, true);
    toolBar.setTargetComponent(panel);

    final JPanel toolbarPanel = new JPanel(new BorderLayout());
    toolbarPanel.add(toolBar.getComponent(), BorderLayout.CENTER);

    myTextFieldAction =
        new TextFieldAction() {
          public void linkSelected(final LinkLabel aSource, final Object aLinkData) {
            toggleShowTextField();
          }
        };
    toolbarPanel.add(myTextFieldAction, BorderLayout.EAST);

    myPathTextFieldWrapper = new JPanel(new BorderLayout());
    myPathTextFieldWrapper.setBorder(JBUI.Borders.emptyBottom(2));
    myPathTextField =
        new FileTextFieldImpl.Vfs(
            FileChooserFactoryImpl.getMacroMap(),
            getDisposable(),
            new LocalFsFinder.FileChooserFilter(myChooserDescriptor, myFileSystemTree)) {
          protected void onTextChanged(final String newValue) {
            myUiUpdater.cancelAllUpdates();
            updateTreeFromPath(newValue);
          }
        };
    Disposer.register(myDisposable, myPathTextField);
    myPathTextFieldWrapper.add(myPathTextField.getField(), BorderLayout.CENTER);
    if (getRecentFiles().length > 0) {
      myPathTextFieldWrapper.add(createHistoryButton(), BorderLayout.EAST);
    }

    myNorthPanel = new JPanel(new BorderLayout());
    myNorthPanel.add(toolbarPanel, BorderLayout.NORTH);

    updateTextFieldShowing();

    panel.add(myNorthPanel, BorderLayout.NORTH);

    registerMouseListener(group);

    JScrollPane scrollPane = ScrollPaneFactory.createScrollPane(myFileSystemTree.getTree());
    // scrollPane.setBorder(BorderFactory.createLineBorder(new Color(148, 154, 156)));
    panel.add(scrollPane, BorderLayout.CENTER);
    panel.setPreferredSize(JBUI.size(400));

    panel.add(
        new JLabel(
            "<html><center><small><font color=gray>Drag and drop a file into the space above to quickly locate it in the tree.</font></small></center></html>",
            SwingConstants.CENTER),
        BorderLayout.SOUTH);

    ApplicationManager.getApplication()
        .getMessageBus()
        .connect(getDisposable())
        .subscribe(
            ApplicationActivationListener.TOPIC,
            new ApplicationActivationListener.Adapter() {
              @Override
              public void applicationActivated(IdeFrame ideFrame) {
                ((SaveAndSyncHandlerImpl) SaveAndSyncHandler.getInstance())
                    .maybeRefresh(ModalityState.current());
              }
            });

    return panel;
  }
  @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];
  }
 public static void suppressMacCornerFor(JComponent popupComponent) {
   popupComponent.putClientProperty(SUPPRESS_MAC_CORNER, Boolean.TRUE);
 }
  private void addListeners() {
    myEditor
        .getDocument()
        .addDocumentListener(
            new DocumentAdapter() {
              @Override
              public void documentChanged(DocumentEvent e) {
                if (!myChangeGuard && !myFinishing) {
                  hide();
                }
              }
            },
            this);

    final CaretListener caretListener =
        new CaretAdapter() {
          @Override
          public void caretPositionChanged(CaretEvent e) {
            if (!myChangeGuard && !myFinishing) {
              hide();
            }
          }
        };
    final SelectionListener selectionListener =
        new SelectionListener() {
          @Override
          public void selectionChanged(final SelectionEvent e) {
            if (!myChangeGuard && !myFinishing) {
              hide();
            }
          }
        };
    final EditorMouseListener mouseListener =
        new EditorMouseAdapter() {
          @Override
          public void mouseClicked(EditorMouseEvent e) {
            e.consume();
            hide();
          }
        };

    myEditor.getCaretModel().addCaretListener(caretListener);
    myEditor.getSelectionModel().addSelectionListener(selectionListener);
    myEditor.addEditorMouseListener(mouseListener);
    Disposer.register(
        this,
        new Disposable() {
          @Override
          public void dispose() {
            myEditor.getCaretModel().removeCaretListener(caretListener);
            myEditor.getSelectionModel().removeSelectionListener(selectionListener);
            myEditor.removeEditorMouseListener(mouseListener);
          }
        });

    JComponent editorComponent = myEditor.getContentComponent();
    if (editorComponent.isShowing()) {
      Disposer.register(
          this,
          new UiNotifyConnector(
              editorComponent,
              new Activatable() {
                @Override
                public void showNotify() {}

                @Override
                public void hideNotify() {
                  hideLookup(false);
                }
              }));
    }

    myList.addListSelectionListener(
        new ListSelectionListener() {
          private LookupElement oldItem = null;

          @Override
          public void valueChanged(@NotNull ListSelectionEvent e) {
            if (!myUpdating) {
              final LookupElement item = getCurrentItem();
              fireCurrentItemChanged(oldItem, item);
              oldItem = item;
            }
          }
        });

    new ClickListener() {
      @Override
      public boolean onClick(@NotNull MouseEvent e, int clickCount) {
        setFocusDegree(FocusDegree.FOCUSED);
        markSelectionTouched();

        if (clickCount == 2) {
          CommandProcessor.getInstance()
              .executeCommand(
                  myProject,
                  new Runnable() {
                    @Override
                    public void run() {
                      finishLookup(NORMAL_SELECT_CHAR);
                    }
                  },
                  "",
                  null);
        }
        return true;
      }
    }.installOn(myList);
  }
  private void updateViewerForSelection() {
    if (myAllContents.isEmpty()) return;
    String fullString = getSelectedText();

    if (myViewer != null) {
      EditorFactory.getInstance().releaseEditor(myViewer);
    }

    if (myUseIdeaEditor) {
      myViewer = createIdeaEditor(fullString);
      JComponent component = myViewer.getComponent();
      component.setPreferredSize(JBUI.size(300, 500));
      mySplitter.setSecondComponent(component);
    } else {
      final JTextArea textArea = new JTextArea(fullString);
      textArea.setRows(3);
      textArea.setWrapStyleWord(true);
      textArea.setLineWrap(true);
      textArea.setSelectionStart(0);
      textArea.setSelectionEnd(textArea.getText().length());
      textArea.setEditable(false);
      mySplitter.setSecondComponent(ScrollPaneFactory.createScrollPane(textArea));
    }
    mySplitter.revalidate();
  }