protected Tree createTree() {
    final Tree tree = new Tree(new DefaultTreeModel(new DefaultMutableTreeNode()));

    tree.setCellRenderer(getTreeCellRenderer());
    UIUtil.setLineStyleAngled(tree);
    tree.setRootVisible(false);
    tree.setShowsRootHandles(true);
    tree.addKeyListener(new TreeKeyListener());
    tree.addTreeSelectionListener(new MyTreeSelectionListener());

    if (!myAllowMultiSelection) {
      tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
    }

    new DoubleClickListener() {
      @Override
      protected boolean onDoubleClick(MouseEvent e) {
        if (tree.getPathForLocation(e.getX(), e.getY()) != null) {
          doOKAction();
          return true;
        }
        return false;
      }
    }.installOn(tree);

    TreeUtil.installActions(tree);
    return tree;
  }
  @SuppressWarnings("unchecked")
  public void resetElements(
      T[] elements,
      final @Nullable Comparator<T> sortComparator,
      final boolean restoreSelectedElements) {
    final List<T> selectedElements =
        restoreSelectedElements && mySelectedElements != null
            ? new ArrayList<T>(mySelectedElements)
            : null;
    myElements = elements;
    if (sortComparator != null) {
      myComparator = new ElementNodeComparatorWrapper(sortComparator);
    }
    mySelectedNodes.clear();
    myNodeToParentMap.clear();
    myElementToNodeMap.clear();
    myContainerNodes.clear();

    ApplicationManager.getApplication()
        .runReadAction(
            new Runnable() {
              @Override
              public void run() {
                myTreeModel = buildModel();
              }
            });

    myTree.setModel(myTreeModel);
    myTree.setRootVisible(false);

    restoreTree();

    if (myOptionControls == null) {
      myCopyJavadocCheckbox = new NonFocusableCheckBox(IdeBundle.message("checkbox.copy.javadoc"));
      if (myIsInsertOverrideVisible) {
        myInsertOverrideAnnotationCheckbox =
            new NonFocusableCheckBox(IdeBundle.message("checkbox.insert.at.override"));
        myOptionControls =
            new JCheckBox[] {myCopyJavadocCheckbox, myInsertOverrideAnnotationCheckbox};
      } else {
        myOptionControls = new JCheckBox[] {myCopyJavadocCheckbox};
      }
    }

    myTree.doLayout();
    setOKActionEnabled(myElements != null && myElements.length > 0);

    if (selectedElements != null) {
      selectElements(selectedElements.toArray(new ClassMember[selectedElements.size()]));
    }
    if (mySelectedElements == null || mySelectedElements.isEmpty()) {
      expandFirst();
    }
  }
Exemplo n.º 3
0
 protected void initTree() {
   ((DefaultTreeModel) myTree.getModel()).setRoot(myRoot);
   myTree.setRootVisible(false);
   myTree.setShowsRootHandles(true);
   UIUtil.setLineStyleAngled(myTree);
   TreeUtil.installActions(myTree);
   myTree.setCellRenderer(
       new ColoredTreeCellRenderer() {
         public void customizeCellRenderer(
             JTree tree,
             Object value,
             boolean selected,
             boolean expanded,
             boolean leaf,
             int row,
             boolean hasFocus) {
           if (value instanceof MyNode) {
             final MyNode node = ((MyNode) value);
             setIcon(node.getIcon(expanded));
             final Font font = UIUtil.getTreeFont();
             if (node.isDisplayInBold()) {
               setFont(font.deriveFont(Font.BOLD));
             } else {
               setFont(font.deriveFont(Font.PLAIN));
             }
             append(
                 node.getDisplayName(),
                 node.isDisplayInBold()
                     ? SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES
                     : SimpleTextAttributes.REGULAR_ATTRIBUTES);
           }
         }
       });
   initToolbar();
   ArrayList<AnAction> actions = createActions(true);
   if (actions != null) {
     final DefaultActionGroup group = new DefaultActionGroup();
     for (AnAction action : actions) {
       group.add(action);
     }
     actions = getAdditionalActions();
     if (actions != null) {
       group.addSeparator();
       for (AnAction action : actions) {
         group.add(action);
       }
     }
     PopupHandler.installPopupHandler(
         myTree,
         group,
         ActionPlaces.UNKNOWN,
         ActionManager.getInstance()); // popup should follow the selection
   }
 }
Exemplo n.º 4
0
  public ServersToolWindowContent(@NotNull Project project) {
    super(new BorderLayout());
    myProject = project;

    myTreeModel = new DefaultTreeModel(new DefaultMutableTreeNode());
    myTree = new Tree(myTreeModel);
    myTree.setRootVisible(false);

    myTree.setShowsRootHandles(true);
    myTree.setCellRenderer(new NodeRenderer());
    myTree.setLineStyleAngled();

    getMainPanel().add(createToolbar(), BorderLayout.WEST);
    Splitter splitter = new Splitter(false, 0.3f);
    splitter.setFirstComponent(ScrollPaneFactory.createScrollPane(myTree, SideBorder.LEFT));
    myPropertiesPanelLayout = new CardLayout();
    myPropertiesPanel = new JPanel(myPropertiesPanelLayout);
    myMessageLabel = new JLabel(EMPTY_SELECTION_MESSAGE, SwingConstants.CENTER);
    myPropertiesPanel.add(MESSAGE_CARD, new Wrapper(myMessageLabel));
    splitter.setSecondComponent(myPropertiesPanel);
    getMainPanel().add(splitter, BorderLayout.CENTER);

    setupBuilder(project);

    for (RemoteServersViewContributor contributor :
        RemoteServersViewContributor.EP_NAME.getExtensions()) {
      contributor.setupTree(myProject, myTree, myBuilder);
    }

    myTree.addTreeSelectionListener(
        new TreeSelectionListener() {
          @Override
          public void valueChanged(TreeSelectionEvent e) {
            onSelectionChanged();
          }
        });
    new DoubleClickListener() {
      @Override
      protected boolean onDoubleClick(MouseEvent event) {
        Set<ServersTreeStructure.RemoteServerNode> nodes = getSelectedRemoteServerNodes();
        if (nodes.size() == 1) {
          RemoteServer<?> server = nodes.iterator().next().getValue();
          ServerConnectionManager.getInstance().getOrCreateConnection(server);
          return true;
        }
        return false;
      }
    }.installOn(myTree);
  }
  protected JTree createTree() {
    Tree internalTree = createInternalTree();
    myFileSystemTree =
        new FileSystemTreeImpl(myProject, myChooserDescriptor, internalTree, null, null, null);
    internalTree.setRootVisible(myChooserDescriptor.isTreeRootVisible());
    internalTree.setShowsRootHandles(true);
    Disposer.register(myDisposable, myFileSystemTree);

    myFileSystemTree.addOkAction(this::doOKAction);
    JTree tree = myFileSystemTree.getTree();
    tree.setCellRenderer(new NodeRenderer());
    tree.getSelectionModel().addTreeSelectionListener(new FileTreeSelectionListener());
    tree.addTreeExpansionListener(new FileTreeExpansionListener());
    setOKActionEnabled(false);

    myFileSystemTree.addListener(
        new FileSystemTree.Listener() {
          public void selectionChanged(final List<VirtualFile> selection) {
            updatePathFromTree(selection, false);
          }
        },
        myDisposable);

    new FileDrop(
        tree,
        new FileDrop.Target() {
          public FileChooserDescriptor getDescriptor() {
            return myChooserDescriptor;
          }

          public boolean isHiddenShown() {
            return myFileSystemTree.areHiddensShown();
          }

          public void dropFiles(final List<VirtualFile> files) {
            if (!myChooserDescriptor.isChooseMultiple() && files.size() > 0) {
              selectInTree(new VirtualFile[] {files.get(0)}, true, true);
            } else {
              selectInTree(VfsUtilCore.toVirtualFileArray(files), true, true);
            }
          }
        });

    return tree;
  }
  public ContentEntryTreeEditor(
      Project project, List<ModuleSourceRootEditHandler<?>> editHandlers) {
    myProject = project;
    myEditHandlers = editHandlers;
    myTree = new Tree();
    myTree.setRootVisible(true);
    myTree.setShowsRootHandles(true);

    myEditingActionsGroup = new DefaultActionGroup();

    TreeUtil.installActions(myTree);
    new TreeSpeedSearch(myTree);

    myTreePanel = new MyPanel(new BorderLayout());
    final JScrollPane scrollPane = ScrollPaneFactory.createScrollPane(myTree);
    myTreePanel.add(
        new ToolbarPanel(scrollPane, myEditingActionsGroup, TOOLBAR_PLACE), BorderLayout.CENTER);

    myTreePanel.setVisible(false);
    myDescriptor = FileChooserDescriptorFactory.createMultipleFoldersDescriptor();
    myDescriptor.setShowFileSystemRoots(false);
  }
  private void initTree(Tree tree) {
    tree.setCellRenderer(new MyTreeCellRenderer());
    tree.setRootVisible(false);
    tree.setShowsRootHandles(true);
    tree.setLineStyleAngled();

    TreeUtil.installActions(tree);
    SmartExpander.installOn(tree);
    new TreeSpeedSearch(tree);
    tree.addTreeWillExpandListener(
        new TreeWillExpandListener() {
          @Override
          public void treeWillExpand(TreeExpansionEvent event) throws ExpandVetoException {
            ((PackageDependenciesNode) event.getPath().getLastPathComponent()).sortChildren();
          }

          @Override
          public void treeWillCollapse(TreeExpansionEvent event) throws ExpandVetoException {}
        });

    PopupHandler.installUnknownPopupHandler(
        tree, createTreePopupActions(), ActionManager.getInstance());
  }
  @Override
  protected JComponent createCenterPanel() {
    final DefaultTreeModel model = new DefaultTreeModel(new DefaultMutableTreeNode());
    myTree = new Tree(model);

    ProjectAbstractTreeStructureBase treeStructure =
        new AbstractProjectTreeStructure(myProject) {
          @Override
          public boolean isFlattenPackages() {
            return false;
          }

          @Override
          public boolean isShowMembers() {
            return myIsShowMembers;
          }

          @Override
          public boolean isHideEmptyMiddlePackages() {
            return true;
          }

          @Override
          public boolean isAbbreviatePackageNames() {
            return false;
          }

          @Override
          public boolean isShowLibraryContents() {
            return myIsShowLibraryContents;
          }

          @Override
          public boolean isShowModules() {
            return false;
          }
        };
    myBuilder =
        new ProjectTreeBuilder(myProject, myTree, model, AlphaComparator.INSTANCE, treeStructure);

    myTree.setRootVisible(false);
    myTree.setShowsRootHandles(true);
    myTree.expandRow(0);
    myTree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
    myTree.setCellRenderer(new NodeRenderer());
    UIUtil.setLineStyleAngled(myTree);

    JScrollPane scrollPane = ScrollPaneFactory.createScrollPane(myTree);
    scrollPane.setPreferredSize(new Dimension(500, 300));

    myTree.addKeyListener(
        new KeyAdapter() {
          @Override
          public void keyPressed(KeyEvent e) {
            if (KeyEvent.VK_ENTER == e.getKeyCode()) {
              doOKAction();
            }
          }
        });

    new DoubleClickListener() {
      @Override
      protected boolean onDoubleClick(MouseEvent event) {
        TreePath path = myTree.getPathForLocation(event.getX(), event.getY());
        if (path != null && myTree.isPathSelected(path)) {
          doOKAction();
          return true;
        }
        return false;
      }
    }.installOn(myTree);

    myTree.addTreeSelectionListener(
        new TreeSelectionListener() {
          @Override
          public void valueChanged(TreeSelectionEvent e) {
            handleSelectionChanged();
          }
        });

    new TreeSpeedSearch(myTree);

    myTabbedPane = new TabbedPaneWrapper(getDisposable());

    final JPanel dummyPanel = new JPanel(new BorderLayout());
    String name = null;
    /*
        if (myInitialClass != null) {
          name = myInitialClass.getName();
        }
    */
    myGotoByNamePanel =
        new ChooseByNamePanel(
            myProject,
            createChooseByNameModel(),
            name,
            myScope.isSearchInLibraries(),
            getContext()) {

          @Override
          protected void showTextFieldPanel() {}

          @Override
          protected void close(boolean isOk) {
            super.close(isOk);

            if (isOk) {
              doOKAction();
            } else {
              doCancelAction();
            }
          }

          @NotNull
          @Override
          protected Set<Object> filter(@NotNull Set<Object> elements) {
            return doFilter(elements);
          }

          @Override
          protected void initUI(
              ChooseByNamePopupComponent.Callback callback,
              ModalityState modalityState,
              boolean allowMultipleSelection) {
            super.initUI(callback, modalityState, allowMultipleSelection);
            dummyPanel.add(myGotoByNamePanel.getPanel(), BorderLayout.CENTER);
            IdeFocusTraversalPolicy.getPreferredFocusedComponent(myGotoByNamePanel.getPanel())
                .requestFocus();
          }

          @Override
          protected void showList() {
            super.showList();
            if (myInitialClass != null && myList.getModel().getSize() > 0) {
              myList.setSelectedValue(myInitialClass, true);
              myInitialClass = null;
            }
          }

          @Override
          protected void chosenElementMightChange() {
            handleSelectionChanged();
          }
        };

    Disposer.register(myDisposable, myGotoByNamePanel);

    myTabbedPane.addTab(IdeBundle.message("tab.chooser.search.by.name"), dummyPanel);
    myTabbedPane.addTab(IdeBundle.message("tab.chooser.project"), scrollPane);

    myGotoByNamePanel.invoke(new MyCallback(), getModalityState(), false);

    myTabbedPane.addChangeListener(
        new ChangeListener() {
          @Override
          public void stateChanged(ChangeEvent e) {
            handleSelectionChanged();
          }
        });

    return myTabbedPane.getComponent();
  }
  public MavenArchetypesStep(MavenModuleBuilder builder, @Nullable StepAdapter step) {
    myBuilder = builder;
    myStep = step;
    Disposer.register(this, myLoadingIcon);

    myArchetypesTree = new Tree();
    myArchetypesTree.setModel(new DefaultTreeModel(new DefaultMutableTreeNode()));
    JScrollPane archetypesScrollPane = ScrollPaneFactory.createScrollPane(myArchetypesTree);

    myArchetypesPanel.add(archetypesScrollPane, "archetypes");

    JPanel loadingPanel = new JPanel(new GridBagLayout());
    JPanel bp = new JPanel(new BorderLayout(10, 10));
    bp.add(new JLabel("Loading archetype list..."), BorderLayout.NORTH);
    bp.add(myLoadingIcon, BorderLayout.CENTER);

    loadingPanel.add(bp, new GridBagConstraints());

    myArchetypesPanel.add(ScrollPaneFactory.createScrollPane(loadingPanel), "loading");
    ((CardLayout) myArchetypesPanel.getLayout()).show(myArchetypesPanel, "archetypes");

    myUseArchetypeCheckBox.addItemListener(
        new ItemListener() {
          @Override
          public void itemStateChanged(ItemEvent e) {
            updateComponents();
            archetypeMayBeChanged();
          }
        });

    myAddArchetypeButton.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            doAddArchetype();
          }
        });

    myArchetypesTree.setRootVisible(false);
    myArchetypesTree.setShowsRootHandles(true);
    myArchetypesTree.setCellRenderer(new MyRenderer());
    myArchetypesTree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);

    myArchetypesTree
        .getSelectionModel()
        .addTreeSelectionListener(
            new TreeSelectionListener() {
              public void valueChanged(TreeSelectionEvent e) {
                updateArchetypeDescription();
                archetypeMayBeChanged();
              }
            });

    new TreeSpeedSearch(
            myArchetypesTree,
            new Convertor<TreePath, String>() {
              public String convert(TreePath path) {
                MavenArchetype info =
                    getArchetypeInfoFromPathComponent(path.getLastPathComponent());
                return info.groupId + ":" + info.artifactId + ":" + info.version;
              }
            })
        .setComparator(new SpeedSearchComparator(false));

    myArchetypeDescriptionField.setEditable(false);
    myArchetypeDescriptionField.setBackground(UIUtil.getPanelBackground());

    requestUpdate();
    updateComponents();
  }
  @NotNull
  private JTree createTree() {
    DefaultMutableTreeNode root = new DefaultMutableTreeNode();
    final Tree tree = new Tree(new DefaultTreeModel(root)) /* {
      @Override
      protected void paintComponent(Graphics g) {
        DuplicateNodeRenderer.paintDuplicateNodesBackground(g, this);
        super.paintComponent(g);
      }
    }*/;
    tree.setOpaque(false);

    tree.setToggleClickCount(-1);
    SliceUsageCellRenderer renderer = new SliceUsageCellRenderer();
    renderer.setOpaque(false);
    tree.setCellRenderer(renderer);
    UIUtil.setLineStyleAngled(tree);
    tree.setRootVisible(false);

    tree.setShowsRootHandles(true);
    tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
    tree.setSelectionPath(new TreePath(root.getPath()));
    // ActionGroup group =
    // (ActionGroup)ActionManager.getInstance().getAction(IdeActions.GROUP_METHOD_HIERARCHY_POPUP);
    // PopupHandler.installPopupHandler(tree, group, ActionPlaces.METHOD_HIERARCHY_VIEW_POPUP,
    // ActionManager.getInstance());
    EditSourceOnDoubleClickHandler.install(tree);

    new TreeSpeedSearch(tree);
    TreeUtil.installActions(tree);
    ToolTipManager.sharedInstance().registerComponent(tree);

    myAutoScrollToSourceHandler.install(tree);

    tree.getSelectionModel()
        .addTreeSelectionListener(
            new TreeSelectionListener() {
              @Override
              public void valueChanged(final TreeSelectionEvent e) {
                treeSelectionChanged();
              }
            });

    tree.addKeyListener(
        new KeyAdapter() {
          @Override
          public void keyPressed(KeyEvent e) {
            if (KeyEvent.VK_ENTER == e.getKeyCode()) {
              List<Navigatable> navigatables = getNavigatables();
              if (navigatables.isEmpty()) return;
              for (Navigatable navigatable : navigatables) {
                if (navigatable instanceof AbstractTreeNode
                    && ((AbstractTreeNode) navigatable).getValue() instanceof Usage) {
                  navigatable = (Usage) ((AbstractTreeNode) navigatable).getValue();
                }
                if (navigatable.canNavigateToSource()) {
                  navigatable.navigate(false);
                  if (navigatable instanceof Usage) {
                    ((Usage) navigatable).highlightInEditor();
                  }
                }
              }
              e.consume();
            }
          }
        });

    tree.addTreeWillExpandListener(
        new TreeWillExpandListener() {
          @Override
          public void treeWillCollapse(TreeExpansionEvent event) {}

          @Override
          public void treeWillExpand(TreeExpansionEvent event) {
            TreePath path = event.getPath();
            SliceNode node = fromPath(path);
            node.calculateDupNode();
          }
        });

    return tree;
  }
  private void initializeUI() {
    myTree = new Tree();
    myTreeBuilder = new CertificateTreeBuilder(myTree);

    // are not fully functional by now
    myCheckHostname.setVisible(false);
    myCheckValidityPeriod.setVisible(false);

    myTrustManager = CertificateManager.getInstance().getCustomTrustManager();
    // show newly added certificates
    myTrustManager.addListener(this);

    myTree.getEmptyText().setText("No certificates");
    myTree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
    myTree.setRootVisible(false);
    // myTree.setShowsRootHandles(false);

    ToolbarDecorator decorator = ToolbarDecorator.createDecorator(myTree).disableUpDownActions();
    decorator
        .setAddAction(
            new AnActionButtonRunnable() {
              @Override
              public void run(AnActionButton button) {
                // show choose file dialog, add certificate
                FileChooser.chooseFile(
                    CERTIFICATE_DESCRIPTOR,
                    null,
                    null,
                    file -> {
                      String path = file.getPath();
                      X509Certificate certificate = CertificateUtil.loadX509Certificate(path);
                      if (certificate == null) {
                        Messages.showErrorDialog(
                            myRootPanel, "Malformed X509 server certificate", "Not Imported");
                      } else if (myCertificates.contains(certificate)) {
                        Messages.showWarningDialog(
                            myRootPanel, "Certificate already exists", "Not Imported");
                      } else {
                        myCertificates.add(certificate);
                        myTreeBuilder.addCertificate(certificate);
                        addCertificatePanel(certificate);
                        myTreeBuilder.selectCertificate(certificate);
                      }
                    });
              }
            })
        .setRemoveAction(
            new AnActionButtonRunnable() {
              @Override
              public void run(AnActionButton button) {
                // allow to delete several certificates at once
                for (X509Certificate certificate : myTreeBuilder.getSelectedCertificates(true)) {
                  myCertificates.remove(certificate);
                  myTreeBuilder.removeCertificate(certificate);
                }
                if (myCertificates.isEmpty()) {
                  showCard(EMPTY_PANEL);
                } else {
                  myTreeBuilder.selectFirstCertificate();
                }
              }
            });

    myTree.addTreeSelectionListener(
        new TreeSelectionListener() {
          @Override
          public void valueChanged(TreeSelectionEvent e) {
            X509Certificate certificate = myTreeBuilder.getFirstSelectedCertificate(true);
            if (certificate != null) {
              showCard(getCardName(certificate));
            }
          }
        });
    myCertificatesListPanel.add(decorator.createPanel(), BorderLayout.CENTER);
  }
  public StructureViewComponent(
      final FileEditor editor,
      final StructureViewModel structureViewModel,
      final Project project,
      final boolean showRootNode) {
    super(true, true);

    myProject = project;
    myFileEditor = editor;
    myTreeModel = structureViewModel;
    myTreeModelWrapper = new TreeModelWrapper(myTreeModel, this);

    SmartTreeStructure treeStructure =
        new SmartTreeStructure(project, myTreeModelWrapper) {
          public void rebuildTree() {
            if (!isDisposed()) {
              super.rebuildTree();
            }
          }

          public boolean isToBuildChildrenInBackground(final Object element) {
            return getRootElement() == element;
          }

          protected TreeElementWrapper createTree() {
            return new StructureViewTreeElementWrapper(myProject, myModel.getRoot(), myModel);
          }

          @Override
          public String toString() {
            return "structure view tree structure(model=" + myTreeModel + ")";
          }
        };

    final DefaultTreeModel model =
        new DefaultTreeModel(new DefaultMutableTreeNode(treeStructure.getRootElement()));
    myTree = new Tree(model);
    myTree.setRootVisible(showRootNode);
    myTree.setShowsRootHandles(true);

    myAbstractTreeBuilder =
        new StructureTreeBuilder(
            project,
            myTree,
            (DefaultTreeModel) myTree.getModel(),
            treeStructure,
            myTreeModelWrapper) {
          @Override
          protected boolean validateNode(Object child) {
            return isValid(child);
          }
        };
    Disposer.register(this, myAbstractTreeBuilder);
    Disposer.register(
        myAbstractTreeBuilder,
        new Disposable() {
          public void dispose() {
            storeState();
          }
        });

    setContent(ScrollPaneFactory.createScrollPane(myAbstractTreeBuilder.getTree()));

    myAbstractTreeBuilder.getTree().setCellRenderer(new NodeRenderer());

    myAutoScrollToSourceHandler = new MyAutoScrollToSourceHandler();
    myAutoScrollFromSourceHandler = new MyAutoScrollFromSourceHandler(myProject, this);

    JComponent toolbarComponent =
        ActionManager.getInstance()
            .createActionToolbar(ActionPlaces.STRUCTURE_VIEW_TOOLBAR, createActionGroup(), true)
            .getComponent();
    setToolbar(toolbarComponent);

    installTree();

    myCopyPasteDelegator =
        new CopyPasteDelegator(myProject, getTree()) {
          @NotNull
          protected PsiElement[] getSelectedElements() {
            return getSelectedPsiElements();
          }
        };
  }
  @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;
  }
    public ResourcePanel(AndroidFacet facet, ResourceType[] types, boolean system) {
      myTree = new Tree();
      myTree.setModel(new DefaultTreeModel(new DefaultMutableTreeNode()));
      myTree.setScrollsOnExpand(true);
      myTree.setRootVisible(false);
      myTree.setShowsRootHandles(true);
      new DoubleClickListener() {
        @Override
        protected boolean onDoubleClick(MouseEvent e) {
          if (!myTreeBuilder.getSelectedElements(ResourceItem.class).isEmpty()) {
            close(OK_EXIT_CODE);
            return true;
          }
          return false;
        }
      }.installOn(myTree);

      ToolTipManager.sharedInstance().registerComponent(myTree);
      TreeUtil.installActions(myTree);

      myManager = facet.getResourceManager(system ? AndroidUtils.SYSTEM_RESOURCE_PACKAGE : null);
      myGroups = new ResourceGroup[types.length];

      for (int i = 0; i < types.length; i++) {
        myGroups[i] = new ResourceGroup(types[i], myManager);
      }

      myTreeBuilder =
          new AbstractTreeBuilder(
              myTree,
              (DefaultTreeModel) myTree.getModel(),
              new TreeContentProvider(myGroups),
              null);
      myTreeBuilder.initRootNode();

      TreeSelectionModel selectionModel = myTree.getSelectionModel();
      selectionModel.setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
      selectionModel.addTreeSelectionListener(ChooseResourceDialog.this);

      myTree.setCellRenderer(new NodeRenderer());
      new TreeSpeedSearch(myTree, TreeSpeedSearch.NODE_DESCRIPTOR_TOSTRING, true);

      myComponent = new JBSplitter(true, 0.8f);
      myComponent.setSplitterProportionKey("android.resource_dialog_splitter");

      myComponent.setFirstComponent(ScrollPaneFactory.createScrollPane(myTree));

      myPreviewPanel = new JPanel(new CardLayout());
      myComponent.setSecondComponent(myPreviewPanel);

      myTextArea = new JTextArea(5, 20);
      myTextArea.setEditable(false);
      myPreviewPanel.add(ScrollPaneFactory.createScrollPane(myTextArea), TEXT);

      myComboTextArea = new JTextArea(5, 20);
      myComboTextArea.setEditable(false);

      myComboBox = new JComboBox();
      myComboBox.setMaximumRowCount(15);
      myComboBox.addActionListener(
          new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
              java.util.List<ResourceElement> resources =
                  (java.util.List<ResourceElement>) myComboBox.getClientProperty(COMBO);
              myComboTextArea.setText(
                  getResourceElementValue(resources.get(myComboBox.getSelectedIndex())));
            }
          });

      JPanel comboPanel =
          new JPanel(
              new BorderLayout(0, 1) {
                @Override
                public void layoutContainer(Container target) {
                  super.layoutContainer(target);
                  Rectangle bounds = myComboBox.getBounds();
                  Dimension size = myComboBox.getPreferredSize();
                  size.width += 20;
                  myComboBox.setBounds(
                      (int) bounds.getMaxX() - size.width, bounds.y, size.width, size.height);
                }
              });
      comboPanel.add(ScrollPaneFactory.createScrollPane(myComboTextArea), BorderLayout.CENTER);
      comboPanel.add(myComboBox, BorderLayout.SOUTH);
      myPreviewPanel.add(comboPanel, COMBO);

      myImageComponent = new JLabel();
      myImageComponent.setHorizontalAlignment(SwingConstants.CENTER);
      myImageComponent.setVerticalAlignment(SwingConstants.CENTER);
      myPreviewPanel.add(myImageComponent, IMAGE);

      myNoPreviewComponent = new JLabel("No Preview");
      myNoPreviewComponent.setHorizontalAlignment(SwingConstants.CENTER);
      myNoPreviewComponent.setVerticalAlignment(SwingConstants.CENTER);
      myPreviewPanel.add(myNoPreviewComponent, NONE);
    }
Exemplo n.º 15
0
  private JPanel createPanel() {
    createModel();
    myTree = new MyTree();
    myTree.setLineStyleAngled();
    myTree.setRootVisible(false);
    myTree.setShowsRootHandles(true);
    myTree.updateUI();
    myTree.setLargeModel(true);

    myTree.addKeyListener(
        new KeyAdapter() {
          public void keyPressed(KeyEvent e) {
            if (e.getKeyCode() == KeyEvent.VK_ENTER) {
              OpenSourceUtil.openSourcesFrom(
                  DataManager.getInstance().getDataContext(myTree), false);
            }
          }
        });

    myTree.addMouseListener(
        new PopupHandler() {
          public void invokePopup(Component comp, int x, int y) {
            popupInvoked(comp, x, y);
          }
        });

    EditSourceOnDoubleClickHandler.install(myTree);

    myAutoScrollToSourceHandler.install(myTree);

    myOccurenceNavigatorSupport =
        new OccurenceNavigatorSupport(myTree) {
          protected Navigatable createDescriptorForNode(DefaultMutableTreeNode node) {
            if (!(node instanceof MessageNode)) {
              return null;
            }
            MessageNode messageNode = (MessageNode) node;
            AntBuildMessageView.MessageType type = messageNode.getType();

            if (type != AntBuildMessageView.MessageType.MESSAGE
                && type != AntBuildMessageView.MessageType.ERROR) {
              return null;
            }

            if (!isValid(messageNode.getFile())) {
              return null;
            }

            return new OpenFileDescriptor(
                myProject, messageNode.getFile(), messageNode.getOffset());
          }

          @Nullable
          public String getNextOccurenceActionName() {
            return AntBundle.message("ant.execution.next.error.warning.action.name");
          }

          @Nullable
          public String getPreviousOccurenceActionName() {
            return AntBundle.message("ant.execution.previous.error.warning.action.name");
          }
        };

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

    JScrollPane scrollPane = MessageTreeRenderer.install(myTree);
    panel.add(scrollPane, BorderLayout.CENTER);
    return panel;
  }
  public GenerateByPatternDialog(Project project, PatternDescriptor[] descriptors) {
    super(project);
    myProject = project;
    setTitle("Generate by Pattern");
    setOKButtonText("Generate");

    myMap = new MultiMap<>();
    for (PatternDescriptor descriptor : descriptors) {
      myMap.putValue(descriptor.getParentId(), descriptor);
    }
    DefaultMutableTreeNode root = createNode(null);

    myTree = new SimpleTree() {};

    myTree.setRootVisible(false);
    myTree.setCellRenderer(
        new DefaultTreeCellRenderer() {
          @NotNull
          @Override
          public Component getTreeCellRendererComponent(
              @NotNull JTree tree,
              Object value,
              boolean sel,
              boolean expanded,
              boolean leaf,
              int row,
              boolean hasFocus) {
            Component component =
                super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);

            Object object = ((DefaultMutableTreeNode) value).getUserObject();
            if (object instanceof PatternDescriptor) {
              setText(((PatternDescriptor) object).getName());
              setIcon(((PatternDescriptor) object).getIcon());
            }
            return component;
          }
        });

    myTree.setModel(new DefaultTreeModel(root));
    myTree
        .getSelectionModel()
        .addTreeSelectionListener(
            new TreeSelectionListener() {
              @Override
              public void valueChanged(@NotNull TreeSelectionEvent e) {
                update();
              }
            });
    myEditor = TemplateEditorUtil.createEditor(true, "");

    mySplitter.setFirstComponent(ScrollPaneFactory.createScrollPane(myTree));
    JPanel details = new JPanel(new BorderLayout());
    details.add(myEditor.getComponent(), BorderLayout.CENTER);
    mySplitter.setSecondComponent(details);
    mySplitter.setHonorComponentsMinimumSize(true);
    mySplitter.setShowDividerControls(true);

    myTree.setSelectionRow(0);

    init();
  }