| paths |
|
|---|
OpenLogi's Objective-C FFI runs on objc2 (0.6 / framework crates 0.3):
Retained<T> smart pointers, typed framework objects, define_class! for
subclasses. It is spread across crates rather than one directory β the GUI owns
almost none of it. The whole workspace's native macOS surface is exactly these
files; keep this table in sync when you add or move one:
| File | What it carries |
|---|---|
openlogi-agent/src/activity_macos.rs |
the device-I/O gate's levels: the IOPMConnection powerd subscription (hand-declared SPI, see below) and the CGSessionCopyCurrentDictionary console read |
openlogi-agent/src/status_item.rs |
safe objc2 wrappers over NSStatusItem / NSMenu / NSMenuItem |
openlogi-agent/src/tray.rs |
the menu-bar semantics, MenuTarget + SessionTarget (define_class!), the Accessory NSApplication loop, the NSWorkspace session (fast-user-switch) notifications |
openlogi-agent-core/src/watchers/camera.rs |
the CoreMediaIO "camera is running" property read |
openlogi-camera/src/capture_macos.rs |
AVCaptureSession capture + the define_class! frame delegate, and the Camera TCC prompt |
openlogi-camera/src/macos.rs |
AVCaptureDevice enumeration (class! + msg_send!) |
openlogi-camera/src/uvc_macos.rs, .../uvc_macos/iokit.rs |
IOKit USB / UVC control transfers; every unsafe in the macOS UVC backend lives in iokit.rs |
openlogi-desktop/src/platform/registration/macos.rs |
SMAppService registration of the agent's launchd service (the login-item side of the agent lifecycle; the GUI must own it β the API resolves the plist against the calling app's bundle) |
openlogi-desktop/src/platform/os.rs |
NSProcessInfo OS version + the NSAppearance titlebar sync |
openlogi-hid/src/permissions.rs |
IOHIDCheckAccess / IOHIDRequestAccess (the prompting half of Input Monitoring) |
openlogi-hook/src/macos.rs |
the CGEventTap (on core-graphics, see below), the Accessibility-trust check/prompt, the off-tap NSWorkspace frontmost-app read, and the CGGetEventTapList enumeration |
openlogi-hook/src/macos/foreground.rs |
the NSWorkspace activation observer, the NSRunningApplication conversion behind every frontmost-app read, and the Safari PID snapshot |
openlogi-hook/src/macos/probe.rs |
Flow's pointer probe: the modifier read (CGEventSourceFlagsState), CGGetActiveDisplayList / CGDisplayBounds, and the CGWarpMouseCursorPosition warp |
openlogi-hook/src/macos/secure_input.rs |
the Secure Event Input read: IsSecureEventInputEnabled (hand-declared, see below) and the kCGSSessionSecureInputPID entry of CGSessionCopyCurrentDictionary, named through foreground.rs's NSRunningApplication conversion |
openlogi-hook/src/macos/sender.rs |
the HID sender-id lookup and the IOKit registry walk that resolves it to a device |
openlogi-inject/src/inject/macos.rs |
CGEvent key and click synthesis, media-key NSEvents |
openlogi-inject/src/inject/macos/scroll.rs |
CGEvent scroll synthesis, including the continuous-scroll phase fields, and the zoom retyping of wheel events while Accessibility Zoom's scroll modifiers are held (+[NSEvent modifierFlags] and the com.apple.universalaccess defaults) |
openlogi-inject/src/inject/macos/ax.rs |
the shared AXUIElement attribute reads (CFRetained adoption of the Copy-rule out-pointer) and AXChildren iteration |
openlogi-inject/src/inject/macos/browser.rs |
Safari's toolbar-button navigation over ax.rs, and the off-thread NSWorkspace Safari validation |
openlogi-inject/src/inject/macos/menu_shortcut.rs |
the hidden probe NSMenu AppKit remaps for the keyboard layout, and pressing the frontmost app's matching menu item through AX |
openlogi-inject/src/inject/macos/{app_services,dock,symbolic_hotkey}.rs |
the dlopen'd private SPIs: CoreDockSendNotification and the CGS symbolic-hotkey trio |
openlogi-inject/src/inject/macos/keyboard_layout.rs |
the active keyboard layout's uchr data (Text Input Source Services, read on the main thread) and UCKeyTranslate over it |
openlogi-inject/src/inject/macos/main_thread.rs |
the bounded hand-off of main-thread work from the action worker to the main queue (dispatch2) |
openlogi-inject/src/inject/macos/virtual_keyboard/device.rs |
the IOHIDUserDevice virtual keyboard that key synthesis types through: its creation (which needs the com.apple.developer.hid.virtual.device entitlement) and its timestamped input reports. The report state in virtual_keyboard.rs above it is safe code |
openlogi-overlay/src/platform.rs |
the Actions Ring helper's window policy: accessory activation, a non-activating panel that a click does not make key, the NSEvent global click-away monitor (block2), and CGGetActiveDisplayList / CGDisplayBounds |
openlogi-permissions/src/macos.rs |
non-prompting permission reads + System-Settings deep links; +[CBManager authorization] via an AnyClass lookup |
Every rule below binds all of them, whichever crate they live in.
Spawning the agent under its own macOS TCC identity (so its Accessibility /
Input-Monitoring grants aren't attributed to the GUI, issue #214) lives in the
external disclaim crate β posix_spawn +
the private responsibility_spawnattrs_setdisclaim, not ObjC.
openlogi-desktop/src/services/ipc/launch.rs's spawn_agent uses it; there is no
in-tree FFI for it. Likewise, installed-application discovery and icon
rendering for per-app profiles live in the external
appcatalog crate (NSWorkspace +
NSBitmapImageRep there, not here); openlogi-desktop/src/platform/app_icon.rs
only wraps its PNG bytes into a gpui::Image. The privacy-grant change
notifications β the com.apple.accessibility.api distributed notification and
tccd's com.apple.tcc.access.changed Darwin notification β are observed by the
external axwatch crate
(CFNotificationCenter there, not here); openlogi-hook's grant::ProbeCue
and openlogi-agent-core's grant watchers only consume its wakes. The System
Settings drag guide for the agent's Accessibility and Input Monitoring grants
lives in the external gpui-tcc crate
(the NSWorkspace icon and frontmost-app reads, the
CGWindowListCopyWindowInfo lookup of the System Settings window, and the
overlay NSWindow level and NSVisualEffectView material are there, not
here); openlogi-desktop/src/platform/permission_guide.rs only decides when
to present it and which agent bundle it holds.
The rest of openlogi-desktop/src/platform/ (updater.rs, on gpui_updater,
and permission_guide.rs, on gpui_tcc) carries no ObjC FFI β don't add
any. Neither do openlogi-core's single_instance.rs (fs4 lock) or
openlogi-agent's autostart/macos.rs (legacy-plist cleanup via std::fs).
objc2 makes ownership a value: a Retained<T> releases exactly once on Drop.
That is why this code can't reproduce issue #99 (a +1 NSString leaked on
every 2 s tray refresh under the old cocoa/objc 0.x path).
- Every string is
NSString::from_str(s)β aRetained<NSString>used as a borrowed temporary; it releases at the end of the statement. There is nonsstring()helper and no autorelease pool in the tray path β don't reintroduce either. alloc/init/new/copyand the framework getters returnRetained<T>/Option<Retained<T>>; you keep what you need and letDropfree it.- IOKit handles get the same treatment by hand in
camera/src/uvc_macos/iokit.rs:IoObject,UsbInterfaceandSeizedDevicerelease on drop, and CoreFoundation values arrive asCFRetained. Never hand-balance a release. - Never call manual
retain/release/autorelease, add rawcocoa/objc0.x, or build a bespoke retain/release helper layer β that re-derivesRetained<T>, worse. AX navigation adopts Copy-rule outputs asCFRetainedand downcasts their runtime types before use.
NSMenuandNSMenuItemare#[thread_kind = MainThreadOnly]β theirRetainedis!Send.NSStatusItem,NSImage,NSWorkspaceareAnyThread(theirRetainedis still!Send, because a bare ObjC object is!Sync).- Constructing a
MainThreadOnlyobject needs aMainThreadMarker(NSMenu::new(mtm),NSMenuItem::alloc(mtm),status_item.button(mtm)). Mutating an already-heldRetained<NSMenuItem>(setTitle/setHidden) does not β possessing the!Sendhandle already proves you're on the main thread. - The
mtmis obtained withMainThreadMarker::new()at each process's entry into AppKit βtray::run_app_loopin the agent,configure_applicationin the overlay,set_app_appearancein the GUI β and threaded down from there. Do not copy gpui's ownNSThread.isMainThread+dispatch2runtime-check idiom; we use the compile-timeMainThreadMarkerguarantee. - The tray needs no
staticand nothread_local:run_app_loopis-> !, so the status item, itsMenuTarget, theSessionTargetand the powerdPowerConnectionare bound as locals that outliveNSApplication::run(). They must stay bound β menu items reference their target weakly, the notification center does the same, and the power callback'sparampoints into the connection's ownArc. openlogi-camera's frame delegate is deliberately the opposite: anNSObjectsubclass with nothread_kind, because AVFoundation drives it on a background dispatch queue. Its one ivar is the owning session'sArc<FrameSink>(Send + Sync), so which session a frame belongs to is carried by ownership instead of process-global statics.
There is no general TCC API: Apple ships no public way to enumerate or request
TCC state generically, and TCC.db is SIP-protected (reading it needs Full Disk
Access). Crates that paper over this exist β permission-flow covers many
services β but none fit here, for the reason in the rules below. Every permission
is its own framework call, so "the TCC layer" is just this table:
| Permission | Crate | Symbol | Read / prompt |
|---|---|---|---|
| Accessibility | objc2-application-services (HIServices + AXUIElement) |
AXIsProcessTrusted / AXIsProcessTrustedWithOptions |
both in openlogi-hook |
| Input Monitoring / Post Event | objc2-io-kit (hidsystem) |
IOHIDCheckAccess / IOHIDRequestAccess |
read in openlogi-permissions, prompt in openlogi-hid |
| Bluetooth | objc2 class lookup (see below) |
+[CBManager authorization] |
openlogi-permissions |
| Camera / microphone | openlogi-camera (capture_macos.rs) |
+[AVCaptureDevice authorizationStatusForMediaType:] / requestAccessForMediaType: |
openlogi-camera |
| Screen Recording (unused) | objc2-core-graphics |
CGPreflightScreenCaptureAccess |
β |
| Full Disk Access (unused) | β | no API; only a probe of a protected path | β |
Rules:
- Never re-declare a permission API in a
#[link(name = "β¦", kind = "framework")] extern "C"block and never hardcode its discriminants. The generated bindings are typed (IOHIDRequestType::ListenEvent,IOHIDAccessType::Granted), which is the workspace rule about wire values in another guise β a bareIOHIDCheckAccess(1) == 0says nothing.IOHIDCheckAccessis a safe fn inobjc2-io-kit; the AX pair isunsafeonly because the options dictionary is untyped. - Add these crates with
cargo add β¦ --no-default-features --features <modules>(they are huge and gated per C header), then declare the version once in the workspace table withdefault-features = falseand pick features per crate. Umbrella-feature trap: a leaf feature is not enough βAXUIElementalso needsHIServices, or the symbols silently don't exist. - Checking never prompts; prompting belongs to whoever owns the resource.
The agent raises the Accessibility prompt (it owns the tap) and calls
IOHIDRequestAccessbefore opening HID; the GUI only reads status and deep-links to System Settings (open_pane, or thegpui-tccdrag guide, which opens the same pane and prompts nothing). Never call the prompting half from the GUI β the grant would land on the wrong code-signing identity (issue #214, seedisclaim). This split is also why the ready-made permission crates don't fit: they model one app asking for itself.permission-flowadditionally brings its own onboarding UI and links the Swift runtime into every downstream binary;macos-accessibility-clientis a raw-externwrapper where this file requires typed bindings. - TCC matches the full Designated Requirement, not the bundle ID (TN3127).
Re-signing one bundle ID with a different kind of certificate leaves a record
that can never match again, and toggling the checkbox does not rewrite the
stored
csreq. Not hypothetical: 0.6.24β0.6.26 shipped.devbundle IDs signed with Developer ID (a344e22f), so a dev build of the same ID signed Apple Development meets a stale Developer ID requirement andtccdlogsFailed to match existing code requirement. Suspect this first when a grant silently does nothing;tccutil reset <service> <bundle-id>clears the record, and a never-used bundle ID (or a fresh user/VM) is the only clean re-test. - Accessibility does not use
tccd's generic consent sheet, so its logs read oddly: a request answers "Service kTCCServiceAccessibility does not allow prompting; returning Unknown" withDB Action:None. That describes thetccdpreflight only β the flow continues intouniversalAccessAuthWarn, which makes its ownTCCAccessCopyInformationcall and pre-creates an unchecked row when no matching record exists. ReadingDB Action:Noneas "nothing is ever written" is wrong, and it points debugging away from the stale-requirement case above. CBCentralManager.authorizationdeliberately stays anAnyClass::get+msg_send!lookup rather thanobjc2-core-bluetooth: a missing class must degrade toUnknown, not panic.
The bundles declare macOS 13.0 (MACOSX_DEPLOYMENT_TARGET in the release
workflows, LSMinimumSystemVersion in the Info.plist templates under
crates/openlogi-desktop/bundle/), but objc2 generates every symbol a header
declares regardless of its API_AVAILABLE(macos(N)), and Rust has no
@available check. A function newer than the floor merely crashes
when called on an older macOS; an extern static β SMAppServiceErrorDomain
is macos(15.0) while the rest of SMAppService is 13.0 β is bound by dyld
at load, so the whole binary is refused before main (#1279; 0.8.2 and 0.8.3
would not launch on 13 or 14). CI never runs on the floor release, so nothing
catches it after the fact.
Before using a generated symbol, read its API_AVAILABLE in the SDK header
(xcrun --show-sdk-path). If it is newer than the floor: for a string
constant, spell the documented value out (the error domain above is the
literal "SMAppServiceErrorDomain" on every release since 13); for a
function, gate the call on the OS version and resolve it with dlsym β
never import it strongly.
Typed framework crates are the default; a hand-written unsafe extern "C" block
is allowed only for symbols objc2 has no bindings for, and it stays next to
its single user. The current set, all deliberate:
openlogi-hook:CGEventCopyIOHIDEvent/IOHIDEventGetSenderIDβ undocumented, no bindings anywhere.openlogi-hook/src/macos/secure_input.rs:IsSecureEventInputEnabledβ Carbon HIToolbox, whichobjc2-carbonskips. It takes no arguments and has no precondition, so the block declares itsafe fn.openlogi-agent/src/activity_macos.rs: theIOPMConnectionSPI (IOPMConnectionCreate/SetNotification/SetDispatchQueue/AcknowledgeEvent/Release/GetSystemCapabilities) β exported by IOKit since 10.6 and whatpmsetis built on, but declared only in Apple's open-sourceIOKitUser/pwr_mgt.subproj/IOPMLibPrivate.h, soobjc2-io-kitcannot generate it. It is the only API that reports a DarkWake β FullWake transition, which is why the gate needs it (seedocs/DECISIONS.md).openlogi-camera: the AVFoundation / CoreMedia / CoreVideo / CoreFoundation statics and functions its capture and enumeration paths need (AVMediaTypeVideo,CMSampleBufferGetImageBuffer, theCVPixelBufferaccessors,CFRunLoopRunInMode,dispatch_queue_create) β AVFoundation has no typed framework crate in the tree.openlogi-agent-core/src/watchers/camera.rs: the CoreMediaIO property API β same reason.openlogi-inject: thedlopen/dlsym-resolved private SPIs (CoreDockSendNotification, the CGS symbolic-hotkey trio), and inkeyboard_layout.rsText Input Source Services,LMGetKbdType, andUCKeyTranslateβobjc2-carbonskips HIToolbox andobjc2-core-servicesskips CarbonCore.UCKeyTranslate's lengths areUniCharCount, anunsigned long:usize, notu32.- the
disclaimcrate:responsibility_spawnattrs_setdisclaim(private SPI).
openlogi-camera's AVAuthorizationStatus integers remain on the
migrate-when-touched list: they belong in objc2-av-foundation.
Don't copy that pattern into new code.
unsafe_code is deny workspace-wide; every file that needs it opts in with a
scoped #[expect(unsafe_code, reason = "β¦")], and every block does one operation
under a SAFETY comment. Where it currently lives on macOS:
agent/status_item.rsβNSMenuItem::initWithTitle_action_keyEquivalent+setTarget:(raw selector; the target is a weak reference, which is why the tray keepsMenuTargetalive for the app's lifetime).agent/activity_macos.rsβ theIOPMConnectioncalls, its C callback (theparamis the gate thePowerConnectionkeeps alive, andDropdrains the delivery queue before thatArcgoes), and theCGSessiondictionary cast.agent/tray.rsβmsg_send![super(this), init], the notification-centeraddObserver:selector:name:object:, and theNSWorkspaceSession*Notificationname statics.agent/lifecycle/armed_session.rsβSessionGetInfo(objc2-security,AuthSession) andsysctlbyname("kern.bootsessionuuid"): two out-pointer reads that identify the login session, so the dormancy gate can re-arm a crash respawn.hook/macos.rsβ the whole tap (Core Graphics / Core Foundation C APIs),AXIsProcessTrusted[WithOptions]with the two extern statics they need (kAXTrustedCheckOptionPrompt,kCFBooleanTrue), and thekern.sleeptime/kern.waketimesysctlbynamereads the lifecycle watchdog gates its gap discount on. Its module-wide#![expect(unsafe_code)]covers the three files below as well.hook/macos/foreground.rsβ theNSWorkspaceactivation-observer registration and typed notification payload, andNSString::to_str(pool)(the borrow is tied to the pool).hook/macos/secure_input.rsβ theCGSessiondictionary cast.hook/macos/sender.rsβ the sender-idexterncalls and the IOKit registry walk, including the Create-ruleCFString/CFNumberwraps.hook/macos/probe.rsβ theCGGetActiveDisplayListout-pointers; the rest of Flow's pointer probe is safeobjc2-core-graphics.inject/macos/ax.rsβ AX attribute-copy out-pointers and the uncheckedAXChildrenelement type; each child is downcast before use.inject/macos/browser.rsβ typed AX creation,AXPress, andNSString::to_str(pool)for Safari validation.inject/macos/menu_shortcut.rsβ AX application creation andAXPresson the frontmost app's menu item. The probe menu itself is safeobjc2-app-kiton the main thread: AppKit remaps an item for the keyboard layout only once the run loop has turned with it in the main menu, so the agent installs the probes beforeNSApplication::run, and workers read them throughmain_thread.rs.inject/macos/keyboard_layout.rsβ the input-source copy and property read,LMGetKbdType, andUCKeyTranslateover the copieduchrbytes. Text Input Source Services must run on the main thread (HIToolbox crashes when another thread reads the layout), so a worker hands the read to the main queue and waits a bounded time; onlyUCKeyTranslate, a pure function of the copied data, runs on the worker.inject/macos/virtual_keyboard/device.rsβIOHIDUserDevice::with_properties,handle_report_with_time_stampover the eight-byte report,mach2'smach_absolute_timefor its timestamp, and theSendimpl that lets the process-wide slot hold the device. The device is never scheduled on a dispatch queue, so it needs noActivate/Cancelpair: releasing it removes it.permissions/macos.rsβ the CoreBluetooth force-link and theCBManagerclass-method send.IOHIDCheckAccessneeds none:objc2-io-kitexposes it as a safe fn, inopenlogi-permissionsandopenlogi-hidalike.overlay/platform.rsβNSEvent::removeMonitorand theCGGetActiveDisplayList/CGDisplayBoundspair.desktop/platform/os.rsβ reading AppKit'sNSAppearanceNamestatics to setNSApp.appearance.desktop/platform/registration/macos.rsβ theSMAppServicecalls (all generated bindings areunsafe fns). Together withos.rs, the GUI's entireunsafesurface.camera/{capture_macos,uvc_macos/iokit}.rsβ the AVFoundation capture FFI and the IOKit USB plug-in;uvc_macos/iokit.rsdeliberately concentrates everyunsafeof the macOS UVC backend so the descriptor parser above it is ordinary safe code.
The event tap in openlogi-hook/src/macos.rs is not migrated.
objc2-core-graphics 0.3 does expose CGEvent::tap_create/tap_enable (it's
not an availability gap), but the tap's Accessibility-revoke freeze-hazard
state machine (the 500 ms run-loop slice + self-disable on its own thread) is
load-bearing and must stay byte-for-byte. Only the NSWorkspace frontmost-app
read moved to objc2. Don't "modernize" the tap casually.
Code on the main run loop needs no pool (Retained frees deterministically);
code on a bare thread does, because the framework still autoreleases internal
temporaries. The call sites that keep an explicit
objc2::rc::autoreleasepool, and the only ones that should:
openlogi-hook's frontmost-application reads and activation observer β the watcher and notification callback may run on threads with no run loop, andto_strborrows its UTF-8 view from the pool (both the bundle id and the localized name). Registration and removal use the same boundary so AppKit's internal autoreleased temporaries are drained as well. The Secure Event Input app read names its app through the same conversion, on the secure-input watcher thread, under its own pool.openlogi-inject'spost_media_keyβ the hook/gesture dispatch threads, where both theNSEventcreation and theCGEventgetter autorelease temporaries.openlogi-inject'sax_browser_navigateβ the action worker, whereto_strborrows the current frontmost app's bundle id while validating the captured Safari process.openlogi-inject's menu-shortcut press β the action worker, where theNSWorkspacefrontmost-app reads autorelease temporaries.openlogi-inject's wheel-event zoom check β the scroll worker and hook threads, where theNSUserDefaultssuite read autoreleases temporaries.openlogi-camera's device enumeration β everyAVCaptureDevicestring is copied out before the pool drains, so noRetained<T>escapes it.
cocoa / objc 0.x are gone from every crate's direct deps (they remain in
Cargo.lock only transitively via gpui β expected). Use cargo add for objc2
framework crates, then verify that Cargo.lock still carries one version-aligned
gpui-pre stack and the workspace's pinned Kit release.
Every ObjC / Core-framework crate is declared once in the workspace table β
objc2, objc2-app-kit, objc2-foundation, objc2-core-foundation,
objc2-core-graphics, objc2-application-services, objc2-io-kit,
objc2-service-management, objc2-security, block2, core-graphics, core-foundation. The header-gated ones carry
default-features = false there, and each member inherits with
workspace = true and adds only the feature modules it uses. A new one belongs
in that table too, never inline in a member manifest: the unified version is what
keeps the native framework types compatible across the app and GPUI. Trim a
member's feature list when the code that needed it moves out.
The GUI crates need the real Xcode toolchain for gpui's Metal shader compile:
DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer,
SDKROOT=$(xcrun --show-sdk-path), xcbuild stripped from PATH. Behavioural
checks (tray icon shows, Open/Quit fire, device rows update, the ring follows the
cursor's display) need the running app. Confirm an FFI memory fix with leaks
over a multi-minute session: the CFString/NSString count must stay flat
(the empirical inverse of #99).