From 54308ffb27ea4e41b0a1893f68063a8a2a147ecc Mon Sep 17 00:00:00 2001 From: tznind Date: Sun, 6 Oct 2024 19:12:50 +0100 Subject: [PATCH] Sixel resolution measuring --- .../ConsoleDrivers/EscSeqUtils/EscSeqUtils.cs | 4 +++ Terminal.Gui/Drawing/SixelSupportDetector.cs | 31 +++++++++++++++++-- 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqUtils.cs b/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqUtils.cs index 8bd970966..2065ced28 100644 --- a/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqUtils.cs +++ b/Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqUtils.cs @@ -1361,6 +1361,10 @@ public static class EscSeqUtils /// public static readonly AnsiEscapeSequenceRequest CSI_RequestSixelResolution = new () { Request = CSI + "16t", Terminator = "t" }; + /// + /// CSI 14 t - Request window size in pixels (width x height) + /// + public static readonly AnsiEscapeSequenceRequest CSI_RequestWindowSizeInPixels = new () { Request = CSI + "14t", Terminator = "t" }; /// /// CSI 1 8 t | yes | yes | yes | report window size in chars diff --git a/Terminal.Gui/Drawing/SixelSupportDetector.cs b/Terminal.Gui/Drawing/SixelSupportDetector.cs index 295dcd4ba..48bc01849 100644 --- a/Terminal.Gui/Drawing/SixelSupportDetector.cs +++ b/Terminal.Gui/Drawing/SixelSupportDetector.cs @@ -41,10 +41,37 @@ public class SixelSupportDetector } } - if (!gotResolutionDirectly) { - // TODO: Try pixel/window resolution getting + // Fallback to window size in pixels and characters + if (AnsiEscapeSequenceRequest.TryExecuteAnsiRequest (EscSeqUtils.CSI_RequestWindowSizeInPixels, out var pixelSizeResponse) && + AnsiEscapeSequenceRequest.TryExecuteAnsiRequest (EscSeqUtils.CSI_ReportTerminalSizeInChars, out var charSizeResponse)) + { + // Example [4;600;1200t + var pixelMatch = Regex.Match (pixelSizeResponse.Response, @"\[\d+;(\d+);(\d+)t$"); + + // Example [8;30;120t + var charMatch = Regex.Match (charSizeResponse.Response, @"\[\d+;(\d+);(\d+)t$"); + + if (pixelMatch.Success && charMatch.Success) + { + // Extract pixel dimensions + if (int.TryParse (pixelMatch.Groups [1].Value, out var pixelHeight) && + int.TryParse (pixelMatch.Groups [2].Value, out var pixelWidth) && + // Extract character dimensions + int.TryParse (charMatch.Groups [1].Value, out var charHeight) && + int.TryParse (charMatch.Groups [2].Value, out var charWidth) && + charWidth != 0 && charHeight != 0) // Avoid divide by zero + { + // Calculate the character cell size in pixels + var cellWidth = pixelWidth / charWidth; + var cellHeight = pixelHeight / charHeight; + + // Set the resolution based on the character cell size + result.Resolution = new Size (cellWidth, cellHeight); + } + } + } } }