All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.nuiton.jaxx.widgets.file.JaxxFileChooser Maven / Gradle / Ivy

The newest version!
package org.nuiton.jaxx.widgets.file;

/*
 * #%L
 * JAXX :: Widgets File
 * %%
 * Copyright (C) 2008 - 2020 Code Lutin, Ultreia.io
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Lesser Public License for more details.
 *
 * You should have received a copy of the GNU General Lesser Public
 * License along with this program.  If not, see
 * .
 * #L%
 */

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;

import javax.swing.JFileChooser;
import javax.swing.filechooser.FileFilter;
import java.awt.Component;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created on 10/29/14.
 *
 * @author Tony Chemit - [email protected]
 * @since 2.15
 */
public class JaxxFileChooser {

    /**
     * To choose a file (in load mode).
     *
     * Customize it and finish by invoking the method {@link ToLoadFile#choose()} to show file chooser.
     */
    public static ToLoadFile forLoadingFile() {
        return new FileChooserBuilderImpl(ChooseMode.LOAD_FILE);
    }

    /**
     * To choose a directory (in load mode).
     *
     * Customize it and finish by invoking the method {@link ToLoadDirectory#choose()} to show file chooser.
     */
    public static ToLoadDirectory forLoadingDirectory() {
        return new FileChooserBuilderImpl(ChooseMode.LOAD_DIRECTORY);
    }

    /**
     * To choose a file (in save mode).
     *
     * Customize it and finish by invoking the method {@link ToSave#choose()} to show file chooser.
     */
    public static ToSave forSaving() {
        return new FileChooserBuilderImpl(ChooseMode.SAVE);
    }

    public static void setCurrentDirectory(File dir) {
        currentDirectory = dir;
    }

    public static File getCurrentDirectory() {
        return currentDirectory;
    }

    public static boolean isCurrentDirectoryDefault() {
        return currentDirectory.equals(DEFAULT_CURRENT_DIRECTORY_FILE);
    }

    /** Logger. */
    private static final Logger log = LogManager.getLogger(JaxxFileChooser.class);

    public static final File DEFAULT_CURRENT_DIRECTORY_FILE = new File(".");

    protected static File currentDirectory = DEFAULT_CURRENT_DIRECTORY_FILE;

    public interface ToLoadFile {

        ToLoadFile setTitle(String title);

        ToLoadFile setApprovalText(String approvalText);

        ToLoadFile setParent(Component parent);

        ToLoadFile setPatternOrDescriptionFilters(List patternOrDescriptionFilters);

        ToLoadFile setPatternOrDescriptionFilters(String pattern, String description, String... patternOrDescriptionFilters);

        ToLoadFile setFileFilters(FileFilter fileFilter, FileFilter... fileFilters);

        ToLoadFile setFileFilters(List fileFilters);

        ToLoadFile setShowFiles(boolean showFiles);

        ToLoadFile setShowDirectories(boolean showDirectories);

        ToLoadFile setMultiSelectionEnabled(boolean multiSelectionEnabled);

        ToLoadFile setFileHidingEnabled(boolean useFileHiding);

        ToLoadFile setUseAcceptAllFileFilter(boolean useAcceptAllFileFilter);

        ToLoadFile setStartDirectory(File startDirectory);

        ToLoadFile setKeepCurrentDirectory(boolean keepCurrentDirectory);

        File choose();

    }

    public interface ToLoadDirectory {

        ToLoadDirectory setTitle(String title);

        ToLoadDirectory setFileHidingEnabled(boolean useFileHiding);

        ToLoadDirectory setApprovalText(String approvalText);

        ToLoadDirectory setParent(Component parent);

        ToLoadDirectory setStartDirectory(File startDirectory);

        ToLoadDirectory setKeepCurrentDirectory(boolean keepCurrentDirectory);

        File choose();

    }

    public interface ToSave {

        ToSave setTitle(String title);

        ToSave setApprovalText(String approvalText);

        ToSave setParent(Component parent);

        ToSave setPatternOrDescriptionFilters(List patternOrDescriptionFilters);

        ToSave setPatternOrDescriptionFilters(String pattern, String description, String... patternOrDescriptionFilters);

        ToSave setFileFilters(FileFilter fileFilter, FileFilter... fileFilters);

        ToSave setFileFilters(List fileFilters);

        ToSave setFileHidingEnabled(boolean useFileHiding);

        ToSave setUseAcceptAllFileFilter(boolean useAcceptAllFileFilter);

        ToSave setFilename(String filename);

        ToSave setStartDirectory(File startDirectory);

        ToSave setKeepCurrentDirectory(boolean keepCurrentDirectory);

        File choose();

    }

    private enum ChooseMode {
        LOAD_FILE,
        LOAD_DIRECTORY,
        SAVE
    }

    static class FileChooserBuilderImpl implements ToLoadFile, ToLoadDirectory, ToSave {

        private final ChooseMode chooseMode;

        protected String title;

        protected File startDirectory;

        protected String approvalText;

        protected Component parent;

        protected List fileFilters;

        protected boolean showFiles;

        protected boolean showDirectories;

        protected boolean multiSelectionEnabled;

        protected boolean fileHidingEnabled;

        protected boolean useAcceptAllFileFilter;

        protected boolean keepCurrentDirectory = true;

        protected String filename;

        FileChooserBuilderImpl(ChooseMode chooseMode) {
            this.chooseMode = chooseMode;
        }

        @Override
        public FileChooserBuilderImpl setTitle(String title) {
            this.title = title;
            return this;
        }

        @Override
        public FileChooserBuilderImpl setApprovalText(String approvalText) {
            this.approvalText = approvalText;
            return this;
        }

        @Override
        public FileChooserBuilderImpl setStartDirectory(File startDirectory) {
            this.startDirectory = startDirectory;
            return this;
        }

        @Override
        public FileChooserBuilderImpl setParent(Component parent) {
            this.parent = parent;
            return this;
        }

        @Override
        public FileChooserBuilderImpl setPatternOrDescriptionFilters(String pattern, String description, String... patternOrDescriptionFilters) {
            List r = new ArrayList<>();
            r.add(pattern);
            r.add(description);
            r.addAll(Arrays.asList(patternOrDescriptionFilters));
            setPatternOrDescriptionFilters(r);
            return this;
        }

        @Override
        public FileChooserBuilderImpl setPatternOrDescriptionFilters(List patternOrDescriptionFilters) {


            List r = new ArrayList<>();
            if (patternOrDescriptionFilters.size() % 2 != 0) {
                throw new IllegalArgumentException(
                        "Arguments must be (pattern, description) couple");
            }
            for (int i = 0, nbFilters = patternOrDescriptionFilters.size() / 2; i < nbFilters; i++) {
                String pattern = patternOrDescriptionFilters.get(i * 2);
                String description = patternOrDescriptionFilters.get(i * 2 + 1);
                r.add(new PatternChooserFilter(pattern, description));
            }

            return setFileFilters(r);

        }

        @Override
        public FileChooserBuilderImpl setFileFilters(FileFilter fileFilter, FileFilter... fileFilters) {
            List r = new ArrayList<>();
            r.add(fileFilter);
            r.addAll(Arrays.asList(fileFilters));
            return setFileFilters(r);
        }

        @Override
        public FileChooserBuilderImpl setFileFilters(List fileFilters) {
            this.fileFilters = fileFilters;
            return this;
        }

        @Override
        public FileChooserBuilderImpl setShowFiles(boolean showFiles) {
            this.showFiles = showFiles;
            return this;
        }

        @Override
        public FileChooserBuilderImpl setShowDirectories(boolean showDirectories) {
            this.showDirectories = showDirectories;
            return this;
        }

        @Override
        public FileChooserBuilderImpl setMultiSelectionEnabled(boolean multiSelectionEnabled) {
            this.multiSelectionEnabled = multiSelectionEnabled;
            return this;
        }

        @Override
        public FileChooserBuilderImpl setFileHidingEnabled(boolean fileHidingEnabled) {
            this.fileHidingEnabled = fileHidingEnabled;
            return this;
        }

        @Override
        public FileChooserBuilderImpl setUseAcceptAllFileFilter(boolean useAcceptAllFileFilter) {
            this.useAcceptAllFileFilter = useAcceptAllFileFilter;
            return this;
        }

        @Override
        public FileChooserBuilderImpl setFilename(String filename) {
            this.filename = filename;
            return this;
        }

        @Override
        public FileChooserBuilderImpl setKeepCurrentDirectory(boolean keepCurrentDirectory) {
            this.keepCurrentDirectory = keepCurrentDirectory;
            return this;
        }

        @Override
        public File choose() {

            File result = null;
            switch (chooseMode) {
                case LOAD_FILE:
                    result = chooseToLoadFile();
                    break;
                case LOAD_DIRECTORY:
                    result = chooseToLoadDirectory();
                    break;
                case SAVE:
                    result = chooseToSave();
                    break;
            }

            return result;

        }

        protected File chooseToLoadFile() {

            try {

                File directory;

                if (startDirectory == null) {
                    directory = getCurrentDirectory();
                } else {
                    directory = startDirectory;
                }

                JFileChooser chooser = new JFileChooser(directory);

                chooser.setDialogType(JFileChooser.CUSTOM_DIALOG);
                if (CollectionUtils.isNotEmpty(fileFilters)) {
                    for (FileFilter filter : fileFilters) {
                        chooser.addChoosableFileFilter(filter);
                    }
                    chooser.setFileFilter(fileFilters.get(0));
                }

                chooser.setAcceptAllFileFilterUsed(useAcceptAllFileFilter);
                chooser.setMultiSelectionEnabled(multiSelectionEnabled);
                chooser.setFileHidingEnabled(fileHidingEnabled);

                if (showFiles) {
                    if (showDirectories) {
                        chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
                    } else {
                        chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
                    }
                } else if (showDirectories) {
                    chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                }

                chooser.setDialogTitle(title);
                int returnVal = chooser.showDialog(parent, approvalText);
                if (returnVal == JFileChooser.APPROVE_OPTION) {
                    File theFile = chooser.getSelectedFile();
                    if (theFile != null) {
                        if (keepCurrentDirectory) {
                            setCurrentDirectory(theFile);
                        }
                        return theFile.getAbsoluteFile();
                    }
                }

            } catch (Exception eee) {
                if (log.isWarnEnabled()) {
                    log.warn("Could not choose file to load", eee);
                }

            }

            return null;

        }

        protected File chooseToLoadDirectory() {

            try {

                File directory;

                if (startDirectory == null) {
                    directory = getCurrentDirectory();
                } else {
                    directory = startDirectory;
                }

                JFileChooser chooser = new JFileChooser(directory);

                chooser.setDialogType(JFileChooser.CUSTOM_DIALOG);
                chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                chooser.setFileHidingEnabled(fileHidingEnabled);
                chooser.setDialogTitle(title);
                int returnVal = chooser.showDialog(parent, approvalText);
                if (returnVal == JFileChooser.APPROVE_OPTION) {
                    File theFile = chooser.getSelectedFile();
                    if (theFile != null) {
                        if (keepCurrentDirectory) {
                            setCurrentDirectory(theFile);
                        }
                        if (theFile.isDirectory()) {
                            return theFile;
                        }
                    }
                } else {
                    return null;
                }
            } catch (Exception eee) {
                log.warn("Could not choose directory to load", eee);
            }
            return null;

        }

        protected File chooseToSave() {

            File directory;

            if (startDirectory == null) {
                directory = getCurrentDirectory();
            } else {
                directory = startDirectory;
            }

            File selectedFile = new File(directory, filename);
            JFileChooser chooser = new JFileChooser(selectedFile);

            chooser.setDialogType(JFileChooser.SAVE_DIALOG);
            chooser.setSelectedFile(selectedFile);
            chooser.setFileHidingEnabled(fileHidingEnabled);
            if (CollectionUtils.isNotEmpty(fileFilters)) {
                for (FileFilter filter : fileFilters) {
                    chooser.addChoosableFileFilter(filter);
                }
                chooser.setFileFilter(fileFilters.get(0));
            }
            chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
            chooser.setDialogTitle(title);

            File result = null;

            int returnVal = chooser.showDialog(parent, approvalText);
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                result = chooser.getSelectedFile();
                if (result != null) {
                    if (keepCurrentDirectory) {
                        setCurrentDirectory(result);
                    }
                    result = result.getAbsoluteFile();
                }
            }
            return result;

        }

        public static class PatternChooserFilter extends FileFilter {
            protected final String pattern;

            protected final String description;

            public PatternChooserFilter(String pattern, String description) {
                this.pattern = StringUtils.lowerCase(pattern);
                this.description = description;
            }

            @Override
            public boolean accept(File f) {
                return f.isDirectory() || f.getAbsolutePath().toLowerCase().matches(pattern);
            }

            @Override
            public String getDescription() {
                return description;
            }

        }

    }

    protected JaxxFileChooser() {
        // no instance please
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy