Skip to content

Instantly share code, notes, and snippets.

@stephancasas
Last active December 3, 2024 10:27
Show Gist options
  • Save stephancasas/cf3856678ebfa01d05275ebad98fb59a to your computer and use it in GitHub Desktop.
Save stephancasas/cf3856678ebfa01d05275ebad98fb59a to your computer and use it in GitHub Desktop.
Set macOS user accent color
#!/usr/bin/env osascript -l JavaScript
function run(argv) {
ObjC.bindFunction('NSColorGetUserAccentColor', ['int', []]);
ObjC.bindFunction('NSColorSetUserAccentColor', ['bool', ['int']]);
console.log($.NSColorGetUserAccentColor());
console.log($.NSColorSetUserAccentColor(4));
return 0;
}
@roelvangils
Copy link

When I execute this code on macOS 14.1 (23B74), this is the console output:

2023-10-25 22:11:56.864 set-macos-user-accent-color.jxa.js[16574:118724] (null)
2023-10-25 22:11:56.865 set-macos-user-accent-color.jxa.js[16574:118724] (null)

Could this be due tot API changes in macOS?

@stephancasas
Copy link
Author

@roelvangils, it could be. It's a private API, so it's subject to change without notice, but more likely is that you're on an Apple Silicon device and id types are broken in the JXA Obj-C bridge for that architecture.

You can play around with combinations of console.log(myVar.js) and console.log(ObjC.deepUnwrap(myVar)) (where myVar is something you want to log). However, I usually just work directly with the Obj-C in Xcode or LLDB, and then translate it to JXA once I'm ready to make a script.

I'm presently downloading 14.1 on my M2 MBP and will let you...


I was just about ready to post this comment when I noticed that I inexplicably set the return type of NSColorGetUserAccentColor to function. It should be int. Similarly the return type of NSColorSetUserAccentColor should be bool.

With that change, I went ahead and also changed the NSLog calls to to regular JS console.log calls. Because we're working with fundamental types, JXA will automatically handle the runtime casts. However, if you work in JXA frequently, please note that my remark concerning id types still applies.

@roelvangils
Copy link

Thanks, @stephancasas! I don't have much experience with JavaScript for Automation on macOS yet, but this definitely helped me! The script now works fine on my Mac with Apple Silicon. I use it in an Apple Shortcut.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment