forked from fyne-io/fyne
-
Notifications
You must be signed in to change notification settings - Fork 0
/
entry_cursor_anim.go
106 lines (95 loc) · 2.27 KB
/
entry_cursor_anim.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package widget
import (
"image/color"
"sync"
"time"
"fyne.io/fyne/v2"
"fyne.io/fyne/v2/canvas"
"fyne.io/fyne/v2/theme"
)
const cursorInterruptTime = 300 * time.Millisecond
type entryCursorAnimation struct {
mu *sync.RWMutex
cursor *canvas.Rectangle
anim *fyne.Animation
lastInterruptTime time.Time
timeNow func() time.Time // useful for testing
}
func newEntryCursorAnimation(cursor *canvas.Rectangle) *entryCursorAnimation {
a := &entryCursorAnimation{mu: &sync.RWMutex{}, cursor: cursor, timeNow: time.Now}
return a
}
// creates fyne animation
func (a *entryCursorAnimation) createAnim(inverted bool) *fyne.Animation {
cursorOpaque := theme.PrimaryColor()
r, g, b, _ := theme.PrimaryColor().RGBA()
cursorDim := color.NRGBA{R: uint8(r), G: uint8(g), B: uint8(b), A: 0x16}
start, end := color.Color(cursorDim), color.Color(cursorOpaque)
if inverted {
start, end = color.Color(cursorOpaque), color.Color(cursorDim)
}
interrupted := false
anim := canvas.NewColorRGBAAnimation(start, end, time.Second/2, func(c color.Color) {
a.mu.RLock()
shouldInterrupt := a.timeNow().Sub(a.lastInterruptTime) <= cursorInterruptTime
a.mu.RUnlock()
if shouldInterrupt {
if !interrupted {
a.cursor.FillColor = cursorOpaque
a.cursor.Refresh()
interrupted = true
}
return
}
if interrupted {
a.mu.Lock()
a.anim.Stop()
if !inverted {
a.anim = a.createAnim(true)
}
interrupted = false
a.mu.Unlock()
go func() {
a.mu.RLock()
canStart := a.anim != nil
a.mu.RUnlock()
if canStart {
a.anim.Start()
}
}()
return
}
a.cursor.FillColor = c
a.cursor.Refresh()
})
anim.RepeatCount = fyne.AnimationRepeatForever
anim.AutoReverse = true
return anim
}
// starts cursor animation.
func (a *entryCursorAnimation) start() {
a.mu.Lock()
isStopped := a.anim == nil
if isStopped {
a.anim = a.createAnim(false)
}
a.mu.Unlock()
if isStopped {
a.anim.Start()
}
}
// temporarily stops the animation by "cursorInterruptTime".
func (a *entryCursorAnimation) interrupt() {
a.mu.Lock()
a.lastInterruptTime = a.timeNow()
a.mu.Unlock()
}
// stops cursor animation.
func (a *entryCursorAnimation) stop() {
a.mu.Lock()
if a.anim != nil {
a.anim.Stop()
a.anim = nil
}
a.mu.Unlock()
}