Screenshot module after Spectacle (Super+Shift+S), with a screen recorder
CI / test (push) Failing after 16s

- Super+Shift+S (or Super+Shift+Print) freezes the screen under a selection overlay, like
  Spectacle's Rectangular Region: drag a rectangle (size readout under it, magnifier while
  drawing), drag inside to move it, drag its handles to resize, or click a window to select it.
  Enter or a double-click takes it, Escape or right-click cancels; F full screen, W active window,
  arrows nudge (Shift+arrows resize). Print takes the full screen, Super+Print the active window,
  Super+Ctrl+Print the window under the pointer.
- Saved as ~/Pictures/Screenshots/Screenshot_YYYYMMDD_HHMMSS.png (XDG_PICTURES_DIR honoured),
  put on the clipboard as image/png (compositor-owned wl_data selection, written to the paste
  pipe without blocking), and confirmed by a notification with a thumbnail.
- Screen recording: Super+Shift+R picks a region on the same overlay, Super+Alt+R the screen,
  Super+Ctrl+R a window; the same shortcut or the REC pill (top centre) stops. Raw frames
  (<= 30 fps, wall-clock stamped) stream into ffmpeg over a unix socket; it writes H.264 MP4 to
  ~/Videos/Screencasts/Screencast_*.mp4. The pointer is drawn in unless switched off.
- renderer: encode_png_compressed (per-row filters + LZ77/fixed-Huffman deflate): a 1280x720
  desktop is ~90 KB instead of 3.7 MB.
- New 'screenshot' capability and 'screenshot' panel module (in the default panel): Spectacle's
  modes and the recording modes with their shortcuts, and a pointer switch; the button becomes
  Stop while recording. Served by both hosts (wasmer stub request 12 / host int 4; host-wasm
  publish-screenshot and a screenshot request). Panel requests wait for a frame without the
  module's popup.
- sys: pwrite with a negative offset is a non-blocking write (pipes, sockets), SIGPIPE ignored.
- Tests: native overlay, shortcuts, window pick, module, recording (with ffmpeg); host-wasm
  module test; renderer compression test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hjMGSLc5tHuzjsxGVa
This commit is contained in:
Claude committed 2026-11-25 19:07:23 +00:00
1 parent b33373d801
commit 85f6ff42f4
45 files changed
+3177 -57

No files matched your search

+2
View File
@@ -141,6 +141,8 @@ pub fn run(args : Array[String]) -> Int {
comp.sync_system_theme = drm // the login session sets apps' dark/light preference
comp.restore_state() // and the layout mode and recent apps from the last session
comp.shell.screen_w = width
// Screenshots and recordings read the host's framebuffer (it draws the desktop).
comp.frame_source = Some(fn() { Some(@raster.read_frame(comp.output_w, comp.output_h)) })
if gfx_out.length() > 0 && !serve {
match comp.compose_scene() {
Some(sg) => @raster.submit(sg)
+65 -5
View File
@@ -94,6 +94,28 @@ pub(all) struct ChandraCompositor {
mut session_seen : String
mut session_seen_at : UInt64
mut session_check_at : UInt64
/// Screenshots (screenshot.mbt): the selection overlay while it is up, the confirmation, a
/// panel module's request waiting for a frame without its popup ((mode, frames_built then)),
/// key codes whose release is swallowed, client frames held back while the screen is frozen,
/// and where pictures go ("" for ~/Pictures/Screenshots).
mut shot : ShotOverlay?
mut shot_toast : ShotToast?
mut shot_request : (ShotMode, Int)?
mut rec_request : (ShotMode, Int)?
mut frames_built : Int
shot_swallow : Array[UInt]
shot_frozen : Map[UInt64, @scene.ShmBufferSnapshot]
mut shot_dir : String
mut last_shot : String
/// Reads the screen for screenshots when the host draws it (the wasm compositor sets it);
/// None uses the software renderer's last frame.
mut frame_source : (() -> @renderer.Pixmap?)?
/// Screen recording (recorder.mbt): the recording running, whether it shows the pointer,
/// a press on the REC pill (its release is swallowed too) and the last video saved.
mut rec : Recording?
mut rec_pointer : Bool
mut rec_press : Bool
mut last_recording : String
}
///|
@@ -160,6 +182,20 @@ pub fn ChandraCompositor::new(
session_seen: "",
session_seen_at: 0UL,
session_check_at: 0UL,
shot: None,
shot_toast: None,
shot_request: None,
rec_request: None,
frames_built: 0,
shot_swallow: [],
shot_frozen: {},
shot_dir: "",
last_shot: "",
frame_source: None,
rec: None,
rec_pointer: true,
rec_press: false,
last_recording: "",
}
// Client popups (menus) are placed to stay on screen: the server asks for the output's
// rectangle relative to the parent's content origin when it applies constraint adjustment.
@@ -188,6 +224,8 @@ pub fn ChandraCompositor::resize(self : ChandraCompositor, w : Int, h : Int) ->
self.output_w = w
self.output_h = h
self.work_area = work_area_for(w, h, self.theme)
self.close_overlay() // its frozen frame is the old size
self.stop_recording()
self.server.set_output_size(w, h)
self.shell.set_output(self.theme, w, h)
self.apply_actions(self.wm.fit_work_area(self.work_area))
@@ -199,6 +237,7 @@ pub fn ChandraCompositor::resize(self : ChandraCompositor, w : Int, h : Int) ->
///|
pub fn ChandraCompositor::close(self : ChandraCompositor) -> Unit {
self.stop_recording()
for _, win in self.windows {
release_snapshot(win.surface)
}
@@ -366,11 +405,16 @@ pub fn ChandraCompositor::step(self : ChandraCompositor) -> Unit {
match self.windows.get(wid) {
Some(win) => {
match snap {
Some(s) => {
release_snapshot(win.surface)
win.surface = Some(s)
self.damage.mark_rect(win.geometry)
}
Some(s) =>
if self.shot is Some(_) {
// The screen is frozen under the screenshot overlay: show it afterwards.
release_snapshot(self.shot_frozen.get(wid))
self.shot_frozen.set(wid, s)
} else {
release_snapshot(win.surface)
win.surface = Some(s)
self.damage.mark_rect(win.geometry)
}
None => ()
}
}
@@ -433,6 +477,8 @@ pub fn ChandraCompositor::step(self : ChandraCompositor) -> Unit {
None => ()
}
ignore(self.windows.remove(wid))
release_snapshot(self.shot_frozen.get(wid))
self.shot_frozen.remove(wid)
ignore(self.restore_claimed.remove(wid))
if self.ptr_win == Some(wid) {
self.ptr_win = None
@@ -471,6 +517,8 @@ pub fn ChandraCompositor::step(self : ChandraCompositor) -> Unit {
}
}
self.session_tick()
self.screenshot_tick()
self.recording_tick()
}
///|
@@ -590,11 +638,15 @@ fn ChandraCompositor::build_scene(
}
}
self.shell.win_list = entries
self.shell.screenshot_state = (if self.rec is Some(_) { 1 } else { 0 }) |
(if self.rec_pointer { 2 } else { 0 })
let t0 = @sys.monotonic_ms()
let (bg_ops, panel_ops) = self.shell.render(self.output_w, self.output_h, self.theme)
if self.switcher_on {
panel_ops.append(self.switcher_ops())
}
panel_ops.append(self.screenshot_ops())
self.frames_built = self.frames_built + 1
self.run_shell_actions()
// The wallpaper (the first ops) is cached by the renderer; the desktop card after it changes.
let n_wall = if self.shell.wallpaper_len <= bg_ops.length() { self.shell.wallpaper_len } else { 0 }
@@ -1043,6 +1095,7 @@ fn ChandraCompositor::run_shell_actions(self : ChandraCompositor) -> Unit {
@shell.ShellAction::FocusWindow(wid) => self.activate_task(wid)
@shell.ShellAction::Logout => self.quit_requested = true
@shell.ShellAction::ThemeChanged => self.apply_theme()
@shell.ShellAction::Screenshot(code) => self.screenshot_request(code)
@shell.ShellAction::SetLayout(m) =>
match m {
0 => self.set_layout_mode(@wm.LayoutMode::Tiling)
@@ -1125,6 +1178,9 @@ pub fn ChandraCompositor::handle_input(
ev : @nested.InputEvent,
time_ms : UInt,
) -> Unit {
if self.screenshot_input(ev, time_ms) {
return
}
match ev {
PointerMove(x, y) => {
self.ptr_x = x
@@ -1406,6 +1462,10 @@ pub fn ChandraCompositor::handle_input(
///| Cursor shape (wp_cursor_shape_v1 value) for the current pointer position: shell UI
/// decides over the launcher; a client window decides inside its client area; otherwise default.
pub fn ChandraCompositor::desired_cursor(self : ChandraCompositor) -> UInt {
match self.shot {
Some(o) => return self.overlay_cursor(o)
None => ()
}
let shell_shape = self.shell.cursor_at(self.ptr_x.to_int(), self.ptr_y.to_int())
if shell_shape != 0U {
return shell_shape
+1
View File
@@ -1,5 +1,6 @@
import {
"moonbitlang/core/builtin",
"moonbitlang/core/encoding/utf8" @utf8,
"chandra/desktop/lib/wm" @wm,
"chandra/desktop/compositor/sys" @sys,
"chandra/desktop/compositor/scene" @scene,
+348
View File
@@ -0,0 +1,348 @@
///| Screen recording, after Spectacle's recording modes.
///
/// Super+Shift+R 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.
///| evdev code of R.
let key_r : UInt = 19
///| xkb Alt bit.
let mod_alt : UInt = 8
///| 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
}
///| 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.grab_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
}
}
// 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
}
}
File diff suppressed because it is too large. Load diff
+228
View File
@@ -0,0 +1,228 @@
///| Screenshots (Super+Shift+S overlay, Print shortcuts, the panel module's requests) and screen
/// recording.
///| A fresh compositor whose pictures and videos go to a temporary folder.
fn shot_comp(tag : String) -> (@host.ChandraCompositor, String) {
let comp = new_comp("shot-" + tag)
let dir = "/tmp/chandra-shot-" + tag + "-" + @sys.getpid().to_string()
comp.shot_dir = dir
(comp, dir)
}
///| Press or release a key.
fn key(comp : @host.ChandraCompositor, code : UInt, down : Bool, t : UInt) -> Unit {
comp.handle_input(@nested.InputEvent::Key(code, down), t)
}
///| Press `code` with modifier keys held (evdev codes) and the matching xkb mask, then let go.
fn chord(comp : @host.ChandraCompositor, mods : Array[UInt], mask : UInt, code : UInt, t : UInt) -> Unit {
for m in mods {
key(comp, m, true, t)
}
comp.handle_input(@nested.InputEvent::Modifiers(mask, 0U, 0U, 0U), t)
key(comp, code, true, t + 1U)
key(comp, code, false, t + 2U)
for m in mods {
key(comp, m, false, t + 3U)
}
comp.handle_input(@nested.InputEvent::Modifiers(0U, 0U, 0U, 0U), t + 3U)
}
///| Width and height in a PNG's IHDR.
fn png_size(png : Bytes) -> (Int, Int) {
let be = fn(o : Int) {
(png[o].to_int() << 24) | (png[o + 1].to_int() << 16) | (png[o + 2].to_int() << 8) | png[o + 3].to_int()
}
(be(16), be(20))
}
///| Drag with the left button from (x0, y0) to (x1, y1).
fn drag(comp : @host.ChandraCompositor, x0 : Int, y0 : Int, x1 : Int, y1 : Int, t : UInt) -> Unit {
comp.handle_input(@nested.InputEvent::PointerMove(x0.to_double(), y0.to_double()), t)
comp.handle_input(@nested.InputEvent::PointerButton(272U, true), t + 1U)
comp.handle_input(@nested.InputEvent::PointerMove(((x0 + x1) / 2).to_double(), ((y0 + y1) / 2).to_double()), t + 2U)
comp.handle_input(@nested.InputEvent::PointerMove(x1.to_double(), y1.to_double()), t + 3U)
comp.handle_input(@nested.InputEvent::PointerButton(272U, false), t + 4U)
}
///|
test "super+shift+s: drag a region, Enter saves it as a PNG and puts it on the clipboard" {
let (comp, dir) = shot_comp("region")
// Super+Shift+S opens the overlay; nothing is saved yet and the launcher stays shut.
chord(comp, [125U, 42U], 64U | 1U, 31U, 1U)
assert_true(comp.screenshot_active())
assert_false(comp.shell.popup_open())
assert_eq(comp.last_screenshot(), "")
ignore(comp.compose_frame())
// Drag out 300 x 200 at (100, 80): the selection follows (either way round).
drag(comp, 400, 280, 100, 80, 10U)
assert_eq(comp.screenshot_selection(), Some(@scene.Rect::new(100, 80, 300, 200)))
ignore(comp.compose_frame())
// Drag inside it to move it by (20, 10).
drag(comp, 200, 150, 220, 160, 20U)
assert_eq(comp.screenshot_selection(), Some(@scene.Rect::new(120, 90, 300, 200)))
// The bottom-right handle resizes it.
drag(comp, 420, 290, 440, 300, 30U)
assert_eq(comp.screenshot_selection(), Some(@scene.Rect::new(120, 90, 320, 210)))
// Shift+Right grows it a pixel.
comp.handle_input(@nested.InputEvent::Modifiers(1U, 0U, 0U, 0U), 40U)
key(comp, 106U, true, 41U)
key(comp, 106U, false, 42U)
comp.handle_input(@nested.InputEvent::Modifiers(0U, 0U, 0U, 0U), 43U)
assert_eq(comp.screenshot_selection(), Some(@scene.Rect::new(120, 90, 321, 210)))
ignore(comp.compose_frame())
// Enter takes it.
key(comp, 28U, true, 50U)
key(comp, 28U, false, 51U)
assert_false(comp.screenshot_active())
let path = comp.last_screenshot()
assert_true(path.has_prefix(dir + "/Screenshot_"))
assert_true(path.has_suffix(".png"))
let png = @sys.read_file_bytes(path)
assert_eq(png[1], b'P')
assert_eq(png_size(png), (321, 210))
assert_true(comp.server.owns_selection())
assert_true(comp.screenshot_toast_shown())
ignore(comp.compose_frame())
}
///|
test "print takes the full screen at once; a second one gets its own name" {
let (comp, _) = shot_comp("full")
key(comp, 99U, true, 1U)
key(comp, 99U, false, 2U)
assert_false(comp.screenshot_active())
let first = comp.last_screenshot()
assert_eq(png_size(@sys.read_file_bytes(first)), (1280, 720))
key(comp, 99U, true, 3U)
key(comp, 99U, false, 4U)
let second = comp.last_screenshot()
assert_true(second.length() > 0 && second != first)
}
///|
test "escape cancels the overlay; a click on a window selects it; W takes the active window" {
let socket_path = "/tmp/wayland-moon-shotwin-" + @sys.getpid().to_string() + ".sock"
let comp = @host.ChandraCompositor::new(socket_path, @scene.ThemeTokens::moon_night(), 1280, 720).unwrap()
comp.shot_dir = "/tmp/chandra-shot-win-" + @sys.getpid().to_string()
ignore(open_and_configure_client(comp, socket_path, "A", "a"))
ignore(open_and_configure_client(comp, socket_path, "B", "b"))
ignore(comp.compose_frame())
chord(comp, [125U, 42U], 65U, 31U, 1U)
assert_true(comp.screenshot_active())
key(comp, 1U, true, 5U)
key(comp, 1U, false, 6U)
assert_false(comp.screenshot_active())
assert_eq(comp.last_screenshot(), "")
// A click (no drag) inside window 1 selects it with its title bar and borders.
let g = comp.windows.get(1UL).unwrap().geometry
chord(comp, [125U, 42U], 65U, 31U, 10U)
click_at(comp, g.x + 20, g.y + 20, 20U)
assert_eq(comp.screenshot_selection(), Some(@scene.Rect::new(g.x - 2, g.y - 32, g.w + 4, g.h + 34)))
// W takes the active window (B) instead.
key(comp, 17U, true, 30U)
key(comp, 17U, false, 31U)
let gb = comp.windows.get(2UL).unwrap().geometry
assert_eq(png_size(@sys.read_file_bytes(comp.last_screenshot())), (gb.w + 4, gb.h + 34))
}
///|
test "the screenshot module's request waits for a frame, then opens the overlay" {
let (comp, _) = shot_comp("request")
comp.screenshot_request(0)
comp.step()
assert_false(comp.screenshot_active()) // no frame drawn since the request yet
ignore(comp.compose_frame())
comp.step()
assert_true(comp.screenshot_active())
comp.cancel_screenshot()
comp.screenshot_request(1)
ignore(comp.compose_frame())
comp.step()
assert_eq(png_size(@sys.read_file_bytes(comp.last_screenshot())), (1280, 720))
}
///|
test "super+alt+r records the screen to a video with ffmpeg; the REC pill stops it" {
let (comp, dir) = shot_comp("rec")
chord(comp, [125U, 56U], 64U | 8U, 19U, 1U)
if !@sys.has_exe("ffmpeg") {
assert_false(comp.recording())
assert_true(comp.screenshot_toast_shown())
return
}
assert_true(comp.recording())
assert_eq(comp.recording_rect(), Some(@scene.Rect::new(0, 0, 1280, 720)))
// Run the loop for a little over a second.
let t0 = @sys.monotonic_ms()
while @sys.monotonic_ms() - t0 < 1500UL {
comp.step()
ignore(comp.compose_frame())
@sys.sleep_ms(10)
}
assert_true(comp.recorded_frames() >= 5)
// A click on the pill stops it; ffmpeg then finishes the file.
click_at(comp, 640, 15, 100U)
assert_false(comp.recording())
let path = comp.last_recording()
assert_true(path.has_prefix(dir + "/Screencast_"))
let mut size = 0
let t1 = @sys.monotonic_ms()
while @sys.monotonic_ms() - t1 < 10000UL {
size = @sys.read_file_bytes(path).length()
if size > 0 {
@sys.sleep_ms(300) // let ffmpeg finish writing
size = @sys.read_file_bytes(path).length()
break
}
@sys.sleep_ms(50)
}
assert_true(size > 1000)
}
///|
test "super+shift+r records a region picked on the overlay" {
let (comp, _) = shot_comp("recregion")
if !@sys.has_exe("ffmpeg") {
return
}
chord(comp, [125U, 42U], 65U, 19U, 1U)
assert_true(comp.screenshot_active())
drag(comp, 100, 100, 301, 251, 10U)
key(comp, 28U, true, 20U)
key(comp, 28U, false, 21U)
assert_false(comp.screenshot_active())
// Made even-sized for the encoder.
assert_eq(comp.recording_rect(), Some(@scene.Rect::new(100, 100, 200, 150)))
// The same shortcut again stops it.
chord(comp, [125U, 42U], 65U, 19U, 30U)
assert_false(comp.recording())
}
///|
test "the screenshot panel module takes a full-screen shot without its popup in it" {
let (comp, _) = shot_comp("module")
let slot = comp.shell.slot_of("screenshot")
assert_true(comp.shell.slot_rect(slot).w > 0) // it is in the default panel
click_module(comp, "screenshot", 1U)
let pr = comp.shell.slot_popup_rect(slot)
assert_true(pr.h >= 6 * 2 + 10 * 30)
// Row 2: Full Screen. The popup closes; the picture is taken after the next frame.
click_at(comp, pr.x + 40, pr.y + 6 + 2 * 30 + 5, 5U)
assert_eq(comp.shell.slot_popup_rect(slot).w, 0)
comp.step()
assert_eq(png_size(@sys.read_file_bytes(comp.last_screenshot())), (1280, 720))
// Row 1: Rectangular Region opens the overlay.
click_module(comp, "screenshot", 10U)
click_at(comp, pr.x + 40, pr.y + 6 + 1 * 30 + 5, 15U)
comp.step()
assert_true(comp.screenshot_active())
key(comp, 1U, true, 20U)
key(comp, 1U, false, 21U)
assert_false(comp.screenshot_active())
// The pointer switch (last row) flips whether recordings show the pointer.
assert_true(comp.record_pointer())
click_module(comp, "screenshot", 30U)
click_at(comp, pr.x + 40, pr.y + 6 + 9 * 30 + 5, 35U)
assert_false(comp.record_pointer())
}
+4
View File
@@ -16,6 +16,8 @@ pub fn draw_ops(Pixmap, Array[@scene.DrawOp], Int32, Int32) -> Unit
pub fn encode_png(Pixmap) -> Bytes
pub fn encode_png_compressed(Pixmap) -> Bytes
pub fn encode_ppm(Pixmap) -> Bytes
pub fn render_scene(@scene.SceneGraph) -> Pixmap
@@ -26,6 +28,8 @@ pub fn set_glyph_source((Int32, Int32, Bool, Bool) -> Glyph) -> Unit
pub fn text_width(String, Int32, Bool, Bool) -> Int32
pub fn zlib_compress(FixedArray[Byte]) -> Array[Byte]
// Errors
// Types and methods
+237
View File
@@ -0,0 +1,237 @@
///| Compressed PNG encoding (screenshots).
///
/// `encode_png` stores the pixels uncompressed, which is fine for test frames but makes a
/// 1080p screenshot an 8 MB file. `encode_png_compressed` picks a PNG filter per row (None,
/// Sub or Up, whichever leaves the smallest values) and deflates the result with LZ77 and the
/// fixed Huffman codes: desktop pictures, with their flat areas and repeated rows, shrink by
/// one or two orders of magnitude, and the encoder stays small and dependency-free.
///| Bits written least-significant first, as deflate wants them.
priv struct BitWriter {
out : Array[Byte]
mut acc : UInt
mut n : Int
}
///|
fn BitWriter::new(cap : Int) -> BitWriter {
{ out: Array(capacity=cap), acc: 0U, n: 0 }
}
///| Append the low `count` bits of `v`, least significant first.
fn BitWriter::bits(self : BitWriter, v : UInt, count : Int) -> Unit {
self.acc = self.acc | (v << self.n)
self.n = self.n + count
while self.n >= 8 {
self.out.push((self.acc & 0xFFU).to_byte())
self.acc = self.acc >> 8
self.n = self.n - 8
}
}
///| Append a Huffman code of `len` bits (codes are sent most-significant bit first).
fn BitWriter::code(self : BitWriter, code : UInt, len : Int) -> Unit {
let mut rev = 0U
for i = 0; i < len; i = i + 1 {
rev = (rev << 1) | ((code >> i) & 1U)
}
self.bits(rev, len)
}
///|
fn BitWriter::flush(self : BitWriter) -> Unit {
if self.n > 0 {
self.out.push((self.acc & 0xFFU).to_byte())
self.acc = 0U
self.n = 0
}
}
///| A literal or length symbol (0..285) with the fixed Huffman code.
fn BitWriter::lit(self : BitWriter, sym : Int) -> Unit {
if sym < 144 {
self.code((0x30 + sym).reinterpret_as_uint(), 8)
} else if sym < 256 {
self.code((0x190 + sym - 144).reinterpret_as_uint(), 9)
} else if sym < 280 {
self.code((sym - 256).reinterpret_as_uint(), 7)
} else {
self.code((0xC0 + sym - 280).reinterpret_as_uint(), 8)
}
}
// The length and distance tables (len_base, len_extra, dist_base, dist_extra) are the
// decoder's, in png.mbt.
///| Send a back-reference of `len` (3..258) bytes `dist` (1..32768) back.
fn BitWriter::match_(self : BitWriter, len : Int, dist : Int) -> Unit {
let mut li = 28
while len_base[li] > len {
li = li - 1
}
self.lit(257 + li)
if len_extra[li] > 0 {
self.bits((len - len_base[li]).reinterpret_as_uint(), len_extra[li])
}
let mut di = 29
while dist_base[di] > dist {
di = di - 1
}
self.code(di.reinterpret_as_uint(), 5)
if dist_extra[di] > 0 {
self.bits((dist - dist_base[di]).reinterpret_as_uint(), dist_extra[di])
}
}
///| A zlib stream (one fixed-Huffman deflate block) of `data`.
pub fn zlib_compress(data : FixedArray[Byte]) -> Array[Byte] {
let n = data.length()
let w = BitWriter::new(n / 8 + 64)
w.out.push(b'\x78')
w.out.push(b'\x01')
w.bits(1U, 1) // BFINAL
w.bits(1U, 2) // BTYPE = fixed Huffman
let hash_bits = 15
let hsize = 1 << hash_bits
// Most recent and previous positions with the same 3-byte hash (a short chain).
let head : FixedArray[Int] = FixedArray::make(hsize, -1)
let prev : FixedArray[Int] = FixedArray::make(32768, -1)
let window = 32768
let max_chain = 8
let hash = fn(i : Int) -> Int {
let v = (data[i].to_int() << 16) | (data[i + 1].to_int() << 8) | data[i + 2].to_int()
((v.reinterpret_as_uint() * 2654435761U) >> (32 - hash_bits)).reinterpret_as_int() &
(hsize - 1)
}
let insert = fn(i : Int) {
if i + 2 < n {
let h = hash(i)
prev[i & (window - 1)] = head[h]
head[h] = i
}
}
let mut i = 0
while i < n {
let mut best_len = 0
let mut best_dist = 0
if i + 2 < n {
let mut cand = head[hash(i)]
let mut chain = 0
let limit = if n - i < 258 { n - i } else { 258 }
while cand >= 0 && i - cand <= window && chain < max_chain {
if data[cand + best_len] == data[i + best_len] || best_len == 0 {
let mut l = 0
while l < limit && data[cand + l] == data[i + l] {
l = l + 1
}
if l > best_len {
best_len = l
best_dist = i - cand
if l == limit {
break
}
}
}
let nxt = prev[cand & (window - 1)]
if nxt >= cand {
break
}
cand = nxt
chain = chain + 1
}
}
if best_len >= 3 {
w.match_(best_len, best_dist)
// Long runs are typical (flat colours): index only their first bytes, it is plenty.
let stop = i + best_len
let index_to = if best_len > 32 { i + 32 } else { stop }
while i < index_to {
insert(i)
i = i + 1
}
i = stop
} else {
w.lit(data[i].to_int())
insert(i)
i = i + 1
}
}
w.lit(256) // end of block
w.flush()
// Adler-32 of the uncompressed data.
let mut s1 = 1U
let mut s2 = 0U
let mut k = 0
while k < n {
let end = if n - k > 5552 { k + 5552 } else { n }
while k < end {
s1 = s1 + data[k].to_uint()
s2 = s2 + s1
k = k + 1
}
s1 = s1 % 65521U
s2 = s2 % 65521U
}
push_u32_be(w.out, (s2 << 16) | s1)
w.out
}
///| Encode `p` as an RGBA PNG with per-row filtering and deflate compression.
pub fn encode_png_compressed(p : Pixmap) -> Bytes {
let out : Array[Byte] = [
b'\x89', b'\x50', b'\x4e', b'\x47', b'\x0d', b'\x0a', b'\x1a', b'\x0a',
]
let ihdr : Array[Byte] = []
push_u32_be(ihdr, p.width.reinterpret_as_uint())
push_u32_be(ihdr, p.height.reinterpret_as_uint())
ihdr.push(b'\x08') // bit depth 8
ihdr.push(b'\x06') // RGBA
ihdr.push(b'\x00')
ihdr.push(b'\x00')
ihdr.push(b'\x00')
push_png_chunk(out, "IHDR", ihdr)
let stride = p.width * 4
let row_bytes = 1 + stride
let raw : FixedArray[Byte] = FixedArray::make(row_bytes * p.height, b'\x00')
for y = 0; y < p.height; y = y + 1 {
let src = y * stride
let dst = y * row_bytes
// Score each filter by the sum of its outputs taken as signed bytes; keep the smallest.
let mut s_none = 0
let mut s_sub = 0
let mut s_up = 0
for i = 0; i < stride; i = i + 1 {
let v = p.data[src + i].to_int()
let left = if i >= 4 { p.data[src + i - 4].to_int() } else { 0 }
let up = if y > 0 { p.data[src - stride + i].to_int() } else { 0 }
s_none = s_none + signed_mag(v)
s_sub = s_sub + signed_mag((v - left) & 0xFF)
s_up = s_up + signed_mag((v - up) & 0xFF)
}
let filter = if s_up <= s_sub && s_up <= s_none && y > 0 {
2
} else if s_sub <= s_none {
1
} else {
0
}
raw[dst] = filter.to_byte()
for i = 0; i < stride; i = i + 1 {
let v = p.data[src + i].to_int()
let f = match filter {
1 => (v - (if i >= 4 { p.data[src + i - 4].to_int() } else { 0 })) & 0xFF
2 => (v - p.data[src - stride + i].to_int()) & 0xFF
_ => v
}
raw[dst + 1 + i] = f.to_byte()
}
}
push_png_chunk(out, "IDAT", zlib_compress(raw))
push_png_chunk(out, "IEND", [])
Bytes::from_array(out)
}
///| |b| for a byte read as a signed value (the usual PNG filter heuristic).
fn signed_mag(b : Int) -> Int {
if b < 128 { b } else { 256 - b }
}
+20
View File
@@ -80,3 +80,23 @@ test "a cached wallpaper renders the same pixels, and a changed one is redrawn"
sg.wallpaper_ops = [@scene.DrawOp::FillRect(@scene.Rect::new(0, 0, 32, 32), @scene.Rgba::new(10, 20, 30, 255), 0)]
assert_eq(render_scene(sg).width, 32)
}
///|
test "a compressed PNG is far smaller than the stored one for a desktop-like picture" {
let pm = @renderer.Pixmap::new(320, 200)
@renderer.draw_ops(pm, [
@scene.DrawOp::FillRect(@scene.Rect::new(0, 0, 320, 200), @scene.Rgba::new(20, 30, 60, 255), 0),
@scene.DrawOp::FillRect(@scene.Rect::new(20, 20, 200, 120), @scene.Rgba::new(240, 240, 240, 255), 8),
@scene.DrawOp::Line(0, 199, 319, 0, @scene.Rgba::new(255, 0, 0, 255), 2),
], 0, 0)
let plain = @renderer.encode_png(pm)
let packed = @renderer.encode_png_compressed(pm)
assert_eq(packed[0], b'\x89')
assert_eq(packed[1], b'\x50')
assert_true(packed.length() * 10 < plain.length())
// It decodes back to the same pixels.
let back = @renderer.decode_png(packed).unwrap()
assert_eq(back.width, 320)
assert_eq(back.height, 200)
assert_true(back.data == pm.data)
}
+7
View File
@@ -142,6 +142,9 @@ pub(all) enum ShellAction {
Logout
/// The Dark mode setting changed: the compositor swaps the theme (see `dark_mode`).
ThemeChanged
/// The screenshot module asked for a screenshot or recording (code: see the compositor's
/// screenshot_request).
Screenshot(Int)
} derive(Eq, Debug)
///| One wasm module loaded into the panel.
@@ -223,6 +226,9 @@ pub(all) struct DesktopShell {
/// Session settings (the session settings module flips them; saved in state.edn): reopen the
/// last session's windows at the next start, and remember where floating windows were left.
mut restore_session : Bool
/// What the screenshot module is told (the compositor sets it every frame): bit 0 a
/// recording is running, bit 1 recordings show the pointer.
mut screenshot_state : Int
mut remember_windows : Bool
/// Dark mode (the configured theme) or light (Moon Day); saved as `:theme :light` when off.
mut dark_mode : Bool
@@ -321,6 +327,7 @@ pub fn DesktopShell::new(display : String) -> DesktopShell {
wallpaper_len: 0,
wallpaper_sel: 0,
restore_session: true,
screenshot_state: 2,
remember_windows: true,
dark_mode: true,
desk_set: false,
+6 -1
View File
@@ -13,7 +13,8 @@
///| Modules loaded into a fresh panel, in order. `tasks` stretches, so what follows it packs right.
let default_panel : Array[String] = [
"launcher", "inspector", "layout", "tasks", "moon-disc", "clock-digital12", "session-settings", "logout",
"launcher", "inspector", "layout", "tasks", "moon-disc", "clock-digital12", "screenshot", "session-settings",
"logout",
]
///| The module whose popup holds the wasm picker (its Modules tab).
@@ -429,6 +430,9 @@ fn DesktopShell::publish_host_data(self : DesktopShell) -> Unit {
@wasm.publish(SessionSettings, st)
@wasm.publish_session_settings(self.session_settings_bits())
}
if self.widgets.iter().any(w => w.has_cap("screenshot")) {
@wasm.publish_screenshot(self.screenshot_state)
}
let it = @wasm.Table::new()
for w in self.widgets {
it.str(w.slot)
@@ -523,6 +527,7 @@ fn DesktopShell::process_requests(self : DesktopShell) -> Unit {
Some(Logout) => self.actions.push(Logout)
Some(SetWallpaper(i)) => self.set_wallpaper(i)
Some(SetSessionSetting(i, on)) => self.set_session_setting(i, on)
Some(Screenshot(code)) => self.actions.push(Screenshot(code))
Some(SetInspector(on)) => self.set_inspecting(on)
Some(LoadModule(path)) => {
match self.load_path(path) {
+6
View File
@@ -141,6 +141,12 @@ pub fn memfd_create(name : String, size : Int) -> Int {
c_memfd_create(str_to_utf8_bytes(name), size)
}
///| Write as much of `buf` as a pipe takes without blocking (the fd is made non-blocking):
/// the byte count, 0 when the pipe is full, -1 on an error (the reader went away).
pub fn write_nonblock(fd : Int, buf : Bytes) -> Int {
c_pwrite_bytes(fd, buf, buf.length(), -1)
}
///|
pub fn pwrite_bytes(fd : Int, buf : Bytes, offset : Int) -> Int {
c_pwrite_bytes(fd, buf, buf.length(), offset)
+11
View File
@@ -227,6 +227,16 @@ MOONBIT_FFI_EXPORT
int32_t mp_pwrite_bytes(int32_t fd, moonbit_bytes_t buf, int32_t len, int32_t offset) {
int32_t cap = Moonbit_array_length(buf);
int32_t n = len < cap ? len : cap;
if (offset < 0) {
/* A pipe or socket (clipboard paste, screen recording): write what fits now. 0 when it is
* full, -1 on error. A reader that went away must not kill us with SIGPIPE. */
signal(SIGPIPE, SIG_IGN);
int fl = fcntl(fd, F_GETFL);
if (fl >= 0 && !(fl & O_NONBLOCK)) fcntl(fd, F_SETFL, fl | O_NONBLOCK);
ssize_t w = write(fd, buf, (size_t)n);
if (w < 0) return (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) ? 0 : -1;
return (int32_t)w;
}
ssize_t w = pwrite(fd, buf, (size_t)n, (off_t)offset);
return w < 0 ? -1 : (int32_t)w;
}
@@ -394,6 +404,7 @@ int32_t mp_spawn(moonbit_bytes_t cmd_bytes, moonbit_bytes_t display_bytes) {
setsid();
/* SIG_IGN survives exec; apps (e.g. terminals that wait() on a helper) need the default. */
signal(SIGCHLD, SIG_DFL);
signal(SIGPIPE, SIG_DFL);
/* Flatpak apps reach the host (shell lookup, portals) through org.freedesktop.Flatpak
* on the real session bus, so they keep it; the sandbox isolates their instances anyway. */
if (private_bus[0] && strstr(cmd, "flatpak run") == NULL) setenv("DBUS_SESSION_BUS_ADDRESS", private_bus, 1);
+6
View File
@@ -93,6 +93,12 @@ pub fn memfd_create(name : String, size : Int) -> Int {
@hostsys.memfd_create(name, size)
}
///| Write as much of `buf` as a pipe takes without blocking (the fd is made non-blocking):
/// the byte count, 0 when the pipe is full, -1 on an error (the reader went away).
pub fn write_nonblock(fd : Int, buf : Bytes) -> Int {
@hostsys.pwrite(fd, to_fixed(buf), -1)
}
///|
pub fn pwrite_bytes(fd : Int, buf : Bytes, offset : Int) -> Int {
@hostsys.pwrite(fd, to_fixed(buf), offset)
+8
View File
@@ -300,6 +300,11 @@ pub fn publish_session_settings(on : Int) -> Unit {
@hostpl.publish_session_settings(on.reinterpret_as_uint())
}
///| Publish the screenshot state: bit 0 a recording is running, bit 1 recordings show the pointer.
pub fn publish_screenshot(state : Int) -> Unit {
@hostpl.publish_screenshot(state.reinterpret_as_uint())
}
///| Something a module asked the host to do during a call.
pub(all) enum HostRequest {
Launch(String)
@@ -313,6 +318,8 @@ pub(all) enum HostRequest {
SetWallpaper(Int)
/// Turn session setting `index` on or off.
SetSessionSetting(Int, Bool)
/// The screenshot capability: 0-3 take, 10-12 record, 20 stop, 30/31 pointer off/on.
Screenshot(Int)
} derive(Eq, Debug)
///|
@@ -329,6 +336,7 @@ pub fn next_request() -> HostRequest? {
Some(Logout) => Some(Logout)
Some(SetWallpaper(i)) => Some(SetWallpaper(i))
Some(SetSessionSetting(c)) => Some(SetSessionSetting(c.index, c.on))
Some(Screenshot(code)) => Some(Screenshot(code))
}
}
+8
View File
@@ -730,6 +730,11 @@ pub fn publish_session_settings(on : Int) -> Unit {
c_host_set_int(3, on)
}
///| Publish the screenshot state: bit 0 a recording is running, bit 1 recordings show the pointer.
pub fn publish_screenshot(state : Int) -> Unit {
c_host_set_int(4, state)
}
///| Something a module asked the host to do during a call.
pub(all) enum HostRequest {
Launch(String)
@@ -743,6 +748,8 @@ pub(all) enum HostRequest {
SetWallpaper(Int)
/// Turn session setting `index` on or off.
SetSessionSetting(Int, Bool)
/// The screenshot capability: 0-3 take, 10-12 record, 20 stop, 30/31 pointer off/on.
Screenshot(Int)
} derive(Eq, Debug)
///|
@@ -766,6 +773,7 @@ pub fn next_request() -> HostRequest? {
9 => Some(SetWallpaper(c_host_req_int()))
10 => Some(SetSessionSetting(c_host_req_int(), false))
11 => Some(SetSessionSetting(c_host_req_int(), true))
12 => Some(Screenshot(c_host_req_int()))
_ => None
}
}
+22 -3
View File
@@ -54,7 +54,8 @@ enum {
K_INSPECT_IS_ON, K_INSPECT_SET, K_MOD_AVAILABLE, K_MOD_LOADED, K_MOD_LOAD, K_MOD_UNLOAD, K_MOD_BROWSE,
K_SYSTEM_READ, K_WIN_ALL, K_WIN_FOCUS_ID, K_LOGOUT, K_WALLPAPERS, K_WALLPAPER_CUR, K_SET_WALLPAPER,
K_SESSION_SETTINGS, K_SESSION_IS_ON, K_SESSION_SET,
K_APP_ICON
K_APP_ICON,
K_SHOT_TAKE, K_SHOT_RECORD, K_SHOT_STOP, K_SHOT_IS_REC, K_SHOT_PTR, K_SHOT_SET_PTR
};
typedef struct Env { Inst *inst; int kind; } Env;
@@ -63,7 +64,8 @@ typedef struct Env { Inst *inst; int kind; } Env;
enum { T_APPS, T_WINDOWS, T_LAYOUTS, T_MODULES, T_INSTANCES, T_WALLPAPERS, T_SESSION_SETTINGS, T_ICONS, T_N };
typedef struct { uint8_t *data; size_t len; } Blob;
static Blob tables[T_N];
static int32_t host_ints[4]; /* 0 layout mode, 1 inspector on, 2 current wallpaper, 3 session settings on (bit i: row i) */
static int32_t host_ints[8]; /* 0 layout mode, 1 inspector on, 2 current wallpaper, 3 session settings on (bit i: row i),
4 screenshot state (bit 0 recording, bit 1 pointer in recordings) */
/* ---- requests a guest made of the host (launch, focus, ...) ; drained by the shell after each call ---- */
typedef struct { int kind; int32_t n; char *s; } Req;
@@ -312,6 +314,17 @@ static wasm_trap_t *host_import(void *env, const wasm_val_vec_t *args, wasm_val_
case K_LOGOUT: push_req(8, 0, NULL); break;
case K_SET_WALLPAPER: push_req(9, a0, NULL); break;
case K_SESSION_SET: push_req(a1 ? 11 : 10, a0, NULL); break; /* 10 off, 11 on */
/* Request 12 carries the screenshot code: 0-3 take, 10-12 record, 20 stop, 30/31 pointer. */
case K_SHOT_TAKE: if (a0 >= 0 && a0 <= 3) push_req(12, a0, NULL); break;
case K_SHOT_RECORD: if (a0 >= 0 && a0 <= 2) push_req(12, 10 + a0, NULL); break;
case K_SHOT_STOP: push_req(12, 20, NULL); break;
case K_SHOT_SET_PTR: push_req(12, a0 ? 31 : 30, NULL); break;
case K_SHOT_IS_REC:
if (results->size >= 1) results->data[0] = (wasm_val_t)WASM_I32_VAL(host_ints[4] & 1);
break;
case K_SHOT_PTR:
if (results->size >= 1) results->data[0] = (wasm_val_t)WASM_I32_VAL((host_ints[4] >> 1) & 1);
break;
case K_INSPECT_SET: push_req(4, a0, NULL); break;
case K_MOD_BROWSE: push_req(7, 0, NULL); break;
case K_MOD_LOAD: { char *s = guest_str(in, a0, a1); push_req(5, 0, s); free(s); break; }
@@ -455,6 +468,12 @@ static int classify_import(const wasm_name_t *m, const wasm_name_t *f) {
if (!strcmp(iface, "session-settings") && !strcmp(fn, "settings")) return K_SESSION_SETTINGS;
if (!strcmp(iface, "session-settings") && !strcmp(fn, "is-on")) return K_SESSION_IS_ON;
if (!strcmp(iface, "session-settings") && !strcmp(fn, "set-setting")) return K_SESSION_SET;
if (!strcmp(iface, "screenshot") && !strcmp(fn, "take")) return K_SHOT_TAKE;
if (!strcmp(iface, "screenshot") && !strcmp(fn, "start-recording")) return K_SHOT_RECORD;
if (!strcmp(iface, "screenshot") && !strcmp(fn, "stop-recording")) return K_SHOT_STOP;
if (!strcmp(iface, "screenshot") && !strcmp(fn, "is-recording")) return K_SHOT_IS_REC;
if (!strcmp(iface, "screenshot") && !strcmp(fn, "records-pointer")) return K_SHOT_PTR;
if (!strcmp(iface, "screenshot") && !strcmp(fn, "set-records-pointer")) return K_SHOT_SET_PTR;
if (!strcmp(iface, "layout-control") && !strcmp(fn, "layout-modes")) return K_LAYOUTS;
if (!strcmp(iface, "layout-control") && !strcmp(fn, "current-layout")) return K_LAYOUT_CUR;
if (!strcmp(iface, "layout-control") && !strcmp(fn, "set-layout")) return K_SET_LAYOUT;
@@ -714,7 +733,7 @@ void mp_host_set_table(int32_t which, moonbit_bytes_t data) {
MOONBIT_FFI_EXPORT
void mp_host_set_int(int32_t which, int32_t v) {
if (which >= 0 && which < 4) host_ints[which] = v;
if (which >= 0 && which < 8) host_ints[which] = v;
}
/* Pop the next guest request: returns its kind (0 = none). Fetch its arguments with req_int / req_str. */
+94 -1
View File
@@ -251,6 +251,12 @@ pub(all) struct WaylandServer {
/// Area a popup must stay inside, as (x, y, w, h) relative to its parent's content origin
/// (the parent window id is passed). The host sets this; the default never constrains.
mut popup_bounds : (UInt64) -> (Int, Int, Int, Int)
/// What the compositor itself offers on the clipboard (a screenshot) while `selection` is
/// `Some((0, 0))`: its mime types and bytes.
mut own_mimes : Array[String]
mut own_data : Bytes
/// Clipboard pastes of `own_data` still being written: (pipe fd, bytes written, give up at ms).
transfers : Array[(Int, Int, UInt64)]
}
///|
@@ -277,11 +283,18 @@ pub fn WaylandServer::listen(
selection: None,
kbd_client: None,
popup_bounds: fn(_) { (-1000000, -1000000, 2000000, 2000000) },
own_mimes: [],
own_data: Bytes::from_array([]),
transfers: [],
})
}
///|
pub fn WaylandServer::close(self : WaylandServer) -> Unit {
for t in self.transfers {
@sys.close_fd(t.0)
}
self.transfers.clear()
for c in self.clients {
c.close_all()
}
@@ -688,7 +701,16 @@ fn WaylandServer::dispatch_msg(
// receive(mime_type, fd): ask the owner to write the data into the fd
let mime = reader.str()
let fd = c.take_fd()
if fd >= 0 {
if fd >= 0 && ocid == 0U {
// The compositor's own clipboard: write it out a piece at a time (pump_transfers),
// so a client that is slow to read can't stall the desktop.
if self.selection == Some((0U, 0U)) && self.own_mimes.contains(mime) {
self.transfers.push((fd, 0, @sys.monotonic_ms() + 10000UL))
self.pump_transfers()
} else {
@sys.close_fd(fd)
}
} else if fd >= 0 {
match self.find_client(ocid) {
Some(oc) =>
if oc.data_sources.contains(osid) {
@@ -1105,6 +1127,7 @@ pub fn WaylandServer::poll_events(
self : WaylandServer,
) -> Array[CompositorEvent] {
let events : Array[CompositorEvent] = []
self.pump_transfers()
// Accept any pending connections
while true {
@@ -1683,6 +1706,7 @@ pub fn WaylandServer::popup_done(self : WaylandServer, win_id : UInt64) -> Unit
///| Offer the current clipboard to `c`'s data devices (or clear it if there is none).
fn WaylandServer::send_selection(self : WaylandServer, c : ClientConn) -> Unit {
let mimes : Array[String] = match self.selection {
Some((0U, 0U)) => self.own_mimes
Some((ocid, osid)) =>
match self.find_client(ocid) {
Some(oc) =>
@@ -1732,3 +1756,72 @@ fn WaylandServer::notify_selection(self : WaylandServer) -> Unit {
None => ()
}
}
///| Put `data` on the clipboard as the compositor's own selection, offered as `mime_types`
/// (a screenshot: image/png). Whoever owned the clipboard is told it was replaced, and the
/// focused client gets the new offer at once.
pub fn WaylandServer::set_own_selection(
self : WaylandServer,
mime_types : Array[String],
data : Bytes,
) -> Unit {
match self.selection {
Some((ocid, osid)) =>
if ocid != 0U {
match self.find_client(ocid) {
Some(oc) => oc.send_msg(WireWriter::new().finish_msg(osid, 2U)) // cancelled
None => ()
}
}
None => ()
}
self.own_mimes = mime_types
self.own_data = data
self.selection = Some((0U, 0U))
self.notify_selection()
}
///| Whether the clipboard holds the compositor's own data (no client has replaced it since).
pub fn WaylandServer::owns_selection(self : WaylandServer) -> Bool {
self.selection == Some((0U, 0U))
}
///| Write what the pipes of pending pastes can take without blocking; close the finished ones
/// and any a reader stopped taking for ten seconds.
pub fn WaylandServer::pump_transfers(self : WaylandServer) -> Unit {
if self.transfers.length() == 0 {
return
}
let total = self.own_data.length()
let now = @sys.monotonic_ms()
let keep : Array[(Int, Int, UInt64)] = []
for t in self.transfers {
let (fd, sent0, deadline) = t
let mut sent = sent0
let mut ok = true
while sent < total {
let len = if total - sent > 65536 { 65536 } else { total - sent }
let n = @sys.write_nonblock(fd, self.own_data[sent:sent + len].to_bytes())
if n < 0 {
ok = false
break
}
if n == 0 {
break // the pipe is full: the rest goes out on a later turn
}
sent = sent + n
}
if ok && sent < total && now < deadline {
keep.push((fd, sent, deadline))
} else {
@sys.close_fd(fd)
}
}
self.transfers.clear()
self.transfers.append(keep)
}
///| Pastes of the compositor's clipboard still being written.
pub fn WaylandServer::pending_transfers(self : WaylandServer) -> Int {
self.transfers.length()
}