android.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881
  1. // Copyright 2014 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 android
  5. // +build android
  6. /*
  7. Android Apps are built with -buildmode=c-shared. They are loaded by a
  8. running Java process.
  9. Before any entry point is reached, a global constructor initializes the
  10. Go runtime, calling all Go init functions. All cgo calls will block
  11. until this is complete. Next JNI_OnLoad is called. When that is
  12. complete, one of two entry points is called.
  13. All-Go apps built using NativeActivity enter at ANativeActivity_onCreate.
  14. Go libraries (for example, those built with gomobile bind) do not use
  15. the app package initialization.
  16. */
  17. package app
  18. /*
  19. #cgo LDFLAGS: -landroid -llog -lEGL -lGLESv2
  20. #include <android/configuration.h>
  21. #include <android/input.h>
  22. #include <android/keycodes.h>
  23. #include <android/looper.h>
  24. #include <android/native_activity.h>
  25. #include <android/native_window.h>
  26. #include <EGL/egl.h>
  27. #include <jni.h>
  28. #include <pthread.h>
  29. #include <stdlib.h>
  30. #include <stdbool.h>
  31. extern EGLDisplay display;
  32. extern EGLSurface surface;
  33. char* createEGLSurface(ANativeWindow* window);
  34. char* destroyEGLSurface();
  35. int32_t getKeyRune(JNIEnv* env, AInputEvent* e);
  36. void showKeyboard(JNIEnv* env, int keyboardType);
  37. void hideKeyboard(JNIEnv* env);
  38. void showFileOpen(JNIEnv* env, char* mimes);
  39. void showFileSave(JNIEnv* env, char* mimes, char* filename);
  40. void finish(JNIEnv* env, jobject ctx);
  41. void Java_org_golang_app_GoNativeActivity_filePickerReturned(JNIEnv *env, jclass clazz, jstring str);
  42. */
  43. import "C"
  44. import (
  45. "fmt"
  46. "log"
  47. "mime"
  48. "os"
  49. "runtime"
  50. "runtime/debug"
  51. "strings"
  52. "time"
  53. "unsafe"
  54. "fyne.io/fyne/v2/internal/driver/mobile/app/callfn"
  55. "fyne.io/fyne/v2/internal/driver/mobile/event/key"
  56. "fyne.io/fyne/v2/internal/driver/mobile/event/lifecycle"
  57. "fyne.io/fyne/v2/internal/driver/mobile/event/paint"
  58. "fyne.io/fyne/v2/internal/driver/mobile/event/size"
  59. "fyne.io/fyne/v2/internal/driver/mobile/event/touch"
  60. "fyne.io/fyne/v2/internal/driver/mobile/mobileinit"
  61. )
  62. // mimeMap contains standard mime entries that are missing on Android
  63. var mimeMap = map[string]string{
  64. ".txt": "text/plain",
  65. }
  66. // GoBack asks the OS to go to the previous app / activity
  67. func GoBack() {
  68. err := RunOnJVM(func(_, jniEnv, ctx uintptr) error {
  69. env := (*C.JNIEnv)(unsafe.Pointer(jniEnv))
  70. C.finish(env, C.jobject(ctx))
  71. return nil
  72. })
  73. if err != nil {
  74. log.Fatalf("app: %v", err)
  75. }
  76. }
  77. // RunOnJVM runs fn on a new goroutine locked to an OS thread with a JNIEnv.
  78. //
  79. // RunOnJVM blocks until the call to fn is complete. Any Java
  80. // exception or failure to attach to the JVM is returned as an error.
  81. //
  82. // The function fn takes vm, the current JavaVM*,
  83. // env, the current JNIEnv*, and
  84. // ctx, a jobject representing the global android.context.Context.
  85. func RunOnJVM(fn func(vm, jniEnv, ctx uintptr) error) error {
  86. return mobileinit.RunOnJVM(fn)
  87. }
  88. //export setCurrentContext
  89. func setCurrentContext(vm *C.JavaVM, ctx C.jobject) {
  90. mobileinit.SetCurrentContext(unsafe.Pointer(vm), uintptr(ctx))
  91. }
  92. //export callMain
  93. func callMain(mainPC uintptr) {
  94. for _, name := range []string{"FILESDIR", "TMPDIR", "PATH", "LD_LIBRARY_PATH"} {
  95. n := C.CString(name)
  96. os.Setenv(name, C.GoString(C.getenv(n)))
  97. C.free(unsafe.Pointer(n))
  98. }
  99. // Set timezone.
  100. //
  101. // Note that Android zoneinfo is stored in /system/usr/share/zoneinfo,
  102. // but it is in some kind of packed TZiff file that we do not support
  103. // yet. As a stopgap, we build a fixed zone using the tm_zone name.
  104. var curtime C.time_t
  105. var curtm C.struct_tm
  106. C.time(&curtime)
  107. C.localtime_r(&curtime, &curtm)
  108. tzOffset := int(curtm.tm_gmtoff)
  109. tz := C.GoString(curtm.tm_zone)
  110. time.Local = time.FixedZone(tz, tzOffset)
  111. go callfn.CallFn(mainPC)
  112. }
  113. //export onSaveInstanceState
  114. func onSaveInstanceState(activity *C.ANativeActivity, outSize *C.size_t) unsafe.Pointer {
  115. return nil
  116. }
  117. //export onBackPressed
  118. func onBackPressed() {
  119. k := key.Event{
  120. Code: key.CodeBackButton,
  121. Direction: key.DirPress,
  122. }
  123. theApp.events.In() <- k
  124. k.Direction = key.DirRelease
  125. theApp.events.In() <- k
  126. }
  127. //export onCreate
  128. func onCreate(activity *C.ANativeActivity) {
  129. // Set the initial configuration.
  130. //
  131. // Note we use unbuffered channels to talk to the activity loop, and
  132. // NativeActivity calls these callbacks sequentially, so configuration
  133. // will be set before <-windowRedrawNeeded is processed.
  134. windowConfigChange <- windowConfigRead(activity)
  135. }
  136. //export onDestroy
  137. func onDestroy(activity *C.ANativeActivity) {
  138. activityDestroyed <- struct{}{}
  139. }
  140. //export onWindowFocusChanged
  141. func onWindowFocusChanged(activity *C.ANativeActivity, hasFocus C.int) {
  142. }
  143. //export onNativeWindowCreated
  144. func onNativeWindowCreated(activity *C.ANativeActivity, window *C.ANativeWindow) {
  145. }
  146. //export onNativeWindowRedrawNeeded
  147. func onNativeWindowRedrawNeeded(activity *C.ANativeActivity, window *C.ANativeWindow) {
  148. // Called on orientation change and window resize.
  149. // Send a request for redraw, and block this function
  150. // until a complete draw and buffer swap is completed.
  151. // This is required by the redraw documentation to
  152. // avoid bad draws.
  153. windowRedrawNeeded <- window
  154. <-windowRedrawDone
  155. }
  156. //export onNativeWindowDestroyed
  157. func onNativeWindowDestroyed(activity *C.ANativeActivity, window *C.ANativeWindow) {
  158. windowDestroyed <- window
  159. }
  160. //export onInputQueueCreated
  161. func onInputQueueCreated(activity *C.ANativeActivity, q *C.AInputQueue) {
  162. inputQueue <- q
  163. <-inputQueueDone
  164. }
  165. //export onInputQueueDestroyed
  166. func onInputQueueDestroyed(activity *C.ANativeActivity, q *C.AInputQueue) {
  167. inputQueue <- nil
  168. <-inputQueueDone
  169. }
  170. //export onContentRectChanged
  171. func onContentRectChanged(activity *C.ANativeActivity, rect *C.ARect) {
  172. }
  173. //export setDarkMode
  174. func setDarkMode(dark C.bool) {
  175. darkMode = bool(dark)
  176. }
  177. type windowConfig struct {
  178. orientation size.Orientation
  179. pixelsPerPt float32
  180. }
  181. func windowConfigRead(activity *C.ANativeActivity) windowConfig {
  182. aconfig := C.AConfiguration_new()
  183. C.AConfiguration_fromAssetManager(aconfig, activity.assetManager)
  184. orient := C.AConfiguration_getOrientation(aconfig)
  185. density := C.AConfiguration_getDensity(aconfig)
  186. C.AConfiguration_delete(aconfig)
  187. // Calculate the screen resolution. This value is approximate. For example,
  188. // a physical resolution of 200 DPI may be quantized to one of the
  189. // ACONFIGURATION_DENSITY_XXX values such as 160 or 240.
  190. //
  191. // A more accurate DPI could possibly be calculated from
  192. // https://developer.android.com/reference/android/util/DisplayMetrics.html#xdpi
  193. // but this does not appear to be accessible via the NDK. In any case, the
  194. // hardware might not even provide a more accurate number, as the system
  195. // does not apparently use the reported value. See golang.org/issue/13366
  196. // for a discussion.
  197. var dpi int
  198. switch density {
  199. case C.ACONFIGURATION_DENSITY_DEFAULT:
  200. dpi = 160
  201. case C.ACONFIGURATION_DENSITY_LOW,
  202. C.ACONFIGURATION_DENSITY_MEDIUM,
  203. 213, // C.ACONFIGURATION_DENSITY_TV
  204. C.ACONFIGURATION_DENSITY_HIGH,
  205. 320, // ACONFIGURATION_DENSITY_XHIGH
  206. 480, // ACONFIGURATION_DENSITY_XXHIGH
  207. 640: // ACONFIGURATION_DENSITY_XXXHIGH
  208. dpi = int(density)
  209. case C.ACONFIGURATION_DENSITY_NONE:
  210. log.Print("android device reports no screen density")
  211. dpi = 72
  212. default:
  213. log.Printf("android device reports unknown density: %d", density)
  214. // All we can do is guess.
  215. if density > 0 {
  216. dpi = int(density)
  217. } else {
  218. dpi = 72
  219. }
  220. }
  221. o := size.OrientationUnknown
  222. switch orient {
  223. case C.ACONFIGURATION_ORIENTATION_PORT:
  224. o = size.OrientationPortrait
  225. case C.ACONFIGURATION_ORIENTATION_LAND:
  226. o = size.OrientationLandscape
  227. }
  228. return windowConfig{
  229. orientation: o,
  230. pixelsPerPt: float32(dpi) / 72,
  231. }
  232. }
  233. //export onConfigurationChanged
  234. func onConfigurationChanged(activity *C.ANativeActivity) {
  235. // A rotation event first triggers onConfigurationChanged, then
  236. // calls onNativeWindowRedrawNeeded. We extract the orientation
  237. // here and save it for the redraw event.
  238. windowConfigChange <- windowConfigRead(activity)
  239. }
  240. //export onLowMemory
  241. func onLowMemory(activity *C.ANativeActivity) {
  242. runtime.GC()
  243. debug.FreeOSMemory()
  244. }
  245. var (
  246. inputQueue = make(chan *C.AInputQueue)
  247. inputQueueDone = make(chan struct{})
  248. windowDestroyed = make(chan *C.ANativeWindow)
  249. windowRedrawNeeded = make(chan *C.ANativeWindow)
  250. windowRedrawDone = make(chan struct{})
  251. windowConfigChange = make(chan windowConfig)
  252. activityDestroyed = make(chan struct{})
  253. screenInsetTop, screenInsetBottom, screenInsetLeft, screenInsetRight int
  254. darkMode bool
  255. )
  256. func init() {
  257. theApp.registerGLViewportFilter()
  258. }
  259. func main(f func(App)) {
  260. mainUserFn = f
  261. // TODO: merge the runInputQueue and mainUI functions?
  262. go func() {
  263. if err := mobileinit.RunOnJVM(runInputQueue); err != nil {
  264. log.Fatalf("app: %v", err)
  265. }
  266. }()
  267. // Preserve this OS thread for:
  268. // 1. the attached JNI thread
  269. // 2. the GL context
  270. if err := mobileinit.RunOnJVM(mainUI); err != nil {
  271. log.Fatalf("app: %v", err)
  272. }
  273. }
  274. // driverShowVirtualKeyboard requests the driver to show a virtual keyboard for text input
  275. func driverShowVirtualKeyboard(keyboard KeyboardType) {
  276. err := mobileinit.RunOnJVM(func(vm, jniEnv, ctx uintptr) error {
  277. env := (*C.JNIEnv)(unsafe.Pointer(jniEnv)) // not a Go heap pointer
  278. C.showKeyboard(env, C.int(int32(keyboard)))
  279. return nil
  280. })
  281. if err != nil {
  282. log.Fatalf("app: %v", err)
  283. }
  284. }
  285. // driverHideVirtualKeyboard requests the driver to hide any visible virtual keyboard
  286. func driverHideVirtualKeyboard() {
  287. if err := mobileinit.RunOnJVM(hideSoftInput); err != nil {
  288. log.Fatalf("app: %v", err)
  289. }
  290. }
  291. func hideSoftInput(vm, jniEnv, ctx uintptr) error {
  292. env := (*C.JNIEnv)(unsafe.Pointer(jniEnv)) // not a Go heap pointer
  293. C.hideKeyboard(env)
  294. return nil
  295. }
  296. var fileCallback func(string, func())
  297. //export filePickerReturned
  298. func filePickerReturned(str *C.char) {
  299. if fileCallback == nil {
  300. return
  301. }
  302. fileCallback(C.GoString(str), nil)
  303. fileCallback = nil
  304. }
  305. //export insetsChanged
  306. func insetsChanged(top, bottom, left, right int) {
  307. screenInsetTop, screenInsetBottom, screenInsetLeft, screenInsetRight = top, bottom, left, right
  308. }
  309. func mimeStringFromFilter(filter *FileFilter) string {
  310. mimes := "*/*"
  311. if filter.MimeTypes != nil {
  312. mimes = strings.Join(filter.MimeTypes, "|")
  313. } else if filter.Extensions != nil {
  314. var mimeTypes []string
  315. for _, ext := range filter.Extensions {
  316. if mimeEntry, ok := mimeMap[ext]; ok {
  317. mimeTypes = append(mimeTypes, mimeEntry)
  318. continue
  319. }
  320. mimeType := mime.TypeByExtension(ext)
  321. if mimeType == "" {
  322. log.Println("Could not find mime for extension " + ext + ", allowing all")
  323. return "*/*" // could not find one, so allow all
  324. }
  325. mimeTypes = append(mimeTypes, mimeType)
  326. }
  327. mimes = strings.Join(mimeTypes, "|")
  328. }
  329. return mimes
  330. }
  331. func driverShowFileOpenPicker(callback func(string, func()), filter *FileFilter) {
  332. fileCallback = callback
  333. mimes := mimeStringFromFilter(filter)
  334. mimeStr := C.CString(mimes)
  335. defer C.free(unsafe.Pointer(mimeStr))
  336. open := func(vm, jniEnv, ctx uintptr) error {
  337. // TODO pass in filter...
  338. env := (*C.JNIEnv)(unsafe.Pointer(jniEnv)) // not a Go heap pointer
  339. C.showFileOpen(env, mimeStr)
  340. return nil
  341. }
  342. if err := mobileinit.RunOnJVM(open); err != nil {
  343. log.Fatalf("app: %v", err)
  344. }
  345. }
  346. func driverShowFileSavePicker(callback func(string, func()), filter *FileFilter, filename string) {
  347. fileCallback = callback
  348. mimes := mimeStringFromFilter(filter)
  349. mimeStr := C.CString(mimes)
  350. defer C.free(unsafe.Pointer(mimeStr))
  351. filenameStr := C.CString(filename)
  352. defer C.free(unsafe.Pointer(filenameStr))
  353. save := func(vm, jniEnv, ctx uintptr) error {
  354. env := (*C.JNIEnv)(unsafe.Pointer(jniEnv)) // not a Go heap pointer
  355. C.showFileSave(env, mimeStr, filenameStr)
  356. return nil
  357. }
  358. if err := mobileinit.RunOnJVM(save); err != nil {
  359. log.Fatalf("app: %v", err)
  360. }
  361. }
  362. var mainUserFn func(App)
  363. var DisplayMetrics struct {
  364. WidthPx int
  365. HeightPx int
  366. }
  367. func mainUI(vm, jniEnv, ctx uintptr) error {
  368. workAvailable := theApp.worker.WorkAvailable()
  369. donec := make(chan struct{})
  370. go func() {
  371. mainUserFn(theApp)
  372. close(donec)
  373. }()
  374. var pixelsPerPt float32
  375. for {
  376. select {
  377. case <-donec:
  378. return nil
  379. case cfg := <-windowConfigChange:
  380. pixelsPerPt = cfg.pixelsPerPt
  381. case w := <-windowRedrawNeeded:
  382. if C.surface == nil {
  383. if errStr := C.createEGLSurface(w); errStr != nil {
  384. return fmt.Errorf("%s (%s)", C.GoString(errStr), eglGetError())
  385. }
  386. DisplayMetrics.WidthPx = int(C.ANativeWindow_getWidth(w))
  387. DisplayMetrics.HeightPx = int(C.ANativeWindow_getHeight(w))
  388. }
  389. theApp.sendLifecycle(lifecycle.StageFocused)
  390. widthPx := int(C.ANativeWindow_getWidth(w))
  391. heightPx := int(C.ANativeWindow_getHeight(w))
  392. theApp.events.In() <- size.Event{
  393. WidthPx: widthPx,
  394. HeightPx: heightPx,
  395. WidthPt: float32(widthPx) / pixelsPerPt,
  396. HeightPt: float32(heightPx) / pixelsPerPt,
  397. InsetTopPx: screenInsetTop,
  398. InsetBottomPx: screenInsetBottom,
  399. InsetLeftPx: screenInsetLeft,
  400. InsetRightPx: screenInsetRight,
  401. PixelsPerPt: pixelsPerPt,
  402. Orientation: screenOrientation(widthPx, heightPx), // we are guessing orientation here as it was not always working
  403. DarkMode: darkMode,
  404. }
  405. theApp.events.In() <- paint.Event{External: true}
  406. case <-windowDestroyed:
  407. if C.surface != nil {
  408. if errStr := C.destroyEGLSurface(); errStr != nil {
  409. return fmt.Errorf("%s (%s)", C.GoString(errStr), eglGetError())
  410. }
  411. }
  412. C.surface = nil
  413. theApp.sendLifecycle(lifecycle.StageAlive)
  414. case <-activityDestroyed:
  415. theApp.sendLifecycle(lifecycle.StageDead)
  416. case <-workAvailable:
  417. theApp.worker.DoWork()
  418. case <-theApp.publish:
  419. // TODO: compare a generation number to redrawGen for stale paints?
  420. if C.surface != nil {
  421. // eglSwapBuffers blocks until vsync.
  422. if C.eglSwapBuffers(C.display, C.surface) == C.EGL_FALSE {
  423. log.Printf("app: failed to swap buffers (%s)", eglGetError())
  424. }
  425. }
  426. select {
  427. case windowRedrawDone <- struct{}{}:
  428. default:
  429. }
  430. theApp.publishResult <- PublishResult{}
  431. }
  432. }
  433. }
  434. func runInputQueue(vm, jniEnv, ctx uintptr) error {
  435. env := (*C.JNIEnv)(unsafe.Pointer(jniEnv)) // not a Go heap pointer
  436. // Android loopers select on OS file descriptors, not Go channels, so we
  437. // translate the inputQueue channel to an ALooper_wake call.
  438. l := C.ALooper_prepare(C.ALOOPER_PREPARE_ALLOW_NON_CALLBACKS)
  439. pending := make(chan *C.AInputQueue, 1)
  440. go func() {
  441. for q := range inputQueue {
  442. pending <- q
  443. C.ALooper_wake(l)
  444. }
  445. }()
  446. var q *C.AInputQueue
  447. for {
  448. if C.ALooper_pollAll(-1, nil, nil, nil) == C.ALOOPER_POLL_WAKE {
  449. select {
  450. default:
  451. case p := <-pending:
  452. if q != nil {
  453. processEvents(env, q)
  454. C.AInputQueue_detachLooper(q)
  455. }
  456. q = p
  457. if q != nil {
  458. C.AInputQueue_attachLooper(q, l, 0, nil, nil)
  459. }
  460. inputQueueDone <- struct{}{}
  461. }
  462. }
  463. if q != nil {
  464. processEvents(env, q)
  465. }
  466. }
  467. }
  468. func processEvents(env *C.JNIEnv, q *C.AInputQueue) {
  469. var e *C.AInputEvent
  470. for C.AInputQueue_getEvent(q, &e) >= 0 {
  471. if C.AInputQueue_preDispatchEvent(q, e) != 0 {
  472. continue
  473. }
  474. processEvent(env, e)
  475. C.AInputQueue_finishEvent(q, e, 0)
  476. }
  477. }
  478. func processEvent(env *C.JNIEnv, e *C.AInputEvent) {
  479. switch C.AInputEvent_getType(e) {
  480. case C.AINPUT_EVENT_TYPE_KEY:
  481. processKey(env, e)
  482. case C.AINPUT_EVENT_TYPE_MOTION:
  483. // At most one of the events in this batch is an up or down event; get its index and change.
  484. upDownIndex := C.size_t(C.AMotionEvent_getAction(e)&C.AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >> C.AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT
  485. upDownType := touch.TypeMove
  486. switch C.AMotionEvent_getAction(e) & C.AMOTION_EVENT_ACTION_MASK {
  487. case C.AMOTION_EVENT_ACTION_DOWN, C.AMOTION_EVENT_ACTION_POINTER_DOWN:
  488. upDownType = touch.TypeBegin
  489. case C.AMOTION_EVENT_ACTION_UP, C.AMOTION_EVENT_ACTION_POINTER_UP:
  490. upDownType = touch.TypeEnd
  491. }
  492. for i, n := C.size_t(0), C.AMotionEvent_getPointerCount(e); i < n; i++ {
  493. t := touch.TypeMove
  494. if i == upDownIndex {
  495. t = upDownType
  496. }
  497. theApp.events.In() <- touch.Event{
  498. X: float32(C.AMotionEvent_getX(e, i)),
  499. Y: float32(C.AMotionEvent_getY(e, i)),
  500. Sequence: touch.Sequence(C.AMotionEvent_getPointerId(e, i)),
  501. Type: t,
  502. }
  503. }
  504. default:
  505. log.Printf("unknown input event, type=%d", C.AInputEvent_getType(e))
  506. }
  507. }
  508. func processKey(env *C.JNIEnv, e *C.AInputEvent) {
  509. deviceID := C.AInputEvent_getDeviceId(e)
  510. if deviceID == 0 {
  511. // Software keyboard input, leaving for scribe/IME.
  512. return
  513. }
  514. k := key.Event{
  515. Rune: rune(C.getKeyRune(env, e)),
  516. Code: convAndroidKeyCode(int32(C.AKeyEvent_getKeyCode(e))),
  517. }
  518. if k.Rune >= '0' && k.Rune <= '9' { // GBoard generates key events for numbers, but we see them in textChanged
  519. return
  520. }
  521. switch C.AKeyEvent_getAction(e) {
  522. case C.AKEY_STATE_DOWN:
  523. k.Direction = key.DirPress
  524. case C.AKEY_STATE_UP:
  525. k.Direction = key.DirRelease
  526. default:
  527. k.Direction = key.DirNone
  528. }
  529. // TODO(crawshaw): set Modifiers.
  530. theApp.events.In() <- k
  531. }
  532. func eglGetError() string {
  533. switch errNum := C.eglGetError(); errNum {
  534. case C.EGL_SUCCESS:
  535. return "EGL_SUCCESS"
  536. case C.EGL_NOT_INITIALIZED:
  537. return "EGL_NOT_INITIALIZED"
  538. case C.EGL_BAD_ACCESS:
  539. return "EGL_BAD_ACCESS"
  540. case C.EGL_BAD_ALLOC:
  541. return "EGL_BAD_ALLOC"
  542. case C.EGL_BAD_ATTRIBUTE:
  543. return "EGL_BAD_ATTRIBUTE"
  544. case C.EGL_BAD_CONTEXT:
  545. return "EGL_BAD_CONTEXT"
  546. case C.EGL_BAD_CONFIG:
  547. return "EGL_BAD_CONFIG"
  548. case C.EGL_BAD_CURRENT_SURFACE:
  549. return "EGL_BAD_CURRENT_SURFACE"
  550. case C.EGL_BAD_DISPLAY:
  551. return "EGL_BAD_DISPLAY"
  552. case C.EGL_BAD_SURFACE:
  553. return "EGL_BAD_SURFACE"
  554. case C.EGL_BAD_MATCH:
  555. return "EGL_BAD_MATCH"
  556. case C.EGL_BAD_PARAMETER:
  557. return "EGL_BAD_PARAMETER"
  558. case C.EGL_BAD_NATIVE_PIXMAP:
  559. return "EGL_BAD_NATIVE_PIXMAP"
  560. case C.EGL_BAD_NATIVE_WINDOW:
  561. return "EGL_BAD_NATIVE_WINDOW"
  562. case C.EGL_CONTEXT_LOST:
  563. return "EGL_CONTEXT_LOST"
  564. default:
  565. return fmt.Sprintf("Unknown EGL err: %d", errNum)
  566. }
  567. }
  568. var androidKeycoe = map[int32]key.Code{
  569. C.AKEYCODE_HOME: key.CodeHome,
  570. C.AKEYCODE_0: key.Code0,
  571. C.AKEYCODE_1: key.Code1,
  572. C.AKEYCODE_2: key.Code2,
  573. C.AKEYCODE_3: key.Code3,
  574. C.AKEYCODE_4: key.Code4,
  575. C.AKEYCODE_5: key.Code5,
  576. C.AKEYCODE_6: key.Code6,
  577. C.AKEYCODE_7: key.Code7,
  578. C.AKEYCODE_8: key.Code8,
  579. C.AKEYCODE_9: key.Code9,
  580. C.AKEYCODE_VOLUME_UP: key.CodeVolumeUp,
  581. C.AKEYCODE_VOLUME_DOWN: key.CodeVolumeDown,
  582. C.AKEYCODE_A: key.CodeA,
  583. C.AKEYCODE_B: key.CodeB,
  584. C.AKEYCODE_C: key.CodeC,
  585. C.AKEYCODE_D: key.CodeD,
  586. C.AKEYCODE_E: key.CodeE,
  587. C.AKEYCODE_F: key.CodeF,
  588. C.AKEYCODE_G: key.CodeG,
  589. C.AKEYCODE_H: key.CodeH,
  590. C.AKEYCODE_I: key.CodeI,
  591. C.AKEYCODE_J: key.CodeJ,
  592. C.AKEYCODE_K: key.CodeK,
  593. C.AKEYCODE_L: key.CodeL,
  594. C.AKEYCODE_M: key.CodeM,
  595. C.AKEYCODE_N: key.CodeN,
  596. C.AKEYCODE_O: key.CodeO,
  597. C.AKEYCODE_P: key.CodeP,
  598. C.AKEYCODE_Q: key.CodeQ,
  599. C.AKEYCODE_R: key.CodeR,
  600. C.AKEYCODE_S: key.CodeS,
  601. C.AKEYCODE_T: key.CodeT,
  602. C.AKEYCODE_U: key.CodeU,
  603. C.AKEYCODE_V: key.CodeV,
  604. C.AKEYCODE_W: key.CodeW,
  605. C.AKEYCODE_X: key.CodeX,
  606. C.AKEYCODE_Y: key.CodeY,
  607. C.AKEYCODE_Z: key.CodeZ,
  608. C.AKEYCODE_COMMA: key.CodeComma,
  609. C.AKEYCODE_PERIOD: key.CodeFullStop,
  610. C.AKEYCODE_ALT_LEFT: key.CodeLeftAlt,
  611. C.AKEYCODE_ALT_RIGHT: key.CodeRightAlt,
  612. C.AKEYCODE_SHIFT_LEFT: key.CodeLeftShift,
  613. C.AKEYCODE_SHIFT_RIGHT: key.CodeRightShift,
  614. C.AKEYCODE_TAB: key.CodeTab,
  615. C.AKEYCODE_SPACE: key.CodeSpacebar,
  616. C.AKEYCODE_ENTER: key.CodeReturnEnter,
  617. C.AKEYCODE_DEL: key.CodeDeleteBackspace,
  618. C.AKEYCODE_GRAVE: key.CodeGraveAccent,
  619. C.AKEYCODE_MINUS: key.CodeHyphenMinus,
  620. C.AKEYCODE_EQUALS: key.CodeEqualSign,
  621. C.AKEYCODE_LEFT_BRACKET: key.CodeLeftSquareBracket,
  622. C.AKEYCODE_RIGHT_BRACKET: key.CodeRightSquareBracket,
  623. C.AKEYCODE_BACKSLASH: key.CodeBackslash,
  624. C.AKEYCODE_SEMICOLON: key.CodeSemicolon,
  625. C.AKEYCODE_APOSTROPHE: key.CodeApostrophe,
  626. C.AKEYCODE_SLASH: key.CodeSlash,
  627. C.AKEYCODE_PAGE_UP: key.CodePageUp,
  628. C.AKEYCODE_PAGE_DOWN: key.CodePageDown,
  629. C.AKEYCODE_ESCAPE: key.CodeEscape,
  630. C.AKEYCODE_FORWARD_DEL: key.CodeDeleteForward,
  631. C.AKEYCODE_CTRL_LEFT: key.CodeLeftControl,
  632. C.AKEYCODE_CTRL_RIGHT: key.CodeRightControl,
  633. C.AKEYCODE_CAPS_LOCK: key.CodeCapsLock,
  634. C.AKEYCODE_META_LEFT: key.CodeLeftGUI,
  635. C.AKEYCODE_META_RIGHT: key.CodeRightGUI,
  636. C.AKEYCODE_INSERT: key.CodeInsert,
  637. C.AKEYCODE_F1: key.CodeF1,
  638. C.AKEYCODE_F2: key.CodeF2,
  639. C.AKEYCODE_F3: key.CodeF3,
  640. C.AKEYCODE_F4: key.CodeF4,
  641. C.AKEYCODE_F5: key.CodeF5,
  642. C.AKEYCODE_F6: key.CodeF6,
  643. C.AKEYCODE_F7: key.CodeF7,
  644. C.AKEYCODE_F8: key.CodeF8,
  645. C.AKEYCODE_F9: key.CodeF9,
  646. C.AKEYCODE_F10: key.CodeF10,
  647. C.AKEYCODE_F11: key.CodeF11,
  648. C.AKEYCODE_F12: key.CodeF12,
  649. C.AKEYCODE_NUM_LOCK: key.CodeKeypadNumLock,
  650. C.AKEYCODE_NUMPAD_0: key.CodeKeypad0,
  651. C.AKEYCODE_NUMPAD_1: key.CodeKeypad1,
  652. C.AKEYCODE_NUMPAD_2: key.CodeKeypad2,
  653. C.AKEYCODE_NUMPAD_3: key.CodeKeypad3,
  654. C.AKEYCODE_NUMPAD_4: key.CodeKeypad4,
  655. C.AKEYCODE_NUMPAD_5: key.CodeKeypad5,
  656. C.AKEYCODE_NUMPAD_6: key.CodeKeypad6,
  657. C.AKEYCODE_NUMPAD_7: key.CodeKeypad7,
  658. C.AKEYCODE_NUMPAD_8: key.CodeKeypad8,
  659. C.AKEYCODE_NUMPAD_9: key.CodeKeypad9,
  660. C.AKEYCODE_NUMPAD_DIVIDE: key.CodeKeypadSlash,
  661. C.AKEYCODE_NUMPAD_MULTIPLY: key.CodeKeypadAsterisk,
  662. C.AKEYCODE_NUMPAD_SUBTRACT: key.CodeKeypadHyphenMinus,
  663. C.AKEYCODE_NUMPAD_ADD: key.CodeKeypadPlusSign,
  664. C.AKEYCODE_NUMPAD_DOT: key.CodeKeypadFullStop,
  665. C.AKEYCODE_NUMPAD_ENTER: key.CodeKeypadEnter,
  666. C.AKEYCODE_NUMPAD_EQUALS: key.CodeKeypadEqualSign,
  667. C.AKEYCODE_VOLUME_MUTE: key.CodeMute,
  668. }
  669. func convAndroidKeyCode(aKeyCode int32) key.Code {
  670. if code, ok := androidKeycoe[aKeyCode]; ok {
  671. return code
  672. }
  673. return key.CodeUnknown
  674. }
  675. /*
  676. Many Android key codes do not map into USB HID codes.
  677. For those, key.CodeUnknown is returned. This switch has all
  678. cases, even the unknown ones, to serve as a documentation
  679. and search aid.
  680. C.AKEYCODE_UNKNOWN
  681. C.AKEYCODE_SOFT_LEFT
  682. C.AKEYCODE_SOFT_RIGHT
  683. C.AKEYCODE_BACK
  684. C.AKEYCODE_CALL
  685. C.AKEYCODE_ENDCALL
  686. C.AKEYCODE_STAR
  687. C.AKEYCODE_POUND
  688. C.AKEYCODE_DPAD_UP
  689. C.AKEYCODE_DPAD_DOWN
  690. C.AKEYCODE_DPAD_LEFT
  691. C.AKEYCODE_DPAD_RIGHT
  692. C.AKEYCODE_DPAD_CENTER
  693. C.AKEYCODE_POWER
  694. C.AKEYCODE_CAMERA
  695. C.AKEYCODE_CLEAR
  696. C.AKEYCODE_SYM
  697. C.AKEYCODE_EXPLORER
  698. C.AKEYCODE_ENVELOPE
  699. C.AKEYCODE_AT
  700. C.AKEYCODE_NUM
  701. C.AKEYCODE_HEADSETHOOK
  702. C.AKEYCODE_FOCUS
  703. C.AKEYCODE_PLUS
  704. C.AKEYCODE_MENU
  705. C.AKEYCODE_NOTIFICATION
  706. C.AKEYCODE_SEARCH
  707. C.AKEYCODE_MEDIA_PLAY_PAUSE
  708. C.AKEYCODE_MEDIA_STOP
  709. C.AKEYCODE_MEDIA_NEXT
  710. C.AKEYCODE_MEDIA_PREVIOUS
  711. C.AKEYCODE_MEDIA_REWIND
  712. C.AKEYCODE_MEDIA_FAST_FORWARD
  713. C.AKEYCODE_MUTE
  714. C.AKEYCODE_PICTSYMBOLS
  715. C.AKEYCODE_SWITCH_CHARSET
  716. C.AKEYCODE_BUTTON_A
  717. C.AKEYCODE_BUTTON_B
  718. C.AKEYCODE_BUTTON_C
  719. C.AKEYCODE_BUTTON_X
  720. C.AKEYCODE_BUTTON_Y
  721. C.AKEYCODE_BUTTON_Z
  722. C.AKEYCODE_BUTTON_L1
  723. C.AKEYCODE_BUTTON_R1
  724. C.AKEYCODE_BUTTON_L2
  725. C.AKEYCODE_BUTTON_R2
  726. C.AKEYCODE_BUTTON_THUMBL
  727. C.AKEYCODE_BUTTON_THUMBR
  728. C.AKEYCODE_BUTTON_START
  729. C.AKEYCODE_BUTTON_SELECT
  730. C.AKEYCODE_BUTTON_MODE
  731. C.AKEYCODE_SCROLL_LOCK
  732. C.AKEYCODE_FUNCTION
  733. C.AKEYCODE_SYSRQ
  734. C.AKEYCODE_BREAK
  735. C.AKEYCODE_MOVE_HOME
  736. C.AKEYCODE_MOVE_END
  737. C.AKEYCODE_FORWARD
  738. C.AKEYCODE_MEDIA_PLAY
  739. C.AKEYCODE_MEDIA_PAUSE
  740. C.AKEYCODE_MEDIA_CLOSE
  741. C.AKEYCODE_MEDIA_EJECT
  742. C.AKEYCODE_MEDIA_RECORD
  743. C.AKEYCODE_NUMPAD_COMMA
  744. C.AKEYCODE_NUMPAD_LEFT_PAREN
  745. C.AKEYCODE_NUMPAD_RIGHT_PAREN
  746. C.AKEYCODE_INFO
  747. C.AKEYCODE_CHANNEL_UP
  748. C.AKEYCODE_CHANNEL_DOWN
  749. C.AKEYCODE_ZOOM_IN
  750. C.AKEYCODE_ZOOM_OUT
  751. C.AKEYCODE_TV
  752. C.AKEYCODE_WINDOW
  753. C.AKEYCODE_GUIDE
  754. C.AKEYCODE_DVR
  755. C.AKEYCODE_BOOKMARK
  756. C.AKEYCODE_CAPTIONS
  757. C.AKEYCODE_SETTINGS
  758. C.AKEYCODE_TV_POWER
  759. C.AKEYCODE_TV_INPUT
  760. C.AKEYCODE_STB_POWER
  761. C.AKEYCODE_STB_INPUT
  762. C.AKEYCODE_AVR_POWER
  763. C.AKEYCODE_AVR_INPUT
  764. C.AKEYCODE_PROG_RED
  765. C.AKEYCODE_PROG_GREEN
  766. C.AKEYCODE_PROG_YELLOW
  767. C.AKEYCODE_PROG_BLUE
  768. C.AKEYCODE_APP_SWITCH
  769. C.AKEYCODE_BUTTON_1
  770. C.AKEYCODE_BUTTON_2
  771. C.AKEYCODE_BUTTON_3
  772. C.AKEYCODE_BUTTON_4
  773. C.AKEYCODE_BUTTON_5
  774. C.AKEYCODE_BUTTON_6
  775. C.AKEYCODE_BUTTON_7
  776. C.AKEYCODE_BUTTON_8
  777. C.AKEYCODE_BUTTON_9
  778. C.AKEYCODE_BUTTON_10
  779. C.AKEYCODE_BUTTON_11
  780. C.AKEYCODE_BUTTON_12
  781. C.AKEYCODE_BUTTON_13
  782. C.AKEYCODE_BUTTON_14
  783. C.AKEYCODE_BUTTON_15
  784. C.AKEYCODE_BUTTON_16
  785. C.AKEYCODE_LANGUAGE_SWITCH
  786. C.AKEYCODE_MANNER_MODE
  787. C.AKEYCODE_3D_MODE
  788. C.AKEYCODE_CONTACTS
  789. C.AKEYCODE_CALENDAR
  790. C.AKEYCODE_MUSIC
  791. C.AKEYCODE_CALCULATOR
  792. Defined in an NDK API version beyond what we use today:
  793. C.AKEYCODE_ASSIST
  794. C.AKEYCODE_BRIGHTNESS_DOWN
  795. C.AKEYCODE_BRIGHTNESS_UP
  796. C.AKEYCODE_RO
  797. C.AKEYCODE_YEN
  798. C.AKEYCODE_ZENKAKU_HANKAKU
  799. */