Skip to content

Commit 8b31dc7

Browse files
committed
config: Rework autosave to be rearmed upon change
1 parent 4170df8 commit 8b31dc7

File tree

3 files changed

+28
-17
lines changed

3 files changed

+28
-17
lines changed

cmd/micro/micro.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -356,9 +356,9 @@ func main() {
356356
log.Println(clipErr, " or change 'clipboard' option")
357357
}
358358

359+
config.StartAutoSave()
359360
if a := config.GetGlobalOption("autosave").(float64); a > 0 {
360361
config.SetAutoTime(a)
361-
config.StartAutoSave()
362362
}
363363

364364
screen.Events = make(chan tcell.Event)

internal/action/command.go

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -553,7 +553,6 @@ func doSetGlobalOptionNative(option string, nativeValue interface{}) error {
553553
} else if option == "autosave" {
554554
if nativeValue.(float64) > 0 {
555555
config.SetAutoTime(nativeValue.(float64))
556-
config.StartAutoSave()
557556
} else {
558557
config.SetAutoTime(0)
559558
}

internal/config/autosave.go

Lines changed: 27 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,49 @@
11
package config
22

33
import (
4-
"sync"
54
"time"
65
)
76

87
var Autosave chan bool
9-
var autotime float64
10-
11-
// lock for autosave
12-
var autolock sync.Mutex
8+
var autotime chan float64
139

1410
func init() {
1511
Autosave = make(chan bool)
12+
autotime = make(chan float64)
1613
}
1714

1815
func SetAutoTime(a float64) {
19-
autolock.Lock()
20-
autotime = a
21-
autolock.Unlock()
16+
autotime <- a
2217
}
2318

2419
func StartAutoSave() {
2520
go func() {
21+
var a float64
22+
var t *time.Timer
23+
var elapsed <-chan time.Time
2624
for {
27-
autolock.Lock()
28-
a := autotime
29-
autolock.Unlock()
30-
if a <= 0 {
31-
break
25+
select {
26+
case a = <-autotime:
27+
if t != nil {
28+
t.Stop()
29+
for len(elapsed) > 0 {
30+
<-elapsed
31+
}
32+
}
33+
if a > 0 {
34+
if t != nil {
35+
t.Reset(time.Duration(a * float64(time.Second)))
36+
} else {
37+
t = time.NewTimer(time.Duration(a * float64(time.Second)))
38+
elapsed = t.C
39+
}
40+
}
41+
case <-elapsed:
42+
if a > 0 {
43+
t.Reset(time.Duration(a * float64(time.Second)))
44+
Autosave <- true
45+
}
3246
}
33-
time.Sleep(time.Duration(a * float64(time.Second)))
34-
Autosave <- true
3547
}
3648
}()
3749
}

0 commit comments

Comments
 (0)