Overview / Developer tools

cli

Terminal output with its own buffer, color and style with graceful downgrade, column width, progress bar, line editor and an argument parser that does not allocate.

Always compiled: part of the core build.Include #include <ethereal/cpp/cli/cli_inc.hpp>C layer

cli_inc.hpp

#include <ethereal/cpp/cli/cli_inc.hpp>

Aggregate entry point of the Cli module.

Terminal and command line. Not to be confused with 'system/console.hpp', which attaches a console window to a Windows GUI program ('AllocConsole'). This module handles what is already attached to the standard output.

Two rules, each one against a common mistake:

  • Ethereal::Cli::Colorize returns the raw text when no one is watching. Color sequences in a log file are garbage ('ESC[31m' in the middle of a 'grep'). The decision to paint is taken once, in one place, and not at every write, where one of them forgets it.
  • Ethereal::Cli::CArgs rejects unknown options. A parser that ignores what it does not know turns a misspelled '--dry-run' into a real run, and reports success.

Ethereal::Cli::CProgressBar does not draw itself when the output is not a terminal. It writes a plain line at each milestone instead, so a CI log is not left silent.

The rules of each half are written out at the top of 'terminal.hpp' and 'args.hpp'.

Including this header brings in the whole module.

argparse.hpp

#include <ethereal/cpp/cli/argparse.hpp>

Argument parser of the Cli module that writes into the caller's variables (CArgParser).

The spec refuses the common form, and says why: "Registration writes directly into caller-owned variables. No result map, no lookup by string after parsing." And: "Parser storage is a fixed-capacity array sized at 'Init'. No allocation during 'Parse'."

The common form is register, then ask: 'Args.GetFlag( "verbose" )'. It has to keep the values somewhere (a map, a vector of pairs) and search by text after parsing. That costs an allocation per stored value at best, and a string compare per read, forever. And a third cost, not about speed: a typo in the name is caught by no one. 'Args.GetFlag( "verbsoe" )' compiles, runs and returns false.

Here registration takes the address of the variable. Parsing writes there. Readers read the variable, which the compiler knows.

Storage belongs to the caller. The capacity is fixed and given in Init, in an array the caller provides. Neither registration nor parsing allocates, and the test checks it.

enum

EValueType

Ethereal::Cli#
C++
enum class   EValueType : ETL_UINT8
{
    /// @brief  const char *, pointing into the caller's argv.
    eString = 0,

    /// @brief  ETL_INT64.
    eInt,

    /// @brief  ETL_UINT64.
    eUInt,

    /// @brief  double.
    eDouble
};

What an option with a value can write.

enum

EParseError

Ethereal::Cli#
C++
enum class   EParseError : ETL_UINT8
{
    /// @brief  Success.
    eNone = 0,

    /// @brief  An option no one declared.
    eUnknownOption,

    /// @brief  An option that expects a value got none.
    eMissingValue,

    /// @brief  A flag got a value.
    eUnexpectedValue,

    /// @brief  The value is not of the declared type.
    eBadValue,

    /// @brief  A required positional is missing.
    eMissingRequired,

    /// @brief  More positionals than declared.
    eTooManyPositional,

    /// @brief  A group of short flags where one expects a value.
    eBadBundle,

    /// @brief  No room for more declarations. See CArgParser::Init.
    eOutOfSlots,

    /// @brief  The declaration is wrong. A defect of the program's author.
    eBadDefinition,

    /// Added at the end, never in the middle: these values cross the C layer,
    /// and reordering them would break every binary already linked.

    /// @brief  A subcommand no one declared.
    ///
    /// @details  Distinct from eUnknownOption on purpose: a wrong subcommand has
    ///            its own suggestion, from the subcommand names. Pointing the
    ///            user to the options would point to the wrong list.
    ///
    eUnknownSubcommand,

    /// @brief  Subcommands are declared and none was invoked.
    ///
    /// @details  A program that only makes sense with a subcommand (like git)
    ///            should refuse instead of doing something by default. Callers
    ///            that want a default handle this state and choose.
    ///
    eMissingSubcommand,

    /// @brief  Refused: no license was accepted and the evaluation of this machine
    ///          has ended, or the license passed was refused (see Bundle::UnlockBundle).
    eNotLicensed
};

What can go wrong.

function

ParseErrorName

Ethereal::Cli#
const ETL_CHAR * ParseErrorName( EParseError eError ) noexcept;

Name of the error, for messages.

eError
The error.
The name. Never null.
struct

SParseResult

Ethereal::Cli#
C++
struct   SParseResult   final
{
    /// @brief  'sizeof( SParseResult )'.
    ETL_UINT32            iStructSize = sizeof( SParseResult );

    /// @brief  The error, or eNone.
    EParseError            eError = EParseError::eNone;

    /// @brief  Padding.
    ETL_UINT8            aPad[ 3 ] = {};

    /// @brief  The argument that caused it. Points into the caller's argv.
    const ETL_CHAR *    pWhich = nullptr;

    /// @brief  The similar name, when there is one. See CArgParser.
    ///
    /// @details  Points into the declarations. Null when nothing was similar.
    ///
    const ETL_CHAR *    pDidYouMean = nullptr;


    /// @brief  true when parsing succeeded.
    ///
    ETL_API_NOIGN    bool IsOk() const ETL_NOEXCEPT
    {
        return eError == EParseError::eNone;
    }
};

What parsing found.

struct

SArgSlot

Ethereal::Cli#
C++
struct   SArgSlot   final
{
    /// @brief  Long name (or the positional name).
    const ETL_CHAR *    pLong;

    /// @brief  Help text.
    const ETL_CHAR *    pHelp;

    /// @brief  Environment variable used as fallback. May be null.
    const ETL_CHAR *    pEnvVar;

    /// @brief  The caller's variable.
    void *                pOut;

    /// @brief  Short letter, or zero.
    ETL_CHAR            cShort;

    /// @brief  0 flag, 1 count, 2 value, 3 positional.
    ETL_UINT8            uKind;

    /// @brief  EValueType, for value slots.
    ETL_UINT8            uType;

    /// @brief  Non zero when required.
    ETL_UINT8            bRequired;

    /// @brief  Non zero when it accepts --no-name.
    ETL_UINT8            bNegatable;

    /// @brief  Non zero when it came in the last Parse.
    ETL_UINT8            bSeen;

    /// @brief  Padding.
    ETL_UINT8            aPad[ 2 ];
};

A declaration. The caller provides the array of these.

Not filled by hand. Use the Add* methods of CArgParser.

struct

SSubcommand

Ethereal::Cli#
C++
struct   SSubcommand   final
{
    /// @brief  The name it is invoked by. Required.
    const ETL_CHAR *    pName = nullptr;

    /// @brief  A line of help. May be null.
    const ETL_CHAR *    pHelp = nullptr;

    /// @brief  Its parser, already initialized. Owned by the caller.
    ///
    /// @details  Must outlive the parent. It is not copied.
    ///
    CArgParser *        pParser = nullptr;
};

A subcommand. The caller provides the array of these.

class

CArgParser

Ethereal::Cli#

Parses a command line writing into the caller's variables.

class CArgParser final
constructor

CArgParser

#
CArgParser() noexcept;

Constructor. Call Init before use.

function

Init

#
void Init( SArgSlot * pSlots, std::size_t uCount, const ETL_CHAR * pProgram = nullptr ) noexcept;

Sets where to keep the declarations.

pSlots
The array. Must outlive this object.
uCount
Number of declarations that fit.
pProgram
Program name, for the help. May be null.
function

AddFlag

#
bool AddFlag( const ETL_CHAR * pLong, ETL_CHAR cShort, const ETL_CHAR * pHelp, bool * pOut ) noexcept;

A flag. Writes true to pOut when it appears.

pLong
Long name.
cShort
Short letter, or zero.
pHelp
Help text.
pOut
The caller's variable.
false when there is no room or pOut is null.
function

AddNegatableFlag

#
bool AddNegatableFlag( const ETL_CHAR * pLong, ETL_CHAR cShort, const ETL_CHAR * pHelp, bool * pOut ) noexcept;

A flag that also accepts --no-name, writing false.

function

AddCount

#
bool AddCount( const ETL_CHAR * pLong, ETL_CHAR cShort, const ETL_CHAR * pHelp, ETL_UINT32 * pOut ) noexcept;

A count. Adds one to pOut per appearance: -vvv gives three.

function

AddValue

#
bool AddValue( const ETL_CHAR * pLong, ETL_CHAR cShort, const ETL_CHAR * pHelp, EValueType eType, void * pOut ) noexcept;

An option with a value.

pLong
Long name.
cShort
Short letter, or zero.
pHelp
Help text.
eType
Type of the value.
pOut
Points to a variable of the type given in eType.
false when there is no room or pOut is null.
function

AddPositional

#
bool AddPositional( const ETL_CHAR * pName, const ETL_CHAR * pHelp, bool bRequired, EValueType eType, void * pOut ) noexcept;

A positional.

pName
Name, for the help.
pHelp
Help text.
bRequired
true when required.
eType
Type of the value.
pOut
Points to a variable of the type given in eType.
false when there is no room or pOut is null.
function

SetEnvFallback

#
bool SetEnvFallback( const ETL_CHAR * pLong, const ETL_CHAR * pEnvVar ) noexcept;

Sets the environment variable this option can come from when it is not on the line.

The command line always wins. The environment is the fallback, not the other way around: whoever wrote the line meant it.

pLong
Long name of a declared option.
pEnvVar
Name of the environment variable.
false when the option is not declared.
function

SetSubcommands

#
void SetSubcommands( const SSubcommand * pSubs, std::size_t uCount ) noexcept;

Sets where the subcommands are. Like Init, the array belongs to the caller.

pSubs
The array, already filled. Must outlive this object.
uCount
Number of subcommands.
function

SelectedSubcommand

#
const ETL_CHAR * SelectedSubcommand() const noexcept

The subcommand invoked. Null when none.

Points into the caller's argv, not to the declared name. Both are equal byte by byte. What matters is that it dies with argv.

function

SelectedParser

#
CArgParser * SelectedParser() const noexcept

The parser of the invoked subcommand. Null when none.

It already ran: the parent's Parse called it with the rest of argv. This is for reading its Rest, or its help.

function

Parse

#
SParseResult Parse( int iArgc, const ETL_CHAR * const * ppArgv ) noexcept;

Walks ppArgv and writes into the declared variables.

Does not allocate. Not once.

iArgc
Argument count.
ppArgv
The arguments.
The result. eNotLicensed when the library is not licensed.
function

Rest

#
const ETL_CHAR * const * Rest() const noexcept

What was left after '--', and the extra positionals.

Points into the caller's argv.

function

RestCount

#
std::size_t RestCount() const noexcept

Number of entries in Rest.

function

WriteUsage

#
void WriteUsage( CWriter & W ) const noexcept;

Writes the usage line.

function

WriteHelp

#
void WriteHelp( CWriter & W, ETL_UINT16 uWidth = 0 ) const noexcept;

Writes the whole help, with aligned columns.

W
The writer.
uWidth
Width to wrap at. Zero asks the terminal.
function

SlotCount

#
std::size_t SlotCount() const noexcept

Number of declarations in use.

args.hpp

#include <ethereal/cpp/cli/args.hpp>

Command line parsing of the Cli module (CArgs).

The six rules of the command line.

1. An unknown option is an error, always. This rule comes from experience. A parser that ignores what it does not know turns a misspelled '--dry-run' into a real run, and '--no-backup' into a backup made. The program does the wrong thing and reports success, because from its point of view it succeeded. Here, anything starting with '-' that was not declared stops parsing with EArgError::eUnknownOption and the name that came in. There is no permissive mode, on purpose.

2. A lone double dash ends the options. After '--', everything is positional, including what starts with a dash. Without it there is no way to pass a file named '-rf', and programs that lack it force the './-rf' workaround. A lone dash ('-') is positional, not an option: the long standing convention for "standard input".

3. An option that expects a value refuses a next argument that looks like an option. '--output --verbose' is almost always a slip, not a request to write to a file named '--verbose'. Taking the second as the value of the first silently loses an option and writes to the wrong place. Here that is EArgError::eMissingValue. To pass a value that starts with a dash, use the equals form: '--output=-x'.

4. The accepted forms, and only these: --name value --name=value --flag -n value -nvalue -n -abc (three short flags together) Short flags only bundle when all of them are flags. '-abc' where 'b' expects a value is refused instead of becoming '-a -b c', which some libraries do, and is a costly surprise. In the attached short form the equals sign is not a separator: '-n=value' gives the value '=value', as the long standing convention says. The equals form is the long one, '--name=value'.

5. When repeated, the last one wins, and CArgs::Count tells how many came. Same choice as the INI dialect of this project, for the same reason: it is what almost everyone expects, and it allows overriding a value from a script. Callers that must refuse repetition have CArgs::Count for it.

6. A failed conversion is an error, not the default value. '--port 8o80' is not 8. The Get* (with default) and TryGet* (strict) pairs exist for this difference, the same split as the Config module. Beware of the classic trap: 'strtoll' accepts "1234abc" and returns 1234 without complaint. Here conversion requires the whole string to be consumed.

enum

EArgError

Ethereal::Cli#
C++
enum class EArgError : ETL_UINT8
{
    /// @brief  Success.
    eNone = 0,

    /// @brief  Something with a dash that was not declared. See rule 1.
    eUnknownOption,

    /// @brief  An option that expects a value got none, or the next argument
    ///             looked like another option. See rule 3.
    eMissingValue,

    /// @brief  A flag got a value, as in '--verbose=3'.
    eUnexpectedValue,

    /// @brief  A required option or positional is missing.
    eMissingRequired,

    /// @brief  More positionals than declared, and extras are not allowed.
    eTooManyPositional,

    /// @brief  Bundled short flags where one expects a value. See rule 4.
    eBadBundle,

    /// @brief  The declaration is wrong: repeated or empty name, repeated short
    ///             letter. A programming error, not a user error.
    eBadDefinition,

    /// @brief  Refused: no license was accepted and the evaluation of this machine
    ///          has ended, or the license passed was refused (see Bundle::UnlockBundle).
    eNotLicensed
};

What can go wrong while parsing.

struct

SArgResult

Ethereal::Cli#
C++
struct   SArgResult   final
{
    /// @brief  The error, or eNone.
    EArgError        eError = EArgError::eNone;

    /// @brief  The argument that caused it, exactly as it came on the command
    ///             line.
    std::string        sWhich;

    /// @brief  A ready sentence to show to the user.
    std::string        sMessage;


    /// @brief  true when parsing succeeded.
    ///
    ETL_API_NOIGN    bool IsOk() const ETL_NOEXCEPT        { return eError == EArgError::eNone; }
};

The result of parsing.

class

CArgs

Ethereal::Cli#

Declares and parses the command line arguments.

class CArgs final

The six rules are written at the top of this file. The first (an unknown option is an error) is the main reason this module exists.

C++
Ethereal::Cli::CArgs Args( "my-tool" );

Args.AddFlag( "verbose", 'v', "shows what it is doing" );
Args.AddOption( "output", 'o', "output file", "output.txt" );
Args.AddPositional( "input", "input file", true );

const auto Result = Args.Parse( argc, argv );

if( !Result.IsOk() )
{
    Ethereal::Cli::WriteLine( Ethereal::Cli::EStream::eErr, Result.sMessage );
    Ethereal::Cli::WriteLine( Ethereal::Cli::EStream::eErr, Args.Usage() );
    return 2;
}
constructor

CArgs

#
explicit CArgs( const std::string & sProgram = std::string() );

Constructor.

sProgram
Program name for the help text. Empty uses argv[0].
function

AddFlag

#
bool AddFlag( const std::string & sName, const char cShort = 0, const std::string & sHelp = std::string() );

An option with no value: present or not.

sName
The long name, without the dashes.
cShort
The short letter, or zero for none.
sHelp
Help text.
false when the declaration is invalid: empty name, repeated name or repeated letter. It is a programming error, so it shows when declaring and not when parsing.
function

AddOption

#
bool AddOption( const std::string & sName, const char cShort = 0, const std::string & sHelp = std::string(), const std::string & sDefault = std::string(), const bool bRequired = false );

An option that takes a value.

sName
The long name, without the dashes.
cShort
The short letter, or zero for none.
sHelp
Help text.
sDefault
What Get returns when the option did not come.
bRequired
When true, its absence is EArgError::eMissingRequired.
false when the declaration is invalid.
function

AddPositional

#
bool AddPositional( const std::string & sName, const std::string & sHelp = std::string(), const bool bRequired = false );

A positional argument, in the order it was declared.

A required positional after an optional one makes no sense (it cannot be satisfied) and is refused here.

sName
The name, for help and Get.
sHelp
Help text.
bRequired
When true, its absence is EArgError::eMissingRequired.
false when the declaration is invalid.
function

SetAllowExtraPositional

#
void SetAllowExtraPositional( const bool bAllow ) noexcept;

Allows positionals beyond the declared ones. They go to Extras.

Off by default, for the same reason as rule 1: an extra argument no one reads is usually a typo, not a leftover.

function

SetDescription

#
void SetDescription( const std::string & sText );

A description line, shown in the help text.

function

Parse

#
SArgResult Parse( const int iArgc, const char * const * ppArgv );

Parses. Can be called again, the previous state is discarded.

argv[0] is not an argument. It is the program name when none was given to the constructor.

iArgc
Argument count.
ppArgv
The arguments.
The result, with a message on error. eNotLicensed when the library is not licensed.
function

Has

#
bool Has( const std::string & sName ) const;

Tells whether sName came on the command line.

Not to be confused with the value. An option with a default answers Get even when it did not come. Has tells whether it really came, which separates "the user asked for the default" from "the user said nothing".

function

Count

#
ETL_UINT32 Count( const std::string & sName ) const;

Number of times sName appeared. See rule 5.

function

Get

#
std::string Get( const std::string & sName, const std::string & sFallback = std::string() ) const;

The value of sName.

sName
The name.
sFallback
Returned when there is no value nor default.
The value, the default or sFallback.
function

GetFlag

#
bool GetFlag( const std::string & sName ) const;

The state of a flag.

function

TryGetInt

#
bool TryGetInt( const std::string & sName, ETL_INT64 & iOut ) const;

Converts to integer, requiring the whole string.

"1234abc" is refused. See rule 6.

sName
The name.
iOut
Receives the value.
false when it did not come, or the text is not a complete integer.
function

GetInt

#
ETL_INT64 GetInt( const std::string & sName, const ETL_INT64 iFallback = 0 ) const;

Same as TryGetInt, returning iFallback instead of failing.

function

TryGetDouble

#
bool TryGetDouble( const std::string & sName, ETL_DOUBLE & dOut ) const;

Converts to double, requiring the whole string.

function

GetDouble

#
ETL_DOUBLE GetDouble( const std::string & sName, const ETL_DOUBLE dFallback = 0.0 ) const;

Same as TryGetDouble, returning dFallback instead of failing.

function

Extras

#
const std::vector< std::string > & Extras() const noexcept;

Positionals beyond the declared ones. See SetAllowExtraPositional.

function

AfterTerminator

#
const std::vector< std::string > & AfterTerminator() const noexcept;

What came after '--', even if it looks like an option. See rule 2.

These also go into Extras or the positionals. This list exists for callers that pass them on unchanged to another program.

function

Usage

#
std::string Usage() const;

A usage line, built from what was declared.

function

HelpText

#
std::string HelpText() const;

The full help text, one line per option.

function

ProgramName

#
const std::string & ProgramName() const noexcept;

The program name in use.

exitcode.hpp

#include <ethereal/cpp/cli/exitcode.hpp>

Process exit codes of the Cli module.

Named constants that follow the 'sysexits.h' conventions, plus a range of Ethereal codes.

A script that runs a tool only knows what happened from the number it returns. With only zero and one, "the file does not exist" and "the license expired" look the same, and the script has to parse the error message, which breaks when the text changes.

The 'sysexits.h' numbers are an old BSD convention that many people already know. What does not fit there goes in a range of its own, from 100 to below 125: 126 and 127 belong to the shell ("cannot execute" and "not found"), and codes above 128 are signals.

enum

EExitCode

Ethereal::Cli#
C++
enum class   EExitCode : int
{
    /// @brief  Success.
    eOk                    = 0,

    /// @brief  Error that fits no other code.
    eFailure            = 1,

    /// The 'sysexits.h' convention.

    /// @brief  The command line is wrong.
    eUsage                = 64,

    /// @brief  The input is not in the expected format.
    eDataError            = 65,

    /// @brief  The input does not exist or cannot be read.
    eNoInput            = 66,

    /// @brief  The given user does not exist.
    eNoUser                = 67,

    /// @brief  The given host does not exist.
    eNoHost                = 68,

    /// @brief  The service is not available.
    eUnavailable        = 69,

    /// @brief  Internal defect. An invariant that should not fail, failed.
    eSoftware            = 70,

    /// @brief  The operating system refused something.
    eOsError            = 71,

    /// @brief  A system file is missing.
    eOsFile                = 72,

    /// @brief  The output could not be created.
    eCantCreate            = 73,

    /// @brief  Error while reading or writing.
    eIoError            = 74,

    /// @brief  Temporary failure, worth trying again.
    eTempFail            = 75,

    /// @brief  The other side did not speak the expected protocol.
    eProtocol            = 76,

    /// @brief  Missing permissions.
    eNoPermission        = 77,

    /// @brief  The configuration is wrong.
    eConfig                = 78,

    /// The Ethereal range, from 100 to below 125 (see the file header).

    /// @brief  The license is not valid, expired, or is not for this machine.
    eLicense            = 100,

    /// @brief  What was going to be loaded failed the integrity check.
    eIntegrity            = 101,

    /// @brief  A plugin refused to start.
    ePlugin                = 102,

    /// @brief  The user cancelled.
    eCancelled            = 103,

    /// @brief  Time ran out.
    eTimeout            = 104
};

Codes a tool returns to the caller.

function

ExitCodeName

Ethereal::Cli#
const ETL_CHAR * ExitCodeName( EExitCode eCode ) noexcept;

Short name of the code, for messages.

eCode
The exit code.
The name. Never null.
function

ExitCodeText

Ethereal::Cli#
const ETL_CHAR * ExitCodeText( EExitCode eCode ) noexcept;

A short sentence that says what the code means.

eCode
The exit code.
The sentence. Never null.
function

IsValidExitCode

Ethereal::Cli#
bool IsValidExitCode( int iCode ) noexcept;

Tells whether the code fits the range a process can return.

A code above 255 does not reach the other side intact. On POSIX only the low eight bits pass, so 256 arrives as zero, which means success. This mistake only shows in production.

iCode
The code to check.
true when the code is in [0, 255].

input.hpp

#include <ethereal/cpp/cli/input.hpp>

Key reading of the Cli module: the decoder state machine and raw mode.

The spec is explicit about the form: "Escape sequence parsing is a table-driven state machine, not a chain of string comparisons."

The reason is not speed (reading keys is not a hot path). A chain of string comparisons cannot express bytes arriving in pieces. A terminal delivers '\x1b' in one read and '[A' in the next, and a string comparison needs the whole string. A state machine eats one byte at a time and tells, for each, whether it has a key, needs more, or is not a sequence at all.

The lone Escape is ambiguous, and cannot be resolved without a clock. The Escape key sends one byte, '\x1b'. The up arrow sends three, '\x1b[A'. Both start the same. The bytes alone cannot tell them apart, time is needed: if nothing follows the '\x1b' within a few milliseconds, it was the Escape key, and if more follows right away, it is the start of a sequence. The spec asks for this time to be configurable, and rightly so: over a slow link fifty milliseconds is not enough, and the user's arrow shows up as Escape followed by a bracket.

What is not recognized is not swallowed. "Unknown sequences are reported as raw bytes rather than swallowed." A terminal this code does not know sends a sequence it cannot read. Dropping the bytes makes the key "not work" without a trace. Delivering them lets the integrator see what arrived and decide.

enum

EKey

Ethereal::Cli#
C++
enum class   EKey : ETL_UINT16
{
    /// @brief  No key.
    eNone = 0,

    /// @brief  A printable character. See uCodePoint.
    eChar,

    /// @brief  Enter.
    eEnter,

    /// @brief  Tab.
    eTab,

    /// @brief  Backspace.
    eBackspace,

    /// @brief  Escape.
    eEscape,

    /// @brief  Space.
    eSpace,

    /// @brief  Delete.
    eDelete,

    /// @brief  Insert.
    eInsert,

    /// @brief  Up arrow.
    eUp,

    /// @brief  Down arrow.
    eDown,

    /// @brief  Right arrow.
    eRight,

    /// @brief  Left arrow.
    eLeft,

    /// @brief  Home.
    eHome,

    /// @brief  End.
    eEnd,

    /// @brief  Page up.
    ePageUp,

    /// @brief  Page down.
    ePageDown,

    /// @brief  Function keys F1 to F12.
    eF1, eF2,  eF3,  eF4,  eF5,  eF6,
    eF7, eF8,  eF9,  eF10, eF11, eF12,

    /// @brief  Bytes that were not recognized. See aRaw and uRawCount.
    eUnknown
};

The named keys.

function

KeyName

Ethereal::Cli#
const ETL_CHAR * KeyName( EKey eKey ) noexcept;

Name of the key, for messages.

eKey
The key.
The name. Never null.
enum

EMod

Ethereal::Cli#
C++
enum class   EMod : ETL_UINT16
{
    /// @brief  No modifier.
    eNone    = 0,

    /// @brief  Shift.
    eShift    = 1u << 0,

    /// @brief  Alt.
    eAlt    = 1u << 1,

    /// @brief  Ctrl.
    eCtrl    = 1u << 2,

    /// @brief  Meta.
    eMeta    = 1u << 3
};

Modifier keys. Flags.

operator

operator|

Ethereal::Cli#
inline EMod operator|( const EMod A, const EMod B ) noexcept

Combines two modifier sets.

struct

SKeyEvent

Ethereal::Cli#
C++
struct   SKeyEvent   final
{
    /// @brief  The key.
    EKey        eKey = EKey::eNone;

    /// @brief  EMod flags.
    ETL_UINT16    uModifiers = 0;

    /// @brief  The code point, when eKey is EKey::eChar.
    ETL_UINT32    uCodePoint = 0;

    /// @brief  The raw bytes, when eKey is EKey::eUnknown.
    ETL_UINT8    aRaw[ 16 ] = {};

    /// @brief  Number of bytes in aRaw.
    ETL_UINT8    uRawCount = 0;

    /// @brief  Padding.
    ETL_UINT8    aPad[ 3 ] = {};
};

A key that was read. POD.

enum

EFeed

Ethereal::Cli#
C++
enum class   EFeed : ETL_UINT8
{
    /// @brief  Not enough yet. Bring more.
    eNeedMore = 0,

    /// @brief  A key is ready.
    eKey,

    /// @brief  It was not a sequence. The key comes out as EKey::eUnknown.
    eInvalid
};

What the machine says after eating a byte.

class

CKeyDecoder

Ethereal::Cli#

Eats bytes and produces keys.

class CKeyDecoder final

It reads from nowhere, on purpose. CRawMode reads, or a test that hands it a sequence. Keeping both apart allows running the corpus of real sequences without a terminal.

constructor

CKeyDecoder

#
CKeyDecoder() noexcept;

Constructor.

function

Feed

#
EFeed Feed( ETL_UINT8 uByte, SKeyEvent * pOut ) noexcept;

Eats one byte.

uByte
The byte.
pOut
Receives the key when the result is EFeed::eKey or EFeed::eInvalid.
What the machine has after the byte.
function

Timeout

#
bool Timeout( SKeyEvent * pOut ) noexcept;

Time is up: whatever is pending is decided now.

This resolves the ambiguity of the lone Escape. The reader calls it when the wait went past the configured time.

pOut
Receives the key.
true when something was pending.
function

Reset

#
void Reset() noexcept;

Forgets what was half way.

function

IsPending

#
bool IsPending() const noexcept

Tells whether something is half way.

enum

ERawOptions

Ethereal::Cli#
C++
enum class   ERawOptions : ETL_UINT32
{
    /// @brief  Nothing.
    eNone            = 0,

    /// @brief  No echo of what is typed.
    eNoEcho            = 1u << 0,

    /// @brief  Delivers key by key, without waiting for the end of the line.
    eNoCanonical    = 1u << 1,

    /// @brief  Ctrl-C stops sending a signal and arrives as a key.
    eNoSignals        = 1u << 2,

    /// @brief  What is usually wanted: no echo and no canonical mode.
    eDefault        = eNoEcho | eNoCanonical
};

What to enable in raw mode. Flags.

operator

operator|

Ethereal::Cli#
inline ERawOptions operator|( const ERawOptions A, const ERawOptions B ) noexcept

Combines two option sets.

class

CRawMode

Ethereal::Cli#

Puts the terminal in raw mode, and restores it when it goes out of scope.

class CRawMode final

Restoring is what matters, so this also registers with the emergency restore (see 'screen.hpp'). A process killed by a signal in raw mode leaves the console with no echo, and the person in front of it does not see what they type.

constructor

CRawMode

#
CRawMode() noexcept;

Constructor. Does not enter raw mode.

function

Enter

#
bool Enter( ERawOptions Options = ERawOptions::eDefault ) noexcept;

Enters raw mode.

Options
What to enable.
false when the input is not a terminal, the system refused, or the library is not licensed.
function

Leave

#
void Leave() noexcept;

Leaves now, instead of waiting for the end of the scope.

function

IsActive

#
bool IsActive() const noexcept

Tells whether raw mode is on.

function

ReadKey

#
bool ReadKey( SKeyEvent * pOut, ETL_UINT32 uTimeoutMs = 0xFFFFFFFFu ) noexcept;

Reads a key, waiting at most uTimeoutMs.

pOut
Receives the key.
uTimeoutMs
Zero does not wait. 0xFFFFFFFF waits forever.
true when there is a key.
function

SetEscapeDelay

#
void SetEscapeDelay( const ETL_UINT32 uMs ) noexcept

How long to wait for more bytes after a lone Escape.

The spec asks for this to be configurable, and the reason is in the file header: over a slow link the default is not enough.

lineedit.hpp

#include <ethereal/cpp/cli/lineedit.hpp>

Line editing of the Cli module.

All buffers belong to the caller, and the spec is explicit: "All buffers come from the caller. The editor never allocates." This is not fussiness. A line editor runs inside a password prompt, or inside a shell already short on memory, the worst place to find out an allocation failed.

The editing logic is apart from the reading. CLineBuffer applies keys to a buffer and reads from nowhere. CLineEditor adds raw mode, the state machine and drawing. It is the same split as 'input.hpp', for the same reason: without it, key bindings can only be tested by hand, at a terminal, with a person pressing keys. With it, a test sends Ctrl-A, Ctrl-K and an arrow and checks the result.

Cursor math is in columns. "Multi-line input with correct wrapping and cursor math under wide characters." Moving the cursor "one place" is not one byte nor one character: an ideogram takes two columns, a combining accent none. See 'width.hpp'.

enum

EEditResult

Ethereal::Cli#
C++
enum class   EEditResult : ETL_UINT8
{
    /// @brief  Something changed, a redraw is needed.
    eChanged = 0,

    /// @brief  Nothing changed.
    eIgnored,

    /// @brief  The line is ready.
    eAccepted,

    /// @brief  The user cancelled.
    eCancelled,

    /// @brief  End of input with an empty line.
    eEndOfInput,

    /// @brief  Completion was requested.
    eComplete,

    /// @brief  History search was requested.
    eSearch
};

What a key did to the buffer.

class

CLineBuffer

Ethereal::Cli#

A line buffer with the usual key bindings.

class CLineBuffer final

Reads from nowhere and allocates nothing. See the file header.

constructor

CLineBuffer

#
CLineBuffer() noexcept;

Constructor. Call Init before use.

function

Init

#
void Init( ETL_CHAR * pBuffer, std::size_t uCapacity, ETL_CHAR * pKill = nullptr, std::size_t uKill = 0 ) noexcept;

Sets where to write.

pBuffer
The line buffer. Owned by the caller.
uCapacity
Bytes that fit, counting the terminator.
pKill
Where to keep what is cut. May be null.
uKill
Size of pKill.
function

Clear

#
void Clear() noexcept;

Empties the buffer.

function

SetText

#
void SetText( const ETL_CHAR * pText ) noexcept;

Sets this text, with the cursor at the end.

function

Apply

#
EEditResult Apply( const SKeyEvent & Key ) noexcept;

Applies a key.

Key
The key.
What the key did.
function

Text

#
const ETL_CHAR * Text() const noexcept

The text, null terminated.

function

Length

#
std::size_t Length() const noexcept

Length of the text, in bytes.

function

Cursor

#
std::size_t Cursor() const noexcept

Cursor position, in bytes.

function

CursorColumn

#
std::size_t CursorColumn() const noexcept;

Cursor position, in columns. This is the one used to draw it.

function

Killed

#
const ETL_CHAR * Killed() const noexcept

What was cut last.

function

MoveHome

#
void MoveHome() noexcept

Moves to the start of the line.

function

MoveEnd

#
void MoveEnd() noexcept

Moves to the end of the line.

function

MoveLeft

#
void MoveLeft() noexcept;

Moves one character left.

function

MoveRight

#
void MoveRight() noexcept;

Moves one character right.

function

MoveWordLeft

#
void MoveWordLeft() noexcept;

Moves one word back.

function

MoveWordRight

#
void MoveWordRight() noexcept;

Moves one word forward.

struct

SLineEditorOptions

Ethereal::Cli#
C++
struct   SLineEditorOptions   final
{
    /// @brief  The line buffer, owned by the caller, and its capacity.
    ETL_CHAR *        pBuffer = nullptr;
    std::size_t        uCapacity = 0;

    /// @brief  Where to keep what is cut, and its capacity. May be null.
    ETL_CHAR *        pKill = nullptr;
    std::size_t        uKillCapacity = 0;

    /// @brief  The history, oldest first, and its size. May be null.
    const ETL_CHAR * const *    ppHistory = nullptr;
    std::size_t                    uHistoryCount = 0;

    /// @brief  What to write before the line.
    const ETL_CHAR *    pPrompt = nullptr;

    /// @brief  Hide what is typed.
    ///
    /// @details  With this on, the buffer is wiped byte by byte when the editor
    ///            dies, not only marked empty. A password left on the stack is a
    ///            password that shows up in a memory dump.
    ///
    bool            bPassword = false;

    /// @brief  What to show for each character in password mode. Zero shows
    ///             nothing.
    ETL_CHAR        cMask = '*';
};

What the caller gives a line editor.

class

CLineEditor

Ethereal::Cli#

Reads a line, with editing.

class CLineEditor final
constructor

CLineEditor

#
CLineEditor() noexcept;

Constructor. Call Init before use.

function

Init

#
bool Init( const SLineEditorOptions & Options ) noexcept;

Sets up the editor.

Options
The options.
false when the buffer is null or holds less than two bytes, or when the library is not licensed.
function

ReadLine

#
bool ReadLine( CWriter & W, std::size_t * pLen = nullptr ) noexcept;

Reads a line.

W
The writer.
pLen
Receives the length in bytes. May be null.
true when there is a line. false when cancelled or at the end of input.
function

Buffer

#
CLineBuffer & Buffer() noexcept

The edit buffer, for callers that drive it by hand.

function

Render

#
void Render( CWriter & W ) noexcept;

Redraws the line and puts the cursor where it belongs.

Public so it can be tested. A test drives the buffer by hand and asks for the drawing, with no terminal at all.

progress.hpp

#include <ethereal/cpp/cli/progress.hpp>

Progress bars and spinners of the Cli module.

The spec of this module opens on this: "A progress bar that issues a write syscall per update will dominate the runtime of the tool it is measuring." The target: "Progress bar overhead | < 1 percent of a 10 second operation at default rate limit".

Two things set this apart from a naive bar.

1. The rate limit. A loop over a million files calls Update a million times. Drawing a million frames serves no one, the eye sees thirty per second. Calls between frames cost one clock read and one compare, nothing more.

2. Only what changed is redrawn. An eighty column bar at 30 Hz for ten seconds is twenty four thousand cells, and most are equal to the previous frame. Keeping what was drawn and writing only the difference cuts that to almost nothing.

Outside a terminal there is no bar at all. "All of them detect non-TTY output and degrade to periodic plain-text lines, because a progress bar piped into a log file is garbage." A log full of '\r' and blocks is unreadable and cannot be searched. Outside a terminal a line with the number is written now and then.

struct

SProgressStyle

Ethereal::Cli#
C++
struct   SProgressStyle   final
{
    /// @brief  The filled cell. Without Unicode it falls back to '#'.
    const ETL_CHAR *    pFill = nullptr;

    /// @brief  The empty cell. Without Unicode it falls back to '-'.
    const ETL_CHAR *    pEmpty = nullptr;

    /// @brief  Columns of the bar. Zero uses a third of the terminal width.
    ETL_UINT16            uWidth = 0;

    /// @brief  Maximum frames per second. Zero uses thirty.
    ETL_UINT16            uMaxFps = 0;

    /// @brief  Seconds between plain lines, outside a terminal.
    ///
    /// @details  Zero means "on every update", not "never". It is what a test
    ///            wants, and it also makes sense for output piped to a log that
    ///            already has timestamps.
    ///
    ETL_UINT16            uPlainSeconds = 5;

    /// @brief  Draw the bar even when the output does not look like a terminal.
    ///
    /// @details  This exists because a test has no terminal. Without it, the
    ///            drawing path (the expensive one, the one the rate limit exists
    ///            to contain) never runs in an automated test, and measuring the
    ///            rate limit would measure the wrong path. It happened in this
    ///            suite: the measure gave zero frames from a million calls, and
    ///            the comment said it forced drawing without forcing anything.
    ///
    ///            It also serves output embedded in a window of its own, whose
    ///            owner knows more than the probe.
    ///
    bool                bForceDraw = false;

    /// @brief  Show the percentage.
    bool                bPercent = true;

    /// @brief  Show the estimated time left.
    bool                bEta = true;
};

How the bar looks.

class

CProgress

Ethereal::Cli#

A progress bar.

class CProgress final
constructor

CProgress

#
CProgress() noexcept;

Constructor. Call Start before use.

function

Start

#
void Start( ETL_UINT64 uTotal, const SProgressStyle & Style = SProgressStyle() ) noexcept;

Starts the bar.

uTotal
The total. Zero makes an indeterminate bar.
Style
How the bar looks.
function

SetLabel

#
void SetLabel( const ETL_CHAR * pLabel ) noexcept;

Text shown before the bar. May be null.

function

Update

#
void Update( CWriter & W, ETL_UINT64 uCurrent ) noexcept;

Reports the progress, and draws when it is time to.

Calling it a million times is cheap. The frame is what costs, and frames only happen thirty times per second.

W
The writer.
uCurrent
Current progress.
function

Advance

#
void Advance( CWriter & W, ETL_UINT64 uDelta = 1 ) noexcept;

Adds uDelta to the progress.

function

Redraw

#
void Redraw( CWriter & W ) noexcept;

Draws now, ignoring the rate limit.

function

Finish

#
void Finish( CWriter & W ) noexcept;

Finishes: draws the last frame and moves to the next line.

function

Current

#
ETL_UINT64 Current() const noexcept

Current progress.

function

Total

#
ETL_UINT64 Total() const noexcept

The total.

function

FrameCount

#
ETL_UINT64 FrameCount() const noexcept

Number of frames drawn.

The oracle of the rate limit: a million calls to Update in one second must leave this in the tens, not in the millions.

function

UpdateCount

#
ETL_UINT64 UpdateCount() const noexcept

Number of calls to Update.

function

IsDrawing

#
bool IsDrawing() const noexcept

true when drawing a bar, false when writing plain lines.

enum

ESpinnerFrames

Ethereal::Cli#
C++
ETL_END_INTENDED_PADDING


///=============================================================================
///  Spinner
///=============================================================================


/// @brief  Frame sets a spinner can use.
///
enum class   ESpinnerFrames : ETL_UINT8
{
    /// @brief  Bars: - \ | /. Works everywhere.
    eAscii = 0,

    /// @brief  Braille dots. Needs Unicode.
    eDots,

    /// @brief  A filling circle.
    eCircle
};
class

CSpinner

Ethereal::Cli#

A spinner, for when the amount left is unknown.

class CSpinner final
constructor

CSpinner

#
CSpinner() noexcept;

Constructor. Call Start before use.

function

Start

#
void Start( ESpinnerFrames eFrames = ESpinnerFrames::eAscii, ETL_UINT16 uMaxFps = 0 ) noexcept;

Starts the spinner.

eFrames
Frame set. Without Unicode it falls back to eAscii.
uMaxFps
Maximum frames per second. Zero uses twelve.
function

SetLabel

#
void SetLabel( const ETL_CHAR * pLabel ) noexcept;

Text shown after the spinner. May be null.

function

Tick

#
void Tick( CWriter & W ) noexcept;

Turns, when it is time to.

function

Finish

#
void Finish( CWriter & W, const ETL_CHAR * pFinal = nullptr ) noexcept;

Finishes: clears the line and writes the given text.

W
The writer.
pFinal
Text to write. May be null.
function

FrameCount

#
ETL_UINT64 FrameCount() const noexcept

Number of frames drawn.

class

CMultiProgress

Ethereal::Cli#

Several stacked bars, redrawn as a block.

class CMultiProgress final

The spec says why it has to be a block: "redrawn as a block with cursor-up positioning, which is the only correct way to do it without flicker."

Redrawing one bar at a time makes them flash in order, and the eye sees a wave crossing the screen. Moving the cursor up, writing the whole block and coming back shows it all at the same instant.

constructor

CMultiProgress

#
CMultiProgress() noexcept;

Constructor. Call Init before use.

function

Init

#
void Init( CProgress * pBars, std::size_t uCount ) noexcept;

Sets how many bars there are and where they live.

pBars
The array. Owned by the caller, and must outlive this.
uCount
Number of bars.
function

Bar

#
CProgress * Bar( std::size_t uIndex ) noexcept;

The bar at uIndex, or null when out of range.

function

Draw

#
void Draw( CWriter & W ) noexcept;

Redraws the whole block, when it is time to.

function

Finish

#
void Finish( CWriter & W ) noexcept;

Finishes: draws the last block and leaves the cursor below it.

function

BlockCount

#
ETL_UINT64 BlockCount() const noexcept

Number of blocks drawn.

screen.hpp

#include <ethereal/cpp/cli/screen.hpp>

Cursor, screen and terminal restore of the Cli module.

The spec makes this an acceptance criterion, the hardest of this module: "Terminal restore | original mode restored after normal exit, after an exception, and after SIGINT, verified on all three platforms".

A destructor handles the normal exit and the exception, since stack unwinding calls it. A signal unwinds no stack. A Ctrl-C that kills the process leaves the terminal in raw mode, with no echo and no line editing, and the person in front of it gets a console that does not respond to what they type.

So there are two separate things here: the destructor, for the normal path and the exception, and an emergency restore registry, which the signal handler calls.

A signal handler can do very little. It cannot allocate, take a lock or call most of the C library. It can write bytes to a descriptor, and that is all the restore does.

function

CursorTo

Ethereal::Cli#
void CursorTo( CWriter & W, ETL_UINT16 uRow, ETL_UINT16 uCol ) noexcept;

Moves the cursor to an absolute position. Both count from one.

W
The writer.
uRow
Row, from one.
uCol
Column, from one.
function

CursorUp

Ethereal::Cli#
void CursorUp( CWriter & W, ETL_UINT16 uLines = 1 ) noexcept;

Moves the cursor up uLines lines.

function

CursorDown

Ethereal::Cli#
void CursorDown( CWriter & W, ETL_UINT16 uLines = 1 ) noexcept;

Moves the cursor down uLines lines.

function

CursorLeft

Ethereal::Cli#
void CursorLeft( CWriter & W, ETL_UINT16 uCols = 1 ) noexcept;

Moves the cursor uCols columns to the left.

function

CursorRight

Ethereal::Cli#
void CursorRight( CWriter & W, ETL_UINT16 uCols = 1 ) noexcept;

Moves the cursor uCols columns to the right.

function

CursorSave

Ethereal::Cli#
void CursorSave( CWriter & W ) noexcept;

Saves the cursor position.

function

CursorRestore

Ethereal::Cli#
void CursorRestore( CWriter & W ) noexcept;

Restores the saved cursor position.

function

CursorShow

Ethereal::Cli#
void CursorShow( CWriter & W ) noexcept;

Shows the cursor.

function

CursorHide

Ethereal::Cli#
void CursorHide( CWriter & W ) noexcept;

Hides the cursor.

function

ClearScreen

Ethereal::Cli#
void ClearScreen( CWriter & W ) noexcept;

Clears the screen and moves the cursor home.

function

ClearLine

Ethereal::Cli#
void ClearLine( CWriter & W ) noexcept;

Clears the current line.

function

ClearToEndOfLine

Ethereal::Cli#
void ClearToEndOfLine( CWriter & W ) noexcept;

Clears from the cursor to the end of the line.

function

ClearToEndOfScreen

Ethereal::Cli#
void ClearToEndOfScreen( CWriter & W ) noexcept;

Clears from the cursor to the end of the screen.

function

SetScrollRegion

Ethereal::Cli#
void SetScrollRegion( CWriter & W, ETL_UINT16 uTop, ETL_UINT16 uBottom ) noexcept;

Limits scrolling to a range of rows. Zero in both undoes it.

W
The writer.
uTop
First row of the region.
uBottom
Last row of the region.
function

EnterAltScreen

Ethereal::Cli#
void EnterAltScreen( CWriter & W ) noexcept;

Enters the alternate screen.

Whoever enters must leave. A program that dies on the alternate screen leaves the terminal there, and what was on screen before looks lost. It is not, but the person in front does not know.

function

LeaveAltScreen

Ethereal::Cli#
void LeaveAltScreen( CWriter & W ) noexcept;

Leaves the alternate screen.

enum

ERestore

Ethereal::Cli#
C++
enum class   ERestore : ETL_UINT32
{
    /// @brief  Nothing.
    eNone            = 0,

    /// @brief  Show the cursor.
    eShowCursor        = 1u << 0,

    /// @brief  Reset the style.
    eResetStyle        = 1u << 1,

    /// @brief  Leave the alternate screen.
    eLeaveAlt        = 1u << 2,

    /// @brief  Undo the scroll region.
    eScrollRegion    = 1u << 3,

    /// @brief  Leave raw mode.
    eRawMode        = 1u << 4
};

What to restore when the process dies suddenly. Flags.

operator

operator|

Ethereal::Cli#
inline ERestore operator|( const ERestore A, const ERestore B ) noexcept

Combines two restore sets.

function

RegisterRestore

Ethereal::Cli#
void RegisterRestore( EStream eStream, ERestore What ) noexcept;

Adds to what the emergency restore will do.

Not safe to call from a signal handler: this is the registry, and it runs on the normal path. EmergencyRestore is the safe one.

eStream
The stream.
What
What to add.
function

UnregisterRestore

Ethereal::Cli#
void UnregisterRestore( EStream eStream, ERestore What ) noexcept;

Removes from the registry.

eStream
The stream.
What
What to remove.
function

EmergencyRestore

Ethereal::Cli#
void EmergencyRestore() noexcept;

Restores everything in the registry. Callable from a signal handler.

Does not allocate, does not lock, does not call the C library. It writes bytes to a descriptor and restores the terminal mode, nothing more.

function

PendingRestore

Ethereal::Cli#
ERestore PendingRestore( EStream eStream ) noexcept;

What is registered now. For diagnostics and tests.

function

InstallSignalRestore

Ethereal::Cli#
bool InstallSignalRestore() noexcept;

Installs signal handlers that restore the terminal and move on.

After restoring, it goes back to the previous behavior, and does not swallow the signal. A Ctrl-C must still kill the program. What it must not do is kill the program leaving the terminal broken.

On POSIX it handles SIGINT, SIGTERM, SIGHUP, SIGQUIT, SIGSEGV and SIGABRT. On Windows, the console handler.

false when it could not be installed.
class

CScreenGuard

Ethereal::Cli#

Restores the screen when it goes out of scope, exceptions included.

class CScreenGuard final

See the file header on why this alone is not enough, and why there is also the emergency registry.

constructor

CScreenGuard

#
CScreenGuard( CWriter & W, ERestore What ) noexcept;

Sets up what What says, and restores it at the end.

W
The writer.
What
What to set up and restore.
function

Restore

#
void Restore() noexcept;

Restores now, instead of waiting for the end of the scope.

function

Release

#
void Release() noexcept

Forgets without restoring.

style.hpp

#include <ethereal/cpp/cli/style.hpp>

Terminal capabilities, colors and styles of the Cli module.

Detection order: explicit override from the caller, then the NO_COLOR and FORCE_COLOR environment variables, then TERM and COLORTERM, then the platform query.

The caller comes first because it may know things no probe finds out (it writes to its own window, for example). NO_COLOR comes before the rest because it is a convention that is either respected or not, and some people need it because they cannot tell colors apart.

Detection runs once per stream and is cached. It is never queried again per write: asking the system whether the output is a terminal on every write would put a syscall on the path this module exists to clear.

Styles are applied as a delta against the current state, so redundant escape sequences are never written.

enum

ECapability

Ethereal::Cli#
C++
enum class   ECapability : ETL_UINT32
{
    /// @brief  Nothing.
    eNone            = 0,

    /// @brief  Understands escape sequences.
    eAnsi            = 1u << 0,

    /// @brief  Sixteen colors.
    eColor16        = 1u << 1,

    /// @brief  256 colors.
    eColor256        = 1u << 2,

    /// @brief  24 bit color.
    eTrueColor        = 1u << 3,

    /// @brief  Draws non ASCII characters.
    eUnicode        = 1u << 4,

    /// @brief  Links text to an address (OSC 8).
    eHyperlinks        = 1u << 5,

    /// @brief  Tells when the input is a paste.
    eBracketedPaste    = 1u << 6,

    /// @brief  Has an alternate screen.
    eAltScreen        = 1u << 7,

    /// @brief  Reports the mouse.
    eMouse            = 1u << 8
};

What the terminal can do. Flags, combined with |.

operator

operator|

Ethereal::Cli#
inline ECapability operator|( const ECapability A, const ECapability B ) noexcept

Combines two capability sets.

function

Has

Ethereal::Cli#
inline bool Has( const ECapability Set, const ECapability One ) noexcept

Tells whether the set has the capability.

function

Capabilities

Ethereal::Cli#
ECapability Capabilities( EStream eStream = EStream::eOut ) noexcept;

What the terminal of this stream can do. Computed once.

eStream
The stream.
The capability set.
function

OverrideCapabilities

Ethereal::Cli#
void OverrideCapabilities( EStream eStream, ECapability Caps ) noexcept;

Sets the capabilities instead of detecting them.

For callers that know more than the probe, and for the tests, which need to run the path of each color level regardless of the terminal at hand. Without it, the 256 color path would never run on a machine whose terminal speaks 24 bits, and a defect there would only show on the integrator's machine.

eStream
The stream.
Caps
The capabilities to use.
function

ResetCapabilities

Ethereal::Cli#
void ResetCapabilities() noexcept;

Detects again. Undoes OverrideCapabilities.

enum

EColorTag

Ethereal::Cli#
C++
enum class   EColorTag : ETL_UINT8
{
    /// @brief  The terminal default. Writes nothing.
    eDefault = 0,

    /// @brief  An index from 0 to 255.
    eIndexed,

    /// @brief  24 bit color.
    eRgb
};

Kind of a color.

struct

SColor

Ethereal::Cli#
C++
struct   SColor   final
{
    /// @brief  The EColorTag.
    ETL_UINT8    uTag;

    /// @brief  Red, or the index when eIndexed.
    ETL_UINT8    uR;

    /// @brief  Green.
    ETL_UINT8    uG;

    /// @brief  Blue.
    ETL_UINT8    uB;


    /// @brief  The terminal default color.
    ///
    ETL_API_NOIGN    static SColor Default() ETL_NOEXCEPT
    {
        return SColor{ static_cast< ETL_UINT8 >( EColorTag::eDefault ), 0, 0, 0 };
    }


    /// @brief  An indexed color.
    ///
    ETL_API_NOIGN    static SColor Indexed( const ETL_UINT8 uIndex ) ETL_NOEXCEPT
    {
        return SColor{ static_cast< ETL_UINT8 >( EColorTag::eIndexed ), uIndex, 0, 0 };
    }


    /// @brief  A 24 bit color.
    ///
    ETL_API_NOIGN    static SColor Rgb( const ETL_UINT8 r, const ETL_UINT8 g,
                                       const ETL_UINT8 b ) ETL_NOEXCEPT
    {
        return SColor{ static_cast< ETL_UINT8 >( EColorTag::eRgb ), r, g, b };
    }
};

A color, in four bytes.

operator

operator==

Ethereal::Cli#
inline bool operator==( const SColor & A, const SColor & B ) noexcept

Equality of colors.

operator

operator!=

Ethereal::Cli#
inline bool operator!=( const SColor & A, const SColor & B ) noexcept

Inequality of colors.

enum

EAttr

Ethereal::Cli#
C++
enum class   EAttr : ETL_UINT16
{
    /// @brief  No attribute.
    eNone        = 0,

    /// @brief  Bold.
    eBold        = 1u << 0,

    /// @brief  Dim.
    eDim        = 1u << 1,

    /// @brief  Italic.
    eItalic        = 1u << 2,

    /// @brief  Underline.
    eUnderline    = 1u << 3,

    /// @brief  Blink.
    eBlink        = 1u << 4,

    /// @brief  Reverse video.
    eReverse    = 1u << 5,

    /// @brief  Strikethrough.
    eStrike        = 1u << 6
};

Text attributes. Flags, combined with |.

operator

operator|

Ethereal::Cli#
inline EAttr operator|( const EAttr A, const EAttr B ) noexcept

Combines two attribute sets.

struct

SStyle

Ethereal::Cli#
C++
struct   SStyle   final
{
    /// @brief  Foreground color.
    SColor        Fg;

    /// @brief  Background color.
    SColor        Bg;

    /// @brief  EAttr flags.
    ETL_UINT16    uAttributes;


    /// @brief  The default style: default colors, no attributes.
    ///
    ETL_API_NOIGN    static SStyle None() ETL_NOEXCEPT
    {
        return SStyle{ SColor::Default(), SColor::Default(), 0 };
    }
};

A complete style.

Ten bytes, while the spec asks for eight. The spec describes SColor as "packed into 4 bytes" and the style as "{ SColor Fg, Bg; uint16_t iAttributes; } // POD, 8 bytes". That does not add up: four plus four plus two is ten.

It would fit in eight by taking bits from something (sixteen attributes are not needed, and the color tag uses a byte for three values). That would put bit shifts in every place that reads a color, to save four bytes in a struct that lives on the stack and never in a large vector.

It stays at ten, and the number is written here. What matters from the spec (POD, trivially copyable, no pointers) holds, and the test asserts it.

operator

operator==

Ethereal::Cli#
inline bool operator==( const SStyle & A, const SStyle & B ) noexcept

Equality of styles.

function

Downgrade

Ethereal::Cli#
SColor Downgrade( SColor Color, ECapability Caps ) noexcept;

Lowers a color to what the terminal supports.

24 bit, then 256, then 16, then none, by the capabilities.

RGB to index uses the six level grid of the 256 mode. To the sixteen colors it uses the nearest by distance. There is no cache because none is needed: the math is a handful of compares, on a path that writes an escape sequence, which already costs more.

Color
The color.
Caps
The terminal capabilities.
The color the terminal can show.
class

CStyleState

Ethereal::Cli#

Keeps the style the terminal has now, to write only the difference.

class CStyleState final

Writing the color on every cell of a thousand row table, when it does not change, is a thousand sequences that do nothing. Each one costs bytes in the buffer and work in the terminal.

constructor

CStyleState

#
explicit CStyleState( ECapability Caps ) noexcept;

Constructor.

Caps
Capabilities of the terminal it writes to.
function

Apply

#
std::size_t Apply( CWriter & W, const SStyle & Style ) noexcept;

Writes only what changed between the current style and Style.

W
The writer.
Style
The new style.
Number of bytes written. Zero means nothing changed.
function

Reset

#
void Reset( CWriter & W ) noexcept;

Restores the terminal style and forgets the current one.

W
The writer.
function

Current

#
const SStyle & Current() const noexcept

The style it believes is set.

function

SequenceCount

#
ETL_UINT64 SequenceCount() const noexcept

Number of sequences written, ever.

The oracle of the delta: applying the same style twice must leave this number unchanged.

class

CScopedStyle

Ethereal::Cli#

Restores the previous style when it goes out of scope.

class CScopedStyle final
constructor

CScopedStyle

#
CScopedStyle( CStyleState & State, CWriter & W, const SStyle & Style ) noexcept;

Applies Style and saves the previous one.

State
The style state.
W
The writer.
Style
The style to apply.

table.hpp

#include <ethereal/cpp/cli/table.hpp>

Tables of the Cli module.

Alignment is by columns, not by bytes nor characters. That is why 'width.hpp' exists. A table aligned with 'strlen' breaks on the first Japanese name, and one aligned by characters breaks on the first combining accent.

Rendering is by rows. The spec: "Rendering is streaming where possible so a large table does not need to be buffered whole before the first row prints."

There is a tension here. The automatic width of a column depends on all the rows, so it cannot be known before seeing them. Both cannot hold together. The way out: callers that want streaming give the widths. Callers that do not, pay for a measuring pass, and that pass does not keep the cells, it only measures.

enum

EAlign

Ethereal::Cli#
C++
enum class   EAlign : ETL_UINT8
{
    /// @brief  Left.
    eLeft = 0,

    /// @brief  Right.
    eRight,

    /// @brief  Centered.
    eCenter
};

Where the text of a column leans.

enum

EBorder

Ethereal::Cli#
C++
enum class   EBorder : ETL_UINT8
{
    /// @brief  None. Only the cells, separated by spaces.
    eNone = 0,

    /// @brief  With '+', '-' and '|'. The fallback when there is no Unicode.
    eAscii,

    /// @brief  Light line.
    eLight,

    /// @brief  Heavy line.
    eHeavy
};

How to draw the borders.

struct

SColumn

Ethereal::Cli#
C++
struct   SColumn   final
{
    /// @brief  Title of the column.
    const ETL_CHAR *    pTitle = nullptr;

    /// @brief  Minimum width. Zero sets no minimum.
    ETL_UINT16            uMin = 0;

    /// @brief  Maximum width. Zero sets no maximum.
    ETL_UINT16            uMax = 0;

    /// @brief  Weight of this column when splitting the space to cut.
    ETL_UINT16            uWeight = 1;

    /// @brief  Alignment of the cells.
    EAlign                eAlign = EAlign::eLeft;

    /// @brief  Wrap the cell in several lines instead of cutting it.
    bool                bWrap = false;

    /// @brief  The resulting width. Filled by CTable::Measure.
    ETL_UINT16            uWidth = 0;

    /// @brief  Padding.
    ETL_UINT8            aPad[ 2 ] = {};
};

A column.

class

CTable

Ethereal::Cli#

Draws a table.

class CTable final

Does not keep the cells. The caller hands one row at a time and the table writes it. It only keeps the columns, which are few.

constructor

CTable

#
CTable() noexcept;

Constructor. Call Init before use.

function

Init

#
void Init( SColumn * pColumns, std::size_t uCount ) noexcept;

Sets the columns.

pColumns
The array. Must outlive this table.
uCount
Number of columns.
function

SetBorder

#
void SetBorder( EBorder eBorder ) noexcept;

How to draw the borders.

Without Unicode, light and heavy fall back to ASCII by themselves. Box drawing characters on a terminal that lacks them fill the table with replacement glyphs.

function

Border

#
EBorder Border() const noexcept

The border style in use.

function

SetTotalWidth

#
void SetTotalWidth( ETL_UINT16 uWidth ) noexcept;

Total width available. Zero asks the terminal.

function

Measure

#
void Measure( const ETL_CHAR * const * ppCells, std::size_t uCount ) noexcept;

Tells the table a row with these cells exists, without drawing it.

For callers that do not know the widths. See the file header on the tension between measuring and streaming: this only measures, and keeps nothing.

ppCells
The cells of the row.
uCount
Number of cells.
function

Finish

#
void Finish() noexcept;

Closes the measuring and splits the space.

function

IsMeasured

#
bool IsMeasured() const noexcept

Tells whether the measuring was closed.

function

WriteTop

#
void WriteTop( CWriter & W ) noexcept;

Writes the top border.

function

WriteHeader

#
void WriteHeader( CWriter & W ) noexcept;

Writes the row of titles.

function

WriteSeparator

#
void WriteSeparator( CWriter & W ) noexcept;

Writes the border between the titles and the body.

function

WriteRow

#
void WriteRow( CWriter & W, const ETL_CHAR * const * ppCells, std::size_t uCount ) noexcept;

Writes a row of cells.

W
The writer.
ppCells
The cells of the row.
uCount
Number of cells.
function

WriteBottom

#
void WriteBottom( CWriter & W ) noexcept;

Writes the bottom border.

terminal.hpp

#include <ethereal/cpp/cli/terminal.hpp>

Terminal detection, color, cursor and progress bar of the Cli module.

A command line program writes for two audiences: a person at a terminal, and a file someone reads later. The sequences that paint the output for the first are garbage for the second ('ESC[31mfailed ESC[0m' in a log file, in a 'grep', in a CI system).

So this module has no "paint it red" function. It has Colorize, which returns the raw text when no one is watching. The decision is taken once, in one place, and not repeated at every write, where one of them forgets it.

1. Detection is per descriptor, not per program. The standard output can be a terminal while the error output is redirected, and the other way around. Every query of this module takes the stream, and IsTerminal answers for it.

2. On Windows, writing the sequence is not enough. The console only interprets terminal sequences after 'ENABLE_VIRTUAL_TERMINAL_PROCESSING' is enabled, and before 2016 it cannot be enabled at all. EnableAnsi tries and returns whether it worked. When it does not, color stays off and the text comes out clean, instead of with the sequences visible.

3. 'NO_COLOR' is respected. It is the de facto convention (no-color.org): the mere presence of the variable, with any value, disables color. It exists so people with screen readers, high contrast terminals or channels that do not understand the sequences can say so once, for all programs. 'CLICOLOR_FORCE' does the opposite and beats detection, for output piped to a pager that understands the sequences. Order of decision, strongest first: 1. SetColorEnabled, if called. The program wins. 2. 'NO_COLOR' present: off. 3. 'CLICOLOR_FORCE' present and not "0": on. 4. The stream is a terminal and the sequences work in it.

4. The width can be unknown, and zero says so. Redirected, in a service, in a pipe, there is no width. Width returns zero in those cases instead of making up 80, because a progress bar needs to tell "80 columns fit" from "there is no screen".

enum

EStream

Ethereal::Cli#
C++
enum class EStream : ETL_UINT8
{
    /// @brief  Standard output. Carries the result of the program, what
    ///             another program consumes through a pipe.
    eOut = 0,

    /// @brief  Error output. Carries the messages for the person: progress,
    ///             warnings, diagnostics. Keeping both apart lets programs be
    ///             chained without diagnostics polluting the result.
    eErr = 1
};

Which of the two output streams.

enum

EColor

Ethereal::Cli#
C++
enum class EColor : ETL_UINT8
{
    /// @brief  The terminal default.
    eDefault = 0,

    /// @brief  Black.
    eBlack,

    /// @brief  Red.
    eRed,

    /// @brief  Green.
    eGreen,

    /// @brief  Yellow.
    eYellow,

    /// @brief  Blue.
    eBlue,

    /// @brief  Magenta.
    eMagenta,

    /// @brief  Cyan.
    eCyan,

    /// @brief  White.
    eWhite,

    /// @brief  Bright black (gray).
    eBrightBlack,

    /// @brief  Bright red.
    eBrightRed,

    /// @brief  Bright green.
    eBrightGreen,

    /// @brief  Bright yellow.
    eBrightYellow,

    /// @brief  Bright blue.
    eBrightBlue,

    /// @brief  Bright magenta.
    eBrightMagenta,

    /// @brief  Bright cyan.
    eBrightCyan,

    /// @brief  Bright white.
    eBrightWhite
};

The sixteen terminal colors.

There is deliberately no 24 bit color here. Modern terminals have it, many do not, and there is no reliable way to detect which case it is. The result would be a color that is sometimes wrong. These sixteen are right everywhere the sequences work.

enum

EStyle

Ethereal::Cli#
C++
enum class EStyle : ETL_UINT8
{
    /// @brief  No style.
    eNone      = 0,

    /// @brief  Bold.
    eBold      = 1 << 0,

    /// @brief  Dim.
    eDim       = 1 << 1,

    /// @brief  Italic.
    eItalic    = 1 << 2,

    /// @brief  Underline.
    eUnderline = 1 << 3,

    /// @brief  Reverse video.
    eReverse   = 1 << 4
};

Text styles. Flags, combined with |.

operator

operator|

Ethereal::Cli#
inline EStyle operator|( const EStyle A, const EStyle B ) noexcept

Combines two style sets.

function

HasStyle

Ethereal::Cli#
inline bool HasStyle( const EStyle Set, const EStyle One ) noexcept

Tells whether the set has the style.

function

IsTerminal

Ethereal::Cli#
bool IsTerminal( const EStream eStream ) noexcept;

Tells whether eStream is attached to a terminal, and not to a file or pipe.

function

EnableAnsi

Ethereal::Cli#
bool EnableAnsi( const EStream eStream ) noexcept;

Tries to enable terminal sequences on eStream.

On Windows, enables ENABLE_VIRTUAL_TERMINAL_PROCESSING. Elsewhere there is nothing to do and the answer is that of IsTerminal. Calling it more than once is harmless.

eStream
The stream.
true when the sequences will be interpreted.
function

IsAnsiEnabled

Ethereal::Cli#
bool IsAnsiEnabled( const EStream eStream ) noexcept;

Tells whether the sequences work on eStream, without trying to enable them.

function

SetAnsiEnabled

Ethereal::Cli#
void SetAnsiEnabled( const EStream eStream, const bool bEnabled ) noexcept;

Decides, for the program, whether the sequences work on eStream.

Beats detection. It exists for two real cases, and one of them is being able to test this module: the drawing path only runs with a terminal, and under a test runner the output is always captured. Without this, half the module could not be exercised, and "cannot be tested" is often the start of "never ran".

The other case is output embedded in a surface that understands the sequences without being a terminal (a panel, a log viewer).

eStream
The stream.
bEnabled
true when the sequences work.
function

ClearAnsiOverride

Ethereal::Cli#
void ClearAnsiOverride( const EStream eStream ) noexcept;

Goes back to deciding by detection.

function

SetWriter

Ethereal::Cli#
void SetWriter( const EStream eStream, std::function< void( const std::string & ) > Fn );

Redirects everything this module writes on eStream to Fn.

For output embedded in another surface (a window, a log file, a test). While redirected, nothing goes to the descriptor.

The redirection covers Write, WriteLine, ClearLine, ShowCursor and the progress bar. It does not cover what the program writes on its own.

eStream
The stream.
Fn
Receives the text.
function

WriteRaw

Ethereal::Cli#
void WriteRaw( const EStream eStream, const char * pBytes, std::size_t uBytes ) noexcept;

One write, one syscall. No 'fflush' on top, no library buffer.

The primitive under CWriter. It goes straight to the system ('write' on POSIX, 'WriteFile' on Windows), because going through 'stdio' would add a second buffer and take away the control of when the syscall happens, which is what this module promises.

The SetWriter redirection still applies: a module embedded in a window still gets the bytes.

Not for direct use. Use CWriter, which batches the writes.

eStream
The stream.
pBytes
The bytes.
uBytes
Number of bytes.
function

ClearWriter

Ethereal::Cli#
void ClearWriter( const EStream eStream );

Removes the redirection.

function

SetColorEnabled

Ethereal::Cli#
void SetColorEnabled( const bool bEnabled ) noexcept;

Decides color for the program, ignoring detection.

It is the '--color' / '--no-color' of the command line. Beats everything, NO_COLOR included, because here the person asked, now.

bEnabled
true to enable color.
function

ClearColorOverride

Ethereal::Cli#
void ClearColorOverride() noexcept;

Goes back to deciding color by detection and environment.

function

IsColorEnabled

Ethereal::Cli#
bool IsColorEnabled( const EStream eStream ) noexcept;

Tells whether color goes out on eStream, considering everything (rule 3 of the file header).

function

Width

Ethereal::Cli#
ETL_UINT16 Width( const EStream eStream = EStream::eErr ) noexcept;

Terminal width in columns. Zero when unknown.

function

Height

Ethereal::Cli#
ETL_UINT16 Height( const EStream eStream = EStream::eErr ) noexcept;

Terminal height in rows. Zero when unknown.

function

Colorize

Ethereal::Cli#
std::string Colorize( const std::string & sText, const EColor eForeground, const EColor eBackground = EColor::eDefault, const EStyle eStyle = EStyle::eNone, const EStream eStream = EStream::eErr );

Returns sText painted, or exactly sText when color is off.

The whole point of this module. Calling it in a program whose output was redirected gives the clean text, without the call site having to remember to ask.

sText
The text.
eForeground
Foreground color.
eBackground
Background color.
eStyle
Text style.
eStream
Stream the text goes to. Color is decided per stream (rule 1).
The painted text, or the text unchanged.
function

BeginStyle

Ethereal::Cli#
std::string BeginStyle( const EColor eForeground, const EColor eBackground = EColor::eDefault, const EStyle eStyle = EStyle::eNone, const EStream eStream = EStream::eErr );

The opening sequence, with no text.

For callers that build the line in pieces. Returns empty when color is off, so it stays correct in that case.

eForeground
Foreground color.
eBackground
Background color.
eStyle
Text style.
eStream
Stream the text goes to.
The sequence, or empty.
function

EndStyle

Ethereal::Cli#
std::string EndStyle( const EStream eStream = EStream::eErr );

The closing sequence. Empty when color is off.

function

Write

Ethereal::Cli#
void Write( const EStream eStream, const std::string & sText );

Writes to eStream, adding nothing.

function

WriteLine

Ethereal::Cli#
void WriteLine( const EStream eStream, const std::string & sText );

Writes and ends the line.

alias

void

Ethereal::Cli#
using FResizeFn = void ( * )( void * pUser, ETL_UINT16 uCols, ETL_UINT16 uRows );

Called when the terminal changes size.

pUser
Context given at registration.
uCols
The new number of columns.
uRows
The new number of rows.
const

RESIZE_HANDLER_MAX

Ethereal::Cli#
constexpr ETL_UINT32 RESIZE_HANDLER_MAX = 4u;

Number of handlers that fit. No allocation: four are enough.

function

AddResizeHandler

Ethereal::Cli#
bool AddResizeHandler( void * pUser, FResizeFn pfn ) noexcept;

Registers to be told when the terminal changes size.

It is not called by itself. See PollResize and the note above.

pUser
Context passed to the handler.
pfn
The handler.
false when there are already RESIZE_HANDLER_MAX handlers, or when the pUser / pfn pair is already registered.
function

RemoveResizeHandler

Ethereal::Cli#
bool RemoveResizeHandler( void * pUser, FResizeFn pfn ) noexcept;

Stops being told. The pair must be the same one registered.

pUser
Context given at registration.
pfn
The handler.
true when the pair was found and removed.
function

ResizeHandlerCount

Ethereal::Cli#
ETL_UINT32 ResizeHandlerCount() noexcept;

Number of registered handlers.

function

EnableResizeWatch

Ethereal::Cli#
bool EnableResizeWatch( const EStream eStream = EStream::eErr ) noexcept;

Starts watching for size changes.

On POSIX this installs a 'SIGWINCH' handler, which is a process wide effect, so it has to be asked for instead of happening behind the back of someone who only wanted to write a line.

The previous handler is saved, restored by DisableResizeWatch, and called in chain while this one is on: a library that swallows another part's signal breaks the integrator's program.

On Windows nothing is installed. There the change is seen by asking for the size, which PollResize does.

eStream
The stream whose terminal is watched.
false when the system refused to install the handler.
function

DisableResizeWatch

Ethereal::Cli#
void DisableResizeWatch() noexcept;

Stops watching and restores the previous handler.

function

IsResizeWatchEnabled

Ethereal::Cli#
bool IsResizeWatchEnabled() noexcept;

Tells whether the watch is on.

function

PollResize

Ethereal::Cli#
bool PollResize( const EStream eStream = EStream::eErr ) noexcept;

Checks whether the size changed, and calls the handlers if so.

Runs on the caller's thread, not in a signal handler nor in a library thread. See the note above.

With the watch off it does nothing, returns false and calls no one. A notice on the first call would make everyone redraw once with nothing changed.

eStream
The stream whose terminal is watched.
true when the size changed and the handlers were called.
function

SimulateResize

Ethereal::Cli#
void SimulateResize( const ETL_UINT16 uCols, const ETL_UINT16 uRows ) noexcept;

Fakes a size change, for tests.

Without it, resizing cannot be tested: there is no way to resize the terminal from a bench, and a case that only runs when someone drags a window corner never runs.

It moves the remembered size to another value. The next PollResize sees the difference and calls the handlers, along the same path a real change takes.

uCols
Columns to remember.
uRows
Rows to remember.
function

ClearLine

Ethereal::Cli#
void ClearLine( const EStream eStream = EStream::eErr );

Clears the current line and moves the cursor to its start.

Does nothing when the sequences do not work, which is right: in a file, "clear the line" does not exist, and writing the sequence anyway would leave garbage in the text.

function

ShowCursor

Ethereal::Cli#
void ShowCursor( const bool bShow, const EStream eStream = EStream::eErr );

Hides or shows the cursor.

Whoever hides it must show it again, also when the program ends on an error. A hidden cursor stays hidden in the terminal after the program died, and the person is left with an odd terminal. CCursorHider does it by scope.

bShow
true to show, false to hide.
eStream
The stream.
class

CCursorHider

Ethereal::Cli#

Hides the cursor while alive, and shows it again when it goes out of scope.

class CCursorHider final
constructor

CCursorHider

#
explicit CCursorHider( const EStream eStream = EStream::eErr );

Hides the cursor on eStream.

class

CProgressBar

Ethereal::Cli#

A progress bar that knows when not to draw itself.

class CProgressBar final

A bar written to a log file turns into thousands of almost equal lines, which is why so many programs leave unreadable logs when they run in CI.

Here, when the stream is not a terminal, the bar does not redraw. It writes one plain line at each milestone, and the milestone size is set by SetPlainStep (10% by default). Full silence was the other option, and it was rejected because it leaves the log reader not knowing whether the program hung.

It goes to the error output by default, not the standard one: the bar is a message for the person, not a result of the program. Sending it to the standard output would break piping.

C++
Ethereal::Cli::CProgressBar Bar( uTotal );

Bar.SetLabel( "copying" );

for( ... )  Bar.Update( uDone );

Bar.Finish();
constructor

CProgressBar

#
explicit CProgressBar( const ETL_UINT64 uTotal, const EStream eStream = EStream::eErr );

Constructor.

uTotal
The total. Zero is allowed and means indeterminate progress: the bar shows activity, with no percentage.
eStream
The stream.
function

SetLabel

#
void SetLabel( const std::string & sLabel );

Text to the left of the bar.

function

SetWidth

#
void SetWidth( const ETL_UINT16 uWidth ) noexcept;

Width of the bar in characters. Zero uses the terminal width.

function

SetPlainStep

#
void SetPlainStep( const ETL_UINT8 uPercentStep ) noexcept;

Percentage step of the plain lines written when there is no terminal.

Zero silences it completely. The default is 10.

function

SetTotal

#
void SetTotal( const ETL_UINT64 uTotal ) noexcept;

Changes the total after starting.

function

Update

#
void Update( const ETL_UINT64 uCurrent );

Reports progress and redraws if needed.

Redrawing on every call would be expensive in a tight loop, so the bar only redraws when what is on screen would change. Calling it a million times costs a million compares, not a million writes.

function

Advance

#
void Advance( const ETL_UINT64 uDelta = 1 );

Adds uDelta to the progress.

function

Finish

#
void Finish();

Closes the bar and ends the line.

Calling it twice is harmless. The destructor calls it, but an explicit call is better: it picks the moment.

function

Clear

#
void Clear();

Clears the bar from the screen without ending the line.

Used to write a message in the middle of the progress without it sticking to the bar: clear, write, and the next Update redraws.

function

Current

#
ETL_UINT64 Current() const noexcept;

Current progress.

function

Total

#
ETL_UINT64 Total() const noexcept;

The total.

function

IsDrawing

#
bool IsDrawing() const noexcept;

Tells whether the bar is really drawing (there is a terminal).

function

DrawCount

#
ETL_UINT64 DrawCount() const noexcept;

Number of times the bar actually wrote to the stream.

Exists to measure that redrawing is cheap. Without it, "only redraws when it changes" would be a claim with no way to fail.

width.hpp

#include <ethereal/cpp/cli/width.hpp>

Terminal column width of UTF-8 text.

Width of UTF-8 text, including wide CJK and combining marks, from a compact range table with binary search. ASCII is the common case and is resolved with a single compare.

Three numbers are often confused: the bytes of a text (what 'strlen' returns), its characters (code points), and the columns it takes on screen. Only the columns align a table. They differ for almost everything outside ASCII. The ideogram 'ri' has three bytes, one character and two columns. An 'e' with a combining accent has three bytes, two characters and one column. A table aligned with 'strlen' breaks on the first Japanese name, and one aligned by characters breaks on the first combining accent.

ASCII is most of what a command line tool writes. One compare ('byte < 0x80') resolves it, and only what fails that compare pays for the binary search.

When the Text module is built with segmentation ('ETL_TEXT_SEGMENTATION'), these functions use it: the whole of Unicode, by grapheme. An emoji family or a flag is two columns, and BytesForColumns never splits them. Without Text, the compact table is used. Invalid bytes count by maximal subpart (the Unicode recommendation), one column each.

function

CodePointWidth

Ethereal::Cli#
int CodePointWidth( ETL_UINT32 uCodePoint ) noexcept;

Number of columns a code point takes.

uCodePoint
The code point.
0 for combining and control characters, 1 for the common ones, 2 for the wide ones.
function

TextWidth

Ethereal::Cli#
std::size_t TextWidth( const ETL_CHAR * pText, std::size_t uBytes ) noexcept;

Number of columns a UTF-8 text takes.

Invalid bytes count one column each. A partly corrupted text still gives a number, so a bad byte does not misalign a table.

pText
The text. Does not need a null terminator.
uBytes
Number of bytes to read.
The width in columns.
function

TextWidth

Ethereal::Cli#
std::size_t TextWidth( const ETL_CHAR * pText ) noexcept;

Same as TextWidth, for a null terminated text.

function

BytesForColumns

Ethereal::Cli#
std::size_t BytesForColumns( const ETL_CHAR * pText, std::size_t uBytes, std::size_t uColumns, std::size_t * pOutWidth = nullptr ) noexcept;

Number of bytes that fit in uColumns columns, without splitting a character.

Cutting by bytes leaves a truncated sequence in the output. The terminal draws a replacement glyph, or swallows what comes next. It also never cuts between a character and its combining mark, which would leave the accent alone on the next line.

pText
The text.
uBytes
Number of bytes in the text.
uColumns
Columns available.
pOutWidth
Receives the columns actually used. May be null.
Number of bytes that fit.
function

SequenceLength

Ethereal::Cli#
std::size_t SequenceLength( ETL_UINT8 uFirst ) noexcept;

Length of the UTF-8 sequence that starts with this byte.

uFirst
First byte of the sequence.
1 to 4, or 1 when the byte cannot start a sequence.
function

DecodeUtf8

Ethereal::Cli#
std::size_t DecodeUtf8( const ETL_CHAR * pText, std::size_t uBytes, ETL_UINT32 * pOut ) noexcept;

Decodes one code point.

pText
The text.
uBytes
Number of bytes available.
pOut
Receives the code point, 0xFFFD when the bytes are invalid.
Number of bytes consumed.

writer.hpp

#include <ethereal/cpp/cli/writer.hpp>

Buffered terminal output and number formatting of the Cli module.

The spec of this module opens with "Terminal output is where CLI tools go to die. A progress bar that issues a write syscall per update will dominate the runtime of the tool it is measuring." The target is one write syscall per flush.

Measured before this was written: the old path (Write) does 'fwrite' and 'fflush' on every call. On this bench, with the output to '/dev/null', comparing zero, 20000 and 40000 writes, the marginal cost per write was 1112 ns. The same call with the output sent to a function cost 3 ns. That is 370 times, and the difference is a syscall, which costs more than all the work this module does around it.

A progress bar frame is not one write. It moves the cursor, paints, writes the text, restores the color and clears to the end of the line, about ten pieces. At 30 Hz for ten seconds that is a few thousand syscalls in a program that should make three hundred.

The buffer belongs to the caller, for the same reason the line editor allocates nothing: a command line tool that allocates on the output path allocates on the hot path. A convenience constructor with an internal buffer exists for the simple case, not for the hot one.

enum

EBufferMode

Ethereal::Cli#
C++
enum class   EBufferMode : ETL_UINT8
{
    /// @brief  Only when full, or when asked. The cheapest.
    eFull = 0,

    /// @brief  Also at every end of line.
    ///
    /// @details  What an interactive terminal wants: the line shows up when it
    ///            ends, not when the buffer happens to fill.
    ///
    eLine,

    /// @brief  On every write. The old behavior, kept to measure against.
    eNone
};

When the buffer flushes by itself.

class

CWriter

Ethereal::Cli#

Buffered terminal output, one flush per frame.

class CWriter final

See the file header. The target is one syscall per Flush, not one per escape sequence.

constructor

CWriter

#
CWriter( EStream eStream, char * pBuffer, std::size_t uBytes ) noexcept;

Constructor with a buffer from the caller.

eStream
Where to write.
pBuffer
The buffer. Must outlive this object.
uBytes
Size of the buffer.
constructor

CWriter

#
explicit CWriter( EStream eStream = EStream::eOut ) noexcept;

Constructor with the internal 4 KiB buffer. For the simple case.

function

Write

#
void Write( const char * pText, std::size_t uBytes ) noexcept;

Writes raw bytes.

pText
The bytes.
uBytes
Number of bytes.
function

Write

#
void Write( const char * pText ) noexcept;

Writes a null terminated string.

function

WriteChar

#
void WriteChar( char c ) noexcept;

Writes one character.

function

WriteInt

#
void WriteInt( ETL_INT64 iValue ) noexcept;

Writes a signed integer in decimal.

Two digits at a time, from a table. The spec asks that "Integer to decimal uses a two-digit lookup table", and the target is five times faster than 'snprintf'.

function

WriteUInt

#
void WriteUInt( ETL_UINT64 uValue ) noexcept;

Writes an unsigned integer in decimal.

function

WriteHex

#
void WriteHex( ETL_UINT64 uValue, bool bUpper = false ) noexcept;

Writes an integer in hexadecimal, without a prefix.

uValue
The value.
bUpper
true for upper case digits.
function

WriteRepeat

#
void WriteRepeat( char c, std::size_t uCount ) noexcept;

Repeats a character. For progress bars and table padding.

c
The character.
uCount
How many times.
function

WriteLine

#
void WriteLine() noexcept;

Writes an end of line.

function

Flush

#
void Flush() noexcept;

Sends the buffer to the system. One syscall.

function

Pending

#
std::size_t Pending() const noexcept

Number of bytes waiting in the buffer.

function

FlushCount

#
ETL_UINT64 FlushCount() const noexcept

Number of flushes, ever.

The oracle of the spec target. A test that writes a thousand times and flushes once must see one here.

function

BytesWritten

#
ETL_UINT64 BytesWritten() const noexcept

Number of bytes that went through this writer.

function

SetMode

#
void SetMode( const EBufferMode eMode ) noexcept

Sets when the buffer flushes by itself.

function

Mode

#
EBufferMode Mode() const noexcept

When the buffer flushes by itself.

function

Stream

#
EStream Stream() const noexcept

Where this writer writes.

function

FormatUInt

Ethereal::Cli#
std::size_t FormatUInt( ETL_UINT64 uValue, char * pOut ) noexcept;
function

FormatInt

Ethereal::Cli#
std::size_t FormatInt( ETL_INT64 iValue, char * pOut ) noexcept;

Same as FormatUInt, signed.

const

DOUBLE_FORMAT_MAX

Ethereal::Cli#
constexpr std::size_t DOUBLE_FORMAT_MAX = 32u;

Bytes enough for any double, with room to spare.

The worst case is seventeen digits, the sign, the point, the 'e', the exponent sign and three exponent digits. Thirty two is enough, and the round number avoids a mental sum someone would get wrong.

enum

EFloatFormat

Ethereal::Cli#
C++
enum class   EFloatFormat : ETL_UINT8
{
    /// @brief  Picks fixed or scientific by the exponent.
    ///
    /// @details  The rule of %g: scientific when the decimal exponent is out
    ///            of [-4, 17). It gives the shortest text for the numbers people
    ///            write.
    ///
    eShortest = 0,

    /// @brief  Always fixed: 0.0001 and never 1e-04.
    eFixed,

    /// @brief  Always scientific: 1e-04 and never 0.0001.
    eScientific
};

How to write the number.

function

FormatDouble

Ethereal::Cli#
std::size_t FormatDouble( double dValue, char * pOut, EFloatFormat eFormat = EFloatFormat::eShortest ) noexcept;

Writes dValue at the start of pOut.

Does not write a terminator. A caller that wants one puts it at the returned offset, which is why DOUBLE_FORMAT_MAX has room.

The three non numbers are written in full and in lower case: nan, inf and -inf. Negative zero is written as -0, because it is a distinct value and hiding it would hide where it came from.

dValue
The value.
pOut
Needs DOUBLE_FORMAT_MAX bytes.
eFormat
How to write the number.
Number of bytes written.
function

FormatFixed

Ethereal::Cli#
std::size_t FormatFixed( double dValue, ETL_UINT32 uDecimals, char * pOut ) noexcept;

Like FormatDouble, with a fixed number of digits after the point.

This is not the shortest representation and does not try to be. It is what a column of numbers needs, where alignment matters. Rounds to nearest, ties to even, the same rule as the processor, so a program does not have two different roundings.

dValue
The value.
uDecimals
Digits after the point. Up to seventeen, above that it is clamped.
pOut
Needs DOUBLE_FORMAT_MAX bytes.
Number of bytes written.