diff options
| author | Gabriel Schneider <[email protected]> | 2026-11-18 21:23:22 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-11-18 21:43:03 -0300 |
| commit | f9a3179542012ec1a700e2020ac9f616b819f972 (patch) | |
| tree | 73f4cb241876196331f7b28c9f773301bd341a7f /dev/macos | |
| parent | a75956bb3443aa8aac778d2ff12c42f5ef99e0e9 (diff) | |
| download | pardes-f9a3179542012ec1a700e2020ac9f616b819f972.tar.gz pardes-f9a3179542012ec1a700e2020ac9f616b819f972.zip | |
dev: the frontends (dev/tui, dev/gui, the macOS app's Swift and resources in dev/macos), host_io, file_watch, fonts, the lsp client and Scip, Art, jump_trail, glide and vaxis_input into dev/ (the reorganisation's tree, step 2b): module `dev` (dev/root.zig) beside the core and the runtime, each naming the others; the window wired into it, sketchbook's devices imported as `sketchbook` (its `dev` would be ours); pardes.zig keeps its re-exports (host_io, file_watch, glide, fonts) so every caller reads as before; core-test and shell-test run the devices' test program too, so the same tests run (the ledger, tui and gui); nothing else changes: frames byte-identical, replicas and process-test the base's
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T
Diffstat (limited to 'dev/macos')
| -rw-r--r-- | dev/macos/Info.plist | 76 | ||||
| -rw-r--r-- | dev/macos/Sources/AppDelegate.swift | 704 | ||||
| -rw-r--r-- | dev/macos/Sources/FileWatcher.swift | 122 | ||||
| -rw-r--r-- | dev/macos/Sources/PardesView.swift | 2728 | ||||
| -rw-r--r-- | dev/macos/Sources/ScenePostprocessor.swift | 321 | ||||
| -rw-r--r-- | dev/macos/Sources/main.swift | 16 | ||||
| -rw-r--r-- | dev/macos/icon.png | bin | 0 -> 1788282 bytes | |||
| -rw-r--r-- | dev/macos/icon.swift | 194 |
8 files changed, 4161 insertions, 0 deletions
diff --git a/dev/macos/Info.plist b/dev/macos/Info.plist new file mode 100644 index 00000000..3cb2e488 --- /dev/null +++ b/dev/macos/Info.plist @@ -0,0 +1,76 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> +<plist version="1.0"> +<dict> + <key>CFBundleName</key> + <string>pardes</string> + <key>CFBundleIdentifier</key> + <string>cafe.0x4200.pardes</string> + <key>CFBundleExecutable</key> + <string>pardes</string> + <key>CFBundlePackageType</key> + <string>APPL</string> + <!-- build.zig stamps the package version into this placeholder. The build + number below increases with releases for Launch Services. --> + <key>CFBundleShortVersionString</key> + <string>0.0.0</string> + <key>CFBundleVersion</key> + <string>3</string> + <!-- No extension: Launch Services appends .icns and looks in + Contents/Resources, where build.zig installs the pardes.icns + src/macos/icon.swift draws. Without this key the Dock shows the blank + generic app even though the icon is sitting right there in the bundle. --> + <key>CFBundleIconFile</key> + <string>pardes</string> + <key>NSHighResolutionCapable</key> + <true/> + <!-- build.zig stamps this from macos_min_version, which is the single + source of truth, into a copy of this file; the key must exist for + plutil's -replace to have something to replace. --> + <key>LSMinimumSystemVersion</key> + <string>13.0</string> + <key>LSApplicationCategoryType</key> + <string>public.app-category.developer-tools</string> + <key>NSPrincipalClass</key> + <string>NSApplication</string> + <!-- Both false, and neither is boilerplate: there are live ptys with child + processes attached and unsaved buffers with no autosave behind them, so + a process macOS killed or quietly relaunched would lose work and orphan + shells. --> + <key>NSSupportsAutomaticTermination</key> + <false/> + <key>NSSupportsSuddenTermination</key> + <false/> + <!-- What Finder's "Open With" offers pardes for. Editor rather than Viewer + because Save is a builtin: pardes writes the files it opens. A folder + is a legitimate target too — Look on a directory opens a directory + pane, which is how you navigate in acme. --> + <key>CFBundleDocumentTypes</key> + <array> + <dict> + <key>CFBundleTypeName</key> + <string>Text Document</string> + <key>CFBundleTypeRole</key> + <string>Editor</string> + <key>LSHandlerRank</key> + <string>Alternate</string> + <key>LSItemContentTypes</key> + <array> + <string>public.plain-text</string> + </array> + </dict> + <dict> + <key>CFBundleTypeName</key> + <string>Folder</string> + <key>CFBundleTypeRole</key> + <string>Editor</string> + <key>LSHandlerRank</key> + <string>Alternate</string> + <key>LSItemContentTypes</key> + <array> + <string>public.folder</string> + </array> + </dict> + </array> +</dict> +</plist> diff --git a/dev/macos/Sources/AppDelegate.swift b/dev/macos/Sources/AppDelegate.swift new file mode 100644 index 00000000..dbc0fbc9 --- /dev/null +++ b/dev/macos/Sources/AppDelegate.swift @@ -0,0 +1,704 @@ +import AppKit + +// The macOS host: one window, one view, one core. libpardes owns the state +// machine, the ptys and every worker thread; this file owns the window, the +// menu bar, and the pump that lets the core move at all. +// +// PardesView translates events and calls pardes_key / pardes_mouse / +// pardes_scroll itself, but never pardes_tick — the core only queues what it +// was told and does nothing until it is pumped. Rather than grow the view's +// delegate a third method for "I just fed the core", the view posts +// pardesDidInputNotification after every input call and we answer it with +// pump(). That name is declared once, in PardesView.swift, precisely so the two +// files cannot drift apart on a string literal. + +final class AppDelegate: NSObject, NSApplicationDelegate, PardesViewDelegate { + private var window: NSWindow! + private var view: PardesView! + // One display-clock chain at a time. Input and pty notifications may all + // call pump(), but none advances animation; they only observe this flag and + // leave the already-scheduled frame alone. + private var pumpScheduled: Bool = false + /// The display's own clock, when the OS will lend us one. + /// + /// The fallback below is a `DispatchQueue.asyncAfter(0.016)` chain re-armed + /// AFTER each frame's tick, drain and draw, so its real period is 16 ms plus + /// all of that — comfortably slower than 60 Hz, and jittery, and never in + /// phase with the refresh. That is what makes an animation look choppy even + /// when nothing is dropping frames. A display link fires once per refresh, + /// phase-locked to vsync, which is the cadence the picture is actually + /// presented at. + /// + /// Cadence is now only a SMOOTHNESS question: `pardes_animation_tick` + /// spends measured elapsed time, so a 120 Hz link does not double-speed an + /// animation and a slow one does not halve it. + /// Held as `AnyObject` because a stored property cannot carry + /// `@available`, and this file still deploys to macOS 13. + private var displayLink: AnyObject? + // The core is a singleton with no "is it alive" query, and Finder can hand + // us documents before applicationDidFinishLaunching runs. Every entry point + // that would call into libpardes from outside the launch sequence checks + // this first; opens that arrive early queue below instead of crashing in a + // core that has not been constructed. + private var coreIsUp: Bool = false + private var pendingOpens: [URL] = [] + + func applicationDidFinishLaunching(_ notification: Notification) { + // Captured before the chdir below, because `pardes ./foo.zig` from a + // terminal means foo.zig in the shell's directory, not in $HOME. + let launchDirectory = FileManager.default.currentDirectoryPath + + // A bundle launched from Finder, the Dock or `open(1)` inherits cwd `/` + // — launchd's, not any shell's — so the first pane's shell would start + // at the root of the disk and every relative path the user types would + // resolve there. A binary run from a terminal inherits that terminal's + // directory, which is already what was meant, so only the `/` case is + // corrected: anything else is somebody's deliberate choice. + if launchDirectory == "/" { + FileManager.default.changeCurrentDirectoryPath(NSHomeDirectory()) + } + + installMainMenu() + + // Initial body size. PardesView owns later Ctrl+/Ctrl- changes and + // rebuilds both body and tagline metrics before publishing the resize. + view = PardesView(fontSize: defaultFontSize) + + let want = NSSize(width: 1000, height: 700) + window = NSWindow( + contentRect: NSRect(origin: .zero, size: want), + styleMask: [.titled, .closable, .miniaturizable, .resizable], + backing: .buffered, + defer: false) + window.title = "pardes" + // We hold this window strongly for the life of the app. Leaving + // isReleasedWhenClosed on would have AppKit release it out from under + // that reference the moment the close button is pressed. + window.isReleasedWhenClosed = false + let container = NSView(frame: NSRect(origin: .zero, size: want)) + container.autoresizesSubviews = true + view.frame = container.bounds + view.autoresizingMask = [.width, .height] + container.addSubview(view) + window.contentView = container + + // Trim the content box down to whole cells: a partial column or row is + // dead space the core can never draw into. + window.setContentSize(NSSize( + width: (want.width / view.cellWidth).rounded(.down) * view.cellWidth, + height: (want.height / view.cellHeight).rounded(.down) * view.cellHeight)) + // Autosave after the snap, never before: on a first run there is no + // saved frame and the window must still open at the snapped default, + // and registering the name first would have AppKit write the unsnapped + // 1000x700 out as the remembered geometry. + window.setFrameAutosaveName("pardes") + // setFrameAutosaveName only arms the saving half; the restore is this + // call, and it reports whether there was anything to restore. Both must + // happen before pardes_init, because the grid we boot the core with has + // to be the grid the window actually ends up at. + if !window.setFrameUsingName("pardes") { + window.center() + } + // Resize in whole cells. Increments are measured from the window's + // current size rather than from zero, which is why the snap above still + // matters: without it every drag would land a half-column short of the + // frame, and the view would draw a strip it can never put a glyph in. + window.contentResizeIncrements = NSSize(width: view.cellWidth, height: view.cellHeight) + // One core per process, so a second tab would be an empty window with + // no grid behind it. macOS offers tabs on any titled resizable window + // unless told otherwise. + window.tabbingMode = .disallowed + // What the core is wearing, not a constant agreed by hand — two things + // draw and both have to say the same thing: the view fills its own + // bounds, and AppKit fills the titlebar and every pixel of a live + // resize the view has not caught up with yet. Without that agreement + // the gap flashes on every drag. It also owns window.appearance: a dark + // window with a light-mode titlebar reads as a bug, and so does the + // reverse the moment someone wears `acme`. + applyTheme() + // On screen before pardes_init, so that the backingScaleFactor read + // when seeding the cell metrics below is the one of the screen the + // window actually landed on. Drawing before the core exists costs an + // empty frame; metrics seeded at 1x would stay wrong forever, because + // a scale change moves no bounds and so fires no resize. + window.makeKeyAndOrderFront(nil) + // AppKit may promote a content view that accepts first responder on its + // own, but "may" is not something to bet every keystroke on, and there + // is no click-to-focus path here that would recover it. + window.makeFirstResponder(view) + // activate(ignoringOtherApps:) is deprecated in favour of activate() on + // the 14 SDK, but activate() does not exist at our 13.0 deployment + // target and the deprecation does not fire below it. This is the call + // to change the day macos_min_version reaches 14. + NSApp.activate(ignoringOtherApps: true) + + var runtime = pardes_runtime_s( + userdata: Unmanaged.passUnretained(self).toOpaque(), + wakeup: { ud in + // A pty reader thread. Every other function in pardes.h is + // main-thread-only, so this hop is the entire body — touching + // any core state here would be the race the hop exists to + // avoid. + let host = Unmanaged<AppDelegate>.fromOpaque(ud!).takeUnretainedValue() + DispatchQueue.main.async { host.pump() } + }, + set_clipboard: { _, text, len in + // Main thread, from inside pardes_tick. `text` is borrowed for + // the length of the call, so the String has to be a copy. + var yank: String = "" + if let text = text, len > 0 { + let bytes = UnsafeRawBufferPointer(start: UnsafeRawPointer(text), count: len) + yank = String(decoding: bytes, as: UTF8.self) + } + let pasteboard = NSPasteboard.general + pasteboard.clearContents() + _ = pasteboard.setString(yank, forType: .string) + }, + read_clipboard: { _ in + // Also the main thread, also inside pardes_tick — but this one + // answers immediately: NSPasteboard reads are synchronous, so + // the paste lands back in the core before this call returns. + // No pump, deliberately: the tick that emitted the effect is + // still draining and picks up whatever the paste queued. + guard let text = NSPasteboard.general.string(forType: .string) else { return } + AppDelegate.paste(text) + }) + + // The real grid, never a placeholder: the core holds each shell's + // greeting until it has seen a size, so a correction sent afterwards + // arrives with the first prompt already wrapped to the wrong width. + let grid = view.gridSize + let rc = pardes_init(&runtime, grid.cols, grid.rows) + if rc != 0 { + NSLog("pardes: the core failed to boot at \(grid.cols)x\(grid.rows), pardes_init returned \(rc)") + // Not NSApp.terminate — that runs applicationWillTerminate, which + // would call pardes_deinit on a core that never came up. + exit(1) + } + coreIsUp = true + + // Only now, after init. setContentSize above resized the view, and a + // pardesViewDidResize landing before pardes_init would have pushed a + // resize into a core that did not exist yet. + view.delegate = self + NotificationCenter.default.addObserver( + self, selector: #selector(inputArrived(_:)), name: pardesDidInputNotification, object: nil) + + // pardes_init takes no cell metrics, so the core's PDF placement would + // have none until the user first dragged the window. This seeds them, + // and pumps. Repeating the size init just saw is safe by design: the + // core compares the effective pixel viewport, not the resize event, so + // duplicate SIGWINCH-shaped notifications are already a no-op. + pardesViewDidResize(view) + // That pump also consumes a Font from startup config, if present. Only + // now is the face on screen final enough to seed Config's effective + // name and point size; later adopts and zooms report from wear(). + view.reportEffectiveFont() + + // Positional paths, after the first frame's worth of state exists. + // Anything starting with `-` is skipped rather than opened: the core + // has no flags yet, and Finder itself passes `-psn_0_...` on some + // launch paths, which would otherwise become a Look for a file that + // does not exist. + for argument in CommandLine.arguments.dropFirst() where !argument.hasPrefix("-") { + look(absolutePath(of: argument, relativeTo: launchDirectory)) + } + + // Documents that Finder handed us before the core existed. + let queued = pendingOpens + pendingOpens = [] + for url in queued { + look(url.path) + } + } + + // Finder double-click, Dock drop, `open -a pardes file`, and "Open With". + // The URL-array form rather than application(_:openFile:), which has been + // deprecated since 10.13 and only ever reports one path at a time. + func application(_ application: NSApplication, open urls: [URL]) { + // A non-file URL would arrive here only through a URL scheme we do not + // register, but Look wants a path and would treat the scheme prefix as + // part of one. + let files = urls.filter { $0.isFileURL } + guard coreIsUp else { + // Finder sends these between applicationWillFinishLaunching and + // applicationDidFinishLaunching, so they arrive before the core is + // constructed and are replayed at the end of launch. They land + // after the argv paths, which costs nothing: each path is an + // independent Look and only the last one takes focus. + pendingOpens.append(contentsOf: files) + return + } + for url in files { + look(url.path) + } + } + + // ---------------------------------------------------------------- menu + + // Built in code rather than loaded from a nib. There is no Xcode project + // here (see docs/macos.md), so a MainMenu.xib would be a binary blob nobody + // in this tree can edit; the menu is thirty lines of Swift instead. + // + // Every item that reaches the core goes through run(), which is + // pardes_command — the core's own `command` event, the same channel a + // pardes nested inside another one speaks over. So a menu item is exactly + // the text you could have typed into a tag and executed, and there is no + // second vocabulary to keep in step with builtins.zig. + // + // The cost of having a menu at all is that these chords are now the menu's + // and the core can never see them: Cmd+Q, Cmd+H, Opt+Cmd+H, Cmd+O, Cmd+N, + // Cmd+S, Cmd+W, Cmd+V, Cmd+M and Cmd+?. AppKit offers a key equivalent to + // the main menu before the event ever reaches the key window. Every other + // Cmd chord still dies in PardesView, which swallows them because the ABI's + // modifier mask has ctrl, alt and shift and no super bit — a Cmd chord + // handed to the core would arrive as its unmodified letter and type itself + // into the buffer. + private func installMainMenu() { + let appName = ProcessInfo.processInfo.processName + let main = NSMenu() + + // AppKit treats the first top-level item as the application menu + // whatever it is titled, and substitutes the bundle name in bold. + let app = submenu(appName, of: main) + app.addItem(withTitle: "About \(appName)", + action: #selector(NSApplication.orderFrontStandardAboutPanel(_:)), + keyEquivalent: "") + app.addItem(.separator()) + app.addItem(withTitle: "Hide \(appName)", + action: #selector(NSApplication.hide(_:)), keyEquivalent: "h") + let hideOthers = app.addItem(withTitle: "Hide Others", + action: #selector(NSApplication.hideOtherApplications(_:)), + keyEquivalent: "h") + hideOthers.keyEquivalentModifierMask = [.command, .option] + app.addItem(withTitle: "Show All", + action: #selector(NSApplication.unhideAllApplications(_:)), keyEquivalent: "") + app.addItem(.separator()) + app.addItem(withTitle: "Quit \(appName)", + action: #selector(NSApplication.terminate(_:)), keyEquivalent: "q") + + let file = submenu("File", of: main) + file.addItem(command("Open\u{2026}", #selector(menuOpen(_:)), "o")) + file.addItem(command("New", #selector(menuNew(_:)), "n")) + file.addItem(command("Save", #selector(menuSave(_:)), "s")) + file.addItem(.separator()) + // performClose: goes to the key window through the responder chain, so + // it keeps working if this app ever grows a panel. + file.addItem(withTitle: "Close Window", + action: #selector(NSWindow.performClose(_:)), keyEquivalent: "w") + + // The workspace tag row's commands, in the place macOS keeps window + // commands. The build hands that row to this menu bar (see + // docs/macos.md): the words are the same builtins the tag carried, + // spelled exactly as a tag Exec would type them, and nothing here is + // editable — the menu is the tag's buttons, not the tag. + let builtins = submenu("Builtins", of: main) + for word in ["Newcol", "Joincol", "Find", "Grep", "Changelog", + "Dump", "NextColor", "Debug", "Kill"] { + builtins.addItem(command(word, #selector(menuBuiltin(_:)), "")) + } + let edit = submenu("Edit", of: main) + // Paste and nothing else. Copy, Cut, Undo and Select All have no + // builtin behind them — the core yanks into the clipboard on its own + // selection gestures and has no undo command to call — and a greyed or + // silently dead menu item teaches the user the menu lies. When the core + // grows those commands they belong here, spelled as run("...") like + // everything else. + edit.addItem(command("Paste", #selector(menuPaste(_:)), "v")) + + // The only menu whose items are not core commands: the font size is a + // property of this shell and nothing else. `Font` picks the FACE and + // lives in the topbar with the other builtins; the size is where the + // window is, so it is where macOS keeps it. + let viewMenu = submenu("View", of: main) + // Cmd+= rather than Cmd++: the key is unshifted `=` on every layout + // that has a `+` above it, and AppKit matches the character, not the + // engraving. The item is titled with the plus users look for. + viewMenu.addItem(command("Zoom In", #selector(menuZoomIn(_:)), "=")) + viewMenu.addItem(command("Zoom Out", #selector(menuZoomOut(_:)), "-")) + viewMenu.addItem(command("Actual Size", #selector(menuZoomReset(_:)), "0")) + + let windowMenu = submenu("Window", of: main) + windowMenu.addItem(withTitle: "Minimize", + action: #selector(NSWindow.performMiniaturize(_:)), keyEquivalent: "m") + windowMenu.addItem(withTitle: "Zoom", action: #selector(NSWindow.performZoom(_:)), keyEquivalent: "") + + let help = submenu("Help", of: main) + // Cmd+? is the system-wide help chord; AppKit draws it as the shift of + // Cmd+/ without being told about the shift. + help.addItem(command("\(appName) Help", #selector(menuHelp(_:)), "?")) + help.addItem(command("Tutorial", #selector(menuTutor(_:)), "")) + + NSApp.mainMenu = main + // Handing AppKit these two makes it keep the window list up to date and + // put the Help search field at the top of the Help menu. Both must come + // after mainMenu is assigned, or AppKit has nothing to attach them to. + NSApp.windowsMenu = windowMenu + NSApp.helpMenu = help + } + + private func submenu(_ title: String, of parent: NSMenu) -> NSMenu { + let holder = NSMenuItem(title: title, action: nil, keyEquivalent: "") + // The submenu's own title is what AppKit shows in the menu bar for the + // Window and Help menus, which it looks up by title rather than by the + // item that holds them. + let menu = NSMenu(title: title) + holder.submenu = menu + parent.addItem(holder) + return menu + } + + // An item that runs one of our own actions. Explicitly targeted at self + // rather than left to the responder chain: PardesView is the first + // responder and answers none of these, and an untargeted item that finds no + // handler renders greyed out. + private func command(_ title: String, _ action: Selector, _ key: String) -> NSMenuItem { + let item = NSMenuItem(title: title, action: action, keyEquivalent: key) + item.target = self + return item + } + + @objc private func menuOpen(_ sender: Any?) { + let panel = NSOpenPanel() + panel.canChooseFiles = true + // Directories are first-class Look targets — the core opens one as a + // directory pane, which is how you navigate in acme — so refusing them + // here would hide half of what Look does. + panel.canChooseDirectories = true + panel.allowsMultipleSelection = true + for url in panel.urls where url.isFileURL { + look(url.path) + } + } + + /// Any workspace-tag word. The title is the builtin's own spelling, so + /// this is the same `run` a tag Exec performs and there is no second + /// vocabulary to keep in step. + @objc private func menuBuiltin(_ sender: NSMenuItem) { run(sender.title) } + + + @objc private func menuNew(_ sender: Any?) { run("New") } + @objc private func menuSave(_ sender: Any?) { run("Save") } + @objc private func menuHelp(_ sender: Any?) { run("Help") } + @objc private func menuTutor(_ sender: Any?) { run("Tutor") } + + // Deliberately the view's paste path and not a second one: Cmd+V from the + // menu and Cmd+V in the view must put the same bytes in through + // pardes_paste, or the two would diverge the first time either grows a + // filter. + @objc private func menuPaste(_ sender: Any?) { + guard coreIsUp else { return } + pardesViewRequestsPaste(view) + } + + // Zoom does not go through the core at all: it changes the cell, the view + // reports the new grid, and the core reflows to it exactly as it does for + // a window drag. Guarded on coreIsUp only because the resize callback it + // triggers calls into libpardes. + @objc private func menuZoomIn(_ sender: Any?) { + guard coreIsUp else { return } + view.zoom(by: 1) + } + + @objc private func menuZoomOut(_ sender: Any?) { + guard coreIsUp else { return } + view.zoom(by: -1) + } + + @objc private func menuZoomReset(_ sender: Any?) { + guard coreIsUp else { return } + view.zoomReset() + } + + // ---------------------------------------------------------------- core + + // One builtin command line, run as if it had been typed into a tag and + // executed. `command` is bridged to a temporary NUL-terminated UTF-8 buffer + // that lives exactly as long as the call, which is exactly as long as the + // core borrows it. + private func run(_ command: String) { + guard coreIsUp else { return } + pardes_command(command, command.utf8.count) + pump() + } + + // Look's operand is the whole tail of the line (executeBuiltinLine in + // src/pardes.zig splits on the first space and trims the rest), so a path + // with spaces in it needs no quoting and must not get any — quotes would + // become part of the filename. + private func look(_ path: String) { run("Look \(path)") } + + // argv paths are whatever the shell handed us. The core resolves a relative + // Look against the pane's directory, not the process's, so `pardes + // ./foo.zig` would open the wrong foo.zig — or nothing — unless it is made + // absolute here against the directory the process was launched from. + private func absolutePath(of argument: String, relativeTo directory: String) -> String { + let expanded = (argument as NSString).expandingTildeInPath + guard !(expanded as NSString).isAbsolutePath else { + return (expanded as NSString).standardizingPath + } + return ((directory as NSString).appendingPathComponent(expanded) as NSString).standardizingPath + } + + /// Dress the WINDOW in what the core is wearing: the background AppKit + /// paints where the view does not (the titlebar, and the strip a live + /// resize outruns). + /// + /// Cheap enough to call every pump: the view compares before it dirties + /// itself, and the window properties are written only when the answer + /// moved. `dressed` is what makes the FIRST call unconditional — a boot + /// theme whose background happened to equal the view's starting guess + /// would otherwise leave the window in AppKit's default clothes forever. + private var dressed = false + + private func applyTheme() { + // Both reads happen every pump, and neither may be short-circuited by + // the other: `changed` has to be the OR of two adoptions, not the first + // one that answered true, or a Theme and a WindowOpacity in the same + // tick would leave one of them unworn. + let themeChanged = view.adoptThemeBG(pardes_theme_bg()) + let opacityChanged = view.adoptWindowOpacity(pardes_window_opacity()) + guard themeChanged || opacityChanged || !dressed else { return } + dressed = true + if let rgb = view.themeBG { + window.isOpaque = view.backgroundAlpha >= 1 + window.backgroundColor = view.backgroundAlpha < 1 ? .clear : NSColor( + srgbRed: CGFloat((rgb >> 16) & 0xFF) / 255, + green: CGFloat((rgb >> 8) & 0xFF) / 255, + blue: CGFloat(rgb & 0xFF) / 255, + alpha: view.backgroundAlpha) + // ...and follow the theme into light mode, so the titlebar, the + // traffic lights and the resize cursor stop belonging to a + // different application than the grid under them. Luminance off + // the same sRGB channels the grid is drawn with. + let luma = (0.2126 * CGFloat((rgb >> 16) & 0xFF) + + 0.7152 * CGFloat((rgb >> 8) & 0xFF) + + 0.0722 * CGFloat(rgb & 0xFF)) / 255 + window.appearance = NSAppearance(named: luma > 0.5 ? .aqua : .darkAqua) + } else { + // Transparent: the window stops painting anything of its own. + // isOpaque false lets the desktop show through at all — a titled + // window is opaque by default and would composite over it. + window.isOpaque = false + window.backgroundColor = .clear + window.appearance = NSAppearance(named: .darkAqua) + } + } + + /// The focused pane, in the titlebar: the proxy icon macOS lets you drag + /// and Cmd-click for the path, and the dot in the close button that means + /// unsaved. + /// + /// A pure read-out — the window says what the core already decided, and + /// nothing here can change it. There is no document ARCHITECTURE behind it + /// and deliberately so: no NSDocument, no save panel, no "do you want to + /// save" on close. Save is a builtin, the pane's tag says so, and this is + /// the same two facts spelled where a Mac user looks for them. + /// + /// Cached, because setting representedURL makes AppKit hit the filesystem + /// for the icon and this runs on every pump. + private var shownPath: String? + private var shownDirty = false + + private func applyDocument() { + let path = pardes_active_path().map { String(cString: $0) } + if path != shownPath { + shownPath = path + // A terminal or an output buffer is not a document: no path means + // no proxy icon, rather than a stale one from the last file pane. + window.representedURL = path.map { URL(fileURLWithPath: $0) } + // ...and the title goes with it. A proxy icon beside a title that + // names something else reads as a bug, and AppKit will not fill the + // title in for us while `title` has been set by hand. The window is + // a SESSION and not a document, so it falls back to the app's own + // name the moment focus lands somewhere with no file behind it. + window.title = path.map { ($0 as NSString).lastPathComponent } ?? "pardes" + } + let dirty = pardes_active_dirty() + if dirty != shownDirty { + shownDirty = dirty + window.isDocumentEdited = dirty + } + } + + @objc private func inputArrived(_ notification: Notification) { + pump() + } + + // Every path into the core ends here. pardes_tick drains the ptys and runs + // the effects the core queued, so nothing the user did takes hold until it + // runs. + private func pump() { + // Unconditionally dirty, and NOT `if pardes_tick()`. That return value + // answers "did I do any IO" — it is true when a pty produced bytes or + // an effect was performed, and false for everything the core changes on + // its own. A cursor moved with j, a selection, a mode change and a + // scroll all queue nothing and perform nothing, so gating the repaint + // on it leaves the screen showing the state before the keystroke until + // some unrelated event happens to force a frame. Measured: four `j` + // presses in a file pane produced a byte-identical screenshot. + // + // The waste is bounded and small. AppKit coalesces needsDisplay within + // a runloop pass, so a burst of pty output is still one frame, and an + // idle wakeup cannot happen — a reader only wakes the host after it has + // read bytes. + _ = pardes_tick() + view.needsDisplay = true + // TaglineSize is host-owned raster state just like Font, but unlike a + // body face change it does not resize the grid. Polling the one-byte + // core setting keeps startup config and live commands on one path. + view.adoptTaglinePercent(pardes_gui_tagline_font_percent()) + // After the tick, because a `Theme` command runs inside it and the + // window has to follow the grid in the same frame rather than at the + // next launch. + applyTheme() + applyDocument() + + // Two verbs, two patterns, because they are two different answers: + // Exec did something, so it gets .generic, the definite tap of a + // committed action; Look went somewhere, so it gets .alignment, the + // lighter detent AppKit uses when a dragged guide snaps into place. + // Same distinction the core draws in Haptic (src/pardes.zig). + // + // No capability check on purpose. perform() is a silent no-op on a Mac + // with no Force Touch trackpad and when the user has turned feedback + // off in System Settings, so a check here would only be a second place + // to get the answer wrong — and it would be wrong the moment an + // external trackpad is plugged in mid-session. + let pulse = pardes_take_haptic() + if pulse == PARDES_HAPTIC_EXEC { + NSHapticFeedbackManager.defaultPerformer.perform(.generic, performanceTime: .now) + } else if pulse == PARDES_HAPTIC_LOOK { + NSHapticFeedbackManager.defaultPerformer.perform(.alignment, performanceTime: .now) + } + + // Beside the haptic, and for the same reason: the `Font` builtin ran + // synchronously inside whatever input reached the core, so its answer + // is already waiting by the time the tick returns. The view re-measures + // and calls back through pardesViewDidResize, so the grid the core is + // holding follows the cell that just changed size. + var fontSize: UInt16 = 0 + if let wanted = pardes_font_take(&fontSize) { + view.adoptFont(path: String(cString: wanted), sizeHundredths: fontSize) + } + + if pardes_should_quit() { + NSApp.terminate(nil) + return + } + // Input and pty pumps only drain work. A frame-count animation advances + // on this 16 ms clock, and only after the sample dirtied above was + // actually presented. A burst of input cannot make it run fast, while + // an occluded/coalesced AppKit view cannot consume invisible samples. + scheduleAnimationFrame() + } + + private func scheduleAnimationFrame() { + guard pardes_animating() else { + stopDisplayLink() + return + } + if #available(macOS 14.0, *) { + // One link for the whole animating run, not one callback armed per + // frame: re-arming after the work is what put the period at 16 ms + // PLUS the work, and no amount of tuning that constant fixes a + // clock that is not the display's. + if displayLink == nil { + let link = view.displayLink(target: self, selector: #selector(displayLinkFired)) + link.add(to: .main, forMode: .common) + displayLink = link + } + return + } + // macOS 13 has no NSView display link. Keep the old chain, which is now + // only a cadence compromise rather than a correctness one — the tick + // spends measured time either way. + guard !pumpScheduled else { return } + let awaitingPresentation = view.presentationSerial + pumpScheduled = true + DispatchQueue.main.asyncAfter(deadline: .now() + 0.016) { + self.pumpScheduled = false + self.animationFrame(after: awaitingPresentation) + } + } + + private func stopDisplayLink() { + if #available(macOS 14.0, *) { (displayLink as? CADisplayLink)?.invalidate() } + displayLink = nil + } + + @objc private func displayLinkFired() { + guard coreIsUp else { return } + animationFrame(after: pendingPresentation) + } + + /// The presentation serial the last dirtied sample is waiting on. Held + /// across display-link callbacks because the link, unlike the old chain, + /// does not carry it in a closure. + private var pendingPresentation: UInt64 = 0 + + private func animationFrame(after awaitingPresentation: UInt64) { + guard view.presentationSerial != awaitingPresentation else { + // Keep the dirty sample pending. AppKit may have coalesced this + // draw or the window may be occluded; retry on the next refresh + // without advancing, until draw(_:) supplies the presentation + // permit. On the link that costs ONE refresh; the old chain paid a + // fresh 16 ms for it, which is where the visible hitching came from. + view.needsDisplay = true + if #available(macOS 14.0, *) {} else { scheduleAnimationFrame() } + return + } + _ = pardes_animation_tick() + pendingPresentation = view.presentationSerial + pump() + } + + func pardesViewDidResize(_ view: PardesView) { + let grid = view.gridSize + // cell_w/cell_h are physical pixels. The core hands them to the native + // PDF placement path, and a point is two pixels on a Retina display, so + // passing points would place every page at half size. + let scale: CGFloat = window.backingScaleFactor + pardes_resize( + grid.cols, grid.rows, + UInt16((view.cellWidth * scale).rounded()), + UInt16((view.cellHeight * scale).rounded())) + pardes_row_metrics(UInt16(max(1,(view.cellWidth*scale).rounded())), UInt16(max(1,(view.cellHeight*scale).rounded())), + UInt16(max(1,(view.taglineCellWidth*scale).rounded())), UInt16(max(1,(view.taglineBandHeight*scale).rounded()))) + pump() + } + + func pardesViewRequestsPaste(_ view: PardesView) { + guard let text = NSPasteboard.general.string(forType: .string) else { return } + AppDelegate.paste(text) + pump() + } + + // Swift lends a temporary NUL-terminated UTF-8 buffer for the duration of + // the call, which is exactly as long as the core borrows it. Static, and + // pumping is the caller's business: the read_clipboard callback is a C + // function pointer that can capture nothing and is already inside a tick, + // where the gesture path is not. + private static func paste(_ text: String) { + pardes_paste(text, text.utf8.count) + } + + // ponytail: one window, no tabs — the core has no multi-window notion, so + // the last window closing really is the end of the process. + func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { + return true + } + + // Nothing in this app's UI state can be restored: the window is one view + // over a core that has to replay its own session, and the frame is already + // handled by setFrameAutosaveName. Answering true opts into the secure + // coder AppKit wants; leaving the method out makes macOS 14 and later log a + // deprecation warning on every launch. + func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool { + return true + } + + func applicationWillTerminate(_ notification: Notification) { + pardes_deinit() + } +} diff --git a/dev/macos/Sources/FileWatcher.swift b/dev/macos/Sources/FileWatcher.swift new file mode 100644 index 00000000..1fee2fd8 --- /dev/null +++ b/dev/macos/Sources/FileWatcher.swift @@ -0,0 +1,122 @@ +// Per-path live reload for the native app. One source watches the file for +// in-place writes; another watches its parent because editors normally save by +// renaming a new inode over the old one. The file source is rearmed after a +// quiet edge so it follows that replacement rather than the unlinked old inode. + +import Darwin +import Dispatch +import Foundation + +private final class WatchedPath { + let pane: UInt8 + let generation: UInt32 + private let path: String + private let directorySource: DispatchSourceFileSystemObject + private var fileSource: DispatchSourceFileSystemObject? + private var active = true + private var eventSerial: UInt64 = 0 + + init?(pane: UInt8, generation: UInt32, path: String) { + let directory = URL(fileURLWithPath: path) + .deletingLastPathComponent().path + let descriptor = directory.withCString { + Darwin.open($0, O_EVTONLY | O_CLOEXEC) + } + guard descriptor >= 0 else { return nil } + + self.pane = pane + self.generation = generation + self.path = path + directorySource = DispatchSource.makeFileSystemObjectSource( + fileDescriptor: descriptor, + eventMask: [.write, .delete, .rename, .extend, .attrib, .link, .revoke], + queue: .main) + directorySource.setCancelHandler { _ = Darwin.close(descriptor) } + directorySource.setEventHandler { [weak self] in self?.pathChanged() } + reopenFileSource() + directorySource.activate() + } + + /// The directory source catches rename-over saves, while the file source + /// catches programs which truncate/write the existing inode. Reopen the + /// latter after every quiet edge because an atomic save leaves it attached + /// to the unlinked old inode forever otherwise. + private func reopenFileSource() { + if let old = fileSource { old.cancel() } + fileSource = nil + guard active else { return } + let descriptor = path.withCString { Darwin.open($0, O_EVTONLY | O_CLOEXEC) } + guard descriptor >= 0 else { return } + let next = DispatchSource.makeFileSystemObjectSource( + fileDescriptor: descriptor, + eventMask: [.write, .delete, .rename, .extend, .attrib, .link, .revoke], + queue: .main) + next.setCancelHandler { _ = Darwin.close(descriptor) } + next.setEventHandler { [weak self] in self?.pathChanged() } + fileSource = next + next.activate() + } + + /// Vnode sources can emit several edges for one save. Reset a small quiet + /// period on every edge; generation plus exact Zig-side identity checks + /// remain authoritative, so this delay is latency control rather than + /// correctness state. + private func pathChanged() { + guard active else { return } + eventSerial &+= 1 + let scheduled = eventSerial + DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(45)) { [weak self] in + guard let self, self.active, self.eventSerial == scheduled else { return } + self.reopenFileSource() + pardes_watch_changed(self.pane, self.generation) + } + } + + func cancel() { + guard active else { return } + active = false + eventSerial &+= 1 + if let old = fileSource { old.cancel() } + fileSource = nil + directorySource.cancel() + } + + deinit { cancel() } +} + +private final class FileWatchRegistry { + static let shared = FileWatchRegistry() + private var slots: [UInt8: WatchedPath] = [:] + + func set(pane: UInt8, generation: UInt32, path: String?) { + if let old = slots.removeValue(forKey: pane) { old.cancel() } + guard let path, + let watched = WatchedPath( + pane: pane, generation: generation, path: path) + else { return } + slots[pane] = watched + } +} + +/// Called only by libpardes's main-thread effect drain. A nil pointer stops the +/// slot. The byte count avoids a second sentinel copy in Zig; Foundation paths +/// are Unicode, so malformed UTF-8 is rejected rather than watched under a +/// replacement spelling that could name a different file. +@_cdecl("pardes_host_watch_file") +func pardesHostWatchFile( + _ pane: UInt8, + _ generation: UInt32, + _ path: UnsafePointer<UInt8>?, + _ pathLength: Int +) { + guard let path, pathLength > 0 else { + FileWatchRegistry.shared.set(pane: pane, generation: generation, path: nil) + return + } + let bytes = UnsafeBufferPointer(start: path, count: pathLength) + guard let value = String(bytes: bytes, encoding: .utf8) else { + FileWatchRegistry.shared.set(pane: pane, generation: generation, path: nil) + return + } + FileWatchRegistry.shared.set(pane: pane, generation: generation, path: value) +} diff --git a/dev/macos/Sources/PardesView.swift b/dev/macos/Sources/PardesView.swift new file mode 100644 index 00000000..23cd0f78 --- /dev/null +++ b/dev/macos/Sources/PardesView.swift @@ -0,0 +1,2728 @@ +// The AppKit half of the macOS backend: NSEvent in, pardes_* out, one +// CoreGraphics pass per frame back. +// +// This file keeps no model of the screen. The core owns the grid and hands it +// over whole through src/macos/pardes.h, so everything here is translation, and +// the only state worth holding is the font metrics — expensive to measure and +// replaced only by Font/TaglineSize/zoom — plus the gesture state remembered +// between events: which button a click started with, and how hard it is being +// pressed. +// +// Every NSEvent override decodes and then calls one of the post-decode entry +// points below (press/release/drag/click/scroll/rotate/typeKey). That split is +// not decoration: NSTouch, pressure stages and rotation have no public +// constructors, so a test can never synthesize them, and the only way the +// trackpad behaviour is reachable by anything but a finger is for the decision +// to live one call below the event. test/macos_e2e.swift drives exactly those +// entry points. +// +// Every C constant below is wrapped in an explicit conversion (UInt16(...), +// UInt32(...)) rather than used bare. A macro's imported Swift type is decided +// by the importer, not by us, and this file should not have an opinion about it. + +import AppKit +import CoreText + +/// Posted after every call this view makes into the core, and answered by +/// AppDelegate.pump(). The core only queues what it was told and does nothing +/// until it is pumped, so an input without one of these is an input that +/// visibly did nothing. Declared here, where the posts are. +let pardesDidInputNotification = Notification.Name("pardesDidInput") + +/// A cell, already clamped to the frame the core last rendered. +struct GridPoint { + var col: UInt16 + var row: UInt16 +} + +protocol PardesViewDelegate: AnyObject { + func pardesViewDidResize(_ view: PardesView) + func pardesViewRequestsPaste(_ view: PardesView) +} + +/// What a click means, from the fingers resting on the trackpad and the button +/// stream AppKit chose to deliver it on. Pure on purpose: NSTouch cannot be +/// constructed, so this is the part of the gesture a test can reach. +/// +/// acme's three buttons are the whole vocabulary — 1 selects, 2 executes, +/// 3 looks — and a trackpad has one surface. More than one finger is Exec, +/// because running something is what a hand does over and over and it gets +/// the gesture that costs nothing; Look is the deep press, one deliberate +/// push past the click for the verb that goes somewhere. +/// +/// Two and three fingers are the same verb here, and that is the hardware +/// talking rather than a shrug. macOS's secondary click is "click or tap with +/// TWO OR MORE fingers": with it on — the default — a three-finger click is +/// delivered as rightMouseDown exactly like a two-finger one, and a view that +/// trusts the stream calls both of them Look. Measured on real hardware, which +/// is the only way this was ever going to be found: +/// `rightMouseDown: resting=3`. So the count is what keeps a multi-finger +/// click off Look, and the stream cannot be trusted to do it. +/// +/// The stream is only the fallback, for when there are no fingers to count: +/// a real mouse's right button is Look and its middle button is Exec, and both +/// arrive with an empty touch set. +enum Trackpad { + static func button(stream: pardes_mouse_button_e, fingers: Int) -> pardes_mouse_button_e { + switch fingers { + case 2...: return PARDES_MOUSE_MIDDLE + // One finger, or none to count: the stream is the answer. A trackpad + // single click comes in on the left stream and stays left; a real + // mouse's right and middle buttons keep their acme meanings. + default: return stream + } + } + + /// A force click is a deliberate second gesture on top of an ordinary one, + /// so it gets the verb that goes somewhere rather than the one that runs + /// something: press harder and you Look. + static let forceClickButton: pardes_mouse_button_e = PARDES_MOUSE_RIGHT +} + +// Matches bg_default/fg_default in src/gui/gui.zig. Two shells render the +// same core; if these drift, comparing +// a screenshot across backends stops meaning anything. +let pardesDefaultFG: UInt32 = 0xCC_CC_CC +let pardesDefaultBG: UInt32 = 0x12_12_12 + +/// Pinned sRGB for rasterized attachments, so a PDF page's bytes mean the same +/// thing here as they do in the SDL shell. DeviceRGB is the fallback rather +/// than a crash: a machine with no sRGB profile is not a reason to stop +/// drawing pages. +private let sRGB: CGColorSpace = CGColorSpace(name: CGColorSpace.sRGB) ?? CGColorSpaceCreateDeviceRGB() + +// UNVERIFIED: kCTFontAttributeName bridged through NSAttributedString.Key. It is +// the same string as .font, but spelling the CoreText key means the value stays +// a CTFont instead of being bridged to NSFont on the way in. +private let fontAttribute = NSAttributedString.Key(kCTFontAttributeName as String) + +// The named sixteen, then xterm's 6x6x6 cube, then the 24-step grey ramp. These +// sixteen are app.mjs's, not gui.zig's: gui.zig borrows ghostty's palette +// because it already links it, and the two disagree on the base colors. +private let ansi16: [UInt32] = [ + 0x00_00_00, 0xCC_00_00, 0x4E_9A_06, 0xC4_A0_00, + 0x34_65_A4, 0x75_50_7B, 0x06_98_9A, 0xD3_D7_CF, + 0x55_57_53, 0xEF_29_29, 0x8A_E2_34, 0xFC_E9_4F, + 0x72_9F_CF, 0xAD_7F_A8, 0x34_E2_E2, 0xEE_EE_EC, +] + +private func paletteColor(_ index: UInt8) -> UInt32 { + if index < 16 { return ansi16[Int(index)] } + if index >= 232 { + let grey = UInt32(8 + (Int(index) - 232) * 10) + return grey << 16 | grey << 8 | grey + } + let n = Int(index) - 16 + func level(_ part: Int) -> UInt32 { part == 0 ? 0 : UInt32(55 + part * 40) } + return level(n / 36) << 16 | level(n / 6 % 6) << 8 | level(n % 6) +} + +private func decodeColor(_ encoded: UInt32, _ fallback: UInt32) -> UInt32 { + if encoded == UInt32(PARDES_COLOR_DEFAULT) { return fallback } + if encoded & UInt32(PARDES_COLOR_TAG_MASK) == UInt32(PARDES_COLOR_INDEXED) { + return paletteColor(UInt8(encoded & 0xFF)) + } + return encoded & UInt32(PARDES_COLOR_RGB_MASK) +} + +/// The four faces, indexed by the two attribute bits that pick one. Also the +/// glyph cache's first key, which is why it is an ordinal and not four fields. +private enum Face: Int, CaseIterable { + case regular = 0, bold = 1, italic = 2, boldItalic = 3 + + init(bold: Bool, italic: Bool) { + self = Face(rawValue: (bold ? 1 : 0) | (italic ? 2 : 0))! + } +} + +/// A background run that must not be painted at all, so the window's own +/// backdrop shows through. Outside the 24-bit RGB range, so it can never +/// collide with a real colour, and distinct from the `.max` the run loop +/// flushes on. +let bgClear: UInt32 = 0x0100_0000 + +/// `block` means the filled cursor sits on this cell. `ground` is what a +/// DEFAULT background resolves to, and `clearGround` asks for those cells to +/// come back as `bgClear` instead of a colour. +private func resolve( + _ cell: pardes_cell_s, + block: Bool, + ground: UInt32, + clearGround: Bool +) -> (fg: UInt32, bg: UInt32, alpha: CGFloat, visible: Bool) { + // The core never painted this cell, which is most of the screen most of the + // time, so this branch is the one that has to stay cheap. + if cell.flags & UInt8(PARDES_CELL_DEFAULT) != 0 { + return block + ? (ground, pardesDefaultFG, 1, false) + : (pardesDefaultFG, clearGround ? bgClear : ground, 1, false) + } + let bgDefault = cell.bg == UInt32(PARDES_COLOR_DEFAULT) + var fg = decodeColor(cell.fg, pardesDefaultFG) + var bg = decodeColor(cell.bg, ground) + // The block cursor is a second reverse, so a cell that is already reversed + // cancels back to normal underneath it. Same rule as emitInstance in + // src/gui/gui.zig; the two must not drift. + var reverse = block + if cell.attrs & UInt16(PARDES_ATTR_REVERSE) != 0 { reverse = !reverse } + if reverse { swap(&fg, &bg) } + // ponytail: PARDES_ATTR_BLINK is decoded into nothing. Honouring it costs a + // timer plus a repaint budget for a bit nothing in pardes emits today; drive + // setNeedsDisplay from an NSTimer here when something does. + let visible = cell.attrs & UInt16(PARDES_ATTR_INVISIBLE) == 0 && cell.len > 0 + // The other shells scale the channels by 6/10. Over a dark background alpha + // lands in the same place and costs one blend instead of three multiplies. + let alpha: CGFloat = cell.attrs & UInt16(PARDES_ATTR_DIM) != 0 ? 0.6 : 1 + // Only an UNREVERSED default background is the ground. A reverse puts the + // text colour there, and text is a real colour that paints. + if clearGround && bgDefault && !reverse { bg = bgClear } + return (fg, bg, alpha, visible) +} + +private func advance(_ font: CTFont, _ character: UniChar) -> CGFloat { + var input = character + var glyph = CGGlyph(0) + guard CTFontGetGlyphsForCharacters(font, &input, &glyph, 1) else { return 0 } + var size = CGSize.zero + CTFontGetAdvancesForGlyphs(font, .horizontal, &glyph, &size, 1) + return size.width +} + +/// The size the window opens at and Cmd+0 returns to. Named here rather than +/// passed in because zoomReset has to know it too, and two spellings of one +/// number is how "actual size" stops being the size it actually opened at. +let defaultFontSize: CGFloat = 14 + +/// The faces CoreText should reach for when the grid face has no glyph. +/// +/// The SDL shell loads a chain of fallback faces itself and rasterizes from +/// whichever one has the codepoint. This shell draws its non-ASCII through +/// CTLine, which already walks a cascade — but the SYSTEM cascade, and the +/// system cascade has never heard of a Nerd Font. Measured on a machine with +/// Mononoki Nerd Font installed: U+E0B0, U+E5FF, U+E700 and U+F015 all resolved +/// to `LastResort`, which is the tofu box. Braille, emoji and CJK resolved +/// fine, which is exactly why this went unnoticed — everything Unicode has an +/// opinion about already worked, and only the Private Use Area did not. +/// +/// Two sources, in this order: +/// +/// 1. `fonts.fallback_names` over the C ABI, so the PREFERENCE ORDER is the +/// one the SDL shell uses and lives in one file. +/// 2. Installed Nerd Font families, found by name and then CONFIRMED BY +/// COVERAGE. Both halves are load-bearing. Coverage alone is not enough: a +/// scan of all 250 families here put `Hannotate TC` and `HanziPen TC` at +/// 4 of 6 probes, because CJK faces map the PUA for their own purposes and +/// would answer a powerline request with an unrelated ideograph. A name +/// alone is not enough either, because "Nerd Font" in a family name is a +/// convention, not a guarantee. So the name decides what a codepoint MEANS +/// and coverage decides whether the face can actually draw it. +/// +/// Computed once. The result is a list of descriptors, which carry no size, so +/// a zoom or a `Font` command reuses it; only installing a font invalidates it, +/// and that is a relaunch. +private enum FontFallbacks { + /// Representative codepoints, one per Nerd Font block that matters: + /// powerline separators, Seti file icons, devicons, Font Awesome. A face + /// answering all four is patched; a face answering one is a coincidence. + private static let nerdProbes: [UInt32] = [0xE0B0, 0xE5FF, 0xE700, 0xF015] + + static let descriptors: [CTFontDescriptor] = build() + + private static func build() -> [CTFontDescriptor] { + var out: [CTFontDescriptor] = [] + var seen = Set<String>() + + func take(_ family: String, _ descriptor: CTFontDescriptor) { + guard seen.insert(family).inserted else { return } + out.append(descriptor) + } + + // 1. The shared preference order. + for index in 0..<pardes_fallback_font_count() { + var length: UInt32 = 0 + guard let bytes = pardes_fallback_font_name(index, &length), length > 0 else { continue } + let name = String(decoding: UnsafeRawBufferPointer(start: bytes, count: Int(length)), as: UTF8.self) + guard let found = resolve(name) else { continue } + take(found.family, found.descriptor) + } + + // 2. Nerd Fonts that are installed AND cover the blocks. `Mono` cuts + // first: this is a fixed grid, and the propo/variable cuts of the + // same family are drawn to different advances. + let families = (CTFontManagerCopyAvailableFontFamilyNames() as? [String]) ?? [] + let nerd = families.filter { $0.range(of: "nerd font", options: .caseInsensitive) != nil } + for family in nerd.sorted(by: { rank($0) < rank($1) }) { + let descriptor = CTFontDescriptorCreateWithAttributes( + [kCTFontFamilyNameAttribute: family] as CFDictionary) + guard coverage(descriptor, nerdProbes) == nerdProbes.count else { continue } + take(family, descriptor) + } + return out + } + + /// "Mono" before "Propo" before the proportional cut. + private static func rank(_ family: String) -> Int { + if family.range(of: "nerd font mono", options: .caseInsensitive) != nil { return 0 } + if family.range(of: "nerd font propo", options: .caseInsensitive) != nil { return 2 } + return 1 + } + + /// A descriptor that really is the font asked for. CoreText SUBSTITUTES + /// rather than failing — asking it for an uninstalled `SymbolsNerdFont- + /// Regular` hands back Helvetica, and a cascade seeded with Helvetica is a + /// cascade that answers every missing glyph with the wrong one. + private static func resolve(_ name: String) -> (family: String, descriptor: CTFontDescriptor)? { + for attribute in [kCTFontNameAttribute, kCTFontFamilyNameAttribute] { + let query = CTFontDescriptorCreateWithAttributes([attribute: name] as CFDictionary) + guard let match = CTFontDescriptorCreateMatchingFontDescriptor(query, nil) else { continue } + let postScript = CTFontDescriptorCopyAttribute(match, kCTFontNameAttribute) as? String ?? "" + let family = CTFontDescriptorCopyAttribute(match, kCTFontFamilyNameAttribute) as? String ?? "" + guard postScript.compare(name, options: .caseInsensitive) == .orderedSame + || family.compare(name, options: .caseInsensitive) == .orderedSame + else { continue } + return (family.isEmpty ? postScript : family, match) + } + return nil + } + + /// How many of `codepoints` this face can actually draw. Size is irrelevant + /// to coverage, so the probe face is built at a nominal one. + private static func coverage(_ descriptor: CTFontDescriptor, _ codepoints: [UInt32]) -> Int { + let font = CTFontCreateWithFontDescriptor(descriptor, 12, nil) + var hits = 0 + for codepoint in codepoints { + guard let scalar = UnicodeScalar(codepoint) else { continue } + var units = Array(String(scalar).utf16) + var glyphs = [CGGlyph](repeating: 0, count: units.count) + if CTFontGetGlyphsForCharacters(font, &units, &glyphs, units.count) { hits += 1 } + } + return hits + } + + /// `face` with the chain attached. Every face pardes draws with goes through + /// here exactly once, at the base: `CTFontCreateCopyWithSymbolicTraits` and + /// `CTFontCreateCopyWithAttributes` both carry the cascade into the copy, so + /// the bold/italic cuts and the smaller tagline cuts inherit it. + static func attach(to face: CTFont, size: CGFloat) -> CTFont { + guard !descriptors.isEmpty else { return face } + let descriptor = CTFontDescriptorCreateCopyWithAttributes( + CTFontCopyFontDescriptor(face), + [kCTFontCascadeListAttribute: descriptors] as CFDictionary) + return CTFontCreateWithFontDescriptor(descriptor, size, nil) + } +} + +/// Everything that changes when the face or its size does, in one value so +/// that changing either is one assignment and cannot leave half the numbers +/// describing the old font. +/// +/// Built at init and again for a `Font` command or a zoom. The view clears its +/// body/tagline glyph caches beside replacing this value: a CGGlyph is an index +/// into a particular face, so carrying one across a font change is invalid. +private struct Metrics { + let fonts: [CTFont] + /// False only when a non-nil requested file could not produce a fixed-pitch + /// CoreText face. The caller rejects that request and keeps old Metrics. + let acceptedPath: Bool + let ascent: CGFloat + let cellWidth: CGFloat + let cellHeight: CGFloat + let ruleThickness: CGFloat + let underlineOffset: CGFloat + /// ASCII is very nearly the whole screen, so its glyphs are resolved once + /// per face here and never looked up again. + let asciiGlyphs: [[CGGlyph]] + + /// Round `v` onto the backing grid: `scale` is the display's + /// backingScaleFactor, so at 2x this lands on half-points, which are whole + /// device pixels. + private static func snap(_ v: CGFloat, _ scale: CGFloat, _ rule: FloatingPointRoundingRule) -> CGFloat { + (v * scale).rounded(rule) / scale + } + + init(size: CGFloat, path: String?, scale: CGFloat) { + let requested = path.flatMap { Metrics.fromFile($0, size) } + // Attached ONCE, at the base: the trait and size copies below inherit + // the cascade, so every cut and the tagline's smaller cuts reach the + // same fallbacks. Metrics is measured from `face` too, and a cascade + // changes no metric — CoreText measures the primary face and only + // consults the chain for a codepoint it lacks. + let face = FontFallbacks.attach(to: requested ?? Metrics.defaultFace(size: size), size: size) + let scale = max(1, scale) + + // UNVERIFIED: CTFontSymbolicTraits member spelling (.traitBold/.traitItalic). + // A face with no italic cut returns nil here, hence the fallback to `face`. + func variant(_ traits: CTFontSymbolicTraits) -> CTFont { + CTFontCreateCopyWithSymbolicTraits(face, size, nil, traits, traits) ?? face + } + let faces = [face, variant(.traitBold), variant(.traitItalic), variant([.traitBold, .traitItalic])] + + // The grid has to land on WHOLE DEVICE PIXELS, and that is the whole + // constraint — a fractional column boundary makes the background pass + // (which runs with antialiasing off, or touching fills seam) wobble by + // a pixel from column to column, and on a screen made of tag bars and + // selections that stripe is visible. + // + // Whole POINTS is how that used to be spelled, and on a Retina display + // it asks for twice what it needs: half a point IS a whole pixel at 2x. + // The difference is not academic — Monaco advances 8.4014pt at 14, so + // ceiling to 9 spaced every column 7.1% wider than the face was drawn + // for, which is loose, washed-out text that reads as bad rendering. + // Snapped to the backing grid it is 8.5, i.e. +1.2%. + // + // Width rounds to NEAREST — a monospace glyph is drawn to fit its own + // advance, so the half-pixel either way is slack — while height rounds + // UP, because losing a pixel off a descender is clipping. + let snap = Metrics.snap + fonts = faces + acceptedPath = path == nil || requested != nil + // The ascent lands on a pixel for a second reason: it is the baseline's + // offset inside the cell, so the rules hung off it are whole-pixel + // fills rather than one-pixel bars smeared across two rows. + let bodyAscent = max(1 / scale, snap(CTFontGetAscent(face), scale, .toNearestOrAwayFromZero)) + let bodyWidth = max(1 / scale, snap(advance(face, 0x4D), scale, .toNearestOrAwayFromZero)) + let bodyHeight = max(1 / scale, snap(CTFontGetAscent(face) + CTFontGetDescent(face) + CTFontGetLeading(face), scale, .up)) + ascent = bodyAscent + cellWidth = bodyWidth + cellHeight = bodyHeight + ruleThickness = max(1 / scale, snap(CTFontGetUnderlineThickness(face), scale, .toNearestOrAwayFromZero)) + underlineOffset = snap(CTFontGetUnderlinePosition(face), scale, .toNearestOrAwayFromZero) + asciiGlyphs = faces.map { font in + var chars = Array(UniChar(0)..<UniChar(128)) + var glyphs = [CGGlyph](repeating: 0, count: 128) + _ = CTFontGetGlyphsForCharacters(font, &chars, &glyphs, 128) + return glyphs + } + } + + /// The regular system face used only when no file was requested. A failed + /// request is reported through `acceptedPath`; it never silently replaces + /// the face already on screen with this fallback. + private static func defaultFace(size: CGFloat) -> CTFont { + let system = NSFont.monospacedSystemFont(ofSize: size, weight: .regular) + // Through the descriptor, not through CTFontCreateWithName(fontName): + // the system monospace face has a dot-prefixed internal name that a + // by-name lookup can miss entirely, and NSFontDescriptor is toll-free + // bridged, so this cannot resolve to a different font than AppKit just + // handed us. + let face = CTFontCreateWithFontDescriptor(system.fontDescriptor as CTFontDescriptor, size, nil) + // The whole layout is a fixed grid, so a proportional face is not a + // cosmetic problem, it is a broken screen. "M" and "i" disagreeing on + // advance is the cheapest possible proof that we got one. + return Metrics.isFixedPitch(face) ? face : CTFontCreateWithName("Menlo" as CFString, size, nil) + } + + /// A face out of a font FILE, which is what the core hands over — it found + /// the path by walking the font directories itself, so nothing here asks + /// CoreText to resolve a name that a different shell might resolve + /// differently. + /// + /// Nil rather than a substitute for anything wrong with the file, because + /// the caller's fallback is the face already on screen: a font that cannot + /// be measured would otherwise leave a terminal with no way back out. + private static func fromFile(_ path: String, _ size: CGFloat) -> CTFont? { + let url = URL(fileURLWithPath: path) as CFURL + guard let descriptors = CTFontManagerCreateFontDescriptorsFromURL(url) as? [CTFontDescriptor], + !descriptors.isEmpty else { return nil } + // A .ttc holds a family's four cuts in one file. Take the one with + // neither trait set — the regular — because the bold and italic ones + // are derived from it below; falling back to the first face keeps a + // collection whose cuts are all styled from being unusable. + let plain = descriptors.first { descriptor in + let traits = CTFontDescriptorCopyAttribute(descriptor, kCTFontTraitsAttribute) as? [CFString: Any] + let symbolic = (traits?[kCTFontSymbolicTrait] as? UInt32) ?? 0 + return symbolic & UInt32(CTFontSymbolicTraits.traitBold.rawValue | CTFontSymbolicTraits.traitItalic.rawValue) == 0 + } + let chosen = CTFontCreateWithFontDescriptor(plain ?? descriptors[0], size, nil) + // A variable face's descriptor carries no variation, and CoreText + // picks whichever named instance it likes for it — Maple Mono's + // variable file comes up Thin. Pin every axis to its own default: + // the face the file itself calls regular. + var face = chosen + if let axes = CTFontCopyVariationAxes(face) as? [[CFString: Any]] { + var defaults: [CFNumber: Any] = [:] + for axis in axes { + guard let tag = axis[kCTFontVariationAxisIdentifierKey], + let value = axis[kCTFontVariationAxisDefaultValueKey] else { continue } + defaults[tag as! CFNumber] = value + } + if !defaults.isEmpty { + let descriptor = CTFontDescriptorCreateCopyWithAttributes( + CTFontCopyFontDescriptor(face), + [kCTFontVariationAttribute: defaults] as CFDictionary) + face = CTFontCreateWithFontDescriptor(descriptor, size, nil) + } + } + // The core already filtered for fixed pitch by reading the file's own + // advances. This is the same question asked of the face CoreText + // actually built, which is the one that will be drawn with. + return Metrics.isFixedPitch(face) ? face : nil + } + + private static func isFixedPitch(_ face: CTFont) -> Bool { + let em = advance(face, 0x4D) + return em > 0 && abs(em - advance(face, 0x69)) <= 0.01 + } +} + +/// The independently replaceable half of font state. A TaglineSize command +/// rebuilds only this value and its non-ASCII cache; body metrics and therefore +/// the core grid never move. `height` is also the painted tag-band height, not +/// merely a smaller glyph centred inside a body-height colour bar. +private struct TaglineMetrics { + let percent: UInt8 + let fonts: [CTFont] + /// The tagline face's OWN ascent. Deliberately not folded together with the + /// band's top offset the way it used to be: that offset is per-row now, and + /// a baseline carrying one row's offset would pin every band back to centre. + let ascent: CGFloat + /// The tagline face's OWN advance, clamped to the body cell it sits in. + /// A tag row steps by THIS, not by the body cell width: the band behind it + /// is still pane-wide on the body grid, but the text on top of it tracks at + /// the smaller face's own pitch. Centring a smaller glyph inside a + /// body-width cell instead — which is what this shell used to do — leaves + /// the tag text visibly looser than the same session in an SDL window. + let width: CGFloat + let height: CGFloat + let asciiGlyphs: [[CGGlyph]] + /// Kept so the band rules below can work in the physical pixels the core + /// states them in, and hand back points. + private let scale: CGFloat + private let bodyCellHeight: CGFloat + + init(body: Metrics, percent: UInt8, scale rawScale: CGFloat) { + let scale = max(1, rawScale) + func snap(_ value: CGFloat, _ rule: FloatingPointRoundingRule) -> CGFloat { + (value * scale).rounded(rule) / scale + } + self.percent = percent + self.scale = scale + bodyCellHeight = body.cellHeight + let size = CTFontGetSize(body.fonts[0]) * CGFloat(percent) / 100 + let faces = body.fonts.map { CTFontCreateCopyWithAttributes($0, size, nil, nil) } + fonts = faces + let face = faces[Face.regular.rawValue] + let measuredHeight = max(1 / scale, snap( + CTFontGetAscent(face) + CTFontGetDescent(face) + CTFontGetLeading(face), .up)) + // Runtime configuration caps the percentage at the body face. Keep the + // clamp here too: a malformed/custom host value must not paint a tag + // over the body row below it. + height = min(body.cellHeight, measuredHeight) + ascent = max(1 / scale, snap(CTFontGetAscent(face), .toNearestOrAwayFromZero)) + width = min(body.cellWidth, max(1 / scale, snap(advance(face, 0x4D), .toNearestOrAwayFromZero))) + asciiGlyphs = faces.map { font in + var chars = Array(UniChar(0)..<UniChar(128)) + var glyphs = [CGGlyph](repeating: 0, count: 128) + _ = CTFontGetGlyphsForCharacters(font, &chars, &glyphs, 128) + return glyphs + } + } + + private var cellPixels: UInt32 { UInt32(max(1, (bodyCellHeight * scale).rounded())) } + private var bandPixels: UInt32 { UInt32(max(1, (height * scale).rounded())) } + + /// Where this band sits inside row `row`, measured down from the row's top. + /// The rule belongs to the core (`pardes_tagline_band_offset`) so that this + /// shell and the SDL one cannot disagree about it: every band is centred, + /// except a Tagbottom band on the last row, which faces the window edge. + func top(row: Int, canvasHeight: CGFloat) -> CGFloat { + CGFloat(pardes_tagline_band_offset( + UInt16(clamping: row), Float(canvasHeight * scale), cellPixels, bandPixels)) / scale + } + + /// Canonical tag cells are physical grip slots; TagLayer positions text. + func glyphX(col: Int, row: Int, bodyCellWidth: CGFloat) -> CGFloat { + // Canonical tag cells are physical grips; TagLayer owns compact text. + CGFloat(col) * bodyCellWidth + } + + /// Thickness of the rule joining the topbar band to the first pane-tag band, + /// zero when the two are meant to join directly. + var borderThickness: CGFloat { + CGFloat(pardes_topbar_pane_border_px(cellPixels, bandPixels)) / scale + } + + /// Top of that rule. Placed the way the SDL shell places it, in WHOLE + /// pixels: half the rule above the topbar/pane boundary, floored, so a + /// one-pixel rule lands on the boundary instead of smeared across two rows. + var borderTop: CGFloat { + let px = pardes_topbar_pane_border_px(cellPixels, bandPixels) + return (CGFloat(cellPixels * UInt32(PARDES_TOPBAR_H)) - CGFloat(px / 2)) / scale + } + + /// One physical pixel, in points. The rules separating discontinuous + /// context rows inside a body layer are a single pixel in the SDL shell, + /// so they are stated there and converted here rather than handing `scale` + /// out and letting the caller reinvent the conversion. + var contextBorderThickness: CGFloat { 1 / scale } +} + +private func modifiers(_ flags: NSEvent.ModifierFlags) -> UInt32 { + var mods: UInt32 = 0 + if flags.contains(.control) { mods |= UInt32(PARDES_MOD_CTRL) } + if flags.contains(.option) { mods |= UInt32(PARDES_MOD_ALT) } + if flags.contains(.shift) { mods |= UInt32(PARDES_MOD_SHIFT) } + if flags.contains(.command) { mods |= UInt32(PARDES_MOD_SUPER) } + return mods +} + +final class PardesView: NSView { + weak var delegate: PardesViewDelegate? + + // The face and the numbers off it, replaced whole by `wear`. + private var metrics: Metrics + private var taglines: TaglineMetrics + /// What `metrics` was built from, so a zoom keeps the face and a font + /// change keeps the size. + private var fontSize: CGFloat + private var fontPath: String? + + var cellWidth: CGFloat { metrics.cellWidth } + var cellHeight: CGFloat { metrics.cellHeight } + + // Glyphs the ASCII table above did not answer for. A stored 0 is .notdef, + // meaning "this face does not have it", which is a cache hit too — the + // CTLine fallback below is far more expensive than the lookup it would + // repeat. Keyed by role, face and codepoint, and thrown away with both + // body and tagline variants whenever the body face changes. + private var bodyGlyphCache: [UInt32: CGGlyph] = [:] + private var taglineGlyphCache: [UInt32: CGGlyph] = [:] + private struct GripGlyph { + let line: CTLine + let ink: CGRect + } + private var gripGlyphCache: [String: GripGlyph] = [:] + // Scratch for one batched run of glyphs. Held rather than made per row so a + // full redraw does not allocate 24 times. + private var runGlyphs: [CGGlyph] = [] + private var runPositions: [CGPoint] = [] + /// Ligature shaping, keyed by face and text. A sequence ligates when + /// shaping it produces fewer glyphs than it has characters — the only + /// answer CoreText gives without interrogating the font's own features. + /// Cleared with the glyph caches, because it belongs to one face. + private var ligatureShaped: [String: Bool] = [:] + /// Columns the current row has already consumed as part of a ligature + /// drawn further left. One row's worth at a time. + private var ligatureCovered: Set<Int> = [] + /// Constructed lazily because the ordinary path is still a direct + /// CoreText/CoreGraphics frame. No scene bit and no panel track means no + /// bitmap, no Core Image context and no Metal work. + private lazy var scenePostprocessor: ScenePostprocessor? = ScenePostprocessor() + /// Kernel compilation is permanent for one executable. Runtime allocation + /// and device failures get three consecutive attempts before this session + /// stops advertising effects its GPU path cannot present. + private var postprocessorUnavailable = false + private var postprocessRetries = 0 + /// The scene mapping of the pixels AppKit most recently accepted. Pointer + /// events use this snapshot, not a clock that may already be one tick ahead. + private var lastPresentedScene: pardes_scene_s? + /// Whether the last frame reached the optional Metal owner successfully. + /// Ordinary direct draws and a runtime-kernel failure leave this false. + private(set) var lastFrameUsedPostprocessor = false + /// Monotonic count of frames AppKit actually let this view present. The + /// host animation clock uses it as a permit: no new sample is consumed + /// while an occluded/coalesced frame is still waiting to be drawn. + private(set) var presentationSerial: UInt64 = 0 + + private var reportedCols: UInt16 = 0 + private var reportedRows: UInt16 = 0 + + /// The backingScaleFactor `metrics` was snapped to, so a move between a + /// Retina and a 1x display re-measures the cell instead of leaving the grid + /// aligned to the other screen's pixels. + private var metricsScale: CGFloat = 2 + + /// The active theme's own background, or nil when it declares none — the + /// `*_transparent` themes and the curated `dark`. Nil is not a colour to + /// substitute but a decision: the ground stops being painted at all, the + /// view stops being opaque, and AppDelegate's NSVisualEffectView shows + /// through it. Read off pardes_theme_bg() once per pump, which is also + /// what makes a `Theme` command take hold without a relaunch. + private(set) var themeBG: UInt32? = pardesDefaultBG + + /// Adopt what the core is wearing. Returns whether anything moved, so the + /// host only reconfigures the window when it has to. + @discardableResult + func adoptThemeBG(_ encoded: UInt32) -> Bool { + let wanted: UInt32? = + encoded == UInt32(PARDES_COLOR_DEFAULT) ? nil : encoded & UInt32(PARDES_COLOR_RGB_MASK) + guard wanted != themeBG else { return false } + themeBG = wanted + needsDisplay = true + return true + } + + /// What `WindowOpacity` asked for, as the alpha every BACKGROUND is painted + /// at: the ground, cell and band backgrounds, and the chrome rules over + /// them. Glyph ink is never scaled by it, and neither is the block cursor — + /// it is foreground chrome that merely happens to be carried in a cell's + /// background, and it has to stay visible at `WindowOpacity 0`. + /// + /// The rule is stated once for the SDL shell in shaders/ui.frag.glsl; this + /// is the same rule in CoreGraphics, where painting the ground at this + /// alpha and the glyph over it at its own coverage composites to what that + /// shader writes premultiplied in one pass. + /// + /// Orthogonal to `themeBG`: a theme with no background of its own drops the + /// ground whatever this says, and an opaque theme still honours it. + private(set) var backgroundAlpha: CGFloat = 1 + + /// Adopt the core's percentage. Returns whether anything moved, on the same + /// contract as adoptThemeBG: the host redresses the window only when it has. + @discardableResult + func adoptWindowOpacity(_ percent: UInt8) -> Bool { + let wanted = CGFloat(min(percent, 100)) / 100 + guard wanted != backgroundAlpha else { return false } + backgroundAlpha = wanted + needsDisplay = true + return true + } + + // The button a left-stream click actually started with. mouseDown decides + // it from the fingers on the trackpad, and mouseDragged/mouseUp must use + // the same one: a press of right followed by a release of left leaves the + // core holding a drag nothing will ever end. + private var latchedButton: pardes_mouse_button_e? + private var latchedCell: GridPoint? + /// Last physical point delivered by AppKit and its mapping through the + /// accepted scene. The CRT's barrel moves a source cell under a stationary + /// hand, so successful scene presentations reconcile this point again. + private var pointerPoint: CGPoint? + private var pointerCell: GridPoint? + private var pointerMapped = false + private var pointerModifiers: UInt32 = 0 + // Force-click stage, reset per press. AppKit repeats stage-2 events for as + // long as the finger stays down, and only the transition is the gesture. + private var pressureStage: Int = 0 + // Fingers currently resting on the trackpad, kept from the touch stream. + // + // mouseDown was originally trusted to carry its own touch set, and on this + // hardware it does not always: AppKit routes NSTouch through the four + // touchesXxx callbacks, and the touch set hanging off a *mouse* event can + // come back empty depending on how the click was produced. Empty reads as + // one finger, which is a two-finger Exec silently degrading into a select + // — the exact failure this was supposed to avoid. So the count is + // maintained here and the mouse event's own set is preferred only when it + // has something in it. + private var restingFingers: Int = 0 + + init(fontSize size: CGFloat) { + // No window yet, so no backing scale to ask for: 2x is the guess every + // Mac shipped this decade would give, and viewDidChangeBackingProperties + // below re-measures the moment there is a real answer — including the + // 1x case, which a bare guess would otherwise leave wrong forever. + let built = Metrics(size: size, path: nil, scale: 2) + metrics = built + taglines = TaglineMetrics( + body: built, percent: pardes_gui_tagline_font_percent(), scale: 2) + fontSize = size + fontPath = nil + + // 80x24 only so the window has a size to open at; the AppDelegate reads + // gridSize back and boots the core with whatever it actually got. + super.init(frame: NSRect(x: 0, y: 0, width: built.cellWidth * 80, height: built.cellHeight * 24)) + + runGlyphs.reserveCapacity(256) + runPositions.reserveCapacity(256) + // Files dropped ON the grid. Finder and the Dock already reach the app + // through application(_:open:), but that path cannot say WHERE — and + // where is the whole difference between "a file opened somewhere" and + // acme's "a file opened next to the pane I pointed at". + registerForDraggedTypes([.fileURL]) + // Indirect touches are the trackpad's. Without this the touch set is + // always empty and every click looks like one finger, which is exactly + // the bug that would make two-finger Exec silently never fire. + allowedTouchTypes = [.indirect] + // Without a pressure configuration the deep-press stages are the + // system's business and stage 2 may never be delivered here. + // .primaryDeepClick is the one that means "a harder press is a second + // gesture", which is what it is being used for. + pressureConfiguration = NSPressureConfiguration(pressureBehavior: .primaryDeepClick) + } + + required init?(coder: NSCoder) { fatalError("PardesView is built in code, not a nib") } + + // MARK: - the face + + /// The PostScript name of the face on screen. The only way anything + /// outside this file can find out which font is being drawn with — the + /// core has no font, so a cell-buffer snapshot cannot see one. + var faceName: String { CTFontCopyPostScriptName(metrics.fonts[0]) as String } + var effectivePointSize: CGFloat { CTFontGetSize(metrics.fonts[0]) } + + /// Put on a face, or the same face at a different size, and tell the host + /// the grid moved under it. + /// + /// A cell that changed size means a different number of columns fit the + /// same window, so this is a resize as far as the core is concerned — and + /// the delegate's resize path is already the one that reports both the + /// grid and the physical cell the PDF placement reads. A requested file + /// which cannot produce a fixed-pitch face is rejected before assignment, + /// leaving the screen exactly as it was rather than substituting a face. + private func wear(size: CGFloat, path: String?, resolvesRequest: Bool = false) { + let scale = window?.backingScaleFactor ?? metricsScale + let next = Metrics(size: size, path: path, scale: scale) + guard next.acceptedPath else { + // The requested file never became the fixed-pitch face the grid + // requires. Keep every old metric and resolve the pending request + // as rejected rather than claiming the system fallback is it. + if resolvesRequest { pardes_font_reject() } + return + } + // A CGGlyph is an index into a particular face. Kept across a change + // it would draw a different character, not a missing one. + bodyGlyphCache.removeAll(keepingCapacity: true) + taglineGlyphCache.removeAll(keepingCapacity: true) + gripGlyphCache.removeAll(keepingCapacity: true) + ligatureShaped.removeAll(keepingCapacity: true) + metrics = next + taglines = TaglineMetrics(body: next, percent: taglines.percent, scale: scale) + metricsScale = scale + fontSize = size + fontPath = path + delegate?.pardesViewDidResize(self) + needsDisplay = true + reportEffectiveFont(resolvesRequest: resolvesRequest) + } + + /// Apply the core's live TaglineSize setting without touching body metrics, + /// the window grid, or PDF cell geometry. Called every pump; equality makes + /// the ordinary path one byte comparison. + @discardableResult + func adoptTaglinePercent(_ percent: UInt8) -> Bool { + guard percent != taglines.percent else { return false } + taglines = TaglineMetrics(body: metrics, percent: percent, scale: metricsScale) + taglineGlyphCache.removeAll(keepingCapacity: true) + gripGlyphCache.removeAll(keepingCapacity: true) + pardes_row_metrics(UInt16(max(1,(cellWidth*metricsScale).rounded())),UInt16(max(1,(cellHeight*metricsScale).rounded())), + UInt16(max(1,(taglines.width*metricsScale).rounded())),UInt16(max(1,(taglines.height*metricsScale).rounded()))) + needsDisplay = true + return true + } + + var taglinePercent: UInt8 { taglines.percent } + var taglineBandHeight: CGFloat { taglines.height } + var taglineCellWidth: CGFloat { taglines.width } + + /// Seed runtime Config after init and update it after every successful + /// adopt/zoom. Points are the native owner's unit; the cell's backing-pixel + /// dimensions continue to travel through pardes_resize separately. + func reportEffectiveFont(resolvesRequest: Bool = false) { + let hundredths = UInt16(min( + max((effectivePointSize * 100).rounded(), 1), + CGFloat(UInt16.max))) + let name = faceName + name.withCString { pointer in + if resolvesRequest { + _ = pardes_font_ack(pointer, name.utf8.count, hundredths) + } else { + _ = pardes_font_observe(pointer, name.utf8.count, hundredths) + } + } + } + + /// The file `Font <name>` resolved to, straight from the core. + func adoptFont(path: String, sizeHundredths: UInt16) { + let size = sizeHundredths == 0 ? fontSize : CGFloat(sizeHundredths) / 100 + wear(size: size, path: path, resolvesRequest: true) + } + + /// Cmd+ and Cmd-. Whole points, because the cell is rounded to whole + /// points anyway: a tenth-of-a-point step would spend several keystrokes + /// landing on the same grid and look like the key had stopped working. + /// The range is what stays legible at the bottom and still fits a useful + /// number of columns at the top. + func zoom(by step: CGFloat) { + let next = min(max(fontSize + step, 6), 72) + guard next != fontSize else { return } + wear(size: next, path: fontPath) + } + + func zoomReset() { + guard fontSize != defaultFontSize else { return } + wear(size: defaultFontSize, path: fontPath) + } + + // Row 0 at the top, so the drawing arithmetic reads like the grid it is. + override var isFlipped: Bool { true } + // Opaque only while the theme brings its own background AND that background + // is painted solid. A transparent theme has none, and an opaque view over a + // visual-effect backdrop is a grey rectangle where the blur should be; + // a WindowOpacity below 100 has the same problem against the desktop. + override var isOpaque: Bool { themeBG != nil && backgroundAlpha >= 1 } + override var acceptsFirstResponder: Bool { true } + // A click that focuses the window should also land in the grid: this is a + // text surface, and having to click twice after switching apps is the kind + // of thing that makes an app feel foreign. + override func acceptsFirstMouse(for event: NSEvent?) -> Bool { true } + + var gridSize: (cols: UInt16, rows: UInt16) { + let cols = min(max((bounds.width / cellWidth).rounded(.down), 1), CGFloat(UInt16.max)) + let rows = min(max((bounds.height / cellHeight).rounded(.down), 1), CGFloat(UInt16.max)) + return (UInt16(cols), UInt16(rows)) + } + + // MARK: - drawing + + override func draw(_ dirtyRect: NSRect) { + guard let destination = NSGraphicsContext.current?.cgContext else { return } + lastFrameUsedPostprocessor = false + // ponytail: dirtyRect is ignored. pardes_frame() re-renders the whole grid + // whatever we do, so clipping would save fills and nothing else. Narrow + // the row loops to the dirty band if that ever shows up in a profile. + let count = pardes_frame() + let nextPointer = pointerShape() + if nextPointer != pointer { + pointer = nextPointer + window?.invalidateCursorRects(for: self) + if let window, bounds.contains(convert(window.mouseLocationOutsideOfEventStream, from: nil)) { + cursorFor(pointer).set() + } + } + let scene = pardes_scene() + let trackCount = Int(pardes_frame_panel_tracks()) + let tracks: UnsafeBufferPointer<pardes_panel_track_s> + if trackCount > 0, let list = pardes_frame_panel_track_list() { + tracks = UnsafeBufferPointer(start: list, count: trackCount) + } else { + tracks = UnsafeBufferPointer(start: nil, count: 0) + } + let wantsPostprocess = scene.flags != 0 || !tracks.isEmpty + if wantsPostprocess { + if postprocessorUnavailable { + pardes_postprocessor_unavailable() + } else if let postprocessor = scenePostprocessor { + if let sceneContext = postprocessor.renderContext( + size: bounds.size, scale: window?.backingScaleFactor ?? metricsScale + ) { + drawFrame(sceneContext, count: count, hideCursor: !tracks.isEmpty) + let needsPrevious = tracks.contains { + $0.effect == UInt8(PARDES_PANEL_DISSOLVE) + || $0.effect == UInt8(PARDES_PANEL_VERTICAL) + } + var oldReady = !needsPrevious + let previousCells = pardes_frame_previous_cells() + let changedCells = pardes_frame_changed_cells() + if needsPrevious, let previousCells, changedCells != nil, + let oldContext = postprocessor.previousRenderContext( + size: bounds.size, + scale: window?.backingScaleFactor ?? metricsScale + ) { + drawFrame( + oldContext, count: count, cells: previousCells, + frozenImages: presentedImages, hideCursor: true) + oldReady = true + } + let outcome: ScenePostprocessor.CompositeOutcome = oldReady + ? postprocessor.composite( + scene: scene, tracks: tracks, + changedCells: changedCells, + changedAttachmentRects: changedAttachmentRects(), + gridSize: ( + cols: Int(pardes_frame_cols()), + rows: Int(pardes_frame_rows())), + cellSize: CGSize(width: cellWidth, height: cellHeight), + ground: themeBG, size: bounds.size, into: destination) + : .unavailable + switch outcome { + case .presented: + postprocessRetries = 0 + lastPresentedScene = scene + lastFrameUsedPostprocessor = true + acknowledgePresentation(animatedPanels: !tracks.isEmpty) + return + case .retry: + postprocessRetries += 1 + case .unavailable: + postprocessorUnavailable = true + } + } else { + postprocessRetries += 1 + } + // This draw now falls back to canonical content. Scene effects + // may retry, but a panel must not resume from a later sample + // after its final geometry has already been shown. + if !tracks.isEmpty { pardes_panel_animation_failed() } + if postprocessRetries >= 3 { postprocessorUnavailable = true } + if postprocessorUnavailable { pardes_postprocessor_unavailable() } + } else { + // The source, Metal device, or fixed kernel set was absent at + // lazy construction. None can recover within this process. + postprocessorUnavailable = true + pardes_postprocessor_unavailable() + } + } else { + postprocessRetries = 0 + } + lastPresentedScene = nil + drawFrame(destination, count: count, hideCursor: false) + acknowledgePresentation(animatedPanels: false) + } + + /// A presentation can materialize a Look target under a stationary mouse + /// after AppDelegate already decided whether to run its 60 Hz clock. Wake + /// the ordinary pump only for that null->active edge; repeated frame acks + /// remain inert and cannot create a redraw loop. + private func acknowledgePresentation(animatedPanels: Bool) { + // Only a canonical presentation advances the attachment baseline. + // During a transition deleted panes keep their cropped CGImages alive + // here even after both the core placement and image cache entry vanish. + if !animatedPanels { + presentedImages = frameImages + presentedBodyLayers = snapshotBodyLayers() + presentedTagLayers = snapshotTagLayers() + } + presentationSerial &+= 1 + let animationWoke = pardes_frame_presented(animatedPanels) + let pointerMoved = refreshPresentedPointer() + guard animationWoke || pointerMoved else { return } + DispatchQueue.main.async { + NotificationCenter.default.post(name: pardesDidInputNotification, object: self) + } + } + + /// Re-feed only a changed mapping. Sending motion on every 60 Hz scene + /// frame would keep resetting the core's hover debounce forever. + private func refreshPresentedPointer() -> Bool { + guard let point = pointerPoint else { return false } + guard let at = cellAt(point) else { + guard pointerMapped else { return false } + pointerMapped = false + pardes_pointer_leave() + return true + } + let changed: Bool + if let previous = pointerCell { + changed = !pointerMapped || previous.col != at.col || previous.row != at.row + } else { + changed = true + } + pointerMapped = true + pointerCell = at + guard changed else { return false } + if let button = latchedButton { + latchedCell = at + sendMouse(button, PARDES_MOUSE_DRAG, at.col, at.row, pointerModifiers) + } else { + sendMouse(PARDES_MOUSE_NONE, PARDES_MOUSE_MOTION, + at.col, at.row, pointerModifiers) + } + return true + } + + /// The canonical CoreText frame, independent of where it lands. Scene + /// effects change only the destination: direct view context when off, the + /// postprocessor's same-sized retained bitmap when on. + private func drawFrame( + _ ctx: CGContext, + count: UInt32, + cells suppliedCells: UnsafePointer<pardes_cell_s>? = nil, + frozenImages: [FrozenImage]? = nil, + hideCursor: Bool + ) { + let cols = Int(pardes_frame_cols()) + let rows = Int(pardes_frame_rows()) + // The ground, from the core rather than from a constant agreed by hand. + // A transparent theme has none: CLEAR rather than fill, because AppKit + // does not blank a non-opaque view and last frame's pixels would + // otherwise pile up on themselves. + let ground = themeBG ?? pardesDefaultBG + let clearGround = themeBG == nil + // AppKit does not blank a non-opaque view, so anything that leaves the + // ground short of solid has to clear first or last frame's pixels pile + // up on themselves — a translucent ground would darken toward opaque + // over a few frames otherwise. + if clearGround || backgroundAlpha < 1 { ctx.clear(bounds) } + if !clearGround { fillBackground(ctx, bounds, ground, backgroundAlpha) } + if frozenImages == nil { frameImages.removeAll(keepingCapacity: true) } + guard cols > 0, rows > 0, Int(count) == cols * rows, + let cells = suppliedCells ?? pardes_frame_cells() + else { return } + + // -1 when hidden, which never matches a real cell, so hidden and "bar, so + // not a block" collapse into the same comparison. + // A cursor has no pane/phase record. Match SDL and TTY by hiding it for + // the short panel transition instead of guessing whether it should + // move, stay fixed, or cover an overlapping opening pane. + let bar = !hideCursor && pardes_cursor_bar() + let blockX = hideCursor || bar ? -1 : Int(pardes_cursor_x()) + let blockY = hideCursor || bar ? -1 : Int(pardes_cursor_y()) + + // Background first, batched into runs of equal color. A full redraw is + // 80x24 cells at the low end and per-cell fills are exactly what makes + // that feel slow. Antialiasing is off because touching rects share an + // edge, and blending that edge twice draws a visible seam. + ctx.setShouldAntialias(false) + // Band geometry is stated against the whole canvas: the last row's rule + // depends on where the window edge is, not just on the row index. + let canvasHeight = bounds.height + for row in 0..<rows { + let base = row * cols + let y = CGFloat(row) * cellHeight + // One offset per ROW, not per run: it is the same answer for every + // cell in the row, and it is a call across the ABI. + let bandTop = taglines.top(row: row, canvasHeight: canvasHeight) + var start = 0 + var block = blockY == row && blockX == 0 + var color = resolve(cells[base], block: block, + ground: ground, clearGround: clearGround).bg + var tagline = cells[base].flags & UInt8(PARDES_CELL_TAGLINE) != 0 + for col in 1...cols { + // A real color is 24 bits, so .max is a sentinel that cannot + // compare equal and therefore always flushes the last run. + let nextBlock = col < cols && blockY == row && blockX == col + let next: UInt32 = col == cols + ? .max + : resolve(cells[base + col], block: nextBlock, + ground: ground, clearGround: clearGround).bg + let nextTagline = col < cols + && cells[base + col].flags & UInt8(PARDES_CELL_TAGLINE) != 0 + // The cursor is in the run key as well as the colour: it is the + // one background that stays solid under WindowOpacity, so it + // cannot share a fill with the cells beside it even when the + // reverse happened to land on their colour. + if next == color && nextTagline == tagline && nextBlock == block { continue } + // bgClear runs are the ground showing through, and the ground is + // already clear — painting them would be painting the hole shut. + if color != bgClear { + let bandY = tagline ? y + bandTop : y + let bandHeight = tagline ? taglines.height : cellHeight + fillBackground(ctx, CGRect(x: CGFloat(start) * cellWidth, y: bandY, + width: CGFloat(col - start) * cellWidth, height: bandHeight), + color, block ? 1 : backgroundAlpha) + } + start = col + color = next + tagline = nextTagline + block = nextBlock + } + } + + // The core grid contains only complete cells, so any window height that + // is not a whole multiple of the cell leaves a strip below the last row. + // A Tagbottom band there is bottom-aligned against the window edge, and + // without this that strip shows the page colour under it. + let gridBottom = CGFloat(rows) * cellHeight + if gridBottom < canvasHeight, rows > 0 { + let base = (rows - 1) * cols + for col in 0..<cols { + let cell = cells[base + col] + guard cell.flags & UInt8(PARDES_CELL_DEFAULT) == 0, + cell.flags & UInt8(PARDES_CELL_TAGLINE) != 0 else { continue } + let bg = resolve(cell, block: false, ground: ground, + clearGround: clearGround).bg + if bg != bgClear { + fillBackground(ctx, CGRect(x: 0, y: gridBottom, width: bounds.width, + height: canvasHeight - gridBottom), bg, backgroundAlpha) + } + break + } + } + + // CTFontDrawGlyphs lays glyph outlines out with +y up, and isFlipped hands + // us a y-down CTM, so drawing text directly in view space renders every + // line mirrored. Un-flip once for the whole glyph pass and convert each + // baseline into it rather than fighting the text matrix per cell. + ctx.setShouldAntialias(true) + // Every glyph sits at an exact multiple of cellWidth and the ascent is + // whole points (see Metrics), so every baseline is already on a pixel: + // letting CoreText place a glyph on a subpixel would blur a grid that + // is aligned by construction. Quantizing keeps the rasterizer's own + // cache hitting. + ctx.setShouldSubpixelPositionFonts(false) + ctx.setShouldSubpixelQuantizeFonts(true) + // Grayscale antialiasing, never LCD subpixel. Smoothing needs to know + // the colour behind the glyph, which over a transparent theme's + // backdrop it cannot — the result is coloured fringing that reads as + // blur. macOS has defaulted this off since 10.14, but the user can turn + // it back on globally and it is not their call to make for this grid. + ctx.setShouldSmoothFonts(false) + ctx.saveGState() + ctx.textMatrix = .identity + ctx.translateBy(x: 0, y: bounds.height) + ctx.scaleBy(x: 1, y: -1) + let height = bounds.height + var paneGripCells = Set<Int>() + if frozenImages == nil { + for index in 0..<pardes_tag_layer_limit() { + if pardes_tag_layer_value(index, 0) == 0 || pardes_tag_layer_value(index, 1) != 2 { continue } + let x = Int(pardes_tag_layer_value(index, 4)) - Int(pardes_tag_text_inset()) + let y = Int(pardes_tag_layer_value(index, 5)) + if x >= 0 && x < cols && y >= 0 && y < rows { paneGripCells.insert(y * cols + x) } + } + } else { + for layer in presentedTagLayers where layer.values[1] == 2 { + let x = layer.values[4] - Int(pardes_tag_text_inset()), y = layer.values[5] + if x >= 0 && x < cols && y >= 0 && y < rows { paneGripCells.insert(y * cols + x) } + } + } + for row in 0..<rows { + drawRow(ctx, cells, base: row * cols, cols: cols, row: row, + baseline: height - (CGFloat(row) * cellHeight + metrics.ascent), + taglineTop: taglines.top(row: row, canvasHeight: canvasHeight), + blockCol: blockY == row ? blockX : -1, paneGripCells: paneGripCells) + } + ctx.restoreGState() + + // Pixel attachments over the grid: rasterized PDF pages, and image + // panes' own pixels. After the glyphs, the way the SDL shell draws them + // after its cells — a PDF pane's cells are blank, so the order only + // matters for the tag row an attachment must never reach, and the clip + // below is what keeps it off. + if let frozenImages { + drawFrozenImages(ctx, frozenImages) + } else { + drawImages(ctx) + } + + if bar { + let x = Int(pardes_cursor_x()), y = Int(pardes_cursor_y()) + if x >= 0, y >= 0, x < cols, y < rows { + // gui.zig paints U+258F here. A rect is the same picture without + // asking the font for a glyph it may not carry. + let cell = cells[y * cols + x] + let fg = resolve(cell, block: false, + ground: themeBG ?? pardesDefaultBG, clearGround: false).fg + let tagline = cell.flags & UInt8(PARDES_CELL_TAGLINE) != 0 + let caretY = CGFloat(y) * cellHeight + + (tagline ? taglines.top(row: y, canvasHeight: bounds.height) : 0) + let caretHeight = tagline ? taglines.height : cellHeight + // On the compact grid when the cell is, or the caret sits a + // growing distance to the left of the character it marks as the + // row runs on. The SDL shell puts its cursor bar through the + // same layout for the same reason. + let caretX = tagline + ? taglines.glyphX(col: x, row: y, bodyCellWidth: cellWidth) + : CGFloat(x) * cellWidth + let caretWidth = max(1, ((tagline ? taglines.width : cellWidth) / 8).rounded(.up)) + ctx.setShouldAntialias(false) + fill(ctx, CGRect(x: caretX, y: caretY, + width: caretWidth, height: caretHeight), fg, 1) + } + } + if frozenImages == nil { + drawBodyLayers(ctx, hideCursor:hideCursor) + drawTagLayers(ctx, hideCursor:hideCursor, canonical:cells, cols:cols, rows:rows) + } else { + for layer in presentedTagLayers { + layer.cells.withUnsafeBufferPointer { tagCells in + if let base = tagCells.baseAddress { + drawTagLayer(ctx, values: layer.values, cells: base, hideCursor: true, + canonical: cells, cols: cols) + } + } + drawTagGrip(ctx, values: layer.values, canonical: cells, cols: cols, rows: rows) + } + for layer in presentedBodyLayers { + layer.cells.withUnsafeBufferPointer { cells in + if let base = cells.baseAddress { drawBodyLayer(ctx, values:layer.values, cells:base, hideCursor:true) } + } + } + drawTagRules(ctx, layers: presentedTagLayers.map { $0.values }) + } + drawHoverGlass(ctx, cells: cells, cols: cols, rows: rows) + } + + private var presentedTagLayers: [FrozenBodyLayer] = [] + + private func snapshotTagLayers() -> [FrozenBodyLayer] { + var result: [FrozenBodyLayer] = [] + for index in 0..<pardes_tag_layer_limit() { + let values = (0...12).map { Int(pardes_tag_layer_value(index, UInt32($0))) } + if values[0] == 0 { continue } + if let cells = pardes_tag_layer_cells(index) { + result.append(FrozenBodyLayer(values: values, cells: Array(UnsafeBufferPointer(start: cells, count: values[0])))) + } + } + return result + } + + private func drawTagLayers(_ ctx: CGContext, hideCursor: Bool, canonical: UnsafePointer<pardes_cell_s>, cols: Int, rows: Int) { + var layers: [[Int]] = [] + for index in 0..<pardes_tag_layer_limit() { + let values = (0...12).map { Int(pardes_tag_layer_value(index, UInt32($0))) } + if values[0] == 0 { continue } + layers.append(values) + // The layer's full-row fill must land before the grip: the row + // background now spans the anchor columns, and the grip glyph + // and the anchor fills have to come back on top of it. + if let cells = pardes_tag_layer_cells(index) { + drawTagLayer(ctx, values: values, cells: cells, hideCursor: hideCursor, + canonical: canonical, cols: cols) + } + drawTagGrip(ctx, values: values, canonical: canonical, cols: cols, rows: rows) + } + drawTagRules(ctx, layers: layers) + } + + /// SDL's chrome overlay is drawn after its compact layers. Keep these + /// one-point rules above the full-row tag backgrounds as well. + private func drawTagRules(_ ctx: CGContext, layers: [[Int]]) { + let pixel = CGFloat(1) + for values in layers where values[1] != 0 { + let kind = values[1] + let bottom = kind == 2 && values[11] != 0 + let left = CGFloat(max(0, values[4] - Int(pardes_tag_text_inset()))) * cellWidth + let right = CGFloat(values[4] + values[6]) * cellWidth + let y = CGFloat(values[5] + (bottom ? 0 : 1)) * cellHeight - (bottom ? 0 : pixel) + fillBackground(ctx, CGRect(x: left, y: y, width: right-left, height: pixel), + UInt32(values[12]), backgroundAlpha) + } + if layers.contains(where: { $0[5] == Int(PARDES_TOPBAR_H) }), taglines.borderThickness > 0 { + fillBackground(ctx, CGRect(x: 0, y: taglines.borderTop, width: bounds.width, + height: taglines.borderThickness), + pardes_topbar_pane_border_rgb(), backgroundAlpha) + } + } + + private func gripGlyph(_ text: String, face: Face) -> GripGlyph? { + let key = "\(face.rawValue):\(text)" + if let cached = gripGlyphCache[key] { return cached } + let attributed = NSAttributedString(string: text, attributes: [fontAttribute: taglines.fonts[face.rawValue], + NSAttributedString.Key(kCTForegroundColorFromContextAttributeName as String): true]) + let line = CTLineCreateWithAttributedString(attributed as CFAttributedString) + let ink = CTLineGetBoundsWithOptions(line, [.useGlyphPathBounds]) + guard !ink.isNull, !ink.isInfinite, !ink.isEmpty else { return nil } + let measured = GripGlyph(line: line, ink: ink) + gripGlyphCache[key] = measured + return measured + } + + private func drawTagGrip(_ ctx: CGContext, values: [Int], canonical: UnsafePointer<pardes_cell_s>, cols: Int, rows: Int) { + let x = values[4] - Int(pardes_tag_text_inset()), y = values[5] + if values[1] != 2 || x < 0 || x >= cols || y < 0 || y >= rows { return } + var cell = canonical[y * cols + x] + let text = withUnsafeBytes(of: &cell.text) { String(decoding: $0.prefix(Int(cell.len)), as: UTF8.self) } + if text.isEmpty { return } + let style = resolve(cell, block:false, ground:themeBG ?? pardesDefaultBG, clearGround:false) + // The box drawTagLayer filled is this mark's ground, so the mark + // centres on that same square rather than on the grip columns: one + // rect measures both and the two cannot drift apart. + guard let square = anchorSquare(values: values) else { return } + let centerX = square.midX, centerY = square.midY + if text != " " { + let face = Face(bold: cell.attrs & UInt16(PARDES_ATTR_BOLD) != 0, + italic: cell.attrs & UInt16(PARDES_ATTR_ITALIC) != 0) + guard style.visible, let measured = gripGlyph(text, face: face) else { return } + let originX = ((centerX - measured.ink.midX) * metricsScale).rounded() / metricsScale + let baseline = ((bounds.height - centerY - measured.ink.midY) * metricsScale).rounded() / metricsScale + ctx.saveGState() + ctx.clip(to: square) + ctx.translateBy(x: 0, y: bounds.height) + ctx.scaleBy(x: 1, y: -1) + ctx.textMatrix = .identity + ctx.textPosition = CGPoint(x: originX, y: baseline) + setFill(ctx, style.fg, style.alpha) + CTLineDraw(measured.line, ctx) + ctx.restoreGState() + return + } + if taglines.height < 6 || taglines.width < 3 { return } + let halfWidth = max(1, min(3, cellWidth - 2)) + fill(ctx, CGRect(x:floor(centerX-halfWidth), y:floor(centerY-2), width:2*halfWidth, height:1), style.fg, 1) + fill(ctx, CGRect(x:floor(centerX-halfWidth), y:floor(centerY+1), width:2*halfWidth, height:1), style.fg, 1) + } + + private func drawTagLayer(_ ctx: CGContext, values: [Int], cells: UnsafePointer<pardes_cell_s>, + hideCursor: Bool, canonical: UnsafePointer<pardes_cell_s>, cols: Int) { + let left = CGFloat(values[4]) * cellWidth + let y = CGFloat(values[5]) * cellHeight + taglines.top(row: values[5], canvasHeight: bounds.height) + // SDL gives the tag a full body-row background; only its glyphs + // and per-cell highlights use the compact band. The band spans the + // row's whole extent, not just its text: the grip and the mode box + // live in the inset columns to the left of `values[4]`, and their + // own fills cover only the compact band — a row background that + // stops at the text leaves holes of ground under those anchors. + // The rule in drawTagRules spans exactly this left-to-right range. + let rowLeft = CGFloat(max(0, values[4] - Int(pardes_tag_text_inset()))) * cellWidth + let rowRight = CGFloat(values[4] + values[6]) * cellWidth + let viewport = CGRect(x: rowLeft, y: CGFloat(values[5]) * cellHeight, + width: rowRight - rowLeft, height: cellHeight) + ctx.saveGState() + ctx.clip(to: viewport) + fillBackground(ctx, viewport, UInt32(values[10]), backgroundAlpha) + // The anchor (grip, mode box) lives in the inset columns that fill + // just covered, so its own box goes back on top: one solid fill in + // the box colour the anchor cell wears, with drawTagGrip's mark + // drawn over it afterwards. + if let square = anchorSquare(values: values) { + let anchorX = max(0, values[4] - Int(pardes_tag_text_inset())) + let cell = canonical[values[5] * cols + anchorX] + let style = resolve(cell, block: false, + ground: UInt32(values[10]), clearGround: false) + if style.visible { fillBackground(ctx, square.integral, style.bg, backgroundAlpha) } + } + + for pass in 0...1 { + for col in 0..<values[0] { + var cell = cells[col] + let isCursor = !hideCursor && col == values[8] + let block = isCursor && values[9] == 0 + let style = resolve(cell, block: block, ground: UInt32(values[10]), clearGround: false) + let x = left + CGFloat(col) * taglines.width + if pass == 0 { + fillBackground(ctx, CGRect(x: x, y: y, width: taglines.width, height: taglines.height), + style.bg, block ? 1 : backgroundAlpha) + continue + } + let text = withUnsafeBytes(of: &cell.text) { String(decoding: $0.prefix(Int(cell.len)), as: UTF8.self) } + if style.visible && !text.isEmpty && text != " " { + let face = Face(bold: cell.attrs & UInt16(PARDES_ATTR_BOLD) != 0, italic: cell.attrs & UInt16(PARDES_ATTR_ITALIC) != 0) + ctx.saveGState() + ctx.translateBy(x: 0, y: bounds.height) + ctx.scaleBy(x: 1, y: -1) + let baseline = bounds.height - y - taglines.ascent + drawRules(ctx, cell, style, x: x, width: taglines.width, baseline: baseline) + setFill(ctx, style.fg, style.alpha) + ctx.textPosition = CGPoint(x: x, y: baseline) + let line = NSAttributedString(string: text, attributes: [fontAttribute: taglines.fonts[face.rawValue], + NSAttributedString.Key(kCTForegroundColorFromContextAttributeName as String): true]) + CTLineDraw(CTLineCreateWithAttributedString(line as CFAttributedString), ctx) + ctx.restoreGState() + } + if isCursor && values[9] != 0 { + fill(ctx, CGRect(x: x, y: y, width: max(1, taglines.width / 8), height: taglines.height), style.fg, 1) + } + } + } + ctx.restoreGState() + } + + /// The anchor square: one box drawn from the tag band's height — square, + /// at the row's left edge, inset by the same amount on both axes — + /// shared by the fill in drawTagLayer and the glyph in drawTagGrip so + /// the two can never disagree. + private func anchorSquare(values: [Int]) -> CGRect? { + let anchorX = max(0, values[4] - Int(pardes_tag_text_inset())) + guard anchorX < values[4] else { return nil } + let pad = (cellHeight - taglines.height) / 2 + return CGRect(x: CGFloat(anchorX) * cellWidth + pad, + y: CGFloat(values[5]) * cellHeight + taglines.top(row: values[5], canvasHeight: bounds.height), + width: taglines.height, height: taglines.height) + } + + /// The look-hover affordance as liquid glass: the core marks the word's + /// cells (PARDES_CELL_HOVER), and this composes a real material over the + /// run — the drawn frame snapshot refracted through CoreImage (a small + /// blur, then a lens scale about the pill's centre, which is what makes + /// the edges swim), the theme's selection colour as a faint tint, a + /// specular sheen from the top edge, and a light rim — with the word's + /// own glyphs drawn back on top, crisp, the way text sits on a real + /// material rather than behind one. + private func drawHoverGlass(_ ctx: CGContext, cells: UnsafePointer<pardes_cell_s>, cols: Int, rows: Int) { + var drew = false + for row in 0..<rows { + var start = -1 + var tint: UInt32 = 0 + for col in 0...cols { + let hover = col < cols + && cells[row * cols + col].flags & UInt8(PARDES_CELL_HOVER) != 0 + if hover, start < 0 { + start = col + tint = cells[row * cols + col].bg + } + if !hover, start >= 0 { + let rect = CGRect(x: CGFloat(start) * cellWidth, y: CGFloat(row) * cellHeight, + width: CGFloat(col - start) * cellWidth, height: cellHeight) + drawLiquidGlass(ctx, rect, tint: tint) + redrawHoverRun(ctx, cells, cols: cols, row: row, start: start, end: col) + drew = true + start = -1 + } + } + } + // No affordance this frame: the held snapshot describes a frame + // that no longer exists, and the next hover must take a fresh one. + if !drew { glassShot = nil } + } + + /// A CoreImage context for the glass refraction, created once. + private lazy var glassContext = CIContext() + /// The snapshot behind the current pill. Refraction reads the already + /// drawn frame, and re-reading it every pump would blur a moving pill + /// out of its own budget, so the shot is taken when the rect changes. + private var glassShot: (rect: CGRect, image: CGImage)? + + private func drawLiquidGlass(_ ctx: CGContext, _ rect: CGRect, tint: UInt32) { + let radius = min(rect.height / 4, 6) + let pill = CGPath(roundedRect: rect.insetBy(dx: 1, dy: 1.5), + cornerWidth: radius, cornerHeight: radius, transform: nil) + // The refraction: the frame as drawn, blurred a little and scaled + // about the pill's centre, so the rim bends what surrounds it. The + // shot extends past the pill for exactly this — the lens needs + // pixels from outside the glass to pull in. + let lens = rect.insetBy(dx: -10, dy: -10) + if refract(ctx, pill: pill, rect: rect, lens: lens, tint: tint) { + // Specular: light caught at the top edge, fading as it falls. + ctx.saveGState() + ctx.addPath(pill) + ctx.clip() + let shine = [CGColor(srgbRed: 1, green: 1, blue: 1, alpha: 0.22), + CGColor(srgbRed: 1, green: 1, blue: 1, alpha: 0.0)] as CFArray + if let gradient = CGGradient(colorsSpace: CGColorSpace(name: CGColorSpace.sRGB), + colors: shine, locations: [0, 0.55]) { + ctx.drawLinearGradient(gradient, + start: CGPoint(x: rect.minX, y: rect.minY), + end: CGPoint(x: rect.minX, y: rect.maxY), options: []) + } + ctx.restoreGState() + } else { + // No refraction without a snapshot: the tint alone, faint. + ctx.saveGState() + ctx.addPath(pill) + ctx.clip() + ctx.setFillColor(CGColor(srgbRed: CGFloat((tint >> 16) & 0xFF) / 255, + green: CGFloat((tint >> 8) & 0xFF) / 255, + blue: CGFloat(tint & 0xFF) / 255, + alpha: 0.18)) + ctx.fill(rect) + ctx.restoreGState() + } + // The lens edge: a light rim and a darker bottom hairline, the way a + // real material catches its own edge. + ctx.addPath(pill) + ctx.setStrokeColor(CGColor(srgbRed: 1, green: 1, blue: 1, alpha: 0.35)) + ctx.setLineWidth(1) + ctx.strokePath() + ctx.addPath(pill) + ctx.setStrokeColor(CGColor(srgbRed: 0, green: 0, blue: 0, alpha: 0.25)) + ctx.setLineWidth(0.5) + ctx.clip() + ctx.stroke(CGRect(x: rect.minX, y: rect.maxY - 2, width: rect.width, height: 1.5)) + } + + /// True when the refraction composited. The snapshot is taken when the + /// pill moves and reused while it sits still. + private func refract(_ ctx: CGContext, pill: CGPath, rect: CGRect, lens: CGRect, tint: UInt32) -> Bool { + guard let shot = snapshotFor(ctx, lens: lens) else { return false } + var image = CIImage(cgImage: shot) + // The blur is grown slightly past the crop and the whole thing is + // pulled toward the centre by a few percent: the rim bends what + // surrounds it, which is the refraction the eye reads as glass. + let blur = image.applyingGaussianBlur(sigma: 2 * metricsScale) + let grown = blur.extent.insetBy(dx: -8 * metricsScale, dy: -8 * metricsScale) + let centre = CGPoint(x: grown.midX, y: grown.midY) + let scale = 1.06 + let lensTransform = CGAffineTransform(translationX: centre.x * (1 - scale), + y: centre.y * (1 - scale)).scaledBy(x: scale, y: scale) + image = blur.transformed(by: lensTransform) + guard let filtered = glassContext.createCGImage(image, from: grown) else { return false } + ctx.saveGState() + ctx.addPath(pill) + ctx.clip() + ctx.draw(filtered, in: rect) + // The glass's own body colour: the theme's selection, faint — the + // refraction and the sheen carry the material, not opacity. + ctx.setFillColor(CGColor(srgbRed: CGFloat((tint >> 16) & 0xFF) / 255, + green: CGFloat((tint >> 8) & 0xFF) / 255, + blue: CGFloat(tint & 0xFF) / 255, + alpha: 0.15)) + ctx.fill(rect) + ctx.restoreGState() + return true + } + + private func snapshotFor(_ ctx: CGContext, lens: CGRect) -> CGImage? { + if let held = glassShot, held.rect == lens { return held.image } + guard let whole = ctx.makeImage() else { return nil } + // makeImage hands back backing pixels; the lens is in view points. + let region = CGRect(x: lens.minX * metricsScale, y: lens.minY * metricsScale, + width: lens.width * metricsScale, height: lens.height * metricsScale) + guard let cropped = whole.cropping(to: region) else { return nil } + glassShot = (lens, cropped) + return cropped + } + + /// The hovered word's glyphs, back on top of the material, crisp: text + /// sits on liquid glass, not behind it. + private func redrawHoverRun(_ ctx: CGContext, _ cells: UnsafePointer<pardes_cell_s>, + cols: Int, row: Int, start: Int, end: Int) { + ctx.saveGState() + ctx.textMatrix = .identity + ctx.translateBy(x: 0, y: bounds.height) + ctx.scaleBy(x: 1, y: -1) + let baseline = bounds.height - (CGFloat(row) * cellHeight + metrics.ascent) + for col in start..<end { + let cell = cells[row * cols + col] + guard cell.flags & UInt8(PARDES_CELL_DEFAULT) == 0 else { continue } + let text = withUnsafeBytes(of: cell.text) { raw in + String(decoding: raw.prefix(Int(cell.len)), as: UTF8.self) + } + guard !text.isEmpty, text != " " else { continue } + let style = resolve(cell, block: false, + ground: themeBG ?? pardesDefaultBG, clearGround: false) + guard style.visible else { continue } + setFill(ctx, style.fg, style.alpha) + ctx.textPosition = CGPoint(x: CGFloat(col) * cellWidth, y: baseline) + let attributed = NSAttributedString(string: text, attributes: [ + fontAttribute: metrics.fonts[Face(bold: cell.attrs & UInt16(PARDES_ATTR_BOLD) != 0, + italic: cell.attrs & UInt16(PARDES_ATTR_ITALIC) != 0).rawValue], + NSAttributedString.Key(kCTForegroundColorFromContextAttributeName as String): true]) + CTLineDraw(CTLineCreateWithAttributedString(attributed as CFAttributedString), ctx) + } + ctx.textMatrix = .identity + ctx.restoreGState() + } + + + + private struct FrozenBodyLayer { + let values: [Int] + let cells: [pardes_cell_s] + } + private var presentedBodyLayers: [FrozenBodyLayer] = [] + + private func snapshotBodyLayers() -> [FrozenBodyLayer] { + var result: [FrozenBodyLayer] = [] + for index in 0..<pardes_body_layer_limit() { + let count = 11 + Int(pardes_body_layer_value(index, 2)) + let values = (0..<count).map { Int(pardes_body_layer_value(index, UInt32($0))) } + if values[0] == 0 { continue } + if let cells = pardes_body_layer_cells(index) { + result.append(FrozenBodyLayer(values:values, cells:Array(UnsafeBufferPointer(start:cells,count:values[0]*values[1])))) + } + } + return result + } + + private func drawBodyLayers(_ ctx: CGContext, hideCursor:Bool) { + for index in 0..<pardes_body_layer_limit() { + let count = 11 + Int(pardes_body_layer_value(index, 2)) + let values = (0..<count).map { Int(pardes_body_layer_value(index, UInt32($0))) } + if values[0] == 0 { continue } + if let cells = pardes_body_layer_cells(index) { drawBodyLayer(ctx, values:values, cells:cells, hideCursor:hideCursor) } + } + } + + private func drawBodyLayer(_ ctx: CGContext, values: [Int], cells: UnsafePointer<pardes_cell_s>, hideCursor: Bool) { + func value(_ field: Int) -> Int { values[field] } + let rows = value(0), cols = value(1), contexts = value(2) + let left = CGFloat(value(3)) * cellWidth, top = CGFloat(value(4)) * cellHeight + let viewport = CGRect(x: left, y: top, width: CGFloat(value(5))*cellWidth, + height: CGFloat(value(6))*cellHeight) + ctx.saveGState() + ctx.clip(to: viewport) + fillBackground(ctx, viewport, themeBG ?? bgClear, backgroundAlpha) + for row in 0..<rows { + let compact = row < contexts + let advance = compact ? taglines.width : cellWidth + let height = compact ? taglines.height : cellHeight + let y = top + CGFloat(min(row, contexts))*taglines.height + CGFloat(max(0, row-contexts))*cellHeight + if y >= viewport.maxY { break } + let rowStyle = resolve(cells[row*cols], block: false, ground: themeBG ?? pardesDefaultBG, clearGround: themeBG == nil) + fillBackground(ctx, CGRect(x: left, y: y, width: viewport.width, height: height), rowStyle.bg, backgroundAlpha) + for pass in 0...1 { + for col in 0..<cols { + var cell = cells[row*cols+col] + let isCursor = !hideCursor && col == value(8) && row == value(9) + let block = isCursor && value(10) == 0 + let style = resolve(cell, block: block, + ground: themeBG ?? pardesDefaultBG, clearGround: themeBG == nil) + let x = left + CGFloat(col)*advance + if pass == 0 { + fillBackground(ctx, CGRect(x: x, y: y, width: advance, height: height), + style.bg, block ? 1 : backgroundAlpha) + continue + } + let text = withUnsafeBytes(of: &cell.text) { bytes in + String(decoding: bytes.prefix(Int(cell.len)), as: UTF8.self) + } + if style.visible && !text.isEmpty && text != " " { + let face = Face(bold: cell.attrs & UInt16(PARDES_ATTR_BOLD) != 0, + italic: cell.attrs & UInt16(PARDES_ATTR_ITALIC) != 0) + let font = compact ? taglines.fonts[face.rawValue] : metrics.fonts[face.rawValue] + ctx.saveGState() + ctx.translateBy(x: 0, y: bounds.height) + ctx.scaleBy(x: 1, y: -1) + let baseline = bounds.height - y - (compact ? taglines.ascent : metrics.ascent) + drawRules(ctx, cell, style, x: x, width: advance, baseline: baseline) + setFill(ctx, style.fg, style.alpha) + ctx.textPosition = CGPoint(x: x, y: baseline) + let line = NSAttributedString(string: text, attributes: [fontAttribute: font, + NSAttributedString.Key(kCTForegroundColorFromContextAttributeName as String): true]) + CTLineDraw(CTLineCreateWithAttributedString(line as CFAttributedString), ctx) + ctx.restoreGState() + } + if isCursor && value(10) != 0 { + fill(ctx, CGRect(x: x, y: y, width: max(1, advance/8), height: height), style.fg, 1) + } + } + } + } + let border = pardes_topbar_pane_border_rgb() + if border != UInt32(PARDES_COLOR_DEFAULT) { + for row in 0..<contexts { + if value(11 + row) == 0 { continue } + // The SDL shell paints this rule over the row's LAST pixel, not + // the next row's first one; keep the two shells on the same pixel. + let thickness = taglines.contextBorderThickness + fillBackground(ctx, CGRect(x: left, y: top + CGFloat(row + 1)*taglines.height - thickness, + width: viewport.width, height: thickness), border, backgroundAlpha) + } + } + ctx.restoreGState() + } + + /// What identifies a decoded raster: the pane's lifetime, the page, and the + /// generation MuPDF last rendered. Panning, zooming to fit and scrolling + /// deliberately move none of them, so the CGImage survives all three. + private struct ImageKey: Hashable { + let serial: UInt32 + let page: UInt32 + let revision: UInt32 + } + + /// A fully-owned attachment placement from the last canonical frame. + /// The cropped CGImage retains its provider bytes, unlike pardes_image_s's + /// pointer, so a vertical closing tombstone can outlive pane deletion. + private struct FrozenImage { + let key: ImageKey + let image: CGImage + let source: CGRect + let body: CGRect + let destination: CGRect + let paperBG: UInt32 + } + + /// Rasterized attachments, decoded once each. The bytes the core lends are + /// only valid until the next `pardes_frame`, so the CGImage owns a COPY — + /// which is exactly why the cache has to be keyed well enough that the copy + /// happens when the pixels change and never on an ordinary scroll. + private var imageCache: [ImageKey: CGImage] = [:] + private var frameImages: [FrozenImage] = [] + private var presentedImages: [FrozenImage] = [] + + private func drawImages(_ ctx: CGContext) { + let count = Int(pardes_frame_images()) + guard count > 0, let list = pardes_frame_image_list() else { + // Nothing on screen owns pixels any more: the pages a closed pane + // rendered would otherwise sit in here for the rest of the session. + if !imageCache.isEmpty { imageCache.removeAll(keepingCapacity: true) } + return + } + + // The core computed every rectangle in PHYSICAL pixels, because that is + // what pardes_resize handed it. The view draws in points. + let scale = max(1, metricsScale) + var live = Set<ImageKey>() + live.reserveCapacity(count) + + ctx.setShouldAntialias(true) + for i in 0..<count { + let place = list[i] + let key = ImageKey(serial: place.serial, page: place.page, revision: place.revision) + live.insert(key) + guard let full = image(for: place, key: key) else { continue } + let source = CGRect( + x: Int(place.src_x), y: Int(place.src_y), + width: Int(place.src_w), height: Int(place.src_h)) + guard let crop = full.cropping(to: source) + else { continue } + + // The body is the rectangle nothing may paint past. The core has + // already clipped the geometry to the viewport, but a tagline is + // not the viewport — a page one pixel too tall would sit on it. + let body = CGRect( + x: CGFloat(place.cell_x) * cellWidth, y: CGFloat(place.cell_y) * cellHeight, + width: CGFloat(place.cell_w) * cellWidth, height: CGFloat(place.cell_h) * cellHeight) + let dst = CGRect( + x: body.minX + CGFloat(place.dst_x) / scale, + y: body.minY + (CGFloat(place.dst_y) + CGFloat(place.offset_y)) / scale, + width: CGFloat(place.dst_w) / scale, + height: CGFloat(place.dst_h) / scale) + let frozen = FrozenImage( + key: key, image: crop, source: source, + body: body, destination: dst, paperBG: place.paper_bg) + frameImages.append(frozen) + drawFrozenImage(ctx, frozen) + } + + // Evict what this frame did not place. Scrolling a document past a page + // is the common case, and holding every page a session ever showed is + // how a PDF viewer ends up owning a gigabyte of decoded bitmaps. + if imageCache.count > live.count { + imageCache = imageCache.filter { live.contains($0.key) } + } + } + + private func drawFrozenImages(_ ctx: CGContext, _ images: [FrozenImage]) { + ctx.setShouldAntialias(true) + for image in images { drawFrozenImage(ctx, image) } + } + + /// Native attachments do not occupy Cell graphemes, so the core's semantic + /// text/style mask cannot see a page appearing, disappearing, rerasterizing + /// or moving. Add only those changed placements to the shader mask; an + /// identical key and geometry remains immediate like any unchanged cell. + private func changedAttachmentRects() -> [CGRect] { + var oldByKey: [ImageKey: FrozenImage] = [:] + for image in presentedImages { oldByKey[image.key] = image } + var changed: [CGRect] = [] + changed.reserveCapacity(frameImages.count + presentedImages.count) + for image in frameImages { + guard let old = oldByKey.removeValue(forKey: image.key) else { + changed.append(image.destination.intersection(image.body)) + continue + } + if old.source != image.source + || old.body != image.body || old.destination != image.destination { + changed.append(old.destination.intersection(old.body)) + changed.append(image.destination.intersection(image.body)) + } + } + for old in oldByKey.values { + changed.append(old.destination.intersection(old.body)) + } + return changed.filter { !$0.isNull && !$0.isEmpty } + } + + private func drawFrozenImage(_ ctx: CGContext, _ placed: FrozenImage) { + ctx.saveGState() + ctx.clip(to: placed.body) + // isFlipped gives us a y-down CTM and CGImage draws +y up, so flip + // about this destination rather than changing the grid arithmetic. + let isPDF = placed.paperBG != UInt32(PARDES_COLOR_DEFAULT) + if isPDF { + fillBackground(ctx, placed.destination, placed.paperBG, backgroundAlpha) + } + ctx.translateBy(x: placed.destination.minX, y: placed.destination.maxY) + ctx.scaleBy(x: 1, y: -1) + ctx.interpolationQuality = .high + let rect = CGRect(x: 0, y: 0, + width: placed.destination.width, height: placed.destination.height) + if isPDF { + // Paper was painted at WindowOpacity. Content keeps the PDF's own + // coverage, so glyphs, photos and paths stay legible at zero opacity. + ctx.setAlpha(1) + ctx.setBlendMode(.normal) + ctx.draw(placed.image, in: rect) + ctx.restoreGState() + return + } + // Match image.frag.glsl/backgroundLayerBlend: source coverage removes + // the destination independently of WindowOpacity, then the source is + // added at that opacity. Ordinary source-over would compound alpha; + // copy would discard the background under transparent image pixels. + ctx.setAlpha(1) + ctx.setBlendMode(.destinationOut) + ctx.draw(placed.image, in: rect) + ctx.setAlpha(backgroundAlpha) + ctx.setBlendMode(.plusLighter) + ctx.draw(placed.image, in: rect) + ctx.restoreGState() + } + + /// The decoded raster for one attachment, made once per generation. + private func image(for place: pardes_image_s, key: ImageKey) -> CGImage? { + if let cached = imageCache[key] { return cached } + let bytes = Int(place.iw) * Int(place.ih) * 4 + guard bytes > 0, let rgba = place.rgba else { return nil } + // Copied, not referenced: the core lends these bytes until the next + // pardes_frame and this image outlives many of them. + guard let data = CFDataCreate(nil, rgba, bytes), + let provider = CGDataProvider(data: data) + else { return nil } + // Straight alpha, R,G,B,A in memory — the same bytes the SDL shell + // uploads as R8G8B8A8_UNORM and blends with ONE_MINUS_SRC_ALPHA. + let made = CGImage( + width: Int(place.iw), height: Int(place.ih), + bitsPerComponent: 8, bitsPerPixel: 32, bytesPerRow: Int(place.iw) * 4, + space: sRGB, + bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.last.rawValue | CGBitmapInfo.byteOrder32Big.rawValue), + provider: provider, decode: nil, shouldInterpolate: true, intent: .defaultIntent) + if let made { imageCache[key] = made } + return made + } + + /// One row of glyphs, batched. Consecutive cells that share a face and a + /// colour go to CoreText as a single call with a position array: a row of + /// plain text is then one draw instead of eighty, which is the difference + /// between a full redraw being free and being felt. + private func drawRow( + _ ctx: CGContext, + _ cells: UnsafePointer<pardes_cell_s>, + base: Int, + cols: Int, + /// This row's grid index. Needed per cell rather than per row for the + /// compact tagline anchor: a column split puts two panes' tags side by + /// side on ONE row, so the origin is a question about the cell. + row: Int, + baseline: CGFloat, + /// Where this row's tagline band starts, from the row's top. Passed in + /// rather than recomputed per cell: it is one answer per row, and the + /// glyph has to sit in the band the background pass painted. + taglineTop: CGFloat, + blockCol: Int, + paneGripCells: Set<Int> + ) { + var runFace = Face.regular + var runTagline = false + var runColor: UInt32 = 0 + var runAlpha: CGFloat = 1 + runGlyphs.removeAll(keepingCapacity: true) + runPositions.removeAll(keepingCapacity: true) + ligatureCovered.removeAll(keepingCapacity: true) + + func flush() { + guard !runGlyphs.isEmpty else { return } + setFill(ctx, runColor, runAlpha) + let font = runTagline + ? taglines.fonts[runFace.rawValue] + : metrics.fonts[runFace.rawValue] + CTFontDrawGlyphs(font, runGlyphs, runPositions, runGlyphs.count, ctx) + runGlyphs.removeAll(keepingCapacity: true) + runPositions.removeAll(keepingCapacity: true) + } + + for col in 0..<cols { + let cell = cells[base + col] + if ligatureCovered.contains(col) { continue } + if cell.flags & UInt8(PARDES_CELL_DEFAULT) != 0 { continue } + let tagline = cell.flags & UInt8(PARDES_CELL_TAGLINE) != 0 + let cellBaseline = tagline + ? baseline + metrics.ascent - (taglineTop + taglines.ascent) + : baseline + // clearGround: false — this pass only reads `fg`, and a glyph is + // never the hole in the ground. + let style = resolve(cell, block: blockCol == col, + ground: themeBG ?? pardesDefaultBG, clearGround: false) + // Tagline cells step on the smaller face's own pitch, anchored at + // their pane; everything else on the body grid. The rules go with + // the glyph, not with the body cell, or an underlined tag word ends + // up underlining its neighbour. + let x = tagline + ? taglines.glyphX(col: col, row: row, bodyCellWidth: cellWidth) + : CGFloat(col) * cellWidth + let advanceWidth = tagline ? taglines.width : cellWidth + + // Rules before the glyph, and independent of it: an underlined space + // is a real thing and so is an underlined invisible cell. They are + // fills, not glyphs, so they interrupt the run. + if cell.attrs >> UInt16(PARDES_ATTR_UL_SHIFT) != 0 + || cell.attrs & UInt16(PARDES_ATTR_STRIKETHROUGH) != 0 { + flush() + drawRules(ctx, cell, style, x: x, width: advanceWidth, baseline: cellBaseline) + } + guard style.visible else { continue } + + // UNVERIFIED: withUnsafeBytes over an imported C fixed-size array, which + // Swift models as an 8-tuple. String(decoding:) substitutes U+FFFD rather + // than trapping, and the core has shipped invalid UTF-8 through here + // before — the renderer must not be the thing that dies over it. prefix + // clamps, so a bogus len cannot walk off the eight bytes either. + let text = withUnsafeBytes(of: cell.text) { raw in + String(decoding: raw.prefix(Int(cell.len)), as: UTF8.self) + } + guard !text.isEmpty, text != " " else { continue } + + let face = Face(bold: cell.attrs & UInt16(PARDES_ATTR_BOLD) != 0, + italic: cell.attrs & UInt16(PARDES_ATTR_ITALIC) != 0) + if paneGripCells.contains(base + col) && gripGlyph(text, face: face) != nil { + // The layer pass centers this symbol by its actual ink bounds. + continue + } + let units = text.utf16 + let known = units.count == 1 ? glyph(face, units.first!, tagline: tagline) : 0 + if known != 0 { + // Ligatures: consecutive cells shaped together when the face + // collapses them into fewer glyphs. A monospace coding + // ligature advances by the same whole cells its characters + // did, so the grid cannot drift and only the ink changes. + if !tagline, let ligature = ligatureSpan(cells, base: base, cols: cols, col: col, + face: face, fg: style.fg, alpha: style.alpha, + blockCol: blockCol, paneGripCells: paneGripCells) { + flush() + setFill(ctx, style.fg, style.alpha) + let attributed = NSAttributedString(string: ligature.text, + attributes: [fontAttribute: metrics.fonts[face.rawValue], + NSAttributedString.Key(kCTForegroundColorFromContextAttributeName as String): true]) + ctx.textPosition = CGPoint(x: x, y: cellBaseline) + CTLineDraw(CTLineCreateWithAttributedString(attributed as CFAttributedString), ctx) + ctx.textMatrix = .identity + for covered in 1..<ligature.covered { ligatureCovered.insert(col + covered) } + continue + } + if !runGlyphs.isEmpty + && (face != runFace || tagline != runTagline + || style.fg != runColor || style.alpha != runAlpha) { + flush() + } + runFace = face + runTagline = tagline + runColor = style.fg + runAlpha = style.alpha + runGlyphs.append(known) + runPositions.append(CGPoint(x: x, y: cellBaseline)) + continue + } + + // Emoji, combining marks and anything the face is missing: CTLine finds + // a fallback font. The position is set explicitly per cell — this is a + // fixed grid, and letting CoreText advance across a row would drift off + // it. + flush() + setFill(ctx, style.fg, style.alpha) + let font = tagline ? taglines.fonts[face.rawValue] : metrics.fonts[face.rawValue] + let attributed = NSAttributedString(string: text, attributes: [fontAttribute: font, + NSAttributedString.Key(kCTForegroundColorFromContextAttributeName as String): true]) + ctx.textPosition = CGPoint(x: x, y: cellBaseline) + CTLineDraw(CTLineCreateWithAttributedString(attributed as CFAttributedString), ctx) + // CTLineDraw leaves the text position at the END of what it drew, + // and textPosition IS the translation of the text matrix, which + // CTFontDrawGlyphs then applies to every position it is handed. So + // one fallback glyph silently displaces the entire rest of the + // frame by that glyph's advance, down and to the right — and since + // the wrap marker and the em dash take this path, that is most + // files. Put it back before anything else draws. + ctx.textMatrix = .identity + } + flush() + } + + /// 0 is .notdef, i.e. "this face does not have it" — a real answer, cached + /// like any other, because the CTLine fallback it sends the caller to costs + /// far more than the lookup it would otherwise repeat every frame. + private func glyph(_ face: Face, _ character: UniChar, tagline: Bool) -> CGGlyph { + if character < 128 { + let ascii = tagline ? taglines.asciiGlyphs : metrics.asciiGlyphs + return ascii[face.rawValue][Int(character)] + } + let key = UInt32(face.rawValue) << 16 | UInt32(character) + if tagline, let cached = taglineGlyphCache[key] { return cached } + if !tagline, let cached = bodyGlyphCache[key] { return cached } + var input = character + var found = CGGlyph(0) + let font = tagline ? taglines.fonts[face.rawValue] : metrics.fonts[face.rawValue] + _ = CTFontGetGlyphsForCharacters(font, &input, &found, 1) + if tagline { + taglineGlyphCache[key] = found + } else { + bodyGlyphCache[key] = found + } + return found + } + + /// Ligature-prone character heads: a coding ligature always begins with + /// one of these, and refusing everything else keeps the per-frame cost of + /// ligature detection a set lookup rather than a shape. + private static let ligatureHeads: Set<Character> = [ + "<", ">", "=", "!", "&", "|", "-", "/", ":", ".", "#", "*", "+", "~", "^", "%", + ] + + private func ligates(_ face: Face, _ text: String) -> Bool { + let key = "\(face.rawValue):\(text)" + if let cached = ligatureShaped[key] { return cached } + let attributed = NSAttributedString(string: text, attributes: [fontAttribute: metrics.fonts[face.rawValue], + NSAttributedString.Key(kCTForegroundColorFromContextAttributeName as String): true]) + let shaped = CTLineCreateWithAttributedString(attributed as CFAttributedString) + var glyphs: [CGGlyph] = [] + for run in (CTLineGetGlyphRuns(shaped) as? [CTRun]) ?? [] { + let count = CTRunGetGlyphCount(run) + var runGlyphs = [CGGlyph](repeating: 0, count: count) + CTRunGetGlyphs(run, CFRange(location: 0, length: count), &runGlyphs) + glyphs.append(contentsOf: runGlyphs) + } + // A ligature is any divergence from per-character mapping. A font may + // collapse the pair into one glyph (JetBrains Mono) or swap each + // character for a joining half kept at the same count (Maple Mono) — + // either way the sequence must be shaped, not mapped. + let singles = text.utf16.map { glyph(face, $0, tagline: false) } + let result = glyphs.count != singles.count + || zip(glyphs, singles).contains { $0 != $1 } + ligatureShaped[key] = result + return result + } + + /// When the cells at `col` ligate under `face`, the text to shape and how + /// many cells the ligature covers. Nil when they do not. Ligature cells + /// must carry the same face, colour and alpha and no rules of their own — + /// a ligature is one glyph of one style, not a style transition. + private func ligatureSpan(_ cells: UnsafePointer<pardes_cell_s>, base: Int, cols: Int, col: Int, + face: Face, fg: UInt32, alpha: CGFloat, + blockCol: Int, paneGripCells: Set<Int>) -> (text: String, covered: Int)? { + func eligible(_ index: Int) -> String? { + let cell = cells[base + index] + if cell.flags & UInt8(PARDES_CELL_DEFAULT) != 0 { return nil } + if cell.flags & UInt8(PARDES_CELL_TAGLINE) != 0 { return nil } + if cell.attrs >> UInt16(PARDES_ATTR_UL_SHIFT) != 0 + || cell.attrs & UInt16(PARDES_ATTR_STRIKETHROUGH) != 0 { return nil } + if paneGripCells.contains(base + index) { return nil } + let text = withUnsafeBytes(of: cell.text) { raw in + String(decoding: raw.prefix(Int(cell.len)), as: UTF8.self) + } + guard text.utf16.count == 1 else { return nil } + let other = resolve(cell, block: blockCol == index, + ground: themeBG ?? pardesDefaultBG, clearGround: false) + guard other.visible, other.fg == fg, other.alpha == alpha, + Face(bold: cell.attrs & UInt16(PARDES_ATTR_BOLD) != 0, + italic: cell.attrs & UInt16(PARDES_ATTR_ITALIC) != 0) == face else { return nil } + return text + } + guard let head = eligible(col), PardesView.ligatureHeads.contains(head.first!) else { return nil } + guard col + 1 < cols, let second = eligible(col + 1) else { return nil } + let pair = head + second + if col + 2 < cols, let third = eligible(col + 2) { + let triple = pair + third + if ligates(face, triple) { return (triple, 3) } + } + if ligates(face, pair) { return (pair, 2) } + return nil + } + + private func drawRules( + _ ctx: CGContext, + _ cell: pardes_cell_s, + _ style: (fg: UInt32, bg: UInt32, alpha: CGFloat, visible: Bool), + x: CGFloat, + /// The cell's advance: the body cell, or the narrower tagline one. A + /// rule is as wide as the character it belongs to, and on a tag row + /// that stopped being the body cell when the text compacted. + width: CGFloat, + baseline: CGFloat + ) { + let underline = Int(cell.attrs >> PARDES_ATTR_UL_SHIFT) & 7 + if underline != Int(PARDES_UL_OFF) { + let y = baseline + metrics.underlineOffset + fill(ctx, CGRect(x: x, y: y, width: width, height: metrics.ruleThickness), style.fg, style.alpha) + // ponytail: curly, dotted and dashed all come out solid; only double + // earns its second rule. ctx.setLineDash for two of them and a sine + // path for the third is the upgrade, once anyone notices. + if underline == Int(PARDES_UL_DOUBLE) { + fill(ctx, CGRect(x: x, y: y - metrics.ruleThickness * 2, width: width, height: metrics.ruleThickness), + style.fg, style.alpha) + } + } + if cell.attrs & UInt16(PARDES_ATTR_STRIKETHROUGH) != 0 { + // Rounded like every other rule offset: a third of the ascent is a + // fraction, and a fractional one-pixel bar is a two-pixel smear. + fill(ctx, CGRect(x: x, y: baseline + (metrics.ascent * 0.3).rounded(), width: width, height: metrics.ruleThickness), + style.fg, style.alpha) + } + } + + private func setFill(_ ctx: CGContext, _ rgb: UInt32, _ alpha: CGFloat) { + // Theme channels, like PDF raster bytes, are sRGB. Device RGB can + // brighten them when AppKit's backing bitmap uses another profile. + ctx.setFillColor(CGColor(srgbRed: CGFloat((rgb >> 16) & 0xFF) / 255, + green: CGFloat((rgb >> 8) & 0xFF) / 255, + blue: CGFloat(rgb & 0xFF) / 255, + alpha: alpha)) + } + + /// One surface pixel has one background opacity, even when a compact + /// layer covers a canonical cell. Source-over would turn 71% into 92%, + /// then 98%, as the ground, row and cell are painted over each other. + private func fillBackground(_ ctx: CGContext, _ rect: CGRect, _ rgb: UInt32, _ alpha: CGFloat) { + ctx.saveGState() + ctx.setShouldAntialias(false) + if rgb == bgClear { + ctx.clear(rect) + } else { + ctx.setBlendMode(.copy) + fill(ctx, rect, rgb, alpha) + } + ctx.restoreGState() + } + + private func fill(_ ctx: CGContext, _ rect: CGRect, _ rgb: UInt32, _ alpha: CGFloat) { + setFill(ctx, rgb, alpha) + ctx.fill(rect) + } + + // MARK: - the core, and the pump + + /// Everything below ends here. Posting the notification in one place is + /// what guarantees no entry point can feed the core and forget to ask for + /// the tick that performs it. + private func fed() { + NotificationCenter.default.post(name: pardesDidInputNotification, object: self) + } + + /// A point inside the NSView can still be outside the CRT's curved tube. + /// For input that is the same as leaving the grid: discard a pending hover + /// preview, but do not manufacture a clamped click or wheel gesture. + private func leftGrid() { + pardes_pointer_leave() + fed() + } + + func typeKey(_ cp: UInt32, text: String, mods: UInt32) { + // The pointer is borrowed for the call and nowhere else, which is the only + // thing the header promises about it. + text.withCString { pardes_key(cp, $0, text.utf8.count, mods) } + fed() + } + + // `mods` defaults to none because a synthesized gesture carries no + // keyboard state; the NSEvent overrides always pass the real mask. Ctrl is + // the one the core actually consults — a left press with it held is + // goto-definition — so dropping it here would silently delete a feature. + private var sampledBodyPointer: CGPoint? + + private func sendMouse(_ button: pardes_mouse_button_e, _ kind: pardes_mouse_kind_e, + _ col: UInt16, _ row: UInt16, _ mods: UInt32) { + guard let point = sampledBodyPointer else { + pardes_mouse(button, kind, col, row, mods) + return + } + let scale = metricsScale + pardes_mouse_pixel(button, kind, col, row, mods, Float(point.x*scale), Float(point.y*scale), + Float(cellWidth*scale), Float(cellHeight*scale), Float(taglines.width*scale), Float(taglines.height*scale)) + } + + func press(_ button: pardes_mouse_button_e, at cell: GridPoint, mods: UInt32 = 0) { + sendMouse(button, PARDES_MOUSE_PRESS, cell.col, cell.row, mods) + fed() + } + + func release(_ button: pardes_mouse_button_e, at cell: GridPoint, mods: UInt32 = 0) { + sendMouse(button, PARDES_MOUSE_RELEASE, cell.col, cell.row, mods) + fed() + } + + func drag(_ button: pardes_mouse_button_e, to cell: GridPoint, mods: UInt32 = 0) { + sendMouse(button, PARDES_MOUSE_DRAG, cell.col, cell.row, mods) + fed() + } + + func motion(to cell: GridPoint, mods: UInt32 = 0) { + sendMouse(PARDES_MOUSE_NONE, PARDES_MOUSE_MOTION, cell.col, cell.row, mods) + fed() + } + + /// A press and its release with nothing in between, which is what every + /// synthesized click is: a trackpad gesture we recognised rather than a + /// button the user held. + func click(_ button: pardes_mouse_button_e, at cell: GridPoint, mods: UInt32 = 0) { + press(button, at: cell, mods: mods) + release(button, at: cell, mods: mods) + } + + /// One discrete wheel notch, as opposed to the continuous travel below. + func wheel(_ button: pardes_mouse_button_e, at cell: GridPoint, mods: UInt32 = 0) { + sendMouse(button, PARDES_MOUSE_PRESS, cell.col, cell.row, mods) + fed() + } + + func scroll(rows: CGFloat, cols: CGFloat = 0, at cell: GridPoint) { + guard rows != 0 || cols != 0 else { return } + pardes_scroll(Float(rows), Float(cols), cell.col, cell.row) + fed() + } + + /// Fingers down and fingers up on a precise scroll. Entry points of their + /// own for the same reason rotateEnd is one: NSEvent phases have no public + /// constructor, and a fling nothing can synthesize is a fling nothing can + /// assert. + func scrollBegin() { + pardes_scroll_begin() + fed() + } + + func scrollEnd() { + pardes_scroll_end() + fed() + } + + func rotate(degrees: CGFloat) { + guard degrees != 0 else { return } + pardes_rotate(Float(degrees)) + fed() + } + + /// The fingers came off the trackpad. A post-decode entry point of its own + /// so the e2e harness can throw the dial: NSEvent phases have no public + /// constructor, and a fling nothing can synthesize is a fling nothing can + /// assert. + func rotateEnd() { + pardes_rotate_end() + fed() + } + + // MARK: - keyboard + + override func keyDown(with event: NSEvent) { + let flags = event.modifierFlags + // Same reason as the trackpad trace below: whether AppKit delivered a + // keystroke at all is not something this process can otherwise answer, + // and "Escape does nothing" has two entirely different causes + // depending on whether this line prints. + trace("key: code=\(event.keyCode) mods=\(flags.rawValue) chars=" + + (event.charactersIgnoringModifiers?.unicodeScalars + .map { String($0.value, radix: 16) }.joined(separator: ",") ?? "-")) + // The ABI has no super bit, so a Command chord cannot be expressed at all. + // Anything the main menu claims never reaches here; the rest is swallowed + // rather than delivered as the bare keystroke the core would insert. + if flags.contains(.command) { + if event.charactersIgnoringModifiers?.lowercased() == "v" { + delegate?.pardesViewRequestsPaste(self) + } + return + } + + let control = flags.contains(.control) + let option = flags.contains(.option) + // With ctrl or option down, `characters` is already the composed result — + // Ctrl-A is U+0001, Option-A is "å". The core wants the base key and no + // text, which is what app.mjs does with the same two bits. + let composed = (control || option ? event.charactersIgnoringModifiers : event.characters) ?? "" + guard let scalar = composed.unicodeScalars.first else { return } + + var codepoint = scalar.value + // 0xF700..0xF8FF is AppKit's private-use block for function keys. The nine + // the core names get translated; the rest (F1-F12, Insert, the keypad) are + // dropped, because passing one through paints a stray glyph. + // These constants come from an unnamed C enum, so which width Swift picks + // for them is not something this file should depend on: wrapping each in + // UInt32() compiles whether they import as Int, Int32 or UInt32. + if scalar.value >= 0xF700 && scalar.value <= 0xF8FF { + switch scalar.value { + case UInt32(NSUpArrowFunctionKey): codepoint = UInt32(PARDES_KEY_UP) + case UInt32(NSDownArrowFunctionKey): codepoint = UInt32(PARDES_KEY_DOWN) + case UInt32(NSLeftArrowFunctionKey): codepoint = UInt32(PARDES_KEY_LEFT) + case UInt32(NSRightArrowFunctionKey): codepoint = UInt32(PARDES_KEY_RIGHT) + case UInt32(NSHomeFunctionKey): codepoint = UInt32(PARDES_KEY_HOME) + case UInt32(NSEndFunctionKey): codepoint = UInt32(PARDES_KEY_END) + case UInt32(NSPageUpFunctionKey): codepoint = UInt32(PARDES_KEY_PAGE_UP) + case UInt32(NSPageDownFunctionKey): codepoint = UInt32(PARDES_KEY_PAGE_DOWN) + case UInt32(NSDeleteFunctionKey): codepoint = UInt32(PARDES_KEY_DELETE) + default: return + } + } + + // Enter, Tab, Escape and Backspace already arrive as the ASCII controls the + // header names. Two keys do not: the keypad's Enter is U+0003 and Shift-Tab + // is U+0019, neither of which is in the function-key block above, so without + // this both reach the core as a control it has no binding for and do + // nothing. The browser shell resolves them from the DOM key name and this + // is what keeps the two hosts saying the same thing. + if codepoint == 0x03 { codepoint = UInt32(PARDES_KEY_ENTER) } + if codepoint == 0x19 { codepoint = UInt32(PARDES_KEY_TAB) } + + // A control character is functional, and functional keys must not also + // carry text. + let functional = codepoint < 0x20 || codepoint == 0x7F || codepoint >= 0xF0000 + let text = functional || control || option ? "" : composed + // Typing is the moment the pointer stops being interesting and starts + // sitting on top of the words. It comes back on the next mouse move. + NSCursor.setHiddenUntilMouseMoves(true) + typeKey(codepoint, text: text, mods: modifiers(flags)) + } + + // MARK: - trackpad + + // NSTouch arrives through these four and nowhere else. They are the only + // reliable source of "how many fingers are down right now": the touch set + // on a mouse event is an accident of how the click was produced, and an + // empty one is indistinguishable from one finger. + override func touchesBegan(with event: NSEvent) { countTouches(event) } + override func touchesMoved(with event: NSEvent) { countTouches(event) } + override func touchesEnded(with event: NSEvent) { countTouches(event) } + override func touchesCancelled(with event: NSEvent) { countTouches(event) } + + private func countTouches(_ event: NSEvent) { + restingFingers = event.touches(matching: .touching, in: nil).count + trace("touch: resting=\(restingFingers)") + } + + // MARK: - mouse + + // All three button streams land in the same three functions, because which + // stream a trackpad click arrives on is not something the app gets to know + // in advance: with macOS's secondary click on, two AND three fingers both + // come in as rightMouseDown. The button is therefore decided once, at the + // press, from the fingers plus the stream, and then LATCHED — the core is + // tracking a drag keyed by button, and answering a press of 3 with a + // release of 1 leaves it holding a sweep nothing will ever end. + // + // The count itself is maintained by the touchesXxx callbacks above; see + // beginClick for why it can only come from there. + private func beginClick(_ stream: pardes_mouse_button_e, _ event: NSEvent) { + guard let at = cell(for: event) else { + leftGrid() + return + } + pressureStage = 0 + // The count comes from the touch stream and NEVER from the mouse event. + // Asking a mouse event for its touches is not merely unreliable, it + // raises: -[NSEvent touchesMatchingPhase:inView:] is defined for + // gesture and touch events, and on anything else AppKit throws, catches + // it inside its own event dispatch, and abandons the rest of this + // method. Nothing crashes and nothing is logged — every click just + // silently stops working, a plain drag included, while rotation and + // scrolling carry on as if the backend were fine. That is exactly how + // this presented, and it is why restingFingers exists. + let button = Trackpad.button(stream: stream, fingers: restingFingers) + trace("press: stream=\(stream.rawValue) fingers=\(restingFingers) -> button=\(button.rawValue)") + latchedButton = button + latchedCell = at + press(button, at: at, mods: modifiers(event.modifierFlags)) + } + + private func continueClick(_ event: NSEvent) { + guard let button = latchedButton else { return } + guard let at = cell(for: event) else { + // The drag is still latched, but the curved CRT edge displays no + // source cell here. Keep its last real endpoint for mouseUp and + // clear hover/seam state without clamping into the grid. + leftGrid() + return + } + latchedCell = at + drag(button, to: at, mods: modifiers(event.modifierFlags)) + } + + private func endClick(_ event: NSEvent) { + pressureStage = 0 + // Already nil when the force click below converted this press: it + // released the button itself and there is nothing left to end. + guard let button = latchedButton else { return } + latchedButton = nil + if let at = cell(for: event) { + latchedCell = nil + release(button, at: at, mods: modifiers(event.modifierFlags)) + return + } + // A release must balance its press even when the hand ends in a black + // CRT corner. The last mapped drag point is an observed source cell, + // not a clamp of the unmappable release point. Send both state changes + // before one pump notification so no frame can observe a held button + // whose pointer is already outside the displayed scene. + if let last = latchedCell { + sendMouse(button, PARDES_MOUSE_RELEASE, last.col, last.row, + modifiers(event.modifierFlags)) + } + latchedCell = nil + pardes_pointer_leave() + fed() + } + + override func mouseDown(with event: NSEvent) { beginClick(PARDES_MOUSE_LEFT, event) } + override func mouseDragged(with event: NSEvent) { continueClick(event) } + override func mouseUp(with event: NSEvent) { endClick(event) } + // Where a two-finger click lands with macOS's own secondary click on, and + // where a three-finger one lands too — hence the finger count in + // Trackpad.button rather than a hardcoded RIGHT here. + override func rightMouseDown(with event: NSEvent) { beginClick(PARDES_MOUSE_RIGHT, event) } + override func rightMouseDragged(with event: NSEvent) { continueClick(event) } + override func rightMouseUp(with event: NSEvent) { endClick(event) } + // Thumb navigation has its own stream so it cannot replace a held + // selection button or inherit a resting trackpad's finger count. + override func otherMouseDown(with event: NSEvent) { + if event.buttonNumber == 2 { beginClick(PARDES_MOUSE_MIDDLE, event); return } + guard event.buttonNumber == 3 || event.buttonNumber == 4, + let at = cell(for: event) else { return } + press(event.buttonNumber == 3 ? PARDES_MOUSE_BACK : PARDES_MOUSE_FORWARD, + at: at, mods: pointerModifiers) + } + override func otherMouseDragged(with event: NSEvent) { + if event.buttonNumber == 2 { continueClick(event) } + } + override func otherMouseUp(with event: NSEvent) { + if event.buttonNumber == 2 { endClick(event); return } + guard event.buttonNumber == 3 || event.buttonNumber == 4, + let at = cell(for: event) else { return } + release(event.buttonNumber == 3 ? PARDES_MOUSE_BACK : PARDES_MOUSE_FORWARD, + at: at, mods: pointerModifiers) + } + + /// A deep press, which is a second gesture layered on the click already in + /// flight. AppKit keeps sending stage-2 events while the finger stays down, + /// so only the transition counts. + /// + /// Whatever button is in flight is released before the look one goes out: + /// a right press arriving while the core holds a left select-drag is + /// acme's 1-3 chord, which is Paste. Releasing first costs a cursor move + /// at the click point — which is what clicking there would have done + /// anyway; a multi-finger press released this way fires its own Exec, + /// which is what the fingers already asked for. + /// + /// Not gated on the press being a LEFT one, which is what stopped this + /// working: on a Force Touch trackpad the deep press is just as likely to + /// have arrived on the right stream, and an in-flight Exec upgraded by + /// pressing harder is precisely the gesture. Already-Look is the only case + /// with nothing to do. + override func pressureChange(with event: NSEvent) { + trace("pressure: stage=\(event.stage) latched=\(String(describing: latchedButton?.rawValue))") + guard pressureStage < 2 else { return } + pressureStage = event.stage + guard event.stage == 2 else { return } + guard let at = latchedCell, let current = latchedButton, + current != Trackpad.forceClickButton else { return } + latchedButton = nil + latchedCell = nil + release(current, at: at, mods: modifiers(event.modifierFlags)) + click(Trackpad.forceClickButton, at: at, mods: modifiers(event.modifierFlags)) + } + + override func mouseMoved(with event: NSEvent) { + guard let at = cell(for: event) else { + leftGrid() + return + } + motion(to: at, mods: modifiers(event.modifierFlags)) + } + + override func mouseExited(with event: NSEvent) { + pointerPoint = nil + pointerMapped = false + leftGrid() + } + + override func scrollWheel(with event: NSEvent) { + guard let at = cell(for: event) else { + leftGrid() + return + } + if event.hasPreciseScrollingDeltas { + // Phases first: a finger back on the pad has to catch a coast before + // its own travel is spent, or the first millimetre of the new swipe + // would be added to the old fling instead of replacing it. + // + // Momentum events carry `phase == .none` and a momentumPhase + // instead, so neither branch here fires for them — they are just + // more travel, and libpardes lets them take the gesture over. That + // is deliberate: AppKit's fling is the one the rest of the system + // uses, and a second fling of our own underneath it would scroll + // everything at double speed. `pardes_scroll_end` exists for the + // devices AppKit does NOT fling for. + if event.phase == .began { scrollBegin() } + // The core scrolls a cell at a time, so libpardes accumulates the + // sub-cell travel and spends it as wheel presses — which is why the + // cell has to travel with the delta. + scroll(rows: -event.scrollingDeltaY / cellHeight, + cols: -event.scrollingDeltaX / cellWidth, + at: at) + switch event.phase { + case .ended: scrollEnd() + // A gesture the system took away should not be thrown. scrollBegin + // is the catching half of the pair — coast stopped, bank and + // velocity cleared — which is exactly what a cancellation means. + case .cancelled: scrollBegin() + default: break + } + } else { + // AppKit's sign is the opposite of the DOM's: positive deltaY means the + // content moved down, which is a scroll back through history. + if event.scrollingDeltaY != 0 { + wheel(event.scrollingDeltaY > 0 ? PARDES_MOUSE_WHEEL_UP : PARDES_MOUSE_WHEEL_DOWN, + at: at, mods: modifiers(event.modifierFlags)) + } + if event.scrollingDeltaX != 0 { + wheel(event.scrollingDeltaX > 0 ? PARDES_MOUSE_WHEEL_LEFT : PARDES_MOUSE_WHEEL_RIGHT, + at: at, mods: modifiers(event.modifierFlags)) + } + } + } + + /// Two fingers twisted on the trackpad are the search-step keys: clockwise + /// walks forward through the matches, counterclockwise back. It is a dial, + /// and n/N is what a dial over a list of hits means. libpardes owns the + /// quantizing and the momentum, exactly as it owns the scroll accumulator. + /// + /// AppKit gives rotation no momentum phase of its own — `momentumPhase` is + /// scroll's alone — so the fling is measured from the release speed on the + /// Zig side rather than handed to us. All this has to get right is telling + /// it where the gesture starts and stops. + override func rotate(with event: NSEvent) { + trace("rotate: degrees=\(event.rotation) phase=\(event.phase.rawValue)") + // A gesture starting drops whatever the last one left banked, so the + // first degree of a new twist cannot inherit a nearly-complete notch — + // and stops a fling still coasting, because a finger back down is how + // a hand catches a dial. + if event.phase == .began { pardes_rotate(0) } + rotate(degrees: CGFloat(event.rotation)) + // .cancelled too: a gesture the system took away should not fling. + if event.phase == .ended || event.phase == .cancelled { rotateEnd() } + } + + /// What the trackpad actually delivered, under PARDES_LOG — the same + /// variable the Zig side gates its logger on (src/macos.zig). + /// + /// This is not scaffolding left behind. Which events a trackpad produces is + /// decided by the hardware and by four different System Settings switches + /// (secondary click, three-finger drag, force click, "look up"), none of + /// which this process can read, and every one of which turns a gesture into + /// a different NSEvent or into none at all. When someone reports that + /// two-finger Exec does nothing, this is the only thing that can answer + /// whether AppKit saw two fingers, one, or no click at all. + private func trace(_ message: @autoclosure () -> String) { + guard PardesView.tracing else { return } + FileHandle.standardError.write(Data(("pardes: " + message() + "\n").utf8)) + } + + private static let tracing = ProcessInfo.processInfo.environment["PARDES_LOG"] != nil + + private func cell(for event: NSEvent) -> GridPoint? { + let point = convert(event.locationInWindow, from: nil) + pointerPoint = point + pointerModifiers = modifiers(event.modifierFlags) + let at = cellAt(point) + pointerMapped = at != nil + if let at { pointerCell = at } + return at + } + + func cellAt(_ point: CGPoint) -> GridPoint? { + // Clamp against the frame the core last rendered, not against our own + // metrics: a window that has been resized but not yet ticked would + // otherwise report a column the core has no cell for. Before the first + // frame there is no grid to point at and the event is meaningless. + let cols = Int(pardes_frame_cols()) + let rows = Int(pardes_frame_rows()) + guard cols > 0, rows > 0 else { return nil } + let sampled: CGPoint + if let scene = lastPresentedScene { + guard let mapped = ScenePostprocessor.sourcePoint(point, size: bounds.size, scene: scene) + else { return nil } + sampled = mapped + } else { + sampled = point + } + sampledBodyPointer = sampled + let row = min(max(Int(sampled.y / cellHeight), 0), rows - 1) + let col = min(max(Int(sampled.x / cellWidth), 0), cols - 1) + return GridPoint(col: UInt16(col), row: UInt16(row)) + } + + // MARK: - files dropped on the grid + + /// A drop is a CLICK followed by `Look`, and that is the whole definition. + /// + /// The core has no notion of a drop and is not being given one: the pointer + /// lands where it landed, which focuses that pane exactly as a left click + /// there would, and then the ordinary `Look` builtin runs in it — so the + /// document opens beside the pane you pointed at rather than beside + /// whichever one happened to be focused. Drop on a tag and you clicked a + /// tag; there is no case to special-case, and nothing here the hand could + /// not have done itself. + override func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation { + // AppKit reuses this answer for draggingUpdated when that is not + // implemented, so the cursor stays right for the whole drag. + droppedFiles(sender).isEmpty ? [] : .copy + } + + override func performDragOperation(_ sender: NSDraggingInfo) -> Bool { + let paths = droppedFiles(sender) + guard !paths.isEmpty else { return false } + drop(paths, at: cellAt(convert(sender.draggingLocation, from: nil))) + return true + } + + /// The drop, decoded: paths and a cell, nothing AppKit left in it. + /// + /// Split out for the reason every gesture here is — `NSDraggingInfo` is a + /// protocol with a dozen members and no public conformer, so a test that + /// had to build one would be testing its own stub. The decision lives one + /// call below the event, and `drop` in test/macos_e2e.swift drives exactly + /// this. + /// + /// A nil cell is a drop before the first frame, which has no grid to point + /// at: the files still open, they just open where focus already was. + func drop(_ paths: [String], at target: GridPoint?) { + if let target { + press(PARDES_MOUSE_LEFT, at: target) + release(PARDES_MOUSE_LEFT, at: target) + } + // Whole tail, unquoted: executeBuiltinLine takes everything after the + // first word as the argument, so a path with spaces in it needs no + // escaping and would in fact break under any. + for path in paths { + let line = "Look \(path)" + line.withCString { pardes_command($0, line.utf8.count) } + } + fed() + } + + /// File paths on the drag pasteboard, in order. Empty for anything else, + /// which is also how draggingEntered decides whether to accept at all. + private func droppedFiles(_ sender: NSDraggingInfo) -> [String] { + let options: [NSPasteboard.ReadingOptionKey: Any] = [.urlReadingFileURLsOnly: true] + guard let urls = sender.draggingPasteboard.readObjects( + forClasses: [NSURL.self], options: options) as? [URL] + else { return [] } + return urls.map(\.path) + } + + // MARK: - geometry + + override func updateTrackingAreas() { + super.updateTrackingAreas() + for area in trackingAreas { removeTrackingArea(area) } + // .inVisibleRect keeps the area correct across resizes on its own, which + // is why the rect argument can be anything. + addTrackingArea(NSTrackingArea(rect: .zero, + options: [.mouseMoved, .mouseEnteredAndExited, .inVisibleRect, .activeInKeyWindow], + owner: self, + userInfo: nil)) + } + + private enum Pointer: Equatable { case text, link, target } + private var pointer: Pointer = .text + + /// The core's pointer_shape, in this shell's cursor vocabulary: a link + /// is a PDF hyperlink (the hand), a target is a word the core's own + /// Look-hover plumbing validated as a real Look or Exec operand, and + /// anything else is text — the I-beam. + private func pointerShape() -> Pointer { + switch pardes_pointer_shape() { + case 1: return .link + case 2: return .target + default: return .text + } + } + + private func cursorFor(_ shape: Pointer) -> NSCursor { + switch shape { + case .link: return .pointingHand + case .target: return .arrow + case .text: return .iBeam + } + } + + override func resetCursorRects() { + // Every cell in this view is text, including the tags. An arrow over + // plain text is the wrong affordance — but a word the core has + // validated as a Look or Exec target earns it: middle- and + // right-clicking there acts, and the cursor says so before it does. + addCursorRect(bounds, cursor: cursorFor(pointer)) + } + + override func setFrameSize(_ newSize: NSSize) { + super.setFrameSize(newSize) + // AppKit resizes a view many times over one drag and almost all of those + // land inside the same cell. Only a changed grid is news, and the core + // reflows every pty on a resize, so the no-ops are not free. + let grid = gridSize + guard grid.cols != reportedCols || grid.rows != reportedRows else { return } + reportedCols = grid.cols + reportedRows = grid.rows + delegate?.pardesViewDidResize(self) + } + + // Dragging the window between a Retina display and a 1x one changes the + // backing scale without moving a single bound, so setFrameSize above never + // fires. This is the only notification of it. (Ghostty hooks the same one, + // and additionally re-fires from the window's didChangeScreen + // notification, which AppKit does not always pair with it.) + // + // TWO things depend on the scale: the physical cell metrics the core uses + // to place PDF pages, and the cell itself, which is snapped to whole + // DEVICE pixels (see Metrics) and is therefore aligned to the display it + // was measured on. Re-measuring reports the resize on its own, so the + // delegate call is the else-branch and not an extra one. + override func viewDidChangeBackingProperties() { + super.viewDidChangeBackingProperties() + if let scale = window?.backingScaleFactor, scale != metricsScale { + wear(size: fontSize, path: fontPath) + } else { + delegate?.pardesViewDidResize(self) + } + } +} + +// ponytail: no NSTextInputClient, so dead keys and IME composition never reach +// the core — keyDown reads `characters` and that is the whole story. Adopting +// the protocol and routing through interpretKeyEvents is the upgrade when +// someone needs to type Japanese, and it needs the core to be able to render an +// underlined preedit run first. diff --git a/dev/macos/Sources/ScenePostprocessor.swift b/dev/macos/Sources/ScenePostprocessor.swift new file mode 100644 index 00000000..41d54e34 --- /dev/null +++ b/dev/macos/Sources/ScenePostprocessor.swift @@ -0,0 +1,321 @@ +// The one GPU owner for panel transitions and persistent scene effects. +// CoreText remains the renderer: while either exists PardesView draws its +// complete ordinary frame into this retained bitmap, then Core Image runs the +// standalone shaders/crt.ci.metal kernels over it. With neither, the view +// bypasses this object entirely. + +import CoreGraphics +import CoreImage +import Darwin +import Metal + +final class ScenePostprocessor { + enum CompositeOutcome { + case presented + case retry + case unavailable + } + + private let colorSpace: CGColorSpace + private let sceneKernel: CIKernel + private let panelClearKernel: CIKernel + private let panelKernel: CIKernel + private let context: CIContext + private var raster: CGContext? + private var previousRaster: CGContext? + private var rasterWidth = 0 + private var rasterHeight = 0 + private var rasterScale: CGFloat = 0 + + init?() { + let colorSpace = CGColorSpace(name: CGColorSpace.sRGB) + ?? CGColorSpaceCreateDeviceRGB() + guard let source = ScenePostprocessor.kernelSource(), + let device = MTLCreateSystemDefaultDevice(), + let made = try? CIKernel.kernels(withMetalString: source), + let sceneKernel = made.first(where: { $0.name == "pardesScene" }), + let panelClearKernel = made.first(where: { $0.name == "pardesPanelClear" }), + let panelKernel = made.first(where: { $0.name == "pardesPanel" }) + else { return nil } + self.colorSpace = colorSpace + self.sceneKernel = sceneKernel + self.panelClearKernel = panelClearKernel + self.panelKernel = panelKernel + self.context = CIContext(mtlDevice: device, options: [ + .workingColorSpace: colorSpace, + .outputColorSpace: colorSpace, + .cacheIntermediates: false, + ]) + } + + private static func kernelSource() -> String? { + var candidates: [URL] = [] + if let resources = Bundle.main.resourceURL { + candidates.append(resources.appendingPathComponent("crt.ci.metal")) + } + // An unbundled e2e executable has no Contents/Resources. Its build + // puts the asset next to the binary, and this explicit candidate keeps + // that dev loop independent of Bundle's treatment of command tools. + if let executable = Bundle.main.executableURL { + candidates.append(executable.deletingLastPathComponent() + .appendingPathComponent("crt.ci.metal")) + } + for url in candidates { + if let source = try? String(contentsOf: url, encoding: .utf8) { + return source + } + } + return nil + } + + /// A body-font-sized, top-left-origin CGContext matching the view's own + /// coordinate system. It is retained across frames; only a resize or a + /// backing-scale move reallocates the pixel storage. + func renderContext(size: CGSize, scale: CGFloat) -> CGContext? { + let scale = max(1, scale) + let width = max(1, Int((size.width * scale).rounded(.up))) + let height = max(1, Int((size.height * scale).rounded(.up))) + if raster == nil || width != rasterWidth || height != rasterHeight || scale != rasterScale { + let info = CGBitmapInfo.byteOrder32Big.rawValue + | CGImageAlphaInfo.premultipliedLast.rawValue + guard let next = CGContext( + data: nil, width: width, height: height, + bitsPerComponent: 8, bytesPerRow: width * 4, + space: colorSpace, bitmapInfo: info) + else { return nil } + next.translateBy(x: 0, y: CGFloat(height)) + next.scaleBy(x: scale, y: -scale) + raster = next + // The old and new snapshots must have identical extents. Lazily + // rebuild the old owner only if an effect actually needs it. + previousRaster = nil + rasterWidth = width + rasterHeight = height + rasterScale = scale + } + return raster + } + + /// A second complete CoreText raster for the frozen old grid. It is + /// intentionally a peer of `raster`, not a collection of per-pane image + /// pointers: deleted PDF/image panes have already released their core + /// bytes, while PardesView's frozen CGImages remain safe to draw here. + func previousRenderContext(size: CGSize, scale: CGFloat) -> CGContext? { + guard renderContext(size: size, scale: scale) != nil else { return nil } + if previousRaster == nil { + let info = CGBitmapInfo.byteOrder32Big.rawValue + | CGImageAlphaInfo.premultipliedLast.rawValue + guard let next = CGContext( + data: nil, width: rasterWidth, height: rasterHeight, + bitsPerComponent: 8, bytesPerRow: rasterWidth * 4, + space: colorSpace, bitmapInfo: info) + else { return nil } + next.translateBy(x: 0, y: CGFloat(rasterHeight)) + next.scaleBy(x: rasterScale, y: -rasterScale) + previousRaster = next + } + return previousRaster + } + + /// Run the one scene kernel and copy its result into the flipped NSView + /// context. Allocation/device failures may be retried briefly. A kernel + /// rejecting its fixed argument layout is permanent for this executable, + /// so the caller can turn the advertised effects back off instead of + /// silently spinning a display clock forever. + func composite( + scene: pardes_scene_s, + tracks: UnsafeBufferPointer<pardes_panel_track_s>, + changedCells: UnsafePointer<UInt8>?, + changedAttachmentRects: [CGRect], + gridSize: (cols: Int, rows: Int), + cellSize: CGSize, + ground: UInt32?, + size: CGSize, + into destination: CGContext + ) -> CompositeOutcome { + guard let raster, let sourceImage = raster.makeImage() else { return .retry } + let extent = CGRect(x: 0, y: 0, width: rasterWidth, height: rasterHeight) + let current = CIImage(cgImage: sourceImage, options: [.colorSpace: colorSpace]) + let old: CIImage + if let previousImage = previousRaster?.makeImage() { + old = CIImage(cgImage: previousImage, options: [.colorSpace: colorSpace]) + } else { + old = current + } + let mask = changeMask( + changedCells, attachmentRects: changedAttachmentRects, + gridSize: gridSize, cellSize: cellSize) ?? + CIImage(color: CIColor(red: 0, green: 0, blue: 0, alpha: 1)) + .cropped(to: CGRect(x: 0, y: 0, width: 1, height: 1)) + var filtered = current + + // Geometric targets are prepared before any presented panel is drawn. + // Horizontal slide/zoom use the theme ground; a vertical opener uses + // the exact old frame inside its fixed clip. Data effects and closing + // tombstones leave the canonical current frame untouched underneath. + let clear = ground.map { encoded in + CIColor( + red: CGFloat((encoded >> 16) & 0xFF) / 255, + green: CGFloat((encoded >> 8) & 0xFF) / 255, + blue: CGFloat(encoded & 0xFF) / 255, + alpha: 1) + } ?? CIColor(red: 0, green: 0, blue: 0, alpha: 0) + for track in tracks { + let content = track.phase == UInt8(PARDES_PANEL_CLOSING) ? track.from : track.to + guard let next = panelClearKernel.apply( + extent: extent, + roiCallback: { _, _ in extent }, + arguments: [ + filtered, old, + pixelBox(content, cellSize: cellSize), clear, + Float(track.effect), Float(track.phase), + ]) + else { return .unavailable } + filtered = next + } + + // libpardes orders moving, opening, then closing tombstones. Each pass + // samples immutable old/new rasters and composes over the prior pass, + // so a deleted pane can safely outlive its core Pane allocation. + let pixelCell = CIVector( + x: cellSize.width * rasterScale, + y: cellSize.height * rasterScale) + for track in tracks { + let content = track.phase == UInt8(PARDES_PANEL_CLOSING) ? track.from : track.to + guard let next = panelKernel.apply( + extent: extent, + roiCallback: { _, _ in extent }, + arguments: [ + current, old, mask, filtered, + pixelBox(content, cellSize: cellSize), + pixelBox(track.from, cellSize: cellSize), + pixelBox(track.to, cellSize: cellSize), + Float(track.effect), Float(track.phase), Float(track.frame), + CIVector( + x: CGFloat(track.serial & 0xFFFF), + y: CGFloat(track.serial >> 16)), + pixelCell, + CIVector( + x: 0, + y: extent.height - CGFloat(gridSize.rows) * pixelCell.y), + ]) + else { return .unavailable } + filtered = next + } + + if scene.flags != 0 { + let crt: Float = scene.flags & UInt32(PARDES_SCENE_CRT) != 0 ? 1 : 0 + // SDL samples the scene with CLAMP_TO_EDGE. A finite Core Image + // instead supplies transparent black outside its extent, which + // would tear dark seams at the window edge. + // Clamp the input only; the kernel still emits true black before + // sampling when a destination lies outside the CRT tube. + let sceneInput = filtered.clampedToExtent() + guard let next = sceneKernel.apply( + extent: extent, + roiCallback: { _, _ in extent }, + arguments: [ + sceneInput, scene.time_seconds, Float(scene.frame), + crt, + CIVector(x: extent.width, y: extent.height), + CIVector(x: extent.minX, y: extent.minY), + ]) + else { return .unavailable } + filtered = next + } + + guard let presented = context.createCGImage(filtered, from: extent) else { return .retry } + + destination.clear(CGRect(origin: .zero, size: size)) + destination.saveGState() + destination.translateBy(x: 0, y: size.height) + destination.scaleBy(x: 1, y: -1) + destination.interpolationQuality = .none + destination.draw(presented, in: CGRect(origin: .zero, size: size)) + destination.restoreGState() + return .presented + } + + /// Byte-per-cell mask from the core. Zig expands true to 255 so the image + /// is a literal normalized 0/1 texture; sampling cell centres below keeps + /// adjacent values from interpolating at pane/cell boundaries. + private func changeMask( + _ cells: UnsafePointer<UInt8>?, + attachmentRects: [CGRect], + gridSize: (cols: Int, rows: Int), + cellSize: CGSize + ) -> CIImage? { + let count = gridSize.cols * gridSize.rows + guard count > 0, let cells, cellSize.width > 0, cellSize.height > 0 else { return nil } + var bytes = Array(UnsafeBufferPointer(start: cells, count: count)) + for rect in attachmentRects where !rect.isNull && !rect.isEmpty { + let x0 = max(0, Int((rect.minX / cellSize.width).rounded(.down))) + let x1 = min(gridSize.cols, Int((rect.maxX / cellSize.width).rounded(.up))) + let y0 = max(0, Int((rect.minY / cellSize.height).rounded(.down))) + let y1 = min(gridSize.rows, Int((rect.maxY / cellSize.height).rounded(.up))) + guard x0 < x1, y0 < y1 else { continue } + for row in y0..<y1 { + for col in x0..<x1 { bytes[row * gridSize.cols + col] = 255 } + } + } + return bytes.withUnsafeBufferPointer { buffer in + guard let base = buffer.baseAddress, + let data = CFDataCreate(nil, base, count), + let provider = CGDataProvider(data: data), + let gray = CGColorSpace(name: CGColorSpace.linearGray), + let image = CGImage( + width: gridSize.cols, height: gridSize.rows, + bitsPerComponent: 8, bitsPerPixel: 8, + bytesPerRow: gridSize.cols, space: gray, + bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.none.rawValue), + provider: provider, decode: nil, + shouldInterpolate: false, intent: .defaultIntent) + else { return nil } + return CIImage(cgImage: image, options: [.colorSpace: gray]) + } + } + + /// Convert the core's top-left logical-cell box to Core Image's + /// bottom-left backing-pixel rectangle. + private func pixelBox(_ box: pardes_panel_box_s, cellSize: CGSize) -> CIVector { + let cellW = cellSize.width * rasterScale + let cellH = cellSize.height * rasterScale + let x = CGFloat(box.x) * cellW + let w = CGFloat(box.w) * cellW + let h = CGFloat(box.h) * cellH + let y = CGFloat(rasterHeight) - (CGFloat(box.y) + CGFloat(box.h)) * cellH + return CIVector(x: x, y: y, z: w, w: h) + } + + /// The scene kernel is a destination-to-source mapping. Pointer input must + /// apply that same mapping before the grid and its panel tracks see a cell, + /// otherwise a visible word under the barrel is not the word Look gets. + static func sourcePoint( + _ point: CGPoint, + size: CGSize, + scene: pardes_scene_s + ) -> CGPoint? { + guard size.width > 0, size.height > 0 else { return nil } + if scene.flags == 0 { return point } + + var uvX = Float(point.x / size.width) + var uvY = 1 - Float(point.y / size.height) // Core Image is bottom-up + var ccX = uvX * 2 - 1 + var ccY = uvY * 2 - 1 + let crt: Float = scene.flags & UInt32(PARDES_SCENE_CRT) != 0 ? 1 : 0 + let radius2 = ccX * ccX + ccY * ccY + let barrel = 1 + 0.016 * radius2 * crt + ccX *= barrel + ccY *= barrel + uvX = ccX * 0.5 + 0.5 + uvY = ccY * 0.5 + 0.5 + // The CRT's black tube has no cell under it. + if crt > 0.5 && min(min(uvX, uvY), min(1 - uvX, 1 - uvY)) <= 0 { return nil } + uvX = min(max(uvX, 0), max(0, 1 - 1 / Float(size.width))) + uvY = min(max(uvY, 0), max(0, 1 - 1 / Float(size.height))) + return CGPoint( + x: CGFloat(uvX) * size.width, + y: CGFloat(1 - uvY) * size.height) + } + +} diff --git a/dev/macos/Sources/main.swift b/dev/macos/Sources/main.swift new file mode 100644 index 00000000..6cb2646e --- /dev/null +++ b/dev/macos/Sources/main.swift @@ -0,0 +1,16 @@ +import AppKit + +// Ghostty's ordering lesson: whatever must exist before AppKit boots goes above +// app.run(), because after that call the runloop owns this thread forever. +// pardes has nothing in that class — the core cannot come up until there is a +// window to measure, so pardes_init waits for applicationDidFinishLaunching. + +let app = NSApplication.shared +app.setActivationPolicy(.regular) + +// NSApplication does not own its delegate. This is a global, so it lives as +// long as the process does; the same line inside a function would not. +let delegate = AppDelegate() +app.delegate = delegate + +app.run() diff --git a/dev/macos/icon.png b/dev/macos/icon.png Binary files differnew file mode 100644 index 00000000..9889c348 --- /dev/null +++ b/dev/macos/icon.png diff --git a/dev/macos/icon.swift b/dev/macos/icon.swift new file mode 100644 index 00000000..2f45220f --- /dev/null +++ b/dev/macos/icon.swift @@ -0,0 +1,194 @@ +// Cuts pardes.app's icon out of a committed drawing and hands the result to +// iconutil. +// +// The mark is still GLENDA, the Plan 9 rabbit — pardes is an acme, and acme is +// Plan 9's, so the bunny is the lineage stated in one shape. What changed is +// where she comes from: she used to be drawn here out of the terminal's own +// palette, four ellipses and a tag bar, and she is now `icon.png` beside this +// file. A drawing is not derivable from a palette, so the old argument for +// generating her ("a checked-in .icns stops matching the app the first time a +// colour moves") no longer applies to the artwork — but it still applies to +// the ICNS, which is why this file did not become a committed binary. What is +// committed is the source picture, in one format, reviewable as an image; what +// is generated is the ten-size container macOS actually reads. +// +// So the work here is no longer drawing. It is the part a designer's PNG never +// has: Apple's icon grid, the rounded-square mask, and ten exact sizes. +// +// build.zig compiles this file alone into a cached binary and runs it with the +// source PNG as argv[1] and the bundle's Resources directory as argv[2]; +// Info.plist's CFBundleIconFile names the pardes.icns that comes out. Compiled +// alone is also what makes top-level code legal here: one file, one module. +// +// Byte-identical output for byte-identical input is a requirement, not a +// nicety — an icns that churns on every build is a bundle that churns on every +// build, and Launch Services notices. Hence a pinned sRGB colour space, +// integer geometry, and nothing read from the clock or the environment. + +import CoreGraphics +import Foundation +import ImageIO +import UniformTypeIdentifiers + +/// Every failure path lands here. A build that ships the generic blank-page +/// icon looks like an app nobody finished, so half-drawn is worse than absent +/// and build.zig has this exit code waiting: a bundle whose icon did not draw +/// should not have built. +func die(_ message: String) -> Never { + fputs("icon.swift: \(message)\n", stderr) + exit(1) +} + +// Apple's icon grid rather than the whole square: the artwork is a rounded +// square floating in a transparent margin, 824 of 1024 with a 185.4 corner +// radius in the template — 80.47% of the canvas, and 22.37% of the SQUARE, not +// of the canvas, which would over-round it by a quarter. Filling the canvas +// edge to edge is the loudest tell that an app was not built on a Mac. +let squareFraction: CGFloat = 0.8047 +let cornerFraction: CGFloat = 0.2237 + +/// Where the crop comes off when the source is not square. +/// +/// The drawing is 1204x1306 — taller than wide — so filling a square throws +/// away 8% of its height, and WHICH 8% is the whole decision. Anchoring the +/// top keeps the sun, which is the only warm thing in the picture and sits in +/// the top-right corner, and spends the loss on the bottom band of grass, +/// which is texture and repeats. Anchoring the centre would clip the sun's +/// rays to buy back grass, which is the trade backwards. 0 is top, 1 is +/// bottom; a square source ignores this entirely. +let cropAnchor: CGFloat = 0 + +/// sRGB in the bitmap, so the paper white in the drawing is the paper white in +/// the icon rather than whatever DeviceRGB would make of it. +func sRGB() -> CGColorSpace { + guard let space = CGColorSpace(name: CGColorSpace.sRGB) else { die("sRGB colour space unavailable") } + return space +} + +func loadSource(_ url: URL) -> CGImage { + guard let source = CGImageSourceCreateWithURL(url as CFURL, nil) else { + die("cannot read \(url.path)") + } + guard let image = CGImageSourceCreateImageAtIndex(source, 0, nil) else { + die("\(url.lastPathComponent) holds no decodable image") + } + return image +} + +func renderIcon(_ art: CGImage, pixels: Int) -> CGImage { + guard + let ctx = CGContext( + data: nil, width: pixels, height: pixels, + bitsPerComponent: 8, bytesPerRow: 0, space: sRGB(), + bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) + else { die("CGContext \(pixels)x\(pixels) failed") } + + // Round the MARGIN and derive the square from it. Rounding the square + // instead leaves an odd remainder to split, and at 16 pixels the artwork + // lands a pixel off centre. At 1024 this is Apple's 100/824/100 exactly. + let canvas = CGFloat(pixels) + let inset = (canvas * (1 - squareFraction) / 2).rounded() + let side = canvas - 2 * inset + let body = CGRect(x: inset, y: inset, width: side, height: side) + let corner = side * cornerFraction + + ctx.addPath(CGPath(roundedRect: body, cornerWidth: corner, cornerHeight: corner, transform: nil)) + ctx.clip() + + // Aspect FILL, not fit. Fitting would letterbox the rounded square with a + // flat band beside textured paper, and the seam between the two is visible + // at every size the band is wide enough to see. Filling overflows the clip + // instead, and the clip is already exact. + let artWidth = CGFloat(art.width) + let artHeight = CGFloat(art.height) + guard artWidth > 0, artHeight > 0 else { die("source image is empty") } + let scale = max(side / artWidth, side / artHeight) + let drawWidth = artWidth * scale + let drawHeight = artHeight * scale + + // CoreGraphics is bottom-left origin, so `cropAnchor` 0 (the TOP of the + // picture) means the drawing's top edge meets the body's top edge and the + // overflow hangs off the bottom, into the clip. + let overflowY = drawHeight - side + let overflowX = drawWidth - side + ctx.interpolationQuality = .high + ctx.draw( + art, + in: CGRect( + x: body.minX - overflowX / 2, + y: body.maxY - drawHeight + overflowY * cropAnchor, + width: drawWidth, height: drawHeight)) + + guard let image = ctx.makeImage() else { die("CGContext.makeImage failed at \(pixels)") } + return image +} + +func writePNG(_ image: CGImage, to url: URL) { + guard + let sink = CGImageDestinationCreateWithURL( + url as CFURL, UTType.png.identifier as CFString, 1, nil) + else { die("cannot open \(url.path) for writing") } + CGImageDestinationAddImage(sink, image, nil) + guard CGImageDestinationFinalize(sink) else { die("encoding \(url.lastPathComponent) failed") } +} + +// The ten names iconutil demands, spelled out rather than derived: the set is +// fixed by the tool, and a loop that generated them would be a loop to read +// before believing the list. 32, 256 and 512 appear twice under two names and +// are simply drawn twice — a third of a megapixel, against the clarity of not +// caching anything in a build tool. +let variants: [(name: String, pixels: Int)] = [ + ("icon_16x16.png", 16), + ("[email protected]", 32), + ("icon_32x32.png", 32), + ("[email protected]", 64), + ("icon_128x128.png", 128), + ("[email protected]", 256), + ("icon_256x256.png", 256), + ("[email protected]", 512), + ("icon_512x512.png", 512), + ("[email protected]", 1024), +] + +let arguments = CommandLine.arguments +guard arguments.count == 3 else { + die("usage: \(URL(fileURLWithPath: arguments.first ?? "icon").lastPathComponent) <source.png> <output-directory>") +} + +let files = FileManager.default +let art = loadSource(URL(fileURLWithPath: arguments[1])) +let outputDir = URL(fileURLWithPath: arguments[2], isDirectory: true) +let output = outputDir.appendingPathComponent("pardes.icns") + +// A fixed scratch path, cleared before use rather than a unique one: a run that +// died half way leaves a partial iconset behind, and iconutil would happily +// fold the stale sizes into the next icns without a word. +let scratch = files.temporaryDirectory.appendingPathComponent("pardes-icon", isDirectory: true) +let iconset = scratch.appendingPathComponent("pardes.iconset", isDirectory: true) + +try? files.removeItem(at: scratch) +do { + try files.createDirectory(at: iconset, withIntermediateDirectories: true) + try files.createDirectory(at: outputDir, withIntermediateDirectories: true) +} catch { + die("cannot create \(iconset.path): \(error.localizedDescription)") +} + +for variant in variants { + writePNG(renderIcon(art, pixels: variant.pixels), to: iconset.appendingPathComponent(variant.name)) +} + +let iconutil = Process() +iconutil.executableURL = URL(fileURLWithPath: "/usr/bin/iconutil") +iconutil.arguments = ["-c", "icns", "-o", output.path, iconset.path] +do { + try iconutil.run() +} catch { + die("cannot run /usr/bin/iconutil: \(error.localizedDescription)") +} +iconutil.waitUntilExit() +guard iconutil.terminationStatus == 0 else { + die("iconutil exited \(iconutil.terminationStatus) over \(iconset.path)") +} + +try? files.removeItem(at: scratch) |
