From c88455c759b891f53ec00ab2a56255df1493a712 Mon Sep 17 00:00:00 2001 From: astar76 Date: Thu, 5 Nov 2026 19:03:58 -0600 Subject: [PATCH] Islet 0.7.6: a Dynamic Island for notched iPhones SpringBoard tweak for the iPhone XR on iOS 18.7.1 (Dopamine rootless), built without Theos using the swift.org clang and linked on the phone. The island shows music with Apple's audio analyzer and live lyrics, timers, calls, flashlight, screen recording, accessories and their batteries, calendar, notifications with actions, and system popups, in portrait and landscape. Includes a Settings page, a Watch ping hook, an offscreen self test and the tools that capture the showcase video. Co-Authored-By: Claude Opus 5.5 --- .gitignore | 1 + README.md | 65 + VERSION | 1 + pkg/Islet-test.plist | 3 + pkg/Islet.plist | 3 + pkg/IsletPing.plist | 3 + pkg/control | 9 + pkg/postinst | 7 + pkg/postrm | 11 + pkg/prefs/Info.plist | 24 + pkg/prefs/Root.plist | 695 +++++++++ pkg/prefs/entry.plist | 21 + pkg/prefs/icon@2x.png | Bin 0 -> 1668 bytes pkg/prefs/icon@3x.png | Bin 0 -> 2511 bytes src/Islet.m | 3417 +++++++++++++++++++++++++++++++++++++++++ src/IsletPing.m | 55 + src/IsletPrefs.m | 87 ++ src/common.h | 16 + src/isletctl.m | 38 + src/probe.m | 21 + tests/loadtest.m | 14 + tests/prefstest.m | 35 + tests/systest.m | 28 + tools/build-arch | 24 + tools/fat.py | 12 + tools/film | 13 + tools/film-edit.py | 143 ++ tools/lint | 29 + tools/package.sh | 36 + tools/selftest | 13 + 30 files changed, 4824 insertions(+) create mode 100644 .gitignore create mode 100644 README.md create mode 100644 VERSION create mode 100644 pkg/Islet-test.plist create mode 100644 pkg/Islet.plist create mode 100644 pkg/IsletPing.plist create mode 100644 pkg/control create mode 100644 pkg/postinst create mode 100644 pkg/postrm create mode 100644 pkg/prefs/Info.plist create mode 100644 pkg/prefs/Root.plist create mode 100644 pkg/prefs/entry.plist create mode 100644 pkg/prefs/icon@2x.png create mode 100644 pkg/prefs/icon@3x.png create mode 100644 src/Islet.m create mode 100644 src/IsletPing.m create mode 100644 src/IsletPrefs.m create mode 100644 src/common.h create mode 100644 src/isletctl.m create mode 100644 src/probe.m create mode 100644 tests/loadtest.m create mode 100644 tests/prefstest.m create mode 100644 tests/systest.m create mode 100755 tools/build-arch create mode 100755 tools/fat.py create mode 100755 tools/film create mode 100755 tools/film-edit.py create mode 100755 tools/lint create mode 100755 tools/package.sh create mode 100755 tools/selftest diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..567609b --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +build/ diff --git a/README.md b/README.md new file mode 100644 index 0000000..f023b73 --- /dev/null +++ b/README.md @@ -0,0 +1,65 @@ +# Islet + +Dynamic Island for notched iPhones (built for iPhone XR, iOS 18.7.1, Dopamine rootless). SpringBoard tweak in +Objective-C, no Theos: compiled with the swift.org clang + iPhoneOS 18.6 SDK, linked and signed on the phone. + +## What it shows + +- **Ongoing:** now playing (artwork, bars driven only by Apple's audio analyzer, controls, lyrics; stays 10 s after pausing), timers (pause, resume, cancel), + calls (answer, decline, mute, end), flashlight with level buttons, screen recording with a stop button, hotspot, screen + mirroring, microphone, upcoming calendar events and reminders. +- **Notifications:** open in the island with the icon, text, photo and action buttons of the stock banner. Hold one for + the stock expanded view with reply. Sticky and critical alerts, and anything arriving while the island is hidden, keep + the stock banner. Other stock banners start below the island. +- **Accessories:** AirPods and other Bluetooth devices connect with their own icon and battery rings (buds, case), and + connected headphones sit in a bubble left of the island. Each device, and each part of it, alerts on its own at 20 and + 10%. Apple Watch and AirPods get charging and fully charged popups, the Watch its Low Power Mode too. +- **iPhone battery:** charging, low battery at 20/10/5%, fully charged, Low Power Mode. +- **Short popups:** volume (replaces the stock HUD), silent switch with the swinging bell, Focus (replaces the stock + banner), airplane mode, Wi-Fi, cellular data and Bluetooth toggles, rotation lock, AirDrop visibility, network changes, + an app starting on the camera or microphone, lock and unlock (off by default). Popups dismiss themselves. + +## Gestures + +| Gesture | Compact | Unfolded | Popup | +| --- | --- | --- | --- | +| Tap | unfold | open the app, fold | open the app or notification | +| Swipe up | hide for 10 s | fold | dismiss | +| Swipe down | unfold | | | +| Swipe sideways | next activity | next activity | | +| Long press | open the app | open the app | stock expanded notification, or open the app | + +A touch outside an unfolded card folds it, and cards fold themselves after 8 s. With two activities, the second sits in +a small bubble on the right: tap it to swap. Tap the headphones bubble on the left for their batteries. While hidden only +calls and critical battery popups come through. In landscape the same tab stays along the notch with its contents upright: swipe +into the notch to hide, away from it to unfold, along it to switch. An option hides the island during full-screen video. The media card's devices button opens the stock output picker. + +## Settings + +Settings > Islet writes `/var/jb/var/mobile/Library/Preferences/com.astar76.islet.plist` and everything applies live. +`isletctl set ` does the same from a shell. Switches: enabled, music, musicPeek, realVisualizer, timer, +calls, flashlight, flashlightPeek, recording, calendar, reminders, bluetooth, hideAccessoryBanners, deviceBattery, +audioBubble, lowBattery, charging, lowPowerMode, ringer, volumeHUD, airplane, focus, network, rotationLock, airdrop, +systemActivities, sensorPill, lockPill, hideStockHUD, hideStatusPills, bannerOffset, notifications, hideBanners, bubble, +lyrics, onlineLyrics, neteaseLyrics, watchPing, hideLandscape, hideFullscreenVideo. Numbers: hideSeconds, autoFold, deviceLowLevel, musicLinger, calendarLead, notchWidth, notchHeight, compactExtra. `lyricApps` (array of bundle ids) adds players to lyric detection. `blockedBanners` (array of bundle ids) overrides which requesters' stock banners are dropped. + +## Build and test + +- `tools/package.sh` builds `build/com.astar76.islet__iphoneos-arm64.deb`. It runs `tools/lint` first, which + catches the arm64e rule breaks the compiler can't see. +- `tools/selftest` renders every island state offscreen on the phone in a throwaway process, never SpringBoard, runs + the behaviour checks and pulls PNGs and `status.txt` to `build/selftest`. +- `tests/prefstest.m` drives the Settings controller the same way, `tests/loadtest.m` only loads the dylib. +- `tools/film` then `tools/film-edit.py` capture the real animations on the phone in a throwaway process and edit `build/Islet-showcase.mp4`. The film code is compiled in only there, never into a package. +- `isletctl demo <1-36>` triggers any activity on a running island (list in `src/isletctl.m`), `isletctl snap` writes + `/var/jb/var/mobile/islet-snap.png`. +- `isletctl dump` writes `/var/jb/var/mobile/islet-dump.txt` (windows, which hooks installed, state) and + `/var/mobile/islet-batteries.txt`. Each new banner requester is noted in `/var/mobile/islet-banners.log`. + +Everything Islet changes lives in memory inside SpringBoard and one daemon: it writes nothing into iOS's own settings, so a +reboot without the jailbreak is plain stock. Switching it off in Settings stands down at once, and while the island is +hidden or stepped aside iOS's own banners, Focus, silent switch and volume indicators show instead. Settings > Islet > +Reset to Recommended Settings (or `isletctl defaults`) puts every setting back. + +Two SpringBoard crashes in a row within 30 s of starting turn Islet off until Settings > Islet > Clear Crash Guard, +`isletctl reset` or a reinstall. diff --git a/VERSION b/VERSION new file mode 100644 index 0000000..c006218 --- /dev/null +++ b/VERSION @@ -0,0 +1 @@ +0.7.6 diff --git a/pkg/Islet-test.plist b/pkg/Islet-test.plist new file mode 100644 index 0000000..7dd17f5 --- /dev/null +++ b/pkg/Islet-test.plist @@ -0,0 +1,3 @@ + + +FilterBundlescom.apple.Preferences diff --git a/pkg/Islet.plist b/pkg/Islet.plist new file mode 100644 index 0000000..59c3a92 --- /dev/null +++ b/pkg/Islet.plist @@ -0,0 +1,3 @@ + + +FilterBundlescom.apple.springboard diff --git a/pkg/IsletPing.plist b/pkg/IsletPing.plist new file mode 100644 index 0000000..bbf6afb --- /dev/null +++ b/pkg/IsletPing.plist @@ -0,0 +1,3 @@ + + +FilterExecutablescompanionfindlocallyd diff --git a/pkg/control b/pkg/control new file mode 100644 index 0000000..b8772cb --- /dev/null +++ b/pkg/control @@ -0,0 +1,9 @@ +Package: com.astar76.islet +Name: Islet +Version: @VERSION@ +Architecture: iphoneos-arm64 +Description: Dynamic Island for notched iPhones: music, timers, calls, AirPods and Watch battery, calendar and system popups. +Maintainer: astar76 +Author: astar76 +Section: Tweaks +Depends: firmware (>= 15.0), mobilesubstrate, preferenceloader diff --git a/pkg/postinst b/pkg/postinst new file mode 100644 index 0000000..f48b13c --- /dev/null +++ b/pkg/postinst @@ -0,0 +1,7 @@ +#!/bin/sh +export PATH=/var/jb/usr/bin:/var/jb/bin:/usr/bin:/bin +rm -f /var/jb/var/mobile/Library/Preferences/com.astar76.islet.bootguard +# The Watch ping hook loads into this daemon, which launchd restarts on demand. It ignores SIGTERM, and killall can't name +# it: that matches the kernel's 16-character process name, and this one is longer. +for p in $(ps -Ao pid,comm | grep companionfindlocallyd | awk '{print $1}'); do kill -9 "$p"; done +exit 0 diff --git a/pkg/postrm b/pkg/postrm new file mode 100644 index 0000000..e40b30d --- /dev/null +++ b/pkg/postrm @@ -0,0 +1,11 @@ +#!/bin/sh +export PATH=/var/jb/usr/bin:/var/jb/bin:/usr/bin:/bin +case "$1" in remove|purge) + # the ping hook lives in this daemon until it restarts + for p in $(ps -Ao pid,comm | grep companionfindlocallyd | awk '{print $1}'); do kill -9 "$p"; done + rm -f /var/mobile/islet-banners.log /var/mobile/islet-batteries.txt /var/jb/var/mobile/islet-dump.txt /var/jb/var/mobile/islet-snap.png + rm -f /var/jb/var/mobile/Library/Preferences/com.astar76.islet.bootguard + ;; +esac +[ "$1" = purge ] && rm -f /var/jb/var/mobile/Library/Preferences/com.astar76.islet.plist +exit 0 diff --git a/pkg/prefs/Info.plist b/pkg/prefs/Info.plist new file mode 100644 index 0000000..8970533 --- /dev/null +++ b/pkg/prefs/Info.plist @@ -0,0 +1,24 @@ + + + + + CFBundleExecutable + IsletPrefs + CFBundleIdentifier + com.astar76.islet.prefs + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + IsletPrefs + CFBundlePackageType + BNDL + CFBundleShortVersionString + 1.0 + CFBundleVersion + 1 + MinimumOSVersion + 15.0 + NSPrincipalClass + IsletRootListController + + diff --git a/pkg/prefs/Root.plist b/pkg/prefs/Root.plist new file mode 100644 index 0000000..a8288ff --- /dev/null +++ b/pkg/prefs/Root.plist @@ -0,0 +1,695 @@ + + + + + items + + + cell + PSGroupCell + footerText + Switching Islet off hands everything back to iOS at once, and on again brings it back. All settings apply live. + + + cell + PSSwitchCell + default + + key + enabled + label + Enabled + + + cell + PSGroupCell + footerText + Lyrics appear for music players, not video apps. Tracks in the Music app use timed embedded tags first. Online lookups send the song title and artist to lrclib.net, then NetEase if it has nothing. + label + Activities + + + cell + PSSwitchCell + default + + key + music + label + Now Playing + + + cell + PSSwitchCell + default + + key + musicPeek + label + Show New Tracks + + + cell + PSSwitchCell + default + + key + realVisualizer + label + Live Audio Bars + + + cell + PSSwitchCell + default + + key + lyrics + label + Lyrics Button + + + cell + PSSwitchCell + default + + key + onlineLyrics + label + Find Lyrics Online + + + cell + PSSwitchCell + default + + key + neteaseLyrics + label + NetEase Backup + + + cell + PSSwitchCell + default + + key + timer + label + Timers + + + cell + PSSwitchCell + default + + key + calls + label + Calls + + + cell + PSSwitchCell + default + + key + flashlight + label + Flashlight + + + cell + PSSwitchCell + default + + key + flashlightPeek + label + Unfold Flashlight Controls + + + cell + PSSwitchCell + default + + key + recording + label + Screen Recording + + + cell + PSSwitchCell + default + + key + calendar + label + Calendar Events + + + cell + PSSwitchCell + default + + key + reminders + label + Reminders + + + cell + PSGroupCell + footerText + Battery popups go away on their own. The stock AirPods pill is replaced by the island while this is on. + label + Accessories & Battery + + + cell + PSSwitchCell + default + + key + bluetooth + label + Device Connections + + + cell + PSSwitchCell + default + + key + hideAccessoryBanners + label + Hide Stock AirPods Pill + + + cell + PSSwitchCell + default + + key + deviceBattery + label + AirPods & Watch Battery + + + cell + PSSwitchCell + default + + key + watchPing + label + Watch Ping + + + cell + PSSwitchCell + default + + key + audioBubble + label + Headphones Beside Island + + + cell + PSSwitchCell + default + + key + lowBattery + label + iPhone Low Battery + + + cell + PSSwitchCell + default + + key + charging + label + Charging + + + cell + PSSwitchCell + default + + key + lowPowerMode + label + Low Power Mode + + + cell + PSGroupCell + label + System Popups + + + cell + PSSwitchCell + default + + key + ringer + label + Silent Switch + + + cell + PSSwitchCell + default + + key + volumeHUD + label + Volume + + + cell + PSSwitchCell + default + + key + airplane + label + Airplane Mode + + + cell + PSSwitchCell + default + + key + focus + label + Focus + + + cell + PSSwitchCell + default + + key + network + label + Wi‑Fi / Cellular Changes + + + cell + PSSwitchCell + default + + key + rotationLock + label + Rotation Lock + + + cell + PSSwitchCell + default + + key + airdrop + label + AirDrop + + + cell + PSSwitchCell + default + + key + systemActivities + label + Hotspot, Mirroring, Microphone + + + cell + PSSwitchCell + default + + key + sensorPill + label + Camera & Microphone Use + + + cell + PSSwitchCell + default + + key + lockPill + label + Lock & Unlock (Face ID) + + + cell + PSGroupCell + label + Stock Interface + + + cell + PSSwitchCell + default + + key + hideStockHUD + label + Hide Stock Silent HUD + + + cell + PSSwitchCell + default + + key + hideStatusPills + label + Hide Coloured Clock Pills + + + cell + PSSwitchCell + default + + key + bannerOffset + label + Keep Banners Below Island + + + cell + PSGroupCell + footerText + Notifications open in the island. Hold one for the full stock view with reply. Sticky alerts, critical alerts and anything arriving while the island is hidden keep the stock banner. + label + Notifications + + + cell + PSSwitchCell + default + + key + notifications + label + Show Notifications in Island + + + cell + PSSwitchCell + default + + key + hideBanners + label + Replace Stock Banners + + + cell + PSGroupCell + footerText + Tap unfolds, swipe up hides the compact island, swipe sideways switches activity, long press opens the app or the full notification. Full-screen video counts as a landscape app that also owns Now Playing; calls still come through. + label + Behaviour + + + cell + PSSwitchCell + default + + key + bubble + label + Second Activity Bubble + + + cell + PSSwitchCell + default + + key + hideLandscape + label + Hide in Landscape + + + cell + PSSwitchCell + default + + key + hideFullscreenVideo + label + Hide During Full-Screen Video + + + cell + PSGroupCell + label + Hide After Swipe Up (seconds) + + + cell + PSSliderCell + default + 10 + key + hideSeconds + max + 60 + min + 5 + showValue + + + + cell + PSGroupCell + footerText + 0 keeps cards open until you fold them. + label + Fold Unfolded Cards After (seconds) + + + cell + PSSliderCell + default + 8 + key + autoFold + max + 30 + min + 0 + showValue + + + + cell + PSGroupCell + footerText + Each device and each part of it alerts on its own, once on the way down, and again at 10%. + label + Accessory Low Battery (percent) + + + cell + PSSliderCell + default + 20 + key + deviceLowLevel + max + 50 + min + 10 + showValue + + + + cell + PSGroupCell + label + Keep Paused Music For (seconds) + + + cell + PSSliderCell + default + 10 + key + musicLinger + max + 60 + min + 0 + showValue + + + + cell + PSGroupCell + label + Show Events Ahead (minutes) + + + cell + PSSliderCell + default + 15 + key + calendarLead + max + 60 + min + 5 + showValue + + + + cell + PSGroupCell + label + Notch Width + + + cell + PSSliderCell + default + 214 + key + notchWidth + max + 250 + min + 180 + showValue + + + + cell + PSGroupCell + label + Notch Height + + + cell + PSSliderCell + default + 30 + key + notchHeight + max + 40 + min + 24 + showValue + + + + cell + PSGroupCell + label + Extra Tab Width + + + cell + PSSliderCell + default + 16 + key + compactExtra + max + 60 + min + 0 + showValue + + + + cell + PSGroupCell + label + Preview + + + action + preview: + cell + PSButtonCell + demo + 19 + label + AirPods + + + action + preview: + cell + PSButtonCell + demo + 20 + label + Apple Watch Low Battery + + + action + preview: + cell + PSButtonCell + demo + 21 + label + iPhone Low Battery + + + action + preview: + cell + PSButtonCell + demo + 24 + label + Hide for a While + + + cell + PSGroupCell + footerText + Reset puts every switch and slider back to the recommended setting. If SpringBoard crashed twice in a row, Islet turns itself off: Clear Crash Guard undoes that, then respring. + label + Recovery + + + action + resetSettings: + cell + PSButtonCell + label + Reset to Recommended Settings + + + action + resetGuard: + cell + PSButtonCell + label + Clear Crash Guard + + + title + Islet + + diff --git a/pkg/prefs/entry.plist b/pkg/prefs/entry.plist new file mode 100644 index 0000000..7c6b115 --- /dev/null +++ b/pkg/prefs/entry.plist @@ -0,0 +1,21 @@ + + + + + entry + + bundle + IsletPrefs + cell + PSLinkCell + detail + IsletRootListController + icon + icon.png + isController + + label + Islet + + + diff --git a/pkg/prefs/icon@2x.png b/pkg/prefs/icon@2x.png new file mode 100644 index 0000000000000000000000000000000000000000..168571852e37505384952164cbdc2f541d98d14d GIT binary patch literal 1668 zcmeAS@N?(olHy`uVBq!ia0y~yV6XyV4mJh`hKIYoG#D7zyggkULn`LHogLp38ZLUQ zKKpI)vw79&42^7Rx3cu5ALB0KYnc4(haRI~bc9FVjw1_R${f7q|3;d_Ug5)xFAC2ZlV+~i!o(;fz4E%$B7vGXQR6&Q2G3~ZVhcAY7irI;Y`UV;oEh_ChsTybiFdWP*_pR3J>|FhacBCDsYx4ET+$V4EoMJ@o6?r=$9M9GjQLR? z1~d81_iPHHwBBs7vTTYrRY^Rjcy8T9@7B4l{D)`vN9r@AEs}ANoMdqG!Hz2u8#Ier zN>bPEW93-sJJGwh@g&=E$w>zoLm0B`H?0qTY;sv-O-;z&SdA5vGMd+4?LRTU)$y{< zL*MBiMY9FMLW^U0+NSgH8u$1-e{)q5S^dP0WY9 zZeL?$@f6_qS66#;(Am{XYxIdj$=rZS}dFwL!Gd?_!2`bf@Z8h(7naDofL*B|+A6>Kf zcH4OuKD2rGC|ba3zR#t9?HA9#aWv06B;~L{bz<(^6_Oo}tDdCSJKFv7esk*nZG)Y) z9{1BG>DSNy(y6#&P3ujDTTwG6-s)f5>X+uw(3Sk{Nn+PV;nd7t_vH(kI3g7Gwahqn zN!NO%jEvi+uK`=0-MrQj)zD@1``2cXhc@1h0ioY~6YPJ7s zQK=PJqIvV#I}W*(TL0$Wcbzn=>Aba<5F@wSu9c@|-Tk{{_A1rP?$X^;KCCzV^w3e| z^0b`Hd+x3V@*4MkRaRcNvauIGknnk7`wRO&0(rUobw$(oOq5b-TdV6JeXQ|I#Eo>06J)b+epHE@sqxDZcR^`}Q9oSVH zeP9g_cayLGgZuW~Ure^I<_vTe+VFo*`_tZv<58Wlxk>L%eYf4&d*MTboPc_S90%|D zTK~M+_WmpaZ$91k66?NwHR(i*AL|yEmTOTF!i$<%C+z#3yyUIH&7E>(Pp`0=6nm_i zVXhKtQXFGhns~6%(BkCsZQD|=J#qH;ww6_yKzR}Muj+w>I#_-&c z{QK&+_w^mC4nL{yKV9(V0o4cGCBN&w{L8&Dg*`T=#Js%UB1db&8@raes_VxeN4O^j zDmxz!=$085P9)0y`d^YgfDQrZ|)Dr?EZ zI$gn&>0IKJ|E)|XuLW18NnGF0JbUZ3l#K4K2nBwRQs$cn6DR50igvdtc^&kV-FKji zY0v*1dUtnqpIRt*C!KvmX8ms0T2AfJ znpZC~=YY@Wy2`_$(_BQn4klb!9O&~yb!wh;ke%!%$w$2LkJeK-X?Ma53xmXv*n`s3j?cX3b^9vgil;NQE1X}uTjsN- zFX>9qnd}nJCK0!)Lv+qc`KNo7lKdpQUjEa|+SfI+F}O{@F!jQuUxJqI&GDZ4oNoIr zncXw$iCLwx@ZjpN%0+#XpRpJ}WZ3mlFzYg_@}#w&On1BK?OjqfcfU{VyyF$J7M>cx zO9~g(itCt)uUu$$c(!Nrd!Kzr+!;2$oF*?}viH}bnki>LxMY0DUinZ(+w+)0se0dL z#>2@9l73YIvmaeuS-+vY$U}|cS((?L`)?KYuD|h^ah`bc{v~&}$fod_-+u7;=RC>X m;b+#EOO*T1s84?=+ literal 0 HcmV?d00001 diff --git a/pkg/prefs/icon@3x.png b/pkg/prefs/icon@3x.png new file mode 100644 index 0000000000000000000000000000000000000000..4600fa0677aa9075217883daadb660663e063da6 GIT binary patch literal 2511 zcmeAS@N?(olHy`uVBq!ia0y~yUU5onEIpWm>|@Jm<^1L_MV)S~7aSH4A-oHV+jNoh>1(Xs9;9P4%$LqR`|I z%o0g19h}EX9&!sVl$fw8K-85pNMXxLZIO)3o14~uE;?WNr{MjWciVQ~m@8ft{Z4=8 z7VF|?=PdvKzVqDX`O|yu7NTVczvwi*mvw1dc0AuwI(HRN7S_^w^P4 zLInY>$9Zi`cRJ6@o?_+L-#VfEpQdP@t48PY6^Z`h&T{L7f9#0ZC31i{Fk9D4mWk!# zex?bs_pwj1oDu!(Yni&{hu+$< zJanbwgMxKyl8Oqu*`3R4SR?OD;V$ z?d2ky+C{AABk}@yogZKFXy-ECcz=c9Auj7Xzf$Oe&L zi)`wrH(ZT6mbhX0+E3|Ra_X@Wy%rK7H!RqWzYcU+^U0uX(vMkB^-gY%(sr4-VR^^F ztX7XtYt}`+Tck4Y;SFUDS6&UzElbfBQLd8%w37`r;+&3Lwx01cIm=fZ)7coKbLeW6C)3lOXM$_O1O(T`CGEUXaX3^+ z=+VsbnmHRiY~q}p@^_qKh@Q0Fc>4vpS5|qPBG(>txSy9?tK4A~5RuGsP3`l>$SD`( zcmz4tn9h;a=Ezi;9+}O4^2l3-nLA`vgts@RJSv;ubBAwI=WR!$LTeATJecH?V(y8r z9*Z+gI>u?vdUZ$MrI~jl--=(~y<^itM<(IzimjJFC^fM5HfR;@^{p09x}~wM>AT0l zMRI>$|Ng*U*Khwtr>Z7p*_llBjTfBcpEY@J6t894{Hkcl@kPO&e{Yp6_57ZDtEzkQ zY42SJ_WqFAYHNQ)_6PG1$+EH(aV!R6yG!K|nhp?PuuM zjoh0pOa7Fu+Anv=zwelB5cjt0dv@GYygM!9{M;SS-?PtV4$u8nAbZq9W~+s(a=#Vp z`ojBWyWba?ZeXnYqHvXc-#ncwCi1ULo{PPDm+;8<)b{nRr}Hm&NMCLf{LrPz@+EHH zoOk@X%2siSe^#1n$X8hFDW7>O*2DV#MErk=gS*bYC@GeWDPB0kYKiuOZO_ABe95>| zxYW?dqvh@1M>Y5U?>+ruSBB;!;}zk5N{(z~=PSr~ZoFe9hl~G<^41q8=OORmTFcYoixYU7UN#XpqwC)`q$XgI)X9^b{Oo43epxwEixNc`+4ch)k0 zi7T{wW%BODfLeBG&56N=U(*SehuSVzhjC%w`$fh?wJ(7cgnlczdKG! z8Qs@o>Rh`u|8%QyzKLD;>EF)(74FU3@xyGJi0+cBNvb<*4o|h6p{lrpwMCF|`4jy& ztPanOh2pb!$(`+<9h8{pw&Ydzd_3^z$Gh;fdl@xi|Kq3et1W!@==P149c*)w zeuXPMkC}1BAobC;K#MPn(?5i^$4;7U+!3(8MZ4Os z?RVQnrZsxA_$9NO-(M5K?741_McMhxn?1hhc<+hXbq=RRWk`m~g(yXBh(($LMHD}o~*#{&Gm6l zFzjvFTz=*OczozWqD1Y=Ohgqn`yz|KCot61MIX@NW`|&X#&! z!6I8mf-*Y_Ol1c;ZMd|Ew1~?{oBcr0sm`eDR4`w_x)Jk4<^=f8P5h@cKpN4T_|0ef6H{l;J%aC!rQ|J? z&G@5peLnMc2L*Fr`u{ z>geMo4PQg&MN1VOeaN}&`Lj-sOMbmmpXjbNcw)P_<%Ukx5Bmxk#cS1Wy^nVtHb1Fy z;ezq$vzK+Gp0|E@7gF?@;p-cZ%dVBPxT3Fo-c%y2A~xsPTG{2y{g0NkAE^GP8ER)a zf5V0gWxYD`w>r-}aXy`>de7y5_q*hp*Ejl8YZlgIM5^uoIdk{(J1R5(FvMFcPQD+u zmFN8Y{!eq)>YsL$3{Dn#$SL}6rrze=UuC9ju6&>7|F@s3U(+V$p5p)9DON|{to+a1 Y&>z36^ySWb3=9kmp00i_>zopr0Jay>d;kCd literal 0 HcmV?d00001 diff --git a/src/Islet.m b/src/Islet.m new file mode 100644 index 0000000..86cb369 --- /dev/null +++ b/src/Islet.m @@ -0,0 +1,3417 @@ +// Islet: a Dynamic Island for notched iPhones (SpringBoard tweak, rootless/Dopamine). +// Activities: now playing, timers, calls, charging, accessories and their batteries, calendar, system status popups. +// +// No static Objective-C classes on purpose: the swift.org clang can't sign ObjC class metadata the way Apple's arm64e +// ABI wants (the runtime traps in readClass). Activities are dictionaries, state lives in file-level globals, and the +// classes UIKit needs (window hit-testing, gesture target) are created at runtime. +#import +#import +#import +#import +#import +#import + +#import +#import "common.h" + +#define SNAP_PATH NS("/var/jb/var/mobile/islet-snap.png") +#define LOG(fmt, ...) NSLog(NS("[Islet] " fmt), ##__VA_ARGS__) + +@interface UIImage (IsletPrivate) ++ (UIImage *)_applicationIconImageForBundleIdentifier:(NSString *)bid format:(int)fmt scale:(CGFloat)scale; +@end + +static void (*MRRegister)(dispatch_queue_t); +static void (*MRGetInfo)(dispatch_queue_t, void (^)(NSDictionary *)); +static void (*MRGetPlaying)(dispatch_queue_t, void (^)(Boolean)); +static Boolean (*MRSendCommand)(int, NSDictionary *); +static void (*MRGetClient)(dispatch_queue_t, void (^)(id)); +static NSString *(*MRClientBID)(CFTypeRef); +static NSString *gMusicBID; + +#pragma mark - Prefs + +// Read constantly (status bar updates, the sentinel), so the plist is cached; PREFS_NOTIFICATION reloads it. +static NSDictionary *gPrefs; +static os_unfair_lock gPrefsLock = OS_UNFAIR_LOCK_INIT; + +static void LoadPrefs(void) { + NSDictionary *d = [NSDictionary dictionaryWithContentsOfFile:PREFS_PATH] ?: [NSDictionary new]; + os_unfair_lock_lock(&gPrefsLock); gPrefs = d; os_unfair_lock_unlock(&gPrefsLock); +} + +static id Pref(NSString *key) { + os_unfair_lock_lock(&gPrefsLock); id v = gPrefs[key]; os_unfair_lock_unlock(&gPrefsLock); + return v; +} +static BOOL PrefBool(NSString *key, BOOL def) { id v = Pref(key); return v ? [v boolValue] : def; } +static CGFloat PrefNum(NSString *key, CGFloat def) { id v = Pref(key); return v ? [v doubleValue] : def; } + +#pragma mark - Activities (dictionaries) + +typedef NSMutableDictionary Act; +typedef NSString *(^StrBlock)(void); +typedef double (^DblBlock)(void); + +static Act *NewAct(NSString *key, NSString *kind) { return [@{NS("key"): key, NS("kind"): kind} mutableCopy]; } +#define S(a, k) ((NSString *)(a)[NS(k)]) +static NSString *CallStr(Act *a, NSString *k) { StrBlock b = a[k]; return b ? b() : nil; } +static double CallDbl(Act *a, NSString *k) { DblBlock b = a[k]; return b ? b() : -1; } + +#pragma mark - Drawing helpers + +static UIColor *AverageColor(UIImage *img) { + if (!img) return nil; + unsigned char px[4] = {0}; + CGColorSpaceRef cs = CGColorSpaceCreateDeviceRGB(); + CGContextRef c = CGBitmapContextCreate(px, 1, 1, 8, 4, cs, kCGImageAlphaPremultipliedLast); + CGContextSetInterpolationQuality(c, kCGInterpolationMedium); + CGContextDrawImage(c, CGRectMake(0, 0, 1, 1), img.CGImage); + CGContextRelease(c); CGColorSpaceRelease(cs); + CGFloat h, s, v, al; + [[UIColor colorWithRed:px[0] / 255.0 green:px[1] / 255.0 blue:px[2] / 255.0 alpha:1] getHue:&h saturation:&s brightness:&v alpha:&al]; + return [UIColor colorWithHue:h saturation:MIN(1, MAX(s, 0.45)) brightness:MAX(v, 0.85) alpha:1]; +} + +// Cached so equal symbols are the same object: SetOngoing compares icons by identity, and a fresh image on every poll +// would rebuild the island each time. +static UIImage *Symbol(NSString *name, CGFloat pt, UIColor *color) { + static NSMutableDictionary *cache; + if (!cache) cache = [NSMutableDictionary new]; + NSString *key = [NSString stringWithFormat:NS("%@|%.1f|%@"), name, pt, color]; + UIImage *img = cache[key]; + if (img) return img; + UIImageSymbolConfiguration *cfg = [UIImageSymbolConfiguration configurationWithPointSize:pt weight:UIImageSymbolWeightSemibold]; + UIImage *base = [UIImage systemImageNamed:name withConfiguration:cfg] ?: [UIImage systemImageNamed:NS("circle.fill") withConfiguration:cfg]; + img = [base imageWithTintColor:color renderingMode:UIImageRenderingModeAlwaysOriginal]; + if (img) cache[key] = img; + return img; +} + +static UIColor *NamedColor(NSString *n) { + static NSDictionary *m; + if (!m) m = @{NS("red"): [UIColor colorWithRed:1 green:0.27 blue:0.23 alpha:1], NS("orange"): [UIColor colorWithRed:1 green:0.62 blue:0.04 alpha:1], + NS("yellow"): [UIColor colorWithRed:1 green:0.84 blue:0.04 alpha:1], NS("green"): [UIColor colorWithRed:0.19 green:0.82 blue:0.35 alpha:1], + NS("mint"): [UIColor colorWithRed:0.39 green:0.9 blue:0.8 alpha:1], NS("teal"): [UIColor colorWithRed:0.25 green:0.78 blue:0.88 alpha:1], + NS("blue"): [UIColor colorWithRed:0.04 green:0.52 blue:1 alpha:1], NS("indigo"): [UIColor colorWithRed:0.37 green:0.36 blue:0.9 alpha:1], + NS("purple"): [UIColor colorWithRed:0.75 green:0.35 blue:0.95 alpha:1], NS("pink"): [UIColor colorWithRed:1 green:0.25 blue:0.5 alpha:1]}; + for (NSString *k in m) if ([n.lowercaseString containsString:k]) return m[k]; + return m[NS("purple")]; +} + +static UIColor *BatteryColor(double pct) { return NamedColor(pct <= 20 ? NS("red") : pct <= 35 ? NS("yellow") : NS("green")); } + +static UILabel *Label(NSString *t, UIFont *f, UIColor *c) { + UILabel *l = [UILabel new]; l.text = t; l.font = f; l.textColor = c; return l; +} + +static UIView *Bar(CGFloat x, CGFloat w, CGFloat y, UIColor *c, CGFloat alpha) { + UIView *v = [[UIView alloc] initWithFrame:CGRectMake(x, y, w, 4)]; + v.backgroundColor = [c colorWithAlphaComponent:alpha]; v.layer.cornerRadius = 2; + return v; +} + +static UIImageView *RoundedIcon(UIImage *img, CGFloat s, CGFloat r) { + UIImageView *iv = [[UIImageView alloc] initWithImage:img]; + iv.frame = CGRectMake(0, 0, s, s); iv.contentMode = UIViewContentModeScaleAspectFill; + iv.layer.cornerRadius = r; iv.layer.cornerCurve = kCACornerCurveContinuous; iv.clipsToBounds = YES; + return iv; +} + +static NSString *FmtTime(NSTimeInterval s) { + int t = MAX(0, (int)ceil(s)); + return t >= 3600 ? [NSString stringWithFormat:NS("%d:%02d:%02d"), t / 3600, (t / 60) % 60, t % 60] + : [NSString stringWithFormat:NS("%d:%02d"), t / 60, t % 60]; +} + +// Battery ring as on the real island: a track and an arc that starts at 12 o'clock. +static UIView *Ring(CGFloat s, double pct, UIColor *c) { + UIView *v = [[UIView alloc] initWithFrame:CGRectMake(0, 0, s, s)]; + CGFloat lw = 3, r = (s - lw) / 2; + CGPoint mid = CGPointMake(s / 2, s / 2); + for (int i = 0; i < 2; i++) { + double frac = i ? MAX(0, MIN(1, pct / 100)) : 1; + CAShapeLayer *l = [CAShapeLayer layer]; + l.path = [UIBezierPath bezierPathWithArcCenter:mid radius:r startAngle:-M_PI_2 endAngle:-M_PI_2 + 2 * M_PI * frac clockwise:YES].CGPath; + l.fillColor = UIColor.clearColor.CGColor; l.lineWidth = lw; l.lineCap = kCALineCapRound; + l.strokeColor = [c colorWithAlphaComponent:i ? 1 : 0.25].CGColor; + [v.layer addSublayer:l]; + } + return v; +} + +// The bars are Apple's waveform and nothing else: MRUAudioAnalyzer's amplitudes, the same data the Now Playing controls +// draw, already gained and shaped by Apple's settings. No data means flat bars, not an animation. The timer only runs +// while data is arriving or the bars are settling back down. +static NSMutableArray *gBars; +static NSArray *gAmps; // latest amplitudes from MRUAudioAnalyzer +static CFTimeInterval gAmpsAt; +static double gLevels[16]; +static NSTimer *gVizTimer; +#define BAR_REST 0.14 + +static BOOL gScreenOff; +static dispatch_queue_t gSlowQ; // EventKit, lyrics and anything else that can block for a while + +// In the common run loop modes, so nothing pauses while SpringBoard tracks a gesture (Control Center, Notification Center). +static NSTimer *Every(NSTimeInterval s, NSTimeInterval tolerance, void (^block)(void)) { + int _islet_z = 0; (void)_islet_z; + NSTimer *t = [NSTimer timerWithTimeInterval:s repeats:YES block:HB(^(NSTimer *x) { (void)_islet_z; block(); })]; + t.tolerance = tolerance; + [NSRunLoop.mainRunLoop addTimer:t forMode:NSRunLoopCommonModes]; + return t; +} + +static void VizStep(void) { + BOOL fresh = gAmps.count > 1 && CACurrentMediaTime() - gAmpsAt < 0.3; + NSUInteger cnt = gAmps.count, nb = gBars.count; + int i = 0; + double total = 0; + for (UIView *b in gBars) { + double target = 0; + if (fresh) { + double pos = nb > 1 ? (double)i * (cnt - 1) / (nb - 1) : 0; + NSUInteger lo = (NSUInteger)pos, hi = MIN(lo + 1, cnt - 1); + double f = pos - lo; + target = MAX(0, MIN(1, [gAmps[lo] doubleValue] * (1 - f) + [gAmps[hi] doubleValue] * f)); + } + double prev = i < 16 ? gLevels[i] : 0; + double v = prev + (target - prev) * (target > prev ? 0.65 : 0.22); // fast attack, slow release + if (i < 16) gLevels[i] = v; + total += v; + b.transform = CGAffineTransformMakeScale(1, BAR_REST + (1 - BAR_REST) * v); + i++; + } + if (!fresh && total < 0.01) { // settled: nothing to do until the analyzer speaks again + memset(gLevels, 0, sizeof(gLevels)); + for (UIView *b in gBars) b.transform = CGAffineTransformMakeScale(1, BAR_REST); + [gVizTimer invalidate]; gVizTimer = nil; + } +} + +static void VizStop(void) { [gVizTimer invalidate]; gVizTimer = nil; [gBars removeAllObjects]; } + +static void VizStart(void) { + int _islet_z = 0; (void)_islet_z; + if (gVizTimer || !gBars.count || gScreenOff || gAmps.count < 2 || CACurrentMediaTime() - gAmpsAt > 0.3) return; + gVizTimer = Every(1.0 / 30, 0.004, HB(^{ (void)_islet_z; VizStep(); })); +} + +static UIView *VizBars(int n, CGFloat w, CGFloat gap, CGFloat h, UIColor *c) { + if (!gBars) gBars = [NSMutableArray new]; + UIView *bars = [[UIView alloc] initWithFrame:CGRectMake(0, 0, n * gap, h)]; + for (int i = 0; i < n; i++) { + UIView *b = [[UIView alloc] initWithFrame:CGRectMake(i * gap, 0, w, h)]; + b.backgroundColor = c; b.layer.cornerRadius = w / 2; + b.layer.anchorPoint = CGPointMake(0.5, 1); b.center = CGPointMake(b.center.x, h); + b.transform = CGAffineTransformMakeScale(1, BAR_REST); + [bars addSubview:b]; [gBars addObject:b]; + } + return bars; +} + +#pragma mark - Lyrics + +// Timed lyrics, from the track's own embedded tags. LRC is "[mm:ss.xx]line", and one line can carry several stamps. +static NSArray *gLyrics; +static BOOL gLyricsOn; // compact island shows the line instead of the bars + +static NSArray *ParseLRC(NSString *text) { + NSMutableArray *out = [NSMutableArray new]; + for (NSString *raw in [text componentsSeparatedByCharactersInSet:NSCharacterSet.newlineCharacterSet]) { + NSString *rest = raw; + NSMutableArray *times = [NSMutableArray new]; + while ([rest hasPrefix:NS("[")]) { + NSRange end = [rest rangeOfString:NS("]")]; + if (end.location == NSNotFound) break; + NSArray *parts = [[rest substringWithRange:NSMakeRange(1, end.location - 1)] componentsSeparatedByString:NS(":")]; + NSScanner *sc = [NSScanner scannerWithString:parts.firstObject ?: NS("")]; + int mins = 0; + if (parts.count != 2 || ![sc scanInt:&mins] || !sc.isAtEnd) break; // [ar:Artist] and other tags aren't times + [times addObject:@(mins * 60 + [parts[1] doubleValue])]; + rest = [rest substringFromIndex:end.location + 1]; + } + NSString *line = [rest stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceCharacterSet]; + BOOL credit = NO; // NetEase opens with "作词 : name", "作曲 : name" and the like + for (NSString *c in @[NS("作词"), NS("作曲"), NS("编曲"), NS("制作人"), NS("词:"), NS("曲:")]) if ([line hasPrefix:c]) credit = YES; + if (credit) continue; + for (NSNumber *t in times) [out addObject:@{NS("t"): t, NS("line"): line}]; + } + [out sortUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:NS("t") ascending:YES]]]; + return out; +} + +static NSString *LyricAt(double pos) { + NSString *cur = NS(""); + for (NSDictionary *l in gLyrics) { if ([l[NS("t")] doubleValue] > pos) break; cur = l[NS("line")]; } + return cur; +} + +static void ReloadMusicCard(void); + +#pragma mark - Island state (globals) + +static UIWindow *gWindow; +static UIView *gIsland, *gBox, *gFill; +static UILabel *gLive, *gBig; +static Act *gCur; +static BOOL gExp; +static CGSize gNotch; +static void (^gOnCommand)(NSString *); + +static NSMutableDictionary *gOngoing; +static NSMutableArray *gQueue; +static Act *gTransient; +static NSString *gExpandedKey; +static NSString *gPinnedKey; // activity picked with a sideways swipe or the bubble, beats plain priority order +static NSDate *gHideUntil; // swipe up on the compact island hides it until this date +static NSTimeInterval gFoldAt; // when an unfolded card folds itself back +static UIView *gHost, *gBubble, *gLeftBubble; +static CAShapeLayer *gBubbleRing, *gLeftRing; +static NSString *gBubbleKey; +static NSDictionary *gAudioDevice; // connected headphones: name, items, low, product. Shown left of the island. +static double gVolume; +static id gMT; +static NSString *gLastTrack; + +// The notch stays where it is when an app rotates, so the island stays on it. gMode says where the notch is from the +// viewer's side: 0 on top, 1 on the left, 2 on the right. gHost is turned to match, and everything inside it is laid out +// in that upright space, with the notch as a band down the side instead of across the top. +static int gMode; +#define NotchRow() (gMode ? 6.0 : gNotch.height) +#define SideDepth() (gMode ? gNotch.height : 0.0) +static CGFloat ScreenW(void) { CGSize b = UIScreen.mainScreen.bounds.size; CGFloat w = MIN(b.width, b.height); return w > 0 ? w : 414; } +static CGSize IdleSize(void) { return gMode ? CGSizeMake(gNotch.height - 6, gNotch.width - 8) : CGSizeMake(gNotch.width - 8, gNotch.height - 6); } +static CGSize CompactSize(void) { + // Landscape: the same tab along the same stretch of notch. Only its depth differs, sized to what's in it. + if (gMode) return CGSizeMake(52, MAX(gNotch.width + PrefNum(NS("compactExtra"), 16), 150)); + // a tab hanging under the notch: the notch row stays empty, the content sits in the strip below it + return CGSizeMake(MAX(gNotch.width + PrefNum(NS("compactExtra"), 16), 150), gNotch.height + 38); +} + +static UIButton *ControlButton(NSString *symbol, NSString *cmd, CGRect frame) { + int _islet_z = 0; (void)_islet_z; // keeps blocks off the static-global (unsigned isa) path + UIAction *act = [UIAction actionWithHandler:HB(^(UIAction *ac) { (void)_islet_z; + [[[UIImpactFeedbackGenerator alloc] initWithStyle:UIImpactFeedbackStyleLight] impactOccurred]; + if (gOnCommand) gOnCommand(cmd); + UIView *b = ac.sender; + if (![b isKindOfClass:UIView.class]) return; + [UIView animateWithDuration:0.12 animations:HB(^{ (void)_islet_z; b.transform = CGAffineTransformMakeScale(0.82, 0.82); }) + completion:HB(^(BOOL f) { (void)_islet_z; [UIView animateWithDuration:0.35 delay:0 usingSpringWithDamping:0.5 initialSpringVelocity:0 options:0 + animations:HB(^{ (void)_islet_z; b.transform = CGAffineTransformIdentity; }) completion:nil]; })]; + })]; + UIButton *b = [UIButton buttonWithType:UIButtonTypeCustom primaryAction:act]; + [b setImage:Symbol(symbol, 24, UIColor.whiteColor) forState:UIControlStateNormal]; + b.frame = frame; + return b; +} + +// The round buttons on call cards. +static UIButton *RoundButton(NSString *symbol, NSString *cmd, CGPoint center, UIColor *bg) { + UIButton *b = ControlButton(symbol, cmd, CGRectMake(0, 0, 50, 50)); + [b setImage:Symbol(symbol, 20, UIColor.whiteColor) forState:UIControlStateNormal]; + b.center = center; b.backgroundColor = bg; b.layer.cornerRadius = 25; + return b; +} + +// The stock silent-switch animation: the bell swings about its top, and going silent draws the slash across it. +static void AnimateBell(UIView *bell, BOOL silent, UIColor *tint) { + bell.layer.anchorPoint = CGPointMake(0.5, 0.12); + bell.layer.position = CGPointMake(bell.layer.position.x, bell.layer.position.y + bell.bounds.size.height * (0.12 - 0.5)); + bell.layer.masksToBounds = NO; + CAKeyframeAnimation *swing = [CAKeyframeAnimation animationWithKeyPath:NS("transform.rotation.z")]; + swing.values = @[@0, @0.55, @-0.5, @0.4, @-0.3, @0.2, @-0.1, @0]; + swing.duration = 1.0; swing.calculationMode = kCAAnimationCubic; + [bell.layer addAnimation:swing forKey:NS("swing")]; + if (!silent) return; + UIBezierPath *line = [UIBezierPath bezierPath]; + [line moveToPoint:CGPointMake(3, 2)]; [line addLineToPoint:CGPointMake(21, 22)]; + for (int i = 0; i < 2; i++) { // a black edge, as on the slashed symbol, then the slash + CAShapeLayer *l = [CAShapeLayer layer]; + l.path = line.CGPath; l.fillColor = UIColor.clearColor.CGColor; l.lineCap = kCALineCapRound; + l.lineWidth = i ? 2.4 : 6; l.strokeColor = (i ? tint : UIColor.blackColor).CGColor; + CABasicAnimation *draw = [CABasicAnimation animationWithKeyPath:NS("strokeEnd")]; + draw.fromValue = @0; draw.toValue = @1; draw.duration = 0.3; draw.beginTime = CACurrentMediaTime() + 0.15; draw.fillMode = kCAFillModeBackwards; + [l addAnimation:draw forKey:NS("draw")]; + [bell.layer addSublayer:l]; + } +} + +#define COMPACT_FONT [UIFont monospacedDigitSystemFontOfSize:15 weight:UIFontWeightSemibold] + +static BOOL ShowsLyrics(Act *a) { return gLyricsOn && gLyrics.count && [S(a, "kind") isEqual:NS("music")] && !a[NS("paused")]; } + +static CGSize CompactSizeFor(Act *a) { + CGSize s = CompactSize(); + // The normal tab: anything wider sits over the clock and the status icons either side of the notch. + if (ShowsLyrics(a)) return gMode ? CGSizeMake(104, s.height) : s; + if (!gMode) return s; + if ([S(a, "kind") isEqual:NS("music")] || [S(a, "kind") isEqual:NS("volume")]) return s; + NSString *t = CallStr(a, NS("liveCompact")) ?: (S(a, "subtitle") ?: NS("")); + CGFloat w = ceil([t sizeWithAttributes:@{NSFontAttributeName: COMPACT_FONT}].width); + return CGSizeMake(MAX(52, MIN(w + 20, 124)), s.height); +} + +// Portrait lays icon and label out along the notch, left and right. Landscape keeps that: they sit at the two ends of the +// same stretch, top and bottom, upright for the viewer. +static void BuildCompact(Act *a, UIView *box, CGSize s) { + CGFloat cy = gNotch.height + (s.height - gNotch.height) / 2 - 1, pad = 20; + NSString *kind = S(a, "kind"); + BOOL music = [kind isEqual:NS("music")], artwork = music || [kind isEqual:NS("notif")]; + if (a[NS("icon")]) { + UIImageView *ic = RoundedIcon(a[NS("icon")], 24, 6); + if (!artwork) { ic.contentMode = UIViewContentModeScaleAspectFit; ic.layer.cornerRadius = 0; ic.clipsToBounds = NO; } // symbols aren't square + ic.center = gMode ? CGPointMake(s.width / 2, pad + 12) : CGPointMake(pad + 12, cy); [box addSubview:ic]; + if ([kind isEqual:NS("ringer")]) AnimateBell(ic, a[NS("silent")] != nil, a[NS("tint")]); + if ([kind isEqual:NS("ping")]) { + for (int i = 0; i < 3; i++) { + CAShapeLayer *w = [CAShapeLayer layer]; + w.path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(-4, -4, 32, 32)].CGPath; + w.frame = CGRectMake(0, 0, 24, 24); w.fillColor = UIColor.clearColor.CGColor; w.lineWidth = 1.5; w.opacity = 0; + w.strokeColor = [(UIColor *)a[NS("tint")] CGColor]; + CABasicAnimation *grow = [CABasicAnimation animationWithKeyPath:NS("transform.scale")]; grow.fromValue = @0.5; grow.toValue = @1.5; + CABasicAnimation *fade = [CABasicAnimation animationWithKeyPath:NS("opacity")]; fade.fromValue = @0.9; fade.toValue = @0; + CAAnimationGroup *g = [CAAnimationGroup animation]; + g.animations = @[grow, fade]; g.duration = 1.5; g.repeatCount = HUGE_VALF; g.beginTime = CACurrentMediaTime() + i * 0.5; + [w addAnimation:g forKey:NS("sonar")]; + [ic.layer addSublayer:w]; + } + } + if ([S(a, "key") isEqual:NS("record")]) { // recording dot blinks + CABasicAnimation *b = [CABasicAnimation animationWithKeyPath:NS("opacity")]; + b.fromValue = @1; b.toValue = @0.15; b.duration = 0.7; b.autoreverses = YES; b.repeatCount = HUGE_VALF; + [ic.layer addAnimation:b forKey:NS("blink")]; + } + } + if ([kind isEqual:NS("volume")]) { + CGFloat x = gMode ? 9 : pad + 36, w = gMode ? s.width - 18 : s.width - pad * 2 - 36, y = gMode ? s.height - pad - 12 : cy - 2; + [box addSubview:Bar(x, w, y, a[NS("tint")], 0.25)]; + gFill = Bar(x, 0, y, a[NS("tint")], 1); [box addSubview:gFill]; + a[NS("fillWidth")] = @(w); + } else if (ShowsLyrics(a)) { + UILabel *l = Label(CallStr(a, NS("liveCompact")), [UIFont systemFontOfSize:12 weight:UIFontWeightSemibold], a[NS("tint")] ?: UIColor.whiteColor); + l.numberOfLines = gMode ? 6 : 2; l.adjustsFontSizeToFitWidth = YES; l.minimumScaleFactor = 0.8; + l.textAlignment = gMode ? NSTextAlignmentCenter : NSTextAlignmentLeft; + l.frame = gMode ? CGRectMake(8, pad + 28, s.width - 16, s.height - pad * 2 - 28) : CGRectMake(pad + 30, cy - 17, s.width - pad - 30 - 12, 34); + [box addSubview:l]; gLive = l; + } else if (music) { + UIView *bars = VizBars(5, 3, 6, 18, [a[NS("tint")] ?: UIColor.whiteColor colorWithAlphaComponent:a[NS("paused")] ? 0.4 : 1]); + bars.frame = gMode ? CGRectMake(s.width / 2 - 15, s.height - pad - 18, 30, 18) : CGRectMake(s.width - pad - 30, cy - 9, 30, 18); + [box addSubview:bars]; + } else { + NSString *t = CallStr(a, NS("liveCompact")) ?: (S(a, "subtitle") ?: NS("")); + UILabel *l = Label(t, COMPACT_FONT, a[NS("tint")] ?: UIColor.whiteColor); + l.textAlignment = gMode ? NSTextAlignmentCenter : NSTextAlignmentRight; l.adjustsFontSizeToFitWidth = YES; l.minimumScaleFactor = 0.7; + l.frame = gMode ? CGRectMake(4, s.height - pad - 22, s.width - 8, 22) : CGRectMake(pad + 34, cy - 11, s.width - pad * 2 - 34, 22); + [box addSubview:l]; gLive = a[NS("liveCompact")] ? l : nil; + } +} + +// Expanded cards sit entirely under the notch: a header row (icon left, label right), then the body. +static CGSize BuildExpanded(Act *a, UIView *box) { + CGFloat W = gMode ? 300 : MIN(ScreenW() - 16, 380), pad = 22, rowTop = NotchRow() + 8, cy = rowTop + 13, y0 = rowTop + 34, H; + CGFloat rx = W / 2; // right half of the first row + UIColor *tint = a[NS("tint")] ?: UIColor.whiteColor, *gray = [UIColor colorWithWhite:1 alpha:0.62]; + NSString *kind = S(a, "kind"); + UIFont *small = [UIFont systemFontOfSize:11 weight:UIFontWeightSemibold]; + UILabel *(^rightLabel)(NSString *, UIFont *, UIColor *) = ^UILabel *(NSString *t, UIFont *f, UIColor *c) { + UILabel *l = Label(t, f, c); l.textAlignment = NSTextAlignmentRight; l.adjustsFontSizeToFitWidth = YES; l.minimumScaleFactor = 0.6; + l.frame = CGRectMake(rx, cy - 10, W - pad - rx + 8, 20); [box addSubview:l]; return l; + }; + if ([kind isEqual:NS("music")]) { + UIView *bars = VizBars(11, 3, 5.5, 18, tint); bars.frame = CGRectMake(pad, cy - 9, 62, 18); [box addSubview:bars]; + gBig = rightLabel(CallStr(a, NS("liveBig")) ?: NS(""), [UIFont monospacedDigitSystemFontOfSize:12 weight:UIFontWeightMedium], gray); + UIImageView *art = RoundedIcon(a[NS("icon")], 58, 12); art.frame = CGRectMake(pad, y0, 58, 58); [box addSubview:art]; + UILabel *t = Label(S(a, "title"), [UIFont systemFontOfSize:17 weight:UIFontWeightSemibold], UIColor.whiteColor); + CGFloat textW = W - pad * 2 - (gLyrics.count ? 158 : 116); + t.frame = CGRectMake(pad + 70, y0 + 9, textW, 22); [box addSubview:t]; + UILabel *s = Label(S(a, "subtitle"), [UIFont systemFontOfSize:14], gray); + s.frame = CGRectMake(pad + 70, y0 + 33, textW, 18); [box addSubview:s]; + if (gLyrics.count) { + NSString *icon = gLyricsOn ? NS("quote.bubble.fill") : NS("quote.bubble"); + UIButton *lyr = ControlButton(icon, NS("lyrics"), CGRectMake(W - pad - 84, y0 + 9, 42, 40)); + [lyr setImage:Symbol(icon, 20, tint) forState:UIControlStateNormal]; + [box addSubview:lyr]; + } + UIButton *routes = ControlButton(NS("airplayaudio"), NS("routes"), CGRectMake(W - pad - 42, y0 + 9, 42, 40)); + [routes setImage:Symbol(NS("airplayaudio"), 20, tint) forState:UIControlStateNormal]; + [box addSubview:routes]; + CGFloat py = y0 + 58 + 12; + [box addSubview:Bar(pad, W - pad * 2, py, UIColor.whiteColor, 0.2)]; + gFill = Bar(pad, 0, py, UIColor.whiteColor, 0.95); [box addSubview:gFill]; + NSArray *icons = @[NS("backward.fill"), a[NS("paused")] ? NS("play.fill") : NS("pause.fill"), NS("forward.fill")], *cmds = @[NS("prev"), NS("toggle"), NS("next")]; + for (int i = 0; i < 3; i++) + [box addSubview:ControlButton(icons[i], cmds[i], CGRectMake(W / 2 - 80 + i * 54, py + 8, 52, 40))]; + H = py + 8 + 40 + 10; + } else if ([kind isEqual:NS("timer")] || [kind isEqual:NS("charge")]) { + BOOL timer = [kind isEqual:NS("timer")]; + UIImageView *ic = [[UIImageView alloc] initWithImage:Symbol(timer ? NS("timer") : NS("bolt.fill"), 20, tint)]; + ic.frame = CGRectMake(pad, cy - 12, 24, 24); ic.contentMode = UIViewContentModeScaleAspectFit; [box addSubview:ic]; + rightLabel(timer ? (S(a, "title") ?: NS("Timer")) : NS("Charging"), small, gray); + UILabel *big = Label(CallStr(a, NS("liveBig")) ?: NS(""), [UIFont monospacedDigitSystemFontOfSize:52 weight:UIFontWeightSemibold], tint); + big.textAlignment = NSTextAlignmentCenter; big.adjustsFontSizeToFitWidth = YES; big.minimumScaleFactor = 0.6; + big.frame = CGRectMake(pad, y0 - 2, W - pad * 2, 60); [box addSubview:big]; gBig = big; + CGFloat py = y0 + 62; + [box addSubview:Bar(pad, W - pad * 2, py, tint, 0.25)]; + gFill = Bar(pad, 0, py, tint, 1); [box addSubview:gFill]; + H = py + 4 + 18; + if (a[NS("timerObject")]) { + if (a[NS("timerDone")]) [box addSubview:ControlButton(NS("xmark"), NS("timer:stop"), CGRectMake(W / 2 - 27, py + 8, 54, 40))]; + else { + [box addSubview:ControlButton(a[NS("paused")] ? NS("play.fill") : NS("pause.fill"), NS("timer:toggle"), CGRectMake(W / 2 - 58, py + 8, 54, 40))]; + [box addSubview:ControlButton(NS("xmark"), NS("timer:stop"), CGRectMake(W / 2 + 4, py + 8, 54, 40))]; + } + H = py + 8 + 40 + 10; + } + } else if ([kind isEqual:NS("record")]) { + UIImageView *ic = [[UIImageView alloc] initWithImage:a[NS("icon")]]; + ic.frame = CGRectMake(pad, cy - 12, 24, 24); ic.contentMode = UIViewContentModeScaleAspectFit; [box addSubview:ic]; + if ([S(a, "key") isEqual:NS("record")]) { + CABasicAnimation *b = [CABasicAnimation animationWithKeyPath:NS("opacity")]; + b.fromValue = @1; b.toValue = @0.15; b.duration = 0.7; b.autoreverses = YES; b.repeatCount = HUGE_VALF; + [ic.layer addAnimation:b forKey:NS("blink")]; + } + rightLabel(S(a, "title"), small, gray); + UILabel *big = Label(CallStr(a, NS("liveBig")) ?: NS(""), [UIFont monospacedDigitSystemFontOfSize:48 weight:UIFontWeightSemibold], tint); + big.textAlignment = NSTextAlignmentCenter; big.adjustsFontSizeToFitWidth = YES; big.minimumScaleFactor = 0.5; + big.frame = CGRectMake(pad, y0 - 2, W - pad * 2, 56); [box addSubview:big]; gBig = big; + H = y0 + 56 + 14; + if (a[NS("activityID")]) { // the same thing as tapping the stock pill: iOS asks, and stops it + NSString *cmd = [NS("activity:") stringByAppendingString:a[NS("activityID")]]; + [box addSubview:RoundButton(a[NS("actionSymbol")] ?: NS("stop.fill"), cmd, CGPointMake(W / 2, y0 + 56 + 27), a[NS("actionSymbol")] ? [UIColor colorWithWhite:0.25 alpha:1] : NamedColor(NS("red")))]; + H = y0 + 56 + 54 + 14; + } + } else if ([kind isEqual:NS("flash")]) { + UIImageView *ic = [[UIImageView alloc] initWithImage:Symbol(NS("flashlight.on.fill"), 20, tint)]; + ic.frame = CGRectMake(pad, cy - 12, 24, 24); ic.contentMode = UIViewContentModeScaleAspectFit; [box addSubview:ic]; + rightLabel(NS("Flashlight"), small, gray); + UILabel *big = Label(CallStr(a, NS("liveBig")) ?: NS(""), [UIFont monospacedDigitSystemFontOfSize:48 weight:UIFontWeightSemibold], tint); + big.textAlignment = NSTextAlignmentCenter; big.frame = CGRectMake(pad, y0 - 2, W - pad * 2, 56); [box addSubview:big]; gBig = big; + CGFloat py = y0 + 56; + [box addSubview:Bar(pad, W - pad * 2, py, tint, 0.25)]; + gFill = Bar(pad, 0, py, tint, 1); [box addSubview:gFill]; + NSArray *icons = @[NS("sun.min.fill"), NS("sun.max.fill"), NS("sun.max.circle.fill"), NS("power")], *cmds = @[NS("torch:0.25"), NS("torch:0.5"), NS("torch:1"), NS("torchoff")]; + for (int i = 0; i < 4; i++) + [box addSubview:ControlButton(icons[i], cmds[i], CGRectMake(W / 2 - 112 + i * 58, py + 8, 54, 40))]; + H = py + 8 + 40 + 10; + } else if ([kind isEqual:NS("call")]) { + UIImageView *ic = [[UIImageView alloc] initWithImage:Symbol(NS("phone.fill"), 14, UIColor.whiteColor)]; + ic.contentMode = UIViewContentModeCenter; ic.frame = CGRectMake(pad, cy - 13, 26, 26); + ic.backgroundColor = tint; ic.layer.cornerRadius = 13; [box addSubview:ic]; + gBig = rightLabel(CallStr(a, NS("liveBig")) ?: S(a, "subtitle"), [UIFont monospacedDigitSystemFontOfSize:13 weight:UIFontWeightMedium], tint); + UILabel *t = Label(S(a, "title"), [UIFont systemFontOfSize:24 weight:UIFontWeightSemibold], UIColor.whiteColor); + t.textAlignment = NSTextAlignmentCenter; t.adjustsFontSizeToFitWidth = YES; t.minimumScaleFactor = 0.6; + t.frame = CGRectMake(pad, y0 + 2, W - pad * 2, 30); [box addSubview:t]; + UILabel *s = Label(S(a, "subtitle"), [UIFont systemFontOfSize:14], gray); + s.textAlignment = NSTextAlignmentCenter; s.frame = CGRectMake(pad, y0 + 34, W - pad * 2, 18); [box addSubview:s]; + CGFloat by = y0 + 56 + 25; + if ([S(a, "subtitle") hasPrefix:NS("Incoming")]) { + [box addSubview:RoundButton(NS("phone.down.fill"), NS("call:end"), CGPointMake(W / 2 - 62, by), NamedColor(NS("red")))]; + [box addSubview:RoundButton(NS("phone.fill"), NS("call:answer"), CGPointMake(W / 2 + 62, by), NamedColor(NS("green")))]; + } else { + BOOL muted = [a[NS("muted")] boolValue]; + [box addSubview:RoundButton(muted ? NS("mic.slash.fill") : NS("mic.fill"), NS("call:mute"), CGPointMake(W / 2 - 62, by), [UIColor colorWithWhite:muted ? 0.55 : 0.25 alpha:1])]; + [box addSubview:RoundButton(NS("phone.down.fill"), NS("call:end"), CGPointMake(W / 2 + 62, by), NamedColor(NS("red")))]; + } + H = by + 25 + 14; + } else if ([kind isEqual:NS("device")]) { + // Accessory card: the device on the left, its name and one battery ring per part (buds, case) on the right. + CGFloat ix = pad + 66, top = NotchRow() + 10; + UIImageView *ic = [[UIImageView alloc] initWithImage:a[NS("bigIcon")] ?: a[NS("icon")]]; + ic.contentMode = UIViewContentModeScaleAspectFit; ic.frame = CGRectMake(pad, top + 4, 54, 54); [box addSubview:ic]; + UILabel *t = Label(S(a, "title"), [UIFont systemFontOfSize:18 weight:UIFontWeightSemibold], UIColor.whiteColor); + t.adjustsFontSizeToFitWidth = YES; t.minimumScaleFactor = 0.7; t.frame = CGRectMake(ix, top, W - ix - pad, 24); [box addSubview:t]; + UILabel *st = Label(S(a, "subtitle"), [UIFont systemFontOfSize:13.5], tint); + st.frame = CGRectMake(ix, top + 24, W - ix - pad, 18); [box addSubview:st]; + NSArray *bats = a[NS("batteries")]; + CGFloat ry = top + 48, cw = bats.count ? (W - ix - pad) / bats.count : 0; + for (NSUInteger i = 0; i < bats.count; i++) { + NSDictionary *b = bats[i]; + double pct = [b[NS("pct")] doubleValue]; + UIView *ring = Ring(22, pct, [b[NS("charging")] boolValue] ? NamedColor(NS("green")) : BatteryColor(pct)); + ring.frame = CGRectMake(ix + i * cw, ry, 22, 22); [box addSubview:ring]; + NSString *lbl = [b[NS("label")] length] ? [NSString stringWithFormat:NS("%@ %d%%"), b[NS("label")], (int)pct] : [NSString stringWithFormat:NS("%d%%"), (int)pct]; + UILabel *n = Label(lbl, [UIFont monospacedDigitSystemFontOfSize:13 weight:UIFontWeightSemibold], UIColor.whiteColor); + n.adjustsFontSizeToFitWidth = YES; n.minimumScaleFactor = 0.7; + n.frame = CGRectMake(ix + i * cw + 27, ry + 1, cw - 30, 20); [box addSubview:n]; + } + H = (bats.count ? ry + 22 : top + 58) + 16; + } else if ([kind isEqual:NS("event")]) { + UIImageView *ic = [[UIImageView alloc] initWithImage:a[NS("icon")]]; + ic.frame = CGRectMake(pad, cy - 12, 24, 24); ic.contentMode = UIViewContentModeScaleAspectFit; [box addSubview:ic]; + gBig = rightLabel(CallStr(a, NS("liveBig")) ?: NS(""), [UIFont monospacedDigitSystemFontOfSize:13 weight:UIFontWeightSemibold], tint); + UILabel *t = Label(S(a, "title"), [UIFont systemFontOfSize:19 weight:UIFontWeightSemibold], UIColor.whiteColor); + t.adjustsFontSizeToFitWidth = YES; t.minimumScaleFactor = 0.7; t.frame = CGRectMake(pad, y0 + 2, W - pad * 2, 26); [box addSubview:t]; + UILabel *s = Label(S(a, "subtitle"), [UIFont systemFontOfSize:14], gray); + s.frame = CGRectMake(pad, y0 + 30, W - pad * 2, 18); [box addSubview:s]; + H = y0 + 48 + 16; + } else { // notification + UIImageView *ic = RoundedIcon(a[NS("icon")], 26, 6.5); ic.frame = CGRectMake(pad, cy - 13, 26, 26); [box addSubview:ic]; + rightLabel([S(a, "subtitle") uppercaseString], [UIFont systemFontOfSize:10.5 weight:UIFontWeightSemibold], gray); + UILabel *t = Label(S(a, "title"), [UIFont systemFontOfSize:16 weight:UIFontWeightSemibold], UIColor.whiteColor); + t.frame = CGRectMake(pad, y0, W - pad * 2, 21); [box addSubview:t]; + CGFloat y = y0 + (S(a, "title").length ? 23 : 0), tw = W - pad * 2; + UIImage *thumb = a[NS("thumbnail")]; + if (thumb) { // a photo sent with the notification sits to the right, as on the stock banner + UIImageView *iv = RoundedIcon(thumb, 46, 8); iv.frame = CGRectMake(W - pad - 46, y0 + 2, 46, 46); [box addSubview:iv]; + tw -= 56; CGRect f = t.frame; f.size.width = tw; t.frame = f; + } + UILabel *b = Label(S(a, "body"), [UIFont systemFontOfSize:14.5], [UIColor colorWithWhite:1 alpha:0.86]); + b.numberOfLines = 3; + CGSize bs = [b sizeThatFits:CGSizeMake(tw, 100)]; + b.frame = CGRectMake(pad, y, tw, MIN(bs.height, 60)); [box addSubview:b]; + H = MAX(y + CGRectGetHeight(b.frame), thumb ? y0 + 50 : 0) + 18; + NSArray *actions = a[NS("actions")]; + if (actions.count) { + NSUInteger n = MIN(actions.count, (NSUInteger)3); + CGFloat bw = (W - pad * 2 - 8 * (n - 1)) / n, by = H - 8; + for (NSUInteger i = 0; i < n; i++) { + UIButton *c = ControlButton(NS("circle"), [NSString stringWithFormat:NS("notif:%lu"), (unsigned long)i], CGRectMake(pad + i * (bw + 8), by, bw, 36)); + [c setImage:nil forState:UIControlStateNormal]; + [c setTitle:[actions[i] valueForKey:NS("title")] forState:UIControlStateNormal]; + c.titleLabel.font = [UIFont systemFontOfSize:14 weight:UIFontWeightSemibold]; c.titleLabel.adjustsFontSizeToFitWidth = YES; c.titleLabel.minimumScaleFactor = 0.7; + c.backgroundColor = [UIColor colorWithWhite:1 alpha:0.16]; c.layer.cornerRadius = 12; c.layer.cornerCurve = kCACornerCurveContinuous; + [box addSubview:c]; + } + H = by + 36 + 14; + } + } + box.frame = CGRectMake(0, 0, W, H); + return CGSizeMake(W, H); +} + +static void Refresh(BOOL animated); + +// The stock output picker, the same sheet Control Center's media player opens. +static void ShowRoutes(void) { + static id controls; + Class c = NSClassFromString(NS("MPMediaControls")); + if (!c) return; + @try { + controls = [[c alloc] init]; + ((void (*)(id, SEL))objc_msgSend)(controls, NSSelectorFromString(NS("present"))); + } @catch (NSException *e) { LOG("routes: %@", e); } +} + +static void Tick(void) { + int _islet_z = 0; (void)_islet_z; // keeps blocks off the static-global (unsigned isa) path + Act *a = gCur; + if (!a || gScreenOff) return; + if (gExpandedKey && !gTransient && gFoldAt > 0 && CACurrentMediaTime() > gFoldAt && PrefNum(NS("autoFold"), 8) > 0) { gExpandedKey = nil; Refresh(YES); return; } + if (gLive && a[NS("liveCompact")]) { + NSString *t = CallStr(a, NS("liveCompact")); + if (![t isEqual:gLive.text]) { + if (ShowsLyrics(a)) { CATransition *fade = [CATransition animation]; fade.duration = 0.25; [gLive.layer addAnimation:fade forKey:NS("fade")]; } + gLive.text = t; + } + } + if (gBig && a[NS("liveBig")]) gBig.text = CallStr(a, NS("liveBig")); + if (gFill && a[NS("liveProgress")]) { + double p = MAX(0, MIN(1, CallDbl(a, NS("liveProgress")))); + UIView *fill = gFill; + CGFloat full = a[NS("fillWidth")] ? [a[NS("fillWidth")] doubleValue] : fill.superview.bounds.size.width - 40; + [UIView animateWithDuration:0.45 delay:0 options:UIViewAnimationOptionBeginFromCurrentState | UIViewAnimationOptionCurveLinear + animations:HB(^{ (void)_islet_z; CGRect f = fill.frame; f.size.width = full * p; fill.frame = f; }) completion:nil]; + } +} + +static NSString *DeviceSymbol(NSString *name, long product, BOOL watch); + +// The ranking every display decision uses: priority, then key so equal priorities never swap on their own. +static NSArray *RankedOngoing(void) { + int _islet_z = 0; (void)_islet_z; + return [gOngoing.allValues sortedArrayUsingComparator:HB(^NSComparisonResult(Act *x, Act *y) { (void)_islet_z; + int px = [x[NS("priority")] intValue], py = [y[NS("priority")] intValue]; + return px != py ? (px > py ? NSOrderedAscending : NSOrderedDescending) : [S(x, "key") compare:S(y, "key")]; + })]; +} + +// With two activities running, the real island splits off a small circle: same here, beside the tab. +static void UpdateBubble(void) { + Act *second = nil; + BOOL compact = gCur && !gExp && !gTransient && gIsland.alpha > 0.01 && PrefBool(NS("bubble"), YES); + if (compact) for (Act *a in RankedOngoing()) if (a != gCur && ![S(a, "key") isEqual:S(gCur, "key")]) { second = a; break; } + CGSize s = CompactSize(), host = gHost.bounds.size; + CGFloat cy = gNotch.height + (s.height - gNotch.height) / 2 - 1; + // Beside the tab, one each side. In landscape that's above and below it, still hugging the notch edge. + CGPoint right = CGPointMake(ScreenW() / 2 + s.width / 2 + 25, cy), left = CGPointMake(ScreenW() / 2 - s.width / 2 - 25, cy); + if (gMode) { + CGFloat x = gMode == 1 ? SideDepth() + 24 : host.width - SideDepth() - 24; + right = CGPointMake(x, host.height / 2 + s.height / 2 + 25); + left = CGPointMake(x, host.height / 2 - s.height / 2 - 25); + } + if (second) { + gBubble.center = right; + UIImageView *iv = gBubble.subviews.firstObject; + iv.image = second[NS("icon")]; + gBubbleRing.strokeColor = [second[NS("tint")] ?: UIColor.whiteColor colorWithAlphaComponent:0.8].CGColor; + gBubble.alpha = 1; gBubbleKey = S(second, "key"); + } else { gBubble.alpha = 0; gBubbleKey = nil; } + // Headphones sit on the other side for as long as they're connected, ring coloured by their battery. + if (compact && gAudioDevice && PrefBool(NS("audioBubble"), YES)) { + gLeftBubble.center = left; + UIImageView *iv = gLeftBubble.subviews.firstObject; + iv.image = Symbol(DeviceSymbol(gAudioDevice[NS("name")], [gAudioDevice[NS("product")] longValue], NO), 15, UIColor.whiteColor); + int low = [gAudioDevice[NS("low")] intValue]; + gLeftRing.strokeColor = (low > 0 && low <= 100 ? BatteryColor(low) : NamedColor(NS("blue"))).CGColor; + gLeftBubble.alpha = 1; + } else gLeftBubble.alpha = 0; +} + +static void AnchorIsland(void) { + CGSize host = gHost.bounds.size; + CALayer *l = gIsland.layer; + if (gMode == 0) { + l.anchorPoint = CGPointMake(0.5, 0); l.position = CGPointMake(host.width / 2, 0); + l.maskedCorners = kCALayerMinXMaxYCorner | kCALayerMaxXMaxYCorner; + } else if (gMode == 1) { + l.anchorPoint = CGPointMake(0, 0.5); l.position = CGPointMake(0, host.height / 2); + l.maskedCorners = kCALayerMaxXMinYCorner | kCALayerMaxXMaxYCorner; + } else { + l.anchorPoint = CGPointMake(1, 0.5); l.position = CGPointMake(host.width, host.height / 2); + l.maskedCorners = kCALayerMinXMinYCorner | kCALayerMinXMaxYCorner; + } +} + +static void ShowActivity(Act *a, BOOL e) { + int _islet_z = 0; (void)_islet_z; // keeps blocks off the static-global (unsigned isa) path + UIView *old = gBox, *island = gIsland; + UIView *box = [UIView new]; + gLive = nil; gBig = nil; gFill = nil; VizStop(); + CGSize s; + if (e) s = BuildExpanded(a, box); + else { s = CompactSizeFor(a); box.frame = CGRectMake(0, 0, s.width, s.height); BuildCompact(a, box, s); } + box.alpha = 0; box.transform = CGAffineTransformMakeScale(0.88, 0.88); + box.layer.anchorPoint = CGPointMake(0.5, 0); + box.layer.position = CGPointMake((gMode == 1 ? SideDepth() : 0) + s.width / 2, 0); + CGSize full = CGSizeMake(s.width + SideDepth(), s.height); + [island addSubview:box]; + gBox = box; gCur = a; gExp = e; + VizStart(); + if (e) gFoldAt = CACurrentMediaTime() + PrefNum(NS("autoFold"), 8); + + if (island.alpha < 0.01) { island.bounds = CGRectMake(0, 0, IdleSize().width, IdleSize().height); island.layer.cornerRadius = 8; } + UIColor *keyline = a[NS("tint")]; + island.layer.borderWidth = keyline ? 1.5 : 0; + island.layer.borderColor = [keyline colorWithAlphaComponent:0.8].CGColor; + island.alpha = 1; + AnchorIsland(); + CGFloat radius = e ? (gMode ? 30 : 36) : 24; + + [UIView animateWithDuration:0.12 animations:HB(^{ (void)_islet_z; old.alpha = 0; old.transform = CGAffineTransformMakeScale(0.9, 0.9); }) + completion:HB(^(BOOL f) { (void)_islet_z; [old removeFromSuperview]; })]; + [UIView animateWithDuration:e ? 0.62 : 0.5 delay:0 usingSpringWithDamping:e ? 0.7 : 0.62 initialSpringVelocity:0.4 + options:UIViewAnimationOptionBeginFromCurrentState | UIViewAnimationOptionAllowUserInteraction + animations:HB(^{ (void)_islet_z; island.bounds = CGRectMake(0, 0, full.width, full.height); island.layer.cornerRadius = radius; }) completion:nil]; + [UIView animateWithDuration:0.28 delay:old ? 0.05 : 0.1 usingSpringWithDamping:0.85 initialSpringVelocity:0 options:UIViewAnimationOptionAllowUserInteraction + animations:HB(^{ (void)_islet_z; box.alpha = 1; box.transform = CGAffineTransformIdentity; }) completion:nil]; + Tick(); + UpdateBubble(); +} + +static void HideIsland(BOOL animated) { + int _islet_z = 0; (void)_islet_z; // keeps blocks off the static-global (unsigned isa) path + UIView *island = gIsland; + if (island.alpha < 0.01) return; + UIView *old = gBox; gBox = nil; gCur = nil; gExp = NO; gLive = nil; gBig = nil; gFill = nil; VizStop(); + gBubble.alpha = 0; gBubbleKey = nil; gLeftBubble.alpha = 0; + CGSize s = IdleSize(); + [UIView animateWithDuration:animated ? 0.4 : 0 delay:0 usingSpringWithDamping:0.9 initialSpringVelocity:0 + options:UIViewAnimationOptionBeginFromCurrentState | UIViewAnimationOptionAllowUserInteraction + animations:HB(^{ (void)_islet_z; + old.alpha = 0; old.transform = CGAffineTransformMakeScale(0.8, 0.8); + island.bounds = CGRectMake(0, 0, s.width, s.height); island.layer.cornerRadius = 8; + }) completion:HB(^(BOOL f) { (void)_islet_z; [old removeFromSuperview]; if (!gCur) { island.alpha = 0; island.layer.borderWidth = 0; } })]; +} + +#pragma mark - Arbitration + +static BOOL IsLandscape(void) { return gMode != 0 && PrefBool(NS("hideLandscape"), NO); } + +// Optional: step aside for full-screen video. A landscape app that also owns now playing, playing or paused, is a video +// being watched; a landscape game with music from another app isn't. Worked out on the events that can change it. +static BOOL gFullscreenVideo; +// The status bar only rereads what it's showing when something changes, and an activity handed back isn't a change it can +// see. This makes it look again, so a recording pill returns as soon as Islet steps aside rather than at the next update. +static void RefreshStockStatusBar(void) { + Class c = NSClassFromString(NS("SBMainStatusBarStateProvider")); + SEL shared = NSSelectorFromString(NS("sharedInstance")), force = NSSelectorFromString(NS("forceUpdateLocalStatusBarData")); + if (!c || ![c respondsToSelector:shared]) return; + @try { + id p = ((id (*)(id, SEL))objc_msgSend)(c, shared); + if ([p respondsToSelector:force]) ((void (*)(id, SEL))objc_msgSend)(p, force); + } @catch (NSException *e) { LOG("status bar refresh: %@", e); } +} + +static void UpdateFullscreenVideo(void) { + BOOL on = NO; + if (gMode && PrefBool(NS("hideFullscreenVideo"), NO)) @try { + Class mc = NSClassFromString(NS("SBMediaController")); + id media = mc ? ((id (*)(id, SEL))objc_msgSend)(mc, NSSelectorFromString(NS("sharedInstance"))) : nil; + id front = ((id (*)(id, SEL))objc_msgSend)(UIApplication.sharedApplication, NSSelectorFromString(NS("_accessibilityFrontMostApplication"))); + id owner = [media valueForKey:NS("nowPlayingApplication")]; + on = front && owner && [[front valueForKey:NS("bundleIdentifier")] isEqual:[owner valueForKey:NS("bundleIdentifier")]]; + } @catch (NSException *e) { LOG("fullscreen video: %@", e); } + if (on == gFullscreenVideo) return; + gFullscreenVideo = on; + Refresh(YES); + RefreshStockStatusBar(); +} + +static BOOL HiddenByUser(void) { return gHideUntil && gHideUntil.timeIntervalSinceNow > 0; } + +// Whether a popup may show right now: nothing in landscape, and while the user has the island hidden only `critical` ones. +static BOOL Suppressed(BOOL critical) { + if (!PrefBool(NS("enabled"), YES) || IsLandscape()) return YES; + return (HiddenByUser() || gFullscreenVideo) && !critical; +} + +static void SetOngoing(Act *a, NSString *key) { + Act *old = gOngoing[key]; + if (!a) { + if (old) { [gOngoing removeObjectForKey:key]; if ([gExpandedKey isEqual:key]) gExpandedKey = nil; Refresh(YES); } + return; + } + gOngoing[key] = a; + BOOL changed = !old || ![S(old, "title") ?: NS("") isEqual:S(a, "title") ?: NS("")] || ![S(old, "subtitle") ?: NS("") isEqual:S(a, "subtitle") ?: NS("")] + || old[NS("icon")] != a[NS("icon")] || (old[NS("paused")] != nil) != (a[NS("paused")] != nil) || [old[NS("muted")] boolValue] != [a[NS("muted")] boolValue]; + if (changed) Refresh(YES); + else if (gCur == old) gCur = a; // same look, but the live blocks may carry fresh data (a seek, a changed timer) + else UpdateBubble(); +} + +static void EndTransient(Act *a); +static void PresentTransient(Act *a) { + int _islet_z = 0; (void)_islet_z; // keeps blocks off the static-global (unsigned isa) path + BOOL alreadyOpen = gExp && gCur && [a[NS("expandFirst")] boolValue]; // no folding down between two cards + gTransient = a; + NSTimeInterval ttl = [a[NS("ttl")] doubleValue]; + if (gQueue.count) ttl = MIN(ttl, 2.0); + ShowActivity(a, alreadyOpen); + if (!alreadyOpen && [a[NS("expandFirst")] boolValue]) { + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.28 * NSEC_PER_SEC)), dispatch_get_main_queue(), HB(^{ (void)_islet_z; + if (gTransient == a) ShowActivity(a, YES); + })); + } + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(ttl * NSEC_PER_SEC)), dispatch_get_main_queue(), HB(^{ (void)_islet_z; EndTransient(a); })); +} + +static void PostTransient(Act *a) { + int _islet_z = 0; (void)_islet_z; + if (Suppressed([a[NS("critical")] boolValue])) return; + // A notification takes over on the spot, as stock banners do; the one it replaces is safe in Notification Center. + // Same for an update to whatever is showing. Anything else waits its turn, and hurries the current one along. + if (gTransient && ([S(a, "kind") isEqual:NS("notif")] || [S(gTransient, "key") isEqual:S(a, "key")])) { gTransient = nil; PresentTransient(a); return; } + if (gTransient) { + if (gQueue.count > 4) [gQueue removeObjectAtIndex:0]; + [gQueue addObject:a]; + Act *cur = gTransient; + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), HB(^{ (void)_islet_z; EndTransient(cur); })); + return; + } + PresentTransient(a); +} + +static void EndTransient(Act *a) { + if (gTransient != a) return; + gTransient = nil; + while (gQueue.count) { + Act *n = gQueue.firstObject; + [gQueue removeObjectAtIndex:0]; + if (!Suppressed([n[NS("critical")] boolValue])) { PresentTransient(n); return; } + } + Refresh(YES); +} + +static void Refresh(BOOL animated) { + int _islet_z = 0; (void)_islet_z; // keeps blocks off the static-global (unsigned isa) path + if (gTransient && Suppressed([gTransient[NS("critical")] boolValue])) { gTransient = nil; [gQueue removeAllObjects]; } // cut off means now + if (gTransient) return; + Act *best = RankedOngoing().firstObject; + Act *top = gExpandedKey ? gOngoing[gExpandedKey] : nil; + BOOL expand = top != nil; + if (gPinnedKey && !gOngoing[gPinnedKey]) gPinnedKey = nil; + if (!top) top = gPinnedKey && [best[NS("priority")] intValue] < 4 ? gOngoing[gPinnedKey] : best; // a call always wins + if (!top || Suppressed([top[NS("priority")] intValue] >= 4)) { HideIsland(animated); return; } + NSDate *until = top[NS("autoExpandUntil")]; + if (until && [until timeIntervalSinceNow] > 0) { + expand = YES; + NSString *k = S(top, "key"); + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)([until timeIntervalSinceNow] * NSEC_PER_SEC)), dispatch_get_main_queue(), HB(^{ (void)_islet_z; + if (!gExpandedKey) { Act *t = gOngoing[k]; if (t) [t removeObjectForKey:NS("autoExpandUntil")]; Refresh(YES); } + })); + } + if (gCur == top && gExp == expand && gIsland.alpha > 0.01) { UpdateBubble(); return; } + ShowActivity(top, expand); +} + +// Swipe up on the compact island: get out of the way for a while, then come back on our own. +static void HideForAWhile(NSTimeInterval secs) { + int _islet_z = 0; (void)_islet_z; + gHideUntil = [NSDate dateWithTimeIntervalSinceNow:secs]; + gExpandedKey = nil; gPinnedKey = nil; + Refresh(YES); + NSDate *mine = gHideUntil; + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(secs * NSEC_PER_SEC)), dispatch_get_main_queue(), HB(^{ (void)_islet_z; + if (gHideUntil == mine) { gHideUntil = nil; Refresh(YES); } + })); +} + +// Sideways swipe: step through what's running without waiting for it to end. +static void CycleActivity(void) { + NSArray *all = RankedOngoing(); + if (gTransient || all.count < 2) return; + NSUInteger i = gCur ? [all indexOfObject:gCur] : 0; + Act *next = all[i == NSNotFound ? 0 : (i + 1) % all.count]; + gPinnedKey = S(next, "key"); + if (gExpandedKey) gExpandedKey = gPinnedKey; + Refresh(YES); +} + +static void OpenApp(NSString *bid) { + int _islet_z = 0; (void)_islet_z; + // LaunchServices blocks until SpringBoard answers its own request: never call it on the main thread. + dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), HB(^{ (void)_islet_z; + @try { + Class c = NSClassFromString(NS("LSApplicationWorkspace")); + id ws = ((id (*)(id, SEL))objc_msgSend)(c, NSSelectorFromString(NS("defaultWorkspace"))); + ((BOOL (*)(id, SEL, id))objc_msgSend)(ws, NSSelectorFromString(NS("openApplicationWithBundleID:")), bid); + } @catch (NSException *e) { LOG("open app: %@", e); } + })); +} + +static void RunNotificationAction(id action, Act *a); + +// A notification opens through its own action, which lands on the right conversation; everything else opens its app. +static void OpenActivity(Act *a) { + id def = [a[NS("request")] valueForKey:NS("defaultAction")]; + if (def) RunNotificationAction(def, a); + else if (S(a, "bundleID")) OpenApp(S(a, "bundleID")); +} + +static void OnTap(void) { + Act *cur = gCur; + if (!cur) return; + NSString *bid = S(cur, "bundleID"); + if (gTransient) { + if (gTransient == cur && gExp) { + OpenActivity(cur); + EndTransient(gTransient); + } + return; + } + if (!gExp) { // compact: unfold + [[[UIImpactFeedbackGenerator alloc] initWithStyle:UIImpactFeedbackStyleLight] impactOccurred]; + gExpandedKey = S(cur, "key"); Refresh(YES); return; + } + if (bid) OpenApp(bid); // unfolded: open the app, fold back + gExpandedKey = nil; Refresh(YES); +} + +// Unfolded folds, a popup goes away, and the plain compact island hides for a while. +static void OnSwipeUp(void) { + if (gTransient) { EndTransient(gTransient); return; } + if (gExpandedKey) { gExpandedKey = nil; Refresh(YES); return; } + if ([gCur[NS("priority")] intValue] >= 4) return; // a call stays put + if (gCur) HideForAWhile(PrefNum(NS("hideSeconds"), 10)); +} + +static void OnSwipeDown(void) { + if (gTransient || !gCur || gExp) return; + gExpandedKey = S(gCur, "key"); Refresh(YES); +} + +static void ExpandNotification(Act *a); + +// Long press: a notification opens the stock expanded view, with reply and all its actions; anything else opens its app. +static void OnLongPress(void) { + Act *cur = gCur; + if (!cur || (!cur[NS("request")] && !S(cur, "bundleID"))) return; + [[[UIImpactFeedbackGenerator alloc] initWithStyle:UIImpactFeedbackStyleMedium] impactOccurred]; + if (cur[NS("request")]) ExpandNotification(cur); + else OpenApp(S(cur, "bundleID")); + if (gTransient) EndTransient(gTransient); + else if (gExpandedKey) { gExpandedKey = nil; Refresh(YES); } +} + +#pragma mark - Runtime-created classes + +static IMP sHitSuper; +static UIView *win_hitTest(UIWindow *self, SEL _cmd, CGPoint p, UIEvent *e) { + int _islet_z = 0; (void)_islet_z; + if (!gIsland || gIsland.alpha < 0.01) return nil; + CGPoint q = [gHost convertPoint:p fromView:self]; + if (gBubble.alpha > 0.01 && CGRectContainsPoint(CGRectInset(gBubble.frame, -6, -6), q)) return [gBubble hitTest:[gBubble convertPoint:q fromView:gHost] withEvent:e] ?: gBubble; + if (gLeftBubble.alpha > 0.01 && CGRectContainsPoint(CGRectInset(gLeftBubble.frame, -6, -6), q)) return gLeftBubble; + CALayer *pl = gIsland.layer.presentationLayer; + CGRect r = CGRectInset(pl ? pl.frame : gIsland.frame, -8, -8); + if (!CGRectContainsPoint(r, q)) { + // A touch anywhere else folds an unfolded card, and still goes through to whatever is underneath. + if (gExpandedKey && !gTransient && e.type == UIEventTypeTouches) + dispatch_async(dispatch_get_main_queue(), HB(^{ (void)_islet_z; if (gExpandedKey) { gExpandedKey = nil; Refresh(YES); } })); + return nil; + } + return ((UIView * (*)(id, SEL, CGPoint, UIEvent *))sHitSuper)(self, _cmd, p, e); +} +static void tgt_tapped(id self, SEL _cmd, id g) { + // taps on a control (skip, pause, torch...) belong to that control, not to the island + UIGestureRecognizer *r = g; + UIView *h = [gIsland hitTest:[r locationInView:gIsland] withEvent:nil]; + for (; h && h != gIsland; h = h.superview) if ([h isKindOfClass:UIControl.class]) return; + OnTap(); +} +// A pan, not swipe recognizers: those want more travel than the compact tab has, which is why swipe up never fired on +// it. This fires once per drag, as soon as the direction is clear. +static void tgt_panned(id self, SEL _cmd, UIPanGestureRecognizer *g) { + static BOOL done; + if (g.state == UIGestureRecognizerStateBegan) done = NO; + if (done || (g.state != UIGestureRecognizerStateChanged && g.state != UIGestureRecognizerStateEnded)) return; + // Along the axis out of the notch: into it hides, away from it unfolds. That's vertical in portrait, sideways in landscape. + CGPoint t = [g translationInView:gIsland]; + CGFloat out = gMode == 0 ? t.y : gMode == 1 ? t.x : -t.x, across = gMode ? t.y : t.x; + if (fabs(out) >= 12 && fabs(out) >= fabs(across)) { done = YES; if (out < 0) OnSwipeUp(); else OnSwipeDown(); } + else if (fabs(across) >= 24) { done = YES; CycleActivity(); } +} +static void tgt_bubble(id self, SEL _cmd, id g) { if (gBubbleKey) { gPinnedKey = gBubbleKey; Refresh(YES); } } +static void ShowAudioDevice(void); +static void tgt_leftBubble(id self, SEL _cmd, id g) { ShowAudioDevice(); } +static void tgt_longPressed(id self, SEL _cmd, UIGestureRecognizer *g) { if (g.state == UIGestureRecognizerStateBegan) OnLongPress(); } + +static Class MakeClass(const char *name, Class super_, void (^setup)(Class)) { + Class c = objc_allocateClassPair(super_, name, 0); + if (!c) return NSClassFromString([NSString stringWithUTF8String:name]); + setup(c); + objc_registerClassPair(c); + return c; +} + +#pragma mark - Sources + +// Apple's own Now Playing waveform (lock screen / Control Center) taps the playing app's audio through +// MRUAudioAnalyzer and publishes FFT amplitudes; Islet subscribes to the same thing. +static id gAnalyzer, gAudioObserver; +static int gAnalyzerPID; +static void (*MRGetPID)(dispatch_queue_t, void (^)(int)); + +static void obs_update(id self, SEL _cmd, id analyzer, id data) { + int _islet_z = 0; (void)_islet_z; + NSArray *amps = nil; + @try { amps = [data valueForKey:NS("amplitudes")]; } @catch (NSException *e) {} + if (![amps isKindOfClass:NSArray.class]) return; + dispatch_async(dispatch_get_main_queue(), HB(^{ (void)_islet_z; + static BOOL logged; + if (!logged) { logged = YES; LOG("audio analyzer live: %lu amplitudes, first=%@", (unsigned long)amps.count, amps.firstObject); } + gAmps = amps; gAmpsAt = CACurrentMediaTime(); + VizStart(); + })); +} + +static void StopAnalyzer(void) { // ends the feed, which is what lets the bars settle + if (gAnalyzer) { + @try { + ((void (*)(id, SEL, id))objc_msgSend)(gAnalyzer, NSSelectorFromString(NS("removeObserver:")), gAudioObserver); + ((void (*)(id, SEL))objc_msgSend)(gAnalyzer, NSSelectorFromString(NS("stop"))); + } @catch (NSException *e) { LOG("stop analyzer: %@", e); } + } + gAnalyzer = nil; gAnalyzerPID = 0; gAmps = nil; +} + +static void StartAnalyzer(int pid) { + int _islet_z = 0; (void)_islet_z; + if (pid <= 0 || !PrefBool(NS("realVisualizer"), YES)) return; + if (gAnalyzer && gAnalyzerPID == pid) return; + StopAnalyzer(); + Class ac = NSClassFromString(NS("MRUAudioAnalyzer")), sc = NSClassFromString(NS("MRUWaveformSettings")); + if (!ac) { LOG("MRUAudioAnalyzer missing"); return; } + if (!gAudioObserver) { + Class oc = MakeClass("IsletAudioObserver", NSObject.class, HB(^(Class c) { (void)_islet_z; + class_addMethod(c, NSSelectorFromString(NS("audioAnalyzer:didUpdateWaveform:")), (IMP)obs_update, "v@:@@"); + Protocol *p = objc_getProtocol("MRUAudioAnalyzerObserver"); if (p) class_addProtocol(c, p); + })); + gAudioObserver = [oc new]; + } + @try { + id an = ((id (*)(id, SEL, int))objc_msgSend)(ac, NSSelectorFromString(NS("audioAnalyzerForPID:")), pid); + if (!an) { LOG("no analyzer for pid %d", pid); return; } + if (sc) ((void (*)(id, SEL, id))objc_msgSend)(an, NSSelectorFromString(NS("setSettings:")), ((id (*)(id, SEL))objc_msgSend)(sc, NSSelectorFromString(NS("currentSettings")))); + ((void (*)(id, SEL, id))objc_msgSend)(an, NSSelectorFromString(NS("addObserver:")), gAudioObserver); + ((void (*)(id, SEL))objc_msgSend)(an, NSSelectorFromString(NS("start"))); + gAnalyzer = an; gAnalyzerPID = pid; + LOG("audio analyzer started for pid %d", pid); + } @catch (NSException *e) { LOG("start analyzer: %@", e); } +} + +static void MediaChanged(void); + +static void ReloadMusicCard(void) { + if ([S(gCur, "kind") isEqual:NS("music")] && !gTransient) ShowActivity(gCur, gExp); +} + +// Which now-playing apps get lyrics: players by name, any app the user lists in `lyricApps`, and unknown apps only when the +// track has an album, the mark of a song. Video and spoken apps stay out, so what's watched isn't looked up anywhere. +static BOOL IsMusicPlayer(NSString *bid, NSString *album) { + NSString *b = bid.lowercaseString; + if (!b.length) return NO; + if ([Pref(NS("lyricApps")) containsObject:bid]) return YES; + if ([b containsString:NS("youtubemusic")]) return YES; + for (NSString *k in @[NS("youtube"), NS("netflix"), NS("hulu"), NS("twitch"), NS("roku"), NS("disney"), NS("tiktok"), NS("musical.ly"), NS("instagram"), NS("twitter"), NS("safari"), + NS("podcast"), NS("audible"), NS("iBooks"), NS("primevideo"), NS("plex.ios")]) if ([b containsString:k.lowercaseString]) return NO; + for (NSString *k in @[NS("music"), NS("mulberry"), NS("flacbox"), NS("spotify"), NS("tidal"), NS("deezer"), NS("soundcloud"), NS("pandora"), NS("vox"), NS("doppler"), NS("plexamp"), NS("foobar"), + NS("qobuz"), NS("audiomack"), NS("musi"), NS("jellyfin"), NS("finamp"), NS("navidrome"), NS("substreamer"), NS("cesium"), NS("marvis"), NS("player"), NS("flac")]) + if ([b containsString:k]) return YES; + return album.length > 0; +} + +static NSString *CleanTitle(NSString *t) { // "Song (2011 Remaster)" and "Song - Single" find nothing under their full names + NSRegularExpression *re = [NSRegularExpression regularExpressionWithPattern:NS("\\s*[\\(\\[][^\\)\\]]*[\\)\\]]|\\s+-\\s+.*$") options:0 error:nil]; + NSString *c = [re stringByReplacingMatchesInString:t options:0 range:NSMakeRange(0, t.length) withTemplate:NS("")]; + return c.length ? c : t; +} + +// NetEase search can return covers and remixes: only a song with the right name and length counts. +static id PickNetEaseSong(NSArray *songs, NSString *title, double dur) { + NSString *want = CleanTitle(title); + for (NSDictionary *x in songs) { + if (![x isKindOfClass:NSDictionary.class] || ![x[NS("name")] isKindOfClass:NSString.class]) continue; + if ([x[NS("name")] caseInsensitiveCompare:want] != NSOrderedSame) continue; + double len = [x[NS("dt")] doubleValue] / 1000; + if (dur <= 0 || fabs(len - dur) <= 4) return x[NS("id")]; + } + return nil; +} + +static void FetchJSON(NSMutableURLRequest *req, void (^done)(id)) { + int _islet_z = 0; (void)_islet_z; + req.timeoutInterval = 8; + [[NSURLSession.sharedSession dataTaskWithRequest:req completionHandler:HB(^(NSData *d, NSURLResponse *r, NSError *e) { (void)_islet_z; + id j = d ? [NSJSONSerialization JSONObjectWithData:d options:0 error:nil] : nil; + dispatch_async(gSlowQ, HB(^{ (void)_islet_z; done(j); })); + })] resume]; +} + +static NSMutableURLRequest *LrclibRequest(const char *path, NSArray *query) { + NSURLComponents *u = [NSURLComponents componentsWithString:[NS("https://lrclib.net/api/") stringByAppendingString:NS(path)]]; + u.queryItems = query; + NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:u.URL]; + [req setValue:NS("Islet (https://archlinux.tail7c4f5e.ts.net/git/astar76/Islet)") forHTTPHeaderField:NS("User-Agent")]; + return req; +} + +static NSMutableURLRequest *NetEaseRequest(NSString *url) { + NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]]; + [req setValue:NS("https://music.163.com/") forHTTPHeaderField:NS("Referer")]; + [req setValue:NS("Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X)") forHTTPHeaderField:NS("User-Agent")]; + return req; +} + +// NetEase is the backup: it has plenty lrclib doesn't, especially Asian releases. +static void LookUpNetEase(NSString *title, NSString *artist, double dur, void (^found)(NSString *)) { + int _islet_z = 0; (void)_islet_z; + if (!PrefBool(NS("neteaseLyrics"), YES)) { found(nil); return; } + NSURLComponents *form = [NSURLComponents new]; + form.queryItems = @[[NSURLQueryItem queryItemWithName:NS("s") value:[NSString stringWithFormat:NS("%@ %@"), CleanTitle(title), artist]], + [NSURLQueryItem queryItemWithName:NS("type") value:NS("1")], [NSURLQueryItem queryItemWithName:NS("limit") value:NS("10")]]; + NSMutableURLRequest *search = NetEaseRequest(NS("https://music.163.com/api/cloudsearch/pc")); + search.HTTPMethod = NS("POST"); search.HTTPBody = [form.percentEncodedQuery dataUsingEncoding:NSUTF8StringEncoding]; + FetchJSON(search, HB(^(id j) { (void)_islet_z; + id result = [j isKindOfClass:NSDictionary.class] ? j[NS("result")] : nil; + id songs = [result isKindOfClass:NSDictionary.class] ? result[NS("songs")] : nil; + id song = [songs isKindOfClass:NSArray.class] ? PickNetEaseSong(songs, title, dur) : nil; + if (!song) { found(nil); return; } + FetchJSON(NetEaseRequest([NSString stringWithFormat:NS("https://music.163.com/api/song/lyric?id=%@&lv=1&kv=1&tv=-1"), song]), HB(^(id l) { (void)_islet_z; + id lrc = [l isKindOfClass:NSDictionary.class] ? l[NS("lrc")] : nil; + id text = [lrc isKindOfClass:NSDictionary.class] ? lrc[NS("lyric")] : nil; + found([text isKindOfClass:NSString.class] ? text : nil); + })); + })); +} + +// lrclib's exact lookup, then its search with a cleaned-up title, then NetEase. Only timed lyrics count anywhere: plain ones +// have no way to follow the song. +static void LookUpLyrics(NSString *title, NSString *artist, NSString *album, double dur, void (^found)(NSString *)) { + int _islet_z = 0; (void)_islet_z; + NSArray *exact = @[[NSURLQueryItem queryItemWithName:NS("track_name") value:title], [NSURLQueryItem queryItemWithName:NS("artist_name") value:artist], + [NSURLQueryItem queryItemWithName:NS("album_name") value:album ?: NS("")], [NSURLQueryItem queryItemWithName:NS("duration") value:[NSString stringWithFormat:NS("%d"), (int)round(dur)]]]; + FetchJSON(LrclibRequest("get", exact), HB(^(id j) { (void)_islet_z; + id lrc = [j isKindOfClass:NSDictionary.class] ? j[NS("syncedLyrics")] : nil; + if ([lrc isKindOfClass:NSString.class] && [lrc length]) { found(lrc); return; } + NSArray *q = @[[NSURLQueryItem queryItemWithName:NS("track_name") value:CleanTitle(title)], [NSURLQueryItem queryItemWithName:NS("artist_name") value:artist]]; + FetchJSON(LrclibRequest("search", q), HB(^(id list) { (void)_islet_z; + if ([list isKindOfClass:NSArray.class]) for (NSDictionary *x in list) { + if (![x isKindOfClass:NSDictionary.class]) continue; + id t = x[NS("syncedLyrics")]; + if ([t isKindOfClass:NSString.class] && [t length] && (dur <= 0 || fabs([x[NS("duration")] doubleValue] - dur) <= 4)) { found(t); return; } + } + LookUpNetEase(title, artist, dur, found); + })); + })); +} + +static NSMutableDictionary *gLyricCache; // per track, NSNull for "nothing out there": one lookup a song +static void (^gRetryLyrics)(void); + +// Embedded lyrics first, from the library item Music is playing, which is also the only place tags can be read. Other players +// keep their files to themselves, so those go online, sending the title and artist, unless that's turned off. +static void LoadLyrics(NSString *track, NSString *title, NSString *artist, NSString *album, double dur) { + int _islet_z = 0; (void)_islet_z; + static NSString *wanted; + wanted = track; gLyrics = nil; + NSString *bid = gMusicBID; + gRetryLyrics = HB(^{ (void)_islet_z; LoadLyrics(track, title, artist, album, dur); }); + if (!PrefBool(NS("enabled"), YES) || !PrefBool(NS("lyrics"), YES) || !IsMusicPlayer(bid, album)) { ReloadMusicCard(); return; } + if (!gLyricCache) gLyricCache = [NSMutableDictionary new]; + id cached = gLyricCache[track]; + if ([cached isKindOfClass:NSArray.class]) { gLyrics = cached; ReloadMusicCard(); return; } + if (cached) return; + void (^deliver)(NSString *) = HB(^(NSString *lrc) { (void)_islet_z; + NSArray *parsed = lrc ? ParseLRC(lrc) : nil; + dispatch_async(dispatch_get_main_queue(), HB(^{ (void)_islet_z; + if (gLyricCache.count > 60) [gLyricCache removeAllObjects]; + gLyricCache[track] = parsed.count ? parsed : (id)NSNull.null; + if (![wanted isEqual:track]) return; + gLyrics = parsed.count ? parsed : nil; + ReloadMusicCard(); + })); + }); + dispatch_async(gSlowQ, HB(^{ (void)_islet_z; + NSString *text = nil; + if ([bid isEqual:NS("com.apple.Music")]) @try { + Class pc = NSClassFromString(NS("MPMusicPlayerController")); + id item = [((id (*)(id, SEL))objc_msgSend)(pc, NSSelectorFromString(NS("systemMusicPlayer"))) valueForKey:NS("nowPlayingItem")]; + if ([[item valueForKey:NS("title")] isEqual:title]) text = [item valueForKey:NS("lyrics")]; + } @catch (NSException *e) { LOG("lyrics: %@", e); } + if (ParseLRC(text).count) { deliver(text); return; } + if (PrefBool(NS("onlineLyrics"), YES)) LookUpLyrics(title, artist, album, dur, deliver); + })); +} + +static void ApplyMedia(NSDictionary *info, BOOL playing) { + int _islet_z = 0; (void)_islet_z; // keeps blocks off the static-global (unsigned isa) path + static NSData *lastArt; static UIImage *lastImg; static UIColor *lastTint; static int lingerGen; + NSString *title = info[NS("kMRMediaRemoteNowPlayingInfoTitle")]; + Act *old = gOngoing[NS("music")]; + if (!title.length || (!playing && !old)) { SetOngoing(nil, NS("music")); StopAnalyzer(); return; } + if (!playing) StopAnalyzer(); + NSString *artist = info[NS("kMRMediaRemoteNowPlayingInfoArtist")] ?: NS(""); + NSData *art = info[NS("kMRMediaRemoteNowPlayingInfoArtworkData")]; + if (art != lastArt && ![art isEqual:lastArt]) { // decoding and averaging is the expensive part: once per cover + lastArt = art; lastImg = art ? [UIImage imageWithData:art] : nil; lastTint = lastImg ? AverageColor(lastImg) : nil; + } + UIImage *img = lastImg ?: Symbol(NS("music.note"), 40, UIColor.whiteColor); + NSString *track = [NSString stringWithFormat:NS("%@|%@"), title, artist]; + BOOL newTrack = ![track isEqual:gLastTrack]; + gLastTrack = track; + + Act *a = NewAct(NS("music"), NS("music")); + a[NS("priority")] = @2; a[NS("title")] = title; a[NS("subtitle")] = artist; a[NS("icon")] = img; + if (gMusicBID) a[NS("bundleID")] = gMusicBID; + a[NS("tint")] = lastTint ?: UIColor.whiteColor; + // Paused keeps the card a moment so resuming is one tap away and a track change doesn't flicker it off. + if (!playing) { + a[NS("paused")] = @YES; + if (!old[NS("paused")]) { + int gen = ++lingerGen; + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(PrefNum(NS("musicLinger"), 10) * NSEC_PER_SEC)), dispatch_get_main_queue(), HB(^{ (void)_islet_z; + if (gen == lingerGen && gOngoing[NS("music")][NS("paused")]) SetOngoing(nil, NS("music")); + })); + } + } else lingerGen++; + double dur = [info[NS("kMRMediaRemoteNowPlayingInfoDuration")] doubleValue], el = [info[NS("kMRMediaRemoteNowPlayingInfoElapsedTime")] doubleValue]; + double rate = playing ? [info[NS("kMRMediaRemoteNowPlayingInfoPlaybackRate")] doubleValue] : 0; + NSDate *ts = info[NS("kMRMediaRemoteNowPlayingInfoTimestamp")] ?: NSDate.date; + a[NS("liveProgress")] = HB(^double { (void)_islet_z; return dur > 0 ? (el + rate * -[ts timeIntervalSinceNow]) / dur : 0; }); + a[NS("liveBig")] = HB(^NSString *{ (void)_islet_z; return dur > 0 ? [NSString stringWithFormat:NS("-%@"), FmtTime(dur - (el + rate * -[ts timeIntervalSinceNow]))] : NS(""); }); + a[NS("liveCompact")] = HB(^NSString *{ (void)_islet_z; return LyricAt(el + rate * -[ts timeIntervalSinceNow]); }); + if (newTrack) LoadLyrics(track, title, artist, info[NS("kMRMediaRemoteNowPlayingInfoAlbum")], dur); + if (newTrack && PrefBool(NS("musicPeek"), YES)) a[NS("autoExpandUntil")] = [NSDate dateWithTimeIntervalSinceNow:3.4]; + else if (old[NS("autoExpandUntil")]) a[NS("autoExpandUntil")] = old[NS("autoExpandUntil")]; + if (newTrack) { gOngoing[NS("music")] = a; Refresh(YES); } + else SetOngoing(a, NS("music")); +} + +static void MediaChanged(void) { + int _islet_z = 0; (void)_islet_z; // keeps blocks off the static-global (unsigned isa) path + if (!MRGetPlaying || !MRGetInfo || !PrefBool(NS("enabled"), YES)) return; + if (!PrefBool(NS("music"), YES) || !PrefBool(NS("enabled"), YES)) { SetOngoing(nil, NS("music")); StopAnalyzer(); return; } + if (MRGetClient && MRClientBID) + MRGetClient(dispatch_get_main_queue(), HB(^(id client) { (void)_islet_z; + NSString *b = client ? MRClientBID((__bridge CFTypeRef)client) : nil; + if (b) { + BOOL changed = ![b isEqual:gMusicBID]; + gMusicBID = b; gOngoing[NS("music")][NS("bundleID")] = b; + if (changed && gRetryLyrics) gRetryLyrics(); // the track may have got here first + } + })); + MRGetPlaying(dispatch_get_main_queue(), HB(^(Boolean playing) { (void)_islet_z; + UpdateFullscreenVideo(); + if (!playing) StopAnalyzer(); + else if (MRGetPID) MRGetPID(dispatch_get_main_queue(), HB(^(int pid) { (void)_islet_z; StartAnalyzer(pid); })); + MRGetInfo(dispatch_get_main_queue(), HB(^(NSDictionary *info) { (void)_islet_z; ApplyMedia(info, playing); })); + })); +} + +static void SetupMedia(void) { + int _islet_z = 0; (void)_islet_z; // keeps blocks off the static-global (unsigned isa) path + void *h = dlopen("/System/Library/PrivateFrameworks/MediaRemote.framework/MediaRemote", RTLD_NOW); + if (!h) { LOG("MediaRemote missing"); return; } + MRRegister = dlsym(h, "MRMediaRemoteRegisterForNowPlayingNotifications"); + MRGetInfo = dlsym(h, "MRMediaRemoteGetNowPlayingInfo"); + MRGetPlaying = dlsym(h, "MRMediaRemoteGetNowPlayingApplicationIsPlaying"); + MRSendCommand = dlsym(h, "MRMediaRemoteSendCommand"); + MRGetClient = dlsym(h, "MRMediaRemoteGetNowPlayingClient"); + MRGetPID = dlsym(h, "MRMediaRemoteGetNowPlayingApplicationPID"); + MRClientBID = dlsym(h, "MRNowPlayingClientGetBundleIdentifier"); + if (!MRRegister || !MRGetInfo || !MRGetPlaying) return; + MRRegister(dispatch_get_main_queue()); + Every(0.25, 0.05, HB(^{ (void)_islet_z; if (!gScreenOff && ShowsLyrics(gCur)) Tick(); })); + for (NSString *n in @[NS("kMRMediaRemoteNowPlayingInfoDidChangeNotification"), + NS("kMRMediaRemoteNowPlayingApplicationIsPlayingDidChangeNotification"), + NS("kMRMediaRemoteNowPlayingApplicationDidChangeNotification")]) + [NSNotificationCenter.defaultCenter addObserverForName:n object:nil queue:NSOperationQueue.mainQueue usingBlock:HB(^(NSNotification *x) { (void)_islet_z; MediaChanged(); })]; + MediaChanged(); +} + +static void PollTimers(void) { + int _islet_z = 0; (void)_islet_z; // keeps blocks off the static-global (unsigned isa) path + if (!gMT) { + dlopen("/System/Library/PrivateFrameworks/MobileTimer.framework/MobileTimer", RTLD_NOW); + Class c = NSClassFromString(NS("MTTimerManager")); + if (!c) return; + gMT = [[c alloc] init]; + } + id mgr = gMT; + static dispatch_queue_t q; static dispatch_once_t once; + dispatch_once(&once, HB(^{ (void)_islet_z; q = dispatch_queue_create("islet.timers", DISPATCH_QUEUE_SERIAL); })); + dispatch_async(q, HB(^{ (void)_islet_z; + id best = nil, firing = nil, paused = nil; NSDate *bestDate = nil; NSString *title = nil; + NSTimeInterval dur = 0, remain = 0; + @try { + NSArray *timers = ((id (*)(id, SEL))objc_msgSend)(mgr, NSSelectorFromString(NS("timersSync"))); + for (id t in timers) { + if ([[t valueForKey:NS("isFiring")] boolValue]) { firing = t; continue; } + if ([[t valueForKey:NS("state")] intValue] == 2) { paused = t; continue; } // MTTimerStatePaused + NSDate *fd = [t valueForKey:NS("fireDate")]; + if (!fd || [fd timeIntervalSinceNow] <= 0) continue; + if (!bestDate || [fd compare:bestDate] == NSOrderedAscending) { best = t; bestDate = fd; } + } + id p = firing ?: best ?: paused; + title = [p valueForKey:NS("displayTitle")] ?: [p valueForKey:NS("title")]; + dur = [[p valueForKey:NS("duration")] doubleValue]; + remain = [[p valueForKey:NS("remainingTime")] doubleValue]; + } @catch (NSException *e) { LOG("timers: %@", e); return; } + id pick = firing ?: best ?: paused; + BOOL isPaused = pick && pick == paused; + dispatch_async(dispatch_get_main_queue(), HB(^{ (void)_islet_z; + if (!pick) { SetOngoing(nil, NS("timer")); return; } + UIColor *orange = NamedColor(NS("orange")); + Act *a = NewAct(NS("timer"), NS("timer")); + a[NS("timerObject")] = pick; + a[NS("bundleID")] = NS("com.apple.mobiletimer"); a[NS("priority")] = @3; a[NS("tint")] = orange; a[NS("title")] = title.length ? title : NS("Timer"); a[NS("icon")] = Symbol(NS("timer"), 17, orange); + if (firing) { + a[NS("subtitle")] = NS("Done"); + a[NS("liveCompact")] = HB(^NSString *{ (void)_islet_z; return NS("Done"); }); a[NS("liveBig")] = HB(^NSString *{ (void)_islet_z; return NS("Done"); }); + a[NS("liveProgress")] = HB(^double { (void)_islet_z; return 1; }); + a[NS("timerDone")] = @YES; + if (![S(gOngoing[NS("timer")], "subtitle") isEqual:NS("Done")]) a[NS("autoExpandUntil")] = [NSDate dateWithTimeIntervalSinceNow:6]; + } else if (isPaused) { + a[NS("subtitle")] = NS("paused"); a[NS("paused")] = @YES; + StrBlock t = HB(^NSString *{ (void)_islet_z; return FmtTime(remain); }); + a[NS("liveCompact")] = t; a[NS("liveBig")] = t; + a[NS("liveProgress")] = HB(^double { (void)_islet_z; return dur > 0 ? 1 - remain / dur : 0; }); + } else { + NSDate *fd = bestDate; + a[NS("subtitle")] = NS("running"); + a[NS("liveCompact")] = HB(^NSString *{ (void)_islet_z; return FmtTime([fd timeIntervalSinceNow]); }); + a[NS("liveBig")] = HB(^NSString *{ (void)_islet_z; return FmtTime([fd timeIntervalSinceNow]); }); + a[NS("liveProgress")] = HB(^double { (void)_islet_z; return dur > 0 ? 1 - [fd timeIntervalSinceNow] / dur : 0; }); + } + SetOngoing(a, NS("timer")); + })); + })); +} + +// The *CurrentTimer calls only know Clock's one classic timer. Every running timer is its own object: change that one. +static void TimerCommand(NSString *c) { + int _islet_z = 0; (void)_islet_z; + id mgr = gMT; Act *a = gOngoing[NS("timer")]; + id timer = a[NS("timerObject")]; + if (!mgr || !timer) return; + BOOL stop = [c isEqual:NS("timer:stop")], done = a[NS("timerDone")] != nil, paused = a[NS("paused")] != nil; + dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), HB(^{ (void)_islet_z; + @try { + if (done) ((id (*)(id, SEL, id))objc_msgSend)(mgr, NSSelectorFromString(NS("dismissTimerWithIdentifier:")), [timer valueForKey:NS("timerID")]); + else { + unsigned long state = stop ? 1 : paused ? 3 : 2; // MTTimerState: stopped, running, paused + id changed = ((id (*)(id, SEL, unsigned long))objc_msgSend)(timer, NSSelectorFromString(NS("timerByUpdatingWithState:")), state); + ((id (*)(id, SEL, id))objc_msgSend)(mgr, NSSelectorFromString(NS("updateTimer:")), changed); + } + } @catch (NSException *e) { LOG("timer command: %@", e); } + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), HB(^{ (void)_islet_z; PollTimers(); })); + })); +} + +static id gCallCenter, gCall; + +static void CallCommand(NSString *c) { + id call = gCall; + if (!call) return; + @try { + if ([c isEqual:NS("call:answer")]) ((void (*)(id, SEL, id))objc_msgSend)(gCallCenter, NSSelectorFromString(NS("answerCall:")), call); + else if ([c isEqual:NS("call:end")]) ((void (*)(id, SEL, id))objc_msgSend)(gCallCenter, NSSelectorFromString(NS("disconnectCall:")), call); + else if ([c isEqual:NS("call:mute")]) { + BOOL muted = ((BOOL (*)(id, SEL))objc_msgSend)(call, NSSelectorFromString(NS("isUplinkMuted"))); + ((void (*)(id, SEL, BOOL))objc_msgSend)(call, NSSelectorFromString(NS("setUplinkMuted:")), !muted); + } + } @catch (NSException *e) { LOG("call command: %@", e); } +} + +static void PollCalls(void) { + int _islet_z = 0; (void)_islet_z; // keeps blocks off the static-global (unsigned isa) path + if (!gCallCenter) { + dlopen("/System/Library/PrivateFrameworks/TelephonyUtilities.framework/TelephonyUtilities", RTLD_NOW); + Class c = NSClassFromString(NS("TUCallCenter")); + if (!c) return; + gCallCenter = ((id (*)(id, SEL))objc_msgSend)(c, NSSelectorFromString(NS("sharedInstance"))); + } + // TUCallStatus: 1 active, 2 held, 3 dialing, 4 ringing, 5/6 ending. Ringing first, then whatever is live. + id call = nil; int status = 0; + @try { + for (id c in ((id (*)(id, SEL))objc_msgSend)(gCallCenter, NSSelectorFromString(NS("currentCalls")))) { + int st = [[c valueForKey:NS("status")] intValue]; + int rank = st == 4 ? 4 : st == 3 ? 3 : st == 1 ? 2 : st == 2 ? 1 : 0; + int curRank = status == 4 ? 4 : status == 3 ? 3 : status == 1 ? 2 : status == 2 ? 1 : 0; + if (rank > curRank) { call = c; status = st; } + } + } @catch (NSException *e) { LOG("calls: %@", e); return; } + gCall = call; + if (!call) { SetOngoing(nil, NS("call")); return; } + UIColor *green = NamedColor(NS("green")); + Act *a = NewAct(NS("call"), NS("call")); + a[NS("bundleID")] = NS("com.apple.mobilephone"); a[NS("priority")] = @4; a[NS("tint")] = green; a[NS("title")] = [call valueForKey:NS("displayName")] ?: NS("Call"); a[NS("icon")] = Symbol(NS("phone.fill"), 16, green); + if (((BOOL (*)(id, SEL))objc_msgSend)(call, NSSelectorFromString(NS("isUplinkMuted")))) a[NS("muted")] = @YES; + if (status == 1 || status == 2) { + a[NS("subtitle")] = status == 2 ? NS("On hold") : NS("active"); + a[NS("liveCompact")] = HB(^NSString *{ (void)_islet_z; return FmtTime([[call valueForKey:NS("callDuration")] doubleValue]); }); + a[NS("liveBig")] = a[NS("liveCompact")]; + } else { + a[NS("subtitle")] = status == 4 ? NS("Incoming call…") : NS("Calling…"); + a[NS("liveCompact")] = HB(^NSString *{ (void)_islet_z; return status == 4 ? NS("Ring") : NS("…"); }); + a[NS("liveBig")] = HB(^NSString *{ (void)_islet_z; return status == 4 ? NS("Incoming call…") : NS("Calling…"); }); + Act *old = gOngoing[NS("call")]; + a[NS("autoExpandUntil")] = [S(old, "subtitle") isEqual:S(a, "subtitle")] && old[NS("autoExpandUntil")] ? old[NS("autoExpandUntil")] : [NSDate dateWithTimeIntervalSinceNow:600]; + } + SetOngoing(a, NS("call")); +} + +static void PollAudioDevice(void); + +static void PollSystem(void) { + if (!PrefBool(NS("enabled"), YES)) return; + UpdateFullscreenVideo(); + if (PrefBool(NS("timer"), YES)) PollTimers(); + if (PrefBool(NS("calls"), YES)) PollCalls(); + PollAudioDevice(); +} + +static void ShowStatusPill(NSString *key, NSString *symbol, NSString *text, UIColor *c, double ttl); + +static void ShowCharging(void) { + int _islet_z = 0; (void)_islet_z; // keeps blocks off the static-global (unsigned isa) path + UIColor *green = NamedColor(NS("green")); + Act *a = NewAct(NS("charge"), NS("charge")); + a[NS("tint")] = green; a[NS("title")] = NS("Charging"); a[NS("ttl")] = @3.4; a[NS("expandFirst")] = @YES; a[NS("icon")] = Symbol(NS("bolt.fill"), 15, green); + StrBlock pct = HB(^NSString *{ (void)_islet_z; + float lv = UIDevice.currentDevice.batteryLevel; + return lv < 0 ? NS("") : [NSString stringWithFormat:NS("%d%%"), (int)round(lv * 100)]; + }); + a[NS("liveCompact")] = pct; a[NS("liveBig")] = pct; + a[NS("liveProgress")] = HB(^double { (void)_islet_z; return UIDevice.currentDevice.batteryLevel; }); + PostTransient(a); +} + +#pragma mark - Accessories and batteries + +static dispatch_queue_t gSQ; + +// One popup style for everything with a battery: icon, name, a line of status, and a ring per part. +static void ShowDevice(NSString *key, NSString *name, NSString *status, NSString *symbol, NSArray *bats, UIColor *tint, double ttl, BOOL critical) { + int _islet_z = 0; (void)_islet_z; + Act *a = NewAct(key, NS("device")); + a[NS("tint")] = tint; a[NS("title")] = name; a[NS("subtitle")] = status; a[NS("ttl")] = @(ttl); a[NS("expandFirst")] = @YES; + a[NS("icon")] = Symbol(symbol, 17, tint); a[NS("bigIcon")] = Symbol(symbol, 40, UIColor.whiteColor); + if (critical) a[NS("critical")] = @YES; + if (bats.count) a[NS("batteries")] = bats; + int lowest = 101; + for (NSDictionary *b in bats) lowest = MIN(lowest, [b[NS("pct")] intValue]); + NSString *t = lowest <= 100 ? [NSString stringWithFormat:NS("%d%%"), lowest] : status; + a[NS("liveCompact")] = HB(^NSString *{ (void)_islet_z; return t; }); + PostTransient(a); +} + +static NSString *DeviceSymbol(NSString *name, long product, BOOL watch) { + if (watch) return NS("applewatch"); + switch (product) { // Apple's Bluetooth product ids + case 8202: case 8223: return NS("airpodsmax"); + case 8206: case 8212: case 8228: return NS("airpodspro"); + case 8211: case 8217: case 8219: return NS("airpods.gen3"); + } + NSString *n = name.lowercaseString; + if ([n containsString:NS("airpods max")]) return NS("airpodsmax"); + if ([n containsString:NS("airpods pro")]) return NS("airpodspro"); + if ([n containsString:NS("airpods")]) return NS("airpods"); + if ([n containsString:NS("beats")]) return NS("beats.headphones"); + if ([n containsString:NS("watch")]) return NS("applewatch"); + if ([n containsString:NS("homepod")] || [n containsString:NS("speaker")]) return NS("hifispeaker.fill"); + if ([n containsString:NS("car")] || [n containsString:NS("sync")]) return NS("car.fill"); + if ([n containsString:NS("keyboard")]) return NS("keyboard.fill"); + if ([n containsString:NS("mouse")] || [n containsString:NS("trackpad")]) return NS("computermouse.fill"); + if ([n containsString:NS("controller")] || [n containsString:NS("xbox")] || [n containsString:NS("dualsense")]) return NS("gamecontroller.fill"); + return NS("headphones"); +} + +// BatteryCenter is what the Batteries widget reads: AirPods show up as one device per part (buds, case) under a group +// name, the Apple Watch as its own device. It only answers inside SpringBoard, so everything here assumes less than +// it could; `isletctl dump` writes what it sees to /var/mobile/islet-batteries.txt. +static id gBC, gBCObserver; +static NSArray *gTestDevices; // the self test feeds dictionaries through the same KVC reads + +static NSArray *BatteryGroups(void) { + if (!gBC && !gTestDevices) return nil; + NSMutableDictionary *groups = [NSMutableDictionary new]; + @try { + for (id d in gTestDevices ?: ((id (*)(id, SEL))objc_msgSend)(gBC, NSSelectorFromString(NS("connectedDevices")))) { + if ([[d valueForKey:NS("isInternal")] boolValue]) continue; + id linked = [d valueForKey:NS("isConnected")]; + if (linked && ![linked boolValue]) continue; + NSString *name = [d valueForKey:NS("name")], *group = [d valueForKey:NS("groupName")]; + if (!name.length) continue; + NSString *gname = group.length ? group : name, *ln = name.lowercaseString; + int pct = [[d valueForKey:NS("percentCharge")] intValue]; + BOOL charging = [[d valueForKey:NS("isCharging")] boolValue]; + long product = [[d valueForKey:NS("productIdentifier")] longValue]; + BOOL isCase = [ln containsString:NS("case")]; + NSString *label = isCase ? NS("Case") : [ln containsString:NS("left")] ? NS("L") : [ln containsString:NS("right")] ? NS("R") : NS(""); + NSMutableDictionary *g = groups[gname]; + if (!g) { + BOOL watch = [gname.lowercaseString containsString:NS("watch")] || [[d valueForKey:NS("accessoryCategory")] intValue] == 3; // 3 confirmed on device + g = [@{NS("name"): gname, NS("low"): @101, NS("items"): [NSMutableArray new], NS("parts"): [NSMutableArray new], NS("charging"): @NO, NS("product"): @(product), NS("watch"): @(watch), + NS("lpm"): [d valueForKey:NS("isLowPowerModeActive")] ?: @NO} mutableCopy]; + groups[gname] = g; + } + NSDictionary *item = @{NS("label"): label, NS("pct"): @(pct), NS("charging"): @(charging)}; + [g[NS("items")] addObject:item]; [g[NS("parts")] addObject:item]; + if (!isCase) { + g[NS("low")] = @(MIN([g[NS("low")] intValue], pct)); + if (charging) g[NS("charging")] = @YES; + } + } + } @catch (NSException *e) { LOG("batteries: %@", e); return nil; } + for (NSMutableDictionary *g in groups.allValues) { + NSMutableArray *items = g[NS("items")]; + // left and right read alike most of the time: one ring is the honest picture then + NSArray *lr = [items filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:NS("label == 'L' OR label == 'R'")]]; + if (lr.count == 2 && abs([lr[0][NS("pct")] intValue] - [lr[1][NS("pct")] intValue]) <= 3) { + NSMutableArray *merged = [NSMutableArray arrayWithObject:@{NS("label"): NS(""), NS("pct"): lr[0][NS("pct")], NS("charging"): lr[0][NS("charging")]}]; + for (NSDictionary *i in items) if (![lr containsObject:i]) [merged addObject:i]; + g[NS("items")] = merged; + } else [items sortUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:NS("label") ascending:YES selector:@selector(compare:)]]]; + if ([g[NS("low")] intValue] > 100 && [g[NS("items")] count]) g[NS("low")] = [g[NS("items")] firstObject][NS("pct")]; + } + return groups.allValues; +} + +static NSMutableDictionary *gDeviceShown; + +// Connected popup. Bluetooth and BatteryCenter both report the same connection, whichever speaks first wins. +static void ShowConnected(NSDictionary *g, NSString *name, long product) { + if (!PrefBool(NS("bluetooth"), YES)) return; + if (!gDeviceShown) gDeviceShown = [NSMutableDictionary new]; + NSDate *last = gDeviceShown[name]; + if (last && last.timeIntervalSinceNow > -30) return; + gDeviceShown[name] = NSDate.date; + long prod = product ?: [g[NS("product")] longValue]; + ShowDevice(NS("bt"), name, NS("Connected"), DeviceSymbol(name, prod, [g[NS("watch")] boolValue]), g[NS("items")], NamedColor(NS("blue")), 3.4, NO); +} + +static NSDictionary *GroupNamed(NSArray *groups, NSString *name) { + for (NSDictionary *g in groups) + if ([g[NS("name")] isEqual:name] || [g[NS("name")] localizedCaseInsensitiveContainsString:name] || [name localizedCaseInsensitiveContainsString:g[NS("name")]]) return g; + return nil; +} + +// Connected headphones, for the bubble left of the island. Main thread. +static void SetAudioDevice(NSDictionary *d) { + if (d == gAudioDevice || [d isEqual:gAudioDevice]) return; + gAudioDevice = d; + UpdateBubble(); +} + +static id gBluetooth; +static NSArray *gTestBluetooth; // the self test feeds dictionaries through the same KVC reads +static NSArray *gBatteryGroups; +static void WriteBatteryReport(void); + +static BOOL IsAudioDevice(id d, NSString *name) { + NSString *n = name.lowercaseString; + if ([n containsString:NS("watch")]) return NO; + return [[d valueForKey:NS("isAppleAudioDevice")] boolValue] || [[d valueForKey:NS("majorClass")] intValue] == 0x400 + || [n containsString:NS("airpods")] || [n containsString:NS("beats")] || [n containsString:NS("buds")] || [n containsString:NS("headphone")]; +} + +// Bluetooth's own connected list decides. Its notifications only say "look now": putting AirPods in their case sends no +// disconnect notification at all, so anything built on those events gets stuck. Polled too, so it can't go stale. +static void PollAudioDevice(void) { + int _islet_z = 0; (void)_islet_z; + static NSMutableDictionary *known; static BOOL primed; + if (!gBluetooth && !gTestBluetooth) return; + if (!known) known = [NSMutableDictionary new]; + NSMutableDictionary *now = [NSMutableDictionary new]; + NSDictionary *audio = nil; + @try { + // Switching Bluetooth off leaves the old list in place. + BOOL powered = gTestBluetooth || ((BOOL (*)(id, SEL))objc_msgSend)(gBluetooth, NSSelectorFromString(NS("enabled"))); + for (id d in powered ? (gTestBluetooth ?: ((id (*)(id, SEL))objc_msgSend)(gBluetooth, NSSelectorFromString(NS("connectedDevices")))) : nil) { + NSString *name = [d valueForKey:NS("name")]; + if (![name isKindOfClass:NSString.class] || !name.length || ![[d valueForKey:NS("connected")] boolValue]) continue; + long product = [[d valueForKey:NS("productId")] longValue]; + int level = [[d valueForKey:NS("batteryLevel")] intValue]; + now[name] = @(product); + if (!audio && IsAudioDevice(d, name)) { + NSDictionary *g = GroupNamed(gBatteryGroups, name); + audio = g ? @{NS("name"): name, NS("product"): @(product), NS("low"): g[NS("low")], NS("items"): g[NS("items")]} + : @{NS("name"): name, NS("product"): @(product), NS("low"): @(level), NS("items"): level > 0 ? @[@{NS("label"): NS(""), NS("pct"): @(level), NS("charging"): @NO}] : @[]}; + } + if (primed && !known[name]) { + // Battery figures arrive a moment after the link does. + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.4 * NSEC_PER_SEC)), gSQ, HB(^{ (void)_islet_z; + NSDictionary *found = GroupNamed(BatteryGroups(), name); + NSDictionary *dev = found ?: @{NS("name"): name, NS("items"): level > 0 ? @[@{NS("label"): NS(""), NS("pct"): @(level), NS("charging"): @NO}] : @[]}; + dispatch_async(dispatch_get_main_queue(), HB(^{ (void)_islet_z; ShowConnected(dev, name, product); })); + })); + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), gSQ, HB(^{ (void)_islet_z; WriteBatteryReport(); })); + } + } + } @catch (NSException *e) { LOG("bluetooth: %@", e); return; } + if (primed && PrefBool(NS("bluetooth"), YES)) + for (NSString *name in known) if (!now[name]) + ShowStatusPill(NS("bt"), DeviceSymbol(name, known[name].longValue, NO), [name stringByAppendingString:NS(" disconnected")], [UIColor colorWithWhite:0.7 alpha:1], 2.4); + known = now; primed = YES; + SetAudioDevice(audio); +} + +static void ShowAudioDevice(void) { + NSDictionary *d = gAudioDevice; + if (!d) return; + NSString *name = d[NS("name")]; + ShowDevice(NS("bt"), name, NS("Connected"), DeviceSymbol(name, [d[NS("product")] longValue], NO), d[NS("items")], NamedColor(NS("blue")), 3.4, NO); +} + +// Each device, and each part of it, has its own alert: left bud, right bud and case can cross on different days. Levels +// are kept per part so a popup fires once on the way down, at the `deviceLowLevel` setting and again at 10. +static void CheckBatteries(void) { // on gSQ + int _islet_z = 0; (void)_islet_z; + static NSMutableDictionary *seen; static NSMutableDictionary *levels; static BOOL primed; + if (!seen) { seen = [NSMutableDictionary new]; levels = [NSMutableDictionary new]; } + NSArray *groups = BatteryGroups(); + if (!groups) return; + int limit = (int)round(PrefNum(NS("deviceLowLevel"), 20)); // sliders store fractions + BOOL alerts = PrefBool(NS("deviceBattery"), YES); + NSMutableSet *present = [NSMutableSet new]; + for (NSDictionary *g in groups) { + NSString *name = g[NS("name")]; + NSDictionary *prev = seen[name]; + [present addObject:name]; + seen[name] = g; + BOOL watch = [g[NS("watch")] boolValue], charging = [g[NS("charging")] boolValue]; + NSString *sym = DeviceSymbol(name, [g[NS("product")] longValue], watch); + for (NSDictionary *part in g[NS("parts")]) { + NSString *label = part[NS("label")], *pk = [NSString stringWithFormat:NS("%@|%@"), name, label]; + int pct = [part[NS("pct")] intValue]; + NSNumber *was = levels[pk]; + levels[pk] = @(pct); + if (!primed || !was || !alerts || [part[NS("charging")] boolValue]) continue; + if ((was.intValue > limit && pct <= limit) || (was.intValue > 10 && pct <= 10)) { + NSString *pn = label.length ? [NSString stringWithFormat:NS("%@ %@"), name, [label isEqual:NS("L")] ? NS("Left") : [label isEqual:NS("R")] ? NS("Right") : label] : name; + NSArray *only = @[@{NS("label"): NS(""), NS("pct"): @(pct), NS("charging"): @NO}]; + dispatch_async(dispatch_get_main_queue(), HB(^{ (void)_islet_z; + ShowDevice(pk, pn, NS("Low Battery"), sym, only, NamedColor(NS("red")), 4.5, pct <= 10); + })); + } + } + if (!primed) continue; + if (!prev) { + if (!watch) dispatch_async(dispatch_get_main_queue(), HB(^{ (void)_islet_z; ShowConnected(g, name, 0); })); + continue; + } + if (!alerts) continue; + int low = [g[NS("low")] intValue], was = [prev[NS("low")] intValue]; + BOOL lpm = [g[NS("lpm")] boolValue]; + if (lpm != [prev[NS("lpm")] boolValue]) dispatch_async(dispatch_get_main_queue(), HB(^{ (void)_islet_z; + ShowDevice(NS("devlpm"), name, lpm ? NS("Low Power Mode On") : NS("Low Power Mode Off"), sym, g[NS("items")], NamedColor(NS("yellow")), 3.0, NO); + })); + if (charging && ![prev[NS("charging")] boolValue]) dispatch_async(dispatch_get_main_queue(), HB(^{ (void)_islet_z; + ShowDevice(NS("devbat"), name, NS("Charging"), sym, g[NS("items")], NamedColor(NS("green")), 3.0, NO); + })); + else if (charging && low >= 100 && was < 100) dispatch_async(dispatch_get_main_queue(), HB(^{ (void)_islet_z; + ShowDevice(NS("devbat"), name, NS("Fully Charged"), sym, g[NS("items")], NamedColor(NS("green")), 3.0, NO); + })); + } + for (NSString *k in seen.allKeys) if (![present containsObject:k]) [seen removeObjectForKey:k]; + primed = YES; + NSArray *fresh = groups; + dispatch_async(dispatch_get_main_queue(), HB(^{ (void)_islet_z; gBatteryGroups = fresh; PollAudioDevice(); })); +} + +static void bat_changed(id self, SEL _cmd, id devices) { + int _islet_z = 0; (void)_islet_z; + dispatch_async(gSQ, HB(^{ (void)_islet_z; CheckBatteries(); })); +} + +static void SetupDeviceBatteries(void) { + int _islet_z = 0; (void)_islet_z; + dlopen("/System/Library/PrivateFrameworks/BatteryCenter.framework/BatteryCenter", RTLD_NOW); + Class bc = NSClassFromString(NS("BCBatteryDeviceController")); + if (!bc) { LOG("no BatteryCenter"); return; } + @try { + gBC = [[bc alloc] init]; + Class oc = MakeClass("IsletBatteryObserver", NSObject.class, HB(^(Class c) { (void)_islet_z; + class_addMethod(c, NSSelectorFromString(NS("connectedDevicesDidChange:")), (IMP)bat_changed, "v@:@"); + Protocol *p = objc_getProtocol("BCBatteryDeviceObserving"); if (p) class_addProtocol(c, p); + })); + gBCObserver = [oc new]; + ((void (*)(id, SEL, id, id))objc_msgSend)(gBC, NSSelectorFromString(NS("addBatteryDeviceObserver:queue:")), gBCObserver, dispatch_get_main_queue()); + } @catch (NSException *e) { LOG("battery observer: %@", e); } +} + +static void ShowPhoneBattery(NSString *status, NSString *symbol, int pct, UIColor *tint, BOOL critical) { + NSArray *bats = @[@{NS("label"): NS(""), NS("pct"): @(pct), NS("charging"): @NO}]; + ShowDevice(NS("phonebat"), UIDevice.currentDevice.localizedModel ?: NS("iPhone"), status, symbol, bats, tint, 4.0, critical); +} + +// iPhone battery: popups at 20, 10 and 5 percent on the way down, and one when it finishes charging. +static void BatteryLevelChanged(void) { + static int last = -1; + UIDevice *d = UIDevice.currentDevice; + int pct = (int)round(d.batteryLevel * 100); + BOOL plugged = d.batteryState == UIDeviceBatteryStateCharging || d.batteryState == UIDeviceBatteryStateFull; + if (last >= 0 && PrefBool(NS("lowBattery"), YES)) { + if (!plugged && ((last > 20 && pct <= 20) || (last > 10 && pct <= 10) || (last > 5 && pct <= 5))) + ShowPhoneBattery(NS("Low Battery"), NS("battery.25percent"), pct, NamedColor(NS("red")), pct <= 10); + else if (plugged && last < 100 && pct >= 100) + ShowPhoneBattery(NS("Fully Charged"), NS("battery.100.bolt"), pct, NamedColor(NS("green")), NO); + } + last = pct; +} + +static void ShowRinger(BOOL ring) { + int _islet_z = 0; (void)_islet_z; // keeps blocks off the static-global (unsigned isa) path + UIColor *c = ring ? UIColor.whiteColor : NamedColor(NS("red")); + Act *a = NewAct(NS("ringer"), NS("ringer")); + a[NS("tint")] = c; a[NS("ttl")] = @2.2; a[NS("icon")] = Symbol(NS("bell.fill"), 18, c); + if (!ring) a[NS("silent")] = @YES; + NSString *t = ring ? NS("Ring") : NS("Silent"); + a[NS("liveCompact")] = HB(^NSString *{ (void)_islet_z; return t; }); + PostTransient(a); +} + +static void SetupBattery(void) { + int _islet_z = 0; (void)_islet_z; // keeps blocks off the static-global (unsigned isa) path + UIDevice.currentDevice.batteryMonitoringEnabled = YES; + __block UIDeviceBatteryState last = UIDevice.currentDevice.batteryState; + [NSNotificationCenter.defaultCenter addObserverForName:UIDeviceBatteryStateDidChangeNotification object:nil queue:NSOperationQueue.mainQueue usingBlock:HB(^(NSNotification *n) { (void)_islet_z; + UIDeviceBatteryState s = UIDevice.currentDevice.batteryState; + BOOL plugged = s == UIDeviceBatteryStateCharging || s == UIDeviceBatteryStateFull; + BOOL was = last == UIDeviceBatteryStateCharging || last == UIDeviceBatteryStateFull; + last = s; + if (plugged && !was && PrefBool(NS("charging"), YES)) ShowCharging(); + })]; + [NSNotificationCenter.defaultCenter addObserverForName:UIDeviceBatteryLevelDidChangeNotification object:nil queue:NSOperationQueue.mainQueue usingBlock:HB(^(NSNotification *n) { (void)_islet_z; BatteryLevelChanged(); })]; + BatteryLevelChanged(); + [NSNotificationCenter.defaultCenter addObserverForName:NSProcessInfoPowerStateDidChangeNotification object:nil queue:NSOperationQueue.mainQueue usingBlock:HB(^(NSNotification *n) { (void)_islet_z; + if (!PrefBool(NS("lowPowerMode"), YES)) return; + BOOL on = NSProcessInfo.processInfo.isLowPowerModeEnabled; + ShowStatusPill(NS("lpm"), on ? NS("battery.50percent") : NS("battery.100percent"), on ? NS("Low Power On") : NS("Low Power Off"), on ? NamedColor(NS("yellow")) : [UIColor colorWithWhite:0.75 alpha:1], 2.2); + })]; +} + +static void SetupRinger(void) { + int _islet_z = 0; (void)_islet_z; // keeps blocks off the static-global (unsigned isa) path + static int token; static int lastState = -1; + notify_register_dispatch("com.apple.springboard.ringerstate", &token, dispatch_get_main_queue(), HB(^(int t) { (void)_islet_z; + uint64_t st = 0; notify_get_state(t, &st); + if (lastState >= 0 && lastState != (int)st && PrefBool(NS("ringer"), YES)) ShowRinger(st != 0); + lastState = (int)st; + })); + uint64_t st = 0; notify_get_state(token, &st); lastState = (int)st; +} + +#pragma mark - Bluetooth + +static void ScheduleRadioCheck(void); + +static void SetupBluetooth(void) { + int _islet_z = 0; (void)_islet_z; + dlopen("/System/Library/PrivateFrameworks/BluetoothManager.framework/BluetoothManager", RTLD_NOW); + Class bc = NSClassFromString(NS("BluetoothManager")); + if (!bc) { LOG("no BluetoothManager"); return; } + gBluetooth = ((id (*)(id, SEL))objc_msgSend)(bc, NSSelectorFromString(NS("sharedInstance"))); + for (NSString *nn in @[NS("BluetoothDeviceConnectSuccessNotification"), NS("BluetoothDeviceDisconnectSuccessNotification"), NS("BluetoothConnectionStatusChangedNotification"), + NS("BluetoothPowerChangedNotification"), NS("BluetoothAvailabilityChangedNotification"), NS("AVAudioSessionRouteChangeNotification")]) + [NSNotificationCenter.defaultCenter addObserverForName:nn object:nil queue:NSOperationQueue.mainQueue usingBlock:HB(^(NSNotification *n) { (void)_islet_z; + PollAudioDevice(); + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.4 * NSEC_PER_SEC)), dispatch_get_main_queue(), HB(^{ (void)_islet_z; PollAudioDevice(); })); + ScheduleRadioCheck(); + })]; +} + +#pragma mark - Calendar and reminders + +static NSString *FmtUntil(NSDate *d) { + int mins = (int)ceil(d.timeIntervalSinceNow / 60); + return mins <= 0 ? NS("Now") : mins < 60 ? [NSString stringWithFormat:NS("in %dm"), mins] : [NSString stringWithFormat:NS("in %dh %dm"), mins / 60, mins % 60]; +} + +// Sits at the bottom of the priority order: only on screen when nothing else is, starting `calendarLead` minutes out. +static void ShowUpcoming(NSString *key, NSString *title, NSString *sub, NSDate *when, NSString *symbol, UIColor *tint, NSString *bid) { + int _islet_z = 0; (void)_islet_z; + if (!title) { SetOngoing(nil, key); return; } + Act *a = NewAct(key, NS("event")); + a[NS("priority")] = @0; a[NS("tint")] = tint; a[NS("title")] = title; a[NS("subtitle")] = sub ?: NS(""); + a[NS("icon")] = Symbol(symbol, 16, tint); a[NS("bundleID")] = bid; + StrBlock t = HB(^NSString *{ (void)_islet_z; return FmtUntil(when); }); + a[NS("liveCompact")] = t; a[NS("liveBig")] = t; + if (!gOngoing[key]) a[NS("autoExpandUntil")] = [NSDate dateWithTimeIntervalSinceNow:3.5]; + else if (gOngoing[key][NS("autoExpandUntil")]) a[NS("autoExpandUntil")] = gOngoing[key][NS("autoExpandUntil")]; + SetOngoing(a, key); +} + +static void PollCalendar(void) { // on gSQ: EventKit answers synchronously over XPC + int _islet_z = 0; (void)_islet_z; + if (!PrefBool(NS("enabled"), YES)) return; + static id store; + BOOL events = PrefBool(NS("calendar"), YES), reminders = PrefBool(NS("reminders"), YES); + if (!store && (events || reminders)) { + dlopen("/System/Library/Frameworks/EventKit.framework/EventKit", RTLD_NOW); + Class c = NSClassFromString(NS("EKEventStore")); + if (c) store = [[c alloc] init]; + } + if (!store) return; + NSDate *now = NSDate.date, *until = [now dateByAddingTimeInterval:PrefNum(NS("calendarLead"), 15) * 60]; + NSDate *from = [now dateByAddingTimeInterval:-120]; + @try { + NSString *title = nil, *where = nil; NSDate *when = nil; + if (events) { + id pred = ((id (*)(id, SEL, id, id, id))objc_msgSend)(store, NSSelectorFromString(NS("predicateForEventsWithStartDate:endDate:calendars:")), from, until, nil); + for (id e in ((id (*)(id, SEL, id))objc_msgSend)(store, NSSelectorFromString(NS("eventsMatchingPredicate:")), pred)) { + if ([[e valueForKey:NS("isAllDay")] boolValue]) continue; + NSDate *st = [e valueForKey:NS("startDate")]; + if (st && (!when || [st compare:when] == NSOrderedAscending)) { when = st; title = [e valueForKey:NS("title")]; where = [e valueForKey:NS("location")]; } + } + } + NSDate *fw = when; NSString *ft = title, *loc = where; + dispatch_async(dispatch_get_main_queue(), HB(^{ (void)_islet_z; + ShowUpcoming(NS("event"), ft, loc, fw, NS("calendar"), NamedColor(NS("red")), NS("com.apple.mobilecal")); + })); + if (reminders) { + id pred = ((id (*)(id, SEL, id, id, id))objc_msgSend)(store, NSSelectorFromString(NS("predicateForIncompleteRemindersWithDueDateStarting:ending:calendars:")), from, until, nil); + ((id (*)(id, SEL, id, id))objc_msgSend)(store, NSSelectorFromString(NS("fetchRemindersMatchingPredicate:completion:")), pred, HB(^(NSArray *found) { (void)_islet_z; + NSString *rt = nil; NSDate *rd = nil; + @try { + for (id r in found) { + NSDate *due = [[r valueForKey:NS("dueDateComponents")] valueForKey:NS("date")]; + if (due && (!rd || [due compare:rd] == NSOrderedAscending)) { rd = due; rt = [r valueForKey:NS("title")]; } + } + } @catch (NSException *e) { LOG("reminders: %@", e); } + dispatch_async(dispatch_get_main_queue(), HB(^{ (void)_islet_z; + ShowUpcoming(NS("reminder"), rt, NS("Reminder"), rd, NS("checklist"), NamedColor(NS("orange")), NS("com.apple.reminders")); + })); + })); + } else dispatch_async(dispatch_get_main_queue(), HB(^{ (void)_islet_z; SetOngoing(nil, NS("reminder")); })); + } @catch (NSException *e) { LOG("calendar: %@", e); } +} + +#pragma mark - Screen recording + +static NSString *ActivityID(const char *tail) { return [NS("com.apple.systemstatus.background-activity.") stringByAppendingString:NS(tail)]; } + +static void ShowRecording(void) { + int _islet_z = 0; (void)_islet_z; + UIColor *red = NamedColor(NS("red")); + Act *a = NewAct(NS("record"), NS("record")); + a[NS("priority")] = @1; a[NS("tint")] = red; a[NS("title")] = NS("Screen Recording"); a[NS("subtitle")] = NS("recording"); + a[NS("icon")] = Symbol(NS("circle.fill"), 12, red); a[NS("activityID")] = ActivityID("ScreenReplayRecording"); + NSDate *start = NSDate.date; + StrBlock t = HB(^NSString *{ (void)_islet_z; return FmtTime(-[start timeIntervalSinceNow]); }); + a[NS("liveCompact")] = t; a[NS("liveBig")] = t; + SetOngoing(a, NS("record")); +} + +static NSSet *gActivities; + +// isCaptured means the screen is being copied somewhere, recording or mirroring alike, and the status bar only names one +// activity at a time, so which of the two it is gets decided once, from whichever name is seen, and held until capture ends. +// A passing popup or a status update can't turn one into the other. +static int gCaptureKind; // 0 not known yet, 1 recording, 2 mirroring or sharing +static int gTestCaptured = -1; +static BOOL ScreenCaptured(void) { return gTestCaptured >= 0 ? gTestCaptured : UIScreen.mainScreen.isCaptured; } + +static void UpdateRecording(void) { + int _islet_z = 0; (void)_islet_z; + BOOL captured = ScreenCaptured(); + if (!captured) gCaptureKind = 0; + else if (!gCaptureKind && UIScreen.mainScreen.mirroredScreen) gCaptureKind = 2; + else if ([gActivities containsObject:ActivityID("ScreenSharing")]) gCaptureKind = 2; + else if (!gCaptureKind && [gActivities containsObject:ActivityID("ScreenReplayRecording")]) gCaptureKind = 1; + if (!captured || gCaptureKind == 2 || !PrefBool(NS("recording"), YES) || !PrefBool(NS("enabled"), YES)) { SetOngoing(nil, NS("record")); return; } + if (gCaptureKind == 0) { // nothing named it yet: give the status bar a moment before calling it a recording + static int waits; + int mine = ++waits; + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), HB(^{ (void)_islet_z; + if (mine != waits || !ScreenCaptured() || gCaptureKind) return; + gCaptureKind = 1; UpdateRecording(); + })); + return; + } + if (!gOngoing[NS("record")]) ShowRecording(); +} + +// Everything else that used to live in a coloured clock pill. Each card's button is the stock tap on that pill. +static void ShowSystemActivity(NSString *key, NSString *title, NSString *symbol, UIColor *tint, NSString *activity) { + int _islet_z = 0; (void)_islet_z; + Act *a = NewAct(key, NS("record")); + a[NS("priority")] = @0; a[NS("tint")] = tint; a[NS("title")] = title; a[NS("subtitle")] = NS("active"); + a[NS("icon")] = Symbol(symbol, 16, tint); a[NS("activityID")] = activity; a[NS("actionSymbol")] = NS("chevron.right"); + StrBlock t = HB(^NSString *{ (void)_islet_z; return NS("On"); }); + a[NS("liveCompact")] = t; a[NS("liveBig")] = t; + SetOngoing(a, key); +} + +static BOOL IsletTakesActivity(NSString *ident) { + if (![ident hasPrefix:NS("com.apple.systemstatus.background-activity.")] || !PrefBool(NS("enabled"), YES) || !PrefBool(NS("hideStatusPills"), YES)) return NO; + if (IsLandscape() || gFullscreenVideo) return NO; // stepped aside: the stock pill does the job + if ([ident hasSuffix:NS(".ScreenReplayRecording")]) return PrefBool(NS("recording"), YES); + if ([ident hasSuffix:NS(".InCall")] || [ident hasSuffix:NS(".CallRinging")]) return PrefBool(NS("calls"), YES); + if ([ident hasSuffix:NS(".Tethering")] || [ident hasSuffix:NS(".ScreenSharing")] || [ident hasSuffix:NS(".Recording")] || [ident containsString:NS(".WebRTC")]) + return PrefBool(NS("systemActivities"), YES); + return NO; +} + +static void UpdateActivities(NSSet *ids) { + gActivities = ids; + BOOL on = PrefBool(NS("systemActivities"), YES) && PrefBool(NS("enabled"), YES); + NSString *tether = ActivityID("Tethering"), *mirror = ActivityID("ScreenSharing"), *mic = nil; + for (NSString *i in ids) if ([i hasSuffix:NS(".Recording")] || [i containsString:NS(".WebRTC")]) mic = i; + if (on && [ids containsObject:tether]) ShowSystemActivity(NS("hotspot"), NS("Personal Hotspot"), NS("personalhotspot"), NamedColor(NS("green")), tether); + else SetOngoing(nil, NS("hotspot")); + if ([ids containsObject:mirror]) gCaptureKind = 2; + if (on && gCaptureKind == 2) { + BOOL external = UIScreen.mainScreen.mirroredScreen != nil || UIScreen.screens.count > 1; + ShowSystemActivity(NS("mirror"), external ? NS("Screen Mirroring") : NS("Screen Sharing"), NS("rectangle.on.rectangle"), NamedColor(NS("blue")), mirror); + } else SetOngoing(nil, NS("mirror")); + if (on && mic) ShowSystemActivity(NS("mic"), NS("Microphone"), NS("mic.fill"), NamedColor(NS("orange")), mic); + else SetOngoing(nil, NS("mic")); + UpdateRecording(); + if (gCaptureKind != 2) SetOngoing(nil, NS("mirror")); // capture ended while no status update said so +} + +static void TapStockActivity(NSString *ident) { + id app = UIApplication.sharedApplication; + SEL sel = NSSelectorFromString(NS("handleStatusBarTapForBackgroundActivityWithIdentifier:")); + @try { if ([app respondsToSelector:sel]) ((BOOL (*)(id, SEL, id))objc_msgSend)(app, sel, ident); } + @catch (NSException *e) { LOG("activity tap: %@", e); } +} + +// SpringBoard's own feed of what's running, where it answers. Outside SpringBoard it delivers nothing, and the status bar +// hook below keeps gActivities honest from what it sees. +static id gActivityDomain; +static BOOL gActivityDomainHasData; +static void SetupActivities(void) { + int _islet_z = 0; (void)_islet_z; + dlopen("/System/Library/PrivateFrameworks/SystemStatus.framework/SystemStatus", RTLD_NOW); + Class c = NSClassFromString(NS("STBackgroundActivitiesStatusDomain")); + if (!c) return; + @try { + gActivityDomain = [[c alloc] init]; + ((void (*)(id, SEL, id))objc_msgSend)(gActivityDomain, NSSelectorFromString(NS("observeData:")), HB(^(id data) { (void)_islet_z; + id active = nil; + @try { active = [data valueForKey:NS("activeBackgroundActivities")]; } @catch (NSException *e) { return; } + if (!active) return; + gActivityDomainHasData = YES; + NSMutableSet *ids = [NSMutableSet new]; + for (id i in active) [ids addObject:i]; + dispatch_async(dispatch_get_main_queue(), HB(^{ (void)_islet_z; UpdateActivities(ids); })); + })); + } @catch (NSException *e) { LOG("activity domain: %@", e); } +} + +static void SetupRecording(void) { + int _islet_z = 0; (void)_islet_z; + [NSNotificationCenter.defaultCenter addObserverForName:UIScreenCapturedDidChangeNotification object:nil queue:NSOperationQueue.mainQueue usingBlock:HB(^(NSNotification *n) { (void)_islet_z; UpdateActivities(gActivities); })]; + SetupActivities(); + UpdateRecording(); +} + +#pragma mark - System state: flashlight, airplane, Focus, network + +static dispatch_source_t gSentinel; +static nw_path_monitor_t gNetMon; +static id gAirplane, gWiFi, gFlash, gFlashCtl, gRotation, gAirDrop, gAirDropObserver, gFocusState, gFocusManager; +static Boolean (*CellDataEnabled)(void); +static double gNetworkQuietUntil; +static double gTorchLevel; + +static void ShowStatusPill(NSString *key, NSString *symbol, NSString *text, UIColor *c, double ttl) { + int _islet_z = 0; (void)_islet_z; + Act *a = NewAct(key, NS("status")); + a[NS("tint")] = c; a[NS("ttl")] = @(ttl); a[NS("icon")] = Symbol(symbol, 16, c); + a[NS("liveCompact")] = HB(^NSString *{ (void)_islet_z; return text; }); + PostTransient(a); +} + +static void ShowAirplane(BOOL on) { + ShowStatusPill(NS("airplane"), NS("airplane"), on ? NS("Airplane On") : NS("Airplane Off"), on ? NamedColor(NS("orange")) : [UIColor colorWithWhite:0.75 alpha:1], 2.2); +} + +static void ShowFocus(BOOL on, NSString *name, NSString *symbol, NSString *tintName) { + UIColor *c = on ? NamedColor(tintName) : [UIColor colorWithWhite:0.75 alpha:1]; + ShowStatusPill(NS("focus"), symbol.length ? symbol : NS("moon.fill"), on ? (name.length ? name : NS("Focus")) : (name.length ? [name stringByAppendingString:NS(" Off")] : NS("Focus Off")), c, 2.4); +} + +static void ShowRadio(NSString *key, NSString *symbol, NSString *text, BOOL on, UIColor *tint) { + ShowStatusPill(key, symbol, text, on ? tint : [UIColor colorWithWhite:0.75 alpha:1], 2.0); +} + +// SpringBoard's own Do Not Disturb monitor, then the Focus manager behind Control Center. DNDStateService never answers +// here, and the stock banner only appears for some changes, so neither can be relied on by itself. +static void PollFocus(void) { // on gSQ + int _islet_z = 0; (void)_islet_z; + static NSString *lastKey, *lastName; static BOOL primed; + if (!PrefBool(NS("focus"), YES)) return; + id state = nil, activity = nil, mode = nil; + @try { + state = gFocusState ? [gFocusState valueForKey:NS("state")] : nil; + activity = gFocusManager ? [gFocusManager valueForKey:NS("activeActivity")] : nil; + } @catch (NSException *e) { return; } + if (!state && !gFocusManager) return; + // The state is the live answer. The manager catches up later, so it only ever fills in the name, never on or off. + BOOL on = state ? [[state valueForKey:NS("isActive")] boolValue] : activity != nil; + if (on) @try { mode = [[state valueForKey:NS("activeModeConfiguration")] valueForKey:NS("mode")]; } @catch (NSException *e) {} + NSString *name = [mode valueForKey:NS("name")] ?: [activity valueForKey:NS("activityDisplayName")]; + NSString *sym = [mode valueForKey:NS("symbolImageName")] ?: [activity valueForKey:NS("activitySymbolImageName")]; + NSString *tint = [mode valueForKey:NS("tintColorName")] ?: [activity valueForKey:NS("activityColorName")]; + NSString *key = on ? (name ?: NS("on")) : NS(""); + if (primed && ![key isEqual:lastKey]) { + NSString *shown = on ? name : lastName, *symbol = sym; + dispatch_async(dispatch_get_main_queue(), HB(^{ (void)_islet_z; ShowFocus(on, shown, symbol, tint); })); + } + if (on && name) lastName = name; + lastKey = key; primed = YES; +} + +static void ShowAirDrop(int mode) { // 0 off, 1 contacts, 2 everyone + ShowStatusPill(NS("airdrop"), [UIImage systemImageNamed:NS("airdrop")] ? NS("airdrop") : NS("dot.radiowaves.up.forward"), mode == 2 ? NS("AirDrop: Everyone") : mode == 1 ? NS("AirDrop: Contacts") : NS("AirDrop Off"), mode ? NamedColor(NS("blue")) : [UIColor colorWithWhite:0.75 alpha:1], 2.2); +} + +static void ShowNetwork(BOOL wifi) { + if (CACurrentMediaTime() < gNetworkQuietUntil) return; // a toggle just said it + NSString *name = nil; + Class wm = NSClassFromString(NS("SBWiFiManager")); + if (wifi && wm) @try { name = [((id (*)(id, SEL))objc_msgSend)(wm, NSSelectorFromString(NS("sharedInstance"))) valueForKey:NS("currentNetworkName")]; } @catch (NSException *e) {} + ShowStatusPill(NS("net"), wifi ? NS("wifi") : NS("antenna.radiowaves.left.and.right"), wifi ? (name.length ? name : NS("Wi\u2011Fi")) : NS("Cellular"), wifi ? NamedColor(NS("blue")) : NamedColor(NS("green")), 2.0); +} + +static void SetFlashlight(double level) { + int _islet_z = 0; (void)_islet_z; + gTorchLevel = level; + if (level < 0.01) { SetOngoing(nil, NS("flash")); return; } + if (gOngoing[NS("flash")]) return; // live blocks read gTorchLevel + UIColor *y = NamedColor(NS("yellow")); + Act *a = NewAct(NS("flash"), NS("flash")); + a[NS("priority")] = @3; a[NS("tint")] = y; a[NS("title")] = NS("Flashlight"); a[NS("subtitle")] = NS("on"); + a[NS("icon")] = Symbol(NS("flashlight.on.fill"), 16, y); + StrBlock t = HB(^NSString *{ (void)_islet_z; return [NSString stringWithFormat:NS("%d%%"), (int)round(gTorchLevel * 100)]; }); + a[NS("liveCompact")] = t; a[NS("liveBig")] = t; + a[NS("liveProgress")] = HB(^double { (void)_islet_z; return gTorchLevel; }); + if (PrefBool(NS("flashlightPeek"), YES)) a[NS("autoExpandUntil")] = [NSDate dateWithTimeIntervalSinceNow:3.2]; + SetOngoing(a, NS("flash")); +} + +// SBUIFlashlightController is the object Control Center itself drives (levels 0-4), so it can always turn off a torch +// that CC turned on. A private AVFlashlight can't: each client owns its own power state, and turnPowerOff on a client +// that never powered on does nothing. Plain AVFlashlight stays as the fallback, and has to power on before it goes off. +static void TorchCommand(NSString *c) { + double v = [c isEqual:NS("torchoff")] ? 0 : [[c substringFromIndex:6] doubleValue]; + @try { + if (gFlashCtl) { + ((void (*)(id, SEL, unsigned long))objc_msgSend)(gFlashCtl, NSSelectorFromString(NS("setLevel:")), (unsigned long)ceil(v * 4)); + if (v <= 0) ((void (*)(id, SEL, id))objc_msgSend)(gFlashCtl, NSSelectorFromString(NS("turnFlashlightOffForReason:")), NS("Islet")); + } else if (gFlash) { + ((BOOL (*)(id, SEL, id *))objc_msgSend)(gFlash, NSSelectorFromString(NS("turnPowerOnWithError:")), NULL); + ((BOOL (*)(id, SEL, float, id *))objc_msgSend)(gFlash, NSSelectorFromString(NS("setFlashlightLevel:withError:")), (float)v, NULL); + if (v <= 0) ((void (*)(id, SEL))objc_msgSend)(gFlash, NSSelectorFromString(NS("turnPowerOff"))); + } + } @catch (NSException *e) { LOG("torch: %@", e); } +} + +// One background timer samples flashlight, airplane mode and Focus (XPC reads, so never on the main thread); +// Network.framework tells us when Wi-Fi and cellular swap. +// Airplane mode, Wi-Fi, cellular data, Bluetooth. Hooks and notifications call this the moment one moves. On gSQ, and +// nothing slow may share that queue: one blocked call here is what used to make every popup late. +static void CheckRadios(void) { + int _islet_z = 0; (void)_islet_z; + if (!PrefBool(NS("enabled"), YES)) return; + static int airplane = -1, wifiOn = -1, dataOn = -1, btOn = -1; static double quietUntil; + @try { + int ap = gAirplane ? ((BOOL (*)(id, SEL))objc_msgSend)(gAirplane, NSSelectorFromString(NS("isInAirplaneMode"))) : -1; + if (airplane >= 0 && ap != airplane) { + quietUntil = CACurrentMediaTime() + 6; // the radios drop with it: one popup is enough + if (PrefBool(NS("airplane"), YES)) dispatch_async(dispatch_get_main_queue(), HB(^{ (void)_islet_z; ShowAirplane(ap); })); + } + airplane = ap; + int wifi = gWiFi ? ((BOOL (*)(id, SEL))objc_msgSend)(gWiFi, NSSelectorFromString(NS("wiFiEnabled"))) : -1; + int data = CellDataEnabled ? CellDataEnabled() : -1; + int bt = gBluetooth ? ((BOOL (*)(id, SEL))objc_msgSend)(gBluetooth, NSSelectorFromString(NS("enabled"))) : -1; + BOOL say = CACurrentMediaTime() >= quietUntil && PrefBool(NS("network"), YES); + if (wifiOn >= 0 && wifi != wifiOn && say) { + gNetworkQuietUntil = CACurrentMediaTime() + 4; + dispatch_async(dispatch_get_main_queue(), HB(^{ (void)_islet_z; ShowRadio(NS("wifi"), wifi ? NS("wifi") : NS("wifi.slash"), wifi ? NS("Wi\u2011Fi On") : NS("Wi\u2011Fi Off"), wifi, NamedColor(NS("blue"))); })); + } + if (dataOn >= 0 && data != dataOn && say) { + gNetworkQuietUntil = CACurrentMediaTime() + 4; + dispatch_async(dispatch_get_main_queue(), HB(^{ (void)_islet_z; ShowRadio(NS("data"), NS("antenna.radiowaves.left.and.right"), data ? NS("Cellular Data On") : NS("Cellular Data Off"), data, NamedColor(NS("green"))); })); + } + if (btOn >= 0 && bt != btOn && say) + dispatch_async(dispatch_get_main_queue(), HB(^{ (void)_islet_z; ShowRadio(NS("btpower"), NS("wave.3.right"), bt ? NS("Bluetooth On") : NS("Bluetooth Off"), bt, NamedColor(NS("blue"))); })); + wifiOn = wifi; dataOn = data; btOn = bt; + } @catch (NSException *e) { LOG("radios: %@", e); } +} + +// Status bar and radio callbacks come in bursts: the first asks for a check, the rest of the burst joins it. +static void ScheduleRadioCheck(void) { + int _islet_z = 0; (void)_islet_z; + static volatile int pending; + if (!gSQ || __sync_lock_test_and_set(&pending, 1)) return; + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.12 * NSEC_PER_SEC)), gSQ, HB(^{ (void)_islet_z; __sync_lock_release(&pending); CheckRadios(); })); +} + +static void CheckFlashlight(void) { + int _islet_z = 0; (void)_islet_z; + static float seen = -1; + if ((!gFlashCtl && !gFlash) || !PrefBool(NS("flashlight"), YES)) return; + @try { + float lv = gFlashCtl ? ((unsigned long (*)(id, SEL))objc_msgSend)(gFlashCtl, NSSelectorFromString(NS("level"))) / 4.0f + : ((float (*)(id, SEL))objc_msgSend)(gFlash, NSSelectorFromString(NS("flashlightLevel"))); + if (fabsf(lv - seen) > 0.01) { seen = lv; dispatch_async(dispatch_get_main_queue(), HB(^{ (void)_islet_z; SetFlashlight(lv); })); } + } @catch (NSException *e) { LOG("flashlight: %@", e); } +} + +static void CheckRotation(void) { + int _islet_z = 0; (void)_islet_z; + static int rotation = -1; + if (!gRotation) return; + int r = ((BOOL (*)(id, SEL))objc_msgSend)(gRotation, NSSelectorFromString(NS("isUserLocked"))); + if (rotation >= 0 && r != rotation && PrefBool(NS("rotationLock"), YES)) dispatch_async(dispatch_get_main_queue(), HB(^{ (void)_islet_z; + ShowStatusPill(NS("rotation"), r ? NS("lock.rotation") : NS("lock.open.rotation"), r ? NS("Rotation Locked") : NS("Rotation Unlocked"), r ? NamedColor(NS("red")) : UIColor.whiteColor, 2.0); + })); + rotation = r; +} + +static void CheckAirDrop(void) { + int _islet_z = 0; (void)_islet_z; + static int airdrop = -1; + if (!gAirDrop) return; + int m = (int)((long (*)(id, SEL))objc_msgSend)(gAirDrop, NSSelectorFromString(NS("discoverableMode"))); + if (airdrop >= 0 && m != airdrop && PrefBool(NS("airdrop"), YES)) dispatch_async(dispatch_get_main_queue(), HB(^{ (void)_islet_z; ShowAirDrop(m); })); + airdrop = m; +} + +static void airdrop_changed(id self, SEL _cmd, id controller) { + int _islet_z = 0; (void)_islet_z; + dispatch_async(gSQ, HB(^{ (void)_islet_z; CheckAirDrop(); })); +} + +static void StartSentinel(void) { + int _islet_z = 0; (void)_islet_z; + Class fc = NSClassFromString(NS("AVFlashlight")); + id (*shared)(id, SEL) = (id (*)(id, SEL))objc_msgSend; + SEL si = NSSelectorFromString(NS("sharedInstance")); + Class ac = NSClassFromString(NS("SBAirplaneModeController")), wc = NSClassFromString(NS("SBWiFiManager")), sc = NSClassFromString(NS("SBDoNotDisturbStateMonitor")); + if (ac) gAirplane = shared(ac, si); + if (wc) gWiFi = shared(wc, si); + if (sc) gFocusState = shared(sc, si); + dlopen("/System/Library/PrivateFrameworks/FocusCore.framework/FocusCore", RTLD_NOW); + Class fm = NSClassFromString(NS("FCActivityManager")); + if (fm) gFocusManager = shared(fm, NSSelectorFromString(NS("sharedActivityManager"))); + void *ct = dlopen("/System/Library/Frameworks/CoreTelephony.framework/CoreTelephony", RTLD_NOW); + if (ct) CellDataEnabled = dlsym(ct, "CTCellularDataPlanGetIsEnabled"); + if (fc) gFlash = [[fc alloc] init]; + Class fcc = NSClassFromString(NS("SBUIFlashlightController")); + if (fcc) gFlashCtl = ((id (*)(id, SEL))objc_msgSend)(fcc, NSSelectorFromString(NS("sharedInstance"))); + Class olm = NSClassFromString(NS("SBOrientationLockManager")); + if (olm) gRotation = ((id (*)(id, SEL))objc_msgSend)(olm, NSSelectorFromString(NS("sharedInstance"))); + Class adc = NSClassFromString(NS("SFAirDropDiscoveryController")); + if (adc) gAirDrop = [[adc alloc] init]; + + Class adc2 = gAirDrop ? [gAirDrop class] : nil; + if (adc2) { + @try { + Class oc = MakeClass("IsletAirDropObserver", NSObject.class, HB(^(Class c) { (void)_islet_z; + class_addMethod(c, NSSelectorFromString(NS("discoveryControllerSettingsDidChange:")), (IMP)airdrop_changed, "v@:@"); + })); + gAirDropObserver = [oc new]; + ((void (*)(id, SEL, id))objc_msgSend)(gAirDrop, NSSelectorFromString(NS("setDelegate:")), gAirDropObserver); + } @catch (NSException *e) { LOG("airdrop observer: %@", e); } + } + + // Everything above arrives as an event. This only catches what an event might miss, so it's slow and idles with the screen. + gSentinel = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, gSQ); + dispatch_source_set_timer(gSentinel, dispatch_time(DISPATCH_TIME_NOW, 2 * NSEC_PER_SEC), 5 * NSEC_PER_SEC, 2 * NSEC_PER_SEC); + dispatch_source_set_event_handler(gSentinel, HB(^{ (void)_islet_z; + static int tick; + tick++; + if ((tick == 1 || tick % 12 == 0) && PrefBool(NS("enabled"), YES)) { // about once a minute + CheckBatteries(); + dispatch_async(gSlowQ, HB(^{ (void)_islet_z; PollCalendar(); })); + } + if (gScreenOff || !PrefBool(NS("enabled"), YES)) return; + CheckRadios(); CheckFlashlight(); CheckRotation(); CheckAirDrop(); PollFocus(); + })); + dispatch_resume(gSentinel); + + gNetMon = nw_path_monitor_create(); + nw_path_monitor_set_queue(gNetMon, gSQ); + nw_path_monitor_set_update_handler(gNetMon, HB(^(nw_path_t path) { (void)_islet_z; + static int last = 0; + int kind = 0; + if (nw_path_get_status(path) == nw_path_status_satisfied) + kind = nw_path_uses_interface_type(path, nw_interface_type_wifi) ? 1 : nw_path_uses_interface_type(path, nw_interface_type_cellular) ? 2 : 3; + if (kind == 1 || kind == 2) { + if (last && last != kind && PrefBool(NS("network"), YES)) dispatch_async(dispatch_get_main_queue(), HB(^{ (void)_islet_z; ShowNetwork(kind == 1); })); + last = kind; + } + })); + nw_path_monitor_start(gNetMon); +} + +#pragma mark - Ping from Apple Watch + +// Sonar rings around the phone. The sound comes from companionfindlocallyd, a daemon; IsletPing.dylib, loaded there, says when. +static int gPingShown; +static void ShowPing(void) { + int _islet_z = 0; (void)_islet_z; + gPingShown++; + UIColor *c = NamedColor(NS("blue")); + Act *a = NewAct(NS("ping"), NS("ping")); + a[NS("tint")] = c; a[NS("ttl")] = @6; a[NS("critical")] = @YES; + a[NS("icon")] = Symbol(NS("iphone.gen1"), 18, c); + a[NS("liveCompact")] = HB(^NSString *{ (void)_islet_z; return NS("Pinging"); }); + PostTransient(a); +} + +#pragma mark - Debug / demo + +static void ShowVolume(float v); +static Act *NotificationAct(id request); +static NSString *ActivityInData(id data); + +static void Demo(int n) { + int _islet_z = 0; (void)_islet_z; // keeps blocks off the static-global (unsigned isa) path + UIColor *orange = NamedColor(NS("orange")); + switch (n) { + case 1: { + Act *a = NewAct(NS("demo"), NS("notif")); + a[NS("ttl")] = @5; a[NS("expandFirst")] = @YES; a[NS("bundleID")] = NS("com.apple.MobileSMS"); + a[NS("subtitle")] = NS("Messages"); a[NS("title")] = NS("Alex"); a[NS("body")] = NS("Are we still on for tonight? I booked the table for 8."); + UIImage *ic = [UIImage _applicationIconImageForBundleIdentifier:NS("com.apple.MobileSMS") format:2 scale:UIScreen.mainScreen.scale]; + a[NS("icon")] = ic ?: Symbol(NS("bell.fill"), 22, UIColor.whiteColor); + PostTransient(a); break; } + case 2: { + NSDate *fd = [NSDate dateWithTimeIntervalSinceNow:272]; + Act *a = NewAct(NS("demo-timer"), NS("timer")); a[NS("priority")] = @3; a[NS("tint")] = orange; a[NS("title")] = NS("Pasta"); + a[NS("icon")] = Symbol(NS("timer"), 17, orange); a[NS("subtitle")] = NS("demo"); + StrBlock t = HB(^NSString *{ (void)_islet_z; return FmtTime([fd timeIntervalSinceNow]); }); + a[NS("liveCompact")] = t; a[NS("liveBig")] = t; + a[NS("liveProgress")] = HB(^double { (void)_islet_z; return 1 - [fd timeIntervalSinceNow] / 300; }); + SetOngoing(a, NS("demo-timer")); break; } + case 3: { + Act *a = NewAct(NS("demo-music"), NS("music")); a[NS("priority")] = @2; + a[NS("title")] = NS("Midnight City"); a[NS("subtitle")] = NS("M83"); a[NS("tint")] = [UIColor colorWithRed:0.4 green:0.8 blue:1 alpha:1]; + UIGraphicsImageRenderer *r = [[UIGraphicsImageRenderer alloc] initWithSize:CGSizeMake(80, 80)]; + a[NS("icon")] = [r imageWithActions:HB(^(UIGraphicsImageRendererContext *c) { (void)_islet_z; + CGColorSpaceRef cs = CGColorSpaceCreateDeviceRGB(); + CGGradientRef g = CGGradientCreateWithColors(cs, (CFArrayRef)@[(id)[UIColor colorWithRed:0.4 green:0.2 blue:0.9 alpha:1].CGColor, (id)[UIColor colorWithRed:0.1 green:0.8 blue:1 alpha:1].CGColor], NULL); + CGContextDrawLinearGradient(c.CGContext, g, CGPointZero, CGPointMake(80, 80), 0); CGGradientRelease(g); CGColorSpaceRelease(cs); })]; + a[NS("liveProgress")] = HB(^double { (void)_islet_z; return 0.38; }); + a[NS("autoExpandUntil")] = [NSDate dateWithTimeIntervalSinceNow:3.4]; + gOngoing[NS("demo-music")] = a; Refresh(YES); break; } + case 4: ShowCharging(); break; + case 5: ShowRinger(NO); break; + case 6: [gOngoing removeAllObjects]; gExpandedKey = nil; gPinnedKey = nil; gHideUntil = nil; Refresh(YES); break; + case 7: if (gOngoing[NS("demo-timer")]) { gExpandedKey = NS("demo-timer"); Refresh(YES); } break; + case 8: if (gOngoing[NS("demo-music")]) { gExpandedKey = NS("demo-music"); Refresh(YES); } break; + case 9: { + UIColor *green = NamedColor(NS("green")); + NSDate *start = NSDate.date; + Act *a = NewAct(NS("demo-call"), NS("call")); a[NS("priority")] = @4; a[NS("tint")] = green; a[NS("title")] = NS("Alex Morgan"); + a[NS("icon")] = Symbol(NS("phone.fill"), 16, green); a[NS("subtitle")] = NS("active"); + StrBlock t = HB(^NSString *{ (void)_islet_z; return FmtTime(-[start timeIntervalSinceNow]); }); + a[NS("liveCompact")] = t; a[NS("liveBig")] = t; + SetOngoing(a, NS("demo-call")); break; } + case 10: gExpandedKey = NS("demo-call"); Refresh(YES); break; + case 12: ShowAirplane(YES); break; + case 13: ShowFocus(YES, NS("Personal"), NS("person.fill"), NS("purple")); break; + case 14: SetFlashlight(0.6); break; + case 15: ShowNetwork(NO); break; + case 16: SetFlashlight(0); break; + case 18: ShowStatusPill(NS("bt"), NS("airpods"), NS("AirPods Pro"), NamedColor(NS("blue")), 2.4); break; + case 17: if (gOngoing[NS("record")]) SetOngoing(nil, NS("record")); else ShowRecording(); break; + case 19: { + NSArray *b = @[@{NS("label"): NS(""), NS("pct"): @84, NS("charging"): @NO}, @{NS("label"): NS("Case"), NS("pct"): @62, NS("charging"): @NO}]; + ShowDevice(NS("bt"), NS("AirPods Pro"), NS("Connected"), NS("airpodspro"), b, NamedColor(NS("blue")), 4, NO); break; } + case 20: ShowDevice(NS("devbat"), NS("Apple Watch"), NS("Low Battery"), NS("applewatch"), @[@{NS("label"): NS(""), NS("pct"): @10, NS("charging"): @NO}], NamedColor(NS("red")), 4.5, YES); break; + case 21: ShowPhoneBattery(NS("Low Battery"), NS("battery.25percent"), 20, NamedColor(NS("red")), NO); break; + case 22: ShowPhoneBattery(NS("Fully Charged"), NS("battery.100.bolt"), 100, NamedColor(NS("green")), NO); break; + case 23: ShowUpcoming(NS("event"), NS("Design review"), NS("Room 4"), [NSDate dateWithTimeIntervalSinceNow:720], NS("calendar"), NamedColor(NS("red")), NS("com.apple.mobilecal")); break; + case 24: HideForAWhile(PrefNum(NS("hideSeconds"), 10)); break; + case 25: ShowStatusPill(NS("lpm"), NS("battery.50percent"), NS("Low Power On"), NamedColor(NS("yellow")), 2.2); break; + case 26: ShowStatusPill(NS("lock"), NS("lock.open.fill"), NS("Unlocked"), UIColor.whiteColor, 1.2); break; + case 27: ShowSystemActivity(NS("hotspot"), NS("Personal Hotspot"), NS("personalhotspot"), NamedColor(NS("green")), ActivityID("Tethering")); break; + case 28: ShowSystemActivity(NS("mirror"), NS("Screen Mirroring"), NS("rectangle.on.rectangle"), NamedColor(NS("blue")), ActivityID("ScreenSharing")); break; + case 29: ShowSystemActivity(NS("mic"), NS("Microphone"), NS("mic.fill"), NamedColor(NS("orange")), ActivityID("Recording")); break; + case 30: ShowVolume(0.6); break; + case 31: ShowRinger(YES); break; + case 32: ShowStatusPill(NS("rotation"), NS("lock.rotation"), NS("Rotation Locked"), NamedColor(NS("red")), 2.0); break; + case 33: ShowAirDrop(2); break; + case 35: ShowPing(); break; + case 36: gLyrics = ParseLRC(NS("[00:00.00]First line of the song\n[00:05.00]Second line goes here")); gLyricsOn = YES; ReloadMusicCard(); break; + case 34: SetAudioDevice(@{NS("name"): NS("AirPods Pro"), NS("product"): @8212, NS("low"): @84, NS("items"): @[@{NS("label"): NS(""), NS("pct"): @84, NS("charging"): @NO}]}); break; + } +} + +// Written by `isletctl dump` and shortly after any device connects, so a report exists without asking for one. On gSQ. +static void WriteBatteryReport(void) { + NSMutableString *b = [NSMutableString new]; + @try { for (id d in [gBC valueForKey:NS("connectedDevices")]) [b appendFormat:NS("%@\n group=%@ model=%@ product=%@ parts=%@ category=%@\n"), d, [d valueForKey:NS("groupName")], [d valueForKey:NS("modelNumber")], [d valueForKey:NS("productIdentifier")], [d valueForKey:NS("parts")], [d valueForKey:NS("accessoryCategory")]]; } + @catch (NSException *e) { [b appendFormat:NS("%@\n"), e]; } + [b appendFormat:NS("groups: %@\n"), BatteryGroups()]; + [b writeToFile:NS("/var/mobile/islet-batteries.txt") atomically:YES encoding:NSUTF8StringEncoding error:nil]; +} + +static IMP orig_auth, orig_shouldpost; +static IMP orig_airplane, orig_wifi, orig_dataitem, orig_telephony, orig_focus, orig_torch, orig_rotation; +static IMP orig_entry, orig_uientry, orig_mute, orig_pill, orig_stpill, orig_callpill, orig_banner, orig_presentable, orig_listener, orig_inset, orig_volume, orig_sensor; + +static void DumpState(void) { + int _islet_z = 0; (void)_islet_z; + NSMutableString *o = [NSMutableString new]; + for (UIScene *sc in UIApplication.sharedApplication.connectedScenes) { + [o appendFormat:NS("scene %@\n"), sc]; + if ([sc respondsToSelector:NSSelectorFromString(NS("systemApertureController"))]) + [o appendFormat:NS(" systemApertureController: %@\n"), [sc valueForKey:NS("systemApertureController")]]; + if ([sc isKindOfClass:UIWindowScene.class]) + for (UIWindow *w in ((UIWindowScene *)sc).windows) + [o appendFormat:NS(" window %@ level=%.0f hidden=%d alpha=%.2f frame=%@\n"), NSStringFromClass(w.class), w.windowLevel, w.hidden, w.alpha, NSStringFromCGRect(w.frame)]; + } + for (NSString *n in @[NS("SBSystemApertureController"), NS("SBSystemApertureStatusBarPillElementProvider"), NS("SAUISystemApertureManager")]) + [o appendFormat:NS("class %@ exists=%d\n"), n, NSClassFromString(n) != nil]; + [o appendFormat:NS("version %s capture=%d lyrics=%lu/%d player=%@ orientation=%d window=%@ view=%@\nhooks: shouldpost=%d auth=%d airplane=%d wifi=%d data=%d/%d focus=%d torch=%d rotation=%d entry=%d/%d mute=%d pill=%d stuipill=%d callpill=%d banner=%d presentable=%d listener=%d inset=%d volume=%d sensor=%d\n"), ISLET_VERSION, gCaptureKind, (unsigned long)gLyrics.count, gLyricsOn, gMusicBID, gMode, NSStringFromCGRect(gWindow.bounds), NSStringFromCGRect(gHost.superview.bounds), + orig_shouldpost != NULL, orig_auth != NULL, orig_airplane != NULL, orig_wifi != NULL, orig_dataitem != NULL, orig_telephony != NULL, orig_focus != NULL, orig_torch != NULL, orig_rotation != NULL, orig_entry != NULL, orig_uientry != NULL, orig_mute != NULL, orig_pill != NULL, orig_stpill != NULL, + orig_callpill != NULL, orig_banner != NULL, orig_presentable != NULL, orig_listener != NULL, orig_inset != NULL, orig_volume != NULL, orig_sensor != NULL]; + [o appendFormat:NS("flash controller=%@ av=%@ rotation=%@ airdrop=%@ domain=%@ domainData=%d\nactivities=%@ audio=%@\nongoing=%@ cur=%@ pinned=%@ hideUntil=%@\n"), gFlashCtl, gFlash, gRotation, gAirDrop, gActivityDomain, gActivityDomainHasData, gActivities, gAudioDevice, gOngoing.allKeys, S(gCur, "key"), gPinnedKey, gHideUntil]; + double peak = 0; for (NSNumber *n in gAmps) peak = MAX(peak, n.doubleValue); + [o appendFormat:NS("analyzer=%@ pid=%d amps=%lu peak=%.3f age=%.2fs bars=%lu vizTimer=%d fullscreen=%d\n"), gAnalyzer, gAnalyzerPID, (unsigned long)gAmps.count, peak, CACurrentMediaTime() - gAmpsAt, (unsigned long)gBars.count, gVizTimer != nil, gFullscreenVideo]; + int pingToken = 0; uint64_t pingHooks = 0, pingFired = 0; + notify_register_check("com.astar76.islet.ping.hooks", &pingToken); notify_get_state(pingToken, &pingHooks); notify_cancel(pingToken); + notify_register_check("com.astar76.islet.ping.fired", &pingToken); notify_get_state(pingToken, &pingFired); notify_cancel(pingToken); + [o appendFormat:NS("ping daemon: hooks=%llu fired=%llu shown=%d\n"), pingHooks, pingFired, gPingShown]; + [o appendFormat:NS("airplane=%@ wifi=%@ celldata=%p bt=%@ connected=%@\nfocus state=%@ activity=%@\n"), gAirplane, gWiFi, CellDataEnabled, gBluetooth, [gBluetooth valueForKey:NS("connectedDevices")], [gFocusState valueForKey:NS("state")], [gFocusManager valueForKey:NS("activeActivity")]]; + [o writeToFile:NS("/var/jb/var/mobile/islet-dump.txt") atomically:YES encoding:NSUTF8StringEncoding error:nil]; + dispatch_async(gSQ, HB(^{ (void)_islet_z; WriteBatteryReport(); })); +} + +static void Snapshot(void) { + int _islet_z = 0; (void)_islet_z; + UIWindow *w = gWindow; + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.9 * NSEC_PER_SEC)), dispatch_get_main_queue(), HB(^{ (void)_islet_z; + CGRect full = w.bounds; + UIImage *img = [[[UIGraphicsImageRenderer alloc] initWithSize:full.size] imageWithActions:HB(^(UIGraphicsImageRendererContext *c) { (void)_islet_z; + [[UIColor colorWithWhite:0.35 alpha:1] setFill]; UIRectFill(full); + [w drawViewHierarchyInRect:full afterScreenUpdates:YES]; + })]; + CGFloat sc = img.scale; + CGImageRef top = CGImageCreateWithImageInRect(img.CGImage, CGRectMake(0, 0, full.size.width * sc, 220 * sc)); + [UIImagePNGRepresentation([UIImage imageWithCGImage:top scale:sc orientation:UIImageOrientationUp]) writeToFile:SNAP_PATH atomically:YES]; + CGImageRelease(top); + })); +} + +#pragma mark - Start + +static void InitState(void) { + gOngoing = [NSMutableDictionary new]; gQueue = [NSMutableArray new]; + gSQ = dispatch_queue_create("islet.sentinel", DISPATCH_QUEUE_SERIAL); + gSlowQ = dispatch_queue_create("islet.slow", dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_SERIAL, QOS_CLASS_UTILITY, 0)); +} + +static void UpdateGeometry(void) { + gNotch = CGSizeMake(PrefNum(NS("notchWidth"), ScreenW() >= 414 ? 214 : 209), PrefNum(NS("notchHeight"), 30)); +} + +static void CreateIsland(UIView *parent) { + int _islet_z = 0; (void)_islet_z; + UpdateGeometry(); + UIView *host = [[UIView alloc] initWithFrame:parent.bounds]; + [parent addSubview:host]; + gHost = host; + UIView *island = [[UIView alloc] initWithFrame:CGRectMake(0, 0, gNotch.width, gNotch.height)]; + island.backgroundColor = UIColor.blackColor; island.clipsToBounds = YES; island.alpha = 0; + island.layer.cornerCurve = kCACornerCurveContinuous; + gIsland = island; + AnchorIsland(); + [host addSubview:island]; + + UIView *(^makeBubble)(CAShapeLayer **) = HB(^UIView *(CAShapeLayer **out) { (void)_islet_z; + UIView *bubble = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 40, 40)]; + bubble.backgroundColor = UIColor.blackColor; bubble.alpha = 0; + bubble.layer.cornerRadius = 20; + CAShapeLayer *ring = [CAShapeLayer layer]; // not layer.border: at a full radius that leaves ticks on the four edges + ring.path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0.75, 0.75, 38.5, 38.5)].CGPath; + ring.fillColor = UIColor.clearColor.CGColor; ring.lineWidth = 1.5; + [bubble.layer addSublayer:ring]; *out = ring; + UIImageView *bi = [[UIImageView alloc] initWithFrame:CGRectMake(9, 9, 22, 22)]; + bi.contentMode = UIViewContentModeScaleAspectFit; bi.layer.cornerRadius = 5; bi.clipsToBounds = YES; + [bubble addSubview:bi]; [host addSubview:bubble]; + return bubble; + }); + CAShapeLayer *ring1 = nil, *ring2 = nil; + UIView *bubble = makeBubble(&ring1), *left = makeBubble(&ring2); + gBubbleRing = ring1; gLeftBubble = left; gLeftRing = ring2; + gIsland = island; gBubble = bubble; +} + +static void NotificationButton(int i); + +// Turns gHost to where the notch now is. Worked out against the screen's fixed axes, so it's right however SpringBoard +// has the window itself turned at that moment. +static void ApplyHostGeometry(void) { + UIView *p = gHost.superview; + CGFloat base = 0; + if (gWindow) { + id fixed = UIScreen.mainScreen.fixedCoordinateSpace; + CGPoint o = [p convertPoint:CGPointZero toCoordinateSpace:fixed], x = [p convertPoint:CGPointMake(1, 0) toCoordinateSpace:fixed]; + base = atan2(x.y - o.y, x.x - o.x); + } + CGSize b = p.bounds.size; + CGFloat lo = MIN(b.width, b.height), hi = MAX(b.width, b.height); + gHost.transform = CGAffineTransformIdentity; + gHost.bounds = gMode ? CGRectMake(0, 0, hi, lo) : CGRectMake(0, 0, lo, hi); + gHost.center = CGPointMake(b.width / 2, b.height / 2); + gHost.transform = CGAffineTransformMakeRotation((gMode == 1 ? M_PI_2 : gMode == 2 ? -M_PI_2 : 0) - base); + AnchorIsland(); +} + +static void SetMode(int mode) { + if (mode == gMode) return; + gMode = mode; + if (PrefBool(NS("hideLandscape"), NO)) RefreshStockStatusBar(); + VizStop(); + [gBox removeFromSuperview]; gBox = nil; gLive = nil; gBig = nil; gFill = nil; + Act *t = gTransient; BOOL open = gExp; + gCur = nil; gExp = NO; gIsland.alpha = 0; gBubble.alpha = 0; gLeftBubble.alpha = 0; + ApplyHostGeometry(); + UpdateFullscreenVideo(); + if (t && !Suppressed([t[NS("critical")] boolValue])) ShowActivity(t, open); else { gTransient = nil; Refresh(NO); } +} + +// UIInterfaceOrientation: 3 is home button right, so the notch is on the viewer's left; 4 the reverse. +static void orient_will(id self, SEL _cmd, long o) {} +static void orient_did(id self, SEL _cmd, long o, double duration, long from) { SetMode(o == 3 ? 1 : o == 4 ? 2 : 0); } + +static void SetupOrientation(void) { + int _islet_z = 0; (void)_islet_z; + id app = UIApplication.sharedApplication; + SEL add = NSSelectorFromString(NS("addActiveOrientationObserver:")), cur = NSSelectorFromString(NS("activeInterfaceOrientation")); + if (![app respondsToSelector:add] || ![app respondsToSelector:cur]) return; + Class oc = MakeClass("IsletOrientationObserver", NSObject.class, HB(^(Class c) { (void)_islet_z; + class_addMethod(c, NSSelectorFromString(NS("activeInterfaceOrientationWillChangeToOrientation:")), (IMP)orient_will, "v@:q"); + class_addMethod(c, NSSelectorFromString(NS("activeInterfaceOrientationDidChangeToOrientation:willAnimateWithDuration:fromOrientation:")), (IMP)orient_did, "v@:qdq"); + })); + static id observer; observer = [oc new]; + ((void (*)(id, SEL, id))objc_msgSend)(app, add, observer); + long o = ((long (*)(id, SEL))objc_msgSend)(app, cur); + SetMode(o == 3 ? 1 : o == 4 ? 2 : 0); +} + +// Nothing to animate or poll for an unlit screen. Everything picks up again when it lights. +static void SetupScreenWatch(void) { + int _islet_z = 0; (void)_islet_z; + static int token; + notify_register_dispatch("com.apple.springboard.hasBlankedScreen", &token, dispatch_get_main_queue(), HB(^(int t) { (void)_islet_z; + uint64_t st = 0; notify_get_state(t, &st); + gScreenOff = st != 0; + if (gScreenOff) { [gVizTimer invalidate]; gVizTimer = nil; StopAnalyzer(); } + else { VizStart(); MediaChanged(); PollSystem(); Tick(); } + })); +} + +static void InstallGestures(void) { + int _islet_z = 0; (void)_islet_z; + UIView *island = gIsland; + Class tc = MakeClass("IsletTarget", NSObject.class, HB(^(Class c) { (void)_islet_z; + class_addMethod(c, @selector(tapped:), (IMP)tgt_tapped, "v@:@"); + class_addMethod(c, @selector(panned:), (IMP)tgt_panned, "v@:@"); + class_addMethod(c, @selector(bubbleTapped:), (IMP)tgt_bubble, "v@:@"); + class_addMethod(c, @selector(leftBubbleTapped:), (IMP)tgt_leftBubble, "v@:@"); + class_addMethod(c, @selector(longPressed:), (IMP)tgt_longPressed, "v@:@"); + })); + static id target; target = [tc new]; + UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:target action:@selector(tapped:)]; + tap.cancelsTouchesInView = NO; [island addGestureRecognizer:tap]; + UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:target action:@selector(panned:)]; + pan.cancelsTouchesInView = NO; pan.maximumNumberOfTouches = 1; [island addGestureRecognizer:pan]; + UILongPressGestureRecognizer *hold = [[UILongPressGestureRecognizer alloc] initWithTarget:target action:@selector(longPressed:)]; + hold.minimumPressDuration = 0.45; hold.cancelsTouchesInView = NO; [island addGestureRecognizer:hold]; + [gBubble addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:target action:@selector(bubbleTapped:)]]; + [gLeftBubble addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:target action:@selector(leftBubbleTapped:)]]; +} + +// Settings changed: reload and re-evaluate everything that depends on a pref, so nothing needs a respring. +// Switched off: everything Islet holds goes at once and the window leaves, so what's underneath is plain stock. +static void StandDown(void) { + int _islet_z = 0; (void)_islet_z; + gTransient = nil; [gQueue removeAllObjects]; [gOngoing removeAllObjects]; + gExpandedKey = nil; gPinnedKey = nil; gHideUntil = nil; gAudioDevice = nil; gFullscreenVideo = NO; + StopAnalyzer(); + HideIsland(YES); + RefreshStockStatusBar(); + UIWindow *w = gWindow; + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.6 * NSEC_PER_SEC)), dispatch_get_main_queue(), HB(^{ (void)_islet_z; + if (!PrefBool(NS("enabled"), YES)) w.hidden = YES; + })); +} + +static void ApplyPrefs(void) { + int _islet_z = 0; (void)_islet_z; + LoadPrefs(); + if (!PrefBool(NS("enabled"), YES)) { StandDown(); return; } + if (gWindow.hidden) { gWindow.hidden = NO; RefreshStockStatusBar(); } + UpdateGeometry(); + UpdateFullscreenVideo(); + if (!PrefBool(NS("timer"), YES)) SetOngoing(nil, NS("timer")); + if (!PrefBool(NS("calls"), YES)) SetOngoing(nil, NS("call")); + if (!PrefBool(NS("flashlight"), YES)) SetOngoing(nil, NS("flash")); + if (!PrefBool(NS("realVisualizer"), YES)) StopAnalyzer(); + MediaChanged(); UpdateRecording(); PollSystem(); + [gLyricCache removeAllObjects]; + if (gRetryLyrics) gRetryLyrics(); // a lyric setting applies to the song already playing + dispatch_async(gSlowQ, HB(^{ (void)_islet_z; PollCalendar(); })); + gTransient = nil; [gQueue removeAllObjects]; // a popup in flight was sized for the old settings + if (gCur) { gCur = nil; [gBox removeFromSuperview]; gBox = nil; gIsland.alpha = 0; } // geometry may have moved + Refresh(YES); +} + +static BOOL vc_no(id self, SEL _cmd) { return NO; } +static unsigned long vc_portrait(id self, SEL _cmd) { return UIInterfaceOrientationMaskPortrait; } + +static void StartIsland(void) { + int _islet_z = 0; (void)_islet_z; // keeps blocks off the static-global (unsigned isa) path + if (gWindow) return; + InitState(); + + CGRect sb = UIScreen.mainScreen.bounds; + UIWindowScene *scene = nil; + Class mainSceneClass = NSClassFromString(NS("SBWindowScene")); // SpringBoard's own scene, not a system-aperture or overlay one + for (UIScene *s in UIApplication.sharedApplication.connectedScenes) { + if (![s isKindOfClass:UIWindowScene.class]) continue; + if (!scene) scene = (UIWindowScene *)s; + if (mainSceneClass && [s isKindOfClass:mainSceneClass]) { scene = (UIWindowScene *)s; break; } + } + + Class winClass = MakeClass("IsletWindow", UIWindow.class, HB(^(Class c) { (void)_islet_z; + sHitSuper = class_getMethodImplementation(UIWindow.class, @selector(hitTest:withEvent:)); + class_addMethod(c, @selector(hitTest:withEvent:), (IMP)win_hitTest, "@@:{CGPoint=dd}@"); + })); + UIWindow *w = scene ? [[winClass alloc] initWithWindowScene:scene] : [[winClass alloc] initWithFrame:sb]; + w.frame = sb; w.windowLevel = 10000010; w.backgroundColor = UIColor.clearColor; + Class vcClass = MakeClass("IsletRootController", UIViewController.class, HB(^(Class c) { (void)_islet_z; + class_addMethod(c, @selector(shouldAutorotate), (IMP)vc_no, "B@:"); + class_addMethod(c, @selector(supportedInterfaceOrientations), (IMP)vc_portrait, "Q@:"); + })); + UIViewController *vc = [vcClass new]; + vc.view.backgroundColor = UIColor.clearColor; + w.rootViewController = vc; + CreateIsland(vc.view); + w.hidden = NO; + gWindow = w; + InstallGestures(); + + gOnCommand = HB(^(NSString *c) { (void)_islet_z; + gFoldAt = CACurrentMediaTime() + PrefNum(NS("autoFold"), 8); + if ([c hasPrefix:NS("torch")]) { + if ([c isEqual:NS("torchoff")]) SetFlashlight(0); // island reacts instantly, hardware follows + TorchCommand(c); + } else if ([c hasPrefix:NS("timer:")]) TimerCommand(c); + else if ([c hasPrefix:NS("call:")]) { CallCommand(c); PollCalls(); } + else if ([c hasPrefix:NS("activity:")]) { gExpandedKey = nil; Refresh(YES); TapStockActivity([c substringFromIndex:9]); } + else if ([c hasPrefix:NS("notif:")]) NotificationButton([[c substringFromIndex:6] intValue]); + else if ([c isEqual:NS("routes")]) { gExpandedKey = nil; Refresh(YES); ShowRoutes(); } + else if ([c isEqual:NS("lyrics")]) { gLyricsOn = !gLyricsOn; ReloadMusicCard(); } + else if (MRSendCommand) MRSendCommand([c isEqual:NS("prev")] ? 5 : [c isEqual:NS("next")] ? 4 : 2, nil); + }); + Every(0.5, 0.1, HB(^{ (void)_islet_z; Tick(); })); + Every(15, 5, HB(^{ (void)_islet_z; if (!gScreenOff) PollSystem(); })); // calls, timers and devices all announce themselves + SetupMedia(); SetupBattery(); SetupRinger(); SetupDeviceBatteries(); StartSentinel(); SetupRecording(); SetupBluetooth(); + SetupOrientation(); SetupScreenWatch(); + PollSystem(); + if (!gMT) PollTimers(); // loads MobileTimer, whose notification names are read below + const char *timerNotes[] = {"MTTimerManagerTimersChanged", "MTTimerManagerFiringTimerChanged"}; + for (int i = 0; i < 2; i++) { + NSString * __unsafe_unretained *note = (NSString * __unsafe_unretained *)dlsym(RTLD_DEFAULT, timerNotes[i]); + if (note && *note) + [NSNotificationCenter.defaultCenter addObserverForName:*note object:nil queue:NSOperationQueue.mainQueue usingBlock:HB(^(NSNotification *n) { (void)_islet_z; + if (PrefBool(NS("timer"), YES)) PollTimers(); + })]; + } + PollCalls(); + + // Ringing shouldn't wait for the next poll. + NSString * __unsafe_unretained *callNote = (NSString * __unsafe_unretained *)dlsym(RTLD_DEFAULT, "TUCallCenterCallStatusChangedNotification"); + if (callNote && *callNote) + [NSNotificationCenter.defaultCenter addObserverForName:*callNote object:nil queue:NSOperationQueue.mainQueue usingBlock:HB(^(NSNotification *n) { (void)_islet_z; + if (PrefBool(NS("calls"), YES)) PollCalls(); + })]; + static int t1, t2, t3, t4; + static int t5; + notify_register_dispatch("com.astar76.islet.ping", &t5, dispatch_get_main_queue(), HB(^(int t) { (void)_islet_z; if (PrefBool(NS("watchPing"), YES)) ShowPing(); })); + notify_register_dispatch("com.astar76.islet.dump", &t3, dispatch_get_main_queue(), HB(^(int t) { (void)_islet_z; DumpState(); })); + notify_register_dispatch("com.astar76.islet.snap", &t1, dispatch_get_main_queue(), HB(^(int t) { (void)_islet_z; Snapshot(); })); + notify_register_dispatch("com.astar76.islet.demo", &t2, dispatch_get_main_queue(), HB(^(int t) { (void)_islet_z; uint64_t n = 0; notify_get_state(t, &n); Demo((int)n); })); + notify_register_dispatch(PREFS_NOTIFICATION, &t4, dispatch_get_main_queue(), HB(^(int t) { (void)_islet_z; ApplyPrefs(); })); + LOG("started on scene %@: notch %.0fx%.0f on %.0fx%.0f, scene=%d", scene, gNotch.width, gNotch.height, sb.size.width, sb.size.height, scene != nil); +} + +#pragma mark - Self test + +static int GuardFails(NSString *path); + +// Runs from tests/loadtest with ISLET_SELFTEST=: builds the real island offscreen in a plain view (no SpringBoard, +// no window), walks every activity through the real arbitration code, and writes a PNG per state plus status.txt. +typedef struct { const char *name; int demo; const char *expand; } TestStep; + +static void TestReset(void) { + SetMode(0); + gTransient = nil; [gQueue removeAllObjects]; [gOngoing removeAllObjects]; + gExpandedKey = nil; gPinnedKey = nil; gHideUntil = nil; gLyrics = nil; gLyricsOn = NO; + Refresh(NO); +} + +static void TestSnap(UIView *host, NSString *dir, NSString *name) { + int _islet_z = 0; (void)_islet_z; + CGRect r = CGRectMake(0, 0, host.bounds.size.width, gMode ? host.bounds.size.height : 260); + UIGraphicsImageRendererFormat *f = [UIGraphicsImageRendererFormat new]; f.scale = 2; + UIImage *img = [[[UIGraphicsImageRenderer alloc] initWithSize:r.size format:f] imageWithActions:HB(^(UIGraphicsImageRendererContext *c) { (void)_islet_z; + [host.layer renderInContext:c.CGContext]; + })]; + [UIImagePNGRepresentation(img) writeToFile:[dir stringByAppendingPathComponent:[name stringByAppendingString:NS(".png")]] atomically:YES]; +} + +static void SelfTest(NSString *dir) { + int _islet_z = 0; (void)_islet_z; + static const TestStep steps[] = { + {"timer-compact", 2, NULL}, {"timer-open", 2, "demo-timer"}, {"music-open", 3, "demo-music"}, {"call-active", 9, "demo-call"}, + {"airpods", 19, NULL}, {"watch-low", 20, NULL}, {"iphone-low", 21, NULL}, {"iphone-full", 22, NULL}, {"charging", 4, NULL}, + {"calendar-open", 23, "event"}, {"calendar-compact", 23, NULL}, {"flash-open", 14, "flash"}, {"recording", 17, NULL}, {"silent", 5, NULL}, + {"airplane", 12, NULL}, {"focus", 13, NULL}, {"lowpower", 25, NULL}, {"lock", 26, NULL}, {"bt-pill", 18, NULL}, {"notification", 1, NULL}, + {"bell-ring", 31, NULL}, {"hotspot-open", 27, "hotspot"}, {"mirror-compact", 28, NULL}, {"mic-compact", 29, NULL}, {"volume", 30, NULL}, + {"rotation", 32, NULL}, {"airdrop", 33, NULL}, {"record-open", 17, "record"}, {"notif-actions", 900, NULL}, + {"ping", 35, NULL}, {"lyrics-compact", 907, NULL}, {"lyrics-open", 908, "demo-music"}, + {"landL-compact", 901, NULL}, {"landL-music", 902, "demo-music"}, {"landL-airpods", 903, NULL}, {"landR-compact", 904, NULL}, {"landR-music", 905, "demo-music"}, {"landR-two", 906, NULL}, + }; + int count = sizeof(steps) / sizeof(steps[0]); + gPrefs = [NSDictionary new]; // defaults, not whatever the phone's sliders happen to be at + InitState(); UpdateGeometry(); + UIView *host = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenW(), 896)]; + host.backgroundColor = [UIColor colorWithWhite:0.35 alpha:1]; + CreateIsland(host); + NSMutableString *out = [NSMutableString new]; + NSMutableArray *checks = [NSMutableArray new]; + void (^check)(const char *, BOOL) = HB(^(const char *n, BOOL ok) { (void)_islet_z; [checks addObject:[NSString stringWithFormat:NS("%s %s"), ok ? "PASS" : "FAIL", n]]; }); + __block int i = 0, phase = 0; + [NSTimer scheduledTimerWithTimeInterval:0.45 repeats:YES block:HB(^(NSTimer *t) { (void)_islet_z; + @try { + if (i < count) { + TestStep st = steps[i]; + if (phase == 0) { + TestReset(); + if (st.demo == 14) { Demo(14); [gOngoing[NS("flash")] removeObjectForKey:NS("autoExpandUntil")]; } + else if (st.demo == 23) { Demo(23); [gOngoing[NS("event")] removeObjectForKey:NS("autoExpandUntil")]; } + else if (st.demo == 3) { Demo(3); [gOngoing[NS("demo-music")] removeObjectForKey:NS("autoExpandUntil")]; } + else if (st.demo == 907 || st.demo == 908) { + Demo(3); [gOngoing[NS("demo-music")] removeObjectForKey:NS("autoExpandUntil")]; + gOngoing[NS("demo-music")][NS("liveCompact")] = HB(^NSString *{ (void)_islet_z; return NS("And the night is young, the city lights are calling out my name"); }); + gLyrics = ParseLRC(NS("[00:00.00]line")); gLyricsOn = YES; gExp = NO; gCur = nil; Refresh(NO); + } + else if (st.demo > 900) { + SetMode(st.demo >= 904 ? 2 : 1); + if (st.demo == 901 || st.demo == 904 || st.demo == 906) Demo(2); + if (st.demo == 906) { Demo(9); Demo(34); [gOngoing[NS("demo-timer")] setObject:@1 forKey:NS("priority")]; } + if (st.demo == 902 || st.demo == 905) { Demo(3); [gOngoing[NS("demo-music")] removeObjectForKey:NS("autoExpandUntil")]; } + if (st.demo == 903) Demo(19); + } + else if (st.demo == 900) { + UIGraphicsImageRenderer *r = [[UIGraphicsImageRenderer alloc] initWithSize:CGSizeMake(60, 60)]; + UIImage *ic = [r imageWithActions:HB(^(UIGraphicsImageRendererContext *c) { (void)_islet_z; [UIColor.systemPinkColor setFill]; UIRectFill(CGRectMake(0, 0, 60, 60)); })]; + NSDictionary *content = @{NS("title"): NS("Sam"), NS("message"): NS("Look at this"), NS("header"): NS("Messages"), NS("icons"): @[ic], NS("attachmentImage"): ic}; + NSDictionary *req = @{NS("content"): content, NS("sectionIdentifier"): NS("com.apple.MobileSMS"), NS("supplementaryActions"): @[@{NS("title"): NS("Reply"), NS("behavior"): @1}, @{NS("title"): NS("Mark as Read"), NS("behavior"): @0}]}; + Act *n = NotificationAct(req); + check("stock icon wins over the app icon", n[NS("icon")] == ic); + check("actions come through", [n[NS("actions")] count] == 2); + PostTransient(n); + } + else Demo(st.demo); + if (st.expand) { gExpandedKey = NS(st.expand); Refresh(YES); } + Refresh(NO); phase = 1; return; + } + Tick(); + TestSnap(host, dir, NS(st.name)); + [out appendFormat:NS("%-18s cur=%@ kind=%@ open=%d size=%.0fx%.0f transient=%d\n"), st.name, S(gCur, "key"), S(gCur, "kind"), gExp, gIsland.bounds.size.width, gIsland.bounds.size.height, gTransient != nil]; + phase = 0; i++; return; + } + // Behaviour that the pictures can't show. + if (i == count && !phase) { + NSString *guardFile = [dir stringByAppendingPathComponent:NS("guard")]; + [NS("2") writeToFile:guardFile atomically:YES encoding:NSUTF8StringEncoding error:nil]; + check("a fresh crash count counts", GuardFails(guardFile) == 2); + [NSFileManager.defaultManager setAttributes:@{NSFileModificationDate: [NSDate dateWithTimeIntervalSinceNow:-600]} ofItemAtPath:guardFile error:nil]; + check("a stale one from a reboot doesn't", GuardFails(guardFile) == 0); + [NSFileManager.defaultManager removeItemAtPath:guardFile error:nil]; + check("no crash count at all is fine", GuardFails(guardFile) == 0); + NSDictionary *savedPrefs = gPrefs; + TestReset(); Demo(2); Demo(5); Demo(12); + gPrefs = @{NS("enabled"): @NO}; StandDown(); + check("disabling clears everything at once", gCur == nil && gTransient == nil && gQueue.count == 0 && gOngoing.count == 0); + Demo(5); Demo(20); check("nothing shows while disabled, critical or not", gTransient == nil); + check("stock gets its pills and banners back", !IsletTakesActivity(ActivityID("ScreenReplayRecording")) && !Suppressed(NO) == NO); + gPrefs = savedPrefs; Demo(2); Refresh(NO); + check("enabling brings it back", gCur != nil); + TestReset(); Demo(2); Demo(5); Demo(12); gHideUntil = [NSDate dateWithTimeIntervalSinceNow:30]; Refresh(NO); + check("hiding cuts off a popup and its queue", gTransient == nil && gQueue.count == 0 && gCur == nil); + gHideUntil = [NSDate dateWithTimeIntervalSinceNow:-1]; Refresh(NO); + check("and the island comes back by itself", gCur != nil); + gPrefs = @{NS("hideLandscape"): @YES}; TestReset(); Demo(2); Demo(5); SetMode(1); + check("hide in landscape cuts off a popup too", gTransient == nil && gCur == nil); + check("and leaves the stock pill alone", !IsletTakesActivity(ActivityID("ScreenReplayRecording"))); + SetMode(0); check("returning to portrait brings it back", gCur != nil); + gPrefs = savedPrefs; + NSArray *lrc = ParseLRC(NS("[ar:Someone]\n[00:12.50]Hello\n[00:20.00][01:00.00]Chorus\nno stamp")); + check("LRC parses, skips tags, keeps repeats", lrc.count == 3 && [lrc[0][NS("t")] doubleValue] == 12.5); + gLyrics = lrc; + check("lyrics follow the position", [LyricAt(15) isEqual:NS("Hello")] && [LyricAt(61) isEqual:NS("Chorus")] && [LyricAt(1) isEqual:NS("")]); + gLyrics = nil; + check("plain lyrics don't count as timed", ParseLRC(NS("just some words\nand more")).count == 0); + check("NetEase credit lines are dropped", ParseLRC(NS("[00:00.000] 作词 : Someone\n[00:01.000] 作曲 : Someone\n[00:37.790]Waiting in a car")).count == 1); + TestReset(); Demo(3); [gOngoing[NS("demo-music")] removeObjectForKey:NS("autoExpandUntil")]; gLyrics = lrc; gLyricsOn = YES; gCur = nil; Refresh(NO); + check("lyrics keep the tab's height and clear the status icons", gIsland.bounds.size.height == CompactSize().height && gIsland.bounds.size.width == CompactSize().width); + gLyrics = nil; gLyricsOn = NO; TestReset(); + check("players are recognised", IsMusicPlayer(NS("com.mulberry.player"), nil) && IsMusicPlayer(NS("com.spotify.client"), nil) && IsMusicPlayer(NS("com.google.ios.youtubemusic"), nil) && IsMusicPlayer(NS("com.apple.Music"), nil)); + check("video and spoken apps aren't", !IsMusicPlayer(NS("com.google.ios.youtube"), NS("x")) && !IsMusicPlayer(NS("com.apple.podcasts"), NS("x")) && !IsMusicPlayer(NS("com.apple.mobilesafari"), NS("x"))); + check("unknown apps need an album", IsMusicPlayer(NS("com.example.app"), NS("Album")) && !IsMusicPlayer(NS("com.example.app"), nil)); + check("titles clean up for searching", [CleanTitle(NS("Song (2011 Remaster)")) isEqual:NS("Song")] && [CleanTitle(NS("Song - Single")) isEqual:NS("Song")] && [CleanTitle(NS("Song")) isEqual:NS("Song")]); + NSArray *hits = @[@{NS("id"): @1, NS("name"): NS("Song (Remix)"), NS("dt"): @200000}, @{NS("id"): @2, NS("name"): NS("Song"), NS("dt"): @300000}, @{NS("id"): @3, NS("name"): NS("song"), NS("dt"): @201000}]; + check("NetEase match needs the name and the length", [PickNetEaseSong(hits, NS("Song"), 200) isEqual:@3] && PickNetEaseSong(hits, NS("Other"), 200) == nil); + TestReset(); gTestCaptured = 1; + UpdateActivities([NSSet setWithObject:ActivityID("ScreenSharing")]); + check("mirroring shows as mirroring", gOngoing[NS("mirror")] != nil && gOngoing[NS("record")] == nil); + UpdateActivities([NSSet set]); + check("and stays that way after other status updates", gCaptureKind == 2 && gOngoing[NS("mirror")] != nil && gOngoing[NS("record")] == nil); + gTestCaptured = 0; UpdateActivities([NSSet set]); + check("ending capture clears it", gCaptureKind == 0 && gOngoing[NS("mirror")] == nil); + gTestCaptured = 1; UpdateActivities([NSSet setWithObject:ActivityID("ScreenReplayRecording")]); + check("recording shows as recording", gOngoing[NS("record")] != nil && gOngoing[NS("mirror")] == nil); + gTestCaptured = 0; UpdateActivities([NSSet set]); gTestCaptured = -1; + TestReset(); Demo(1); Act *firstNotif = gTransient; Demo(1); + check("a new notification takes over at once", gTransient != firstNotif && gQueue.count == 0 && gCur == gTransient); + TestReset(); Demo(5); Demo(12); + check("other popups wait their turn", [S(gTransient, "key") isEqual:NS("ringer")] && gQueue.count == 1); + TestReset(); SetMode(1); Demo(2); Refresh(NO); + check("landscape anchors on the notch", gIsland.layer.position.x == 0 && gIsland.bounds.size.width > CompactSize().width); + check("landscape tab spans the notch like portrait", gIsland.bounds.size.height == CompactSize().height && gIsland.bounds.size.height >= gNotch.width); + TestReset(); SetMode(2); Demo(2); Refresh(NO); + check("and on the other side", gIsland.layer.position.x == gHost.bounds.size.width); + TestReset(); Demo(3); [gOngoing[NS("demo-music")] removeObjectForKey:NS("autoExpandUntil")]; Refresh(NO); + gAmps = nil; VizStart(); + check("no audio data, no bar motion", gVizTimer == nil && gBars.count > 0); + double flat = gBars[0].transform.d; + for (int k = 0; k < 20; k++) VizStep(); + check("bars stay flat without data", gBars[0].transform.d == flat); + gAmps = @[@0.9, @0.9, @0.9, @0.9]; gAmpsAt = CACurrentMediaTime(); VizStart(); + check("real data starts them", gVizTimer != nil); + for (int k = 0; k < 8; k++) { gAmpsAt = CACurrentMediaTime(); VizStep(); } + check("and they follow it", gBars[0].transform.d > 0.6); + gAmpsAt = 0; + for (int k = 0; k < 60; k++) VizStep(); + check("data stopping settles them and stops the timer", gVizTimer == nil && fabs(gBars[0].transform.d - BAR_REST) < 0.001); + gAmps = @[@0.9, @0.9]; gAmpsAt = CACurrentMediaTime(); gScreenOff = YES; VizStart(); check("screen off stops the bars", gVizTimer == nil); gScreenOff = NO; gAmps = nil; + TestReset(); gFullscreenVideo = YES; Demo(2); Refresh(NO); + check("full-screen video clears the island", gCur == nil); + Demo(5); check("and its popups", gTransient == nil); + Demo(9); Refresh(NO); check("a call still gets through", gCur != nil); + gFullscreenVideo = NO; + TestReset(); check("back to portrait", gMode == 0 && gHost.bounds.size.height > gHost.bounds.size.width); + TestReset(); Demo(5); check("bell swings", [gBox.subviews.firstObject.layer animationForKey:NS("swing")] != nil); + TestReset(); ShowVolume(0.4); Act *vol = gTransient; ShowVolume(0.5); + check("volume presses reuse one card", gTransient == vol && gVolume == (double)0.5f); + TestReset(); Demo(34); Demo(2); Refresh(NO); + check("headphones sit left of the island", gLeftBubble.alpha > 0.5); + NSDictionary *pods = @{NS("name"): NS("Sam's AirPods"), NS("connected"): @YES, NS("isAppleAudioDevice"): @YES, NS("productId"): @8212, NS("batteryLevel"): @0, NS("majorClass"): @0}; + gTestBluetooth = @[pods]; PollAudioDevice(); + check("connected list sets the audio device", [gAudioDevice[NS("name")] isEqual:NS("Sam's AirPods")]); + gTestBluetooth = @[]; PollAudioDevice(); + check("gone from the list, gone from the island", gAudioDevice == nil && gLeftBubble.alpha < 0.5); + check("and it says so", [CallStr(gTransient, NS("liveCompact")) containsString:NS("disconnected")]); + gTestBluetooth = @[@{NS("name"): NS("Sam's Apple Watch"), NS("connected"): @YES, NS("isAppleAudioDevice"): @NO, NS("productId"): @0, NS("batteryLevel"): @0, NS("majorClass"): @0}]; + TestReset(); PollAudioDevice(); + check("a watch isn't headphones", gAudioDevice == nil); + gTestBluetooth = nil; gAudioDevice = nil; + NSDictionary *live = @{NS("isEnabled"): @YES, NS("backgroundActivityIdentifier"): ActivityID("ScreenReplayRecording")}; + check("activity reading finds the id", [ActivityInData(@{NS("backgroundActivityEntry"): live}) hasSuffix:NS("Recording")]); + check("stock pills: recording taken, navigation left alone", IsletTakesActivity(ActivityID("ScreenReplayRecording")) && !IsletTakesActivity(ActivityID("Navigation"))); + check("activity reading tolerates no entry", ActivityInData([NSDictionary new]) == nil); + TestReset(); UpdateActivities([NSSet setWithObject:ActivityID("Tethering")]); + check("hotspot activity shows", gOngoing[NS("hotspot")] != nil); + UpdateActivities([NSSet set]); check("and clears", gOngoing[NS("hotspot")] == nil); + TestReset(); Demo(2); Demo(9); gExpandedKey = nil; Refresh(NO); + check("call outranks timer", [S(gCur, "key") isEqual:NS("demo-call")]); + check("bubble shows the second activity", [gBubbleKey isEqual:NS("demo-timer")]); + TestSnap(host, dir, NS("two-activities")); + OnSwipeUp(); + check("swipe up can't hide a call", gHideUntil == nil && gCur != nil); + [gOngoing removeObjectForKey:NS("demo-call")]; Refresh(NO); + check("timer takes over when the call ends", [S(gCur, "key") isEqual:NS("demo-timer")]); + OnSwipeUp(); + check("swipe up on compact hides", gHideUntil != nil && gCur == nil); + Demo(5); check("popups stay away while hidden", gTransient == nil); + Demo(20); check("critical popups still come through", gTransient != nil); + gTransient = nil; [gQueue removeAllObjects]; + gHideUntil = [NSDate dateWithTimeIntervalSinceNow:-1]; Refresh(NO); + check("island returns after the hide", [S(gCur, "key") isEqual:NS("demo-timer")]); + Demo(3); [gOngoing[NS("demo-music")] removeObjectForKey:NS("autoExpandUntil")]; Refresh(NO); + NSString *before = S(gCur, "key"); CycleActivity(); + check("sideways swipe switches activity", ![S(gCur, "key") isEqual:before]); + NSString *pin = S(gCur, "key"); Refresh(NO); + check("the pick sticks", [S(gCur, "key") isEqual:pin]); + OnTap(); check("tap unfolds", gExp); + gFoldAt = 1; Tick(); check("unfolded card folds itself", !gExp); + Act *keep = gCur; Act *same = [gOngoing[S(keep, "key")] mutableCopy]; same[NS("liveCompact")] = nil; + SetOngoing(same, S(keep, "key")); check("refreshing an activity swaps data without a rebuild", gCur == same); + check("symbols are cached", Symbol(NS("timer"), 17, UIColor.redColor) == Symbol(NS("timer"), 17, UIColor.redColor)); + check("Ring and NamedColor", Ring(20, 50, NamedColor(NS("mint"))).layer.sublayers.count == 2); + phase = 1; return; + } + // Batteries, with dictionaries standing in for BCBatteryDevice. + NSDictionary *(^dev)(const char *, const char *, int, BOOL) = HB(^NSDictionary *(const char *n, const char *g, int pct, BOOL ch) { (void)_islet_z; + return @{NS("isInternal"): @NO, NS("name"): NS(n), NS("groupName"): NS(g), NS("percentCharge"): @(pct), NS("isCharging"): @(ch), NS("productIdentifier"): @8212, NS("modelNumber"): NS("")}; + }); + if (i == count) { + TestReset(); + gTestDevices = @[dev("Sam's Apple Watch", "", 21, NO)]; + CheckBatteries(); + gTestDevices = @[dev("Sam's Apple Watch", "", 20, NO)]; + CheckBatteries(); + i++; return; + } + if (i == count + 1) { + check("watch crossing 20% pops up", [S(gTransient, "subtitle") isEqual:NS("Low Battery")] && [S(gTransient, "title") containsString:NS("Watch")]); + gTransient = nil; [gQueue removeAllObjects]; + NSDictionary *w = dev("Sam's Apple Watch", "", 20, NO); + gTestDevices = @[w, dev("Sam's AirPods Left", "Sam's AirPods", 80, NO), dev("Sam's AirPods Right", "Sam's AirPods", 82, NO), dev("Sam's AirPods Case", "Sam's AirPods", 55, NO)]; + CheckBatteries(); + i++; return; + } + if (i == count + 2) { + check("new AirPods pop up connected", [S(gTransient, "subtitle") isEqual:NS("Connected")]); + NSArray *b = gTransient[NS("batteries")]; + check("left and right merge, case stays apart", b.count == 2 && [b[0][NS("pct")] intValue] == 80 && [b[1][NS("label")] isEqual:NS("Case")]); + check("AirPods Pro id picks its icon", [DeviceSymbol(NS("x"), 8212, NO) isEqual:NS("airpodspro")] && [DeviceSymbol(NS("Sam's Apple Watch"), 0, NO) isEqual:NS("applewatch")]); + gTransient = nil; [gQueue removeAllObjects]; + gTestDevices = @[dev("Sam's Apple Watch", "", 20, NO), dev("Sam's AirPods Left", "Sam's AirPods", 80, NO), dev("Sam's AirPods Right", "Sam's AirPods", 82, NO), dev("Sam's AirPods Case", "Sam's AirPods", 20, NO)]; + CheckBatteries(); + i++; return; + } + if (i == count + 3) { + check("the case alerts on its own at 20%", [S(gTransient, "title") hasSuffix:NS("Case")] && [S(gTransient, "subtitle") isEqual:NS("Low Battery")]); + gTransient = nil; [gQueue removeAllObjects]; + gTestDevices = @[dev("AirPods Left", "AirPods", 80, NO), dev("AirPods Right", "AirPods", 40, NO)]; + NSArray *items = GroupNamed(BatteryGroups(), NS("AirPods"))[NS("items")]; + check("left and right stay apart when they differ", items.count == 2 && [items[0][NS("label")] isEqual:NS("L")]); + check("lowest bud counts as the level", [GroupNamed(BatteryGroups(), NS("AirPods"))[NS("low")] intValue] == 40); + } + [out appendString:[checks componentsJoinedByString:NS("\n")]]; + [out appendFormat:NS("\nDONE %d steps\n"), count]; + [out writeToFile:[dir stringByAppendingPathComponent:NS("status.txt")] atomically:YES encoding:NSUTF8StringEncoding error:nil]; + exit(0); + } @catch (NSException *e) { + [[NSString stringWithFormat:NS("EXCEPTION at step %d: %@\n%@"), i, e, out] writeToFile:[dir stringByAppendingPathComponent:NS("status.txt")] atomically:YES encoding:NSUTF8StringEncoding error:nil]; + exit(1); + } + })]; +} + +#ifdef ISLET_FILM +#pragma mark - Film (tools/film only, never in a package) + +// Plays every activity through the real code on a mock Lock Screen and saves what Core Animation shows at each moment, so +// springs and morphs are the real ones. The bars are fed made-up levels here: there's no audio in a throwaway process. +static NSString *gFilmDir; +static NSMutableString *gFilmLog; +static BOOL gFilmAudio; +#define FILM_SCALE 1.5 + +static void At(double secs, void (^b)(void)) { + int _islet_z = 0; (void)_islet_z; + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(secs * NSEC_PER_SEC)), dispatch_get_main_queue(), b); +} + +static UIView *FilmScreen(void) { + int _islet_z = 0; (void)_islet_z; + CGRect r = CGRectMake(0, 0, 414, 896); + UIView *v = [[UIView alloc] initWithFrame:r]; + CAGradientLayer *g = [CAGradientLayer layer]; + g.frame = r; g.startPoint = CGPointMake(0.1, 0); g.endPoint = CGPointMake(0.9, 1); + g.colors = @[(id)[UIColor colorWithRed:0.16 green:0.2 blue:0.52 alpha:1].CGColor, (id)[UIColor colorWithRed:0.42 green:0.2 blue:0.62 alpha:1].CGColor, (id)[UIColor colorWithRed:0.93 green:0.45 blue:0.45 alpha:1].CGColor]; + [v.layer addSublayer:g]; + UILabel *t = Label(NS("9:41"), [UIFont systemFontOfSize:15 weight:UIFontWeightSemibold], UIColor.whiteColor); + t.textAlignment = NSTextAlignmentCenter; t.frame = CGRectMake(24, 10, 70, 20); t.tag = 7; [v addSubview:t]; + CGFloat x = 310; + for (NSString *n in @[NS("cellularbars"), NS("wifi"), NS("battery.100percent")]) { + UIImageView *iv = [[UIImageView alloc] initWithImage:Symbol(n, 12, UIColor.whiteColor)]; + iv.contentMode = UIViewContentModeScaleAspectFit; iv.frame = CGRectMake(x, 11, [n hasPrefix:NS("battery")] ? 30 : 22, 18); iv.tag = 7; [v addSubview:iv]; + x += [n hasPrefix:NS("wifi")] ? 26 : 26; + } + UILabel *clock = Label(NS("9:41"), [UIFont systemFontOfSize:84 weight:UIFontWeightThin], UIColor.whiteColor); + clock.textAlignment = NSTextAlignmentCenter; clock.frame = CGRectMake(0, 280, 414, 100); clock.tag = 7; [v addSubview:clock]; + UIView *notch = [[UIView alloc] initWithFrame:CGRectMake(207 - 105, 0, 210, 30)]; + notch.backgroundColor = UIColor.blackColor; notch.layer.cornerRadius = 18; notch.layer.maskedCorners = kCALayerMinXMaxYCorner | kCALayerMaxXMaxYCorner; notch.layer.cornerCurve = kCACornerCurveContinuous; + [v addSubview:notch]; + return v; +} + +static void FilmMusic(void) { + int _islet_z = 0; (void)_islet_z; + Demo(3); + Act *a = gOngoing[NS("demo-music")]; + [a removeObjectForKey:NS("autoExpandUntil")]; + a[NS("title")] = NS("Harbour Lights"); a[NS("subtitle")] = NS("The Notch Band"); + a[NS("liveBig")] = HB(^NSString *{ (void)_islet_z; return NS("-2:14"); }); + gFilmAudio = YES; gCur = nil; Refresh(YES); +} + +static void FilmNotification(void) { + int _islet_z = 0; (void)_islet_z; + UIImage *ic = [UIImage _applicationIconImageForBundleIdentifier:NS("com.apple.MobileSMS") format:2 scale:3] ?: Symbol(NS("message.fill"), 22, UIColor.greenColor); + NSDictionary *content = @{NS("title"): NS("Sam"), NS("message"): NS("Dinner at 8?"), NS("header"): NS("Messages"), NS("icons"): @[ic]}; + NSDictionary *req = @{NS("content"): content, NS("sectionIdentifier"): NS("com.apple.MobileSMS"), NS("supplementaryActions"): @[@{NS("title"): NS("Reply"), NS("behavior"): @1}, @{NS("title"): NS("Mark as Read"), NS("behavior"): @0}]}; + PostTransient(NotificationAct(req)); +} + +typedef struct { const char *group, *title; double secs; int code; } FilmScene; +static const FilmScene gFilmScenes[] = { + {"Battery", "Charging", 2.2, 4}, {"Accessories", "AirPods connect", 2.6, 19}, {"Music", "Now Playing", 2.6, 100}, {"Music", "Live lyrics", 2.2, 101}, + {"Activities", "Timer", 2.4, 102}, {"Activities", "Calls", 2.4, 103}, {"Activities", "Flashlight", 2.4, 14}, {"Activities", "Screen recording", 2.4, 104}, + {"System", "Ringer", 1.7, 31}, {"System", "Silent mode", 1.9, 5}, {"System", "Volume", 2.0, 105}, {"System", "Focus", 1.6, 13}, {"System", "Airplane mode", 1.6, 12}, + {"System", "Wi‑Fi", 1.4, 106}, {"System", "Cellular data", 1.4, 107}, {"System", "Bluetooth", 1.4, 108}, {"System", "Rotation lock", 1.5, 32}, {"System", "AirDrop", 1.5, 33}, + {"System", "Low Power Mode", 1.5, 25}, {"System", "Face ID unlock", 1.4, 26}, + {"Battery", "Apple Watch low battery", 2.4, 20}, {"Battery", "iPhone low battery", 2.4, 21}, {"Battery", "Fully charged", 2.2, 22}, + {"Notifications", "Banners in the island", 2.0, 1}, {"Notifications", "Instant swap", 2.2, 109}, {"Notifications", "Actions and reply", 2.6, 110}, + {"Activities", "Calendar", 2.2, 111}, {"Activities", "Personal Hotspot", 1.8, 27}, {"Activities", "Screen mirroring", 1.8, 28}, {"Activities", "Microphone", 1.6, 29}, + {"Accessories", "Ping from Apple Watch", 2.6, 35}, + {"Gestures", "Two activities", 2.8, 112}, {"Gestures", "Swipe to hide", 3.0, 113}, + {"Landscape", "Clings to the notch", 3.4, 114}, {"Landscape", "Either side", 3.0, 115}, +}; + +static void FilmPlay(int code) { + int _islet_z = 0; (void)_islet_z; + switch (code) { + case 100: FilmMusic(); At(0.9, HB(^{ (void)_islet_z; gExpandedKey = NS("demo-music"); Refresh(YES); })); break; + case 101: + FilmMusic(); + gOngoing[NS("demo-music")][NS("liveCompact")] = HB(^NSString *{ (void)_islet_z; return CACurrentMediaTime() - gAmpsAt < 9 && fmod(CACurrentMediaTime(), 2.2) < 1.1 ? NS("Every light along the water") : NS("is calling me back home"); }); + gLyrics = ParseLRC(NS("[00:00.00]line")); gLyricsOn = YES; gCur = nil; Refresh(YES); break; + case 102: Demo(2); At(1.0, HB(^{ (void)_islet_z; gExpandedKey = NS("demo-timer"); Refresh(YES); })); break; + case 103: Demo(9); At(1.0, HB(^{ (void)_islet_z; gExpandedKey = NS("demo-call"); Refresh(YES); })); break; + case 104: Demo(17); At(1.0, HB(^{ (void)_islet_z; gExpandedKey = NS("record"); Refresh(YES); })); break; + case 105: for (int i = 0; i < 7; i++) { float v = 0.3 + i * 0.09; At(i * 0.14, HB(^{ (void)_islet_z; ShowVolume(v); })); } break; + case 106: ShowRadio(NS("wifi"), NS("wifi"), NS("Wi‑Fi On"), YES, NamedColor(NS("blue"))); break; + case 107: ShowRadio(NS("data"), NS("antenna.radiowaves.left.and.right"), NS("Cellular Data On"), YES, NamedColor(NS("green"))); break; + case 108: ShowRadio(NS("btpower"), NS("wave.3.right"), NS("Bluetooth On"), YES, NamedColor(NS("blue"))); break; + case 109: Demo(1); At(0.9, HB(^{ (void)_islet_z; FilmNotification(); })); break; + case 110: FilmNotification(); break; + case 111: Demo(23); break; + case 112: Demo(2); Demo(9); Demo(34); [gOngoing[NS("demo-call")] setObject:@1 forKey:NS("priority")]; Refresh(YES); At(1.3, HB(^{ (void)_islet_z; CycleActivity(); })); break; + case 113: FilmMusic(); At(0.9, HB(^{ (void)_islet_z; OnSwipeUp(); gHideUntil = [NSDate dateWithTimeIntervalSinceNow:1.1]; At(1.15, HB(^{ (void)_islet_z; gHideUntil = nil; Refresh(YES); })); })); break; + case 114: SetMode(1); Demo(2); At(1.2, HB(^{ (void)_islet_z; gExpandedKey = NS("demo-timer"); Refresh(YES); })); break; + case 115: SetMode(2); FilmMusic(); At(1.2, HB(^{ (void)_islet_z; gExpandedKey = NS("demo-music"); Refresh(YES); })); break; + case 4: // no battery in a throwaway process + Demo(4); + gTransient[NS("liveCompact")] = HB(^NSString *{ (void)_islet_z; return NS("82%"); }); gTransient[NS("liveBig")] = gTransient[NS("liveCompact")]; + gTransient[NS("liveProgress")] = HB(^double { (void)_islet_z; return 0.82; }); + gLive.text = NS("82%"); break; + default: Demo(code); + } +} + +static void Film(NSString *dir) { + int _islet_z = 0; (void)_islet_z; + gPrefs = [NSDictionary new]; + gFilmDir = dir; gFilmLog = [NSMutableString new]; + InitState(); UpdateGeometry(); + UIView *screen = FilmScreen(); + CreateIsland(screen); + int count = sizeof(gFilmScenes) / sizeof(gFilmScenes[0]); + int limit = getenv("ISLET_FILM_SCENES") ? MIN(atoi(getenv("ISLET_FILM_SCENES")), count) : count; + // A local context is what makes Core Animation run the animations at all in a process with no display. + static id context; + context = ((id (*)(id, SEL, id))objc_msgSend)(NSClassFromString(NS("CAContext")), NSSelectorFromString(NS("localContextWithOptions:")), [NSDictionary new]); + [context setValue:screen.layer forKey:NS("layer")]; + Every(0.05, 0, HB(^{ (void)_islet_z; + if (!gFilmAudio) return; + NSMutableArray *amps = [NSMutableArray new]; + double t = CACurrentMediaTime(); + for (int i = 0; i < 12; i++) [amps addObject:@(0.2 + 0.7 * fabs(sin(t * (2.1 + i * 0.37) + i)))]; + gAmps = amps; gAmpsAt = t; VizStart(); + })); + Every(0.5, 0, HB(^{ (void)_islet_z; Tick(); })); + Every(0.25, 0, HB(^{ (void)_islet_z; if (ShowsLyrics(gCur)) Tick(); })); + dispatch_queue_t enc = dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0); + dispatch_semaphore_t slots = dispatch_semaphore_create(4); + UIGraphicsImageRendererFormat *f = [UIGraphicsImageRendererFormat new]; f.scale = FILM_SCALE; f.opaque = YES; + UIGraphicsImageRenderer *r = [[UIGraphicsImageRenderer alloc] initWithSize:screen.bounds.size format:f]; + CFTimeInterval t0 = CACurrentMediaTime(); + __block int frame = 0, scene = -1; + __block CFTimeInterval sceneEnd = 0; + NSMutableString *log = gFilmLog; + Every(1.0 / 30, 0, HB(^{ (void)_islet_z; + CFTimeInterval now = CACurrentMediaTime(); + if (now >= sceneEnd) { + scene++; + if (scene >= limit) { + for (int i = 0; i < 4; i++) dispatch_semaphore_wait(slots, DISPATCH_TIME_FOREVER); + [log writeToFile:[gFilmDir stringByAppendingPathComponent:NS("frames.txt")] atomically:YES encoding:NSUTF8StringEncoding error:nil]; + exit(0); + } + FilmScene s = gFilmScenes[scene]; + gFilmAudio = NO; gAmps = nil; TestReset(); gCur = nil; + for (UIView *v in screen.subviews) if (v.tag == 7) v.hidden = s.code == 114 || s.code == 115; + [log appendFormat:NS("scene %.3f %d %@|%@\n"), now - t0, s.code, NS(s.group), NS(s.title)]; + sceneEnd = now + s.secs; + FilmPlay(s.code); + } + [CATransaction flush]; + if (dispatch_semaphore_wait(slots, DISPATCH_TIME_NOW)) return; + CALayer *live = screen.layer.presentationLayer ?: screen.layer; + UIImage *img = [r imageWithActions:HB(^(UIGraphicsImageRendererContext *c) { (void)_islet_z; [live renderInContext:c.CGContext]; })]; + int n = frame++; + [log appendFormat:NS("frame %.3f %d\n"), now - t0, n]; + dispatch_async(enc, HB(^{ (void)_islet_z; + [UIImageJPEGRepresentation(img, 0.88) writeToFile:[gFilmDir stringByAppendingPathComponent:[NSString stringWithFormat:NS("f%05d.jpg"), n]] atomically:NO]; + dispatch_semaphore_signal(slots); + })); + })); +} +#endif + +#pragma mark - Hooks + +static void Swizzle(Class c, SEL s, IMP imp, IMP *orig) { + Method m = class_getInstanceMethod(c, s); + if (!m) { LOG("missing %@ %@", c, NSStringFromSelector(s)); return; } + *orig = method_getImplementation(m); + method_setImplementation(m, imp); +} + +// Only swizzles a method that is there and returns what the hook expects: an OS update must not become a crash. +static void SwizzleChecked(Class c, NSString *sel, char ret, IMP imp, IMP *orig) { + if (!c || *orig) return; + Method m = class_getInstanceMethod(c, NSSelectorFromString(sel)); + if (m && method_getTypeEncoding(m)[0] == ret) Swizzle(c, NSSelectorFromString(sel), imp, orig); + else LOG("hook skipped: %@ %@ (%s)", c, sel, m ? method_getTypeEncoding(m) : "missing"); +} + +// Notifications are taken at the last step, after iOS has already said yes: SBBannerAuthority is asked just before a +// banner goes up, once foreground and in-chat suppression, per-app banner settings, Focus and Screen Time have all had +// their say. Whatever reaches it is what stock would really show, so Islet needs no rules of its own about any of that. +static id gBannerDest; +static NSMutableArray *gPendingRequests; // handed over by the destination, in order, until their banner asks to post + +static Act *NotificationAct(id request) { + id content = [request valueForKey:NS("content")]; + NSString *bid = [request valueForKey:NS("sectionIdentifier")]; + NSString *title = [content valueForKey:NS("title")], *msg = [content valueForKey:NS("message")], *sub = [content valueForKey:NS("subtitle")]; + NSString *hdr = [content valueForKey:NS("header")] ?: [content valueForKey:NS("defaultHeader")]; + NSCharacterSet *ws = NSCharacterSet.whitespaceAndNewlineCharacterSet; + title = [title stringByTrimmingCharactersInSet:ws]; msg = [msg stringByTrimmingCharactersInSet:ws]; sub = [sub stringByTrimmingCharactersInSet:ws]; + Act *a = NewAct(NS("notif"), NS("notif")); + a[NS("ttl")] = @5.5; a[NS("expandFirst")] = @YES; a[NS("request")] = request; + if (bid) a[NS("bundleID")] = bid; + a[NS("subtitle")] = hdr.length ? hdr : (bid ?: NS("")); + a[NS("title")] = title.length ? title : (sub.length ? sub : NS("")); + a[NS("body")] = msg.length ? (title.length && sub.length ? [NSString stringWithFormat:NS("%@\n%@"), sub, msg] : msg) : (title.length ? NS("") : (sub ?: NS(""))); + if (!S(a, "title").length && !S(a, "body").length) a[NS("title")] = S(a, "subtitle").length ? S(a, "subtitle") : NS("Notification"); + // iOS resolves the icon for the content itself, system senders like screen recording included. + id icons = [content valueForKey:NS("icons")]; + UIImage *ic = [icons isKindOfClass:NSArray.class] ? [icons firstObject] : nil; + if (![ic isKindOfClass:UIImage.class]) ic = [content valueForKey:NS("icon")]; + if (![ic isKindOfClass:UIImage.class] && bid) ic = [UIImage _applicationIconImageForBundleIdentifier:bid format:2 scale:UIScreen.mainScreen.scale]; + a[NS("icon")] = ic ?: Symbol(NS("bell.fill"), 22, UIColor.whiteColor); + UIImage *thumb = [content valueForKey:NS("attachmentImage")]; + if ([thumb isKindOfClass:UIImage.class]) a[NS("thumbnail")] = thumb; + NSMutableArray *actions = [NSMutableArray new]; + id acts = [request valueForKey:NS("supplementaryActions")]; + if ([acts isKindOfClass:NSArray.class]) for (id x in acts) if ([[x valueForKey:NS("title")] length]) [actions addObject:x]; + if (actions.count) { a[NS("actions")] = actions; a[NS("ttl")] = @8; } + return a; +} + +// The stock expanded view, reply field and all. +static void ExpandNotification(Act *a) { + @try { + if (gBannerDest) ((void (*)(id, SEL, id))objc_msgSend)(gBannerDest, NSSelectorFromString(NS("presentModalBannerAndExpandForNotificationRequest:")), a[NS("request")]); + } @catch (NSException *e) { LOG("expand notification: %@", e); } +} + +static void RunNotificationAction(id action, Act *a) { + int _islet_z = 0; (void)_islet_z; + @try { + id runner = [action valueForKey:NS("actionRunner")]; + if (!runner) { if (S(a, "bundleID")) OpenApp(S(a, "bundleID")); return; } + id origin = [gBannerDest valueForKey:NS("identifier")]; + ((void (*)(id, SEL, id, id, id, id, id))objc_msgSend)(runner, NSSelectorFromString(NS("executeAction:fromOrigin:endpoint:withParameters:completion:")), action, origin, nil, [NSDictionary new], HB(^(BOOL ok) { (void)_islet_z; })); + } @catch (NSException *e) { LOG("notification action: %@", e); if (S(a, "bundleID")) OpenApp(S(a, "bundleID")); } +} + +// Buttons on the island card. Anything that needs typing or authentication belongs to the stock view. +static void NotificationButton(int i) { + Act *a = gTransient; + NSArray *actions = a[NS("actions")]; + if (i < 0 || i >= (int)actions.count) return; + id action = actions[i]; + if ([[action valueForKey:NS("behavior")] intValue] != 0 || [[action valueForKey:NS("requiresAuthentication")] boolValue]) ExpandNotification(a); + else RunNotificationAction(action, a); + EndTransient(a); +} + +// The stock silent-switch pill: skip it so only the island answers the switch (volume HUD is untouched). +static void hook_mute(id self, SEL _cmd, BOOL arg) { + if (gWindow && !Suppressed(NO) && PrefBool(NS("hideStockHUD"), YES) && PrefBool(NS("ringer"), YES)) return; + ((void (*)(id, SEL, BOOL))orig_mute)(self, _cmd, arg); +} + +// Stock coloured clock pills (recording red, call green...): turned off while Islet is showing that same activity. +// The legacy UIKit item and the StatusKit one iOS 18's SpringBoard uses take the same arguments. +// Hiding only the pill wasn't enough: the entry stays in the status bar data, so the bar keeps its "clock inside a pill" +// layout (STUIStatusBarTimeItem's pillTimeView) with no pill behind it, which is the odd clock. Taking the entry out of +// the data means the bar never knows the activity exists. Decided by identifier and not by whether Islet is showing it +// yet, so nothing can slip through while an activity starts or ends. +static void NoteActivity(NSString *ident) { + int _islet_z = 0; (void)_islet_z; + static NSString *last; + if (gActivityDomainHasData || ident == last || [ident isEqual:last]) return; + last = ident; + NSSet *ids = ident ? [NSSet setWithObject:ident] : [NSSet set]; + dispatch_async(dispatch_get_main_queue(), HB(^{ (void)_islet_z; UpdateActivities(ids); })); +} + +static id FilterEntry(id entry) { + if (!entry || !gWindow || ![entry respondsToSelector:NSSelectorFromString(NS("backgroundActivityIdentifier"))]) return entry; + @try { + BOOL enabled = [[entry valueForKey:NS("isEnabled")] boolValue]; + NSString *ident = [entry valueForKey:NS("backgroundActivityIdentifier")]; + NoteActivity(enabled ? ident : nil); + return enabled && ident && IsletTakesActivity(ident) ? nil : entry; + } @catch (NSException *e) { return entry; } +} +static id hook_entry(id self, SEL _cmd) { return FilterEntry(((id (*)(id, SEL))orig_entry)(self, _cmd)); } +static id hook_uientry(id self, SEL _cmd) { return FilterEntry(((id (*)(id, SEL))orig_uientry)(self, _cmd)); } + +static NSString *ActivityInData(id data) { + @try { + id entry = orig_entry && [data isKindOfClass:NSClassFromString(NS("STStatusBarData"))] ? ((id (*)(id, SEL))orig_entry)(data, NSSelectorFromString(NS("backgroundActivityEntry"))) + : [data valueForKey:NS("backgroundActivityEntry")]; + if (entry && ![[entry valueForKey:NS("isEnabled")] boolValue]) return nil; + return [entry valueForKey:NS("backgroundActivityIdentifier")]; + } @catch (NSException *e) { return nil; } +} + +// Second line, should an item ever read the entry some other way. +static BOOL HidePill(id data) { + NSString *ident = gWindow ? ActivityInData(data) : nil; + return ident && IsletTakesActivity(ident); +} +static BOOL hook_pill(id self, SEL _cmd, id item, id data) { + return HidePill(data) ? NO : ((BOOL (*)(id, SEL, id, id))orig_pill)(self, _cmd, item, data); +} +static BOOL hook_stpill(id self, SEL _cmd, id item, id data) { + return HidePill(data) ? NO : ((BOOL (*)(id, SEL, id, id))orig_stpill)(self, _cmd, item, data); +} + +// The call pill as data: with no descriptors, SpringBoard publishes no call activity, so apps' own status bars drop it too. +static void hook_callpill(id self, SEL _cmd, id descriptors) { + BOOL hide = gWindow && !IsLandscape() && !gFullscreenVideo && PrefBool(NS("enabled"), YES) && PrefBool(NS("hideStatusPills"), YES) && PrefBool(NS("calls"), YES); + id none = [descriptors isKindOfClass:NSSet.class] ? (id)NSSet.set : (id)NSArray.array; + ((void (*)(id, SEL, id))orig_callpill)(self, _cmd, hide ? none : descriptors); +} + +static void hook_banner(id self, SEL _cmd, id request) { + gBannerDest = self; + if (!gPendingRequests) gPendingRequests = [NSMutableArray new]; + if (gPendingRequests.count > 8) [gPendingRequests removeObjectAtIndex:0]; + [gPendingRequests addObject:request]; + ((void (*)(id, SEL, id))orig_banner)(self, _cmd, request); +} + +// Sticky alerts wait for an answer and critical ones must be seen, so those keep the stock banner, as does anything arriving +// while the island is out of the way. Nothing can be lost: refusing here is the path stock uses itself (-1 is its "drop", +// as for banners during screen sharing), and the notification stays in Notification Center. +static BOOL IslandTakesNotification(id presentable) { + if (!gWindow || !PrefBool(NS("notifications"), YES) || !PrefBool(NS("hideBanners"), YES) || Suppressed(NO)) return NO; + if (![[presentable valueForKey:NS("requesterIdentifier")] isEqual:NS("com.apple.UserNotificationsKit")]) return NO; + id request = gPendingRequests.firstObject; + if (!request) return NO; + [gPendingRequests removeObjectAtIndex:0]; + id opts = [request valueForKey:NS("options")]; + if (opts && ![[opts valueForKey:NS("dismissAutomatically")] boolValue]) return NO; + if ([[request valueForKey:NS("isCriticalAlert")] boolValue]) return NO; + PostTransient(NotificationAct(request)); + return YES; +} + +static long hook_shouldpost(id self, SEL _cmd, id presentable, id info, id *reason) { + long decision = ((long (*)(id, SEL, id, id, id *))orig_shouldpost)(self, _cmd, presentable, info, reason); + if (decision != 0) return decision; + @try { + if (IslandTakesNotification(presentable)) { if (reason) *reason = NS("Islet"); return -1; } + } @catch (NSException *e) { LOG("notification: %@", e); } + return decision; +} + +// Stock banners that do appear start below the island instead of underneath it. +static double hook_inset(id self, SEL _cmd, id presenter) { + double v = ((double (*)(id, SEL, id))orig_inset)(self, _cmd, presenter); + if (!gWindow || gMode || gIsland.alpha < 0.01 || !PrefBool(NS("bannerOffset"), YES)) return v; + return MAX(v, gIsland.bounds.size.height + 6); +} + +// The lock glyph, driven by authentication itself and not by anything about the lock screen UI: Notification Center is the +// same cover sheet, so every UI signal also fires for pulling it down. +static void hook_auth(id self, SEL _cmd, long state) { + int _islet_z = 0; (void)_islet_z; + static int last = -1; + ((void (*)(id, SEL, long))orig_auth)(self, _cmd, state); + int authed = ((BOOL (*)(id, SEL))objc_msgSend)(self, NSSelectorFromString(NS("isAuthenticatedCached"))); + BOOL changed = last >= 0 && authed != last; + last = authed; + if (!changed || gScreenOff || !gWindow || !PrefBool(NS("lockPill"), NO)) return; + dispatch_async(dispatch_get_main_queue(), HB(^{ (void)_islet_z; + ShowStatusPill(NS("lock"), authed ? NS("lock.open.fill") : NS("lock.fill"), authed ? NS("Unlocked") : NS("Locked"), UIColor.whiteColor, 1.2); + })); +} + +// The moments each state really changes, so popups are on time instead of waiting for a poll. +static void hook_airplane(id self, SEL _cmd) { ((void (*)(id, SEL))orig_airplane)(self, _cmd); ScheduleRadioCheck(); } +static void hook_wifi(id self, SEL _cmd) { ((void (*)(id, SEL))orig_wifi)(self, _cmd); ScheduleRadioCheck(); } +static void hook_dataitem(id self, SEL _cmd) { ((void (*)(id, SEL))orig_dataitem)(self, _cmd); ScheduleRadioCheck(); } +static void hook_telephony(id self, SEL _cmd) { ((void (*)(id, SEL))orig_telephony)(self, _cmd); ScheduleRadioCheck(); } +static void hook_focus(id self, SEL _cmd, id state) { + int _islet_z = 0; (void)_islet_z; + ((void (*)(id, SEL, id))orig_focus)(self, _cmd, state); + if (gSQ) dispatch_async(gSQ, HB(^{ (void)_islet_z; PollFocus(); })); +} +static void hook_torch(id self, SEL _cmd, unsigned long level) { + int _islet_z = 0; (void)_islet_z; + ((void (*)(id, SEL, unsigned long))orig_torch)(self, _cmd, level); + if (gSQ) dispatch_async(gSQ, HB(^{ (void)_islet_z; CheckFlashlight(); })); +} +static void hook_rotation(id self, SEL _cmd, id changes) { + int _islet_z = 0; (void)_islet_z; + ((void (*)(id, SEL, id))orig_rotation)(self, _cmd, changes); + if (gSQ) dispatch_async(gSQ, HB(^{ (void)_islet_z; CheckRotation(); })); +} + +// The volume HUD, drawn in the island. One card for a whole run of presses: it stays up and its bar moves. +static int gVolumeGen; +static void ShowVolume(float v) { + int _islet_z = 0; (void)_islet_z; + gVolume = v; + BOOL open = [S(gTransient, "key") isEqual:NS("volume")]; + if (!open) { + UIColor *white = UIColor.whiteColor; + Act *a = NewAct(NS("volume"), NS("volume")); + a[NS("tint")] = white; a[NS("ttl")] = @30; + a[NS("icon")] = Symbol(v <= 0.001 ? NS("speaker.slash.fill") : NS("speaker.wave.2.fill"), 15, white); + a[NS("liveProgress")] = HB(^double { (void)_islet_z; return gVolume; }); + if (gTransient) { gTransient = nil; } + PresentTransient(a); + } else Tick(); + Act *a = gTransient; + int gen = ++gVolumeGen; + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.6 * NSEC_PER_SEC)), dispatch_get_main_queue(), HB(^{ (void)_islet_z; if (gen == gVolumeGen) EndTransient(a); })); +} + +static void hook_volume(id self, SEL _cmd, float v) { + if (gWindow && PrefBool(NS("volumeHUD"), YES) && !Suppressed(NO)) { ShowVolume(v); return; } + ((void (*)(id, SEL, float))orig_volume)(self, _cmd, v); +} + +// An app starting on the camera or microphone gets a quick popup. Read-only: the stock dots are left alone. +static void hook_sensor(id self, SEL _cmd, id provider) { + int _islet_z = 0; (void)_islet_z; + ((void (*)(id, SEL, id))orig_sensor)(self, _cmd, provider); + if (!gWindow || !PrefBool(NS("sensorPill"), YES)) return; + @try { + static NSMutableSet *active; if (!active) active = [NSMutableSet new]; + NSMutableSet *now = [NSMutableSet new]; + for (id attr in [provider valueForKey:NS("activeCameraAndMicrophoneActivityAttributions")]) { + if ([[attr valueForKey:NS("isSystemService")] boolValue]) continue; + int sensor = [[attr valueForKey:NS("sensor")] intValue]; // 0 camera, 1 microphone + NSString *name = [attr valueForKey:NS("displayName")] ?: NS("An app"); + NSString *k = [NSString stringWithFormat:NS("%@|%d"), name, sensor]; + [now addObject:k]; + if ([active containsObject:k]) continue; + dispatch_async(dispatch_get_main_queue(), HB(^{ (void)_islet_z; + ShowStatusPill(NS("sensor"), sensor ? NS("mic.fill") : NS("camera.fill"), name, NamedColor(sensor ? NS("orange") : NS("green")), 2.0); + })); + } + active = now; + } @catch (NSException *e) { LOG("sensor: %@", e); } +} + +// Every banner on the system, the AirPods "Connected" pill included, comes through SBBannerManager tagged with the +// process that asked for it. Each new requester is noted in /var/mobile/islet-banners.log so a pill can be identified +// after the fact; the ones whose job Islet took over get refused the normal way, as a post that failed. +static BOOL DropBanner(id presentable) { + int _islet_z = 0; (void)_islet_z; + NSString *req = nil; + @try { if ([presentable respondsToSelector:NSSelectorFromString(NS("requesterIdentifier"))]) req = [presentable valueForKey:NS("requesterIdentifier")]; } @catch (NSException *e) {} + if (!gSQ || !req) return NO; + NSString *line = [NSString stringWithFormat:NS("%@ %@\n"), req, NSStringFromClass([presentable class])]; + dispatch_async(gSQ, HB(^{ (void)_islet_z; + static NSMutableSet *seen; if (!seen) seen = [NSMutableSet new]; + if ([seen containsObject:line]) return; + [seen addObject:line]; + NSFileHandle *h = [NSFileHandle fileHandleForWritingAtPath:NS("/var/mobile/islet-banners.log")]; + if (!h) { [line writeToFile:NS("/var/mobile/islet-banners.log") atomically:NO encoding:NSUTF8StringEncoding error:nil]; return; } + [h seekToEndOfFile]; [h writeData:[line dataUsingEncoding:NSUTF8StringEncoding]]; [h closeFile]; + })); + if (!gWindow || !PrefBool(NS("enabled"), YES)) return NO; + // Focus changes announce themselves here with everything the pill needs. + if ([req containsString:NS("com.apple.FocusUI")] && PrefBool(NS("focus"), YES) && !Suppressed(NO)) { + @try { + id d = [presentable valueForKey:NS("activityDescription")]; + BOOL on = [[presentable valueForKey:NS("isActivityEnabled")] boolValue]; + NSString *name = [d valueForKey:NS("activityDisplayName")], *sym = [d valueForKey:NS("activitySymbolImageName")], *tint = [d valueForKey:NS("activityColorName")]; + dispatch_async(dispatch_get_main_queue(), HB(^{ (void)_islet_z; ShowFocus(on, name, sym, tint); })); + return YES; + } @catch (NSException *e) { LOG("focus banner: %@", e); return NO; } + } + if (!PrefBool(NS("hideAccessoryBanners"), YES) || !PrefBool(NS("bluetooth"), YES) || Suppressed(NO)) return NO; + NSArray *blocked = Pref(NS("blockedBanners")) ?: @[NS("com.apple.BluetoothUIService"), NS("com.apple.Sharing.SharingHUDService")]; + return [blocked containsObject:req]; +} + +static BOOL hook_presentable(id self, SEL _cmd, id presentable, unsigned long opts, id info, id *err) { + if (DropBanner(presentable)) return NO; + return ((BOOL (*)(id, SEL, id, unsigned long, id, id *))orig_presentable)(self, _cmd, presentable, opts, info, err); +} + +static BOOL hook_listener(id self, SEL _cmd, id listener, id presentable, unsigned long opts, id info, id *err) { + if (DropBanner(presentable)) return NO; + return ((BOOL (*)(id, SEL, id, id, unsigned long, id, id *))orig_listener)(self, _cmd, listener, presentable, opts, info, err); +} + +static void InstallHooks(void) { + Class rh = NSClassFromString(NS("SBRingerHUDViewController")); + if (rh && !orig_mute) Swizzle(rh, NSSelectorFromString(NS("presentForMuteChange:")), (IMP)hook_mute, &orig_mute); + SwizzleChecked(NSClassFromString(NS("STStatusBarData")), NS("backgroundActivityEntry"), '@', (IMP)hook_entry, &orig_entry); + SwizzleChecked(NSClassFromString(NS("_UIStatusBarData")), NS("backgroundActivityEntry"), '@', (IMP)hook_uientry, &orig_uientry); + SwizzleChecked(NSClassFromString(NS("_UIStatusBarBackgroundActivityItem")), NS("canEnableDisplayItem:fromData:"), 'B', (IMP)hook_pill, &orig_pill); + SwizzleChecked(NSClassFromString(NS("STUIStatusBarBackgroundActivityItem")), NS("canEnableDisplayItem:fromData:"), 'B', (IMP)hook_stpill, &orig_stpill); + SwizzleChecked(NSClassFromString(NS("SBStatusBarStateAggregator")), NS("_updateCallingBackgroundActivityAssertionsForCallDescriptors:"), 'v', (IMP)hook_callpill, &orig_callpill); + Class bm = NSClassFromString(NS("SBBannerManager")); + SwizzleChecked(bm, NS("postPresentable:withOptions:userInfo:error:"), 'B', (IMP)hook_presentable, &orig_presentable); + SwizzleChecked(bm, NS("bannerSourceListener:requestsPostingPresentable:options:userInfo:error:"), 'B', (IMP)hook_listener, &orig_listener); + SwizzleChecked(bm, NS("presenterMinimumPreferredTopEdgeInset:"), 'd', (IMP)hook_inset, &orig_inset); + SwizzleChecked(NSClassFromString(NS("SBFUserAuthenticationController")), NS("_setAuthState:"), 'v', (IMP)hook_auth, &orig_auth); + SwizzleChecked(NSClassFromString(NS("SBBannerAuthority")), NS("shouldPostPresentable:userInfo:reason:"), 'q', (IMP)hook_shouldpost, &orig_shouldpost); + SwizzleChecked(NSClassFromString(NS("SBAirplaneModeController")), NS("airplaneModeChanged"), 'v', (IMP)hook_airplane, &orig_airplane); + SwizzleChecked(NSClassFromString(NS("SBWiFiManager")), NS("_powerStateDidChange"), 'v', (IMP)hook_wifi, &orig_wifi); + SwizzleChecked(NSClassFromString(NS("SBStatusBarStateAggregator")), NS("_updateDataNetworkItem"), 'v', (IMP)hook_dataitem, &orig_dataitem); + SwizzleChecked(NSClassFromString(NS("SBTelephonyManager")), NS("_updateState"), 'v', (IMP)hook_telephony, &orig_telephony); + SwizzleChecked(NSClassFromString(NS("SBDoNotDisturbStateMonitor")), NS("_noteNewDNDState:"), 'v', (IMP)hook_focus, &orig_focus); + SwizzleChecked(NSClassFromString(NS("SBUIFlashlightController")), NS("_postLevelChangeNotification:"), 'v', (IMP)hook_torch, &orig_torch); + SwizzleChecked(NSClassFromString(NS("SBOrientationLockManager")), NS("_updateLockStateWithChanges:"), 'v', (IMP)hook_rotation, &orig_rotation); + SwizzleChecked(NSClassFromString(NS("SBVolumeControl")), NS("_presentVolumeHUDWithVolume:"), 'v', (IMP)hook_volume, &orig_volume); + SwizzleChecked(NSClassFromString(NS("SBStatusBarStateAggregator")), NS("activityDidChangeForSensorActivityDataProvider:"), 'v', (IMP)hook_sensor, &orig_sensor); + SwizzleChecked(NSClassFromString(NS("SBNotificationBannerDestination")), NS("postNotificationRequest:"), 'v', (IMP)hook_banner, &orig_banner); +} + +// A count only means a crash loop if the failed starts were just now. One left behind by a reboot or a jailbreak restart +// a while ago says nothing, so it must not count against this start. +static int GuardFails(NSString *path) { + NSDate *when = [NSFileManager.defaultManager attributesOfItemAtPath:path error:nil].fileModificationDate; + if (!when || when.timeIntervalSinceNow < -300) return 0; + return [[NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil] intValue]; +} + +static void BeginStart(BOOL springboard) { + int _islet_z = 0; (void)_islet_z; + if (springboard && !getenv("ISLET_BID")) { + // Crash-loop guard: the counter is cleared after 30 s of uptime, well past the island's start at 4 s. Two starts + // in a row that did not survive that long disable Islet until Settings, `isletctl reset` or a reinstall clears it. + NSString *gp = GUARD_PATH; + int fails = GuardFails(gp); + if (fails >= 2) { LOG("disabled by crash-loop guard (%d failed starts); run isletctl reset", fails); return; } + [[NSString stringWithFormat:NS("%d"), fails + 1] writeToFile:gp atomically:YES encoding:NSUTF8StringEncoding error:nil]; + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 30 * NSEC_PER_SEC), dispatch_get_main_queue(), HB(^{ (void)_islet_z; + [NS("0") writeToFile:gp atomically:YES encoding:NSUTF8StringEncoding error:nil]; + })); + } + NSDate *born = NSDate.date; + dispatch_async(dispatch_get_main_queue(), HB(^{ (void)_islet_z; + __block int tries = 0; + [NSTimer scheduledTimerWithTimeInterval:0.5 repeats:YES block:HB(^(NSTimer *t) { (void)_islet_z; + tries++; + if (springboard) InstallHooks(); + // wait until SpringBoard is well past launch before touching windows + BOOL settled = [[NSDate date] timeIntervalSinceDate:born] > (springboard ? 4 : 2); + BOOL ready = settled && UIApplication.sharedApplication.connectedScenes.count > 0 && (!springboard || NSClassFromString(NS("NCNotificationDispatcher"))); + if (ready || tries > 180) { + [t invalidate]; + if (ready) { if (springboard) InstallHooks(); StartIsland(); } + else LOG("gave up waiting for launch"); + } + })]; + })); +} + +__attribute__((constructor)) static void islet_init(void) { + int _islet_z = 0; (void)_islet_z; // keeps blocks off the static-global (unsigned isa) path + LoadPrefs(); + if (getenv("ISLET_SELFTEST")) { NSString *dir = NS(getenv("ISLET_SELFTEST")); dispatch_async(dispatch_get_main_queue(), HB(^{ (void)_islet_z; SelfTest(dir); })); return; } +#ifdef ISLET_FILM + if (getenv("ISLET_FILM")) { NSString *dir = NS(getenv("ISLET_FILM")); dispatch_async(dispatch_get_main_queue(), HB(^{ (void)_islet_z; Film(dir); })); return; } +#endif + NSString *bid = getenv("ISLET_BID") ? NS(getenv("ISLET_BID")) : NSBundle.mainBundle.bundleIdentifier; // env override: used by tests/loadtest + BOOL springboard = [bid isEqual:NS("com.apple.springboard")]; + // testBundle pref: run the island inside a harmless app (e.g. com.apple.Preferences) to try changes safely. + if (!springboard && !(bid && [bid isEqual:Pref(NS("testBundle"))])) return; + if (PrefBool(NS("enabled"), YES)) { BeginStart(springboard); return; } + if (!springboard) return; + // Off at launch: nothing is hooked, nothing runs. Switching it on in Settings starts it from here, no respring. + static int token; + notify_register_dispatch(PREFS_NOTIFICATION, &token, dispatch_get_main_queue(), HB(^(int t) { (void)_islet_z; + LoadPrefs(); + if (!PrefBool(NS("enabled"), YES) || gWindow) return; + notify_cancel(t); + BeginStart(YES); + })); +} diff --git a/src/IsletPing.m b/src/IsletPing.m new file mode 100644 index 0000000..abeaf06 --- /dev/null +++ b/src/IsletPing.m @@ -0,0 +1,55 @@ +// Loaded only into companionfindlocallyd, the daemon that plays the sound when an Apple Watch pings this iPhone. SpringBoard +// never hears about a ping, so this tells the island. Foundation only, and it must stay that small: a daemon has no UIKit. +#import +#import +#import +#import "common.h" + +#define PING_NOTIFICATION "com.astar76.islet.ping" +#define MAX_HOOKS 12 + +static struct { Method method; IMP orig; } gHooks[MAX_HOOKS]; +static int gHookCount, gHooksToken, gFiredToken; +static uint64_t gFired; + +// The handlers take one pointer-sized argument or none, so passing two registers through suits all of them. +static void *ping_hook(id self, SEL _cmd, void *a, void *b) { + notify_set_state(gFiredToken, ++gFired); + notify_post(PING_NOTIFICATION); + Method m = class_getInstanceMethod(object_getClass(self), _cmd); + for (int i = 0; i < gHookCount; i++) + if (gHooks[i].method == m) return ((void *(*)(id, SEL, void *, void *))gHooks[i].orig)(self, _cmd, a, b); + return NULL; +} + +static void HookClass(Class cls) { + static const char *wanted[] = {"playSound:", "playSoundAndFlash:", "playFindLocallySound", "playNearbySound", "flashLights"}; + unsigned n = 0; + Method *list = class_copyMethodList(cls, &n); + for (unsigned i = 0; i < n && gHookCount < MAX_HOOKS; i++) + for (int w = 0; w < 5; w++) { + if (strcmp(sel_getName(method_getName(list[i])), wanted[w])) continue; + gHooks[gHookCount].method = list[i]; + gHooks[gHookCount].orig = method_setImplementation(list[i], (IMP)ping_hook); + gHookCount++; + } + free(list); +} + +// Every class of this executable, found by path: at load time the image index isn't reliably the main program. The count +// goes out over notify state, 1 meaning loaded and each hook adding one, so `isletctl dump` can show what happened in here. +__attribute__((constructor)) static void islet_ping_init(void) { + notify_register_check("com.astar76.islet.ping.hooks", &gHooksToken); + notify_register_check("com.astar76.islet.ping.fired", &gFiredToken); + notify_set_state(gHooksToken, 1); + char path[1024]; uint32_t size = sizeof(path); + if (_NSGetExecutablePath(path, &size)) return; + unsigned count = 0; + const char **names = objc_copyClassNamesForImage(path, &count); + for (unsigned c = 0; names && c < count; c++) { + Class cls = objc_getClass(names[c]); + if (cls) HookClass(cls); + } + free(names); + notify_set_state(gHooksToken, 1 + gHookCount); +} diff --git a/src/IsletPrefs.m b/src/IsletPrefs.m new file mode 100644 index 0000000..955d6d8 --- /dev/null +++ b/src/IsletPrefs.m @@ -0,0 +1,87 @@ +// Islet's page in the Settings app. A PreferenceLoader bundle whose list controller, like everything else built with +// this clang, is created at runtime (see the notes at the top of Islet.m). Crashes here only take down Settings. +#import +#import +#import +#import +#import +#import "common.h" + +#define BUNDLE_PATH (getenv("ISLET_PREFS_BUNDLE") ? NS(getenv("ISLET_PREFS_BUNDLE")) : NS("/var/jb/Library/PreferenceBundles/IsletPrefs.bundle")) + +static id SpecProp(id spec, const char *key) { + return ((id (*)(id, SEL, id))objc_msgSend)(spec, NSSelectorFromString(NS("propertyForKey:")), NS(key)); +} + +static NSString *PrefsPath(void) { return getenv("ISLET_PREFS_FILE") ? NS(getenv("ISLET_PREFS_FILE")) : PREFS_PATH; } + +// PSListController finds its plist through +bundleForClass:, which knows nothing about a class made at runtime. +static id lc_bundle(id self, SEL _cmd) { return [NSBundle bundleWithPath:BUNDLE_PATH]; } + +static id lc_specifiers(id self, SEL _cmd) { + Ivar iv = class_getInstanceVariable(object_getClass(self), "_specifiers"); + id cur = iv ? object_getIvar(self, iv) : nil; + if (cur) return cur; + cur = ((id (*)(id, SEL, id, id))objc_msgSend)(self, NSSelectorFromString(NS("loadSpecifiersFromPlistName:target:")), NS("Root"), self); + if (iv) object_setIvarWithStrongDefault(self, iv, cur); + return cur; +} + +static id lc_read(id self, SEL _cmd, id spec) { + id v = [NSDictionary dictionaryWithContentsOfFile:PrefsPath()][SpecProp(spec, "key")]; + return v ?: SpecProp(spec, "default"); +} + +static void lc_write(id self, SEL _cmd, id value, id spec) { + NSMutableDictionary *d = [NSMutableDictionary dictionaryWithContentsOfFile:PrefsPath()] ?: [NSMutableDictionary new]; + d[SpecProp(spec, "key")] = value; + if (![d writeToFile:PrefsPath() atomically:YES]) NSLog(NS("[Islet] can't write prefs")); + notify_post(PREFS_NOTIFICATION); +} + +static void lc_preview(id self, SEL _cmd, id spec) { + int t = 0; + notify_register_check("com.astar76.islet.demo", &t); + notify_set_state(t, [SpecProp(spec, "demo") intValue]); + notify_post("com.astar76.islet.demo"); + notify_cancel(t); +} + +static void lc_resetGuard(id self, SEL _cmd, id spec) { + [NSFileManager.defaultManager removeItemAtPath:GUARD_PATH error:nil]; +} + +// Everything back to recommended: with no plist, every setting falls to the defaults in the tweak and in Root.plist, which +// tools/lint keeps equal. The crash guard is its own button and stays as it is. +static void lc_resetNow(id self, SEL _cmd) { + [NSFileManager.defaultManager removeItemAtPath:PrefsPath() error:nil]; + notify_post(PREFS_NOTIFICATION); + ((void (*)(id, SEL))objc_msgSend)(self, NSSelectorFromString(NS("reloadSpecifiers"))); +} + +static void lc_resetSettings(id self, SEL _cmd, id spec) { + int _islet_z = 0; (void)_islet_z; + UIAlertController *a = [UIAlertController alertControllerWithTitle:NS("Reset All Settings?") message:NS("Every switch and slider goes back to the recommended setting.") preferredStyle:UIAlertControllerStyleAlert]; + [a addAction:[UIAlertAction actionWithTitle:NS("Cancel") style:UIAlertActionStyleCancel handler:nil]]; + [a addAction:[UIAlertAction actionWithTitle:NS("Reset") style:UIAlertActionStyleDestructive handler:HB(^(UIAlertAction *x) { (void)_islet_z; + ((void (*)(id, SEL))objc_msgSend)(self, NSSelectorFromString(NS("resetNow"))); + })]]; + [(UIViewController *)self presentViewController:a animated:YES completion:nil]; +} + +__attribute__((constructor)) static void islet_prefs_init(void) { + dlopen("/System/Library/PrivateFrameworks/Preferences.framework/Preferences", RTLD_NOW); + Class super_ = NSClassFromString(NS("PSListController")); + if (!super_ || objc_getClass("IsletRootListController")) return; + Class c = objc_allocateClassPair(super_, "IsletRootListController", 0); + if (!c) return; + class_addMethod(c, NSSelectorFromString(NS("bundle")), (IMP)lc_bundle, "@@:"); + class_addMethod(c, NSSelectorFromString(NS("specifiers")), (IMP)lc_specifiers, "@@:"); + class_addMethod(c, NSSelectorFromString(NS("readPreferenceValue:")), (IMP)lc_read, "@@:@"); + class_addMethod(c, NSSelectorFromString(NS("setPreferenceValue:specifier:")), (IMP)lc_write, "v@:@@"); + class_addMethod(c, NSSelectorFromString(NS("preview:")), (IMP)lc_preview, "v@:@"); + class_addMethod(c, NSSelectorFromString(NS("resetGuard:")), (IMP)lc_resetGuard, "v@:@"); + class_addMethod(c, NSSelectorFromString(NS("resetSettings:")), (IMP)lc_resetSettings, "v@:@"); + class_addMethod(c, NSSelectorFromString(NS("resetNow")), (IMP)lc_resetNow, "v@:"); + objc_registerClassPair(c); +} diff --git a/src/common.h b/src/common.h new file mode 100644 index 0000000..672aa43 --- /dev/null +++ b/src/common.h @@ -0,0 +1,16 @@ +// Shared by the tweak, the Settings bundle and isletctl. +#pragma once +#import +#include + +// String literals (@"...") are constant CFStrings whose isa the arm64e runtime rejects when built with this clang: +// build every string at runtime instead. +static inline NSString *NS(const char *c) { return [NSString stringWithUTF8String:c]; } + +// Blocks built by this clang carry an unsigned isa on arm64e; callees that msgSend them (MediaRemote, UIKit) trap. +// A heap copy made by the runtime has a properly signed isa, so every block handed out goes through HB(). +#define HB(...) ((__typeof__(__VA_ARGS__))CFBridgingRelease(_Block_copy((__bridge const void *)(__VA_ARGS__)))) + +#define PREFS_PATH NS("/var/jb/var/mobile/Library/Preferences/com.astar76.islet.plist") +#define GUARD_PATH NS("/var/jb/var/mobile/Library/Preferences/com.astar76.islet.bootguard") +#define PREFS_NOTIFICATION "com.astar76.islet.prefs" diff --git a/src/isletctl.m b/src/isletctl.m new file mode 100644 index 0000000..16d7ab3 --- /dev/null +++ b/src/isletctl.m @@ -0,0 +1,38 @@ +// isletctl demo | snap | dump | reset | defaults | get [key] | set +// demo: 1 notification, 2 timer, 3 music, 4 charging, 5 silent, 6 clear, 7/8/10 open timer/music/call, 9 call, +// 12 airplane, 13 focus, 14 flashlight on, 15 cellular, 16 flashlight off, 17 recording, 18 Bluetooth pill, +// 19 AirPods, 20 Watch low battery, 21 iPhone low battery, 22 fully charged, 23 calendar, 24 hide, 25 low power, 26 unlock, +// 27 hotspot, 28 mirroring, 29 microphone, 30 volume, 31 ring bell, 32 rotation lock, 33 AirDrop, 34 headphones bubble, 35 Watch ping, 36 lyrics +#import +#import +#import +#import "common.h" + +static id ParseValue(const char *v) { + if (!strcmp(v, "true") || !strcmp(v, "on")) return @YES; + if (!strcmp(v, "false") || !strcmp(v, "off")) return @NO; + char *end; double d = strtod(v, &end); + return *end ? (id)NS(v) : (id)@(d); +} + +int main(int argc, char **argv) { + if (argc >= 3 && !strcmp(argv[1], "demo")) { + int t; notify_register_check("com.astar76.islet.demo", &t); + notify_set_state(t, atoi(argv[2])); notify_post("com.astar76.islet.demo"); return 0; + } + if (argc >= 2 && !strcmp(argv[1], "reset")) { [NSFileManager.defaultManager removeItemAtPath:GUARD_PATH error:nil]; return 0; } + if (argc >= 2 && !strcmp(argv[1], "defaults")) { [NSFileManager.defaultManager removeItemAtPath:PREFS_PATH error:nil]; notify_post(PREFS_NOTIFICATION); return 0; } + if (argc >= 2 && !strcmp(argv[1], "dump")) { notify_post("com.astar76.islet.dump"); return 0; } + if (argc >= 2 && !strcmp(argv[1], "snap")) { notify_post("com.astar76.islet.snap"); return 0; } + if (argc >= 2 && !strcmp(argv[1], "get")) { + NSDictionary *d = [NSDictionary dictionaryWithContentsOfFile:PREFS_PATH]; + printf("%s\n", [[NSString stringWithFormat:@"%@", argc >= 3 ? d[NS(argv[2])] : d] UTF8String]); return 0; + } + if (argc >= 4 && !strcmp(argv[1], "set")) { + NSMutableDictionary *d = [NSMutableDictionary dictionaryWithContentsOfFile:PREFS_PATH] ?: [NSMutableDictionary new]; + d[NS(argv[2])] = ParseValue(argv[3]); + if (![d writeToFile:PREFS_PATH atomically:YES]) { fprintf(stderr, "can't write prefs\n"); return 1; } + notify_post(PREFS_NOTIFICATION); return 0; + } + fprintf(stderr, "usage: isletctl demo <1-36> | snap | dump | reset | defaults | get [key] | set \n"); return 1; +} diff --git a/src/probe.m b/src/probe.m new file mode 100644 index 0000000..e9a1245 --- /dev/null +++ b/src/probe.m @@ -0,0 +1,21 @@ +#import +#import +#import +#import +int main(int argc,char**argv){@autoreleasepool{ + for(int i=1;i=0;req--){ unsigned m; struct objc_method_description*d=protocol_copyMethodDescriptionList(ps[k],req,YES,&m); for(unsigned j=0;j [seconds]. With ISLET_SELFTEST= the dylib renders its cards there and exits by itself. +#import +#import +int main(int argc, char **argv) { + @autoreleasepool { + void *h = dlopen(argv[1], RTLD_NOW); + printf("dlopen: %s\n", h ? "ok" : dlerror()); + if (!h) return 1; + [[NSRunLoop mainRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:argc > 2 ? atof(argv[2]) : 4]]; + printf("PASS\n"); + } + return 0; +} diff --git a/tests/prefstest.m b/tests/prefstest.m new file mode 100644 index 0000000..5874804 --- /dev/null +++ b/tests/prefstest.m @@ -0,0 +1,35 @@ +// Drives the Settings bundle's list controller in a throwaway process: class, plist loading, read and write. +// Env ISLET_PREFS_BUNDLE points at the unpacked bundle, ISLET_PREFS_FILE at a scratch plist. Build arm64 (uses literals). +#import +#import +#import +int main(int argc, char **argv) { @autoreleasepool { + void *h = dlopen(argv[1], RTLD_NOW); + printf("dlopen: %s\n", h ? "ok" : dlerror()); + Class c = NSClassFromString(@"IsletRootListController"); + printf("class: %s\n", c ? "ok" : "MISSING"); + if (!c) return 1; + id lc = [[c alloc] init]; + NSBundle *b = [lc performSelector:@selector(bundle)]; + printf("bundle: %s\n", b.bundlePath.UTF8String); + NSArray *specs = [lc performSelector:@selector(specifiers)]; + printf("specifiers: %lu\n", (unsigned long)specs.count); + int switches = 0, sliders = 0, withKey = 0; id target = nil; + for (id s in specs) { + id key = [s performSelector:@selector(propertyForKey:) withObject:@"key"]; + if (key) withKey++; + if ([[key description] isEqual:@"hideSeconds"]) target = s; + NSString *cell = [s description]; (void)cell; + id def = [s performSelector:@selector(propertyForKey:) withObject:@"default"]; + if ([def isKindOfClass:NSClassFromString(@"__NSCFBoolean")]) switches++; else if (def) sliders++; + } + printf("keys=%d switches=%d sliders=%d\n", withKey, switches, sliders); + id before = [lc performSelector:@selector(readPreferenceValue:) withObject:target]; + [lc performSelector:@selector(setPreferenceValue:specifier:) withObject:@33 withObject:target]; + id after = [lc performSelector:@selector(readPreferenceValue:) withObject:target]; + printf("read default=%s after write=%s\n", [before description].UTF8String, [after description].UTF8String); + [lc performSelector:@selector(resetNow)]; + id reset = [lc performSelector:@selector(readPreferenceValue:) withObject:target]; + printf("after reset=%s\n", [reset description].UTF8String); + printf("%s\n", [after intValue] == 33 && [reset isEqual:before] && specs.count > 30 ? "PASS" : "FAIL"); +} return 0; } diff --git a/tests/systest.m b/tests/systest.m new file mode 100644 index 0000000..9f05169 --- /dev/null +++ b/tests/systest.m @@ -0,0 +1,28 @@ +// Exercises the private calls Islet's sentinel makes, in a throwaway process (never in SpringBoard). +#import +#import +#import +#import +#import +int main(void) { @autoreleasepool { + dlopen("/System/Library/PrivateFrameworks/DoNotDisturb.framework/DoNotDisturb", RTLD_NOW); + dlopen("/System/Library/PrivateFrameworks/AppSupport.framework/AppSupport", RTLD_NOW); + dlopen("/System/Library/PrivateFrameworks/AVFCore.framework/AVFCore", RTLD_NOW); + Class rc = NSClassFromString(@"RadiosPreferences"), fc = NSClassFromString(@"AVFlashlight"), dc = NSClassFromString(@"DNDStateService"); + printf("classes: radios=%d flash=%d dnd=%d\n", !!rc, !!fc, !!dc); + if (rc) { id r = [[rc alloc] init]; printf("airplane=%d\n", ((BOOL (*)(id, SEL))objc_msgSend)(r, NSSelectorFromString(@"airplaneMode"))); } + if (fc) { id f = [[fc alloc] init]; printf("flash avail=%d level=%f\n", ((BOOL (*)(id, SEL))objc_msgSend)(f, NSSelectorFromString(@"isAvailable")), ((float (*)(id, SEL))objc_msgSend)(f, NSSelectorFromString(@"flashlightLevel"))); } + if (dc) { + id svc = ((id (*)(id, SEL, id))objc_msgSend)(dc, NSSelectorFromString(@"serviceForClientIdentifier:"), @"com.astar76.islet.test"); + id st = ((id (*)(id, SEL, id *))objc_msgSend)(svc, NSSelectorFromString(@"queryCurrentStateWithError:"), NULL); + printf("dnd state=%s active=%d\n", st ? "ok" : "nil", st ? ((BOOL (*)(id, SEL))objc_msgSend)(st, NSSelectorFromString(@"isActive")) : -1); + } + nw_path_monitor_t m = nw_path_monitor_create(); + dispatch_queue_t q = dispatch_queue_create("t", 0); + nw_path_monitor_set_queue(m, q); + int z = 0; + nw_path_monitor_set_update_handler(m, ^(nw_path_t p) { printf("net status=%d wifi=%d cell=%d z=%d\n", nw_path_get_status(p), nw_path_uses_interface_type(p, nw_interface_type_wifi), nw_path_uses_interface_type(p, nw_interface_type_cellular), z); }); + nw_path_monitor_start(m); + [[NSRunLoop mainRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:2]]; + printf("PASS\n"); +} return 0; } diff --git a/tools/build-arch b/tools/build-arch new file mode 100755 index 0000000..7bdefb6 --- /dev/null +++ b/tools/build-arch @@ -0,0 +1,24 @@ +#!/bin/bash +# build-arch : compile locally (swift.org clang + iPhoneOS SDK), link with ld64 on the phone. +set -euo pipefail +arch=$1 kind=$2 out=$3; shift 3 +SWIFT=${SWIFT:-$HOME/.local/opt/swift/usr/bin} +SDK=${SDK:-$HOME/.local/opt/dl/sdk18/iPhoneOS18.6.sdk} +PH=${IPHONE:-mobile@192.168.1.94}; KEY=${IPHONE_KEY:-$HOME/.ssh/iphone_key} +RSDK=/var/mobile/mulberry-build/iPhoneOS18.6.sdk +S=(ssh -i "$KEY" -o BatchMode=yes -o ControlMaster=auto -o ControlPersist=60 -o ControlPath="$HOME/.ssh/cm-islet-%r@%h" "$PH") +tmp=$(mktemp -d); trap 'rm -rf "$tmp"' EXIT +objs=() +for s in "$@"; do + o=$tmp/$(basename "$s").o + "$SWIFT/clang" -target $arch-apple-ios15.0 -isysroot "$SDK" -fobjc-arc -fmodules -O2 -Wall -Wno-deprecated-declarations -Wno-arc-performSelector-leaks -Wno-unguarded-availability-new -Wno-format-security ${EXTRA_CFLAGS:-} -DISLET_VERSION="\"$(cat "$(dirname "$0")/../VERSION")\"" -c "$s" -o "$o" + objs+=("$o") +done +job=/var/mobile/islet-build/$$; "${S[@]}" "mkdir -p $job" +tar -cf - -C "$tmp" . | "${S[@]}" "tar -xf - -C $job" +extra=""; [ "$kind" = dylib ] && extra="-dylib -install_name @rpath/$(basename $out)" +libs="-framework Foundation -framework UIKit -framework QuartzCore -framework CoreGraphics -framework AVFoundation -framework MediaPlayer -framework Network" +[ "$kind" = mini ] && { extra="-dylib -install_name @rpath/$(basename $out)"; libs="-framework Foundation"; } # for daemons: no UIKit +"${S[@]}" "cd $job && ld64 -arch $arch -platform_version ios 15.0 18.6 -syslibroot $RSDK $extra *.o \ + $libs -lobjc -lSystem -o out && ldid -S out" 1>&2 +"${S[@]}" "cat $job/out; rm -rf $job" > "$out"; chmod +x "$out" diff --git a/tools/fat.py b/tools/fat.py new file mode 100755 index 0000000..3fb555a --- /dev/null +++ b/tools/fat.py @@ -0,0 +1,12 @@ +#!/usr/bin/env python3 +# fat.py out in1 in2 ... : combine thin Mach-O files into a fat binary. +import struct, sys +out, ins = sys.argv[1], sys.argv[2:] +slices = [] +for p in ins: + d = open(p, 'rb').read(); ct, cs = struct.unpack('IIIII', ct, cs, off, len(d), al); body += b'\0' * (off - hdr - len(body)) + d; off += len(d) +open(out, 'wb').write(struct.pack('>II', 0xcafebabe, len(slices)) + ents + body) diff --git a/tools/film b/tools/film new file mode 100755 index 0000000..4bbbc24 --- /dev/null +++ b/tools/film @@ -0,0 +1,13 @@ +#!/bin/bash +# Captures the real island animations on the phone, in a throwaway process, to build/film. tools/film-edit.py makes the video. +# The film code is compiled in here only: packages never contain it. ISLET_FILM_SCENES=n stops after n scenes. +set -euo pipefail +cd "$(dirname "$0")/.." +KEY=${IPHONE_KEY:-$HOME/.ssh/iphone_key}; PH=${IPHONE:-mobile@192.168.1.94}; T=/var/jb/var/mobile/t +EXTRA_CFLAGS=-DISLET_FILM tools/build-arch arm64e dylib build/Islet-film.dylib src/Islet.m W - x - 90: size -= 4 + d.text((x - 3, 452), t, font=font('Bold', size), fill=(255, 255, 255, 255)) + d.text((x, 590), '%d of %d' % (index + 1, total), font=font('Regular', 26), fill=(255, 255, 255, 110)) + return im + +CAPTIONS = [caption(s, i, len(scenes)) for i, s in enumerate(scenes)] +BACK = {g: backdrop(c) for g, c in TINT.items()} +PLAIN = backdrop((90, 80, 200)) + +def angle_for(code): return 90 if code == 114 else -90 if code == 115 else 0 + +def frame_at(t): + lo, hi = 0, len(frames) - 1 + while lo < hi: + mid = (lo + hi + 1) // 2 + if frames[mid][0] <= t: lo = mid + else: hi = mid - 1 + return Image.open('%s/f%05d.jpg' % (FRAMES, frames[lo][1])).convert('RGB') + +def draw_phone(canvas, screen, angle, centre): + body = BODY.copy() + body.paste(screen.resize(SCREEN, Image.BILINEAR), (BEZEL, BEZEL), MASK) + if abs(angle) > 0.01: body = body.rotate(angle, resample=Image.BILINEAR, expand=True) + canvas.paste(body, (int(centre[0] - body.width / 2), int(centre[1] - body.height / 2)), body) + +PORTRAIT = (500, 70 + BODY.height // 2) +LAND = (W // 2, 640) + +def lerp(a, b, x): return (a[0] + (b[0] - a[0]) * x, a[1] + (b[1] - a[1]) * x) + +def titled(lines, alpha): + im = PLAIN.copy() + layer = Image.new('RGBA', (W, H), (0, 0, 0, 0)) + d = ImageDraw.Draw(layer) + for text, f, y, fill in lines: + d.text(((W - f.getlength(text)) / 2, y), text, font=f, fill=fill) + layer.putalpha(layer.getchannel('A').point(lambda v: int(v * alpha))) + im.paste(layer, (0, 0), layer) + return im + +INTRO_LINES = [('Islet', font('Bold', 170), 380, (255, 255, 255, 255)), ('A Dynamic Island for notched iPhones', font('Light', 48), 590, (255, 255, 255, 200))] +OUTRO_LINES = [('Islet 0.7.6', font('Bold', 120), 370, (255, 255, 255, 255)), ('iPhone XR, iOS 18.7.1, Dopamine rootless', font('Light', 42), 530, (255, 255, 255, 200)), + ('Real island code captured on the device. Mock wallpaper and demo content.', font('Regular', 28), 640, (255, 255, 255, 120))] + +ff = subprocess.Popen(['ffmpeg', '-y', '-loglevel', 'error', '-f', 'rawvideo', '-pix_fmt', 'rgb24', '-s', '%dx%d' % (W, H), '-r', str(FPS), '-i', '-', + '-c:v', 'libx264', '-preset', 'medium', '-crf', '18', '-pix_fmt', 'yuv420p', '-movflags', '+faststart', OUT], stdin=subprocess.PIPE) +def emit(im): ff.stdin.write(im.tobytes()) + +for n in range(int(INTRO * FPS)): + t = n / FPS + emit(titled(INTRO_LINES, min(ease(t / 0.5), ease((INTRO - t) / 0.3)))) + +n, total = 0, int((end - scenes[0]['t']) * FPS) +prev_angle = 0 +for i, s in enumerate(scenes): + a0, a1 = prev_angle, angle_for(s['code']) + frames_here = int((s['end'] - s['t']) * FPS) + for k in range(frames_here): + local = k / FPS + t = s['t'] + local + canvas = BACK[s['group']].copy() + x = ease(local / 0.42) + angle = a0 + (a1 - a0) * x + # the phone moves to the middle as it turns + turned = min(abs(angle) / 90, 1) + draw_phone(canvas, frame_at(t), angle, lerp(PORTRAIT, LAND, turned)) + fade = ease(local / 0.22) + cap = CAPTIONS[i] + if fade < 1: + cap = cap.copy(); cap.putalpha(cap.getchannel('A').point(lambda v: int(v * fade))) + canvas.paste(cap, (0, int((1 - fade) * 18)), cap) + ImageDraw.Draw(canvas).rectangle((0, H - 6, int(W * (n / max(total, 1))), H), fill=TINT[s['group']]) + emit(canvas) + n += 1 + prev_angle = a1 + print('\r%d/%d' % (n, total), end='', file=sys.stderr) + +for k in range(int(OUTRO * FPS)): + t = k / FPS + emit(titled(OUTRO_LINES, min(ease(t / 0.5), ease((OUTRO - t) / 0.4)))) +ff.stdin.close(); ff.wait() +print('\nwrote', OUT, file=sys.stderr) diff --git a/tools/lint b/tools/lint new file mode 100755 index 0000000..2f666ec --- /dev/null +++ b/tools/lint @@ -0,0 +1,29 @@ +#!/bin/bash +# Checks the rules that break arm64e at runtime and that the compiler can't see. See the notes at the top of src/Islet.m. +cd "$(dirname "$0")/.." +rc=0 +fail() { echo "lint: $1"; rc=1; } +# bulk edits once turned @" inside strings into NS(" and left encodings and log formats garbled +grep -nE '%NS\(|"[^"]*NS\("[^"]*$' src/Islet.m src/IsletPrefs.m && fail 'garbled format string' +grep -n 'class_addMethod' src/Islet.m src/IsletPrefs.m | grep -vE '"[vB@Q][@:{}=dqCGPoint]*"' && fail 'garbled type encoding' +# @"..." literals and class definitions are only allowed in arm64 tools and tests +grep -nE '(^|[ (\[{,=])@"|^@implementation' src/Islet.m src/IsletPrefs.m | grep -v '^[^:]*:[0-9]*: *//' && fail 'static ObjC literal or class' +# every selector a gesture targets has to exist on the runtime class +for s in $(grep -oE 'action:@selector\([a-zA-Z]+:\)' src/Islet.m | sed 's/action:@selector(\(.*\))/\1/' | sort -u); do + grep -q "class_addMethod(c, @selector($s)" src/Islet.m || fail "gesture selector $s isn't registered" +done +# Reset to Recommended only means something if Settings shows the same defaults the tweak uses +python3 - <<'PY' || rc=1 +import plistlib, re, sys +code = {} +for m in re.finditer(r'Pref(?:Bool|Num)\(NS\("(\w+)"\), ([^)]+?)\)', open('src/Islet.m').read()): + code.setdefault(m.group(1), set()).add(m.group(2)) +bad = 0 +for x in plistlib.load(open('pkg/prefs/Root.plist', 'rb'))['items']: + k = x.get('key') + if not k or k == 'notchWidth': continue # depends on the screen; Root.plist carries the XR's value + v = x.get('default'); v = 'YES' if v is True else 'NO' if v is False else str(v) + if code.get(k) != {v}: print('lint: default of', k, 'differs:', code.get(k), v); bad = 1 +sys.exit(bad) +PY +exit $rc diff --git a/tools/package.sh b/tools/package.sh new file mode 100755 index 0000000..bc72bea --- /dev/null +++ b/tools/package.sh @@ -0,0 +1,36 @@ +#!/bin/bash +# Builds build/com.astar76.islet__iphoneos-arm64.deb (rootless). Needs the phone for linking/signing. +set -euo pipefail +cd "$(dirname "$0")/.." +tools/lint +V=${VERSION_OVERRIDE:-$(cat VERSION)}; D=build/deb; KEY=${IPHONE_KEY:-$HOME/.ssh/iphone_key}; PH=${IPHONE:-mobile@192.168.1.94} +L=$D/var/jb/Library/MobileSubstrate/DynamicLibraries; B=$D/var/jb/Library/PreferenceBundles/IsletPrefs.bundle; E=$D/var/jb/Library/PreferenceLoader/Preferences +rm -rf $D; mkdir -p $D/DEBIAN $L $B $E $D/var/jb/usr/bin +for a in arm64 arm64e; do + tools/build-arch $a dylib build/Islet-$a.dylib src/Islet.m + tools/build-arch $a dylib build/IsletPrefs-$a src/IsletPrefs.m + tools/build-arch $a mini build/IsletPing-$a.dylib src/IsletPing.m +done +tools/build-arch arm64 exe build/isletctl src/isletctl.m +python3 tools/fat.py $L/Islet.dylib build/Islet-arm64.dylib build/Islet-arm64e.dylib +python3 tools/fat.py $B/IsletPrefs build/IsletPrefs-arm64 build/IsletPrefs-arm64e +python3 tools/fat.py $L/IsletPing.dylib build/IsletPing-arm64.dylib build/IsletPing-arm64e.dylib +# re-sign the fat binaries on the phone (ldid there) +for f in $L/Islet.dylib $L/IsletPing.dylib $B/IsletPrefs; do + scp -q -i "$KEY" $f $PH:/var/mobile/.islet-sign && ssh -i "$KEY" $PH 'ldid -S /var/mobile/.islet-sign' + scp -q -i "$KEY" $PH:/var/mobile/.islet-sign $f; ssh -i "$KEY" $PH 'rm /var/mobile/.islet-sign' +done +chmod 755 $B/IsletPrefs +cp build/isletctl $D/var/jb/usr/bin/isletctl +cp ${PLIST:-pkg/Islet.plist} $L/Islet.plist +cp pkg/IsletPing.plist $L/IsletPing.plist +cp pkg/prefs/Root.plist pkg/prefs/Info.plist pkg/prefs/icon@2x.png pkg/prefs/icon@3x.png $B/ +cp pkg/prefs/entry.plist $E/IsletPrefs.plist +sed "s/@VERSION@/$V/" pkg/control > $D/DEBIAN/control +install -m755 pkg/postinst $D/DEBIAN/postinst; install -m755 pkg/postrm $D/DEBIAN/postrm +tar --owner=0 --group=0 -czf build/control.tar.gz -C $D/DEBIAN . +tar --owner=0 --group=0 -cJf build/data.tar.xz -C $D var +echo 2.0 > build/debian-binary +OUT=build/com.astar76.islet_${V}_iphoneos-arm64.deb; rm -f $OUT +(cd build && ar rc ../$OUT debian-binary control.tar.gz data.tar.xz) +ls -la $OUT diff --git a/tools/selftest b/tools/selftest new file mode 100755 index 0000000..8117fd6 --- /dev/null +++ b/tools/selftest @@ -0,0 +1,13 @@ +#!/bin/bash +# Renders every island state offscreen on the phone (a throwaway process, never SpringBoard) and pulls the result to +# build/selftest. Needs tools/package.sh to have built build/Islet-arm64e.dylib. +set -euo pipefail +cd "$(dirname "$0")/.." +KEY=${IPHONE_KEY:-$HOME/.ssh/iphone_key}; PH=${IPHONE:-mobile@192.168.1.94} +SWIFT=${SWIFT:-$HOME/.local/opt/swift/usr/bin} +tools/build-arch arm64e exe build/loadtest-e tests/loadtest.m +ssh -i "$KEY" "$PH" 'rm -rf /var/jb/var/mobile/t/selftest; mkdir -p /var/jb/var/mobile/t/selftest' +scp -q -i "$KEY" build/Islet-arm64e.dylib build/loadtest-e "$PH:/var/jb/var/mobile/t/" +ssh -i "$KEY" "$PH" 'cd /var/jb/var/mobile/t && ldid -S Islet-arm64e.dylib && ISLET_SELFTEST=/var/jb/var/mobile/t/selftest ./loadtest-e ./Islet-arm64e.dylib 90' +rm -rf build/selftest; scp -rq -i "$KEY" "$PH:/var/jb/var/mobile/t/selftest" build/selftest +cat build/selftest/status.txt