-
Notifications
You must be signed in to change notification settings - Fork 50
/
fileselectdlg.go
419 lines (357 loc) · 9.88 KB
/
fileselectdlg.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
package clui
import (
"fmt"
"os"
"path/filepath"
"sort"
"strings"
term "github.com/nsf/termbox-go"
)
// FileSelectDialog is a dialog to select a file or directory.
// Public properties:
// * Selected - whether a user has selected an object, or the user canceled
// or closed the dialog. In latter case all other properties are not
// used and contain default values
// * FilePath - full path to the selected file or directory
// * Exists - if the selected object exists or a user entered manually a
// name of the object
type FileSelectDialog struct {
View *Window
FilePath string
Exists bool
Selected bool
fileMasks []string
currPath string
mustExist bool
selectDir bool
result int
onClose func()
listBox *ListBox
edFile *EditField
curDir *Label
}
// Set the cursor the first item in the file list
func (d *FileSelectDialog) selectFirst() {
d.listBox.SelectItem(0)
}
// Checks if the file name matches the mask. Empty mask, *, and *.* match any file
func (d *FileSelectDialog) fileFitsMask(finfo os.FileInfo) bool {
if finfo.IsDir() {
return true
}
if d.selectDir {
return false
}
if len(d.fileMasks) == 0 {
return true
}
for _, msk := range d.fileMasks {
if msk == "*" || msk == "*.*" {
return true
}
matched, err := filepath.Match(msk, finfo.Name())
if err == nil && matched {
return true
}
}
return false
}
// Fills the ListBox with the file names from current directory.
// Files which names do not match mask are filtered out.
// If select directory is set, then the ListBox contains only directories.
// Directory names ends with path separator
func (d *FileSelectDialog) populateFiles() error {
d.listBox.Clear()
isRoot := filepath.Dir(d.currPath) == d.currPath
if !isRoot {
d.listBox.AddItem("..")
}
f, err := os.Open(d.currPath)
if err != nil {
return err
}
finfos, err := f.Readdir(0)
f.Close()
if err != nil {
return err
}
fnLess := func(i, j int) bool {
if finfos[i].IsDir() && !finfos[j].IsDir() {
return true
} else if !finfos[i].IsDir() && finfos[j].IsDir() {
return false
}
return strings.ToLower(finfos[i].Name()) < strings.ToLower(finfos[j].Name())
}
sort.Slice(finfos, fnLess)
for _, finfo := range finfos {
if !d.fileFitsMask(finfo) {
continue
}
if finfo.IsDir() {
d.listBox.AddItem(finfo.Name() + string(os.PathSeparator))
} else {
d.listBox.AddItem(finfo.Name())
}
}
return nil
}
// Tries to find the best fit for the given path.
// It goes up until it gets into the existing directory.
// If all fails it returns working directory.
func (d *FileSelectDialog) detectPath() {
p := d.currPath
if p == "" {
d.currPath, _ = os.Getwd()
return
}
p = filepath.Clean(p)
for {
_, err := os.Stat(p)
if err == nil {
break
}
dirUp := filepath.Dir(p)
if dirUp == p {
p, _ = os.Getwd()
break
}
p = dirUp
}
d.currPath = p
}
// Goes up in the directory tree if it is possible
func (d *FileSelectDialog) pathUp() {
dirUp := filepath.Dir(d.currPath)
if dirUp == d.currPath {
return
}
d.currPath = dirUp
d.populateFiles()
d.selectFirst()
}
// Enters the directory
func (d *FileSelectDialog) pathDown(dir string) {
d.currPath = filepath.Join(d.currPath, dir)
d.populateFiles()
d.selectFirst()
}
// Sets the EditField value with the selected item in ListBox if:
// * a directory is selected and option 'select directory' is set
// * a file is selected and option 'select directory' is not set
func (d *FileSelectDialog) updateEditBox() {
s := d.listBox.SelectedItemText()
if s == "" || s == ".." ||
(strings.HasSuffix(s, string(os.PathSeparator)) && !d.selectDir) {
d.edFile.Clear()
return
}
d.edFile.SetTitle(strings.TrimSuffix(s, string(os.PathSeparator)))
}
// CreateFileSelectDialog creates a new file select dialog. It is useful if
// the application needs a way to select a file or directory for reading and
// writing data.
// * title - custom dialog title (the final dialog title includes this one
// and the file mask
// * fileMasks - a list of file masks separated with comma or path separator.
// If selectDir is true this option is not used. Setting fileMasks to
// '*', '*.*', or empty string means all files
// * selectDir - what kind of object to select: file (false) or directory
// (true). If selectDir is true then the dialog does not show files
// * mustExists - if it is true then the dialog allows a user to select
// only existing object ('open file' case). If it is false then the dialog
// makes possible to enter a name manually and click 'Select' (useful
// for file 'file save' case)
func CreateFileSelectDialog(title, fileMasks, initPath string, selectDir, mustExist bool) *FileSelectDialog {
dlg := new(FileSelectDialog)
cw, ch := term.Size()
dlg.selectDir = selectDir
dlg.mustExist = mustExist
if fileMasks != "" {
maskList := strings.FieldsFunc(fileMasks,
func(c rune) bool { return c == ',' || c == ':' })
dlg.fileMasks = make([]string, 0, len(maskList))
for _, m := range maskList {
if m != "" {
dlg.fileMasks = append(dlg.fileMasks, m)
}
}
}
dlg.View = AddWindow(10, 4, 20, 16, fmt.Sprintf("%s (%s)", title, fileMasks))
WindowManager().BeginUpdate()
defer WindowManager().EndUpdate()
dlg.View.SetModal(true)
dlg.View.SetPack(Vertical)
dlg.currPath = initPath
dlg.detectPath()
dlg.curDir = CreateLabel(dlg.View, AutoSize, AutoSize, "", Fixed)
dlg.curDir.SetTextDisplay(AlignRight)
flist := CreateFrame(dlg.View, 1, 1, BorderNone, 1)
flist.SetPaddings(1, 1)
flist.SetPack(Horizontal)
dlg.listBox = CreateListBox(flist, 16, ch-20, 1)
fselected := CreateFrame(dlg.View, 1, 1, BorderNone, Fixed)
// text + edit field to enter name manually
fselected.SetPack(Vertical)
fselected.SetPaddings(1, 0)
CreateLabel(fselected, AutoSize, AutoSize, "Selected object:", 1)
dlg.edFile = CreateEditField(fselected, cw-22, "", 1)
// buttons at the right
blist := CreateFrame(flist, 1, 1, BorderNone, Fixed)
blist.SetPack(Vertical)
blist.SetPaddings(1, 1)
btnOpen := CreateButton(blist, AutoSize, AutoSize, "Open", Fixed)
btnSelect := CreateButton(blist, AutoSize, AutoSize, "Select", Fixed)
btnCancel := CreateButton(blist, AutoSize, AutoSize, "Cancel", Fixed)
btnCancel.OnClick(func(ev Event) {
WindowManager().DestroyWindow(dlg.View)
WindowManager().BeginUpdate()
dlg.Selected = false
closeFunc := dlg.onClose
WindowManager().EndUpdate()
if closeFunc != nil {
closeFunc()
}
})
btnSelect.OnClick(func(ev Event) {
WindowManager().DestroyWindow(dlg.View)
WindowManager().BeginUpdate()
dlg.Selected = true
dlg.FilePath = filepath.Join(dlg.currPath, dlg.listBox.SelectedItemText())
if dlg.edFile.Title() != "" {
dlg.FilePath = filepath.Join(dlg.currPath, dlg.edFile.Title())
}
_, err := os.Stat(dlg.FilePath)
dlg.Exists = !os.IsNotExist(err)
closeFunc := dlg.onClose
WindowManager().EndUpdate()
if closeFunc != nil {
closeFunc()
}
})
dlg.View.OnClose(func(ev Event) bool {
if dlg.result == DialogAlive {
dlg.result = DialogClosed
if ev.X != 1 {
WindowManager().DestroyWindow(dlg.View)
}
if dlg.onClose != nil {
dlg.onClose()
}
}
return true
})
dlg.listBox.OnSelectItem(func(ev Event) {
item := ev.Msg
if item == ".." {
btnSelect.SetEnabled(false)
btnOpen.SetEnabled(true)
return
}
isDir := strings.HasSuffix(item, string(os.PathSeparator))
if isDir {
btnOpen.SetEnabled(true)
if !dlg.selectDir {
btnSelect.SetEnabled(false)
return
}
}
if !isDir {
btnOpen.SetEnabled(false)
}
btnSelect.SetEnabled(true)
if (isDir && dlg.selectDir) || !isDir {
dlg.edFile.SetTitle(item)
} else {
dlg.edFile.Clear()
}
})
btnOpen.OnClick(func(ev Event) {
s := dlg.listBox.SelectedItemText()
if s != ".." && (s == "" || !strings.HasSuffix(s, string(os.PathSeparator))) {
return
}
if s == ".." {
dlg.pathUp()
} else {
dlg.pathDown(s)
}
})
dlg.edFile.OnChange(func(ev Event) {
s := ""
lowCurrText := strings.ToLower(dlg.listBox.SelectedItemText())
lowEditText := strings.ToLower(dlg.edFile.Title())
if !strings.HasPrefix(lowCurrText, lowEditText) {
itemIdx := dlg.listBox.PartialFindItem(dlg.edFile.Title(), false)
if itemIdx == -1 {
if dlg.mustExist {
btnSelect.SetEnabled(false)
}
return
}
s, _ = dlg.listBox.Item(itemIdx)
dlg.listBox.SelectItem(itemIdx)
} else {
s = dlg.listBox.SelectedItemText()
}
isDir := strings.HasSuffix(s, string(os.PathSeparator))
equal := strings.EqualFold(s, dlg.edFile.Title()) ||
strings.EqualFold(s, dlg.edFile.Title()+string(os.PathSeparator))
btnOpen.SetEnabled(isDir || s == "..")
if isDir {
btnSelect.SetEnabled(dlg.selectDir && (equal || !dlg.mustExist))
return
}
btnSelect.SetEnabled(equal || !dlg.mustExist)
})
dlg.edFile.OnKeyPress(func(key term.Key, c rune) bool {
if key == term.KeyArrowUp {
idx := dlg.listBox.SelectedItem()
if idx > 0 {
dlg.listBox.SelectItem(idx - 1)
dlg.updateEditBox()
}
return true
}
if key == term.KeyArrowDown {
idx := dlg.listBox.SelectedItem()
if idx < dlg.listBox.ItemCount()-1 {
dlg.listBox.SelectItem(idx + 1)
dlg.updateEditBox()
}
return true
}
return false
})
dlg.listBox.OnKeyPress(func(key term.Key) bool {
if key == term.KeyBackspace || key == term.KeyBackspace2 {
dlg.pathUp()
return true
}
if key == term.KeyCtrlM {
s := dlg.listBox.SelectedItemText()
if s == ".." {
dlg.pathUp()
return true
}
if strings.HasSuffix(s, string(os.PathSeparator)) {
dlg.pathDown(s)
return true
}
return false
}
return false
})
dlg.curDir.SetTitle(dlg.currPath)
dlg.populateFiles()
dlg.selectFirst()
ActivateControl(dlg.View, dlg.listBox)
return dlg
}
// OnClose sets the callback that is called when the
// dialog is closed
func (d *FileSelectDialog) OnClose(fn func()) {
WindowManager().BeginUpdate()
defer WindowManager().EndUpdate()
d.onClose = fn
}