General cleanup of OSX in OpenTK, may break things.

This commit is contained in:
UnknownShadow200 2015-11-04 09:33:45 +11:00
parent 62f1ca71d6
commit c169a9707d
11 changed files with 272 additions and 808 deletions

View File

@ -34,6 +34,25 @@ namespace Launcher2 {
} }
} }
// TODO: broken
public sealed class OSXPlatformDrawer : PlatformDrawer {
Graphics g;
public override void Init( IWindowInfo info ) {
g = Graphics.FromHwnd( info.WinHandle );
}
public override void Resize( IWindowInfo info ) {
if( g != null )
g.Dispose();
g = Graphics.FromHwnd( info.WinHandle );
}
public override void Draw( IWindowInfo info, Bitmap framebuffer ) {
g.DrawImage( framebuffer, 0, 0, framebuffer.Width, framebuffer.Height );
}
}
public sealed class X11PlatformDrawer : PlatformDrawer { public sealed class X11PlatformDrawer : PlatformDrawer {
IntPtr gc; IntPtr gc;

View File

@ -58,8 +58,8 @@ namespace Launcher2 {
platformDrawer = new WinPlatformDrawer(); platformDrawer = new WinPlatformDrawer();
else if( Configuration.RunningOnX11 ) else if( Configuration.RunningOnX11 )
platformDrawer = new X11PlatformDrawer(); platformDrawer = new X11PlatformDrawer();
else else if( Configuration.RunningOnMacOS )
platformDrawer = new WinPlatformDrawer(); // TODO: mac osx support platformDrawer = new OSXPlatformDrawer();
} }
void FocusedChanged( object sender, EventArgs e ) { void FocusedChanged( object sender, EventArgs e ) {

View File

@ -5,11 +5,6 @@ namespace OpenTK {
/// <summary> Placeholder for System.Diagnostics.Debug class because it crashes on some Mono version on Linux. </summary> /// <summary> Placeholder for System.Diagnostics.Debug class because it crashes on some Mono version on Linux. </summary>
public static class Debug { public static class Debug {
public static void Assert( bool condition ) {
if( !condition )
throw new InvalidOperationException( "Assertion failed!" );
}
public static void Print( string text ) { public static void Print( string text ) {
Console.WriteLine( text ); Console.WriteLine( text );
} }

View File

@ -106,32 +106,15 @@ namespace OpenTK.Platform.MacOS {
Update(carbonWindow); Update(carbonWindow);
MakeCurrent(carbonWindow); MakeCurrent(carbonWindow);
Debug.Print("context: {0}", ContextHandle); Debug.Print("context: {0}", ContextHandle);
} }
private IntPtr GetQuartzDevice(CarbonWindowInfo carbonWindow) private IntPtr GetQuartzDevice( CarbonWindowInfo carbonWindow ) {
{ CarbonGLNative nativeWindow = carbonWindow.nativeWindow;
IntPtr windowRef = carbonWindow.WindowRef; return QuartzDisplayDeviceDriver.HandleTo( nativeWindow.TargetDisplayDevice );
if (!CarbonGLNative.WindowRefMap.ContainsKey(windowRef))
return IntPtr.Zero;
WeakReference nativeRef = CarbonGLNative.WindowRefMap[windowRef];
if (!nativeRef.IsAlive)
return IntPtr.Zero;
CarbonGLNative window = nativeRef.Target as CarbonGLNative;
if (window == null)
return IntPtr.Zero;
return QuartzDisplayDeviceDriver.HandleTo(window.TargetDisplayDevice);
} }
void SetDrawable(CarbonWindowInfo carbonWindow) void SetDrawable(CarbonWindowInfo carbonWindow) {
{
IntPtr windowPort = API.GetWindowPort(carbonWindow.WindowRef); IntPtr windowPort = API.GetWindowPort(carbonWindow.WindowRef);
//Debug.Print("Setting drawable for context {0} to window port: {1}", Handle.Handle, windowPort); //Debug.Print("Setting drawable for context {0} to window port: {1}", Handle.Handle, windowPort);
@ -139,14 +122,12 @@ namespace OpenTK.Platform.MacOS {
Agl.CheckReturnValue( code, "aglSetDrawable" ); Agl.CheckReturnValue( code, "aglSetDrawable" );
} }
public override void Update(IWindowInfo window) public override void Update(IWindowInfo window) {
{ CarbonWindowInfo winInfo = (CarbonWindowInfo)window;
CarbonWindowInfo carbonWindow = (CarbonWindowInfo)window;
if (carbonWindow.goFullScreenHack) if (winInfo.goFullScreenHack) {
{ winInfo.goFullScreenHack = false;
carbonWindow.goFullScreenHack = false; CarbonGLNative wind = winInfo.nativeWindow;
CarbonGLNative wind = GetCarbonWindow(carbonWindow);
if (wind != null) if (wind != null)
wind.SetFullscreen(this); wind.SetFullscreen(this);
@ -154,11 +135,9 @@ namespace OpenTK.Platform.MacOS {
Debug.Print("Could not find window!"); Debug.Print("Could not find window!");
return; return;
} } else if (winInfo.goWindowedHack) {
else if (carbonWindow.goWindowedHack) winInfo.goWindowedHack = false;
{ CarbonGLNative wind = winInfo.nativeWindow;
carbonWindow.goWindowedHack = false;
CarbonGLNative wind = GetCarbonWindow(carbonWindow);
if (wind != null) if (wind != null)
wind.UnsetFullscreen(this); wind.UnsetFullscreen(this);
@ -170,22 +149,13 @@ namespace OpenTK.Platform.MacOS {
if (mIsFullscreen) if (mIsFullscreen)
return; return;
SetDrawable(carbonWindow); SetDrawable(winInfo);
Agl.aglUpdateContext(ContextHandle); Agl.aglUpdateContext(ContextHandle);
} }
private CarbonGLNative GetCarbonWindow(CarbonWindowInfo carbonWindow)
{
WeakReference r = CarbonGLNative.WindowRefMap[carbonWindow.WindowRef];
return r.IsAlive ? (CarbonGLNative)r.Target : null;
}
bool firstFullScreen = false; bool firstFullScreen = false;
internal void SetFullScreen(CarbonWindowInfo info, out int width, out int height) internal void SetFullScreen(CarbonWindowInfo info, out int width, out int height) {
{ CarbonGLNative wind = info.nativeWindow;
CarbonGLNative wind = GetCarbonWindow(info);
Debug.Print("Switching to full screen {0}x{1} on context {2}", Debug.Print("Switching to full screen {0}x{1} on context {2}",
wind.TargetDisplayDevice.Width, wind.TargetDisplayDevice.Height, ContextHandle); wind.TargetDisplayDevice.Width, wind.TargetDisplayDevice.Height, ContextHandle);
@ -205,12 +175,10 @@ namespace OpenTK.Platform.MacOS {
UnsetFullScreen(info); UnsetFullScreen(info);
SetFullScreen(info, out width, out height); SetFullScreen(info, out width, out height);
} }
mIsFullscreen = true; mIsFullscreen = true;
} }
internal void UnsetFullScreen(CarbonWindowInfo windowInfo) internal void UnsetFullScreen(CarbonWindowInfo windowInfo) {
{
Debug.Print("Unsetting AGL fullscreen."); Debug.Print("Unsetting AGL fullscreen.");
byte code = Agl.aglSetDrawable(ContextHandle, IntPtr.Zero); byte code = Agl.aglSetDrawable(ContextHandle, IntPtr.Zero);
Agl.CheckReturnValue( code, "aglSetDrawable" ); Agl.CheckReturnValue( code, "aglSetDrawable" );
@ -224,7 +192,6 @@ namespace OpenTK.Platform.MacOS {
mIsFullscreen = false; mIsFullscreen = false;
} }
#region IGraphicsContext Members #region IGraphicsContext Members
public override void SwapBuffers() { public override void SwapBuffers() {

View File

@ -12,41 +12,35 @@ using System.Collections.Generic;
using System.IO; using System.IO;
using System.Text; using System.Text;
namespace OpenTK.Platform.MacOS.Carbon namespace OpenTK.Platform.MacOS.Carbon {
{
static class Application static class Application {
{
static bool mInitialized = false; static bool mInitialized = false;
static IntPtr uppHandler; static IntPtr uppHandler;
static CarbonGLNative eventHandler; public static CarbonGLNative WindowEventHandler;
static int osMajor, osMinor, osBugfix; static int osMajor, osMinor, osBugfix;
static Application() static Application() {
{
Initialize(); Initialize();
} }
internal static void Initialize() internal static void Initialize() {
{
if (mInitialized) return; if (mInitialized) return;
API.AcquireRootMenu(); API.AcquireRootMenu();
ConnectEvents(); ConnectEvents();
API.Gestalt(GestaltSelector.SystemVersionMajor, out osMajor); API.Gestalt(GestaltSelector.SystemVersionMajor, out osMajor);
API.Gestalt(GestaltSelector.SystemVersionMinor, out osMinor); API.Gestalt(GestaltSelector.SystemVersionMinor, out osMinor);
API.Gestalt(GestaltSelector.SystemVersionBugFix, out osBugfix); API.Gestalt(GestaltSelector.SystemVersionBugFix, out osBugfix);
Debug.Print("Running on Mac OS X {0}.{1}.{2}.", osMajor, osMinor, osBugfix); Debug.Print("Running on Mac OS X {0}.{1}.{2}.", osMajor, osMinor, osBugfix);
TransformProcessToForeground(); TransformProcessToForeground();
} }
private static void TransformProcessToForeground() private static void TransformProcessToForeground() {
{
Carbon.ProcessSerialNumber psn = new ProcessSerialNumber(); Carbon.ProcessSerialNumber psn = new ProcessSerialNumber();
Debug.Print("Setting process to be foreground application."); Debug.Print("Setting process to be foreground application.");
API.GetCurrentProcess(ref psn); API.GetCurrentProcess(ref psn);
@ -54,16 +48,8 @@ namespace OpenTK.Platform.MacOS.Carbon
API.SetFrontProcess(ref psn); API.SetFrontProcess(ref psn);
} }
internal static CarbonGLNative WindowEventHandler static void ConnectEvents() {
{ EventTypeSpec[] eventTypes = new EventTypeSpec[] {
get { return eventHandler; }
set { eventHandler = value; }
}
static void ConnectEvents()
{
EventTypeSpec[] eventTypes = new EventTypeSpec[]
{
new EventTypeSpec(EventClass.Application, AppEventKind.AppActivated), new EventTypeSpec(EventClass.Application, AppEventKind.AppActivated),
new EventTypeSpec(EventClass.Application, AppEventKind.AppDeactivated), new EventTypeSpec(EventClass.Application, AppEventKind.AppDeactivated),
new EventTypeSpec(EventClass.Application, AppEventKind.AppQuit), new EventTypeSpec(EventClass.Application, AppEventKind.AppQuit),
@ -89,23 +75,12 @@ namespace OpenTK.Platform.MacOS.Carbon
API.InstallApplicationEventHandler( API.InstallApplicationEventHandler(
uppHandler, eventTypes, IntPtr.Zero, IntPtr.Zero); uppHandler, eventTypes, IntPtr.Zero, IntPtr.Zero);
mInitialized = true; mInitialized = true;
} }
static OSStatus EventHandler(IntPtr inCaller, IntPtr inEvent, IntPtr userData) static OSStatus EventHandler(IntPtr inCaller, IntPtr inEvent, IntPtr userData) {
{
EventInfo evt = new EventInfo(inEvent); EventInfo evt = new EventInfo(inEvent);
switch (evt.EventClass) {
switch (evt.EventClass)
{
case EventClass.Application:
switch (evt.AppEventKind)
{
default:
return OSStatus.EventNotHandled;
}
case EventClass.AppleEvent: case EventClass.AppleEvent:
// only event here is the apple event. // only event here is the apple event.
Debug.Print("Processing apple event."); Debug.Print("Processing apple event.");
@ -115,35 +90,10 @@ namespace OpenTK.Platform.MacOS.Carbon
case EventClass.Keyboard: case EventClass.Keyboard:
case EventClass.Mouse: case EventClass.Mouse:
if (WindowEventHandler != null) if (WindowEventHandler != null)
{
return WindowEventHandler.DispatchEvent(inCaller, inEvent, evt, userData); return WindowEventHandler.DispatchEvent(inCaller, inEvent, evt, userData);
}
break; break;
} }
return OSStatus.EventNotHandled; return OSStatus.EventNotHandled;
} }
public static void Run(CarbonGLNative window)
{
window.Closed += MainWindowClosed;
window.Visible = true;
API.RunApplicationEventLoop();
window.Closed -= MainWindowClosed;
}
static void MainWindowClosed(object sender, EventArgs e)
{
Debug.Print("Quitting application event loop.");
API.QuitApplicationEventLoop();
}
internal static void ProcessEvents()
{
API.ProcessEvents();
}
} }
} }

View File

@ -354,8 +354,7 @@ namespace OpenTK.Platform.MacOS.Carbon
StandardFloating = (CloseBox | CollapseBox) StandardFloating = (CloseBox | CollapseBox)
} }
internal enum WindowPositionMethod : uint internal enum WindowPositionMethod : uint {
{
CenterOnMainScreen = 1, CenterOnMainScreen = 1,
CenterOnParentWindow = 2, CenterOnParentWindow = 2,
CenterOnParentWindowScreen = 3, CenterOnParentWindowScreen = 3,
@ -370,8 +369,7 @@ namespace OpenTK.Platform.MacOS.Carbon
internal delegate OSStatus MacOSEventHandler(IntPtr inCaller, IntPtr inEvent, IntPtr userData); internal delegate OSStatus MacOSEventHandler(IntPtr inCaller, IntPtr inEvent, IntPtr userData);
internal enum WindowPartCode : short internal enum WindowPartCode : short {
{
inDesk = 0, inDesk = 0,
inNoWindow = 0, inNoWindow = 0,
inMenuBar = 1, inMenuBar = 1,
@ -402,13 +400,11 @@ namespace OpenTK.Platform.MacOS.Carbon
#endregion #endregion
#region --- Process Manager --- #region --- Process Manager ---
enum ProcessApplicationTransformState : int enum ProcessApplicationTransformState : int {
{
kProcessTransformToForegroundApplication = 1, kProcessTransformToForegroundApplication = 1,
} }
struct ProcessSerialNumber struct ProcessSerialNumber {
{
public ulong high; public ulong high;
public ulong low; public ulong low;
} }
@ -437,23 +433,8 @@ namespace OpenTK.Platform.MacOS.Carbon
#region --- Window Construction --- #region --- Window Construction ---
[DllImport(carbon,EntryPoint="CreateNewWindow")] [DllImport(carbon)]
private static extern OSStatus _CreateNewWindow(WindowClass @class, WindowAttributes attributes, ref Rect r, out IntPtr window); internal static extern OSStatus CreateNewWindow(WindowClass @class, WindowAttributes attributes, ref Rect r, out IntPtr window);
internal static IntPtr CreateNewWindow(WindowClass @class, WindowAttributes attributes, Rect r)
{
IntPtr retval;
OSStatus stat = _CreateNewWindow(@class, attributes, ref r, out retval);
Debug.Print("Created Window: {0}", retval);
if (stat != OSStatus.NoError)
{
throw new MacOSException(stat);
}
return retval;
}
[DllImport(carbon)] [DllImport(carbon)]
internal static extern void DisposeWindow(IntPtr window); internal static extern void DisposeWindow(IntPtr window);
@ -482,15 +463,11 @@ namespace OpenTK.Platform.MacOS.Carbon
[DllImport(carbon)] [DllImport(carbon)]
static extern OSStatus GetWindowBounds(IntPtr window, WindowRegionCode regionCode, out Rect globalBounds); static extern OSStatus GetWindowBounds(IntPtr window, WindowRegionCode regionCode, out Rect globalBounds);
internal static Rect GetWindowBounds(IntPtr window, WindowRegionCode regionCode) internal static Rect GetWindowBounds(IntPtr window, WindowRegionCode regionCode) {
{ Rect rect;
Rect retval; OSStatus result = GetWindowBounds(window, regionCode, out rect);
OSStatus result = GetWindowBounds(window, regionCode, out retval); CheckReturn(result);
return rect;
if (result != OSStatus.NoError)
throw new MacOSException(result);
return retval;
} }
//[DllImport(carbon)] //[DllImport(carbon)]
@ -502,11 +479,9 @@ namespace OpenTK.Platform.MacOS.Carbon
[DllImport(carbon)] [DllImport(carbon)]
static extern IntPtr GetEventDispatcherTarget(); static extern IntPtr GetEventDispatcherTarget();
[DllImport(carbon,EntryPoint="ReceiveNextEvent")] [DllImport(carbon)]
static extern OSStatus ReceiveNextEvent(uint inNumTypes, static extern OSStatus ReceiveNextEvent(uint inNumTypes, IntPtr inList,
IntPtr inList, double inTimeout, bool inPullEvent,
double inTimeout,
bool inPullEvent,
out IntPtr outEvent); out IntPtr outEvent);
[DllImport(carbon)] [DllImport(carbon)]
@ -515,56 +490,37 @@ namespace OpenTK.Platform.MacOS.Carbon
[DllImport(carbon)] [DllImport(carbon)]
static extern void ReleaseEvent(IntPtr theEvent); static extern void ReleaseEvent(IntPtr theEvent);
internal static void SendEvent(IntPtr theEvent) internal static void SendEvent(IntPtr theEvent) {
{
IntPtr theTarget = GetEventDispatcherTarget(); IntPtr theTarget = GetEventDispatcherTarget();
SendEventToEventTarget(theEvent, theTarget); SendEventToEventTarget(theEvent, theTarget);
} }
// Processes events in the queue and then returns. // Processes events in the queue and then returns.
internal static void ProcessEvents() internal static void ProcessEvents() {
{
IntPtr theEvent; IntPtr theEvent;
IntPtr theTarget = GetEventDispatcherTarget(); IntPtr theTarget = GetEventDispatcherTarget();
for (;;) for (;;) {
{
OSStatus status = ReceiveNextEvent(0, IntPtr.Zero, 0.0, true, out theEvent); OSStatus status = ReceiveNextEvent(0, IntPtr.Zero, 0.0, true, out theEvent);
if (status == OSStatus.EventLoopTimedOut) if (status == OSStatus.EventLoopTimedOut)
break; break;
if (status != OSStatus.NoError) if (status != OSStatus.NoError) {
{
Debug.Print("Message Loop status: {0}", status); Debug.Print("Message Loop status: {0}", status);
break; break;
} }
if (theEvent == IntPtr.Zero) if (theEvent == IntPtr.Zero)
break; break;
try
{
SendEventToEventTarget(theEvent, theTarget); SendEventToEventTarget(theEvent, theTarget);
}
catch (System.ExecutionEngineException e)
{
Console.Error.WriteLine("ExecutionEngineException caught.");
Console.Error.WriteLine("theEvent: " + new EventInfo(theEvent).ToString());
Console.Error.WriteLine(e.Message);
Console.Error.WriteLine(e.StackTrace);
}
ReleaseEvent(theEvent); ReleaseEvent(theEvent);
} }
} }
#region --- Processing apple event ---
[StructLayout(LayoutKind.Sequential)] [StructLayout(LayoutKind.Sequential)]
struct EventRecord {
struct EventRecord
{
public ushort what; public ushort what;
public uint message; public uint message;
public uint when; public uint when;
@ -578,33 +534,15 @@ namespace OpenTK.Platform.MacOS.Carbon
[DllImport(carbon)] [DllImport(carbon)]
static extern OSStatus AEProcessAppleEvent(ref EventRecord theEventRecord); static extern OSStatus AEProcessAppleEvent(ref EventRecord theEventRecord);
static internal void ProcessAppleEvent(IntPtr inEvent) internal static void ProcessAppleEvent(IntPtr inEvent) {
{
EventRecord record; EventRecord record;
ConvertEventRefToEventRecord(inEvent, out record); ConvertEventRefToEventRecord(inEvent, out record);
AEProcessAppleEvent(ref record); AEProcessAppleEvent(ref record);
} }
#endregion #endregion
#endregion #region --- Event handlers ---
#region --- Getting Event Parameters ---
[DllImport(carbon)]
static extern OSStatus CreateEvent( IntPtr inAllocator,
EventClass inClassID, UInt32 kind, EventTime when,
EventAttributes flags, out IntPtr outEvent);
internal static IntPtr CreateWindowEvent(WindowEventKind kind) {
IntPtr retval;
OSStatus stat = CreateEvent(IntPtr.Zero, EventClass.Window, (uint)kind,
0, EventAttributes.kEventAttributeNone, out retval);
if (stat != OSStatus.NoError)
throw new MacOSException(stat);
return retval;
}
[DllImport(carbon)] [DllImport(carbon)]
static extern OSStatus GetEventParameter( static extern OSStatus GetEventParameter(
@ -616,9 +554,7 @@ namespace OpenTK.Platform.MacOS.Carbon
OSStatus result = API.GetEventParameter(inEvent, OSStatus result = API.GetEventParameter(inEvent,
EventParamName.KeyCode, EventParamType.typeUInt32, IntPtr.Zero, EventParamName.KeyCode, EventParamType.typeUInt32, IntPtr.Zero,
sizeof(uint), IntPtr.Zero, (IntPtr)(void*)&code); sizeof(uint), IntPtr.Zero, (IntPtr)(void*)&code);
CheckReturn(result);
if (result != OSStatus.NoError)
throw new MacOSException(result);
return (MacOSKeyCode)code; return (MacOSKeyCode)code;
} }
@ -627,9 +563,7 @@ namespace OpenTK.Platform.MacOS.Carbon
OSStatus result = API.GetEventParameter(inEvent, OSStatus result = API.GetEventParameter(inEvent,
EventParamName.KeyMacCharCode, EventParamType.typeChar, IntPtr.Zero, EventParamName.KeyMacCharCode, EventParamType.typeChar, IntPtr.Zero,
Marshal.SizeOf(typeof(char)), IntPtr.Zero, (IntPtr)(void*)&code); Marshal.SizeOf(typeof(char)), IntPtr.Zero, (IntPtr)(void*)&code);
CheckReturn(result);
if (result != OSStatus.NoError)
throw new MacOSException(result);
return code; return code;
} }
@ -660,7 +594,7 @@ namespace OpenTK.Platform.MacOS.Carbon
OSStatus result = API.GetEventParameter(inEvent, OSStatus result = API.GetEventParameter(inEvent,
EventParamName.WindowMouseLocation, EventParamType.typeHIPoint, IntPtr.Zero, EventParamName.WindowMouseLocation, EventParamType.typeHIPoint, IntPtr.Zero,
Marshal.SizeOf(typeof(HIPoint)), IntPtr.Zero, (IntPtr)(void*)&point); Marshal.SizeOf(typeof(HIPoint)), IntPtr.Zero, (IntPtr)(void*)&point);
CheckReturn(result);
pt = point; pt = point;
return result; return result;
} }
@ -670,7 +604,7 @@ namespace OpenTK.Platform.MacOS.Carbon
OSStatus result = API.GetEventParameter(inEvent, OSStatus result = API.GetEventParameter(inEvent,
EventParamName.WindowRef, EventParamType.typeWindowRef, IntPtr.Zero, EventParamName.WindowRef, EventParamType.typeWindowRef, IntPtr.Zero,
sizeof(IntPtr), IntPtr.Zero, (IntPtr)(void*)&retval); sizeof(IntPtr), IntPtr.Zero, (IntPtr)(void*)&retval);
CheckReturn(result);
windowRef = retval; windowRef = retval;
return result; return result;
} }
@ -680,7 +614,7 @@ namespace OpenTK.Platform.MacOS.Carbon
OSStatus result = API.GetEventParameter(inEvent, OSStatus result = API.GetEventParameter(inEvent,
EventParamName.MouseLocation, EventParamType.typeHIPoint, IntPtr.Zero, EventParamName.MouseLocation, EventParamType.typeHIPoint, IntPtr.Zero,
Marshal.SizeOf(typeof(HIPoint)), IntPtr.Zero, (IntPtr)(void*)&point); Marshal.SizeOf(typeof(HIPoint)), IntPtr.Zero, (IntPtr)(void*)&point);
CheckReturn(result);
pt = point; pt = point;
return result; return result;
} }
@ -690,75 +624,41 @@ namespace OpenTK.Platform.MacOS.Carbon
OSStatus result = API.GetEventParameter(inEvent, OSStatus result = API.GetEventParameter(inEvent,
EventParamName.KeyModifiers, EventParamType.typeUInt32, IntPtr.Zero, EventParamName.KeyModifiers, EventParamType.typeUInt32, IntPtr.Zero,
sizeof(uint), IntPtr.Zero, (IntPtr)(void*)&code); sizeof(uint), IntPtr.Zero, (IntPtr)(void*)&code);
CheckReturn(result);
if (result != OSStatus.NoError)
throw new MacOSException(result);
return (MacOSKeyModifiers)code; return (MacOSKeyModifiers)code;
} }
#endregion [DllImport(carbon)]
#region --- Event Handlers --- static extern OSStatus InstallEventHandler(
[DllImport(carbon,EntryPoint="InstallEventHandler")]
static extern OSStatus _InstallEventHandler(
IntPtr eventTargetRef, IntPtr handlerProc, IntPtr eventTargetRef, IntPtr handlerProc,
int numtypes, EventTypeSpec[] typeList, int numtypes, EventTypeSpec[] typeList,
IntPtr userData, IntPtr handlerRef); IntPtr userData, IntPtr handlerRef);
internal static void InstallWindowEventHandler(IntPtr windowRef, IntPtr uppHandlerProc, internal static void InstallWindowEventHandler(IntPtr windowRef, IntPtr uppHandlerProc, EventTypeSpec[] eventTypes,
EventTypeSpec[] eventTypes, IntPtr userData, IntPtr handlerRef) IntPtr userData, IntPtr handlerRef) {
{
IntPtr windowTarget = GetWindowEventTarget(windowRef); IntPtr windowTarget = GetWindowEventTarget(windowRef);
OSStatus error = InstallEventHandler(windowTarget, uppHandlerProc, eventTypes.Length,
eventTypes, userData, handlerRef);
CheckReturn( error );
}
//Debug.Print("Window: {0}", windowRef); internal static void InstallApplicationEventHandler(IntPtr uppHandlerProc, EventTypeSpec[] eventTypes,
//Debug.Print("Window Target: {0}", windowTarget); IntPtr userData, IntPtr handlerRef) {
//Debug.Print("Handler: {0}", uppHandlerProc); OSStatus error = InstallEventHandler(GetApplicationEventTarget(), uppHandlerProc,
//Debug.Print("Num Events: {0}", eventTypes.Length);
//Debug.Print("User Data: {0}", userData);
//Debug.Print("Handler Ref: {0}", handlerRef);
OSStatus error = _InstallEventHandler(windowTarget, uppHandlerProc,
eventTypes.Length, eventTypes, eventTypes.Length, eventTypes,
userData, handlerRef); userData, handlerRef);
CheckReturn( error );
//Debug.Print("Status: {0}", error);
if (error != OSStatus.NoError)
{
throw new MacOSException(error);
}
}
internal static void InstallApplicationEventHandler(IntPtr uppHandlerProc,
EventTypeSpec[] eventTypes, IntPtr userData, IntPtr handlerRef)
{
OSStatus error = _InstallEventHandler(GetApplicationEventTarget(), uppHandlerProc,
eventTypes.Length, eventTypes,
userData, handlerRef);
if (error != OSStatus.NoError)
{
throw new MacOSException(error);
}
} }
[DllImport(carbon)] [DllImport(carbon)]
internal static extern OSStatus RemoveEventHandler(IntPtr inHandlerRef); internal static extern OSStatus RemoveEventHandler(IntPtr inHandlerRef);
#endregion
#region --- GetWindowEventTarget ---
[DllImport(carbon)] [DllImport(carbon)]
internal static extern IntPtr GetWindowEventTarget(IntPtr window); internal static extern IntPtr GetWindowEventTarget(IntPtr window);
[DllImport(carbon)] [DllImport(carbon)]
internal static extern IntPtr GetApplicationEventTarget(); internal static extern IntPtr GetApplicationEventTarget();
#endregion
#region --- UPP Event Handlers ---
[DllImport(carbon)] [DllImport(carbon)]
internal static extern IntPtr NewEventHandlerUPP(MacOSEventHandler handler); internal static extern IntPtr NewEventHandlerUPP(MacOSEventHandler handler);
@ -791,26 +691,14 @@ namespace OpenTK.Platform.MacOS.Carbon
#endregion #endregion
[DllImport(carbon)]
internal static extern OSStatus ActivateWindow (IntPtr inWindow, bool inActivate);
[DllImport(carbon)]
internal static extern void RunApplicationEventLoop();
[DllImport(carbon)]
internal static extern void QuitApplicationEventLoop();
#region --- SetWindowTitle --- #region --- SetWindowTitle ---
[DllImport(carbon)] [DllImport(carbon)]
static extern void SetWindowTitleWithCFString(IntPtr windowRef, IntPtr title); static extern void SetWindowTitleWithCFString(IntPtr windowRef, IntPtr title);
internal static void SetWindowTitle(IntPtr windowRef, string title) internal static void SetWindowTitle(IntPtr windowRef, string title) {
{
IntPtr str = __CFStringMakeConstantString(title); IntPtr str = __CFStringMakeConstantString(title);
Debug.Print("Setting window title: {0}, CFstring : {1}, Text : {2}", windowRef, str, title); Debug.Print("Setting window title: {0}, CFstring : {1}, Text : {2}", windowRef, str, title);
SetWindowTitleWithCFString(windowRef, str); SetWindowTitleWithCFString(windowRef, str);
// Apparently releasing this reference to the CFConstantString here // Apparently releasing this reference to the CFConstantString here
@ -822,18 +710,6 @@ namespace OpenTK.Platform.MacOS.Carbon
#endregion #endregion
[DllImport(carbon,EntryPoint="ChangeWindowAttributes")]
static extern OSStatus _ChangeWindowAttributes(IntPtr windowRef, WindowAttributes setTheseAttributes, WindowAttributes clearTheseAttributes);
internal static void ChangeWindowAttributes(IntPtr windowRef, WindowAttributes setTheseAttributes, WindowAttributes clearTheseAttributes)
{
OSStatus error = _ChangeWindowAttributes(windowRef, setTheseAttributes, clearTheseAttributes);
if (error != OSStatus.NoError)
{
throw new MacOSException(error);
}
}
[DllImport(carbon)] [DllImport(carbon)]
static extern IntPtr __CFStringMakeConstantString(string cStr); static extern IntPtr __CFStringMakeConstantString(string cStr);
@ -846,58 +722,28 @@ namespace OpenTK.Platform.MacOS.Carbon
[DllImport(carbon)] [DllImport(carbon)]
internal static extern IntPtr GetWindowPort(IntPtr windowRef); internal static extern IntPtr GetWindowPort(IntPtr windowRef);
#region --- Menus ---
[DllImport(carbon)] [DllImport(carbon)]
internal static extern IntPtr AcquireRootMenu(); internal static extern IntPtr AcquireRootMenu();
#endregion
[DllImport(carbon)] [DllImport(carbon)]
internal static extern bool IsWindowCollapsed(IntPtr windowRef); internal static extern bool IsWindowCollapsed(IntPtr windowRef);
[DllImport(carbon, EntryPoint = "CollapseWindow")] [DllImport(carbon)]
static extern OSStatus _CollapseWindow(IntPtr windowRef, bool collapse); internal static extern OSStatus CollapseWindow(IntPtr windowRef, bool collapse);
internal static void CollapseWindow(IntPtr windowRef, bool collapse)
{
OSStatus error = _CollapseWindow(windowRef, collapse);
if (error != OSStatus.NoError)
{
throw new MacOSException(error);
}
}
[DllImport(carbon, EntryPoint="IsWindowInStandardState")] [DllImport(carbon, EntryPoint="IsWindowInStandardState")]
static extern bool _IsWindowInStandardState(IntPtr windowRef, IntPtr inIdealSize, IntPtr outIdealStandardState); static extern bool _IsWindowInStandardState(IntPtr windowRef, IntPtr inIdealSize, IntPtr outIdealStandardState);
internal static bool IsWindowInStandardState(IntPtr windowRef) internal static bool IsWindowInStandardState(IntPtr windowRef) {
{
return _IsWindowInStandardState(windowRef, IntPtr.Zero, IntPtr.Zero); return _IsWindowInStandardState(windowRef, IntPtr.Zero, IntPtr.Zero);
} }
[DllImport(carbon, EntryPoint = "ZoomWindowIdeal")] [DllImport(carbon)]
unsafe static extern OSStatus _ZoomWindowIdeal(IntPtr windowRef, short inPartCode, IntPtr toIdealSize); internal unsafe static extern OSStatus ZoomWindowIdeal(IntPtr windowRef, short inPartCode, ref CarbonPoint toIdealSize);
internal static void ZoomWindowIdeal(IntPtr windowRef, WindowPartCode inPartCode, ref CarbonPoint toIdealSize) internal static void CheckReturn( OSStatus status ) {
{ if( status != OSStatus.NoError )
CarbonPoint pt = toIdealSize; throw new MacOSException( status );
OSStatus error ;
IntPtr handle = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(CarbonPoint)));
Marshal.StructureToPtr(toIdealSize, handle, false);
error = _ZoomWindowIdeal(windowRef, (short)inPartCode, handle);
toIdealSize = (CarbonPoint)Marshal.PtrToStructure(handle,typeof(CarbonPoint));
Marshal.FreeHGlobal(handle);
if (error != OSStatus.NoError)
{
throw new MacOSException(error);
}
} }
[DllImport(carbon)] [DllImport(carbon)]
@ -955,14 +801,8 @@ namespace OpenTK.Platform.MacOS.Carbon
#endregion #endregion
const string gestaltlib = "/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon"; const string gestaltlib = "/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon";
[DllImport(gestaltlib)] [DllImport(gestaltlib)]
internal static extern OSStatus Gestalt(GestaltSelector selector, out int response); internal static extern OSStatus Gestalt(GestaltSelector selector, out int response);
} }
#endregion #endregion
} }

View File

@ -1,18 +1,14 @@
using System; using System;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
namespace OpenTK.Platform.MacOS.Carbon {
namespace OpenTK.Platform.MacOS.Carbon
{
// Quartz Display services used here are available in MacOS X 10.3 and later. // Quartz Display services used here are available in MacOS X 10.3 and later.
enum CGDisplayErr {
enum CGDisplayErr
{
} }
internal static class CG internal static class CG {
{
const string appServices = "/System/Library/Frameworks/ApplicationServices.framework/Versions/Current/ApplicationServices"; const string appServices = "/System/Library/Frameworks/ApplicationServices.framework/Versions/Current/ApplicationServices";
// CGPoint -> HIPoint // CGPoint -> HIPoint

View File

@ -26,18 +26,14 @@
#endregion #endregion
using System; using System;
using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
using System.Drawing; using System.Drawing;
using OpenTK.Graphics;
using OpenTK.Platform.MacOS.Carbon;
using OpenTK.Input; using OpenTK.Input;
using OpenTK.Platform.MacOS.Carbon;
namespace OpenTK.Platform.MacOS namespace OpenTK.Platform.MacOS {
{
class CarbonGLNative : INativeWindow class CarbonGLNative : INativeWindow {
{
#region Fields
CarbonWindowInfo window; CarbonWindowInfo window;
static MacOSKeyMap Keymap = new MacOSKeyMap(); static MacOSKeyMap Keymap = new MacOSKeyMap();
@ -46,150 +42,88 @@ namespace OpenTK.Platform.MacOS
string title = "OpenTK Window"; string title = "OpenTK Window";
Rectangle bounds, clientRectangle; Rectangle bounds, clientRectangle;
Rectangle windowedBounds; Rectangle windowedBounds;
bool mIsDisposed = false; bool isDisposed = false;
bool mExists = true; bool exists = true;
DisplayDevice mDisplayDevice; DisplayDevice displayDevice;
WindowAttributes mWindowAttrib; WindowPositionMethod positionMethod = WindowPositionMethod.CenterOnMainScreen;
WindowClass mWindowClass; int titlebarHeight;
WindowPositionMethod mPositionMethod = WindowPositionMethod.CenterOnMainScreen;
int mTitlebarHeight;
private WindowState windowState = WindowState.Normal; private WindowState windowState = WindowState.Normal;
static Dictionary<IntPtr, WeakReference> mWindows = new Dictionary<IntPtr, WeakReference>(); KeyPressEventArgs keyPressArgs = new KeyPressEventArgs();
bool mouseIn = false, isActive = false;
Icon icon;
internal DisplayDevice TargetDisplayDevice { get { return displayDevice; } }
KeyPressEventArgs mKeyPressArgs = new KeyPressEventArgs(); static CarbonGLNative() {
bool mMouseIn = false;
bool mIsActive = false;
Icon mIcon;
#endregion
#region AGL Device Hack
static internal Dictionary<IntPtr, WeakReference> WindowRefMap { get { return mWindows; } }
internal DisplayDevice TargetDisplayDevice { get { return mDisplayDevice; } }
#endregion
#region Constructors
static CarbonGLNative()
{
Application.Initialize(); Application.Initialize();
} }
CarbonGLNative() public CarbonGLNative(int x, int y, int width, int height, string title,
: this(WindowClass.Document, GameWindowFlags options, DisplayDevice device) {
WindowAttributes.StandardDocument | this.title = title;
WindowAttributes.StandardHandler |
WindowAttributes.InWindowMenu |
WindowAttributes.LiveResize)
{ }
CarbonGLNative(WindowClass @class, WindowAttributes attrib)
{
mWindowClass = @class;
mWindowAttrib = attrib;
}
public CarbonGLNative(int x, int y, int width, int height, string title, GameWindowFlags options, DisplayDevice device)
{
CreateNativeWindow(WindowClass.Document, CreateNativeWindow(WindowClass.Document,
WindowAttributes.StandardDocument | WindowAttributes.StandardHandler | WindowAttributes.StandardDocument | WindowAttributes.StandardHandler |
WindowAttributes.InWindowMenu | WindowAttributes.LiveResize, WindowAttributes.InWindowMenu | WindowAttributes.LiveResize,
new Rect((short)x, (short)y, (short)width, (short)height)); new Rect((short)x, (short)y, (short)width, (short)height));
displayDevice = device;
mDisplayDevice = device;
} }
#endregion public void Dispose() {
#region IDisposable
public void Dispose()
{
Dispose(true); Dispose(true);
GC.SuppressFinalize(this); GC.SuppressFinalize(this);
} }
protected virtual void Dispose(bool disposing) protected virtual void Dispose(bool disposing) {
{ if (isDisposed)
if (mIsDisposed)
return; return;
Debug.Print("Disposing of CarbonGLNative window."); Debug.Print("Disposing of CarbonGLNative window.");
API.DisposeWindow(window.WindowRef); API.DisposeWindow(window.WindowRef);
isDisposed = true;
exists = false;
mIsDisposed = true; if (disposing) {
mExists = false;
if (disposing)
{
mWindows.Remove(window.WindowRef);
window.Dispose(); window.Dispose();
window = null; window = null;
} }
DisposeUPP(); DisposeUPP();
} }
~CarbonGLNative() ~CarbonGLNative() {
{
Dispose(false); Dispose(false);
} }
#endregion void DisposeUPP() {
if (uppHandler != IntPtr.Zero) {
#region Private Members API.RemoveEventHandler(uppHandler);
API.DisposeEventHandlerUPP(uppHandler);
void DisposeUPP()
{
if (uppHandler != IntPtr.Zero)
{
//API.RemoveEventHandler(uppHandler);
//API.DisposeEventHandlerUPP(uppHandler);
} }
uppHandler = IntPtr.Zero; uppHandler = IntPtr.Zero;
} }
void CreateNativeWindow(WindowClass @class, WindowAttributes attrib, Rect r) void CreateNativeWindow(WindowClass @class, WindowAttributes attrib, Rect r) {
{
Debug.Print("Creating window..."); Debug.Print("Creating window...");
IntPtr windowRef;
OSStatus err = API.CreateNewWindow(@class, attrib, ref r, out windowRef);
Debug.Print("Created Window: {0}", windowRef);
API.CheckReturn(err);
IntPtr windowRef = API.CreateNewWindow(@class, attrib, r);
API.SetWindowTitle(windowRef, title); API.SetWindowTitle(windowRef, title);
window = new CarbonWindowInfo(windowRef, this, true);
window = new CarbonWindowInfo(windowRef, true);
SetLocation(r.X, r.Y); SetLocation(r.X, r.Y);
SetSize(r.Width, r.Height); SetSize(r.Width, r.Height);
Debug.Print("Created window.");
mWindows.Add(windowRef, new WeakReference(this));
LoadSize(); LoadSize();
Rect titleSize = API.GetWindowBounds(window.WindowRef, WindowRegionCode.TitleBarRegion); Rect titleSize = API.GetWindowBounds(window.WindowRef, WindowRegionCode.TitleBarRegion);
mTitlebarHeight = titleSize.Height; titlebarHeight = titleSize.Height;
Debug.Print("Titlebar size: {0}", titleSize); Debug.Print("Titlebar size: {0}", titleSize);
ConnectEvents(); ConnectEvents();
Debug.Print("Attached window events."); Debug.Print("Attached window events.");
} }
void ConnectEvents() void ConnectEvents() {
{
EventTypeSpec[] eventTypes = new EventTypeSpec[] EventTypeSpec[] eventTypes = new EventTypeSpec[]
{ {
new EventTypeSpec(EventClass.Window, WindowEventKind.WindowClose), new EventTypeSpec(EventClass.Window, WindowEventKind.WindowClose),
@ -214,9 +148,7 @@ namespace OpenTK.Platform.MacOS
MacOSEventHandler handler = EventHandler; MacOSEventHandler handler = EventHandler;
uppHandler = API.NewEventHandlerUPP(handler); uppHandler = API.NewEventHandlerUPP(handler);
API.InstallWindowEventHandler(window.WindowRef, uppHandler, eventTypes, window.WindowRef, IntPtr.Zero); API.InstallWindowEventHandler(window.WindowRef, uppHandler, eventTypes, window.WindowRef, IntPtr.Zero);
Application.WindowEventHandler = this; Application.WindowEventHandler = this;
} }
@ -226,7 +158,7 @@ namespace OpenTK.Platform.MacOS
void Show() { void Show() {
API.ShowWindow(window.WindowRef); API.ShowWindow(window.WindowRef);
API.RepositionWindow(window.WindowRef, IntPtr.Zero, WindowPositionMethod); API.RepositionWindow(window.WindowRef, IntPtr.Zero, positionMethod);
API.SelectWindow(window.WindowRef); API.SelectWindow(window.WindowRef);
} }
@ -244,7 +176,7 @@ namespace OpenTK.Platform.MacOS
Debug.Print("New Size: {0}, {1}", Width, Height); Debug.Print("New Size: {0}, {1}", Width, Height);
// TODO: if we go full screen we need to make this use the device specified. // TODO: if we go full screen we need to make this use the device specified.
bounds = mDisplayDevice.Bounds; bounds = displayDevice.Bounds;
windowState = WindowState.Fullscreen; windowState = WindowState.Fullscreen;
} }
@ -253,106 +185,53 @@ namespace OpenTK.Platform.MacOS
Debug.Print("Telling Carbon to reset window state to " + windowState.ToString()); Debug.Print("Telling Carbon to reset window state to " + windowState.ToString());
SetCarbonWindowState(); SetCarbonWindowState();
SetSize((short)windowedBounds.Width, (short)windowedBounds.Height); SetSize((short)windowedBounds.Width, (short)windowedBounds.Height);
} }
bool IsDisposed internal OSStatus DispatchEvent( IntPtr inCaller, IntPtr inEvent, EventInfo evt, IntPtr userData ) {
{ switch (evt.EventClass) {
get { return mIsDisposed; }
}
WindowPositionMethod WindowPositionMethod
{
get { return mPositionMethod; }
set { mPositionMethod = value; }
}
internal OSStatus DispatchEvent(IntPtr inCaller, IntPtr inEvent, EventInfo evt, IntPtr userData)
{
switch (evt.EventClass)
{
case EventClass.Window: case EventClass.Window:
return ProcessWindowEvent(inCaller, inEvent, evt, userData); return ProcessWindowEvent(inCaller, inEvent, evt, userData);
case EventClass.Mouse: case EventClass.Mouse:
return ProcessMouseEvent(inCaller, inEvent, evt, userData); return ProcessMouseEvent(inCaller, inEvent, evt, userData);
case EventClass.Keyboard: case EventClass.Keyboard:
return ProcessKeyboardEvent(inCaller, inEvent, evt, userData); return ProcessKeyboardEvent(inCaller, inEvent, evt, userData);
default: default:
return OSStatus.EventNotHandled; return OSStatus.EventNotHandled;
} }
} }
protected static OSStatus EventHandler(IntPtr inCaller, IntPtr inEvent, IntPtr userData) protected OSStatus EventHandler( IntPtr inCaller, IntPtr inEvent, IntPtr userData ) {
{
// bail out if the window passed in is not actually our window. // bail out if the window passed in is not actually our window.
// I think this happens if using winforms with a GameWindow sometimes. if( userData != window.WindowRef)
if (!mWindows.ContainsKey(userData))
return OSStatus.EventNotHandled; return OSStatus.EventNotHandled;
WeakReference reference = mWindows[userData];
// bail out if the CarbonGLNative window has been garbage collected.
if (!reference.IsAlive) {
mWindows.Remove(userData);
return OSStatus.EventNotHandled;
}
CarbonGLNative window = (CarbonGLNative)reference.Target;
EventInfo evt = new EventInfo(inEvent); EventInfo evt = new EventInfo(inEvent);
return DispatchEvent( inCaller, inEvent, evt, userData );
//Debug.Print("Processing {0} event for {1}.", evt, window.window);
if (window == null) {
Debug.Print("Window for event not found.");
return OSStatus.EventNotHandled;
} }
switch (evt.EventClass) private OSStatus ProcessKeyboardEvent( IntPtr inCaller, IntPtr inEvent, EventInfo evt, IntPtr userData ) {
{
case EventClass.Window:
return window.ProcessWindowEvent(inCaller, inEvent, evt, userData);
case EventClass.Mouse:
return window.ProcessMouseEvent(inCaller, inEvent, evt, userData);
case EventClass.Keyboard:
return window.ProcessKeyboardEvent(inCaller, inEvent, evt, userData);
default:
return OSStatus.EventNotHandled;
}
}
private OSStatus ProcessKeyboardEvent(IntPtr inCaller, IntPtr inEvent, EventInfo evt, IntPtr userData)
{
Debug.Assert(evt.EventClass == EventClass.Keyboard);
MacOSKeyCode code = (MacOSKeyCode)0; MacOSKeyCode code = (MacOSKeyCode)0;
char charCode = '\0'; char charCode = '\0';
//Debug.Print("Processing keyboard event {0}", evt.KeyboardEventKind); //Debug.Print("Processing keyboard event {0}", evt.KeyboardEventKind);
switch (evt.KeyboardEventKind) switch ((KeyboardEventKind)evt.EventKind) {
{
case KeyboardEventKind.RawKeyDown: case KeyboardEventKind.RawKeyDown:
case KeyboardEventKind.RawKeyRepeat: case KeyboardEventKind.RawKeyRepeat:
case KeyboardEventKind.RawKeyUp: case KeyboardEventKind.RawKeyUp:
GetCharCodes(inEvent, out code, out charCode); GetCharCodes(inEvent, out code, out charCode);
mKeyPressArgs.KeyChar = charCode; keyPressArgs.KeyChar = charCode;
break; break;
} }
switch (evt.KeyboardEventKind) switch ((KeyboardEventKind)evt.EventKind) {
{
case KeyboardEventKind.RawKeyRepeat: case KeyboardEventKind.RawKeyRepeat:
keyboard.KeyRepeat = true; keyboard.KeyRepeat = true;
goto case KeyboardEventKind.RawKeyDown; goto case KeyboardEventKind.RawKeyDown;
case KeyboardEventKind.RawKeyDown: case KeyboardEventKind.RawKeyDown:
OnKeyPress(mKeyPressArgs); OnKeyPress(keyPressArgs);
keyboard[Keymap[code]] = true; keyboard[Keymap[code]] = true;
return OSStatus.NoError; return OSStatus.NoError;
@ -369,12 +248,8 @@ namespace OpenTK.Platform.MacOS
} }
} }
private OSStatus ProcessWindowEvent(IntPtr inCaller, IntPtr inEvent, EventInfo evt, IntPtr userData) private OSStatus ProcessWindowEvent(IntPtr inCaller, IntPtr inEvent, EventInfo evt, IntPtr userData) {
{ switch ((WindowEventKind)evt.EventKind) {
Debug.Assert(evt.EventClass == EventClass.Window);
switch (evt.WindowEventKind)
{
case WindowEventKind.WindowClose: case WindowEventKind.WindowClose:
CancelEventArgs cancel = new CancelEventArgs(); CancelEventArgs cancel = new CancelEventArgs();
OnClosing(cancel); OnClosing(cancel);
@ -385,7 +260,7 @@ namespace OpenTK.Platform.MacOS
return OSStatus.EventNotHandled; return OSStatus.EventNotHandled;
case WindowEventKind.WindowClosed: case WindowEventKind.WindowClosed:
mExists = false; exists = false;
OnClosed(); OnClosed();
return OSStatus.NoError; return OSStatus.NoError;
@ -410,42 +285,34 @@ namespace OpenTK.Platform.MacOS
return OSStatus.EventNotHandled; return OSStatus.EventNotHandled;
default: default:
Debug.Print("{0}", evt); Debug.Print("unhandled {0}", evt);
return OSStatus.EventNotHandled; return OSStatus.EventNotHandled;
} }
} }
protected OSStatus ProcessMouseEvent(IntPtr inCaller, IntPtr inEvent, EventInfo evt, IntPtr userData)
{ protected OSStatus ProcessMouseEvent(IntPtr inCaller, IntPtr inEvent, EventInfo evt, IntPtr userData) {
Debug.Assert(evt.EventClass == EventClass.Mouse);
MacOSMouseButton button; MacOSMouseButton button;
HIPoint pt = new HIPoint(); HIPoint pt = new HIPoint();
HIPoint screenLoc = new HIPoint(); HIPoint screenLoc = new HIPoint();
OSStatus err = API.GetEventMouseLocation(inEvent, out screenLoc); OSStatus err = API.GetEventMouseLocation(inEvent, out screenLoc);
if (this.windowState == WindowState.Fullscreen) if (this.windowState == WindowState.Fullscreen) {
{
pt = screenLoc; pt = screenLoc;
} } else {
else
{
err = API.GetEventWindowMouseLocation(inEvent, out pt); err = API.GetEventWindowMouseLocation(inEvent, out pt);
} }
if (err != OSStatus.NoError) if (err != OSStatus.NoError) {
{
// this error comes up from the application event handler. // this error comes up from the application event handler.
if (err != OSStatus.EventParameterNotFound) if (err != OSStatus.EventParameterNotFound) {
{
throw new MacOSException(err); throw new MacOSException(err);
} }
} }
Point mousePosInClient = new Point((int)pt.X, (int)pt.Y); Point mousePosInClient = new Point((int)pt.X, (int)pt.Y);
if (this.windowState != WindowState.Fullscreen) if (this.windowState != WindowState.Fullscreen) {
{ mousePosInClient.Y -= titlebarHeight;
mousePosInClient.Y -= mTitlebarHeight;
} }
// check for enter/leave events // check for enter/leave events
@ -453,8 +320,7 @@ namespace OpenTK.Platform.MacOS
API.GetEventWindowRef(inEvent, out thisEventWindow); API.GetEventWindowRef(inEvent, out thisEventWindow);
CheckEnterLeaveEvents(thisEventWindow, mousePosInClient); CheckEnterLeaveEvents(thisEventWindow, mousePosInClient);
switch (evt.MouseEventKind) switch ((MouseEventKind)evt.EventKind) {
{
case MouseEventKind.MouseDown: case MouseEventKind.MouseDown:
button = API.GetEventMouseButton(inEvent); button = API.GetEventMouseButton(inEvent);
@ -521,13 +387,12 @@ namespace OpenTK.Platform.MacOS
return OSStatus.EventNotHandled; return OSStatus.EventNotHandled;
default: default:
Debug.Print("{0}", evt); Debug.Print("unhandled {0}", evt);
return OSStatus.EventNotHandled; return OSStatus.EventNotHandled;
} }
} }
private void CheckEnterLeaveEvents(IntPtr eventWindowRef, Point pt) private void CheckEnterLeaveEvents(IntPtr eventWindowRef, Point pt) {
{
if (window == null) if (window == null)
return; return;
@ -536,25 +401,21 @@ namespace OpenTK.Platform.MacOS
if (pt.Y < 0) if (pt.Y < 0)
thisIn = false; thisIn = false;
if (thisIn != mMouseIn) if (thisIn == mouseIn) return;
{ mouseIn = thisIn;
mMouseIn = thisIn;
if (mMouseIn) if (mouseIn)
OnMouseEnter(); OnMouseEnter();
else else
OnMouseLeave(); OnMouseLeave();
} }
}
private static void GetCharCodes(IntPtr inEvent, out MacOSKeyCode code, out char charCode) private static void GetCharCodes(IntPtr inEvent, out MacOSKeyCode code, out char charCode) {
{
code = API.GetEventKeyboardKeyCode(inEvent); code = API.GetEventKeyboardKeyCode(inEvent);
charCode = API.GetEventKeyboardChar(inEvent); charCode = API.GetEventKeyboardChar(inEvent);
} }
private void ProcessModifierKey(IntPtr inEvent) private void ProcessModifierKey(IntPtr inEvent) {
{
MacOSKeyModifiers modifiers = API.GetEventKeyModifiers(inEvent); MacOSKeyModifiers modifiers = API.GetEventKeyModifiers(inEvent);
bool caps = (modifiers & MacOSKeyModifiers.CapsLock) != 0; bool caps = (modifiers & MacOSKeyModifiers.CapsLock) != 0;
@ -579,11 +440,6 @@ namespace OpenTK.Platform.MacOS
if (keyboard[Key.CapsLock] ^ caps) if (keyboard[Key.CapsLock] ^ caps)
keyboard[Key.CapsLock] = caps; keyboard[Key.CapsLock] = caps;
}
Rect GetRegion() {
return API.GetWindowBounds(window.WindowRef, WindowRegionCode.ContentRegion);
} }
void SetLocation(short x, short y) { void SetLocation(short x, short y) {
@ -631,53 +487,43 @@ namespace OpenTK.Platform.MacOS
clientRectangle = new Rectangle(0, 0, r.Width, r.Height); clientRectangle = new Rectangle(0, 0, r.Width, r.Height);
} }
#endregion
#region INativeWindow Members #region INativeWindow Members
public void ProcessEvents() public void ProcessEvents() {
{ API.ProcessEvents();
Application.ProcessEvents();
} }
public Point PointToClient(Point point) public Point PointToClient(Point point) {
{
IntPtr handle = window.WindowRef; IntPtr handle = window.WindowRef;
Rect r = Carbon.API.GetWindowBounds(window.WindowRef, WindowRegionCode.ContentRegion); Rect r = Carbon.API.GetWindowBounds(window.WindowRef, WindowRegionCode.ContentRegion);
Debug.Print("Rect: {0}", r); Debug.Print("Rect: {0}", r);
return new Point(point.X - r.X, point.Y - r.Y); return new Point(point.X - r.X, point.Y - r.Y);
} }
public Point PointToScreen(Point point)
{
IntPtr handle = window.WindowRef;
public Point PointToScreen(Point point) {
IntPtr handle = window.WindowRef;
Rect r = Carbon.API.GetWindowBounds(window.WindowRef, WindowRegionCode.ContentRegion); Rect r = Carbon.API.GetWindowBounds(window.WindowRef, WindowRegionCode.ContentRegion);
Debug.Print("Rect: {0}", r); Debug.Print("Rect: {0}", r);
return new Point(point.X + r.X, point.Y + r.Y); return new Point(point.X + r.X, point.Y + r.Y);
} }
public bool Exists public bool Exists {
{ get { return exists; }
get { return mExists; }
} }
public IWindowInfo WindowInfo public IWindowInfo WindowInfo {
{
get { return window; } get { return window; }
} }
public Icon Icon { public Icon Icon {
get { return mIcon; } get { return icon; }
set { set {
icon = value;
SetIcon(value); SetIcon(value);
} }
} }
private void SetIcon(Icon icon) private void SetIcon(Icon icon) {
{
// The code for this function was adapted from Mono's // The code for this function was adapted from Mono's
// XplatUICarbon implementation, written by Geoff Norton // XplatUICarbon implementation, written by Geoff Norton
// http://anonsvn.mono-project.com/viewvc/trunk/mcs/class/Managed.Windows.Forms/System.Windows.Forms/XplatUICarbon.cs?view=markup&pathrev=136932 // http://anonsvn.mono-project.com/viewvc/trunk/mcs/class/Managed.Windows.Forms/System.Windows.Forms/XplatUICarbon.cs?view=markup&pathrev=136932
@ -727,45 +573,31 @@ namespace OpenTK.Platform.MacOS
} }
} }
public string Title public string Title {
{ get { return title; }
get set {
{
return title;
}
set
{
API.SetWindowTitle(window.WindowRef, value); API.SetWindowTitle(window.WindowRef, value);
title = value; title = value;
} }
} }
public bool Visible public bool Visible {
{
get { return API.IsWindowVisible(window.WindowRef); } get { return API.IsWindowVisible(window.WindowRef); }
set set {
{ if (value && !Visible)
if (value && Visible == false)
Show(); Show();
else else
Hide(); Hide();
} }
} }
public bool Focused public bool Focused {
{ get { return isActive; }
get { return this.mIsActive; }
} }
public Rectangle Bounds public Rectangle Bounds {
{ get { return bounds; }
get set {
{
return bounds;
}
set
{
Location = value.Location; Location = value.Location;
Size = value.Size; Size = value.Size;
} }
@ -781,14 +613,12 @@ namespace OpenTK.Platform.MacOS
set { SetSize((short)value.Width, (short)value.Height); } set { SetSize((short)value.Width, (short)value.Height); }
} }
public int Width public int Width {
{
get { return ClientRectangle.Width; } get { return ClientRectangle.Width; }
set { SetClientSize((short)value, (short)Height); } set { SetClientSize((short)value, (short)Height); }
} }
public int Height public int Height {
{
get { return ClientRectangle.Height; } get { return ClientRectangle.Height; }
set { SetClientSize((short)Width, (short)value); } set { SetClientSize((short)Width, (short)value); }
} }
@ -803,35 +633,24 @@ namespace OpenTK.Platform.MacOS
set { Location = new Point(X, value); } set { Location = new Point(X, value); }
} }
public Rectangle ClientRectangle public Rectangle ClientRectangle {
{ get { return clientRectangle; }
get set {
{
return clientRectangle;
}
set
{
// just set the size, and ignore the location value. // just set the size, and ignore the location value.
// this is the behavior of the Windows WinGLNative. // this is the behavior of the Windows WinGLNative.
ClientSize = value.Size; ClientSize = value.Size;
} }
} }
public Size ClientSize public Size ClientSize {
{ get { return clientRectangle.Size; }
get set {
{
return clientRectangle.Size;
}
set
{
API.SizeWindow(window.WindowRef, (short)value.Width, (short)value.Height, true); API.SizeWindow(window.WindowRef, (short)value.Width, (short)value.Height, true);
OnResize(); OnResize();
} }
} }
public void Close() public void Close() {
{
CancelEventArgs e = new CancelEventArgs(); CancelEventArgs e = new CancelEventArgs();
OnClosing(e); OnClosing(e);
@ -839,14 +658,11 @@ namespace OpenTK.Platform.MacOS
return; return;
OnClosed(); OnClosed();
Dispose(); Dispose();
} }
public WindowState WindowState public WindowState WindowState {
{ get {
get
{
if (windowState == WindowState.Fullscreen) if (windowState == WindowState.Fullscreen)
return WindowState.Fullscreen; return WindowState.Fullscreen;
@ -854,14 +670,11 @@ namespace OpenTK.Platform.MacOS
return WindowState.Minimized; return WindowState.Minimized;
if (Carbon.API.IsWindowInStandardState(window.WindowRef)) if (Carbon.API.IsWindowInStandardState(window.WindowRef))
{
return WindowState.Maximized; return WindowState.Maximized;
}
return WindowState.Normal; return WindowState.Normal;
} }
set set {
{
if (value == WindowState) if (value == WindowState)
return; return;
@ -870,8 +683,7 @@ namespace OpenTK.Platform.MacOS
windowState = value; windowState = value;
if (oldState == WindowState.Fullscreen) if (oldState == WindowState.Fullscreen) {
{
window.goWindowedHack = true; window.goWindowedHack = true;
// when returning from full screen, wait until the context is updated // when returning from full screen, wait until the context is updated
@ -879,21 +691,20 @@ namespace OpenTK.Platform.MacOS
return; return;
} }
if (oldState == WindowState.Minimized) if (oldState == WindowState.Minimized) {
{ OSStatus err = API.CollapseWindow(window.WindowRef, false);
API.CollapseWindow(window.WindowRef, false); API.CheckReturn( err );
} }
SetCarbonWindowState(); SetCarbonWindowState();
} }
} }
private void SetCarbonWindowState() private void SetCarbonWindowState() {
{
CarbonPoint idealSize; CarbonPoint idealSize;
OSStatus err;
switch (windowState) switch (windowState) {
{
case WindowState.Fullscreen: case WindowState.Fullscreen:
window.goFullScreenHack = true; window.goFullScreenHack = true;
break; break;
@ -903,83 +714,69 @@ namespace OpenTK.Platform.MacOS
// meaning they are maximized up to their reported ideal size. So we report a // meaning they are maximized up to their reported ideal size. So we report a
// large ideal size. // large ideal size.
idealSize = new CarbonPoint(9000, 9000); idealSize = new CarbonPoint(9000, 9000);
API.ZoomWindowIdeal(window.WindowRef, WindowPartCode.inZoomOut, ref idealSize); err = API.ZoomWindowIdeal(window.WindowRef, (short)WindowPartCode.inZoomOut, ref idealSize);
API.CheckReturn( err );
break; break;
case WindowState.Normal: case WindowState.Normal:
if (WindowState == WindowState.Maximized) if (WindowState == WindowState.Maximized) {
{
idealSize = new CarbonPoint(); idealSize = new CarbonPoint();
API.ZoomWindowIdeal(window.WindowRef, WindowPartCode.inZoomIn, ref idealSize); err = API.ZoomWindowIdeal(window.WindowRef, (short)WindowPartCode.inZoomIn, ref idealSize);
API.CheckReturn( err );
} }
break; break;
case WindowState.Minimized: case WindowState.Minimized:
API.CollapseWindow(window.WindowRef, true); err = API.CollapseWindow(window.WindowRef, true);
API.CheckReturn( err );
break; break;
} }
OnWindowStateChanged(); OnWindowStateChanged();
OnResize(); OnResize();
} }
#region --- Event wrappers --- private void OnKeyPress(KeyPressEventArgs keyPressArgs) {
private void OnKeyPress(KeyPressEventArgs keyPressArgs)
{
if (KeyPress != null) if (KeyPress != null)
KeyPress(this, keyPressArgs); KeyPress(this, keyPressArgs);
} }
private void OnWindowStateChanged() {
private void OnWindowStateChanged()
{
if (WindowStateChanged != null) if (WindowStateChanged != null)
WindowStateChanged(this, EventArgs.Empty); WindowStateChanged(this, EventArgs.Empty);
} }
protected virtual void OnClosing(CancelEventArgs e) protected virtual void OnClosing(CancelEventArgs e) {
{
if (Closing != null) if (Closing != null)
Closing(this, e); Closing(this, e);
} }
protected virtual void OnClosed() protected virtual void OnClosed() {
{
if (Closed != null) if (Closed != null)
Closed(this, EventArgs.Empty); Closed(this, EventArgs.Empty);
} }
private void OnMouseLeave() {
private void OnMouseLeave()
{
if (MouseLeave != null) if (MouseLeave != null)
MouseLeave(this, EventArgs.Empty); MouseLeave(this, EventArgs.Empty);
} }
private void OnMouseEnter() private void OnMouseEnter() {
{
if (MouseEnter != null) if (MouseEnter != null)
MouseEnter(this, EventArgs.Empty); MouseEnter(this, EventArgs.Empty);
} }
private void OnActivate() private void OnActivate() {
{ isActive = true;
mIsActive = true;
if (FocusedChanged != null)
FocusedChanged(this, EventArgs.Empty);
}
private void OnDeactivate()
{
mIsActive = false;
if (FocusedChanged != null) if (FocusedChanged != null)
FocusedChanged(this, EventArgs.Empty); FocusedChanged(this, EventArgs.Empty);
} }
#endregion private void OnDeactivate() {
isActive = false;
if (FocusedChanged != null)
FocusedChanged(this, EventArgs.Empty);
}
public event EventHandler<EventArgs> Load; public event EventHandler<EventArgs> Load;
public event EventHandler<EventArgs> Unload; public event EventHandler<EventArgs> Unload;
@ -1000,8 +797,6 @@ namespace OpenTK.Platform.MacOS
#endregion #endregion
#region IInputDriver Members
KeyboardDevice keyboard = new KeyboardDevice(); KeyboardDevice keyboard = new KeyboardDevice();
MouseDevice mouse = new MouseDevice(); MouseDevice mouse = new MouseDevice();
@ -1040,7 +835,5 @@ namespace OpenTK.Platform.MacOS
CG.CGDisplayHideCursor(CG.CGMainDisplayID()); CG.CGDisplayHideCursor(CG.CGMainDisplayID());
} }
} }
#endregion
} }
} }

View File

@ -26,64 +26,35 @@
#endregion #endregion
using System; using System;
using System.Collections.Generic;
using System.Text;
namespace OpenTK.Platform.MacOS namespace OpenTK.Platform.MacOS {
{
/// \internal /// \internal
/// <summary> /// <summary> Describes a Carbon window.</summary>
/// Describes a Carbon window. sealed class CarbonWindowInfo : IWindowInfo {
/// </summary>
sealed class CarbonWindowInfo : IWindowInfo public IntPtr WindowRef;
{
IntPtr windowRef;
bool ownHandle = false; bool ownHandle = false;
bool disposed = false; bool disposed = false;
internal bool goFullScreenHack = false; internal bool goFullScreenHack = false;
internal bool goWindowedHack = false; internal bool goWindowedHack = false;
internal CarbonGLNative nativeWindow;
#region Constructors public CarbonWindowInfo( IntPtr windowRef, CarbonGLNative nativeWindow, bool ownHandle ) {
this.WindowRef = windowRef;
/// <summary> this.nativeWindow = nativeWindow;
/// Constructs a new instance with the specified parameters.
/// </summary>
/// <param name="windowRef">A valid Carbon window reference.</param>
/// <param name="ownHandle"></param>
public CarbonWindowInfo(IntPtr windowRef, bool ownHandle)
{
this.windowRef = windowRef;
this.ownHandle = ownHandle; this.ownHandle = ownHandle;
} }
#endregion public override string ToString() {
return String.Format("CarbonWindowInfo: Handle {0}", WindowRef);
#region Public Members
/// <summary>
/// Gets the window reference for this instance.
/// </summary>
internal IntPtr WindowRef
{
get { return this.windowRef; }
} }
/// <summary>Returns a System.String that represents the current window.</summary>
/// <returns>A System.String that represents the current window.</returns>
public override string ToString()
{
return String.Format("MacOS.CarbonWindowInfo: Handle {0}", WindowRef);
}
#endregion
// TODO: I have no idea if this is right. // TODO: I have no idea if this is right.
public IntPtr WinHandle { public IntPtr WinHandle {
get { return windowRef; } get { return WindowRef; }
} }
#region IDisposable Members
public void Dispose() { public void Dispose() {
Dispose(true); Dispose(true);
} }
@ -92,11 +63,10 @@ namespace OpenTK.Platform.MacOS
if (disposed) if (disposed)
return; return;
if (ownHandle) if (ownHandle) {
{ Debug.Print("Disposing window {0}.", WindowRef);
Debug.Print("Disposing window {0}.", windowRef); Carbon.API.DisposeWindow(this.WindowRef);
Carbon.API.DisposeWindow(this.windowRef); WindowRef = IntPtr.Zero;
windowRef = IntPtr.Zero;
} }
disposed = true; disposed = true;
@ -105,7 +75,5 @@ namespace OpenTK.Platform.MacOS
~CarbonWindowInfo() { ~CarbonWindowInfo() {
Dispose(false); Dispose(false);
} }
#endregion
} }
} }

View File

@ -14,76 +14,18 @@ using System.Text;
namespace OpenTK.Platform.MacOS.Carbon namespace OpenTK.Platform.MacOS.Carbon
{ {
internal struct EventInfo internal struct EventInfo {
{
internal EventInfo(IntPtr eventRef) internal EventInfo(IntPtr eventRef) {
{ EventClass = API.GetEventClass(eventRef);
this._eventClass = API.GetEventClass(eventRef); EventKind = API.GetEventKind(eventRef);
this._eventKind = API.GetEventKind(eventRef);
} }
uint _eventKind; public uint EventKind;
EventClass _eventClass; public EventClass EventClass;
public EventClass EventClass { get { return _eventClass; }} public override string ToString() {
return "Event class " + EventClass + ", kind: " + EventKind;
public WindowEventKind WindowEventKind
{
get
{
if (EventClass == EventClass.Window)
return (WindowEventKind) _eventKind;
else
throw new InvalidCastException("Event is not a Window event.");
}
}
public KeyboardEventKind KeyboardEventKind
{
get
{
if (EventClass == EventClass.Keyboard)
return (KeyboardEventKind) _eventKind;
else
throw new InvalidCastException("Event is not a Keyboard event.");
}
}
public MouseEventKind MouseEventKind
{
get
{
if (EventClass == EventClass.Mouse)
return (MouseEventKind) _eventKind;
else
throw new InvalidCastException("Event is not an Mouse event.");
}
}
public AppEventKind AppEventKind
{
get
{
if (EventClass == EventClass.Application)
return (AppEventKind) _eventKind;
else
throw new InvalidCastException("Event is not an Application event.");
}
}
public override string ToString()
{
switch(EventClass)
{
case EventClass.Application:
return "Event: App " + AppEventKind.ToString();
case EventClass.Keyboard:
return "Event: Keyboard " + KeyboardEventKind.ToString();
case EventClass.Mouse:
return "Event: Mouse " + MouseEventKind.ToString();
case EventClass.Window:
return "Event: Window " + WindowEventKind.ToString();
}
return "Event: Unknown Class " + EventClass.ToString() + " kind: " + _eventKind.ToString();
} }
} }
} }

View File

@ -86,9 +86,7 @@ namespace OpenTK.Platform.MacOS
} }
} }
internal static IntPtr HandleTo(DisplayDevice displayDevice) {
internal static IntPtr HandleTo(DisplayDevice displayDevice)
{
if (displayMap.ContainsKey(displayDevice)) if (displayMap.ContainsKey(displayDevice))
return displayMap[displayDevice]; return displayMap[displayDevice];
else else
@ -127,9 +125,7 @@ namespace OpenTK.Platform.MacOS
} }
Debug.Print("Changing resolution to {0}x{1}x{2}@{3}.", width, height, bpp, freq); Debug.Print("Changing resolution to {0}x{1}x{2}@{3}.", width, height, bpp, freq);
CG.CGDisplaySwitchToMode(display, displayModes[j]); CG.CGDisplaySwitchToMode(display, displayModes[j]);
return true; return true;
} }
@ -137,12 +133,10 @@ namespace OpenTK.Platform.MacOS
return false; return false;
} }
public bool TryRestoreResolution(DisplayDevice device) public bool TryRestoreResolution(DisplayDevice device) {
{
IntPtr display = displayMap[device]; IntPtr display = displayMap[device];
if (storedModes.ContainsKey(display)) if (storedModes.ContainsKey(display)) {
{
Debug.Print("Restoring resolution."); Debug.Print("Restoring resolution.");
CG.CGDisplaySwitchToMode(display, storedModes[display]); CG.CGDisplaySwitchToMode(display, storedModes[display]);