|
| 1 | +import sys |
| 2 | + |
| 3 | + |
| 4 | +def bring_app_to_front() -> None: |
| 5 | + """Brings the current application to the front on macOS.""" |
| 6 | + if sys.platform != 'darwin': |
| 7 | + raise ValueError('Not supported on this OS') |
| 8 | + |
| 9 | + try: |
| 10 | + import ctypes |
| 11 | + import ctypes.util |
| 12 | + |
| 13 | + # Load the AppKit framework |
| 14 | + appkit_path = ctypes.util.find_library('AppKit') |
| 15 | + if appkit_path is None: |
| 16 | + print('Warning: Could not find AppKit framework', file=sys.stderr) |
| 17 | + return |
| 18 | + objc_path = ctypes.util.find_library('objc') |
| 19 | + if objc_path is None: |
| 20 | + print('Warning: Could not find objc library', file=sys.stderr) |
| 21 | + return |
| 22 | + |
| 23 | + appkit = ctypes.cdll.LoadLibrary(appkit_path) |
| 24 | + objc = ctypes.cdll.LoadLibrary(objc_path) |
| 25 | + |
| 26 | + # Define objc_getClass to lookup Objective-C classes |
| 27 | + objc.objc_getClass.restype = ctypes.c_void_p |
| 28 | + objc.objc_getClass.argtypes = [ctypes.c_char_p] |
| 29 | + |
| 30 | + # Define sel_registerName to lookup Objective-C selectors |
| 31 | + objc.sel_registerName.restype = ctypes.c_void_p |
| 32 | + objc.sel_registerName.argtypes = [ctypes.c_char_p] |
| 33 | + |
| 34 | + # Define objc_msgSend for calling Objective-C methods |
| 35 | + objc_msgSend = objc.objc_msgSend |
| 36 | + objc_msgSend.restype = ctypes.c_void_p |
| 37 | + objc_msgSend.argtypes = [ctypes.c_void_p, ctypes.c_void_p] |
| 38 | + |
| 39 | + # Get the shared application instance |
| 40 | + NSApplication = objc.objc_getClass(b'NSApplication') |
| 41 | + sharedApplication = objc.sel_registerName(b'sharedApplication') |
| 42 | + app = objc_msgSend(NSApplication, sharedApplication) |
| 43 | + |
| 44 | + # Activate the application, ignoring other apps |
| 45 | + activateIgnoringOtherApps = objc.sel_registerName(b'activateIgnoringOtherApps:') |
| 46 | + objc_msgSend_bool = objc.objc_msgSend |
| 47 | + objc_msgSend_bool.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_bool] |
| 48 | + objc_msgSend_bool(app, activateIgnoringOtherApps, True) |
| 49 | + |
| 50 | + except Exception as e: |
| 51 | + print(f'Warning: Failed to bring application to front: {e}', file=sys.stderr) |
0 commit comments