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

Try to call tput to get console size if System.Console.BufferWidth/WindowHeight fails #1190

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
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
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;
}
}