config: Rework autosave to be rearmed upon change

This commit is contained in:
Jöran Karl 2024-06-24 19:12:47 +02:00
parent 4170df89eb
commit 8b31dc79bf
3 changed files with 28 additions and 17 deletions

View File

@ -356,9 +356,9 @@ func main() {
log.Println(clipErr, " or change 'clipboard' option")
}
config.StartAutoSave()
if a := config.GetGlobalOption("autosave").(float64); a > 0 {
config.SetAutoTime(a)
config.StartAutoSave()
}
screen.Events = make(chan tcell.Event)

View File

@ -553,7 +553,6 @@ func doSetGlobalOptionNative(option string, nativeValue interface{}) error {
} else if option == "autosave" {
if nativeValue.(float64) > 0 {
config.SetAutoTime(nativeValue.(float64))
config.StartAutoSave()
} else {
config.SetAutoTime(0)
}

View File

@ -1,37 +1,49 @@
package config
import (
"sync"
"time"
)
var Autosave chan bool
var autotime float64
// lock for autosave
var autolock sync.Mutex
var autotime chan float64
func init() {
Autosave = make(chan bool)
autotime = make(chan float64)
}
func SetAutoTime(a float64) {
autolock.Lock()
autotime = a
autolock.Unlock()
autotime <- a
}
func StartAutoSave() {
go func() {
var a float64
var t *time.Timer
var elapsed <-chan time.Time
for {
autolock.Lock()
a := autotime
autolock.Unlock()
if a <= 0 {
break
select {
case a = <-autotime:
if t != nil {
t.Stop()
for len(elapsed) > 0 {
<-elapsed
}
}
if a > 0 {
if t != nil {
t.Reset(time.Duration(a * float64(time.Second)))
} else {
t = time.NewTimer(time.Duration(a * float64(time.Second)))
elapsed = t.C
}
}
case <-elapsed:
if a > 0 {
t.Reset(time.Duration(a * float64(time.Second)))
Autosave <- true
}
}
time.Sleep(time.Duration(a * float64(time.Second)))
Autosave <- true
}
}()
}