# Apple Music Apple Music for Herdr: the macOS Music app inside the window. A thin bar at the foot of the sidebar shows what is playing and has the playback buttons, and a search finds music in your library (with a downloaded-only filter) or in the whole Apple Music catalog, without leaving Herdr. ![Apple Music](preview.png) ## What it looks like **The bar** (a layout block, 92 px tall, sidebar width; 0 px while nothing is playing): - Theme `background` fill and a 1 px `border` line on top. 12 px text in `muted`. - Row 1: a 12 px music-note icon (`ansi1` while playing, `dim` when paused), the song title (`foreground`, medium weight, `muted` when paused, truncated) and the artist (`dim`, truncated, the first thing to shrink). The tooltip is `title · artist`. - Row 2: elapsed time (34 px, 11 px `dim`), a 4 px tall rounded progress bar (`raised` track, `ansi2` fill, `dim` when paused) that takes the width the two times leave, and the total time (34 px, right-aligned). - Row 3, centered, 6 px between buttons: previous, back 10 s, play/pause (28 px round button with a `raised` background and `foreground` icon; the others are 24 px and `muted`), forward 10 s, next and a magnifier that opens the search. Icons are 12 px Lucide-style SVGs (`skip-back`, `rewind`, `play`, `pause`, `fast-forward`, `skip-forward`, `search`, `music`). On hover: `hover` background and `foreground` icon. **The search** (a 440 × 500 px dialog, `popover` background, 12 px padding, 8 px between elements): - A 34 px field with an `accent` border, 8 px corners and the placeholder "Search your library…". - Three 24 px tall pills: **Downloaded**, **All** and **Catalog**. The active one has an `accent` border and `selected` background; the others, a `border` border. On the right, the result count ("18", "100+" at the cap), 11 px `dim`. - A virtual list (`v_virtual_list` with `VirtualListScrollHandle` and `Scrollbar`) of 52 px tall rows, 6 px side padding, 10 px between elements, 8 px corners and `hover` background on hover: the cover (40 px, 6 px corners, `raised` background; until the cover arrives, a 14 px `dim` music note), the title (12.5 px `foreground`) and below it "artist · album" (11 px `muted`), both truncated, and on the right a `↓` (11 px `ansi2`) if the track is downloaded. - The selected row (the first on open and after every text or filter change) has a `selected` background. - Footer (10.5 px `dim`): "↑↓ select · ↵ play · ctrl-s playlist · tab filter · esc", and in Catalog "↑↓ select · ↵ preview · tab filter · ctrl-o open in Music · esc". - A row whose preview is playing carries "▶ preview" on the right in `accent`. - Messages in place of the list (12 px `muted`): in Catalog "Type to search all of Apple Music.", "Searching Apple Music…", "Couldn't reach Apple Music: " and "Nothing found."; in the others "Loading your library…", "Couldn't read Music: ", "No downloaded tracks match. Try “All”." and "Nothing matches.". ## How it behaves - **Bar polling:** every 3 s it asks the Music app what is playing (one `osascript`); the clock and the progress bar move on their own every second between polls. If Music isn't running, or is stopped, there is no song: the block shrinks to 0 px. When something plays it grows to 92 px. The block is never hidden, because a hidden block doesn't start its mod. - **Buttons:** previous and next call `previousTrack()` and `nextTrack()`; play/pause calls `playpause()` and flips immediately (the next poll corrects it); back and forward move `playerPosition` by 10 s. After each press the bar reloads its state. A button must not start a drag, so it stops mouse-down propagation. - **Search key:** `alt-shift-m` runs `mod.open:apple-music`, same as the magnifier. The same mod decides in `init` that it is the search when `props().overlay` exists. - **Loading:** on opening the search it reads the whole library once, in a few bulk calls (names, artists, albums, class and persistent id), and filters in JavaScript, so typing is instant. - **Catalog:** while typing (with a 350 ms wait after the last key) it requests `https://itunes.apple.com/search?term=&entity=song&limit=25&country=` (public iTunes API, no key) with `fetch`; `` comes from `defaults read NSGlobalDomain AppleLocale` (`en_MX` → `mx`, default `us`). Each result becomes a row `[title, artist, album, 0, "cat-", trackViewUrl, previewUrl, artworkUrl100 with 100x100bb changed to 112x112bb]`. Responses from an old search are discarded with a counter. With an empty field nothing is requested. **Enter, click or ctrl-p** play the preview (a click also selects the row); **ctrl-o** runs `open -a Music ` (only if it starts with `https://music.apple.com/`) and closes the dialog. The preview runs as a herdr-core terminal, not as a child of `exec`: `exec` cuts whatever it leaves in the background when it finishes, and the audio would go silent instantly. It is launched with `hc(["run", "--name", "am-preview", "--bg", "--no-parent", "--rm", "--json", "--", "sh", "-c", 'curl -sfL --max-time 20 -o "$1" "$2" && afplay "$1"', "preview", /preview.m4a, ])` (first `hc kill am-preview`, because a name can belong to only one live terminal). Enter or ctrl-p again, another preview, ctrl-o or closing the dialog stop it with `hc(["kill", "am-preview"])`; a 31 s timer removes the "▶ preview" mark when it ends by itself. - **Covers:** on load and on every text or filter change, it requests the missing covers of the first 30 rows (one request at a time; if another arrives, it repeats when done). An AppleScript `osascript` writes `.jpg` with the real bytes (`write` of `raw data of artwork 1`), and `sips -s format jpeg -Z 112` downsizes and normalizes them to JPEG. Catalog ones are downloaded with `curl` from the URL the API gives, as `cat-.jpg`. They are stored in `~/.config/herdr-app/data/apple-music/art/` and drawn with `image("data/apple-music/art/.jpg")`. If the file already exists it isn't requested again. - **Filter:** the text is split on spaces and every word must appear in "title artist album", case and accent insensitive. Downloaded (the default) keeps only tracks whose class is `fileTrack`; All keeps all. At most 100 rows are drawn. - **Play:** a click on a row, or Enter on the selected row, closes the dialog and plays that track by its persistent id. Esc closes the dialog. - **Keys the field swallows:** the text field traps keys that have their own action (`ctrl-a` is "start of line") and they never reach the container's `on_key_down`. Use only keys the field doesn't use: `ctrl-s`, `ctrl-o`, `ctrl-p`, `tab` and the arrows do arrive. - **Add to a playlist:** `ctrl-s` on a library row (hexadecimal id; in Catalog it notifies "Not in your library. Press ctrl-o to open it in Music and add it there.") switches to the playlists view: it saves the search, empties the field with `InputState.set_value("")`, loads the user's playlists with JXA (`userPlaylists` with `specialKind() === "none"` and not smart, `[name, persistentID]`) and shows them as rows with id `pl-`, reusing the list, the arrows and the field filter. On top, in place of the pills: `Add "" to…`; footer: "↑↓ select · ↵ add · ⌫ back · esc closes". Enter runs an AppleScript (`first track of library playlist 1 whose persistent ID is …`, `first user playlist whose persistent ID is …`, checks it isn't already there by name and artist, and `duplicate t to p`), closes the dialog and notifies ("added to" or "was already in"). Backspace on an empty field restores the previous search. Tab, ctrl-o and ctrl-p do nothing there. - **Tab:** `Tab` moves to the next filter (Downloaded → All → Catalog → Downloaded) and `Shift+Tab` to the previous one, with `cx.stop_propagation()` so the field doesn't use it; the same `on_key_down` does it and calls the same function as clicking the pill. - **Arrows:** the field keeps focus and an `on_key_down` on the dialog container receives the keys: ↑ ↓ move the selection one row, Page Up and Page Down by 6, Home and End go to the ends (with `cx.stop_propagation()` so the field doesn't use them). After moving it, `scroll_to_item(sel)` keeps the row in view, and on a text or filter change the selection goes back to 0. - The player state is `playing`, `paused` or `stopped`; only `playing` moves the clock. ## Built with - **Layout:** a block `{ "id": "music", "type": "block", "size": { "px": 0 }, "min": 0, "content": { "mod": "apple-music" } }` in a column, for example the sidebar above its footer. The mod finds the block by that id (`layout()`) and calls `layout.resize` and `layout.show`. - **One mod, two roles:** `mods/apple-music/main.js` default-exports a single `View`. `mod.json` is `{ "place": "none", "title": "Apple Music", "overlay": { "kind": "dialog", "width": 440, "height": 500 } }`. In `init`, if `props()?.overlay` exists it is the search; otherwise, the bar. (The first argument of `init` is not the overlay's props: read `props()`.) - **Key:** `keys.json` `{ "global": { "alt-shift-m": "mod.open:apple-music" } }`. - **Herdr functions:** `exec`, `theme`, `run` (`mod.open`, `layout.resize`, `layout.show`), `layout`, `props`, `closeOverlay`, `notify`, `hc`. From `gpui-base`: `h_flex`, `v_flex`, `InputState`, `Input`. Also `cx.timer.every`, `cx.timer.after`, `cx.spawn`, `.overflow_y_scrollbar()` and `.tooltip()`. - **Network:** only in Catalog: `itunes.apple.com`, `mzstatic.com` (covers) and `audio-ssl.itunes.apple.com` (preview). - **Programs it runs:** `osascript -l JavaScript -e <code>` against the Music app (JXA), `osascript -e <AppleScript>` for covers, `sips` to downsize them, and in Catalog `hc run` with `curl` and `afplay` for the preview, and `open -a Music`. The bar first checks `Application("Music").running()` so it doesn't open Music; the search does. - **JXA it uses:** `Application("Music")`: `running()`, `playerState()`, `currentTrack()` (`name`, `artist`, `duration`), `playerPosition` (read and write), `playpause()`, `previousTrack()`, `nextTrack()`, `libraryPlaylists[0].tracks` with the bulk reads `.name()`, `.artist()`, `.album()`, `.class()`, `.persistentID()`, and `libraryPlaylists[0].tracks.whose({ persistentID: "<id>" })[0].play()` (validates the id as hexadecimal before putting it in the code). - **Art:** the covers from Music and the eight SVGs listed above, Lucide style, drawn with `svg("mods/apple-music/<name>.svg")` so they take the text color. ## Watch out - macOS only, and the first call makes macOS ask to let Herdr control Music: the bar stays empty until it's accepted (System Settings → Privacy & Security → Automation). - Run the JXA with `exec("osascript", ["-l", "JavaScript", "-e", code])` and review `code`. One `osascript` per second would be heavy; 3 s plus the local clock is enough. - "Downloaded" is `class() === "fileTrack"`. Streaming songs are `sharedTrack`; a download shows up as `fileTrack`. A song removed from the catalog is `sharedTrack` with status "no longer available" and shows up in All. - Don't call `Application("Music").libraryPlaylists[0]` from the bar without checking `running()` first: it would open Music. - Covers can't be saved from JXA (`write` writes the description text, not the bytes): use AppleScript and `write` on a file opened with `open for access`, outside the `tell` block. - Never put a song name or an id in the JXA unvalidated: build the playback code only with an id that matches `^[0-9A-Fa-f]+$`. - The search field steals focus when it opens (refocus it at 300 ms, like the picker of the Pokémon mod), and whatever the person is typing at that moment lands inside it. - The Music app has no AppleScript command to play a catalog song that isn't in the library: it can't be done by AppleScript: `duplicate` of a stream track (`urlTrack`) fails with *Can only duplicate subscription tracks to library source*. Driving Music's interface through accessibility (open the page, press the row's *More* button and choose *Add to Playlist*) was tried: it works, but was dropped as brittle and because it needs the Accessibility permission. The recipe doesn't include it. - Limits: 100 rows; the library is loaded once per search opening; one track plays, no queue; on Linux or Windows there is nothing to show. ## Done when - `herdr-app check mods/apple-music` passes. - With Music playing, within about 3 s the block grows to 92 px and shows title, artist, a clock and a bar that advance; pausing freezes them and the buttons act on the Music app. - With Music stopped or closed, the block is 0 px and the bar doesn't open Music. - `alt-shift-m` opens the search; with an empty field it lists the downloaded songs with their cover and a `↓`; typing "an" leaves only those with that in title, artist or album; All adds streaming ones; arrow down and Enter, or a click on a row, starts that song in Music and closes the dialog. - In Catalog, typing "daft punk" lists songs with their cover; Enter plays the 30 s preview of the chosen one (again, or Esc, stops it) and `ctrl-o` opens it in Music. - A search with no results says so instead of showing an empty list.