private void updatePathFromTree(final List<VirtualFile> selection, boolean now) {
    if (!isToShowTextField() || myTreeIsUpdating) return;

    String text = "";
    if (selection.size() > 0) {
      text = VfsUtil.getReadableUrl(selection.get(0));
    } else {
      final List<VirtualFile> roots = myChooserDescriptor.getRoots();
      if (!myFileSystemTree.getTree().isRootVisible() && roots.size() == 1) {
        text = VfsUtil.getReadableUrl(roots.get(0));
      }
    }

    myPathTextField.setText(
        text,
        now,
        () -> {
          myPathTextField.getField().selectAll();
          setErrorText(null);
        });
  }
Ejemplo n.º 2
0
 public FileChooserDescriptor getHomeChooserDescriptor() {
   final FileChooserDescriptor descriptor =
       new FileChooserDescriptor(false, true, false, false, false, false) {
         @Override
         public void validateSelectedFiles(VirtualFile[] files) throws Exception {
           if (files.length != 0) {
             final String selectedPath = files[0].getPath();
             boolean valid = isValidSdkHome(selectedPath);
             if (!valid) {
               valid = isValidSdkHome(adjustSelectedSdkHome(selectedPath));
               if (!valid) {
                 String message =
                     files[0].isDirectory()
                         ? ProjectBundle.message(
                             "sdk.configure.home.invalid.error", getPresentableName())
                         : ProjectBundle.message(
                             "sdk.configure.home.file.invalid.error", getPresentableName());
                 throw new Exception(message);
               }
             }
           }
         }
       };
   descriptor.setTitle(ProjectBundle.message("sdk.configure.home.title", getPresentableName()));
   return descriptor;
 }
 private void setUpChooseHtmlToShow() {
   FileChooserDescriptor fileChooserDescriptor =
       FileChooserDescriptorFactory.createSingleFileDescriptor(StdFileTypes.HTML);
   fileChooserDescriptor.setRoots(ProjectRootManager.getInstance(project).getContentRoots());
   htmlChooseFile.addBrowseFolderListener(
       "Choose file to show after translation is finished", null, project, fileChooserDescriptor);
 }
Ejemplo n.º 4
0
 @Override
 public FileChooserDescriptor getHomeChooserDescriptor() {
   final FileChooserDescriptor result = super.getHomeChooserDescriptor();
   if (SystemInfo.isMac) {
     result.putUserData(PathChooserDialog.NATIVE_MAC_CHOOSER_SHOW_HIDDEN_FILES, Boolean.TRUE);
   }
   return result;
 }
 public FileChooserDescriptor getFileChooserDescriptor() {
   FileChooserDescriptor d = new FileChooserDescriptor(false, true, false, true, false, false);
   if (myTitle != null) {
     d.setTitle(myTitle);
   }
   d.setShowFileSystemRoots(true);
   return d;
 }
Ejemplo n.º 6
0
  @Nullable
  public static AddModuleWizard selectFileAndCreateWizard(
      final Project project, Component dialogParent) {
    FileChooserDescriptor descriptor =
        FileChooserDescriptorFactory.createSingleLocalFileDescriptor();
    descriptor.setHideIgnored(false);
    descriptor.setTitle("Select File or Directory to Import");
    ProjectImportProvider[] providers =
        ProjectImportProvider.PROJECT_IMPORT_PROVIDER.getExtensions();
    String description = getFileChooserDescription(project);
    descriptor.setDescription(description);

    return selectFileAndCreateWizard(project, dialogParent, descriptor, providers);
  }
 @NotNull
 private static FileChooserDescriptor addFileChooser(
     @NotNull final String title,
     @NotNull final TextFieldWithBrowseButton textField,
     @NotNull final Project project) {
   final FileChooserDescriptor fileChooserDescriptor =
       new FileChooserDescriptor(false, true, false, false, false, false) {
         @Override
         public boolean isFileVisible(VirtualFile file, boolean showHiddenFiles) {
           return super.isFileVisible(file, showHiddenFiles) && file.isDirectory();
         }
       };
   fileChooserDescriptor.setTitle(title);
   textField.addBrowseFolderListener(title, null, project, fileChooserDescriptor);
   return fileChooserDescriptor;
 }
 private void setupRootAndAnnotateExternally(
     @NotNull final OrderEntry entry,
     @NotNull final Project project,
     @NotNull final PsiModifierListOwner listOwner,
     @NotNull final String annotationFQName,
     @NotNull final PsiFile fromFile,
     @NotNull final String packageName,
     @Nullable final PsiNameValuePair[] value) {
   final FileChooserDescriptor descriptor =
       FileChooserDescriptorFactory.createSingleFolderDescriptor();
   descriptor.setTitle(
       ProjectBundle.message(
           "external.annotations.root.chooser.title", entry.getPresentableName()));
   descriptor.setDescription(
       ProjectBundle.message("external.annotations.root.chooser.description"));
   final VirtualFile newRoot = FileChooser.chooseFile(descriptor, project, null);
   if (newRoot == null) {
     notifyAfterAnnotationChanging(listOwner, annotationFQName, false);
     return;
   }
   new WriteCommandAction(project) {
     @Override
     protected void run(final Result result) throws Throwable {
       appendChosenAnnotationsRoot(entry, newRoot);
       XmlFile xmlFileInRoot =
           findXmlFileInRoot(findExternalAnnotationsXmlFiles(listOwner), newRoot);
       if (xmlFileInRoot != null) { // file already exists under appeared content root
         if (!CodeInsightUtilBase.preparePsiElementForWrite(xmlFileInRoot)) {
           notifyAfterAnnotationChanging(listOwner, annotationFQName, false);
           return;
         }
         annotateExternally(listOwner, annotationFQName, xmlFileInRoot, fromFile, value);
       } else {
         final XmlFile annotationsXml = createAnnotationsXml(newRoot, packageName);
         if (annotationsXml != null) {
           final List<PsiFile> createdFiles = new ArrayList<PsiFile>();
           createdFiles.add(annotationsXml);
           String fqn = getFQN(packageName, fromFile);
           if (fqn != null) {
             myExternalAnnotations.put(fqn, createdFiles);
           }
         }
         annotateExternally(listOwner, annotationFQName, annotationsXml, fromFile, value);
       }
     }
   }.execute();
 }
  private void chooseManifest() {
    final FileChooserDescriptor descriptor =
        new FileChooserDescriptor(true, false, false, false, false, false) {
          @Override
          public boolean isFileVisible(VirtualFile file, boolean showHiddenFiles) {
            return super.isFileVisible(file, showHiddenFiles)
                && (file.isDirectory()
                    || file.getName().equalsIgnoreCase(ManifestFileUtil.MANIFEST_FILE_NAME));
          }
        };
    descriptor.setTitle("Specify Path to MANIFEST.MF file");
    final VirtualFile[] files = FileChooser.chooseFiles(myContext.getProject(), descriptor);
    if (files.length != 1) return;

    ManifestFileUtil.addManifestFileToLayout(files[0].getPath(), myContext, myElement);
    updateManifest();
    myContext.getThisArtifactEditor().updateLayoutTree();
  }
  @Nullable
  protected final JComponent createTitlePane() {
    final String description = myChooserDescriptor.getDescription();
    if (StringUtil.isEmptyOrSpaces(description)) return null;

    final JLabel label = new JLabel(description);
    label.setBorder(
        BorderFactory.createCompoundBorder(
            new SideBorder(UIUtil.getPanelBackground().darker(), SideBorder.BOTTOM),
            JBUI.Borders.empty(0, 5, 10, 5)));
    return label;
  }
Ejemplo n.º 11
0
 @NotNull
 @Override
 public FileChooserDescriptor getHomeChooserDescriptor() {
   final FileChooserDescriptor baseDescriptor = super.getHomeChooserDescriptor();
   final FileChooserDescriptor descriptor =
       new FileChooserDescriptor(baseDescriptor) {
         @Override
         public void validateSelectedFiles(VirtualFile[] files) throws Exception {
           if (files.length > 0 && !JrtFileSystem.isSupported()) {
             String path = files[0].getPath();
             if (JrtFileSystem.isModularJdk(path)
                 || JrtFileSystem.isModularJdk(adjustSelectedSdkHome(path))) {
               throw new Exception(LangBundle.message("jrt.not.available.message"));
             }
           }
           baseDescriptor.validateSelectedFiles(files);
         }
       };
   descriptor.putUserData(KEY, Boolean.TRUE);
   return descriptor;
 }
 @Override
 public NewLibraryConfiguration createNewLibrary(
     @NotNull JComponent parentComponent, VirtualFile contextDirectory) {
   final FileChooserDescriptor descriptor =
       new FileChooserDescriptor(false, false, true, false, false, true);
   descriptor.setTitle(IdeBundle.message("new.library.file.chooser.title"));
   descriptor.setDescription(IdeBundle.message("new.library.file.chooser.description"));
   final VirtualFile[] files =
       FileChooser.chooseFiles(descriptor, parentComponent, null, contextDirectory);
   if (files.length == 0) {
     return null;
   }
   return new NewLibraryConfiguration(
       myDefaultLibraryName, getDownloadableLibraryType(), new LibraryVersionProperties()) {
     @Override
     public void addRoots(@NotNull LibraryEditor editor) {
       for (VirtualFile file : files) {
         editor.addRoot(file, OrderRootType.CLASSES);
       }
     }
   };
 }
  /** Init components */
  private void initListeners() {
    FileChooserDescriptor fcd = FileChooserDescriptorFactory.createSingleFolderDescriptor();
    fcd.setShowFileSystemRoots(true);
    fcd.setTitle(GitBundle.getString("clone.destination.directory.title"));
    fcd.setDescription(GitBundle.getString("clone.destination.directory.description"));
    fcd.setHideIgnored(false);
    myParentDirectory.addActionListener(
        new ComponentWithBrowseButton.BrowseFolderActionListener<JTextField>(
            fcd.getTitle(),
            fcd.getDescription(),
            myParentDirectory,
            myProject,
            fcd,
            TextComponentAccessor.TEXT_FIELD_WHOLE_TEXT) {
          @Override
          protected VirtualFile getInitialFile() {
            // suggest project base directory only if nothing is typed in the component.
            String text = getComponentText();
            if (text.length() == 0) {
              VirtualFile file = myProject.getBaseDir();
              if (file != null) {
                return file;
              }
            }
            return super.getInitialFile();
          }
        });

    final DocumentListener updateOkButtonListener =
        new DocumentAdapter() {
          @Override
          protected void textChanged(DocumentEvent e) {
            updateButtons();
          }
        };
    myParentDirectory.getChildComponent().getDocument().addDocumentListener(updateOkButtonListener);
    String parentDir = GitRememberedInputs.getInstance().getCloneParentDir();
    if (StringUtil.isEmptyOrSpaces(parentDir)) {
      parentDir = ProjectUtil.getBaseDir();
    }
    myParentDirectory.setText(parentDir);

    myDirectoryName.getDocument().addDocumentListener(updateOkButtonListener);

    myTestButton.addActionListener(
        new ActionListener() {
          public void actionPerformed(final ActionEvent e) {
            test();
          }
        });

    setOKActionEnabled(false);
    myTestButton.setEnabled(false);
  }
 @Override
 protected boolean isAlwaysShowPlus(NodeDescriptor nodeDescriptor) {
   Object element = nodeDescriptor.getElement();
   if (element != null) {
     FileElement descriptor = (FileElement) element;
     VirtualFile file = descriptor.getFile();
     if (file != null) {
       if (myChooserDescriptor.isChooseJarContents() && FileElement.isArchive(file)) {
         return true;
       }
       return file.isDirectory();
     }
   }
   return true;
 }
  private void setUpChooseGenerateFilePath() {
    FileChooserDescriptor fileChooserDescriptor =
        FileChooserDescriptorFactory.getDirectoryChooserDescriptor(
            "directory where generated files will be stored");
    fileChooserDescriptor.setRoots(ProjectRootManager.getInstance(project).getContentRoots());
    generatedChooseFile.addBrowseFolderListener(null, null, project, fileChooserDescriptor);
    final JTextField textField = generatedChooseFile.getTextField();
    textField
        .getDocument()
        .addDocumentListener(
            new DocumentListener() {
              @Override
              public void insertUpdate(DocumentEvent e) {
                onChange();
              }

              @Override
              public void removeUpdate(DocumentEvent e) {
                onChange();
              }

              @Override
              public void changedUpdate(DocumentEvent e) {
                onChange();
              }

              private void onChange() {
                File file = new File(generatedChooseFile.getText());
                if (!file.isDirectory()) {
                  textField.setForeground(Color.RED);
                } else {
                  textField.setForeground(Color.BLACK);
                }
              }
            });
  }
  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);
  }
  protected void doOKAction() {
    if (!isOKActionEnabled()) {
      return;
    }

    if (isTextFieldActive()) {
      final String text = myPathTextField.getTextFieldText();
      final LookupFile file = myPathTextField.getFile();
      if (text == null || file == null || !file.exists()) {
        setErrorText("Specified path cannot be found");
        return;
      }
    }

    final List<VirtualFile> selectedFiles = Arrays.asList(getSelectedFilesInt());
    final VirtualFile[] files =
        VfsUtilCore.toVirtualFileArray(
            FileChooserUtil.getChosenFiles(myChooserDescriptor, selectedFiles));
    if (files.length == 0) {
      myChosenFiles = VirtualFile.EMPTY_ARRAY;
      close(CANCEL_EXIT_CODE);
      return;
    }

    try {
      myChooserDescriptor.validateSelectedFiles(files);
    } catch (Exception e) {
      Messages.showErrorDialog(getContentPane(), e.getMessage(), getTitle());
      return;
    }

    myChosenFiles = files;
    storeSelection(files[files.length - 1]);

    super.doOKAction();
  }
Ejemplo n.º 19
0
  /** Init components */
  private void initListeners() {
    FileChooserDescriptor fcd = new FileChooserDescriptor(false, true, false, false, false, false);
    fcd.setShowFileSystemRoots(true);
    fcd.setTitle(GitBundle.getString("clone.destination.directory.title"));
    fcd.setDescription(GitBundle.getString("clone.destination.directory.description"));
    fcd.setHideIgnored(false);
    myParentDirectory.addActionListener(
        new ComponentWithBrowseButton.BrowseFolderActionListener<JTextField>(
            fcd.getTitle(),
            fcd.getDescription(),
            myParentDirectory,
            myProject,
            fcd,
            TextComponentAccessor.TEXT_FIELD_WHOLE_TEXT) {
          @Override
          protected VirtualFile getInitialFile() {
            // suggest project base directory only if nothing is typed in the component.
            String text = getComponentText();
            if (text.length() == 0) {
              VirtualFile file = myProject.getBaseDir();
              if (file != null) {
                return file;
              }
            }
            return super.getInitialFile();
          }
        });
    final DocumentListener updateOkButtonListener =
        new DocumentListener() {
          // update Ok button state depending on the current state of the fields
          public void insertUpdate(final DocumentEvent e) {
            updateOkButton();
          }

          public void removeUpdate(final DocumentEvent e) {
            updateOkButton();
          }

          public void changedUpdate(final DocumentEvent e) {
            updateOkButton();
          }
        };
    myParentDirectory.getChildComponent().getDocument().addDocumentListener(updateOkButtonListener);
    myDirectoryName.getDocument().addDocumentListener(updateOkButtonListener);
    myOriginName.getDocument().addDocumentListener(updateOkButtonListener);
    myRepositoryURL
        .getDocument()
        .addDocumentListener(
            new DocumentListener() {
              // enable test button only if something is entered in repository URL
              public void insertUpdate(final DocumentEvent e) {
                changed();
              }

              public void removeUpdate(final DocumentEvent e) {
                changed();
              }

              public void changedUpdate(final DocumentEvent e) {
                changed();
              }

              private void changed() {
                final String url = myRepositoryURL.getText();
                myTestButton.setEnabled(url.length() != 0);
                if (myDefaultDirectoryName.equals(myDirectoryName.getText())
                    || myDirectoryName.getText().length() == 0) {
                  // modify field if it was unmodified or blank
                  myDefaultDirectoryName = defaultDirectoryName(url);
                  myDirectoryName.setText(myDefaultDirectoryName);
                }
                updateOkButton();
              }
            });
    myTestButton.addActionListener(
        new ActionListener() {
          public void actionPerformed(final ActionEvent e) {
            myTestURL = myRepositoryURL.getText();
            String output =
                GitHandlerUtil.doSynchronously(
                    GitSimpleHandler.checkRepository(myProject, myTestURL),
                    GitBundle.message("clone.testing", myTestURL),
                    "connection test");
            if (output != null) {
              Messages.showInfoMessage(
                  myTestButton,
                  GitBundle.message("clone.test.success.message", myTestURL),
                  GitBundle.getString("clone.test.success"));
              myTestResult = Boolean.TRUE;
            } else {
              myTestResult = Boolean.FALSE;
            }
            updateOkButton();
          }
        });
    setOKActionEnabled(false);
  }
  private void importBtnListner() {
    FileChooserDescriptor fileChooserDescriptor =
        new FileChooserDescriptor(true, false, false, false, false, false) {
          @Override
          public boolean isFileVisible(VirtualFile file, boolean showHiddenFiles) {
            return file.isDirectory()
                || (file.getExtension() != null
                    && (file.getExtension().equals("pfx")
                        || file.getExtension().equals("pfx")
                        || file.getExtension().equals("cer")
                        || file.getExtension().equals(".CER")));
          }

          @Override
          public boolean isFileSelectable(VirtualFile file) {
            return (file.getExtension() != null
                && (file.getExtension().equals("pfx")
                    || file.getExtension().equals("pfx")
                    || file.getExtension().equals("cer")
                    || file.getExtension().equals(".CER")));
          }
        };
    fileChooserDescriptor.setTitle("Select Certificate");

    FileChooser.chooseFile(
        fileChooserDescriptor,
        null,
        null,
        new Consumer<VirtualFile>() {
          @Override
          public void consume(VirtualFile virtualFile) {
            if (virtualFile != null) {
              String path = virtualFile.getPath();
              String password = null;
              boolean proceed = true;
              if (path.endsWith(".pfx") || path.endsWith(".PFX")) {
                SimplePfxPwdDlg dlg = new SimplePfxPwdDlg(path);
                dlg.show();
                if (dlg.isOK()) {
                  password = dlg.getPwd();
                } else {
                  proceed = false;
                }
              }
              if (proceed) {
                X509Certificate cert = CerPfxUtil.getCert(path, password);
                if (cert != null) {
                  if (txtName.getText().isEmpty()) {
                    populateCertName(
                        CertificateDialogUtilMethods.removeSpaceFromCN(
                            cert.getSubjectDN().getName()));
                  }
                  String thumbprint = "";
                  try {
                    thumbprint = CerPfxUtil.getThumbPrint(cert);
                  } catch (Exception e) {
                    PluginUtil.displayErrorDialog(message("certErrTtl"), message("certImpEr"));
                  }
                  txtThumb.setText(thumbprint);
                }
              }
            }
          }
        });
  }
  @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;
  }
  @Override
  public void actionPerformed(AnActionEvent event) {
    final Project project = event.getData(CommonDataKeys.PROJECT);

    LOG.assertTrue(project != null);

    final FileChooserDescriptor descriptor =
        new FileChooserDescriptor(false, true, false, false, false, false) {
          @Override
          public Icon getIcon(VirtualFile file) {
            if (file.isDirectory()) {
              if (file.findChild(
                      InspectionApplication.DESCRIPTIONS
                          + "."
                          + StdFileTypes.XML.getDefaultExtension())
                  != null) {
                return AllIcons.Nodes.InspectionResults;
              }
            }
            return super.getIcon(file);
          }
        };
    descriptor.setTitle("Select Path");
    descriptor.setDescription("Select directory which contains exported inspections results");
    final VirtualFile virtualFile = FileChooser.chooseFile(descriptor, project, null);
    if (virtualFile == null || !virtualFile.isDirectory()) return;

    final Map<String, Map<String, Set<OfflineProblemDescriptor>>> resMap = new HashMap<>();
    final String[] profileName = new String[1];
    final Runnable process =
        () -> {
          final VirtualFile[] files = virtualFile.getChildren();
          try {
            for (final VirtualFile inspectionFile : files) {
              if (inspectionFile.isDirectory()) continue;
              final String shortName = inspectionFile.getNameWithoutExtension();
              final String extension = inspectionFile.getExtension();
              if (shortName.equals(InspectionApplication.DESCRIPTIONS)) {
                profileName[0] =
                    ApplicationManager.getApplication()
                        .runReadAction(
                            (Computable<String>)
                                () ->
                                    OfflineViewParseUtil.parseProfileName(
                                        LoadTextUtil.loadText(inspectionFile).toString()));
              } else if (XML_EXTENSION.equals(extension)) {
                resMap.put(
                    shortName,
                    ApplicationManager.getApplication()
                        .runReadAction(
                            new Computable<Map<String, Set<OfflineProblemDescriptor>>>() {
                              @Override
                              public Map<String, Set<OfflineProblemDescriptor>> compute() {
                                return OfflineViewParseUtil.parse(
                                    LoadTextUtil.loadText(inspectionFile).toString());
                              }
                            }));
              }
            }
          } catch (final Exception e) { // all parse exceptions
            SwingUtilities.invokeLater(
                () ->
                    Messages.showInfoMessage(
                        e.getMessage(),
                        InspectionsBundle.message("offline.view.parse.exception.title")));
            throw new ProcessCanceledException(); // cancel process
          }
        };
    ProgressManager.getInstance()
        .runProcessWithProgressAsynchronously(
            project,
            InspectionsBundle.message("parsing.inspections.dump.progress.title"),
            process,
            () ->
                SwingUtilities.invokeLater(
                    () -> {
                      final String name = profileName[0];
                      showOfflineView(
                          project,
                          name,
                          resMap,
                          InspectionsBundle.message("offline.view.title")
                              + " ("
                              + (name != null
                                  ? name
                                  : InspectionsBundle.message("offline.view.editor.settings.title"))
                              + ")");
                    }),
            null,
            new PerformAnalysisInBackgroundOption(project));
  }
 private static String getChooserTitle(final FileChooserDescriptor descriptor) {
   final String title = descriptor.getTitle();
   return title != null ? title : UIBundle.message("file.chooser.default.title");
 }
  private void doImportAction(final DataContext dataContext) {
    final FileChooserDescriptor descriptor =
        new FileChooserDescriptor(true, false, true, false, true, false) {
          @Override
          public boolean isFileVisible(VirtualFile file, boolean showHiddenFiles) {
            return super.isFileVisible(file, showHiddenFiles)
                && (file.isDirectory()
                    || "xml".equals(file.getExtension())
                    || file.getFileType() == FileTypes.ARCHIVE);
          }

          @Override
          public boolean isFileSelectable(VirtualFile file) {
            return file.getFileType() == StdFileTypes.XML;
          }
        };
    descriptor.setDescription(
        "Please select the configuration file (usually named IntelliLang.xml) to import.");
    descriptor.setTitle("Import Configuration");

    descriptor.putUserData(LangDataKeys.MODULE_CONTEXT, LangDataKeys.MODULE.getData(dataContext));

    final SplitterProportionsData splitterData = new SplitterProportionsDataImpl();
    splitterData.externalizeFromDimensionService(
        "IntelliLang.ImportSettingsKey.SplitterProportions");

    final VirtualFile file = FileChooser.chooseFile(descriptor, myProject, null);
    if (file == null) return;
    try {
      final Configuration cfg = Configuration.load(file.getInputStream());
      if (cfg == null) {
        Messages.showWarningDialog(
            myProject,
            "The selected file does not contain any importable configuration.",
            "Nothing to Import");
        return;
      }
      final CfgInfo info = getDefaultCfgInfo();
      final Map<String, Set<InjInfo>> currentMap =
          ContainerUtil.classify(
              info.injectionInfos.iterator(),
              new Convertor<InjInfo, String>() {
                public String convert(final InjInfo o) {
                  return o.injection.getSupportId();
                }
              });
      final List<BaseInjection> originalInjections = new ArrayList<BaseInjection>();
      final List<BaseInjection> newInjections = new ArrayList<BaseInjection>();
      //// remove duplicates
      // for (String supportId : InjectorUtils.getActiveInjectionSupportIds()) {
      //  final Set<BaseInjection> currentInjections = currentMap.get(supportId);
      //  if (currentInjections == null) continue;
      //  for (BaseInjection injection : currentInjections) {
      //    Configuration.importInjections(newInjections, Collections.singleton(injection),
      // originalInjections, newInjections);
      //  }
      // }
      // myInjections.clear();
      // myInjections.addAll(newInjections);

      for (String supportId : InjectorUtils.getActiveInjectionSupportIds()) {
        ArrayList<InjInfo> list =
            new ArrayList<InjInfo>(
                ObjectUtils.notNull(currentMap.get(supportId), Collections.<InjInfo>emptyList()));
        final List<BaseInjection> currentInjections = getInjectionList(list);
        final List<BaseInjection> importingInjections = cfg.getInjections(supportId);
        if (currentInjections == null) {
          newInjections.addAll(importingInjections);
        } else {
          Configuration.importInjections(
              currentInjections, importingInjections, originalInjections, newInjections);
        }
      }
      info.replace(originalInjections, newInjections);
      myInjectionsTable.getListTableModel().setItems(getInjInfoList(myInfos));
      final int n = newInjections.size();
      if (n > 1) {
        Messages.showInfoMessage(
            myProject, n + " entries have been successfully imported", "Import Successful");
      } else if (n == 1) {
        Messages.showInfoMessage(
            myProject, "One entry has been successfully imported", "Import Successful");
      } else {
        Messages.showInfoMessage(myProject, "No new entries have been imported", "Import");
      }
    } catch (Exception ex) {
      Configuration.LOG.error(ex);

      final String msg = ex.getLocalizedMessage();
      Messages.showErrorDialog(
          myProject, msg != null && msg.length() > 0 ? msg : ex.toString(), "Import Failed");
    }
  }
 public static FileChooserDescriptor createDescriptorForManifestDirectory() {
   FileChooserDescriptor descriptor = FileChooserDescriptorFactory.createSingleFolderDescriptor();
   descriptor.setTitle("Select Directory for META-INF/MANIFEST.MF file");
   return descriptor;
 }
Ejemplo n.º 26
0
 public PathEditor(final FileChooserDescriptor descriptor) {
   myDescriptor = descriptor;
   myDescriptor.putUserData(FileChooserDialog.PREFER_LAST_OVER_TO_SELECT, Boolean.TRUE);
   myModel = createListModel();
 }
  @NotNull
  protected PsiElement[] invokeDialog(final Project project, final PsiDirectory directory) {
    final FileChooserDescriptor descriptor =
        FileChooserDescriptorFactory.createSingleFolderDescriptor();
    descriptor.setRoots(project.getBaseDir());
    PsiDirectory currentDir = currentFile.getContainingDirectory();
    PsiDirectory includeDir = currentDir.findSubdirectory("Includes");
    VirtualFile selectDir = directory.getVirtualFile();
    if (includeDir == null) {
      PsiDirectory parentDir = currentDir.getParentDirectory();
      if (parentDir != null) {
        includeDir = parentDir.findSubdirectory("Includes");
      }
    }
    if (includeDir != null) selectDir = includeDir.getVirtualFile();

    final VirtualFile myFolder = FileChooser.chooseFile(descriptor, project, selectDir);
    if (myFolder != null) {
      PsiDirectory myDirectory = PsiManager.getInstance(project).findDirectory(myFolder);
      final MyInputValidator validator = new MyInputValidator(project, myDirectory);
      final String fileName =
          Messages.showInputDialog(
              project,
              getDialogPrompt(),
              getDialogTitle(),
              Messages.getQuestionIcon(),
              "",
              validator);

      final PsiElement[] elements = validator.getCreatedElements();
      if (elements.length > 0) {
        ApplicationManager.getApplication()
            .invokeLater(
                new Runnable() {
                  @Override
                  public void run() {
                    ApplicationManager.getApplication()
                        .runWriteAction(
                            new Runnable() {
                              @Override
                              public void run() {
                                try {
                                  CodeStyleManager codeStyleManager =
                                      CodeStyleManager.getInstance(project);
                                  CaretModel caretModel = editor.getCaretModel();
                                  int caretOffset = selectonModel.getSelectionStart();
                                  EditorModificationUtil.deleteSelectedText(editor);
                                  PsiDocumentManager psiDocumentManager =
                                      PsiDocumentManager.getInstance(project);
                                  caretModel.moveToOffset(caretOffset);
                                  EditorModificationUtil.insertStringAtCaret(
                                      editor, "<% include " + fileName + " %>", true, false);
                                  PsiFile createdFile = (PsiFile) elements[0];
                                  codeStyleManager.reformat(createdFile);
                                  psiDocumentManager.commitDocument(
                                      psiDocumentManager.getDocument(currentFile));
                                  FileEditorManager.getInstance(project)
                                      .openFile(currentFile.getVirtualFile(), true);
                                  codeStyleManager.adjustLineIndent(currentFile, caretOffset);
                                  psiDocumentManager.commitDocument(
                                      psiDocumentManager.getDocument(currentFile));
                                } catch (Exception e) {
                                  e.printStackTrace(); // To change body of catch statement use
                                  // File | Settings | File Templates.
                                }
                              }
                            });
                  }
                });
      }
      return elements;
    }
    return PsiElement.EMPTY_ARRAY;
  }
 static {
   CHOOSER_DESCRIPTOR.setDescription("Select Scala compiler plugin JAR");
 }
  /** @param contentEntryEditor : null means to clear the editor */
  public void setContentEntryEditor(final ContentEntryEditor contentEntryEditor) {
    if (myContentEntryEditor != null && myContentEntryEditor.equals(contentEntryEditor)) {
      return;
    }
    if (myFileSystemTree != null) {
      Disposer.dispose(myFileSystemTree);
      myFileSystemTree = null;
    }
    if (myContentEntryEditor != null) {
      myContentEntryEditor.removeContentEntryEditorListener(myContentEntryEditorListener);
      myContentEntryEditor = null;
    }
    if (contentEntryEditor == null) {
      ((DefaultTreeModel) myTree.getModel()).setRoot(EMPTY_TREE_ROOT);
      myTreePanel.setVisible(false);
      if (myFileSystemTree != null) {
        Disposer.dispose(myFileSystemTree);
      }
      return;
    }
    myTreePanel.setVisible(true);
    myContentEntryEditor = contentEntryEditor;
    myContentEntryEditor.addContentEntryEditorListener(myContentEntryEditorListener);

    final ContentEntry entry = contentEntryEditor.getContentEntry();
    assert entry != null : contentEntryEditor;
    final VirtualFile file = entry.getFile();
    myDescriptor.setRoots(file);
    if (file == null) {
      final String path = VfsUtilCore.urlToPath(entry.getUrl());
      myDescriptor.setTitle(FileUtil.toSystemDependentName(path));
    }

    final Runnable init =
        new Runnable() {
          @Override
          public void run() {
            //noinspection ConstantConditions
            myFileSystemTree.updateTree();
            myFileSystemTree.select(file, null);
          }
        };

    myFileSystemTree =
        new FileSystemTreeImpl(
            myProject, myDescriptor, myTree, getContentEntryCellRenderer(), init, null) {
          @Override
          protected AbstractTreeBuilder createTreeBuilder(
              JTree tree,
              DefaultTreeModel treeModel,
              AbstractTreeStructure treeStructure,
              Comparator<NodeDescriptor> comparator,
              FileChooserDescriptor descriptor,
              final Runnable onInitialized) {
            return new MyFileTreeBuilder(
                tree, treeModel, treeStructure, comparator, descriptor, onInitialized);
          }
        };
    myFileSystemTree.showHiddens(true);
    Disposer.register(myProject, myFileSystemTree);

    final NewFolderAction newFolderAction = new MyNewFolderAction();
    final DefaultActionGroup mousePopupGroup = new DefaultActionGroup();
    mousePopupGroup.add(myEditingActionsGroup);
    mousePopupGroup.addSeparator();
    mousePopupGroup.add(newFolderAction);
    myFileSystemTree.registerMouseListener(mousePopupGroup);
  }
Ejemplo n.º 30
0
 public AddPathActionListener() {
   myDescriptor = new FileChooserDescriptor(false, true, true, false, true, true);
   myDescriptor.setTitle(ProjectBundle.message("add.external.annotations.path.title"));
   myDescriptor.setDescription(
       ProjectBundle.message("add.external.annotations.path.description"));
 }