Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixes #1265 - Adds Sixel rendering support #3734

Merged
merged 74 commits into from
Oct 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
74 commits
Select commit Hold shift + click to select a range
4d1d740
Initial exploration of how to sixel encode
tznind Sep 9, 2024
f096062
Add ColorQuantizer
tznind Sep 9, 2024
943fa11
Work on SixelEncoder
tznind Sep 9, 2024
c6281dd
Build color palette using median cut instead of naive method
tznind Sep 11, 2024
b482306
Fix build errors
tznind Sep 11, 2024
3081765
Refactoring and comments
tznind Sep 11, 2024
e334bfd
Refactor and split into seperate files WIP
tznind Sep 11, 2024
891adec
Switch to a new WriteSixel algorithm
tznind Sep 13, 2024
484b75a
Output palette in Images scenario
tznind Sep 14, 2024
68d5e99
Fix ConvertToColorArray and namespaces
tznind Sep 14, 2024
d747867
Fix comment
tznind Sep 14, 2024
f103b04
Attribution for the WriteSixel method
tznind Sep 15, 2024
cbef6c5
Add comments
tznind Sep 15, 2024
eaa5c0e
Simplify and speed up palette building
tznind Sep 15, 2024
f8bb2f0
Fix infinite loop building palette
tznind Sep 15, 2024
f40b7b4
Fix test and make comments clearer
tznind Sep 22, 2024
93ce9a8
Add sixel test for grid 3x3 to make 12x12 checkerboard
tznind Sep 22, 2024
ef56998
Tidy up test file and comments in NetDriver
tznind Sep 23, 2024
a7c65bf
Move lab colors to UICatalog
tznind Sep 23, 2024
f07ab92
Switch to simpler and faster palette builder
tznind Sep 23, 2024
2378570
Fix early exit bug in palette builder and change to far more conserva…
tznind Sep 23, 2024
b9bb2ba
Merge branch 'v2_develop' into sixel-encoder-tinkering
tznind Sep 23, 2024
4571978
Fix fill area - y is not in sixels its in pixels
tznind Sep 25, 2024
3c6804a
Move license to top of page and credit both source repos
tznind Sep 25, 2024
6149c5f
Add 2 tabs to Image scenario - one for sixel one for basic
tznind Sep 26, 2024
050db7a
Merge branch 'v2_develop' into sixel-encoder-tinkering
tznind Sep 26, 2024
9322b9a
Output at specific position
tznind Sep 26, 2024
519d8c0
Investigate changing sixel to output as part of view render
tznind Sep 28, 2024
94cbc1c
Restore the static approach to rendering for now and fix dispose
tznind Sep 28, 2024
d16f1b6
Fix tabbing into sixel tab view
tznind Sep 28, 2024
18f185d
Fix scenario dispose
tznind Sep 28, 2024
db0fc41
Determine whether sixel is supported by issuing a Device Attributes R…
tznind Sep 29, 2024
08aa992
Switch to existing consts
tznind Sep 30, 2024
b67c662
WIP: trying to get fully transparent alpha to not render
tznind Sep 30, 2024
c240cb1
Fix for when we want alpha pixels
tznind Oct 1, 2024
0122442
Merge branch 'v2_develop' into sixel-encoder-tinkering
tznind Oct 2, 2024
5e356c2
WindowsDriver prototype sixel support
tznind Oct 3, 2024
f22ef30
Merge branch 'sixel-encoder-tinkering' of https://github.com/tznind/g…
tznind Oct 3, 2024
d60b1fa
Remove double paint!
tznind Oct 3, 2024
23cd888
Do not output sixel if driver does not support it
tznind Oct 3, 2024
14a5fa7
Improve usability of Images scenario
tznind Oct 4, 2024
3566ac2
Make sixel output stop on dispose/close Images scenario
tznind Oct 4, 2024
9058554
Adjust default quantizer
tznind Oct 4, 2024
c4c7754
Add UI components for sixel algorithm
tznind Oct 4, 2024
9d5d853
Actually call relevant builders
tznind Oct 4, 2024
36a8cba
Make updates to the sixel image easier (e.g. changing algorithm)
tznind Oct 4, 2024
a6b1221
Tidy up scenario quantizer options
tznind Oct 5, 2024
97da4cd
Fix unit test expectations
tznind Oct 5, 2024
fd7f994
Fix GetPaletteBuilder
tznind Oct 5, 2024
a3eb19f
Merge branch 'v2_develop' into sixel-encoder-tinkering
tznind Oct 6, 2024
eee0ded
Merge branch 'v2_develop' into sixel-encoder-tinkering
tznind Oct 10, 2024
ccb974b
Change to using ansi escape sequences in new standalone class
tznind Oct 5, 2024
78d49fc
Fix algorithm to look for exactly 4 not things like 42 etc.
tznind Oct 5, 2024
ffe8969
Fix new palette order
tznind Oct 5, 2024
fe7e10a
Get sixel resolution using CSI 16 t
tznind Oct 6, 2024
54308ff
Sixel resolution measuring
tznind Oct 6, 2024
64baeca
Update sixel status class name and move to new file
tznind Oct 6, 2024
a8e3a0e
Update xmldoc
tznind Oct 6, 2024
4073ef3
Use round to nearest whole number when calculating sixel resolution f…
tznind Oct 7, 2024
61667fb
Refactor SixelSupportDetector for cleaner reading
tznind Oct 7, 2024
54b737f
If not supporting transparency warn user
tznind Oct 7, 2024
1c3b0d7
Merge pull request #170 from tznind/add-sixel-detector-interface
tznind Oct 10, 2024
9990a55
Fix for accepting
tznind Oct 10, 2024
64d286c
Remove ConsoleDriver.SupportsSixel
tznind Oct 10, 2024
5a6aae6
Fix warnings and tidup code
tznind Oct 10, 2024
bcdb11e
Run TidyCode on all new classes
tznind Oct 10, 2024
57de1ff
Merge branch 'v2_develop' into sixel-encoder-tinkering
tig Oct 11, 2024
06a2f71
Merge branch 'v2_develop' into sixel-encoder-tinkering
tznind Oct 11, 2024
c46cf78
Merge branch 'v2_develop' into sixel-encoder-tinkering
tznind Oct 13, 2024
04b336a
Try adding sixel to curses driver
tznind Oct 13, 2024
8ddfd71
Merge branch 'v2_develop' into sixel-encoder-tinkering
tig Oct 15, 2024
a6f03e4
Merge branch 'v2_develop' into sixel-encoder-tinkering
tig Oct 23, 2024
3156641
Make sixel 'opt in' in images scenario and apply a hack to fix TabVie…
tznind Oct 23, 2024
ce41afd
xml comments
tznind Oct 23, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions Terminal.Gui/Application/Application.Driver.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,10 @@ public static partial class Application // Driver abstractions
/// </remarks>
[SerializableConfigurationProperty (Scope = typeof (SettingsScope))]
public static string ForceDriver { get; set; } = string.Empty;

/// <summary>
/// Collection of sixel images to write out to screen when updating.
/// Only add to this collection if you are sure terminal supports sixel format.
/// </summary>
public static List<SixelToRender> Sixel = new List<SixelToRender> ();
}
7 changes: 7 additions & 0 deletions Terminal.Gui/ConsoleDrivers/CursesDriver/CursesDriver.cs
Original file line number Diff line number Diff line change
Expand Up @@ -420,6 +420,13 @@ public override void UpdateScreen ()
}
}

// SIXELS
foreach (var s in Application.Sixel)
{
SetCursorPosition (s.ScreenPosition.X, s.ScreenPosition.Y);
Console.Write(s.SixelData);
}

SetCursorPosition (0, 0);

_currentCursorVisibility = savedVisibility;
Expand Down
13 changes: 13 additions & 0 deletions Terminal.Gui/ConsoleDrivers/EscSeqUtils/EscSeqUtils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1356,6 +1356,19 @@ public enum DECSCUSR_Style
/// </summary>
public const string CSI_ReportDeviceAttributes_Terminator = "c";

/*
TODO: depends on https://github.com/gui-cs/Terminal.Gui/pull/3768
/// <summary>
/// CSI 16 t - Request sixel resolution (width and height in pixels)
/// </summary>
public static readonly AnsiEscapeSequenceRequest CSI_RequestSixelResolution = new () { Request = CSI + "16t", Terminator = "t" };

/// <summary>
/// CSI 14 t - Request window size in pixels (width x height)
/// </summary>
public static readonly AnsiEscapeSequenceRequest CSI_RequestWindowSizeInPixels = new () { Request = CSI + "14t", Terminator = "t" };
*/

/// <summary>
/// CSI 1 8 t | yes | yes | yes | report window size in chars
/// https://terminalguide.namepad.de/seq/csi_st-18/
Expand Down
12 changes: 11 additions & 1 deletion Terminal.Gui/ConsoleDrivers/NetDriver.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1020,6 +1020,15 @@ public override void UpdateScreen ()
SetCursorPosition (lastCol, row);
Console.Write (output);
}

foreach (var s in Application.Sixel)
{
if (!string.IsNullOrWhiteSpace (s.SixelData))
{
SetCursorPosition (s.ScreenPosition.X, s.ScreenPosition.Y);
Console.Write (s.SixelData);
}
}
}

SetCursorPosition (0, 0);
Expand Down Expand Up @@ -1126,9 +1135,10 @@ internal override MainLoop Init ()
_mainLoopDriver = new NetMainLoop (this);
_mainLoopDriver.ProcessInput = ProcessInput;


return new MainLoop (_mainLoopDriver);
}

private void ProcessInput (InputResult inputEvent)
{
switch (inputEvent.EventType)
Expand Down
17 changes: 16 additions & 1 deletion Terminal.Gui/ConsoleDrivers/WindowsDriver.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ internal class WindowsConsole
private CursorVisibility? _currentCursorVisibility;
private CursorVisibility? _pendingCursorVisibility;
private readonly StringBuilder _stringBuilder = new (256 * 1024);
private string _lastWrite = string.Empty;

public WindowsConsole ()
{
Expand Down Expand Up @@ -118,7 +119,21 @@ public bool WriteToConsole (Size size, ExtendedCharInfo [] charInfoBuffer, Coord

var s = _stringBuilder.ToString ();

result = WriteConsole (_screenBuffer, s, (uint)s.Length, out uint _, nint.Zero);
// TODO: requires extensive testing if we go down this route
// If console output has changed
if (s != _lastWrite)
{
// supply console with the new content
result = WriteConsole (_screenBuffer, s, (uint)s.Length, out uint _, nint.Zero);
}

_lastWrite = s;

foreach (var sixel in Application.Sixel)
{
SetCursorPosition (new Coord ((short)sixel.ScreenPosition.X, (short)sixel.ScreenPosition.Y));
WriteConsole (_screenBuffer, sixel.SixelData, (uint)sixel.SixelData.Length, out uint _, nint.Zero);
}
}

if (!result)
Expand Down
20 changes: 20 additions & 0 deletions Terminal.Gui/Drawing/AssumeSupportDetector.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
namespace Terminal.Gui;

/// <summary>
/// Implementation of <see cref="ISixelSupportDetector"/> that assumes best
/// case scenario (full support including transparency with 10x20 resolution).
/// </summary>
public class AssumeSupportDetector : ISixelSupportDetector
{
/// <inheritdoc/>
public SixelSupportResult Detect ()
{
return new()
{
IsSupported = true,
MaxPaletteColors = 256,
Resolution = new (10, 20),
SupportsTransparency = true
};
}
}
15 changes: 15 additions & 0 deletions Terminal.Gui/Drawing/ISixelSupportDetector.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
namespace Terminal.Gui;

/// <summary>
/// Interface for detecting sixel support. Either through
/// ansi requests to terminal or config file etc.
/// </summary>
public interface ISixelSupportDetector
{
/// <summary>
/// Gets the supported sixel state e.g. by sending Ansi escape sequences
/// or from a config file etc.
/// </summary>
/// <returns>Description of sixel support.</returns>
public SixelSupportResult Detect ();
}
91 changes: 91 additions & 0 deletions Terminal.Gui/Drawing/Quant/ColorQuantizer.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
using System.Collections.Concurrent;

namespace Terminal.Gui;

/// <summary>
/// Translates colors in an image into a Palette of up to <see cref="MaxColors"/> colors (typically 256).
/// </summary>
public class ColorQuantizer
{
/// <summary>
/// Gets the current colors in the palette based on the last call to
/// <see cref="BuildPalette"/>.
/// </summary>
public IReadOnlyCollection<Color> Palette { get; private set; } = new List<Color> ();

/// <summary>
/// Gets or sets the maximum number of colors to put into the <see cref="Palette"/>.
/// Defaults to 256 (the maximum for sixel images).
/// </summary>
public int MaxColors { get; set; } = 256;

/// <summary>
/// Gets or sets the algorithm used to map novel colors into existing
/// palette colors (closest match). Defaults to <see cref="EuclideanColorDistance"/>
/// </summary>
public IColorDistance DistanceAlgorithm { get; set; } = new EuclideanColorDistance ();

/// <summary>
/// Gets or sets the algorithm used to build the <see cref="Palette"/>.
/// </summary>
public IPaletteBuilder PaletteBuildingAlgorithm { get; set; } = new PopularityPaletteWithThreshold (new EuclideanColorDistance (), 8);

private readonly ConcurrentDictionary<Color, int> _nearestColorCache = new ();

/// <summary>
/// Builds a <see cref="Palette"/> of colors that most represent the colors used in <paramref name="pixels"/> image.
/// This is based on the currently configured <see cref="PaletteBuildingAlgorithm"/>.
/// </summary>
/// <param name="pixels"></param>
public void BuildPalette (Color [,] pixels)
{
List<Color> allColors = new ();
int width = pixels.GetLength (0);
int height = pixels.GetLength (1);

for (var x = 0; x < width; x++)
{
for (var y = 0; y < height; y++)
{
allColors.Add (pixels [x, y]);
}
}

_nearestColorCache.Clear ();
Palette = PaletteBuildingAlgorithm.BuildPalette (allColors, MaxColors);
}

/// <summary>
/// Returns the closest color in <see cref="Palette"/> that matches <paramref name="toTranslate"/>
/// based on the color comparison algorithm defined by <see cref="DistanceAlgorithm"/>
/// </summary>
/// <param name="toTranslate"></param>
/// <returns></returns>
public int GetNearestColor (Color toTranslate)
{
if (_nearestColorCache.TryGetValue (toTranslate, out int cachedAnswer))
{
return cachedAnswer;
}

// Simple nearest color matching based on DistanceAlgorithm
var minDistance = double.MaxValue;
var nearestIndex = 0;

for (var index = 0; index < Palette.Count; index++)
{
Color color = Palette.ElementAt (index);
double distance = DistanceAlgorithm.CalculateDistance (color, toTranslate);

if (distance < minDistance)
{
minDistance = distance;
nearestIndex = index;
}
}

_nearestColorCache.TryAdd (toTranslate, nearestIndex);

return nearestIndex;
}
}
31 changes: 31 additions & 0 deletions Terminal.Gui/Drawing/Quant/EuclideanColorDistance.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
namespace Terminal.Gui;

/// <summary>
/// <para>
/// Calculates the distance between two colors using Euclidean distance in 3D RGB space.
/// This measures the straight-line distance between the two points representing the colors.
/// </para>
/// <para>
/// Euclidean distance in RGB space is calculated as:
/// </para>
/// <code>
/// √((R2 - R1)² + (G2 - G1)² + (B2 - B1)²)
/// </code>
/// <remarks>Values vary from 0 to ~441.67 linearly</remarks>
/// <remarks>
/// This distance metric is commonly used for comparing colors in RGB space, though
/// it doesn't account for perceptual differences in color.
/// </remarks>
/// </summary>
public class EuclideanColorDistance : IColorDistance
{
/// <inheritdoc/>
public double CalculateDistance (Color c1, Color c2)
{
int rDiff = c1.R - c2.R;
int gDiff = c1.G - c2.G;
int bDiff = c1.B - c2.B;

return Math.Sqrt (rDiff * rDiff + gDiff * gDiff + bDiff * bDiff);
}
}
18 changes: 18 additions & 0 deletions Terminal.Gui/Drawing/Quant/IColorDistance.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
namespace Terminal.Gui;

/// <summary>
/// Interface for algorithms that compute the relative distance between pairs of colors.
/// This is used for color matching to a limited palette, such as in Sixel rendering.
/// </summary>
public interface IColorDistance
{
/// <summary>
/// Computes a similarity metric between two <see cref="Color"/> instances.
/// A larger value indicates more dissimilar colors, while a smaller value indicates more similar colors.
/// The metric is internally consistent for the given algorithm.
/// </summary>
/// <param name="c1">The first color.</param>
/// <param name="c2">The second color.</param>
/// <returns>A numeric value representing the distance between the two colors.</returns>
double CalculateDistance (Color c1, Color c2);
}
19 changes: 19 additions & 0 deletions Terminal.Gui/Drawing/Quant/IPaletteBuilder.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
namespace Terminal.Gui;

/// <summary>
/// Builds a palette of a given size for a given set of input colors.
/// </summary>
public interface IPaletteBuilder
{
/// <summary>
/// Reduce the number of <paramref name="colors"/> to <paramref name="maxColors"/> (or less)
/// using an appropriate selection algorithm.
/// </summary>
/// <param name="colors">
/// Color of every pixel in the image. Contains duplication in order
/// to support algorithms that weigh how common a color is.
/// </param>
/// <param name="maxColors">The maximum number of colours that should be represented.</param>
/// <returns></returns>
List<Color> BuildPalette (List<Color> colors, int maxColors);
}
Loading
Loading