Files
chandra/compositor/host/recorder.mbt
T
Claude 34885bfdda
CI / test (push) Failing after 18s
Settings > Shortcuts: rebind the compositor's keyboard shortcuts
- One shortcut table (compositor/shell/shortcuts.mbt): named actions with their default combos,
  the same as before: Super tap launcher, Super+D, Alt+Tab, Super+Shift+S, Super+Shift+Print,
  Print, Super+Print, Super+Ctrl+Print, Super+Shift+R, Super+Alt+R, Super+Ctrl+R. Combos are
  "Super+Ctrl+Alt+Shift+Key" text (parse/print, aliases like Meta, PrtSc, Return); "Super" alone
  is a Super tap. Two shortcuts on one combo conflict and the one listed first wins.
- The compositor looks every non-modifier key press up in the table (compositor/host/
  shortcuts.mbt) instead of the hardcoded checks in showdesktop/screenshot/recorder; the switcher
  reads its combo from it (hold the combo's modifiers, its key steps, Shift reverses, releasing a
  held modifier switches). Matching is now exact on Super/Ctrl/Alt/Shift (caps/num lock ignored),
  so e.g. Super+Shift+D or Ctrl+Print no longer fire Super+D / Print.
- Settings gets a fifth tab, Shortcuts (key 5, SettingsTab::Shortcuts): every shortcut and its
  combo. Click a row (or Enter) and press the new keys: the compositor captures the combo before
  anything else sees it (Escape cancels, Backspace unbinds, a Super tap binds "Super"; window
  switching keeps waiting until the combo has a modifier). Changed rows get a Reset button
  (Backspace/Delete on the highlighted row too), plus "Reset all to defaults"; conflicting combos
  show in red with a line saying which shortcut wins. The popup is 360 px wide for the fifth tab.
- New `shortcuts` capability (shortcuts, capture, cancel-capture, reset, reset-all), served from
  host table 10 and request 18 by the wasmer/wasmtime stub, host-wasm and the MoonBit wasmhost
  (chandra:host/plasmoids `shortcut(s32)`).
- Changes are kept in state.edn as :shortcuts {:show-desktop "Super+Ctrl+D" ...} (only the ones
  that differ; "" unbinds), applied at startup and live.
- There were no window-management or tiling key shortcuts to move into the table.
- Tests: combo parsing/printing, defaults, conflicts, switcher constraint, save/restore pairs,
  rebinding through the compositor, capture (Escape/Backspace/Super tap), the Shortcuts tab
  (capture, conflict line, Reset, Reset all) and the state.edn round trip.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hjypNwGHE9WeFvnWLA
2026-11-25 20:41:22 +00:00

378 lines
13 KiB
MoonBit

///| Screen recording, after Spectacle's recording modes.
///
/// Super+Shift+R (by default; the shortcut table can rebind it) puts the selection overlay up to pick a region to record (drag a rectangle or
/// click a window, Enter starts); Super+Alt+R records the whole screen; Super+Ctrl+R the window
/// under the pointer. While recording, a red "REC" pill with the elapsed time sits at the top
/// centre; clicking it, or any of the recording shortcuts again, stops. The pointer is drawn into
/// the video unless that is switched off (P on the overlay, or the screenshot panel module).
///
/// Encoding is ffmpeg's: the compositor starts `ffmpeg` listening on a unix socket and streams
/// raw RGBA frames into it (at most 30 a second, each stamped with the wall clock as it arrives,
/// so the video plays at real speed even when frames are skipped), and ffmpeg writes H.264 in an
/// MP4: ~/Videos/Screencasts/Screencast_YYYYMMDD_HHMMSS.mp4. Writes never block: a frame that
/// ffmpeg hasn't taken yet when the next one is due makes that next one wait (it is skipped).
/// Without ffmpeg on PATH a notification says so.
///| A recording in progress.
pub(all) struct Recording {
/// The part of the screen recorded (even width and height, as H.264 wants).
rect : @scene.Rect
/// Where the video goes, and the socket ffmpeg listens on.
path : String
sock : String
/// The connection to ffmpeg (-1 until it is listening), and until when to keep trying.
mut fd : Int
connect_until : UInt64
started : UInt64
/// The frame being written and how much of it went out.
mut pending : Bytes
mut sent : Int
mut next_at : UInt64
mut frames : Int
}
///| Screen recording done by the host that draws the screen: `grab` copies a rectangle of the
/// screen (with the pointer at a screen position when asked) into the host's frame, and `send`
/// writes what is left of it to the encoder's socket (the bytes still left, or -1).
pub(all) struct FrameRecorder {
grab : (@scene.Rect, Bool, Int, Int) -> Bool
send : (Int) -> Int
}
///| Whether a recording is running.
pub fn ChandraCompositor::recording(self : ChandraCompositor) -> Bool {
self.rec is Some(_)
}
///| The region being recorded.
pub fn ChandraCompositor::recording_rect(self : ChandraCompositor) -> @scene.Rect? {
self.rec.map(r => r.rect)
}
///| Frames sent to the encoder so far in the current recording.
pub fn ChandraCompositor::recorded_frames(self : ChandraCompositor) -> Int {
match self.rec {
Some(r) => r.frames
None => 0
}
}
///| Whether recordings show the pointer.
pub fn ChandraCompositor::record_pointer(self : ChandraCompositor) -> Bool {
self.rec_pointer
}
///| Draw the pointer into recordings, or not.
pub fn ChandraCompositor::set_record_pointer(self : ChandraCompositor, on : Bool) -> Unit {
self.rec_pointer = on
self.damage.mark_full()
}
///| Start recording in `mode` (Region opens the overlay; WindowUnderCursor asks for a click when
/// no window is under the pointer); stop instead when a recording is running.
pub fn ChandraCompositor::toggle_recording(self : ChandraCompositor, mode : ShotMode) -> Unit {
if self.rec is Some(_) {
self.stop_recording()
return
}
if self.shot is Some(_) {
return
}
let full = @scene.Rect::new(0, 0, self.output_w, self.output_h)
match mode {
FullScreen => self.start_recording(full)
ActiveWindow =>
match self.active_window().bind(w => self.outer_rect(w)) {
Some(r) => self.start_recording(r)
None => self.start_recording(full)
}
WindowUnderCursor =>
match self.window_at(self.ptr_x.to_int(), self.ptr_y.to_int()).bind(w => self.outer_rect(w.0)) {
Some(r) => self.start_recording(r)
None => self.open_record_overlay(true)
}
Region => self.open_record_overlay(false)
}
}
///| The overlay, picking what to record.
fn ChandraCompositor::open_record_overlay(self : ChandraCompositor, pick : Bool) -> Unit {
match self.freeze_screen() {
Some(frame) => {
self.open_overlay(frame, pick)
match self.shot {
Some(o) => o.record = true
None => ()
}
}
None => ()
}
}
///| The user's videos folder: XDG_VIDEOS_DIR from user-dirs.dirs, else ~/Videos.
fn videos_dir() -> String {
match user_dir("XDG_VIDEOS_DIR") {
Some(d) => d
None => @sys.getenv("HOME") + "/Videos"
}
}
///| Start recording `r` (made even-sized and kept on screen).
fn ChandraCompositor::start_recording(self : ChandraCompositor, r : @scene.Rect) -> Unit {
let r = self.clip_to_screen(r)
let w = r.w / 2 * 2
let h = r.h / 2 * 2
if w < 2 || h < 2 {
return
}
if !@sys.has_exe("ffmpeg") {
self.notify("Can't record the screen", "Screen recording needs ffmpeg; install it and try again")
return
}
let dir = if self.shot_dir.length() > 0 { self.shot_dir } else { videos_dir() + "/Screencasts" }
ignore(@sys.mkdir_p(dir))
let base = dir + "/Screencast_" + timestamp()
let mut path = base + ".mp4"
let mut n = 2
while @sys.read_file_bytes(path).length() > 0 && n < 100 {
path = base + "-" + n.to_string() + ".mp4"
n = n + 1
}
let rt = match @sys.getenv("XDG_RUNTIME_DIR") {
"" => "/tmp"
d => d
}
let sock = rt + "/chandra-rec-" + @sys.getpid().to_string() + "-" + @sys.monotonic_ms().to_string() + ".sock"
let size = w.to_string() + "x" + h.to_string()
let cmd = "exec ffmpeg -hide_banner -loglevel error -nostdin -y -f rawvideo -pix_fmt rgba -video_size " +
size + " -use_wallclock_as_timestamps 1 -listen 1 -timeout 10000 -i 'unix:" + sock + "'" +
" -c:v libx264 -preset ultrafast -crf 23 -pix_fmt yuv420p -fps_mode cfr -r 30 -movflags +faststart '" +
path + "' ; rm -f '" + sock + "'"
if !@sys.spawn(cmd, self.server.socket_path) {
self.notify("Can't record the screen", "ffmpeg didn't start")
return
}
let now = @sys.monotonic_ms()
self.rec = Some({
rect: @scene.Rect::new(r.x, r.y, w, h),
path,
sock,
fd: -1,
connect_until: now + 5000UL,
started: now,
pending: Bytes::from_array([]),
sent: 0,
next_at: now,
frames: 0,
})
self.damage.mark_full()
}
///| Stop the recording: closing the stream makes ffmpeg finish the file.
pub fn ChandraCompositor::stop_recording(self : ChandraCompositor) -> Unit {
match self.rec {
Some(rec) => {
self.rec = None
if rec.fd >= 0 {
// Whatever is left of the frame in flight is dropped; ffmpeg ignores a partial frame.
@sys.close_fd(rec.fd)
let secs = (@sys.monotonic_ms() - rec.started) / 1000UL
self.last_recording = rec.path
self.notify("Recording saved", base_name(rec.path) + " · " + clock_text(secs.to_int()))
} else {
// ffmpeg may be about to listen: connect and hang up so it ends now (it also gives up
// by itself after ten seconds).
let fd = @sys.unix_connect(rec.sock)
if fd >= 0 {
@sys.close_fd(fd)
}
self.notify("Recording stopped", "ffmpeg never started listening; nothing was saved")
}
self.damage.mark_full()
}
None => ()
}
}
///| The path of the last recording saved.
pub fn ChandraCompositor::last_recording(self : ChandraCompositor) -> String {
self.last_recording
}
///| m:ss.
fn clock_text(secs : Int) -> String {
(secs / 60).to_string() + ":" + pad2(secs % 60)
}
///| A notification without a picture.
fn ChandraCompositor::notify(self : ChandraCompositor, title : String, detail : String) -> Unit {
self.shot_toast = Some({ title, detail, until: @sys.monotonic_ms() + 5000UL, thumb: [], tw: 0, th: 0 })
self.damage.mark_full()
}
///| Move the recording along (called from `step`): connect to ffmpeg, push out what the socket
/// takes, and grab the next frame when one is due and the last one is out.
fn ChandraCompositor::recording_tick(self : ChandraCompositor) -> Unit {
let rec = match self.rec {
Some(r) => r
None => return
}
let now = @sys.monotonic_ms()
if rec.fd < 0 {
rec.fd = @sys.unix_connect(rec.sock)
if rec.fd < 0 {
if now > rec.connect_until {
self.stop_recording()
}
return
}
}
match self.frame_recorder {
Some(host) => {
// The host holds the frame in flight.
if rec.sent > 0 {
let left = (host.send)(rec.fd)
if left < 0 {
self.stop_recording()
return
}
if left > 0 {
return
}
rec.sent = 0
}
if now < rec.next_at {
return
}
rec.next_at = now + 33UL
if (host.grab)(rec.rect, self.rec_pointer, self.ptr_x.to_int(), self.ptr_y.to_int()) {
rec.sent = 1 // a frame is waiting on the host
rec.frames = rec.frames + 1
}
self.damage.mark_full()
return
}
None => ()
}
// The frame in flight.
while rec.sent < rec.pending.length() {
let len = (rec.pending.length() - rec.sent).min(1 << 20)
let n = @sys.write_nonblock(rec.fd, rec.pending[rec.sent:rec.sent + len].to_bytes())
if n < 0 {
// ffmpeg went away (killed, disk full): end the recording with what it has.
self.stop_recording()
return
}
if n == 0 {
return
}
rec.sent = rec.sent + n
}
if now < rec.next_at {
return
}
rec.next_at = now + 33UL
match self.grab_region(rec.rect) {
Some(px) => {
if self.rec_pointer {
draw_pointer(px, self.ptr_x.to_int() - rec.rect.x, self.ptr_y.to_int() - rec.rect.y)
}
rec.pending = Bytes::from_fixedarray(px.data)
rec.sent = 0
rec.frames = rec.frames + 1
}
None => ()
}
// Redraw now and then so the elapsed time on the pill moves on.
self.damage.mark_full()
}
///| The pixels of `r` on screen now (opaque).
fn ChandraCompositor::grab_region(self : ChandraCompositor, r : @scene.Rect) -> @renderer.Pixmap? {
let src = match self.frame_source {
Some(f) => f()
None => self.last_frame
}
match src {
Some(p) => {
if r.x < 0 || r.y < 0 || r.x + r.w > p.width || r.y + r.h > p.height || p.data.length() < p.width * p.height * 4 {
return None
}
let data = FixedArray::make(r.w * r.h * 4, b'\xff')
for y = 0; y < r.h; y = y + 1 {
FixedArray::blit_to(p.data, data, len=r.w * 4, src_offset=((r.y + y) * p.width + r.x) * 4, dst_offset=y * r.w * 4)
}
for i = 3; i < data.length(); i = i + 4 {
data[i] = b'\xff'
}
Some({ width: r.w, height: r.h, data })
}
None => None
}
}
///| Draw an arrow pointer with its tip at (x, y): white, outlined in black.
fn draw_pointer(p : @renderer.Pixmap, x : Int, y : Int) -> Unit {
let ops : Array[@scene.DrawOp] = []
let black = @scene.Rgba::new(0, 0, 0, 255)
let white = @scene.Rgba::new(255, 255, 255, 255)
// Rows of a classic arrow: the body widens to 9 pixels over 13 rows, then a short tail.
for i = 0; i < 17; i = i + 1 {
let (l, w) = if i < 13 { (0, i * 2 / 3 + 1) } else { (3 + (i - 13), 3) }
ops.push(@scene.DrawOp::FillRect(@scene.Rect::new(x + l - 1, y + i - 1, w + 2, 3), black, 0))
}
for i = 1; i < 16; i = i + 1 {
let (l, w) = if i < 13 { (0, i * 2 / 3 - 1) } else { (4 + (i - 13), 1) }
if w > 0 {
ops.push(@scene.DrawOp::FillRect(@scene.Rect::new(x + l + 1, y + i, w, 1), white, 0))
}
}
@renderer.draw_ops(p, ops, 0, 0)
}
///| The REC pill (top right), and the outline of a region smaller than the screen.
fn ChandraCompositor::recording_ops(self : ChandraCompositor, ops : Array[@scene.DrawOp]) -> Unit {
match self.rec {
Some(rec) => {
let red = @scene.Rgba::new(235, 64, 52, 255)
let r = rec.rect
if r.w < self.output_w || r.h < self.output_h {
ops.push(@scene.DrawOp::StrokeRect(@scene.Rect::new(r.x - 2, r.y - 2, r.w + 4, r.h + 4), red, 2, 0))
}
let pill = self.rec_pill()
let p = self.theme.palette
let fs = self.theme.font_size
let secs = ((@sys.monotonic_ms() - rec.started) / 1000UL).to_int()
let starting = rec.fd < 0
ops.push(@scene.DrawOp::FillRect(pill, p.surface_popup, pill.h / 2))
ops.push(@scene.DrawOp::StrokeRect(pill, red, 1, pill.h / 2))
ops.push(@scene.DrawOp::Circle(pill.x + 16, pill.y + pill.h / 2, 6, red, true))
let label = if starting { "Starting…" } else { "REC " + clock_text(secs) + " Stop" }
ops.push(@scene.DrawOp::Text(pill.x + 30, pill.y + pill.h / 2, label, fs - 1, p.foreground, @scene.TextAlign::Left, true))
}
None => ()
}
}
///| Where the REC pill is (it stops the recording when clicked): top centre, where title bars
/// have no buttons.
fn ChandraCompositor::rec_pill(self : ChandraCompositor) -> @scene.Rect {
let w = 150
let h = 26
@scene.Rect::new((self.output_w - w) / 2, 3, w, h)
}
///| A press on the REC pill stops the recording. True when it was one.
fn ChandraCompositor::recording_click(self : ChandraCompositor, x : Int, y : Int) -> Bool {
if self.rec is None {
return false
}
let r = self.rec_pill()
if x >= r.x && x < r.x + r.w && y >= r.y && y < r.y + r.h {
self.stop_recording()
true
} else {
false
}
}