From bed6d549a388212ee0795c3a51923ebc5874e37b Mon Sep 17 00:00:00 2001 From: Devan <68340659+DevanMetz@users.noreply.github.com> Date: Tue, 27 Oct 2026 18:03:48 -0500 Subject: [PATCH 1/4] Map snip selections in desktop pixels per monitor A 1x screen beside a 2x screen cannot share one scale. The new map crops a matching frame 1:1, including monitors at negative coordinates, and spreads any other frame uniformly across the desktop. Arrow keys move one desktop pixel. --- .github/workflows/build.yml | 3 + linux/AssemblyInfo.cs | 3 + linux/MonitorMap.cs | 282 +++++++++++++++++++++ linux/SnipSession.cs | 145 +++++++++++ tests/OpenSnip.Tests/MonitorMapTests.cs | 138 ++++++++++ tests/OpenSnip.Tests/OpenSnip.Tests.csproj | 25 ++ tests/OpenSnip.Tests/SnipSessionTests.cs | 116 +++++++++ 7 files changed, 712 insertions(+) create mode 100644 linux/AssemblyInfo.cs create mode 100644 linux/MonitorMap.cs create mode 100644 linux/SnipSession.cs create mode 100644 tests/OpenSnip.Tests/MonitorMapTests.cs create mode 100644 tests/OpenSnip.Tests/OpenSnip.Tests.csproj create mode 100644 tests/OpenSnip.Tests/SnipSessionTests.cs diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 07db7a9..4bca468 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -47,6 +47,9 @@ jobs: with: dotnet-version: 9.0.x + - name: Test + run: dotnet test tests/OpenSnip.Tests/OpenSnip.Tests.csproj -c Release --nologo + - name: Publish run: dotnet publish linux/OpenSnip.Linux.csproj -c Release -r linux-x64 --self-contained true -p:PublishSingleFile=true -p:IncludeNativeLibrariesForSelfExtract=true -p:EnableCompressionInSingleFile=true -p:DebugType=none -o dist/linux diff --git a/linux/AssemblyInfo.cs b/linux/AssemblyInfo.cs new file mode 100644 index 0000000..2a2947a --- /dev/null +++ b/linux/AssemblyInfo.cs @@ -0,0 +1,3 @@ +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("OpenSnip.Tests")] diff --git a/linux/MonitorMap.cs b/linux/MonitorMap.cs new file mode 100644 index 0000000..af66597 --- /dev/null +++ b/linux/MonitorMap.cs @@ -0,0 +1,282 @@ +using Avalonia; + +namespace OpenSnip; + +/// +/// One monitor in desktop pixels, the same space as Avalonia Screen.Bounds. +/// is that screen's scale (physical pixels per DIP). +/// +readonly record struct MonitorLayout(PixelRect Bounds, double Scale, bool Primary) +{ + public double ScaleOrOne => Scale > 0 && !double.IsNaN(Scale) && !double.IsInfinity(Scale) ? Scale : 1; +} + +/// Rectangle of the desktop an X11 capture should read, in root coordinates. +readonly record struct CaptureRegion(int X, int Y, int Width, int Height) +{ + public static CaptureRegion From(IReadOnlyList monitors, int rootWidth, int rootHeight) + { + if (rootWidth < 0) rootWidth = 0; + if (rootHeight < 0) rootHeight = 0; + if (monitors == null || monitors.Count == 0) + return new CaptureRegion(0, 0, rootWidth, rootHeight); + + int minX = int.MaxValue, minY = int.MaxValue, maxX = int.MinValue, maxY = int.MinValue; + bool any = false; + foreach (var monitor in monitors) + { + if (monitor.Width <= 0 || monitor.Height <= 0) continue; + any = true; + if (monitor.X < minX) minX = monitor.X; + if (monitor.Y < minY) minY = monitor.Y; + if (monitor.Right > maxX) maxX = monitor.Right; + if (monitor.Bottom > maxY) maxY = monitor.Bottom; + } + if (!any || maxX <= minX || maxY <= minY) + return new CaptureRegion(0, 0, rootWidth, rootHeight); + return new CaptureRegion(minX, minY, maxX - minX, maxY - minY); + } +} + +/// +/// Maps a captured frame onto the monitors it covers. +/// Each monitor is shown in its own window so a 1x screen beside a 2x screen is not +/// stretched through one scale. A frame whose size matches the bounding box is cropped +/// 1:1 (including monitors that sit at negative root coordinates). Any other size is +/// mapped uniformly across that box, which is what a portal screenshot sometimes is. +/// +sealed class MonitorMap +{ + readonly List _monitors; + readonly bool _oneToOne; + readonly int _originX; + readonly int _originY; + + MonitorMap(PixelRect desktop, List monitors, int frameWidth, int frameHeight, int originX, int originY, bool oneToOne) + { + Desktop = desktop; + _monitors = monitors; + FrameWidth = frameWidth; + FrameHeight = frameHeight; + _originX = originX; + _originY = originY; + _oneToOne = oneToOne; + } + + public PixelRect Desktop { get; } + public int FrameWidth { get; } + public int FrameHeight { get; } + public IReadOnlyList Monitors => _monitors; + public bool OneToOne => _oneToOne; + + public static MonitorMap Create(IReadOnlyList monitors, int frameWidth, int frameHeight, bool originKnown, int originX, int originY) + { + var usable = new List(); + if (monitors != null) + { + foreach (var monitor in monitors) + { + if (monitor.Bounds.Width > 0 && monitor.Bounds.Height > 0) + usable.Add(monitor); + } + } + if (usable.Count == 0) + { + usable.Add(new MonitorLayout( + new PixelRect(0, 0, Math.Max(1, frameWidth), Math.Max(1, frameHeight)), + 1, + true)); + } + + var desktop = usable[0].Bounds; + for (int i = 1; i < usable.Count; i++) desktop = desktop.Union(usable[i].Bounds); + + bool oneToOne; + int frameOriginX; + int frameOriginY; + if (originKnown) + { + frameOriginX = originX; + frameOriginY = originY; + oneToOne = true; + } + else if (frameWidth == desktop.Width && frameHeight == desktop.Height) + { + // A tight screenshot of every output. Pixel (0, 0) is the top-left of the box, + // which is not always root (0, 0) when a monitor sits to the left or above. + frameOriginX = desktop.X; + frameOriginY = desktop.Y; + oneToOne = true; + } + else + { + frameOriginX = desktop.X; + frameOriginY = desktop.Y; + oneToOne = false; + } + + return new MonitorMap(desktop, usable, Math.Max(0, frameWidth), Math.Max(0, frameHeight), frameOriginX, frameOriginY, oneToOne); + } + + public PixelPoint Clamp(PixelPoint point) + { + int maxX = Desktop.Width <= 1 ? Desktop.X : Desktop.Right - 1; + int maxY = Desktop.Height <= 1 ? Desktop.Y : Desktop.Bottom - 1; + return new PixelPoint(Math.Clamp(point.X, Desktop.X, maxX), Math.Clamp(point.Y, Desktop.Y, maxY)); + } + + public PixelPoint Center + { + get + { + int x = Desktop.X + Math.Max(0, Desktop.Width - 1) / 2; + int y = Desktop.Y + Math.Max(0, Desktop.Height - 1) / 2; + return new PixelPoint(x, y); + } + } + + public int IndexAt(PixelPoint point) + { + int best = 0; + long bestDistance = long.MaxValue; + for (int i = 0; i < _monitors.Count; i++) + { + var bounds = _monitors[i].Bounds; + if (point.X >= bounds.X && point.Y >= bounds.Y && point.X < bounds.Right && point.Y < bounds.Bottom) + return i; + + long dx = 0; + if (point.X < bounds.X) dx = bounds.X - point.X; + else if (point.X >= bounds.Right) dx = point.X - (bounds.Right - 1); + long dy = 0; + if (point.Y < bounds.Y) dy = bounds.Y - point.Y; + else if (point.Y >= bounds.Bottom) dy = point.Y - (bounds.Bottom - 1); + long distance = dx + dy; + if (distance < bestDistance) + { + bestDistance = distance; + best = i; + } + } + return best; + } + + public PixelRect MonitorRectAt(PixelPoint point) => _monitors[IndexAt(point)].Bounds; + + /// + /// Desktop pixel under a point in a monitor's window. + /// is allowed to fall outside the window while a drag is grabbed, + /// so the result can land on a neighboring monitor. The caller clamps it to the desktop. + /// + public PixelPoint DesktopPoint(int index, double dipX, double dipY, double dipWidth, double dipHeight) + { + var bounds = _monitors[index].Bounds; + double width = dipWidth <= 0 ? 1 : dipWidth; + double height = dipHeight <= 0 ? 1 : dipHeight; + int x = bounds.X + (int)Math.Floor(dipX / width * bounds.Width); + int y = bounds.Y + (int)Math.Floor(dipY / height * bounds.Height); + return new PixelPoint(x, y); + } + + public PixelRect RectBetween(PixelPoint a, PixelPoint b) + { + int left = Math.Min(a.X, b.X); + int top = Math.Min(a.Y, b.Y); + int right = Math.Max(a.X, b.X) + 1; + int bottom = Math.Max(a.Y, b.Y) + 1; + left = Math.Clamp(left, Desktop.X, Desktop.Right); + top = Math.Clamp(top, Desktop.Y, Desktop.Bottom); + right = Math.Clamp(right, left, Desktop.Right); + bottom = Math.Clamp(bottom, top, Desktop.Bottom); + return new PixelRect(left, top, right - left, bottom - top); + } + + public PixelRect TranslateClamped(PixelRect rect, int dx, int dy) + { + int width = Math.Min(Math.Max(0, rect.Width), Math.Max(0, Desktop.Width)); + int height = Math.Min(Math.Max(0, rect.Height), Math.Max(0, Desktop.Height)); + int x = rect.X + dx; + int y = rect.Y + dy; + int maxX = Desktop.Right - width; + int maxY = Desktop.Bottom - height; + if (x < Desktop.X) x = Desktop.X; + if (y < Desktop.Y) y = Desktop.Y; + if (x > maxX) x = maxX; + if (y > maxY) y = maxY; + return new PixelRect(x, y, width, height); + } + + public bool TryToImage(PixelRect desktop, out PixelRect image) + { + image = default; + if (FrameWidth <= 0 || FrameHeight <= 0) return false; + + if (_oneToOne) + { + var covered = Intersect(desktop, new PixelRect(_originX, _originY, FrameWidth, FrameHeight)); + if (covered.Width <= 0 || covered.Height <= 0) return false; + image = new PixelRect(covered.X - _originX, covered.Y - _originY, covered.Width, covered.Height); + return true; + } + + if (Desktop.Width <= 0 || Desktop.Height <= 0) return false; + var hit = Intersect(desktop, Desktop); + if (hit.Width <= 0 || hit.Height <= 0) return false; + double sx = FrameWidth / (double)Desktop.Width; + double sy = FrameHeight / (double)Desktop.Height; + int x = (int)Math.Round((hit.X - Desktop.X) * sx); + int y = (int)Math.Round((hit.Y - Desktop.Y) * sy); + int right = (int)Math.Round((hit.Right - Desktop.X) * sx); + int bottom = (int)Math.Round((hit.Bottom - Desktop.Y) * sy); + x = Math.Clamp(x, 0, FrameWidth); + y = Math.Clamp(y, 0, FrameHeight); + right = Math.Clamp(right, 0, FrameWidth); + bottom = Math.Clamp(bottom, 0, FrameHeight); + if (right <= x) right = Math.Min(FrameWidth, x + 1); + if (bottom <= y) bottom = Math.Min(FrameHeight, y + 1); + if (right <= x || bottom <= y) return false; + image = new PixelRect(x, y, right - x, bottom - y); + return true; + } + + public Rect? LocalRect(int index, PixelRect desktop, double dipWidth, double dipHeight) + { + if (index < 0 || index >= _monitors.Count || dipWidth <= 0 || dipHeight <= 0) return null; + var bounds = _monitors[index].Bounds; + if (bounds.Width <= 0 || bounds.Height <= 0) return null; + var hit = Intersect(desktop, bounds); + if (hit.Width <= 0 || hit.Height <= 0) return null; + double x0 = (hit.X - bounds.X) * dipWidth / bounds.Width; + double y0 = (hit.Y - bounds.Y) * dipHeight / bounds.Height; + double x1 = (hit.Right - bounds.X) * dipWidth / bounds.Width; + double y1 = (hit.Bottom - bounds.Y) * dipHeight / bounds.Height; + return new Rect(x0, y0, Math.Max(0, x1 - x0), Math.Max(0, y1 - y0)); + } + + public bool TryPlacement(int index, double dipWidth, double dipHeight, out PixelRect source, out Rect dest) + { + source = default; + dest = default; + if (index < 0 || index >= _monitors.Count) return false; + var bounds = _monitors[index].Bounds; + if (!TryToImage(bounds, out source)) return false; + + PixelRect covered = _oneToOne + ? new PixelRect(source.X + _originX, source.Y + _originY, source.Width, source.Height) + : bounds; + var local = LocalRect(index, covered, dipWidth, dipHeight); + if (local == null || source.Width <= 0 || source.Height <= 0) return false; + dest = local.Value; + return dest.Width > 0 && dest.Height > 0; + } + + static PixelRect Intersect(PixelRect a, PixelRect b) + { + int left = Math.Max(a.X, b.X); + int top = Math.Max(a.Y, b.Y); + int right = Math.Min(a.Right, b.Right); + int bottom = Math.Min(a.Bottom, b.Bottom); + if (right <= left || bottom <= top) return default; + return new PixelRect(left, top, right - left, bottom - top); + } +} diff --git a/linux/SnipSession.cs b/linux/SnipSession.cs new file mode 100644 index 0000000..bc3a246 --- /dev/null +++ b/linux/SnipSession.cs @@ -0,0 +1,145 @@ +using Avalonia; + +namespace OpenSnip; + +enum SnipCommand +{ + Escape, + Enter, + Monitor, + All, + Left, + Right, + Up, + Down, +} + +readonly record struct SnipOutcome(bool Close, bool Cancel, bool HasRegion, PixelRect Region) +{ + public static SnipOutcome Continue() => default; + public static SnipOutcome Cancelled() => new(true, true, false, default); + public static SnipOutcome Chosen(PixelRect region) => new(true, false, true, region); +} + +/// +/// Selection state in desktop pixels. A movement of more than 3 pixels becomes a drag, +/// matching the Windows overlay; anything smaller grabs the monitor under the pointer. +/// Arrow keys move 1 desktop pixel (10 with Shift), not one DIP. +/// +sealed class SnipSession +{ + public const int DragThreshold = 3; + + readonly MonitorMap _map; + bool _dragging; + bool _armed; + PixelPoint _dragStart; + + public SnipSession(MonitorMap map) => _map = map; + + public bool Dragging => _dragging; + public bool HasCursor { get; private set; } + public bool KeyboardCursor { get; private set; } + public PixelPoint Cursor { get; private set; } + public PixelRect? Selection { get; private set; } + + public void Press(PixelPoint point) + { + Cursor = _map.Clamp(point); + HasCursor = true; + KeyboardCursor = false; + _dragging = true; + _armed = false; + _dragStart = Cursor; + Selection = null; + } + + public void Move(PixelPoint point) + { + Cursor = _map.Clamp(point); + HasCursor = true; + KeyboardCursor = false; + if (!_dragging) return; + if (!_armed && Exceeds(_dragStart, Cursor)) _armed = true; + if (_armed) Selection = _map.RectBetween(_dragStart, Cursor); + } + + public SnipOutcome Release(PixelPoint point) + { + if (!_dragging) return SnipOutcome.Continue(); + _dragging = false; + Cursor = _map.Clamp(point); + HasCursor = true; + KeyboardCursor = false; + bool armed = _armed; + _armed = false; + if (!armed) + { + Selection = null; + return SnipOutcome.Chosen(_map.MonitorRectAt(Cursor)); + } + + var rect = _map.RectBetween(_dragStart, Cursor); + Selection = null; + if (rect.Width < 2 || rect.Height < 2) return SnipOutcome.Continue(); + return SnipOutcome.Chosen(rect); + } + + public SnipOutcome Command(SnipCommand command, bool large) + { + switch (command) + { + case SnipCommand.Escape: + return SnipOutcome.Cancelled(); + case SnipCommand.Enter: + if (Selection is { Width: > 0, Height: > 0 } selected) + return SnipOutcome.Chosen(selected); + return SnipOutcome.Chosen(_map.MonitorRectAt(CurrentCursor())); + case SnipCommand.Monitor: + Selection = _map.MonitorRectAt(CurrentCursor()); + KeyboardCursor = false; + return SnipOutcome.Continue(); + case SnipCommand.All: + Selection = _map.Desktop; + KeyboardCursor = false; + return SnipOutcome.Continue(); + case SnipCommand.Left: + case SnipCommand.Right: + case SnipCommand.Up: + case SnipCommand.Down: + Nudge(command, large ? 10 : 1); + return SnipOutcome.Continue(); + default: + return SnipOutcome.Continue(); + } + } + + void Nudge(SnipCommand command, int step) + { + int dx = command == SnipCommand.Left ? -step : command == SnipCommand.Right ? step : 0; + int dy = command == SnipCommand.Up ? -step : command == SnipCommand.Down ? step : 0; + if (!HasCursor) + { + Cursor = _map.Center; + HasCursor = true; + } + var next = _map.Clamp(new PixelPoint(Cursor.X + dx, Cursor.Y + dy)); + int appliedX = next.X - Cursor.X; + int appliedY = next.Y - Cursor.Y; + Cursor = next; + KeyboardCursor = true; + if (_dragging) + { + if (!_armed && Exceeds(_dragStart, Cursor)) _armed = true; + if (_armed) Selection = _map.RectBetween(_dragStart, Cursor); + return; + } + if (Selection is { } selected) + Selection = _map.TranslateClamped(selected, appliedX, appliedY); + } + + PixelPoint CurrentCursor() => HasCursor ? Cursor : _map.Center; + + static bool Exceeds(PixelPoint start, PixelPoint point) => + Math.Abs(point.X - start.X) > DragThreshold || Math.Abs(point.Y - start.Y) > DragThreshold; +} diff --git a/tests/OpenSnip.Tests/MonitorMapTests.cs b/tests/OpenSnip.Tests/MonitorMapTests.cs new file mode 100644 index 0000000..21708cd --- /dev/null +++ b/tests/OpenSnip.Tests/MonitorMapTests.cs @@ -0,0 +1,138 @@ +using Avalonia; + +namespace OpenSnip.Tests; + +public class MonitorMapTests +{ + static MonitorLayout Monitor(int x, int y, int width, int height, double scale, bool primary = false) => + new(new PixelRect(x, y, width, height), scale, primary); + + static MonitorMap Mixed(bool originKnown = true) => MonitorMap.Create(new[] + { + Monitor(0, 0, 1920, 1080, 1, primary: true), + Monitor(1920, 0, 3840, 2160, 2), + }, 5760, 2160, originKnown, 0, 0); + + [Fact] + public void Mixed_scale_center_of_the_second_monitor_is_its_physical_center() + { + var map = Mixed(); + // The 2x monitor is 3840x2160 physical pixels, shown in a 1920x1080 DIP window. + var point = map.DesktopPoint(1, 960, 540, 1920, 1080); + + Assert.Equal(new PixelPoint(3840, 1080), point); + Assert.True(map.TryToImage(new PixelRect(point.X, point.Y, 1, 1), out var image)); + Assert.Equal(new PixelRect(3840, 1080, 1, 1), image); + } + + [Fact] + public void Mixed_scale_window_fraction_stays_on_that_monitor() + { + var map = Mixed(); + var left = map.DesktopPoint(0, 0, 0, 1920, 1080); + var rightEdge = map.DesktopPoint(0, 1919, 1079, 1920, 1080); + var second = map.DesktopPoint(1, 0, 0, 1920, 1080); + + Assert.Equal(new PixelPoint(0, 0), left); + Assert.Equal(new PixelPoint(1919, 1079), rightEdge); + Assert.Equal(new PixelPoint(1920, 0), second); + Assert.Equal(0, map.IndexAt(rightEdge)); + Assert.Equal(1, map.IndexAt(second)); + } + + [Fact] + public void Full_monitor_crop_is_that_monitors_pixels() + { + var map = Mixed(); + Assert.True(map.TryToImage(new PixelRect(1920, 0, 3840, 2160), out var image)); + Assert.Equal(new PixelRect(1920, 0, 3840, 2160), image); + + Assert.True(map.TryPlacement(1, 1920, 1080, out var source, out var dest)); + Assert.Equal(image, source); + Assert.Equal(new Rect(0, 0, 1920, 1080), dest); + } + + [Fact] + public void Selection_crossing_the_boundary_splits_per_monitor() + { + var map = Mixed(); + var selection = new PixelRect(1800, 100, 400, 50); + + var onFirst = map.LocalRect(0, selection, 1920, 1080); + var onSecond = map.LocalRect(1, selection, 1920, 1080); + + Assert.NotNull(onFirst); + Assert.NotNull(onSecond); + Assert.Equal(120, onFirst.Value.Width, 0); + Assert.Equal(1920, onFirst.Value.Right, 0); + Assert.Equal(0, onSecond.Value.X, 0); + Assert.Equal(280 * 1920 / 3840d, onSecond.Value.Width, 3); + } + + [Fact] + public void Negative_origin_capture_lines_up_with_both_monitors() + { + var monitors = new[] + { + Monitor(-1920, 0, 1920, 1080, 1), + Monitor(0, 0, 1920, 1080, 1, primary: true), + }; + var map = MonitorMap.Create(monitors, 3840, 1080, originKnown: true, originX: -1920, originY: 0); + + Assert.True(map.TryToImage(new PixelRect(-1920, 0, 10, 10), out var left)); + Assert.True(map.TryToImage(new PixelRect(0, 0, 10, 10), out var right)); + Assert.Equal(new PixelRect(0, 0, 10, 10), left); + Assert.Equal(new PixelRect(1920, 0, 10, 10), right); + } + + [Fact] + public void Tight_screenshot_without_an_origin_uses_the_bounding_box() + { + var monitors = new[] + { + Monitor(-1920, 0, 1920, 1080, 1), + Monitor(0, 0, 1920, 1080, 1, primary: true), + }; + var map = MonitorMap.Create(monitors, 3840, 1080, originKnown: false, 0, 0); + + Assert.True(map.OneToOne); + Assert.True(map.TryToImage(new PixelRect(-1910, 5, 4, 6), out var image)); + Assert.Equal(new PixelRect(10, 5, 4, 6), image); + } + + [Fact] + public void Differently_sized_frame_is_spread_across_the_desktop() + { + var monitors = new[] + { + Monitor(-1920, 0, 1920, 1080, 1), + Monitor(0, 0, 1920, 1080, 1, primary: true), + }; + var map = MonitorMap.Create(monitors, 1920, 540, originKnown: false, 0, 0); + + Assert.False(map.OneToOne); + Assert.True(map.TryToImage(new PixelRect(-1920, 0, 1920, 1080), out var left)); + Assert.True(map.TryToImage(new PixelRect(0, 0, 1920, 1080), out var right)); + Assert.Equal(new PixelRect(0, 0, 960, 540), left); + Assert.Equal(new PixelRect(960, 0, 960, 540), right); + } + + [Fact] + public void Capture_region_includes_monitors_above_and_left_of_the_origin() + { + var region = CaptureRegion.From(new[] + { + new PixelRect(-1920, -1080, 1920, 1080), + new PixelRect(0, 0, 1920, 1080), + }, 1920, 1080); + + Assert.Equal(new CaptureRegion(-1920, -1080, 3840, 2160), region); + } + + [Fact] + public void Capture_region_without_monitors_is_the_root_window() + { + Assert.Equal(new CaptureRegion(0, 0, 1920, 1080), CaptureRegion.From(null, 1920, 1080)); + Assert.Equal(new CaptureRegion(0, 0, 800, 600), CaptureRegion.From(new[] { new PixelRect(0, 0, 0, 0) }, 800, 600)); + } +} diff --git a/tests/OpenSnip.Tests/OpenSnip.Tests.csproj b/tests/OpenSnip.Tests/OpenSnip.Tests.csproj new file mode 100644 index 0000000..69c6f44 --- /dev/null +++ b/tests/OpenSnip.Tests/OpenSnip.Tests.csproj @@ -0,0 +1,25 @@ + + + + net9.0 + enable + disable + false + OpenSnip.Tests + + + + + + + + + + + + + + + + + diff --git a/tests/OpenSnip.Tests/SnipSessionTests.cs b/tests/OpenSnip.Tests/SnipSessionTests.cs new file mode 100644 index 0000000..ee4a77e --- /dev/null +++ b/tests/OpenSnip.Tests/SnipSessionTests.cs @@ -0,0 +1,116 @@ +using Avalonia; + +namespace OpenSnip.Tests; + +public class SnipSessionTests +{ + static SnipSession Session() + { + var map = MonitorMap.Create(new[] + { + new MonitorLayout(new PixelRect(0, 0, 1920, 1080), 1, true), + new MonitorLayout(new PixelRect(1920, 0, 3840, 2160), 2, false), + }, 5760, 2160, true, 0, 0); + return new SnipSession(map); + } + + [Fact] + public void Click_grabs_the_monitor_under_the_pointer() + { + var session = Session(); + session.Press(new PixelPoint(4000, 1000)); + session.Move(new PixelPoint(4002, 1001)); + var outcome = session.Release(new PixelPoint(4002, 1001)); + + Assert.True(outcome.HasRegion); + Assert.Equal(new PixelRect(1920, 0, 3840, 2160), outcome.Region); + } + + [Fact] + public void Drag_uses_desktop_pixels_and_includes_both_ends() + { + var session = Session(); + session.Press(new PixelPoint(100, 80)); + session.Move(new PixelPoint(110, 100)); + var outcome = session.Release(new PixelPoint(110, 100)); + + Assert.True(outcome.HasRegion); + Assert.Equal(new PixelRect(100, 80, 11, 21), outcome.Region); + } + + [Fact] + public void Drag_that_never_reaches_two_pixels_does_not_capture() + { + var session = Session(); + session.Press(new PixelPoint(0, 0)); + session.Move(new PixelPoint(10, 10)); + session.Move(new PixelPoint(1, 0)); + var outcome = session.Release(new PixelPoint(1, 0)); + + Assert.False(outcome.Close); + Assert.False(session.Dragging); + } + + [Fact] + public void Enter_confirms_the_selection_or_the_monitor() + { + var session = Session(); + session.Move(new PixelPoint(10, 10)); + var monitor = session.Command(SnipCommand.Enter, false); + Assert.Equal(new PixelRect(0, 0, 1920, 1080), monitor.Region); + + session = Session(); + session.Move(new PixelPoint(2000, 10)); + var marked = session.Command(SnipCommand.Monitor, false); + Assert.False(marked.Close); + Assert.Equal(new PixelRect(1920, 0, 3840, 2160), session.Selection); + var chosen = session.Command(SnipCommand.Enter, false); + Assert.Equal(session.Selection, chosen.Region); + } + + [Fact] + public void All_selects_the_whole_desktop_without_closing() + { + var session = Session(); + var outcome = session.Command(SnipCommand.All, false); + + Assert.False(outcome.Close); + Assert.Equal(new PixelRect(0, 0, 5760, 2160), session.Selection); + } + + [Fact] + public void Arrow_nudges_one_desktop_pixel_or_ten_with_shift() + { + var session = Session(); + session.Move(new PixelPoint(3840, 1080)); + session.Command(SnipCommand.Right, large: false); + Assert.Equal(new PixelPoint(3841, 1080), session.Cursor); + + session.Command(SnipCommand.Down, large: true); + Assert.Equal(new PixelPoint(3841, 1090), session.Cursor); + Assert.True(session.KeyboardCursor); + } + + [Fact] + public void Arrow_moves_an_existing_selection_with_the_cursor() + { + var session = Session(); + session.Move(new PixelPoint(100, 100)); + session.Command(SnipCommand.Monitor, false); + session.Command(SnipCommand.Right, false); + + Assert.Equal(new PixelPoint(101, 100), session.Cursor); + Assert.Equal(new PixelRect(1, 0, 1920, 1080), session.Selection); + } + + [Fact] + public void Escape_cancels() + { + var session = Session(); + session.Press(new PixelPoint(10, 10)); + var outcome = session.Command(SnipCommand.Escape, false); + + Assert.True(outcome.Close); + Assert.True(outcome.Cancel); + } +} From b17eb61517ea32fcc25d40e2cee9d7c53ab9621e Mon Sep 17 00:00:00 2001 From: Devan <68340659+DevanMetz@users.noreply.github.com> Date: Tue, 27 Oct 2026 18:19:37 -0500 Subject: [PATCH 2/4] Draw one snip window per monitor at that screen's scale. A single overlay stretched mixed-DPI desktops. Each monitor now gets its own window, and drags that leave it use the X11 root pointer so the crop stays in desktop pixels. --- linux/App.cs | 3 +- linux/CapturedFrame.cs | 12 + linux/MonitorMap.cs | 8 + linux/OverlayWindow.cs | 626 +++++++++++++----------- linux/X11Pointer.cs | 116 +++++ tests/OpenSnip.Tests/MonitorMapTests.cs | 9 + tests/OpenSnip.Tests/X11PointerTests.cs | 12 + 7 files changed, 490 insertions(+), 296 deletions(-) create mode 100644 linux/X11Pointer.cs create mode 100644 tests/OpenSnip.Tests/X11PointerTests.cs diff --git a/linux/App.cs b/linux/App.cs index 5df37c6..ed14df8 100644 --- a/linux/App.cs +++ b/linux/App.cs @@ -191,8 +191,7 @@ public async void StartSnip(int delaySeconds = 0) if (delaySeconds > 0) await CountdownWindow.RunAsync(delaySeconds); var frame = await CaptureService.CaptureAsync(); - var overlay = new OverlayWindow(frame, Settings); - var region = await overlay.SelectAsync(); + var region = await OverlayWindow.SelectAsync(frame, Settings); if (region is not { } selected) return; _lastRegion = selected; diff --git a/linux/CapturedFrame.cs b/linux/CapturedFrame.cs index b4cf311..883041d 100644 --- a/linux/CapturedFrame.cs +++ b/linux/CapturedFrame.cs @@ -12,6 +12,18 @@ sealed class CapturedFrame public int Height { get; } public byte[] Bgra { get; } + /// Desktop pixel of frame (0, 0). Set by the X11 capture; other backends leave it unknown. + public int OriginX { get; private set; } + public int OriginY { get; private set; } + public bool OriginKnown { get; private set; } + + public void NoteOrigin(int x, int y) + { + OriginX = x; + OriginY = y; + OriginKnown = true; + } + public CapturedFrame(int width, int height, byte[] bgra) { if (width <= 0 || height <= 0) throw new ArgumentException("Invalid image size"); diff --git a/linux/MonitorMap.cs b/linux/MonitorMap.cs index af66597..32171a1 100644 --- a/linux/MonitorMap.cs +++ b/linux/MonitorMap.cs @@ -168,6 +168,14 @@ public int IndexAt(PixelPoint point) /// is allowed to fall outside the window while a drag is grabbed, /// so the result can land on a neighboring monitor. The caller clamps it to the desktop. /// + public Point LocalCenter(int index, PixelPoint desktop, double dipWidth, double dipHeight) + { + var bounds = _monitors[index].Bounds; + double x = bounds.Width <= 0 ? 0 : (desktop.X - bounds.X + 0.5) * dipWidth / bounds.Width; + double y = bounds.Height <= 0 ? 0 : (desktop.Y - bounds.Y + 0.5) * dipHeight / bounds.Height; + return new Point(x, y); + } + public PixelPoint DesktopPoint(int index, double dipX, double dipY, double dipWidth, double dipHeight) { var bounds = _monitors[index].Bounds; diff --git a/linux/OverlayWindow.cs b/linux/OverlayWindow.cs index df3fdbc..69605c0 100644 --- a/linux/OverlayWindow.cs +++ b/linux/OverlayWindow.cs @@ -2,29 +2,174 @@ using Avalonia; using Avalonia.Controls; using Avalonia.Input; +using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Media.Imaging; using Avalonia.Threading; namespace OpenSnip; -sealed class OverlayWindow : Window +static class OverlayWindow { + public static Task SelectAsync(CapturedFrame frame, Settings settings) + { + var session = new OverlaySession(frame, settings); + return session.Run(); + } +} + +sealed class OverlaySession +{ + readonly Settings _settings; + readonly MonitorMap _map; + readonly SnipSession _snip; + readonly X11Pointer _pointer; + readonly WriteableBitmap _bitmap; + readonly List _windows = new(); readonly TaskCompletionSource _result = new(TaskCreationOptions.RunContinuationsAsynchronously); - readonly PixelRect _virtualBounds; - readonly CaptureCanvas _canvas; + bool _done; + + public OverlaySession(CapturedFrame frame, Settings settings) + { + _settings = settings; + _pointer = X11Pointer.TryOpen(); + _map = MonitorMap.Create(ReadLayouts(frame), frame.Width, frame.Height, frame.OriginKnown, frame.OriginX, frame.OriginY); + _snip = new SnipSession(_map); + _bitmap = frame.ToBitmap(); + } + + public MonitorMap Map => _map; + public SnipSession Snip => _snip; + public Settings Settings => _settings; + public WriteableBitmap Bitmap => _bitmap; + + public Task Run() + { + for (int i = 0; i < _map.Monitors.Count; i++) + _windows.Add(new MonitorOverlayWindow(this, i)); + + int focus = 0; + for (int i = 0; i < _map.Monitors.Count; i++) + { + if (_map.Monitors[i].Primary) focus = i; + } + + for (int i = 0; i < _windows.Count; i++) + { + _windows[i].ShowActivated = i == focus; + _windows[i].Show(); + } + _windows[focus].Activate(); + _windows[focus].FocusCanvas(); + return _result.Task; + } + + public PixelPoint PointerDesktop(int index, Point local, Size size) + { + bool inside = local.X >= 0 && local.Y >= 0 && local.X < size.Width && local.Y < size.Height; + if (!inside && _pointer != null) + { + var root = _pointer.Position(); + if (root is { } point) return point; + } + return _map.DesktopPoint(index, local.X, local.Y, size.Width, size.Height); + } + + public void Apply(SnipOutcome outcome) + { + if (_done) return; + if (!outcome.Close) + { + Invalidate(); + return; + } + if (outcome.Cancel || !outcome.HasRegion || !_map.TryToImage(outcome.Region, out var image)) + Finish(null); + else + Finish(image); + } + + public void WindowClosed() => Finish(null); + + void Invalidate() + { + foreach (var window in _windows) window.InvalidateCanvas(); + } + + void Finish(PixelRect? image) + { + if (_done) return; + _done = true; + _result.TrySetResult(image); + foreach (var window in _windows.ToArray()) + { + try { window.Close(); } catch { } + } + _pointer?.Dispose(); + var bitmap = _bitmap; + Dispatcher.UIThread.Post(() => + { + try { bitmap.Dispose(); } catch { } + }, DispatcherPriority.Background); + } - public OverlayWindow(CapturedFrame frame, Settings settings) + static List ReadLayouts(CapturedFrame frame) { - var screens = Screens.All; - PixelRect union = screens.Count > 0 ? screens[0].Bounds : new PixelRect(0, 0, frame.Width, frame.Height); - foreach (var screen in screens) union = union.Union(screen.Bounds); - _virtualBounds = union; + var layouts = new List(); + Window probe = null; + try + { + probe = new Window + { + SystemDecorations = SystemDecorations.None, + ShowInTaskbar = false, + ShowActivated = false, + Width = 1, + Height = 1, + Opacity = 0, + WindowStartupLocation = WindowStartupLocation.Manual, + }; + var screens = probe.Screens?.All; + if (screens != null) + { + foreach (var screen in screens) + { + if (screen == null || screen.Bounds.Width <= 0 || screen.Bounds.Height <= 0) continue; + layouts.Add(new MonitorLayout(screen.Bounds, screen.Scaling, screen.IsPrimary)); + } + } + } + catch (Exception ex) + { + Log.Error(ex); + } + finally + { + try { probe?.Close(); } catch { } + } + + if (layouts.Count == 0) + { + layouts.Add(new MonitorLayout( + new PixelRect(0, 0, Math.Max(1, frame.Width), Math.Max(1, frame.Height)), + 1, + true)); + } + return layouts; + } +} - var scale = Screens.ScreenFromPoint(union.Position)?.Scaling - ?? Screens.Primary?.Scaling - ?? 1; +sealed class MonitorOverlayWindow : Window +{ + readonly OverlaySession _session; + readonly MonitorLayout _layout; + readonly CaptureCanvas _canvas; + bool _fitting; + public MonitorOverlayWindow(OverlaySession session, int index) + { + _session = session; + _layout = session.Map.Monitors[index]; Title = "OpenSnip"; Icon = IconLoader.Icon; SystemDecorations = SystemDecorations.None; @@ -34,185 +179,126 @@ public OverlayWindow(CapturedFrame frame, Settings settings) WindowStartupLocation = WindowStartupLocation.Manual; Background = Brushes.Black; Cursor = new Cursor(StandardCursorType.Cross); - Position = union.Position; - Width = Math.Max(1, union.Width / scale); - Height = Math.Max(1, union.Height / scale); + UseLayoutRounding = false; + Position = new PixelPoint(_layout.Bounds.X, _layout.Bounds.Y); + Width = Math.Max(1, _layout.Bounds.Width / _layout.ScaleOrOne); + Height = Math.Max(1, _layout.Bounds.Height / _layout.ScaleOrOne); - _canvas = new CaptureCanvas(frame, settings, union, Complete); + _canvas = new CaptureCanvas(session, index); Content = _canvas; - Closed += (_, _) => _result.TrySetResult(null); + Opened += (_, _) => Fit(); + ScalingChanged += (_, _) => Fit(); + Closed += (_, _) => session.WindowClosed(); + AddHandler(KeyDownEvent, OnKey, RoutingStrategies.Tunnel); } - public Task SelectAsync() + public void FocusCanvas() { - Show(); - Activate(); Focus(); _canvas.Focus(); - return _result.Task; } - protected override void OnOpened(EventArgs e) - { - base.OnOpened(e); - _canvas.Focus(); - } + public void InvalidateCanvas() => _canvas.InvalidateVisual(); - protected override void OnKeyDown(KeyEventArgs e) + void OnKey(object sender, KeyEventArgs e) { - if (_canvas.HandleKey(e)) + SnipCommand? command = e.Key switch { - e.Handled = true; - return; - } - base.OnKeyDown(e); + Key.Escape => SnipCommand.Escape, + Key.Enter => SnipCommand.Enter, + Key.F => SnipCommand.Monitor, + Key.A => SnipCommand.All, + Key.Left => SnipCommand.Left, + Key.Right => SnipCommand.Right, + Key.Up => SnipCommand.Up, + Key.Down => SnipCommand.Down, + _ => null, + }; + if (command == null) return; + _session.Apply(_session.Snip.Command(command.Value, e.KeyModifiers.HasFlag(KeyModifiers.Shift))); + e.Handled = true; } - void Complete(PixelRect? selection) + void Fit() { - if (_result.TrySetResult(selection)) Close(); + if (_fitting) return; + _fitting = true; + try + { + double scale = RenderScaling; + if (scale < 0.01 || double.IsNaN(scale) || double.IsInfinity(scale)) + scale = _layout.ScaleOrOne; + double width = Math.Max(1, _layout.Bounds.Width / scale); + double height = Math.Max(1, _layout.Bounds.Height / scale); + if (double.IsNaN(Width) || Math.Abs(Width - width) > 0.5) Width = width; + if (double.IsNaN(Height) || Math.Abs(Height - height) > 0.5) Height = height; + var position = new PixelPoint(_layout.Bounds.X, _layout.Bounds.Y); + if (Position != position) Position = position; + } + catch (Exception ex) + { + Log.Error(ex); + } + finally + { + _fitting = false; + } } } sealed class CaptureCanvas : Control { - readonly CapturedFrame _frame; - readonly Bitmap _bitmap; - readonly Settings _settings; - readonly PixelRect _virtualBounds; - readonly Action _complete; + readonly OverlaySession _session; + readonly int _index; readonly Typeface _typeface = new("Inter"); - bool _dragging; - bool _hasPointer; - bool _keyboardCursor; - Point _start; - Point _end; - Point _cursor; - Rect? _selection; - static readonly IBrush DimBrush = new SolidColorBrush(Color.FromArgb(150, 0, 0, 0)); static readonly IBrush ReadoutBrush = new SolidColorBrush(Color.FromArgb(238, 38, 38, 44)); static readonly IPen AccentPen = new Pen(AppTheme.Accent, 2); static readonly IPen CrosshairPen = new Pen(AppTheme.Accent, 1); - public CaptureCanvas(CapturedFrame frame, Settings settings, PixelRect virtualBounds, Action complete) + public CaptureCanvas(OverlaySession session, int index) { - _frame = frame; - _bitmap = frame.ToBitmap(); - _settings = settings; - _virtualBounds = virtualBounds; - _complete = complete; + _session = session; + _index = index; Focusable = true; ClipToBounds = true; - } - - public bool HandleKey(KeyEventArgs e) - { - switch (e.Key) - { - case Key.Escape: - _complete(null); - return true; - case Key.Enter: - if (_selection is { } current) _complete(ToImageRect(current)); - else _complete(MonitorAt(CurrentCursor())); - return true; - case Key.A: - _selection = new Rect(0, 0, Bounds.Width, Bounds.Height); - _keyboardCursor = false; - InvalidateVisual(); - return true; - case Key.F: - _selection = MonitorRect(CurrentCursor()); - _keyboardCursor = false; - InvalidateVisual(); - return true; - case Key.Left: - case Key.Right: - case Key.Up: - case Key.Down: - Nudge(e.Key, e.KeyModifiers.HasFlag(KeyModifiers.Shift)); - return true; - } - return false; - } - - void Nudge(Key key, bool large) - { - double step = large ? 10 : 1; - var delta = key switch - { - Key.Left => new Vector(-step, 0), - Key.Right => new Vector(step, 0), - Key.Up => new Vector(0, -step), - _ => new Vector(0, step), - }; - if (!_hasPointer) - { - _cursor = new Point(Bounds.Width / 2, Bounds.Height / 2); - _hasPointer = true; - } - _cursor = ClampPoint(_cursor + delta); - if (_selection is { } current) - _selection = ClampRect(current.Translate(delta)); - _keyboardCursor = true; - InvalidateVisual(); + Cursor = new Cursor(StandardCursorType.Cross); + RenderOptions.SetBitmapInterpolationMode(this, BitmapInterpolationMode.None); } protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); - var point = e.GetPosition(this); - if (e.GetCurrentPoint(this).Properties.IsRightButtonPressed) + var point = e.GetCurrentPoint(this); + if (point.Properties.IsRightButtonPressed) { - _complete(null); + _session.Apply(SnipOutcome.Cancelled()); e.Handled = true; return; } - if (!e.GetCurrentPoint(this).Properties.IsLeftButtonPressed) return; - - _dragging = true; - _start = _end = _cursor = ClampPoint(point); - _hasPointer = true; - _keyboardCursor = false; - _selection = null; - e.Pointer.Capture(this); - InvalidateVisual(); + if (!point.Properties.IsLeftButtonPressed) return; + _session.Snip.Press(_session.PointerDesktop(_index, e.GetPosition(this), Bounds.Size)); + _session.Apply(SnipOutcome.Continue()); e.Handled = true; } protected override void OnPointerMoved(PointerEventArgs e) { base.OnPointerMoved(e); - var point = ClampPoint(e.GetPosition(this)); - _cursor = point; - _hasPointer = true; - if (_dragging) - { - _end = point; - var rect = RectFromPoints(_start, _end); - _selection = rect.Width >= 1 && rect.Height >= 1 ? rect : null; - } - InvalidateVisual(); + _session.Snip.Move(_session.PointerDesktop(_index, e.GetPosition(this), Bounds.Size)); + _session.Apply(SnipOutcome.Continue()); + e.Handled = true; } protected override void OnPointerReleased(PointerReleasedEventArgs e) { base.OnPointerReleased(e); - if (!_dragging) return; - _dragging = false; - e.Pointer.Capture(null); - var point = ClampPoint(e.GetPosition(this)); - _cursor = point; - var rect = RectFromPoints(_start, point); - if (rect.Width < 3 && rect.Height < 3) - { - _complete(MonitorAt(point)); - return; - } - _complete(ToImageRect(rect)); + if (!_session.Snip.Dragging) return; + var outcome = _session.Snip.Release(_session.PointerDesktop(_index, e.GetPosition(this), Bounds.Size)); + _session.Apply(outcome); + e.Handled = true; } protected override void OnPointerWheelChanged(PointerWheelEventArgs e) @@ -221,210 +307,162 @@ protected override void OnPointerWheelChanged(PointerWheelEventArgs e) e.Handled = true; } - Rect RectFromPoints(Point a, Point b) - { - double left = Math.Clamp(Math.Min(a.X, b.X), 0, Math.Max(0, Bounds.Width)); - double top = Math.Clamp(Math.Min(a.Y, b.Y), 0, Math.Max(0, Bounds.Height)); - double right = Math.Clamp(Math.Max(a.X, b.X), 0, Math.Max(0, Bounds.Width)); - double bottom = Math.Clamp(Math.Max(a.Y, b.Y), 0, Math.Max(0, Bounds.Height)); - return new Rect(left, top, Math.Max(0, right - left), Math.Max(0, bottom - top)); - } - - Point ClampPoint(Point point) => - new(Math.Clamp(point.X, 0, Math.Max(0, Bounds.Width)), Math.Clamp(point.Y, 0, Math.Max(0, Bounds.Height))); - - Rect ClampRect(Rect rect) - { - double x = Math.Clamp(rect.X, 0, Math.Max(0, Bounds.Width - rect.Width)); - double y = Math.Clamp(rect.Y, 0, Math.Max(0, Bounds.Height - rect.Height)); - return new Rect(x, y, rect.Width, rect.Height); - } - - Point CurrentCursor() - { - if (_hasPointer) return _cursor; - return new Point(Bounds.Width / 2, Bounds.Height / 2); - } - - Rect MonitorRect(Point local) - { - var screens = TopLevel.GetTopLevel(this)?.Screens; - if (screens == null) return new Rect(0, 0, Bounds.Width, Bounds.Height); - double physicalX = _virtualBounds.X + local.X * _virtualBounds.Width / Math.Max(1, Bounds.Width); - double physicalY = _virtualBounds.Y + local.Y * _virtualBounds.Height / Math.Max(1, Bounds.Height); - var screen = screens.ScreenFromPoint(new PixelPoint((int)physicalX, (int)physicalY)) - ?? screens.Primary; - if (screen == null) return new Rect(0, 0, Bounds.Width, Bounds.Height); - double sx = Bounds.Width / Math.Max(1, _virtualBounds.Width); - double sy = Bounds.Height / Math.Max(1, _virtualBounds.Height); - return new Rect( - (screen.Bounds.X - _virtualBounds.X) * sx, - (screen.Bounds.Y - _virtualBounds.Y) * sy, - screen.Bounds.Width * sx, - screen.Bounds.Height * sy); - } - - PixelRect MonitorAt(Point local) - { - var rect = MonitorRect(local); - return ToImageRect(rect); - } - - PixelRect ToImageRect(Rect local) - { - double sx = _frame.Width / Math.Max(1, Bounds.Width); - double sy = _frame.Height / Math.Max(1, Bounds.Height); - int x = (int)Math.Round(local.X * sx); - int y = (int)Math.Round(local.Y * sy); - int width = (int)Math.Round(local.Width * sx); - int height = (int)Math.Round(local.Height * sy); - x = Math.Clamp(x, 0, _frame.Width - 1); - y = Math.Clamp(y, 0, _frame.Height - 1); - width = Math.Clamp(width, 1, _frame.Width - x); - height = Math.Clamp(height, 1, _frame.Height - y); - return new PixelRect(x, y, width, height); - } - public override void Render(DrawingContext context) { base.Render(context); - var bounds = new Rect(0, 0, Bounds.Width, Bounds.Height); - context.DrawImage(_bitmap, bounds); + var view = new Rect(0, 0, Bounds.Width, Bounds.Height); + if (view.Width <= 0 || view.Height <= 0) return; + + context.FillRectangle(Brushes.Black, view); + var map = _session.Map; + if (map.TryPlacement(_index, view.Width, view.Height, out var source, out var dest) && _session.Bitmap != null) + { + var src = new Rect(source.X, source.Y, source.Width, source.Height); + context.DrawImage(_session.Bitmap, src, dest); + } + var snip = _session.Snip; Rect? readout = null; - if (_selection is { } selection) + if (snip.Selection is { } selection) { - var top = new Rect(0, 0, Bounds.Width, Math.Max(0, selection.Y)); - var bottom = new Rect(0, Math.Max(0, selection.Bottom), Bounds.Width, Math.Max(0, Bounds.Height - selection.Bottom)); - var left = new Rect(0, Math.Max(0, selection.Y), Math.Max(0, selection.X), Math.Max(0, selection.Height)); - var right = new Rect(Math.Max(0, selection.Right), Math.Max(0, selection.Y), Math.Max(0, Bounds.Width - selection.Right), Math.Max(0, selection.Height)); - context.FillRectangle(DimBrush, top); - context.FillRectangle(DimBrush, bottom); - context.FillRectangle(DimBrush, left); - context.FillRectangle(DimBrush, right); - context.DrawRectangle(null, AccentPen, selection); - readout = DrawReadout(context, selection); + var local = map.LocalRect(_index, selection, view.Width, view.Height); + if (local is { } box && box.Width > 0 && box.Height > 0) + { + DimOutside(context, view, box); + context.DrawRectangle(null, AccentPen, box); + if (Owns(new PixelPoint(selection.X, selection.Y))) + readout = DrawReadout(context, box, selection); + } + else + { + context.FillRectangle(DimBrush, view); + } } else { - context.FillRectangle(DimBrush, bounds); + context.FillRectangle(DimBrush, view); } - if (_hasPointer) + if (!snip.HasCursor || !Owns(snip.Cursor)) return; + var cursor = map.LocalCenter(_index, snip.Cursor, view.Width, view.Height); + if (snip.KeyboardCursor) { - if (_keyboardCursor) - { - context.DrawLine(CrosshairPen, new Point(_cursor.X - 8, _cursor.Y), new Point(_cursor.X + 8, _cursor.Y)); - context.DrawLine(CrosshairPen, new Point(_cursor.X, _cursor.Y - 8), new Point(_cursor.X, _cursor.Y + 8)); - } - if (_settings.ShowMagnifier) DrawMagnifier(context, readout); + context.DrawLine(CrosshairPen, new Point(cursor.X - 8, cursor.Y), new Point(cursor.X + 8, cursor.Y)); + context.DrawLine(CrosshairPen, new Point(cursor.X, cursor.Y - 8), new Point(cursor.X, cursor.Y + 8)); } + if (_session.Settings.ShowMagnifier) DrawMagnifier(context, cursor, readout, view); } - Rect DrawReadout(DrawingContext context, Rect selection) + bool Owns(PixelPoint point) => _session.Map.IndexAt(point) == _index; + + static void DimOutside(DrawingContext context, Rect view, Rect box) { - double sx = _frame.Width / Math.Max(1, Bounds.Width); - double sy = _frame.Height / Math.Max(1, Bounds.Height); - int width = Math.Max(1, (int)Math.Round(selection.Width * sx)); - int height = Math.Max(1, (int)Math.Round(selection.Height * sy)); - var text = new FormattedText($"{width} × {height}", CultureInfo.InvariantCulture, + var top = new Rect(0, 0, view.Width, Math.Max(0, box.Y)); + var bottom = new Rect(0, Math.Max(0, box.Bottom), view.Width, Math.Max(0, view.Height - box.Bottom)); + var left = new Rect(0, Math.Max(0, box.Y), Math.Max(0, box.X), Math.Max(0, box.Height)); + var right = new Rect(Math.Max(0, box.Right), Math.Max(0, box.Y), Math.Max(0, view.Width - box.Right), Math.Max(0, box.Height)); + if (top.Height > 0) context.FillRectangle(DimBrush, top); + if (bottom.Height > 0) context.FillRectangle(DimBrush, bottom); + if (left.Width > 0) context.FillRectangle(DimBrush, left); + if (right.Width > 0) context.FillRectangle(DimBrush, right); + } + + Rect DrawReadout(DrawingContext context, Rect box, PixelRect selection) + { + string label = _session.Map.TryToImage(selection, out var image) + ? $"{image.Width} × {image.Height}" + : $"{selection.Width} × {selection.Height}"; + var text = new FormattedText(label, CultureInfo.InvariantCulture, FlowDirection.LeftToRight, _typeface, 13, AppTheme.Text); const double padX = 9, padY = 5; double boxW = text.Width + padX * 2; double boxH = text.Height + padY * 2; - - // Sit just above the selection's top-left corner; if the selection touches - // the top edge, keep the readout inside its top-left corner instead. - double x = selection.Left; - double y = selection.Top - boxH - 8; + double x = box.Left; + double y = box.Top - boxH - 8; if (y < 4) { - x = selection.Left + 8; - y = selection.Top + 8; + x = box.Left + 8; + y = box.Top + 8; } x = Math.Clamp(x, 4, Math.Max(4, Bounds.Width - boxW - 4)); y = Math.Clamp(y, 4, Math.Max(4, Bounds.Height - boxH - 4)); - var box = new Rect(x, y, boxW, boxH); - context.DrawRectangle(ReadoutBrush, null, box, 5, 5); + var frame = new Rect(x, y, boxW, boxH); + context.DrawRectangle(ReadoutBrush, null, frame, 5, 5); context.DrawText(text, new Point(x + padX, y + padY)); - return box; + return frame; } - static bool Overlaps(Rect a, Rect b) => - a.Left < b.Right && a.Right > b.Left && a.Top < b.Bottom && a.Bottom > b.Top; + void DrawMagnifier(DrawingContext context, Point cursor, Rect? readout, Rect view) + { + if (!_session.Map.TryToImage(new PixelRect(_session.Snip.Cursor.X, _session.Snip.Cursor.Y, 1, 1), out var pixel)) + return; + + const double inner = 104; + const double pad = 3; + const double labelHeight = 20; + double total = inner + pad * 2; + var box = PlaceMagnifier(cursor, total, total + labelHeight, readout, view); + int imageX = Math.Clamp(pixel.X, 0, Math.Max(0, _session.Bitmap.PixelSize.Width - 1)); + int imageY = Math.Clamp(pixel.Y, 0, Math.Max(0, _session.Bitmap.PixelSize.Height - 1)); + int frameW = _session.Bitmap.PixelSize.Width; + int frameH = _session.Bitmap.PixelSize.Height; + const int sourceSize = 24; + int left = Math.Clamp(imageX - sourceSize / 2, 0, Math.Max(0, frameW - sourceSize)); + int top = Math.Clamp(imageY - sourceSize / 2, 0, Math.Max(0, frameH - sourceSize)); + var source = new Rect(left, top, Math.Min(sourceSize, frameW), Math.Min(sourceSize, frameH)); + var dest = new Rect(box.X + pad, box.Y + pad, inner, inner); + + context.DrawRectangle(ReadoutBrush, new Pen(AppTheme.Accent, 2), new Rect(box.X, box.Y, total, total + labelHeight), 7, 7); + using (context.PushClip(dest)) + context.DrawImage(_session.Bitmap, source, dest); + var center = dest.Center; + context.DrawLine(CrosshairPen, new Point(center.X - 7, center.Y), new Point(center.X + 7, center.Y)); + context.DrawLine(CrosshairPen, new Point(center.X, center.Y - 7), new Point(center.X, center.Y + 7)); - Rect PlaceMagnifier(double width, double height, Rect? readout) + var label = new FormattedText($"{_session.Snip.Cursor.X}, {_session.Snip.Cursor.Y}", CultureInfo.InvariantCulture, + FlowDirection.LeftToRight, _typeface, 11, AppTheme.Muted); + context.DrawText(label, new Point(box.X + (total - label.Width) / 2, box.Y + total + 2)); + } + + static Rect PlaceMagnifier(Point cursor, double width, double height, Rect? readout, Rect view) { const double gap = 22; const double margin = 4; Rect? TryAt(double x, double y) { - if (x < margin || y < margin || - x + width > Bounds.Width - margin || - y + height > Bounds.Height - margin) + if (x < margin || y < margin || x + width > view.Width - margin || y + height > view.Height - margin) return null; var rect = new Rect(x, y, width, height); if (readout is { } box && Overlaps(rect, box)) return null; return rect; } - double right = _cursor.X + gap; - double left = _cursor.X - width - gap; - double down = _cursor.Y + gap; - double up = _cursor.Y - height - gap; - + double right = cursor.X + gap; + double left = cursor.X - width - gap; + double down = cursor.Y + gap; + double up = cursor.Y - height - gap; var found = TryAt(right, down) ?? TryAt(left, down) ?? TryAt(right, up) ?? TryAt(left, up); - if (found == null && readout is { } r) + if (found == null && readout is { } blocked) { - found = TryAt(r.Right + gap, down) - ?? TryAt(r.Left - width - gap, down) - ?? TryAt(right, r.Bottom + gap) - ?? TryAt(right, r.Top - height - gap) - ?? TryAt(left, r.Bottom + gap) - ?? TryAt(left, r.Top - height - gap); + found = TryAt(blocked.Right + gap, down) + ?? TryAt(blocked.Left - width - gap, down) + ?? TryAt(right, blocked.Bottom + gap) + ?? TryAt(right, blocked.Top - height - gap) + ?? TryAt(left, blocked.Bottom + gap) + ?? TryAt(left, blocked.Top - height - gap); } if (found is { } placed) return placed; - // Tiny screen: flip away from the nearest edges and clamp to the bounds. double fx = right; double fy = down; - if (fx + width > Bounds.Width - margin) fx = left; - if (fy + height > Bounds.Height - margin) fy = up; - fx = Math.Clamp(fx, margin, Math.Max(margin, Bounds.Width - width - margin)); - fy = Math.Clamp(fy, margin, Math.Max(margin, Bounds.Height - height - margin)); + if (fx + width > view.Width - margin) fx = left; + if (fy + height > view.Height - margin) fy = up; + fx = Math.Clamp(fx, margin, Math.Max(margin, view.Width - width - margin)); + fy = Math.Clamp(fy, margin, Math.Max(margin, view.Height - height - margin)); return new Rect(fx, fy, width, height); } - void DrawMagnifier(DrawingContext context, Rect? readout) - { - const double inner = 104; - const double pad = 3; - const double labelHeight = 20; - double total = inner + pad * 2; - var box = PlaceMagnifier(total, total + labelHeight, readout); - double x = box.X; - double y = box.Y; - - int imageX = Math.Clamp((int)(_cursor.X * _frame.Width / Math.Max(1, Bounds.Width)), 0, _frame.Width - 1); - int imageY = Math.Clamp((int)(_cursor.Y * _frame.Height / Math.Max(1, Bounds.Height)), 0, _frame.Height - 1); - int sourceSize = 24; - int left = Math.Clamp(imageX - sourceSize / 2, 0, Math.Max(0, _frame.Width - sourceSize)); - int top = Math.Clamp(imageY - sourceSize / 2, 0, Math.Max(0, _frame.Height - sourceSize)); - var source = new Rect(left, top, Math.Min(sourceSize, _frame.Width), Math.Min(sourceSize, _frame.Height)); - var dest = new Rect(x + pad, y + pad, inner, inner); - - context.DrawRectangle(ReadoutBrush, new Pen(AppTheme.Accent, 2), new Rect(x, y, total, total + labelHeight), 7, 7); - using (context.PushClip(dest)) - { - context.DrawImage(_bitmap, source, dest); - } - var center = dest.Center; - context.DrawLine(CrosshairPen, new Point(center.X - 7, center.Y), new Point(center.X + 7, center.Y)); - context.DrawLine(CrosshairPen, new Point(center.X, center.Y - 7), new Point(center.X, center.Y + 7)); - - var label = new FormattedText($"{imageX}, {imageY}", CultureInfo.InvariantCulture, - FlowDirection.LeftToRight, _typeface, 11, AppTheme.Muted); - context.DrawText(label, new Point(x + (total - label.Width) / 2, y + total + 2)); - } + static bool Overlaps(Rect a, Rect b) => + a.Left < b.Right && a.Right > b.Left && a.Top < b.Bottom && a.Bottom > b.Top; } diff --git a/linux/X11Pointer.cs b/linux/X11Pointer.cs new file mode 100644 index 0000000..eaa63d0 --- /dev/null +++ b/linux/X11Pointer.cs @@ -0,0 +1,116 @@ +using System.Runtime.InteropServices; +using Avalonia; + +namespace OpenSnip; + +/// +/// Root-pixel pointer position on X11. A drag is grabbed by the monitor where it started, +/// and that window's coordinates do not continue linearly onto a monitor with another scale. +/// Wayland does not expose the pointer, so the overlay keeps the event it was given. +/// +sealed class X11Pointer : IDisposable +{ + readonly IntPtr _display; + readonly CloseDisplay _close; + readonly QueryPointer _query; + bool _closed; + + X11Pointer(IntPtr display, IntPtr root, CloseDisplay close, QueryPointer query) + { + _display = display; + Root = root; + _close = close; + _query = query; + } + + public IntPtr Display => _display; + public IntPtr Root { get; } + + public static X11Pointer TryOpen() + { + if (!PlatformInfo.HasDisplay || PlatformInfo.IsWayland) return null; + var lib = X11Lib.Handle; + if (lib == IntPtr.Zero) return null; + try + { + var open = Marshal.GetDelegateForFunctionPointer(NativeLibrary.GetExport(lib, "XOpenDisplay")); + var close = Marshal.GetDelegateForFunctionPointer(NativeLibrary.GetExport(lib, "XCloseDisplay")); + var rootOf = Marshal.GetDelegateForFunctionPointer(NativeLibrary.GetExport(lib, "XDefaultRootWindow")); + var query = Marshal.GetDelegateForFunctionPointer(NativeLibrary.GetExport(lib, "XQueryPointer")); + var display = open(null); + if (display == IntPtr.Zero) return null; + var root = rootOf(display); + if (root == IntPtr.Zero) + { + close(display); + return null; + } + return new X11Pointer(display, root, close, query); + } + catch (EntryPointNotFoundException) { return null; } + catch (DllNotFoundException) { return null; } + } + + public PixelPoint? Position() + { + if (_closed) return null; + try + { + if (_query(_display, Root, out _, out _, out int x, out int y, out _, out _, out _) == 0) + return null; + return new PixelPoint(x, y); + } + catch (Exception ex) + { + Log.Error(ex); + return null; + } + } + + public void Dispose() + { + if (_closed) return; + _closed = true; + try { _close(_display); } catch { } + } + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + delegate IntPtr OpenDisplay(string name); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + delegate int CloseDisplay(IntPtr display); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + delegate IntPtr DefaultRoot(IntPtr display); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + delegate int QueryPointer(IntPtr display, IntPtr window, out IntPtr root, out IntPtr child, out int rootX, out int rootY, out int winX, out int winY, out uint mask); +} + +static class X11Lib +{ + static readonly object Gate = new(); + static IntPtr _handle; + static bool _tried; + + public static IntPtr Handle + { + get + { + lock (Gate) + { + if (_tried) return _handle; + _tried = true; + foreach (var name in new[] { "libX11.so.6", "libX11.so", "libX11" }) + { + if (NativeLibrary.TryLoad(name, out var handle)) + { + _handle = handle; + return _handle; + } + } + return IntPtr.Zero; + } + } + } +} diff --git a/tests/OpenSnip.Tests/MonitorMapTests.cs b/tests/OpenSnip.Tests/MonitorMapTests.cs index 21708cd..167eb98 100644 --- a/tests/OpenSnip.Tests/MonitorMapTests.cs +++ b/tests/OpenSnip.Tests/MonitorMapTests.cs @@ -40,6 +40,15 @@ public void Mixed_scale_window_fraction_stays_on_that_monitor() Assert.Equal(1, map.IndexAt(second)); } + [Fact] + public void Local_center_of_a_pixel_stays_on_that_pixel() + { + var map = Mixed(); + var point = map.LocalCenter(1, new PixelPoint(1920, 0), 1920, 1080); + Assert.Equal(0.5 * 1920 / 3840d, point.X, 3); + Assert.InRange(point.Y, 0, 1); + } + [Fact] public void Full_monitor_crop_is_that_monitors_pixels() { diff --git a/tests/OpenSnip.Tests/X11PointerTests.cs b/tests/OpenSnip.Tests/X11PointerTests.cs new file mode 100644 index 0000000..eb51c9c --- /dev/null +++ b/tests/OpenSnip.Tests/X11PointerTests.cs @@ -0,0 +1,12 @@ +namespace OpenSnip.Tests; + +public class X11PointerTests +{ + [Fact] + public void Query_returns_a_point_when_the_display_opens() + { + using var pointer = X11Pointer.TryOpen(); + if (pointer == null) return; + Assert.NotNull(pointer.Position()); + } +} From 66ec87938e10c5d28e1a8c52f7bd7b33b2331eaf Mon Sep 17 00:00:00 2001 From: Devan <68340659+DevanMetz@users.noreply.github.com> Date: Tue, 27 Oct 2026 18:19:43 -0500 Subject: [PATCH 3/4] Capture X11 outputs that sit outside the origin. XRRGetMonitors supplies the bounding box, including monitors left of or above (0, 0). The frame records that origin so the overlay crops 1:1. A rejected grab falls back to the root window. --- linux/Capture.cs | 36 +++++++++- linux/X11Randr.cs | 87 +++++++++++++++++++++++++ tests/OpenSnip.Tests/X11PointerTests.cs | 19 ++++++ 3 files changed, 140 insertions(+), 2 deletions(-) create mode 100644 linux/X11Randr.cs diff --git a/linux/Capture.cs b/linux/Capture.cs index 4a6ebf6..e79d24f 100644 --- a/linux/Capture.cs +++ b/linux/Capture.cs @@ -167,7 +167,23 @@ static CapturedFrame Capture() throw new CaptureException("Cannot read the X11 screen size."); if (width == 0 || height == 0) throw new CaptureException("The X11 screen is empty."); - image = XGetImage(display, root, 0, 0, width, height, AllPlanes, ZPixmap); + var monitors = X11Randr.Query(display, root); + var region = CaptureRegion.From(monitors, (int)width, (int)height); + if (region.Width <= 0 || region.Height <= 0) + region = new CaptureRegion(0, 0, (int)width, (int)height); + + image = Grab(display, root, region); + var rootRegion = new CaptureRegion(0, 0, (int)width, (int)height); + if (!ImageMatches(image, region) && !SameRegion(region, rootRegion)) + { + if (image != IntPtr.Zero) + { + try { XDestroyImage(image); } catch { } + image = IntPtr.Zero; + } + region = rootRegion; + image = Grab(display, root, region); + } if (image == IntPtr.Zero) throw new CaptureException("XGetImage failed."); var header = Marshal.PtrToStructure(image); @@ -220,7 +236,10 @@ static CapturedFrame Capture() } } - return new CapturedFrame(w, h, output); + var frame = new CapturedFrame(w, h, output); + if (header.width == region.Width && header.height == region.Height) + frame.NoteOrigin(region.X, region.Y); + return frame; } catch (DllNotFoundException ex) { throw new CaptureException("libX11 is not available.", ex); } catch (EntryPointNotFoundException ex) { throw new CaptureException("libX11 is missing a required function.", ex); } @@ -231,6 +250,19 @@ static CapturedFrame Capture() } } + static IntPtr Grab(IntPtr display, IntPtr root, CaptureRegion region) => + XGetImage(display, root, region.X, region.Y, (uint)region.Width, (uint)region.Height, AllPlanes, ZPixmap); + + static bool ImageMatches(IntPtr image, CaptureRegion region) + { + if (image == IntPtr.Zero) return false; + var header = Marshal.PtrToStructure(image); + return header.width == region.Width && header.height == region.Height && header.data != IntPtr.Zero; + } + + static bool SameRegion(CaptureRegion a, CaptureRegion b) => + a.X == b.X && a.Y == b.Y && a.Width == b.Width && a.Height == b.Height; + static byte Extract(uint pixel, ulong mask) { if (mask == 0) return 0; diff --git a/linux/X11Randr.cs b/linux/X11Randr.cs new file mode 100644 index 0000000..c9f7aa4 --- /dev/null +++ b/linux/X11Randr.cs @@ -0,0 +1,87 @@ +using System.Runtime.InteropServices; +using Avalonia; + +namespace OpenSnip; + +/// +/// Active XRandR monitors. The layout is the LP64 XRRMonitorInfo from libXrandr 1.5 +/// (56 bytes): Atom name, two Bools, then x, y, width, height at offsets 20, 24, 28 and 32. +/// +static class X11Randr +{ + const int InfoSize = 56; + const int OffX = 20; + const int OffY = 24; + const int OffWidth = 28; + const int OffHeight = 32; + + static readonly object Gate = new(); + static IntPtr _lib; + static bool _tried; + + public static List Query(IntPtr display, IntPtr root) + { + if (display == IntPtr.Zero || root == IntPtr.Zero || IntPtr.Size != 8) return null; + var lib = Library(); + if (lib == IntPtr.Zero) return null; + try + { + var get = Marshal.GetDelegateForFunctionPointer(NativeLibrary.GetExport(lib, "XRRGetMonitors")); + var free = Marshal.GetDelegateForFunctionPointer(NativeLibrary.GetExport(lib, "XRRFreeMonitors")); + IntPtr data = get(display, root, 1, out int count); + if (data == IntPtr.Zero || count <= 0) return null; + try + { + var list = new List(count); + for (int i = 0; i < count; i++) + { + IntPtr item = IntPtr.Add(data, i * InfoSize); + int x = Marshal.ReadInt32(item, OffX); + int y = Marshal.ReadInt32(item, OffY); + int width = Marshal.ReadInt32(item, OffWidth); + int height = Marshal.ReadInt32(item, OffHeight); + if (width <= 0 || height <= 0) continue; + list.Add(new PixelRect(x, y, width, height)); + } + return list.Count == 0 ? null : list; + } + finally + { + free(data); + } + } + catch (EntryPointNotFoundException) { return null; } + catch (DllNotFoundException) { return null; } + } + + public static List TryMonitors() + { + using var pointer = X11Pointer.TryOpen(); + if (pointer == null) return null; + return Query(pointer.Display, pointer.Root); + } + + static IntPtr Library() + { + lock (Gate) + { + if (_tried) return _lib; + _tried = true; + foreach (var name in new[] { "libXrandr.so.2", "libXrandr.so", "libXrandr" }) + { + if (NativeLibrary.TryLoad(name, out var handle)) + { + _lib = handle; + return _lib; + } + } + return IntPtr.Zero; + } + } + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + delegate IntPtr GetMonitors(IntPtr display, IntPtr window, int getActive, out int count); + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + delegate void FreeMonitors(IntPtr monitors); +} diff --git a/tests/OpenSnip.Tests/X11PointerTests.cs b/tests/OpenSnip.Tests/X11PointerTests.cs index eb51c9c..7718731 100644 --- a/tests/OpenSnip.Tests/X11PointerTests.cs +++ b/tests/OpenSnip.Tests/X11PointerTests.cs @@ -9,4 +9,23 @@ public void Query_returns_a_point_when_the_display_opens() if (pointer == null) return; Assert.NotNull(pointer.Position()); } + + [Fact] + public async Task Capture_covers_the_xrandr_bounding_box() + { + var monitors = X11Randr.TryMonitors(); + if (monitors == null) return; + + var expected = CaptureRegion.From(monitors, 1, 1); + CapturedFrame frame; + try { frame = await new X11CaptureBackend().CaptureAsync(); } + catch (CaptureException) { return; } + + Assert.True(frame.OriginKnown); + Assert.Equal(expected.X, frame.OriginX); + Assert.Equal(expected.Y, frame.OriginY); + Assert.Equal(expected.Width, frame.Width); + Assert.Equal(expected.Height, frame.Height); + Assert.Equal(expected.Width * expected.Height * 4, frame.Bgra.Length); + } } From 311242d878925af7f92e373127f73a27a320cdac Mon Sep 17 00:00:00 2001 From: Devan <68340659+DevanMetz@users.noreply.github.com> Date: Tue, 27 Oct 2026 18:19:47 -0500 Subject: [PATCH 4/4] Record mixed-DPI parity against Windows. PARITY.md lists each Windows feature and setting. The README notes per-monitor scale and X11 outputs outside the origin. --- PARITY.md | 83 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ README.md | 5 ++-- 2 files changed, 86 insertions(+), 2 deletions(-) create mode 100644 PARITY.md diff --git a/PARITY.md b/PARITY.md new file mode 100644 index 0000000..e0cb18e --- /dev/null +++ b/PARITY.md @@ -0,0 +1,83 @@ +# Linux parity + +Each Windows feature and setting, and where Linux stands on this branch. + +`working` matches Windows. `partial` works, with the gap named here. `missing` is not implemented. Nothing on this list is `not possible`; where one piece cannot exist, the row says so. + +## Selection + +| Feature | Linux | Where | +|---|---|---| +| Drag a region in desktop pixels (inclusive edge, 3 px before a drag arms) | working | `linux/SnipSession.cs`, `linux/MonitorMap.cs`, `linux/OverlayWindow.cs` | +| One window per monitor at that screen's scale | working | `linux/OverlayWindow.cs`, `linux/MonitorMap.cs` | +| X11 drag across monitors that use different scales | working | `linux/X11Pointer.cs` reads root pixels once the pointer leaves the window | +| Wayland drag across monitors that use different scales | partial | Wayland cannot report the pointer. The press window's coordinates are extended, which stays exact only when both screens share a scale. `linux/OverlayWindow.cs` | +| X11 capture of outputs left of or above the origin | working | `linux/X11Randr.cs`, `linux/Capture.cs`. If the server rejects that rectangle, the grab falls back to the root window at (0, 0). | +| Click grabs the monitor | working | `linux/SnipSession.cs` | +| Click grabs the window under the cursor | missing | `src/CaptureOverlay.cs` | +| `F` grabs the monitor immediately | partial | Linux selects it. Enter completes the grab. `linux/SnipSession.cs` | +| `A` grabs every monitor immediately | partial | Linux selects the desktop. Enter completes the grab. On Windows a recording stays on one monitor. | +| Enter grabs the selection, or the monitor under the cursor | working | `linux/SnipSession.cs` | +| Esc or right-click during a drag cancels the drag first | partial | Linux cancels the whole snip. `linux/SnipSession.cs`, `linux/OverlayWindow.cs` | +| Arrow keys move the pointer 1 px, Shift moves 10 | partial | Linux moves the overlay cursor in desktop pixels and does not move the OS pointer. Wayland cannot warp the pointer. `linux/SnipSession.cs` | +| Magnifier with desktop coordinates | working | `linux/OverlayWindow.cs` | +| Magnifier color | missing | `src/CaptureOverlay.cs` | +| Hint text on the overlay | missing | Left off. The Windows hint is helper text. | +| Nearest-neighbor frozen frame | working | `linux/OverlayWindow.cs` | + +## After a snip + +| Feature | Linux | Where | +|---|---|---| +| Copy a PNG to the clipboard | working | `linux/App.cs` | +| Auto-save PNG or JPG | working | `linux/CapturedFrame.cs`. `--capture file.jpeg` writes a PNG; only the format string `jpg` is JPEG. | +| Monthly subfolders | working | `src/Settings.cs` | +| Preview on the monitor that was snipped | partial | The preview sits on the primary monitor. `linux/ThumbnailWindow.cs` | +| Preview click opens the editor | missing | Click opens the file with `xdg-open`. `linux/ThumbnailWindow.cs` | +| Drag the preview out as a file | missing | `src/SmallWindows.cs` | +| Open the editor after a snip | missing | `OpenEditorAfterSnip` is stored in `src/Settings.cs` and unused on Linux. | +| Pin an image | missing | `src/SmallWindows.cs` | +| Repeat the last region | working | `linux/App.cs` | +| Countdown at the bottom of the monitor under the pointer | partial | The countdown is centered on the primary monitor. `linux/CountdownWindow.cs` | + +## Tray and commands + +| Feature | Linux | Where | +|---|---|---| +| Snip, snip after delay, repeat, screenshots folder, settings, exit | working | `linux/App.cs` | +| Tray click starts a snip | working | `linux/App.cs` | +| Record, pin, editor, recordings folder | missing | `src/TrayApp.cs` | +| Tooltip names the snip shortcut | missing | `src/TrayApp.cs` | +| First-run balloon | missing | Left off. It is helper text. `src/TrayApp.cs` | +| Second instance forwards snip, delay, repeat, and settings | working | `linux/SingleInstance.cs` | +| `--capture` and `--diagnostics` | working | `linux/Cli.cs`, `linux/CaptureCli.cs`, `linux/Diagnostics.cs` | +| Built-in global shortcuts (Win+Shift+S, Win+Shift+R, Print Screen) | missing | Settings lists the commands to bind. `linux/SettingsWindow.cs` | + +## Settings + +| Setting | Linux | Where | +|---|---|---| +| Copy to the clipboard | working | `linux/SettingsWindow.cs` | +| Show a preview, and how long it stays | working | `linux/SettingsWindow.cs` | +| Open the editor, or do nothing else | missing | `src/SettingsForm.cs` | +| Magnifier | working | `linux/SettingsWindow.cs` | +| Delayed-snip length | working | `linux/SettingsWindow.cs` | +| Auto-save, screenshot folder, PNG or JPG, monthly folders | working | `linux/SettingsWindow.cs` | +| Recording folder | missing | `src/SettingsForm.cs` | +| System audio, microphone, device, frame rate, quality, cursor, countdown, copy the video | missing | `src/Settings.cs`, `src/Recording.cs` | +| Shortcut editor and Print Screen | missing | The Shortcuts page lists commands. `linux/SettingsWindow.cs` | +| Start on login | working | XDG autostart. `linux/Autostart.cs` | +| Open the settings folder, reset to defaults | working | `linux/SettingsWindow.cs` | + +## Capture + +| Backend | Linux | Where | +|---|---|---| +| X11 through libX11, then `maim`, ImageMagick `import`, and `scrot` | partial | The native grab uses `DllImport("libX11")`, so a system that only has `libX11.so.6` fails that path and uses a fallback. `linux/Capture.cs` | +| Wayland portal, then `grim`, `gnome-screenshot`, and `spectacle` | partial | A portal image whose size is not the desktop bounding box is stretched across that box, so mixed DPI is not pixel-exact. `linux/DBus.cs`, `linux/MonitorMap.cs` | + +## Recording + +| Feature | Linux | Where | +|---|---|---| +| Region recording, audio, cursor, countdown, red outline, control bar | missing | `src/Recording.cs` | diff --git a/README.md b/README.md index 987b573..f61f505 100644 --- a/README.md +++ b/README.md @@ -117,7 +117,7 @@ Run `OpenSnip.exe --diagnostics` to write a report (displays, audio devices, and The Linux app is a separate native Avalonia build. It covers the screenshot side of OpenSnip; recording, the annotation editor, pins and built-in global shortcuts remain Windows-only. -**What works:** X11 capture through libX11, with `maim`, ImageMagick `import` and `scrot` as fallbacks; Wayland capture through the `xdg-desktop-portal` Screenshot API, with `grim`, `gnome-screenshot` and `spectacle` as fallbacks; region, monitor and all-monitor selection with a magnifier; clipboard as PNG; auto-save as PNG or JPG; preview; tray icon; and settings. +**What works:** X11 capture through libX11, with `maim`, ImageMagick `import` and `scrot` as fallbacks; Wayland capture through the `xdg-desktop-portal` Screenshot API, with `grim`, `gnome-screenshot` and `spectacle` as fallbacks; region, monitor and all-monitor selection, one window per screen at that screen's scale, with a magnifier; clipboard as PNG; auto-save as PNG or JPG; preview; tray icon; and settings. X11 capture includes outputs that sit left of or above the origin. **Install:** download `OpenSnip-linux-x64.tar.gz` from [Releases](https://github.com/DevanMetz/OpenSnip/releases), then: @@ -207,7 +207,8 @@ Issues and pull requests are welcome. The code is plain WinForms + GDI+; recordi | `src/Imaging.cs` | Screen capture, window detection, clipboard, saving, icon | | `linux/Program.cs` / `linux/App.cs` | Linux app startup, single instance, tray and snip flow | | `linux/Capture.cs` / `linux/DBus.cs` | X11, Wayland portal and external capture backends | -| `linux/OverlayWindow.cs` | Linux selection overlay and magnifier | +| `linux/OverlayWindow.cs` | One Linux selection window per monitor, and the magnifier | +| `linux/MonitorMap.cs` | Desktop-pixel mapping for mixed-DPI snips | | `linux/SettingsWindow.cs` | Linux Settings window | ## License