-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathfile_chooser.go
468 lines (401 loc) · 11.2 KB
/
file_chooser.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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
package explorer
import (
"errors"
"image/color"
"io"
"io/fs"
"os"
"path/filepath"
"slices"
"strings"
"time"
"gioui.org/layout"
"gioui.org/op"
"gioui.org/text"
"gioui.org/unit"
"gioui.org/widget"
"gioui.org/widget/material"
"github.com/oligo/gioview/misc"
"github.com/oligo/gioview/theme"
"github.com/oligo/gioview/view"
gvwidget "github.com/oligo/gioview/widget"
)
type opKind uint8
const (
openFileOp opKind = iota
openFilesOp
openFolderOp
saveFileOp
)
var (
fileChooserID = view.NewViewID("FileChooser")
)
type result struct {
paths []string
err error
}
type FileChooser struct {
vm view.ViewManager
resultChan chan result
}
type FileChooserDialog struct {
*view.BaseView
fileExplorer *FileExplorer
resultChan chan result
op opKind
}
type bottomPanel struct {
op opKind
saveFileInput gvwidget.TextField
addFolderInput gvwidget.TextField
addFolderBtn widget.Clickable
cancelAddFolderBtn widget.Clickable
confirmBtn widget.Clickable
cancelBtn widget.Clickable
isAddingFoder bool
confirmCb func() error
cancelCb func()
addFolderCb func(folderName string) error
err error
errShowAt time.Time
}
func NewFileChooser(vm view.ViewManager) (*FileChooser, error) {
err := vm.Register(fileChooserID, newFileChooserDialog)
if err != nil {
return nil, err
}
return &FileChooser{
vm: vm,
resultChan: make(chan result),
}, nil
}
// CreateFile opens the file chooser, and writes the given content into
// some file, which the use can choose the location. It's important to
// close the `io.WriteCloser`.
//
// It's a blocking call, you should call it on a separated goroutine.
func (fc *FileChooser) CreateFile(name string) (io.WriteCloser, error) {
fc.show(saveFileOp, name)
resp := <-fc.resultChan
return os.Create(resp.paths[0])
}
// ChooseFile shows the file chooser, allowing the user to select a single file. It returns the
// file as a reader to user.
//
// This is a blocking call, you should call it in a seperated goroutine.
//
// Optionally, it's possible to set which file extensions is supported to
// be selected (such as `.jpg`, `.png`).
func (fc *FileChooser) ChooseFile(extensions ...string) (io.ReadCloser, error) {
fc.show(openFileOp, "", extensions...)
resp := <-fc.resultChan
return os.Open(resp.paths[0])
}
// ChooseFile shows the file chooser, allowing the user to select multiple files. It returns the files as
// a list of reader to user.
// This is a blocking call, you should call it in a seperated goroutine.
//
// Optionally, it's possible to set which file extensions is supported to
// be selected (such as `.jpg`, `.png`).
func (fc *FileChooser) ChooseFiles(extensions ...string) ([]io.ReadCloser, error) {
fc.show(openFilesOp, "", extensions...)
resp := <-fc.resultChan
readers := make([]io.ReadCloser, len(resp.paths))
for idx, path := range resp.paths {
d, err := os.Open(path)
if err != nil {
return nil, err
}
readers[idx] = d
}
return readers, nil
}
// ChooseFolder shows the file chooser, allowing the user to select a single folder. It returns the folder
// path to user. This is a blocking call, you should call it in a seperated goroutine.
func (fc *FileChooser) ChooseFolder() (string, error) {
fc.show(openFolderOp, "")
resp := <-fc.resultChan
return resp.paths[0], nil
}
func (fc *FileChooser) show(op opKind, filename string, extensions ...string) {
params := map[string]interface{}{"resultChan": fc.resultChan, "op": op}
if op == saveFileOp {
params["filename"] = filename
}
params["filter"] = chooserFilter(op, extensions...)
fc.vm.RequestSwitch(view.Intent{
Target: fileChooserID,
ShowAsModal: true,
Params: params,
})
}
func chooserFilter(op opKind, extensions ...string) EntryFilter {
return func(info fs.FileInfo) bool {
if op == openFolderOp {
return info.IsDir()
}
// In other cases, folder should be kept.
if info.IsDir() || len(extensions) <= 0 {
return true
}
ext := filepath.Ext(info.Name())
return slices.ContainsFunc(extensions, func(extension string) bool { return strings.EqualFold(extension, ext) })
}
}
func (d *FileChooserDialog) ID() view.ViewID {
return fileChooserID
}
func (vw *FileChooserDialog) Title() string {
switch vw.op {
case openFileOp:
return "Open File"
case openFilesOp:
return "Open Files"
case openFolderOp:
return "Open Folder"
case saveFileOp:
return "Save File"
}
return "File Chooser"
}
func (vw *FileChooserDialog) OnNavTo(intent view.Intent) error {
vw.BaseView.OnNavTo(intent)
rc, ok := intent.Params["resultChan"]
if !ok {
return errors.New("missing mandatory params")
}
opVal, ok := intent.Params["op"]
if !ok {
return errors.New("missing mandatory params")
}
op := opVal.(opKind)
vw.resultChan = rc.(chan result)
vw.fileExplorer.bottomPanel.op = op
vw.op = op
if op == saveFileOp {
param := intent.Params["filename"]
vw.fileExplorer.bottomPanel.saveFileInput.SetText(param.(string))
}
vw.fileExplorer.bottomPanel.addFolderInput.SetText("untitled folder")
vw.fileExplorer.bottomPanel.cancelCb = func() { vw.OnFinish() }
vw.fileExplorer.bottomPanel.confirmCb = func() error {
currentPath := vw.fileExplorer.viewer.entryTree.Path
switch op {
case saveFileOp:
filename := strings.TrimSpace(vw.fileExplorer.bottomPanel.saveFileInput.Text())
if filename == "" {
return errors.New("Empty filename")
}
vw.resultChan <- result{paths: []string{filepath.Join(currentPath, filename)}}
case openFileOp, openFilesOp, openFolderOp:
paths := make([]string, 0)
if len(vw.fileExplorer.viewer.selectedItems) <= 0 {
if op == openFileOp || op == openFilesOp {
return errors.New("No file/folder selected")
}
if op == openFolderOp {
// use the current dir.
paths = append(paths, vw.fileExplorer.viewer.entryTree.Path)
}
}
for item := range vw.fileExplorer.viewer.selectedItems {
if (op == openFileOp || op == openFolderOp) && len(paths) == 1 {
break
}
paths = append(paths, item.node.Path)
}
vw.resultChan <- result{paths: paths}
}
vw.OnFinish()
return nil
}
vw.fileExplorer.bottomPanel.addFolderCb = func(folderName string) error {
err := vw.fileExplorer.viewer.entryTree.AddChild(folderName, FolderNode)
if err == nil {
vw.fileExplorer.viewer.refresh()
}
return err
}
if f, ok := intent.Params["filter"]; ok {
vw.fileExplorer.entryFilter = f.(EntryFilter)
}
return nil
}
func (vw *FileChooserDialog) Layout(gtx layout.Context, th *theme.Theme) layout.Dimensions {
return vw.fileExplorer.Layout(gtx, th)
}
func newFileChooserDialog() view.View {
return &FileChooserDialog{
BaseView: &view.BaseView{},
fileExplorer: newFileExplorer(),
}
}
func (p *bottomPanel) Layout(gtx C, th *theme.Theme) D {
if p.addFolderBtn.Clicked(gtx) {
if p.isAddingFoder {
p.err = p.addFolderCb(p.addFolderInput.Text())
if p.err == nil {
p.isAddingFoder = false
}
} else {
p.isAddingFoder = true
}
}
if p.cancelAddFolderBtn.Clicked(gtx) {
p.addFolderInput.Clear()
p.err = nil
p.isAddingFoder = false
}
if p.isAddingFoder && p.err != nil && p.addFolderInput.Changed() {
p.err = nil
}
if p.cancelBtn.Clicked(gtx) {
p.cancelCb()
}
if p.confirmBtn.Clicked(gtx) {
p.err = p.confirmCb()
}
return layout.Flex{
Axis: layout.Vertical,
}.Layout(gtx,
layout.Rigid(func(gtx C) D {
switch p.op {
case saveFileOp:
return p.layoutSaveFileForm(gtx, th)
}
return D{}
}),
layout.Rigid(func(gtx C) D {
if p.op != saveFileOp {
return D{}
}
return layout.Spacer{Height: unit.Dp(16)}.Layout(gtx)
}),
layout.Rigid(func(gtx C) D {
return layout.Flex{
Axis: layout.Horizontal,
Alignment: layout.Middle,
Spacing: layout.SpaceBetween,
}.Layout(gtx,
layout.Flexed(1, func(gtx C) D {
return p.layoutAddFolderForm(gtx, th)
}),
layout.Rigid(layout.Spacer{Width: unit.Dp(32)}.Layout),
layout.Rigid(func(gtx C) D {
if p.err == nil {
return D{}
}
return p.layoutError(gtx, th)
}),
layout.Rigid(func(gtx C) D {
return layout.Flex{
Axis: layout.Horizontal,
Alignment: layout.Middle,
Spacing: layout.SpaceStart,
}.Layout(gtx,
layout.Rigid(func(gtx C) D {
btn := material.Button(th.Theme, &p.cancelBtn, "Cancel")
btn.Inset = layout.UniformInset(unit.Dp(6))
btn.Background = th.Bg
btn.Color = th.Fg
return btn.Layout(gtx)
}),
layout.Rigid(layout.Spacer{Width: unit.Dp(16)}.Layout),
layout.Rigid(func(gtx C) D {
label := "Open"
if p.op == saveFileOp {
label = "Save"
}
btn := material.Button(th.Theme, &p.confirmBtn, label)
btn.Inset = layout.UniformInset(unit.Dp(6))
return btn.Layout(gtx)
}),
)
}),
)
}),
)
}
func (p *bottomPanel) layoutSaveFileForm(gtx C, th *theme.Theme) D {
return layout.Flex{
Axis: layout.Horizontal,
Alignment: layout.Middle,
}.Layout(gtx,
layout.Rigid(func(gtx C) D {
lb := material.Label(th.Theme, th.TextSize, "Save as:")
lb.Color = misc.WithAlpha(th.Fg, 0xb6)
return lb.Layout(gtx)
}),
layout.Rigid(layout.Spacer{Width: unit.Dp(8)}.Layout),
layout.Rigid(func(gtx C) D {
p.saveFileInput.SingleLine = true
p.saveFileInput.LabelOption = gvwidget.LabelOption{Alignment: gvwidget.Hidden}
p.saveFileInput.Padding = unit.Dp(6)
return p.saveFileInput.Layout(gtx, th, "")
}),
)
}
func (p *bottomPanel) layoutAddFolderForm(gtx C, th *theme.Theme) D {
btn := "New Folder"
if p.isAddingFoder {
btn = "Save"
}
return layout.Flex{
Axis: layout.Horizontal,
Alignment: layout.Middle,
}.Layout(gtx,
layout.Rigid(func(gtx C) D {
if !p.isAddingFoder {
return D{}
}
gtx.Constraints.Max.X = gtx.Dp(unit.Dp(250))
p.addFolderInput.SingleLine = true
p.addFolderInput.LabelOption = gvwidget.LabelOption{Alignment: gvwidget.Hidden}
p.addFolderInput.Padding = unit.Dp(6)
return p.addFolderInput.Layout(gtx, th, "")
}),
layout.Rigid(func(gtx C) D {
if !p.isAddingFoder {
return D{}
}
return layout.Spacer{Width: unit.Dp(8)}.Layout(gtx)
}),
layout.Rigid(func(gtx C) D {
btn := material.Button(th.Theme, &p.addFolderBtn, btn)
btn.Inset = layout.UniformInset(unit.Dp(6))
return btn.Layout(gtx)
}),
layout.Rigid(layout.Spacer{Width: unit.Dp(16)}.Layout),
layout.Rigid(func(gtx C) D {
if !p.isAddingFoder {
return D{}
}
btn := material.Button(th.Theme, &p.cancelAddFolderBtn, "Cancel")
btn.Inset = layout.UniformInset(unit.Dp(6))
btn.Background = th.Bg
btn.Color = th.Fg
return btn.Layout(gtx)
}),
)
}
const errorShowDuration = time.Second * 2
func (p *bottomPanel) layoutError(gtx C, th *theme.Theme) D {
if p.err == nil {
return D{}
}
if p.errShowAt.IsZero() {
p.errShowAt = gtx.Now
gtx.Execute(op.InvalidateCmd{At: p.errShowAt.Add(errorShowDuration)})
} else if p.errShowAt.Add(errorShowDuration).Before(gtx.Now) {
defer func() {
p.errShowAt = time.Time{}
p.err = nil
}()
}
return layout.Inset{Right: unit.Dp(36)}.Layout(gtx, func(gtx C) D {
label := material.Label(th.Theme, th.TextSize, p.err.Error())
label.Color = color.NRGBA{R: 255, A: 255}
label.Alignment = text.Middle
return label.Layout(gtx)
})
}