ecere/Android: Initial support for key events (for mouse wheel)
[sdk] / ecere / src / gui / drivers / AndroidInterface.ec
1 namespace gui::drivers;
2
3 import "Window"
4 import "Interface"
5 import "Condition"
6
7 #define uint _uint
8 #define set _set
9 #include <errno.h>
10 #include <locale.h>
11 #include <pthread.h>
12 #include <unistd.h>
13
14 #include <android/configuration.h>
15 #include <android/looper.h>
16 #include <android/native_activity.h>
17 #include <android/sensor.h>
18 #include <android/log.h>
19 #include <android/window.h>
20
21 #include <jni.h>
22 #undef set
23 #undef uint
24
25 #define LOGI(...) ((void)__android_log_print(ANDROID_LOG_INFO, "ecere-app", __VA_ARGS__))
26 #define LOGE(...) ((void)__android_log_print(ANDROID_LOG_ERROR, "ecere-app", __VA_ARGS__))
27 #define LOGW(...) ((void)__android_log_print(ANDROID_LOG_WARN, "ecere-app", __VA_ARGS__))
28 #ifdef _DEBUG
29 #define LOGV(...)  ((void)0)
30 #else
31 #define LOGV(...)  ((void)__android_log_print(ANDROID_LOG_VERBOSE, "ecere-app", __VA_ARGS__))
32 #endif
33
34 // *** NATIVE APP GLUE ********
35 enum LooperID : byte { main = 1, input = 2, user = 3 };
36 enum AppCommand : byte
37 {
38    error = 0, inputChanged, initWindow, termWindow, windowResized, windowRedrawNeeded,
39    contentRectChanged, gainedFocus, lostFocus,
40    configChanged, lowMemory, start, resume, saveState, pause, stop, destroy
41 };
42
43 class AndroidPollSource
44 {
45 public:
46    void * userData;
47    LooperID id;
48    virtual void any_object::process();
49 };
50
51 class AndroidAppGlue : Thread
52 {
53    void* userData;
54    virtual void onAppCmd(AppCommand cmd);
55    virtual int onInputEvent(AInputEvent* event);
56    virtual void main();
57
58    ANativeActivity* activity;
59    AConfiguration* config;
60    void* savedState;
61    uint savedStateSize;
62
63    ALooper* looper;
64    AInputQueue* inputQueue;
65    ANativeWindow* window;
66    ARect contentRect;
67    AppCommand activityState;
68    bool destroyRequested;
69    char * moduleName;
70
71 private:
72    Mutex mutex { };
73    Condition cond { };
74
75    int msgread, msgwrite;
76
77    unsigned int Main()
78    {
79       config = AConfiguration_new();
80       AConfiguration_fromAssetManager(config, activity->assetManager);
81
82       print_cur_config();
83
84       looper = ALooper_prepare(ALOOPER_PREPARE_ALLOW_NON_CALLBACKS);
85       ALooper_addFd(looper, msgread, LooperID::main, ALOOPER_EVENT_INPUT, null, cmdPollSource);
86
87       mutex.Wait();
88       running = true;
89       cond.Signal();
90       mutex.Release();
91
92       main();
93
94       destroy();
95       return 0;
96    }
97
98    void destroy()
99    {
100       free_saved_state();
101       mutex.Wait();
102       if(inputQueue)
103          AInputQueue_detachLooper(inputQueue);
104       AConfiguration_delete(config);
105       destroyed = true;
106       cond.Signal();
107       mutex.Release();
108    }
109
110    AndroidPollSource cmdPollSource
111    {
112       this, main;
113
114       void process()
115       {
116          AppCommand cmd = read_cmd();
117          pre_exec_cmd(cmd);
118          onAppCmd(cmd);
119          post_exec_cmd(cmd);
120       }
121    };
122    AndroidPollSource inputPollSource
123    {
124       this, input;
125
126       void process()
127       {
128          AInputEvent* event = null;
129          if(AInputQueue_getEvent(inputQueue, &event) >= 0)
130          {
131             int handled = 0;
132             LOGV("New input event: type=%d\n", AInputEvent_getType(event));
133             if(AInputQueue_preDispatchEvent(inputQueue, event))
134                return;
135             handled = onInputEvent(event);
136             //AInputQueue_finishEvent(inputQueue, event, handled);
137          }
138          else
139             LOGE("Failure reading next input event: %s\n", strerror(errno));
140       }
141    };
142
143    bool running;
144    bool stateSaved;
145    bool destroyed;
146    AInputQueue* pendingInputQueue;
147    ANativeWindow* pendingWindow;
148    ARect pendingContentRect;
149
150    void free_saved_state()
151    {
152       mutex.Wait();
153       if(savedState)
154          free(savedState);
155       savedState = 0;
156       savedStateSize = 0;
157       mutex.Release();
158    }
159
160    AppCommand read_cmd()
161    {
162       AppCommand cmd;
163       if(read(msgread, &cmd, sizeof(cmd)) == sizeof(cmd))
164       {
165          if(cmd == saveState)
166             free_saved_state();
167          return cmd;
168       }
169       else
170          LOGE("No data on command pipe!");
171       return error;
172    }
173
174    void print_cur_config()
175    {
176       char lang[2], country[2];
177       AConfiguration_getLanguage(config, lang);
178       AConfiguration_getCountry(config, country);
179
180       LOGV("Config: mcc=%d mnc=%d lang=%c%c cnt=%c%c orien=%d touch=%d dens=%d "
181               "keys=%d nav=%d keysHid=%d navHid=%d sdk=%d size=%d long=%d "
182               "modetype=%d modenight=%d",
183               AConfiguration_getMcc(config),
184               AConfiguration_getMnc(config),
185               lang[0], lang[1], country[0], country[1],
186               AConfiguration_getOrientation(config),
187               AConfiguration_getTouchscreen(config),
188               AConfiguration_getDensity(config),
189               AConfiguration_getKeyboard(config),
190               AConfiguration_getNavigation(config),
191               AConfiguration_getKeysHidden(config),
192               AConfiguration_getNavHidden(config),
193               AConfiguration_getSdkVersion(config),
194               AConfiguration_getScreenSize(config),
195               AConfiguration_getScreenLong(config),
196               AConfiguration_getUiModeType(config),
197               AConfiguration_getUiModeNight(config));
198    }
199
200    void pre_exec_cmd(AppCommand cmd)
201    {
202       PrintLn("pre_exec_cmd: ", (int)cmd);
203       switch(cmd)
204       {
205          case inputChanged:
206             mutex.Wait();
207             if(inputQueue)
208                AInputQueue_detachLooper(inputQueue);
209             inputQueue = pendingInputQueue;
210             if(inputQueue)
211                AInputQueue_attachLooper(inputQueue, looper, LooperID::input, null, inputPollSource);
212             cond.Signal();
213             mutex.Release();
214             break;
215          case initWindow:
216             mutex.Wait();
217             window = pendingWindow;
218             cond.Signal();
219             mutex.Release();
220             break;
221          case termWindow:
222             cond.Signal();
223             break;
224          case resume:
225          case start:
226          case pause:
227          case stop:
228             mutex.Wait();
229             activityState = cmd;
230             cond.Signal();
231             mutex.Release();
232             break;
233          case configChanged:
234             AConfiguration_fromAssetManager(config, activity->assetManager);
235             print_cur_config();
236             break;
237          case destroy:
238             destroyRequested = true;
239             break;
240       }
241    }
242
243    void post_exec_cmd(AppCommand cmd)
244    {
245       PrintLn("post_exec_cmd: ", (int)cmd);
246       switch(cmd)
247       {
248          case termWindow:
249             mutex.Wait();
250             window = null;
251             cond.Signal();
252             mutex.Release();
253             break;
254          case saveState:
255             mutex.Wait();
256             stateSaved = true;
257             cond.Signal();
258             mutex.Release();
259             break;
260          case resume:
261             free_saved_state();
262             break;
263       }
264    }
265
266    void write_cmd(AppCommand cmd)
267    {
268       if(write(msgwrite, &cmd, sizeof(cmd)) != sizeof(cmd))
269          LOGE("Failure writing android_app cmd: %s\n", strerror(errno));
270    }
271
272    void set_input(AInputQueue* inputQueue)
273    {
274       mutex.Wait();
275       pendingInputQueue = inputQueue;
276       write_cmd(inputChanged);
277       while(inputQueue != pendingInputQueue)
278          cond.Wait(mutex);
279       mutex.Release();
280    }
281
282    void set_window(ANativeWindow* window)
283    {
284       mutex.Wait();
285       if(pendingWindow)
286          write_cmd(termWindow);
287       pendingWindow = window;
288       if(window)
289          write_cmd(initWindow);
290       while(window != pendingWindow)
291          cond.Wait(mutex);
292       mutex.Release();
293    }
294
295    void set_activity_state(AppCommand cmd)
296    {
297       mutex.Wait();
298       write_cmd(cmd);
299       while(activityState != cmd)
300          cond.Wait(mutex);
301       mutex.Release();
302    }
303
304    void cleanup()
305    {
306       mutex.Wait();
307       write_cmd(destroy);
308       while(!destroyed)
309          cond.Wait(mutex);
310       mutex.Release();
311       close(msgread);
312       close(msgwrite);
313    }
314
315    void setSavedState(void * state, uint size)
316    {
317       if(savedState)
318          free(savedState);
319       savedState = null;
320       if(state)
321       {
322          savedState = malloc(size);
323          savedStateSize = size;
324          memcpy(savedState, state, size);
325       }
326       else
327          savedStateSize = 0;
328    }
329
330    void Create()
331    {
332       int msgpipe[2];
333       if(pipe(msgpipe))
334          LOGE("could not create pipe: %s", strerror(errno));
335       msgread = msgpipe[0];
336       msgwrite = msgpipe[1];
337
338       Thread::Create();
339
340       // Wait for thread to start.
341       mutex.Wait();
342       while(!running) cond.Wait(mutex);
343       mutex.Release();
344    }
345 }
346
347 // Callbacks
348 static void onDestroy(ANativeActivity* activity)
349 {
350    AndroidAppGlue app = (AndroidAppGlue)activity->instance;
351    LOGV("Destroy: %p\n", activity);
352    app.cleanup();
353    app.Wait();
354    delete androidActivity;
355    delete __androidCurrentModule;
356    LOGV("THE END.");
357 }
358
359 static void onStart(ANativeActivity* activity)
360 {
361    AndroidAppGlue app = (AndroidAppGlue)activity->instance;
362    LOGV("Start: %p\n", activity);
363    app.set_activity_state(start);
364 }
365
366 static void onResume(ANativeActivity* activity)
367 {
368    AndroidAppGlue app = (AndroidAppGlue)activity->instance;
369    LOGV("Resume: %p\n", activity);
370    app.set_activity_state(resume);
371 }
372
373 static void* onSaveInstanceState(ANativeActivity* activity, size_t* outLen)
374 {
375    AndroidAppGlue app = (AndroidAppGlue)activity->instance;
376    void* savedState = null;
377    LOGV("SaveInstanceState: %p\n", activity);
378    app.mutex.Wait();
379    app.stateSaved = false;
380    app.write_cmd(saveState);
381    while(!app.stateSaved)
382       app.cond.Wait(app.mutex);
383    if(app.savedState)
384    {
385       savedState = app.savedState;
386       *outLen = app.savedStateSize;
387       app.savedState = null;
388       app.savedStateSize = 0;
389    }
390    app.mutex.Release();
391    return savedState;
392 }
393
394 static void onPause(ANativeActivity* activity)
395 {
396    AndroidAppGlue app = (AndroidAppGlue)activity->instance;
397    LOGV("Pause: %p\n", activity);
398    app.set_activity_state(pause);
399 }
400
401 static void onStop(ANativeActivity* activity)
402 {
403    AndroidAppGlue app = (AndroidAppGlue)activity->instance;
404    LOGV("Stop: %p\n", activity);
405    app.set_activity_state(stop);
406 }
407
408 static void onConfigurationChanged(ANativeActivity* activity)
409 {
410    AndroidAppGlue app = (AndroidAppGlue)activity->instance;
411    LOGV("ConfigurationChanged: %p\n", activity);
412    app.write_cmd(configChanged);
413 }
414
415 static void onLowMemory(ANativeActivity* activity)
416 {
417    AndroidAppGlue app = (AndroidAppGlue)activity->instance;
418    LOGV("LowMemory: %p\n", activity);
419    app.write_cmd(lowMemory);
420 }
421
422 static void onWindowFocusChanged(ANativeActivity* activity, int focused)
423 {
424    AndroidAppGlue app = (AndroidAppGlue)activity->instance;
425    LOGV("WindowFocusChanged: %p -- %d\n", activity, focused);
426    app.write_cmd(focused ? gainedFocus : lostFocus);
427 }
428
429 static void onNativeWindowCreated(ANativeActivity* activity, ANativeWindow* window)
430 {
431    AndroidAppGlue app = (AndroidAppGlue)activity->instance;
432    LOGV("NativeWindowCreated: %p -- %p\n", activity, window);
433    app.set_window(window);
434 }
435
436 static void onNativeWindowDestroyed(ANativeActivity* activity, ANativeWindow* window)
437 {
438    AndroidAppGlue app = (AndroidAppGlue)activity->instance;
439    LOGV("NativeWindowDestroyed: %p -- %p\n", activity, window);
440    app.set_window(null);
441 }
442
443 static void onInputQueueCreated(ANativeActivity* activity, AInputQueue* queue)
444 {
445    AndroidAppGlue app = (AndroidAppGlue)activity->instance;
446    LOGV("InputQueueCreated: %p -- %p\n", activity, queue);
447    app.set_input(queue);
448 }
449
450 static void onInputQueueDestroyed(ANativeActivity* activity, AInputQueue* queue)
451 {
452    AndroidAppGlue app = (AndroidAppGlue)activity->instance;
453    LOGV("InputQueueDestroyed: %p -- %p\n", activity, queue);
454    app.inputQueue = null;
455    app.set_input(null);
456 }
457
458 default dllexport void ANativeActivity_onCreate(ANativeActivity* activity, void* savedState, size_t savedStateSize)
459 {
460    AndroidAppGlue app;
461    char * moduleName;
462
463    // Determine our package name
464    JNIEnv* env=activity->env;
465    jclass clazz;
466    const char* str;
467    jboolean isCopy;
468    jmethodID methodID;
469    jobject result;
470
471    // *** Reinitialize static global variables ***
472    gotInit = false;
473    guiApplicationInitialized = false;
474    guiApp = null;
475    desktopW = 0; desktopH = 0;
476    clipBoardData = null;
477    __thisModule = null;
478    __androidCurrentModule = null;
479
480    LOGV("Creating: %p\n", activity);
481
482    //(*activity->vm)->AttachCurrentThread(activity->vm, &env, 0);
483    clazz = (*env)->GetObjectClass(env, activity->clazz);
484    methodID = (*env)->GetMethodID(env, clazz, "getPackageName", "()Ljava/lang/String;");
485    result = (*env)->CallObjectMethod(env, activity->clazz, methodID);
486    str = (*env)->GetStringUTFChars(env, (jstring)result, &isCopy);
487    // (*activity->vm)->DetachCurrentThread(activity->vm);
488    moduleName = strstr(str, "com.ecere.");
489    if(moduleName) moduleName += 10;
490    androidArgv[0] = moduleName;
491
492    // Create a base Application class
493    __androidCurrentModule = __ecere_COM_Initialize(true, 1, androidArgv);
494    // Load up Ecere
495    eModule_Load(__androidCurrentModule, "ecere", publicAccess);
496
497
498    if(activity->internalDataPath) PrintLn("internalDataPath is ", activity->internalDataPath);
499    if(activity->externalDataPath) PrintLn("externalDataPath is ", activity->externalDataPath);
500    {
501       char tmp[256];
502       PrintLn("cwd is ", GetWorkingDir(tmp, sizeof(tmp)));
503    }
504
505    ANativeActivity_setWindowFlags(activity, AWINDOW_FLAG_FULLSCREEN|AWINDOW_FLAG_KEEP_SCREEN_ON, 0 );
506    app = AndroidActivity { activity = activity, moduleName = moduleName };
507    incref app;
508    app.setSavedState(savedState, savedStateSize);
509    activity->callbacks->onDestroy = onDestroy;
510    activity->callbacks->onStart = onStart;
511    activity->callbacks->onResume = onResume;
512    activity->callbacks->onSaveInstanceState = onSaveInstanceState;
513    activity->callbacks->onPause = onPause;
514    activity->callbacks->onStop = onStop;
515    activity->callbacks->onConfigurationChanged = onConfigurationChanged;
516    activity->callbacks->onLowMemory = onLowMemory;
517    activity->callbacks->onWindowFocusChanged = onWindowFocusChanged;
518    activity->callbacks->onNativeWindowCreated = onNativeWindowCreated;
519    activity->callbacks->onNativeWindowDestroyed = onNativeWindowDestroyed;
520    activity->callbacks->onInputQueueCreated = onInputQueueCreated;
521    activity->callbacks->onInputQueueDestroyed = onInputQueueDestroyed;
522    activity->instance = app;
523    app.Create();
524 }
525
526 // *** END OF NATIVE APP GLUE ******
527
528 default:
529 extern int __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnKeyHit;
530 extern int __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnKeyUp;
531 extern int __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnKeyDown;
532 extern int __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnKeyHit;
533 extern int __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnMouseMove;
534 extern int __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnLeftDoubleClick;
535 extern int __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnLeftButtonDown;
536 extern int __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnLeftButtonUp;
537 extern int __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnMiddleDoubleClick;
538 extern int __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnMiddleButtonDown;
539 extern int __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnMiddleButtonUp;
540 extern int __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnRightDoubleClick;
541 extern int __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnRightButtonDown;
542 extern int __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnRightButtonUp;
543 private:
544
545 static Module __androidCurrentModule;
546 static char * androidArgv[1];
547
548 static int desktopW, desktopH;
549 static char * clipBoardData;
550
551 class AndroidInterface : Interface
552 {
553    class_property(name) = "Android";
554
555    // --- User Interface System ---
556    bool Initialize()
557    {
558       setlocale(LC_ALL, "en_US.UTF-8");
559       return true;
560    }
561
562    void Terminate()
563    {
564
565    }
566
567    #define DBLCLICK_DELAY  300   // 0.3 second
568    #define DBLCLICK_DELTA  1
569
570    bool ProcessInput(bool processAll)
571    {
572       bool eventAvailable = false;
573       if(androidActivity.ident >= 0)
574       {
575          AndroidPollSource source = androidActivity.source;
576          //PrintLn("androidActivity.ident >= 0");
577          // Process this event.
578          androidActivity.ident = 0;
579          androidActivity.source = null;
580          if(source)
581             source.process(source.userData);
582
583          // If a sensor has data, process it now.
584          /*
585          if(androidActivity.ident == user)
586          {
587             if(androidActivity.accelerometerSensor)
588             {
589                ASensorEvent event;
590                while (ASensorEventQueue_getEvents(androidActivity.sensorEventQueue, &event, 1) > 0)
591                   LOGI("accelerometer: x=%f y=%f z=%f", event.acceleration.x, event.acceleration.y, event.acceleration.z);
592             }
593          }
594          */
595          // eventAvailable = true;
596          if(androidActivity.destroyRequested)
597          {
598             guiApp.desktop.Destroy(0);
599             eventAvailable = true;
600          }
601       }
602
603       if(androidActivity.animating)
604          guiApp.desktop.Update(null);
605
606       if(!eventAvailable)
607          return false;
608       return true;
609    }
610
611    void Wait()
612    {
613       androidActivity.ident = (LooperID)ALooper_pollAll(androidActivity.animating ? 0 : -1, null, &androidActivity.events, (void**)&androidActivity.source);
614       // guiApp.WaitEvent();
615    }
616
617    void Lock(Window window)
618    {
619
620    }
621
622    void Unlock(Window window)
623    {
624
625    }
626
627    char ** GraphicsDrivers(int * numDrivers)
628    {
629       static char *graphicsDrivers[] = { "OpenGL" };
630       *numDrivers = sizeof(graphicsDrivers) / sizeof(char *);
631       return (char **)graphicsDrivers;
632    }
633
634    void GetCurrentMode(bool * fullScreen, int * resolution, int * colorDepth, int * refreshRate)
635    {
636       *fullScreen = true;
637    }
638
639    void EnsureFullScreen(bool *fullScreen)
640    {
641       *fullScreen = true;
642    }
643
644    bool ScreenMode(bool fullScreen, int resolution, int colorDepth, int refreshRate, bool * textMode)
645    {
646       bool result = true;
647
648       return result;
649    }
650
651    // --- Window Creation ---
652    void * CreateRootWindow(Window window)
653    {
654       return androidActivity.window;
655    }
656
657    void DestroyRootWindow(Window window)
658    {
659
660    }
661
662    // -- Window manipulation ---
663
664    void SetRootWindowCaption(Window window, char * name)
665    {
666
667    }
668
669    void PositionRootWindow(Window window, int x, int y, int w, int h, bool move, bool resize)
670    {
671
672    }
673
674    void OrderRootWindow(Window window, bool topMost)
675    {
676
677    }
678
679    void SetRootWindowColor(Window window)
680    {
681
682    }
683
684    void OffsetWindow(Window window, int * x, int * y)
685    {
686
687    }
688
689    void UpdateRootWindow(Window window)
690    {
691       if(!window.parent || !window.parent.display)
692       {
693          if(window.visible)
694          {
695             Box box = window.box;
696             box.left -= window.clientStart.x;
697             box.top -= window.clientStart.y;
698             box.right -= window.clientStart.x;
699             box.bottom -= window.clientStart.y;
700             // Logf("Update root window %s\n", window.name);
701             window.Update(null);
702             box.left   += window.clientStart.x;
703             box.top    += window.clientStart.y;
704             box.right  += window.clientStart.x;
705             box.bottom += window.clientStart.y;
706             window.UpdateDirty(box);
707          }
708       }
709    }
710
711
712    void SetRootWindowState(Window window, WindowState state, bool visible)
713    {
714    }
715
716    void FlashRootWindow(Window window)
717    {
718
719    }
720
721    void ActivateRootWindow(Window window)
722    {
723
724    }
725
726    // --- Mouse-based window movement ---
727
728    void StartMoving(Window window, int x, int y, bool fromKeyBoard)
729    {
730
731    }
732
733    void StopMoving(Window window)
734    {
735
736    }
737
738    // -- Mouse manipulation ---
739
740    void GetMousePosition(int *x, int *y)
741    {
742       int rootWindow, childWindow;
743       int mx, my;
744       unsigned int state;
745    }
746
747    void SetMousePosition(int x, int y)
748    {
749
750    }
751
752    void SetMouseRange(Window window, Box box)
753    {
754    }
755
756    void SetMouseCapture(Window window)
757    {
758    }
759
760    // -- Mouse cursor ---
761
762    void SetMouseCursor(int cursor)
763    {
764       if(cursor == -1)
765       {
766
767       }
768    }
769
770    // --- Caret ---
771
772    void SetCaret(int x, int y, int size)
773    {
774       Window caretOwner = guiApp.caretOwner;
775       Window window = caretOwner ? caretOwner.rootWindow : null;
776       if(window && window.windowData)
777       {
778       }
779    }  
780
781    void ClearClipboard()
782    {
783       if(clipBoardData)
784       {
785          delete clipBoardData;
786       }
787    }
788
789    bool AllocateClipboard(ClipBoard clipBoard, uint size)
790    {
791       bool result = false;
792       if((clipBoard.text = new0 byte[size]))
793          result = true;   
794       return result;
795    }
796
797    bool SaveClipboard(ClipBoard clipBoard)
798    {
799       bool result = false;
800       if(clipBoard.text)
801       {
802          if(clipBoardData)
803             delete clipBoardData;
804
805          clipBoardData = clipBoard.text;
806          clipBoard.text = null;
807          result = true;
808       }
809       return result;
810    }
811
812    bool LoadClipboard(ClipBoard clipBoard)
813    {
814       bool result = false;
815
816       // The data is inside this client...
817       if(clipBoardData)
818       {
819          clipBoard.text = new char[strlen(clipBoardData)+1];
820          strcpy(clipBoard.text, clipBoardData);
821          result = true;
822       }
823       // The data is with another client...
824       else
825       {
826       }
827       return result;
828    }
829
830    void UnloadClipboard(ClipBoard clipBoard)
831    {
832       delete clipBoard.text;
833    }
834
835    // --- State based input ---
836
837    bool AcquireInput(Window window, bool state)
838    {
839       return false;
840    }
841
842    bool GetMouseState(MouseButtons * buttons, int * x, int * y)
843    {
844       bool result = false;
845       if(x) *x = 0;
846       if(y) *y = 0;
847       return result;
848    }
849
850    bool GetJoystickState(int device, Joystick joystick)
851    {
852       bool result = false;
853       return result;
854    }
855
856    bool GetKeyState(Key key)
857    {
858       int keyState = 0;
859       return keyState;
860    }
861
862    void SetTimerResolution(uint hertz)
863    {
864       // timerDelay = hertz ? (1000000 / hertz) : MAXINT;
865    }  
866
867    bool SetIcon(Window window, BitmapResource resource)
868    {
869       if(resource)
870       {
871          /*Bitmap bitmap { };
872          if(bitmap.Load(resource.fileName, null, null))
873          {
874          }
875          delete bitmap;*/
876       }
877       return true;
878    }
879 }
880
881 struct SavedState
882 {
883     float angle;
884     int x;
885     int y;
886 };
887
888 static AndroidActivity androidActivity;
889
890 static bool gotInit;
891
892 default float AMotionEvent_getAxisValue(const AInputEvent* motion_event,
893         int32_t axis, size_t pointer_index);
894
895 static Key keyCodeTable[] =
896 {
897     0, //AKEYCODE_UNKNOWN         = 0,
898     0, //AKEYCODE_SOFT_LEFT       = 1,
899     0, //AKEYCODE_SOFT_RIGHT      = 2,
900     0, //AKEYCODE_HOME            = 3,
901     0, //AKEYCODE_BACK            = 4,
902     0, //AKEYCODE_CALL            = 5,
903     0, //AKEYCODE_ENDCALL         = 6,
904     k0, //AKEYCODE_0               = 7,
905     k1, //AKEYCODE_1               = 8,
906     k2, //AKEYCODE_2               = 9,
907     k3, //AKEYCODE_3               = 10,
908     k4, //AKEYCODE_4               = 11,
909     k5, //AKEYCODE_5               = 12,
910     k6, //AKEYCODE_6               = 13,
911     k7, //AKEYCODE_7               = 14,
912     k8, //AKEYCODE_8               = 15,
913     k9, //AKEYCODE_9               = 16,
914     keyPadStar, //AKEYCODE_STAR            = 17,
915     Key { k3, shift = true }, //AKEYCODE_POUND           = 18,
916     wheelDown, //AKEYCODE_DPAD_UP         = 19,
917     wheelUp, //AKEYCODE_DPAD_DOWN       = 20,
918     wheelDown, //AKEYCODE_DPAD_LEFT       = 21,
919     wheelUp, //AKEYCODE_DPAD_RIGHT      = 22,
920     keyPad5, //AKEYCODE_DPAD_CENTER     = 23,
921     0, //AKEYCODE_VOLUME_UP       = 24,
922     0, //AKEYCODE_VOLUME_DOWN     = 25,
923     0, //AKEYCODE_POWER           = 26,
924     0, //AKEYCODE_CAMERA          = 27,
925     0, //AKEYCODE_CLEAR           = 28,
926     a, //AKEYCODE_A               = 29,
927     b, //AKEYCODE_B               = 30,
928     c, //AKEYCODE_C               = 31,
929     d, //AKEYCODE_D               = 32,
930     e, //AKEYCODE_E               = 33,
931     f, //AKEYCODE_F               = 34,
932     g, //AKEYCODE_G               = 35,
933     h, //AKEYCODE_H               = 36,
934     i, //AKEYCODE_I               = 37,
935     j, //AKEYCODE_J               = 38,
936     k, //AKEYCODE_K               = 39,
937     l, //AKEYCODE_L               = 40,
938     m, //AKEYCODE_M               = 41,
939     n, //AKEYCODE_N               = 42,
940     o, //AKEYCODE_O               = 43,
941     p, //AKEYCODE_P               = 44,
942     q, //AKEYCODE_Q               = 45,
943     r, //AKEYCODE_R               = 46,
944     s, //AKEYCODE_S               = 47,
945     t, //AKEYCODE_T               = 48,
946     u, //AKEYCODE_U               = 49,
947     v, //AKEYCODE_V               = 50,
948     w, //AKEYCODE_W               = 51,
949     x, //AKEYCODE_X               = 52,
950     y, //AKEYCODE_Y               = 53,
951     z, //AKEYCODE_Z               = 54,
952     comma, //AKEYCODE_COMMA           = 55,
953     period, //AKEYCODE_PERIOD          = 56,
954     Key { left, alt = true }, //AKEYCODE_ALT_LEFT        = 57,
955     Key { right, alt = true }, //AKEYCODE_ALT_RIGHT       = 58,
956     Key { left, shift = true }, //AKEYCODE_SHIFT_LEFT      = 59,
957     Key { right, shift = true }, //AKEYCODE_SHIFT_RIGHT     = 60,
958     tab, //AKEYCODE_TAB             = 61,
959     space, //AKEYCODE_SPACE           = 62,
960     0, //AKEYCODE_SYM             = 63,
961     0, //AKEYCODE_EXPLORER        = 64,
962     0, //AKEYCODE_ENVELOPE        = 65,
963     enter, //AKEYCODE_ENTER           = 66,
964     del, //AKEYCODE_DEL             = 67,
965     backQuote, //AKEYCODE_GRAVE           = 68,
966     minus, //AKEYCODE_MINUS           = 69,
967     plus, //AKEYCODE_EQUALS          = 70,
968     leftBracket, //AKEYCODE_LEFT_BRACKET    = 71,
969     rightBracket, //AKEYCODE_RIGHT_BRACKET   = 72,
970     backSlash, //AKEYCODE_BACKSLASH       = 73,
971     semicolon, //AKEYCODE_SEMICOLON       = 74,
972     quote, //AKEYCODE_APOSTROPHE      = 75,
973     slash, //AKEYCODE_SLASH           = 76,
974     Key { k2, shift = true }, //AKEYCODE_AT              = 77,
975     0, //AKEYCODE_NUM             = 78,
976     0, //AKEYCODE_HEADSETHOOK     = 79,
977     0, //AKEYCODE_FOCUS           = 80,   // *Camera* focus
978     keyPadPlus, //AKEYCODE_PLUS            = 81,
979     0, //AKEYCODE_MENU            = 82,
980     0, //AKEYCODE_NOTIFICATION    = 83,
981     0, //AKEYCODE_SEARCH          = 84,
982     0, //AKEYCODE_MEDIA_PLAY_PAUSE= 85,
983     0, //AKEYCODE_MEDIA_STOP      = 86,
984     0, //AKEYCODE_MEDIA_NEXT      = 87,
985     0, //AKEYCODE_MEDIA_PREVIOUS  = 88,
986     0, //AKEYCODE_MEDIA_REWIND    = 89,
987     0, //AKEYCODE_MEDIA_FAST_FORWARD = 90,
988     0, //AKEYCODE_MUTE            = 91,
989     0, //AKEYCODE_PAGE_UP         = 92,
990     0, //AKEYCODE_PAGE_DOWN       = 93,
991     0, //AKEYCODE_PICTSYMBOLS     = 94,
992     0, //AKEYCODE_SWITCH_CHARSET  = 95,
993     0, //AKEYCODE_BUTTON_A        = 96,
994     0, //AKEYCODE_BUTTON_B        = 97,
995     0, //AKEYCODE_BUTTON_C        = 98,
996     0, //AKEYCODE_BUTTON_X        = 99,
997     0, //AKEYCODE_BUTTON_Y        = 100,
998     0, //AKEYCODE_BUTTON_Z        = 101,
999     0, //AKEYCODE_BUTTON_L1       = 102,
1000     0, //AKEYCODE_BUTTON_R1       = 103,
1001     0, //AKEYCODE_BUTTON_L2       = 104,
1002     0, //AKEYCODE_BUTTON_R2       = 105,
1003     0, //AKEYCODE_BUTTON_THUMBL   = 106,
1004     0, //AKEYCODE_BUTTON_THUMBR   = 107,
1005     0, //AKEYCODE_BUTTON_START    = 108,
1006     0, //AKEYCODE_BUTTON_SELECT   = 109,
1007     0, //AKEYCODE_BUTTON_MODE     = 110,
1008 };
1009
1010 class AndroidActivity : AndroidAppGlue
1011 {
1012    AndroidPollSource source;
1013    int events;
1014    LooperID ident;
1015    /*
1016    ASensorManager* sensorManager;
1017    const ASensor* accelerometerSensor;
1018    ASensorEventQueue* sensorEventQueue;
1019    */
1020    bool animating;
1021    SavedState state;
1022
1023    int onInputEvent(AInputEvent* event)
1024    {
1025       Window window = guiApp.desktop;
1026       uint type = AInputEvent_getType(event);
1027       if(type == AINPUT_EVENT_TYPE_MOTION)
1028       {
1029          uint actionAndIndex = AMotionEvent_getAction(event);
1030          uint source = AInputEvent_getSource(event);
1031          uint action = actionAndIndex & AMOTION_EVENT_ACTION_MASK;
1032          uint index  = (actionAndIndex & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
1033          uint flags = AMotionEvent_getFlags(event);
1034          uint meta = AMotionEvent_getMetaState(event);
1035          uint edge = AMotionEvent_getEdgeFlags(event);
1036          int64 downTime = AMotionEvent_getDownTime(event);     // nanotime
1037          int64 eventTime = AMotionEvent_getDownTime(event);
1038          //float axis;
1039          Modifiers keyFlags = 0;
1040          int x = (int)AMotionEvent_getX(event, 0);
1041          int y = (int)AMotionEvent_getY(event, 0);
1042          //PrintLn("Got a motion input event: ", action);
1043          /*
1044          if(action == 8) //AMOTION_EVENT_ACTION_SCROLL)
1045             axis = AMotionEvent_getAxisValue(event, 9, index); //AMOTION_EVENT_AXIS_VSCROLL); 
1046          */
1047
1048          AInputQueue_finishEvent(inputQueue, event, 1);
1049          switch(action)
1050          {
1051             /*
1052             case 8: //AMOTION_EVENT_ACTION_SCROLL:
1053                window.KeyMessage(__ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnKeyHit, (axis < 0) ? wheelUp : wheelDown, 0);
1054                break;
1055                */
1056             case AMOTION_EVENT_ACTION_DOWN:
1057                window.MouseMessage(__ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnLeftButtonDown, x, y, &keyFlags, false, true);
1058                break;
1059             case AMOTION_EVENT_ACTION_UP:
1060                window.MouseMessage(__ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnLeftButtonUp, x, y, &keyFlags, false, true);
1061                break;
1062             case AMOTION_EVENT_ACTION_MOVE:
1063                window.MouseMessage(__ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnMouseMove, x, y, &keyFlags, false, true);
1064                break;
1065             case AMOTION_EVENT_ACTION_CANCEL: break;
1066             case AMOTION_EVENT_ACTION_OUTSIDE: break;
1067             case AMOTION_EVENT_ACTION_POINTER_DOWN: break;
1068             case AMOTION_EVENT_ACTION_POINTER_UP: break;
1069          }
1070
1071          animating = true;
1072          return 1;
1073       }
1074       else if(type == AINPUT_EVENT_TYPE_KEY)
1075       {
1076          uint action = AKeyEvent_getAction(event);
1077          uint flags = AKeyEvent_getFlags(event);
1078          uint keyCode = AKeyEvent_getKeyCode(event);
1079          uint meta = AKeyEvent_getMetaState(event);
1080          Key key = keyCodeTable[keyCode];
1081
1082          AInputQueue_finishEvent(inputQueue, event, 1);
1083
1084          //PrintLn("Got a key: action = ", action, ", flags = ", flags, ", keyCode = ", keyCode, ", meta = ", meta, ": key = ", (int)key);
1085
1086          if(key)
1087          {
1088             if(action == AKEY_STATE_DOWN)
1089             {
1090                window.KeyMessage(__ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnKeyHit, key, 0);
1091             }
1092          }
1093          return 1;
1094       }
1095       else
1096          AInputQueue_finishEvent(inputQueue, event, 0);
1097       return 0;
1098    }
1099
1100    void onAppCmd(AppCommand cmd)
1101    {
1102       switch(cmd)
1103       {
1104          case saveState:
1105             setSavedState(&state, sizeof(state));
1106             break;
1107          case initWindow:
1108             if(window)
1109             {
1110                int w, h;
1111                gotInit = true;
1112                PrintLn("onAppCmd: initWindow");
1113                ANativeWindow_setBuffersGeometry(window, 0, 0, 0); //format);
1114                w = ANativeWindow_getWidth(window);
1115                h = ANativeWindow_getHeight(window);
1116                guiApp.Initialize(false);
1117                guiApp.desktop.windowHandle = window;
1118                guiApp.interfaceDriver = null;
1119                guiApp.SwitchMode(true, null, 0, 0, 0, null, false);
1120
1121                if(desktopW != w || desktopH != h)
1122                {
1123                   guiApp.SetDesktopPosition(0, 0, w, h, true);
1124                   desktopW = w;
1125                   desktopH = h;
1126                }
1127                guiApp.desktop.Update(null);
1128             }
1129             break;
1130          case termWindow:
1131             animating = false;
1132             guiApp.desktop.UnloadGraphics(false);
1133             break;
1134          case gainedFocus:
1135             androidActivity.animating = true;
1136             guiApp.SetAppFocus(true);
1137             /*
1138             if(accelerometerSensor)
1139             {
1140                ASensorEventQueue_enableSensor(sensorEventQueue, accelerometerSensor);
1141                ASensorEventQueue_setEventRate(sensorEventQueue, accelerometerSensor, (1000L/60)*1000);
1142             }
1143             */
1144             break;
1145          case lostFocus:
1146             /*
1147             if(accelerometerSensor)
1148                ASensorEventQueue_disableSensor(sensorEventQueue, accelerometerSensor);
1149             */
1150             animating = false;
1151             guiApp.SetAppFocus(false);
1152             guiApp.desktop.Update(null);
1153             break;
1154       }
1155    }
1156
1157    void main()
1158    {
1159       androidActivity = this;
1160       /* Let's have fun with sensors when we have an actual device to play with
1161       sensorManager = ASensorManager_getInstance();
1162       accelerometerSensor = ASensorManager_getDefaultSensor(sensorManager, ASENSOR_TYPE_ACCELEROMETER);
1163       sensorEventQueue = ASensorManager_createEventQueue(sensorManager, looper, LooperID::user, null, null);
1164       */
1165
1166       if(savedState)
1167          state = *(SavedState*)savedState;
1168
1169       {
1170          Module app;
1171           
1172          // Evolve the Application class into a GuiApplication
1173          eInstance_Evolve((Instance *)&__androidCurrentModule, class(GuiApplication));
1174
1175          // Wait for the initWindow command:
1176          guiApp.interfaceDriver = class(AndroidInterface);
1177          while(!gotInit)
1178          {
1179             // Can't call the GuiApplication here, because GuiApplication::Initialize() has not been called yet
1180             guiApp.interfaceDriver.Wait();
1181             guiApp.interfaceDriver.ProcessInput(true);
1182          }
1183
1184          // Invoke __ecereDll_Load() in lib[our package name].so
1185          app = eModule_Load(__androidCurrentModule, moduleName, publicAccess);
1186          if(app)
1187          {
1188             Class c;
1189             // Find out if any GuiApplication class was defined in our module
1190             for(c = app.classes.first; c && !eClass_IsDerived(c, class(GuiApplication)); c = c.next);
1191             if(!c) c = class(GuiApplication);
1192
1193             // Evolve the Application into it
1194             eInstance_Evolve((Instance *)&__androidCurrentModule, c);
1195             guiApp = (GuiApplication)__androidCurrentModule;
1196
1197             {
1198                String skin = guiApp.skin;
1199                *&guiApp.currentSkin = null;
1200                guiApp.SelectSkin(skin);
1201             }
1202
1203             // Call Main()
1204             __androidCurrentModule._vTbl[12](__androidCurrentModule);
1205          }
1206
1207          if(!destroyRequested)
1208             ANativeActivity_finish(activity);
1209          while(!destroyRequested)
1210          {
1211             guiApp.interfaceDriver.Wait();
1212             guiApp.interfaceDriver.ProcessInput(true);
1213          }
1214       }
1215    }
1216 }