android.go 25 KB

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