forked from fyne-io/fyne
-
Notifications
You must be signed in to change notification settings - Fork 0
/
settings_desktop.go
75 lines (59 loc) · 1.62 KB
/
settings_desktop.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
//go:build !android && !ios && !mobile && !js && !wasm && !test_web_driver
// +build !android,!ios,!mobile,!js,!wasm,!test_web_driver
package app
import (
"os"
"path/filepath"
"github.com/fsnotify/fsnotify"
"github.com/gorustyt/fyne/v2"
)
func watchFileAddTarget(watcher *fsnotify.Watcher, path string) {
dir := filepath.Dir(path)
ensureDirExists(dir)
err := watcher.Add(dir)
if err != nil {
fyne.LogError("Settings watch error:", err)
}
}
func ensureDirExists(dir string) {
if stat, err := os.Stat(dir); err == nil && stat.IsDir() {
return
}
err := os.MkdirAll(dir, 0700)
if err != nil {
fyne.LogError("Unable to create settings storage:", err)
}
}
func watchFile(path string, callback func()) *fsnotify.Watcher {
watcher, err := fsnotify.NewWatcher()
if err != nil {
fyne.LogError("Failed to watch settings file:", err)
return nil
}
go func() {
for event := range watcher.Events {
if event.Op.Has(fsnotify.Remove) { // if it was deleted then watch again
watcher.Remove(path) // fsnotify returns false positives, see https://github.com/fsnotify/fsnotify/issues/268
watchFileAddTarget(watcher, path)
} else {
callback()
}
}
err = watcher.Close()
if err != nil {
fyne.LogError("Settings un-watch error:", err)
}
}()
watchFileAddTarget(watcher, path)
return watcher
}
func (s *settings) watchSettings() {
s.watcher = watchFile(s.schema.StoragePath(), s.fileChanged)
watchTheme()
}
func (s *settings) stopWatching() {
if s.watcher == nil {
return
}
s.watcher.(*fsnotify.Watcher).Close() // fsnotify returns false positives, see https://github.com/fsnotify/fsnotify/issues/268
}