RepositoryC++
MA

magiblot/tvision

A modern port of Turbo Vision 2.0, the classical framework for text-based user interfaces. Now cross-platform and with Unicode support.

3.2kstars
240forks
43issues
7views

Featured achievements

The project's latest awards

1
TINIX TRENDING·Topic: turbo-vision

#1 Repository of the week

1
TINIX TRENDING·Topic: utf-8

#1 Repository of the week

1
TINIX TRENDING·Topic: borland-cpp

#1 Repository of the week

Turbo Vision

A modern port of Turbo Vision 2.0, the classical framework for text-based user interfaces. Now cross-platform and with Unicode support.

tvedit in Konsole

I started this as a personal project at the very end of 2018. By May 2020 I considered it was very close to feature parity with the original, and decided to make it open.

The original goals of this project were:

  • Making Turbo Vision work on Linux by altering the legacy codebase as little as possible.
  • Keeping it functional on DOS/Windows.
  • Being as compatible as possible at the source code level with old Turbo Vision applications. This led me to implement some of the Borland C++ RTL functions, as explained below.

At one point I considered I had done enough, and that any attempts at revamping the library and overcoming its original limitations would require either extending the API or breaking backward compatibility, and that a major rewrite would be most likely necessary.

However, between July and August 2020 I found the way to integrate full-fledged Unicode support into the existing architecture, wrote the Turbo text editor and also made the new features available on Windows. So I am confident that Turbo Vision can now meet many of the expectations of modern users and programmers.

The original location of this project is https://github.com/magiblot/tvision.

Table of contents

Unicode support

The Turbo Vision API has been extended to allow receiving Unicode input and displaying Unicode text. The supported encoding is UTF-8, for a number of reasons:

  • It is compatible with already present data types (char *), so it does not require intrusive modifications to existing code.
  • It is the same encoding used for terminal I/O, so redundant conversions are avoided.
  • Conformance to the UTF-8 Everywhere Manifesto, which exposes many other advantages.

Note that when built with Borland C++, Turbo Vision does not support Unicode. However, this does not affect the way Turbo Vision applications are written, since the API extensions are designed to allow for encoding-agnostic code.

Reading Unicode input

The traditional way to get text from a key press event is as follows:

// 'ev' is a TEvent, and 'ev.what' equals 'evKeyDown'.
switch (ev.keyDown.keyCode) {
    // Key shortcuts are usually checked first.
    // ...
    default: {
        char c = ev.keyDown.charScan.charCode;
        // ...
    }
}

However, the charScan.charCode field can only hold a single-byte character and therefore it does not support Unicode. For backward compatibility, the charScan.charCode field in key press events still contains code page characters (CP437, unless overriden by the developer).

For Unicode support, two new fields have been introduced in ev.keyDown (which is a struct KeyDownEvent):

  • char text[4], which may contain whatever was read from the terminal: usually a UTF-8 sequence, but possibly any kind of raw data.
  • uchar textLength, which is the number of bytes of data available in text, from 0 to 4.

Note that the text string is not null-terminated. In order not to tamper with the text and textLength fields directly, you may instead use the getText() method which returns a string view.

So, a Unicode character can be retrieved from TEvent in the following way:

switch (ev.keyDown.keyCode) {
    // ...
    default: {
        std::string_view ch = ev.keyDown.getText();
        std::cerr << "Character received: " << ch << std::endl;
    }
}

Let's see it from another perspective. If the user types ñ, a TEvent is generated with the following keyDown struct:

KeyDownEvent {
    union {
        .keyCode = 0xA4,
        .charScan = CharScanType {
            .charCode = 164 ('ñ'), // In CP437
            .scanCode = 0
        }
    },
    .controlKeyState = 0x200 (kbInsState),
    .text = {'\xC3', '\xB1'}, // In UTF-8
    .textLength = 2
}

However, if they type € the following will happen:

KeyDownEvent {
    union {
        .keyCode = 0x0 (kbNoKey), // '€' not part of CP437
        .charScan = CharScanType {
            .charCode = 0,
            .scanCode = 0
        }
    },
    .controlKeyState = 0x200 (kbInsState),
    .text = {'\xE2', '\x82', '\xAC'}, // In UTF-8
    .textLength = 3
}

If a key shortcut is pressed instead, text is empty:

KeyDownEvent {
    union {
        .keyCode = 0xB (kbCtrlK),
        .charScan = CharScanType {
            .charCode = 11 ('♂'),
            .scanCode = 0
        }
    },
    .controlKeyState = 0x20C (kbCtrlShift | kbInsState),
    .text = {},
    .textLength = 0
}

So, in short: views designed without Unicode input in mind will continue to work exactly as they did before, and views which want to be Unicode-aware will have no issues in being so.

Displaying Unicode text

The original design of Turbo Vision uses 16 bits to represent a screen cell—8 bit for a character and 8 bit for BIOS color attributes.

A new TScreenCell type is defined in <tvision/scrncell.h> which is capable of holding a limited number of UTF-8 codepoints in addition to extended attributes (bold, underline, italic...). However, you should not write text into a TScreenCell directly but make use of Unicode-aware API functions instead.

Text display rules

Turbo Vision API functions that handle text display behave as follows:

  • ASCII control characters are handled as code page characters. For example, '\x09' is displayed as ○ instead of a tabulator, and 0x7F as ⌂. Null characters are displayed as spaces.
  • Other valid UTF-8 character sequences are displayed as-is. Double-width and combining characters are handled specially; see below.
  • Characters that do not form a valid UTF-8 sequence are also handled as code page characters. For example, a stray '\xF0' is displayed as ≡, even if it is surrounded by valid UTF-8 sequences. So, the string "╔[\xFE]╗" is displayed as ╔[■]╗.

This means that extended ASCII characters can be mixed with UTF-8, which is useful for backward-compatibility. If you rely on this behaviour, though, you may get unexpected results: for instance, "\xC4\xBF" is a valid UTF-8 sequence and is displayed as Ŀ instead of ─┐.

Another aspect of Unicode support is the existence of double-width characters and combining characters. This conflicts with Turbo Vision's original assumption that the screen is a grid of cells occupied by a single character each. Nevertheless, these cases are handled in the following way:

  • Double-width characters can be drawn anywhere on the screen and nothing bad happens if they overlap partially with other characters.

  • Zero-width characters overlay the previous character. For example, the sequence में consists of the single-width character म and the combining characters े and ं. In this case, three Unicode codepoints are fit into the same cell.

    The ZERO WIDTH JOINER (U+200D) is always omitted, as it complicates things too much. For example, it can turn a string like "👩👦" (4 columns wide) into "👩‍👦" (2 columns wide). Not all terminal emulators respect the ZWJ, so, in order to produce predictable results, Turbo Vision will print both "👩👦" and "👩‍👦" as 👩👦.

  • No notable graphical glitches will occur as long as your terminal emulator respects character widths as measured by wcwidth.

Here is an example of such characters in the Turbo text editor: Wide character display

Unicode-aware API functions

The usual way of writing to the screen is by using TDrawBuffer. Some of its methods have been updated to support the new features:

void TDrawBuffer::moveChar(ushort indent, char c, TColorAttr attr, ushort count);
void TDrawBuffer::putChar(ushort indent, char c);

c is handled as a code page character.

ushort TDrawBuffer::moveStr( ushort indent, TStringView str, TColorAttr attr,
                             ushort maxStrWidth = USHRT_MAX, ushort strIndent = 0 ); // New
ushort TDrawBuffer::moveCStr( ushort indent, TStringView str, TColorAttr attr, 
                              ushort maxStrWidth = USHRT_MAX, ushort strIndent = 0 ); // New

str is handled according to the rules exposed previously, and there are two new parameters:

  • maxStrWidth specifies the maximum amount of text that should be copied from str, measured in columns (not in bytes).
  • strIndent specifies the initial position in str where to copy from, measured in columns (not in bytes). This is useful for horizontal scrolling. If strIndent points to the middle of a double-width character, a space will be copied instead of the right half of the double-width character, since it is not possible to do such a thing.

The return value is the width (in columns) of the copied text.

void TDrawBuffer::moveBuf(ushort indent, const void *source, TColorAttr attr, ushort count);

This function is actually the same as moveStr. However, it exists because it used to be the only TDrawBuffer function that could be used with non-null-terminated strings before the introduction of TStringView.

There are other useful Unicode-aware functions:

int cstrlen(TStringView s);

Returns the displayed length of s according to the aforementioned rules, discarding ~ characters.

int strwidth(TStringView s); // New

Returns the displayed length of s.

On Borland C++, these methods assume a single-byte encoding and all characters being one column wide. This makes it possible to write encoding-agnostic draw() and handleEvent() methods that work on both platforms without a single #ifdef.

The functions above are implemented using the functions from the TText namespace, another API extension. You will have to use them directly if you want to fill TScreenCell objects with text manually or to use a custom code page translation table. To give an example, below are some of the TText functions. You can find all of them with complete descriptions in <tvision/ttext.h>.

size_t TText::next(TStringView text);
size_t TText::prev(TStringView text, size_t index);
void TText::drawChar(TSpan<TScreenCell> cells, char c);
size_t TText::drawStr(TSpan<TScreenCell> cells, size_t indent, TStringView text, int textIndent);
bool TText::drawOne(TSpan<TScreenCell> cells, size_t &i, TStringView text, size_t &j);

For drawing TScreenCell buffers into a view, the following methods are available:

void TView::writeBuf(short x, short y, short w, short h, const TScreenCell *b); // New
void TView::writeLine(short x, short y, short w, short h, const TScreenCell *b); // New

Example: Unicode text in menus and status bars

It's as simple as it can be. Let's modify hello.cpp as follows:

TMenuBar *THelloApp::initMenuBar( TRect r )
{
    r.b.y = r.a.y+1;
    return new TMenuBar( r,
      *new TSubMenu( "~Ñ~ello", kbAltH ) +
        *new TMenuItem( "階~毎~料入報最...", GreetThemCmd, kbAltG ) +
        *new TMenuItem( "五劫~の~擦り切れ", cmYes, kbNoKey, hcNoContext ) +
        *new TMenuItem( "העברית ~א~ינטרנט", cmNo, kbNoKey, hcNoContext ) +
         newLine() +
        *new TMenuItem( "E~x~it", cmQuit, cmQuit, hcNoContext, "Alt-X" )
        );
}

TStatusLine *THelloApp::initStatusLine( TRect r )
{
    r.a.y = r.b.y-1;
    return new TStatusLine( r,
        *new TStatusDef( 0, 0xFFFF ) +
            *new TStatusItem( "~Alt-Ç~ Exit", kbAltX, cmQuit ) +
            *new TStatusItem( 0, kbF10, cmMenu )
            );
}

Here is what it looks like:

Unicode Hello

Example: writing Unicode-aware draw() methods

The following is an excerpt from an old implementation of TFileViewer::draw() (part of the tvdemo application), which does not draw Unicode text properly:

if (delta.y + i < fileLines->getCount()) {
    char s[maxLineLength+1];
    p = (char *)(fileLines->at(delta.y+i));
    if (p == 0 || strlen(p) < delta.x)
        s[0] = EOS;
    else
        strnzcpy(s, p+delta.x, maxLineLength+1);
    b.moveStr(0, s, c);
}
writeBuf( 0, i, size.x, 1, b );

All it does is move part of a string in fileLines into b, which is a TDrawBuffer. delta is a TPoint representing the scroll offset in the text view, and i is the index of the visible line being processed. c is the text color. A few issues are present:

  • TDrawBuffer::moveStr takes a null-terminated string. In order to pass a substring of the current line, a copy is made into the array s, at the risk of a buffer overrun. The case where the line does not fit into s is not handled, so at most maxLineLenght characters will be copied. What's more, a multibyte character near position maxLineLength could be copied incompletely and be displayed as garbage.
  • delta.x is the first visible column. With multibyte-encoded text, it is no longer true that such column begins at position delta.x in the string.

Below is a corrected version of the code above that handles Unicode properly:

if (delta.y + i < fileLines->getCount()) {
    p = (char *)(fileLines->at(delta.y+i));
    if (p)
        b.moveStr(0, p, c, size.x, delta.x);
}
writeBuf( 0, i, size.x, 1, b );

The overload of moveStr used here is TDrawBuffer::moveStr(ushort indent, TStringView str, TColorAttr attr, ushort maxStrWidth, ushort strIndent = 0). This function not only provides Unicode support, but also helps us write cleaner code and overcome some of the limitations previously present:

  • The intermediary copy is avoided, so the displayed text is not limited to maxLineLength bytes.
  • moveStr takes care of printing the string starting at column delta.x. We do not even need to worry about how many bytes correspond to delta.x columns.
  • Similarly, moveStr is instructed to copy at most size.x columns of text without us having to care about how many bytes that is nor dealing with edge cases. The code is written in an encoding-agnostic way and will work whether multibyte characters are being considered or not.
  • In case you hadn't realized yet, the intermediary copy in the previous version was completely unnecessary. It would have been necessary only if we had needed to trim the end of the line, but that was not the case: text occupies all of the view's width, and TView::writeBuf already takes care of not writing beyond it. Yet it is interesting to see how an unnecessary step not only was limiting functionality but also was prone to bugs.

Unicode support across standard views

Support for creating Unicode-aware views is in place, and most views in the original Turbo Vision library have been adapted to handle Unicode.

The following views can display Unicode text properly. Some of them also do horizontal scrolling or word wrapping; all of that should work fine.

The following views can, in addition, process Unicode user input:

  • TInputLine (81066ee5, cb489d42).
  • TEditor (702114dc). Instances are in UTF-8 mode by default. You may switch back to single-byte mode by pressing Ctrl+P. This only changes how the document is displayed and the encoding of user input; it does not alter the document. This class is used in the tvedit application; you may test it there.
  • Shortcuts in TMenuView (64e60064).

Views not in this list may not have needed any corrections or I simply forgot to fix them. Please submit an issue if you notice anything not working as expected.

Use cases where Unicode is not supported (not an exhaustive list):

  • Highlighted key shortcuts, in general (e.g. TStatusLine, TButton...).

Clipboard interaction

Originally, Turbo Vision offered no integration with the system clipboard, since there was no such thing on MS-DOS.

It did offer the possibility of using an instance of TEditor as an internal clipboard, via the TEditor::clipboard static member. However, TEditor was the only class able to interact with this clipboard. It was not possible to use it with TInputLine, for example.

Turbo Vision applications are now most likely to be ran in a graphical environment through a terminal emulator. In this context, it would be desirable to interact with the system clipboard in the same way as a regular GUI application would do.

To deal with this, a new class TClipboard has been added which allows accessing the system clipboard. If the system clipboard is not accessible, it will instead use an internal clipboard.

Enabling clipboard support

On Windows (including WSL) and macOS, clipboard integration is supported out-of-the-box.

On Unix systems other than macOS, it is necessary to install some external dependencies. See runtime requirements.

For applications running remotely (e.g. through SSH), clipboard integration is supported in the following situations:

  • When X11 forwarding over SSH is enabled (ssh -X).
  • When your terminal emulator supports far2l's terminal extensions (far2l, putty4far2l).
  • When your terminal emulator supports OSC 52 escape codes:
    • alacritty, kitty, foot.
    • xterm, if the allowWindowOps option is enabled.
    • A few other terminals only support the Copy action.

Additionally, it is always possible to paste text using your terminal emulator's own Paste command (usually Ctrl+Shift+V or Cmd+V).

API usage

To use the TClipboard class, define the macro Uses_TClipboard before including <tvision/tv.h>.

Writing to the clipboard

static void TClipboard::setText(TStringView text);

Sets the contents of the system clipboard to text. If the system clipboard is not accessible, an internal clipboard is used instead.

Reading the clipboard

static void TClipboard::requestText();

Requests the contents of the system clipboard asynchronously, which will be later received in the form of regular evKeyDown events. If the system clipboard is not accessible, an internal clipboard is used instead.

Processing Paste events

A Turbo Vision application may receive a Paste event for two different reasons:

  • Because TClipboard::requestText() was invoked.
  • Because the user pasted text through the terminal.

In both cases the application will receive the clipboard contents in the form of regular evKeyDown events. These events will have a kbPaste flag in keyDown.controlKeyState so that they can be distinguished from regular key presses.

Therefore, if your view can handle user input it will also handle Paste events by default. However, if the user pastes 5000 characters, the application will behave as if the user pressed the keyboard 5000 times. This involves drawing views, completing the event loop, updating the screen..., which is far from optimal if your view is a text editing component, for example.

For the purpose of dealing with this situation, another function has been added:

bool TView::textEvent(TEvent &event, TSpan<char> dest, size_t &length);

textEvent() attempts to read text from consecutive evKeyDown events and stores it in a user-provided buffer dest. It returns false when no more events are available or if a non-text event is found, in which case this event is saved with putEvent() so that it can be processed in the next iteration of the event loop. Finally, it calls clearEvent(event).

The exact number of bytes read is stored in the output parameter length, which will never be larger than dest.size().

Here is an example on how to use it:

// 'ev' is a TEvent, and 'ev.what' equals 'evKeyDown'.
// If we received text from the clipboard...
if (ev.keyDown.controlKeyState & kbPaste) {
    char buf[512];
    size_t length;
    // Fill 'buf' with the text in 'ev' and in
    // upcoming events from the input queue.
    while (textEvent(ev, buf, length)) {
        // Process 'length' bytes of text in 'buf'...
    }
}

Enabling application-wide clipboard usage

The standard views TEditor and TInputLine react to the cmCut, cmCopy and cmPaste commands. However, your application first has to be set up to use these commands. For example:

TStatusLine *TMyApplication::initStatusLine( TRect r )
{
    r.a.y = r.b.y - 1;
    return new TStatusLine( r,
        *new TStatusDef( 0, 0xFFFF ) +
            // ...
            *new TStatusItem( 0, kbCtrlX, cmCut ) +
            *new TStatusItem( 0, kbCtrlC, cmCopy ) +
            *new TStatusItem( 0, kbCtrlV, cmPaste ) +
            // ...
    );
}

TEditor and TInputLine automatically enable and disable these commands. For example, if a TEditor or TInputLine is focused, the cmPaste command will be enabled. If there is selected text, the cmCut and cmCopy commands will also be enabled. If no TEditor or TInputLines are focused, then these commands will be disabled.

Extended color support

The Turbo Vision API has been extended to allow more than the original 16 colors.

Colors can be specified using any of the following formats:

  • BIOS color attributes (4-bit), the format used originally on MS-DOS.
  • RGB (24-bit).
  • xterm-256color palette indices (8-bit).
  • The terminal default color. This is the color used by terminal emulators when no display attributes (bold, color...) are enabled (usually white for foreground and black for background).

Although Turbo Vision applications are likely to be ran in a terminal emulator, the API makes no assumptions about the display device. That is to say, the complexity of dealing with terminal emulators is hidden from the programmer and managed by Turbo Vision itself.

For example: color support varies among terminals. If the programmer uses a color format not supported by the terminal emulator, Turbo Vision will quantize it to what the terminal can display. The following images represent the quantization of a 24-bit RGB picture to 256, 16 and 8 color palettes:

24-bit color (original)256 colors
mpv-shot0005mpv-shot0002
16 colors8 colors (bold as bright)
mpv-shot0003mpv-shot0004

Extended color support basically comes down to the following:

  • Turbo Vision has originally used BIOS color attributes stored in an uchar. ushort is used to represent attribute pairs. This is still the case when using Borland C++.
  • In modern platforms a new type TColorAttr has been added which replaces uchar. It specifies a foreground and background color and a style. Colors can be specified in different formats (BIOS color attributes, 24-bit RGB...). Styles are the typical ones (bold, italic, underline...). There's also TAttrPair, which replaces ushort.
  • TDrawBuffer's methods, which used to take uchar or ushort parameters to specify color attributes, now take TColorAttr or TAttrPair.
  • TPalette, which used to contain an array of uchar, now contains an array of TColorAttr. The TView::mapColor method also returns TColorAttr instead of uchar.
  • TView::mapColor has been made virtual so that the palette system can be bypassed without having to rewrite any draw methods.
  • TColorAttr and TAttrPair can be initialized with and casted into uchar and ushort in a way such that legacy code still compiles out-of-the-box without any change in functionality.

Below is a more detailed explanation aimed at developers.

Data Types

In the first place we will explain the data types the programmer needs to know in order to take advantage of the extended color support. To get access to them, you may have to define the macro Uses_TColorAttr before including <tvision/tv.h>.

All the types described in this section are trivial. This means that they can be memset'd and memcpy'd. But variables of these types are uninitialized when declared without initializer, just like primitive types. So make sure you don't manipulate them before initializing them.

Color format types

Several types are defined which represent different color formats. The reason why these types exist is to allow distinguishing color formats using the type system. Some of them also have public fields which make it easier to manipulate individual bits.

  • TColorBIOS represents a BIOS color. It allows accessing the r, g, b and bright bits individually, and can be casted implicitly into/from uint8_t.

    The memory layout is:

    • Bit 0: Blue (field b).
    • Bit 1: Green (field g).
    • Bit 2: Red (field r).
    • Bit 3: Bright (field bright).
    • Bits 4-7: unused.

    Examples of TColorBIOS usage:

    TColorBIOS bios = 0x4;  // 0x4: red.
    bios.bright = 1;        // 0xC: light red.
    bios.b = bios.r;        // 0xD: light magenta.
    bios = bios ^ 3;        // 0xE: yellow.
    uint8_t c = bios;       // Implicit conversion to integer types.
    

    In terminal emulators, BIOS colors are mapped to the basic 16 ANSI colors.

  • TColorRGB represents a color in 24-bit RGB. It allows accessing the r, g and b bit fields individually, and can be casted implicitly into/from uint32_t.

    The memory layout is:

    • Bits 0-7: Blue (field b).
    • Bits 8-15: Green (field g).
    • Bits 16-23: Red (field r).
    • Bits 24-31: unused.

    Examples of TColorRGB usage:

    TColorRGB rgb = 0x9370DB;   // 0xRRGGBB.
    rgb = {0x93, 0x70, 0xDB};   // {R, G, B}.
    rgb = rgb ^ 0xFFFFFF;       // Negated.
    rgb.g = rgb.r & 0x88;       // Access to individual components.
    uint32_t c = rgb;           // Implicit conversion to integer types.
    
  • TColorXTerm represents an index into the xterm-256color color palette. It can be casted into and from uint8_t.

TColorDesired

TColorDesired represents a color which the programmer intends to show on screen, encoded in any of the supported color types.

A TColorDesired can be initialized in the following ways:

  • As a BIOS color: with a char literal or a TColorBIOS object:

    TColorDesired bios1 = '\xF';
    TColorDesired bios2 = TColorBIOS(0xF);
    
  • As a RGB color: with an int literal or a TColorRGB object:

    TColorDesired rgb1 = 0xFF7700; // 0xRRGGBB.
    TColorDesired rgb2 = TColorRGB(0xFF, 0x77, 0x00); // {R, G, B}.
    TColorDesired rgb3 = TColorRGB(0xFF7700); // 0xRRGGBB.
    
  • As an XTerm palette index: with a TColorXTerm object.

  • As the terminal default color: through zero-initialization:

    TColorDesired def1 {};
    // Or with 'memset':
    TColorDesired def2;
    memset(&def2, 0, sizeof(def2));
    

TColorDesired has methods to query the contained color, but you will usually not need to use them. See the struct definition in <tvision/colors.h> for more information.

Trivia: the name is inspired by Scintilla's ColourDesired.

TColorAttr

TColorAttr describes the color attributes of a screen cell. This is the type you are most likely to interact with if you intend to change the colors in a view.

A TColorAttr is composed of:

  • A foreground color, of type TColorDesired.

  • A background color, of type TColorDesired.

  • A style bitmask containing a combination of the following flags:

    • slBold.
    • slItalic.
    • slUnderline.
    • slBlink.
    • slReverse.
    • slStrike.

    These flags are based on the basic display attributes selectable through ANSI escape codes. The results may vary between terminal emulators. slReverse is probably the least reliable of them: prefer using the TColorAttr reverseAttribute(TColorAttr attr) free function over setting this flag.

The most straight-forward way to create a TColorAttr is by means of the TColorAttr(TColorDesired fg, TColorDesired bg, ushort style=0) and TColorAttr(int bios) constructors:

// Foreground: RGB 0x892312
// Background: RGB 0x7F00BB
// Style: Normal.
TColorAttr a1 = {TColorRGB(0x89, 0x23, 0x12), TColorRGB(0x7F, 0x00, 0xBB)};

// Foreground: BIOS 0x7.
// Background: RGB 0x7F00BB.
// Style: Bold, Italic.
TColorAttr a2 = {'\x7', 0x7F00BB, slBold | slItalic};

// Foreground: Terminal default.
// Background: BIOS 0xF.
// Style: Normal.
TColorAttr a3 = {{}, TColorBIOS(0xF)};

// Foreground: Terminal default.
// Background: Terminal default.
// Style: Normal.
TColorAttr a4 = {};

// Foreground: BIOS 0x0
// Background: BIOS 0x7
// Style: Normal
TColorAttr a5 = 0x70;

The fields of a TColorAttr can be accessed with the following free functions:

TColorDesired getFore(const TColorAttr &attr);
TColorDesired getBack(const TColorAttr &attr);
ushort getStyle(const TColorAttr &attr);
void setFore(TColorAttr &attr, TColorDesired fg);
void setBack(TColorAttr &attr, TColorDesired bg);
void setStyle(TColorAttr &attr, ushort style);

TAttrPair

TAttrPair is a pair of TColorAttr, used by some API functions to pass two attributes at once.

You may initialize a TAttrPair with the TAttrPair(const TColorAttrs &lo, const TColorAttrs &hi) constructor:

TColorAttr cNormal = {0x234983, 0x267232};
TColorAttr cHigh = {0x309283, 0x127844};
TAttrPair attrs = {cNormal, cHigh};
TDrawBuffer b;
b.moveCStr(0, "Normal text, ~Highlighted text~", attrs);

The attributes can be accessed with the [0] and [1] subindices:

TColorAttr lo = {0x892343, 0x271274};
TColorAttr hi = '\x93';
TAttrPair attrs = {lo, hi};
assert(lo == attrs[0]);
assert(hi == attrs[1]);

Changing the appearance of a TView

Views are commonly drawn by means of a TDrawBuffer. Most TDrawBuffer member functions take color attributes by parameter. For example:

ushort TDrawBuffer::moveStr(ushort indent, TStringView str, TColorAttr attr, ushort maxStrWidth, ushort strIndent);
ushort TDrawBuffer::moveCStr(ushort indent, TStringView str, TAttrPair attrs, ushort maxStrWidth, ushort strIndent);
void TDrawBuffer::putAttribute(ushort indent, TColorAttr attr);

However, the views provided with Turbo Vision usually store their color information in palettes. A view's palette can be queried with the following member functions:

TColorAttr TView::mapColor(uchar index);
TAttrPair TView::getColor(ushort indices);
  • mapColor looks up a single color attribute in the view's palette, given an index into the palette. Remember that the palette indices for each view class can be found in the Turbo Vision headers. For example, <tvision/views.h> says the following about TScrollBar:

    /* ---------------------------------------------------------------------- */
    /*      class TScrollBar                                                  */
    /*                                                                        */
    /*      Palette layout                                                    */
    /*        1 = Page areas                                                  */
    /*        2 = Arrows                                                      */
    /*        3 = Indicator                                                   */
    /* ---------------------------------------------------------------------- */
    
  • getColor is a helper function that allows querying two cell attributes at once. Each byte in the indices parameter contains an index into the palette. The TAttrPair result contains the two cell attributes.

    For example, the following can be found in the draw method of TMenuBar:

    TAttrPair cNormal = getColor(0x0301);
    TAttrPair cSelect = getColor(0x0604);
    

    Which would be equivalent to this:

    TAttrPair cNormal = {mapColor(1), mapColor(3)};
    TAttrPair cSelect = {mapColor(4), mapColor(6)};
    

As an API extension, the mapColor method has been made virtual. This makes it possible to override Turbo Vision's hierarchical palette system with a custom solution without having to rewrite the draw() method.

So, in general, there are three ways to use extended colors in views:

  1. By returning extended color attributes from an overridden mapColor method:
// The 'TMyScrollBar' class inherits from 'TScrollBar' and overrides 'TView::mapColor'.
TColorAttr TMyScrollBar::mapColor(uchar index)
{
    // In this example the values are hardcoded,
    // but they could be stored elsewhere if desired.
    switch (index)
    {
        case 1:     return {0x492983, 0x826124}; // Page areas.
        case 2:     return {0x438939, 0x091297}; // Arrows.
        case 3:     return {0x123783, 0x329812}; // Indicator.
        default:    return errorAttr;
    }
}
  1. By providing extended color attributes directly to TDrawBuffer methods, if the palette system is not being used. For example:

    // The 'TMyView' class inherits from 'TView' and overrides 'TView::draw'.
    void TMyView::draw()
    {
        TDrawBuffer b;
        TColorAttr color {0x1F1C1B, 0xFAFAFA, slBold};
        b.moveStr(0, "This is bold black text over a white background", color);
        /* ... */
    }
    
  2. By modifying the palettes. There are two ways to do this:

    1. By modifying the application palette after it has been built. Note that the palette elements are TColorAttr. For example:
    void updateAppPalette()
    {
        TPalette &pal = TProgram::application->getPalete();
        pal[1] = {0x762892, 0x828712};              // TBackground.
        pal[2] = {0x874832, 0x249838, slBold};      // TMenuView normal text.
        pal[3] = {{}, {}, slItalic | slUnderline};  // TMenuView disabled text.
        /* ... */
    }
    
    1. By using extended color attributes in the application palette definition:
    static const TColorAttr cpMyApp[] =
    {
        {0x762892, 0x828712},               // TBackground.
        {0x874832, 0x249838, slBold},       // TMenuView normal text.
        {{}, {}, slItalic | slUnderline},   // TMenuView disabled text.
        /* ... */
    };
    
    // The 'TMyApp' class inherits from 'TApplication' and overrides 'TView::getPalette'.
    TPalette &TMyApp::getPalette() const
    {
        static TPalette palette(cpMyApp);
        return palette;
    }
    

Display capabilities

TScreen::screenMode exposes some information about the display's color support:

  • If (TScreen::screenMode & 0xFF) == TDisplay::smMono, the display is monocolor (only relevant in DOS).
  • If (TScreen::screenMode & 0xFF) == TDisplay::smBW80, the display is grayscale (only relevant in DOS).
  • If (TScreen::screenMode & 0xFF) == TDisplay::smCO80, the display supports at least 16 colors.
    • If TScreen::screenMode & TDisplay::smColor256, the display supports at least 256 colors.
    • If TScreen::screenMode & TDisplay::smColorHigh, the display supports even more colors (e.g. 24-bit color). TDisplay::smColor256 is also set in this case.

Backward-compatibility of color types

The types defined previously represent concepts that are also important when developing for Borland C++:

ConceptLayout in Borland C++Layout in modern platforms
Color Attributeuchar. A BIOS color attribute.struct TColorAttr.
ColorA 4-bit number.struct TColorDesired.
Attribute Pairushort. An attribute in each byte.struct TAttrPair.

One of this project's key principles is that the API should be used in the same way both in Borland C++ and modern platforms, that is to say, without the need for #ifdefs. Another principle is that legacy code should compile out-of-the-box, and adapting it to the new features should increase complexity as little as possible.

Backward-compatibility is accomplished in the following way:

  • In Borland C++, TColorAttr and TAttrPair are typedef'd to uchar and ushort, respectively.

  • In modern platforms, TColorAttr and TAttrPair can be used in place of uchar and ushort, respectively, since they are able to hold any value that fits into them and can be casted implicitly into/from them.

    A TColorAttr initialized with uchar represents a BIOS color attribute. When converting back to uchar, the following happens:

    • If fg and bg are BIOS colors, and style is cleared, the resulting uchar represents the same BIOS color attribute contained in the TColorAttr (as in the code above).
    • Otherwise, the conversion results in a color attribute that stands out, i.e. white on magenta, meaning that the programmer should consider replacing uchar/ushort with TColorAttr/TAttrPair if they intend to support the extended color attributes.

    The same goes for TAttrPair and ushort, considering that it is composed of two TColorAttr.

A use case of backward-compatibility within Turbo Vision itself is the TPalette class, core of the palette system. In its original design, it used a single data type (uchar) to represent different things: array length, palette indices or color attributes.

The new design simply replaces uchar with TColorAttr. This means there are no changes in the way TPalette is used, yet TPalette is now able to store extended color attributes.

TColorDialog hasn't been remodeled, and thus it can't be used to pick extended color attributes at runtime.

Example: adding extended color support to legacy code

The following pattern of code is common across draw methods of views:

void TMyView::draw()
{
    ushort cFrame, cTitle;
    if (state & sfDragging)
    {
        cFrame = 0x0505;
        cTitle = 0x0005;
    }
    else
    {
        cFrame = 0x0503;
        cTitle = 0x0004;
    }
    cFrame = getColor(cFrame);
    cTitle = getColor(cTitle);
    /* ... */
}

In this case, ushort is used both as a pair of palette indices and as a pair of color attributes. getColor now returns a TAttrPair, so even though this compiles out-of-the-box, extended attributes will be lost in the implicit conversion to ushort.

The code above still works just like it did originally. It's only non-BIOS color attributes that don't produce the expected result. Because of the compatibility between TAttrPair and ushort, the following is enough to enable support for extended color attributes:

-    ushort cFrame, cTitle;
+    TAttrPair cFrame, cTitle;

Nothing prevents you from using different variables for palette indices and color attributes, which is what should actually be done. The point of backward-compatibility is the ability to support new features without changing the program's logic, that is to say, minimizing the risk of increasing code complexity or introducing bugs.

Similar Projects

Discover other similar projects and AI models.

RepositoryRust
sxyazi/yazi

💥 Blazing fast terminal file manager written in Rust, based on async I/O.

43.8k
Dec 1, 2026
RepositoryC++
shadps4-emu/shadPS4

PlayStation 4 emulator for Windows, Linux, macOS and FreeBSD written in C++

34.4k
Nov 28, 2026
RepositoryC++
magiblot/turbo

An experimental text editor based on Scintilla and Turbo Vision.

696
Oct 4, 2026
RepositoryRust
alacritty/alacritty

A cross-platform, OpenGL terminal emulator.

66.4k
Dec 1, 2026
RepositoryJavaScript
GitSquared/edex-ui

A cross-platform, customizable science fiction terminal emulator with advanced monitoring & touchscreen support.

45.0k
Oct 19, 2021
RepositoryC
kingToolbox/WindTerm

A professional cross-platform SSH/Sftp/Shell/Telnet/Tmux/Serial terminal.

32.7k
Mar 11, 2025
Repository
jlevy/the-art-of-command-line

Master the command line, in one page

162.8k
Jun 25, 2024
RepositoryTypeScript
clash-verge-rev/clash-verge-rev

A modern GUI client based on Tauri, designed to run in Windows, macOS and Linux for tailored proxy experience

162.1k
Dec 2, 2026
RepositoryJavaScript
nodejs/node

Node.js JavaScript runtime ✨🐢🚀✨

124.1k
Nov 30, 2026