summaryrefslogtreecommitdiff
path: root/Xamarin.Forms.Platform.iOS/CADisplayLinkTicker.cs
blob: e910297875994917ebcf86ba8b52091f06c74e06 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
using System;
using System.Collections.Concurrent;
using System.Threading;
using Xamarin.Forms.Internals;
#if __UNIFIED__
using UIKit;
using CoreAnimation;
using Foundation;

#else
using MonoTouch.UIKit;
using MonoTouch.CoreAnimation;
using MonoTouch.Foundation;
#endif

namespace Xamarin.Forms.Platform.iOS
{
	internal class CADisplayLinkTicker : Ticker
	{
		readonly BlockingCollection<Action> _queue = new BlockingCollection<Action>();
		CADisplayLink _link;

		public CADisplayLinkTicker()
		{
			var thread = new Thread(StartThread);
			thread.Start();
		}

		internal new static CADisplayLinkTicker Default
		{
			get { return Ticker.Default as CADisplayLinkTicker; }
		}

		public void Invoke(Action action)
		{
			_queue.Add(action);
		}

		protected override void DisableTimer()
		{
			if (_link != null)
			{
				_link.RemoveFromRunLoop(NSRunLoop.Current, NSRunLoop.NSRunLoopCommonModes);
				_link.Dispose();
			}
			_link = null;
		}

		protected override void EnableTimer()
		{
			_link = CADisplayLink.Create(() => SendSignals());
			_link.AddToRunLoop(NSRunLoop.Current, NSRunLoop.NSRunLoopCommonModes);
		}

		void StartThread()
		{
			while (true)
			{
				var action = _queue.Take();
				var previous = UIApplication.CheckForIllegalCrossThreadCalls;
				UIApplication.CheckForIllegalCrossThreadCalls = false;

				CATransaction.Begin();
				action.Invoke();

				while (_queue.TryTake(out action))
					action.Invoke();
				CATransaction.Commit();

				UIApplication.CheckForIllegalCrossThreadCalls = previous;
			}
		}
	}
}