private static void installActions(JTable table) {
   InputMap inputMap = table.getInputMap(WHEN_FOCUSED);
   inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_END, 0), "selectLastRow");
   inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_HOME, 0), "selectFirstRow");
   inputMap.put(
       KeyStroke.getKeyStroke(KeyEvent.VK_HOME, KeyEvent.SHIFT_DOWN_MASK),
       "selectFirstRowExtendSelection");
   inputMap.put(
       KeyStroke.getKeyStroke(KeyEvent.VK_END, KeyEvent.SHIFT_DOWN_MASK),
       "selectLastRowExtendSelection");
 }
示例#2
0
  @Override
  public ActionCallback show() {
    LOG.assertTrue(
        EventQueue.isDispatchThread(), "Access is allowed from event dispatch thread only");
    if (myTypeAheadCallback != null) {
      IdeFocusManager.getInstance(myProject).typeAheadUntil(myTypeAheadCallback);
    }
    LOG.assertTrue(
        EventQueue.isDispatchThread(), "Access is allowed from event dispatch thread only");
    final ActionCallback result = new ActionCallback();

    final AnCancelAction anCancelAction = new AnCancelAction();
    final JRootPane rootPane = getRootPane();
    anCancelAction.registerCustomShortcutSet(
        new CustomShortcutSet(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0)), rootPane);
    myDisposeActions.add(
        new Runnable() {
          @Override
          public void run() {
            anCancelAction.unregisterCustomShortcutSet(rootPane);
          }
        });

    if (!myCanBeParent && myWindowManager != null) {
      myWindowManager.doNotSuggestAsParent(myDialog.getWindow());
    }

    final CommandProcessorEx commandProcessor =
        ApplicationManager.getApplication() != null
            ? (CommandProcessorEx) CommandProcessor.getInstance()
            : null;
    final boolean appStarted = commandProcessor != null;

    if (myDialog.isModal() && !isProgressDialog()) {
      if (appStarted) {
        commandProcessor.enterModal();
        LaterInvocator.enterModal(myDialog);
      }
    }

    if (appStarted) {
      hidePopupsIfNeeded();
    }

    try {
      myDialog.show();
    } finally {
      if (myDialog.isModal() && !isProgressDialog()) {
        if (appStarted) {
          commandProcessor.leaveModal();
          LaterInvocator.leaveModal(myDialog);
        }
      }

      myDialog.getFocusManager().doWhenFocusSettlesDown(result.createSetDoneRunnable());
    }

    return result;
  }
 private MergeDupLines() {
   super(
       UsageViewImpl.this,
       UsageViewBundle.message("action.merge.same.line"),
       IconLoader.getIcon("/toolbar/filterdups.png"));
   setShortcutSet(
       new CustomShortcutSet(KeyStroke.getKeyStroke(KeyEvent.VK_F, InputEvent.CTRL_DOWN_MASK)));
 }
  protected void fillToolbarActions(DefaultActionGroup group) {
    final boolean alphabeticallySorted = PropertiesComponent.getInstance().isTrueValue(PROP_SORTED);
    if (alphabeticallySorted) {
      setSortComparator(new OrderComparator());
    }
    myAlphabeticallySorted = alphabeticallySorted;
    group.add(mySortAction);

    if (!supportsNestedContainers()) {
      ShowContainersAction showContainersAction = getShowContainersAction();
      showContainersAction.registerCustomShortcutSet(
          new CustomShortcutSet(KeyStroke.getKeyStroke(KeyEvent.VK_C, InputEvent.ALT_MASK)),
          myTree);
      setShowClasses(PropertiesComponent.getInstance().isTrueValue(PROP_SHOWCLASSES));
      group.add(showContainersAction);
    }
  }
 protected MemberChooser(
     boolean allowEmptySelection,
     boolean allowMultiSelection,
     @NotNull Project project,
     boolean isInsertOverrideVisible,
     @Nullable JComponent headerPanel,
     @Nullable JComponent[] optionControls) {
   super(project, true);
   myAllowEmptySelection = allowEmptySelection;
   myAllowMultiSelection = allowMultiSelection;
   myProject = project;
   myIsInsertOverrideVisible = isInsertOverrideVisible;
   myHeaderPanel = headerPanel;
   myTree = createTree();
   myOptionControls = optionControls;
   mySortAction = new SortEmAction();
   mySortAction.registerCustomShortcutSet(
       new CustomShortcutSet(KeyStroke.getKeyStroke(KeyEvent.VK_A, InputEvent.ALT_MASK)), myTree);
 }
  public ClasspathPanelImpl(ModuleConfigurationState state) {
    super(new BorderLayout());

    myState = state;
    myModel = new ClasspathTableModel(state, getStructureConfigurableContext());
    myEntryTable =
        new JBTable(myModel) {
          @Override
          protected TableRowSorter<TableModel> createRowSorter(TableModel model) {
            return new DefaultColumnInfoBasedRowSorter(model) {
              @Override
              public void toggleSortOrder(int column) {
                if (isSortable(column)) {
                  SortKey oldKey = ContainerUtil.getFirstItem(getSortKeys());
                  SortOrder oldOrder;
                  if (oldKey == null || oldKey.getColumn() != column) {
                    oldOrder = SortOrder.UNSORTED;
                  } else {
                    oldOrder = oldKey.getSortOrder();
                  }
                  setSortKeys(
                      Collections.singletonList(new SortKey(column, getNextSortOrder(oldOrder))));
                }
              }
            };
          }
        };
    myEntryTable.setShowGrid(false);
    myEntryTable.setDragEnabled(false);
    myEntryTable.setIntercellSpacing(new Dimension(0, 0));

    myEntryTable.setDefaultRenderer(
        ClasspathTableItem.class, new TableItemRenderer(getStructureConfigurableContext()));
    myEntryTable.setDefaultRenderer(
        Boolean.class, new ExportFlagRenderer(myEntryTable.getDefaultRenderer(Boolean.class)));

    JComboBox scopeEditor =
        new ComboBox(new EnumComboBoxModel<DependencyScope>(DependencyScope.class));
    myEntryTable.setDefaultEditor(DependencyScope.class, new DefaultCellEditor(scopeEditor));
    myEntryTable.setDefaultRenderer(
        DependencyScope.class,
        new ComboBoxTableRenderer<DependencyScope>(DependencyScope.values()) {
          @Override
          protected String getTextFor(@NotNull final DependencyScope value) {
            return value.getDisplayName();
          }
        });

    myEntryTable.setTransferHandler(
        new TransferHandler() {
          @Nullable
          @Override
          protected Transferable createTransferable(JComponent c) {
            OrderEntry entry = getSelectedEntry();
            if (entry == null) return null;
            String text = entry.getPresentableName();
            return new TextTransferable(text);
          }

          @Override
          public int getSourceActions(JComponent c) {
            return COPY;
          }
        });

    myEntryTable
        .getSelectionModel()
        .setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

    new SpeedSearchBase<JBTable>(myEntryTable) {
      @Override
      public int getSelectedIndex() {
        return myEntryTable.getSelectedRow();
      }

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

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

      @Override
      public String getElementText(Object element) {
        return getCellAppearance(
                (ClasspathTableItem<?>) element, getStructureConfigurableContext(), false)
            .getText();
      }

      @Override
      public void selectElement(Object element, String selectedText) {
        final int count = myModel.getRowCount();
        for (int row = 0; row < count; row++) {
          if (element.equals(myModel.getItem(row))) {
            final int viewRow = myEntryTable.convertRowIndexToView(row);
            myEntryTable.getSelectionModel().setSelectionInterval(viewRow, viewRow);
            TableUtil.scrollSelectionToVisible(myEntryTable);
            break;
          }
        }
      }
    };
    setFixedColumnWidth(ClasspathTableModel.EXPORT_COLUMN);
    setFixedColumnWidth(ClasspathTableModel.SCOPE_COLUMN); // leave space for combobox border

    myEntryTable.registerKeyboardAction(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            final int[] selectedRows = myEntryTable.getSelectedRows();
            boolean currentlyMarked = true;
            for (final int selectedRow : selectedRows) {
              final ClasspathTableItem<?> item = getItemAt(selectedRow);
              if (selectedRow < 0 || !item.isExportable()) {
                return;
              }
              currentlyMarked &= item.isExported();
            }
            for (final int selectedRow : selectedRows) {
              getItemAt(selectedRow).setExported(!currentlyMarked);
            }
            myModel.fireTableDataChanged();
            TableUtil.selectRows(myEntryTable, selectedRows);
          }
        },
        KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0),
        WHEN_FOCUSED);

    myEditButton =
        new AnActionButton(
            ProjectBundle.message("module.classpath.button.edit"), null, IconUtil.getEditIcon()) {
          @Override
          public void actionPerformed(@NotNull AnActionEvent e) {
            doEdit();
          }

          @Override
          public boolean isEnabled() {
            ClasspathTableItem<?> selectedItem = getSelectedItem();
            return selectedItem != null && selectedItem.isEditable();
          }

          @Override
          public boolean isDumbAware() {
            return true;
          }
        };
    add(createTableWithButtons(), BorderLayout.CENTER);

    if (myEntryTable.getRowCount() > 0) {
      myEntryTable.getSelectionModel().setSelectionInterval(0, 0);
    }

    new DoubleClickListener() {
      @Override
      protected boolean onDoubleClick(MouseEvent e) {
        navigate(true);
        return true;
      }
    }.installOn(myEntryTable);

    DefaultActionGroup actionGroup = new DefaultActionGroup();
    final AnAction navigateAction =
        new AnAction(ProjectBundle.message("classpath.panel.navigate.action.text")) {
          @Override
          public void actionPerformed(@NotNull AnActionEvent e) {
            navigate(false);
          }

          @Override
          public void update(@NotNull AnActionEvent e) {
            final Presentation presentation = e.getPresentation();
            presentation.setEnabled(false);
            final OrderEntry entry = getSelectedEntry();
            if (entry != null && entry.isValid()) {
              if (!(entry instanceof ModuleSourceOrderEntry)) {
                presentation.setEnabled(true);
              }
            }
          }
        };
    navigateAction.registerCustomShortcutSet(
        ActionManager.getInstance().getAction(IdeActions.ACTION_EDIT_SOURCE).getShortcutSet(),
        myEntryTable);
    actionGroup.add(myEditButton);
    actionGroup.add(myRemoveButton);
    actionGroup.add(navigateAction);
    actionGroup.add(new InlineModuleDependencyAction(this));
    actionGroup.add(new MyFindUsagesAction());
    actionGroup.add(new AnalyzeDependencyAction());
    addChangeLibraryLevelAction(actionGroup, LibraryTablesRegistrar.PROJECT_LEVEL);
    addChangeLibraryLevelAction(actionGroup, LibraryTablesRegistrar.APPLICATION_LEVEL);
    addChangeLibraryLevelAction(actionGroup, LibraryTableImplUtil.MODULE_LEVEL);
    PopupHandler.installPopupHandler(
        myEntryTable, actionGroup, ActionPlaces.UNKNOWN, ActionManager.getInstance());
  }
  private void createActions(ToolbarDecorator decorator) {
    final Consumer<BaseInjection> consumer =
        new Consumer<BaseInjection>() {
          public void consume(final BaseInjection injection) {
            addInjection(injection);
          }
        };
    final Factory<BaseInjection> producer =
        new NullableFactory<BaseInjection>() {
          public BaseInjection create() {
            final InjInfo info = getSelectedInjection();
            return info == null ? null : info.injection;
          }
        };
    for (LanguageInjectionSupport support : InjectorUtils.getActiveInjectionSupports()) {
      ContainerUtil.addAll(myAddActions, support.createAddActions(myProject, consumer));
      final AnAction action = support.createEditAction(myProject, producer);
      myEditActions.put(
          support.getId(),
          action == null
              ? AbstractLanguageInjectionSupport.createDefaultEditAction(myProject, producer)
              : action);
      mySupports.put(support.getId(), support);
    }
    Collections.sort(
        myAddActions,
        new Comparator<AnAction>() {
          public int compare(final AnAction o1, final AnAction o2) {
            return Comparing.compare(
                o1.getTemplatePresentation().getText(), o2.getTemplatePresentation().getText());
          }
        });
    decorator.disableUpDownActions();
    decorator.setAddActionUpdater(
        new AnActionButtonUpdater() {
          @Override
          public boolean isEnabled(AnActionEvent e) {
            return !myAddActions.isEmpty();
          }
        });
    decorator.setAddAction(
        new AnActionButtonRunnable() {
          @Override
          public void run(AnActionButton button) {
            performAdd(button);
          }
        });
    decorator.setRemoveActionUpdater(
        new AnActionButtonUpdater() {
          @Override
          public boolean isEnabled(AnActionEvent e) {
            boolean enabled = false;
            for (InjInfo info : getSelectedInjections()) {
              if (!info.bundled) {
                enabled = true;
                break;
              }
            }
            return enabled;
          }
        });
    decorator.setRemoveAction(
        new AnActionButtonRunnable() {
          @Override
          public void run(AnActionButton button) {
            performRemove();
          }
        });

    decorator.setEditActionUpdater(
        new AnActionButtonUpdater() {
          @Override
          public boolean isEnabled(AnActionEvent e) {
            AnAction edit = getEditAction();
            if (edit != null) edit.update(e);
            return edit != null && edit.getTemplatePresentation().isEnabled();
          }
        });
    decorator.setEditAction(
        new AnActionButtonRunnable() {
          @Override
          public void run(AnActionButton button) {
            performEditAction();
          }
        });
    decorator.addExtraAction(
        new DumbAwareActionButton("Duplicate", "Duplicate", PlatformIcons.COPY_ICON) {

          @Override
          public boolean isEnabled() {
            return getEditAction() != null;
          }

          @Override
          public void actionPerformed(@NotNull AnActionEvent e) {
            final InjInfo injection = getSelectedInjection();
            if (injection != null) {
              addInjection(injection.injection.copy());
              // performEditAction(e);
            }
          }
        });

    decorator.addExtraAction(
        new DumbAwareActionButton(
            "Enable Selected Injections",
            "Enable Selected Injections",
            PlatformIcons.SELECT_ALL_ICON) {

          @Override
          public void actionPerformed(@NotNull final AnActionEvent e) {
            performSelectedInjectionsEnabled(true);
          }
        });
    decorator.addExtraAction(
        new DumbAwareActionButton(
            "Disable Selected Injections",
            "Disable Selected Injections",
            PlatformIcons.UNSELECT_ALL_ICON) {

          @Override
          public void actionPerformed(@NotNull final AnActionEvent e) {
            performSelectedInjectionsEnabled(false);
          }
        });

    new DumbAwareAction("Toggle") {
      @Override
      public void update(@NotNull AnActionEvent e) {
        SpeedSearchSupply supply = SpeedSearchSupply.getSupply(myInjectionsTable);
        e.getPresentation().setEnabled(supply == null || !supply.isPopupActive());
      }

      @Override
      public void actionPerformed(@NotNull final AnActionEvent e) {
        performToggleAction();
      }
    }.registerCustomShortcutSet(
        new CustomShortcutSet(KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0)), myInjectionsTable);

    if (myInfos.length > 1) {
      AnActionButton shareAction =
          new DumbAwareActionButton("Move to IDE Scope", null, PlatformIcons.IMPORT_ICON) {
            {
              addCustomUpdater(
                  new AnActionButtonUpdater() {
                    @Override
                    public boolean isEnabled(AnActionEvent e) {
                      CfgInfo cfg = getTargetCfgInfo(getSelectedInjections());
                      e.getPresentation()
                          .setText(
                              cfg == getDefaultCfgInfo()
                                  ? "Move to IDE Scope"
                                  : "Move to Project Scope");
                      return cfg != null;
                    }
                  });
            }

            @Override
            public void actionPerformed(@NotNull final AnActionEvent e) {
              final List<InjInfo> injections = getSelectedInjections();
              final CfgInfo cfg = getTargetCfgInfo(injections);
              if (cfg == null) return;
              for (InjInfo info : injections) {
                if (info.cfgInfo == cfg) continue;
                if (info.bundled) continue;
                info.cfgInfo.injectionInfos.remove(info);
                cfg.addInjection(info.injection);
              }
              final int[] selectedRows = myInjectionsTable.getSelectedRows();
              myInjectionsTable.getListTableModel().setItems(getInjInfoList(myInfos));
              TableUtil.selectRows(myInjectionsTable, selectedRows);
            }

            @Nullable
            private CfgInfo getTargetCfgInfo(final List<InjInfo> injections) {
              CfgInfo cfg = null;
              for (InjInfo info : injections) {
                if (info.bundled) {
                  continue;
                }
                if (cfg == null) cfg = info.cfgInfo;
                else if (cfg != info.cfgInfo) return info.cfgInfo;
              }
              if (cfg == null) return null;
              for (CfgInfo info : myInfos) {
                if (info != cfg) return info;
              }
              throw new AssertionError();
            }
          };
      shareAction.setShortcut(
          new CustomShortcutSet(
              KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, InputEvent.SHIFT_DOWN_MASK)));
      decorator.addExtraAction(shareAction);
    }
    decorator.addExtraAction(
        new DumbAwareActionButton("Import", "Import", AllIcons.Actions.Install) {

          @Override
          public void actionPerformed(@NotNull final AnActionEvent e) {
            doImportAction(e.getDataContext());
            updateCountLabel();
          }
        });
    decorator.addExtraAction(
        new DumbAwareActionButton("Export", "Export", AllIcons.Actions.Export) {

          @Override
          public void actionPerformed(@NotNull final AnActionEvent e) {
            final List<BaseInjection> injections = getInjectionList(getSelectedInjections());
            final VirtualFileWrapper wrapper =
                FileChooserFactory.getInstance()
                    .createSaveFileDialog(
                        new FileSaverDescriptor("Export Selected Injections to File...", "", "xml"),
                        myProject)
                    .save(null, null);
            if (wrapper == null) return;
            final Configuration configuration = new Configuration();
            configuration.setInjections(injections);
            final Document document = new Document(configuration.getState());
            try {
              JDOMUtil.writeDocument(document, wrapper.getFile(), "\n");
            } catch (IOException ex) {
              final String msg = ex.getLocalizedMessage();
              Messages.showErrorDialog(
                  myProject,
                  msg != null && msg.length() > 0 ? msg : ex.toString(),
                  "Export Failed");
            }
          }

          @Override
          public boolean isEnabled() {
            return !getSelectedInjections().isEmpty();
          }
        });
  }
示例#8
0
  private boolean updateTextComponent(final boolean search) {
    JTextComponent oldComponent = search ? mySearchTextComponent : myReplaceTextComponent;
    Color oldBackground = oldComponent != null ? oldComponent.getBackground() : null;
    Wrapper wrapper = search ? mySearchFieldWrapper : myReplaceFieldWrapper;
    boolean multiline = myFindModel.isMultiline();
    if (multiline && oldComponent instanceof JTextArea) return false;
    if (!multiline && oldComponent instanceof JTextField) return false;

    final JTextComponent textComponent;
    if (multiline) {
      textComponent = new JTextArea();
      ((JTextArea) textComponent).setColumns(25);
      ((JTextArea) textComponent).setRows(2);
      wrapper.setContent(
          new SearchWrapper(textComponent, new ShowHistoryAction(textComponent, this)));
    } else {
      SearchTextField searchTextField = new SearchTextField(true);
      searchTextField.setOpaque(false);
      textComponent = searchTextField.getTextEditor();
      searchTextField.getTextEditor().setColumns(25);
      if (UIUtil.isUnderGTKLookAndFeel()) {
        textComponent.setOpaque(false);
      }
      setupHistoryToSearchField(
          searchTextField,
          search
              ? FindSettings.getInstance().getRecentFindStrings()
              : FindSettings.getInstance().getRecentReplaceStrings());
      textComponent.registerKeyboardAction(
          new ActionListener() {
            @Override
            public void actionPerformed(final ActionEvent e) {
              final String text = textComponent.getText();
              myFindModel.setMultiline(true);
              ApplicationManager.getApplication()
                  .invokeLater(
                      new Runnable() {
                        @Override
                        public void run() {
                          if (search) {
                            mySearchTextComponent.setText(text + "\n");
                          } else {
                            myReplaceTextComponent.setText(text + "\n");
                          }
                        }
                      });
            }
          },
          KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, InputEvent.ALT_DOWN_MASK),
          JComponent.WHEN_FOCUSED);
      wrapper.setContent(searchTextField);
    }

    if (search) {
      mySearchTextComponent = textComponent;
    } else {
      myReplaceTextComponent = textComponent;
    }

    UIUtil.addUndoRedoActions(textComponent);
    Utils.setSmallerFont(textComponent);

    textComponent.putClientProperty("AuxEditorComponent", Boolean.TRUE);
    if (oldBackground != null) {
      textComponent.setBackground(oldBackground);
    }
    textComponent.addFocusListener(
        new FocusListener() {
          @Override
          public void focusGained(final FocusEvent e) {
            textComponent.repaint();
          }

          @Override
          public void focusLost(final FocusEvent e) {
            textComponent.repaint();
          }
        });
    new CloseOnESCAction(this, textComponent);
    return true;
  }
示例#9
0
  private void updateSearchComponent() {
    final int oldCaretPosition =
        mySearchTextComponent != null ? mySearchTextComponent.getCaretPosition() : 0;
    String oldText =
        mySearchTextComponent != null
            ? mySearchTextComponent.getText()
            : myFindModel.getStringToFind();

    if (!updateTextComponent(true)) {
      return;
    }

    if (oldText != null) {
      mySearchTextComponent.setText(oldText);
    }
    mySearchTextComponent
        .getDocument()
        .addDocumentListener(
            new DocumentAdapter() {
              @Override
              protected void textChanged(DocumentEvent e) {
                ApplicationManager.getApplication()
                    .invokeLater(
                        new Runnable() {
                          @Override
                          public void run() {
                            ApplicationManager.getApplication()
                                .invokeLater(
                                    new Runnable() {
                                      @Override
                                      public void run() {
                                        searchFieldDocumentChanged();
                                      }
                                    });
                          }
                        });
              }
            });

    mySearchTextComponent.registerKeyboardAction(
        new ActionListener() {
          @Override
          public void actionPerformed(final ActionEvent e) {
            if (StringUtil.isEmpty(mySearchTextComponent.getText())) {
              close();
            } else {
              requestFocus(myEditor.getContentComponent());
              addTextToRecent(EditorSearchComponent.this.mySearchTextComponent);
            }
          }
        },
        KeyStroke.getKeyStroke(
            KeyEvent.VK_ENTER,
            SystemInfo.isMac ? InputEvent.META_DOWN_MASK : InputEvent.CTRL_DOWN_MASK),
        JComponent.WHEN_FOCUSED);

    ApplicationManager.getApplication()
        .invokeLater(
            new Runnable() {
              @Override
              public void run() {
                mySearchTextComponent.setCaretPosition(oldCaretPosition);
              }
            });

    new RestorePreviousSettingsAction(this, mySearchTextComponent);
    new VariantsCompletionAction(
        mySearchTextComponent); // It registers a shortcut set automatically on construction
  }
  public MainWatchPanel(Project project, DebuggerStateManager stateManager) {
    super(project, stateManager);
    final WatchDebuggerTree watchTree = getWatchTree();

    final AnAction removeWatchesAction =
        ActionManager.getInstance().getAction(DebuggerActions.REMOVE_WATCH);
    removeWatchesAction.registerCustomShortcutSet(CommonShortcuts.DELETE, watchTree);

    final AnAction newWatchAction =
        ActionManager.getInstance().getAction(DebuggerActions.NEW_WATCH);
    newWatchAction.registerCustomShortcutSet(CommonShortcuts.INSERT, watchTree);

    final ClickListener mouseListener =
        new DoubleClickListener() {
          @Override
          protected boolean onDoubleClick(MouseEvent e) {
            AnAction editWatchAction =
                ActionManager.getInstance().getAction(DebuggerActions.EDIT_WATCH);
            Presentation presentation = editWatchAction.getTemplatePresentation().clone();
            DataContext context = DataManager.getInstance().getDataContext(watchTree);

            AnActionEvent actionEvent =
                new AnActionEvent(
                    null, context, "WATCH_TREE", presentation, ActionManager.getInstance(), 0);
            editWatchAction.actionPerformed(actionEvent);
            return true;
          }
        };
    ListenerUtil.addClickListener(watchTree, mouseListener);

    final AnAction editWatchAction =
        ActionManager.getInstance().getAction(DebuggerActions.EDIT_WATCH);
    editWatchAction.registerCustomShortcutSet(
        new CustomShortcutSet(KeyStroke.getKeyStroke(KeyEvent.VK_F2, 0)), watchTree);
    registerDisposable(
        new Disposable() {
          public void dispose() {
            ListenerUtil.removeClickListener(watchTree, mouseListener);
            removeWatchesAction.unregisterCustomShortcutSet(watchTree);
            newWatchAction.unregisterCustomShortcutSet(watchTree);
            editWatchAction.unregisterCustomShortcutSet(watchTree);
          }
        });

    DnDManager.getInstance()
        .registerTarget(
            new DnDNativeTarget() {
              public boolean update(final DnDEvent aEvent) {
                Object object = aEvent.getAttachedObject();
                if (object == null) return true;

                String add = DebuggerBundle.message("watchs.add.text");

                if (object.getClass().isArray()) {
                  Class<?> type = object.getClass().getComponentType();
                  if (DebuggerTreeNodeImpl.class.isAssignableFrom(type)) {
                    aEvent.setHighlighting(
                        myTree,
                        DnDEvent.DropTargetHighlightingType.RECTANGLE
                            | DnDEvent.DropTargetHighlightingType.TEXT);
                    aEvent.setDropPossible(
                        add,
                        new DropActionHandler() {
                          public void performDrop(final DnDEvent aEvent) {
                            addWatchesFrom((DebuggerTreeNodeImpl[]) aEvent.getAttachedObject());
                          }
                        });
                  }
                } else if (object instanceof EventInfo) {
                  EventInfo info = (EventInfo) object;
                  final String text = info.getTextForFlavor(DataFlavor.stringFlavor);
                  if (text != null) {
                    aEvent.setHighlighting(
                        myTree,
                        DnDEvent.DropTargetHighlightingType.RECTANGLE
                            | DnDEvent.DropTargetHighlightingType.TEXT);
                    aEvent.setDropPossible(
                        add,
                        new DropActionHandler() {
                          public void performDrop(final DnDEvent aEvent) {
                            addWatchesFrom(text);
                          }
                        });
                  }
                }

                return true;
              }

              public void drop(final DnDEvent aEvent) {}

              public void cleanUpOnLeave() {}

              public void updateDraggedImage(
                  final Image image, final Point dropPoint, final Point imageOffset) {}
            },
            myTree);
  }
  private void prepareToShow() {
    final MouseAdapter mouseAdapter =
        new MouseAdapter() {
          public void mousePressed(MouseEvent e) {
            Point point = (Point) e.getPoint().clone();
            SwingUtilities.convertPointToScreen(point, e.getComponent());

            final Dimension dimension = myContent.getSize();
            dimension.height +=
                myResizable && isToDrawMacCorner() ? ourMacCorner.getHeight(myContent) : 4;
            dimension.width += 4;
            Point locationOnScreen = myContent.getLocationOnScreen();
            final Rectangle bounds =
                new Rectangle(new Point(locationOnScreen.x - 2, locationOnScreen.y - 2), dimension);
            if (!bounds.contains(point)) {
              cancel();
            }
          }
        };
    myContent.addMouseListener(mouseAdapter);
    Disposer.register(
        this,
        new Disposable() {
          public void dispose() {
            myContent.removeMouseListener(mouseAdapter);
          }
        });

    myContent.registerKeyboardAction(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            if (myCancelKeyEnabled) {
              cancel();
            }
          }
        },
        KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0),
        JComponent.WHEN_IN_FOCUSED_WINDOW);

    mySearchKeyListener = new SpeedSearchKeyListener();
    myContent.addKeyListener(mySearchKeyListener);

    if (myCancelOnMouseOutCallback != null || myCancelOnWindow) {
      myMouseOutCanceller = new Canceller();
      Toolkit.getDefaultToolkit()
          .addAWTEventListener(
              myMouseOutCanceller,
              AWTEvent.MOUSE_EVENT_MASK
                  | WindowEvent.WINDOW_ACTIVATED
                  | AWTEvent.MOUSE_MOTION_EVENT_MASK);
    }

    myFocusWatcher =
        new ChildFocusWatcher(myContent) {
          protected void onFocusGained(final FocusEvent event) {
            setWindowActive(true);
          }

          protected void onFocusLost(final FocusEvent event) {
            setWindowActive(false);
          }
        };

    mySpeedSearchPatternField = new JTextField();
    if (SystemInfo.isMac) {
      Font f = mySpeedSearchPatternField.getFont();
      mySpeedSearchPatternField.setFont(f.deriveFont(f.getStyle(), f.getSize() - 2));
    }
  }
  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);
  }
  private static JBPopup getPsiElementPopup(
      final Object[] elements,
      final Map<PsiElement, GotoRelatedItem> itemsMap,
      final String title,
      final boolean showContainingModules,
      final Processor<Object> processor) {

    final Ref<Boolean> hasMnemonic = Ref.create(false);
    final DefaultPsiElementCellRenderer renderer =
        new DefaultPsiElementCellRenderer() {
          {
            setFocusBorderEnabled(false);
          }

          @Override
          public String getElementText(PsiElement element) {
            String customName = itemsMap.get(element).getCustomName();
            return (customName != null ? customName : super.getElementText(element));
          }

          @Override
          protected Icon getIcon(PsiElement element) {
            Icon customIcon = itemsMap.get(element).getCustomIcon();
            return customIcon != null ? customIcon : super.getIcon(element);
          }

          @Override
          public String getContainerText(PsiElement element, String name) {
            String customContainerName = itemsMap.get(element).getCustomContainerName();

            if (customContainerName != null) {
              return customContainerName;
            }
            PsiFile file = element.getContainingFile();
            return file != null && !getElementText(element).equals(file.getName())
                ? "(" + file.getName() + ")"
                : null;
          }

          @Override
          protected DefaultListCellRenderer getRightCellRenderer(Object value) {
            return showContainingModules ? super.getRightCellRenderer(value) : null;
          }

          @Override
          protected boolean customizeNonPsiElementLeftRenderer(
              ColoredListCellRenderer renderer,
              JList list,
              Object value,
              int index,
              boolean selected,
              boolean hasFocus) {
            final GotoRelatedItem item = (GotoRelatedItem) value;
            Color color = list.getForeground();
            final SimpleTextAttributes nameAttributes =
                new SimpleTextAttributes(SimpleTextAttributes.STYLE_PLAIN, color);
            final String name = item.getCustomName();
            if (name == null) return false;
            renderer.append(name, nameAttributes);
            renderer.setIcon(item.getCustomIcon());
            return true;
          }

          @Override
          public Component getListCellRendererComponent(
              JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
            final JPanel component =
                (JPanel)
                    super.getListCellRendererComponent(
                        list, value, index, isSelected, cellHasFocus);
            if (!hasMnemonic.get()) return component;

            final JPanel panelWithMnemonic = new JPanel(new BorderLayout());
            final int mnemonic = getMnemonic(value, itemsMap);
            final JLabel label = new JLabel("");
            if (mnemonic != -1) {
              label.setText(mnemonic + ".");
              label.setDisplayedMnemonicIndex(0);
            }
            label.setPreferredSize(new JLabel("8.").getPreferredSize());

            final JComponent leftRenderer = (JComponent) component.getComponents()[0];
            component.remove(leftRenderer);
            panelWithMnemonic.setBorder(BorderFactory.createEmptyBorder(0, 7, 0, 0));
            panelWithMnemonic.setBackground(leftRenderer.getBackground());
            label.setBackground(leftRenderer.getBackground());
            panelWithMnemonic.add(label, BorderLayout.WEST);
            panelWithMnemonic.add(leftRenderer, BorderLayout.CENTER);
            component.add(panelWithMnemonic);
            return component;
          }
        };
    final ListPopupImpl popup =
        new ListPopupImpl(
            new BaseListPopupStep<Object>(title, Arrays.asList(elements)) {
              @Override
              public boolean isSpeedSearchEnabled() {
                return true;
              }

              @Override
              public String getIndexedString(Object value) {
                if (value instanceof GotoRelatedItem) {
                  //noinspection ConstantConditions
                  return ((GotoRelatedItem) value).getCustomName();
                }
                PsiElement element = (PsiElement) value;
                if (!element.isValid()) return "INVALID";
                return renderer.getElementText(element)
                    + " "
                    + renderer.getContainerText(element, null);
              }

              @Override
              public PopupStep onChosen(Object selectedValue, boolean finalChoice) {
                processor.process(selectedValue);
                return super.onChosen(selectedValue, finalChoice);
              }
            }) {};
    popup
        .getList()
        .setCellRenderer(
            new PopupListElementRenderer(popup) {
              Map<Object, String> separators = new HashMap<Object, String>();

              {
                final ListModel model = popup.getList().getModel();
                String current = null;
                boolean hasTitle = false;
                for (int i = 0; i < model.getSize(); i++) {
                  final Object element = model.getElementAt(i);
                  final GotoRelatedItem item = itemsMap.get(element);
                  if (item != null && !StringUtil.equals(current, item.getGroup())) {
                    current = item.getGroup();
                    separators.put(element, current);
                    if (!hasTitle && !StringUtil.isEmpty(current)) {
                      hasTitle = true;
                    }
                  }
                }

                if (!hasTitle) {
                  separators.remove(model.getElementAt(0));
                }
              }

              @Override
              public Component getListCellRendererComponent(
                  JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
                final Component component =
                    renderer.getListCellRendererComponent(
                        list, value, index, isSelected, cellHasFocus);
                final String separator = separators.get(value);

                if (separator != null) {
                  JPanel panel = new JPanel(new BorderLayout());
                  panel.add(component, BorderLayout.CENTER);
                  final SeparatorWithText sep =
                      new SeparatorWithText() {
                        @Override
                        protected void paintComponent(Graphics g) {
                          g.setColor(new JBColor(Color.WHITE, UIUtil.getSeparatorColor()));
                          g.fillRect(0, 0, getWidth(), getHeight());
                          super.paintComponent(g);
                        }
                      };
                  sep.setCaption(separator);
                  panel.add(sep, BorderLayout.NORTH);
                  return panel;
                }
                return component;
              }
            });

    popup.setMinimumSize(new Dimension(200, -1));

    for (Object item : elements) {
      final int mnemonic = getMnemonic(item, itemsMap);
      if (mnemonic != -1) {
        final Action action = createNumberAction(mnemonic, popup, itemsMap, processor);
        popup.registerAction(
            mnemonic + "Action", KeyStroke.getKeyStroke(String.valueOf(mnemonic)), action);
        popup.registerAction(
            mnemonic + "Action",
            KeyStroke.getKeyStroke("NUMPAD" + String.valueOf(mnemonic)),
            action);
        hasMnemonic.set(true);
      }
    }
    return popup;
  }
  private JComponent createMasterView() {
    myTreeController = new BreakpointItemsTreeController(myRulesEnabled);
    JTree tree = new BreakpointsCheckboxTree(myProject, myTreeController);

    new AnAction("BreakpointDialog.GoToSource") {
      @Override
      public void actionPerformed(AnActionEvent e) {
        navigate();
        close(OK_EXIT_CODE);
      }
    }.registerCustomShortcutSet(
        new CustomShortcutSet(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0)), tree);

    new AnAction("BreakpointDialog.ShowSource") {
      @Override
      public void actionPerformed(AnActionEvent e) {
        navigate();
      }
    }.registerCustomShortcutSet(
        ActionManager.getInstance().getAction(IdeActions.ACTION_EDIT_SOURCE).getShortcutSet(),
        tree);

    tree.addMouseListener(
        new MouseAdapter() {
          @Override
          public void mouseClicked(MouseEvent event) {
            if (event.getClickCount() == 2
                && UIUtil.isActionClick(event, MouseEvent.MOUSE_CLICKED)
                && !UIUtil.isSelectionButtonDown(event)
                && !event.isConsumed()) {
              navigate();
              close(OK_EXIT_CODE);
            }
          }
        });

    final DefaultActionGroup breakpointTypes = new DefaultActionGroup();
    for (BreakpointPanelProvider provider : myBreakpointsPanelProviders) {
      breakpointTypes.addAll(provider.getAddBreakpointActions(myProject));
    }

    ToolbarDecorator decorator =
        ToolbarDecorator.createDecorator(tree)
            .setAddAction(
                new AnActionButtonRunnable() {
                  @Override
                  public void run(AnActionButton button) {
                    JBPopupFactory.getInstance()
                        .createActionGroupPopup(
                            null,
                            breakpointTypes,
                            DataManager.getInstance().getDataContext(button.getContextComponent()),
                            JBPopupFactory.ActionSelectionAid.NUMBERING,
                            false)
                        .show(button.getPreferredPopupPoint());
                  }
                })
            .setRemoveAction(
                new AnActionButtonRunnable() {
                  @Override
                  public void run(AnActionButton button) {
                    myTreeController.removeSelectedBreakpoints(myProject);
                  }
                })
            .setRemoveActionUpdater(
                new AnActionButtonUpdater() {
                  @Override
                  public boolean isEnabled(AnActionEvent e) {
                    boolean enabled = false;
                    final ItemWrapper[] items = myMasterController.getSelectedItems();
                    for (ItemWrapper item : items) {
                      if (item.allowedToRemove()) {
                        enabled = true;
                      }
                    }
                    return enabled;
                  }
                });

    for (ToggleActionButton action : myToggleRuleActions) {
      decorator.addExtraAction(action);
    }

    JPanel decoratedTree = decorator.createPanel();
    myTreeController.setTreeView(tree);

    myDetailController.setTree(tree);

    myTreeController.buildTree(myBreakpointItems);

    initSelection(myBreakpointItems);

    final BreakpointPanelProvider.BreakpointsListener listener =
        new BreakpointPanelProvider.BreakpointsListener() {
          @Override
          public void breakpointsChanged() {
            collectItems();
            myTreeController.rebuildTree(myBreakpointItems);
          }
        };

    for (BreakpointPanelProvider provider : myBreakpointsPanelProviders) {
      provider.addListener(listener, myProject, myListenerDisposable);
    }

    return decoratedTree;
  }