[NUI] Change GetDefaultWindow() to static func (#900)
[platform/core/csapi/tizenfx.git] / src / Tizen.NUI / src / internal / XamlBinding / Internals / Ticker.cs
1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Diagnostics;
5 using System.Linq;
6 using Tizen.NUI.Binding;
7
8 namespace Tizen.NUI.Binding.Internals
9 {
10     internal abstract class Ticker
11     {
12         static Ticker s_ticker;
13         readonly Stopwatch _stopwatch;
14         readonly List<Tuple<int, Func<long, bool>>> _timeouts;
15
16         int _count;
17         bool _enabled;
18
19         protected Ticker()
20         {
21             _count = 0;
22             _timeouts = new List<Tuple<int, Func<long, bool>>>();
23
24             _stopwatch = new Stopwatch();
25         }
26
27         public static void SetDefault(Ticker ticker) => Default = ticker;
28         public static Ticker Default
29         {
30             internal set { s_ticker = value; }
31             get { return s_ticker ?? (s_ticker =  Device.PlatformServices.CreateTicker()); }
32         }
33
34         public virtual int Insert(Func<long, bool> timeout)
35         {
36             _count++;
37             _timeouts.Add(new Tuple<int, Func<long, bool>>(_count, timeout));
38
39             if (!_enabled)
40             {
41                 _enabled = true;
42                 Enable();
43             }
44
45             return _count;
46         }
47
48         public virtual void Remove(int handle)
49         {
50             Device.BeginInvokeOnMainThread(() =>
51             {
52                 _timeouts.RemoveAll(t => t.Item1 == handle);
53
54                 if (!_timeouts.Any())
55                 {
56                     _enabled = false;
57                     Disable();
58                 }
59             });
60         }
61
62         protected abstract void DisableTimer();
63
64         protected abstract void EnableTimer();
65
66         protected void SendSignals(int timestep = -1)
67         {
68             long step = timestep >= 0 ? timestep : _stopwatch.ElapsedMilliseconds;
69             _stopwatch.Reset();
70             _stopwatch.Start();
71
72             var localCopy = new List<Tuple<int, Func<long, bool>>>(_timeouts);
73             foreach (Tuple<int, Func<long, bool>> timeout in localCopy)
74             {
75                 bool remove = !timeout.Item2(step);
76                 if (remove)
77                     _timeouts.RemoveAll(t => t.Item1 == timeout.Item1);
78             }
79
80             if (!_timeouts.Any())
81             {
82                 _enabled = false;
83                 Disable();
84             }
85         }
86
87         void Disable()
88         {
89             _stopwatch.Reset();
90             DisableTimer();
91         }
92
93         void Enable()
94         {
95             _stopwatch.Start();
96             EnableTimer();
97         }
98     }
99 }