Created
April 18, 2023 19:56
-
-
Save stephancasas/847e29b72bce1900a1521d1a8ab02121 to your computer and use it in GitHub Desktop.
JXA macOS Automation: Fast User Switching
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env osascript -l JavaScript | |
const USER = 'stephan'; | |
function run() { | |
const ControlCenterPID = | |
$.NSRunningApplication.runningApplicationsWithBundleIdentifier( | |
'com.apple.controlcenter', | |
).firstObject.processIdentifier; | |
const ControlCenter = $.AXUIElementCreateApplication(ControlCenterPID); | |
const $ccMenu = Ref(); | |
$.AXUIElementCopyAttributeValue(ControlCenter, 'AXChildren', $ccMenu); | |
const $ccMenuItems = Ref(); | |
$.AXUIElementCopyAttributeValue($ccMenu[0].js[0], 'AXChildren', $ccMenuItems); | |
const $itemDesc = Ref(); | |
const ccUserMenu = $ccMenuItems[0].js.find( | |
(item) => | |
$.AXUIElementCopyAttributeValue(item, 'AXDescription', $itemDesc) || | |
!!`${$itemDesc[0].js}`.match(/user/i), | |
); | |
$.AXUIElementPerformAction(ccUserMenu, 'AXPress'); | |
delay(0.1); | |
const $ccWindows = Ref(); | |
$.AXUIElementCopyAttributeValue(ControlCenter, 'AXWindows', $ccWindows); | |
const $ccUserWindowContent = Ref(); | |
$.AXUIElementCopyAttributeValue( | |
$ccWindows[0].js[0], | |
'AXChildren', | |
$ccUserWindowContent, | |
); | |
const $ccUsers = Ref(); | |
$.AXUIElementCopyAttributeValue( | |
$ccUserWindowContent[0].js[0], | |
'AXChildren', | |
$ccUsers, | |
); | |
const $userDesc = Ref(); | |
const userButton = $ccUsers[0].js.find( | |
(user) => | |
$.AXUIElementCopyAttributeValue( | |
user, | |
'AXAttributedDescription', | |
$userDesc, | |
) || !!`${$userDesc[0].string.js}`.match(new RegExp(USER, 'i')), | |
); | |
$.AXUIElementPerformAction(userButton, 'AXPress'); | |
return 0; | |
} | |
// prettier-ignore | |
(() => { | |
ObjC.import('Cocoa'); | |
ObjC.bindFunction('AXUIElementPerformAction', ['int', ['id', 'id']]); | |
ObjC.bindFunction('AXUIElementCreateApplication', ['id', ['unsigned int']]); | |
ObjC.bindFunction('AXUIElementCopyAttributeValue',['int', ['id', 'id', 'id*']]); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment