Introduce ElmSharp project
[platform/core/csapi/tizenfx.git] / src / ElmSharp / ElmSharp / EcoreMainloop.cs
1 using System;
2 using System.Collections.Generic;
3
4 namespace ElmSharp
5 {
6     public static class EcoreMainloop
7     {
8         static readonly Dictionary<int, Func<bool>> _taskMap = new Dictionary<int, Func<bool>>();
9         static readonly Object _taskLock = new Object();
10         static int _newTaskId = 0;
11
12
13         static Interop.Ecore.EcoreTaskCallback _nativeHandler;
14
15         static EcoreMainloop()
16         {
17             Interop.Ecore.ecore_init();
18             Interop.Ecore.ecore_main_loop_glib_integrate();
19             _nativeHandler = NativeHandler;
20         }
21
22         public static void Begin()
23         {
24             Interop.Ecore.ecore_main_loop_begin();
25         }
26
27         public static void Quit()
28         {
29             Interop.Ecore.ecore_main_loop_quit();
30         }
31
32         public static void Post(Action task)
33         {
34             int id = RegistHandler(() => { task(); return false; });
35             Interop.Ecore.ecore_idler_add(_nativeHandler, (IntPtr)id);
36         }
37
38         public static void PostAndWakeUp(Action task)
39         {
40             int id = RegistHandler(() => { task(); return false; });
41             Interop.Ecore.ecore_main_loop_thread_safe_call_async(_nativeHandler, (IntPtr)id);
42         }
43
44         public static void Send(Action task)
45         {
46             int id = RegistHandler(() => { task(); return false; });
47             Interop.Ecore.ecore_main_loop_thread_safe_call_sync(_nativeHandler, (IntPtr)id);
48         }
49
50         public static IntPtr AddTimer(double interval, Func<bool> handler)
51         {
52             int id = RegistHandler(handler);
53             return Interop.Ecore.ecore_timer_add(interval, _nativeHandler, (IntPtr)id);
54         }
55
56         public static void RemoveTimer(IntPtr id)
57         {
58             int taskId = (int)Interop.Ecore.ecore_timer_del(id);
59             _taskMap.Remove(taskId);
60         }
61
62         static int RegistHandler(Func<bool> task)
63         {
64             int taskId;
65             lock (_taskLock)
66             {
67                 taskId = _newTaskId++;
68             }
69             _taskMap[taskId] = task;
70             return taskId;
71         }
72
73         static bool NativeHandler(IntPtr user_data)
74         {
75             int task_id = (int)user_data;
76             Func<bool> userAction = null;
77             _taskMap.TryGetValue(task_id, out userAction);
78             if (userAction != null)
79             {
80                 _taskMap.Remove(task_id);
81                 return userAction();
82             }
83             return false;
84         }
85
86     }
87 }