Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions omarchy-mac/README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# omarchy-mac

Apple Silicon defaults and support services for Omarchy. Version: `0.1.3` (candidate). This add-on complements `omarchy` and `omarchy-settings`; it selects no kernel and contains no installer or repository trust configuration. It covers what stays on an installed Mac; installing one is the job of the [Omarchy Installer](https://github.com/omacom/omarchy-mac-installer), and boot support is the separate `omarchy-mac-boot` package beside this one.
Apple Silicon defaults and support services for Omarchy. Version: `0.1.4` (candidate). This add-on complements `omarchy` and `omarchy-settings`; it selects no kernel and contains no installer or repository trust configuration. It covers what stays on an installed Mac; installing one is the job of the [Omarchy Installer](https://github.com/omacom/omarchy-mac-installer), and boot support is the separate `omarchy-mac-boot` package beside this one.

## Build and stage

Expand All @@ -14,7 +14,7 @@ Upgrade the matching runtime, settings and add-on candidates in one pacman trans

Run `omarchy-mac-setup-system` as root on the target hardware (inside its target chroot for offline provisioning). An optional absolute root argument supports staging against the same target hardware without a bus. It exits without changes unless the runtime's Apple predicate `omarchy-hw-apple-silicon` holds (`omarchy-hw-platform` reports `aarch64-apple`, or `apple-silicon` on a runtime from before the platform rename), and fails if the detector does. It removes the Intel Mac Broadcom quirk (`options brcmfmac feature_disable=0x82000`, which breaks Apple Silicon Wi-Fi) from `/etc/modprobe.d/brcmfmac.conf` wherever an unguarded runtime migration appended it: only that exact line, with the comment block and blank line written right above it, goes; the file goes when nothing but blank lines is left, a link is left alone with the manual fix, and the initramfs rebuild it owes is recorded under `/var/lib/omarchy/migrations/1789172112-initramfs-pending`, which the runtime's migration finishes. It enables resume recovery only for BCM4378, BCM4387 and BCM4388 on Apple Silicon; Intel/T2 Macs are excluded. It is the only enabler of `speakersafetyd`, without which the kernel keeps the speakers muted: it applies the package's `80-omarchy-mac-audio.preset` once speakersafetyd is installed, so `/etc` presets that sort before it or replace it by name, masks and later explicit disables win, and image builders that apply presets get the same result. A live run also restarts a speakersafetyd left dead by a start-limit. No NetworkManager restart or driver reload occurs during setup. The backend applies when NetworkManager next starts; notch changes apply when appledrm next loads. A live run gives iwd a profile for each Wi-Fi network NetworkManager saved with its key before the switch, as NetworkManager itself does for a new connection, so saved networks keep connecting instead of reading as a wrong password. The greeter drop-in needs no setup: from the next `sddm` start it holds the greeter, for at most 10 s, until Apple's display controller has replaced the boot framebuffer.

Run `omarchy-mac-setup-user` as each target user with their HOME/XDG directories. It enables the vendor unit without a session bus. It writes nothing into the user's Hyprland files; a block an earlier version appended to `input.lua` or `looknfeel.lua` stays, as the user's. With a live bus, reached only through XDG_RUNTIME_DIR (which `sudo -i` clears), it reloads the user manager, reports the effective unit and starts the mapper. The mapper makes the microphone a typed stereo source, `omarchy_asahi_mic` ("MacBook Microphone"): pipewire-pulse's `module-remap-source` records asahi-audio's mono DSP source, which WirePlumber links to the left side and the mapper to the right, and offers an `Audio/Source` with front-left and front-right, the shape of a stock microphone, so the desktop's audio panel drives its volume, mute and level meter as it does any other. It makes that source the default input only if a brief sample finds signal, and hands a silent one back to the DSP source. A muted mapping is the user's microphone mute and is left alone. On upgrade from 0.1.2 the mapper replaces 0.1.2's virtual source of the same name (an `Audio/Source/Virtual`, which the panel gives no level meter) on its next start, keeping its gain, mute and selection. Provisioning and first run call setup; subsequent session starts only start the enabled unit, without reloading the user manager or repeating setup. The first desktop session does not depend on a bus existing during installation. Custom fragments, masks, activation links and headset or speaker policies are preserved; setup markers preserve explicit disables after initial setup. User gain state remains in `omarchy/asahi-mic-gain.json` under XDG_STATE_HOME. The desktop saves that state before restarting audio.
Run `omarchy-mac-setup-user` as each target user with their HOME/XDG directories. It enables the vendor unit without a session bus. It writes nothing into the user's Hyprland files; a block an earlier version appended to `input.lua` or `looknfeel.lua` stays, as the user's. With a live bus, reached only through XDG_RUNTIME_DIR (which `sudo -i` clears), it reloads the user manager, reports the effective unit and starts the mapper. The mapper makes the microphone a typed stereo source, `omarchy_asahi_mic` ("MacBook Microphone"): pipewire-pulse's `module-remap-source` records asahi-audio's mono DSP source, which WirePlumber links to the left side and the mapper to the right, and offers an `Audio/Source` with front-left and front-right, the shape of a stock microphone, so the desktop's audio panel drives its volume, mute and level meter as it does any other. It makes that source the default input only if a brief sample finds signal, and hands a silent one back to the DSP source. A muted mapping is the user's microphone mute and is left alone. On upgrade from 0.1.2 the mapper replaces 0.1.2's virtual source of the same name (an `Audio/Source/Virtual`, which the panel gives no level meter), keeping its gain, mute and selection. pacman restarts no user service, so a running mapper watches its own file: once an upgrade has replaced it and the transaction has ended, it runs the new file in place, within a few seconds, and that reconciles the live session. At session start the mapper subscribes to audio events before its first pass, so a DSP microphone that appears after it starts is mapped and made the default input at once. Provisioning and first run call setup; subsequent session starts only start the enabled unit, without reloading the user manager or repeating setup. The first desktop session does not depend on a bus existing during installation. Custom fragments, masks, activation links and headset or speaker policies are preserved; setup markers preserve explicit disables after initial setup. User gain state remains in `omarchy/asahi-mic-gain.json` under XDG_STATE_HOME. The desktop saves that state before restarting audio.

A runtime whose `omarchy-lifecycle-dispatch` has the `setup-system` and `setup-user` operations (the platform setup seam, which registers `/usr/lib/omarchy/mac` for Apple Silicon) reaches both through the entrypoints this package stages there; an older runtime calls the two commands itself: `setup-system [image-first-boot]` (root, from the last hardware leaf and on an image's first boot, where it downloads nothing; it rebuilds no boot file) and `setup-user` (as the user being set up, at finalization and again in first run). Each re-checks the platform.

Expand Down
116 changes: 106 additions & 10 deletions omarchy-mac/bin/omarchy-audio-asahi-mic-map
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,10 @@ outage = dict(since=None, notified=False, repaired=False)
recheck = dict(at=None)
# The mapping's Pulse index, so a change of its own gain or mute is saved.
mapping_index = dict(value=None)
# A package upgrade replaces this file under a running watcher, and pacman
# restarts no user service: the watcher runs the new file itself.
PACMAN_LOCK = Path('/var/lib/pacman/db.lck')
RELOAD = 'reload'


class Deferred(Exception):
Expand Down Expand Up @@ -688,6 +692,56 @@ def run_once(audio, runtime, state, save_only=False, checked=None):
reconcile(audio, state, save_only, checked)


def pacman_running():
for comm in Path('/proc').glob('[0-9]*/comm'):
with contextlib.suppress(OSError):
if comm.read_text().strip() == 'pacman':
return True
return False


class Program:
# The watcher's own file is replaced once it differs from the one started,
# is unchanged since the previous look and no pacman transaction (which may
# upgrade the interpreter too) holds the database; a lock no pacman holds is stale.
def __init__(self, path, lock=None, running=pacman_running):
self.path = Path(path)
self.lock = Path(PACMAN_LOCK if lock is None else lock)
self.running = running
self.started = self.seen = self.signature()
self.retry_at = None
self.backoff = 2.0

def signature(self):
try:
status = os.stat(self.path)
except OSError:
return None
return status.st_dev, status.st_ino, status.st_size, status.st_mtime_ns

def replaced(self):
current = self.signature()
previous, self.seen = self.seen, current
if current is None or current == self.started or current != previous:
return False
if self.retry_at is not None and time.monotonic() < self.retry_at:
return False
if self.lock.exists() and self.running():
return False
return os.access(self.path, os.X_OK)

def run(self):
# Returns only when the new file cannot be run (the interpreter may be
# mid-replacement): the old code goes on and tries again, backing off.
print('Running the updated microphone mapper', file=sys.stderr, flush=True)
try:
os.execv(self.path, [str(self.path), *sys.argv[1:]])
except OSError as error:
print('Could not run the updated microphone mapper: ' + str(error), file=sys.stderr, flush=True)
self.retry_at = time.monotonic() + self.backoff
self.backoff = min(self.backoff * 2, 300.0)


class Subscription:
# Wakes the supervisor when the mapping may need repair: a sink, source,
# card or module appeared or vanished, a card or module changed, or the
Expand All @@ -703,9 +757,15 @@ class Subscription:
EVENT = re.compile(rb"^Event '(new|remove)' on (sink|source|card|module) #|^Event 'change' on (card|module|server) #")
SOURCE_CHANGE = re.compile(rb"^Event 'change' on source #([0-9]+)$")

def __init__(self, command=('pactl', 'subscribe'), quiet=0.5, settle=5.0, backstop=600.0, retry=2.0):
def __init__(self, command=('pactl', 'subscribe'), quiet=0.5, settle=5.0, backstop=600.0, retry=2.0, stale=None, poll=2.0):
self.command = list(command)
self.quiet, self.settle, self.backstop, self.retry = quiet, settle, backstop, retry
# stale() is asked every poll seconds, across waits, whether to stop
# for RELOAD. A pass a moment after subscribing covers a device that
# appeared before pactl had registered the subscription.
self.stale, self.poll = stale, poll
self.next_poll = None
self.confirm = None
self.process = None
self.buffer = b''
# Save-only wakes never reset the backstop, or a busy microphone
Expand All @@ -718,6 +778,8 @@ class Subscription:
except OSError:
self.process = None
self.buffer = b''
if self.process is not None:
self.confirm = time.monotonic() + 1.0
return self.process is not None

def stop(self):
Expand All @@ -743,22 +805,47 @@ class Subscription:

def full(self):
self.last_full = time.monotonic()
self.confirm = None
return False

def reload_due(self):
if self.stale is None:
return False
now = time.monotonic()
if self.next_poll is None:
self.next_poll = now + self.poll
if now < self.next_poll:
return False
self.next_poll = now + self.poll
return self.stale()

def wait(self, limit=None):
# True: only the mapping's gain or mute may have changed.
if self.process is None and not self.start():
time.sleep(self.retry)
# True: only the mapping's gain or mute may have changed. RELOAD: the
# watcher's program was replaced.
# A full pass follows every subscription, so a device that appeared
# while nothing listened (the DSP at login) is still mapped.
if self.reload_due():
return RELOAD
if self.process is None:
if not self.start():
time.sleep(self.retry)
return self.full()
started = time.monotonic()
hard = self.last_full + self.backstop if limit is None else min(self.last_full + self.backstop, started + limit)
if self.confirm is not None:
hard = min(hard, self.confirm)
due = None
latest = None
repair = False
while True:
if self.reload_due():
return RELOAD
now = time.monotonic()
deadline = hard if due is None else min(due, latest) if repair else min(due, latest, hard)
if deadline <= now or not select.select([self.process.stdout], [], [], deadline - now)[0]:
wake = deadline if self.next_poll is None else min(deadline, self.next_poll)
if wake <= now or not select.select([self.process.stdout], [], [], wake - now)[0]:
if time.monotonic() < deadline:
continue
if due is None or repair or time.monotonic() >= hard:
return self.full()
return True
Expand All @@ -784,9 +871,11 @@ class Subscription:
latest = now + self.settle


def supervise(operation, wait=None):
subscription = Subscription() if wait is None else None
if subscription is not None:
def supervise(operation, wait=None, program=None):
subscription = None
if wait is None:
subscription = Subscription(stale=None if program is None else program.replaced)
subscription.start()
wait = lambda: subscription.wait(outage_due())
previous_error = None
save_only = False
Expand All @@ -803,7 +892,14 @@ def supervise(operation, wait=None):
if message != previous_error:
print(message, file=sys.stderr, flush=True)
previous_error = message
save_only = bool(wait())
result = wait()
if result == RELOAD:
if subscription is not None:
subscription.stop()
program.run()
save_only = False
else:
save_only = bool(result)
finally:
if subscription is not None:
subscription.stop()
Expand All @@ -825,7 +921,7 @@ def main():
if args.watch:
# Let a service stop unwind through supervise so the subscriber exits too.
signal.signal(signal.SIGTERM, lambda *_: sys.exit(0))
supervise(operation)
supervise(operation, program=Program(os.path.abspath(sys.argv[0])))
else:
try:
operation()
Expand Down
56 changes: 56 additions & 0 deletions omarchy-mac/test/mic-reload-test.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
#!/bin/bash
set -euo pipefail
source "$(dirname "$0")/base-test.sh"
work=$(mktemp -d)
watcher=
cleanup() {
[[ -z $watcher ]] || kill "$watcher" 2>/dev/null || true
rm -rf "$work"
}
trap cleanup EXIT
mkdir -p "$work/bin" "$work/run" "$work/state"
printf '#!/bin/bash\necho "${PLATFORM:-aarch64-apple}"\n' >"$work/bin/omarchy-hw-platform"
stub_apple_predicate "$work/bin"
# The subscriber records its PID and waits; nothing else answers.
cat >"$work/bin/pactl" <<'STUB'
#!/bin/bash
[[ $1 == "subscribe" ]] || exit 1
echo $$ >"$WORK/subscriber"
exec sleep 60
STUB
chmod +x "$work/bin/"*

# A package upgrade replaces the running watcher's file: the watcher runs the
# new file under its own PID with its arguments, and stops its subscriber.
"$ROOT"/install "$work/root"
mapper=$work/root/usr/bin/omarchy-audio-asahi-mic-map
# The host's pacman lock and audio session stay out of it.
cat >"$work/watch.py" <<'WATCH'
import importlib.machinery, importlib.util, sys
from pathlib import Path
loader = importlib.machinery.SourceFileLoader('mapper', sys.argv[1])
spec = importlib.util.spec_from_loader(loader.name, loader)
mapper = importlib.util.module_from_spec(spec); loader.exec_module(mapper)
mapper.PACMAN_LOCK = Path(sys.argv[2])
sys.argv = [sys.argv[1], '--watch']
sys.exit(mapper.main())
WATCH
env -u PULSE_SERVER -u PIPEWIRE_REMOTE WORK="$work" PATH="$work/bin:$PATH" XDG_RUNTIME_DIR="$work/run" XDG_STATE_HOME="$work/state" \
python3 "$work/watch.py" "$mapper" "$work/db.lck" 2>"$work/log" &
watcher=$!
for _ in $(seq 100); do
[[ -s $work/subscriber ]] && break
sleep 0.1
done
subscriber=$(<"$work/subscriber")
printf '#!/bin/bash\necho "$$ $*" >"$WORK/reloaded"\nexec sleep 60\n' >"$work/new"
chmod +x "$work/new"
mv "$work/new" "$mapper"
for _ in $(seq 200); do
[[ -s $work/reloaded ]] && break
sleep 0.1
done
[[ $(<"$work/reloaded") == "$watcher --watch" ]] || fail 'the watcher runs its replaced file in place' "$(cat "$work/log")"
! kill -0 "$subscriber" 2>/dev/null || fail 'the old subscriber stops with the old code'
grep -q 'Running the updated microphone mapper' "$work/log" || fail 'the reload is logged'
pass 'a running watcher runs its upgraded program in place within seconds'
Loading
Loading