Welcome to mirror list, hosted at ThFree Co, Russian Federation.

MonoMacMainLoopIntegration.cs « GuiUnit « framework « src - github.com/mono/guiunit.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 4314dbaad139053c366c4cbde3394a8633a446b3 (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
using System;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;

namespace GuiUnit
{
	public class MonoMacMainLoopIntegration : IMainLoopIntegration
	{
		Type Application {
			get; set;
		}

		object SharedApplication {
			get; set;
		}

		public MonoMacMainLoopIntegration ()
		{
			Application =
				Type.GetType ("AppKit.NSApplication, Xamarin.Mac") ??
				Type.GetType ("MonoMac.AppKit.NSApplication, XamMac") ??
				Type.GetType ("MonoMac.AppKit.NSApplication, MonoMac");
			if (Application == null)
				throw new NotSupportedException ();
		}

		public void InitializeToolkit ()
		{
			// First, dlopen libxammac.dylib from the same dir we loaded the Xamarin.Mac dll
			var dylibPath = Path.Combine (Path.GetDirectoryName (Application.Assembly.Location), "libxammac.dylib");
			if (dlopen (dylibPath, 0) == IntPtr.Zero) {
				var errPtr = dlerror ();
				var errStr = (errPtr == IntPtr.Zero)? "<unknown error>" : Marshal.PtrToStringAnsi (errPtr);
				Console.WriteLine ("WARNING: Cannot load {0}: {1}", dylibPath, errStr);
				throw new InvalidOperationException("Unable to initialize Xamarin.Mac");
			}

			var initMethod = Application.GetMethod ("Init", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);
			initMethod.Invoke (null, null);

			var sharedAppProperty = Application.GetProperty ("SharedApplication", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);
			SharedApplication = sharedAppProperty.GetValue (null, null);
		}

		public void InvokeOnMainLoop (InvokerHelper helper)
		{
			var potentialMethods = Application.GetMethods (System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
			var invokeOnMainThreadMethod = potentialMethods.First (m => m.Name == "InvokeOnMainThread" && m.GetParameters ().Length == 1);
			var invoker = Delegate.CreateDelegate (invokeOnMainThreadMethod.GetParameters () [0].ParameterType, helper, "Invoke");
			invokeOnMainThreadMethod.Invoke (SharedApplication, new [] { invoker });
		}

		public void RunMainLoop ()
		{
			Application.GetMethod ("Run").Invoke (SharedApplication, null);
		}

		public void Shutdown (int exitCode)
		{
			Application.GetMethod ("Terminate").Invoke (SharedApplication, new [] { SharedApplication });
		}

		[DllImport ("/usr/lib/libSystem.dylib")]
		static extern IntPtr dlopen (string path, int mode);

		[DllImport ("/usr/lib/libSystem.dylib")]
		static extern IntPtr dlerror ();
	}
}