lifecycle.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package app
  2. import (
  3. "sync/atomic"
  4. "fyne.io/fyne/v2"
  5. )
  6. var _ fyne.Lifecycle = (*Lifecycle)(nil)
  7. // Lifecycle represents the various phases that an app can transition through.
  8. //
  9. // Since: 2.1
  10. type Lifecycle struct {
  11. onForeground atomic.Value // func()
  12. onBackground atomic.Value // func()
  13. onStarted atomic.Value // func()
  14. onStopped atomic.Value // func()
  15. }
  16. // SetOnEnteredForeground hooks into the the app becoming foreground.
  17. func (l *Lifecycle) SetOnEnteredForeground(f func()) {
  18. l.onForeground.Store(f)
  19. }
  20. // SetOnExitedForeground hooks into the app having moved to the background.
  21. // Depending on the platform it may still be visible but will not receive keyboard events.
  22. // On some systems hover or desktop mouse move events may still occur.
  23. func (l *Lifecycle) SetOnExitedForeground(f func()) {
  24. l.onBackground.Store(f)
  25. }
  26. // SetOnStarted hooks into an event that says the app is now running.
  27. func (l *Lifecycle) SetOnStarted(f func()) {
  28. l.onStarted.Store(f)
  29. }
  30. // SetOnStopped hooks into an event that says the app is no longer running.
  31. func (l *Lifecycle) SetOnStopped(f func()) {
  32. l.onStopped.Store(f)
  33. }
  34. // TriggerEnteredForeground will call the focus gained hook, if one is registered.
  35. func (l *Lifecycle) TriggerEnteredForeground() {
  36. f := l.onForeground.Load()
  37. if ff, ok := f.(func()); ok && ff != nil {
  38. ff()
  39. }
  40. }
  41. // TriggerExitedForeground will call the focus lost hook, if one is registered.
  42. func (l *Lifecycle) TriggerExitedForeground() {
  43. f := l.onBackground.Load()
  44. if ff, ok := f.(func()); ok && ff != nil {
  45. ff()
  46. }
  47. }
  48. // TriggerStarted will call the started hook, if one is registered.
  49. func (l *Lifecycle) TriggerStarted() {
  50. f := l.onStarted.Load()
  51. if ff, ok := f.(func()); ok && ff != nil {
  52. ff()
  53. }
  54. }
  55. // TriggerStopped will call the stopped hook, if one is registered.
  56. func (l *Lifecycle) TriggerStopped() {
  57. f := l.onStopped.Load()
  58. if ff, ok := f.(func()); ok && ff != nil {
  59. ff()
  60. }
  61. }