@Override
 public Object previous() {
   final int i = myCurrentIndex - 1;
   if (i < 0) throw new NoSuchElementException();
   final Object previous = myElements[mySpeedSearch.convertIndexToModel(i)];
   myCurrentIndex = i;
   return previous;
 }
    public ViewIterator(@NotNull final SpeedSearchBase speedSearch, final int startIndex) {
      mySpeedSearch = speedSearch;
      myCurrentIndex = startIndex;
      myElements = speedSearch.getAllElements();

      if (startIndex < 0 || startIndex > myElements.length) {
        throw new IndexOutOfBoundsException("Index: " + startIndex);
      }
    }
Example #3
0
    @Override
    public void update(AnActionEvent e) {
      Component focusOwner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
      e.getPresentation().setEnabled(false);
      if (focusOwner instanceof JComponent
          && SpeedSearchBase.hasActiveSpeedSearch((JComponent) focusOwner)) {
        return;
      }

      if (StackingPopupDispatcher.getInstance().isPopupFocused()) return;

      if (focusOwner instanceof JTree) {
        JTree tree = (JTree) focusOwner;
        if (!tree.isEditing()) {
          e.getPresentation().setEnabled(true);
        }
      } else if (focusOwner instanceof JTable) {
        JTable table = (JTable) focusOwner;
        if (!table.isEditing()) {
          e.getPresentation().setEnabled(true);
        }
      }
    }
 @Override
 public Object next() {
   if (myCurrentIndex + 1 > myElements.length) throw new NoSuchElementException();
   return myElements[mySpeedSearch.convertIndexToModel(myCurrentIndex++)];
 }
  public ProcessedModulesTable(final Project project) {
    super(new BorderLayout());

    myTableModel = new MyTableModel(project);
    myTable = new JBTable(myTableModel);
    myTable.getEmptyText().setText("No modules configured");

    // myTable.setShowGrid(false);
    myTable.setIntercellSpacing(JBUI.emptySize());
    myTable.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN);
    myTable.setColumnSelectionAllowed(false);

    final TableColumnModel columnModel = myTable.getColumnModel();

    final TableColumn dirNameColumn = columnModel.getColumn(myTableModel.DIRNAME_COLUMN_INDEX);
    final String title = "Generated Sources Directory Name";
    dirNameColumn.setHeaderValue(title);
    final JTableHeader tableHeader = myTable.getTableHeader();
    final FontMetrics metrics = tableHeader.getFontMetrics(tableHeader.getFont());
    final int preferredWidth = metrics.stringWidth(title) + 12;
    dirNameColumn.setPreferredWidth(preferredWidth);
    dirNameColumn.setMaxWidth(preferredWidth + 20);
    dirNameColumn.setCellRenderer(new MyElementColumnCellRenderer());

    final TableColumn moduleColumn = columnModel.getColumn(myTableModel.ELEMENT_COLUMN_INDEX);
    moduleColumn.setHeaderValue("Module");
    moduleColumn.setCellRenderer(new MyElementColumnCellRenderer());

    final JPanel panel =
        ToolbarDecorator.createDecorator(myTable)
            .disableUpDownActions()
            .setPreferredSize(JBUI.size(100, 155))
            .createPanel();
    add(panel, BorderLayout.CENTER);

    final SpeedSearchBase<JBTable> speedSearch =
        new SpeedSearchBase<JBTable>(myTable) {
          public int getSelectedIndex() {
            return myTable.getSelectedRow();
          }

          @Override
          protected int convertIndexToModel(int viewIndex) {
            return myTable.convertRowIndexToModel(viewIndex);
          }

          public Object[] getAllElements() {
            final int count = myTableModel.getRowCount();
            Object[] elements = new Object[count];
            for (int idx = 0; idx < count; idx++) {
              elements[idx] = myTableModel.getModuleAt(idx);
            }
            return elements;
          }

          public String getElementText(Object element) {
            return ((Module) element).getName()
                + " ("
                + FileUtil.toSystemDependentName(((Module) element).getModuleFilePath())
                + ")";
          }

          public void selectElement(Object element, String selectedText) {
            final int count = myTableModel.getRowCount();
            for (int row = 0; row < count; row++) {
              if (element.equals(myTableModel.getModuleAt(row))) {
                final int viewRow = myTable.convertRowIndexToView(row);
                myTable.getSelectionModel().setSelectionInterval(viewRow, viewRow);
                TableUtil.scrollSelectionToVisible(myTable);
                break;
              }
            }
          }
        };
    speedSearch.setComparator(new SpeedSearchComparator(false));
  }
  private void showElementUsages(
      @NotNull final FindUsagesHandler handler,
      final Editor editor,
      @NotNull final RelativePoint popupPosition,
      final int maxUsages,
      @NotNull final FindUsagesOptions options) {
    ApplicationManager.getApplication().assertIsDispatchThread();
    final UsageViewSettings usageViewSettings = UsageViewSettings.getInstance();
    final UsageViewSettings savedGlobalSettings = new UsageViewSettings();

    savedGlobalSettings.loadState(usageViewSettings);
    usageViewSettings.loadState(myUsageViewSettings);

    final Project project = handler.getProject();
    UsageViewManager manager = UsageViewManager.getInstance(project);
    FindUsagesManager findUsagesManager =
        ((FindManagerImpl) FindManager.getInstance(project)).getFindUsagesManager();
    final UsageViewPresentation presentation =
        findUsagesManager.createPresentation(handler, options);
    presentation.setDetachedMode(true);
    final UsageViewImpl usageView =
        (UsageViewImpl)
            manager.createUsageView(UsageTarget.EMPTY_ARRAY, Usage.EMPTY_ARRAY, presentation, null);

    Disposer.register(
        usageView,
        new Disposable() {
          @Override
          public void dispose() {
            myUsageViewSettings.loadState(usageViewSettings);
            usageViewSettings.loadState(savedGlobalSettings);
          }
        });

    final List<Usage> usages = new ArrayList<Usage>();
    final Set<UsageNode> visibleNodes = new LinkedHashSet<UsageNode>();
    UsageInfoToUsageConverter.TargetElementsDescriptor descriptor =
        new UsageInfoToUsageConverter.TargetElementsDescriptor(
            handler.getPrimaryElements(), handler.getSecondaryElements());

    final MyTable table = new MyTable();
    final AsyncProcessIcon processIcon = new AsyncProcessIcon("xxx");
    boolean hadMoreSeparator = visibleNodes.remove(MORE_USAGES_SEPARATOR_NODE);
    if (hadMoreSeparator) {
      usages.add(MORE_USAGES_SEPARATOR);
      visibleNodes.add(MORE_USAGES_SEPARATOR_NODE);
    }

    addUsageNodes(usageView.getRoot(), usageView, new ArrayList<UsageNode>());

    TableScrollingUtil.installActions(table);

    final List<UsageNode> data = collectData(usages, visibleNodes, usageView, presentation);
    setTableModel(table, usageView, data);

    SpeedSearchBase<JTable> speedSearch = new MySpeedSearch(table);
    speedSearch.setComparator(new SpeedSearchComparator(false));

    final JBPopup popup =
        createUsagePopup(
            usages,
            descriptor,
            visibleNodes,
            handler,
            editor,
            popupPosition,
            maxUsages,
            usageView,
            options,
            table,
            presentation,
            processIcon,
            hadMoreSeparator);

    Disposer.register(popup, usageView);

    // show popup only if find usages takes more than 300ms, otherwise it would flicker needlessly
    Alarm alarm = new Alarm(usageView);
    alarm.addRequest(
        new Runnable() {
          @Override
          public void run() {
            showPopupIfNeedTo(popup, popupPosition);
          }
        },
        300);

    final PingEDT pingEDT =
        new PingEDT(
            "Rebuild popup in EDT",
            new Condition<Object>() {
              @Override
              public boolean value(Object o) {
                return popup.isDisposed();
              }
            },
            100,
            new Runnable() {
              @Override
              public void run() {
                if (popup.isDisposed()) return;

                final List<UsageNode> nodes = new ArrayList<UsageNode>();
                List<Usage> copy;
                synchronized (usages) {
                  // open up popup as soon as several usages 've been found
                  if (!popup.isVisible()
                      && (usages.size() <= 1 || !showPopupIfNeedTo(popup, popupPosition))) {
                    return;
                  }
                  addUsageNodes(usageView.getRoot(), usageView, nodes);
                  copy = new ArrayList<Usage>(usages);
                }

                rebuildPopup(
                    usageView,
                    copy,
                    nodes,
                    table,
                    popup,
                    presentation,
                    popupPosition,
                    !processIcon.isDisposed());
              }
            });

    final MessageBusConnection messageBusConnection = project.getMessageBus().connect(usageView);
    messageBusConnection.subscribe(
        UsageFilteringRuleProvider.RULES_CHANGED,
        new Runnable() {
          @Override
          public void run() {
            pingEDT.ping();
          }
        });

    Processor<Usage> collect =
        new Processor<Usage>() {
          private final UsageTarget[] myUsageTarget = {
            new PsiElement2UsageTargetAdapter(handler.getPsiElement())
          };

          @Override
          public boolean process(@NotNull Usage usage) {
            synchronized (usages) {
              if (!filter.shouldShow(usage)) return true;
              if (visibleNodes.size() >= maxUsages) return false;
              if (UsageViewManager.isSelfUsage(usage, myUsageTarget)) {
                return true;
              }

              Usage usageToAdd = transform(usage);
              if (usageToAdd == null) return true;

              UsageNode node = usageView.doAppendUsage(usageToAdd);
              usages.add(usageToAdd);
              if (node != null) {
                visibleNodes.add(node);
                boolean continueSearch = true;
                if (visibleNodes.size() == maxUsages) {
                  visibleNodes.add(MORE_USAGES_SEPARATOR_NODE);
                  usages.add(MORE_USAGES_SEPARATOR);
                  continueSearch = false;
                }
                pingEDT.ping();

                return continueSearch;
              }
              return true;
            }
          }
        };

    final ProgressIndicator indicator =
        FindUsagesManager.startProcessUsages(
            handler,
            handler.getPrimaryElements(),
            handler.getSecondaryElements(),
            collect,
            options,
            new Runnable() {
              @Override
              public void run() {
                ApplicationManager.getApplication()
                    .invokeLater(
                        new Runnable() {
                          @Override
                          public void run() {
                            Disposer.dispose(processIcon);
                            Container parent = processIcon.getParent();
                            parent.remove(processIcon);
                            parent.repaint();
                            pingEDT.ping(); // repaint title
                            synchronized (usages) {
                              if (visibleNodes.isEmpty()) {
                                if (usages.isEmpty()) {
                                  String text =
                                      UsageViewBundle.message(
                                          "no.usages.found.in",
                                          searchScopePresentableName(options, project));
                                  showHint(
                                      text, editor, popupPosition, handler, maxUsages, options);
                                  popup.cancel();
                                } else {
                                  // all usages filtered out
                                }
                              } else if (visibleNodes.size() == 1) {
                                if (usages.size() == 1) {
                                  // the only usage
                                  Usage usage = visibleNodes.iterator().next().getUsage();
                                  usage.navigate(true);
                                  // String message =
                                  // UsageViewBundle.message("show.usages.only.usage",
                                  // searchScopePresentableName(options, project));
                                  // navigateAndHint(usage, message, handler, popupPosition,
                                  // maxUsages, options);
                                  popup.cancel();
                                } else {
                                  assert usages.size() > 1 : usages;
                                  // usage view can filter usages down to one
                                  Usage visibleUsage = visibleNodes.iterator().next().getUsage();
                                  if (areAllUsagesInOneLine(visibleUsage, usages)) {
                                    String hint =
                                        UsageViewBundle.message(
                                            "all.usages.are.in.this.line",
                                            usages.size(),
                                            searchScopePresentableName(options, project));
                                    navigateAndHint(
                                        visibleUsage,
                                        hint,
                                        handler,
                                        popupPosition,
                                        maxUsages,
                                        options);
                                    popup.cancel();
                                  }
                                }
                              } else {
                                String title = presentation.getTabText();
                                boolean shouldShowMoreSeparator =
                                    visibleNodes.contains(MORE_USAGES_SEPARATOR_NODE);
                                String fullTitle =
                                    getFullTitle(
                                        usages,
                                        title,
                                        shouldShowMoreSeparator,
                                        visibleNodes.size() - (shouldShowMoreSeparator ? 1 : 0),
                                        false);
                                ((AbstractPopup) popup).setCaption(fullTitle);
                              }
                            }
                          }
                        },
                        project.getDisposed());
              }
            });
    Disposer.register(
        popup,
        new Disposable() {
          @Override
          public void dispose() {
            indicator.cancel();
          }
        });
  }
  private ElementsChooser(@Nullable List<T> elements, boolean marked, boolean elementsCanBeMarked) {
    super(new BorderLayout());

    myTableModel = new MyTableModel(elementsCanBeMarked);
    myTable = new Table(myTableModel);
    myTable.setShowGrid(false);
    myTable.setIntercellSpacing(new Dimension(0, 0));
    myTable.setTableHeader(null);
    myTable.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN);
    myTable.setColumnSelectionAllowed(false);
    JScrollPane pane = ScrollPaneFactory.createScrollPane(myTable);
    pane.setPreferredSize(new Dimension(100, 155));
    int width = new JCheckBox().getPreferredSize().width;
    TableColumnModel columnModel = myTable.getColumnModel();

    if (elementsCanBeMarked) {
      TableColumn checkMarkColumn = columnModel.getColumn(myTableModel.CHECK_MARK_COLUM_INDEX);
      checkMarkColumn.setPreferredWidth(width);
      checkMarkColumn.setMaxWidth(width);
      checkMarkColumn.setCellRenderer(
          new CheckMarkColumnCellRenderer(myTable.getDefaultRenderer(Boolean.class)));
    }
    columnModel
        .getColumn(myTableModel.ELEMENT_COLUMN_INDEX)
        .setCellRenderer(new MyElementColumnCellRenderer());

    add(pane, BorderLayout.CENTER);
    myTable.registerKeyboardAction(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            final int[] selectedRows = myTable.getSelectedRows();
            boolean currentlyMarked = true;
            for (int selectedRow : selectedRows) {
              currentlyMarked = myTableModel.isElementMarked(selectedRow);
              if (!currentlyMarked) {
                break;
              }
            }
            myTableModel.setMarked(selectedRows, !currentlyMarked);
          }
        },
        KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0),
        JComponent.WHEN_FOCUSED);

    final SpeedSearchBase<JBTable> speedSearch =
        new SpeedSearchBase<JBTable>(myTable) {
          public int getSelectedIndex() {
            return myTable.getSelectedRow();
          }

          @Override
          protected int convertIndexToModel(int viewIndex) {
            return myTable.convertRowIndexToModel(viewIndex);
          }

          public Object[] getAllElements() {
            final int count = myTableModel.getRowCount();
            Object[] elements = new Object[count];
            for (int idx = 0; idx < count; idx++) {
              elements[idx] = myTableModel.getElementAt(idx);
            }
            return elements;
          }

          public String getElementText(Object element) {
            return getItemText((T) element);
          }

          public void selectElement(Object element, String selectedText) {
            final int count = myTableModel.getRowCount();
            for (int row = 0; row < count; row++) {
              if (element.equals(myTableModel.getElementAt(row))) {
                final int viewRow = myTable.convertRowIndexToView(row);
                myTable.getSelectionModel().setSelectionInterval(viewRow, viewRow);
                TableUtil.scrollSelectionToVisible(myTable);
                break;
              }
            }
          }
        };
    speedSearch.setComparator(new SpeedSearchBase.SpeedSearchComparator(false));
    setElements(elements, marked);
    installActions(myTable);
  }