private void layoutPanel() {
    if (myUsagePreviewPanel != null) {
      Disposer.dispose(myUsagePreviewPanel);
    }
    removeAll();
    JScrollPane pane = ScrollPaneFactory.createScrollPane(myTree);

    if (isPreview()) {
      pane.setBorder(IdeBorderFactory.createBorder(SideBorder.LEFT | SideBorder.RIGHT));

      boolean vertical =
          myToolWindow.getAnchor() == ToolWindowAnchor.LEFT
              || myToolWindow.getAnchor() == ToolWindowAnchor.RIGHT;
      Splitter splitter =
          new Splitter(
              vertical, UsageViewSettings.getInstance().PREVIEW_USAGES_SPLITTER_PROPORTIONS);
      splitter.setFirstComponent(pane);
      myUsagePreviewPanel = new UsagePreviewPanel(myProject, new UsageViewPresentation());
      myUsagePreviewPanel.setBorder(IdeBorderFactory.createBorder(SideBorder.LEFT));

      Disposer.register(this, myUsagePreviewPanel);
      splitter.setSecondComponent(myUsagePreviewPanel);
      add(splitter, BorderLayout.CENTER);
    } else {
      pane.setBorder(IdeBorderFactory.createBorder(SideBorder.LEFT));
      add(pane, BorderLayout.CENTER);
    }

    add(createToolbar().getComponent(), BorderLayout.WEST);

    myTree.getParent().setBackground(UIManager.getColor("Tree.background"));

    revalidate();
  }
 public void setupCorners() {
   setBorder(IdeBorderFactory.createBorder());
   setCorner(UPPER_RIGHT_CORNER, new Corner(UPPER_RIGHT_CORNER));
   setCorner(UPPER_LEFT_CORNER, new Corner(UPPER_LEFT_CORNER));
   setCorner(LOWER_RIGHT_CORNER, new Corner(LOWER_RIGHT_CORNER));
   setCorner(LOWER_LEFT_CORNER, new Corner(LOWER_LEFT_CORNER));
 }
  private RepositoryChangesBrowser createRepositoryChangesBrowser(final Project project) {
    TableView<ChangeInfo> table = changeListPanel.getTable();

    RepositoryChangesBrowser repositoryChangesBrowser =
        new RepositoryChangesBrowser(
            project,
            Collections.<CommittedChangeList>emptyList(),
            Collections.<Change>emptyList(),
            null);
    repositoryChangesBrowser
        .getDiffAction()
        .registerCustomShortcutSet(CommonShortcuts.getDiff(), table);
    repositoryChangesBrowser
        .getViewer()
        .setScrollPaneBorder(IdeBorderFactory.createBorder(SideBorder.LEFT | SideBorder.TOP));

    changeListPanel.addListSelectionListener(
        new Consumer<ChangeInfo>() {
          @Override
          public void consume(ChangeInfo changeInfo) {
            changeSelected(changeInfo, project);
          }
        });
    return repositoryChangesBrowser;
  }
  private void setupCentralPanel() {
    myCentralPanel.removeAll();
    if (myUsagePreviewPanel != null) {
      Disposer.dispose(myUsagePreviewPanel);
      myUsagePreviewPanel = null;
    }
    JScrollPane pane = ScrollPaneFactory.createScrollPane(myTree);

    if (UsageViewSettings.getInstance().IS_PREVIEW_USAGES) {
      Splitter splitter =
          new Splitter(false, UsageViewSettings.getInstance().PREVIEW_USAGES_SPLITTER_PROPORTIONS);
      pane.putClientProperty(UIUtil.KEEP_BORDER_SIDES, SideBorder.RIGHT);

      splitter.setFirstComponent(pane);
      myUsagePreviewPanel = new UsagePreviewPanel(myProject);
      myUsagePreviewPanel.setBorder(IdeBorderFactory.createBorder(SideBorder.LEFT));
      Disposer.register(this, myUsagePreviewPanel);
      splitter.setSecondComponent(myUsagePreviewPanel);
      myCentralPanel.add(splitter, BorderLayout.CENTER);
    } else {
      myCentralPanel.add(pane, BorderLayout.CENTER);
    }
    myCentralPanel.add(myButtonPanel, BorderLayout.SOUTH);

    myRootPanel.revalidate();
  }
Beispiel #5
0
  @Override
  public VcsDependentHistoryComponents getUICustomization(
      final VcsHistorySession session, JComponent forShortcutRegistration) {
    final ColumnInfo[] columns;
    final Consumer<VcsFileRevision> listener;
    final JComponent addComp;
    if (((SvnHistorySession) session).isHaveMergeSources()) {
      final MergeSourceColumnInfo mergeSourceColumn =
          new MergeSourceColumnInfo((SvnHistorySession) session);
      columns = new ColumnInfo[] {new CopyFromColumnInfo(), mergeSourceColumn};

      final JPanel panel = new JPanel(new BorderLayout());

      final JTextArea field = new JTextArea();
      field.setEditable(false);
      field.setBackground(UIUtil.getComboBoxDisabledBackground());
      field.setWrapStyleWord(true);
      listener =
          new Consumer<VcsFileRevision>() {
            @Override
            public void consume(VcsFileRevision vcsFileRevision) {
              field.setText(mergeSourceColumn.getText(vcsFileRevision));
            }
          };

      final MergeSourceDetailsAction sourceAction = new MergeSourceDetailsAction();
      sourceAction.registerSelf(forShortcutRegistration);

      JPanel fieldPanel =
          new ToolbarDecorator() {
            @Override
            protected JComponent getComponent() {
              return field;
            }

            @Override
            protected void updateButtons() {}

            @Override
            protected void installDnDSupport() {}

            @Override
            protected boolean isModelEditable() {
              return false;
            }
          }.initPosition().addExtraAction(AnActionButton.fromAction(sourceAction)).createPanel();
      fieldPanel.setBorder(IdeBorderFactory.createBorder(SideBorder.LEFT | SideBorder.TOP));

      panel.add(fieldPanel, BorderLayout.CENTER);
      panel.add(new JLabel("Merge Sources:"), BorderLayout.NORTH);
      addComp = panel;
    } else {
      columns = new ColumnInfo[] {new CopyFromColumnInfo()};
      addComp = null;
      listener = null;
    }
    return new VcsDependentHistoryComponents(columns, listener, addComp);
  }
 protected JComponent createCenterPanel() {
   JScrollPane scrollPane = ScrollPaneFactory.createScrollPane(myTree);
   scrollPane.setBorder(IdeBorderFactory.createBorder(SideBorder.LEFT));
   myCenterPanel.add(CARD_STATUS, scrollPane);
   myTreeBrowser =
       new CommittedChangesTreeBrowser(myProject, Collections.<CommittedChangeList>emptyList());
   Disposer.register(this, myTreeBrowser);
   myTreeBrowser.setHelpId(getHelpId());
   myCenterPanel.add(CARD_CHANGES, myTreeBrowser);
   return myCenterPanel;
 }
  @Override
  public void createToolWindowContent(final Project project, ToolWindow toolWindow) {
    Component component = toolWindow.getComponent();

    changeListPanel = new GerritChangeListPanel(Lists.<ChangeInfo>newArrayList(), null);

    SimpleToolWindowPanel panel = new SimpleToolWindowPanel(false, true);

    ActionToolbar toolbar = createToolbar();
    toolbar.setTargetComponent(changeListPanel);
    panel.setToolbar(toolbar.getComponent());

    myRepositoryChangesBrowser = createRepositoryChangesBrowser(project);

    myDetailsSplitter = new Splitter(true, 0.6f);
    myDetailsSplitter.setShowDividerControls(true);

    changeListPanel.setBorder(
        IdeBorderFactory.createBorder(SideBorder.TOP | SideBorder.RIGHT | SideBorder.BOTTOM));
    myDetailsSplitter.setFirstComponent(changeListPanel);

    myDetailsPanel = new GerritChangeDetailsPanel(project);
    JPanel details = myDetailsPanel.getComponent();
    details.setBorder(IdeBorderFactory.createBorder(SideBorder.TOP | SideBorder.RIGHT));
    myDetailsSplitter.setSecondComponent(details);

    Splitter myHorizontalSplitter = new Splitter(false, 0.7f);
    myHorizontalSplitter.setShowDividerControls(true);
    myHorizontalSplitter.setFirstComponent(myDetailsSplitter);
    myHorizontalSplitter.setSecondComponent(myRepositoryChangesBrowser);

    panel.setContent(myHorizontalSplitter);

    component.getParent().add(panel);

    reloadChanges(project, false);

    setupRefreshTask(project);
  }
Beispiel #8
0
  private JComponent getLibrariesTable() {
    myLibraryTableModel = new LibraryTableModel();
    final JBTable librariesTable = new JBTable(myLibraryTableModel);
    librariesTable.setTableHeader(null);
    librariesTable.setDefaultRenderer(String.class, new MyPathRenderer());
    librariesTable.setShowHorizontalLines(false);
    librariesTable.setShowVerticalLines(false);
    librariesTable.setAutoCreateRowSorter(false);
    librariesTable.setAutoscrolls(true);

    ToolbarDecorator decorator = ToolbarDecorator.createDecorator(librariesTable);
    decorator
        .setAddAction(
            new AnActionButtonRunnable() {
              @Override
              public void run(AnActionButton anActionButton) {
                List<ModelRootDescriptor> modelRoots =
                    new ArrayList<ModelRootDescriptor>(
                        myJavaModuleFacet
                            .getModule()
                            .getModuleDescriptor()
                            .getModelRootDescriptors());
                StubRootChooser stubRootChooser =
                    new StubRootChooser(
                        modelRoots,
                        (myJavaModuleFacet.getModule() instanceof Language ? true : false));
                myLibraryTableModel.addAll(stubRootChooser.compute());
              }
            })
        .setRemoveAction(
            new AnActionButtonRunnable() {
              @Override
              public void run(AnActionButton anActionButton) {
                TableUtil.removeSelectedItems(librariesTable);
                myLibraryTableModel.fireTableDataChanged();
              }
            });
    decorator.setToolbarBorder(IdeBorderFactory.createBorder());
    decorator.setPreferredSize(new Dimension(500, 100));

    JPanel table = decorator.createPanel();
    table.setBorder(
        IdeBorderFactory.createTitledBorder(
            PropertiesBundle.message("mps.properties.configurable.module.javatab.librariesborder"),
            false));
    return table;
  }
    public void addButtonRunnable(int index, final Runnable runnable, String text) {
      if (getBorder() == null) setBorder(IdeBorderFactory.createBorder(SideBorder.TOP));

      final JButton button = new JButton(UIUtil.replaceMnemonicAmpersand(text));
      DialogUtil.registerMnemonic(button);

      button.setFocusable(false);
      button.addActionListener(
          new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
              runnable.run();
            }
          });

      add(button, index);

      invalidate();
      if (getParent() != null) {
        getParent().validate();
      }
    }
Beispiel #10
0
  private JComponent getSourcePathsTable() {
    myPathsTableModel = new PathsTableModel();
    final JBTable sourcePathTable = new JBTable(myPathsTableModel);
    sourcePathTable.setTableHeader(null);
    sourcePathTable.setDefaultRenderer(String.class, new MyPathRenderer());
    sourcePathTable.setShowHorizontalLines(false);
    sourcePathTable.setShowVerticalLines(false);
    sourcePathTable.setAutoCreateRowSorter(false);
    sourcePathTable.setAutoscrolls(true);

    ToolbarDecorator decorator = ToolbarDecorator.createDecorator(sourcePathTable);
    decorator
        .setAddAction(
            new AnActionButtonRunnable() {
              @Override
              public void run(AnActionButton anActionButton) {
                myPathsTableModel.add((new PathChooser()).compute());
              }
            })
        .setRemoveAction(
            new AnActionButtonRunnable() {
              @Override
              public void run(AnActionButton anActionButton) {
                TableUtil.removeSelectedItems(sourcePathTable);
                myPathsTableModel.fireTableDataChanged();
              }
            });
    decorator.setToolbarBorder(IdeBorderFactory.createBorder());
    decorator.setPreferredSize(new Dimension(500, 100));

    JPanel table = decorator.createPanel();
    table.setBorder(
        IdeBorderFactory.createTitledBorder(
            PropertiesBundle.message("mps.properties.configurable.module.javatab.sourcepathborder"),
            false));
    return table;
  }
  public JComponent createCenterPanel() {
    List<FileStructureFilter> fileStructureFilters = new ArrayList<FileStructureFilter>();
    List<FileStructureNodeProvider> fileStructureNodeProviders =
        new ArrayList<FileStructureNodeProvider>();
    if (myTreeActionsOwner != null) {
      for (Filter filter : myBaseTreeModel.getFilters()) {
        if (filter instanceof FileStructureFilter) {
          final FileStructureFilter fsFilter = (FileStructureFilter) filter;
          myTreeActionsOwner.setActionIncluded(fsFilter, true);
          fileStructureFilters.add(fsFilter);
        }
      }

      if (myBaseTreeModel instanceof ProvidingTreeModel) {
        for (NodeProvider provider : ((ProvidingTreeModel) myBaseTreeModel).getNodeProviders()) {
          if (provider instanceof FileStructureNodeProvider) {
            fileStructureNodeProviders.add((FileStructureNodeProvider) provider);
          }
        }
      }
    }
    final JPanel panel = new JPanel(new BorderLayout());
    JPanel comboPanel = new JPanel(new GridLayout(0, 2, 0, 0));

    final Shortcut[] F4 =
        ActionManager.getInstance()
            .getAction(IdeActions.ACTION_EDIT_SOURCE)
            .getShortcutSet()
            .getShortcuts();
    final Shortcut[] ENTER = CustomShortcutSet.fromString("ENTER").getShortcuts();
    final CustomShortcutSet shortcutSet = new CustomShortcutSet(ArrayUtil.mergeArrays(F4, ENTER));
    new AnAction() {
      public void actionPerformed(AnActionEvent e) {
        final boolean succeeded = navigateSelectedElement();
        if (succeeded) {
          unregisterCustomShortcutSet(panel);
        }
      }
    }.registerCustomShortcutSet(shortcutSet, panel);

    new AnAction() {
      public void actionPerformed(AnActionEvent e) {
        if (mySpeedSearch != null && mySpeedSearch.isPopupActive()) {
          mySpeedSearch.hidePopup();
        } else {
          myPopup.cancel();
        }
      }
    }.registerCustomShortcutSet(CustomShortcutSet.fromString("ESCAPE"), myTree);

    new ClickListener() {
      @Override
      public boolean onClick(MouseEvent e, int clickCount) {
        navigateSelectedElement();
        return true;
      }
    }.installOn(myTree);

    for (FileStructureFilter filter : fileStructureFilters) {
      addCheckbox(comboPanel, filter);
    }

    for (FileStructureNodeProvider provider : fileStructureNodeProviders) {
      addCheckbox(comboPanel, provider);
    }
    myPreferredWidth = Math.max(comboPanel.getPreferredSize().width, 350);
    panel.add(comboPanel, BorderLayout.NORTH);
    JScrollPane scrollPane = ScrollPaneFactory.createScrollPane(myAbstractTreeBuilder.getTree());
    scrollPane.setBorder(IdeBorderFactory.createBorder(SideBorder.TOP | SideBorder.BOTTOM));
    panel.add(scrollPane, BorderLayout.CENTER);
    panel.add(createSouthPanel(), BorderLayout.SOUTH);
    DataManager.registerDataProvider(
        panel,
        new DataProvider() {
          @Override
          public Object getData(@NonNls String dataId) {
            if (PlatformDataKeys.PROJECT.is(dataId)) {
              return myProject;
            }
            if (LangDataKeys.PSI_ELEMENT.is(dataId)) {
              final Object node =
                  ContainerUtil.getFirstItem(myAbstractTreeBuilder.getSelectedElements());
              if (!(node instanceof FilteringTreeStructure.FilteringNode)) return null;
              return getPsi((FilteringTreeStructure.FilteringNode) node);
            }
            if (LangDataKeys.POSITION_ADJUSTER_POPUP.is(dataId)) {
              return myPopup;
            }
            if (PlatformDataKeys.TREE_EXPANDER.is(dataId)) {
              return myTreeExpander;
            }
            return null;
          }
        });

    return panel;
  }
  public DocumentationComponent(
      final DocumentationManager manager, final AnAction[] additionalActions) {
    myManager = manager;
    myIsEmpty = true;
    myIsShown = false;

    myEditorPane =
        new JEditorPane(UIUtil.HTML_MIME, "") {
          @Override
          public Dimension getPreferredScrollableViewportSize() {
            if (getWidth() == 0 || getHeight() == 0) {
              setSize(MAX_WIDTH, MAX_HEIGHT);
            }
            Insets ins = myEditorPane.getInsets();
            View rootView = myEditorPane.getUI().getRootView(myEditorPane);
            rootView.setSize(
                MAX_WIDTH,
                MAX_HEIGHT); // Necessary! Without this line, size will not increase then you go
            // from small page to bigger one
            int prefHeight = (int) rootView.getPreferredSpan(View.Y_AXIS);
            prefHeight +=
                ins.bottom
                    + ins.top
                    + myScrollPane.getHorizontalScrollBar().getMaximumSize().height;
            return new Dimension(MAX_WIDTH, Math.max(MIN_HEIGHT, Math.min(MAX_HEIGHT, prefHeight)));
          }

          {
            enableEvents(AWTEvent.KEY_EVENT_MASK);
          }

          @Override
          protected void processKeyEvent(KeyEvent e) {
            KeyStroke keyStroke = KeyStroke.getKeyStrokeForEvent(e);
            ActionListener listener = myKeyboardActions.get(keyStroke);
            if (listener != null) {
              listener.actionPerformed(new ActionEvent(DocumentationComponent.this, 0, ""));
              e.consume();
              return;
            }
            super.processKeyEvent(e);
          }

          @Override
          protected void paintComponent(Graphics g) {
            GraphicsUtil.setupAntialiasing(g);
            super.paintComponent(g);
          }
        };
    DataProvider helpDataProvider =
        new DataProvider() {
          @Override
          public Object getData(@NonNls String dataId) {
            return PlatformDataKeys.HELP_ID.is(dataId) ? DOCUMENTATION_TOPIC_ID : null;
          }
        };
    myEditorPane.putClientProperty(DataManager.CLIENT_PROPERTY_DATA_PROVIDER, helpDataProvider);
    myText = "";
    myEditorPane.setEditable(false);
    myEditorPane.setBackground(HintUtil.INFORMATION_COLOR);
    myEditorPane.setEditorKit(UIUtil.getHTMLEditorKit());
    myScrollPane =
        new JBScrollPane(myEditorPane) {
          @Override
          protected void processMouseWheelEvent(MouseWheelEvent e) {
            if (!EditorSettingsExternalizable.getInstance().isWheelFontChangeEnabled()
                || !EditorUtil.isChangeFontSize(e)) {
              super.processMouseWheelEvent(e);
              return;
            }

            int change = Math.abs(e.getWheelRotation());
            boolean increase = e.getWheelRotation() <= 0;
            EditorColorsManager colorsManager = EditorColorsManager.getInstance();
            EditorColorsScheme scheme = colorsManager.getGlobalScheme();
            FontSize newFontSize = scheme.getQuickDocFontSize();
            for (; change > 0; change--) {
              if (increase) {
                newFontSize = newFontSize.larger();
              } else {
                newFontSize = newFontSize.smaller();
              }
            }

            if (newFontSize == scheme.getQuickDocFontSize()) {
              return;
            }

            scheme.setQuickDocFontSize(newFontSize);
            applyFontSize();
            setFontSizeSliderSize(newFontSize);
          }
        };
    myScrollPane.setBorder(null);
    myScrollPane.putClientProperty(DataManager.CLIENT_PROPERTY_DATA_PROVIDER, helpDataProvider);

    final MouseAdapter mouseAdapter =
        new MouseAdapter() {
          @Override
          public void mousePressed(MouseEvent e) {
            myManager.requestFocus();
            myShowSettingsButton.hideSettings();
          }
        };
    myEditorPane.addMouseListener(mouseAdapter);
    Disposer.register(
        this,
        new Disposable() {
          @Override
          public void dispose() {
            myEditorPane.removeMouseListener(mouseAdapter);
          }
        });

    final FocusAdapter focusAdapter =
        new FocusAdapter() {
          @Override
          public void focusLost(FocusEvent e) {
            Component previouslyFocused =
                WindowManagerEx.getInstanceEx()
                    .getFocusedComponent(manager.getProject(getElement()));

            if (!(previouslyFocused == myEditorPane)) {
              if (myHint != null && !myHint.isDisposed()) myHint.cancel();
            }
          }
        };
    myEditorPane.addFocusListener(focusAdapter);

    Disposer.register(
        this,
        new Disposable() {
          @Override
          public void dispose() {
            myEditorPane.removeFocusListener(focusAdapter);
          }
        });

    setLayout(new BorderLayout());
    JLayeredPane layeredPane =
        new JBLayeredPane() {
          @Override
          public void doLayout() {
            final Rectangle r = getBounds();
            for (Component component : getComponents()) {
              if (component instanceof JScrollPane) {
                component.setBounds(0, 0, r.width, r.height);
              } else {
                int insets = 2;
                Dimension d = component.getPreferredSize();
                component.setBounds(r.width - d.width - insets, insets, d.width, d.height);
              }
            }
          }

          @Override
          public Dimension getPreferredSize() {
            Dimension editorPaneSize = myEditorPane.getPreferredScrollableViewportSize();
            Dimension controlPanelSize = myControlPanel.getPreferredSize();
            return new Dimension(
                Math.max(editorPaneSize.width, controlPanelSize.width),
                editorPaneSize.height + controlPanelSize.height);
          }
        };
    layeredPane.add(myScrollPane);
    layeredPane.setLayer(myScrollPane, 0);

    mySettingsPanel = createSettingsPanel();
    layeredPane.add(mySettingsPanel);
    layeredPane.setLayer(mySettingsPanel, JLayeredPane.POPUP_LAYER);
    add(layeredPane, BorderLayout.CENTER);
    setOpaque(true);
    myScrollPane.setViewportBorder(JBScrollPane.createIndentBorder());

    final DefaultActionGroup actions = new DefaultActionGroup();
    final BackAction back = new BackAction();
    final ForwardAction forward = new ForwardAction();
    actions.add(back);
    actions.add(forward);
    actions.add(myExternalDocAction = new ExternalDocAction());
    back.registerCustomShortcutSet(CustomShortcutSet.fromString("LEFT"), this);
    forward.registerCustomShortcutSet(CustomShortcutSet.fromString("RIGHT"), this);
    myExternalDocAction.registerCustomShortcutSet(CustomShortcutSet.fromString("UP"), this);
    if (additionalActions != null) {
      for (final AnAction action : additionalActions) {
        actions.add(action);
      }
    }

    myToolBar =
        ActionManager.getInstance()
            .createActionToolbar(ActionPlaces.JAVADOC_TOOLBAR, actions, true);

    myControlPanel = new JPanel();
    myControlPanel.setLayout(new BorderLayout());
    myControlPanel.setBorder(IdeBorderFactory.createBorder(SideBorder.BOTTOM));
    JPanel dummyPanel = new JPanel();

    myElementLabel = new JLabel();

    dummyPanel.setLayout(new BorderLayout());
    dummyPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 5));

    dummyPanel.add(myElementLabel, BorderLayout.EAST);

    myControlPanel.add(myToolBar.getComponent(), BorderLayout.WEST);
    myControlPanel.add(dummyPanel, BorderLayout.CENTER);
    myControlPanel.add(myShowSettingsButton = new MyShowSettingsButton(), BorderLayout.EAST);
    myControlPanelVisible = false;

    final HyperlinkListener hyperlinkListener =
        new HyperlinkListener() {
          @Override
          public void hyperlinkUpdate(HyperlinkEvent e) {
            HyperlinkEvent.EventType type = e.getEventType();
            if (type == HyperlinkEvent.EventType.ACTIVATED) {
              manager.navigateByLink(DocumentationComponent.this, e.getDescription());
            }
          }
        };
    myEditorPane.addHyperlinkListener(hyperlinkListener);
    Disposer.register(
        this,
        new Disposable() {
          @Override
          public void dispose() {
            myEditorPane.removeHyperlinkListener(hyperlinkListener);
          }
        });

    registerActions();

    updateControlState();
  }
  public ImplementationViewComponent(PsiElement[] elements, final int index) {
    super(new BorderLayout());

    final Project project = elements.length > 0 ? elements[0].getProject() : null;
    EditorFactory factory = EditorFactory.getInstance();
    Document doc = factory.createDocument("");
    doc.setReadOnly(true);
    myEditor = factory.createEditor(doc, project);
    ((EditorEx) myEditor).setBackgroundColor(EditorFragmentComponent.getBackgroundColor(myEditor));

    final EditorSettings settings = myEditor.getSettings();
    settings.setAdditionalLinesCount(1);
    settings.setAdditionalColumnsCount(1);
    settings.setLineMarkerAreaShown(false);
    settings.setIndentGuidesShown(false);
    settings.setLineNumbersShown(false);
    settings.setFoldingOutlineShown(false);

    myBinarySwitch = new CardLayout();
    myViewingPanel = new JPanel(myBinarySwitch);
    myEditor.setBorder(null);
    ((EditorEx) myEditor).getScrollPane().setViewportBorder(JBScrollPane.createIndentBorder());
    myViewingPanel.add(myEditor.getComponent(), TEXT_PAGE_KEY);

    myBinaryPanel = new JPanel(new BorderLayout());
    myViewingPanel.add(myBinaryPanel, BINARY_PAGE_KEY);

    add(myViewingPanel, BorderLayout.CENTER);

    myToolbar = createToolbar();
    myLocationLabel = new JLabel();
    myCountLabel = new JLabel();

    final JPanel header = new JPanel(new BorderLayout(2, 0));
    header.setBorder(
        BorderFactory.createCompoundBorder(
            IdeBorderFactory.createBorder(SideBorder.BOTTOM),
            IdeBorderFactory.createEmptyBorder(0, 0, 0, 5)));
    final JPanel toolbarPanel = new JPanel(new GridBagLayout());
    final GridBagConstraints gc =
        new GridBagConstraints(
            GridBagConstraints.RELATIVE,
            0,
            1,
            1,
            0,
            0,
            GridBagConstraints.WEST,
            GridBagConstraints.NONE,
            new Insets(0, 2, 0, 0),
            0,
            0);
    toolbarPanel.add(myToolbar.getComponent(), gc);

    setPreferredSize(new Dimension(600, 400));

    update(
        elements,
        new PairFunction<PsiElement[], List<FileDescriptor>, Boolean>() {
          @Override
          public Boolean fun(
              final PsiElement[] psiElements, final List<FileDescriptor> fileDescriptors) {
            if (psiElements.length == 0) return false;
            myElements = psiElements;

            myIndex = index < myElements.length ? index : 0;
            PsiFile psiFile = getContainingFile(myElements[myIndex]);

            VirtualFile virtualFile = psiFile.getVirtualFile();
            EditorHighlighter highlighter;
            if (virtualFile != null)
              highlighter = HighlighterFactory.createHighlighter(project, virtualFile);
            else {
              String fileName = psiFile.getName(); // some artificial psi file, lets do best we can
              highlighter = HighlighterFactory.createHighlighter(project, fileName);
            }

            ((EditorEx) myEditor).setHighlighter(highlighter);

            gc.fill = GridBagConstraints.HORIZONTAL;
            gc.weightx = 1;
            if (myElements.length > 1) {
              myFileChooser =
                  new ComboBox(
                      fileDescriptors.toArray(new FileDescriptor[fileDescriptors.size()]), 250);
              updateRenderer(project);

              myFileChooser.addActionListener(
                  new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                      int index = myFileChooser.getSelectedIndex();
                      if (myIndex != index) {
                        myIndex = index;
                        updateControls();
                      }
                    }
                  });

              myLabel = new JLabel();
              myLabel.setVisible(false);
              toolbarPanel.add(myFileChooser, gc);
            } else {
              myFileChooser = new ComboBox();
              myFileChooser.setVisible(false);
              myCountLabel.setVisible(false);

              myLabel = new JLabel();
              VirtualFile file = psiFile.getVirtualFile();
              if (file != null) {
                myLabel.setIcon(getIconForFile(psiFile));
                myLabel.setForeground(
                    FileStatusManager.getInstance(project).getStatus(file).getColor());
                myLabel.setText(file.getPresentableName());
                myLabel.setBorder(
                    new CompoundBorder(
                        IdeBorderFactory.createRoundedBorder(),
                        IdeBorderFactory.createEmptyBorder(0, 0, 0, 5)));
              }
              toolbarPanel.add(myLabel, gc);
            }

            gc.fill = GridBagConstraints.NONE;
            gc.weightx = 0;
            toolbarPanel.add(myCountLabel, gc);

            header.add(toolbarPanel, BorderLayout.CENTER);
            header.add(myLocationLabel, BorderLayout.EAST);

            add(header, BorderLayout.NORTH);

            updateControls();
            return true;
          }
        });
  }
  public VcsDependentHistoryComponents getUICustomization(
      final VcsHistorySession session, JComponent forShortcutRegistration) {
    final ColumnInfo[] columns;
    final Consumer<VcsFileRevision> listener;
    final JComponent addComp;
    if (((MyHistorySession) session).isSupports15()) {
      final MergeSourceColumnInfo mergeSourceColumn =
          new MergeSourceColumnInfo((MyHistorySession) session);
      columns = new ColumnInfo[] {new CopyFromColumnInfo(), mergeSourceColumn};

      final JTextArea field = new JTextArea();
      field.setEditable(false);
      field.setBackground(UIUtil.getComboBoxDisabledBackground());
      field.setWrapStyleWord(true);
      listener =
          new Consumer<VcsFileRevision>() {
            public void consume(VcsFileRevision vcsFileRevision) {
              field.setText(mergeSourceColumn.getText(vcsFileRevision));
            }
          };
      final JPanel panel = new JPanel(new GridBagLayout());
      final GridBagConstraints gb =
          new GridBagConstraints(
              0,
              0,
              1,
              1,
              0,
              0,
              GridBagConstraints.WEST,
              GridBagConstraints.NONE,
              new Insets(0, 0, 0, 0),
              0,
              0);

      final JLabel mergeLabel = new JLabel("Merge Sources:");
      final MergeSourceDetailsAction sourceAction = new MergeSourceDetailsAction();
      sourceAction.registerSelf(forShortcutRegistration);
      final DefaultActionGroup group = new DefaultActionGroup();
      group.add(sourceAction);
      final JComponent toolbar =
          ActionManager.getInstance()
              .createActionToolbar(ActionPlaces.UNKNOWN, group, true)
              .getComponent();

      panel.add(mergeLabel, gb);
      ++gb.gridx;
      gb.insets.left = 10;
      gb.anchor = GridBagConstraints.NORTHWEST;
      panel.add(toolbar, gb);

      ++gb.gridy;
      gb.insets.left = 0;
      gb.gridx = 0;
      gb.gridwidth = 2;
      gb.weightx = gb.weighty = 1;
      gb.fill = GridBagConstraints.BOTH;
      JScrollPane pane = ScrollPaneFactory.createScrollPane(field);
      pane.setBorder(IdeBorderFactory.createBorder(SideBorder.LEFT | SideBorder.TOP));
      panel.add(pane, gb);
      addComp = panel;
    } else {
      columns = new ColumnInfo[] {new CopyFromColumnInfo()};
      addComp = null;
      listener = null;
    }
    return new VcsDependentHistoryComponents(columns, listener, addComp);
  }
/** @author irengrig Date: 2/3/11 Time: 12:04 PM */
public class VcsStructureChooser extends DialogWrapper {
  private static final int MAX_FOLDERS = 100;
  public static final Border BORDER =
      IdeBorderFactory.createBorder(SideBorder.TOP | SideBorder.LEFT);
  public static final String CAN_NOT_ADD_TEXT =
      "<html>Selected: <font color=red>(You have added "
          + MAX_FOLDERS
          + " elements. No more is allowed.)</font></html>";

  @NotNull private final Project myProject;
  @NotNull private final List<VirtualFile> myInitialRoots;
  @NotNull private final Map<VirtualFile, String> myModulesSet = ContainerUtil.newHashMap();
  @NotNull private final Set<VirtualFile> mySelectedFiles = ContainerUtil.newHashSet();

  @NotNull private final SelectionManager mySelectionManager;

  private Set<VirtualFile> myRoots;
  private JLabel mySelectedLabel;
  private DefaultMutableTreeNode myRoot;
  private Tree myTree;

  public VcsStructureChooser(
      @NotNull Project project,
      String title,
      Collection<VirtualFile> initialSelection,
      @NotNull List<VirtualFile> initialRoots) {
    super(project, true);
    setTitle(title);
    myProject = project;
    myInitialRoots = initialRoots;
    mySelectionManager = new SelectionManager(MAX_FOLDERS, 500, MyNodeConverter.getInstance());

    init();

    mySelectionManager.setSelection(initialSelection);

    checkEmpty();
  }

  private void calculateRoots() {
    final ModuleManager moduleManager = ModuleManager.getInstance(myProject);
    // assertion for read access inside
    final Module[] modules =
        ApplicationManager.getApplication()
            .runReadAction(
                new Computable<Module[]>() {
                  public Module[] compute() {
                    return moduleManager.getModules();
                  }
                });

    final TreeSet<VirtualFile> checkSet =
        new TreeSet<VirtualFile>(FilePathComparator.getInstance());
    myRoots = new HashSet<VirtualFile>();
    myRoots.addAll(myInitialRoots);
    checkSet.addAll(myInitialRoots);
    for (Module module : modules) {
      final VirtualFile[] files = ModuleRootManager.getInstance(module).getContentRoots();
      for (VirtualFile file : files) {
        final VirtualFile floor = checkSet.floor(file);
        if (floor != null) {
          myModulesSet.put(file, module.getName());
          myRoots.add(file);
        }
      }
    }
  }

  @NotNull
  public Collection<VirtualFile> getSelectedFiles() {
    return mySelectedFiles;
  }

  private void checkEmpty() {
    setOKActionEnabled(!mySelectedFiles.isEmpty());
  }

  @Override
  protected String getDimensionServiceKey() {
    return "git4idea.history.wholeTree.VcsStructureChooser";
  }

  @Override
  public JComponent getPreferredFocusedComponent() {
    return myTree;
  }

  @Override
  protected JComponent createCenterPanel() {
    final FileChooserDescriptor descriptor =
        FileChooserDescriptorFactory.createAllButJarContentsDescriptor();
    calculateRoots();
    final ArrayList<VirtualFile> list = new ArrayList<VirtualFile>(myRoots);
    final Comparator<VirtualFile> comparator =
        new Comparator<VirtualFile>() {
          @Override
          public int compare(VirtualFile o1, VirtualFile o2) {
            final boolean isDir1 = o1.isDirectory();
            final boolean isDir2 = o2.isDirectory();
            if (isDir1 != isDir2) return isDir1 ? -1 : 1;

            final String module1 = myModulesSet.get(o1);
            final String path1 = module1 != null ? module1 : o1.getPath();
            final String module2 = myModulesSet.get(o2);
            final String path2 = module2 != null ? module2 : o2.getPath();
            return path1.compareToIgnoreCase(path2);
          }
        };
    descriptor.setRoots(list);
    myTree = new Tree();
    myTree.setMinimumSize(new Dimension(200, 200));
    myTree.setBorder(BORDER);
    myTree.setShowsRootHandles(true);
    myTree.setRootVisible(true);
    myTree.getExpandableItemsHandler().setEnabled(false);
    final MyCheckboxTreeCellRenderer cellRenderer =
        new MyCheckboxTreeCellRenderer(
            mySelectionManager, myModulesSet, myProject, myTree, myRoots);
    final FileSystemTreeImpl fileSystemTree =
        new FileSystemTreeImpl(
            myProject,
            descriptor,
            myTree,
            cellRenderer,
            null,
            new Convertor<TreePath, String>() {
              @Override
              public String convert(TreePath o) {
                final DefaultMutableTreeNode lastPathComponent =
                    ((DefaultMutableTreeNode) o.getLastPathComponent());
                final Object uo = lastPathComponent.getUserObject();
                if (uo instanceof FileNodeDescriptor) {
                  final VirtualFile file = ((FileNodeDescriptor) uo).getElement().getFile();
                  final String module = myModulesSet.get(file);
                  if (module != null) return module;
                  return file == null ? "" : file.getName();
                }
                return o.toString();
              }
            });
    final AbstractTreeUi ui = fileSystemTree.getTreeBuilder().getUi();
    ui.setNodeDescriptorComparator(
        new Comparator<NodeDescriptor>() {
          @Override
          public int compare(NodeDescriptor o1, NodeDescriptor o2) {
            if (o1 instanceof FileNodeDescriptor && o2 instanceof FileNodeDescriptor) {
              final VirtualFile f1 = ((FileNodeDescriptor) o1).getElement().getFile();
              final VirtualFile f2 = ((FileNodeDescriptor) o2).getElement().getFile();
              return comparator.compare(f1, f2);
            }
            return o1.getIndex() - o2.getIndex();
          }
        });
    myRoot = (DefaultMutableTreeNode) myTree.getModel().getRoot();

    new ClickListener() {
      @Override
      public boolean onClick(@NotNull MouseEvent e, int clickCount) {
        int row = myTree.getRowForLocation(e.getX(), e.getY());
        if (row < 0) return false;
        final Object o = myTree.getPathForRow(row).getLastPathComponent();
        if (myRoot == o || getFile(o) == null) return false;

        Rectangle rowBounds = myTree.getRowBounds(row);
        cellRenderer.setBounds(rowBounds);
        Rectangle checkBounds = cellRenderer.myCheckbox.getBounds();
        checkBounds.setLocation(rowBounds.getLocation());

        if (checkBounds.height == 0) checkBounds.height = rowBounds.height;

        if (checkBounds.contains(e.getPoint())) {
          mySelectionManager.toggleSelection((DefaultMutableTreeNode) o);
          myTree.revalidate();
          myTree.repaint();
        }
        return true;
      }
    }.installOn(myTree);

    myTree.addKeyListener(
        new KeyAdapter() {
          public void keyPressed(KeyEvent e) {
            if (e.getKeyCode() == KeyEvent.VK_SPACE) {
              TreePath[] paths = myTree.getSelectionPaths();
              if (paths == null) return;
              for (TreePath path : paths) {
                if (path == null) continue;
                final Object o = path.getLastPathComponent();
                if (myRoot == o || getFile(o) == null) return;
                mySelectionManager.toggleSelection((DefaultMutableTreeNode) o);
              }

              myTree.revalidate();
              myTree.repaint();
              e.consume();
            }
          }
        });

    JBPanel panel = new JBPanel(new BorderLayout());
    panel.add(new JBScrollPane(fileSystemTree.getTree()), BorderLayout.CENTER);
    mySelectedLabel = new JLabel("");
    mySelectedLabel.setBorder(BorderFactory.createEmptyBorder(2, 0, 2, 0));
    panel.add(mySelectedLabel, BorderLayout.SOUTH);

    mySelectionManager.setSelectionChangeListener(
        new PlusMinus<VirtualFile>() {
          @Override
          public void plus(VirtualFile virtualFile) {
            mySelectedFiles.add(virtualFile);
            recalculateErrorText();
          }

          private void recalculateErrorText() {
            checkEmpty();
            if (mySelectionManager.canAddSelection()) {
              mySelectedLabel.setText("");
            } else {
              mySelectedLabel.setText(CAN_NOT_ADD_TEXT);
            }
            mySelectedLabel.revalidate();
          }

          @Override
          public void minus(VirtualFile virtualFile) {
            mySelectedFiles.remove(virtualFile);
            recalculateErrorText();
          }
        });
    return panel;
  }

  @Nullable
  private static VirtualFile getFile(final Object node) {
    if (!(((DefaultMutableTreeNode) node).getUserObject() instanceof FileNodeDescriptor))
      return null;
    final FileNodeDescriptor descriptor =
        (FileNodeDescriptor) ((DefaultMutableTreeNode) node).getUserObject();
    if (descriptor.getElement().getFile() == null) return null;
    return descriptor.getElement().getFile();
  }

  private static class MyCheckboxTreeCellRenderer extends JPanel implements TreeCellRenderer {
    private final WithModulesListCellRenderer myTextRenderer;
    public final JCheckBox myCheckbox;
    private final SelectionManager mySelectionManager;
    private final Map<VirtualFile, String> myModulesSet;
    private final Collection<VirtualFile> myRoots;
    private final ColoredTreeCellRenderer myColoredRenderer;
    private final JLabel myEmpty;
    private final JList myFictive;

    private MyCheckboxTreeCellRenderer(
        final SelectionManager selectionManager,
        Map<VirtualFile, String> modulesSet,
        final Project project,
        final JTree tree,
        final Collection<VirtualFile> roots) {
      super(new BorderLayout());
      mySelectionManager = selectionManager;
      myModulesSet = modulesSet;
      myRoots = roots;
      setBackground(tree.getBackground());
      myColoredRenderer =
          new ColoredTreeCellRenderer() {
            @Override
            public void customizeCellRenderer(
                JTree tree,
                Object value,
                boolean selected,
                boolean expanded,
                boolean leaf,
                int row,
                boolean hasFocus) {
              append(value.toString());
            }
          };
      myFictive = new JBList();
      myFictive.setBackground(tree.getBackground());
      myFictive.setSelectionBackground(UIUtil.getListSelectionBackground());
      myFictive.setSelectionForeground(UIUtil.getListSelectionForeground());

      myTextRenderer =
          new WithModulesListCellRenderer(project, myModulesSet) {
            @Override
            protected void putParentPath(Object value, FilePath path, FilePath self) {
              if (myRoots.contains(self.getVirtualFile())) {
                super.putParentPath(value, path, self);
              }
            }
          };
      myTextRenderer.setBackground(tree.getBackground());

      myCheckbox = new JCheckBox();
      myCheckbox.setBackground(tree.getBackground());
      myEmpty = new JLabel("");

      add(myCheckbox, BorderLayout.WEST);
      add(myTextRenderer, BorderLayout.CENTER);
      myCheckbox.setVisible(true);
    }

    @Override
    public Component getTreeCellRendererComponent(
        JTree tree,
        Object value,
        boolean selected,
        boolean expanded,
        boolean leaf,
        int row,
        boolean hasFocus) {
      invalidate();
      final VirtualFile file = getFile(value);
      final DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
      if (file == null) {
        if (value instanceof DefaultMutableTreeNode) {
          final Object uo = node.getUserObject();
          if (uo instanceof String) {
            myColoredRenderer.getTreeCellRendererComponent(
                tree, value, selected, expanded, leaf, row, hasFocus);
            return myColoredRenderer;
          }
        }
        return myEmpty;
      }
      myCheckbox.setVisible(true);
      final TreeNodeState state = mySelectionManager.getState(node);
      myCheckbox.setEnabled(
          TreeNodeState.CLEAR.equals(state) || TreeNodeState.SELECTED.equals(state));
      myCheckbox.setSelected(!TreeNodeState.CLEAR.equals(state));
      myCheckbox.setOpaque(false);
      myCheckbox.setBackground(null);
      setBackground(null);
      myTextRenderer.getListCellRendererComponent(myFictive, file, 0, selected, hasFocus);
      revalidate();
      return this;
    }
  }

  private static class MyNodeConverter implements Convertor<DefaultMutableTreeNode, VirtualFile> {
    private static final MyNodeConverter ourInstance = new MyNodeConverter();

    public static MyNodeConverter getInstance() {
      return ourInstance;
    }

    @Override
    public VirtualFile convert(DefaultMutableTreeNode o) {
      return ((FileNodeDescriptor) o.getUserObject()).getElement().getFile();
    }
  }

  private static class WithModulesListCellRenderer extends VirtualFileListCellRenderer {
    private final Map<VirtualFile, String> myModules;

    private WithModulesListCellRenderer(Project project, final Map<VirtualFile, String> modules) {
      super(project, true);
      myModules = modules;
    }

    @Override
    protected String getName(FilePath path) {
      final String module = myModules.get(path.getVirtualFile());
      if (module != null) {
        return module;
      }
      return super.getName(path);
    }

    @Override
    protected void renderIcon(FilePath path) {
      final String module = myModules.get(path.getVirtualFile());
      if (module != null) {
        setIcon(PlatformIcons.CONTENT_ROOT_ICON_CLOSED);
      } else {
        if (path.isDirectory()) {
          setIcon(PlatformIcons.DIRECTORY_CLOSED_ICON);
        } else {
          setIcon(path.getFileType().getIcon());
        }
      }
    }

    @Override
    protected void putParentPathImpl(Object value, String parentPath, FilePath self) {
      append(self.getPath(), SimpleTextAttributes.GRAYED_ATTRIBUTES);
    }
  }
}
  protected JComponent createNorthPanel() {
    JPanel panel = new JPanel();
    panel.setLayout(new GridBagLayout());

    panel.setBorder(IdeBorderFactory.createBorder());

    myNameLabel = new JLabel();
    panel.add(
        myNameLabel,
        new GridBagConstraints(
            0,
            0,
            2,
            1,
            1,
            0,
            GridBagConstraints.WEST,
            GridBagConstraints.HORIZONTAL,
            new Insets(4, 8, 4, 8),
            0,
            0));

    panel.add(
        new JLabel(RefactoringBundle.message("move.files.to.directory.label")),
        new GridBagConstraints(
            0,
            1,
            1,
            1,
            0,
            0,
            GridBagConstraints.WEST,
            GridBagConstraints.HORIZONTAL,
            new Insets(4, 8, 4, 8),
            0,
            0));

    myTargetDirectoryField = new TextFieldWithBrowseButton();
    myTargetDirectoryField.addBrowseFolderListener(
        RefactoringBundle.message("select.target.directory"),
        RefactoringBundle.message("the.file.will.be.moved.to.this.directory"),
        null,
        FileChooserDescriptorFactory.createSingleFolderDescriptor());
    myTargetDirectoryField.setTextFieldPreferredWidth(60);
    panel.add(
        myTargetDirectoryField,
        new GridBagConstraints(
            1,
            1,
            1,
            1,
            1,
            0,
            GridBagConstraints.WEST,
            GridBagConstraints.HORIZONTAL,
            new Insets(4, 0, 4, 8),
            0,
            0));

    myTargetDirectoryField
        .getTextField()
        .getDocument()
        .addDocumentListener(
            new DocumentAdapter() {
              public void textChanged(DocumentEvent event) {
                validateOKButton();
              }
            });

    return panel;
  }