Example usage for com.intellij.openapi.fileChooser FileChooserDescriptor putUserData

List of usage examples for com.intellij.openapi.fileChooser FileChooserDescriptor putUserData

Introduction

In this page you can find the example usage for com.intellij.openapi.fileChooser FileChooserDescriptor putUserData.

Prototype

public <T> void putUserData(@NotNull DataKey<T> key, @Nullable T data) 

Source Link

Usage

From source file:com.android.tools.idea.actions.AndroidOpenFileAction.java

License:Apache License

@Override
public void actionPerformed(AnActionEvent e) {
    Project project = e.getProject();/*from   w ww  .  j av a  2 s .  c o m*/
    boolean showFiles = project != null || PlatformProjectOpenProcessor.getInstanceIfItExists() != null;
    FileChooserDescriptor descriptor = showFiles ? new ProjectOrFileChooserDescriptor()
            : new ProjectOnlyFileChooserDescriptor();
    descriptor.putUserData(PathChooserDialog.PREFER_LAST_OVER_EXPLICIT, showFiles);

    VirtualFile explicitPreferredDirectory = ((project != null) && !project.isDefault()) ? project.getBaseDir()
            : getUserHomeDir();
    chooseFiles(descriptor, project, explicitPreferredDirectory, files -> {
        for (VirtualFile file : files) {
            if (!descriptor.isFileSelectable(file)) {
                String message = IdeBundle.message("error.dir.contains.no.project", file.getPresentableUrl());
                Messages.showInfoMessage(project, message, IdeBundle.message("title.cannot.open.project"));
                return;
            }
        }
        doOpenFile(project, files);
    });

}

From source file:com.android.tools.idea.gradle.structure.DefaultSdksConfigurable.java

License:Apache License

@NotNull
private static FileChooserDescriptor createSingleFolderDescriptor(@NotNull String title,
        @NotNull final Function<File, Void> validation) {
    final FileChooserDescriptor descriptor = new FileChooserDescriptor(false, true, false, false, false,
            false) {/* w  w w .j a  v a  2s  .co  m*/
        @Override
        public void validateSelectedFiles(VirtualFile[] files) throws Exception {
            for (VirtualFile virtualFile : files) {
                File file = VfsUtilCore.virtualToIoFile(virtualFile);
                validation.fun(file);
            }
        }
    };
    if (SystemInfo.isMac) {
        descriptor.putUserData(PathChooserDialog.NATIVE_MAC_CHOOSER_SHOW_HIDDEN_FILES, Boolean.TRUE);
    }
    descriptor.setTitle(title);
    return descriptor;
}

From source file:com.intellij.execution.ui.CommonProgramParametersPanel.java

License:Apache License

protected void initComponents() {
    myProgramParametersComponent = LabeledComponent.create(new RawCommandLineEditor(),
            ExecutionBundle.message("run.configuration.program.parameters"));

    final JPanel panel = new JPanel(new BorderLayout());
    myWorkingDirectoryField = new TextFieldWithBrowseButton(new ActionListener() {
        @Override/* w w  w  .j a  va  2s  .  c  o m*/
        public void actionPerformed(ActionEvent e) {
            FileChooserDescriptor fileChooserDescriptor = FileChooserDescriptorFactory
                    .createSingleFolderDescriptor();
            fileChooserDescriptor.setTitle(ExecutionBundle.message("select.working.directory.message"));
            fileChooserDescriptor.putUserData(LangDataKeys.MODULE_CONTEXT, myModuleContext);
            Project project = myModuleContext != null ? myModuleContext.getProject() : null;
            VirtualFile file = FileChooser.chooseFile(fileChooserDescriptor, myWorkingDirectoryComponent,
                    project, null);
            if (file != null) {
                setWorkingDirectory(file.getPresentableUrl());
            }
        }
    }) {
        @Override
        protected void installPathCompletion(FileChooserDescriptor fileChooserDescriptor) {
            super.installPathCompletion(FileChooserDescriptorFactory.createSingleFolderDescriptor());
        }
    };
    panel.add(myWorkingDirectoryField, BorderLayout.CENTER);

    final FixedSizeButton button = new FixedSizeButton(myWorkingDirectoryField);
    button.setIcon(AllIcons.RunConfigurations.Variables);
    button.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            final List<String> macros = new ArrayList<String>(PathMacros.getInstance().getUserMacroNames());
            if (myHaveModuleContext)
                macros.add("MODULE_DIR");

            final JList list = new JBList(ArrayUtil.toStringArray(macros));
            final JBPopup popup = JBPopupFactory.getInstance().createListPopupBuilder(list)
                    .setItemChoosenCallback(new Runnable() {
                        @Override
                        public void run() {
                            final Object value = list.getSelectedValue();
                            if (value instanceof String) {
                                setWorkingDirectory("$" + value + "$");
                            }
                        }
                    }).setMovable(false).setResizable(false).createPopup();
            popup.showUnderneathOf(button);
        }
    });
    panel.add(button, BorderLayout.EAST);

    myWorkingDirectoryComponent = LabeledComponent.create(panel,
            ExecutionBundle.message("run.configuration.working.directory.label"));
    myEnvVariablesComponent = new EnvironmentVariablesComponent();

    myEnvVariablesComponent.setLabelLocation(BorderLayout.WEST);
    myProgramParametersComponent.setLabelLocation(BorderLayout.WEST);
    myWorkingDirectoryComponent.setLabelLocation(BorderLayout.WEST);

    addComponents();

    setPreferredSize(new Dimension(10, 10));

    setAnchor(myEnvVariablesComponent.getLabel());
}

From source file:com.intellij.ide.actions.OpenFileAction.java

License:Apache License

@Override
public void actionPerformed(AnActionEvent e) {
    @Nullable/*from  w  w w  .  j a v a  2s .c  om*/
    final Project project = CommonDataKeys.PROJECT.getData(e.getDataContext());
    final boolean showFiles = project != null;

    final FileChooserDescriptor descriptor = new OpenProjectFileChooserDescriptor(true) {
        @Override
        public boolean isFileSelectable(VirtualFile file) {
            if (super.isFileSelectable(file)) {
                return true;
            }
            if (file.isDirectory()) {
                return false;
            }
            return showFiles && !FileElement.isArchive(file);
        }

        @Override
        public boolean isFileVisible(VirtualFile file, boolean showHiddenFiles) {
            if (!file.isDirectory() && isFileSelectable(file)) {
                if (!showHiddenFiles && FileElement.isFileHidden(file))
                    return false;
                return true;
            }
            return super.isFileVisible(file, showHiddenFiles);
        }

        @Override
        public boolean isChooseMultiple() {
            return showFiles;
        }
    };
    descriptor.setTitle(showFiles ? "Open File or Project" : "Open Project");

    VirtualFile userHomeDir = null;
    if (SystemInfo.isUnix) {
        userHomeDir = VfsUtil.getUserHomeDir();
    }

    descriptor.putUserData(PathChooserDialog.PREFER_LAST_OVER_EXPLICIT, Boolean.TRUE);

    FileChooser.chooseFiles(descriptor, project, userHomeDir, new Consumer<List<VirtualFile>>() {
        @Override
        public void consume(final List<VirtualFile> files) {
            for (VirtualFile file : files) {
                if (!descriptor.isFileSelectable(file)) { // on Mac, it could be selected anyway
                    Messages.showInfoMessage(project,
                            file.getPresentableUrl() + " contains no "
                                    + ApplicationNamesInfo.getInstance().getFullProductName() + " project",
                            "Cannot Open Project");
                    return;
                }
            }
            doOpenFile(project, files);
        }
    });
}

From source file:com.intellij.ide.actions.OpenProjectAction.java

License:Apache License

@Override
public void actionPerformed(AnActionEvent e) {
    final FileChooserDescriptor descriptor = new OpenProjectFileChooserDescriptor(true);
    descriptor.setTitle(IdeBundle.message("title.open.project"));
    final Set<String> extensions = new LinkedHashSet<String>();
    for (ProjectOpenProcessor openProcessor : ProjectOpenProcessor.EXTENSION_POINT_NAME.getExtensions()) {
        if (openProcessor instanceof ProjectOpenProcessorBase) {
            final String[] supportedExtensions = ((ProjectOpenProcessorBase) openProcessor)
                    .getSupportedExtensions();
            if (supportedExtensions != null) {
                Collections.addAll(extensions, supportedExtensions);
            }//from w ww . java 2  s  .  c  om
        }
    }
    if (extensions.isEmpty()) {
        descriptor.setDescription(IdeBundle.message("filter.project.directories"));
    } else {
        descriptor.setDescription(IdeBundle.message("filter.project.files", StringUtil.join(extensions, ", ")));
    }
    VirtualFile userHomeDir = null;
    if (SystemInfo.isUnix) {
        userHomeDir = VfsUtil.getUserHomeDir();
    }

    descriptor.putUserData(PathChooserDialog.PREFER_LAST_OVER_EXPLICIT, Boolean.TRUE);

    final Project project = CommonDataKeys.PROJECT.getData(e.getDataContext());
    FileChooser.chooseFiles(descriptor, project, userHomeDir, new Consumer<List<VirtualFile>>() {
        @Override
        public void consume(final List<VirtualFile> files) {
            if (files.size() == 1) {
                ProjectUtil.openOrImport(files.get(0).getPath(), project, false);
            }
        }
    });
}

From source file:org.dylanfoundry.deft.library.LibraryAttachDialog.java

License:Apache License

public LibraryAttachDialog(@Nullable Project project) {
    super(project, true);

    this.project = project;

    PropertiesComponent storage = PropertiesComponent.getInstance(project);
    boolean registryPathSet = storage.isValueSet(PROPERTY_REGISTRY_PATH);
    if (registryPathSet) {
        String value = storage.getValue(PROPERTY_REGISTRY_PATH);
        myDirectoryField.getTextField().setText(value);
        registryFile = value;/*  w  ww .  j  a  va 2 s.  c om*/
    }

    final FileChooserDescriptor descriptor = FileChooserDescriptorFactory.createSingleLocalFileDescriptor();
    descriptor.putUserData(FileChooserDialog.PREFER_LAST_OVER_TO_SELECT, Boolean.TRUE);
    myDirectoryField.addBrowseFolderListener("Choose registry", "Choose registry file for library", null,
            descriptor);

    myDirectoryField.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            if (!myDirectoryField.getTextField().getText().isEmpty()) {
                registryFile = myDirectoryField.getTextField().getText();

                registryEntries.clear();

                registryEntries.add(DeftRegistryInfo.parseRegistryEntry(registryFile));

                matchedRegistryEntries.setListData(
                        registryEntries.toArray(new DeftRegistryEntryInfo[registryEntries.size()]));
            }

            setOKActionEnabled(!registryEntries.isEmpty());
        }
    });

    setOKActionEnabled(false);
    init();
}

From source file:org.intellij.plugins.intelliLang.InjectionsSettingsUI.java

License:Apache License

private void doImportAction(final DataContext dataContext) {
    final FileChooserDescriptor descriptor = new FileChooserDescriptor(true, false, true, false, true, false) {
        @Override// w  w w .ja va 2 s  .c  o m
        public boolean isFileVisible(VirtualFile file, boolean showHiddenFiles) {
            return super.isFileVisible(file, showHiddenFiles) && (file.isDirectory()
                    || "xml".equals(file.getExtension()) || file.getFileType() instanceof ArchiveFileType);
        }

        @Override
        public boolean isFileSelectable(VirtualFile file) {
            return "xml".equalsIgnoreCase(file.getExtension());
        }
    };
    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>() {
                    @Override
                    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");
    }
}

From source file:org.intellij.plugins.relaxNG.config.NoNamespaceConfigPanel.java

License:Apache License

NoNamespaceConfigPanel(NoNamespaceConfig noNamespaceConfig, PsiFile file) {
    myConfig = noNamespaceConfig;/*from   w  ww . j a  va  2  s. c  o m*/
    myFile = file;
    myMapping = myConfig.getMapping(file);

    final FileChooserDescriptor descriptor = new FileChooserDescriptor(true, false, false, false, false,
            false) {
        @Override
        public boolean isFileSelectable(VirtualFile file) {
            final boolean b = super.isFileSelectable(file);
            if (b) {
                final FileType type = file.getFileType();
                if (type != XmlFileType.INSTANCE) {
                    return type == RncFileType.getInstance();
                }
            }
            return b;
        }
    };

    final Project project = file.getProject();
    final VirtualFile virtualFile = file.getVirtualFile();
    if (virtualFile != null) {
        final Module module = ProjectRootManager.getInstance(project).getFileIndex()
                .getModuleForFile(virtualFile);
        descriptor.putUserData(LangDataKeys.MODULE_CONTEXT, module);
    }

    // that's kind of a hack that ensures the Hector Panel stays open when selecting a file. otherwise it will close
    // as soon as a file selected.
    final ComponentWithBrowseButton.BrowseFolderActionListener<JTextField> actionListener = new ComponentWithBrowseButton.BrowseFolderActionListener<JTextField>(
            "Select Schema", "Select a RELAX-NG file to associate with the document", mySchemaFile, project,
            descriptor, TextComponentAccessor.TEXT_FIELD_WHOLE_TEXT) {
        @Override
        public void actionPerformed(ActionEvent e) {
            myDialogOpen = true;
            try {
                super.actionPerformed(e);
            } finally {
                myDialogOpen = false;
            }
        }
    };

    mySchemaFile.addActionListener(actionListener);
}

From source file:org.intellij.plugins.relaxNG.convert.ConvertSchemaSettingsImpl.java

License:Apache License

public ConvertSchemaSettingsImpl(Project project, @Nonnull SchemaType inputType, VirtualFile firstFile) {
    myProject = project;/*from w  ww  . j  a v a 2  s. co m*/
    myInputType = inputType;

    final FileType type;
    switch (inputType) {
    case RNG:
        myOutputRng.setVisible(false);
        myOutputXsd.setSelected(true);
        type = XmlFileType.INSTANCE;
        break;
    case RNC:
        myOutputRnc.setVisible(false);
        myOutputRng.setSelected(true);
        type = RncFileType.getInstance();
        break;
    case XSD:
        myOutputXsd.setVisible(false);
        myOutputRng.setSelected(true);
        type = XmlFileType.INSTANCE;
        break;
    case DTD:
        myOutputDtd.setVisible(false);
        myOutputRng.setSelected(true);
        type = DTDFileType.INSTANCE;
        break;
    case XML:
        myOutputRng.setSelected(true);
        type = XmlFileType.INSTANCE;
        break;
    default:
        assert false;
        type = null;
    }

    final Charset[] charsets = CharsetToolkit.getAvailableCharsets();
    final List<String> suggestions = new ArrayList<>(charsets.length);
    for (Charset charset : charsets) {
        if (charset.canEncode()) {
            String name = charset.name();
            suggestions.add(name);
        }
    }

    myEncoding.setModel(new DefaultComboBoxModel(suggestions.toArray()));
    final Charset charset = EncodingProjectManager.getInstance(project).getDefaultCharset();
    myEncoding.setSelectedItem(charset.name());

    final CodeStyleSettings styleSettings = CodeStyleSettingsManager.getSettings(project);
    final int indent = styleSettings.getIndentSize(type);
    myIndent.setText(String.valueOf(indent));

    myLineLength.setText(String.valueOf(styleSettings.getDefaultRightMargin()));
    final SchemaType outputType = getOutputType();
    myLineLength.setEnabled(outputType == SchemaType.DTD || outputType == SchemaType.RNC);

    final FileChooserDescriptor descriptor = FileChooserDescriptorFactory.createSingleFileOrFolderDescriptor();
    final Module module = ProjectRootManager.getInstance(project).getFileIndex().getModuleForFile(firstFile);
    descriptor.putUserData(LangDataKeys.MODULE_CONTEXT, module);

    myOutputDestination.addBrowseFolderListener("Schema Conversion Destination",
            "Please select the destination the generated file(s) should be placed at", project, descriptor);

    final JTextField tf = myOutputDestination.getTextField();
    tf.getDocument().addDocumentListener(new DocumentAdapter() {
        @Override
        protected void textChanged(DocumentEvent e) {
            myPropertyChangeSupport.firePropertyChange(OUTPUT_PATH, null, getOutputDestination());
        }
    });
    tf.setText(firstFile.getParent().getPath().replace('/', File.separatorChar));

    final ItemListener listener = new ItemListener() {
        @Override
        public void itemStateChanged(ItemEvent e) {
            if (e.getStateChange() == ItemEvent.SELECTED) {
                final SchemaType type = getOutputType();
                myPropertyChangeSupport.firePropertyChange(OUTPUT_TYPE, null, type);
                myLineLength.setEnabled(type == SchemaType.DTD || type == SchemaType.RNC);
            }
        }
    };
    myOutputRng.addItemListener(listener);
    myOutputRnc.addItemListener(listener);
    myOutputXsd.addItemListener(listener);
    myOutputDtd.addItemListener(listener);

    if (inputType == SchemaType.DTD) {
        myInputOptions = AdvancedDtdOptions.prepareNamespaceMap(project, firstFile);
    }
}

From source file:org.jetbrains.idea.maven.utils.RepositoryAttachDialog.java

License:Apache License

public RepositoryAttachDialog(Project project, boolean managed,
        final @javax.annotation.Nullable String initialFilter) {
    super(project, true);
    myProject = project;/* w w  w.j a  v a 2s. co  m*/
    myManaged = managed;
    myProgressIcon.suspend();
    myCaptionLabel.setText(XmlStringUtil.wrapInHtml(
            StringUtil.escapeXml("enter keyword, pattern or class name to search by or Maven coordinates,"
                    + "i.e. 'springframework', 'Logger' or 'org.hibernate:hibernate-core:3.5.0.GA':")));
    myInfoLabel.setPreferredSize(
            new Dimension(myInfoLabel.getFontMetrics(myInfoLabel.getFont()).stringWidth("Showing: 1000"),
                    myInfoLabel.getPreferredSize().height));

    myComboComponent.setButtonIcon(AllIcons.Actions.Menu_find);
    myComboComponent.getButton().addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            performSearch();
        }
    });
    myCombobox = myComboComponent.getComboBox();
    myCombobox.setModel(new CollectionComboBoxModel(myShownItems, null));
    myCombobox.setEditable(true);
    final JTextField textField = (JTextField) myCombobox.getEditor().getEditorComponent();
    textField.setColumns(20);
    if (initialFilter != null) {
        textField.setText(initialFilter);
    }
    textField.getDocument().addDocumentListener(new DocumentAdapter() {
        @Override
        protected void textChanged(DocumentEvent e) {
            ApplicationManager.getApplication().invokeLater(new Runnable() {
                public void run() {
                    if (myProgressIcon.isDisposed())
                        return;
                    updateComboboxSelection(false);
                }
            });
        }
    });
    myCombobox.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            final boolean popupVisible = myCombobox.isPopupVisible();
            if (!myInUpdate && (!popupVisible || myCoordinates.isEmpty())) {
                performSearch();
            } else {
                final String item = (String) myCombobox.getSelectedItem();
                if (StringUtil.isNotEmpty(item)) {
                    ((JTextField) myCombobox.getEditor().getEditorComponent()).setText(item);
                }
            }
        }
    });
    final PropertiesComponent storage = PropertiesComponent.getInstance(myProject);
    final boolean pathValueSet = storage.isValueSet(PROPERTY_DOWNLOAD_TO_PATH);
    if (pathValueSet) {
        myDirectoryField.setText(storage.getValue(PROPERTY_DOWNLOAD_TO_PATH));
    }
    myJavaDocCheckBox.setSelected(
            storage.isValueSet(PROPERTY_ATTACH_JAVADOC) && storage.isTrueValue(PROPERTY_ATTACH_JAVADOC));
    mySourcesCheckBox.setSelected(
            storage.isValueSet(PROPERTY_ATTACH_SOURCES) && storage.isTrueValue(PROPERTY_ATTACH_SOURCES));
    if (!myManaged) {
        if (!pathValueSet && myProject != null && !myProject.isDefault()) {
            final VirtualFile baseDir = myProject.getBaseDir();
            if (baseDir != null) {
                myDirectoryField.setText(FileUtil.toSystemDependentName(baseDir.getPath() + "/lib"));
            }
        }
        final FileChooserDescriptor descriptor = FileChooserDescriptorFactory.createSingleFolderDescriptor();
        descriptor.putUserData(FileChooserDialog.PREFER_LAST_OVER_TO_SELECT, Boolean.TRUE);
        myDirectoryField.addBrowseFolderListener(
                ProjectBundle.message("file.chooser.directory.for.downloaded.libraries.title"),
                ProjectBundle.message("file.chooser.directory.for.downloaded.libraries.description"), null,
                descriptor);
    } else {
        myDirectoryField.setVisible(false);
    }
    updateInfoLabel();
    init();
}