Skip to content

Commit

Permalink
config: Rework autosave to be rearmed upon change
Browse files Browse the repository at this point in the history
  • Loading branch information
JoeKar committed Aug 18, 2024
1 parent 4170df8 commit 8b31dc7
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 17 deletions.
2 changes: 1 addition & 1 deletion cmd/micro/micro.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
1 change: 0 additions & 1 deletion internal/action/command.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down
42 changes: 27 additions & 15 deletions internal/config/autosave.go
Original file line number Diff line number Diff line change
@@ -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
}
}()
}

0 comments on commit 8b31dc7

Please sign in to comment.