Browse Source

entry_osx: setMouseLock implementation

Attila Kocsis 5 years ago
parent
commit
0e8e22b049
1 changed files with 56 additions and 1 deletions
  1. 56 1
      examples/common/entry/entry_osx.mm

+ 56 - 1
examples/common/entry/entry_osx.mm

@@ -100,6 +100,7 @@ namespace entry
 			, m_scroll(0)
 			, m_style(0)
 			, m_exit(false)
+			, m_mouseLock(NULL)
 		{
 			s_translateKey[27]             = Key::Esc;
 			s_translateKey[uint8_t('\r')]  = Key::Return;
@@ -194,6 +195,43 @@ namespace entry
 			*outY = bx::clamp(y, 0, int32_t(adjustFrame.size.height) );
 		}
 
+		void setMousePos(NSWindow* _window, int _x, int _y)
+		{
+			NSRect  originalFrame = [_window frame];
+			NSRect  adjustFrame   = [_window contentRectForFrameRect: originalFrame];
+			
+			adjustFrame.origin.y = NSMaxY(NSScreen.screens[0].frame) - NSMaxY(adjustFrame);
+			
+			CGWarpMouseCursorPosition(CGPointMake(_x + adjustFrame.origin.x, _y + adjustFrame.origin.y));
+			CGAssociateMouseAndMouseCursorPosition(YES);
+		}
+		
+		void setMouseLock(NSWindow* _window, bool _lock)
+		{
+			NSWindow* newMouseLock = _lock ? _window : NULL;
+
+			if ( m_mouseLock != newMouseLock )
+			{
+				if ( _lock )
+				{
+					NSRect  originalFrame = [_window frame];
+					NSRect  adjustFrame   = [_window contentRectForFrameRect: originalFrame];
+					
+					m_cmx = (int)adjustFrame.size.width / 2;
+					m_cmy = (int)adjustFrame.size.height / 2;
+					
+					setMousePos(_window, m_cmx, m_cmy);
+					[NSCursor hide];
+				}
+				else
+				{
+					[NSCursor unhide];
+				}
+				m_mouseLock = newMouseLock;
+			}
+		}
+
+
 		uint8_t translateModifiers(int flags)
 		{
 			return 0
@@ -286,6 +324,15 @@ namespace entry
 				case NSEventTypeRightMouseDragged:
 				case NSEventTypeOtherMouseDragged:
 					getMousePos(window, &m_mx, &m_my);
+						
+					if (window == m_mouseLock)
+					{
+						m_mx -= m_cmx;
+						m_my -= m_cmy;
+							
+						setMousePos(window, m_cmx, m_cmy);
+					}
+
 					m_eventQueue.postMouseEvent(handle, m_mx, m_my, m_scroll);
 					break;
 
@@ -525,6 +572,10 @@ namespace entry
 		int32_t m_scroll;
 		int32_t m_style;
 		bool    m_exit;
+		
+		NSWindow* m_mouseLock;
+		int32_t m_cmx;
+		int32_t m_cmy;
 	};
 
 	static Context s_ctx;
@@ -671,7 +722,11 @@ namespace entry
 
 	void setMouseLock(WindowHandle _handle, bool _lock)
 	{
-		BX_UNUSED(_handle, _lock);
+		dispatch_async(dispatch_get_main_queue()
+			, ^{
+				NSWindow* window = s_ctx.m_window[_handle.idx];
+				s_ctx.setMouseLock(window, _lock);
+			});
 	}
 
 } // namespace entry