From 85f6ff42f4b1ffd15e1452f0b7743f8aa8f8a964 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 19:04:14 +0000 Subject: [PATCH] Screenshot module after Spectacle (Super+Shift+S), with a screen recorder - 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 Claude-Session: https://claude.ai/code/session_01DPL5hjMGSLc5tHuzjsxGVa --- components/screenshot/gen/ffi.mbt | 82 ++ .../chandra/desktop/plasmoid/README.md | 1 + .../chandra/desktop/plasmoid/ffi.mbt | 409 +++++++ .../chandra/desktop/plasmoid/moon.pkg | 8 + .../chandra/desktop/plasmoid/stub.mbt | 260 +++++ .../chandra/desktop/plasmoid/top.mbt | 42 + components/screenshot/gen/moon.pkg | 26 + compositor/app/app.mbt | 2 + compositor/host/compositor.mbt | 70 +- compositor/host/moon.pkg | 1 + compositor/host/recorder.mbt | 348 ++++++ compositor/host/screenshot.mbt | 1011 +++++++++++++++++ compositor/host/screenshot_test.mbt | 228 ++++ compositor/renderer/pkg.generated.mbti | 4 + compositor/renderer/png_encode.mbt | 237 ++++ compositor/renderer/renderer_test.mbt | 20 + compositor/shell/shell.mbt | 7 + compositor/shell/widgets.mbt | 7 +- compositor/sys/sys_native.mbt | 6 + compositor/sys/sys_stub.c | 11 + compositor/sys/sys_wasm.mbt | 6 + compositor/wasm/wasm_host.mbt | 8 + compositor/wasm/wasm_native.mbt | 8 + compositor/wasm/wasm_stub.c | 25 +- compositor/wayland/server.mbt | 95 +- host-wasm/src/main.rs | 21 + host-wasm/src/plasmoid.rs | 59 + .../chandra/desktop/screenshot/README.md | 2 + interface/chandra/desktop/screenshot/ffi.mbt | 20 + interface/chandra/desktop/screenshot/moon.pkg | 1 + interface/chandra/desktop/screenshot/top.mbt | 50 + interface/chandra/host/plasmoids/ffi.mbt | 59 +- .../chandra/host/plasmoids/native_stub.mbt | 43 +- .../chandra/host/plasmoids/pkg.generated.mbti | 3 + interface/chandra/host/plasmoids/top.mbt | 12 + interface/chandra/host/sys/top.mbt | 2 + scripts/components.txt | 1 + wit/capabilities.wit | 19 + wit/host/plasmoids.wit | 5 + wit/host/sys.wit | 2 + wit/worlds.wit | 7 + world/screenshot-widget/README.md | 1 + world/screenshot-widget/ffi_import.mbt | 2 + world/screenshot-widget/import.mbt | 2 + world/screenshot-widget/moon.pkg | 1 + 45 files changed, 3177 insertions(+), 57 deletions(-) create mode 100644 components/screenshot/gen/ffi.mbt create mode 100644 components/screenshot/gen/interface/chandra/desktop/plasmoid/README.md create mode 100644 components/screenshot/gen/interface/chandra/desktop/plasmoid/ffi.mbt create mode 100644 components/screenshot/gen/interface/chandra/desktop/plasmoid/moon.pkg create mode 100644 components/screenshot/gen/interface/chandra/desktop/plasmoid/stub.mbt create mode 100644 components/screenshot/gen/interface/chandra/desktop/plasmoid/top.mbt create mode 100644 components/screenshot/gen/moon.pkg create mode 100644 compositor/host/recorder.mbt create mode 100644 compositor/host/screenshot.mbt create mode 100644 compositor/host/screenshot_test.mbt create mode 100644 compositor/renderer/png_encode.mbt create mode 100644 interface/chandra/desktop/screenshot/README.md create mode 100644 interface/chandra/desktop/screenshot/ffi.mbt create mode 100644 interface/chandra/desktop/screenshot/moon.pkg create mode 100644 interface/chandra/desktop/screenshot/top.mbt create mode 100644 world/screenshot-widget/README.md create mode 100644 world/screenshot-widget/ffi_import.mbt create mode 100644 world/screenshot-widget/import.mbt create mode 100644 world/screenshot-widget/moon.pkg diff --git a/components/screenshot/gen/ffi.mbt b/components/screenshot/gen/ffi.mbt new file mode 100644 index 0000000..539e8f0 --- /dev/null +++ b/components/screenshot/gen/ffi.mbt @@ -0,0 +1,82 @@ +// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT! + +///| +pub fn mbt_ffi_cabi_realloc( +src_offset : Int, +src_size : Int, +_dst_alignment : Int, +dst_size : Int, +) -> Int { + // malloc + if src_offset == 0 && src_size == 0 { + return mbt_ffi_malloc(dst_size) + } + // free + if dst_size == 0 { + mbt_ffi_free(src_offset) + return 0 + } + // realloc + let dst = mbt_ffi_malloc(dst_size) + mbt_ffi_copy(dst, src_offset, if src_size < dst_size { src_size } else { dst_size }) + mbt_ffi_free(src_offset) + dst +} + +///| +extern "wasm" fn mbt_ffi_copy(dest : Int, src : Int, len : Int) = +#|(func (param i32) (param i32) (param i32) local.get 0 local.get 1 local.get 2 memory.copy) + +///| +extern "wasm" fn mbt_ffi_malloc(size : Int) -> Int = +#|(func (param i32) (result i32) (local i32) +#| local.get 0 i32.const 4 i32.add call $moonbit.gc.malloc +#| local.tee 1 i32.const 0 call $moonbit.init_array8 +#| local.get 1) + +///| +extern "wasm" fn mbt_ffi_free(position : Int) = +#|(func (param i32) local.get 0 call $moonbit.decref) + +///| +#doc(hidden) +pub fn wasmExportRenderPostReturn(p0 : Int) -> Unit { + @plasmoid.wasmExportRenderPostReturn(p0) +} + +///| +#doc(hidden) +pub fn wasmExportOnEvent(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int { + @plasmoid.wasmExportOnEvent(p0, p1, p2, p3) +} + +///| +#doc(hidden) +pub fn wasmExportInfo() -> Int { + @plasmoid.wasmExportInfo() +} + +///| +#doc(hidden) +pub fn wasmExportPopup() -> Int { + @plasmoid.wasmExportPopup() +} + +///| +#doc(hidden) +pub fn wasmExportPopupPostReturn(p0 : Int) -> Unit { + @plasmoid.wasmExportPopupPostReturn(p0) +} + +///| +#doc(hidden) +pub fn wasmExportRender(p0 : Int, p1 : Int) -> Int { + @plasmoid.wasmExportRender(p0, p1) +} + +///| +#doc(hidden) +pub fn wasmExportInfoPostReturn(p0 : Int) -> Unit { + @plasmoid.wasmExportInfoPostReturn(p0) +} + diff --git a/components/screenshot/gen/interface/chandra/desktop/plasmoid/README.md b/components/screenshot/gen/interface/chandra/desktop/plasmoid/README.md new file mode 100644 index 0000000..53ecf69 --- /dev/null +++ b/components/screenshot/gen/interface/chandra/desktop/plasmoid/README.md @@ -0,0 +1 @@ +The widget (plasmoid) contract. \ No newline at end of file diff --git a/components/screenshot/gen/interface/chandra/desktop/plasmoid/ffi.mbt b/components/screenshot/gen/interface/chandra/desktop/plasmoid/ffi.mbt new file mode 100644 index 0000000..1fa7d88 --- /dev/null +++ b/components/screenshot/gen/interface/chandra/desktop/plasmoid/ffi.mbt @@ -0,0 +1,409 @@ +// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT! + +///| +#doc(hidden) +pub fn wasmExportInfo() -> Int { + + let (result) : (PlasmoidInfo) = info(); + let return_area = mbt_ffi_malloc(32) + + let ptr = mbt_ffi_str2ptr((result).id) + mbt_ffi_store32((return_area) + 4, (result).id.length()) + mbt_ffi_store32((return_area) + 0, ptr) + + let ptr0 = mbt_ffi_str2ptr((result).name) + mbt_ffi_store32((return_area) + 12, (result).name.length()) + mbt_ffi_store32((return_area) + 8, ptr0) + mbt_ffi_store32((return_area) + 16, (((result).preferred).w).reinterpret_as_int()) + mbt_ffi_store32((return_area) + 20, (((result).preferred).h).reinterpret_as_int()) + mbt_ffi_store32((return_area) + 24, ((result).min_width).reinterpret_as_int()) + mbt_ffi_store8((return_area) + 28, (if (result).stretch { 1 } else { 0 })) + let ret = return_area + return ret + +} + +///| +#doc(hidden) +pub fn wasmExportInfoPostReturn(p0 : Int) -> Unit { + mbt_ffi_free(mbt_ffi_load32((p0) + 0)) + mbt_ffi_free(mbt_ffi_load32((p0) + 8)) + +} + +///| +#doc(hidden) +pub fn wasmExportRender(p0 : Int, p1 : Int) -> Int { + + let (result) : (Array[@types.DrawOp]) = render(@types.Size::{w : (p0).reinterpret_as_uint(), h : (p1).reinterpret_as_uint()}); + let return_area = mbt_ffi_malloc(8) + + let address = mbt_ffi_malloc((result).length() * 32); + for index = 0; index < (result).length(); index = index + 1 { + let iter_elem : @types.DrawOp = (result)[(index)] + let iter_base = address + (index * 32); + + match iter_elem { + FillRect(payload) => { + mbt_ffi_store8((iter_base) + 0, (0)) + mbt_ffi_store32((iter_base) + 4, ((payload).rect).x) + mbt_ffi_store32((iter_base) + 8, ((payload).rect).y) + mbt_ffi_store32((iter_base) + 12, (((payload).rect).w).reinterpret_as_int()) + mbt_ffi_store32((iter_base) + 16, (((payload).rect).h).reinterpret_as_int()) + mbt_ffi_store8((iter_base) + 20, (((payload).color).r).to_int()) + mbt_ffi_store8((iter_base) + 21, (((payload).color).g).to_int()) + mbt_ffi_store8((iter_base) + 22, (((payload).color).b).to_int()) + mbt_ffi_store8((iter_base) + 23, (((payload).color).a).to_int()) + mbt_ffi_store32((iter_base) + 24, ((payload).radius).reinterpret_as_int()) + + () + } + StrokeRect(payload0) => { + mbt_ffi_store8((iter_base) + 0, (1)) + mbt_ffi_store32((iter_base) + 4, ((payload0).rect).x) + mbt_ffi_store32((iter_base) + 8, ((payload0).rect).y) + mbt_ffi_store32((iter_base) + 12, (((payload0).rect).w).reinterpret_as_int()) + mbt_ffi_store32((iter_base) + 16, (((payload0).rect).h).reinterpret_as_int()) + mbt_ffi_store8((iter_base) + 20, (((payload0).color).r).to_int()) + mbt_ffi_store8((iter_base) + 21, (((payload0).color).g).to_int()) + mbt_ffi_store8((iter_base) + 22, (((payload0).color).b).to_int()) + mbt_ffi_store8((iter_base) + 23, (((payload0).color).a).to_int()) + mbt_ffi_store32((iter_base) + 24, ((payload0).width).reinterpret_as_int()) + mbt_ffi_store32((iter_base) + 28, ((payload0).radius).reinterpret_as_int()) + + () + } + Line(payload1) => { + mbt_ffi_store8((iter_base) + 0, (2)) + mbt_ffi_store32((iter_base) + 4, ((payload1).start).x) + mbt_ffi_store32((iter_base) + 8, ((payload1).start).y) + mbt_ffi_store32((iter_base) + 12, ((payload1).end).x) + mbt_ffi_store32((iter_base) + 16, ((payload1).end).y) + mbt_ffi_store8((iter_base) + 20, (((payload1).color).r).to_int()) + mbt_ffi_store8((iter_base) + 21, (((payload1).color).g).to_int()) + mbt_ffi_store8((iter_base) + 22, (((payload1).color).b).to_int()) + mbt_ffi_store8((iter_base) + 23, (((payload1).color).a).to_int()) + mbt_ffi_store32((iter_base) + 24, ((payload1).width).reinterpret_as_int()) + + () + } + Circle(payload2) => { + mbt_ffi_store8((iter_base) + 0, (3)) + mbt_ffi_store32((iter_base) + 4, ((payload2).center).x) + mbt_ffi_store32((iter_base) + 8, ((payload2).center).y) + mbt_ffi_store32((iter_base) + 12, ((payload2).radius).reinterpret_as_int()) + mbt_ffi_store8((iter_base) + 16, (((payload2).color).r).to_int()) + mbt_ffi_store8((iter_base) + 17, (((payload2).color).g).to_int()) + mbt_ffi_store8((iter_base) + 18, (((payload2).color).b).to_int()) + mbt_ffi_store8((iter_base) + 19, (((payload2).color).a).to_int()) + mbt_ffi_store8((iter_base) + 20, (if (payload2).filled { 1 } else { 0 })) + + () + } + Text(payload3) => { + mbt_ffi_store8((iter_base) + 0, (4)) + mbt_ffi_store32((iter_base) + 4, ((payload3).origin).x) + mbt_ffi_store32((iter_base) + 8, ((payload3).origin).y) + + let ptr = mbt_ffi_str2ptr((payload3).text) + mbt_ffi_store32((iter_base) + 16, (payload3).text.length()) + mbt_ffi_store32((iter_base) + 12, ptr) + mbt_ffi_store32((iter_base) + 20, (((payload3).style).size).reinterpret_as_int()) + mbt_ffi_store8((iter_base) + 24, ((((payload3).style).color).r).to_int()) + mbt_ffi_store8((iter_base) + 25, ((((payload3).style).color).g).to_int()) + mbt_ffi_store8((iter_base) + 26, ((((payload3).style).color).b).to_int()) + mbt_ffi_store8((iter_base) + 27, ((((payload3).style).color).a).to_int()) + mbt_ffi_store8((iter_base) + 28, ((payload3).style).align.ordinal()) + mbt_ffi_store8((iter_base) + 29, (if ((payload3).style).bold { 1 } else { 0 })) + + () + } + PushClip(payload4) => { + mbt_ffi_store8((iter_base) + 0, (5)) + mbt_ffi_store32((iter_base) + 4, (payload4).x) + mbt_ffi_store32((iter_base) + 8, (payload4).y) + mbt_ffi_store32((iter_base) + 12, ((payload4).w).reinterpret_as_int()) + mbt_ffi_store32((iter_base) + 16, ((payload4).h).reinterpret_as_int()) + + () + } + PopClip => { + mbt_ffi_store8((iter_base) + 0, (6)) + + () + } + } + + } + mbt_ffi_store32((return_area) + 4, (result).length()) + mbt_ffi_store32((return_area) + 0, address) + let ret = return_area + return ret + +} + +///| +#doc(hidden) +pub fn wasmExportRenderPostReturn(p0 : Int) -> Unit { + + for index = 0; index < (mbt_ffi_load32((p0) + 4)); index = index + 1 { + let iter_base = (mbt_ffi_load32((p0) + 0)) + (index * 32) + + match (mbt_ffi_load8_u((iter_base) + 0)) { + 0 => () + 1 => () + 2 => () + 3 => () + 4 => { + mbt_ffi_free(mbt_ffi_load32((iter_base) + 12)) + + } + 5 => () + 6 => () + _ => panic() + } + + } + mbt_ffi_free(mbt_ffi_load32((p0) + 0)) + +} + +///| +#doc(hidden) +pub fn wasmExportPopup() -> Int { + + let (result) : (PopupSurface?) = popup(); + let return_area = mbt_ffi_malloc(20) + + match (result) { + None => { + mbt_ffi_store8((return_area) + 0, (0)) + + () + } + Some(payload0) => { + mbt_ffi_store8((return_area) + 0, (1)) + mbt_ffi_store32((return_area) + 4, (((payload0).size).w).reinterpret_as_int()) + mbt_ffi_store32((return_area) + 8, (((payload0).size).h).reinterpret_as_int()) + + let address = mbt_ffi_malloc(((payload0).ops).length() * 32); + for index = 0; index < ((payload0).ops).length(); index = index + 1 { + let iter_elem : @types.DrawOp = ((payload0).ops)[(index)] + let iter_base = address + (index * 32); + + match iter_elem { + FillRect(payload1) => { + mbt_ffi_store8((iter_base) + 0, (0)) + mbt_ffi_store32((iter_base) + 4, ((payload1).rect).x) + mbt_ffi_store32((iter_base) + 8, ((payload1).rect).y) + mbt_ffi_store32((iter_base) + 12, (((payload1).rect).w).reinterpret_as_int()) + mbt_ffi_store32((iter_base) + 16, (((payload1).rect).h).reinterpret_as_int()) + mbt_ffi_store8((iter_base) + 20, (((payload1).color).r).to_int()) + mbt_ffi_store8((iter_base) + 21, (((payload1).color).g).to_int()) + mbt_ffi_store8((iter_base) + 22, (((payload1).color).b).to_int()) + mbt_ffi_store8((iter_base) + 23, (((payload1).color).a).to_int()) + mbt_ffi_store32((iter_base) + 24, ((payload1).radius).reinterpret_as_int()) + + () + } + StrokeRect(payload2) => { + mbt_ffi_store8((iter_base) + 0, (1)) + mbt_ffi_store32((iter_base) + 4, ((payload2).rect).x) + mbt_ffi_store32((iter_base) + 8, ((payload2).rect).y) + mbt_ffi_store32((iter_base) + 12, (((payload2).rect).w).reinterpret_as_int()) + mbt_ffi_store32((iter_base) + 16, (((payload2).rect).h).reinterpret_as_int()) + mbt_ffi_store8((iter_base) + 20, (((payload2).color).r).to_int()) + mbt_ffi_store8((iter_base) + 21, (((payload2).color).g).to_int()) + mbt_ffi_store8((iter_base) + 22, (((payload2).color).b).to_int()) + mbt_ffi_store8((iter_base) + 23, (((payload2).color).a).to_int()) + mbt_ffi_store32((iter_base) + 24, ((payload2).width).reinterpret_as_int()) + mbt_ffi_store32((iter_base) + 28, ((payload2).radius).reinterpret_as_int()) + + () + } + Line(payload3) => { + mbt_ffi_store8((iter_base) + 0, (2)) + mbt_ffi_store32((iter_base) + 4, ((payload3).start).x) + mbt_ffi_store32((iter_base) + 8, ((payload3).start).y) + mbt_ffi_store32((iter_base) + 12, ((payload3).end).x) + mbt_ffi_store32((iter_base) + 16, ((payload3).end).y) + mbt_ffi_store8((iter_base) + 20, (((payload3).color).r).to_int()) + mbt_ffi_store8((iter_base) + 21, (((payload3).color).g).to_int()) + mbt_ffi_store8((iter_base) + 22, (((payload3).color).b).to_int()) + mbt_ffi_store8((iter_base) + 23, (((payload3).color).a).to_int()) + mbt_ffi_store32((iter_base) + 24, ((payload3).width).reinterpret_as_int()) + + () + } + Circle(payload4) => { + mbt_ffi_store8((iter_base) + 0, (3)) + mbt_ffi_store32((iter_base) + 4, ((payload4).center).x) + mbt_ffi_store32((iter_base) + 8, ((payload4).center).y) + mbt_ffi_store32((iter_base) + 12, ((payload4).radius).reinterpret_as_int()) + mbt_ffi_store8((iter_base) + 16, (((payload4).color).r).to_int()) + mbt_ffi_store8((iter_base) + 17, (((payload4).color).g).to_int()) + mbt_ffi_store8((iter_base) + 18, (((payload4).color).b).to_int()) + mbt_ffi_store8((iter_base) + 19, (((payload4).color).a).to_int()) + mbt_ffi_store8((iter_base) + 20, (if (payload4).filled { 1 } else { 0 })) + + () + } + Text(payload5) => { + mbt_ffi_store8((iter_base) + 0, (4)) + mbt_ffi_store32((iter_base) + 4, ((payload5).origin).x) + mbt_ffi_store32((iter_base) + 8, ((payload5).origin).y) + + let ptr = mbt_ffi_str2ptr((payload5).text) + mbt_ffi_store32((iter_base) + 16, (payload5).text.length()) + mbt_ffi_store32((iter_base) + 12, ptr) + mbt_ffi_store32((iter_base) + 20, (((payload5).style).size).reinterpret_as_int()) + mbt_ffi_store8((iter_base) + 24, ((((payload5).style).color).r).to_int()) + mbt_ffi_store8((iter_base) + 25, ((((payload5).style).color).g).to_int()) + mbt_ffi_store8((iter_base) + 26, ((((payload5).style).color).b).to_int()) + mbt_ffi_store8((iter_base) + 27, ((((payload5).style).color).a).to_int()) + mbt_ffi_store8((iter_base) + 28, ((payload5).style).align.ordinal()) + mbt_ffi_store8((iter_base) + 29, (if ((payload5).style).bold { 1 } else { 0 })) + + () + } + PushClip(payload6) => { + mbt_ffi_store8((iter_base) + 0, (5)) + mbt_ffi_store32((iter_base) + 4, (payload6).x) + mbt_ffi_store32((iter_base) + 8, (payload6).y) + mbt_ffi_store32((iter_base) + 12, ((payload6).w).reinterpret_as_int()) + mbt_ffi_store32((iter_base) + 16, ((payload6).h).reinterpret_as_int()) + + () + } + PopClip => { + mbt_ffi_store8((iter_base) + 0, (6)) + + () + } + } + + } + mbt_ffi_store32((return_area) + 16, ((payload0).ops).length()) + mbt_ffi_store32((return_area) + 12, address) + + () + } + } + let ret = return_area + return ret + +} + +///| +#doc(hidden) +pub fn wasmExportPopupPostReturn(p0 : Int) -> Unit { + + match (mbt_ffi_load8_u((p0) + 0)) { + 0 => () + 1 => { + + for index = 0; index < (mbt_ffi_load32((p0) + 16)); index = index + 1 { + let iter_base = (mbt_ffi_load32((p0) + 12)) + (index * 32) + + match (mbt_ffi_load8_u((iter_base) + 0)) { + 0 => () + 1 => () + 2 => () + 3 => () + 4 => { + mbt_ffi_free(mbt_ffi_load32((iter_base) + 12)) + + } + 5 => () + 6 => () + _ => panic() + } + + } + mbt_ffi_free(mbt_ffi_load32((p0) + 12)) + + } + _ => panic() + } + +} + +///| +#doc(hidden) +pub fn wasmExportOnEvent(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int { + + let lifted = match (p1) { + 0 => { + + @types.InputEvent::PointerMove(@types.Point::{x : p2, y : p3}) + } + 1 => { + + @types.InputEvent::PointerDown(@types.Point::{x : p2, y : p3}) + } + 2 => { + + @types.InputEvent::PointerUp(@types.Point::{x : p2, y : p3}) + } + 3 => { + + @types.InputEvent::PointerLeave + } + 4 => { + + @types.InputEvent::FocusLost + } + 5 => { + + let result = mbt_ffi_ptr2str(p2, p3) + + @types.InputEvent::KeyDown(result) + } + _ => panic() + } + + let (result0) : (Bool) = on_event(Surface::from(p0), lifted); + let ret = (if result0 { 1 } else { 0 }) + return ret + +} + +///| +extern "wasm" fn mbt_ffi_store8(offset : Int, value : Int) = +#|(func (param i32) (param i32) local.get 0 local.get 1 i32.store8) + +///| +extern "wasm" fn mbt_ffi_malloc(size : Int) -> Int = +#|(func (param i32) (result i32) (local i32) +#| local.get 0 i32.const 4 i32.add call $moonbit.gc.malloc +#| local.tee 1 i32.const 0 call $moonbit.init_array8 +#| local.get 1) + +///| +extern "wasm" fn mbt_ffi_free(position : Int) = +#|(func (param i32) local.get 0 call $moonbit.decref) + +///| +extern "wasm" fn mbt_ffi_store32(offset : Int, value : Int) = +#|(func (param i32) (param i32) local.get 0 local.get 1 i32.store) + +///| +extern "wasm" fn mbt_ffi_load32(offset : Int) -> Int = +#|(func (param i32) (result i32) local.get 0 i32.load) + +///| +extern "wasm" fn mbt_ffi_ptr2str(ptr : Int, len : Int) -> String = +#|(func (param i32) (param i32) (result i32) +#| local.get 0 +#| local.get 1 call $moonbit.init_array16 +#| local.get 0) + +///| +#owned(str) +extern "wasm" fn mbt_ffi_str2ptr(str : String) -> Int = +#|(func (param i32) (result i32) local.get 0) + +///| +extern "wasm" fn mbt_ffi_load8_u(offset : Int) -> Int = +#|(func (param i32) (result i32) local.get 0 i32.load8_u) + diff --git a/components/screenshot/gen/interface/chandra/desktop/plasmoid/moon.pkg b/components/screenshot/gen/interface/chandra/desktop/plasmoid/moon.pkg new file mode 100644 index 0000000..c6af18a --- /dev/null +++ b/components/screenshot/gen/interface/chandra/desktop/plasmoid/moon.pkg @@ -0,0 +1,8 @@ +import { + "chandra/desktop/interface/chandra/desktop/types" @types, + "chandra/desktop/interface/chandra/desktop/theme" @theme, + "chandra/desktop/interface/chandra/desktop/screenshot" @shot, + "chandra/desktop/lib/ui" @ui, +} + +warnings = "-44" diff --git a/components/screenshot/gen/interface/chandra/desktop/plasmoid/stub.mbt b/components/screenshot/gen/interface/chandra/desktop/plasmoid/stub.mbt new file mode 100644 index 0000000..2f18ff8 --- /dev/null +++ b/components/screenshot/gen/interface/chandra/desktop/plasmoid/stub.mbt @@ -0,0 +1,260 @@ +///| Implementation of `chandra:desktop/plasmoid` for the screenshot launcher, after KDE Spectacle. +/// The panel button opens a popup with Spectacle's capture modes (Rectangular Region, Full Screen, +/// Active Window, Window Under Cursor), its recording modes (region, screen, window) and a switch +/// for showing the pointer in recordings, each with its keyboard shortcut. Picking a mode closes +/// the popup and asks the compositor (`screenshot` capability), which captures once the popup is +/// gone. While a recording runs the button turns red and a click on it stops the recording. +/// Up/Down move the highlight, Enter picks, Escape or a click elsewhere closes. + +///| One popup row: a heading, an action (the request code the compositor knows), or the switch. +priv enum Row { + Heading(String) + Action(String, String, Int) + PointerSwitch +} + +///| +let rows : Array[Row] = [ + Heading("Screenshot"), + Action("Rectangular Region", "Meta+Shift+S", 0), + Action("Full Screen", "Print", 1), + Action("Active Window", "Meta+Print", 2), + Action("Window Under Cursor", "Meta+Ctrl+Print", 3), + Heading("Record"), + Action("Record a Region", "Meta+Shift+R", 10), + Action("Record the Screen", "Meta+Alt+R", 11), + Action("Record a Window", "Meta+Ctrl+R", 12), + PointerSwitch, +] + +///| Popup geometry. +let popup_w : Int = 300 + +///| +let row_h : Int = 30 + +///| +let margin : Int = 6 + +///| +let open_ : Ref[Bool] = { val: false } + +///| Highlighted row (-1: none). +let hover : Ref[Int] = { val: -1 } + +///| +fn popup_h() -> Int { + margin * 2 + rows.length() * row_h +} + +///| Whether row `i` can be picked. +fn pickable(i : Int) -> Bool { + i >= 0 && i < rows.length() && !(rows[i] is Heading(_)) +} + +///| Row under a popup-local point, or -1. +fn row_at(x : Int, y : Int) -> Int { + if x < margin || x >= popup_w - margin || y < margin { + return -1 + } + let i = (y - margin) / row_h + if pickable(i) { i } else { -1 } +} + +///| +fn close() -> Unit { + open_.val = false + hover.val = -1 +} + +///| Carry out row `i`: an action closes the popup first so it isn't in the picture. +fn pick(i : Int) -> Unit { + if !pickable(i) { + return + } + match rows[i] { + Action(_, _, code) => { + close() + if code < 10 { + @shot.take(code.reinterpret_as_uint()) + } else { + @shot.start_recording((code - 10).reinterpret_as_uint()) + } + } + PointerSwitch => @shot.set_records_pointer(!@shot.records_pointer()) + Heading(_) => () + } +} + +///| The next pickable row from `i` in direction `d`, or `i` when there is none. +fn step(i : Int, d : Int) -> Int { + let mut j = i + d + while j >= 0 && j < rows.length() { + if pickable(j) { + return j + } + j = j + d + } + i +} + +///| +pub fn info() -> PlasmoidInfo { + { + id: "org.chandra.screenshot", + name: "Screenshot", + preferred: { w: 110, h: 34 }, + min_width: 34, + stretch: false, + } +} + +///| A small camera: body, lens and the bump on top. +fn camera(cx : Int, cy : Int, c : @types.Color) -> Array[@types.DrawOp] { + [ + @ui.stroke_rect(@ui.rect(cx - 9, cy - 5, 18, 12), c, width=1, radius=2), + @ui.fill_rect(@ui.rect(cx - 4, cy - 8, 8, 3), c, radius=1), + @ui.circle(cx, cy + 1, 3, c, filled=false), + ] +} + +///| +pub fn render(size : @types.Size) -> Array[@types.DrawOp] { + let t = @theme.get_tokens() + let w = size.w.reinterpret_as_int() + let h = size.h.reinterpret_as_int() + let r = t.radius.reinterpret_as_int() + let fs = t.font_size.reinterpret_as_int() + let recording = @shot.is_recording() + let red = @ui.color(235, 64, 52, 255) + let bg = if recording { red } else if open_.val { t.palette.accent } else { t.palette.surface_hover } + let fg = if recording { + @ui.color(255, 255, 255, 255) + } else if open_.val { + t.palette.accent_foreground + } else { + t.palette.foreground + } + let ops = [@ui.fill_rect(@ui.rect(0, 0, w, h), bg, radius=r)] + let gy = h / 2 + if recording { + ops.push(@ui.fill_rect(@ui.rect(12, gy - 5, 10, 10), fg, radius=2)) // a stop square + if w >= 70 { + ops.push(@ui.text(30, gy, "Stop", fs - 2, fg)) + } + } else { + ops.append(camera(17, gy, fg)) + if w >= 90 { + ops.push(@ui.text(32, gy, "Screenshot", fs - 2, fg)) + } + } + ops +} + +///| +pub fn popup() -> PopupSurface? { + if !open_.val { + return None + } + let t = @theme.get_tokens() + let w = popup_w + let h = popup_h() + let r = t.radius.reinterpret_as_int() + let fs = t.font_size.reinterpret_as_int() + let p = t.palette + let ops : Array[@types.DrawOp] = [ + @ui.fill_rect(@ui.rect(0, 0, w, h), p.surface_popup, radius=r), + @ui.stroke_rect(@ui.rect(0, 0, w, h), p.border, width=1, radius=r), + ] + for i = 0; i < rows.length(); i = i + 1 { + let y = margin + i * row_h + let mid = y + (row_h - 2) / 2 + if i == hover.val { + ops.push(@ui.fill_rect(@ui.rect(margin, y, w - 2 * margin, row_h - 2), p.surface_hover, radius=r)) + } + match rows[i] { + Heading(s) => ops.push(@ui.text(margin + 8, mid + 2, s, fs - 3, p.foreground_muted, bold=true)) + Action(label, keys, _) => { + ops.push(@ui.text(margin + 18, mid, label, fs - 1, p.foreground)) + ops.push(@ui.text(w - margin - 10, mid, keys, fs - 3, p.foreground_muted, align=RIGHT)) + } + PointerSwitch => { + ops.push(@ui.text(margin + 18, mid, "Show pointer in recordings", fs - 1, p.foreground)) + let sw = 34 + let sh = 18 + let sx = w - margin - 10 - sw + let sy = mid - sh / 2 + let knob = sh / 2 - 3 + if @shot.records_pointer() { + ops.push(@ui.fill_rect(@ui.rect(sx, sy, sw, sh), p.accent, radius=sh / 2)) + ops.push(@ui.circle(sx + sw - sh / 2, mid, knob, p.accent_foreground)) + } else { + ops.push(@ui.stroke_rect(@ui.rect(sx, sy, sw, sh), p.foreground_muted, width=1, radius=sh / 2)) + ops.push(@ui.circle(sx + sh / 2, mid, knob, p.foreground_muted)) + } + } + } + } + Some({ size: { w: w.reinterpret_as_uint(), h: h.reinterpret_as_uint() }, ops }) +} + +///| +pub fn on_event(target : Surface, event : @types.InputEvent) -> Bool { + match (target, event) { + (WIDGET, PointerDown(_)) => { + if @shot.is_recording() { + close() + @shot.stop_recording() + } else if open_.val { + close() + } else { + open_.val = true + hover.val = step(-1, 1) + } + true + } + (POPUP, PointerMove(p)) => { + let i = row_at(p.x, p.y) + if i != hover.val && i >= 0 { + hover.val = i + true + } else { + false + } + } + (POPUP, PointerDown(p)) => { + let i = row_at(p.x, p.y) + if i >= 0 { + hover.val = i + pick(i) + } + true + } + (_, FocusLost) => + if open_.val { + close() + true + } else { + false + } + (_, KeyDown(k)) => + if !open_.val { + false + } else if k == "Escape" { + close() + true + } else if k == "Enter" || k == " " || k == "Space" { + pick(hover.val) + true + } else if k == "ArrowDown" || k == "Down" { + hover.val = step(hover.val, 1) + true + } else if k == "ArrowUp" || k == "Up" { + hover.val = step(hover.val, -1) + true + } else { + false + } + _ => false + } +} diff --git a/components/screenshot/gen/interface/chandra/desktop/plasmoid/top.mbt b/components/screenshot/gen/interface/chandra/desktop/plasmoid/top.mbt new file mode 100644 index 0000000..24d7d0e --- /dev/null +++ b/components/screenshot/gen/interface/chandra/desktop/plasmoid/top.mbt @@ -0,0 +1,42 @@ +// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT! +///| +pub(all) struct PlasmoidInfo { + id : String; name : String; preferred : @types.Size; min_width : UInt; stretch : Bool +} +///| +pub(all) struct PopupSurface { + size : @types.Size; ops : Array[@types.DrawOp] +} +///| +pub(all) enum Surface { + WIDGET; POPUP +} derive() + +///| +pub fn Surface::ordinal(self : Surface) -> Int { + match self { + WIDGET => 0 + POPUP => 1 + } +} + +///| +pub fn Surface::from(self : Int) -> Surface { + match self { + 0 => WIDGET + 1 => POPUP + _ => panic() + } +} +///| +declare pub fn info() -> PlasmoidInfo +///| +/// Draw the widget into a `size` box (local coordinates). +declare pub fn render(size : @types.Size) -> Array[@types.DrawOp] +///| +/// Present when the widget wants a popup surface (e.g. a launcher menu). +declare pub fn popup() -> PopupSurface? +///| +/// Returns true when the widget's visuals changed and a redraw is needed. +declare pub fn on_event(target : Surface, event : @types.InputEvent) -> Bool + diff --git a/components/screenshot/gen/moon.pkg b/components/screenshot/gen/moon.pkg new file mode 100644 index 0000000..7dc90d1 --- /dev/null +++ b/components/screenshot/gen/moon.pkg @@ -0,0 +1,26 @@ +import { + "chandra/desktop/components/screenshot/gen/interface/chandra/desktop/plasmoid" @plasmoid, +} + +warnings = "-44" + +pkgtype(kind: "foreign_library") + +options( + link: { + "wasm": { + "export-memory-name": "memory", + "heap-start-address": 16, + "exports": [ + "mbt_ffi_cabi_realloc:cabi_realloc", + "wasmExportInfo:chandra:desktop/plasmoid@0.1.0#info", + "wasmExportInfoPostReturn:cabi_post_chandra:desktop/plasmoid@0.1.0#info", + "wasmExportOnEvent:chandra:desktop/plasmoid@0.1.0#on-event", + "wasmExportPopup:chandra:desktop/plasmoid@0.1.0#popup", + "wasmExportPopupPostReturn:cabi_post_chandra:desktop/plasmoid@0.1.0#popup", + "wasmExportRender:chandra:desktop/plasmoid@0.1.0#render", + "wasmExportRenderPostReturn:cabi_post_chandra:desktop/plasmoid@0.1.0#render" + ], + }, + }, +) diff --git a/compositor/app/app.mbt b/compositor/app/app.mbt index f34e6a6..7094a59 100644 --- a/compositor/app/app.mbt +++ b/compositor/app/app.mbt @@ -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) diff --git a/compositor/host/compositor.mbt b/compositor/host/compositor.mbt index 7ee72c3..857812e 100644 --- a/compositor/host/compositor.mbt +++ b/compositor/host/compositor.mbt @@ -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 diff --git a/compositor/host/moon.pkg b/compositor/host/moon.pkg index 5839b73..e03a35d 100644 --- a/compositor/host/moon.pkg +++ b/compositor/host/moon.pkg @@ -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, diff --git a/compositor/host/recorder.mbt b/compositor/host/recorder.mbt new file mode 100644 index 0000000..c8b89e7 --- /dev/null +++ b/compositor/host/recorder.mbt @@ -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 + } +} diff --git a/compositor/host/screenshot.mbt b/compositor/host/screenshot.mbt new file mode 100644 index 0000000..b2b6aa5 --- /dev/null +++ b/compositor/host/screenshot.mbt @@ -0,0 +1,1011 @@ +///| Screenshots, after KDE Spectacle. +/// +/// Super+Shift+S (or Super+Shift+Print) freezes the screen and puts a selection overlay over it, +/// like Spectacle's "Rectangular Region": drag out a rectangle (its size is shown under it and a +/// magnifier follows the pointer while drawing), drag inside it to move it, drag its handles to +/// resize it, or just click a window to select that window. Enter or a double-click takes the +/// picture, Escape cancels; F takes the whole screen and W the active window instead, the arrow +/// keys nudge the selection (Shift+arrows resize it). +/// +/// The other Spectacle shortcuts take a picture at once: Print the full screen, Super+Print the +/// active window, Super+Ctrl+Print the window under the pointer. The screenshot panel module +/// offers the same four modes. +/// +/// The picture is what was on screen when the shortcut was pressed (the overlay is never in it). +/// It is saved as ~/Pictures/Screenshots/Screenshot_YYYYMMDD_HHMMSS.png (XDG_PICTURES_DIR when +/// user-dirs.dirs names one), put on the clipboard as image/png, and a notification with a +/// thumbnail confirms it for a few seconds. + +///| evdev codes. +let key_s : UInt = 31 + +///| +let key_print : UInt = 99 + +///| +let key_enter : UInt = 28 + +///| +let key_kp_enter : UInt = 96 + +///| +let key_f : UInt = 33 + +///| +let key_w : UInt = 17 + +///| +let key_c : UInt = 46 + +///| +let key_p : UInt = 25 + +///| xkb modifier bits (wl_keyboard.modifiers depressed mask). +let mod_shift : UInt = 1 + +///| +let mod_ctrl : UInt = 4 + +///| +let mod_logo : UInt = 64 + +///| What a screenshot takes. +pub(all) enum ShotMode { + /// Draw a rectangle on the overlay (or click a window). + Region + FullScreen + ActiveWindow + /// The window under the pointer; when there is none there (the request came from the panel), + /// the overlay asks for a click on one. + WindowUnderCursor +} derive(Eq, Debug) + +///| The mode with number `i` (the screenshot capability's numbering), if any. +pub fn ShotMode::from_int(i : Int) -> ShotMode? { + match i { + 0 => Some(Region) + 1 => Some(FullScreen) + 2 => Some(ActiveWindow) + 3 => Some(WindowUnderCursor) + _ => None + } +} + +///| The selection overlay while it is up. +pub(all) struct ShotOverlay { + /// The frozen screen. + frame : @renderer.Pixmap + /// Window-pick mode: a click takes the window under it, there is no rectangle. + pick : Bool + /// Picking what to record (recorder.mbt) rather than what to take a picture of. + mut record : Bool + /// Outer rectangles (decorations included) of the windows on screen, top-most first. + wins : Array[@scene.Rect] + /// The active window's rectangle, for W. + active : @scene.Rect? + mut sel : @scene.Rect? + /// 0 nothing, 1 drawing a new rectangle, 2 moving it, 3 + h resizing by handle h. + mut drag : Int + mut ax : Int + mut ay : Int + mut orig : @scene.Rect + mut moved : Bool + mut last_press : UInt + mut last_px : Int + mut last_py : Int + /// The window that had the keyboard before, given it back afterwards. + prev_focus : UInt64? +} + +///| The confirmation shown after a screenshot. +pub(all) struct ShotToast { + title : String + detail : String + until : UInt64 + thumb : Array[@scene.DrawOp] + tw : Int + th : Int +} + +///| Whether the selection overlay is up. +pub fn ChandraCompositor::screenshot_active(self : ChandraCompositor) -> Bool { + self.shot is Some(_) +} + +///| The current selection on the overlay. +pub fn ChandraCompositor::screenshot_selection(self : ChandraCompositor) -> @scene.Rect? { + match self.shot { + Some(o) => o.sel + None => None + } +} + +///| The path of the last screenshot saved ("" when none was, or saving failed). +pub fn ChandraCompositor::last_screenshot(self : ChandraCompositor) -> String { + self.last_shot +} + +///| Whether the confirmation is on screen. +pub fn ChandraCompositor::screenshot_toast_shown(self : ChandraCompositor) -> Bool { + self.shot_toast is Some(_) +} + +///| A panel module asked for a screenshot: take it once a frame without the module's popup has +/// been drawn, so the popup isn't in the picture. +pub fn ChandraCompositor::request_screenshot(self : ChandraCompositor, mode : ShotMode) -> Unit { + self.shot_request = Some((mode, self.frames_built)) +} + +///| What the screenshot capability asked for: 0-3 a screenshot in that mode (ShotMode::from_int), +/// 10-12 start (or stop) recording a region, the screen or a window, 20 stop recording, 30/31 +/// hide/show the pointer in recordings. +pub fn ChandraCompositor::screenshot_request(self : ChandraCompositor, code : Int) -> Unit { + match code { + 0 | 1 | 2 | 3 => + match ShotMode::from_int(code) { + Some(m) => self.request_screenshot(m) + None => () + } + 10 => self.rec_request = Some((ShotMode::Region, self.frames_built)) + 11 => self.rec_request = Some((ShotMode::FullScreen, self.frames_built)) + 12 => self.rec_request = Some((ShotMode::WindowUnderCursor, self.frames_built)) + 20 => self.stop_recording() + 30 => self.set_record_pointer(false) + 31 => self.set_record_pointer(true) + _ => () + } +} + +///| Take a requested screenshot when its frame has been drawn (called from `step`). +fn ChandraCompositor::screenshot_tick(self : ChandraCompositor) -> Unit { + match self.shot_request { + Some((mode, at)) => + if self.frames_built > at { + self.shot_request = None + self.take_screenshot(mode) + } + None => () + } + match self.rec_request { + Some((mode, at)) => + if self.frames_built > at { + self.rec_request = None + self.toggle_recording(mode) + } + None => () + } +} + +///| What is on screen now, as pixels: the host framebuffer (wasm compositor) or the last frame +/// the software renderer drew. A copy, so later frames don't change it. +fn ChandraCompositor::grab_screen(self : ChandraCompositor) -> @renderer.Pixmap? { + let src = match self.frame_source { + Some(f) => f() + None => + match self.last_frame { + Some(p) => Some(p) + None => Some(self.compose_frame()) + } + } + match src { + Some(p) => + if p.width <= 0 || p.height <= 0 || p.data.length() < p.width * p.height * 4 { + None + } else { + let data = FixedArray::make(p.width * p.height * 4, b'\x00') + FixedArray::blit_to(p.data, data, len=data.length()) + Some({ width: p.width, height: p.height, data }) + } + None => None + } +} + +///| A window's rectangle on screen with its title bar and borders (Spectacle's default). +fn ChandraCompositor::outer_rect(self : ChandraCompositor, wid : UInt64) -> @scene.Rect? { + match self.windows.get(wid) { + Some(win) => { + let g = win.geometry + let r = if win.fullscreen { + g + } else { + @scene.Rect::new(g.x - 2, g.y - 32, g.w + 4, g.h + 34) + } + Some(self.clip_to_screen(r)) + } + None => None + } +} + +///| +fn ChandraCompositor::clip_to_screen(self : ChandraCompositor, r : @scene.Rect) -> @scene.Rect { + let x0 = if r.x < 0 { 0 } else { r.x } + let y0 = if r.y < 0 { 0 } else { r.y } + let x1 = if r.x + r.w > self.output_w { self.output_w } else { r.x + r.w } + let y1 = if r.y + r.h > self.output_h { self.output_h } else { r.y + r.h } + @scene.Rect::new(x0, y0, x1 - x0, y1 - y0) +} + +///| The focused window, if one is on screen. +fn ChandraCompositor::active_window(self : ChandraCompositor) -> UInt64? { + for wid in self.wm.stacking_order() { + match self.windows.get(wid) { + Some(w) => if w.focused { return Some(wid) } + None => () + } + } + None +} + +///| Take a screenshot in `mode`: at once, or by opening the overlay (Region, or a window pick +/// when no window is under the pointer). +pub fn ChandraCompositor::take_screenshot(self : ChandraCompositor, mode : ShotMode) -> Unit { + if self.shot is Some(_) { + return + } + let frame = match self.grab_screen() { + Some(f) => f + None => return + } + let full = @scene.Rect::new(0, 0, frame.width, frame.height) + match mode { + FullScreen => self.finish_screenshot(frame, full) + ActiveWindow => + match self.active_window().bind(w => self.outer_rect(w)) { + Some(r) => self.finish_screenshot(frame, r) + None => self.finish_screenshot(frame, full) + } + WindowUnderCursor => + match self.window_at(self.ptr_x.to_int(), self.ptr_y.to_int()) { + Some((wid, _)) => + match self.outer_rect(wid) { + Some(r) => self.finish_screenshot(frame, r) + None => self.open_overlay(frame, true) + } + None => self.open_overlay(frame, true) + } + Region => self.open_overlay(frame, false) + } +} + +///| Put the selection overlay up over the frozen `frame`. +fn ChandraCompositor::open_overlay(self : ChandraCompositor, frame : @renderer.Pixmap, pick : Bool) -> Unit { + let wins : Array[@scene.Rect] = [] + let order = self.wm.stacking_order() + let mut i = order.length() - 1 + while i >= 0 { + match self.outer_rect(order[i]) { + Some(r) => if r.w > 0 && r.h > 0 { wins.push(r) } + None => () + } + i = i - 1 + } + // Client menus would be drawn over the overlay: close them (they are in the picture). + let mut j = self.popups.length() - 1 + while j >= 0 { + self.server.popup_done(self.popups[j].id) + j = j - 1 + } + let prev_focus = self.kbd_win + self.leave_pointer() + self.set_kbd_focus(None) + self.shot = Some({ + frame, + pick, + record: false, + wins, + active: self.active_window().bind(w => self.outer_rect(w)), + sel: None, + drag: 0, + ax: 0, + ay: 0, + orig: @scene.Rect::new(0, 0, 0, 0), + moved: false, + last_press: 0U, + last_px: -100, + last_py: -100, + prev_focus, + }) + self.damage.mark_full() +} + +///| Take the overlay down: give the keyboard back and show what clients drew meanwhile. +fn ChandraCompositor::close_overlay(self : ChandraCompositor) -> Unit { + match self.shot { + Some(o) => { + self.shot = None + for wid, snap in self.shot_frozen { + match self.windows.get(wid) { + Some(win) => { + release_snapshot(win.surface) + win.surface = Some(snap) + } + None => release_snapshot(Some(snap)) + } + } + self.shot_frozen.clear() + match o.prev_focus { + Some(w) => + if self.windows.contains(w) { + self.set_kbd_focus(Some(w)) + } else { + match self.active_window() { + Some(a) => self.set_kbd_focus(Some(a)) + None => () + } + } + None => () + } + self.damage.mark_full() + } + None => () + } +} + +///| Cancel the overlay without taking a picture. +pub fn ChandraCompositor::cancel_screenshot(self : ChandraCompositor) -> Unit { + self.close_overlay() +} + +///| The top-most window rectangle under (x, y) on the overlay. +fn ShotOverlay::window_at(self : ShotOverlay, x : Int, y : Int) -> @scene.Rect? { + for r in self.wins { + if x >= r.x && x < r.x + r.w && y >= r.y && y < r.y + r.h { + return Some(r) + } + } + None +} + +///| Crop `r` out of `frame`, save it, put it on the clipboard and confirm with a notification. +fn ChandraCompositor::finish_screenshot(self : ChandraCompositor, frame : @renderer.Pixmap, r : @scene.Rect) -> Unit { + let record = match self.shot { + Some(o) => o.record + None => false + } + self.close_overlay() + if record { + self.start_recording(r) + return + } + let x0 = if r.x < 0 { 0 } else { r.x } + let y0 = if r.y < 0 { 0 } else { r.y } + let x1 = if r.x + r.w > frame.width { frame.width } else { r.x + r.w } + let y1 = if r.y + r.h > frame.height { frame.height } else { r.y + r.h } + if x1 <= x0 || y1 <= y0 { + return + } + let w = x1 - x0 + let h = y1 - y0 + let data = FixedArray::make(w * h * 4, b'\x00') + for y = 0; y < h; y = y + 1 { + FixedArray::blit_to(frame.data, data, len=w * 4, src_offset=((y0 + y) * frame.width + x0) * 4, dst_offset=y * w * 4) + } + // Fully opaque: the framebuffer's alpha means nothing in a saved picture. + for i = 3; i < data.length(); i = i + 4 { + data[i] = b'\xff' + } + let shot : @renderer.Pixmap = { width: w, height: h, data } + let png = @renderer.encode_png_compressed(shot) + self.server.set_own_selection(["image/png"], png) + let dir = if self.shot_dir.length() > 0 { self.shot_dir } else { pictures_dir() + "/Screenshots" } + let path = save_png(dir, png) + self.last_shot = path + let (thumb, tw, th) = thumbnail_ops(shot, 96, 60) + let (title, detail) = if path.length() > 0 { + ("Screenshot saved", base_name(path) + " · copied to clipboard") + } else { + ("Screenshot copied to clipboard", "Couldn't save it to " + dir) + } + self.shot_toast = Some({ title, detail, until: @sys.monotonic_ms() + 5000UL, thumb, tw, th }) + self.damage.mark_full() +} + +///| The last part of a path. +fn base_name(path : String) -> String { + match path.rev_find("/") { + Some(i) => path[i + 1:].to_string() + None => path + } +} + +///| A folder named in user-dirs.dirs (`key`: XDG_PICTURES_DIR, XDG_VIDEOS_DIR), if it names one. +fn user_dir(key : String) -> String? { + let home = @sys.getenv("HOME") + let cfg = match @sys.getenv("XDG_CONFIG_HOME") { + "" => home + "/.config" + c => c + } + let text = @utf8.decode_lossy(@sys.read_file_bytes(cfg + "/user-dirs.dirs")) + let prefix = key + "=" + for line in text.split("\n") { + let l = line.trim(chars=" \t\r").to_string() + if l.has_prefix(prefix) { + let v = l[prefix.length():].to_string().trim(chars="\"").to_string() + let v = if v.has_prefix("$HOME") { home + v["$HOME".length():].to_string() } else { v } + if v.length() > 0 && v != home && v != home + "/" { + return Some(v) + } + } + } + None +} + +///| The user's pictures folder: XDG_PICTURES_DIR from user-dirs.dirs, else ~/Pictures. +fn pictures_dir() -> String { + match user_dir("XDG_PICTURES_DIR") { + Some(d) => d + None => @sys.getenv("HOME") + "/Pictures" + } +} + +///| Two digits. +fn pad2(n : Int) -> String { + if n < 10 { "0" + n.to_string() } else { n.to_string() } +} + +///| Local time as YYYYMMDD_HHMMSS. +fn timestamp() -> String { + @sys.wall_time_field(0).to_string() + pad2(@sys.wall_time_field(1)) + + pad2(@sys.wall_time_field(2)) + "_" + pad2(@sys.wall_time_field(3)) + + pad2(@sys.wall_time_field(4)) + pad2(@sys.wall_time_field(5)) +} + +///| Save `png` in `dir` (created if missing) as Screenshot_YYYYMMDD_HHMMSS.png, with -2, -3, ... +/// when that name is taken. The path, or "" when it couldn't be written. +fn save_png(dir : String, png : Bytes) -> String { + ignore(@sys.mkdir_p(dir)) + let base = dir + "/Screenshot_" + timestamp() + let mut path = base + ".png" + let mut n = 2 + while @sys.read_file_bytes(path).length() > 0 && n < 100 { + path = base + "-" + n.to_string() + ".png" + n = n + 1 + } + if @sys.write_file_bytes(path, png) == 0 { path } else { "" } +} + +///| A small picture of `p` as draw ops (runs of one colour per row become one rectangle), +/// fitted into `max_w` x `max_h`, and its size. +fn thumbnail_ops(p : @renderer.Pixmap, max_w : Int, max_h : Int) -> (Array[@scene.DrawOp], Int, Int) { + let ops : Array[@scene.DrawOp] = [] + if p.width <= 0 || p.height <= 0 { + return (ops, 0, 0) + } + // Fit, keeping the aspect ratio, never enlarging. + let (tw, th) = if p.width * max_h > p.height * max_w { + (max_w, (p.height * max_w / p.width).max(1)) + } else { + ((p.width * max_h / p.height).max(1), max_h) + } + let tw = tw.min(p.width) + let th = th.min(p.height) + for ty = 0; ty < th; ty = ty + 1 { + let sy = ty * p.height / th + let mut run_x = 0 + let mut run_c : @scene.Rgba? = None + for tx = 0; tx <= tw; tx = tx + 1 { + let c = if tx < tw { + let sx = tx * p.width / tw + let o = (sy * p.width + sx) * 4 + // Quantise a little so near-identical neighbours share a run. + Some( + @scene.Rgba::new( + p.data[o].to_int() & 0xFC, + p.data[o + 1].to_int() & 0xFC, + p.data[o + 2].to_int() & 0xFC, + 255, + ), + ) + } else { + None + } + if c != run_c { + match run_c { + Some(rc) => ops.push(@scene.DrawOp::FillRect(@scene.Rect::new(run_x, ty, tx - run_x, 1), rc, 0)) + None => () + } + run_x = tx + run_c = c + } + } + } + (ops, tw, th) +} + +///| Move every op of `ops` by (dx, dy). +fn offset_ops(ops : Array[@scene.DrawOp], dx : Int, dy : Int) -> Array[@scene.DrawOp] { + ops.map(op => match op { + FillRect(r, c, rad) => @scene.DrawOp::FillRect(@scene.Rect::new(r.x + dx, r.y + dy, r.w, r.h), c, rad) + other => other + }) +} + +///| Handle input for screenshots: the shortcuts, and everything while the overlay is up. +/// True when the event was used (it doesn't go on to the shell or clients). +fn ChandraCompositor::screenshot_input(self : ChandraCompositor, ev : @nested.InputEvent, time_ms : UInt) -> Bool { + match ev { + Key(code, pressed) => self.screenshot_key(code, pressed) + Modifiers(_, _, _, _) => false + PointerMove(x, y) => + match self.shot { + Some(o) => { + self.ptr_x = x + self.ptr_y = y + self.overlay_motion(o, x.to_int(), y.to_int()) + true + } + None => false + } + PointerButton(button, pressed) => + match self.shot { + Some(o) => { + self.overlay_button(o, button, pressed, time_ms) + true + } + None => + if pressed && button == 272U && self.recording_click(self.ptr_x.to_int(), self.ptr_y.to_int()) { + self.rec_press = true + true + } else if !pressed && self.rec_press { + self.rec_press = false + true + } else { + false + } + } + Scroll(_, _, _) => self.shot is Some(_) + } +} + +///| A key, for the shortcuts and the overlay. +fn ChandraCompositor::screenshot_key(self : ChandraCompositor, code : UInt, pressed : Bool) -> Bool { + if code == key_lsuper || code == key_rsuper { + self.super_down = pressed // shared with Super+D + if self.shot is Some(_) { + self.super_solo = false + return true + } + return false + } + if !pressed { + // Releases of keys we took must not reach a client either. + if self.shot_swallow.contains(code) { + self.shot_swallow.retain(c => c != code) + return true + } + return self.shot is Some(_) + } + let logo = self.super_down || (self.mods & mod_logo) != 0U + let shift = (self.mods & mod_shift) != 0U + let ctrl = (self.mods & mod_ctrl) != 0U + match self.shot { + Some(o) => { + self.shot_swallow.push(code) + self.overlay_key(o, code, shift, ctrl) + true + } + None => { + if self.shell.inspecting() || self.switcher_on { + return false + } + if code == key_r && logo && (shift || ctrl || (self.mods & mod_alt) != 0U) { + self.shot_swallow.push(code) + self.super_solo = false + self.toggle_recording( + if shift { + ShotMode::Region + } else if ctrl { + ShotMode::WindowUnderCursor + } else { + ShotMode::FullScreen + }, + ) + return true + } + let mode = if code == key_s && logo && shift { + Some(ShotMode::Region) + } else if code == key_print { + Some( + if logo && shift { + ShotMode::Region + } else if logo && ctrl { + ShotMode::WindowUnderCursor + } else if logo { + ShotMode::ActiveWindow + } else { + ShotMode::FullScreen + }, + ) + } else { + None + } + match mode { + Some(m) => { + self.shot_swallow.push(code) + self.super_solo = false + self.take_screenshot(m) + true + } + None => false + } + } + } +} + +///| A key press on the overlay. +fn ChandraCompositor::overlay_key(self : ChandraCompositor, o : ShotOverlay, code : UInt, shift : Bool, ctrl : Bool) -> Unit { + let full = @scene.Rect::new(0, 0, o.frame.width, o.frame.height) + if code == key_esc { + self.close_overlay() + } else if code == key_enter || code == key_kp_enter || (code == key_c && ctrl) { + if o.pick { + return + } + self.finish_screenshot(o.frame, o.sel.unwrap_or(full)) + } else if code == key_p && o.record { + self.set_record_pointer(!self.rec_pointer) + } else if code == key_f && !o.pick { + self.finish_screenshot(o.frame, full) + } else if code == key_w && !o.pick { + self.finish_screenshot(o.frame, o.active.unwrap_or(full)) + } else if code == key_left || code == key_right || code == key_up || code == key_down { + match o.sel { + Some(r) => { + let step = if ctrl { 10 } else { 1 } + let dx = if code == key_left { -step } else if code == key_right { step } else { 0 } + let dy = if code == key_up { -step } else if code == key_down { step } else { 0 } + let nr = if shift { + @scene.Rect::new(r.x, r.y, (r.w + dx).max(1), (r.h + dy).max(1)) + } else { + @scene.Rect::new(r.x + dx, r.y + dy, r.w, r.h) + } + o.sel = Some(self.keep_on_screen(nr)) + self.damage.mark_full() + } + None => () + } + } +} + +///| `r` moved (not shrunk) back onto the screen where it can be, then clipped. +fn ChandraCompositor::keep_on_screen(self : ChandraCompositor, r : @scene.Rect) -> @scene.Rect { + let x = if r.x + r.w > self.output_w { self.output_w - r.w } else { r.x } + let y = if r.y + r.h > self.output_h { self.output_h - r.h } else { r.y } + self.clip_to_screen(@scene.Rect::new(if x < 0 { 0 } else { x }, if y < 0 { 0 } else { y }, r.w, r.h)) +} + +///| Selection handle `h` (0 NW, 1 N, 2 NE, 3 E, 4 SE, 5 S, 6 SW, 7 W) of `r`: its centre. +fn handle_pos(r : @scene.Rect, h : Int) -> (Int, Int) { + let cx = r.x + r.w / 2 + let cy = r.y + r.h / 2 + let x1 = r.x + r.w + let y1 = r.y + r.h + match h { + 0 => (r.x, r.y) + 1 => (cx, r.y) + 2 => (x1, r.y) + 3 => (x1, cy) + 4 => (x1, y1) + 5 => (cx, y1) + 6 => (r.x, y1) + _ => (r.x, cy) + } +} + +///| The handle of `r` under (x, y), or -1. +fn handle_at(r : @scene.Rect, x : Int, y : Int) -> Int { + for h = 0; h < 8; h = h + 1 { + let (hx, hy) = handle_pos(r, h) + if (x - hx).abs() <= 8 && (y - hy).abs() <= 8 { + return h + } + } + -1 +} + +///| The rectangle with corners (x0, y0) and (x1, y1), either way round, on screen. +fn ChandraCompositor::rect_between(self : ChandraCompositor, x0 : Int, y0 : Int, x1 : Int, y1 : Int) -> @scene.Rect { + let l = x0.min(x1) + let t = y0.min(y1) + self.clip_to_screen(@scene.Rect::new(l, t, (x0 - x1).abs().max(1), (y0 - y1).abs().max(1))) +} + +///| The pointer moved on the overlay. +fn ChandraCompositor::overlay_motion(self : ChandraCompositor, o : ShotOverlay, x : Int, y : Int) -> Unit { + if o.drag != 0 && ((x - o.ax).abs() > 2 || (y - o.ay).abs() > 2) { + o.moved = true + } + if o.drag == 1 && o.moved { + o.sel = Some(self.rect_between(o.ax, o.ay, x, y)) + } else if o.drag == 2 { + let r = o.orig + o.sel = Some(self.keep_on_screen(@scene.Rect::new(r.x + x - o.ax, r.y + y - o.ay, r.w, r.h))) + } else if o.drag >= 3 { + let r = o.orig + let mut l = r.x + let mut t = r.y + let mut rr = r.x + r.w + let mut b = r.y + r.h + let dx = x - o.ax + let dy = y - o.ay + match o.drag - 3 { + 0 => { l = l + dx; t = t + dy } + 1 => t = t + dy + 2 => { rr = rr + dx; t = t + dy } + 3 => rr = rr + dx + 4 => { rr = rr + dx; b = b + dy } + 5 => b = b + dy + 6 => { l = l + dx; b = b + dy } + _ => l = l + dx + } + o.sel = Some(self.rect_between(l, t, rr, b)) + } + self.damage.mark_full() +} + +///| A button on the overlay: left draws, moves or resizes the selection (a click selects the +/// window under it, a double-click inside takes the picture); right clears the selection, or +/// cancels when there is none. +fn ChandraCompositor::overlay_button(self : ChandraCompositor, o : ShotOverlay, button : UInt, pressed : Bool, time_ms : UInt) -> Unit { + let x = self.ptr_x.to_int() + let y = self.ptr_y.to_int() + let full = @scene.Rect::new(0, 0, o.frame.width, o.frame.height) + if button == 273U { + if pressed && o.drag == 0 { + if o.sel is Some(_) && !o.pick { + o.sel = None + self.damage.mark_full() + } else { + self.close_overlay() + } + } + return + } + if button != 272U { + return + } + if pressed { + if o.pick { + return + } + let double = time_ms - o.last_press < 400U && (x - o.last_px).abs() <= 4 && (y - o.last_py).abs() <= 4 + o.last_press = time_ms + o.last_px = x + o.last_py = y + match o.sel { + Some(r) => { + let inside = x >= r.x && x < r.x + r.w && y >= r.y && y < r.y + r.h + if double && inside { + self.finish_screenshot(o.frame, r) + return + } + let h = handle_at(r, x, y) + o.drag = if h >= 0 { 3 + h } else if inside { 2 } else { 1 } + } + None => o.drag = 1 + } + o.ax = x + o.ay = y + o.orig = o.sel.unwrap_or(@scene.Rect::new(x, y, 0, 0)) + o.moved = false + } else { + if o.pick { + self.finish_screenshot(o.frame, o.window_at(x, y).unwrap_or(full)) + return + } + if o.drag == 1 && !o.moved { + // A click: select the window under it (nothing on bare desktop). + o.sel = o.window_at(x, y) + } + o.drag = 0 + self.damage.mark_full() + } +} + +///| Cursor shape over the overlay: crosshair, or move / resize over the selection. +fn ChandraCompositor::overlay_cursor(self : ChandraCompositor, o : ShotOverlay) -> UInt { + if o.pick { + return 8U // crosshair + } + let x = self.ptr_x.to_int() + let y = self.ptr_y.to_int() + let h = if o.drag >= 3 { + o.drag - 3 + } else if o.drag == 0 { + match o.sel { + Some(r) => handle_at(r, x, y) + None => -1 + } + } else { + -1 + } + match h { + 0 | 4 => 29U // nwse-resize + 2 | 6 => 28U // nesw-resize + 1 | 5 => 27U // ns-resize + 3 | 7 => 26U // ew-resize + _ => + if o.drag == 2 { + 13U // move + } else { + match o.sel { + Some(r) => + if o.drag == 0 && x >= r.x && x < r.x + r.w && y >= r.y && y < r.y + r.h { 13U } else { 8U } + None => 8U + } + } + } +} + +///| Draw ops for the overlay and the notification, on top of everything else. +fn ChandraCompositor::screenshot_ops(self : ChandraCompositor) -> Array[@scene.DrawOp] { + let ops : Array[@scene.DrawOp] = [] + self.recording_ops(ops) + match self.shot { + Some(o) => self.overlay_ops(o, ops) + None => () + } + match self.shot_toast { + Some(t) => + if @sys.monotonic_ms() >= t.until { + self.shot_toast = None + } else { + self.toast_ops(t, ops) + } + None => () + } + ops +} + +///| A rounded card with lines of text, centred on screen. +fn ChandraCompositor::help_card(self : ChandraCompositor, lines : Array[String], ops : Array[@scene.DrawOp]) -> Unit { + let p = self.theme.palette + let fs = self.theme.font_size + let line_h = fs + 12 + let mut w = 0 + for i, l in lines { + w = w.max(@renderer.text_width(l, if i == 0 { fs + 2 } else { fs }, i == 0, false)) + } + w = w + 48 + let h = lines.length() * line_h + 24 + let x = (self.output_w - w) / 2 + let y = (self.output_h - h) / 2 + let r = self.theme.radius + 4 + ops.push(@scene.DrawOp::FillRect(@scene.Rect::new(x, y, w, h), p.surface_popup, r)) + ops.push(@scene.DrawOp::StrokeRect(@scene.Rect::new(x, y, w, h), p.border, 1, r)) + for i, l in lines { + let ly = y + 12 + i * line_h + line_h / 2 + if i == 0 { + ops.push(@scene.DrawOp::Text(x + w / 2, ly, l, fs + 2, p.foreground, @scene.TextAlign::Center, true)) + } else { + ops.push(@scene.DrawOp::Text(x + w / 2, ly, l, fs, p.foreground_muted, @scene.TextAlign::Center, false)) + } + } +} + +///| +fn ChandraCompositor::overlay_ops(self : ChandraCompositor, o : ShotOverlay, ops : Array[@scene.DrawOp]) -> Unit { + let p = self.theme.palette + let sw = self.output_w + let sh = self.output_h + let dim = @scene.Rgba::new(0, 0, 0, 120) + let accent = p.accent + let x = self.ptr_x.to_int() + let y = self.ptr_y.to_int() + match o.sel { + None => { + ops.push(@scene.DrawOp::FillRect(@scene.Rect::new(0, 0, sw, sh), dim, 0)) + // The window a click would take. + match o.window_at(x, y) { + Some(r) => + if o.drag == 0 || !o.moved { + ops.push(@scene.DrawOp::FillRect(r, @scene.Rgba::new(accent.r.to_int(), accent.g.to_int(), accent.b.to_int(), 40), 0)) + ops.push(@scene.DrawOp::StrokeRect(r, accent, 2, 0)) + } + None => () + } + if o.drag == 0 { + let pointer = "P: pointer " + (if self.rec_pointer { "shown" } else { "hidden" }) + " in the video" + let lines = if o.pick && o.record { + ["Record a window", "Click a window to record it", pointer, "Esc: cancel"] + } else if o.pick { + ["Window under cursor", "Click a window to take a screenshot of it", "Esc: cancel"] + } else if o.record { + [ + "Record a region", "Drag to select a region, or click a window", "Enter or double-click: start recording", + "F: full screen W: active window", pointer, "Esc or right-click: cancel", + ] + } else { + [ + "Rectangular region", "Drag to select a region, or click a window", "Enter or double-click: take the screenshot", + "F: full screen W: active window", "Arrow keys: move Shift+arrows: resize", "Esc or right-click: cancel", + ] + } + self.help_card(lines, ops) + } + } + Some(r) => { + // Dim around the selection, outline it, then its handles and size. + ops.push(@scene.DrawOp::FillRect(@scene.Rect::new(0, 0, sw, r.y), dim, 0)) + ops.push(@scene.DrawOp::FillRect(@scene.Rect::new(0, r.y + r.h, sw, sh - r.y - r.h), dim, 0)) + ops.push(@scene.DrawOp::FillRect(@scene.Rect::new(0, r.y, r.x, r.h), dim, 0)) + ops.push(@scene.DrawOp::FillRect(@scene.Rect::new(r.x + r.w, r.y, sw - r.x - r.w, r.h), dim, 0)) + ops.push(@scene.DrawOp::StrokeRect(@scene.Rect::new(r.x - 1, r.y - 1, r.w + 2, r.h + 2), accent, 2, 0)) + if o.drag != 2 { + for h = 0; h < 8; h = h + 1 { + let (hx, hy) = handle_pos(r, h) + ops.push(@scene.DrawOp::Circle(hx, hy, 5, accent, true)) + ops.push(@scene.DrawOp::Circle(hx, hy, 5, p.accent_foreground, false)) + } + } + let fs = self.theme.font_size + let label = r.w.to_string() + " × " + r.h.to_string() + let hint = if o.record { "Enter: start recording Esc: cancel" } else { "Enter: take screenshot Esc: cancel" } + let show_hint = o.drag == 0 + let lw = @renderer.text_width(if show_hint { hint } else { label }, fs, false, false) + 24 + let lh = if show_hint { fs * 2 + 22 } else { fs + 14 } + let lx = (r.x + r.w / 2 - lw / 2).clamp(min=4, max=(sw - lw - 4).max(4)) + let ly = if r.y + r.h + 10 + lh <= sh { + r.y + r.h + 10 + } else if r.y - 10 - lh >= 0 { + r.y - 10 - lh + } else { + r.y + 10 + } + ops.push(@scene.DrawOp::FillRect(@scene.Rect::new(lx, ly, lw, lh), p.surface_popup, self.theme.radius)) + ops.push(@scene.DrawOp::Text(lx + lw / 2, ly + (fs + 14) / 2, label, fs, p.foreground, @scene.TextAlign::Center, true)) + if show_hint { + ops.push(@scene.DrawOp::Text(lx + lw / 2, ly + fs + 6 + (fs + 14) / 2, hint, fs - 2, p.foreground_muted, @scene.TextAlign::Center, false)) + } + } + } + if (o.drag == 1 && o.moved) || o.drag >= 3 { + self.magnifier_ops(o, x, y, ops) + } +} + +///| A magnified view of the frozen screen around (x, y), the pixel under the pointer framed. +fn ChandraCompositor::magnifier_ops(self : ChandraCompositor, o : ShotOverlay, x : Int, y : Int, ops : Array[@scene.DrawOp]) -> Unit { + let n = 15 + let z = 8 + let size = n * z + let mx = if x + 24 + size <= self.output_w { x + 24 } else { x - 24 - size } + let my = if y + 24 + size <= self.output_h { y + 24 } else { y - 24 - size } + let p = self.theme.palette + ops.push(@scene.DrawOp::FillRect(@scene.Rect::new(mx - 2, my - 2, size + 4, size + 4), p.border, 2)) + for j = 0; j < n; j = j + 1 { + for i = 0; i < n; i = i + 1 { + let c = match o.frame.pixel(x - n / 2 + i, y - n / 2 + j) { + Some(c) => @scene.Rgba::new(c.r.to_int(), c.g.to_int(), c.b.to_int(), 255) + None => @scene.Rgba::new(0, 0, 0, 255) + } + ops.push(@scene.DrawOp::FillRect(@scene.Rect::new(mx + i * z, my + j * z, z, z), c, 0)) + } + } + ops.push(@scene.DrawOp::StrokeRect(@scene.Rect::new(mx + n / 2 * z - 1, my + n / 2 * z - 1, z + 2, z + 2), p.accent, 2, 0)) + ops.push(@scene.DrawOp::StrokeRect(@scene.Rect::new(mx - 1, my - 1, size + 2, size + 2), p.accent, 1, 2)) +} + +///| The notification card: thumbnail, title, file name. +fn ChandraCompositor::toast_ops(self : ChandraCompositor, t : ShotToast, ops : Array[@scene.DrawOp]) -> Unit { + let p = self.theme.palette + let fs = self.theme.font_size + let pad = 12 + let text_w = @renderer.text_width(t.title, fs, true, false).max(@renderer.text_width(t.detail, fs - 2, false, false)) + let w = (pad * 3 + 96 + text_w).min(self.output_w - 32) + let h = 60 + pad * 2 + let x = self.output_w - w - 16 + let y = self.output_h - self.theme.panel_height - h - 16 + let r = self.theme.radius + 4 + ops.push(@scene.DrawOp::FillRect(@scene.Rect::new(x, y, w, h), p.surface_popup, r)) + ops.push(@scene.DrawOp::StrokeRect(@scene.Rect::new(x, y, w, h), p.border, 1, r)) + let tx = x + pad + (96 - t.tw) / 2 + let ty = y + pad + (60 - t.th) / 2 + ops.append(offset_ops(t.thumb, tx, ty)) + ops.push(@scene.DrawOp::StrokeRect(@scene.Rect::new(tx - 1, ty - 1, t.tw + 2, t.th + 2), p.border, 1, 0)) + let cx = x + pad * 2 + 96 + ops.push(@scene.DrawOp::PushClip(@scene.Rect::new(cx, y, x + w - pad - cx, h))) + ops.push(@scene.DrawOp::Text(cx, y + h / 2 - fs / 2 - 3, t.title, fs, p.foreground, @scene.TextAlign::Left, true)) + ops.push(@scene.DrawOp::Text(cx, y + h / 2 + fs / 2 + 3, t.detail, fs - 2, p.foreground_muted, @scene.TextAlign::Left, false)) + ops.push(@scene.DrawOp::PopClip) +} diff --git a/compositor/host/screenshot_test.mbt b/compositor/host/screenshot_test.mbt new file mode 100644 index 0000000..fb442d1 --- /dev/null +++ b/compositor/host/screenshot_test.mbt @@ -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()) +} diff --git a/compositor/renderer/pkg.generated.mbti b/compositor/renderer/pkg.generated.mbti index bd9eef0..2b63da9 100644 --- a/compositor/renderer/pkg.generated.mbti +++ b/compositor/renderer/pkg.generated.mbti @@ -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 diff --git a/compositor/renderer/png_encode.mbt b/compositor/renderer/png_encode.mbt new file mode 100644 index 0000000..32dcbd3 --- /dev/null +++ b/compositor/renderer/png_encode.mbt @@ -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 } +} diff --git a/compositor/renderer/renderer_test.mbt b/compositor/renderer/renderer_test.mbt index e97059a..f33f489 100644 --- a/compositor/renderer/renderer_test.mbt +++ b/compositor/renderer/renderer_test.mbt @@ -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) +} diff --git a/compositor/shell/shell.mbt b/compositor/shell/shell.mbt index b3ed4e4..dce28c4 100644 --- a/compositor/shell/shell.mbt +++ b/compositor/shell/shell.mbt @@ -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, diff --git a/compositor/shell/widgets.mbt b/compositor/shell/widgets.mbt index fb08f8e..fd70d2d 100644 --- a/compositor/shell/widgets.mbt +++ b/compositor/shell/widgets.mbt @@ -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) { diff --git a/compositor/sys/sys_native.mbt b/compositor/sys/sys_native.mbt index 19abe41..b16c980 100644 --- a/compositor/sys/sys_native.mbt +++ b/compositor/sys/sys_native.mbt @@ -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) diff --git a/compositor/sys/sys_stub.c b/compositor/sys/sys_stub.c index 6bfab67..9b6ec3f 100644 --- a/compositor/sys/sys_stub.c +++ b/compositor/sys/sys_stub.c @@ -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); diff --git a/compositor/sys/sys_wasm.mbt b/compositor/sys/sys_wasm.mbt index 744e3d5..33706bf 100644 --- a/compositor/sys/sys_wasm.mbt +++ b/compositor/sys/sys_wasm.mbt @@ -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) diff --git a/compositor/wasm/wasm_host.mbt b/compositor/wasm/wasm_host.mbt index e88ef71..7da6e97 100644 --- a/compositor/wasm/wasm_host.mbt +++ b/compositor/wasm/wasm_host.mbt @@ -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)) } } diff --git a/compositor/wasm/wasm_native.mbt b/compositor/wasm/wasm_native.mbt index ab02101..3795ca7 100644 --- a/compositor/wasm/wasm_native.mbt +++ b/compositor/wasm/wasm_native.mbt @@ -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 } } diff --git a/compositor/wasm/wasm_stub.c b/compositor/wasm/wasm_stub.c index b38eb3f..e349812 100644 --- a/compositor/wasm/wasm_stub.c +++ b/compositor/wasm/wasm_stub.c @@ -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. */ diff --git a/compositor/wayland/server.mbt b/compositor/wayland/server.mbt index aeb2490..7dc931f 100644 --- a/compositor/wayland/server.mbt +++ b/compositor/wayland/server.mbt @@ -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() +} diff --git a/host-wasm/src/main.rs b/host-wasm/src/main.rs index 4bdb86d..be0167e 100644 --- a/host-wasm/src/main.rs +++ b/host-wasm/src/main.rs @@ -199,6 +199,10 @@ impl chandra::host::plasmoids::Host for State { self.pl().shared.borrow_mut().session_settings = on; } + fn publish_screenshot(&mut self, state: u32) { + self.pl().shared.borrow_mut().screenshot = state; + } + fn publish_system(&mut self, s: chandra::host::plasmoids::SystemSnapshot) { use plasmoid::ph::chandra::desktop::system::Snapshot; self.pl().shared.borrow_mut().system = Some(Snapshot { @@ -236,6 +240,7 @@ impl chandra::host::plasmoids::Host for State { Req::SetSessionSetting(index, on) => { R::SetSessionSetting(chandra::host::plasmoids::SettingChange { index, on }) } + Req::Screenshot(code) => R::Screenshot(code), }) } @@ -565,6 +570,22 @@ impl Host for State { } fn pwrite(&mut self, fd: i32, data: Vec, offset: i32) -> i32 { + if offset < 0 { + // A pipe or socket (clipboard paste, screen recording): write what fits now. 0 when it + // is full, -1 on error. (Rust already ignores SIGPIPE, so a gone reader is just EPIPE.) + unsafe { + let fl = libc::fcntl(fd, libc::F_GETFL); + if fl >= 0 && fl & libc::O_NONBLOCK == 0 { + libc::fcntl(fd, libc::F_SETFL, fl | libc::O_NONBLOCK); + } + let w = libc::write(fd, data.as_ptr() as *const _, data.len()); + if w < 0 { + let e = std::io::Error::last_os_error().raw_os_error().unwrap_or(0); + return if e == libc::EAGAIN || e == libc::EWOULDBLOCK || e == libc::EINTR { 0 } else { -1 }; + } + return w as i32; + } + } let w = unsafe { libc::pwrite(fd, data.as_ptr() as *const _, data.len(), offset as libc::off_t) }; if w < 0 { -1 } else { w as i32 } } diff --git a/host-wasm/src/plasmoid.rs b/host-wasm/src/plasmoid.rs index d115b9b..6d34ac1 100644 --- a/host-wasm/src/plasmoid.rs +++ b/host-wasm/src/plasmoid.rs @@ -46,6 +46,8 @@ pub enum Req { Logout, SetWallpaper(i32), SetSessionSetting(i32, bool), + /// The screenshot capability: 0-3 take, 10-12 record, 20 stop, 30/31 pointer off/on. + Screenshot(i32), } pub const T_APPS: usize = 0; @@ -66,6 +68,8 @@ pub struct Shared { pub wallpaper: i32, /// Which session settings are on: bit i for row i of the session settings table. pub session_settings: u32, + /// Screenshot state: bit 0 a recording is running, bit 1 recordings show the pointer. + pub screenshot: u32, pub inspector_on: bool, pub system: Option, /// (id, title, app id, focused) @@ -303,6 +307,31 @@ impl d::wallpaper::Host for PState { } } +impl d::screenshot::Host for PState { + fn take(&mut self, mode: u32) { + if mode <= 3 { + self.shared.borrow_mut().requests.push_back(Req::Screenshot(mode as i32)); + } + } + fn start_recording(&mut self, mode: u32) { + if mode <= 2 { + self.shared.borrow_mut().requests.push_back(Req::Screenshot(10 + mode as i32)); + } + } + fn stop_recording(&mut self) { + self.shared.borrow_mut().requests.push_back(Req::Screenshot(20)); + } + fn is_recording(&mut self) -> bool { + self.shared.borrow().screenshot & 1 == 1 + } + fn records_pointer(&mut self) -> bool { + self.shared.borrow().screenshot & 2 == 2 + } + fn set_records_pointer(&mut self, on: bool) { + self.shared.borrow_mut().requests.push_back(Req::Screenshot(if on { 31 } else { 30 })); + } +} + impl d::session_settings::Host for PState { fn settings(&mut self) -> Vec { self.rows(T_SESSION_SETTINGS, "s").iter().map(|r| s(&r[0])).collect() @@ -741,4 +770,34 @@ mod tests { assert_eq!(texts(&ops), ["Firefox", "F", "foot"]); rt.unload(l.handle); } + #[test] + fn screenshot_module_offers_the_modes_and_asks_for_them() { + let mut rt = runtime(); + let l = rt.load(&module("screenshot")).expect("screenshot loads"); + assert!(l.imports.contains(&"screenshot".to_string())); + let h = l.handle; + rt.shared.borrow_mut().screenshot = 0b10; // not recording, pointer shown + assert!(texts(&rt.render(h, Size { w: 110, h: 34 })).contains(&"Screenshot".to_string())); + assert!(rt.on_event(h, false, InputEvent::PointerDown(Point { x: 5, y: 5 }))); + let p = rt.popup(h).expect("popup open"); + for n in ["Rectangular Region", "Full Screen", "Record a Region", "Show pointer in recordings"] { + assert!(texts(&p.ops).contains(&n.to_string()), "{n} listed"); + } + // Row 2 (Full Screen): the popup closes and a full-screen shot is asked for. + assert!(rt.on_event(h, true, InputEvent::PointerDown(Point { x: 20, y: 6 + 2 * 30 + 5 }))); + assert!(matches!(rt.shared.borrow_mut().requests.pop_front(), Some(Req::Screenshot(1)))); + assert!(rt.popup(h).is_none()); + // Reopen; Record the Screen (row 7). + assert!(rt.on_event(h, false, InputEvent::PointerDown(Point { x: 5, y: 5 }))); + assert!(rt.on_event(h, true, InputEvent::PointerDown(Point { x: 20, y: 6 + 7 * 30 + 5 }))); + assert!(matches!(rt.shared.borrow_mut().requests.pop_front(), Some(Req::Screenshot(11)))); + // While recording the button reads Stop, and a click stops it. + rt.shared.borrow_mut().screenshot = 0b11; + assert!(texts(&rt.render(h, Size { w: 110, h: 34 })).contains(&"Stop".to_string())); + assert!(rt.on_event(h, false, InputEvent::PointerDown(Point { x: 5, y: 5 }))); + assert!(matches!(rt.shared.borrow_mut().requests.pop_front(), Some(Req::Screenshot(20)))); + assert!(rt.popup(h).is_none()); + rt.unload(h); + } + } diff --git a/interface/chandra/desktop/screenshot/README.md b/interface/chandra/desktop/screenshot/README.md new file mode 100644 index 0000000..c3ca29c --- /dev/null +++ b/interface/chandra/desktop/screenshot/README.md @@ -0,0 +1,2 @@ +Screenshots and screen recordings, after KDE Spectacle. The compositor captures (it alone sees +the screen); a module with this capability offers the modes and starts them. \ No newline at end of file diff --git a/interface/chandra/desktop/screenshot/ffi.mbt b/interface/chandra/desktop/screenshot/ffi.mbt new file mode 100644 index 0000000..307d04b --- /dev/null +++ b/interface/chandra/desktop/screenshot/ffi.mbt @@ -0,0 +1,20 @@ +// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT! + +///| +fn wasmImportTake(p0 : Int) = "chandra:desktop/screenshot@0.1.0" "take" + +///| +fn wasmImportStartRecording(p0 : Int) = "chandra:desktop/screenshot@0.1.0" "start-recording" + +///| +fn wasmImportStopRecording() = "chandra:desktop/screenshot@0.1.0" "stop-recording" + +///| +fn wasmImportIsRecording() -> Int = "chandra:desktop/screenshot@0.1.0" "is-recording" + +///| +fn wasmImportRecordsPointer() -> Int = "chandra:desktop/screenshot@0.1.0" "records-pointer" + +///| +fn wasmImportSetRecordsPointer(p0 : Int) = "chandra:desktop/screenshot@0.1.0" "set-records-pointer" + diff --git a/interface/chandra/desktop/screenshot/moon.pkg b/interface/chandra/desktop/screenshot/moon.pkg new file mode 100644 index 0000000..e2a6033 --- /dev/null +++ b/interface/chandra/desktop/screenshot/moon.pkg @@ -0,0 +1 @@ +warnings = "-44" diff --git a/interface/chandra/desktop/screenshot/top.mbt b/interface/chandra/desktop/screenshot/top.mbt new file mode 100644 index 0000000..0e551b8 --- /dev/null +++ b/interface/chandra/desktop/screenshot/top.mbt @@ -0,0 +1,50 @@ +// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT! +///| +/// Take a screenshot: 0 rectangular region (drawn on the selection overlay), 1 full screen, +/// 2 active window, 3 window under cursor (clicked on the overlay). It is saved to +/// ~/Pictures/Screenshots and put on the clipboard. Other values are ignored. +pub fn take(mode : UInt) -> Unit { + + wasmImportTake((mode).reinterpret_as_int()); + +} +///| +/// Record the screen to ~/Videos/Screencasts: 0 a region (picked on the overlay), 1 the full +/// screen, 2 a window (clicked on the overlay). While a recording runs this stops it instead. +pub fn start_recording(mode : UInt) -> Unit { + + wasmImportStartRecording((mode).reinterpret_as_int()); + +} +///| +/// Stop the recording, if one is running. +pub fn stop_recording() -> Unit { + + wasmImportStopRecording(); + +} +///| +/// Whether a recording is running. +pub fn is_recording() -> Bool { + + let result : Int = wasmImportIsRecording(); + let ret = (result != 0) + return ret + +} +///| +/// Whether recordings show the pointer, and switching that. +pub fn records_pointer() -> Bool { + + let result : Int = wasmImportRecordsPointer(); + let ret = (result != 0) + return ret + +} +///| +pub fn set_records_pointer(on : Bool) -> Unit { + + wasmImportSetRecordsPointer((if on { 1 } else { 0 })); + +} + diff --git a/interface/chandra/host/plasmoids/ffi.mbt b/interface/chandra/host/plasmoids/ffi.mbt index 4acecb4..adbbe72 100644 --- a/interface/chandra/host/plasmoids/ffi.mbt +++ b/interface/chandra/host/plasmoids/ffi.mbt @@ -36,6 +36,9 @@ fn wasmImportPublishWallpaper(p0 : Int) = "chandra:host/plasmoids@0.1.0" "publi ///| fn wasmImportPublishSessionSettings(p0 : Int) = "chandra:host/plasmoids@0.1.0" "publish-session-settings" +///| +fn wasmImportPublishScreenshot(p0 : Int) = "chandra:host/plasmoids@0.1.0" "publish-screenshot" + ///| fn wasmImportPublishSystem(p0 : Int, p1 : Int64, p2 : Int64, p3 : Int, p4 : Int, p5 : Int64, p6 : Int64, p7 : Int64, p8 : Int) = "chandra:host/plasmoids@0.1.0" "publish-system" @@ -58,25 +61,11 @@ fn wasmImportPickerStart() -> Int = "chandra:host/plasmoids@0.1.0" "picker-start fn wasmImportPickerPoll(p0 : Int) = "chandra:host/plasmoids@0.1.0" "picker-poll" ///| -extern "wasm" fn mbt_ffi_ptr2str(ptr : Int, len : Int) -> String = -#|(func (param i32) (param i32) (result i32) -#| local.get 0 -#| local.get 1 call $moonbit.init_array16 -#| local.get 0) - -///| -#owned(str) -extern "wasm" fn mbt_ffi_str2ptr(str : String) -> Int = -#|(func (param i32) (result i32) local.get 0) - -///| -extern "wasm" fn mbt_ffi_store8(offset : Int, value : Int) = -#|(func (param i32) (param i32) local.get 0 local.get 1 i32.store8) - -///| -#owned(bytes) -extern "wasm" fn mbt_ffi_bytes2ptr(bytes : FixedArray[Byte]) -> Int = -#|(func (param i32) (result i32) local.get 0) +extern "wasm" fn mbt_ffi_malloc(size : Int) -> Int = +#|(func (param i32) (result i32) (local i32) +#| local.get 0 i32.const 4 i32.add call $moonbit.gc.malloc +#| local.tee 1 i32.const 0 call $moonbit.init_array8 +#| local.get 1) ///| extern "wasm" fn mbt_ffi_store64(offset : Int, value : Int64) = @@ -87,23 +76,37 @@ extern "wasm" fn mbt_ffi_load64(offset : Int) -> Int64 = #|(func (param i32) (result i64) local.get 0 i64.load) ///| -extern "wasm" fn mbt_ffi_malloc(size : Int) -> Int = -#|(func (param i32) (result i32) (local i32) -#| local.get 0 i32.const 4 i32.add call $moonbit.gc.malloc -#| local.tee 1 i32.const 0 call $moonbit.init_array8 -#| local.get 1) +extern "wasm" fn mbt_ffi_free(position : Int) = +#|(func (param i32) local.get 0 call $moonbit.decref) ///| -extern "wasm" fn mbt_ffi_load8_u(offset : Int) -> Int = -#|(func (param i32) (result i32) local.get 0 i32.load8_u) +#owned(str) +extern "wasm" fn mbt_ffi_str2ptr(str : String) -> Int = +#|(func (param i32) (result i32) local.get 0) ///| extern "wasm" fn mbt_ffi_store32(offset : Int, value : Int) = #|(func (param i32) (param i32) local.get 0 local.get 1 i32.store) ///| -extern "wasm" fn mbt_ffi_free(position : Int) = -#|(func (param i32) local.get 0 call $moonbit.decref) +#owned(bytes) +extern "wasm" fn mbt_ffi_bytes2ptr(bytes : FixedArray[Byte]) -> Int = +#|(func (param i32) (result i32) local.get 0) + +///| +extern "wasm" fn mbt_ffi_ptr2str(ptr : Int, len : Int) -> String = +#|(func (param i32) (param i32) (result i32) +#| local.get 0 +#| local.get 1 call $moonbit.init_array16 +#| local.get 0) + +///| +extern "wasm" fn mbt_ffi_load8_u(offset : Int) -> Int = +#|(func (param i32) (result i32) local.get 0 i32.load8_u) + +///| +extern "wasm" fn mbt_ffi_store8(offset : Int, value : Int) = +#|(func (param i32) (param i32) local.get 0 local.get 1 i32.store8) ///| extern "wasm" fn mbt_ffi_load32(offset : Int) -> Int = diff --git a/interface/chandra/host/plasmoids/native_stub.mbt b/interface/chandra/host/plasmoids/native_stub.mbt index 494c7ef..068efc2 100644 --- a/interface/chandra/host/plasmoids/native_stub.mbt +++ b/interface/chandra/host/plasmoids/native_stub.mbt @@ -60,6 +60,11 @@ fn wasmImportPublishSessionSettings(p0 : Int) -> Unit { abort("wasm-only host import") } +///| +fn wasmImportPublishScreenshot(p0 : Int) -> Unit { + abort("wasm-only host import") +} + ///| fn wasmImportPublishSystem(p0 : Int, p1 : Int64, p2 : Int64, p3 : Int, p4 : Int, p5 : Int64, p6 : Int64, p7 : Int64, p8 : Int) -> Unit { abort("wasm-only host import") @@ -96,22 +101,7 @@ fn wasmImportPickerPoll(p0 : Int) -> Unit { } ///| -fn mbt_ffi_ptr2str(ptr : Int, len : Int) -> String { - abort("wasm-only") -} - -///| -fn mbt_ffi_str2ptr(str : String) -> Int { - abort("wasm-only") -} - -///| -fn mbt_ffi_store8(offset : Int, value : Int) -> Unit { - abort("wasm-only") -} - -///| -fn mbt_ffi_bytes2ptr(bytes : FixedArray[Byte]) -> Int { +fn mbt_ffi_malloc(size : Int) -> Int { abort("wasm-only") } @@ -126,12 +116,12 @@ fn mbt_ffi_load64(offset : Int) -> Int64 { } ///| -fn mbt_ffi_malloc(size : Int) -> Int { +fn mbt_ffi_free(position : Int) -> Unit { abort("wasm-only") } ///| -fn mbt_ffi_load8_u(offset : Int) -> Int { +fn mbt_ffi_str2ptr(str : String) -> Int { abort("wasm-only") } @@ -141,7 +131,22 @@ fn mbt_ffi_store32(offset : Int, value : Int) -> Unit { } ///| -fn mbt_ffi_free(position : Int) -> Unit { +fn mbt_ffi_bytes2ptr(bytes : FixedArray[Byte]) -> Int { + abort("wasm-only") +} + +///| +fn mbt_ffi_ptr2str(ptr : Int, len : Int) -> String { + abort("wasm-only") +} + +///| +fn mbt_ffi_load8_u(offset : Int) -> Int { + abort("wasm-only") +} + +///| +fn mbt_ffi_store8(offset : Int, value : Int) -> Unit { abort("wasm-only") } diff --git a/interface/chandra/host/plasmoids/pkg.generated.mbti b/interface/chandra/host/plasmoids/pkg.generated.mbti index 211e2db..efd6b74 100644 --- a/interface/chandra/host/plasmoids/pkg.generated.mbti +++ b/interface/chandra/host/plasmoids/pkg.generated.mbti @@ -23,6 +23,8 @@ pub fn picker_start() -> Bool pub fn popup(UInt32) -> PopupSurface? +pub fn publish_screenshot(UInt32) -> Unit + pub fn publish_session_settings(UInt32) -> Unit pub fn publish_state(Int32, Bool) -> Unit @@ -87,6 +89,7 @@ pub(all) enum Request { Logout SetWallpaper(Int32) SetSessionSetting(SettingChange) + Screenshot(Int32) } pub(all) struct SettingChange { diff --git a/interface/chandra/host/plasmoids/top.mbt b/interface/chandra/host/plasmoids/top.mbt index 3b55353..26910e7 100644 --- a/interface/chandra/host/plasmoids/top.mbt +++ b/interface/chandra/host/plasmoids/top.mbt @@ -41,6 +41,7 @@ pub(all) enum Request { Logout SetWallpaper(Int) SetSessionSetting(SettingChange) + Screenshot(Int) } ///| /// A native file-chooser dialog (zenity on the host session) for "Add widget". @@ -400,6 +401,13 @@ pub fn publish_session_settings(on : UInt) -> Unit { wasmImportPublishSessionSettings((on).reinterpret_as_int()); +} +///| +/// Screenshot state: bit 0 a recording is running, bit 1 recordings show the pointer. +pub fn publish_screenshot(state : UInt) -> Unit { + + wasmImportPublishScreenshot((state).reinterpret_as_int()); + } ///| pub fn publish_system(s : SystemSnapshot) -> Unit { @@ -493,6 +501,10 @@ pub fn next_request() -> Request? { Request::SetSessionSetting(SettingChange::{index : mbt_ffi_load32((return_area) + 8), on : (mbt_ffi_load8_u((return_area) + 12) != 0)}) } + 10 => { + + Request::Screenshot(mbt_ffi_load32((return_area) + 8)) + } _ => panic() } diff --git a/interface/chandra/host/sys/top.mbt b/interface/chandra/host/sys/top.mbt index dbb4ac5..5341542 100644 --- a/interface/chandra/host/sys/top.mbt +++ b/interface/chandra/host/sys/top.mbt @@ -93,6 +93,8 @@ pub fn memfd_create(name : String, size : Int) -> Int { } ///| +/// Write at `offset` (shm pools). A negative offset writes at the current position without +/// blocking (a clipboard pipe): the byte count, 0 when the pipe is full, -1 on error. pub fn pwrite(fd : Int, data : FixedArray[Byte], offset : Int) -> Int { let ptr = mbt_ffi_bytes2ptr(data) diff --git a/scripts/components.txt b/scripts/components.txt index 4d694a1..7f68631 100644 --- a/scripts/components.txt +++ b/scripts/components.txt @@ -9,3 +9,4 @@ layout layout-widget inspector inspector-widget logout logout-widget session-settings session-settings-widget +screenshot screenshot-widget diff --git a/wit/capabilities.wit b/wit/capabilities.wit index 27e07be..35fc6cb 100644 --- a/wit/capabilities.wit +++ b/wit/capabilities.wit @@ -148,3 +148,22 @@ interface session-settings { /// Turn setting `index` on or off (out-of-range indices are ignored). The choice is remembered. set-setting: func(index: u32, on: bool); } + +/// Screenshots and screen recordings, after KDE Spectacle. The compositor captures (it alone sees +/// the screen); a module with this capability offers the modes and starts them. +interface screenshot { + /// Take a screenshot: 0 rectangular region (drawn on the selection overlay), 1 full screen, + /// 2 active window, 3 window under cursor (clicked on the overlay). It is saved to + /// ~/Pictures/Screenshots and put on the clipboard. Other values are ignored. + take: func(mode: u32); + /// Record the screen to ~/Videos/Screencasts: 0 a region (picked on the overlay), 1 the full + /// screen, 2 a window (clicked on the overlay). While a recording runs this stops it instead. + start-recording: func(mode: u32); + /// Stop the recording, if one is running. + stop-recording: func(); + /// Whether a recording is running. + is-recording: func() -> bool; + /// Whether recordings show the pointer, and switching that. + records-pointer: func() -> bool; + set-records-pointer: func(on: bool); +} diff --git a/wit/host/plasmoids.wit b/wit/host/plasmoids.wit index 33697b9..1362de4 100644 --- a/wit/host/plasmoids.wit +++ b/wit/host/plasmoids.wit @@ -62,6 +62,8 @@ interface plasmoids { publish-wallpaper: func(current: s32); /// Which session settings are on: bit i for row i of the session settings table. publish-session-settings: func(on: u32); + /// Screenshot state: bit 0 a recording is running, bit 1 recordings show the pointer. + publish-screenshot: func(state: u32); record system-snapshot { cpu-permille: u32, @@ -103,6 +105,9 @@ interface plasmoids { logout, set-wallpaper(s32), set-session-setting(setting-change), + /// The screenshot capability: 0-3 take(mode), 10-12 start-recording(mode), 20 stop recording, + /// 30/31 hide/show the pointer in recordings. + screenshot(s32), } /// The next pending request, oldest first. next-request: func() -> option; diff --git a/wit/host/sys.wit b/wit/host/sys.wit index 4879702..3f24415 100644 --- a/wit/host/sys.wit +++ b/wit/host/sys.wit @@ -26,6 +26,8 @@ interface sys { sendmsg: func(fd: s32, data: list, send-fd: s32) -> s32; memfd-create: func(name: string, size: s32) -> s32; + /// Write at `offset` (shm pools). A negative offset writes at the current position without + /// blocking (a clipboard pipe): the byte count, 0 when the pipe is full, -1 on error. pwrite: func(fd: s32, data: list, offset: s32) -> s32; /// Copy `size` bytes of the file behind `fd` (mapped read-only by the host). mmap-read: func(fd: s32, size: s32) -> list; diff --git a/wit/worlds.wit b/wit/worlds.wit index 7b6878b..78f93e6 100644 --- a/wit/worlds.wit +++ b/wit/worlds.wit @@ -79,6 +79,7 @@ world plasmoid-host { import wallpaper; import session-settings; import icons; + import screenshot; export plasmoid; } @@ -96,3 +97,9 @@ world session-settings-widget { import wallpaper; import modules; } + +/// Screenshot and screen recording launcher. +world screenshot-widget { + include widget; + import screenshot; +} diff --git a/world/screenshot-widget/README.md b/world/screenshot-widget/README.md new file mode 100644 index 0000000..341f285 --- /dev/null +++ b/world/screenshot-widget/README.md @@ -0,0 +1 @@ +Screenshot and screen recording launcher. \ No newline at end of file diff --git a/world/screenshot-widget/ffi_import.mbt b/world/screenshot-widget/ffi_import.mbt new file mode 100644 index 0000000..cdedbce --- /dev/null +++ b/world/screenshot-widget/ffi_import.mbt @@ -0,0 +1,2 @@ +// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT! + diff --git a/world/screenshot-widget/import.mbt b/world/screenshot-widget/import.mbt new file mode 100644 index 0000000..cdedbce --- /dev/null +++ b/world/screenshot-widget/import.mbt @@ -0,0 +1,2 @@ +// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT! + diff --git a/world/screenshot-widget/moon.pkg b/world/screenshot-widget/moon.pkg new file mode 100644 index 0000000..e2a6033 --- /dev/null +++ b/world/screenshot-widget/moon.pkg @@ -0,0 +1 @@ +warnings = "-44"