Context.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. package giu
  2. import (
  3. "sync"
  4. "github.com/AllenDang/imgui-go"
  5. "gopkg.in/eapache/queue.v1"
  6. )
  7. // Context represents a giu context.
  8. var Context context
  9. // Disposable should be implemented by all states stored in context.
  10. // Dispose method is called when state is removed from context.
  11. type Disposable interface {
  12. Dispose()
  13. }
  14. type state struct {
  15. valid bool
  16. data Disposable
  17. }
  18. type context struct {
  19. // TODO: should be handled by mainthread tbh
  20. // see https://github.com/faiface/mainthread/pull/4
  21. isRunning bool
  22. renderer imgui.Renderer
  23. platform imgui.Platform
  24. widgetIndexCounter int
  25. // Indicate whether current application is running
  26. isAlive bool
  27. // States will used by custom widget to store data
  28. state sync.Map
  29. InputHandler InputHandler
  30. textureLoadingQueue *queue.Queue
  31. }
  32. func (c *context) GetRenderer() imgui.Renderer {
  33. return c.renderer
  34. }
  35. func (c *context) GetPlatform() imgui.Platform {
  36. return c.platform
  37. }
  38. func (c *context) IO() imgui.IO {
  39. return imgui.CurrentIO()
  40. }
  41. func (c *context) invalidAllState() {
  42. c.state.Range(func(k, v any) bool {
  43. if s, ok := v.(*state); ok {
  44. s.valid = false
  45. }
  46. return true
  47. })
  48. }
  49. func (c *context) cleanState() {
  50. c.state.Range(func(k, v any) bool {
  51. if s, ok := v.(*state); ok {
  52. if !s.valid {
  53. c.state.Delete(k)
  54. s.data.Dispose()
  55. }
  56. }
  57. return true
  58. })
  59. // Reset widgetIndexCounter
  60. c.widgetIndexCounter = 0
  61. }
  62. func (c *context) SetState(id string, data Disposable) {
  63. c.state.Store(id, &state{valid: true, data: data})
  64. }
  65. func (c *context) GetState(id string) any {
  66. if v, ok := c.state.Load(id); ok {
  67. if s, ok := v.(*state); ok {
  68. s.valid = true
  69. return s.data
  70. }
  71. }
  72. return nil
  73. }
  74. // Get widget index for current layout.
  75. func (c *context) GetWidgetIndex() int {
  76. i := c.widgetIndexCounter
  77. c.widgetIndexCounter++
  78. return i
  79. }