testapp.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. // Copyright 2015 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. //go:build darwin || linux
  5. // Small test app used by app/app_test.go.
  6. package main
  7. import (
  8. "log"
  9. "net"
  10. "golang.org/x/mobile/app"
  11. "golang.org/x/mobile/app/internal/apptest"
  12. "golang.org/x/mobile/event/lifecycle"
  13. "golang.org/x/mobile/event/paint"
  14. "golang.org/x/mobile/event/size"
  15. "golang.org/x/mobile/event/touch"
  16. "golang.org/x/mobile/gl"
  17. )
  18. func main() {
  19. app.Main(func(a app.App) {
  20. var (
  21. glctx gl.Context
  22. visible bool
  23. )
  24. addr := "127.0.0.1:" + apptest.Port
  25. log.Printf("addr: %s", addr)
  26. conn, err := net.Dial("tcp", addr)
  27. if err != nil {
  28. log.Fatal(err)
  29. }
  30. defer conn.Close()
  31. log.Printf("dialled")
  32. comm := &apptest.Comm{
  33. Conn: conn,
  34. Fatalf: log.Panicf,
  35. Printf: log.Printf,
  36. }
  37. comm.Send("hello_from_testapp")
  38. comm.Recv("hello_from_host")
  39. color := "red"
  40. sendPainting := false
  41. for e := range a.Events() {
  42. switch e := a.Filter(e).(type) {
  43. case lifecycle.Event:
  44. switch e.Crosses(lifecycle.StageVisible) {
  45. case lifecycle.CrossOn:
  46. comm.Send("lifecycle_visible")
  47. sendPainting = true
  48. visible = true
  49. glctx, _ = e.DrawContext.(gl.Context)
  50. case lifecycle.CrossOff:
  51. comm.Send("lifecycle_not_visible")
  52. visible = false
  53. }
  54. case size.Event:
  55. comm.Send("size", e.PixelsPerPt, e.Orientation)
  56. case paint.Event:
  57. if visible {
  58. if color == "red" {
  59. glctx.ClearColor(1, 0, 0, 1)
  60. } else {
  61. glctx.ClearColor(0, 1, 0, 1)
  62. }
  63. glctx.Clear(gl.COLOR_BUFFER_BIT)
  64. a.Publish()
  65. }
  66. if sendPainting {
  67. comm.Send("paint", color)
  68. sendPainting = false
  69. }
  70. case touch.Event:
  71. comm.Send("touch", e.Type, e.X, e.Y)
  72. if e.Type == touch.TypeEnd {
  73. if color == "red" {
  74. color = "green"
  75. } else {
  76. color = "red"
  77. }
  78. sendPainting = true
  79. // Send a paint event so the screen gets redrawn.
  80. a.Send(paint.Event{})
  81. }
  82. }
  83. }
  84. })
  85. }