Refactor main

This commit is contained in:
Kristóf Tóth 2020-08-18 12:30:55 +02:00
parent 8222f24fa7
commit 97884bfb64
1 changed files with 41 additions and 22 deletions

63
main.go
View File

@ -16,35 +16,54 @@ const (
func main() { func main() {
var wg sync.WaitGroup al := newAfterLock()
wg.Add(1) al.start()
stopFlag := atomicflag.New(false) }
keypressFlag := atomicflag.New(false)
go func() { type afterLock struct {
for { wg sync.WaitGroup
err := evdev.BlockUntilKeypress(keyboardDeviceNode) stopFlag *atomicflag.AtomicFlag
if err != nil { keypressFlag *atomicflag.AtomicFlag
panic(err) }
}
if stopFlag.Get() {
wg.Done()
return
} else {
keypressFlag.Set(true)
}
}
}()
func newAfterLock() *afterLock {
return &afterLock{
stopFlag: atomicflag.New(false),
keypressFlag: atomicflag.New(false),
}
}
func (af *afterLock) start() {
af.wg.Add(1)
go af.detectKeypresses()
time.Sleep(initialDelay * time.Second) time.Sleep(initialDelay * time.Second)
af.hybernateDisplayLoop()
}
func (af *afterLock) detectKeypresses() {
for {
err := evdev.BlockUntilKeypress(keyboardDeviceNode)
if err != nil {
panic(err)
}
if af.stopFlag.Get() {
af.wg.Done()
return
}
af.keypressFlag.Set(true)
}
}
func (af *afterLock) hybernateDisplayLoop() {
for { for {
active, err := screensaver.IsActive() active, err := screensaver.IsActive()
if err != nil { if err != nil {
panic(err) panic(err)
} }
if !active { if !active {
stopFlag.Set(true) af.stopFlag.Set(true)
wg.Wait() af.wg.Wait()
return return
} }
@ -59,8 +78,8 @@ func main() {
} }
for { for {
time.Sleep(loopDelay * time.Second) time.Sleep(loopDelay * time.Second)
if keypressFlag.Get() { if af.keypressFlag.Get() {
keypressFlag.Set(false) af.keypressFlag.Set(false)
continue continue
} else { } else {
break break