1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 package org.nuiton.jrst.ui;
23
24 import com.google.common.io.Files;
25
26 import javax.swing.*;
27 import javax.swing.filechooser.FileFilter;
28 import java.io.File;
29
30
31
32
33 public class FileEditorHandler {
34
35 public static final String SEPARATOR_REGEX = "\\s*,\\s*";
36 protected FileEditor view;
37
38 public FileEditorHandler(FileEditor view) {
39 this.view = view;
40 }
41
42 public void openLocation() {
43
44
45 File startFile = view.getSelectedFile();
46 String startPath = view.getStartPath();
47 if (startFile == null && startPath != null) {
48
49
50
51 startFile = new File(startPath);
52 } else {
53
54
55 startFile = new File(System.getProperty("user.home"));
56 }
57 JFileChooser fc = new JFileChooser(startFile);
58
59 fc.setDialogTitle(view.getTitle());
60 fc.setAcceptAllFileFilterUsed(view.getAcceptAllFileFilterUsed());
61
62
63
64
65
66
67 boolean directoryEnabled = view.isDirectoryEnabled();
68 if (directoryEnabled) {
69 fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
70 }
71
72
73 boolean fileEnabled = view.isFileEnabled();
74 if (fileEnabled) {
75
76 if (directoryEnabled) {
77
78
79 fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
80 } else {
81 fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
82 }
83 String extsAsString = view.getExts();
84 if (extsAsString != null) {
85
86
87 String[] exts = extsAsString.split(SEPARATOR_REGEX);
88 String extsDescription = view.getExtsDescription();
89
90 String[] descs = new String[0];
91 if (extsDescription != null) {
92 descs = extsDescription.split(SEPARATOR_REGEX);
93 }
94 for (int i = 0;i<exts.length;i++) {
95
96
97 String ext = exts[i];
98 String desc = ext;
99 if (descs.length > i) {
100 desc = descs[i];
101 }
102
103 fc.addChoosableFileFilter(new ExtentionFileFiler(ext, desc));
104 }
105 }
106 }
107
108
109 if (!directoryEnabled && !fileEnabled) {
110 throw new IllegalArgumentException("You must enable at least file or directory to open dialog");
111 }
112
113
114 int returnVal = fc.showOpenDialog(view);
115 if (returnVal == JFileChooser.APPROVE_OPTION) {
116
117
118 File file = fc.getSelectedFile();
119
120 view.setSelectedFile(file);
121 }
122 }
123
124 public static class ExtentionFileFiler extends FileFilter {
125 protected String ext;
126 protected String desciption;
127
128 public ExtentionFileFiler(String ext, String desciption) {
129 this.ext = ext;
130 this.desciption = desciption;
131 }
132
133 @Override
134 public boolean accept(File file) {
135 if (file.isDirectory()) {
136 return true;
137 }
138 String fileExtension = Files.getFileExtension(file.getName());
139 return ext.equals(fileExtension);
140 }
141
142 @Override
143 public String getDescription() {
144 return desciption;
145 }
146 }
147 }