lifecycle.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. onStoppedHookExecuted func()
  16. }
  17. // SetOnStoppedHookExecuted is an internal function that lets Fyne schedule a clean-up after
  18. // the user-provided stopped hook. It should only be called once during an application start-up.
  19. func (l *Lifecycle) SetOnStoppedHookExecuted(f func()) {
  20. l.onStoppedHookExecuted = f
  21. }
  22. // SetOnEnteredForeground hooks into the the app becoming foreground.
  23. func (l *Lifecycle) SetOnEnteredForeground(f func()) {
  24. l.onForeground.Store(f)
  25. }
  26. // SetOnExitedForeground hooks into the app having moved to the background.
  27. // Depending on the platform it may still be visible but will not receive keyboard events.
  28. // On some systems hover or desktop mouse move events may still occur.
  29. func (l *Lifecycle) SetOnExitedForeground(f func()) {
  30. l.onBackground.Store(f)
  31. }
  32. // SetOnStarted hooks into an event that says the app is now running.
  33. func (l *Lifecycle) SetOnStarted(f func()) {
  34. l.onStarted.Store(f)
  35. }
  36. // SetOnStopped hooks into an event that says the app is no longer running.
  37. func (l *Lifecycle) SetOnStopped(f func()) {
  38. l.onStopped.Store(f)
  39. }
  40. // TriggerEnteredForeground will call the focus gained hook, if one is registered.
  41. func (l *Lifecycle) TriggerEnteredForeground() {
  42. f := l.onForeground.Load()
  43. if ff, ok := f.(func()); ok && ff != nil {
  44. ff()
  45. }
  46. }
  47. // TriggerExitedForeground will call the focus lost hook, if one is registered.
  48. func (l *Lifecycle) TriggerExitedForeground() {
  49. f := l.onBackground.Load()
  50. if ff, ok := f.(func()); ok && ff != nil {
  51. ff()
  52. }
  53. }
  54. // TriggerStarted will call the started hook, if one is registered.
  55. func (l *Lifecycle) TriggerStarted() {
  56. f := l.onStarted.Load()
  57. if ff, ok := f.(func()); ok && ff != nil {
  58. ff()
  59. }
  60. }
  61. // TriggerStopped will call the stopped hook, if one is registered,
  62. // and an internal stopped hook after that.
  63. func (l *Lifecycle) TriggerStopped() {
  64. f := l.onStopped.Load()
  65. if ff, ok := f.(func()); ok && ff != nil {
  66. ff()
  67. }
  68. if l.onStoppedHookExecuted != nil {
  69. l.onStoppedHookExecuted()
  70. }
  71. }