diff --git a/PARITY.md b/PARITY.md index 72cb700..9c36963 100644 --- a/PARITY.md +++ b/PARITY.md @@ -11,11 +11,12 @@ Status of each Windows feature on Linux. This file describes the tree it ships w | Region snip on a frozen screen | working | `linux/Capture.cs`, `linux/OverlayWindow.cs` | | Click grabs the monitor | working | `linux/OverlayWindow.cs` | | Click grabs the window under the cursor | partial. X11 only | `linux/OverlayWindow.cs`, `src/CaptureOverlay.cs` | -| `F` captures the monitor under the cursor immediately | working | `linux/SnipGesture.cs`, `linux/OverlayWindow.cs` | -| `A` captures all monitors immediately | working. Recording selects the monitor under the cursor. | `linux/SnipGesture.cs`, `linux/OverlayWindow.cs` | +| `F` selects the monitor; Enter captures it | partial | `linux/SnipGesture.cs`, `linux/OverlayWindow.cs` | +| `A` selects all monitors; Enter captures them | partial | `linux/SnipGesture.cs`, `linux/OverlayWindow.cs` | | Enter confirms the selection or monitor; arrows nudge 1 px, or 10 with Shift | working. X11 warps the pointer; Wayland moves the overlay cursor. | `linux/SnipGesture.cs`, `linux/OverlayWindow.cs` | -| Esc and right-click cancel the drag first, then the snip | working | `linux/SnipGesture.cs`, `linux/OverlayWindow.cs` | -| Mixed-DPI placement | partial. The overlay uses one scale for the whole desktop. | `linux/OverlayWindow.cs` | +| Esc and right-click cancel the snip | partial | `linux/SnipGesture.cs`, `linux/OverlayWindow.cs` | +| Mixed-DPI placement | working on X11, with one window per monitor. Wayland cross-monitor drags are exact when scales match. | `linux/OverlayWindow.cs`, `linux/MonitorMap.cs`, `linux/X11Pointer.cs` | +| X11 outputs left of or above the origin | working. Capture falls back to the root at (0, 0) if the server rejects the bounding box. | `linux/X11Randr.cs`, `linux/Capture.cs` | | Magnifier with coordinates | working | `linux/OverlayWindow.cs` | | Magnifier color | working | `linux/OverlayWindow.cs` | | X11 capture | working | `linux/Capture.cs` | diff --git a/README.md b/README.md index 36f3f56..4767e98 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 screenshots, annotation, pinned images, global shortcuts and screen recording on X11. -**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, window, monitor and all-monitor selection with a magnifier; clipboard as PNG; auto-save as PNG or JPG; preview; annotation; pinned images (under the pointer on X11, centered on Wayland); tray icon; global shortcuts and MP4 recording on X11; 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, window, monitor and all-monitor selection with a magnifier and one overlay window per screen at its scale; clipboard as PNG; auto-save as PNG or JPG; preview; annotation; pinned images (under the pointer on X11, centered on Wayland); tray icon; global shortcuts and MP4 recording on X11; and settings. X11 capture includes outputs left of or above the origin. **Install:** download `OpenSnip-linux-x64.tar.gz` from [Releases](https://github.com/DevanMetz/OpenSnip/releases), then: @@ -228,7 +228,8 @@ Issues and pull requests are welcome. The code is plain WinForms + GDI+; recordi | `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/X11Windows.cs` | Top-level X11 windows for click-to-capture | -| `linux/OverlayWindow.cs` | Linux selection overlay and magnifier | +| `linux/OverlayWindow.cs` | Per-monitor Linux selection overlays and magnifier | +| `linux/MonitorMap.cs` | Desktop-pixel mapping for mixed-DPI snips | | `linux/RecordingSession.cs` | X11 recording, red outline, and control bar | | `linux/PinWindow.cs` | Linux pinned images | | `linux/Annotation.cs` | Annotation shapes for the Linux editor | diff --git a/linux/App.cs b/linux/App.cs index 6a35b16..69e9576 100644 --- a/linux/App.cs +++ b/linux/App.cs @@ -411,8 +411,7 @@ public async void StartRecording() if (hadThumbnail) await Task.Delay(100); var frame = await CaptureService.CaptureAsync(); - var overlay = new OverlayWindow(frame, Settings, WindowsFor(frame), record: true); - var region = await overlay.SelectAsync(); + var region = await OverlayWindow.SelectAsync(frame, Settings, WindowsFor(frame), record: true); if (region is not { } selected) return; var monitors = X11Monitors.Query(); @@ -493,12 +492,11 @@ public async void StartSnip(int delaySeconds = 0, int settleMs = 0) if (delaySeconds > 0) await CountdownWindow.RunAsync(delaySeconds); var frame = await CaptureService.CaptureAsync(); - var overlay = new OverlayWindow(frame, Settings, WindowsFor(frame)); - var region = await overlay.SelectAsync(); + var region = await OverlayWindow.SelectAsync(frame, Settings, WindowsFor(frame)); if (region is not { } selected) return; _lastRegion = selected; - _lastScreen = SnipGeometry.ToScreen(selected, overlay.VirtualBounds, frame.Width, frame.Height); + _lastScreen = OverlayWindow.ScreenRect(frame, selected); var cropped = frame.Crop(selected.X, selected.Y, selected.Width, selected.Height); await DeliverAsync(cropped, _lastScreen.Value); } diff --git a/linux/Capture.cs b/linux/Capture.cs index 8c12906..033ff41 100644 --- a/linux/Capture.cs +++ b/linux/Capture.cs @@ -180,7 +180,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); @@ -233,7 +249,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); } @@ -244,6 +263,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/CapturedFrame.cs b/linux/CapturedFrame.cs index 9223132..2c02a64 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 new file mode 100644 index 0000000..32171a1 --- /dev/null +++ b/linux/MonitorMap.cs @@ -0,0 +1,290 @@ +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 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; + 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/OverlayWindow.cs b/linux/OverlayWindow.cs index 5224fc1..5200e14 100644 --- a/linux/OverlayWindow.cs +++ b/linux/OverlayWindow.cs @@ -2,588 +2,506 @@ 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 { - readonly TaskCompletionSource _result = new(TaskCreationOptions.RunContinuationsAsynchronously); - readonly PixelRect _virtualBounds; - readonly CaptureCanvas _canvas; - - public OverlayWindow(CapturedFrame frame, Settings settings, PixelRect[] windows = null, bool record = false) - { - 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 scale = Screens.ScreenFromPoint(union.Position)?.Scaling - ?? Screens.Primary?.Scaling - ?? 1; - - Title = "OpenSnip"; - Icon = IconLoader.Icon; - SystemDecorations = SystemDecorations.None; - CanResize = false; - Topmost = true; - ShowInTaskbar = false; - 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); - - _canvas = new CaptureCanvas(frame, settings, union, windows, Complete, record); - Content = _canvas; - Closed += (_, _) => _result.TrySetResult(null); - } - - public PixelRect VirtualBounds => _virtualBounds; - - public Task SelectAsync() - { - Show(); - Activate(); - Focus(); - _canvas.Focus(); - return _result.Task; - } - - protected override void OnOpened(EventArgs e) - { - base.OnOpened(e); - _canvas.Focus(); - } - - protected override void OnKeyDown(KeyEventArgs e) + public static PixelRect ScreenRect(CapturedFrame frame, PixelRect image) { - if (_canvas.HandleKey(e)) + var map = MonitorMap.Create(OverlaySession.ReadLayouts(frame), frame.Width, frame.Height, frame.OriginKnown, frame.OriginX, frame.OriginY); + if (map.OneToOne) { - e.Handled = true; - return; + int x = frame.OriginKnown ? frame.OriginX : map.Desktop.X; + int y = frame.OriginKnown ? frame.OriginY : map.Desktop.Y; + return new PixelRect(image.X + x, image.Y + y, image.Width, image.Height); } - base.OnKeyDown(e); + return SnipGeometry.ToScreen(image, map.Desktop, frame.Width, frame.Height); } - void Complete(PixelRect? selection) + public static Task SelectAsync(CapturedFrame frame, Settings settings, PixelRect[] windows = null, bool record = false) { - if (_result.TrySetResult(selection)) Close(); + var session = new OverlaySession(frame, settings, windows, record); + return session.Run(); } } -sealed class CaptureCanvas : Control +sealed class OverlaySession { - readonly CapturedFrame _frame; - readonly Bitmap _bitmap; readonly Settings _settings; - readonly PixelRect _virtualBounds; - readonly PixelRect[] _windows; - readonly bool _windowsAlign; - readonly Action _complete; - readonly Typeface _typeface = new("Inter"); + readonly CapturedFrame _frame; + readonly PixelRect[] _targets; readonly bool _record; - readonly IPen _framePen; - readonly IPen _hairPen; - - bool _pressing; - bool _dragging; - bool _hasPointer; - bool _keyboardCursor; - IPointer _pointer; - Point _start; - Point _end; - Point _cursor; - Rect? _selection; - Rect? _hoverLocal; - PixelRect? _hoverImage; - - static readonly IBrush DimBrush = new SolidColorBrush(Color.FromArgb(150, 0, 0, 0)); - static readonly IBrush ReadoutBrush = new SolidColorBrush(Color.FromArgb(238, 38, 38, 44)); + readonly MonitorMap _map; + readonly SnipSession _snip; + readonly X11Pointer _pointer; + readonly WriteableBitmap _bitmap; + readonly List _windows = new(); + readonly TaskCompletionSource _result = new(TaskCreationOptions.RunContinuationsAsynchronously); + bool _done; - public CaptureCanvas(CapturedFrame frame, Settings settings, PixelRect virtualBounds, PixelRect[] windows, Action complete, bool record = false) + public OverlaySession(CapturedFrame frame, Settings settings, PixelRect[] windows, bool record) { - _frame = frame; - _bitmap = frame.ToBitmap(); _settings = settings; - _virtualBounds = virtualBounds; - _windows = windows ?? Array.Empty(); - _windowsAlign = frame.Width == virtualBounds.Width && frame.Height == virtualBounds.Height; - _complete = complete; + _frame = frame; + _targets = windows; _record = record; - var color = record ? AppTheme.Record : AppTheme.Accent; - _framePen = new Pen(color, 2); - _hairPen = new Pen(color, 1); - Focusable = true; - ClipToBounds = true; + _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 bool HandleKey(KeyEventArgs e) + public MonitorMap Map => _map; + public SnipSession Snip => _snip; + public Settings Settings => _settings; + public WriteableBitmap Bitmap => _bitmap; + public CapturedFrame Frame => _frame; + public PixelRect? Hover(PixelPoint point) { - if (!TryMapKey(e.Key, out var key)) return false; - bool pastSlop = DragPastSlop(); - bool ready = pastSlop && SelectionReady; - Apply(SnipGesture.FromKey(key, e.KeyModifiers.HasFlag(KeyModifiers.Shift), _pressing, ready, pastSlop)); - return true; + if (!_map.TryToImage(new PixelRect(point.X, point.Y, 1, 1), out var image)) return null; + var hit = WindowHit.At(_targets, image.X, image.Y, _frame.Width, _frame.Height); + if (hit is not { } rect || !_map.OneToOne) return null; + return new PixelRect(rect.X + point.X - image.X, rect.Y + point.Y - image.Y, rect.Width, rect.Height); } - - bool DragPastSlop() + public SnipOutcome Release(PixelPoint point) { - if (!_pressing) return false; - return Math.Abs(_end.X - _start.X) > 3 || Math.Abs(_end.Y - _start.Y) > 3; + var hover = Hover(point); + var outcome = _snip.Release(point); + if (hover is { } window && outcome.HasRegion && outcome.Region == _map.MonitorRectAt(point)) + return SnipOutcome.Chosen(window); + return outcome; } - static bool TryMapKey(Key key, out SnipKey mapped) + public Task Run() { - switch (key) + 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++) { - case Key.Escape: mapped = SnipKey.Escape; return true; - case Key.Enter: mapped = SnipKey.Enter; return true; - case Key.F: mapped = SnipKey.Monitor; return true; - case Key.A: mapped = SnipKey.All; return true; - case Key.Left: mapped = SnipKey.Left; return true; - case Key.Right: mapped = SnipKey.Right; return true; - case Key.Up: mapped = SnipKey.Up; return true; - case Key.Down: mapped = SnipKey.Down; return true; - default: mapped = default; return false; + if (_map.Monitors[i].Primary) focus = i; } - } - - bool SelectionReady => _selection is { Width: >= 1, Height: >= 1 }; - void Apply(SnipGesture gesture) - { - switch (gesture.Kind) + for (int i = 0; i < _windows.Count; i++) { - case SnipGestureKind.Cancel: - _complete(null); - break; - case SnipGestureKind.ResetDrag: - ResetDrag(); - break; - case SnipGestureKind.CompleteSelection: - if (_selection is { } current) _complete(ToImageRect(current)); - break; - case SnipGestureKind.CompleteMonitor: - _complete(ToImageRect(MonitorRect(CurrentCursor()))); - break; - case SnipGestureKind.CompleteAll: - _complete(_record ? ToImageRect(MonitorRect(CurrentCursor())) : new PixelRect(0, 0, _frame.Width, _frame.Height)); - break; - case SnipGestureKind.Nudge: - Nudge(gesture.Dx, gesture.Dy); - break; + _windows[i].ShowActivated = i == focus; + _windows[i].Show(); } + _windows[focus].Activate(); + _windows[focus].FocusCanvas(); + return _result.Task; } - void ResetDrag() + public PixelPoint PointerDesktop(int index, Point local, Size size) { - _pressing = false; - _dragging = false; - _selection = null; - try { _pointer?.Capture(null); } catch { } - _pointer = null; - InvalidateVisual(); + 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); } - void Nudge(int dx, int dy) + public void Apply(SnipOutcome outcome) { - if (X11Cursor.TryGet() is { } pointer) + if (_done) return; + if (!outcome.Close) { - var screen = SnipGeometry.ClampTo(pointer.X + dx, pointer.Y + dy, _virtualBounds); - bool warped = X11Cursor.TryWarp(screen.X, screen.Y); - MoveCursor(ScreenToLocal(screen.X, screen.Y), keyboard: !warped); + Invalidate(); return; } - - var delta = SnipGeometry.ControlDelta(dx, dy, Bounds.Width, Bounds.Height, _frame.Width, _frame.Height); - var origin = _hasPointer ? _cursor : new Point(Bounds.Width / 2, Bounds.Height / 2); - MoveCursor(origin + new Vector(delta.X, delta.Y), keyboard: true); + if (outcome.Cancel || !outcome.HasRegion || !_map.TryToImage(outcome.Region, out var image)) + Finish(null); + else + Finish(_record ? outcome.Region : image); } - void MoveCursor(Point local, bool keyboard) + public void WindowClosed() => Finish(null); + + void Invalidate() { - _cursor = ClampPoint(local); - _hasPointer = true; - _keyboardCursor = keyboard; - if (_pressing) - { - _end = _cursor; - var rect = RectFromPoints(_start, _end); - if (rect.Width >= 3 || rect.Height >= 3) _dragging = true; - if (_dragging) - { - _selection = rect.Width >= 1 && rect.Height >= 1 ? rect : null; - ClearHover(); - } - } - if (!_dragging) UpdateHover(_cursor); - InvalidateVisual(); + foreach (var window in _windows) window.InvalidateCanvas(); } - protected override void OnPointerPressed(PointerPressedEventArgs e) + void Finish(PixelRect? image) { - base.OnPointerPressed(e); - Focus(); - var point = e.GetPosition(this); - if (e.GetCurrentPoint(this).Properties.IsRightButtonPressed) + if (_done) return; + _done = true; + _result.TrySetResult(image); + foreach (var window in _windows.ToArray()) { - Apply(SnipGesture.FromRightClick(_pressing)); - e.Handled = true; - return; + try { window.Close(); } catch { } } - if (!e.GetCurrentPoint(this).Properties.IsLeftButtonPressed) return; - - _pressing = true; - _dragging = false; - _pointer = e.Pointer; - _start = _end = _cursor = ClampPoint(point); - _hasPointer = true; - _keyboardCursor = false; - _selection = null; - UpdateHover(_cursor); - e.Pointer.Capture(this); - InvalidateVisual(); - e.Handled = true; + _pointer?.Dispose(); + var bitmap = _bitmap; + Dispatcher.UIThread.Post(() => + { + try { bitmap.Dispose(); } catch { } + }, DispatcherPriority.Background); } - protected override void OnPointerMoved(PointerEventArgs e) + public static List ReadLayouts(CapturedFrame frame) { - base.OnPointerMoved(e); - var point = ClampPoint(e.GetPosition(this)); - _cursor = point; - _hasPointer = true; - _keyboardCursor = false; - _end = point; - if (_pressing) + var layouts = new List(); + Window probe = null; + try { - var rect = RectFromPoints(_start, point); - if (rect.Width >= 3 || rect.Height >= 3) + 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) { - _dragging = true; - _selection = rect.Width >= 1 && rect.Height >= 1 ? rect : null; - ClearHover(); + 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)); + } } } - else if (_selection == null) + catch (Exception ex) { - _keyboardCursor = false; - UpdateHover(point); + Log.Error(ex); + } + finally + { + try { probe?.Close(); } catch { } } - InvalidateVisual(); - } - protected override void OnPointerReleased(PointerReleasedEventArgs e) - { - base.OnPointerReleased(e); - if (!_pressing) return; - _pressing = false; - _pointer = null; - e.Pointer.Capture(null); - var point = ClampPoint(e.GetPosition(this)); - _cursor = point; - if (!_dragging) + if (layouts.Count == 0) { - _complete(HitAt(point).Image); - return; + layouts.Add(new MonitorLayout( + new PixelRect(0, 0, Math.Max(1, frame.Width), Math.Max(1, frame.Height)), + 1, + true)); } - _dragging = false; - _complete(ToImageRect(RectFromPoints(_start, point))); + return layouts; } +} - protected override void OnPointerWheelChanged(PointerWheelEventArgs e) - { - base.OnPointerWheelChanged(e); - e.Handled = true; - } +sealed class MonitorOverlayWindow : Window +{ + readonly OverlaySession _session; + readonly MonitorLayout _layout; + readonly CaptureCanvas _canvas; + bool _fitting; - Rect RectFromPoints(Point a, Point b) + public MonitorOverlayWindow(OverlaySession session, int index) { - 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))); + _session = session; + _layout = session.Map.Monitors[index]; + Title = "OpenSnip"; + Icon = IconLoader.Icon; + SystemDecorations = SystemDecorations.None; + CanResize = false; + Topmost = true; + ShowInTaskbar = false; + WindowStartupLocation = WindowStartupLocation.Manual; + Background = Brushes.Black; + Cursor = new Cursor(StandardCursorType.Cross); + 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); - Point CurrentCursor() - { - if (_hasPointer) return _cursor; - if (Bounds.Width > 1 && X11Cursor.TryGet() is { } pointer) - { - _cursor = ClampPoint(ScreenToLocal(pointer.X, pointer.Y)); - _hasPointer = true; - return _cursor; - } - if (Bounds.Width > 1) return new Point(Bounds.Width / 2, Bounds.Height / 2); - return new Point(0, 0); + _canvas = new CaptureCanvas(session, index); + Content = _canvas; + Opened += (_, _) => Fit(); + ScalingChanged += (_, _) => Fit(); + Closed += (_, _) => session.WindowClosed(); + AddHandler(KeyDownEvent, OnKey, RoutingStrategies.Tunnel); } - Point ScreenToLocal(int screenX, int screenY) + public void FocusCanvas() { - double sx = Bounds.Width / Math.Max(1, _virtualBounds.Width); - double sy = Bounds.Height / Math.Max(1, _virtualBounds.Height); - return new Point((screenX - _virtualBounds.X) * sx, (screenY - _virtualBounds.Y) * sy); + Focus(); + _canvas.Focus(); } - 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); - } + public void InvalidateCanvas() => _canvas.InvalidateVisual(); - readonly struct ScreenHit + void OnKey(object sender, KeyEventArgs e) { - public PixelRect Image { get; init; } - public Rect Local { get; init; } + SnipCommand? command = e.Key switch + { + 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; + var outcome = _session.Snip.Command(command.Value, e.KeyModifiers.HasFlag(KeyModifiers.Shift)); + if (command is SnipCommand.Left or SnipCommand.Right or SnipCommand.Up or SnipCommand.Down && !PlatformInfo.IsWayland) + X11Pointer.TryWarp(null, _session.Snip.Cursor.X, _session.Snip.Cursor.Y); + _session.Apply(outcome); + e.Handled = true; } - ScreenHit HitAt(Point local) + void Fit() { - if (_windowsAlign) + if (_fitting) return; + _fitting = true; + try { - int x = ImageCoord(local.X, Bounds.Width, _frame.Width); - int y = ImageCoord(local.Y, Bounds.Height, _frame.Height); - var window = WindowHit.At(_windows, x, y, _frame.Width, _frame.Height); - if (window is { } rect) - return new ScreenHit { Image = rect, Local = ImageToLocal(rect) }; + 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; } - var monitor = MonitorRect(local); - return new ScreenHit { Image = ToImageRect(monitor), Local = monitor }; } +} + +sealed class CaptureCanvas : Control +{ + readonly OverlaySession _session; + readonly int _index; + readonly Typeface _typeface = new("Inter"); + + 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); - void UpdateHover(Point local) + public CaptureCanvas(OverlaySession session, int index) { - var hit = HitAt(local); - _hoverImage = hit.Image; - _hoverLocal = hit.Local; + _session = session; + _index = index; + Focusable = true; + ClipToBounds = true; + Cursor = new Cursor(StandardCursorType.Cross); + RenderOptions.SetBitmapInterpolationMode(this, BitmapInterpolationMode.None); } - void ClearHover() + protected override void OnPointerPressed(PointerPressedEventArgs e) { - _hoverImage = null; - _hoverLocal = null; + base.OnPointerPressed(e); + Focus(); + var point = e.GetCurrentPoint(this); + if (point.Properties.IsRightButtonPressed) + { + _session.Apply(SnipOutcome.Cancelled()); + e.Handled = true; + return; + } + if (!point.Properties.IsLeftButtonPressed) return; + _session.Snip.Press(_session.PointerDesktop(_index, e.GetPosition(this), Bounds.Size)); + _session.Apply(SnipOutcome.Continue()); + e.Handled = true; } - Rect ImageToLocal(PixelRect rect) + protected override void OnPointerMoved(PointerEventArgs e) { - double sx = Bounds.Width / Math.Max(1, _frame.Width); - double sy = Bounds.Height / Math.Max(1, _frame.Height); - return new Rect(rect.X * sx, rect.Y * sy, rect.Width * sx, rect.Height * sy); + base.OnPointerMoved(e); + _session.Snip.Move(_session.PointerDesktop(_index, e.GetPosition(this), Bounds.Size)); + _session.Apply(SnipOutcome.Continue()); + e.Handled = true; } - static int ImageCoord(double local, double localSpan, int imageSpan) + protected override void OnPointerReleased(PointerReleasedEventArgs e) { - if (localSpan <= 0 || imageSpan <= 0) return 0; - int value = (int)Math.Floor(local * imageSpan / localSpan); - if (value < 0) return 0; - if (value >= imageSpan) return imageSpan - 1; - return value; + base.OnPointerReleased(e); + if (!_session.Snip.Dragging) return; + var outcome = _session.Release(_session.PointerDesktop(_index, e.GetPosition(this), Bounds.Size)); + _session.Apply(outcome); + e.Handled = true; } - PixelRect ToImageRect(Rect local) + protected override void OnPointerWheelChanged(PointerWheelEventArgs e) { - 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); + base.OnPointerWheelChanged(e); + e.Handled = true; } public override void Render(DrawingContext context) { - if (!_hasPointer) CurrentCursor(); 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; - var active = _selection ?? _hoverLocal; - if (active is { } selection) + if ((snip.Selection ?? (snip.HasCursor && !snip.Dragging ? _session.Hover(snip.Cursor) : null)) 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, _framePen, selection); - readout = DrawReadout(context, selection, _selection == null ? _hoverImage : null); + 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(_hairPen, new Point(_cursor.X - 8, _cursor.Y), new Point(_cursor.X + 8, _cursor.Y)); - context.DrawLine(_hairPen, 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, PixelRect? exact) + bool Owns(PixelPoint point) => _session.Map.IndexAt(point) == _index; + + static void DimOutside(DrawingContext context, Rect view, Rect box) { - int width; - int height; - if (exact is { } pixels) - { - width = Math.Max(1, pixels.Width); - height = Math.Max(1, pixels.Height); - } - else - { - double sx = _frame.Width / Math.Max(1, Bounds.Width); - double sy = _frame.Height / Math.Max(1, Bounds.Height); - width = Math.Max(1, (int)Math.Round(selection.Width * sx)); - 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; - Rect PlaceMagnifier(double width, double height, Rect? readout) + 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 = imageX - sourceSize / 2; + int top = imageY - sourceSize / 2; + int srcL = Math.Max(0, left), srcT = Math.Max(0, top); + int srcR = Math.Min(frameW, left + sourceSize), srcB = Math.Min(frameH, top + sourceSize); + var source = new Rect(srcL, srcT, srcR - srcL, srcB - srcT); + 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, new Rect(dest.X + (srcL - left) * inner / sourceSize, dest.Y + (srcT - top) * inner / sourceSize, source.Width * inner / sourceSize, source.Height * inner / sourceSize)); + var center = new Point(dest.X + (imageX - left + 0.5) * inner / sourceSize, dest.Y + (imageY - top + 0.5) * inner / sourceSize); + 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($"{_session.Snip.Cursor.X}, {_session.Snip.Cursor.Y} {_session.Frame.ColorLabel(imageX, imageY)}", 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 = 22; - const int sourceSize = 24; - - int imageX = ImageCoord(_cursor.X, Bounds.Width, _frame.Width); - int imageY = ImageCoord(_cursor.Y, Bounds.Height, _frame.Height); - var label = new FormattedText(_frame.ColorLabel(imageX, imageY), CultureInfo.InvariantCulture, - FlowDirection.LeftToRight, _typeface, 11, AppTheme.Muted); - - double square = inner + pad * 2; - double boxW = Math.Max(square, label.Width + 16); - var box = PlaceMagnifier(boxW, square + labelHeight, readout); - double squareX = box.X + (boxW - square) / 2; - var dest = new Rect(squareX + pad, box.Y + pad, inner, inner); - - context.DrawRectangle(ReadoutBrush, _framePen, new Rect(box.X, box.Y, boxW, square + labelHeight), 7, 7); - - // Keep the source centered on the cursor. Clamping it used to slide the - // crosshair off the real pixel once the cursor reached the screen edge. - int left = imageX - sourceSize / 2; - int top = imageY - sourceSize / 2; - int srcL = Math.Max(0, left); - int srcT = Math.Max(0, top); - int srcR = Math.Min(_frame.Width, left + sourceSize); - int srcB = Math.Min(_frame.Height, top + sourceSize); - double scale = inner / sourceSize; - if (srcR > srcL && srcB > srcT) - { - var source = new Rect(srcL, srcT, srcR - srcL, srcB - srcT); - var destPart = new Rect( - dest.X + (srcL - left) * scale, - dest.Y + (srcT - top) * scale, - (srcR - srcL) * scale, - (srcB - srcT) * scale); - using (context.PushClip(dest)) - context.DrawImage(_bitmap, source, destPart); - } - - double cx = dest.X + (imageX - left + 0.5) * scale; - double cy = dest.Y + (imageY - top + 0.5) * scale; - context.DrawLine(_hairPen, new Point(cx - 7, cy), new Point(cx + 7, cy)); - context.DrawLine(_hairPen, new Point(cx, cy - 7), new Point(cx, cy + 7)); - - context.DrawText(label, new Point(box.X + (boxW - label.Width) / 2, box.Y + square + 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/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/linux/X11Pointer.cs b/linux/X11Pointer.cs index a717fb3..d57e2b3 100644 --- a/linux/X11Pointer.cs +++ b/linux/X11Pointer.cs @@ -1,58 +1,111 @@ using System.Runtime.InteropServices; +using Avalonia; namespace OpenSnip; /// -/// Reads the X11 pointer. The import uses libX11.so.6 because desktops ship that soname; -/// the unversioned libX11.so symlink is only in the development package. +/// 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. /// -static class X11Pointer +sealed class X11Pointer : IDisposable { - public static (int X, int Y)? TryGet(string displayName = null) + 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 (!TryOpen(displayName, out var display)) return null; + if (!PlatformInfo.HasDisplay || PlatformInfo.IsWayland) return null; + var lib = X11Lib.Handle; + if (lib == IntPtr.Zero) return null; try { - var root = Native.XDefaultRootWindow(display); - if (root == IntPtr.Zero) return null; - if (Native.XQueryPointer(display, root, out _, out _, out int x, out int y, out _, out _, out _) == 0) + 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 (x, y); + } + return new X11Pointer(display, root, close, query); } - catch (DllNotFoundException) { return null; } catch (EntryPointNotFoundException) { return null; } - finally - { - try { Native.XCloseDisplay(display); } catch { } - } + catch (DllNotFoundException) { return null; } } - public static bool TryWarp(string displayName, int x, int y) + public PixelPoint? Position() { - if (!TryOpen(displayName, out var display)) return false; + if (_closed) return null; try { - var root = Native.XDefaultRootWindow(display); - if (root == IntPtr.Zero) return false; - Native.XWarpPointer(display, IntPtr.Zero, root, 0, 0, 0, 0, x, y); - Native.XSync(display, 0); - return true; + if (_query(_display, Root, out _, out _, out int x, out int y, out _, out _, out _) == 0) + return null; + return new PixelPoint(x, y); } - catch (DllNotFoundException) { return false; } - catch (EntryPointNotFoundException) { return false; } - finally + catch (Exception ex) + { + Log.Error(ex); + return null; + } + } + + public void Dispose() + { + if (_closed) return; + _closed = true; + try { _close(_display); } catch { } + } + + public static (int X, int Y)? TryGet(string displayName = null) + { + try { - try { Native.XCloseDisplay(display); } catch { } + var display = Native.XOpenDisplay(displayName); + if (display == IntPtr.Zero) return null; + try + { + var root = Native.XDefaultRootWindow(display); + return root != IntPtr.Zero && Native.XQueryPointer(display, root, out _, out _, out int x, out int y, out _, out _, out _) != 0 ? (x, y) : null; + } + finally { Native.XCloseDisplay(display); } } + catch (DllNotFoundException) { return null; } + catch (EntryPointNotFoundException) { return null; } } - static bool TryOpen(string displayName, out IntPtr display) + public static bool TryWarp(string displayName, int x, int y) { - display = IntPtr.Zero; try { - display = Native.XOpenDisplay(displayName); - return display != IntPtr.Zero; + var display = Native.XOpenDisplay(displayName); + if (display == IntPtr.Zero) return false; + try + { + var root = Native.XDefaultRootWindow(display); + if (root == IntPtr.Zero) return false; + Native.XWarpPointer(display, IntPtr.Zero, root, 0, 0, 0, 0, x, y); + Native.XSync(display, 0); + return true; + } + finally { Native.XCloseDisplay(display); } } catch (DllNotFoundException) { return false; } catch (EntryPointNotFoundException) { return false; } @@ -61,12 +114,51 @@ static bool TryOpen(string displayName, out IntPtr display) static class Native { const string Lib = "libX11.so.6"; - - [DllImport(Lib)] public static extern IntPtr XOpenDisplay(string displayName); + [DllImport(Lib)] public static extern IntPtr XOpenDisplay(string name); [DllImport(Lib)] public static extern int XCloseDisplay(IntPtr display); [DllImport(Lib)] public static extern IntPtr XDefaultRootWindow(IntPtr display); [DllImport(Lib)] public static extern int XQueryPointer(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); [DllImport(Lib)] public static extern int XWarpPointer(IntPtr display, IntPtr src, IntPtr dest, int srcX, int srcY, uint srcWidth, uint srcHeight, int destX, int destY); [DllImport(Lib)] public static extern int XSync(IntPtr display, int discard); } + + [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/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/MonitorMapTests.cs b/tests/OpenSnip.Tests/MonitorMapTests.cs new file mode 100644 index 0000000..167eb98 --- /dev/null +++ b/tests/OpenSnip.Tests/MonitorMapTests.cs @@ -0,0 +1,147 @@ +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 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() + { + 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/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); + } +} diff --git a/tests/OpenSnip.Tests/X11PointerTests.cs b/tests/OpenSnip.Tests/X11PointerTests.cs index 605e291..9bd13c8 100644 --- a/tests/OpenSnip.Tests/X11PointerTests.cs +++ b/tests/OpenSnip.Tests/X11PointerTests.cs @@ -4,6 +4,32 @@ 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()); + } + + [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); + } [Fact] public void Query_returns_the_warped_pointer() {