private static void drawSelection(JTable table, int column, Graphics g, final int width) {
   int y = 0;
   final int[] rows = table.getSelectedRows();
   final int height = table.getRowHeight();
   for (int row : rows) {
     final TableCellRenderer renderer = table.getCellRenderer(row, column);
     final Component component =
         renderer.getTableCellRendererComponent(
             table, table.getValueAt(row, column), false, false, row, column);
     g.translate(0, y);
     component.setBounds(0, 0, width, height);
     boolean wasOpaque = false;
     if (component instanceof JComponent) {
       final JComponent j = (JComponent) component;
       if (j.isOpaque()) wasOpaque = true;
       j.setOpaque(false);
     }
     component.paint(g);
     if (wasOpaque) {
       ((JComponent) component).setOpaque(true);
     }
     y += height;
     g.translate(0, -y);
   }
 }
 private static void drawSelection(JTree tree, Graphics g, final int width) {
   int y = 0;
   final int[] rows = tree.getSelectionRows();
   final int height = tree.getRowHeight();
   for (int row : rows) {
     final TreeCellRenderer renderer = tree.getCellRenderer();
     final Object value = tree.getPathForRow(row).getLastPathComponent();
     if (value == null) continue;
     final Component component =
         renderer.getTreeCellRendererComponent(tree, value, false, false, false, row, false);
     if (component.getFont() == null) {
       component.setFont(tree.getFont());
     }
     g.translate(0, y);
     component.setBounds(0, 0, width, height);
     boolean wasOpaque = false;
     if (component instanceof JComponent) {
       final JComponent j = (JComponent) component;
       if (j.isOpaque()) wasOpaque = true;
       j.setOpaque(false);
     }
     component.paint(g);
     if (wasOpaque) {
       ((JComponent) component).setOpaque(true);
     }
     y += height;
     g.translate(0, -y);
   }
 }
  private void assertTabCount(Content content) {
    //        PluginSettingsBean bean = (PluginSettingsBean)
    // SharedObjectPool.getUserData(SharedConstants.PLUGIN_SETTINGS);
    PluginSettingsBean bean = PluginKeys.PLUGIN_SETTINGS.getData();

    if (bean == null) {
      bean = new PluginSettingsBean();
    }

    int max = bean.getNumberOfTabs();

    if (max <= getTabComponent(content).getTabCount()) {
      // remove the oldest tab
      JTabbedPane tabbedPane = getTabComponent(content);
      long lastMin = Long.MAX_VALUE;
      int index = 0;
      for (int i = 0; i < tabbedPane.getTabCount(); i++) {
        JComponent tab = (JComponent) tabbedPane.getTabComponentAt(i);
        Long time = (Long) tab.getClientProperty(CREATE_TIME);
        if (time != null && lastMin < time) {
          lastMin = time;
          index = i;
        }
      }

      tabbedPane.remove(index);
    }
  }
 @Override
 public void actionPerformed(AnActionEvent e) {
   Presentation presentation = e.getPresentation();
   JComponent button = (JComponent) presentation.getClientProperty("button");
   DefaultActionGroup group =
       createPopupActionGroup(myProject, myToDoSettings, myTodoFilterConsumer);
   ActionPopupMenu popupMenu =
       ActionManager.getInstance().createActionPopupMenu(ActionPlaces.TODO_VIEW_TOOLBAR, group);
   popupMenu.getComponent().show(button, button.getWidth(), 0);
 }
  @Nullable
  private Editor validateCurrentEditor() {
    Component focusOwner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
    if (focusOwner instanceof JComponent) {
      final JComponent jComponent = (JComponent) focusOwner;
      if (jComponent.getClientProperty("AuxEditorComponent") != null)
        return null; // Hack for EditorSearchComponent
    }

    return myEditor;
  }
  private void showAntView(boolean treeView) {
    AntOutputView oldView = getOutputView(treeView);
    AntOutputView newView = getOutputView(!treeView);
    myCurrentView = newView;
    myMessagePanel.remove(oldView.getComponent());
    myMessagePanel.add(newView.getComponent(), BorderLayout.CENTER);
    myMessagePanel.validate();

    JComponent component = IdeFocusTraversalPolicy.getPreferredFocusedComponent(myMessagePanel);
    component.requestFocus();
    repaint();
  }
  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;
      }
    };
  }
  /**
   * Sets current tool windows pane (panel where all tool windows are located). If <code>
   * toolWindowsPane</code> is <code>null</code> then the method just removes the current tool
   * windows pane.
   */
  final void setToolWindowsPane(@Nullable final ToolWindowsPane toolWindowsPane) {
    final JComponent contentPane = (JComponent) getContentPane();
    if (myToolWindowsPane != null) {
      contentPane.remove(myToolWindowsPane);
    }

    hideWelcomeScreen(contentPane);

    myToolWindowsPane = toolWindowsPane;
    if (myToolWindowsPane != null) {
      contentPane.add(myToolWindowsPane, BorderLayout.CENTER);
    } else if (!myApplication.isDisposeInProgress()) {
      showWelcomeScreen();
    }

    contentPane.revalidate();
  }
 // Event forwarding. We need it if user does press-and-drag gesture for opening popup and
 // choosing item there.
 // It works in JComboBox, here we provide the same behavior
 private void dispatchEventToPopup(MouseEvent e) {
   if (myPopup != null && myPopup.isVisible()) {
     JComponent content = myPopup.getContent();
     Rectangle rectangle = content.getBounds();
     Point location = rectangle.getLocation();
     SwingUtilities.convertPointToScreen(location, content);
     Point eventPoint = e.getLocationOnScreen();
     rectangle.setLocation(location);
     if (rectangle.contains(eventPoint)) {
       MouseEvent event =
           SwingUtilities.convertMouseEvent(e.getComponent(), e, myPopup.getContent());
       Component component =
           SwingUtilities.getDeepestComponentAt(content, event.getX(), event.getY());
       if (component != null) component.dispatchEvent(event);
     }
   }
 }
 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;
 }
Esempio n. 11
0
 private void hideWelcomeScreen(JComponent contentPane) {
   if (myWelcomePane != null) {
     Disposer.dispose(myWelcomeScreen);
     contentPane.remove(myWelcomePane);
     myWelcomeScreen = null;
     myWelcomePane = null;
     updateToolbarVisibility();
   }
 }
  @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;
  }
  @Nullable
  private static JScrollBar findHorizontalScrollBar(Component c) {
    if (c == null) return null;
    if (c instanceof JScrollPane) {
      return ((JScrollPane) c).getHorizontalScrollBar();
    }

    if (isDiagramViewComponent(c)) {
      final JComponent view = (JComponent) c;
      for (int i = 0; i < view.getComponentCount(); i++) {
        if (view.getComponent(i) instanceof JScrollBar) {
          final JScrollBar scrollBar = (JScrollBar) view.getComponent(i);
          if (scrollBar.getOrientation() == Adjustable.HORIZONTAL) {
            return scrollBar;
          }
        }
      }
    }
    return findHorizontalScrollBar(c.getParent());
  }
  protected JComponent createCenterPanel() {
    myList.setCellRenderer(new CvsListCellRenderer());

    myCenterPanelLayout.setHgap(6);

    myCenterPanel.add(createActionsPanel(), BorderLayout.NORTH);
    JComponent listPanel = createListPanel();

    myCenterPanel.add(listPanel, BorderLayout.CENTER);
    myCenterPanel.add(createCvsConfigurationPanel(), BorderLayout.EAST);
    myCenterPanel.add(new JSeparator(JSeparator.HORIZONTAL), BorderLayout.SOUTH);

    myList.setModel(myModel);

    addSelectionListener();

    int minWidth = myList.getFontMetrics(myList.getFont()).stringWidth(SAMPLE_CVSROOT) + 40;
    Dimension minSize = new Dimension(minWidth, myList.getMaximumSize().height);
    listPanel.setMinimumSize(minSize);
    listPanel.setPreferredSize(minSize);
    return myCenterPanel;
  }
Esempio n. 15
0
  private void onSelectionChanged() {
    Set<AbstractTreeNode> nodes = myBuilder.getSelectedElements(AbstractTreeNode.class);
    if (nodes.size() != 1) {
      showMessageLabel(EMPTY_SELECTION_MESSAGE);
      myLastSelection = null;
      return;
    }

    AbstractTreeNode<?> node = nodes.iterator().next();
    if (Comparing.equal(node, myLastSelection)) {
      return;
    }

    myLastSelection = node;
    if (node instanceof ServersTreeStructure.LogProvidingNode) {
      ServersTreeStructure.LogProvidingNode logNode = (ServersTreeStructure.LogProvidingNode) node;
      LoggingHandlerImpl loggingHandler = logNode.getLoggingHandler();
      if (loggingHandler != null) {
        String cardName = logNode.getLogId();
        JComponent oldComponent = myLogComponents.get(cardName);
        JComponent logComponent = loggingHandler.getConsole().getComponent();
        if (!logComponent.equals(oldComponent)) {
          myLogComponents.put(cardName, logComponent);
          if (oldComponent != null) {
            myPropertiesPanel.remove(oldComponent);
          }
          myPropertiesPanel.add(cardName, logComponent);
        }
        myPropertiesPanelLayout.show(myPropertiesPanel, cardName);
      } else {
        showMessageLabel("");
      }
    } else if (node instanceof ServersTreeStructure.RemoteServerNode) {
      updateServerDetails((ServersTreeStructure.RemoteServerNode) node);
    } else {
      showMessageLabel("");
    }
  }
  GitManualPushToBranch(
      @NotNull Collection<GitRepository> repositories, @NotNull final Runnable performOnRefresh) {
    super();
    myRepositories = repositories;

    myManualPush = new JCheckBox("Push current branch to alternative branch: ", false);
    myManualPush.setMnemonic('b');

    myDestBranchTextField = new JTextField(20);

    myComment =
        new JBLabel("This will apply to all selected repositories", UIUtil.ComponentStyle.SMALL);

    myRefreshAction =
        new GitPushLogRefreshAction() {
          @Override
          public void actionPerformed(AnActionEvent e) {
            performOnRefresh.run();
          }
        };
    myRefreshButton =
        new ActionButton(
            myRefreshAction,
            myRefreshAction.getTemplatePresentation(),
            myRefreshAction.getTemplatePresentation().getText(),
            ActionToolbar.DEFAULT_MINIMUM_BUTTON_SIZE);
    myRefreshButton.setFocusable(true);
    final ShortcutSet shortcutSet =
        ActionManager.getInstance().getAction(IdeActions.ACTION_REFRESH).getShortcutSet();
    myRefreshAction.registerCustomShortcutSet(shortcutSet, myRefreshButton);

    myRemoteSelector = new RemoteSelector(getRemotesWithCommonNames(repositories));
    myRemoteSelectorComponent = myRemoteSelector.createComponent();

    setDefaultComponentsEnabledState(myManualPush.isSelected());
    myManualPush.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            boolean isManualPushSelected = myManualPush.isSelected();
            setDefaultComponentsEnabledState(isManualPushSelected);
            if (isManualPushSelected) {
              myDestBranchTextField.requestFocus();
              myDestBranchTextField.selectAll();
            }
          }
        });

    layoutComponents();
  }
Esempio n. 17
0
 private void updateToolbarVisibility() {
   myToolbar.setVisible(myUISettings.SHOW_MAIN_TOOLBAR && myWelcomeScreen == null);
 }
  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;
  }
Esempio n. 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;
  }
  @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);
  }
  @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];
  }
 protected void requestFocusInternal() {
   JComponent component = getPreferredFocusedComponent();
   if (component != null) component.requestFocusInWindow();
 }
    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());
            }
          });
    }
Esempio n. 24
0
  ImageEditorUI(@Nullable ImageEditor editor) {
    this.editor = editor;

    Options options = OptionsManager.getInstance().getOptions();
    EditorOptions editorOptions = options.getEditorOptions();
    options.addPropertyChangeListener(optionsChangeListener);

    final PsiActionSupportFactory factory = PsiActionSupportFactory.getInstance();
    if (factory != null && editor != null) {
      copyPasteSupport =
          factory.createPsiBasedCopyPasteSupport(
              editor.getProject(),
              this,
              new PsiActionSupportFactory.PsiElementSelector() {
                public PsiElement[] getSelectedElements() {
                  PsiElement[] data = LangDataKeys.PSI_ELEMENT_ARRAY.getData(ImageEditorUI.this);
                  return data == null ? PsiElement.EMPTY_ARRAY : data;
                }
              });
    } else {
      copyPasteSupport = null;
    }

    deleteProvider = factory == null ? null : factory.createPsiBasedDeleteProvider();

    ImageDocument document = imageComponent.getDocument();
    document.addChangeListener(changeListener);

    // Set options
    TransparencyChessboardOptions chessboardOptions =
        editorOptions.getTransparencyChessboardOptions();
    GridOptions gridOptions = editorOptions.getGridOptions();
    imageComponent.setTransparencyChessboardCellSize(chessboardOptions.getCellSize());
    imageComponent.setTransparencyChessboardWhiteColor(chessboardOptions.getWhiteColor());
    imageComponent.setTransparencyChessboardBlankColor(chessboardOptions.getBlackColor());
    imageComponent.setGridLineZoomFactor(gridOptions.getLineZoomFactor());
    imageComponent.setGridLineSpan(gridOptions.getLineSpan());
    imageComponent.setGridLineColor(gridOptions.getLineColor());

    // Create layout
    ImageContainerPane view = new ImageContainerPane(imageComponent);
    view.addMouseListener(new EditorMouseAdapter());
    view.addMouseListener(new FocusRequester());

    JScrollPane scrollPane = ScrollPaneFactory.createScrollPane(view);
    scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
    scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);

    // Zoom by wheel listener
    scrollPane.addMouseWheelListener(wheelAdapter);

    // Construct UI
    setLayout(new BorderLayout());

    ActionManager actionManager = ActionManager.getInstance();
    ActionGroup actionGroup =
        (ActionGroup) actionManager.getAction(ImageEditorActions.GROUP_TOOLBAR);
    ActionToolbar actionToolbar =
        actionManager.createActionToolbar(ImageEditorActions.ACTION_PLACE, actionGroup, true);

    // Make sure toolbar is 'ready' before it's added to component hierarchy
    // to prevent ActionToolbarImpl.updateActionsImpl(boolean, boolean) from increasing popup size
    // unnecessarily
    actionToolbar.updateActionsImmediately();

    actionToolbar.setTargetComponent(this);

    JComponent toolbarPanel = actionToolbar.getComponent();
    toolbarPanel.addMouseListener(new FocusRequester());

    JLabel errorLabel =
        new JLabel(
            ImagesBundle.message("error.broken.image.file.format"),
            Messages.getErrorIcon(),
            SwingConstants.CENTER);

    JPanel errorPanel = new JPanel(new BorderLayout());
    errorPanel.add(errorLabel, BorderLayout.CENTER);

    contentPanel = new JPanel(new CardLayout());
    contentPanel.add(scrollPane, IMAGE_PANEL);
    contentPanel.add(errorPanel, ERROR_PANEL);

    JPanel topPanel = new JPanel(new BorderLayout());
    topPanel.add(toolbarPanel, BorderLayout.WEST);
    infoLabel = new JLabel((String) null, SwingConstants.RIGHT);
    infoLabel.setBorder(IdeBorderFactory.createEmptyBorder(0, 0, 0, 2));
    topPanel.add(infoLabel, BorderLayout.EAST);

    add(topPanel, BorderLayout.NORTH);
    add(contentPanel, BorderLayout.CENTER);

    updateInfo();
  }