/**
  * This is hack. AWT doesn't allow to create KeyStroke with specified key code and key char
  * simultaneously. Therefore we are using reflection.
  */
 private static KeyStroke getKeyStrokeWithoutMouseModifiers(KeyStroke originalKeyStroke) {
   int modifier =
       originalKeyStroke.getModifiers()
           & ~InputEvent.BUTTON1_DOWN_MASK
           & ~InputEvent.BUTTON1_MASK
           & ~InputEvent.BUTTON2_DOWN_MASK
           & ~InputEvent.BUTTON2_MASK
           & ~InputEvent.BUTTON3_DOWN_MASK
           & ~InputEvent.BUTTON3_MASK;
   try {
     Method[] methods = AWTKeyStroke.class.getDeclaredMethods();
     Method getCachedStrokeMethod = null;
     for (Method method : methods) {
       if (GET_CACHED_STROKE_METHOD_NAME.equals(method.getName())) {
         getCachedStrokeMethod = method;
         getCachedStrokeMethod.setAccessible(true);
         break;
       }
     }
     if (getCachedStrokeMethod == null) {
       throw new IllegalStateException("not found method with name getCachedStrokeMethod");
     }
     Object[] getCachedStrokeMethodArgs =
         new Object[] {
           originalKeyStroke.getKeyChar(),
           originalKeyStroke.getKeyCode(),
           modifier,
           originalKeyStroke.isOnKeyRelease()
         };
     return (KeyStroke) getCachedStrokeMethod.invoke(originalKeyStroke, getCachedStrokeMethodArgs);
   } catch (Exception exc) {
     throw new IllegalStateException(exc.getMessage());
   }
 }
  public static InputEvent getInputEvent(String actionName) {
    final Shortcut[] shortcuts =
        KeymapManager.getInstance().getActiveKeymap().getShortcuts(actionName);
    KeyStroke keyStroke = null;
    for (Shortcut each : shortcuts) {
      if (each instanceof KeyboardShortcut) {
        keyStroke = ((KeyboardShortcut) each).getFirstKeyStroke();
        if (keyStroke != null) break;
      }
    }

    if (keyStroke != null) {
      return new KeyEvent(
          JOptionPane.getRootFrame(),
          KeyEvent.KEY_PRESSED,
          System.currentTimeMillis(),
          keyStroke.getModifiers(),
          keyStroke.getKeyCode(),
          keyStroke.getKeyChar(),
          KeyEvent.KEY_LOCATION_STANDARD);
    } else {
      return new MouseEvent(
          JOptionPane.getRootFrame(),
          MouseEvent.MOUSE_PRESSED,
          0,
          0,
          0,
          0,
          1,
          false,
          MouseEvent.BUTTON1);
    }
  }
  private ActionToolbar createToolbar() {
    DefaultActionGroup group = new DefaultActionGroup();

    BackAction back = new BackAction();
    back.registerCustomShortcutSet(
        new CustomShortcutSet(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0)), this);
    group.add(back);

    ForwardAction forward = new ForwardAction();
    forward.registerCustomShortcutSet(
        new CustomShortcutSet(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0)), this);
    group.add(forward);

    EditSourceActionBase edit = new EditSourceAction();
    edit.registerCustomShortcutSet(
        new CompositeShortcutSet(CommonShortcuts.getEditSource(), CommonShortcuts.ENTER), this);
    group.add(edit);

    edit = new ShowSourceAction();
    edit.registerCustomShortcutSet(
        new CompositeShortcutSet(CommonShortcuts.getViewSource(), CommonShortcuts.CTRL_ENTER),
        this);
    group.add(edit);

    return ActionManager.getInstance().createActionToolbar(ActionPlaces.UNKNOWN, group, true);
  }
Esempio n. 4
0
  private void initActions() {
    @NonNls InputMap inputMap = getInputMap(WHEN_FOCUSED);
    inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0, false), "moveFocusDown");
    inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0, false), "moveFocusUp");
    inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0, false), "collapse");
    inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0, false), "expand");

    @NonNls ActionMap actionMap = getActionMap();
    actionMap.put("moveFocusDown", new MoveFocusAction(true));
    actionMap.put("moveFocusUp", new MoveFocusAction(false));
    actionMap.put("collapse", new ExpandAction(false));
    actionMap.put("expand", new ExpandAction(true));
  }
  public VariablesPanel(Project project, DebuggerStateManager stateManager, Disposable parent) {
    super(project, stateManager);

    setBorder(null);

    final FrameVariablesTree frameTree = getFrameTree();

    myCards = new JPanel(new CardLayout());
    myCards.add(frameTree, TREE);

    myXTree = new MyXVariablesView(project);
    registerDisposable(myXTree);
    myCards.add(myXTree.getTree(), X_TREE);

    JScrollPane pane = ScrollPaneFactory.createScrollPane(myCards);
    pane.getVerticalScrollBar().setUnitIncrement(10);
    add(pane, BorderLayout.CENTER);
    registerDisposable(
        DebuggerAction.installEditAction(frameTree, DebuggerActions.EDIT_NODE_SOURCE));

    overrideShortcut(frameTree, DebuggerActions.COPY_VALUE, CommonShortcuts.getCopy());
    overrideShortcut(
        frameTree,
        DebuggerActions.SET_VALUE,
        new CustomShortcutSet(KeyStroke.getKeyStroke(KeyEvent.VK_F2, 0)));

    new ValueNodeDnD(myTree, parent);
  }
  private void init() {
    enableEvents(AWTEvent.COMPONENT_EVENT_MASK);

    final JPanel contentPane = new JPanel(new BorderLayout());
    contentPane.add(myHeader, BorderLayout.NORTH);

    JPanel innerPanel = new JPanel(new BorderLayout());
    JComponent toolWindowComponent = myToolWindow.getComponent();
    innerPanel.add(toolWindowComponent, BorderLayout.CENTER);

    final NonOpaquePanel inner = new NonOpaquePanel(innerPanel);
    inner.setBorder(new EmptyBorder(-1, 0, 0, 0));

    contentPane.add(inner, BorderLayout.CENTER);
    add(contentPane, BorderLayout.CENTER);
    if (SystemInfo.isMac) {
      setBackground(new JBColor(Gray._200, Gray._90));
    }

    // Add listeners
    registerKeyboardAction(
        new ActionListener() {
          @Override
          public void actionPerformed(final ActionEvent e) {
            ToolWindowManager.getInstance(myProject).activateEditorComponent();
          }
        },
        KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0),
        JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
  }
  public NextOccurrenceAction(
      EditorSearchComponent editorSearchComponent, Getter<JTextComponent> editorTextField) {
    super(editorSearchComponent);
    myTextField = editorTextField;
    copyFrom(ActionManager.getInstance().getAction(IdeActions.ACTION_NEXT_OCCURENCE));
    ArrayList<Shortcut> shortcuts = new ArrayList<Shortcut>();
    ContainerUtil.addAll(
        shortcuts,
        ActionManager.getInstance()
            .getAction(IdeActions.ACTION_FIND_NEXT)
            .getShortcutSet()
            .getShortcuts());
    if (!editorSearchComponent.getFindModel().isMultiline()) {
      ContainerUtil.addAll(
          shortcuts,
          ActionManager.getInstance()
              .getAction(IdeActions.ACTION_EDITOR_MOVE_CARET_DOWN)
              .getShortcutSet()
              .getShortcuts());

      shortcuts.add(new KeyboardShortcut(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), null));
    }

    registerShortcutsForComponent(shortcuts, editorTextField.get());
  }
Esempio n. 8
0
 private void registerShortcuts() {
   ActionManager actionManager = ActionManager.getInstance();
   actionManager
       .getAction(XDebuggerActions.SET_VALUE)
       .registerCustomShortcutSet(
           new CustomShortcutSet(KeyStroke.getKeyStroke(KeyEvent.VK_F2, 0)), this);
   actionManager
       .getAction(XDebuggerActions.COPY_VALUE)
       .registerCustomShortcutSet(CommonShortcuts.getCopy(), this);
   actionManager
       .getAction(XDebuggerActions.JUMP_TO_SOURCE)
       .registerCustomShortcutSet(CommonShortcuts.getEditSource(), this);
   Shortcut[] editTypeShortcuts =
       KeymapManager.getInstance()
           .getActiveKeymap()
           .getShortcuts(XDebuggerActions.EDIT_TYPE_SOURCE);
   actionManager
       .getAction(XDebuggerActions.JUMP_TO_TYPE_SOURCE)
       .registerCustomShortcutSet(new CustomShortcutSet(editTypeShortcuts), this);
   actionManager
       .getAction(XDebuggerActions.MARK_OBJECT)
       .registerCustomShortcutSet(
           new CustomShortcutSet(
               KeymapManager.getInstance().getActiveKeymap().getShortcuts("ToggleBookmark")),
           this);
 }
Esempio n. 9
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;
  }
 public MyCopyAction() {
   super(CvsBundle.message("action.name.copy"), null, IconLoader.getIcon("/general/copy.png"));
   registerCustomShortcutSet(
       new CustomShortcutSet(
           KeyStroke.getKeyStroke(
               KeyEvent.VK_C, SystemInfo.isMac ? KeyEvent.META_MASK : KeyEvent.CTRL_MASK)),
       myList);
 }
 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)));
 }
  private void updateMnemonic(int lastMnemonic, int mnemonic) {
    if (mnemonic == lastMnemonic) {
      return;
    }
    InputMap windowInputMap = SwingUtilities.getUIInputMap(this, JComponent.WHEN_IN_FOCUSED_WINDOW);

    int mask = SystemInfo.isMac ? InputEvent.ALT_MASK | InputEvent.CTRL_MASK : InputEvent.ALT_MASK;
    if (lastMnemonic != 0 && windowInputMap != null) {
      windowInputMap.remove(KeyStroke.getKeyStroke(lastMnemonic, mask, false));
    }
    if (mnemonic != 0) {
      if (windowInputMap == null) {
        windowInputMap = new ComponentInputMapUIResource(this);
        SwingUtilities.replaceUIInputMap(this, JComponent.WHEN_IN_FOCUSED_WINDOW, windowInputMap);
      }
      windowInputMap.put(KeyStroke.getKeyStroke(mnemonic, mask, false), "doClick");
    }
  }
  public static String getKeystrokeText(KeyStroke accelerator) {
    if (accelerator == null) return "";
    if (SystemInfo.isMac) {
      return MacKeymapUtil.getKeyStrokeText(accelerator);
    }
    String acceleratorText = "";
    int modifiers = accelerator.getModifiers();
    if (modifiers > 0) {
      acceleratorText = getModifiersText(modifiers);
    }

    final int code = accelerator.getKeyCode();
    String keyText = SystemInfo.isMac ? MacKeymapUtil.getKeyText(code) : KeyEvent.getKeyText(code);
    // [vova] this is dirty fix for bug #35092
    if (CANCEL_KEY_TEXT.equals(keyText)) {
      keyText = BREAK_KEY_TEXT;
    }

    acceleratorText += keyText;
    return acceleratorText.trim();
  }
  private int getMnemonicCharIndex(String text) {
    final int mnemonicIndex = myPresentation.getDisplayedMnemonicIndex();
    if (mnemonicIndex != -1) {
      return mnemonicIndex;
    }
    final ShortcutSet shortcutSet = myAction.getShortcutSet();
    final Shortcut[] shortcuts = shortcutSet.getShortcuts();
    for (Shortcut shortcut : shortcuts) {
      if (!(shortcut instanceof KeyboardShortcut)) continue;

      KeyboardShortcut keyboardShortcut = (KeyboardShortcut) shortcut;
      if (keyboardShortcut.getSecondKeyStroke()
          == null) { // we are interested only in "mnemonic-like" shortcuts
        final KeyStroke keyStroke = keyboardShortcut.getFirstKeyStroke();
        final int modifiers = keyStroke.getModifiers();
        if (BitUtil.isSet(modifiers, InputEvent.ALT_MASK)) {
          return (keyStroke.getKeyChar() != KeyEvent.CHAR_UNDEFINED)
              ? text.indexOf(keyStroke.getKeyChar())
              : text.indexOf(KeyEvent.getKeyText(keyStroke.getKeyCode()));
        }
      }
    }
    return -1;
  }
  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);
    }
  }
Esempio n. 16
0
 public MyEvaluationPanel(final Project project) {
   super(project, (DebuggerManagerEx.getInstanceEx(project)).getContextManager());
   final WatchDebuggerTree watchTree = getWatchTree();
   final AnAction setValueAction =
       ActionManager.getInstance().getAction(DebuggerActions.SET_VALUE);
   setValueAction.registerCustomShortcutSet(
       new CustomShortcutSet(KeyStroke.getKeyStroke(KeyEvent.VK_F2, 0)), watchTree);
   registerDisposable(
       new Disposable() {
         public void dispose() {
           setValueAction.unregisterCustomShortcutSet(watchTree);
         }
       });
   setUpdateEnabled(true);
   getTree().getEmptyText().setText(XDebuggerBundle.message("debugger.no.results"));
   new ValueNodeDnD(myTree, project);
 }
 private static void addShortcut(
     @NotNull final String shortcutString,
     @NotNull final String actionIdString,
     boolean isAdditional) {
   Keymap keymap = KeymapManager.getInstance().getActiveKeymap();
   Shortcut[] shortcuts = keymap.getShortcuts(actionIdString);
   if (shortcuts.length > 0 && !isAdditional) {
     return;
   }
   Shortcut studyActionShortcut =
       new KeyboardShortcut(KeyStroke.getKeyStroke(shortcutString), null);
   String[] actionsIds = keymap.getActionIds(studyActionShortcut);
   for (String actionId : actionsIds) {
     myDeletedShortcuts.put(actionId, shortcutString);
     keymap.removeShortcut(actionId, studyActionShortcut);
   }
   keymap.addShortcut(actionIdString, studyActionShortcut);
 }
 @Override
 public void projectClosed() {
   //noinspection AssignmentToStaticFieldFromInstanceMethod
   StudyCondition.VALUE = false;
   if (myCourse != null) {
     ToolWindowManager.getInstance(myProject)
         .getToolWindow(StudyToolWindowFactory.STUDY_TOOL_WINDOW)
         .getContentManager()
         .removeAllContents(false);
     if (!myDeletedShortcuts.isEmpty()) {
       for (Map.Entry<String, String> shortcut : myDeletedShortcuts.entrySet()) {
         final Keymap keymap = KeymapManager.getInstance().getActiveKeymap();
         final Shortcut actionShortcut =
             new KeyboardShortcut(KeyStroke.getKeyStroke(shortcut.getValue()), null);
         keymap.addShortcut(shortcut.getKey(), actionShortcut);
       }
     }
   }
 }
 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);
 }
  @Override
  protected void installTableActions(final PluginTable pluginTable) {
    super.installTableActions(pluginTable);
    new DoubleClickListener() {
      @Override
      protected boolean onDoubleClick(MouseEvent e) {
        if (pluginTable.columnAtPoint(e.getPoint()) < 0) return false;
        if (pluginTable.rowAtPoint(e.getPoint()) < 0) return false;
        return installSelected(pluginTable);
      }
    }.installOn(pluginTable);

    pluginTable.registerKeyboardAction(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            installSelected(pluginTable);
          }
        },
        KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0),
        JComponent.WHEN_FOCUSED);
  }
  private boolean inSecondStrokeInProgressState() {
    KeyEvent e = myContext.getInputEvent();

    // when any key is released, we stop waiting for the second stroke
    if (KeyEvent.KEY_RELEASED == e.getID()) {
      myFirstKeyStroke = null;
      setState(KeyState.STATE_INIT);
      Project project = PlatformDataKeys.PROJECT.getData(myContext.getDataContext());
      StatusBar.Info.set(null, project);
      return false;
    }

    KeyStroke originalKeyStroke = KeyStroke.getKeyStrokeForEvent(e);
    KeyStroke keyStroke = getKeyStrokeWithoutMouseModifiers(originalKeyStroke);

    updateCurrentContext(
        myContext.getFoundComponent(),
        new KeyboardShortcut(myFirstKeyStroke, keyStroke),
        myContext.isModalContext());

    // consume the wrong second stroke and keep on waiting
    if (myContext.getActions().isEmpty()) {
      return true;
    }

    // finally user had managed to enter the second keystroke, so let it be processed
    Project project = PlatformDataKeys.PROJECT.getData(myContext.getDataContext());
    StatusBarEx statusBar = (StatusBarEx) WindowManager.getInstance().getStatusBar(project);
    if (processAction(e, myActionProcessor)) {
      if (statusBar != null) {
        statusBar.setInfo(null);
      }
      return true;
    } else {
      return false;
    }
  }
  private DefaultActionGroup createActionGroup() {
    DefaultActionGroup actionGroup = new DefaultActionGroup();
    if (ApplicationManager.getApplication() == null || Pico.isUnitTest()) return actionGroup;

    addRefreshAction(actionGroup);
    myOpenFileAction = new OpenFileAction(myTree, myIdeFacade);
    myOpenFileAction.registerCustomShortcutSet(
        new CustomShortcutSet(KeyStroke.getKeyStroke(KeyEvent.VK_F4, 0)), myTree);

    AnAction diffAction =
        new DiffAction(myTree) {
          protected User getUser() {
            return myUser;
          }
        };

    diffAction.registerCustomShortcutSet(CommonShortcuts.getDiff(), myTree);

    actionGroup.add(myOpenFileAction);
    actionGroup.add(diffAction);

    addToggleReadOnlyAction(actionGroup);
    return actionGroup;
  }
  private void registerActions() {
    myExternalDocAction.registerCustomShortcutSet(
        ActionManager.getInstance().getAction(IdeActions.ACTION_EXTERNAL_JAVADOC).getShortcutSet(),
        myEditorPane);

    myKeyboardActions.put(
        KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0),
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            JScrollBar scrollBar = myScrollPane.getVerticalScrollBar();
            int value = scrollBar.getValue() - scrollBar.getUnitIncrement(-1);
            value = Math.max(value, 0);
            scrollBar.setValue(value);
          }
        });

    myKeyboardActions.put(
        KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0),
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            JScrollBar scrollBar = myScrollPane.getVerticalScrollBar();
            int value = scrollBar.getValue() + scrollBar.getUnitIncrement(+1);
            value = Math.min(value, scrollBar.getMaximum());
            scrollBar.setValue(value);
          }
        });

    myKeyboardActions.put(
        KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0),
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            JScrollBar scrollBar = myScrollPane.getHorizontalScrollBar();
            int value = scrollBar.getValue() - scrollBar.getUnitIncrement(-1);
            value = Math.max(value, 0);
            scrollBar.setValue(value);
          }
        });

    myKeyboardActions.put(
        KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0),
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            JScrollBar scrollBar = myScrollPane.getHorizontalScrollBar();
            int value = scrollBar.getValue() + scrollBar.getUnitIncrement(+1);
            value = Math.min(value, scrollBar.getMaximum());
            scrollBar.setValue(value);
          }
        });

    myKeyboardActions.put(
        KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, 0),
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            JScrollBar scrollBar = myScrollPane.getVerticalScrollBar();
            int value = scrollBar.getValue() - scrollBar.getBlockIncrement(-1);
            value = Math.max(value, 0);
            scrollBar.setValue(value);
          }
        });

    myKeyboardActions.put(
        KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_DOWN, 0),
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            JScrollBar scrollBar = myScrollPane.getVerticalScrollBar();
            int value = scrollBar.getValue() + scrollBar.getBlockIncrement(+1);
            value = Math.min(value, scrollBar.getMaximum());
            scrollBar.setValue(value);
          }
        });

    myKeyboardActions.put(
        KeyStroke.getKeyStroke(KeyEvent.VK_HOME, 0),
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            JScrollBar scrollBar = myScrollPane.getHorizontalScrollBar();
            scrollBar.setValue(0);
          }
        });

    myKeyboardActions.put(
        KeyStroke.getKeyStroke(KeyEvent.VK_END, 0),
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            JScrollBar scrollBar = myScrollPane.getHorizontalScrollBar();
            scrollBar.setValue(scrollBar.getMaximum());
          }
        });

    myKeyboardActions.put(
        KeyStroke.getKeyStroke(KeyEvent.VK_HOME, KeyEvent.CTRL_MASK),
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            JScrollBar scrollBar = myScrollPane.getVerticalScrollBar();
            scrollBar.setValue(0);
          }
        });

    myKeyboardActions.put(
        KeyStroke.getKeyStroke(KeyEvent.VK_END, KeyEvent.CTRL_MASK),
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            JScrollBar scrollBar = myScrollPane.getVerticalScrollBar();
            scrollBar.setValue(scrollBar.getMaximum());
          }
        });
  }
  private static JBPopup getPsiElementPopup(
      final Object[] elements,
      final Map<PsiElement, GotoRelatedItem> itemsMap,
      final String title,
      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) {
            PsiFile file = element.getContainingFile();
            return file != null && !getElementText(element).equals(file.getName())
                ? "(" + file.getName() + ")"
                : null;
          }

          @Override
          protected DefaultListCellRenderer getRightCellRenderer() {
            return 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(Font.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.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 PopupStep onChosen(Object selectedValue, boolean finalChoice) {
                processor.process(selectedValue);
                return super.onChosen(selectedValue, finalChoice);
              }
            }) {
          @Override
          protected ListCellRenderer getListElementRenderer() {
            return renderer;
          }
        };
    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);
        hasMnemonic.set(true);
      }
    }
    return popup;
  }
Esempio n. 25
0
 private static boolean isEnterKeyStroke(KeyStroke keyStroke) {
   return keyStroke.getKeyCode() == KeyEvent.VK_ENTER && keyStroke.getModifiers() == 0;
 }
  protected ActionCallback _execute(final PlaybackContext context) {
    final String actionName = getText().substring(PREFIX.length()).trim();

    final ActionManager am = ActionManager.getInstance();
    final AnAction targetAction = am.getAction(actionName);
    if (targetAction == null) {
      dumpError(context, "Unknown action: " + actionName);
      return new ActionCallback.Rejected();
    }

    if (!context.isUseDirectActionCall()) {
      final Shortcut[] sc = KeymapManager.getInstance().getActiveKeymap().getShortcuts(actionName);
      KeyStroke stroke = null;
      for (Shortcut each : sc) {
        if (each instanceof KeyboardShortcut) {
          final KeyboardShortcut ks = (KeyboardShortcut) each;
          final KeyStroke first = ks.getFirstKeyStroke();
          final KeyStroke second = ks.getSecondKeyStroke();
          if (first != null && second == null) {
            stroke = KeyStroke.getKeyStroke(first.getKeyCode(), first.getModifiers(), false);
            break;
          }
        }
      }

      if (stroke != null) {
        final ActionCallback result =
            new TimedOutCallback(
                Registry.intValue("actionSystem.commandProcessingTimeout"),
                "Timed out calling action id=" + actionName,
                new Throwable(),
                true) {
              @Override
              protected void dumpError() {
                context.error(getMessage(), getLine());
              }
            };
        context.message("Invoking action via shortcut: " + stroke.toString(), getLine());

        final KeyStroke finalStroke = stroke;

        IdeFocusManager.getGlobalInstance()
            .doWhenFocusSettlesDown(
                new Runnable() {
                  @Override
                  public void run() {
                    final Ref<AnActionListener> listener = new Ref<AnActionListener>();
                    listener.set(
                        new AnActionListener.Adapter() {

                          @Override
                          public void beforeActionPerformed(
                              final AnAction action, DataContext dataContext, AnActionEvent event) {
                            SwingUtilities.invokeLater(
                                new Runnable() {
                                  @Override
                                  public void run() {
                                    if (context.isDisposed()) {
                                      am.removeAnActionListener(listener.get());
                                      return;
                                    }

                                    if (targetAction.equals(action)) {
                                      context.message(
                                          "Performed action: " + actionName,
                                          context.getCurrentLine());
                                      am.removeAnActionListener(listener.get());
                                      result.setDone();
                                    }
                                  }
                                });
                          }
                        });
                    am.addAnActionListener(listener.get());

                    context.runPooledThread(
                        new Runnable() {
                          @Override
                          public void run() {
                            type(context.getRobot(), finalStroke);
                          }
                        });
                  }
                });

        return result;
      }
    }

    final InputEvent input = getInputEvent(actionName);

    final ActionCallback result = new ActionCallback();

    context.getRobot().delay(Registry.intValue("actionSystem.playback.delay"));
    SwingUtilities.invokeLater(
        new Runnable() {
          public void run() {
            am.tryToExecute(targetAction, input, null, null, false)
                .doWhenProcessed(result.createSetDoneRunnable());
          }
        });

    return result;
  }
  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();
          }
        });
  }
  public ArrangementSettingsPanel(@NotNull CodeStyleSettings settings, @NotNull Language language) {
    super(settings);
    myLanguage = language;
    Rearranger<?> rearranger = Rearranger.EXTENSION.forLanguage(language);

    assert rearranger instanceof ArrangementStandardSettingsAware;
    mySettingsAware = (ArrangementStandardSettingsAware) rearranger;

    final ArrangementColorsProvider colorsProvider;
    if (rearranger instanceof ArrangementColorsAware) {
      colorsProvider = new ArrangementColorsProviderImpl((ArrangementColorsAware) rearranger);
    } else {
      colorsProvider = new ArrangementColorsProviderImpl(null);
    }

    ArrangementStandardSettingsManager settingsManager =
        new ArrangementStandardSettingsManager(mySettingsAware, colorsProvider);

    myGroupingRulesPanel = new ArrangementGroupingRulesPanel(settingsManager, colorsProvider);
    myMatchingRulesPanel =
        new ArrangementMatchingRulesPanel(myLanguage, settingsManager, colorsProvider);

    myContent.add(
        myGroupingRulesPanel, new GridBag().coverLine().fillCellHorizontally().weightx(1));
    myContent.add(myMatchingRulesPanel, new GridBag().fillCell().weightx(1).weighty(1).coverLine());

    if (settings.getCommonSettings(myLanguage).isForceArrangeMenuAvailable()) {
      myForceArrangementPanel = new ForceArrangementPanel();
      myForceArrangementPanel.setSelectedMode(
          settings.getCommonSettings(language).FORCE_REARRANGE_MODE);
      myContent.add(
          myForceArrangementPanel.getPanel(),
          new GridBag().anchor(GridBagConstraints.WEST).coverLine().fillCellHorizontally());
    } else {
      myForceArrangementPanel = null;
    }

    final List<CompositeArrangementSettingsToken> groupingTokens =
        settingsManager.getSupportedGroupingTokens();
    myGroupingRulesPanel.setVisible(groupingTokens != null && !groupingTokens.isEmpty());

    registerShortcut(
        ArrangementConstants.MATCHING_RULE_ADD, CommonShortcuts.getNew(), myMatchingRulesPanel);
    registerShortcut(
        ArrangementConstants.MATCHING_RULE_REMOVE,
        CommonShortcuts.getDelete(),
        myMatchingRulesPanel);
    registerShortcut(
        ArrangementConstants.MATCHING_RULE_MOVE_UP, CommonShortcuts.MOVE_UP, myMatchingRulesPanel);
    registerShortcut(
        ArrangementConstants.MATCHING_RULE_MOVE_DOWN,
        CommonShortcuts.MOVE_DOWN,
        myMatchingRulesPanel);
    final CustomShortcutSet edit = new CustomShortcutSet(KeyStroke.getKeyStroke(KeyEvent.VK_F2, 0));
    registerShortcut(ArrangementConstants.MATCHING_RULE_EDIT, edit, myMatchingRulesPanel);

    registerShortcut(
        ArrangementConstants.GROUPING_RULE_MOVE_UP, CommonShortcuts.MOVE_UP, myGroupingRulesPanel);
    registerShortcut(
        ArrangementConstants.GROUPING_RULE_MOVE_DOWN,
        CommonShortcuts.MOVE_DOWN,
        myGroupingRulesPanel);
  }
  public XWatchesViewImpl(
      @NotNull final XDebugSession session, final @NotNull XDebugSessionData sessionData) {
    mySession = session;
    mySessionData = sessionData;
    myTreePanel =
        new XDebuggerTreePanel(
            session.getProject(),
            session.getDebugProcess().getEditorsProvider(),
            this,
            null,
            XDebuggerActions.WATCHES_TREE_POPUP_GROUP,
            ((XDebugSessionImpl) session).getValueMarkers());

    ActionManager actionManager = ActionManager.getInstance();

    XDebuggerTree tree = myTreePanel.getTree();
    actionManager
        .getAction(XDebuggerActions.XNEW_WATCH)
        .registerCustomShortcutSet(CommonShortcuts.INSERT, tree);
    actionManager
        .getAction(XDebuggerActions.XREMOVE_WATCH)
        .registerCustomShortcutSet(CommonShortcuts.DELETE, tree);

    CustomShortcutSet f2Shortcut = new CustomShortcutSet(KeyStroke.getKeyStroke(KeyEvent.VK_F2, 0));
    actionManager
        .getAction(XDebuggerActions.XEDIT_WATCH)
        .registerCustomShortcutSet(f2Shortcut, tree);

    DnDManager.getInstance().registerTarget(this, tree);
    myRootNode = new WatchesRootNode(tree, session, this, sessionData.getWatchExpressions());
    tree.setRoot(myRootNode, false);

    final ToolbarDecorator decorator =
        ToolbarDecorator.createDecorator(myTreePanel.getTree()).disableUpDownActions();
    decorator.setAddAction(
        new AnActionButtonRunnable() {
          @Override
          public void run(AnActionButton button) {
            executeAction(XDebuggerActions.XNEW_WATCH);
          }
        });
    decorator.setRemoveAction(
        new AnActionButtonRunnable() {
          @Override
          public void run(AnActionButton button) {
            executeAction(XDebuggerActions.XREMOVE_WATCH);
          }
        });
    CustomLineBorder border =
        new CustomLineBorder(
            CaptionPanel.CNT_ACTIVE_BORDER_COLOR,
            SystemInfo.isMac ? 1 : 0,
            0,
            SystemInfo.isMac ? 0 : 1,
            0);
    decorator.setToolbarBorder(border);
    myDecoratedPanel = decorator.createPanel();
    myDecoratedPanel.setBorder(null);

    myTreePanel.getTree().getEmptyText().setText(XDebuggerBundle.message("debugger.no.watches"));
  }