diff --git a/README.md b/README.md index e4382bc..64b90d9 100644 --- a/README.md +++ b/README.md @@ -137,6 +137,11 @@ new keys) | Super+Shift+R | Record a region or window (Enter starts) | | Super+Alt+R / Super+Ctrl+R | Record the whole screen / the window under the pointer | +Every screenshot opens in the screenshot editor first: annotate it (arrow, line, rectangle, +ellipse, pen, highlighter, text, numbered markers), hide parts of it (blur, pixelate, redact) or +crop it, then Enter saves and copies it, Ctrl+C only copies it and Esc discards it. See +[docs/screenshot-editor.md](docs/screenshot-editor.md). + Screenshots go to `~/Pictures/Screenshots/` and the clipboard; recordings (H.264 MP4, via `ffmpeg`) go to `~/Videos/Screencasts/`. A red REC pill shows while recording; click it or press a recording shortcut again to stop. diff --git a/compositor/host/annotate.mbt b/compositor/host/annotate.mbt new file mode 100644 index 0000000..c935428 --- /dev/null +++ b/compositor/host/annotate.mbt @@ -0,0 +1,501 @@ +///| Screenshot annotations: what each tool of the screenshot editor (shot_editor.mbt) leaves on +/// the picture, and the pixel work that puts it there. +/// +/// Every annotation is drawn into the picture's own pixels at full size the moment it is made +/// (`apply_annotation`), and the editor shows that picture, so what is on screen is what gets +/// saved. Blur, Pixelate and Redact replace the pixels under them: Redact paints an opaque box, +/// Pixelate averages blocks, and Blur first averages small blocks and then box-blurs them three +/// times, so nothing of the detail underneath is left in the file. Crop doesn't touch pixels: +/// the last crop picks the part of the picture that is saved. + +///| An editor tool. +pub(all) enum Tool { + Arrow + Line + Rectangle + Ellipse + /// Freehand. + Pen + /// Freehand, wide and translucent. + Highlighter + Text + /// A numbered disc (1, 2, 3, ... in the order they are placed). + Number + Blur + Pixelate + /// An opaque box in the chosen colour. + Redact + Crop +} derive(Eq, Debug) + +///| One annotation, in picture pixels. Shapes and regions use the first and last point; Pen +/// and Highlighter every point; Text and Number the first (Text: its left end, vertically +/// centred; Number: the disc's centre). +pub(all) struct Annotation { + tool : Tool + color : @scene.Rgba + /// Stroke width; text size, marker size and pixel blocks follow from it. + width : Int + points : Array[(Int, Int)] + mut text : String + number : Int +} derive(Debug) + +///| Text size for stroke width `w`. +pub fn annotation_text_size(w : Int) -> Int { + 10 + w * 3 +} + +///| A number marker's radius for stroke width `w`. +pub fn annotation_marker_radius(w : Int) -> Int { + 10 + w * 2 +} + +///| Pixelate's block size for stroke width `w`. +pub fn annotation_pixel_block(w : Int) -> Int { + 8 + w * 4 +} + +///| Half the highlighter's width for stroke width `w`. +fn highlighter_half(w : Int) -> Double { + (w * 3).max(8).to_double() +} + +///| The highlighter's alpha (out of 255). +let highlighter_alpha : Int = 110 + +///| The rectangle spanned by the first and last point (the last point's pixel included). +pub fn Annotation::rect(self : Annotation) -> @scene.Rect { + let (x0, y0) = self.points[0] + let (x1, y1) = self.points[self.points.length() - 1] + @scene.Rect::new(x0.min(x1), y0.min(y1), (x1 - x0).abs(), (y1 - y0).abs()) +} + +///| `r` clipped to `p`. +fn clip_rect(p : @renderer.Pixmap, r : @scene.Rect) -> @scene.Rect { + let x0 = r.x.max(0) + let y0 = r.y.max(0) + let x1 = (r.x + r.w).min(p.width) + let y1 = (r.y + r.h).min(p.height) + @scene.Rect::new(x0, y0, (x1 - x0).max(0), (y1 - y0).max(0)) +} + +///| A copy of `p`. +pub fn copy_pixmap(p : @renderer.Pixmap) -> @renderer.Pixmap { + let data = FixedArray::make(p.data.length(), b'\x00') + FixedArray::blit_to(p.data, data, len=data.length()) + { width: p.width, height: p.height, data } +} + +///| `r` of `p` as a new pixmap (clipped to `p`; at least 1 x 1). +pub fn crop_pixmap(p : @renderer.Pixmap, r : @scene.Rect) -> @renderer.Pixmap { + let c = clip_rect(p, r) + let out = @renderer.Pixmap::new(c.w, c.h) + for y = 0; y < c.h; y = y + 1 { + FixedArray::blit_to(p.data, out.data, len=c.w * 4, src_offset=((c.y + y) * p.width + c.x) * 4, dst_offset=y * c.w * 4) + } + out +} + +///| Paint `r` of `p` opaque `color`. +pub fn redact_region(p : @renderer.Pixmap, r : @scene.Rect, color : @scene.Rgba) -> Unit { + let c = clip_rect(p, r) + for y = c.y; y < c.y + c.h; y = y + 1 { + for x = c.x; x < c.x + c.w; x = x + 1 { + let o = (y * p.width + x) * 4 + p.data[o] = color.r + p.data[o + 1] = color.g + p.data[o + 2] = color.b + p.data[o + 3] = b'\xff' + } + } +} + +///| Replace each `block` x `block` square of `r` (counted from its top-left corner) with its +/// average colour. +pub fn pixelate_region(p : @renderer.Pixmap, r : @scene.Rect, block : Int) -> Unit { + let c = clip_rect(p, r) + let b = block.max(1) + let mut by = c.y + while by < c.y + c.h { + let bh = b.min(c.y + c.h - by) + let mut bx = c.x + while bx < c.x + c.w { + let bw = b.min(c.x + c.w - bx) + let mut sr = 0 + let mut sg = 0 + let mut sb = 0 + for y = by; y < by + bh; y = y + 1 { + for x = bx; x < bx + bw; x = x + 1 { + let o = (y * p.width + x) * 4 + sr = sr + p.data[o].to_int() + sg = sg + p.data[o + 1].to_int() + sb = sb + p.data[o + 2].to_int() + } + } + let n = bw * bh + let ar = ((sr + n / 2) / n).to_byte() + let ag = ((sg + n / 2) / n).to_byte() + let ab = ((sb + n / 2) / n).to_byte() + for y = by; y < by + bh; y = y + 1 { + for x = bx; x < bx + bw; x = x + 1 { + let o = (y * p.width + x) * 4 + p.data[o] = ar + p.data[o + 1] = ag + p.data[o + 2] = ab + p.data[o + 3] = b'\xff' + } + } + bx = bx + b + } + by = by + b + } +} + +///| One box-blur pass of radius `k` along a line of `n` pixels starting at byte offset `start`, +/// `step` bytes apart, reading only those pixels (the ends repeat), through `tmp`. +fn box_line(p : @renderer.Pixmap, start : Int, step : Int, n : Int, k : Int, tmp : FixedArray[Int]) -> Unit { + for ch = 0; ch < 3; ch = ch + 1 { + let at = fn(i : Int) { p.data[start + i.clamp(min=0, max=n - 1) * step + ch].to_int() } + let mut sum = 0 + for i = -k; i <= k; i = i + 1 { + sum = sum + at(i) + } + let d = 2 * k + 1 + for i = 0; i < n; i = i + 1 { + tmp[i] = (sum + d / 2) / d + sum = sum + at(i + k + 1) - at(i - k) + } + for i = 0; i < n; i = i + 1 { + p.data[start + i * step + ch] = tmp[i].to_byte() + } + } +} + +///| The blur radius for a region: strong, and stronger for big regions. +pub fn blur_radius(r : @scene.Rect) -> Int { + (r.w.min(r.h) / 6).clamp(min=6, max=24) +} + +///| Blur `r` of `p` so its content can't be read back: 6 x 6 block averages first (fine detail is +/// gone for good), then three box-blur passes each way. Only pixels of `r` are read or written. +pub fn blur_region(p : @renderer.Pixmap, r : @scene.Rect) -> Unit { + let c = clip_rect(p, r) + if c.w <= 0 || c.h <= 0 { + return + } + pixelate_region(p, c, 6) + let k = blur_radius(c) + let tmp = FixedArray::make(c.w.max(c.h), 0) + for _ in 0..<3 { + for y = c.y; y < c.y + c.h; y = y + 1 { + box_line(p, (y * p.width + c.x) * 4, 4, c.w, k, tmp) + } + for x = c.x; x < c.x + c.w; x = x + 1 { + box_line(p, (c.y * p.width + x) * 4, p.width * 4, c.h, k, tmp) + } + } +} + +///| Antialiased coverage (0-255) over a box of the picture: strokes and shapes add to it (the +/// highest coverage wins), then it is blended once, so overlapping parts of a translucent stroke +/// aren't darker. +priv struct Mask { + x0 : Int + y0 : Int + w : Int + h : Int + cov : FixedArray[Int] +} + +///| A mask over (x0, y0)-(x1, y1) of `p`, clipped to it. +fn Mask::new(p : @renderer.Pixmap, x0 : Int, y0 : Int, x1 : Int, y1 : Int) -> Mask { + let a = x0.max(0) + let b = y0.max(0) + let w = (x1.min(p.width) - a).max(0) + let h = (y1.min(p.height) - b).max(0) + { x0: a, y0: b, w, h, cov: FixedArray::make((w * h).max(1), 0) } +} + +///| +fn Mask::put(self : Mask, x : Int, y : Int, c : Double) -> Unit { + if c <= 0.0 { + return + } + let v = if c >= 1.0 { 255 } else { (c * 255.0).to_int() } + let i = (y - self.y0) * self.w + (x - self.x0) + if v > self.cov[i] { + self.cov[i] = v + } +} + +///| The pixels of the mask within `pad` of the box (ax, ay)-(bx, by): (x0, y0, x1, y1), ends excluded. +fn Mask::span(self : Mask, ax : Double, ay : Double, bx : Double, by : Double, pad : Double) -> (Int, Int, Int, Int) { + let x0 = ((ax.min(bx) - pad).floor().to_int()).max(self.x0) + let y0 = ((ay.min(by) - pad).floor().to_int()).max(self.y0) + let x1 = ((ax.max(bx) + pad).ceil().to_int() + 1).min(self.x0 + self.w) + let y1 = ((ay.max(by) + pad).ceil().to_int() + 1).min(self.y0 + self.h) + (x0, y0, x1, y1) +} + +///| A stroke from (ax, ay) to (bx, by) with round ends, `half` its half width. +fn Mask::segment(self : Mask, ax : Double, ay : Double, bx : Double, by : Double, half : Double) -> Unit { + let (x0, y0, x1, y1) = self.span(ax, ay, bx, by, half + 1.0) + let dx = bx - ax + let dy = by - ay + let len2 = dx * dx + dy * dy + for y = y0; y < y1; y = y + 1 { + let py = y.to_double() + 0.5 + for x = x0; x < x1; x = x + 1 { + let px = x.to_double() + 0.5 + let t = if len2 <= 0.0 { + 0.0 + } else { + (((px - ax) * dx + (py - ay) * dy) / len2).clamp(min=0.0, max=1.0) + } + let qx = ax + t * dx - px + let qy = ay + t * dy - py + self.put(x, y, half + 0.5 - (qx * qx + qy * qy).sqrt()) + } + } +} + +///| A filled triangle. +fn Mask::triangle(self : Mask, ax : Double, ay : Double, bx : Double, by : Double, cx : Double, cy : Double) -> Unit { + let area = (bx - ax) * (cy - ay) - (by - ay) * (cx - ax) + if area == 0.0 { + return + } + let s = if area > 0.0 { 1.0 } else { -1.0 } + // Signed distance of (px, py) from the edge p -> q, positive inside. + let edge = fn(px : Double, py : Double, ex : Double, ey : Double, fx : Double, fy : Double) { + let l = ((fx - ex) * (fx - ex) + (fy - ey) * (fy - ey)).sqrt() + s * ((fx - ex) * (py - ey) - (fy - ey) * (px - ex)) / l + } + let (x0, y0, x1, y1) = self.span(ax.min(bx).min(cx), ay.min(by).min(cy), ax.max(bx).max(cx), ay.max(by).max(cy), 1.0) + for y = y0; y < y1; y = y + 1 { + let py = y.to_double() + 0.5 + for x = x0; x < x1; x = x + 1 { + let px = x.to_double() + 0.5 + let d = edge(px, py, ax, ay, bx, by).min(edge(px, py, bx, by, cx, cy)).min(edge(px, py, cx, cy, ax, ay)) + self.put(x, y, d + 0.5) + } + } +} + +///| Blend `color` over `p` through the mask. +fn Mask::blend(self : Mask, p : @renderer.Pixmap, color : @scene.Rgba) -> Unit { + let cr = color.r.to_int() + let cg = color.g.to_int() + let cb = color.b.to_int() + let ca = color.a.to_int() + for y = 0; y < self.h; y = y + 1 { + for x = 0; x < self.w; x = x + 1 { + let m = self.cov[y * self.w + x] + if m > 0 { + let a = ca * m / 255 + let o = ((self.y0 + y) * p.width + self.x0 + x) * 4 + let blend = fn(i : Int, c : Int) { + let d = p.data[o + i].to_int() + p.data[o + i] = ((d * (255 - a) + c * a + 127) / 255).to_byte() + } + blend(0, cr) + blend(1, cg) + blend(2, cb) + let da = p.data[o + 3].to_int() + p.data[o + 3] = (da + (255 - da) * a / 255).to_byte() + } + } + } +} + +///| A point's centre. +fn centre(pt : (Int, Int)) -> (Double, Double) { + (pt.0.to_double() + 0.5, pt.1.to_double() + 0.5) +} + +///| A mask covering points `pts` plus `pad` around them. +fn mask_around(p : @renderer.Pixmap, pts : Array[(Int, Int)], pad : Int) -> Mask { + let mut x0 = pts[0].0 + let mut y0 = pts[0].1 + let mut x1 = x0 + let mut y1 = y0 + for pt in pts { + x0 = x0.min(pt.0) + y0 = y0.min(pt.1) + x1 = x1.max(pt.0) + y1 = y1.max(pt.1) + } + Mask::new(p, x0 - pad, y0 - pad, x1 + pad + 1, y1 + pad + 1) +} + +///| A stroke through `pts` (a dot when there is one). +fn Mask::polyline(self : Mask, pts : Array[(Int, Int)], half : Double) -> Unit { + if pts.length() == 1 { + let (x, y) = centre(pts[0]) + self.segment(x, y, x, y, half) + return + } + for i = 1; i < pts.length(); i = i + 1 { + let (ax, ay) = centre(pts[i - 1]) + let (bx, by) = centre(pts[i]) + self.segment(ax, ay, bx, by, half) + } +} + +///| The points of an ellipse inscribed in `r` (a closed loop). +pub fn ellipse_points(r : @scene.Rect) -> Array[(Int, Int)] { + let cx = r.x.to_double() + r.w.to_double() / 2.0 + let cy = r.y.to_double() + r.h.to_double() / 2.0 + let rx = r.w.to_double() / 2.0 + let ry = r.h.to_double() / 2.0 + let n = 96 + let pts : Array[(Int, Int)] = [] + for i = 0; i <= n; i = i + 1 { + let t = 2.0 * @math.pi * i.to_double() / n.to_double() + pts.push(((cx + rx * @math.cos(t)).round().to_int(), (cy + ry * @math.sin(t)).round().to_int())) + } + pts +} + +///| An arrow's head: (tip, the two corners of its base, where the shaft ends), for stroke width +/// `w`, as doubles. +pub fn arrow_head( + x0 : Double, + y0 : Double, + x1 : Double, + y1 : Double, + w : Int, +) -> ((Double, Double), (Double, Double), (Double, Double), (Double, Double)) { + let dx = x1 - x0 + let dy = y1 - y0 + let len = (dx * dx + dy * dy).sqrt() + let (ux, uy) = if len > 0.0 { (dx / len, dy / len) } else { (1.0, 0.0) } + let l = (w * 4 + 8).to_double().min(len * 0.6).max(4.0) + let hw = l * 0.5 + let bx = x1 - ux * l + let by = y1 - uy * l + ((x1, y1), (bx - uy * hw, by + ux * hw), (bx + uy * hw, by - ux * hw), (x1 - ux * l * 0.5, y1 - uy * l * 0.5)) +} + +///| Black or white, whichever reads better on `c`. +pub fn contrast_on(c : @scene.Rgba) -> @scene.Rgba { + let lum = c.r.to_int() * 299 + c.g.to_int() * 587 + c.b.to_int() * 114 + if lum > 160 * 1000 { + @scene.Rgba::new(0, 0, 0, 255) + } else { + @scene.Rgba::new(255, 255, 255, 255) + } +} + +///| Draw annotation `a` into `p`. +pub fn apply_annotation(p : @renderer.Pixmap, a : Annotation) -> Unit { + let half = a.width.to_double() / 2.0 + match a.tool { + Line | Arrow => { + let (x0, y0) = centre(a.points[0]) + let (x1, y1) = centre(a.points[a.points.length() - 1]) + let pad = a.width * 4 + 12 + let m = mask_around(p, [a.points[0], a.points[a.points.length() - 1]], pad) + if a.tool == Line { + m.segment(x0, y0, x1, y1, half) + } else { + let (tip, b1, b2, shaft_end) = arrow_head(x0, y0, x1, y1, a.width) + m.segment(x0, y0, shaft_end.0, shaft_end.1, half) + m.triangle(tip.0, tip.1, b1.0, b1.1, b2.0, b2.1) + } + m.blend(p, a.color) + } + Rectangle => { + let r = a.rect() + let c = [(r.x, r.y), (r.x + r.w, r.y), (r.x + r.w, r.y + r.h), (r.x, r.y + r.h), (r.x, r.y)] + let m = mask_around(p, c, a.width + 2) + m.polyline(c, half) + m.blend(p, a.color) + } + Ellipse => { + let pts = ellipse_points(a.rect()) + let m = mask_around(p, pts, a.width + 2) + m.polyline(pts, half) + m.blend(p, a.color) + } + Pen => { + let m = mask_around(p, a.points, a.width + 2) + m.polyline(a.points, half) + m.blend(p, a.color) + } + Highlighter => { + let hh = highlighter_half(a.width) + let m = mask_around(p, a.points, hh.to_int() + 2) + m.polyline(a.points, hh) + m.blend(p, a.color.with_alpha(highlighter_alpha)) + } + Text => + if a.text.length() > 0 { + let (x, y) = a.points[0] + @renderer.draw_ops( + p, + [@scene.DrawOp::Text(x, y, a.text, annotation_text_size(a.width), a.color, @scene.TextAlign::Left, false)], + 0, + 0, + ) + } + Number => { + let r = annotation_marker_radius(a.width) + let m = mask_around(p, [a.points[0]], r + 2) + m.polyline([a.points[0]], r.to_double()) + m.blend(p, a.color.with_alpha(255)) + let (x, y) = a.points[0] + @renderer.draw_ops( + p, + [ + @scene.DrawOp::Text( + x, + y, + a.number.to_string(), + r * 6 / 5, + contrast_on(a.color), + @scene.TextAlign::Center, + true, + ), + ], + 0, + 0, + ) + } + Blur => blur_region(p, a.rect()) + Pixelate => pixelate_region(p, a.rect(), annotation_pixel_block(a.width)) + Redact => redact_region(p, a.rect(), a.color) + Crop => () + } +} + +///| The part of the picture that is saved: the last crop's rectangle (clipped), else all of it. +pub fn final_crop(w : Int, h : Int, anns : Array[Annotation]) -> @scene.Rect { + let full = @scene.Rect::new(0, 0, w, h) + let mut i = anns.length() - 1 + while i >= 0 { + if anns[i].tool == Crop { + let r = anns[i].rect() + let x0 = r.x.max(0) + let y0 = r.y.max(0) + let x1 = (r.x + r.w).min(w) + let y1 = (r.y + r.h).min(h) + if x1 > x0 && y1 > y0 { + return @scene.Rect::new(x0, y0, x1 - x0, y1 - y0) + } + return full + } + i = i - 1 + } + full +} + +///| `base` with `anns` drawn into it in order, cropped by the last crop: the picture to save. +pub fn render_annotations(base : @renderer.Pixmap, anns : Array[Annotation]) -> @renderer.Pixmap { + let p = copy_pixmap(base) + for a in anns { + apply_annotation(p, a) + } + crop_pixmap(p, final_crop(p.width, p.height, anns)) +} diff --git a/compositor/host/annotate_test.mbt b/compositor/host/annotate_test.mbt new file mode 100644 index 0000000..ecfa052 --- /dev/null +++ b/compositor/host/annotate_test.mbt @@ -0,0 +1,490 @@ +///| The screenshot editor: its pixel work (blur, pixelate, redact, crop, strokes) checked pixel by +/// pixel, and its keys and buttons driven headlessly. + +///| A `w` x `h` picture where pixel (x, y) is `f(x, y)` as grey, opaque. +fn grey_pic(w : Int, h : Int, f : (Int, Int) -> Int) -> @renderer.Pixmap { + let p = @renderer.Pixmap::new(w, h) + for y = 0; y < h; y = y + 1 { + for x = 0; x < w; x = x + 1 { + let o = (y * w + x) * 4 + let v = f(x, y).to_byte() + p.data[o] = v + p.data[o + 1] = v + p.data[o + 2] = v + p.data[o + 3] = b'\xff' + } + } + p +} + +///| Pixel (x, y) as (r, g, b, a). +fn px(p : @renderer.Pixmap, x : Int, y : Int) -> (Int, Int, Int, Int) { + let o = (y * p.width + x) * 4 + (p.data[o].to_int(), p.data[o + 1].to_int(), p.data[o + 2].to_int(), p.data[o + 3].to_int()) +} + +///| Whether every pixel outside `r` is the same in `a` and `b`. +fn same_outside(a : @renderer.Pixmap, b : @renderer.Pixmap, r : @scene.Rect) -> Bool { + for y = 0; y < a.height; y = y + 1 { + for x = 0; x < a.width; x = x + 1 { + if !r.contains(x, y) && px(a, x, y) != px(b, x, y) { + return false + } + } + } + true +} + +///| An annotation with `tool` from `p0` to `p1`. +fn ann(tool : @host.Tool, p0 : (Int, Int), p1 : (Int, Int), color? : @scene.Rgba = @scene.Rgba::new(255, 0, 0, 255), width? : Int = 4) -> @host.Annotation { + { tool, color, width, points: [p0, p1], text: "", number: 0 } +} + +///| Text-like detail: 1-pixel black/white stripes (vertical in `a`, a checkerboard in `b`), both +/// half white. +fn stripes(x : Int, _y : Int) -> Int { + if x % 2 == 0 { 255 } else { 0 } +} + +///| +fn checker(x : Int, y : Int) -> Int { + if (x + y) % 2 == 0 { 0 } else { 255 } +} + +///| +test "blur changes only the pixels in its region, and leaves nothing of what was there" { + let r = @scene.Rect::new(40, 20, 90, 50) + let a = grey_pic(200, 100, stripes) + let b = grey_pic(200, 100, checker) + let a0 = @host.copy_pixmap(a) + @host.blur_region(a, r) + @host.blur_region(b, r) + // Outside the region: untouched. + assert_true(same_outside(a, a0, r)) + // Inside: no fine detail left (the stripes went from 0 to 255 between neighbours), and two + // different patterns with the same average come out the same. + let mut lo = 255 + let mut hi = 0 + let mut diff = 0 + for y = r.y; y < r.y + r.h; y = y + 1 { + for x = r.x; x < r.x + r.w; x = x + 1 { + let (v, _, _, al) = px(a, x, y) + assert_eq(al, 255) + lo = lo.min(v) + hi = hi.max(v) + diff = diff.max((v - px(b, x, y).0).abs()) + } + } + assert_true(hi - lo <= 8) + assert_true(diff <= 8) + // Every pixel of the region changed (each was 0 or 255, now mid-grey). + assert_true(lo > 100 && hi < 160) +} + +///| +test "blur hides a dark word on a light background: the region ends up nearly flat" { + // A 'word': dark bars of different widths on white, like glyph stems. + let word = fn(x : Int, y : Int) { + if y >= 30 && y < 44 && (x % 7 == 0 || x % 11 == 0 || x % 13 < 2) { 20 } else { 240 } + } + let p = grey_pic(160, 80, word) + let r = @scene.Rect::new(20, 24, 120, 26) + @host.blur_region(p, r) + // Across the blurred word, neighbouring columns differ by at most 4 levels. + let mut worst = 0 + for y = r.y; y < r.y + r.h; y = y + 1 { + for x = r.x + 1; x < r.x + r.w; x = x + 1 { + worst = worst.max((px(p, x, y).0 - px(p, x - 1, y).0).abs()) + } + } + assert_true(worst <= 4) // the word was 220 levels against its background +} + +///| +test "pixelate makes each block one colour, and nothing outside changes" { + let p = grey_pic(100, 60, fn(x, y) { (x * 7 + y * 13) % 256 }) + let p0 = @host.copy_pixmap(p) + let r = @scene.Rect::new(10, 10, 48, 32) + @host.pixelate_region(p, r, 16) + assert_true(same_outside(p, p0, r)) + for by = 0; by < 2; by = by + 1 { + for bx = 0; bx < 3; bx = bx + 1 { + let c = px(p, r.x + bx * 16, r.y + by * 16) + for y = 0; y < 16; y = y + 1 { + for x = 0; x < 16; x = x + 1 { + assert_eq(px(p, r.x + bx * 16 + x, r.y + by * 16 + y), c) + } + } + } + } + // A block's colour is its average: block (0, 0) of the gradient isn't any one of its pixels' old values only. + assert_true(px(p, r.x, r.y) != px(p0, r.x, r.y)) +} + +///| +test "redact is fully opaque, even over a picture with alpha, and stays in its box" { + let p = grey_pic(64, 64, checker) + // Make the picture translucent: redact must still leave nothing showing through. + for i = 3; i < p.data.length(); i = i + 4 { + p.data[i] = b'\x40' + } + let p0 = @host.copy_pixmap(p) + let r = @scene.Rect::new(8, 12, 30, 20) + @host.apply_annotation(p, ann(@host.Tool::Redact, (8, 12), (38, 32), color=@scene.Rgba::new(10, 20, 30, 255))) + assert_true(same_outside(p, p0, r)) + for y = r.y; y < r.y + r.h; y = y + 1 { + for x = r.x; x < r.x + r.w; x = x + 1 { + assert_eq(px(p, x, y), (10, 20, 30, 255)) + } + } +} + +///| +test "crop: the last crop sets the saved size; crops are clipped to the picture" { + let base = grey_pic(300, 200, fn(x, _) { x % 256 }) + let anns = [ + ann(@host.Tool::Crop, (10, 10), (110, 60)), + ann(@host.Tool::Line, (0, 100), (299, 100)), + ann(@host.Tool::Crop, (250, 150), (20, 40)), + ] + let out = @host.render_annotations(base, anns) + assert_eq((out.width, out.height), (230, 110)) + // The saved pixels are the picture's, from the crop's corner. + assert_eq(px(out, 0, 0), px(base, 20, 40)) + assert_eq(px(out, 229, 0), px(base, 249, 40)) + // The line went through the crop: it's in the saved picture, red. + assert_eq(px(out, 100, 60), (255, 0, 0, 255)) + // A crop that runs off the picture is cut to it. + let off = @host.render_annotations(base, [ann(@host.Tool::Crop, (200, 150), (400, 300))]) + assert_eq((off.width, off.height), (100, 50)) + // No crop: the whole picture. + let all = @host.render_annotations(base, []) + assert_eq((all.width, all.height), (300, 200)) +} + +///| +test "strokes: lines, arrows, rectangles, ellipses and the pen draw where they go and nowhere else" { + let white = fn(_x : Int, _y : Int) { 255 } + let red = (255, 0, 0, 255) + // A line: on it red, 10 px away untouched. + let p = grey_pic(120, 80, white) + @host.apply_annotation(p, ann(@host.Tool::Line, (10, 40), (110, 40))) + assert_eq(px(p, 60, 40), red) + assert_eq(px(p, 60, 50), (255, 255, 255, 255)) + // An arrow: its head is wider than its shaft. + let q = grey_pic(120, 80, white) + @host.apply_annotation(q, ann(@host.Tool::Arrow, (10, 40), (110, 40))) + assert_eq(px(q, 30, 40), red) + assert_eq(px(q, 30, 46), (255, 255, 255, 255)) + assert_eq(px(q, 100, 44), red) // inside the head, beside the shaft's line + // A rectangle: its edges, not its inside. + let r = grey_pic(120, 80, white) + @host.apply_annotation(r, ann(@host.Tool::Rectangle, (20, 20), (100, 60))) + assert_eq(px(r, 20, 40), red) + assert_eq(px(r, 60, 20), red) + assert_eq(px(r, 60, 40), (255, 255, 255, 255)) + // An ellipse: through the middle of each side of its box, not in its centre or the corners. + let e = grey_pic(120, 80, white) + @host.apply_annotation(e, ann(@host.Tool::Ellipse, (20, 20), (100, 60))) + assert_eq(px(e, 60, 20), red) + assert_eq(px(e, 20, 40), red) + assert_eq(px(e, 60, 40), (255, 255, 255, 255)) + assert_eq(px(e, 21, 21), (255, 255, 255, 255)) + // The pen follows its points. + let pen = grey_pic(120, 80, white) + @host.apply_annotation(pen, { ..ann(@host.Tool::Pen, (10, 10), (50, 10)), points: [(10, 10), (50, 10), (50, 60)] }) + assert_eq(px(pen, 30, 10), red) + assert_eq(px(pen, 50, 35), red) + assert_eq(px(pen, 30, 35), (255, 255, 255, 255)) +} + +///| +test "the highlighter is translucent and even where its stroke crosses itself" { + let p = grey_pic(120, 120, fn(_, _) { 255 }) + let yellow = @scene.Rgba::new(255, 220, 0, 255) + // Across, then back down through the first part. + @host.apply_annotation(p, { ..ann(@host.Tool::Highlighter, (10, 60), (110, 60), color=yellow), points: [(10, 60), (110, 60), (60, 10), (60, 110)] }) + let once = px(p, 30, 60) + let twice = px(p, 60, 60) + assert_eq(once, twice) + // Translucent: the white shows through the blue channel. + assert_true(once.2 > 100 && once.2 < 255) +} + +///| +test "a number marker is a filled disc of its colour with the number on it" { + let p = grey_pic(100, 100, fn(_, _) { 255 }) + let m : @host.Annotation = { ..ann(@host.Tool::Number, (50, 50), (50, 50), color=@scene.Rgba::new(30, 136, 229, 255)), number: 3 } + @host.apply_annotation(p, m) + let r = @host.annotation_marker_radius(4) + // The rim of the disc is the marker colour; outside it, white. + assert_eq(px(p, 50 + r - 2, 50), (30, 136, 229, 255)) + assert_eq(px(p, 50 + r + 3, 50), (255, 255, 255, 255)) + // The number: some white pixels inside the disc. + let mut white = 0 + for y = 50 - r / 2; y < 50 + r / 2; y = y + 1 { + for x = 50 - r / 2; x < 50 + r / 2; x = x + 1 { + if px(p, x, y).0 > 200 { + white = white + 1 + } + } + } + assert_true(white > 5) +} + +///| Open the editor on a full-screen picture (Print). +fn editor_comp(tag : String) -> (@host.ChandraCompositor, String) raise { + let (comp, dir) = shot_comp(tag) + key(comp, 99U, true, 1U) + key(comp, 99U, false, 2U) + assert_true(comp.screenshot_editing()) + ignore(comp.compose_frame()) + (comp, dir) +} + +///| Picture pixel (x, y) on screen in the editor. +fn on_screen(comp : @host.ChandraCompositor, x : Int, y : Int) -> (Int, Int) { + let (v, s) = comp.screenshot_editor().unwrap().view() + (v.x + (x.to_double() * s).round().to_int(), v.y + (y.to_double() * s).round().to_int()) +} + +///| Drag in the editor between picture pixels. +fn edit_drag(comp : @host.ChandraCompositor, x0 : Int, y0 : Int, x1 : Int, y1 : Int, t : UInt) -> Unit { + let (a, b) = on_screen(comp, x0, y0) + let (c, d) = on_screen(comp, x1, y1) + drag(comp, a, b, c, d, t) +} + +///| Ctrl + `code`. +fn ctrl_key(comp : @host.ChandraCompositor, code : UInt, t : UInt, shift? : Bool = false) -> Unit { + key(comp, 29U, true, t) + if shift { + key(comp, 42U, true, t) + } + comp.handle_input(@nested.InputEvent::Modifiers(4U | (if shift { 1U } else { 0U }), 0U, 0U, 0U), t) + key(comp, code, true, t + 1U) + key(comp, code, false, t + 2U) + if shift { + key(comp, 42U, false, t + 3U) + } + key(comp, 29U, false, t + 3U) + comp.handle_input(@nested.InputEvent::Modifiers(0U, 0U, 0U, 0U), t + 3U) +} + +///| Press and let go of a key. +fn tap(comp : @host.ChandraCompositor, code : UInt, t : UInt) -> Unit { + key(comp, code, true, t) + key(comp, code, false, t + 1U) +} + +///| +test "editor: Print opens it with the keyboard; Esc discards without saving and gives the keyboard back" { + let (comp, dir) = editor_comp("ed-esc") + // The picture fits between the bars, scaled down. + let (v, s) = comp.screenshot_editor().unwrap().view() + assert_true(s < 1.0 && v.y > 40 && v.y + v.h < 720 - 40) + // Keys go to the editor: B picks Blur. + tap(comp, 48U, 10U) + assert_eq(comp.screenshot_editor().unwrap().current_tool(), @host.Tool::Blur) + tap(comp, 1U, 20U) + assert_false(comp.screenshot_editing()) + assert_eq(comp.last_screenshot(), "") + assert_eq(@sys.read_file_bytes(dir).length(), 0) +} + +///| +test "editor: draw, undo, redo, crop, then Enter saves exactly what is shown" { + let (comp, dir) = editor_comp("ed-flow") + // R: rectangle, then a drag. + tap(comp, 19U, 10U) + edit_drag(comp, 100, 100, 300, 200, 20U) + assert_eq(comp.screenshot_editor().unwrap().annotations().length(), 1) + // D: redact a box; X: pixelate one. + tap(comp, 32U, 30U) + edit_drag(comp, 400, 300, 500, 360, 40U) + tap(comp, 45U, 50U) + edit_drag(comp, 600, 100, 700, 200, 60U) + let e = comp.screenshot_editor().unwrap() + assert_eq(e.annotations().length(), 3) + // The redacted box is opaque in the picture shown (red: the first colour). + assert_eq(px(e.picture(), 450, 330), (0xe5, 0x39, 0x35, 255)) + // Ctrl+Z takes the pixelation back out, Ctrl+Shift+Z puts it back; Ctrl+Y after another undo too. + ctrl_key(comp, 44U, 70U) + assert_eq(comp.screenshot_editor().unwrap().annotations().length(), 2) + ctrl_key(comp, 44U, 80U, shift=true) + assert_eq(comp.screenshot_editor().unwrap().annotations().length(), 3) + ctrl_key(comp, 44U, 90U) + ctrl_key(comp, 21U, 100U) + assert_eq(comp.screenshot_editor().unwrap().annotations().length(), 3) + // A click without a drag adds no shape. + tap(comp, 19U, 110U) + let (cx, cy) = on_screen(comp, 900, 500) + click_at(comp, cx, cy, 120U) + assert_eq(comp.screenshot_editor().unwrap().annotations().length(), 3) + // C: crop to (380, 280)-(520, 380). + tap(comp, 46U, 130U) + edit_drag(comp, 380, 280, 520, 380, 140U) + let e = comp.screenshot_editor().unwrap() + let crop = @host.final_crop(1280, 720, e.annotations()) + let expected = e.export() + assert_eq((expected.width, expected.height), (crop.w, crop.h)) + assert_true(crop.w >= 138 && crop.w <= 142 && crop.h >= 98 && crop.h <= 102) + ignore(comp.compose_frame()) + // Enter saves it (and copies it). + tap(comp, 28U, 150U) + assert_false(comp.screenshot_editing()) + let path = comp.last_screenshot() + assert_true(path.has_prefix(dir + "/Screenshot_")) + let saved = @renderer.decode_png(@sys.read_file_bytes(path)).unwrap() + assert_eq((saved.width, saved.height), (crop.w, crop.h)) + assert_eq(saved.data, expected.data) + assert_true(comp.server.owns_selection()) +} + +///| +test "editor: Ctrl+C and the Copy button copy without saving a file" { + let (comp, dir) = editor_comp("ed-copy") + ctrl_key(comp, 46U, 10U) + assert_false(comp.screenshot_editing()) + assert_true(comp.server.owns_selection()) + assert_eq(comp.last_screenshot(), "") + assert_eq(@sys.read_file_bytes(dir).length(), 0) + assert_true(comp.screenshot_toast_shown()) +} + +///| +test "editor: the toolbar and bottom bar buttons work" { + let (comp, dir) = editor_comp("ed-buttons") + ignore(comp.compose_frame()) + // The tool buttons are along the top, in order: the 9th is Blur. + let y = 12 + 16 + let mut found = false + let mut x = 0 + while x < 1280 && !found { + click_at(comp, x, y, 10U + x.reinterpret_as_uint()) + if comp.screenshot_editor().unwrap().current_tool() == @host.Tool::Blur { + found = true + } + x = x + 6 + } + assert_true(found) + edit_drag(comp, 50, 50, 250, 150, 3000U) + assert_eq(comp.screenshot_editor().unwrap().annotations().length(), 1) + // Save is the right-most button of the bottom bar. + click_at(comp, 1280 - 12 - 10, 720 - 12 - 16, 3100U) + assert_false(comp.screenshot_editing()) + assert_true(comp.last_screenshot().has_prefix(dir)) +} + +///| +test "editor: text is typed through the keymap; numbers count up" { + let (comp, _) = editor_comp("ed-text") + tap(comp, 20U, 10U) // T + let (x, y) = on_screen(comp, 200, 200) + click_at(comp, x, y, 20U) + // Shift+H, i, Backspace, i, ! -> "Hi!" + key(comp, 42U, true, 30U) + comp.handle_input(@nested.InputEvent::Modifiers(1U, 0U, 0U, 0U), 30U) + tap(comp, 35U, 31U) + key(comp, 42U, false, 33U) + comp.handle_input(@nested.InputEvent::Modifiers(0U, 0U, 0U, 0U), 33U) + tap(comp, 23U, 34U) + tap(comp, 23U, 36U) + tap(comp, 14U, 38U) + key(comp, 42U, true, 40U) + comp.handle_input(@nested.InputEvent::Modifiers(1U, 0U, 0U, 0U), 40U) + tap(comp, 2U, 41U) + key(comp, 42U, false, 43U) + comp.handle_input(@nested.InputEvent::Modifiers(0U, 0U, 0U, 0U), 43U) + ignore(comp.compose_frame()) + // Enter ends the text (and doesn't save yet). + tap(comp, 28U, 50U) + assert_true(comp.screenshot_editing()) + let anns = comp.screenshot_editor().unwrap().annotations() + assert_eq(anns.length(), 1) + assert_eq(anns[0].text, "Hi!") + // N: two markers, numbered 1 and 2. + tap(comp, 49U, 60U) + let (a, b) = on_screen(comp, 400, 300) + click_at(comp, a, b, 70U) + let (c, d) = on_screen(comp, 500, 300) + click_at(comp, c, d, 80U) + let anns = comp.screenshot_editor().unwrap().annotations() + assert_eq(anns.map(a => a.number), [0, 1, 2]) + tap(comp, 1U, 90U) + assert_false(comp.screenshot_editing()) +} + +///| +test "editor: a region screenshot opens at full size when it fits" { + let (comp, _) = shot_comp("ed-region") + chord(comp, [125U, 42U], 65U, 31U, 1U) + drag(comp, 100, 100, 500, 400, 10U) + tap(comp, 28U, 20U) + let (v, s) = comp.screenshot_editor().unwrap().view() + assert_eq(s, 1.0) + assert_eq((v.w, v.h), (400, 300)) + tap(comp, 1U, 30U) +} + +///| Headless pictures of the editor for the docs: written when CHANDRA_EDITOR_SHOTS names a folder. +test "editor: headless screenshots" { + let out = @sys.getenv("CHANDRA_EDITOR_SHOTS") + if out.length() == 0 { + return + } + let socket_path = "/tmp/wayland-moon-edshots-" + @sys.getpid().to_string() + ".sock" + let comp = @host.ChandraCompositor::new(socket_path, @scene.ThemeTokens::moon_night(), 1280, 720).unwrap() + comp.shot_dir = "/tmp/chandra-edshots-" + @sys.getpid().to_string() + ignore(open_and_configure_client(comp, socket_path, "Notes", "notes")) + ignore(open_and_configure_client(comp, socket_path, "Terminal", "term")) + ignore(comp.compose_frame()) + key(comp, 99U, true, 1U) + key(comp, 99U, false, 2U) + ignore(comp.compose_frame()) + // An arrow, a rectangle, a blur, a redaction, a highlight, text and two markers. + tap(comp, 30U, 10U) + edit_drag(comp, 200, 560, 420, 380, 20U) + tap(comp, 19U, 30U) + tap(comp, 6U, 31U) // blue + edit_drag(comp, 430, 200, 760, 360, 40U) + tap(comp, 48U, 50U) + edit_drag(comp, 750, 628, 1275, 674, 60U) // the notification + tap(comp, 32U, 70U) + tap(comp, 8U, 71U) // black + edit_drag(comp, 895, 12, 1025, 42, 80U) // a title + tap(comp, 45U, 85U) + edit_drag(comp, 930, 686, 1060, 719, 86U) // the clock + tap(comp, 35U, 90U) + tap(comp, 4U, 91U) // yellow + let (h0, h1) = on_screen(comp, 436, 590) + let (h2, h3) = on_screen(comp, 640, 590) + drag(comp, h0, h1, h2, h3, 100U) + tap(comp, 49U, 110U) + tap(comp, 2U, 111U) // red + let (m0, m1) = on_screen(comp, 450, 190) + click_at(comp, m0, m1, 120U) + let (m2, m3) = on_screen(comp, 810, 110) + click_at(comp, m2, m3, 130U) + tap(comp, 20U, 140U) + tap(comp, 9U, 141U) // white + let (t0, t1) = on_screen(comp, 440, 590) + click_at(comp, t0, t1, 150U) + for c in [20U, 35U, 18U, 57U, 48U, 22U, 34U, 57U, 23U, 31U, 57U, 35U, 18U, 19U, 18U] { + tap(comp, c, 160U) + } + tap(comp, 28U, 170U) + // A crop being drawn. + tap(comp, 46U, 180U) + let (c0, c1) = on_screen(comp, 60, 60) + let (c2, c3) = on_screen(comp, 1220, 690) + comp.handle_input(@nested.InputEvent::PointerMove(c0.to_double(), c1.to_double()), 190U) + comp.handle_input(@nested.InputEvent::PointerButton(272U, true), 191U) + comp.handle_input(@nested.InputEvent::PointerMove(c2.to_double(), c3.to_double()), 192U) + let frame = comp.compose_frame() + ignore(@sys.mkdir_p(out)) + assert_eq(@sys.write_file_bytes(out + "/screenshot-editor.png", @renderer.encode_png_compressed(frame)), 0) + comp.handle_input(@nested.InputEvent::PointerButton(272U, false), 193U) + let saved = comp.screenshot_editor().unwrap().export() + assert_eq(@sys.write_file_bytes(out + "/screenshot-editor-saved.png", @renderer.encode_png_compressed(saved)), 0) +} diff --git a/compositor/host/compositor.mbt b/compositor/host/compositor.mbt index 49fc26e..812e444 100644 --- a/compositor/host/compositor.mbt +++ b/compositor/host/compositor.mbt @@ -249,6 +249,13 @@ pub(all) struct ChandraCompositor { shot_frozen : Map[UInt64, @scene.ShmBufferSnapshot] mut shot_dir : String mut last_shot : String + /// The screenshot editor (shot_editor.mbt) while it is up, the image handles its picture is + /// shown under, a strip each (kept for the next one), and the tool, colour and size it was left with. + mut shot_edit : ShotEditor? + shot_edit_images : Array[UInt] + mut shot_edit_tool : Tool + mut shot_edit_color : Int + mut shot_edit_size : Int /// 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?)? @@ -412,6 +419,11 @@ pub fn ChandraCompositor::new( shot_frozen: {}, shot_dir: "", last_shot: "", + shot_edit: None, + shot_edit_images: [], + shot_edit_tool: Tool::Arrow, + shot_edit_color: 0, + shot_edit_size: 1, frame_source: None, frame_recorder: None, frame_shots: None, @@ -663,8 +675,8 @@ pub fn ChandraCompositor::step(self : ChandraCompositor) -> Unit { Some(win) => { match snap { Some(s) => - if self.shot is Some(_) { - // The screen is frozen under the screenshot overlay: show it afterwards. + if self.shot is Some(_) || self.shot_edit is Some(_) { + // The screen is frozen under the screenshot overlay and editor: show it afterwards. release_snapshot(self.shot_frozen.get(wid)) self.shot_frozen.set(wid, s) } else { @@ -2329,6 +2341,10 @@ pub fn ChandraCompositor::desired_cursor(self : ChandraCompositor) -> UInt { Some(o) => return self.overlay_cursor(o) None => () } + match self.shot_edit { + Some(e) => return self.editor_cursor(e) + 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 a5adf54..a213739 100644 --- a/compositor/host/moon.pkg +++ b/compositor/host/moon.pkg @@ -1,6 +1,7 @@ import { "moonbitlang/core/builtin", "moonbitlang/core/encoding/utf8" @utf8, + "moonbitlang/core/math" @math, "chandra/desktop/lib/wm" @wm, "chandra/desktop/compositor/sys" @sys, "chandra/desktop/compositor/scene" @scene, @@ -9,6 +10,7 @@ import { "chandra/desktop/compositor/nested" @nested, "chandra/desktop/compositor/font" @font, "chandra/desktop/compositor/renderer" @renderer, + "chandra/desktop/compositor/raster" @raster, "chandra/desktop/compositor/wayland" @wayland, "chandra/desktop/compositor/gfx" @gfx, "chandra/desktop/compositor/network" @network, diff --git a/compositor/host/screenshot.mbt b/compositor/host/screenshot.mbt index f6c199f..d7153a6 100644 --- a/compositor/host/screenshot.mbt +++ b/compositor/host/screenshot.mbt @@ -12,9 +12,10 @@ /// 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 +/// It opens in the screenshot editor (shot_editor.mbt) for annotating, cropping and blurring; +/// from there 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. +/// thumbnail confirms it for a few seconds. Esc in the editor discards it. ///| evdev codes (keys on the overlay; the shortcuts themselves are in the shortcut table, /// compositor/shell/shortcuts.mbt, and can be rebound in Settings > Shortcuts). @@ -255,7 +256,7 @@ fn ChandraCompositor::active_window(self : ChandraCompositor) -> UInt64? { ///| 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(_) { + if self.shot is Some(_) || self.shot_edit is Some(_) { return } let frame = match self.freeze_screen() { @@ -304,6 +305,8 @@ fn ChandraCompositor::open_overlay(self : ChandraCompositor, frame : @renderer.P let prev_focus = self.kbd_win self.leave_pointer() self.set_kbd_focus(None) + // Clients stop drawing while the screen is frozen (they are sent their frame callbacks after). + self.server.set_hold_frames(true) self.shot = Some({ frame, pick, @@ -326,31 +329,52 @@ fn ChandraCompositor::open_overlay(self : ChandraCompositor, frame : @renderer.P ///| Take the overlay down: give the keyboard back and show what clients drew meanwhile. fn ChandraCompositor::close_overlay(self : ChandraCompositor) -> Unit { + self.close_overlay_to(false) +} + +///| Give the keyboard back to `prev` (the window that had it before a screenshot), or to the +/// active window when that one has gone. +fn ChandraCompositor::restore_focus(self : ChandraCompositor, prev : UInt64?) -> Unit { + match prev { + 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 => () + } +} + +///| Show what clients drew while the screen was frozen (under the overlay or the editor), and let +/// them draw again. +fn ChandraCompositor::thaw_windows(self : ChandraCompositor) -> Unit { + for wid, snap in self.shot_frozen { + match self.windows.get(wid) { + Some(win) => { + release_snapshot(win.surface) + win.surface = Some(snap) + self.thumb_stale(wid) + } + None => release_snapshot(Some(snap)) + } + } + self.shot_frozen.clear() + self.server.set_hold_frames(false) +} + +///| Take the overlay down. `to_editor`: the editor opens next, keeping the keyboard and the +/// frozen screen behind it; else give the keyboard back and show what clients drew meanwhile. +fn ChandraCompositor::close_overlay_to(self : ChandraCompositor, to_editor : Bool) -> 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) - self.thumb_stale(wid) - } - 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 => () + if !to_editor { + self.thaw_windows() + self.restore_focus(o.prev_focus) } self.damage.mark_full() } @@ -373,52 +397,61 @@ fn ShotOverlay::window_at(self : ShotOverlay, x : Int, y : Int) -> @scene.Rect? None } -///| Crop `r` out of `frame`, save it, put it on the clipboard and confirm with a notification. +///| Crop `r` out of `frame` and open it in the screenshot editor (or start recording `r`, when +/// the overlay was picking what to record). fn ChandraCompositor::finish_screenshot(self : ChandraCompositor, frame : @renderer.Pixmap, r : @scene.Rect) -> Unit { - let record = match self.shot { - Some(o) => o.record - None => false + let (record, prev_focus) = match self.shot { + Some(o) => (o.record, o.prev_focus) + None => (false, self.kbd_win) } - self.close_overlay() if record { + self.close_overlay() self.start_recording(r) return } + self.close_overlay_to(true) 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 { + self.thaw_windows() + self.restore_focus(prev_focus) return } let w = x1 - x0 let h = y1 - y0 - // `shot` is what the thumbnail is made from: the picture, or a small copy from the host. - let (shot, png) = match self.frame_shots { - Some(host) => { - let crop = @scene.Rect::new(x0, y0, w, h) - let (tw, th) = thumb_size(w, h, 96, 60) - ((host.pixels)(crop, tw, th), (host.png)(crop)) - } + let crop = @scene.Rect::new(x0, y0, w, h) + // The picture, opaque (the framebuffer's alpha means nothing in a saved picture). When the + // host holds the frozen screen it hands over this part of it, and encodes it itself when it is + // saved unchanged. + let (pic, host_png) = match self.frame_shots { + Some(host) => ((host.pixels)(crop, w, h), Some(fn() { (host.png)(crop) })) None => { 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 } - (shot, @renderer.encode_png_compressed(shot)) + ({ width: w, height: h, data }, None) } } + self.open_editor(pic, prev_focus, host_png) +} + +///| Put `png` (the picture `pic`) on the clipboard, save it when `save`, and confirm with a +/// notification. +fn ChandraCompositor::deliver_screenshot(self : ChandraCompositor, pic : @renderer.Pixmap, png : Bytes, save : Bool) -> Unit { 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) + let path = if save { save_png(dir, png) } else { "" } self.last_shot = path - let (thumb, tw, th) = thumbnail_ops(shot, 96, 60) - let (title, detail) = if path.length() > 0 { + let (thumb, tw, th) = thumbnail_ops(pic, 96, 60) + let (title, detail) = if !save { + ("Screenshot copied to clipboard", "Not saved") + } else if path.length() > 0 { ("Screenshot saved", base_name(path) + " · copied to clipboard") } else { ("Screenshot copied to clipboard", "Couldn't save it to " + dir) @@ -557,22 +590,30 @@ fn ChandraCompositor::screenshot_input(self : ChandraCompositor, ev : @nested.In Key(code, pressed) => self.screenshot_key(code, pressed) Modifiers(_, _, _, _) => false PointerMove(x, y) => - match self.shot { - Some(o) => { + match (self.shot, self.shot_edit) { + (Some(o), _) => { self.ptr_x = x self.ptr_y = y self.overlay_motion(o, x.to_int(), y.to_int()) true } - None => false + (None, Some(e)) => { + self.editor_input(e, ev) + true + } + (None, None) => false } PointerButton(button, pressed) => - match self.shot { - Some(o) => { + match (self.shot, self.shot_edit) { + (Some(o), _) => { self.overlay_button(o, button, pressed, time_ms) true } - None => + (None, Some(e)) => { + self.editor_input(e, ev) + true + } + (None, None) => if pressed && button == 272U && self.recording_click(self.ptr_x.to_int(), self.ptr_y.to_int()) { self.rec_press = true true @@ -583,14 +624,15 @@ fn ChandraCompositor::screenshot_input(self : ChandraCompositor, ev : @nested.In false } } - Scroll(_, _, _) => self.shot is Some(_) + Scroll(_, _, _) => self.shot is Some(_) || self.shot_edit is Some(_) } } ///| A key, for the overlay. fn ChandraCompositor::screenshot_key(self : ChandraCompositor, code : UInt, pressed : Bool) -> Bool { + let modal = self.shot is Some(_) || self.shot_edit is Some(_) if code == key_lsuper || code == key_rsuper { - if self.shot is Some(_) { + if modal { self.super_solo = false return true } @@ -602,16 +644,21 @@ fn ChandraCompositor::screenshot_key(self : ChandraCompositor, code : UInt, pres self.shot_swallow.retain(c => c != code) return true } - return self.shot is Some(_) + return modal } - match self.shot { - Some(o) => { + match (self.shot, self.shot_edit) { + (Some(o), _) => { self.shot_swallow.push(code) self.overlay_key(o, code, (self.mods & mod_shift) != 0U, (self.mods & mod_ctrl) != 0U) true } + (None, Some(e)) => { + self.shot_swallow.push(code) + self.editor_key(e, code) + true + } // The shortcuts that start screenshots and recordings are in the shortcut table (shortcuts.mbt). - None => false + (None, None) => false } } @@ -828,6 +875,10 @@ fn ChandraCompositor::screenshot_ops(self : ChandraCompositor) -> Array[@scene.D Some(o) => self.overlay_ops(o, ops) None => () } + match self.shot_edit { + Some(e) => self.editor_ops(e, ops) + None => () + } match self.shot_toast { Some(t) => if @sys.monotonic_ms() >= t.until { diff --git a/compositor/host/screenshot_test.mbt b/compositor/host/screenshot_test.mbt index 836f75d..216d1f6 100644 --- a/compositor/host/screenshot_test.mbt +++ b/compositor/host/screenshot_test.mbt @@ -36,6 +36,13 @@ fn png_size(png : Bytes) -> (Int, Int) { (be(16), be(20)) } +///| In the screenshot editor: press Enter (save and copy). +fn save_edit(comp : @host.ChandraCompositor, t : UInt) -> Unit raise { + assert_true(comp.screenshot_editing()) + key(comp, 28U, true, t) + key(comp, 28U, false, t + 1U) +} + ///| 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) @@ -71,10 +78,16 @@ test "super+shift+s: drag a region, Enter saves it as a PNG and puts it on the c 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. + // Enter takes it: the editor opens with it; nothing is saved yet. key(comp, 28U, true, 50U) key(comp, 28U, false, 51U) assert_false(comp.screenshot_active()) + assert_true(comp.screenshot_editing()) + assert_eq(comp.last_screenshot(), "") + ignore(comp.compose_frame()) + // Enter in the editor saves it. + save_edit(comp, 52U) + assert_false(comp.screenshot_editing()) let path = comp.last_screenshot() assert_true(path.has_prefix(dir + "/Screenshot_")) assert_true(path.has_suffix(".png")) @@ -92,10 +105,12 @@ test "print takes the full screen at once; a second one gets its own name" { key(comp, 99U, true, 1U) key(comp, 99U, false, 2U) assert_false(comp.screenshot_active()) + save_edit(comp, 3U) 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) + key(comp, 99U, true, 5U) + key(comp, 99U, false, 6U) + save_edit(comp, 7U) let second = comp.last_screenshot() assert_true(second.length() > 0 && second != first) } @@ -122,6 +137,7 @@ test "escape cancels the overlay; a click on a window selects it; W takes the ac // W takes the active window (B) instead. key(comp, 17U, true, 30U) key(comp, 17U, false, 31U) + save_edit(comp, 32U) let gb = comp.windows.get(2UL).unwrap().geometry assert_eq(png_size(@sys.read_file_bytes(comp.last_screenshot())), (gb.w + 2, gb.h + 39)) } @@ -139,6 +155,7 @@ test "the screenshot module's request waits for a frame, then opens the overlay" comp.screenshot_request(1) ignore(comp.compose_frame()) comp.step() + save_edit(comp, 1U) assert_eq(png_size(@sys.read_file_bytes(comp.last_screenshot())), (1280, 720)) } @@ -280,6 +297,7 @@ test "the screenshot panel module takes a full-screen shot without its popup in 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() + save_edit(comp, 6U) 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) diff --git a/compositor/host/shot_editor.mbt b/compositor/host/shot_editor.mbt new file mode 100644 index 0000000..460a2f1 --- /dev/null +++ b/compositor/host/shot_editor.mbt @@ -0,0 +1,864 @@ +///| The screenshot editor, after KDE Spectacle's annotation mode. Every screenshot opens here +/// once it is taken (screenshot.mbt `finish_screenshot`): the picture fills the screen, with the +/// tools above it and the colours, sizes, Undo/Redo and Discard / Copy / Save below. +/// +/// Tools: Arrow, Line, Rectangle, Ellipse, Pen, Highlighter, Text, Number (numbered markers), +/// Blur, Pixelate, Redact and Crop (annotate.mbt draws them). Drag to draw; Text and Number take +/// a click (type, then Enter or a click elsewhere). Keys: Enter or Ctrl+S saves the picture (where +/// screenshots always go) and copies it, Ctrl+C only copies it, Esc discards it; Ctrl+Z undoes, +/// Ctrl+Shift+Z or Ctrl+Y redoes; A L R E P H T N B X D C pick a tool, 1-8 a colour, [ and ] +/// the size. +/// +/// The editor is drawn by the compositor, on top of everything, and has the keyboard while it is +/// up (the window that had it gets it back). Windows behind it stay as they were: what clients +/// draw meanwhile is shown when it closes, and their frame callbacks wait until then, so they +/// stop drawing and cost nothing. Each finished annotation is drawn once into a full +/// size copy of the picture, which is shown as one image, so idle costs nothing and a frame +/// draws only the annotation being made. + +///| What a click on the editor's bars does. +priv enum EditHit { + PickTool(Tool) + PickColor(Int) + PickSize(Int) + Undo + Redo + Discard + CopyOnly + Save +} derive(Eq) + +///| The colours on offer. +let edit_colors : Array[@scene.Rgba] = [ + @scene.Rgba::from_hex("#e53935"), + @scene.Rgba::from_hex("#fb8c00"), + @scene.Rgba::from_hex("#fdd835"), + @scene.Rgba::from_hex("#43a047"), + @scene.Rgba::from_hex("#1e88e5"), + @scene.Rgba::from_hex("#8e24aa"), + @scene.Rgba::from_hex("#000000"), + @scene.Rgba::from_hex("#ffffff"), +] + +///| Stroke widths: thin, medium, thick. +let edit_widths : Array[Int] = [2, 4, 8] + +///| The tools in toolbar order: label and key (evdev code). +let edit_tools : Array[(Tool, String, UInt)] = [ + (Tool::Arrow, "Arrow", 30U), + (Tool::Line, "Line", 38U), + (Tool::Rectangle, "Rectangle", 19U), + (Tool::Ellipse, "Ellipse", 18U), + (Tool::Pen, "Pen", 25U), + (Tool::Highlighter, "Highlighter", 35U), + (Tool::Text, "Text", 20U), + (Tool::Number, "Number", 49U), + (Tool::Blur, "Blur", 48U), + (Tool::Pixelate, "Pixelate", 45U), + (Tool::Redact, "Redact", 32U), + (Tool::Crop, "Crop", 46U), +] + +///| evdev codes the editor uses beyond the tool letters. +let key_s : UInt = 31 + +///| +let key_z : UInt = 44 + +///| +let key_y : UInt = 21 + +///| +let key_lbrace : UInt = 26 + +///| +let key_rbrace : UInt = 27 + +///| The editor while it is up. +pub(all) struct ShotEditor { + /// The picture as taken (opaque). + base : @renderer.Pixmap + /// `base` with every annotation in `anns` drawn in (crops aside): what is shown and saved. + mut rendered : @renderer.Pixmap + anns : Array[Annotation] + /// Undone annotations, the last undone last. + redo : Array[Annotation] + mut tool : Tool + mut color : Int + mut size : Int + /// The annotation being drawn (or typed, when `typing`). + mut cur : Annotation? + mut typing : Bool + /// The window that had the keyboard before, given it back afterwards. + prev_focus : UInt64? + /// The host's PNG of the picture as taken (the host keeps the frozen screen), used when + /// nothing was changed; None encodes `rendered`. + host_png : (() -> Bytes)? + /// Where the picture is drawn and at what scale (picture pixels to screen pixels). + mut view : @scene.Rect + mut scale : Double + /// What the renderer holds of the picture: its size, rows per image and how many images. + mut shown : (Int, Int, Int, Int) + priv hits : Array[(@scene.Rect, EditHit)] +} + +///| The annotations made so far (undone ones not included). +pub fn ShotEditor::annotations(self : ShotEditor) -> Array[Annotation] { + self.anns +} + +///| The picture with the annotations so far, before cropping. +pub fn ShotEditor::picture(self : ShotEditor) -> @renderer.Pixmap { + self.rendered +} + +///| The tool in use. +pub fn ShotEditor::current_tool(self : ShotEditor) -> Tool { + self.tool +} + +///| What would be saved now. +pub fn ShotEditor::export(self : ShotEditor) -> @renderer.Pixmap { + crop_pixmap(self.rendered, final_crop(self.rendered.width, self.rendered.height, self.anns)) +} + +///| Where the picture is on screen, and its scale. +pub fn ShotEditor::view(self : ShotEditor) -> (@scene.Rect, Double) { + (self.view, self.scale) +} + +///| Whether the editor is up. +pub fn ChandraCompositor::screenshot_editing(self : ChandraCompositor) -> Bool { + self.shot_edit is Some(_) +} + +///| The editor, while it is up. +pub fn ChandraCompositor::screenshot_editor(self : ChandraCompositor) -> ShotEditor? { + self.shot_edit +} + +///| The most bytes sent to the renderer in one image: the wasm host copies a call's data under a +/// fixed budget (wasmtime's hostcall fuel), which a whole 1920 x 1080 picture (8 MB) runs out. +let strip_bytes : Int = 2 * 1024 * 1024 + +///| Show the picture in the editor: `rendered`, scaled to the size it is drawn at, sent to +/// whatever draws the screen as images of a few rows each (`strip_bytes`), drawn one under the +/// other at 1:1 so they meet without seams. +fn ChandraCompositor::editor_upload(self : ChandraCompositor, e : ShotEditor) -> Unit { + let vw = e.view.w + let vh = e.view.h + let p = if vw == e.rendered.width && vh == e.rendered.height { + e.rendered + } else { + @renderer.scale_pixmap(e.rendered, vw, vh) + } + let rows = (strip_bytes / (vw * 4)).max(1) + let n = (vh + rows - 1) / rows + let imgs = self.shot_edit_images + for i = 0; i < n; i = i + 1 { + let y0 = i * rows + let rh = rows.min(vh - y0) + let reuse = if i < imgs.length() { imgs[i] } else { 0U } + let strip = FixedArray::make(vw * rh * 4, b'\x00') + FixedArray::blit_to(p.data, strip, len=vw * rh * 4, src_offset=y0 * vw * 4) + let px = Bytes::from_fixedarray(strip) + let h = @raster.image_pixels(vw, rh, px, reuse) + if h == 0U { + // image-pixels refuses only sizes over 16384 pixels a side, which no screen has. + @sys.log("screenshot editor: the renderer refused a " + vw.to_string() + "x" + rh.to_string() + " image") + self.shot_toast = Some({ + title: "Screenshot editor can't show this picture", + detail: "the renderer refused a " + vw.to_string() + "x" + rh.to_string() + " image", + until: @sys.monotonic_ms() + 8000UL, + thumb: [], + tw: 0, + th: 0, + }) + } + if i < imgs.length() { + imgs[i] = h + } else { + imgs.push(h) + } + } + e.shown = (vw, vh, rows, n) + self.damage.mark_full() +} + +///| Open the editor on `pic` (an opaque picture just taken). `prev_focus`: the window to give +/// the keyboard back to. +fn ChandraCompositor::open_editor( + self : ChandraCompositor, + pic : @renderer.Pixmap, + prev_focus : UInt64?, + host_png : (() -> Bytes)?, +) -> Unit { + // Client menus would be drawn over the editor. + let mut j = self.popups.length() - 1 + while j >= 0 { + self.server.popup_done(self.popups[j].id) + j = j - 1 + } + self.leave_pointer() + self.set_kbd_focus(None) + self.server.set_hold_frames(true) + let e : ShotEditor = { + base: pic, + rendered: copy_pixmap(pic), + anns: [], + redo: [], + tool: self.shot_edit_tool, + color: self.shot_edit_color, + size: self.shot_edit_size, + cur: None, + typing: false, + prev_focus, + host_png, + view: @scene.Rect::new(0, 0, 0, 0), + scale: 1.0, + shown: (0, 0, 1, 0), + hits: [], + } + self.shot_edit = Some(e) + self.editor_layout(e) + self.editor_upload(e) +} + +///| Take the editor down and give the keyboard back. +fn ChandraCompositor::close_editor(self : ChandraCompositor) -> Unit { + match self.shot_edit { + Some(e) => { + self.shot_edit = None + // Remember the tool, colour and size for the next screenshot. + self.shot_edit_tool = e.tool + self.shot_edit_color = e.color + self.shot_edit_size = e.size + // Let the renderer drop the picture's memory (the handles are kept for the next one). + let imgs = self.shot_edit_images + for i = 0; i < imgs.length(); i = i + 1 { + if imgs[i] != 0U { + imgs[i] = @raster.image_pixels(1, 1, b"\x00\x00\x00\x00", imgs[i]) + } + } + self.thaw_windows() + self.restore_focus(e.prev_focus) + self.damage.mark_full() + } + None => () + } +} + +///| Discard the picture (Esc). +pub fn ChandraCompositor::discard_screenshot(self : ChandraCompositor) -> Unit { + self.close_editor() +} + +///| Copy the picture to the clipboard and, when `save`, save it; confirm with a notification. +fn ChandraCompositor::editor_finish(self : ChandraCompositor, e : ShotEditor, save : Bool) -> Unit { + self.commit_typing(e) + let (pic, png) = match e.host_png { + Some(f) if e.anns.length() == 0 => (e.base, f()) + _ => { + let p = e.export() + (p, @renderer.encode_png_compressed(p)) + } + } + self.close_editor() + self.deliver_screenshot(pic, png, save) +} + +///| A point on screen as a picture pixel, kept on the picture. +fn ShotEditor::to_pic(self : ShotEditor, x : Int, y : Int) -> (Int, Int) { + let px = ((x - self.view.x).to_double() / self.scale).floor().to_int() + let py = ((y - self.view.y).to_double() / self.scale).floor().to_int() + (px.clamp(min=0, max=self.base.width - 1), py.clamp(min=0, max=self.base.height - 1)) +} + +///| A picture position on screen. +fn ShotEditor::sx(self : ShotEditor, x : Double) -> Int { + (self.view.x.to_double() + x * self.scale).round().to_int() +} + +///| +fn ShotEditor::sy(self : ShotEditor, y : Double) -> Int { + (self.view.y.to_double() + y * self.scale).round().to_int() +} + +///| A picture rectangle on screen. +fn ShotEditor::srect(self : ShotEditor, r : @scene.Rect) -> @scene.Rect { + let x0 = self.sx(r.x.to_double()) + let y0 = self.sy(r.y.to_double()) + let x1 = self.sx((r.x + r.w).to_double()) + let y1 = self.sy((r.y + r.h).to_double()) + @scene.Rect::new(x0, y0, x1 - x0, y1 - y0) +} + +///| The toolbar's buttons' height, and the gap around the bars. +let bar_h : Int = 32 + +///| +let bar_gap : Int = 12 + +///| Lay out the bars and the picture for the screen's size (`hits` and `view`). +fn ChandraCompositor::editor_layout(self : ChandraCompositor, e : ShotEditor) -> Unit { + let sw = self.output_w + let sh = self.output_h + let fs = self.theme.font_size + e.hits.clear() + // Top: the tools, centred. + let pad = 12 + let widths = edit_tools.map(t => @renderer.text_width(t.1, fs, false, false) + pad * 2) + let total = widths.fold(init=0, (a, w) => a + w) + 4 * (widths.length() - 1) + let mut x = ((sw - total) / 2).max(4) + for i, t in edit_tools { + e.hits.push((@scene.Rect::new(x, bar_gap, widths[i], bar_h), EditHit::PickTool(t.0))) + x = x + widths[i] + 4 + } + // Bottom left: colours, sizes, Undo, Redo. + let by = sh - bar_gap - bar_h + let mut bx = bar_gap + for i = 0; i < edit_colors.length(); i = i + 1 { + e.hits.push((@scene.Rect::new(bx, by, bar_h, bar_h), EditHit::PickColor(i))) + bx = bx + bar_h + 2 + } + bx = bx + 14 + for i = 0; i < edit_widths.length(); i = i + 1 { + e.hits.push((@scene.Rect::new(bx, by, bar_h, bar_h), EditHit::PickSize(i))) + bx = bx + bar_h + 2 + } + bx = bx + 14 + for b in [("Undo", EditHit::Undo), ("Redo", EditHit::Redo)] { + let w = @renderer.text_width(b.0, fs, false, false) + pad * 2 + e.hits.push((@scene.Rect::new(bx, by, w, bar_h), b.1)) + bx = bx + w + 4 + } + // Bottom right: Discard, Copy, Save. + let mut rx = sw - bar_gap + for b in [("Save", EditHit::Save), ("Copy", EditHit::CopyOnly), ("Discard", EditHit::Discard)] { + let w = @renderer.text_width(b.0, fs, true, false) + pad * 2 + 8 + rx = rx - w + e.hits.push((@scene.Rect::new(rx, by, w, bar_h), b.1)) + rx = rx - 6 + } + // The picture: as big as fits between the bars, never enlarged. + let top = bar_gap + bar_h + fs + 20 + let bottom = by - 12 + let aw = (sw - 2 * bar_gap).max(1) + let ah = (bottom - top).max(1) + let pw = e.base.width + let ph = e.base.height + let scale = (aw.to_double() / pw.to_double()).min(ah.to_double() / ph.to_double()).min(1.0) + let vw = (pw.to_double() * scale).round().to_int().max(1) + let vh = (ph.to_double() * scale).round().to_int().max(1) + e.view = @scene.Rect::new((sw - vw) / 2, top + (ah - vh) / 2, vw, vh) + e.scale = vw.to_double() / pw.to_double() +} + +///| The button under (x, y). +fn ShotEditor::hit_at(self : ShotEditor, x : Int, y : Int) -> EditHit? { + for h in self.hits { + if h.0.contains(x, y) { + return Some(h.1) + } + } + None +} + +///| A new annotation with the current tool, colour and size at `pt`. +fn ShotEditor::start(self : ShotEditor, pt : (Int, Int), number : Int) -> Annotation { + let color = if self.tool == Redact { edit_colors[self.color].with_alpha(255) } else { edit_colors[self.color] } + { tool: self.tool, color, width: edit_widths[self.size], points: [pt, pt], text: "", number } +} + +///| The next number marker's number. +fn ShotEditor::next_number(self : ShotEditor) -> Int { + self.anns.filter(a => a.tool == Number).length() + 1 +} + +///| Add `a` to the picture. +fn ChandraCompositor::editor_commit(self : ChandraCompositor, e : ShotEditor, a : Annotation) -> Unit { + apply_annotation(e.rendered, a) + e.anns.push(a) + e.redo.clear() + self.editor_upload(e) +} + +///| Redraw the picture from the one taken (after an undo). +fn ChandraCompositor::editor_rebuild(self : ChandraCompositor, e : ShotEditor) -> Unit { + let p = copy_pixmap(e.base) + for a in e.anns { + apply_annotation(p, a) + } + e.rendered = p + self.editor_upload(e) +} + +///| Undo the last annotation. +pub fn ChandraCompositor::editor_undo(self : ChandraCompositor) -> Unit { + match self.shot_edit { + Some(e) => { + e.cur = None + e.typing = false + match e.anns.pop() { + Some(a) => { + e.redo.push(a) + self.editor_rebuild(e) + } + None => () + } + } + None => () + } +} + +///| Redo the last undone annotation. +pub fn ChandraCompositor::editor_redo(self : ChandraCompositor) -> Unit { + match self.shot_edit { + Some(e) => { + self.commit_typing(e) + match e.redo.pop() { + Some(a) => { + apply_annotation(e.rendered, a) + e.anns.push(a) + self.editor_upload(e) + } + None => () + } + } + None => () + } +} + +///| Finish the text being typed (dropped when empty). +fn ChandraCompositor::commit_typing(self : ChandraCompositor, e : ShotEditor) -> Unit { + if !e.typing { + return + } + e.typing = false + match e.cur { + Some(a) => { + e.cur = None + if a.text.length() > 0 { + self.editor_commit(e, a) + } else { + self.damage.mark_full() + } + } + None => () + } +} + +///| Pick a tool (ends any text being typed). +fn ChandraCompositor::editor_pick_tool(self : ChandraCompositor, e : ShotEditor, t : Tool) -> Unit { + self.commit_typing(e) + e.tool = t + self.damage.mark_full() +} + +///| Do what a bar button does. +fn ChandraCompositor::editor_hit(self : ChandraCompositor, e : ShotEditor, h : EditHit) -> Unit { + match h { + PickTool(t) => self.editor_pick_tool(e, t) + PickColor(i) => { + e.color = i + self.damage.mark_full() + } + PickSize(i) => { + e.size = i + self.damage.mark_full() + } + Undo => self.editor_undo() + Redo => self.editor_redo() + Discard => self.close_editor() + CopyOnly => self.editor_finish(e, false) + Save => self.editor_finish(e, true) + } +} + +///| Input while the editor is up: it takes everything. +fn ChandraCompositor::editor_input(self : ChandraCompositor, e : ShotEditor, ev : @nested.InputEvent) -> Unit { + match ev { + PointerMove(x, y) => { + self.ptr_x = x + self.ptr_y = y + if e.typing { + return + } + match e.cur { + Some(a) => { + let pt = e.to_pic(x.to_int(), y.to_int()) + if a.tool == Pen || a.tool == Highlighter { + if a.points[a.points.length() - 1] != pt { + // The first two points start out the same: the press. + if a.points.length() == 2 && a.points[0] == a.points[1] { + a.points[1] = pt + } else { + a.points.push(pt) + } + } + } else { + a.points[a.points.length() - 1] = pt + } + self.damage.mark_full() + } + None => () + } + } + PointerButton(button, pressed) => { + let x = self.ptr_x.to_int() + let y = self.ptr_y.to_int() + if button == 273U { + // Right button: drop what is being drawn. + if pressed && e.cur is Some(_) { + e.cur = None + e.typing = false + self.damage.mark_full() + } + return + } + if button != 272U { + return + } + if pressed { + match e.hit_at(x, y) { + Some(h) => { + self.editor_hit(e, h) + return + } + None => () + } + if e.typing { + // A click elsewhere finishes the text. + self.commit_typing(e) + return + } + let v = e.view + if x < v.x - 8 || y < v.y - 8 || x >= v.x + v.w + 8 || y >= v.y + v.h + 8 { + return + } + let pt = e.to_pic(x, y) + match e.tool { + Text => { + e.cur = Some({ ..e.start(pt, 0), points: [pt] }) + e.typing = true + } + Number => self.editor_commit(e, { ..e.start(pt, e.next_number()), points: [pt] }) + _ => e.cur = Some(e.start(pt, 0)) + } + self.damage.mark_full() + } else { + if e.typing { + return + } + match e.cur { + Some(a) => { + e.cur = None + if annotation_ready(a) { + self.editor_commit(e, a) + } else { + self.damage.mark_full() + } + } + None => () + } + } + } + _ => () + } +} + +///| Whether a drawn annotation is big enough to keep (a click without a drag isn't a shape). +fn annotation_ready(a : Annotation) -> Bool { + match a.tool { + Pen | Highlighter => true + Arrow | Line => { + let (x0, y0) = a.points[0] + let (x1, y1) = a.points[a.points.length() - 1] + (x1 - x0).abs() + (y1 - y0).abs() >= 3 + } + Text => a.text.length() > 0 + Number => true + _ => { + let r = a.rect() + r.w >= 2 && r.h >= 2 + } + } +} + +///| A key press while the editor is up. +fn ChandraCompositor::editor_key(self : ChandraCompositor, e : ShotEditor, code : UInt) -> Unit { + let ctrl = (self.mods & mod_ctrl) != 0U + let shift = (self.mods & mod_shift) != 0U + if e.typing { + match e.cur { + Some(a) => + if code == key_esc { + e.cur = None + e.typing = false + } else if code == key_enter || code == key_kp_enter { + self.commit_typing(e) + } else if code == key_backspace { + // Drop the last character. + let chars : Array[Char] = [] + for ch in a.text { + chars.push(ch) + } + ignore(chars.pop()) + let buf = StringBuilder::new() + for ch in chars { + buf.write_char(ch) + } + a.text = buf.to_string() + } else if !ctrl { + let mods = self.mods | self.mods_latched | self.mods_locked + match self.auth_keymap().char_for(code, mods, self.mods_group) { + Some(ch) => if ch.to_int() >= 32 && ch.to_int() != 127 { a.text = a.text + ch.to_string() } + None => () + } + } + None => e.typing = false + } + self.damage.mark_full() + return + } + if code == key_esc { + if e.cur is Some(_) { + e.cur = None + self.damage.mark_full() + } else { + self.close_editor() + } + } else if code == key_enter || code == key_kp_enter || (ctrl && code == key_s) { + self.editor_finish(e, true) + } else if ctrl && code == key_c { + self.editor_finish(e, false) + } else if ctrl && code == key_z && !shift { + self.editor_undo() + } else if ctrl && ((code == key_z && shift) || code == key_y) { + self.editor_redo() + } else if ctrl { + () + } else if code >= 2U && code < 2U + edit_colors.length().reinterpret_as_uint() { + e.color = (code - 2U).reinterpret_as_int() + self.damage.mark_full() + } else if code == key_lbrace { + e.size = (e.size - 1).max(0) + self.damage.mark_full() + } else if code == key_rbrace { + e.size = (e.size + 1).min(edit_widths.length() - 1) + self.damage.mark_full() + } else { + for t in edit_tools { + if t.2 == code { + self.editor_pick_tool(e, t.0) + return + } + } + } +} + +///| Cursor shape over the editor: a hand over buttons, an I-beam for text, else a crosshair +/// over the picture. +fn ChandraCompositor::editor_cursor(self : ChandraCompositor, e : ShotEditor) -> UInt { + let x = self.ptr_x.to_int() + let y = self.ptr_y.to_int() + if e.hit_at(x, y) is Some(_) { + return 4U // pointer + } + if e.view.contains(x, y) { + return if e.tool == Text { 9U } else { 8U } // text / crosshair + } + 1U +} + +///| A dashed outline of `r` (crop and region tools while they are drawn). +fn dashed_rect(r : @scene.Rect, c : @scene.Rgba, ops : Array[@scene.DrawOp]) -> Unit { + let dash = 6 + let mut x = r.x + while x < r.x + r.w { + let l = dash.min(r.x + r.w - x) + ops.push(@scene.DrawOp::FillRect(@scene.Rect::new(x, r.y, l, 1), c, 0)) + ops.push(@scene.DrawOp::FillRect(@scene.Rect::new(x, r.y + r.h - 1, l, 1), c, 0)) + x = x + dash * 2 + } + let mut y = r.y + while y < r.y + r.h { + let l = dash.min(r.y + r.h - y) + ops.push(@scene.DrawOp::FillRect(@scene.Rect::new(r.x, y, 1, l), c, 0)) + ops.push(@scene.DrawOp::FillRect(@scene.Rect::new(r.x + r.w - 1, y, 1, l), c, 0)) + y = y + dash * 2 + } +} + +///| Draw ops showing annotation `a` (being drawn) over the picture: the same shapes `apply_annotation` +/// will put in, at the picture's scale. +fn ChandraCompositor::annotation_preview(self : ChandraCompositor, e : ShotEditor, a : Annotation, ops : Array[@scene.DrawOp]) -> Unit { + let s = e.scale + let lw = (a.width.to_double() * s).round().to_int().max(1) + let pt = fn(p : (Int, Int)) { (e.sx(p.0.to_double() + 0.5), e.sy(p.1.to_double() + 0.5)) } + let line = fn(p : (Int, Int), q : (Int, Int), c : @scene.Rgba, w : Int) { + let (x0, y0) = pt(p) + let (x1, y1) = pt(q) + ops.push(@scene.DrawOp::Line(x0, y0, x1, y1, c, w)) + } + let poly = fn(pts : Array[(Int, Int)], c : @scene.Rgba, w : Int) { + if pts.length() == 1 { + let (x, y) = pt(pts[0]) + ops.push(@scene.DrawOp::Circle(x, y, (w / 2).max(1), c, true)) + } + for i = 1; i < pts.length(); i = i + 1 { + line(pts[i - 1], pts[i], c, w) + } + } + let first = a.points[0] + let last = a.points[a.points.length() - 1] + match a.tool { + Line => line(first, last, a.color, lw) + Arrow => { + let (fx, fy) = centre(first) + let (lx, ly) = centre(last) + let (tip, b1, b2, shaft) = arrow_head(fx, fy, lx, ly, a.width) + let (x0, y0) = pt(first) + ops.push(@scene.DrawOp::Line(x0, y0, e.sx(shaft.0), e.sy(shaft.1), a.color, lw)) + // The head as a fan of lines from the tip to its base. + let n = 12 + for i = 0; i <= n; i = i + 1 { + let t = i.to_double() / n.to_double() + let bx = b1.0 + (b2.0 - b1.0) * t + let by = b1.1 + (b2.1 - b1.1) * t + ops.push(@scene.DrawOp::Line(e.sx(tip.0), e.sy(tip.1), e.sx(bx), e.sy(by), a.color, 2)) + } + } + Rectangle => { + let r = a.rect() + poly([(r.x, r.y), (r.x + r.w, r.y), (r.x + r.w, r.y + r.h), (r.x, r.y + r.h), (r.x, r.y)], a.color, lw) + } + Ellipse => poly(ellipse_points(a.rect()), a.color, lw) + Pen => poly(a.points, a.color, lw) + Highlighter => + poly(a.points, a.color.with_alpha(highlighter_alpha), (highlighter_half(a.width) * 2.0 * s).round().to_int().max(1)) + Text => { + let (x, y) = (e.sx(first.0.to_double()), e.sy(first.1.to_double())) + let size = (annotation_text_size(a.width).to_double() * s).round().to_int().max(6) + let tw = @renderer.text_width(a.text, size, false, false) + ops.push(@scene.DrawOp::Text(x, y, a.text, size, a.color, @scene.TextAlign::Left, false)) + // The caret, and a dashed box around what is typed. + ops.push(@scene.DrawOp::FillRect(@scene.Rect::new(x + tw + 1, y - size / 2 - 2, 2, size + 4), a.color, 0)) + dashed_rect(@scene.Rect::new(x - 4, y - size / 2 - 6, tw + 12, size + 12), self.theme.palette.accent, ops) + } + Number => () + Redact => ops.push(@scene.DrawOp::FillRect(e.srect(a.rect()), a.color.with_alpha(255), 0)) + Blur | Pixelate => { + let r = e.srect(a.rect()) + ops.push(@scene.DrawOp::FillRect(r, @scene.Rgba::new(128, 128, 128, 140), 0)) + dashed_rect(r, self.theme.palette.accent, ops) + if r.w > 60 && r.h > 24 { + ops.push(@scene.DrawOp::Text(r.x + r.w / 2, r.y + r.h / 2, if a.tool == Blur { "Blur" } else { "Pixelate" }, self.theme.font_size, @scene.Rgba::new(255, 255, 255, 255), @scene.TextAlign::Center, true)) + } + } + Crop => () + } +} + +///| The editor's draw ops. +fn ChandraCompositor::editor_ops(self : ChandraCompositor, e : ShotEditor, ops : Array[@scene.DrawOp]) -> Unit { + self.editor_layout(e) + let p = self.theme.palette + let fs = self.theme.font_size + let sw = self.output_w + let sh = self.output_h + ops.push(@scene.DrawOp::FillRect(@scene.Rect::new(0, 0, sw, sh), @scene.Rgba::new(28, 28, 32, 255), 0)) + // The picture. + let v = e.view + ops.push(@scene.DrawOp::StrokeRect(@scene.Rect::new(v.x - 1, v.y - 1, v.w + 2, v.h + 2), @scene.Rgba::new(255, 255, 255, 40), 1, 0)) + if e.shown.0 != v.w || e.shown.1 != v.h { + self.editor_upload(e) // the screen changed size + } + let (_, _, rows, n) = e.shown + for i = 0; i < n; i = i + 1 { + let h = self.shot_edit_images[i] + if h != 0U { + ops.push(@scene.DrawOp::Image(@scene.Rect::new(v.x, v.y + i * rows, v.w, rows.min(v.h - i * rows)), h)) + } + } + // The crop: the one being drawn, else the last one made. + let crop = match e.cur { + Some(a) if a.tool == Crop => Some(a.rect()) + _ => { + let r = final_crop(e.base.width, e.base.height, e.anns) + if r.w == e.base.width && r.h == e.base.height { None } else { Some(r) } + } + } + match crop { + Some(r) => { + let c = e.srect(r) + let dim = @scene.Rgba::new(0, 0, 0, 150) + ops.push(@scene.DrawOp::FillRect(@scene.Rect::new(v.x, v.y, v.w, c.y - v.y), dim, 0)) + ops.push(@scene.DrawOp::FillRect(@scene.Rect::new(v.x, c.y + c.h, v.w, v.y + v.h - c.y - c.h), dim, 0)) + ops.push(@scene.DrawOp::FillRect(@scene.Rect::new(v.x, c.y, c.x - v.x, c.h), dim, 0)) + ops.push(@scene.DrawOp::FillRect(@scene.Rect::new(c.x + c.w, c.y, v.x + v.w - c.x - c.w, c.h), dim, 0)) + dashed_rect(c, @scene.Rgba::new(255, 255, 255, 230), ops) + ops.push(@scene.DrawOp::Text(c.x + 4, c.y - fs / 2 - 6, r.w.to_string() + " × " + r.h.to_string(), fs - 2, @scene.Rgba::new(255, 255, 255, 230), @scene.TextAlign::Left, false)) + } + None => () + } + match e.cur { + Some(a) => { + ops.push(@scene.DrawOp::PushClip(v)) + self.annotation_preview(e, a, ops) + ops.push(@scene.DrawOp::PopClip) + } + None => () + } + // The bars. + let hint = "Enter: save and copy Ctrl+C: copy Esc: discard Ctrl+Z / Ctrl+Shift+Z: undo / redo " + + "A L R E P H T N B X D C: tools 1-8: colour [ ]: size" + ops.push(@scene.DrawOp::Text(sw / 2, bar_gap + bar_h + 6 + fs / 2, hint, fs - 2, @scene.Rgba::new(200, 200, 210, 255), @scene.TextAlign::Center, false)) + for h in e.hits { + let r = h.0 + let hover = r.contains(self.ptr_x.to_int(), self.ptr_y.to_int()) + match h.1 { + PickTool(t) => { + let on = t == e.tool + let label = edit_tools.filter(x => x.0 == t)[0].1 + ops.push(@scene.DrawOp::FillRect(r, if on { p.accent } else if hover { p.surface_hover } else { p.surface_popup }, self.theme.radius)) + ops.push(@scene.DrawOp::Text(r.x + r.w / 2, r.y + r.h / 2, label, fs, if on { p.accent_foreground } else { p.foreground }, @scene.TextAlign::Center, on)) + } + PickColor(i) => { + if i == e.color { + ops.push(@scene.DrawOp::FillRect(r, p.surface_popup, self.theme.radius)) + ops.push(@scene.DrawOp::StrokeRect(r, p.accent, 2, self.theme.radius)) + } + ops.push(@scene.DrawOp::Circle(r.x + r.w / 2, r.y + r.h / 2, 10, edit_colors[i], true)) + ops.push(@scene.DrawOp::Circle(r.x + r.w / 2, r.y + r.h / 2, 10, @scene.Rgba::new(255, 255, 255, 90), false)) + } + PickSize(i) => { + ops.push(@scene.DrawOp::FillRect(r, if i == e.size { p.accent } else if hover { p.surface_hover } else { p.surface_popup }, self.theme.radius)) + let fg = if i == e.size { p.accent_foreground } else { p.foreground } + ops.push(@scene.DrawOp::Circle(r.x + r.w / 2, r.y + r.h / 2, edit_widths[i] / 2 + 2, fg, true)) + } + Undo | Redo | Discard | CopyOnly => { + let label = match h.1 { + Undo => "Undo" + Redo => "Redo" + Discard => "Discard" + _ => "Copy" + } + let enabled = match h.1 { + Undo => e.anns.length() > 0 + Redo => e.redo.length() > 0 + _ => true + } + ops.push(@scene.DrawOp::FillRect(r, if hover && enabled { p.surface_hover } else { p.surface_popup }, self.theme.radius)) + ops.push(@scene.DrawOp::Text(r.x + r.w / 2, r.y + r.h / 2, label, fs, if enabled { p.foreground } else { p.foreground_muted }, @scene.TextAlign::Center, false)) + } + Save => { + ops.push(@scene.DrawOp::FillRect(r, p.accent, self.theme.radius)) + ops.push(@scene.DrawOp::Text(r.x + r.w / 2, r.y + r.h / 2, "Save", fs, p.accent_foreground, @scene.TextAlign::Center, true)) + } + } + } + // The picture's size (as it will be saved) in the middle of the bottom bar. + let out = final_crop(e.base.width, e.base.height, e.anns) + ops.push(@scene.DrawOp::Text(sw / 2, sh - bar_gap - bar_h / 2, out.w.to_string() + " × " + out.h.to_string(), fs - 2, @scene.Rgba::new(200, 200, 210, 255), @scene.TextAlign::Center, false)) +} diff --git a/compositor/raster/raster_native.mbt b/compositor/raster/raster_native.mbt index 9fcc8f3..6e53ade 100644 --- a/compositor/raster/raster_native.mbt +++ b/compositor/raster/raster_native.mbt @@ -43,7 +43,7 @@ pub fn snapshot_pixels(_r : @scene.Rect, _w : Int, _h : Int) -> @renderer.Pixmap ///| `w` x `h` RGBA pixels as an image (`reuse`: an earlier handle of this kind to overwrite, or 0). pub fn image_pixels(w : Int, h : Int, rgba : Bytes, reuse : UInt) -> UInt { - if w <= 0 || h <= 0 || w > 1024 || h > 1024 || rgba.length() < w * h * 4 { + if w <= 0 || h <= 0 || w > 16384 || h > 16384 || rgba.length() < w * h * 4 { return 0U } let p : @renderer.Pixmap = { width: w, height: h, data: rgba.to_fixedarray() } diff --git a/compositor/wayland/server.mbt b/compositor/wayland/server.mbt index 06282fb..50e3115 100644 --- a/compositor/wayland/server.mbt +++ b/compositor/wayland/server.mbt @@ -359,6 +359,10 @@ pub(all) struct WaylandServer { /// Drag and drop in progress (dnd.mbt), and a drop its target is still taking. mut drag : DragState? mut drop_pending : DropState? + /// While the screen is frozen (screenshot overlay and editor) frame callbacks are held back, + /// so clients stop drawing frames nobody sees: (client id, callback id), sent on release. + mut hold_frames : Bool + held_frames : Array[(UInt, UInt)] } ///| @@ -392,9 +396,35 @@ pub fn WaylandServer::listen( debug_configure: @sys.getenv("CHANDRA_DEBUG_CONFIGURE").length() > 0, drag: None, drop_pending: None, + hold_frames: false, + held_frames: [], }) } +///| Tell a client its frame callback `cb_id` is done. +fn WaylandServer::frame_done(self : WaylandServer, c : ClientConn, cb_id : UInt) -> Unit { + let fw = WireWriter::new() + fw.u32(self.next_serial()) + c.send_msg(fw.finish_msg(cb_id, 0U)) + send_delete_id(c, cb_id) +} + +///| Hold frame callbacks back (`on`), or send the ones held to the clients still connected. +pub fn WaylandServer::set_hold_frames(self : WaylandServer, on : Bool) -> Unit { + self.hold_frames = on + if on { + return + } + for h in self.held_frames { + for c in self.clients { + if c.client_id == h.0 { + self.frame_done(c, h.1) + } + } + } + self.held_frames.clear() +} + ///| pub fn WaylandServer::close(self : WaylandServer) -> Unit { for t in self.transfers { @@ -809,10 +839,11 @@ fn WaylandServer::dispatch_msg( match surf.pending_frame_cb { Some(cb_id) => { surf.pending_frame_cb = None - let fw = WireWriter::new() - fw.u32(self.next_serial()) - c.send_msg(fw.finish_msg(cb_id, 0U)) - send_delete_id(c, cb_id) + if self.hold_frames { + self.held_frames.push((c.client_id, cb_id)) + } else { + self.frame_done(c, cb_id) + } } None => () } diff --git a/docs/screenshot-editor.md b/docs/screenshot-editor.md new file mode 100644 index 0000000..67fb387 --- /dev/null +++ b/docs/screenshot-editor.md @@ -0,0 +1,82 @@ +# Screenshot editor + +Every screenshot (Super+Shift+S, Print, Super+Print, Super+Ctrl+Print, or the Screenshot panel +module) opens in the editor before it is saved, after KDE Spectacle's annotation mode. The +picture fills the screen. The tools are above it, and the colours, sizes, Undo/Redo and the +Discard / Copy / Save buttons are below it. + +![Screenshot editor](screenshots/screenshot-editor.png) + +## Tools + +| Tool | Key | What it does | +|---|---|---| +| Arrow | A | Drag from the tail to the tip | +| Line | L | Drag | +| Rectangle | R | Drag an outline | +| Ellipse | E | Drag an outline (fits the dragged box) | +| Pen | P | Draw freehand | +| Highlighter | H | Freehand, wide and translucent, even where the stroke crosses itself | +| Text | T | Click, type, then Enter or a click elsewhere (Backspace deletes, Esc drops it) | +| Number | N | Click to drop a numbered disc: 1, 2, 3, ... | +| Blur | B | Drag a box: its content is destroyed (see below) | +| Pixelate | X | Drag a box: blocks of one colour (block size follows the size setting) | +| Redact | D | Drag a box: an opaque box in the chosen colour | +| Crop | C | Drag the part to keep; the last crop counts and can be undone | + +Colours: 1-8 (red, orange, yellow, green, blue, purple, black, white). Size: `[` and `]` +(thin, medium, thick); text, markers and pixel blocks grow with it. The editor remembers the +tool, colour and size for the next screenshot. + +## Keys + +| Keys | Action | +|---|---| +| Enter, Ctrl+S, Save button | Save to `~/Pictures/Screenshots/` (XDG_PICTURES_DIR) and copy to the clipboard | +| Ctrl+C, Copy button | Copy to the clipboard only, no file | +| Esc, Discard button | Discard (Esc first drops a shape or text being made) | +| Ctrl+Z / Ctrl+Shift+Z, Ctrl+Y | Undo / redo | +| Right-click | Drop the shape being drawn | + +## Hiding things for real + +Annotations are drawn into the picture's pixels at full size the moment you finish them, and the +editor shows that picture, so what you see is what is saved. + +- **Redact** paints every pixel of the box in the chosen colour with full opacity. +- **Pixelate** replaces each block with its average colour. +- **Blur** first replaces each 6 x 6 block with its average (the detail is gone at that point), + then runs three box-blur passes each way with a radius of a sixth of the box's smaller side + (6 to 24 px). It reads and writes only the pixels inside the box. + +`compositor/host/annotate_test.mbt` checks this pixel by pixel. Pixels outside the box don't +change. Two different patterns with the same average blur to the same result. A blurred "word" +ends up flat, with neighbouring columns at most 4 levels apart (the word was 220 levels darker than its background). Redact stays opaque over a +translucent picture. + +## How it is built + +The editor is drawn by the compositor (`compositor/host/shot_editor.mbt`), like the selection +overlay, rather than being a separate component window: + +- The picture is already there. When the host holds the frozen screen (the wasm compositor), the + selected part is handed over once with `snapshot-pixels`. +- The keyboard has a single owner: the editor takes it, and the window that had it gets it back + when the editor closes. +- On the CPU: each finished annotation is drawn once into a full-size copy of the picture + (`annotate.mbt`). That copy is scaled to the size it is shown at and handed to the renderer + as a few images of at most 2 MB each (`raster.image-pixels`), drawn 1:1 one under the other. + A single 8 MB call runs out wasmtime's hostcall fuel and kills the wasm host. A frame then + draws only the annotation in progress as plain draw ops, and nothing is redrawn while you + aren't drawing. Undo redraws the picture from the original. +- The windows behind are frozen, as under the selection overlay. Their commits are shown when + the editor closes, and their frame callbacks are held back until then + (`WaylandServer::set_hold_frames`), so apps stop drawing frames nobody sees. Measured on the + wasm host at 1920x1080 with an app redrawing full screen behind the editor: 0% CPU, against + 52% for the same app on the desktop. +- A picture saved unchanged is encoded by the host (`snapshot-png`), as before. An edited one is + encoded with `@renderer.encode_png_compressed`. + +Headless pictures of the editor: run the host tests with `CHANDRA_EDITOR_SHOTS=` set, +and the test "editor: headless screenshots" writes `screenshot-editor.png` (the editor) and +`screenshot-editor-saved.png` (what it would save) there. diff --git a/docs/screenshots/screenshot-editor.png b/docs/screenshots/screenshot-editor.png new file mode 100644 index 0000000..e005ae3 Binary files /dev/null and b/docs/screenshots/screenshot-editor.png differ diff --git a/wasmhost/bin/raster_stub.c b/wasmhost/bin/raster_stub.c index dade7ef..57607ab 100644 --- a/wasmhost/bin/raster_stub.c +++ b/wasmhost/bin/raster_stub.c @@ -345,7 +345,7 @@ void rs_draw_glyph(int32_t slot, int32_t cp, int32_t size, int32_t pen, int32_t /* ------------------------------------------------------------------ images */ -#define MAX_IMAGE 1024 +#define MAX_IMAGE 16384 typedef struct Sized { int32_t w, h; uint8_t *rgba; struct Sized *next; } Sized; typedef struct { diff --git a/wasmhost/wt/wt_stub.c b/wasmhost/wt/wt_stub.c index 923e07a..12cfc29 100644 --- a/wasmhost/wt/wt_stub.c +++ b/wasmhost/wt/wt_stub.c @@ -37,7 +37,7 @@ static wasmtime_component_t *component; static wasmtime_component_instance_t instance; static int have_instance; static wt_dispatch_t dispatch; -static char last_error[1024]; +static char last_error[16384]; /* wasmtime backtraces are long; the cause comes last */ static void set_error(const char *what, wasmtime_error_t *e) { if (!e) {