main.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. // Copyright 2023 The Ebitengine Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package main
  15. import (
  16. "image"
  17. "image/color"
  18. "log"
  19. "math"
  20. "strings"
  21. "unicode/utf8"
  22. "github.com/hajimehoshi/bitmapfont/v3"
  23. "github.com/hajimehoshi/ebiten/v2"
  24. "github.com/hajimehoshi/ebiten/v2/exp/textinput"
  25. "github.com/hajimehoshi/ebiten/v2/inpututil"
  26. "github.com/hajimehoshi/ebiten/v2/text/v2"
  27. "github.com/hajimehoshi/ebiten/v2/vector"
  28. )
  29. var fontFace = text.NewGoXFace(bitmapfont.FaceEA)
  30. const (
  31. screenWidth = 640
  32. screenHeight = 480
  33. )
  34. type TextField struct {
  35. bounds image.Rectangle
  36. multilines bool
  37. field textinput.Field
  38. }
  39. func NewTextField(bounds image.Rectangle, multilines bool) *TextField {
  40. return &TextField{
  41. bounds: bounds,
  42. multilines: multilines,
  43. }
  44. }
  45. func (t *TextField) Contains(x, y int) bool {
  46. return image.Pt(x, y).In(t.bounds)
  47. }
  48. func (t *TextField) SetSelectionStartByCursorPosition(x, y int) bool {
  49. idx, ok := t.textIndexByCursorPosition(x, y)
  50. if !ok {
  51. return false
  52. }
  53. t.field.SetSelection(idx, idx)
  54. return true
  55. }
  56. func (t *TextField) textIndexByCursorPosition(x, y int) (int, bool) {
  57. if !t.Contains(x, y) {
  58. return 0, false
  59. }
  60. x -= t.bounds.Min.X
  61. y -= t.bounds.Min.Y
  62. px, py := textFieldPadding()
  63. x -= px
  64. y -= py
  65. if x < 0 {
  66. x = 0
  67. }
  68. if y < 0 {
  69. y = 0
  70. }
  71. lineSpacingInPixels := int(fontFace.Metrics().HLineGap + fontFace.Metrics().HAscent + fontFace.Metrics().HDescent)
  72. var nlCount int
  73. var lineStart int
  74. var prevAdvance float64
  75. txt := t.field.Text()
  76. for i, r := range txt {
  77. var x0, x1 int
  78. currentAdvance := text.Advance(txt[lineStart:i], fontFace)
  79. if lineStart < i {
  80. x0 = int((prevAdvance + currentAdvance) / 2)
  81. }
  82. if r == '\n' {
  83. x1 = int(math.MaxInt32)
  84. } else if i < len(txt) {
  85. nextI := i + 1
  86. for !utf8.ValidString(txt[i:nextI]) {
  87. nextI++
  88. }
  89. nextAdvance := text.Advance(txt[lineStart:nextI], fontFace)
  90. x1 = int((currentAdvance + nextAdvance) / 2)
  91. } else {
  92. x1 = int(currentAdvance)
  93. }
  94. if x0 <= x && x < x1 && nlCount*lineSpacingInPixels <= y && y < (nlCount+1)*lineSpacingInPixels {
  95. return i, true
  96. }
  97. prevAdvance = currentAdvance
  98. if r == '\n' {
  99. nlCount++
  100. lineStart = i + 1
  101. prevAdvance = 0
  102. }
  103. }
  104. return len(txt), true
  105. }
  106. func (t *TextField) Focus() {
  107. t.field.Focus()
  108. }
  109. func (t *TextField) Blur() {
  110. t.field.Blur()
  111. }
  112. func (t *TextField) Update() error {
  113. if !t.field.IsFocused() {
  114. return nil
  115. }
  116. x, y := t.bounds.Min.X, t.bounds.Min.Y
  117. cx, cy := t.cursorPos()
  118. px, py := textFieldPadding()
  119. x += cx + px
  120. y += cy + py + int(fontFace.Metrics().HAscent)
  121. handled, err := t.field.HandleInput(x, y)
  122. if err != nil {
  123. return err
  124. }
  125. if handled {
  126. return nil
  127. }
  128. switch {
  129. case inpututil.IsKeyJustPressed(ebiten.KeyEnter):
  130. if t.multilines {
  131. text := t.field.Text()
  132. selectionStart, selectionEnd := t.field.Selection()
  133. text = text[:selectionStart] + "\n" + text[selectionEnd:]
  134. selectionStart += len("\n")
  135. selectionEnd = selectionStart
  136. t.field.SetTextAndSelection(text, selectionStart, selectionEnd)
  137. }
  138. case inpututil.IsKeyJustPressed(ebiten.KeyBackspace):
  139. text := t.field.Text()
  140. selectionStart, selectionEnd := t.field.Selection()
  141. if selectionStart != selectionEnd {
  142. text = text[:selectionStart] + text[selectionEnd:]
  143. } else if selectionStart > 0 {
  144. // TODO: Remove a grapheme instead of a code point.
  145. _, l := utf8.DecodeLastRuneInString(text[:selectionStart])
  146. text = text[:selectionStart-l] + text[selectionEnd:]
  147. selectionStart -= l
  148. }
  149. selectionEnd = selectionStart
  150. t.field.SetTextAndSelection(text, selectionStart, selectionEnd)
  151. case inpututil.IsKeyJustPressed(ebiten.KeyLeft):
  152. text := t.field.Text()
  153. selectionStart, _ := t.field.Selection()
  154. if selectionStart > 0 {
  155. // TODO: Remove a grapheme instead of a code point.
  156. _, l := utf8.DecodeLastRuneInString(text[:selectionStart])
  157. selectionStart -= l
  158. }
  159. t.field.SetTextAndSelection(text, selectionStart, selectionStart)
  160. case inpututil.IsKeyJustPressed(ebiten.KeyRight):
  161. text := t.field.Text()
  162. _, selectionEnd := t.field.Selection()
  163. if selectionEnd < len(text) {
  164. // TODO: Remove a grapheme instead of a code point.
  165. _, l := utf8.DecodeRuneInString(text[selectionEnd:])
  166. selectionEnd += l
  167. }
  168. t.field.SetTextAndSelection(text, selectionEnd, selectionEnd)
  169. }
  170. if !t.multilines {
  171. orig := t.field.Text()
  172. new := strings.ReplaceAll(orig, "\n", "")
  173. if new != orig {
  174. selectionStart, selectionEnd := t.field.Selection()
  175. selectionStart -= strings.Count(orig[:selectionStart], "\n")
  176. selectionEnd -= strings.Count(orig[:selectionEnd], "\n")
  177. t.field.SetSelection(selectionStart, selectionEnd)
  178. }
  179. }
  180. return nil
  181. }
  182. func (t *TextField) cursorPos() (int, int) {
  183. var nlCount int
  184. lastNLPos := -1
  185. txt := t.field.TextForRendering()
  186. selectionStart, _ := t.field.Selection()
  187. if s, _, ok := t.field.CompositionSelection(); ok {
  188. selectionStart += s
  189. }
  190. txt = txt[:selectionStart]
  191. for i, r := range txt {
  192. if r == '\n' {
  193. nlCount++
  194. lastNLPos = i
  195. }
  196. }
  197. txt = txt[lastNLPos+1:]
  198. x := int(text.Advance(txt, fontFace))
  199. y := nlCount * int(fontFace.Metrics().HLineGap+fontFace.Metrics().HAscent+fontFace.Metrics().HDescent)
  200. return x, y
  201. }
  202. func (t *TextField) Draw(screen *ebiten.Image) {
  203. vector.DrawFilledRect(screen, float32(t.bounds.Min.X), float32(t.bounds.Min.Y), float32(t.bounds.Dx()), float32(t.bounds.Dy()), color.White, false)
  204. var clr color.Color = color.Black
  205. if t.field.IsFocused() {
  206. clr = color.RGBA{0, 0, 0xff, 0xff}
  207. }
  208. vector.StrokeRect(screen, float32(t.bounds.Min.X), float32(t.bounds.Min.Y), float32(t.bounds.Dx()), float32(t.bounds.Dy()), 1, clr, false)
  209. px, py := textFieldPadding()
  210. selectionStart, _ := t.field.Selection()
  211. if t.field.IsFocused() && selectionStart >= 0 {
  212. x, y := t.bounds.Min.X, t.bounds.Min.Y
  213. cx, cy := t.cursorPos()
  214. x += px + cx
  215. y += py + cy
  216. h := int(fontFace.Metrics().HLineGap + fontFace.Metrics().HAscent + fontFace.Metrics().HDescent)
  217. vector.StrokeLine(screen, float32(x), float32(y), float32(x), float32(y+h), 1, color.Black, false)
  218. }
  219. tx := t.bounds.Min.X + px
  220. ty := t.bounds.Min.Y + py
  221. op := &text.DrawOptions{}
  222. op.GeoM.Translate(float64(tx), float64(ty))
  223. op.ColorScale.ScaleWithColor(color.Black)
  224. op.LineSpacing = fontFace.Metrics().HLineGap + fontFace.Metrics().HAscent + fontFace.Metrics().HDescent
  225. text.Draw(screen, t.field.TextForRendering(), fontFace, op)
  226. }
  227. const textFieldHeight = 24
  228. func textFieldPadding() (int, int) {
  229. m := fontFace.Metrics()
  230. return 4, (textFieldHeight - int(m.HLineGap+m.HAscent+m.HDescent)) / 2
  231. }
  232. type Game struct {
  233. textFields []*TextField
  234. }
  235. func (g *Game) Update() error {
  236. if g.textFields == nil {
  237. g.textFields = append(g.textFields, NewTextField(image.Rect(16, 16, screenWidth-16, 16+textFieldHeight), false))
  238. g.textFields = append(g.textFields, NewTextField(image.Rect(16, 48, screenWidth-16, 48+textFieldHeight), false))
  239. g.textFields = append(g.textFields, NewTextField(image.Rect(16, 80, screenWidth-16, screenHeight-16), true))
  240. }
  241. ids := inpututil.AppendJustPressedTouchIDs(nil)
  242. if inpututil.IsMouseButtonJustPressed(ebiten.MouseButtonLeft) || len(ids) > 0 {
  243. var x, y int
  244. if len(ids) > 0 {
  245. x, y = ebiten.TouchPosition(ids[0])
  246. } else {
  247. x, y = ebiten.CursorPosition()
  248. }
  249. for _, tf := range g.textFields {
  250. if tf.Contains(x, y) {
  251. tf.Focus()
  252. tf.SetSelectionStartByCursorPosition(x, y)
  253. } else {
  254. tf.Blur()
  255. }
  256. }
  257. }
  258. for _, tf := range g.textFields {
  259. if err := tf.Update(); err != nil {
  260. return err
  261. }
  262. }
  263. x, y := ebiten.CursorPosition()
  264. var inTextField bool
  265. for _, tf := range g.textFields {
  266. if tf.Contains(x, y) {
  267. inTextField = true
  268. break
  269. }
  270. }
  271. if inTextField {
  272. ebiten.SetCursorShape(ebiten.CursorShapeText)
  273. } else {
  274. ebiten.SetCursorShape(ebiten.CursorShapeDefault)
  275. }
  276. return nil
  277. }
  278. func (g *Game) Draw(screen *ebiten.Image) {
  279. screen.Fill(color.RGBA{0xcc, 0xcc, 0xcc, 0xff})
  280. for _, tf := range g.textFields {
  281. tf.Draw(screen)
  282. }
  283. }
  284. func (g *Game) Layout(outsideWidth, outsideHeight int) (int, int) {
  285. return screenWidth, screenHeight
  286. }
  287. func main() {
  288. ebiten.SetWindowSize(screenWidth, screenHeight)
  289. ebiten.SetWindowTitle("Text Input (Ebitengine Demo)")
  290. if err := ebiten.RunGame(&Game{}); err != nil {
  291. log.Fatal(err)
  292. }
  293. }