testapp.go 2.0 KB

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