Skip to content

Commit

Permalink
Try to call tput to get console size if System.Console.BufferWidth/Wi…
Browse files Browse the repository at this point in the history
…ndowHeight fails

This fixes size issues on console such as mintty on Windows.
  • Loading branch information
Frassle committed Mar 6, 2023
1 parent 819b948 commit d639191
Showing 1 changed file with 59 additions and 16 deletions.
75 changes: 59 additions & 16 deletions src/Spectre.Console/Internal/ConsoleHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,39 +2,82 @@ namespace Spectre.Console;

internal static class ConsoleHelper
{
private static int InvokeTPut(string arg)
{
var startInfo = new ProcessStartInfo("tput", arg);
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
var process = Process.Start(startInfo);
if (process == null)
{
throw new Exception("Failed to start tput");
}

var output = new StringBuilder();
var error = new StringBuilder();
process.OutputDataReceived += (obj, data) => output.AppendLine(data.Data);
process.ErrorDataReceived += (obj, data) => error.AppendLine(data.Data);
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
process.WaitForExit();
if (process.ExitCode == 0)
{
return int.Parse(output.ToString());
}

throw new Exception(error.ToString());
}

public static int GetSafeWidth(int defaultValue = Constants.DefaultTerminalWidth)
{
var width = 0;
try
{
var width = System.Console.BufferWidth;
if (width == 0)
{
width = defaultValue;
}

return width;
width = System.Console.BufferWidth;
}
catch (IOException)
{
return defaultValue;
}

if (width == 0)
{
try
{
width = InvokeTPut("cols");
}
catch
{
width = defaultValue;
}
}

return width;
}

public static int GetSafeHeight(int defaultValue = Constants.DefaultTerminalHeight)
{
var height = 0;
try
{
var height = System.Console.WindowHeight;
if (height == 0)
{
height = defaultValue;
}

return height;
height = System.Console.WindowHeight;
}
catch (IOException)
{
return defaultValue;
}

if (height == 0)
{
try
{
height = InvokeTPut("lines");
}
catch
{
height = defaultValue;
}
}

return height;
}
}

0 comments on commit d639191

Please sign in to comment.