Before You Start

This book shows how to write software for DVX in C: programs, and the widgets and libraries that extend DVX itself for every program, in C and in DVX BASIC. It explains how DVX runs your code, builds a complete program for each part of the system, and takes your work to a signed package that anyone can install from the package server.

Who This Book Is For

You know C, make, and a Linux shell. You need not know DOS, protected mode, or DJGPP: the book explains what is particular to them, and to DVX, where it matters. It does not teach C.

To write programs in DVX BASIC instead, read the DVX BASIC Programming Guide. DVX BASIC programs reach DVX’s libraries through their include files, and Part III shows how to give BASIC the libraries and widgets you write.

What You Need

  • A Linux PC (x86-64) for building. The SDK’s tools are Linux programs.

  • The DVX SDK (sdk.zip) and the DJGPP cross compiler. Chapter 1 sets them up.

  • DVX, on a DOS PC or in an emulator such as 86Box or DOSBox, to run what you build. Some chapters need more: a packet driver for networking, a serial port and something on its other end for serial links, a sound card (or the PC speaker) for sound, a printer (or a file) for printing.

Every program in this book is a complete project in the SDK’s samples/c folder, ready for make. The book shows the parts it explains; the files hold the rest.

How This Book Is Organized

  • Part I sets up the SDK, builds a first program and explains it line by line, and describes how DVX runs your code: modules, the shell, cooperative tasks, the display, memory, and faults. Read it first.

  • Part II builds programs: windows, widgets and layout, menus, dialog boxes, the keyboard and mouse, drawing, files and settings, timers and tasks, printing, databases, networking, serial links, sound and music, and games. Each chapter stands mostly on its own; read the ones you need.

  • Part III extends DVX: libraries, widgets, help files, resources, and fonts, packaging and publishing, and debugging and performance.

  • The appendices list every setting of the SDK’s build rules (Appendix A) and cover porting existing C code, game libraries included (Appendix B).

This book explains how the parts fit together and shows the calls a program uses most. Its companion, the DVX C Library Reference, describes every function, type, and constant; the chapters here point into it for the full lists.

Conventions

  • Function, type, and file names, and anything you type, are in a monospace font. Longer code is shown in boxes:

    WindowT *win = dvxCreateWindow(ac, "Hello", x, y, w, h, true);
  • The examples are written in DVX’s own style: camelCase names, types that end in T (enumerations in E), braces around every body, // comments, the stdint.h and stdbool.h types, named constants instead of bare numbers, a prototype for every function at the top of the file, and the functions in alphabetical order with appMain last. Your code may follow any style; DVX does not care.

  • A line of C too long for the page is broken where C allows it, and the rest is indented under it. The example files keep such a line whole.

  • Paths on the DOS PC are written as DVX shows them, with backslashes (APPS\LOCAL\HELLO); paths on the Linux PC with slashes (samples/c/hello). DVX also accepts the slash.

  • Keys are shown as F1 and Ctrl+Esc; menu commands as File › Run…​.

Part I: Getting Started

Chapter 1. Setting Up the SDK

A DVX program is not a DOS executable. It is a module: a file of compiled code that DVX loads into its own memory and calls. You build it on a Linux machine with a cross compiler and copy it to the DOS machine, real or emulated, that runs DVX. The DVX SDK holds everything that takes except the compiler: the headers, the build rules, the host tools, and a template for each kind of project. This chapter sets up the SDK and the compiler, makes a project from the program template, builds it, and runs it in DVX. Chapter 2 then explains that program line by line, and Chapter 3 explains how DVX runs it.

1.1. What the SDK Holds

The SDK comes as sdk.zip, which unpacks to a folder named DVX-SDK. A DVX source tree builds the same tree, without docs/, into bin/sdk, and the zip into dist/sdk.zip.

Path Holds

README.TXT

A summary of the SDK: the quick start, the folders, packaging, and the binary interface rule.

newProject.sh

The script that makes a project from a template (Section 1.3).

sdk.mk

The build rules every project’s Makefile includes (Section 1.5).

bin/

The host tools a build runs, all Linux programs: dvxres (resources), dvxhlpc (the help compiler), bascomp (the DVX BASIC compiler), mkfont (fonts), dvxpkg (add-on packages and signing keys), secproxy (the far end of Terminal’s secure link), and dxeGen.sh, which runs DJGPP’s dxe3gen.

include/

The C headers, one folder per library: core (the windowing core), shell (programs and the shell), tasks (cooperative tasks), widget (a folder for each widget), and a folder for each of the other libraries (sql, print, audio, http, and the rest). include/basic holds DVX BASIC declaration files and include/net the socket headers.

templates/

The templates newProject.sh copies.

samples/basic/

Two DVX BASIC programs.

samples/c/

The programs, widgets, and libraries this book builds, each a project ready for make.

docs/

This book, the DVX C Library Reference, and the two DVX BASIC books, as HTML.

secproxy.md

How to run secproxy.

Every header folder except include/basic and include/net is on the compiler’s include path, so a program names a core header by its file name and a widget’s header by its folder and file name: #include "dvxApp.h", #include "label/label.h".

1.2. The Host and the Cross Compiler

DVX runs on DOS, but you build for it on Linux: the tools in bin/ are 64-bit x86 Linux programs. (On DVX itself, SYSTEM\DVXRES.EXE, SYSTEM\DVXHLPC.EXE, SYSTEM\BASCOMP.EXE, and SYSTEM\DVXPKG.EXE are the same tools, installed with the parts of DVX that use them. DVX itself has no C compiler.)

The compiler is DJGPP: GCC, binutils, and a C library for 32-bit protected-mode DOS, here built as a cross compiler that runs on Linux. Its compiler is i586-pc-msdosdjgpp-gcc, and it comes with dxe3gen, which links DJGPP’s loadable modules (DXE3). DVX and the SDK are built with GCC 12.2.0 from release 3.4 of the build-djgpp project (the file djgpp-linux64-gcc1220.tar.bz2); use the same to build your modules as DVX’s own are built.

A project finds the compiler through DJGPP_PREFIX, the directory that holds bin/i586-pc-msdosdjgpp-gcc, taken from the environment or the make command line:

$ mkdir -p /opt/djgpp
$ tar -xjf djgpp-linux64-gcc1220.tar.bz2 -C /opt/djgpp --strip-components=1
$ export DJGPP_PREFIX=/opt/djgpp
$ $DJGPP_PREFIX/bin/i586-pc-msdosdjgpp-gcc --version
i586-pc-msdosdjgpp-gcc (GCC) 12.2.0

Without DJGPP_PREFIX, the SDK looks in toolchains/djgpp two folders above itself. That is where a DVX source tree keeps its toolchain: there ./installToolchain.sh downloads and installs it (with the emulators and other tools the DVX build and its tests use), and nothing needs setting. When make cannot find the compiler, it stops before compiling anything:

DJGPP cross compiler not found: /opt/djgpp/bin/i586-pc-msdosdjgpp-gcc
Set DJGPP_PREFIX to your DJGPP installation: the directory holding
bin/i586-pc-msdosdjgpp-gcc.

1.3. Creating a Project

newProject.sh makes a project from one of the templates:

$ DVX-SDK/newProject.sh KIND NAME [DIR]
KIND Makes

app

A C program (NAME.app). This book’s Part II is about these.

widget

A C widget (NAME.wgt), usable from C programs and DVX BASIC (Chapter 19).

library

A C library of shared functions (NAME.lib), with DVX BASIC declarations (Chapter 18).

game

A C game (NAME.app): a 320 x 200 screen in a window, frame pacing, keyboard and joystick, sound effects, and music (Chapter 17).

basic

A DVX BASIC program (NAME.dbp, built to NAME.app).

basicgame

A DVX BASIC game.

control

A control written in DVX BASIC (built to NAME.wgt), usable from DVX BASIC and C.

NAME becomes a DOS file name, so it is a letter followed by letters and digits, eight characters at most. The script refuses a DOS device name (CON, PRN, AUX, NUL, COM1 to COM9, LPT1 to LPT9), the name of a widget DVX already has (for the widget and control kinds), and a DIR that exists. The project goes in DIR, or else in a new folder named after the project in the current one. Its files are named NAME with the first letter in lower case (camelCase: myApp); DOS and DVX see the name in capitals.

The template’s placeholder names become yours everywhere: file names, identifiers in each of their case styles (tplName, TplName, tplname, TPLNAME), help topic IDs, and a library’s or widget’s ABI stamp. The Makefile names the SDK by a relative path, so the project and the SDK can move together; move one without the other and change SDK_DIR, or give it on the make command line. Make the program this chapter and the next one use:

$ DVX-SDK/newProject.sh app hello
Created a C program project in /home/you/hello

Next steps:
  cd /home/you/hello
  make                                 # builds hello.app and hello.hlp
  make install DVX_DIR=/path/to/dvx    # copies it into a DVX installation
...

1.4. What a Project Holds

An app project holds five files:

File What it is

Makefile

Names the SDK, the kind of module, and its name, and includes sdk.mk.

hello.c

The program.

hello.res

The resources dvxres appends to hello.app: its icon, name, and description (what Program Manager shows), its author, and a text the program reads itself.

icon32.bmp

The program’s 32 x 32 icon.

hello.dhs

The program’s help, which dvxhlpc compiles into hello.hlp.

The Makefile sets three variables and includes the rules:

SDK_DIR ?= ../../../../bin/sdk
KIND     = app
NAME     = hello

include $(SDK_DIR)/sdk.mk

SDK_DIR is the SDK’s folder, relative to the project: the book’s copy of hello points into a DVX source tree, and yours points wherever newProject.sh found the SDK (the ?= lets the command line or the environment override it). KIND is app, widget, library, basic, or control (the game templates are app and basic projects), and NAME is the module’s name. sdk.mk takes every .c file in the folder as the module’s source, NAME.res as its resources, and NAME.dhs (with NAME.bhs for a widget’s DVX BASIC help) as its help source. Add source files by putting them in the folder; there is no list to keep.

1.5. Building

Everything else comes from sdk.mk:

Command Does

make

Builds the module with its resources (hello.app) and the help file (hello.hlp).

make package

Lays out pkg/ exactly as the files go into the DVX folder, and makes hello.dpk, an add-on package of them that DVX’s Software program installs (Chapter 21).

make install DVX_DIR=dir

Packages, then copies pkg/ into the DVX folder dir.

make clean

Removes everything the build made.

These settings can go on the make command line or in the environment; Appendix A lists every one, with the package settings:

Setting Meaning

DJGPP_PREFIX

The DJGPP installation (Section 1.2).

DVX_DIR

The DVX folder make install copies into.

VENDOR

The folder, under APPS, WIDGETS, or LIBS, the module installs into; local unless you set it. Use a short name of your own: it also names your packages (Chapter 21).

CFLAGS

Flags added after the SDK’s own: CFLAGS=-g for debugging information, CFLAGS=-I../mathx for the header of a library you wrote.

NET

1 for a module that uses sockets: it puts include/net (sys/socket.h, netdb.h, and the rest) ahead of the C library’s headers (Chapter 14). It goes in the Makefile, before the include.

A build of hello runs four steps (the include options are shortened here):

$ make
.../i586-pc-msdosdjgpp-gcc -O2 -Wall -Wextra -Werror -march=i486 -mtune=i586 \
    -MMD -MP -I. -I.../include/audio ... -c -o hello.o hello.c
... dxeGen.sh .../dxe3gen -o hello.dxe -U hello.o
mv hello.dxe hello.app
.../dvxres build hello.app hello.res
  icon32 (icon, 3126 bytes)
  ...
Built 5 resource(s) into hello.app
.../dvxhlpc -o hello.hlp hello.dhs
...

The compiler options are fixed by sdk.mk:

Option Why

-O2

Optimized code: DVX’s floor is a 486.

-Wall -Wextra -Werror

Every warning stops the build. Code with a warning does not get as far as DVX.

-march=i486 -mtune=i586

Instructions a 486 has, scheduled for a Pentium. The module runs on any 486DX or later.

-MMD -MP

Dependency files (hello.d), so a changed header rebuilds what includes it.

-I. and the SDK folders

The project’s own folder first, then every SDK header folder (with include/net only for NET = 1).

dxe3gen links the objects into a DXE3 module, DJGPP’s form of a shared library: the code and data, a table of the symbols it exports, and a table of the symbols it uses but does not define. Every function and variable that is not static is exported. The -U option lets the unresolved symbols stand: calls to dvxCreateWindow, wgtInitWindow, malloc, and snprintf are not linked into the module but connected when DVX loads it, to DVX’s own copies (Section 3.2). One consequence matters at once: a misspelled or missing function is not a link error. The build succeeds, and DVX refuses to start the program, naming the symbol. i586-pc-msdosdjgpp-nm hello.o lists what a module needs (the U lines) before you copy it anywhere.

sdk.mk then renames the module to hello.app and has dvxres append the resources listed in hello.res. Resources go after the module’s own content, where the DXE3 loader never looks, and the program and Program Manager read them from the file. dvxres list hello.app (with the dvxres in the SDK’s bin/) shows them. Last, dvxhlpc compiles the help; it stops with the file and line of an error (Chapter 20).

1.6. Installing and Running

make install needs the DVX folder as the build machine sees it:

$ make install DVX_DIR=/path/to/dvx

It copies pkg/ into that folder, so the program lands in APPS\LOCAL\HELLO\ as HELLO.APP and HELLO.HLP (LOCAL is the VENDOR). How the DVX folder gets to be visible from Linux depends on where DVX runs:

  • In an emulator that gives DOS a folder of the host as a drive (DOSBox mounts a folder as drive C:, for example), DVX_DIR is the DVX folder inside it, and the program is there as soon as make install ends.

  • On a PC, or in an emulator whose DOS runs from a disk image, copy the contents of pkg/ into the DVX folder by any means you have, or copy hello.dpk and install it with DVX’s Software program (File › Install from File…​).

Note
sdk.mk writes the folder names in lower case (apps/local/hello). DOS does not mind, but a Linux folder does, so make install copies with dvxpkg copy, which puts the files into the folders already there whatever the case of their names: into an upper-case APPS when the DVX folder has one, never into a second, lower-case apps beside it.

DVX runs on a PC or in an emulator such as 86Box or DOSBox. Start it from its folder at the DOS prompt by typing DVX. Program Manager lists every installed program in its Installed Programs group, so Hello is there with its icon when DVX starts; if DVX was already running when the files arrived, choose View › Refresh (F5) in Program Manager. Double-click the icon, or choose File › Run…​ and type APPS\LOCAL\HELLO\HELLO.APP. To start a program as soon as DVX is up, name it on DVX’s command line:

C:\DVX>DVX /RUN=APPS\LOCAL\HELLO\HELLO.APP
The Hello window, with its welcome line and Greet button, in front of Program Manager
Figure 1. Hello, the program the SDK’s template makes, over Program Manager

DVX keeps a log, DVX.LOG in the user folder: USER\DVX.LOG in the DVX folder, unless the DVXUSER environment variable names another user folder. Each start of DVX begins a new log. Each module it loads, each program it starts or refuses (and why), each crash, and every line a program writes with dvxLog go there (Section 2.7.1). When a program does not start, read the log first.

To change the program, edit it, run make install again, and start it again. Close the running copy first: starting a program that is already running only brings up a message that it is running, unless the program allows several copies (Section 2.2). DVX itself need not restart for a new version of a program. A widget or a library is different: DVX looks for those only as it starts, so install one and restart DVX.

Tip
A widget or library of yours that DVX cannot load at start-up is left out, and DVX says which and why. (Most libraries are loaded only when something first uses them; a library that fails then is noted only in DVX.LOG.) If one keeps DVX from working, start DVX with DVX /SAFE (or hold down Shift while it starts): it then loads no add-on libraries or widgets at all, and uses the safe video mode.

Chapter 2. Your First Program

The program newProject.sh app hello made in Chapter 1 is a complete DVX program: a window with a menu bar, a label, and a button that shows a message read from the program’s own file, with a help file that F1 opens. This chapter reads it from top to bottom. It is the SDK’s program template as newProject.sh makes it, so every C program you start from the template begins with what you learn here. (The book’s copy, in examples/hello, differs only in its greeting and its comments.)

A message box titled Hello saying Hello from DVX!, with the information icon and an OK button, over the Hello window
Figure 2. Hello’s message box, after a click on Greet

hello is a callback-only program. Its appMain builds the window and returns, and from then on DVX calls the program’s functions when something happens to the window, a menu, or the button. The other kind, a program with a main loop of its own, is the subject of Chapter 3.

2.1. Headers and Definitions

#include "dvxApp.h"
#include "dvxDlg.h"
#include "dvxPlat.h"
#include "dvxRes.h"
#include "dvxWgt.h"
#include "dvxWm.h"
#include "shellApp.h"
#include "button/button.h"
#include "label/label.h"

#include <stdint.h>
#include <stdbool.h>
#include <stdlib.h>

#define HELLO_TITLE         "Hello"
#define HELLO_WIN_W         280
#define HELLO_WIN_H         140
#define HELLO_SPACING       6
#define HELLO_RES_GREETING  "greeting"
#define HELLO_ABOUT_TEXT    "Hello\n\nA DVX application."

// Menu command IDs
#define CMD_FILE_EXIT      100
#define CMD_HELP_CONTENTS  200
#define CMD_HELP_ABOUT     201

static DxeAppContextT *sCtx = NULL;
static WindowT        *sWin = NULL;

Each core header covers one part of DVX:

Header For

dvxApp.h

The application layer: AppContextT, windows (dvxCreateWindow, dvxDestroyWindow, dvxFitWindowH), and everything else a program asks of the GUI as a whole. It includes dvxTypes.h, which defines the shared types (WindowT, DisplayT, RectT).

dvxDlg.h

The standard dialog boxes (dvxInfoBox).

dvxPlat.h

The platform layer: files, paths, time, and dvxLog.

dvxRes.h

Resources in module files (dvxResOpen, dvxResRead).

dvxWgt.h

The widget system (WidgetT, wgtInitWindow, wgtPixels).

dvxWm.h

The window manager: menu bars and menus (wmAddMenuBar, wmAddMenuItem).

shellApp.h

Programs and the shell: SHELL_APP_DESCRIPTOR, DxeAppContextT, shellOpenHelpFile.

button/button.h, label/label.h

The Button and Label widgets.

The sizes and texts are named once, with the program’s name as a prefix, and the menu commands get numbers of their own: onMenu receives the number of the item chosen. The two static pointers hold the program’s state between calls. A program’s static data belongs to it alone: each program is a module with its own data, loaded fresh each time it starts.

2.2. The Descriptor

// ============================================================
// Prototypes
// ============================================================

static void    closeWindow(void);
static void    onClose(WindowT *win);
static void    onGreetClick(WidgetT *w);
static void    onMenu(WindowT *win, int32_t menuId);
int32_t        appMain(DxeAppContextT *ctx);

// ============================================================
// App descriptor
// ============================================================

// Records the DVX version this app was built for; DVX refuses to run an
// app built for a different version.
SHELL_APP_DESCRIPTOR(
    .name          = HELLO_TITLE,
    .hasMainLoop   = false,
    .multiInstance = false,
    .stackSize     = SHELL_STACK_DEFAULT,
    .priority      = TS_PRIORITY_NORMAL
);

SHELL_APP_DESCRIPTOR defines the global appDescriptor, an AppDescriptorT, from designated initializers. The shell reads it before it runs any of the program’s code, to know how to start it:

Field Meaning

abiVersion

Filled in by the macro, always first: the binary interface version (DVX_ABI_VERSION) of the headers the program was built with. The shell refuses a program whose number is not its own: “This program was built for a different version of DVX and cannot run.” (Section 3.11).

name

The program’s name, as Task Manager and the shell’s messages show it: at most 63 characters (SHELL_APP_NAME_MAX is 64, with the terminating zero).

hasMainLoop

false for a callback-only program; true for one whose appMain runs a loop on a task of its own (Section 3.4).

multiInstance

false: the program runs once, and starting it again brings up a message that it is running (or hands the new arguments to the running copy, Section 2.3). true: every start is a separate copy, made by loading a copy of the module file, so each one has its own static data.

stackSize

A main-loop program’s stack, in bytes: SHELL_STACK_DEFAULT gives TS_DEFAULT_STACK_SIZE (32 KB). A callback-only program runs on the shell’s stack and ignores it.

priority

A main-loop program’s share of turns, TS_PRIORITY_LOW (0) to TS_PRIORITY_HIGH (10), usually TS_PRIORITY_NORMAL (5); outside that range a main-loop program does not start. A callback-only program ignores it.

The shell finds appDescriptor and appMain by name in the module, so those two are global. Everything else in the file is static: a module exports every name that is not, and a program has nothing else to offer anyone.

2.3. appMain and the Program’s Context

The shell calls int32_t appMain(DxeAppContextT *ctx) once, after loading the module. A callback-only program’s appMain runs on the shell’s own task and must return promptly: DVX does nothing else until it does. Return 0 to go on running. Any other value means the program declined to start: the shell logs it (“Shell: 'Hello' appMain returned -1, unloading”), destroys any window it made, and unloads it.

The context ctx is the program’s own. The shell allocates it, keeps it in place while the program runs, and frees it when the program ends, so the program keeps the pointer (sCtx) for its callbacks:

Member Holds

shellCtx

The shell’s GUI context (AppContextT), shared by every program; every window, drawing, and dialog call takes it.

appId

The program’s ID, as the shell numbers running programs.

appPath

The path of the .app file it was started from, with DOS separators (\).

appDir

The folder that file is in.

userDir

The program’s own folder in the user folder, for its settings and the files it saves: USER\APPS\LOCAL\HELLO for this one. It is not made until the program asks (shellEnsureUserDir; Chapter 10).

args

The arguments the program was started with, empty when there are none.

helpFile

The help file F1 opens: hello.hlp beside hello.app when it is there, and the program may change it.

helpTopic, onHelpQuery

The help topic F1 opens, and a callback the shell calls on F1 so the program can set it first (Chapter 20).

onNewArgs

A callback for a program that runs once: the shell hands it the arguments of a second start instead of refusing (Chapter 11).

2.4. Creating the Window

sCtx = ctx;
AppContextT *ac = ctx->shellCtx;

int32_t winX = (ac->display.width - HELLO_WIN_W) / 2;
int32_t winY = (ac->display.height - HELLO_WIN_H) / 2;

sWin = dvxCreateWindow(ac, HELLO_TITLE, winX, winY, HELLO_WIN_W, HELLO_WIN_H, true);

if (!sWin) {
    return -1;
}

sWin->onClose = onClose;
sWin->onMenu  = onMenu;

ctx->shellCtx is DVX’s one GUI context: the display, the stack of windows, the colors, the fonts, and the input state of the whole system. Read what you need from it; change DVX through its calls, not by writing its fields. ac->display is the screen (DisplayT), and its width and height are the screen’s size in pixels, which depends on the video mode the user chose, so the window is centered by arithmetic rather than placed at fixed coordinates. (dvxCreateWindowCentered does the same arithmetic for you.)

dvxCreateWindow(ac, title, x, y, w, h, resizable) makes a window whose outer frame (title bar and borders included) is at x, y and w by h pixels, and returns it raised and focused. The window belongs to the program that is running when it is made (its appId says which), and that ownership is what ends the program later. The call returns NULL only when memory runs out; appMain then returns -1 and the program does not start.

A WindowT is a structure of state and callbacks. hello sets two:

  • onClose runs when the user asks to close the window: the close gadget, Alt+F4, or Close on the window menu. Exit DVX asks every program to close its windows the same way. The callback decides; it may close the window, ask first, or refuse. A window with no onClose is simply destroyed.

  • onMenu runs with the command ID of a menu item the user chose (or a keyboard shortcut bound to one, Chapter 6).

2.5. The Menu Bar

MenuBarT *menuBar  = wmAddMenuBar(sWin);
MenuT    *fileMenu = menuBar ? wmAddMenu(menuBar, "&File") : NULL;
MenuT    *helpMenu = menuBar ? wmAddMenu(menuBar, "&Help") : NULL;

if (fileMenu) {
    wmAddMenuItem(fileMenu, "E&xit", CMD_FILE_EXIT);
}

if (helpMenu) {
    wmAddMenuItem(helpMenu, "&Contents\tF1", CMD_HELP_CONTENTS);
    wmAddMenuSeparator(helpMenu);
    wmAddMenuItem(helpMenu, "&About " HELLO_TITLE "...", CMD_HELP_ABOUT);
}

wmAddMenuBar gives the window its menu bar, taking a strip of the content area for it. wmAddMenu adds a menu to the bar and wmAddMenuItem an item to a menu, with the command ID onMenu gets; each returns NULL (or does nothing) when memory runs out, hence the tests. The & marks the access key, underlined on the screen: Alt+F opens the File menu, and X then chooses Exit. A menu label is cut to 31 characters, its shortcut text included (MAX_MENU_LABEL is 32, with the terminating zero).

The text after a tab is shown at the right of the item, as its shortcut. It is only text: F1 works because the shell handles it for every program, opening the focused program’s helpFile. Chapter 6 covers check and radio items, submenus, pop-up menus, and real keyboard shortcuts.

2.6. Widgets

WidgetT *root = wgtInitWindow(ac, sWin);

if (!root) {
    closeWindow();
    return -1;
}

root->spacing = wgtPixels(HELLO_SPACING);

WidgetT *label = wgtLabel(root, "Welcome to Hello!");
WidgetT *greet = wgtButton(root, "&Greet");

if (label) {
    label->weight = WGT_WEIGHT_FILL;
}

if (greet) {
    greet->onClick = onGreetClick;
}

wgtInitWindow hands the window’s content area to the widget system and returns the root of its widget tree: a vertical box (VBox) that fills the content area and stacks its children top to bottom. It installs the window callbacks the widgets need (painting, the mouse, the keys, resizing, and focus); it leaves onClose and onMenu alone, but a program that sets any of the others sets them after this call (Chapter 4).

Sizes in the widget system are tagged with their unit: wgtPixels(6) is 6 pixels, wgtChars(n) is n character widths of the font, and wgtPercent(n) is n percent of the parent. root->spacing is the gap between the root’s children.

wgtLabel(parent, text) and wgtButton(parent, text) make a widget as the last child of parent. Each widget type is a module of its own (LABEL.WGT, BUTTON.WGT), loaded when DVX starts, so these are macros from the widget’s header that call through the table of functions the widget registered (wgtGetApi; Chapter 5). The text is copied. The & in &Greet makes Alt+G press the button.

A child’s weight is its share of the space its parent has to spare, and WGT_WEIGHT_FILL is one full share: the label takes any extra height, and the button keeps its natural size. onClick is the callback a button calls when it is pressed, by the mouse, by Alt+G, or by Space or Enter while it has the focus. Widgets belong to their window and are freed with it; a program never frees them itself.

2.7. Fitting the Window and Returning

// Grow the window to fit its contents (the button would be clipped).
dvxFitWindowH(ac, sWin);

dvxLog("hello: started from %s", ctx->appPath);
return 0;

dvxFitWindowH sets the window’s height to what the widget tree needs, keeping its width; dvxFitWindow fits both. Then appMain logs a line and returns 0. The program now consists of its window and three callbacks.

2.7.1. The Log

dvxLog(fmt, ...) formats like printf and appends the result as one line to DVX.LOG in the user folder. It opens and closes the file for every line, so everything logged before a crash is in the file after it, and it is too slow to call on every pass of a loop. A program has no console: standard output is not where its messages go. DVX logs there too, so a program’s lines appear among the shell’s:

Shell: loaded 'Hello' (id=2, mainLoop=no, entry=0x..., desc=0x...)
hello: started from APPS\LOCAL\HELLO\HELLO.APP

The entry address is where appMain was loaded. The shell writes its line before appMain runs, so even a fault inside appMain finds the program in the log (Chapter 22).

2.8. The Callbacks

The button’s callback reads the greeting from the program’s own file:

// Reads a text resource embedded in our own .app file by hello.res.
static void onGreetClick(WidgetT *w) {
    (void)w;

    AppContextT   *ac   = sCtx->shellCtx;
    DvxResHandleT *res  = dvxResOpen(sCtx->appPath);
    uint32_t       size = 0;
    char          *text = res ? (char *)dvxResRead(res, HELLO_RES_GREETING, &size) : NULL;

    dvxLog("hello: greeting resource %s", text ? "found" : "missing");
    dvxInfoBox(ac, HELLO_TITLE, text ? text : "Hello!");
    free(text);
    dvxResClose(res);
}

hello.res listed the resources dvxres appended to hello.app:

icon32      icon    icon32.bmp
name        text    "Hello"
author      text    "Scott Duensing"
description text    "A DVX application"
greeting    text    "Hello from DVX!"

dvxResOpen(path) reads the resource directory at the end of a module file and returns a handle, or NULL when the file has none; sCtx->appPath is the program’s own file. dvxResRead(handle, name, &size) returns a copy of the named resource in memory from malloc, with its size, or NULL when there is no such resource; the caller frees it. A text resource is stored with its terminating zero, so the copy is a C string. dvxResClose frees the handle (and accepts NULL). For text there are shorter ways: dvxResReadText copies into a buffer of yours, and dvxResLoadText (in dvxApp.h) opens, reads, and closes in one call. Resources are the subject of Chapter 20.

dvxInfoBox(ac, title, message) shows a message box with an OK button and returns when the user closes it. While it is open it is the only window in DVX that takes input, but DVX does not stop: the box runs the event loop itself until it closes, so the screen, the other programs, and their timers go on. A callback may therefore wait for an answer, as long as what it waits in runs the event loop (Section 3.6). Chapter 7 covers the other dialog boxes.

The menu callback dispatches on the command ID:

static void onMenu(WindowT *win, int32_t menuId) {
    (void)win;

    switch (menuId) {
        case CMD_FILE_EXIT:
            closeWindow();
            break;

        // The help file, with no particular topic
        case CMD_HELP_CONTENTS:
            shellOpenHelpFile(sCtx->shellCtx, sCtx->helpFile, NULL);
            break;

        case CMD_HELP_ABOUT:
            dvxInfoBox(sCtx->shellCtx, "About " HELLO_TITLE, HELLO_ABOUT_TEXT);
            break;

        default:
            break;
    }
}

The About box is another dvxInfoBox; the C compiler joins "About " HELLO_TITLE into one string.

Help › Contents calls shellOpenHelpFile(ac, helpFile, topicId), which opens DVX’s help viewer on a help file at one of its topics, or brings forward the viewer that is already open and shows it there. A NULL topicId opens the file at its default topic, and a NULL or empty helpFile opens DVX’s own help. The shell hands the viewer the help file as one argument of a command line, in quotes when its path has blanks in it, the way F1 passes it (Section 11.5), so a program installed in a folder with a long name needs nothing more.

Closing the window, from the close gadget or from File › Exit, comes down to one function:

// Destroying the last window of a callback-only app ends the app: the
// shell unloads it on its next pass.
static void closeWindow(void) {
    dvxDestroyWindow(sCtx->shellCtx, sWin);
    sWin = NULL;
}


static void onClose(WindowT *win) {
    (void)win;
    closeWindow();
}

dvxDestroyWindow destroys the window with its widgets, its menu bar, and its content buffer. Called from inside a callback, as here, it hides the window at once and finishes the job when the callback has returned, so the code that called the callback never touches freed memory. sWin = NULL keeps the program from using the pointer afterward.

2.9. How the Program Ends

A callback-only program ends when it has no windows left. On each pass of its main loop the shell looks for programs that have none and ends them: it calls the program’s appShutdown function if the module has one, destroys anything left, releases what DVX tracked for it (timers, hotkeys, fonts it carried, callbacks it registered), and unloads the module. The next start loads it fresh, with its static data as initialized.

void appShutdown(void) is optional. A program that has one exports it like appMain, and the shell calls it when the program ends normally, and also when Task Manager’s End Task or Exit DVX ends it, after its tasks are stopped; it does not run after a fault, for a program that is not responding, or when End Task had to wait for the program’s code to return. Free there what the program allocated, but save nothing important there: save when the user closes the window.

Free what you allocate. DVX counts every allocation a program makes (Task Manager shows the total), but the count is not a collector: a block a program leaves allocated stays allocated until DVX exits (Section 3.9). hello allocates only the resource handle and the resource copy, and frees both before the callback returns.

2.10. The Help File

hello.dhs is the source of the program’s help; make compiles it to hello.hlp, and make install puts it beside hello.app. Because the shell presets helpFile to that file, F1 in any of the program’s windows opens it with no code at all, and Help › Contents opens it through shellOpenHelpFile. The source is plain text with directives (.topic, .h1, .list, .table, and the rest); Chapter 20 describes the format and context help.

2.11. Changing the Program

Make a change, rebuild, and run it again:

  1. Change the greeting in hello.res, for example to greeting text "Hello, world!". A resource change needs no recompiling, but make sees that hello.res changed and builds hello.app again with the new resources.

  2. Change the label’s text in appMain, or the window’s width (HELLO_WIN_W): a C change rebuilds the object first.

  3. Add a menu item: a new CMD_ number, a wmAddMenuItem call, and a case in onMenu that shows a message with dvxInfoBox.

  4. Close the running copy, run make install DVX_DIR=dir, and start Hello again from Program Manager.

If the program does not start, DVX.LOG says why. Every warning stops the build, so what reaches DVX compiled cleanly; what can still go wrong is a name DVX does not have (the message box names it) or a fault (Section 3.10).

Chapter 3. How DVX Runs Your Code

DVX looks like a windowing system, and its calls look like those of other GUI toolkits, but the machine under it is a DOS PC and the rules are DOS rules: one address space, one processor, no threads, and no operating system to step in when a program misbehaves. This chapter explains the model a program lives in: the machine, how modules are loaded and connected, the shell and its event loop, cooperative tasks, the display, memory, faults, and the binary interface. Its example, ticker, is a program with a main loop of its own. The reference’s architecture chapter has the details behind each section (“System Architecture” in the DVX C Library Reference).

3.1. The Machine

DOS runs one program at a time, in 16-bit real mode, in the first megabyte of memory. DVX is that one program. DVX.EXE is a DJGPP program: it switches the processor to 32-bit protected mode through DPMI, the DOS Protected Mode Interface, and runs there with all the computer’s memory in one flat address space. A DPMI host provides the switch; DVX.EXE carries CWSDPMI, which it uses when no other host is running. To your code this is an ordinary 32-bit C environment: int and pointers are 32 bits, malloc reaches the machine’s extended memory, and there are no segments to manage. DOS itself is still underneath: a file read or a call for the time goes through the C library to DOS, which costs a trip to real mode and back.

The floor is a 486DX (a 486 with its math coprocessor) with 4 MB of memory, and everything in DVX is written to be fast enough there. That is why the SDK compiles for the 486 (-march=i486), why drawing goes through hand-written assembly loops, and why the display is built to repaint as little as possible. Write and measure for that machine: a loop that is instant on your build machine may take seconds on it.

There is one address space and no protection inside it. DVX.EXE, every library, every widget, and every running program share it, so a stray pointer in your program can overwrite DVX or another program, and nothing stops it. DVX does catch the faults the processor raises, such as a reference outside its memory or a division by zero (Section 3.10), but a write that lands in valid memory is not a fault.

3.2. Modules and the Loader

DVX.EXE is the only executable. Everything else is a DXE3 module, DJGPP’s form of a shared library, which DVX.EXE loads into its own address space:

Kind Where What it is

.lib

LIBS\<vendor>\<name>

A library: functions that programs, widgets, and other libraries call. The windowing core (LIBDVX.LIB), the task switcher (LIBTASKS.LIB), and the shell (DVXSHELL.LIB) are libraries too.

.wgt

WIDGETS\<vendor>\<name>

A widget: one or more widget types, registered when it loads.

.app

APPS\<vendor>\<name>

A program, loaded when the user starts it.

DVX.EXE holds the code that is DVX’s own platform: the video, keyboard, mouse, timer, and file code behind dvxPlat.h, dvxLog, and its own copy of DJGPP’s C library. It publishes a chosen set of the C library’s functions to modules (strings, memory, stdio files, directories, time, math, setjmp, and others) with some replaced by DVX’s own: malloc, calloc, realloc, strdup, and free become the tracking allocator (Section 3.9); exit, abort, and a failed assert end only the program that calls them, and the functions given to atexit are the program’s (Section 3.10); sleep and usleep let other tasks run while a task waits in them (Section 3.5); system is refused; and signal will not take over the fault signals. A C library function outside that set is a name nothing supplies, and the program that calls it will not load; Appendix B covers what the C library offers a DVX program.

When DVX starts, the loader, DVX.EXE, shows its title screen and scans LIBS and WIDGETS. A module may have a .dep file beside it, a text file naming (one per line, by base name) the modules that must be loaded before it. The loader reads every library’s table of exported names from its file, without loading it, then loads, each after what it needs, the libraries that run code as they load (sound, music, joysticks, the network, Task Manager, and the text-editing helpers, which hook themselves into the shell that way), the shell, and every widget, calling each widget’s wgtRegister. Any other library is loaded the first time something needs one of its names. A control written in DVX BASIC (Chapter 19) is registered by its name only; the DVX BASIC run-time library that runs it loads the first time something uses one. Then the loader calls the shell’s shellMain, which sets the video mode, starts the desktop program (Program Manager), and runs DVX from then on.

A module is linked with its outside references left open (Section 1.5). When DVX opens a module, it connects each one to a definition of the name:

  1. in a module already loaded (LIBDVX.LIB, DVXSHELL.LIB, the widgets, and the libraries);

  2. else among the functions and variables DVX.EXE publishes (when a loaded module and DVX.EXE both have a name, the module’s is used);

  3. else in a library not yet loaded that exports the name, which DVX then loads first, with what its .dep file names.

A name none of them has stops the load: the shell shows “Failed to load file:” with the reason, which for a missing name is “unresolved symbol:” and the name. nm shows a module’s side of this. For hello:

$ i586-pc-msdosdjgpp-nm hello.o
00000000 D _appDescriptor
00000240 T _appMain
         U _dvxCreateWindow
         U _dvxDestroyWindow
         U _dvxFitWindowH
         U _dvxInfoBox
         U _dvxLog
         U _dvxResClose
         U _dvxResOpen
         U _dvxResRead
         U _free
000000f0 t _onClose
00000040 t _onGreetClick
00000140 t _onMenu
...
         U _shellOpenHelpFile
         U _wgtGetApi
         U _wgtInitWindow
         U _wmAddMenu
         U _wmAddMenuBar
         U _wmAddMenuItem
         U _wmAddMenuSeparator

(DJGPP puts an underscore before every C name.) The capital D and T are the two names the module exports; the lower-case t lines are its static functions, which only it can call. Each U is resolved when the program loads: dvxLog and free by DVX.EXE (free as the tracking allocator’s), shellOpenHelpFile by DVXSHELL.LIB, and the rest by LIBDVX.LIB. The Label and Button widgets appear only as wgtGetApi, through which their headers' macros find each widget’s table of functions.

Modules are loaded so that what they export is visible to every module loaded after them; that is how a widget calls LIBDVX.LIB, and how one library calls another. So a program should export only appDescriptor, appMain, and (if it has one) appShutdown, and keep everything else static.

3.3. The Shell and the Two Contexts

The shell, DVXSHELL.LIB, runs DVX after the loader: it owns the GUI, starts and ends programs, runs the main loop, and handles what belongs to no program, such as F1, Ctrl+Esc (Task Manager), and the screen saver. Program Manager is a program like any other; the shell starts it first, and closing it exits DVX.

A program sees two structures:

  • AppContextT is the GUI context, and there is one for all of DVX: the display, the stack of windows, the list of dirty rectangles, the fonts and colors, the input state, and the ID of the program whose code is running. Nearly every window, drawing, and dialog call takes it.

  • DxeAppContextT is the program’s own, one for each running program: its ID, its paths, its arguments, its help file, and shellCtx, the pointer to the one AppContextT (Section 2.3).

AppContextT.currentAppId is the program whose code is running now. DVX sets it before it calls a program’s code (appMain, a window’s callbacks, an idle handler the program registered) and keeps it right as tasks switch. Everything DVX does on a program’s behalf is charged to that ID: the windows it creates are its own, and the memory allocated is counted against it.

3.4. Two Kinds of Program

The descriptor’s hasMainLoop chooses how the shell runs a program.

A callback-only program (hasMainLoop = false), like hello, has no code running of its own. The shell calls appMain on its own task; appMain creates windows, sets callbacks, and returns, and from then on the program’s code runs only inside the callbacks DVX makes: a button’s onClick, a window’s onClose, a timer’s tick. It ends when its last window is gone. It needs no stack of its own and costs the least, and it is the right kind for anything that waits for the user. Work that has to happen without the user, once a second say, comes from a Timer widget’s callback (Chapter 11).

A main-loop program (hasMainLoop = true) gets a task of its own: a stack (stackSize bytes) and a share of turns (priority). The shell creates the task and returns; appMain starts on it at the shell’s next yield and can loop for as long as the program runs, as long as it yields often. The program ends when appMain returns (its return value is not used); the shell then destroys any window it left. This is the kind for continuous work: a game, a terminal, an animation, a long computation. (Every DVX BASIC program runs this way, as a task of its own.)

A main-loop program’s windows still have callbacks, and they still run on the shell’s task, never on the program’s. Since only one task runs at a time, a callback and the program’s loop never run at once, but the loop sees what a callback did only at its next turn. ticker (Section 3.7) uses that: its callbacks set flags, and its loop acts on them.

Task Manager (Ctrl+Esc) shows which kind each running program is, in its Type column: Task for a program with a task of its own (a main-loop program, or a callback-only one while a task it started runs; Chapter 11), Callback for one that runs only in callbacks.

Task Manager listing Program Manager, Hello, and Ticker, with their types, memory, and status
Figure 3. Task Manager with Hello and Ticker running: Hello is a Callback program, Ticker a Task

3.5. Cooperative Tasks

DOS has no threads and DPMI provides none, so DVX’s tasks come from its own library, libtasks (taskSwch.h). A task is a stack and a saved set of registers. Tasks switch only when the running one calls tsYield, or calls something that does; nothing ever interrupts one task to run another. This is cooperative multitasking, and it makes the GUI simple: no two pieces of code ever touch a window at the same time, so nothing needs a lock.

The scheduler gives each ready task priority + 1 turns per round and goes round them in order, so a higher priority means more turns, never all of them: the shell’s own task runs at TS_PRIORITY_HIGH (11 turns a round), and a program at TS_PRIORITY_NORMAL gets 6. A turn lasts until the task yields, however long that is.

That is the rule every DVX program lives by: nothing may block. While your code runs, whether in a callback on the shell’s task or in a loop on your own task, nothing else in DVX does. No input is read, no window is painted, the mouse pointer (which DVX draws itself) stops moving, no other program runs, and the work DVX does in the background waits: the shell’s idle handlers, which feed sound streams and keep the network and the joysticks serviced, run at least every 20 ms only while the shell gets its turns. A loop that never yields freezes DVX, and there is nothing that can interrupt it. So:

  • A callback does its work and returns. Work that takes longer than a moment is split into pieces a Timer runs, or done on a task (Chapter 11).

  • A main-loop program calls tsYield on every pass of its loop, and its passes are short.

  • A wait is a loop that checks and yields, never a call that waits. sleep, usleep, and delay are DVX’s own versions: on a program’s own task they let the other tasks run while they wait, but in a callback, on the shell’s task, nothing else can run, and they stop all of DVX for their length. DOS calls that wait for a device (a printer that is not ready) stop DVX too.

  • Calls that run the event loop themselves are the exception that proves the rule: a dialog box such as dvxInfoBox does not return until the user closes it, but it runs DVX while it waits (Section 3.6).

Task Manager (Ctrl+Esc) can end a program that hangs, as long as DVX itself is still running: a program whose loop yields but never ends, or one stuck in a callback that keeps the event loop going (it shows such a program as Not responding after five seconds, DVX_HUNG_APP_MS). A program that never yields at all leaves nothing running to open Task Manager with.

3.6. The Event Loop

The shell’s main loop runs on the shell’s task, and each pass is one frame of dvxUpdate:

  1. Read the mouse and the keyboard, and dispatch what happened: to the system keys and the menus, to the focused window’s callbacks, and through a window’s widget tree to the widget’s own handling and then its callbacks (onClick, onChange, and the rest). Widget timers fire here too.

  2. Paint each window that asked to be painted (Section 3.8), once, however many times it asked during the frame.

  3. Destroy the windows that were destroyed from inside a callback.

  4. Composite the changed parts of the screen and copy them to video memory.

  5. Yield: run the idle handlers when the frame painted nothing (and at least every 20 ms when frames keep painting), and give the other tasks their turns.

After the frame, the shell ends the programs that are done (a callback-only program with no windows, a main-loop program whose appMain returned, and a main-loop program whose windows are all gone when none of them had an onClose) and carries out requests to close a program or exit DVX.

Input is read only on the shell’s task, so every window callback runs there, for every program. If a program’s own task calls dvxUpdate, that frame paints and yields but normally reads no input.

A modal dialog box is an event loop of its own: dvxInfoBox, the file dialogs, and your own modal windows (Chapter 7) call dvxUpdate until the box closes, inside the callback that opened them. The callback waits; DVX does not. Everything else in DVX goes on, though only the box takes input while it is open. That is the only proper way for a callback to wait for anything.

Callbacks may destroy windows, even their own, but the window’s memory is freed only after the callbacks under way have returned. The frame’s step 3 does that, so the code that called a callback never returns into a freed window.

3.7. A Program with a Main Loop

ticker is a main-loop program: a window with a label that counts the seconds since the program started, and a Reset button that starts the count again.

The Ticker window, showing the seconds it has been running and a Reset button
Figure 4. Ticker, a program with its own main loop
#include "dvxApp.h"
#include "dvxPlat.h"
#include "dvxWgt.h"
#include "shellApp.h"
#include "taskSwch.h"
#include "button/button.h"
#include "label/label.h"

#include <inttypes.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>

#define TICKER_TITLE     "Ticker"
#define TICKER_WIN_W     280
#define TICKER_WIN_H     100
#define TICKER_SPACING   6
#define TICKER_TEXT_MAX  48

static AppContextT *sAc         = NULL;
static WindowT     *sWin        = NULL;
static WidgetT     *sLabel      = NULL;
static bool         sQuit       = false;
static bool         sResetAsked = false;

// ============================================================
// Prototypes
// ============================================================

static void onClose(WindowT *win);
static void onResetClick(WidgetT *w);
static void showSeconds(uint32_t seconds);
int32_t     appMain(DxeAppContextT *ctx);

// ============================================================
// App descriptor
// ============================================================

SHELL_APP_DESCRIPTOR(
    .name          = TICKER_TITLE,
    .hasMainLoop   = true,
    .multiInstance = false,
    .stackSize     = SHELL_STACK_DEFAULT,
    .priority      = TS_PRIORITY_NORMAL
);

The descriptor sets hasMainLoop = true, so the shell gives ticker a task with the default stack (32 KB) at normal priority. taskSwch.h declares tsYield; shellApp.h includes it too, but a file that calls a function names its header.

// Runs on the shell's task: the loop sees the flag at its next turn.
static void onClose(WindowT *win) {
    (void)win;
    sQuit = true;
}


static void onResetClick(WidgetT *w) {
    (void)w;
    sResetAsked = true;
}

The callbacks run on the shell’s task, while the loop of ticker waits for its next turn. They do nothing but set flags. onClose does not destroy the window: the loop does that as it ends, so nothing the loop uses goes away under it. A main-loop program sets onClose: a window without one is simply destroyed when the user closes it, and the loop is not told. When the last window of a main-loop program goes and none of its windows had an onClose, the shell ends the program, its loop stopped where it yielded.

sAc  = ctx->shellCtx;
sWin = dvxCreateWindowCentered(sAc, TICKER_TITLE, TICKER_WIN_W, TICKER_WIN_H, false);

if (!sWin) {
    return -1;
}

sWin->onClose = onClose;

WidgetT *root = wgtInitWindow(sAc, sWin);

if (!root) {
    dvxDestroyWindow(sAc, sWin);
    return -1;
}

root->spacing = wgtPixels(TICKER_SPACING);

sLabel = wgtLabel(root, "");

WidgetT *reset = wgtButton(root, "&Reset");

if (!sLabel || !reset) {
    dvxDestroyWindow(sAc, sWin);
    return -1;
}

sLabel->weight = WGT_WEIGHT_FILL;
reset->onClick = onResetClick;
wgtLabelSetAlign(sLabel, AlignCenterE);
showSeconds(0);
dvxFitWindowH(sAc, sWin);

The window is built as hello’s is. `dvxCreateWindowCentered centers it on the screen, and false makes it a window the user cannot resize. wgtLabelSetAlign centers the label’s text in its width. Here a widget create that fails (memory has run out) ends the program, since the loop needs both.

// The label copies the text, so a buffer on the stack will do.
static void showSeconds(uint32_t seconds) {
    char text[TICKER_TEXT_MAX];

    snprintf(text, sizeof(text), "Seconds running: %" PRIu32, seconds);
    wgtSetText(sLabel, text);
}

wgtSetText copies the text, lays out the window again (a longer text may need more room), and schedules the repaint. It does nothing when the text is what the widget already shows. The repaint happens in the shell’s next frame, not at once.

uint64_t start = platformMicros();
uint32_t shown = 0;

dvxLog("ticker: started from %s", ctx->appPath);

while (!sQuit) {
    if (sResetAsked) {
        sResetAsked = false;
        start       = platformMicros();
    }

    uint32_t seconds = (uint32_t)((platformMicros() - start) / PLATFORM_US_PER_SEC);

    if (seconds != shown) {
        shown = seconds;
        showSeconds(shown);
    }

    tsYield();
}

dvxDestroyWindow(sAc, sWin);
dvxLog("ticker: ended at %" PRIu32 " seconds", shown);
return 0;

The loop is the whole program:

  • platformMicros() (dvxPlat.h) is a 64-bit count of microseconds from DVX’s timer, rising steadily and cheap to read: it makes no DOS call. The seconds since start come from dividing by PLATFORM_US_PER_SEC.

  • Each pass first takes what the callbacks asked for: a Reset moves start to now, so the next comparison shows 0.

  • The label changes only when the second does, not on every pass: a pass is quick, and there are many of them each second.

  • tsYield at the bottom hands the processor to the other tasks: the shell runs a frame (taking input, so a callback may set a flag), other programs run, and then the turn of ticker comes again and the loop checks sQuit.

  • When sQuit is set, the loop ends, destroys the window, logs a line, and returns. Returning from appMain ends the program; the shell reaps it after its next frame.

The other ways out work too. Exit DVX closes every program’s windows as the close gadget does, so onClose sets sQuit and the loop ends at its next turn; the shell waits for the window to go. Task Manager’s End Task kills the task where it stands, at its tsYield, which is safe in a cooperative system: the task is never in the middle of anything else. The shell then calls the program’s appShutdown, if it has one, but nothing after the loop’s tsYield runs; and a program that faults, or does not respond, gets no appShutdown at all. That is one more reason to save as you go.

ticker is a teaching program: a callback-only program with a Timer widget does the same job without a task of its own. A main loop pays off when a program has continuous work, such as a game’s frames (gameFrameWait in the game library yields while it waits for the next frame; Chapter 17) or a computation that runs for minutes (Chapter 11).

3.8. The Display

DVX draws in a VESA graphics mode the user chooses on Control Panel’s Video page (Setup sets the first one), at 8, 15, 16, or 32 bits per pixel, and a program finds the screen’s size at run time. DisplayT describes it: its size, its pixel format, and its buffers. A color is packed into the mode’s pixel format before it is drawn, so drawing never converts a pixel (Chapter 9).

Nothing draws on the screen directly. Writing video memory across the bus is far slower than writing main memory on these machines, so all drawing goes to memory: a window’s content into the window’s own buffer (below), and the picture of the whole screen into a backbuffer in system memory the size of the screen. Only the rectangles of the backbuffer that changed are copied to video memory: through the linear framebuffer when the card has one, or through its 64 KB bank window when it has not. Only that last copy knows the difference.

Each window has a content buffer of its own: its content area, drawn by its widgets or its onPaint callback, kept from frame to frame. When a window moves, or another window passes over it, DVX copies from the buffers it already has; the window’s own code is not asked to draw anything. A window paints only when its content changes. The cost is memory: a content buffer takes width x height x bytes per pixel, 240,000 bytes for a 400 x 300 content area in 16-bit color, as long as the window exists, minimized or not.

The compositor builds the screen from those pieces. Whatever changes on the screen (a window moved, a menu opened, a window’s content repainted) adds its rectangle to the dirty list. Once per frame the compositor merges the rectangles that overlap, and for each one draws into the backbuffer, back to front, the desktop, the windows' frames and content buffers, the menus, the tooltip, and the mouse pointer, then copies the rectangle to video memory. The less that changes, the less a frame costs.

For a program, that means: change the state, and ask for a repaint. A widget’s own calls (wgtSetText, and the like) ask for you. Code that draws its own content asks with wgtInvalidatePaint (repaint only) or wgtInvalidate (lay out again and repaint), and DVX paints once in the next frame. Repainting less than everything, and less often, is the first thing to look at when a program is slow (Chapter 22). A game that needs the whole screen can take it, mode and all, with DVX’s full-screen mode (dvxExclusiveBegin; Chapter 17).

3.9. Memory

DVX accounts for every program’s memory. malloc, calloc, realloc, strdup, and free in a module are DVX’s tracking versions (dvxMem.h, which a program need not include): each block carries a 16-byte header with its owner and size. A block’s owner is the program whose code was running when it was allocated (currentAppId), including what DVX allocates on that program’s behalf: the content buffers of its windows, its widgets, the copy dvxResRead returns. Task Manager shows each program’s total; dvxMemGetAppUsage gives it to code.

When a program ends, DVX destroys its windows (freeing their widgets and buffers), releases what it keeps track of for the program, unloads the module, and sets the program’s count back to zero. It does not free the blocks the program allocated and left allocated. The count is bookkeeping, not a collector: DVX.LOG notes what was left (“Memory: program 3 ended with 10240 bytes still allocated to it; they stay until DVX exits”), and a leaked block stays allocated until DVX exits, and every run of a leaking program takes more from every other program. Free what you allocate, on every path, including the one where the user closes the window.

Some memory is not counted at all: what DVX.EXE allocates itself, such as the buffer of a file fopen opened, belongs to its own C library. Close the file and it is freed. A library can keep its own memory in DVX’s name rather than a program’s (dvxMemSetApp; Chapter 18).

3.10. Faults

When a program’s code raises a processor fault (a page fault from a bad pointer, a division by zero, an invalid instruction), DVX’s handler writes a crash report to DVX.LOG (the signal, the module the faulting instruction is in, and every register), stops the code that faulted, and ends the program that was running. A box titled Application Error tells the user: 'Hello' has caused a fault and will be terminated. The other programs and DVX itself go on, including a dialog box that was open at the time. This works on any task: a main-loop program’s task stops on its own stack, and a callback that faults is abandoned in the frame it ran in. Chapter 22 shows how to find the faulting line from the report.

exit and abort in a program end that program the same way, without a message: DVX logs “Shell: 'Hello' called exit (status 0); ending it”. A program never ends DVX by calling them. The functions a program gives atexit are its own: exit runs them first, and any end that runs appShutdown runs them after it; abort, _exit, and a fault drop them.

A program ended by a fault is ended by force: its appShutdown does not run and its unsaved work is lost. And faults are only the errors the processor notices. A pointer that strays outside DVX’s memory altogether (DOS’s memory, the interrupt vectors, the screen) faults, but every program shares DVX’s memory, so a write through a bad pointer that lands inside it corrupts it silently, perhaps in another program, perhaps in DVX, and shows up later and elsewhere; the fault handler is a safety net, not memory protection.

3.11. The Binary Interface

A module is compiled against DVX’s headers, and much of them is compiled into it: the layout of WindowT and AppContextT, the offsets of the fields it reads, the values of constants, the order of the functions in a widget’s API table. A module built against the headers of another DVX release could call the wrong functions or read the wrong fields. So DVX has one number for its whole binary interface, DVX_ABI_VERSION in dvxTypes.h, which changes whenever anything a compiled module depends on changes, and every module records the number it was built with:

Module Records it with When it differs

Program

SHELL_APP_DESCRIPTOR (AppDescriptorT.abiVersion)

The shell refuses to start it: “This program was built for a different version of DVX and cannot run.”

Library, widget

DVX_ABI_STAMP(name), which exports nameAbiVersion

The loader refuses it. At start-up an add-on is left out and DVX says so, and one of DVX’s own stops DVX; a library loaded later, when first used, is refused with a line in DVX.LOG only.

Widget API table

WGT_API_HEADER in its first member

wgtGetApi refuses it.

DVX.LOG has the details in each case. The rule for you is short: build your modules with the SDK of the DVX release they will run on, and rebuild them all when DVX’s number changes. The rules for your own libraries' and widgets' interfaces, which their users compile against in the same way, are in Chapter 18 and Chapter 19.

Part II: Writing Programs

Chapter 4. Windows

Everything a DVX program shows is in a window: a framed rectangle with a title bar, a close gadget, a minimize gadget, and, when it can be resized, a maximize gadget and resize edges. The window manager draws the frame and moves, sizes, stacks, and minimizes windows without your code; your code fills the content area, usually with widgets, and hears about what happens to the window through callbacks.

This chapter covers making windows and managing them from code: where a window goes and how big it is, its title and icon, the callbacks and when each one runs, programs with several windows, modal windows, and how a program ends. The example, windows, is a main window that opens tool windows and moves, resizes, minimizes, and restores them. The calls are in dvxApp.h (the dvx* functions, which are what programs use) and dvxWm.h (the window manager’s wm* functions, a few of which programs use directly); the reference book lists them all in “dvxApp.h — Layer 5: Application API” in the DVX C Library Reference and “dvxWm.h — Layer 4: Window Manager” in the DVX C Library Reference.

4.1. The Example: Windows

The windows example is a callback-only program, like hello in Chapter 2: appMain creates the main window, fills it with widgets, and returns, and DVX calls the program’s callbacks from then on. Its main window shows three labels, which the callbacks keep up to date, and six buttons:

Button What it does

New Tool

Opens a tool window beside the main window (six at most).

Arrange Tools

Brings every tool window back from an icon or from maximized and lines them up in a column beside the main window.

Minimize Tools

Makes every tool window an icon at the bottom of the screen.

Options…​

Opens a modal Options window with one setting: whether new tool windows can be resized.

Grow and Shrink

Make the main window 40 pixels larger or smaller each way.

Each tool window has a Bring Main Forward button. Closing the main window closes the tool windows too, and the program ends. The project, windows, holds windows.c, windows.res (the program’s icon and name), windows.dhs (its help), and icon32.bmp; build and install it as Chapter 1 describes, and run it from Program Manager.

The Windows window, counting its tool windows and showing its content size, with New Tool, Arrange Tools, Minimize Tools, Options, Grow, and Shrink buttons
Figure 5. The Windows program’s main window

The program keeps its windows in static variables, prefixed s as DVX’s own programs do:

static AppContextT *sAc             = NULL;
static WindowT     *sMain           = NULL;
static WindowT     *sOptions        = NULL;
static WindowT     *sTools[WINDOWS_TOOL_MAX];
static int32_t      sToolCount      = 0;
static int32_t      sToolsMade      = 0;
static bool         sToolsResizable = false;
static WidgetT     *sCountLabel     = NULL;
static WidgetT     *sSizeLabel      = NULL;
static WidgetT     *sFocusLabel     = NULL;
static WidgetT     *sResizableCheck = NULL;

4.2. Creating a Window

A window is made with dvxCreateWindow:

WindowT *dvxCreateWindow(AppContextT *ctx, const char *title, int32_t x, int32_t y, int32_t w, int32_t h, bool resizable);

ctx is the shell’s GUI context, DxeAppContextT.shellCtx (Chapter 2). title is copied into the window (at most 127 characters; MAX_TITLE_LEN is 128 with the NUL). x and y are the screen position of the window’s top-left corner, and w and h the size of the whole frame, title bar and borders included, in pixels. resizable says whether the user can change its size. The new window is on top of every other window and has the keyboard focus, and it belongs to the program that created it: the shell destroys it if the program ends without doing so. dvxCreateWindow returns NULL when there is not enough memory for the window or its content buffer.

The position you pass is a request. When another visible window already has its top-left corner exactly at (x, y), DVX moves the new window down and to the right by the height of a title bar (CHROME_TITLEBAR_BOTTOM, 24 pixels) until the corner is free, starting over near the top-left of the screen if that walk would leave the screen. Then, if the window would hang off the screen, it is moved so that all of it is on the screen. Opening several windows at the same place therefore cascades them, which the example’s tool windows show.

The content area, where your widgets or drawing go, is the frame less the chrome. The window keeps its geometry in WindowT: x, y, w, and h for the frame, and contentX, contentY, contentW, and contentH for the content area, relative to the frame. The borders take CHROME_TOTAL_SIDE (6) pixels on each side, the title bar and borders CHROME_TOTAL_TOP (26) at the top and CHROME_TOTAL_BOTTOM (6) at the bottom, a menu bar another CHROME_MENU_HEIGHT (20), and a window scroll bar SCROLLBAR_WIDTH (16). A 320 by 200 window without a menu bar has a 308 by 168 content area. All of these are in dvxTypes.h.

Each window has a content buffer of its own: a copy of its content area in the display’s pixel format, which DVX copies to the screen whenever the window’s part of the screen needs repainting. That is why a window being dragged over others costs those others nothing, and also why windows cost memory: a full-screen window at 1024 by 768 and 16 bits per pixel holds 1.5 MB. Make windows the size their contents need.

The screen’s size is in the context’s display, ctx→display.width and ctx→display.height (dvxGetDisplay returns the same DisplayT). Work positions out from it rather than assuming 640 by 480, since the user chooses the video mode. The example places its main window so that the main window and one tool window beside it are centered together:

int32_t appMain(DxeAppContextT *ctx) {
    sAc = ctx->shellCtx;

    // The main window and a tool window beside it, centered on the screen
    int32_t x = (sAc->display.width - (WINDOWS_MAIN_W + WINDOWS_GAP + WINDOWS_TOOL_W)) / 2;
    int32_t y = (sAc->display.height - WINDOWS_MAIN_H) / 2;

    sMain = dvxCreateWindow(sAc, WINDOWS_TITLE, x, y, WINDOWS_MAIN_W, WINDOWS_MAIN_H, true);

    if (!sMain) {
        return -1;
    }

    WidgetT *root = wgtInitWindow(sAc, sMain);

    if (!root) {
        dvxDestroyWindow(sAc, sMain);
        return -1;
    }

    // After wgtInitWindow, which installs handlers of its own
    sMain->onClose  = onMainClose;
    sMain->onResize = onMainResize;
    sMain->onFocus  = onMainFocus;
    sMain->onBlur   = onMainBlur;

    // The picture the window shows when minimized and in the Alt+Tab
    // switcher: the program's own icon, from its resources.  The window
    // owns the pixels from here on.
    int32_t  iconW     = 0;
    int32_t  iconH     = 0;
    int32_t  iconPitch = 0;
    uint8_t *icon      = dvxResLoadIcon(sAc, ctx->appPath, DVX_RES_NAME_ICON, &iconW, &iconH, &iconPitch);

    wmSetIconData(sMain, icon, iconW, iconH, iconPitch);

    root->spacing = wgtPixels(WINDOWS_SPACING);
    sCountLabel   = wgtLabel(root, "");
    sSizeLabel    = wgtLabel(root, "");
    sFocusLabel   = wgtLabel(root, "This window is active.");

    WidgetT *row1 = wgtHBox(root);
    WidgetT *row2 = wgtHBox(root);
    WidgetT *row3 = wgtHBox(root);

    addButton(row1, "&New Tool", onNewToolClick);
    addButton(row1, "&Arrange Tools", onArrangeClick);
    addButton(row2, "&Minimize Tools", onMinimizeClick);
    addButton(row2, "&Options...", onOptionsClick);
    addButton(row3, "&Grow", onGrowClick);
    addButton(row3, "&Shrink", onShrinkClick);

    updateMain();
    dvxFitWindowH(sAc, sMain);
    return 0;
}

dvxCreateWindowCentered(ctx, title, w, h, resizable) centers a window of the given size on the screen. It centers the size you pass, so a window you then fit to its controls (Section 4.5) is centered no longer; the example’s Options window centers itself again after fitting, with a helper shown in Section 4.6.

4.2.1. Resizable Windows and Size Limits

A resizable window has resize edges and a maximize gadget; double-clicking its title bar maximizes or restores it, and its system menu (the close gadget’s menu) has Size and Maximize. A window that is not resizable has none of these, and the user can only move it, minimize it, and close it. WindowT.resizable holds the setting.

A window has no minimum size of your choosing. Neither the user nor dvxResizeWindow can make it smaller than its frame needs, which wmMinWindowSize reports: room for the gadgets and one character of the title, the width of every menu title when it has a menu bar, and the height of its chrome. Below the size its widgets need, a window with widgets gets scroll bars of its own, and its controls keep their minimum sizes; Chapter 5 explains those sizes.

The maximum is WindowT.maxW and maxH, which start as WM_MAX_FROM_SCREEN, the screen’s size. Set them to keep a window smaller: maximizing then makes it that size at the top-left of the screen, and the user cannot drag it larger. dvxResizeWindow does not apply them.

4.3. Window Callbacks

A window tells the program what happens to it by calling function pointers in its WindowT. They all start as NULL, which means the program does not want to hear about that event. The ones a program uses are these:

Callback When DVX calls it Who sets it

onClose(win)

The user asks to close the window: the close gadget (double-click), Alt+F4, or Close on the system menu; also dvxRequestWindowClose and DVX’s exit.

The program.

onMenu(win, id)

A menu item, a context-menu item, or an accelerator key is chosen.

The program (Chapter 6).

onMenuOpen(win, menu)

A menu of the window’s menu bar, or a submenu, is about to open.

The program (Chapter 6).

onResize(win, contentW, contentH)

The content area changed size.

wgtInitWindow; a program may chain to it.

onFocus(win), onBlur(win)

The window gained or lost the keyboard focus.

wgtInitWindow; a program may chain to it.

onPaint(win, dirtyArea)

The content needs painting.

wgtInitWindow.

onMouse(win, x, y, buttons)

The mouse moved or a button changed over the content area.

wgtInitWindow.

onKey(win, key, mod), onKeyUp(win, scancode, mod)

A key was pressed or released while the window had the focus.

wgtInitWindow.

onScroll(win, orient, value)

A window scroll bar moved.

The widget layer, when it first lays the window out.

onCursorQuery(win, x, y)

DVX asks which mouse pointer to show over a point.

A program drawing its own content (Chapter 8).

onRawKey(win, evt)

A key went down or up, in a game input window.

A game (Chapter 17).

wgtInitWindow turns a window over to the widget layer by installing seven of these handlers: onPaint, onMouse, onKey, onKeyUp, onResize, onFocus, and onBlur, the last three as widgetOnResize, widgetOnFocus, and widgetOnBlur. Two rules follow:

  • Set your handlers after wgtInitWindow, or it overwrites them. onClose, onMenu, and onMenuOpen are untouched by it, so the order does not matter for those, but setting every handler in one place after wgtInitWindow avoids the question.

  • Leave onPaint, onMouse, onKey, onKeyUp, and onScroll to the widget layer in a window with widgets. To act on onResize, onFocus, or onBlur as well, call the widget layer’s handler from yours, first.

The example installs its four:

    // After wgtInitWindow, which installs handlers of its own
    sMain->onClose  = onMainClose;
    sMain->onResize = onMainResize;
    sMain->onFocus  = onMainFocus;
    sMain->onBlur   = onMainBlur;

WindowT.userData is the program’s: DVX never touches it (except in a dialog box made with dvxDialogCreate, which keeps its state there; Chapter 7), and wgtInitWindow leaves it alone (the widget root’s userData holds the context). Use it to find your own data from a callback that several windows share.

Every callback runs inside DVX’s event loop under the window’s program ID, so the memory it allocates is counted to that program. It must return promptly: until it does, no window repaints, no other program runs, and after DVX_HUNG_APP_MS (5 seconds) the Task Manager reports the program as not responding. A callback may open a dialog box, which runs a nested event loop of its own until it closes; Chapter 7 explains that. Long work goes in a task (Chapter 11).

4.3.1. Resizing: onResize

onResize runs after the content area changed size, with the new content size: while the user drags a resize edge (each time the mouse moves the edge), when the window is maximized or restored, when a menu bar appears or goes, and from dvxResizeWindow and the dvxFitWindow calls, before they return. The content buffer has already been reallocated, and the window is repainted at the next frame.

The widget layer’s widgetOnResize lays the controls out at the new size and adds or removes the window’s scroll bars, which changes the content area again. A handler that wants the final size reads it from the window after calling widgetOnResize, as the example’s does to show it:

// The main window changed size: a drag, maximize or restore, or
// dvxResizeWindow.  widgetOnResize lays the controls out again and adds
// or removes the window's scroll bars, which changes the content area, so
// the size shown is read from the window after it.
static void onMainResize(WindowT *win, int32_t contentW, int32_t contentH) {
    char text[WINDOWS_TEXT_MAX];

    widgetOnResize(win, contentW, contentH);
    snprintf(text, sizeof(text), "Content area: %ld x %ld pixels", (long)win->contentW, (long)win->contentH);
    wgtSetText(sSizeLabel, text);
}

Changing a label’s text from onResize is safe: wgtSetText lays the window out again, which does not call onResize again. Keep the handler cheap, since a drag calls it many times.

4.3.2. Focus: onFocus and onBlur

One window at a time has the keyboard focus, and its title bar is drawn in the active colors. onFocus runs when a window gets the focus and onBlur when it loses it: when the user clicks a window or switches with Alt+Tab, when code calls dvxRaiseWindow, when the focused window closes, is minimized, or is hidden (the window then on top gets the focus), and when a new window opens (it takes the focus, so the window that had it gets onBlur). A new window’s own onFocus does not run for its creation: dvxCreateWindow gives it the focus before you can set the handler. A window being destroyed gets no onBlur.

widgetOnBlur takes the keyboard focus from the control that had it (its onBlur runs, so a text field can commit what was typed), and remembers the control on the window; widgetOnFocus marks the window for repainting, and the paint hands the focus back to that control. A program that replaces either without calling it leaves the window’s controls without focus. The example chains both and shows which state the window is in:

// The main window lost the focus.  The widget layer's handler runs first:
// it takes the focus from the control that had it and remembers that
// control, which gets the focus back when the window does.
static void onMainBlur(WindowT *win) {
    widgetOnBlur(win);
    wgtSetText(sFocusLabel, "This window is inactive.");
}

4.3.3. Closing: onClose

onClose does not close anything: it asks. The window stays until the program destroys it with dvxDestroyWindow, so onClose is where a program asks about unsaved work, or refuses. A window with no onClose is destroyed by DVX when the user closes it.

dvxRequestWindowClose(ctx, win, reason) asks a window to close from code exactly as the close gadget does: its onClose runs, or the window is destroyed when it has none. While onClose runs, ctx→closeReason says why it was called: WinCloseUserE for the user (the gadget, Alt+F4, the system menu, and the reason a program passes for its own Exit command), WinCloseExitE when the user is exiting DVX and every program is asked to close in turn, and WinCloseRequestE when the shell asks for another reason (another program’s request, or a screen saver ending). On the way out, DVX asks each program’s visible windows to close, oldest first, so a save prompt in onClose works there too; a window that stays open without showing anything is treated as a program that does not respond, which the user is offered to end.

The example’s tool windows use closeTool itself as their onClose; the same function serves the main window’s close, which closes every tool window and then itself:

// A tool window's close box (it is the window's onClose) and the main
// window's: the window leaves the list and is destroyed.
static void closeTool(WindowT *win) {
    for (int32_t i = 0; i < sToolCount; i++) {
        if (sTools[i] == win) {
            sToolCount--;
            memmove(&sTools[i], &sTools[i + 1], (size_t)(sToolCount - i) * sizeof(sTools[0]));
            break;
        }
    }

    dvxDestroyWindow(sAc, win);
    updateMain();
}
// The main window's close box, Alt+F4, or the system menu's Close: the
// tool windows go, then the main window.  With its last window gone, the
// program ends.
static void onMainClose(WindowT *win) {
    while (sToolCount > 0) {
        closeTool(sTools[sToolCount - 1]);
    }

    dvxDestroyWindow(sAc, win);
}

dvxDestroyWindow called from inside a callback, which is nearly always, does not free the window at once: the code that called your callback may still use it. DVX hides the window, takes the focus from it, and cuts it off from input at once, and frees it, with its widgets and menu bar, once the event loop has unwound. Do not use a window pointer after destroying the window. dvxDestroyWindow closes a menu the window has open, ends its modal state, and gives the focus to the window now on top.

4.4. Titles and Icons

dvxSetTitle(ctx, win, title) changes a window’s title. It repaints only the title bar, does nothing when the title is the one the window has, and lets the shell know the title changed. The example counts its tool windows in its title:

// The main window's title and first label count the tool windows.
// dvxSetTitle repaints only the title bar, and does nothing when the
// title is the same.
static void updateMain(void) {
    char text[WINDOWS_TEXT_MAX];

    snprintf(text, sizeof(text), "%s (%ld Open)", WINDOWS_TITLE, (long)sToolCount);
    dvxSetTitle(sAc, sMain, text);
    snprintf(text, sizeof(text), "Tool windows open: %ld", (long)sToolCount);
    wgtSetText(sCountLabel, text);
}

A minimized window is drawn as an icon at the bottom of the screen, ICON_TOTAL_SIZE (68) pixels square, and the Alt+Tab switcher draws the same picture. A window with no icon of its own shows a small copy of its content there; the example’s tool windows do. To give a window an icon, load a picture in the display’s pixel format and hand it to the window with wmSetIconData(win, pixels, w, h, pitch), which takes ownership of the pixels and frees them with the window. dvxSetWindowIcon(ctx, win, path) does both from an image file. A program’s own icon is its icon32 resource (Chapter 20), which dvxResLoadIcon loads from the program’s .app file:

    // The picture the window shows when minimized and in the Alt+Tab
    // switcher: the program's own icon, from its resources.  The window
    // owns the pixels from here on.
    int32_t  iconW     = 0;
    int32_t  iconH     = 0;
    int32_t  iconPitch = 0;
    uint8_t *icon      = dvxResLoadIcon(sAc, ctx->appPath, DVX_RES_NAME_ICON, &iconW, &iconH, &iconPitch);

    wmSetIconData(sMain, icon, iconW, iconH, iconPitch);

dvxResLoadIcon returns NULL and leaves the sizes alone when the resource is missing, and wmSetIconData given NULL removes the icon, so the code needs no test.

4.5. Fitting a Window to Its Controls

Rather than guess how big a window of controls must be, build the controls and let DVX measure them. dvxFitWindow(ctx, win) sets the window’s size to its widget tree’s minimum size plus the chrome, never smaller than wmMinWindowSize; dvxFitWindowH fits only the height, keeping the width you chose, and dvxFitWindowW only the width. They resize through dvxResizeWindow, so onResize runs and the window is kept on the screen. A window with no widgets is left alone.

The example’s main window and tool windows keep the widths they were created with and fit their heights with dvxFitWindowH; its Options window, whose size is set by its contents alone, uses dvxFitWindow:

// The Options window.  It is modal: until it closes, only it takes the
// mouse and the keyboard, whichever program's window the user tries.
static void openOptions(void) {
    WindowT *win = dvxCreateWindowCentered(sAc, "Options", WINDOWS_OPTIONS_W, WINDOWS_OPTIONS_H, false);

    if (!win) {
        return;
    }

    WidgetT *root = wgtInitWindow(sAc, win);

    if (!root) {
        dvxDestroyWindow(sAc, win);
        return;
    }

    sOptions        = win;
    win->modal      = true;
    win->onClose    = onOptionsClose;
    root->spacing   = wgtPixels(WINDOWS_SPACING);
    sResizableCheck = wgtCheckbox(root, "&Resizable tool windows");
    wgtCheckboxSetChecked(sResizableCheck, sToolsResizable);

    WidgetT *row    = wgtHBox(root);
    WidgetT *ok     = addButton(row, "OK", onOptionsOkClick);
    WidgetT *cancel = addButton(row, "Cancel", onOptionsCancelClick);

    dvxSetWindowButtons(win, ok, cancel);
    dvxFitWindow(sAc, win);
    centerWindow(win);
    dvxModalBegin(sAc, win);
}

4.6. Moving and Resizing from Code

dvxResizeWindow(ctx, win, w, h) sets the frame’s size. A size smaller than wmMinWindowSize becomes that minimum; a window that would hang off the right or bottom edge of the screen is moved left or up to stay on it. The content buffer is reallocated and onResize runs before the call returns; the window is repainted at the next frame, so several changes in one callback paint once. It works on a window of either kind, resizable or not, and does not apply maxW and maxH. The example’s Grow and Shrink buttons use it; Shrink, pressed often enough, stops at the minimum, and the window gets scroll bars once its controls no longer fit:

// Grow and Shrink.  dvxResizeWindow sets the frame's size (never below
// the smallest the frame fits in), keeps the window on the screen, and
// calls onResize before it returns.
static void resizeMain(int32_t delta) {
    dvxResizeWindow(sAc, sMain, sMain->w + delta, sMain->h + delta);
}

dvxMoveWindow(ctx, win, x, y) moves a window’s frame so that its top-left corner is at x, y on the screen, keeping its size, as a drag of its title bar does: the position is first adjusted as a drag’s is (wmClampWindowPos), so that the title bar stays where the mouse can reach it, the place the window leaves and the place it takes are repainted at the next frame (the compositor is described in Chapter 3), and a maximized window that moves is no longer maximized. The content is not painted again, since it has not changed. The call does nothing for a window that is being destroyed. The example’s centerWindow uses it:

// Centers win on the screen at the size it has now.  A window fitted to
// its controls after dvxCreateWindowCentered is no longer centered.
// dvxMoveWindow keeps the title bar where the mouse can reach it, and
// repaints the place the window leaves and the place it takes.
static void centerWindow(WindowT *win) {
    dvxMoveWindow(sAc, win, (sAc->display.width - win->w) / 2, (sAc->display.height - win->h) / 2);
}

4.7. Raising, Lowering, Hiding, and Showing

The windows of every program share one stack, front to back. dvxRaiseWindow(ctx, win) brings a window to the front and gives it the keyboard focus, and dvxLowerWindow(ctx, win) puts it behind all the others, passing the focus to the window now on top if it had it. Both do nothing for a window that is being destroyed. A tool window’s Bring Main Forward calls dvxRaiseWindow on the main window, and Arrange Tools ends with it, since restoring each tool window raised that window and gave it the focus:

// Arrange Tools: each tool window restored (from an icon or from
// maximized) and put in a column beside the main window, which then
// comes to the front again.
static void onArrangeClick(WidgetT *w) {
    (void)w;

    int32_t x = sMain->x + sMain->w + WINDOWS_GAP;
    int32_t y = sMain->y;

    for (int32_t i = 0; i < sToolCount; i++) {
        dvxRestoreWindow(sAc, sTools[i]);
        dvxMoveWindow(sAc, sTools[i], x, y);
        y += sTools[i]->h + WINDOWS_GAP;
    }

    dvxRaiseWindow(sAc, sMain);
}

dvxHideWindow(ctx, win) takes a window off the screen without destroying it: it gets no input, gives up the focus, and stops being modal. dvxShowWindow(ctx, win) puts it back where it was, behind any window raised meanwhile, without the focus; call dvxRaiseWindow after it to bring it forward. A hidden window still belongs to its program, which matters when the program ends (Section 4.12).

dvxSetWindowEnabled(ctx, win, false) disables a whole window, as Visual Basic’s Form.Enabled and Windows' EnableWindow do: it stays on the screen and paints, but takes no mouse and no keys from the user. Its widgets and its own onMouse, onKey, onKeyUp, and onScroll get nothing, and its frame neither: a click does not move, size, close, or activate it, and Alt+F4, its menus, and its system menu do nothing. Alt+Tab passes it over. Its widgets paint grayed, as the widgets in a disabled container do (Section 5.8). A disabled window that had the focus stays the active one, its keys dropped; its focused widget loses the focus (onBlur) and gets it back (onFocus) when dvxSetWindowEnabled(ctx, win, true) enables the window again. The program’s own calls still work on it: it can be moved, sized, shown, hidden, raised, and closed from code. WindowT.disabled says which state a window is in.

4.8. Minimizing, Maximizing, and Restoring

dvxMinimizeWindow(ctx, win) makes a window an icon at the bottom of the screen, passing the focus on if it had it; the user restores it by double-clicking the icon. It does nothing for a modal window, one with WindowT.modal set or the window that is modal now (Section 4.10): while a minimized window is modal, the mouse could not reach its icon. dvxMaximizeWindow(ctx, win) makes it fill the screen, or the size maxW and maxH allow, at the top-left corner, keeping its old place and size to go back to. From code this works on any window, though the user can maximize only a resizable one. dvxRestoreWindow(ctx, win) brings a minimized window back, or a maximized one back to its old place and size, and then raises it and gives it the focus. WindowT.minimized and maximized say which state a window is in. The user cannot minimize a modal window either: it has no minimize gadget, and its system menu’s Minimize is grayed.

The example’s Minimize Tools minimizes every tool window. Arrange Tools, shown above, restores each one before moving it with dvxMoveWindow: moving an icon would not bring it back, and a maximized window would keep its full-screen size.

// Minimize Tools: each tool window becomes an icon at the bottom of the
// screen.  A window that has no icon of its own shows a small picture of
// its contents.
static void onMinimizeClick(WidgetT *w) {
    (void)w;

    for (int32_t i = 0; i < sToolCount; i++) {
        dvxMinimizeWindow(sAc, sTools[i]);
    }
}

4.9. Several Windows in One Program

A program may have as many windows as memory allows. Keep a pointer to each one you need to reach, and forget it in the window’s onClose when you destroy the window, as the example does with its sTools array:

// A new tool window beside the main window.  Each opens at the same
// place; DVX moves a window that would sit exactly on another one down
// and to the right, so they cascade.
static void openTool(void) {
    char title[WINDOWS_TEXT_MAX];

    if (sToolCount >= WINDOWS_TOOL_MAX) {
        dvxInfoBox(sAc, WINDOWS_TITLE, "Close a tool window first.");
        return;
    }

    sToolsMade++;
    snprintf(title, sizeof(title), "Tool %ld", (long)sToolsMade);

    WindowT *win = dvxCreateWindow(sAc, title, sMain->x + sMain->w + WINDOWS_GAP, sMain->y, WINDOWS_TOOL_W, WINDOWS_TOOL_H, sToolsResizable);

    if (!win) {
        return;
    }

    WidgetT *root = wgtInitWindow(sAc, win);

    if (!root) {
        dvxDestroyWindow(sAc, win);
        return;
    }

    win->onClose  = closeTool;
    root->spacing = wgtPixels(WINDOWS_SPACING);
    wgtLabel(root, "A tool window.");
    addButton(root, "Bring &Main Forward", onRaiseMainClick);
    dvxFitWindowH(sAc, win);

    sTools[sToolCount++] = win;
    updateMain();
}

Every window also has an id, never reused while DVX runs. When a window can go away without your code knowing, keep its id instead of its pointer and look it up with wmWindowById(&ctx→stack, id), which returns NULL once the window is gone.

A tool window can borrow its main window’s menu bar for the keyboard: set the tool window’s menuWinId to the main window’s id, and Alt with a letter and F10 in the tool window open the main window’s menus, as in the DVX BASIC IDE’s Code and Project windows. The tool window’s own controls' access keys come first.

The classic Window menu commands are there too: dvxCascadeWindows, dvxTileWindows (a grid), dvxTileWindowsH (stacked, full width), and dvxTileWindowsV (side by side, full height). Each takes only the context and arranges every visible, unminimized window on the screen, of every program. A resizable window gets a new size; one that is not resizable keeps its size and is only moved, kept on the screen. (dvxMaximizeWindow, by contrast, works on any window from code.)

4.10. Modal Windows

A modal window is one that must be dealt with before anything else: while it is modal, only it takes the mouse and the keyboard. This is system-wide, not per program: clicks on any other window, of any program, and on minimized icons are ignored, and Alt+Tab does nothing. The message boxes and file dialogs of Chapter 7 are modal windows.

dvxModalBegin(ctx, win) makes a window modal and dvxModalEnd(ctx, win) ends it; every dvxModalBegin needs its dvxModalEnd. Modal windows stack: a modal window opened from another (a message box from an Options window) is modal on top of it, and when it ends, the one before it is modal again. A modal window that is hidden or destroyed leaves the stack by itself, wherever it is in it, so a program that is ended while its modal window is open does not leave the screen locked.

While a window is modal, dvxModalBegin also marks it as a modal window, WindowT.modal: it has no minimize gadget, its system menu’s Minimize is grayed, and DVX plays no open or close sound for it. dvxModalEnd, or hiding or destroying the window, gives it back its own WindowT.modal, so a window that stays open after its modal time gets its minimize gadget and its sounds back. A window that is always a dialog sets WindowT.modal itself, as DVX’s dialog boxes do, and keeps it; the example’s Options window does, so it closes without a sound after its dvxModalEnd. dvxSetWindowButtons(win, defaultBtn, cancelBtn) gives it the keys a dialog box has: Enter presses the default button (unless the focused control uses Enter itself) and Esc the cancel button.

The example’s Options window, shown in Section 4.5, is modal in the callback style: openOptions creates it, makes it modal, and returns, and its buttons' callbacks finish the job. OK reads the setting and closes the window, and Cancel and the close gadget close it:

// The Options window's OK, Cancel, and close box all end here.
static void closeOptions(void) {
    dvxModalEnd(sAc, sOptions);
    dvxDestroyWindow(sAc, sOptions);
    sOptions        = NULL;
    sResizableCheck = NULL;
}

The other way to use a modal window is the way the message boxes do it: open it, then run the event loop yourself (call dvxUpdate until the window says it is done) and return the answer, so the caller simply waits for it. Chapter 7 builds a dialog box that way.

4.11. Windows Without Widgets

A window need not have widgets. Without wgtInitWindow, the window’s callbacks are all the program’s: onPaint draws the content into the window’s content buffer (dvxContentDisplay gives a DisplayT aimed at it, for DVX’s drawing functions), onMouse and onKey take the input, and dvxInvalidateWindow calls onPaint again to redraw it all (dvxInvalidateRect only puts a rectangle of what the buffer already holds back on the screen, the part of it inside the content area). Most programs that draw use the Canvas widget instead, in a window that has widgets; Chapter 9 covers both.

4.12. Ending the Program

A callback-only program, such as the example, ends when it has no windows left. Between frames the shell looks for such programs and unloads them, so destroying the last window, even from inside one of its callbacks, is all a program does to end. Hidden windows count: a program that hides its only window keeps running, unseen, until something shows the window or destroys it.

A program may export a function the shell calls just before it unloads the program:

void appShutdown(void);

The shell looks it up by name, as it does appMain, and calls it when the program ends normally: for a callback-only program, after its last window is gone. DVX does not free a program’s memory when it ends, so appShutdown is where a program frees what it allocated and its windows did not take with them, such as accelerator tables and context menus (Chapter 6). It runs too when the Task Manager’s End Task or Exit DVX ends the program, after its tasks are stopped. It does not run when the program faults, when it is not responding, or when End Task had to wait for the program’s code to return.

When appMain of a callback-only program returns anything but 0, the shell logs it to DVX.LOG and unloads the program at once, destroying any window it made, without calling appShutdown. The example returns -1 when it cannot set up its main window, destroying the window itself first, as the SDK’s template does.

A program with a main loop (hasMainLoop, Chapter 3) is different: it ends when appMain returns, whether or not it still has windows, and closing its windows does not end it. Its loop must notice that its window closed, typically from a flag its onClose sets, and return. (A main-loop program whose windows have no onClose at all is ended by the shell once the last of them is gone, its loop stopped where it yielded.)

Chapter 5. Widgets and Layout

Almost everything a DVX program shows sits in widgets: labels, buttons, text boxes, lists, trees, and the boxes that arrange them. You do not place widgets at coordinates. You build a tree of them, give some of them size hints, and DVX’s layout engine works out where each one goes, again whenever the window changes size. This chapter explains the tree, the containers, the layout rules, the common widgets and their events, focus, and access keys, and builds two programs: signup, a data-entry form that checks what the user typed, and browser, a tree beside a list in a splitter. The DVX C Library Reference has every widget’s full API (“Base WidgetT (Common Properties, Events, and Operations)” in the DVX C Library Reference and the sections after it); this chapter shows how the pieces fit.

5.1. The Widget Tree

Every widget is a WidgetT (dvxWgt.h), whatever its kind. The core of DVX knows nothing about buttons or lists: each kind is a class registered by a widget module, the class’s functions do the drawing and the input, and the widget’s private state hangs off w->data, which only its module reads. What a program sees is the common part: the tree links, the geometry the layout computed, the size hints, the state flags, and the callbacks.

The tree is linked through parent, firstChild, lastChild, and nextSibling; every widget also has window, the window it belongs to. Every create call takes the parent as its first argument and appends the new widget as the parent’s last child, so the order you create widgets in is the order they appear in, and the order Tab visits them (Section 5.9).

5.1.1. The Root

A window has no widgets until you call wgtInitWindow(ctx, win). It creates the window’s root, a VBox (a vertical box, Section 5.3) that fills the window’s content area, and returns it; you build everything else under it. It also takes over the window: it sets onPaint, onMouse, onKey, onKeyUp, onResize, onBlur, and onFocus to the widget layer’s own handlers, which paint the tree and send input to the widgets. It returns NULL only when the box widget is missing or memory runs out, and a second call on the same window returns the root it already has.

So set any of those window callbacks after wgtInitWindow, and from yours call the widget layer’s handler first, or the widgets stop working: widgetOnResize measures and lays out the tree for the new size, and widgetOnBlur and widgetOnFocus keep the keyboard focus right when the window loses and regains the focus. Chapter 4 covers the window callbacks. A program’s own resize handler, for example:

static void onResize(WindowT *win, int32_t newW, int32_t newH) {
    // The widget layer re-measures and lays out the tree first
    widgetOnResize(win, newW, newH);
    // ... then the program's own work
}

// In appMain, after wgtInitWindow, which sets its own:
win->onResize = onResize;

The root’s userData holds the AppContextT; wgtGetContext(w) reads it back from any widget of the window. Leave the root’s userData alone. Every other widget’s userData, and the window’s own win->userData, are yours.

5.1.2. Who Owns What

The tree owns its widgets. Destroying the window destroys the tree, so a program that builds a window never frees its widgets one by one. wgtDestroy(w) takes a widget and everything under it out of the tree and frees them; wgtDestroyChildren(w) frees everything under w and keeps w, the way to rebuild a container’s contents.

Text you give a widget is copied: a caption, a text box’s text, a tree item’s text, an item added to a list with an add call. Some things are not copied, and must live as long as the widget uses them:

  • a tooltip’s text (wgtSetTooltip),

  • an array of items given to wgtListBoxSetItems, wgtDropdownSetItems, or wgtComboBoxSetItems (until the program adds or removes an item, when the widget makes its own copy first),

  • a ListView’s columns (wgtListViewSetColumns) and its cells (wgtListViewSetData, until the program adds, removes, or sets a cell, or the user drags a row, when it copies them).

A string literal or a static array lives long enough; an array on the stack does not. Everything a widget allocates is counted against your program and freed when it ends (Chapter 3).

5.1.3. The Fields You Use

A WidgetT has many fields. These are the ones a program touches:

Field What it is

x, y, w, h

The widget’s place and size in the window’s content, as the last layout computed them. Read them; never set them.

minW, minH, maxW, maxH

Size hints (Section 5.4); 0 is none.

weight

How much of a box’s extra room the widget takes (Section 5.4.2).

align, padding, spacing

A container’s arrangement of its children (Section 5.4.5).

fgColor, bgColor

Colors of the widget’s own (Section 5.13); 0 is the color scheme’s.

userData

A pointer of yours.

tooltip, contextMenu

Set with wgtSetTooltip; a menu for a right click (Chapter 6).

onClick, onChange, …​

The callbacks (Section 5.7).

visible, enabled, readOnly

Read them; change them with wgtSetVisible, wgtSetEnabled, and wgtSetReadOnly (Section 5.8).

name

A name for wgtFind; set it with wgtSetName.

wgtSetName(w, name) gives a widget a name of up to 31 characters (MAX_WIDGET_NAME is 32 with the NUL), and wgtFind(root, name) finds the first widget of that name under root, depth first. Most C programs keep the widgets they need in variables instead; names help when one routine builds a window and another, far away, needs a widget in it.

5.2. Widget Headers and Their APIs

Each kind of widget is a module of its own, a .wgt file in DVX’s WIDGETS folder, which DVX loads when it starts. A module publishes its functions as a table, a struct of function pointers it registers under a name, and its header gives you a typed accessor for the table and a macro for each function. button/button.h, for example, declares ButtonApiT, the accessor dvxButtonApi(), which asks wgtGetApi("button", sizeof(ButtonApiT)) for the table and keeps it, and the macro wgtButton(parent, text), which is dvxButtonApi()→create(parent, text). You call the macros as if they were functions.

The headers are in the SDK’s include/widget/<name>/ folders, and sdk.mk puts include/widget on the include path, so you write #include "button/button.h". Their names are DOS file names, eight characters at most, so some are shortened: textInpt.h, scrlPane.h, statBar.h, tabCtrl.h, separatr.h, progress.h, and imgBtn.h. dvxWgt.h declares WidgetT and the calls that work on every widget; every widget header includes it.

Widget Header Create

VBox, HBox, Frame

box/box.h

wgtVBox(p), wgtHBox(p), wgtFrame(p, title)

Label

label/label.h

wgtLabel(p, text)

Button

button/button.h

wgtButton(p, text)

TextInput, TextArea

textInput/textInpt.h

wgtTextInput(p, maxLen), wgtPasswordInput(p, maxLen), wgtMaskedInput(p, mask), wgtTextArea(p, maxLen)

Checkbox

checkbox/checkbox.h

wgtCheckbox(p, text)

Radio

radio/radio.h

wgtRadioGroup(p), wgtRadio(p, text)

ListBox

listBox/listBox.h

wgtListBox(p)

Dropdown

dropdown/dropdown.h

wgtDropdown(p)

ComboBox

comboBox/comboBox.h

wgtComboBox(p, maxLen)

ListView

listView/listView.h

wgtListView(p)

TreeView

treeView/treeView.h

wgtTreeView(p), wgtTreeItem(p, text)

Slider

slider/slider.h

wgtSlider(p, min, max)

Spinner

spinner/spinner.h

wgtSpinner(p, min, max, step)

ProgressBar

progressBar/progress.h

wgtProgressBar(p), wgtProgressBarV(p)

Image

image/image.h

wgtImage(p, data, w, h, pitch), wgtImageFromFile(p, path)

ImageButton

imageButton/imgBtn.h

wgtImageButton(p, data, w, h, pitch), wgtImageButtonFromFile(p, path)

Separator

separator/separatr.h

wgtSeparator(p), wgtHSeparator(p), wgtVSeparator(p)

Spacer

spacer/spacer.h

wgtSpacer(p)

ScrollPane

scrollPane/scrlPane.h

wgtScrollPane(p)

Splitter

splitter/splitter.h

wgtSplitter(p, vertical)

TabControl

tabControl/tabCtrl.h

wgtTabControl(p), wgtTabPage(p, title)

WrapBox

wrapBox/wrapBox.h

wgtWrapBox(p)

Toolbar

toolbar/toolbar.h

wgtToolbar(p)

StatusBar

statusBar/statBar.h

wgtStatusBar(p)

Other chapters cover the rest: the Canvas (Chapter 9), the Timer (Chapter 11), the Data control and DBGrid (Chapter 13), and the Terminal control (Chapter 15).

Every create call returns the new widget, or NULL when memory runs out. A create call cannot report that its widget is missing, though: the macro calls through the table without looking, and when no module registered the name, the table is NULL. wgtGetApi returns NULL when no loaded module registered the name, when the module was built for another DVX binary interface, or when its table is shorter than the header you compiled with (an older module); it logs the last two refusals in DVX.LOG. DVX’s own core widgets are loaded at start-up, and DVX does not start without one that it finds but cannot load. But the Terminal control, the Data control, and DBGrid are optional parts of DVX, which a user may not have installed; a widget from another vendor is an add-on, which DVX skips when it cannot load it; and DVX does not notice a widget file that is missing. So before you use a widget, call its accessor (dvx, the widget’s name, and Api: dvxListViewApi, dvxSplitterApi, and so on) and check for NULL:

// Each of these widgets comes with DVX, but a module can be missing or
// too old: its API is then NULL, and calling one of its macros would
// dereference NULL.
if (!dvxSplitterApi() || !dvxTreeViewApi() || !dvxListViewApi() || !dvxStatusBarApi()) {
    dvxErrorBox(ac, BROWSER_TITLE, BROWSER_NO_WIDGET);
    return -1;
}

Checking once, at the start, is enough: after that the accessor returns the same table.

5.3. Containers

A container is a widget that holds and arranges others. You add widgets to one by passing it as the parent. (The short fragments in this chapter use DEMO_ names for the defines a real program would have.)

VBox and HBox (wgtVBox, wgtHBox) are the workhorses: a VBox stacks its children top to bottom, an HBox puts them side by side, left to right. They draw nothing, unless you give one a background color. A window’s root is a VBox, and a form is usually a VBox of HBox rows. Section 5.4 gives the rules they follow.

A Frame (wgtFrame(parent, title)) is a VBox inside a grooved border, its title on the border’s top line: a group box. Its title can have an access key, which moves the focus to the first widget in the frame that takes it.

A RadioGroup (wgtRadioGroup) is a VBox that holds a set of radio buttons and knows which one is selected (Section 5.6.3).

A TabControl (wgtTabControl) shows one page at a time, with a row of tabs above it; wgtTabPage(tabs, title) adds a page, which is a VBox you fill like any other. The control is as large as its largest page. A page’s title can have an access key, which shows the page even while it is hidden. wgtTabControlSetActive(tabs, idx) shows page idx (from 0) and wgtTabControlGetActive says which one is shown; the control’s onChange fires when the user changes the page, not when the program does.

WidgetT *tabs     = wgtTabControl(root);
WidgetT *general  = wgtTabPage(tabs, "&General");
WidgetT *advanced = wgtTabPage(tabs, "&Advanced");

wgtCheckbox(general, "Show &hidden files");
wgtCheckbox(advanced, "Use &long names");
wgtTabControlSetActive(tabs, 0);

A ScrollPane (wgtScrollPane) shows more than fits: it stacks its children top to bottom, as a VBox does, and adds scroll bars when they need more room than it has. Give it one child, a VBox or HBox holding the rest, and it scrolls that. Unlike the boxes, it has no padding or spacing unless you set some. Its children are capped as a VBox’s are: a child with maxW is centered across the pane, and a maxH in percent is of the content’s height. Its onChange fires when the user scrolls it; wgtScrollPaneScrollToChild(pane, child) scrolls a child into view, and the wgtScrollPaneGet... and wgtScrollPaneSet... calls read and set the scroll position in pixels.

WidgetT *pane    = wgtScrollPane(root);
WidgetT *options = wgtVBox(pane);

for (int32_t i = 0; i < DEMO_OPTION_COUNT; i++) {
    char caption[DEMO_CAPTION_MAX];

    snprintf(caption, sizeof(caption), "Option %ld", (long)(i + 1));
    wgtCheckbox(options, caption);
}

A Splitter (wgtSplitter(parent, vertical)) divides its room between exactly two children, with a bar between them the user drags. With vertical true the bar is vertical and the children are side by side; with false they are one above the other. Each child fills its pane. wgtSplitterSetPos(split, pos) puts the bar pos pixels from the left (or top) edge, and wgtSplitterGetPos reads it; until you set it, it sits as close to the leading edge as the first child’s minimum width (or height) allows. The bar never makes a pane smaller than its child’s minimum, or than 20 pixels. The splitter’s onChange fires when the user drags the bar. The browser program below uses one.

A WrapBox (wgtWrapBox) lays its children out left to right, at their natural sizes, and starts a new row when the next one does not fit: tags, color swatches, a toolbar that wraps.

static const char *tags[] = { "Red", "Green", "Blue", "Cyan", "Magenta", "Yellow" };
WidgetT           *wrap   = wgtWrapBox(root);

for (int32_t i = 0; i < DVX_ARRAY_LEN(tags); i++) {
    wgtButton(wrap, tags[i]);
}

A Toolbar (wgtToolbar) and a StatusBar (wgtStatusBar) are HBoxes that look the part: a toolbar paints the window face behind a row of buttons, a status bar draws each child in a sunken panel. Chapter 6 builds both; browser has a status bar.

The window itself is the outermost container. When the root’s minimum size is larger than the window, DVX gives the window scroll bars and lays the tree out at its minimum size, so nothing is ever squeezed below its minimum; when the window grows again, the bars go.

5.4. How Layout Works

Layout runs in two passes over the tree. The first, bottom up, measures every widget’s minimum size. The second, top down, gives the root the window’s content area and lets each container divide its room among its children. Five things decide the result: each widget’s natural minimum, the minW, minH, maxW, and maxH hints, the weight of each child, each container’s padding, spacing, and align, and which widgets are visible. Hidden widgets take no room at all, and no gap.

5.4.1. Minimum Sizes

Each kind of widget knows its natural minimum: a label is as wide as its text and one line high, a button is its text plus 8 pixels a side, a text box is 8 characters wide, a list shows a few rows. A container’s minimum is the sum of its children’s minimums along its direction, plus the spacing between them and its padding at both ends, and the largest child’s minimum across it, plus its padding (a Frame adds its border and title).

minW and minH raise a minimum, never lower it. maxW and maxH cap the size: a widget is never laid out larger than its cap, and a cap below the minimum lowers the minimum to the cap. A hint of 0 means none.

5.4.2. Weight: Sharing the Extra Room

Along its direction, a box first gives every visible child its minimum. What is left over, the room beyond the minimums, the spacing, and the padding, goes to the children with a weight above 0, in proportion to their weights: a child’s share is the extra room times its weight divided by the sum of the weights. WGT_WEIGHT_FILL is 100, one ordinary share; 200 takes twice as much as 100.

WidgetT *row   = wgtHBox(root);
WidgetT *list  = wgtListBox(row);
WidgetT *notes = wgtTextArea(row, 0);

list->weight  = WGT_WEIGHT_FILL;        // one share of the extra width
notes->weight = 2 * WGT_WEIGHT_FILL;    // two shares

A widget’s weight starts at 0, so it stays at its minimum, except in the kinds that are usually meant to fill: text boxes and text areas, combo boxes, sliders, list views, tree views, splitters, scroll panes, tab controls, and spacers start at WGT_WEIGHT_FILL. Labels, buttons, check boxes, radio buttons, list boxes, drop-down lists, spinners, progress bars, images, and the boxes themselves start at 0: to make a list box or a nested box take the extra room, give it a weight.

A fixed width in a row is minW with weight 0: the widget gets exactly its minimum, and minW sets that minimum (if the widget’s natural minimum is smaller). That is how you make a column of labels line up, or two buttons the same width. On a weighted widget, minW is only a floor.

A weighted child with a cap along the box stops growing at its cap, and the room it cannot take goes to the other weighted children. When no child has weight, the extra room is not given to anyone: the box’s align decides where it goes (Section 5.4.5).

One exception: a single-line text box and a combo box are one line high, and they keep that height in a VBox whatever their weight. Their weight works along a row only.

5.4.3. Across a Box

Across its direction, a box gives every child its whole inner size: in a VBox every child is as wide as the box, and in an HBox every child is as tall as the row. A button in a VBox stretches across the window. To keep it narrower, put it in an HBox, where it keeps its minimum width, or cap it: a child with maxW in a VBox (or maxH in an HBox) is cut to the cap and centered across the box.

WidgetT *ok = wgtButton(root, "OK");

ok->maxW   = wgtChars(DEMO_BUTTON_COLS);    // no wider than that, centered
list->maxW = wgtPercent(DEMO_SIDE_PCT);     // in the row: at most that share of it

Widgets that are shorter than their row look right anyway: a label draws its text centered from top to bottom in whatever height it gets, so a label beside a taller text box lines up with the box’s text.

5.4.4. Size Units

A size hint is an int32_t that carries its unit in its top two bits. Make one with a macro:

Macro Size

wgtPixels(n)

n pixels.

wgtChars(n)

n times the character width of the widget’s font (its own, or its container’s: Section 5.13), so the size follows the font.

wgtPercent(n)

n percent of the parent’s inner size: minW and maxW of its inner width, minH and maxH of its inner height (and a ListView column’s width, a percentage of the list’s width). In padding and spacing, a percentage of the container’s own width.

A raw 0 is no hint. wgtResolveSize(size, parentSize, charWidth) turns a hint into pixels the way the layout does. Use wgtChars for anything that holds text, so the layout survives a larger font; use wgtPixels for gaps and for things measured in pixels, such as a picture.

Important
The minimums are measured before any parent’s size is known, so a percentage counts as 0 when the tree is measured: it never makes a widget’s minimum larger, nor a window that dvxFitWindow fits. It takes effect when the container lays its children out, and only out of the room the container has beyond its children’s minimums: padding first, then spacing, then the children’s percentage minimums, which shrink in proportion when they ask for more than there is. So a percentage never squeezes another widget below its minimum, nested percentages compose (50% of 50% is a quarter), and a resize works them out again. A child’s weight shares out what is left beyond its percentage minimum, and a maximum wins over a minimum. A WrapBox takes no padding or spacing in percent, and containers whose children fill them (TabControl pages, Splitter panes, the root) ignore a child’s percentage minimum.

5.4.5. Padding, Spacing, and Alignment

A container’s padding is the room inside it around its children, on every side; its spacing is the gap between one child and the next. Both are size hints, and both start at WGT_GAP_DEFAULT, which means the class’s own default; wgtPixels(0) means none.

Container Padding Spacing

VBox, HBox, RadioGroup, TabControl page, the root

4

4

Frame (inside its border)

4

0

WrapBox

2

4

Toolbar

2

2

StatusBar

1

2

ScrollPane

0

0

Boxes inside boxes add their padding up: a widget in an HBox row inside a Frame inside the root starts 4 + 2 + 4 + 4 pixels from the content area’s left edge (the root’s padding, the frame’s border and padding, the row’s padding). Rows inside a frame usually want padding = wgtPixels(0). wgtSetPaddingPx(w, size) and wgtSetSpacingPx(w, size) set the two, in pixels (from 0 to WGT_GAP_PIXELS_MAX, 4096) or as a wgtChars or wgtPercent size, and lay the window out again; wgtGetPaddingPx and wgtGetSpacingPx give the pixels the layout uses now, the class’s default included and a percentage worked out.

row->padding = wgtPixels(0);           // no margin inside the row
row->spacing = wgtPixels(DEMO_GAP);    // the gap between its children
root->align  = AlignCenterE;           // the root's fixed-size children centered top to bottom

A box’s align, AlignStartE (the default), AlignCenterE, or AlignEndE, places its children along its direction when none of them has weight, and does nothing when one has: the weighted children take all the room. In an HBox, AlignEndE pushes a row of buttons to the right. To push some children one way and some the other, put a Spacer (wgtSpacer) between them: it draws nothing and has weight WGT_WEIGHT_FILL, so it takes the extra room.

WidgetT *buttons = wgtHBox(root);

wgtButton(buttons, "&Help");
wgtSpacer(buttons);                    // takes the extra width
wgtButton(buttons, "OK");
wgtButton(buttons, "Cancel");

5.4.6. When the Layout Runs

Creating a widget does not measure anything at once. It marks its window’s tree as not measured, and the window’s next full paint measures such a tree, scroll bars included, before it lays it out; so a window you build and leave at the size you created it comes out right without a call. The tree is also measured by wgtInvalidate(w), by the window fit calls, and when the window changes size. To size the window to its widgets, or to read the widgets' geometry before the first paint, measure them yourself, with one of these:

  • dvxFitWindow(ctx, win) measures the tree and makes the window exactly as large as it needs (never smaller than the window manager’s minimum); dvxFitWindowH fits only the height and dvxFitWindowW only the width. Use them for forms and dialogs.

  • wgtInvalidate(root) measures the tree and lays it out at the window’s present size, adding or removing the window’s scroll bars as needed, at once.

wgtInvalidate(w) works on the whole window of w, whichever widget you pass. It measures and lays out at once, so the geometry is right when it returns, and asks for a full repaint, which happens once, at the end of the frame, however many changes came before it. wgtInvalidatePaint(w) only asks for w to be painted again, for changes that do not affect any size, such as a color.

Many calls lay the window out again themselves: wgtSetText (when the text changes), wgtSetVisible, wgtSetFont, wgtSetPaddingPx and wgtSetSpacingPx, wgtSplitterSetPos, wgtLabelSetWordWrap, wgtListViewSetColumns, and the list calls that change how wide the list’s widest item is. Writing a field does not. After you change minW, maxW, weight, padding, spacing, or align on a window that is showing, call wgtInvalidate; after fgColor or bgColor, wgtInvalidatePaint. To rebuild part of a window, empty a container and fill it again:

wgtDestroyChildren(results);     // empty the box
wgtLabel(results, "No matches.");
wgtInvalidate(results);          // measure and lay out again

When a layout does not come out as you meant, wgtSetDebugLayout(ctx, true) outlines every container in every window in a bright color of its own, so you can see which box is where and how large. wgtGetDebugLayout says whether it is on.

5.5. A Data-Entry Form

The first program is a sign-up form: an Account frame of four text boxes, a Details frame with a spinner and a drop-down list, a Plan frame of radio buttons with a Company row that only one plan shows, a check box that enables the Sign Up button, and a line where the program says what to fix. It uses most of the rules above, and shows how a C program checks what the user typed.

The Sign Up form with the Account, Details, and Plan frames, the terms check box, and the Sign Up and Cancel buttons
Figure 6. Sign Up as it starts

The program is in the signup folder of the examples. Its includes are the widget headers it uses:

#include "dvxApp.h"
#include "dvxDlg.h"
#include "dvxWgt.h"
#include "shellApp.h"
#include "box/box.h"
#include "button/button.h"
#include "checkbox/checkbox.h"
#include "dropdown/dropdown.h"
#include "label/label.h"
#include "radio/radio.h"
#include "spinner/spinner.h"
#include "textInput/textInpt.h"

5.5.1. The Form’s Widgets

A program needs to reach some of its widgets again: to read a text box, to enable a button, to show a row. signup keeps them in one struct. The plans are an enum, so that the radio buttons' order and the program’s names for them cannot disagree, and the countries are a static array, because a drop-down list keeps the pointer it is given.

// The plans, in the order of their radio buttons
typedef enum {
    PlanIndividualE,
    PlanStudentE,
    PlanBusinessE
} PlanE;

// The widgets the program reads or changes after building them
typedef struct {
    WidgetT *name;
    WidgetT *email;
    WidgetT *password;
    WidgetT *confirm;
    WidgetT *age;
    WidgetT *country;
    WidgetT *plan;      // the radio group
    WidgetT *company;   // its row is shown for the Business plan only
    WidgetT *agree;
    WidgetT *message;   // the label that explains what to fix
    WidgetT *signUp;
} SignupFormT;

// The drop-down list keeps a pointer to its items: they must outlive it.
static const char *sCountries[] = {
    "Australia",
    "Canada",
    "Germany",
    "Japan",
    "United Kingdom",
    "United States"
};

static const char *sPlans[] = {
    "&Individual",
    "&Student",
    "&Business"
};

static DxeAppContextT *sCtx = NULL;
static WindowT        *sWin = NULL;
static SignupFormT     sForm;

Every number the layout uses has a name:

#define SIGNUP_TITLE         "Sign Up"
#define SIGNUP_WIN_W         360
#define SIGNUP_WIN_H         420       // a first guess: dvxFitWindowH sets the height
#define SIGNUP_LABEL_COLS    10        // the label column, in characters
#define SIGNUP_BUTTON_COLS   10        // the width both buttons share, in characters
#define SIGNUP_ROW_GAP       2         // pixels between the rows of a frame
#define SIGNUP_NAME_MAX      40        // characters each text box holds
#define SIGNUP_EMAIL_MAX     60
#define SIGNUP_PASSWORD_MAX  32
#define SIGNUP_COMPANY_MAX   40
#define SIGNUP_PASSWORD_MIN  6
#define SIGNUP_AGE_MIN       13
#define SIGNUP_AGE_MAX       120
#define SIGNUP_AGE_STEP      1
#define SIGNUP_ERROR_RGB     0xB00000  // the message's color, 0xRRGGBB
#define SIGNUP_SUMMARY_MAX   256

// A number as a string literal, so a message can quote a limit
#define SIGNUP_STR(x)        #x
#define SIGNUP_XSTR(x)       SIGNUP_STR(x)

#define SIGNUP_PASSWORD_TIP  "At least " SIGNUP_XSTR(SIGNUP_PASSWORD_MIN) " characters"

5.5.2. A Column of Labels

A form’s labels should make a column, and its fields should start at the same place on every row. addRow makes an HBox row with a label in it and gives the label a minimum width in characters. A label’s weight is 0, so every label is exactly that wide, and the field the caller adds next starts at the same x on every row. The row’s padding is set to none, so the frame’s padding is the only margin.

// One row of a form: a label in the label column, then the field the
// caller adds.  The label's minimum width makes the column (a label's
// weight is 0, so it never grows past it); the row has no padding of its
// own, so the frame's padding is the only margin.  NULL when out of
// memory.
static WidgetT *addRow(WidgetT *parent, const char *caption) {
    WidgetT *row   = wgtHBox(parent);
    WidgetT *label = row ? wgtLabel(row, caption) : NULL;

    if (!label) {
        return NULL;
    }

    row->padding = wgtPixels(0);
    label->minW  = wgtChars(SIGNUP_LABEL_COLS);
    return row;
}


// A labeled text box (a password box when password is true) whose edits
// clear the message.  A text box's weight is WGT_WEIGHT_FILL, so it takes
// the rest of the row.
static WidgetT *addTextField(WidgetT *parent, const char *caption, int32_t maxLen, bool password) {
    WidgetT *row   = addRow(parent, caption);
    WidgetT *field = NULL;

    if (row) {
        field = password ? wgtPasswordInput(row, maxLen) : wgtTextInput(row, maxLen);
    }

    if (field) {
        field->onChange = onFieldChange;
    }

    return field;
}

addTextField adds a text box to a row. A text box’s weight is WGT_WEIGHT_FILL, so it takes the rest of the row, and grows when the user makes the window wider. Each text box gets the same onChange handler, which clears the message line (Section 5.5.6). Both routines check every create call, and a caller that gets NULL gives up; the label’s & is its access key (Section 5.10), which moves the focus to the field after it.

5.5.3. Frames and Fields

The Account frame is four rows. A frame packs its children with no gap, so buildAccount gives it a little spacing. The password box shows a tooltip when the mouse rests on it; its text is a string literal, which outlives the widget, as a tooltip’s text must.

// The Account frame: four text boxes beside a column of labels.  True
// when every field was made.
static bool buildAccount(WidgetT *root) {
    WidgetT *frame = wgtFrame(root, "Account");

    if (!frame) {
        return false;
    }

    frame->spacing = wgtPixels(SIGNUP_ROW_GAP);
    sForm.name     = addTextField(frame, "&Name:", SIGNUP_NAME_MAX, false);
    sForm.email    = addTextField(frame, "&E-mail:", SIGNUP_EMAIL_MAX, false);
    sForm.password = addTextField(frame, "&Password:", SIGNUP_PASSWORD_MAX, true);
    sForm.confirm  = addTextField(frame, "&Confirm:", SIGNUP_PASSWORD_MAX, true);

    // The tooltip's text is not copied: a string literal lives forever
    wgtSetTooltip(sForm.password, SIGNUP_PASSWORD_TIP);
    return sForm.name && sForm.email && sForm.password && sForm.confirm;
}

The Details frame holds a spinner and a drop-down list. Both have weight 0, so each is only as wide as it needs to be: a spinner wide enough for six digits and its arrows, a drop-down list as wide as its longest item. A spinner starts at its lowest value and keeps its value between its limits however the user types, so the program never needs to check the age. A drop-down list starts with nothing selected.

// The Details frame: a spinner and a drop-down list, each as wide as it
// needs (their weight is 0), not as wide as the row.
static bool buildDetails(WidgetT *root) {
    WidgetT *frame      = wgtFrame(root, "Details");
    WidgetT *ageRow     = frame ? addRow(frame, "&Age:") : NULL;
    WidgetT *countryRow = frame ? addRow(frame, "C&ountry:") : NULL;

    if (!ageRow || !countryRow) {
        return false;
    }

    frame->spacing = wgtPixels(SIGNUP_ROW_GAP);
    sForm.age      = wgtSpinner(ageRow, SIGNUP_AGE_MIN, SIGNUP_AGE_MAX, SIGNUP_AGE_STEP);
    sForm.country  = wgtDropdown(countryRow);

    if (!sForm.age || !sForm.country) {
        return false;
    }

    sForm.country->onChange = onFieldChange;
    wgtDropdownSetItems(sForm.country, sCountries, DVX_ARRAY_LEN(sCountries));
    return true;
}

5.5.4. Showing a Row Only When Needed

The Plan frame holds a radio group of three buttons and, under it, a Company row. A new radio group has its first button selected. addTextField returns the text box, whose parent is its row, so the program hides the row, label and all, through the field. A hidden widget takes no room, no gap, and no focus, and its access key does nothing.

// The Plan frame: a radio group, then a Company row that only the
// Business plan shows.  A new radio group has its first button selected.
static bool buildPlan(WidgetT *root) {
    WidgetT *frame = wgtFrame(root, "Plan");
    WidgetT *group = frame ? wgtRadioGroup(frame) : NULL;

    if (!group) {
        return false;
    }

    for (int32_t i = 0; i < DVX_ARRAY_LEN(sPlans); i++) {
        if (!wgtRadio(group, sPlans[i])) {
            return false;
        }
    }

    frame->spacing = wgtPixels(SIGNUP_ROW_GAP);
    sForm.plan     = group;
    sForm.company  = addTextField(frame, "Co&mpany:", SIGNUP_COMPANY_MAX, false);

    if (!sForm.company) {
        return false;
    }

    // A user's choice fires onChange on the group, not on the button
    group->onChange = onPlanChange;

    // The row is the field's parent: hiding it hides the label too
    wgtSetVisible(sForm.company->parent, false);
    return true;
}

When the user picks a plan, the group’s onChange fires (the group’s, not the button’s). onPlanChange shows the row for the Business plan and hides it for the others. wgtSetVisible lays the window out again, and dvxFitWindowH then makes the window as tall as the form now is, so the window grows by a row instead of growing scroll bars.

// Shows the Company row for the Business plan only.  wgtSetVisible lays
// the window out again; dvxFitWindowH then makes the window as tall as
// the form now is.
static void onPlanChange(WidgetT *w) {
    wgtSetVisible(sForm.company->parent, wgtRadioGroupGetSelected(w) == PlanBusinessE);
    dvxFitWindowH(sCtx->shellCtx, sWin);
}
The Sign Up form with Business chosen and a Company box under the plans
Figure 7. Sign Up with the Business plan chosen: the Company row is shown and the window has grown to fit it

5.5.5. The Buttons

The footer is the check box, the message line, and an HBox with the two buttons. The row’s align is AlignEndE: neither button has weight, so the row’s extra width goes before them and they sit at the right. Both get the same minW in characters, which makes them the same width.

// Under the frames: the check box, the message line, and the buttons,
// which share one width and sit at the right end of their row.
static bool buildFooter(WidgetT *root) {
    WidgetT *row    = NULL;
    WidgetT *cancel = NULL;

    sForm.agree   = wgtCheckbox(root, "I agree to the &terms of service");
    sForm.message = wgtLabel(root, "");
    row           = wgtHBox(root);

    if (row) {
        sForm.signUp = wgtButton(row, "Sign &Up");
        cancel       = wgtButton(row, "Cancel");
    }

    if (!sForm.agree || !sForm.message || !sForm.signUp || !cancel) {
        return false;
    }

    sForm.agree->onChange  = onAgreeChange;
    sForm.message->fgColor = WGT_COLOR_SET | SIGNUP_ERROR_RGB;
    row->align             = AlignEndE;
    sForm.signUp->minW     = wgtChars(SIGNUP_BUTTON_COLS);
    sForm.signUp->onClick  = onSignUpClick;
    cancel->minW           = wgtChars(SIGNUP_BUTTON_COLS);
    cancel->onClick        = onCancelClick;

    // Enter presses Sign Up, Esc presses Cancel; a disabled button is not
    // pressed, so Enter does nothing until the terms are accepted
    dvxSetWindowButtons(sWin, sForm.signUp, cancel);
    wgtSetEnabled(sForm.signUp, false);
    return true;
}

The message label is empty to start with. An empty label is one line high, so the form does not jump when a message appears. Its fgColor makes the text red: a widget color is 0xRRGGBB with WGT_COLOR_SET (Section 5.13).

dvxSetWindowButtons(win, defaultBtn, cancelBtn) gives the window a default and a cancel button, as a dialog box has: Enter presses Sign Up unless the focused widget uses Enter itself (a button presses itself, a text area starts a new line), and Esc presses Cancel. Sign Up starts disabled. A disabled button ignores the mouse, Enter, and its access key, so the user cannot sign up before accepting the terms. The check box enables it:

// Accepting the terms enables Sign Up; a disabled button ignores the
// mouse, Enter, and its access key.
static void onAgreeChange(WidgetT *w) {
    wgtSetEnabled(sForm.signUp, wgtCheckboxIsChecked(w));
}

5.5.6. Checking the Fields

When the user chooses Sign Up, validate checks the fields in the order they appear on the form, so the first one that is wrong is the one the user is sent to. rejectField puts the message in the message line and moves the focus to the field, where the user can fix it at once.

// Shows message, puts the focus on the field to fix, and returns false
// for validate to return.
static bool rejectField(WidgetT *field, const char *message) {
    wgtSetText(sForm.message, message);
    wgtSetFocused(field);
    return false;
}


// Checks the fields in the order they are on the form, so the first one
// that is wrong is the one the user is sent to.  The spinner needs no
// check: it keeps its value between SIGNUP_AGE_MIN and SIGNUP_AGE_MAX.
static bool validate(void) {
    const char *password = wgtGetText(sForm.password);

    if (wgtGetText(sForm.name)[0] == '\0') {
        return rejectField(sForm.name, "Enter your name.");
    }

    if (!isEmailLike(wgtGetText(sForm.email))) {
        return rejectField(sForm.email, "Enter an e-mail address, such as name@example.com.");
    }

    if ((int32_t)strlen(password) < SIGNUP_PASSWORD_MIN) {
        return rejectField(sForm.password, "The password needs at least " SIGNUP_XSTR(SIGNUP_PASSWORD_MIN) " characters.");
    }

    if (strcmp(password, wgtGetText(sForm.confirm)) != 0) {
        return rejectField(sForm.confirm, "The two passwords are not the same.");
    }

    if (wgtDropdownGetSelected(sForm.country) < 0) {
        return rejectField(sForm.country, "Choose a country.");
    }

    if (wgtRadioGroupGetSelected(sForm.plan) == PlanBusinessE && wgtGetText(sForm.company)[0] == '\0') {
        return rejectField(sForm.company, "Enter the name of your company.");
    }

    return true;
}

wgtGetText reads a text box, and never returns NULL: a widget with no text gives "". A password box gives what the user typed, not the bullets it shows. The string belongs to the widget and stays valid until the widget’s text changes. The e-mail check is deliberately light:

// A light check, not the e-mail standard: something before the '@', and
// after it a '.' with something on both sides.
static bool isEmailLike(const char *text) {
    const char *at  = strchr(text, '@');
    const char *dot = at ? strrchr(at, '.') : NULL;

    return at && at > text && dot && dot > at + 1 && dot[1] != '\0';
}

Every edit clears the message, so the old complaint goes away as soon as the user starts fixing it. Setting a label to the text it already has costs nothing, so the handler does not test first:

// Any change to a field clears the message.  wgtSetText returns at once
// when a label already shows the text, so this costs nothing after the
// first key.
static void onFieldChange(WidgetT *w) {
    (void)w;
    wgtSetText(sForm.message, "");
}

When everything is right, the program greets the user in a message box and closes its window, which ends it:

static void onSignUpClick(WidgetT *w) {
    char summary[SIGNUP_SUMMARY_MAX];

    (void)w;

    if (!validate()) {
        return;
    }

    snprintf(summary, sizeof(summary), "Welcome, %s.\n\nWe will write to you at %s.", wgtGetText(sForm.name), wgtGetText(sForm.email));
    dvxInfoBox(sCtx->shellCtx, SIGNUP_TITLE, summary);
    closeWindow();
}

5.5.7. Putting It Together

appMain creates a resizable window, makes the widget root, and builds the four parts. Any part that fails ends the program cleanly. Last, dvxFitWindowH measures the finished tree and sets the window’s height to fit it; the width stays as created, and the text boxes take whatever width the user gives the window.

int32_t appMain(DxeAppContextT *ctx) {
    AppContextT *ac   = ctx->shellCtx;
    WidgetT     *root = NULL;

    sCtx = ctx;
    sWin = dvxCreateWindowCentered(ac, SIGNUP_TITLE, SIGNUP_WIN_W, SIGNUP_WIN_H, true);

    if (!sWin) {
        return -1;
    }

    sWin->onClose = onClose;
    root          = wgtInitWindow(ac, sWin);

    if (!root || !buildAccount(root) || !buildDetails(root) || !buildPlan(root) || !buildFooter(root)) {
        closeWindow();
        return -1;
    }

    // Measure the finished tree, then make the window as tall as it needs
    dvxFitWindowH(ac, sWin);
    return 0;
}

The program never sets the focus at the start: when a window is first painted, DVX gives the focus to its first widget that takes it, here the Name box. Build it with make, install it, and try the keys: Tab through the fields, Alt+P to the password, Alt+B for the Business plan, Alt+T to accept the terms, Enter to sign up, and Esc to leave.

5.6. The Common Widgets

This section is a tour of the widgets most programs use: what each one is for, how to read and set its value, and the events it fires. The full API of each is in the DVX C Library Reference (“Label” in the DVX C Library Reference and the sections around it).

Two calls work on every widget that has text: wgtSetText(w, text) copies the text in, and wgtGetText(w) returns it, or "". For a label, a button, a check box, a radio button, a frame, and a tab page the text is the caption; for a text box, a text area, and a combo box it is the contents; for a tree item it is the item’s text.

5.6.1. Labels and Buttons

A Label (wgtLabel(parent, text)) shows text the user cannot change: one line, as wide as its text, centered from top to bottom in the height it is given. wgtLabelSetAlign(w, align) places the text in a label wider than it: AlignStartE (the default) at the left, AlignCenterE, or AlignEndE at the right. wgtLabelSetWordWrap(w, true) makes a label wrap its text at its minW and grow as tall as its lines; without a minW it stays one line. A label does not take the focus, but its access key moves the focus to the next widget that does.

A Button (wgtButton(parent, text)) fires onClick when the user presses and releases the mouse over it (moving off before the release cancels the click), presses Space or Enter while it has the focus, or types its access key.

5.6.2. Text Boxes

The textInput module makes four kinds of text box:

  • wgtTextInput(parent, maxLen), one line holding up to maxLen characters (0 is 256, and at most 32,767).

  • wgtPasswordInput(parent, maxLen), the same, but it shows a bullet for each character and refuses to copy or cut.

  • wgtMaskedInput(parent, mask), a box of fixed shape: in the mask, takes a digit, A a letter, * any printable character, and anything else is shown as it is and skipped. "() -###" makes a telephone number. Its text is always the whole shape, an empty place shown as _.

  • wgtTextArea(parent, maxLen), many lines, with scroll bars, holding up to maxLen characters (0 is TEXTAREA_DEFAULT_MAX_LEN, 65,536, and at most 262,144). It is a full editor: find and replace, line numbers, line markers, syntax colors (“TextInput / TextArea” in the DVX C Library Reference).

All four fire onChange at every edit, and none fires it when the program sets the text. They start with weight WGT_WEIGHT_FILL. In a window with a default button, Enter in a one-line box presses that button; in a text area it starts a new line. Tab moves the focus on out of a text area too, unless wgtTextAreaSetCaptureTabs(w, true) makes it insert a tab. wgtSetReadOnly(w, true) lets the user select and copy but not change the text. The selection and clipboard calls (wgtTextInputGetSelText, wgtTextInputCopy, and the others) work on every kind, and a text area has them under its own names too (wgtTextAreaGetSelText, wgtTextAreaCopy, wgtTextAreaUndo, …​), with wgtTextAreaAppendText to add text at the end and wgtTextAreaGetCursorCol beside wgtTextAreaGetCursorLine.

WidgetT *notes = wgtTextArea(root, DEMO_NOTES_MAX);   // up to that many characters

wgtSetText(notes, "First line\nSecond line");
wgtTextAreaSetShowLineNumbers(notes, true);

5.6.3. Check Boxes and Radio Buttons

A Checkbox (wgtCheckbox(parent, text)) is a choice of its own, on or off. wgtCheckboxIsChecked(w) reads it and wgtCheckboxSetChecked(w, checked) sets it without firing anything. A click, Space, or the access key toggles it and fires onChange, then onClick. Enter does not toggle it: in a window with a default button, Enter is the button’s.

A Radio button (wgtRadio(parent, text)) is one choice of several. Put a set of them in a radio group (wgtRadioGroup(parent)), a VBox that knows which one is selected: wgtRadioGroupGetSelected(group) gives its index, from 0 (-1 for a group with no buttons), and wgtRadioGroupSetSelected(group, idx) selects one without firing anything (an index below 0 selects none). A new group has its first button selected. When the user selects a button that was not selected, by clicking it, with the arrow keys, Space, or its access key, the group’s onChange fires, then the button’s onClick. Tab stops at each button of a group.

A radio group is always a column. For a row of radio buttons, put them in an HBox: radio buttons in any other container form a group with their radio siblings, and wgtRadioGroupGetSelected(row) works on the row too. Such a set starts with none selected (the call gives -1), and the user’s choice fires the chosen button’s onChange, as there is no group.

WidgetT *align = wgtHBox(root);

wgtRadio(align, "&Left");
wgtRadio(align, "&Center");
wgtRadio(align, "&Right");
wgtRadioSetSelected(align->firstChild, true);
// ... later: wgtRadioGroupGetSelected(align) is 0, 1, 2, or -1

5.6.4. Lists: ListBox, Dropdown, and ComboBox

A ListBox (wgtListBox(parent)) shows a column of items, with a scroll bar when they need one. Give it items either all at once from your own array, wgtListBoxSetItems(w, items, count), which keeps the pointer, or one at a time with wgtListBoxAddItem and wgtListBoxInsertItem, which copy the text. wgtListBoxGetSelected gives the selected item’s index, or -1; wgtListBoxSetSelected selects one and scrolls it into view; wgtListBoxGetItem and wgtListBoxGetItemCount read the items. A list box can let the user select several items, sort itself, show a check box before each item, carry a number with each item, and let the user drag items into a new order (“ListBox” in the DVX C Library Reference). Its weight starts at 0: give it a weight to make it take the room it has.

static const char *colors[] = { "Red", "Green", "Blue" };
WidgetT           *list     = wgtListBox(root);

wgtListBoxSetItems(list, colors, DVX_ARRAY_LEN(colors));  // keeps the pointer
wgtListBoxAddItem(list, "Cyan");      // copies: the list now owns copies of all four
wgtListBoxSetSelected(list, 0);

A Dropdown (wgtDropdown(parent)) shows the selected item and opens its list when clicked or on F4 or Alt+Down; the user can only choose an item. A ComboBox (wgtComboBox(parent, maxLen)) is a one-line text box with a list to fill it from: the user can type anything, and wgtGetText reads what is there. Both have the ListBox’s item calls, named wgtDropdown... and wgtComboBox.... A drop-down list starts with nothing selected; a combo box’s wgtComboBoxGetSelected is -1 when the text was typed rather than chosen.

The lists fire their events when the user picks, never when the program sets the selection. A pick that changes the selection fires onChange, then every pick fires onClick (a click on the item already selected fires onClick alone); a double click fires onDblClick, when the widget has one, instead of the second onClick. A ComboBox is different, as in Visual Basic: typing fires onChange, and picking from the list fires only onClick.

5.6.5. ListView and TreeView

A ListView (wgtListView(parent)) is a list of rows with several columns and a heading for each. wgtListViewSetColumns(w, cols, count) takes an array of ListViewColT, each a title, a width (a size hint, or 0 to fit the widest cell), and an alignment; wgtListViewSetData(w, cells, rowCount) takes the cells as one array of strings, row after row. The list keeps both pointers. Clicking a heading sorts the rows by that column and clicking it again reverses the order; dragging the border between two headings changes a column’s width. wgtListViewGetSelected gives the selected row and wgtListViewGetCell(w, row, col) a cell’s text. Rows are numbered as they are in your data, whatever order a sort shows them in.

A TreeView (wgtTreeView(parent)) shows items in a hierarchy the user opens and closes. wgtTreeItem(parent, text) adds an item under the tree or under another item. Each item is a widget, a child of its parent item, so userData, wgtGetText, wgtSetText, and wgtDestroy work on items as on any widget. wgtTreeViewGetSelected(tree) returns the current item, wgtTreeViewSetSelected(tree, item) makes an item current (opening the items above it), and wgtTreeItemSetExpanded(item, true) opens one.

The browser program below uses both, and explains their events.

5.6.6. Numbers: Slider, Spinner, and ProgressBar

A Slider (wgtSlider(parent, min, max)) chooses a whole number from a range by dragging a thumb along a horizontal track. wgtSliderGetValue and wgtSliderSetValue read and set it (the setter keeps it in the range); onChange fires when the user changes it. Its weight starts at WGT_WEIGHT_FILL.

A Spinner (wgtSpinner(parent, min, max, step)) is a number box with arrows. It starts at min. The user can type a number, which takes effect on Enter or when the focus leaves, step it with the arrows or the arrow keys, or page it; it never leaves its range. wgtSpinnerGetValue reads it, a number being typed included, and onChange fires when the value changes and as the user types. wgtSpinnerSetRealMode makes it a spinner of real numbers, with a number of decimals of your choice.

A ProgressBar (wgtProgressBar(parent), or wgtProgressBarV for one standing up) shows a value from 0 to 100; wgtProgressBarSetValue sets it. It fires no events. Its weight starts at 0, so in a row give it a weight to make it as long as the row. Chapter 11 uses one to show a long job’s progress.

5.6.7. Pictures, Lines, and Space

An Image (wgtImageFromFile(parent, path)) shows a picture from a file, in any format DVX reads (Chapter 9), or from pixels you already have (wgtImage). An ImageButton (wgtImageButtonFromFile) is a button with a picture instead of a caption, and fires onClick as a button does; toolbars are made of them.

A Separator is a line between groups of widgets: wgtSeparator(parent) draws a vertical line in a row and a horizontal one anywhere else; wgtHSeparator and wgtVSeparator choose. A Spacer (wgtSpacer) is empty room that takes the extra space (Section 5.4.5).

5.7. Widget Events

Every widget has the same set of callback fields. Set one to a function and the widget calls it; leave it NULL and nothing happens. They fire for a user’s action, and almost never for the program’s own calls: setting a value, a selection, or a text from code fires nothing, so your handlers never run because of your own setters. (The TreeView is the exception: wgtTreeViewSetSelected and wgtTreeItemSetSelected fire the tree’s onChange when they change the current item, and so does wgtTreeItemSetExpanded when closing an item moves the current item onto it.)

Callback Fires when

onClick(w)

A button or check box is clicked (on the release), a list item is picked, or another widget is clicked (after onMouseUp, released over it).

onDblClick(w)

The second press of a double click lands on the widget.

onChange(w)

The user changes the widget’s value: an edit, a toggle, a new selection, a scroll, a drag of a splitter’s bar.

onFocus(w), onBlur(w)

The widget gains or loses the keyboard focus.

onKeyDown(w, keyCode, shift)

A key goes down while the widget has the focus, before the widget acts on it.

onKeyPress(w, keyAscii)

A key with a character goes down, after onKeyDown and before the widget acts on it.

onKeyUp(w, keyCode, shift)

A key goes up while the widget has the focus.

onMouseDown, onMouseUp, onMouseMove (w, button, x, y)

A mouse button goes down or up over the widget, or the mouse moves over it; x and y are from the widget’s top-left corner. None of the mouse events fires for a press on a scroll bar or a list’s column heading (Section 8.10.1).

onScroll(w, delta)

The mouse wheel turns while the widget has the focus.

onEvent(w, name, args, argc)

The widget fires a named event that has no field of its own (below).

When one action fires several, the order is fixed. A pick in a list fires onChange (if the selection changed), then onClick; a check box fires onChange, then onClick; a radio button fires its group’s onChange, then its own onClick. A key goes to onKeyDown and onKeyPress before the widget sees it, and a handler can change it or cancel it with wgtKeyReplace(key) (0 cancels). Chapter 8 covers the keys and the mouse in detail.

Some widgets have events of their own that no field covers: a ListView’s ItemClick and ColumnClick, a TreeView’s NodeClick, Expand, and Collapse, a Dropdown’s DropDown. They go to onEvent with their name and their arguments as WgtValueT values (Section 5.12); each widget’s section in the reference lists its events and their arguments.

The onValidate field belongs to the Data control, which calls it before it leaves or writes a record (Chapter 13); other widgets never call it.

A callback may change anything, destroy widgets included, even the widget it was called for, or close the window: DVX notices and stops dispatching to widgets that are gone. Do not touch a widget after your own code destroyed it, though, and do not keep pointers to destroyed widgets.

5.8. Enabling, Hiding, and Read-Only

wgtSetEnabled(w, false) disables a widget: it ignores the mouse and the keys, takes no focus, and its access key does nothing. Most widgets draw themselves grayed. Disabling a container disables everything in it, for input, for the focus, and to the eye: the widgets inside paint grayed, as in Windows Forms (Visual Basic 6 leaves them looking enabled). Each widget’s own enabled flag stays as it was, so enabling the container brings back the ones that were enabled. A disabled window grays its widgets the same way (Section 4.7). Disabling the widget that has the focus takes the focus away. A disabled widget keeps its place in the layout.

wgtSetVisible(w, false) hides a widget and everything in it: it takes no room and no gap, the window is laid out again at once, and its access keys are ignored. Hiding the widget that has the focus, or a container holding it, takes the focus away. wgtSetVisible(w, true) shows it again.

wgtSetReadOnly(w, true) is for text: the user can scroll, select, and copy, but not change it.

All three do nothing when the widget is already in that state, so set them without testing first: wgtSetEnabled(save, changed).

5.9. Focus and Tab Order

One widget at a time has the keyboard focus, in the window that has the focus. wgtGetFocused() returns it (or NULL) and wgtSetFocused(w) moves it to w, unless w is disabled or hidden or inside a disabled or hidden container. A focus change fires the old widget’s onBlur and the new one’s onFocus.

You rarely need to set the focus at the start. The first time a window is painted with the focus, DVX gives it to the first widget, in tree order, that takes the focus; when the window loses the focus and gets it back, the widget that had it gets it again.

Tab moves the focus to the next widget that takes it, and Shift+Tab to the previous one, in tree order, depth first, skipping disabled and hidden widgets, and wrapping at the end. The tab order is therefore the order you create widgets in: build a form top to bottom and left to right, and Tab goes through it in that order. When the window has scroll bars, Tab scrolls the widget it moves to into view.

Widgets that take the focus are buttons, image buttons, check boxes, radio buttons, text boxes and text areas, list boxes, drop-down lists, combo boxes, list views, tree views, sliders, spinners, and tab controls. Labels, frames, boxes, images, separators, spacers, progress bars, toolbars, and status bars do not.

A widget can keep Tab for itself: set its swallowTab field, or, for a text area, call wgtTextAreaSetCaptureTabs(w, true). A window whose only focusable widget is the focused one also hands it Tab as a key.

5.10. Access Keys

An & in a caption marks the next character as the widget’s access key: it is drawn underlined, and Alt with that letter acts on the widget, in either case. && is a plain &. Labels, buttons, check boxes, radio buttons, frames, and tab pages take one in their caption; the widget’s accelKey field holds it, worked out from the text whenever the text is set.

What the key does depends on the widget:

  • A button is clicked, a check box toggled, and a radio button selected, with their events.

  • A label or a frame moves the focus to the next widget after it, in tree order, that takes the focus. That is how a text box or a list, which has no caption, gets an access key: create its label just before it.

  • A tab page’s key shows the page, even while it is hidden.

Alt and a letter goes first to the window’s menu bar, then to the window’s widgets, the first enabled and visible widget in tree order with that key. So give each widget of a window, and each menu, a letter of its own. A window’s accelerator table and the keyboard shortcuts of menu items are something else, keys such as Ctrl+S that run a command (Chapter 6).

5.11. A Browser: TreeView, ListView, and Splitter

The second program is a parts browser: a tree of part categories on the left, a list of the parts in the chosen category on the right, a bar between them the user can drag, and a status bar. The data is a few static arrays, so the program is all widgets.

The Parts Browser window, with Hardware and Electronics categories in a tree, Screws chosen, its parts in a list, and a status bar
Figure 8. The Parts Browser: a TreeView and a ListView in a splitter, with a status bar
#include "dvxApp.h"
#include "dvxDlg.h"
#include "dvxWgt.h"
#include "shellApp.h"
#include "box/box.h"
#include "label/label.h"
#include "listView/listView.h"
#include "splitter/splitter.h"
#include "statusBar/statBar.h"
#include "treeView/treeView.h"

5.11.1. The Data

A category is a name for its tree item and a flat array of cells, three to a row, which the ListView shows straight from the array. A group is a name and its categories.

// A category of parts: the text of its tree item and its rows, which the
// ListView shows straight from this static array (BROWSER_COLS cells a
// row, row after row).
typedef struct {
    const char  *name;
    const char **cells;
    int32_t      rowCount;
} CategoryT;

// A group of categories: a tree item with one item under it for each
typedef struct {
    const char *name;
    CategoryT  *categories;
    int32_t     count;
} GroupT;

// The ListView sorts a column of numbers by their values, so the
// quantities sort as numbers.
static const char *sScrewCells[] = {
    "Machine screw M3 x 8",   "250", "A1",
    "Machine screw M3 x 16",  "120", "A2",
    "Wood screw 4 x 20",      "300", "A3",
    "Sheet metal screw 8",     "75", "A4"
};

The ListView sorts a column in a numbers-first order: a cell that is a number sorts by its value, ahead of every cell that is not, and the others sort as text without regard to case; cells that compare equal keep their order. So the quantities sort as numbers with no help from the program, 75 before 250. The other categories are built the same way, and the groups list them:

static CategoryT sHardware[] = {
    { "Screws",      sScrewCells,     DVX_ARRAY_LEN(sScrewCells) / BROWSER_COLS },
    { "Nuts",        sNutCells,       DVX_ARRAY_LEN(sNutCells) / BROWSER_COLS },
    { "Washers",     sWasherCells,    DVX_ARRAY_LEN(sWasherCells) / BROWSER_COLS }
};

static CategoryT sElectronics[] = {
    { "Resistors",   sResistorCells,  DVX_ARRAY_LEN(sResistorCells) / BROWSER_COLS },
    { "Capacitors",  sCapacitorCells, DVX_ARRAY_LEN(sCapacitorCells) / BROWSER_COLS },
    { "LEDs",        sLedCells,       DVX_ARRAY_LEN(sLedCells) / BROWSER_COLS }
};

static GroupT sGroups[] = {
    { "Hardware",    sHardware,       DVX_ARRAY_LEN(sHardware) },
    { "Electronics", sElectronics,    DVX_ARRAY_LEN(sElectronics) }
};

5.11.2. The Splitter and Its Panes

The window’s root holds two things: a splitter, which has weight WGT_WEIGHT_FILL and so takes all of the root’s height that the status bar leaves, and the status bar. The splitter’s first child, the TreeView, is the left pane; its second, a VBox with a heading and the ListView, is the right one. appMain builds them, after checking that every widget it needs is there:

int32_t appMain(DxeAppContextT *ctx) {
    AppContextT *ac    = ctx->shellCtx;
    WidgetT     *root  = NULL;
    WidgetT     *split = NULL;
    WidgetT     *first = NULL;

    sCtx = ctx;

    // Each of these widgets comes with DVX, but a module can be missing or
    // too old: its API is then NULL, and calling one of its macros would
    // dereference NULL.
    if (!dvxSplitterApi() || !dvxTreeViewApi() || !dvxListViewApi() || !dvxStatusBarApi()) {
        dvxErrorBox(ac, BROWSER_TITLE, BROWSER_NO_WIDGET);
        return -1;
    }

    sWin = dvxCreateWindowCentered(ac, BROWSER_TITLE, BROWSER_WIN_W, BROWSER_WIN_H, true);

    if (!sWin) {
        return -1;
    }

    sWin->onClose = onClose;
    root          = wgtInitWindow(ac, sWin);
    split         = root ? wgtSplitter(root, true) : NULL;
    sTree         = split ? wgtTreeView(split) : NULL;
    first         = sTree ? buildTree(sTree) : NULL;

    if (!first || !buildList(split) || !buildStatusBar(root)) {
        closeWindow();
        return -1;
    }

    wgtSplitterSetPos(split, BROWSER_TREE_W);

    // Set onChange first: selecting the first category then fills the
    // list.  (A tree with nothing selected selects its first item when it
    // is laid out, but quietly: no onChange.)
    sTree->onChange = onTreeChange;
    wgtTreeViewSetSelected(sTree, first);

    // Measure and lay out the finished tree
    wgtInvalidate(root);
    return 0;
}

wgtSplitterSetPos puts the bar 150 pixels from the left. Without it, the bar would start as far left as the tree’s minimum width allows.

5.11.3. The Tree

buildTree adds an item for each group and, under it, one for each category. Each category’s item carries a pointer to its CategoryT in userData, so the handler can go from the item the user chose straight to its data. A group’s item carries none. Opening the groups shows their categories at the start.

// A tree item for each group and, under it, one for each of its
// categories, which carries the category in userData (a group's item
// carries none).  Returns the first category's item, NULL when out of
// memory.
static WidgetT *buildTree(WidgetT *tree) {
    WidgetT *first = NULL;

    for (int32_t g = 0; g < DVX_ARRAY_LEN(sGroups); g++) {
        WidgetT *group = wgtTreeItem(tree, sGroups[g].name);

        if (!group) {
            return NULL;
        }

        for (int32_t c = 0; c < sGroups[g].count; c++) {
            WidgetT *item = wgtTreeItem(group, sGroups[g].categories[c].name);

            if (!item) {
                return NULL;
            }

            item->userData = &sGroups[g].categories[c];

            if (!first) {
                first = item;
            }
        }

        wgtTreeItemSetExpanded(group, true);
    }

    return first;
}

The program sets the tree’s onChange only after building it, then makes the first category current with wgtTreeViewSetSelected, which fires onChange and so fills the list. Setting the selection from code fires onChange in a TreeView only; the other widgets' setters fire nothing. A tree with nothing selected selects its first item itself when it is laid out, but without firing onChange, so a program that leaves the start to the tree must fill its list some other way.

5.11.4. The List

The right pane is a VBox with no padding, so the list lines up with the tree. Its heading keeps its minimum height; the ListView, whose weight is WGT_WEIGHT_FILL, takes the rest of the pane.

// The splitter's second pane: a VBox holding a heading and the list.  The
// pane fills its side of the splitter; the list (a ListView's weight is
// WGT_WEIGHT_FILL) takes all of the pane the heading leaves.
static bool buildList(WidgetT *split) {
    WidgetT *pane = wgtVBox(split);

    if (!pane) {
        return false;
    }

    pane->padding = wgtPixels(0);
    sHeader       = wgtLabel(pane, "");
    sList         = wgtListView(pane);

    if (!sHeader || !sList) {
        return false;
    }

    wgtListViewSetColumns(sList, sColumns, BROWSER_COLS);
    sList->onChange   = onListChange;
    sList->onDblClick = onListDblClick;
    return true;
}

The columns are a static array, because the list keeps the pointer. The Part and Quantity columns are a number of characters wide, the quantities right-aligned, and the Bin column’s width is 0, as wide as its widest cell. A width can also be wgtPercent(n), a share of the list’s width.

// The ListView keeps a pointer to its columns too, so they are static.
static const ListViewColT sColumns[BROWSER_COLS] = {
    { "Part",     wgtChars(BROWSER_PART_CHARS), ListViewAlignLeftE  },
    { "Quantity", wgtChars(BROWSER_QTY_CHARS),  ListViewAlignRightE },
    { "Bin",      BROWSER_COL_AUTO,             ListViewAlignLeftE  }
};

5.11.5. The Status Bar

A status bar is an HBox that draws each child in a sunken panel. The left label has weight, so it stretches; the right one has a fixed width (minW with weight 0, its default) and right-aligned text, so the panel does not jump about as the count changes.

// A status bar is an HBox that draws each child in a sunken panel.  The
// left panel stretches; the right one keeps one width, its text against
// its right edge.
static bool buildStatusBar(WidgetT *root) {
    WidgetT *bar = wgtStatusBar(root);

    if (!bar) {
        return false;
    }

    sStatus = wgtLabel(bar, "");
    sCount  = wgtLabel(bar, "");

    if (!sStatus || !sCount) {
        return false;
    }

    sStatus->weight = WGT_WEIGHT_FILL;
    sCount->minW    = wgtChars(BROWSER_COUNT_CHARS);
    wgtLabelSetAlign(sCount, AlignEndE);
    return true;
}

5.11.6. Following the Selection

The tree’s onChange fires on the tree, not on the item, whenever the current item changes, by a click or by the keys. The handler asks the tree for its current item and shows that item’s category. wgtListViewSetData keeps the pointer, so it is given the static array itself; for a group’s item, which has no category, the list is emptied. The heading and count are formatted on the stack, because wgtSetText copies its text.

// The tree's current item changed: show its category.  A group's item
// has no category (userData NULL).
static void onTreeChange(WidgetT *w) {
    WidgetT *item = wgtTreeViewGetSelected(w);

    showCategory(item ? (const CategoryT *)item->userData : NULL);
}


// Puts category's parts in the list (none for NULL), the cursor on the
// first row.  wgtListViewSetData keeps the pointer it is given, not a
// copy: the static array outlives the list.
static void showCategory(const CategoryT *category) {
    char header[BROWSER_TEXT_MAX];
    char count[BROWSER_TEXT_MAX];

    if (category) {
        wgtListViewSetData(sList, category->cells, category->rowCount);
        snprintf(header, sizeof(header), "Parts in %s:", category->name);
        snprintf(count, sizeof(count), "%ld parts", (long)category->rowCount);
    } else {
        wgtListViewSetData(sList, NULL, 0);
        snprintf(header, sizeof(header), "Choose a category.");
        count[0] = '\0';
    }

    // New data keeps the cursor's row number when the new rows have one;
    // start at the top instead (in an empty list, 0 selects nothing)
    wgtListViewSetSelected(sList, 0);

    // wgtSetText copies the text: stack buffers are fine
    wgtSetText(sHeader, header);
    wgtSetText(sCount, count);
    showSelection();
}


// The status bar's left panel: the part under the list's cursor, if any
static void showSelection(void) {
    char    text[BROWSER_TEXT_MAX];
    int32_t row = wgtListViewGetSelected(sList);

    text[0] = '\0';

    if (row >= 0) {
        describePart(row, text, (int32_t)sizeof(text));
    }

    wgtSetText(sStatus, text);
}

New data alone keeps the list’s cursor at the same row number when the new data has that many rows, so showCategory puts it on the first row with wgtListViewSetSelected; in an empty list that selects nothing, and wgtListViewGetSelected returns -1. describePart formats a row. The row number is the row in the program’s data, whatever order the user sorted the list into, so it reads the cells with wgtListViewGetCell without any translation:

// One line about data row row of the list: the ListView numbers rows as
// they are in the data, whatever order a sort shows them in, so a row
// from wgtListViewGetSelected reads straight from wgtListViewGetCell.
static void describePart(int32_t row, char *out, int32_t outSize) {
    const char *part = wgtListViewGetCell(sList, row, BROWSER_COL_PART);
    int32_t     qty  = (int32_t)strtol(wgtListViewGetCell(sList, row, BROWSER_COL_QTY), NULL, 10);
    const char *bin  = wgtListViewGetCell(sList, row, BROWSER_COL_BIN);

    snprintf(out, (size_t)outSize, "%s: %ld in bin %s", part, (long)qty, bin);
}

The list’s own events update the status bar and answer a double click. The ListView fires onDblClick for a double click and also for Enter while it has the focus, and a double click fires it even on an empty list, so the handler checks that there is a row:

// The user moved the list's cursor (a click or the keys)
static void onListChange(WidgetT *w) {
    (void)w;
    showSelection();
}


// A double click on the list, or Enter while it has the focus: the part
// under the cursor, if the list has any (an empty list fires it too)
static void onListDblClick(WidgetT *w) {
    char    text[BROWSER_TEXT_MAX];
    int32_t row = wgtListViewGetSelected(w);

    if (row < 0) {
        return;
    }

    describePart(row, text, (int32_t)sizeof(text));
    dvxInfoBox(sCtx->shellCtx, BROWSER_TITLE, text);
}

Run it and drag the bar: both panes are laid out again as it moves, and neither gets smaller than its minimum. Click the Quantity heading twice to sort the parts both ways, and make the window larger: the tree and the list take all the new room, and the status bar stays at the bottom.

5.12. Properties by Name

Every widget module also describes its widget for DVX BASIC: its properties, methods, and events, by name. The same descriptions work from C, through four calls: wgtGetProp(w, name, &value) and wgtSetProp(w, name, &value) read and write a property, wgtCallMethod(w, name, args, argc, &result) calls a method, and wgtCreateByName(name, parent) creates a widget from its name. Values are WgtValueT, made with wgtValueInt, wgtValueBool, wgtValueStr, wgtValueFloat, or wgtValueDouble, and read with wgtValueToInt, wgtValueToBool, wgtValueToFloat, or wgtValueToText, which convert between types. The first three return false when the widget has no such property or method, or refuses the value; wgtCreateByName returns NULL for a name no widget has.

Use them for two things. One is a widget you have no header for, such as a control written in DVX BASIC (Chapter 19):

WidgetT  *box   = wgtCreateByName("ListBox", root);
WgtValueT item  = wgtValueStr("first");
WgtValueT count;

wgtCallMethod(box, "AddItem", &item, 1, NULL);
wgtCallMethod(box, "ListCount", NULL, 0, &count);   // count.i is 1

The other is a property the C header does not offer. A Slider’s C API sets its range only when it is created, for example, but its BASIC interface has Min and Max properties:

WidgetT  *volume = wgtSlider(root, 0, DEMO_VOLUME_MAX);
WgtValueT max    = wgtValueInt(DEMO_VOLUME_LOUDER);

if (!wgtSetProp(volume, "Max", &max)) {
    dvxLog("demo: Max refused");
}

The names are the ones in each widget’s "Properties (BASIC Interface)" and "Methods" tables in the reference, compared without regard to case. Only a widget’s own properties are there: the ones every BASIC control has, such as Enabled and Visible, belong to the BASIC run time, and from C you use wgtSetEnabled and the other calls of dvxWgt.h. A string a property or method returns belongs to the widget, and stays valid only until the next call on that widget; copy it to keep it.

5.13. Tooltips, Colors, and Fonts

wgtSetTooltip(w, text) gives a widget text that appears when the mouse rests on it; NULL takes it away. The widget keeps the pointer, so use a string that lives as long as the widget, such as a literal.

A widget’s fgColor and bgColor override the color scheme’s colors for its text and its background. A color is 0xRRGGBB with WGT_COLOR_SET; 0 means none, the scheme’s color (or, for a background, what the widget sits on), so black is WGT_COLOR_SET alone. A VBox or HBox with a bgColor fills its area, and the widgets on it that have no face of their own, such as labels and check boxes, show it. Call wgtInvalidatePaint(w) after changing a color on a widget that is showing.

wgtSetFont(w, family, size, style) gives a widget a font of its own, and the widgets inside it use it too unless they have their own; a NULL family goes back to the container’s. It lays the window out again, and returns false when memory runs out. Text boxes, combo boxes, and spinners edit by columns, so a proportional font set on them, or above them, is drawn as the system font.

WidgetT *title = wgtLabel(root, "Results");

if (!wgtSetFont(title, "DejaVu Sans", DEMO_TITLE_PX, FONT_STYLE_BOLD)) {
    dvxLog("demo: no memory for the font");
}

A size in wgtChars follows the widget’s font, which is the best reason to size text widgets in characters. Chapter 9 explains fonts and their families.

Chapter 6. Menus, Toolbars, and Shortcuts

A program with more than a few commands puts them in a menu bar, gives the common ones shortcut keys and toolbar buttons, and reports what it is doing in a status bar. DVX draws and runs the menus itself: the program builds them once, gives each command a number, and hears the number in one callback, onMenu, however the user chose the command. This chapter builds tinyedit, a small text editor with File, Edit, View, and Help menus, a toolbar, a context menu, shortcut keys, and a status bar, and shows how they all lead to one routine.

The menu calls are in dvxWm.h (building menus) and dvxApp.h (accelerator tables, context menus, and changing menus that may be open); the toolbar and status bar are widgets, in toolbar/toolbar.h and statusBar/statBar.h. The reference book has the full lists in “dvxWm.h — Layer 4: Window Manager” in the DVX C Library Reference, “dvxApp.h — Layer 5: Application API” in the DVX C Library Reference, “Toolbar” in the DVX C Library Reference, and “StatusBar” in the DVX C Library Reference.

6.1. The Example: TinyEdit

TinyEdit is one resizable window: a menu bar, a toolbar with New, Open, and Save buttons, a text area, and a status bar with a message panel and a panel that says whether the text has changes not saved. It opens and saves DOS text files, asks before throwing changes away, and enables Cut, Copy, and Paste only when they can do something. A right click in the text gives a context menu with the Edit commands. The project, tinyedit, holds tinyedit.c, tinyedit.res (the program’s icon and the three toolbar pictures), tinyedit.dhs (its help), and the four pictures, icon32.bmp, new.bmp, open.bmp, and save.bmp.

The TinyEdit window with a toolbar, a line of text with the word dog selected, the Edit menu open, and a status bar
Figure 9. TinyEdit with a word selected and its Edit menu open: Cut and Copy are enabled, Paste is not
The TinyEdit window with the View menu open, Toolbar and Status Bar checked, and the Tab Width submenu showing 2, 4, and 8 Spaces with 4 chosen
Figure 10. TinyEdit’s View menu: check items and the Tab Width submenu of radio items

Every command has a number, its command ID, used by everything that can run it: the menu item, the shortcut key, the toolbar button, and the context-menu item. TinyEdit defines them together:

// Command IDs, shared by the menus, the accelerator table, the toolbar,
// and the context menu.  A separator's ID is 0 and a submenu item's -1,
// so commands stay above both.
#define CMD_FILE_NEW           100
#define CMD_FILE_OPEN          101
#define CMD_FILE_SAVE          102
#define CMD_FILE_SAVE_AS       103
#define CMD_FILE_EXIT          104
#define CMD_EDIT_UNDO          200
#define CMD_EDIT_CUT           201
#define CMD_EDIT_COPY          202
#define CMD_EDIT_PASTE         203
#define CMD_EDIT_SELECT_ALL    204
#define CMD_VIEW_TOOLBAR       300
#define CMD_VIEW_STATUS_BAR    301
#define CMD_VIEW_LINE_NUMBERS  302
#define CMD_VIEW_TAB_FIRST     310  // one per sTabWidths entry, in order
#define CMD_HELP_CONTENTS      400
#define CMD_HELP_ABOUT         401

The IDs are yours to choose, and each window’s onMenu receives its own, so two windows may use the same numbers. Keep them above 0: a separator’s ID is 0 and the item that opens a submenu has -1, and the calls that find an item by ID (Section 6.5) would find those.

6.2. One Routine for Every Command

When the user chooses a menu item, DVX closes the menu and calls the window’s onMenu(win, id) with the item’s ID. A shortcut key from the window’s accelerator table (Section 6.7) and an item of a context menu shown over the window call the same onMenu. TinyEdit’s passes the ID on:

// Menu items, context-menu items, and accelerator keys all arrive here
// with their command IDs.
static void onMenu(WindowT *win, int32_t menuId) {
    (void)win;
    runCommand(menuId);
}

A toolbar button is a widget, whose onClick gets the button, not a number. TinyEdit stores each button’s command ID in the button’s userData when it makes it (Section 6.8), so one onClick serves them all:

// Every toolbar button: its command ID is in its userData.
static void onToolClick(WidgetT *w) {
    runCommand((int32_t)(intptr_t)w->userData);
}

runCommand is a switch on the ID. Most cases call a routine of their own; the Edit and View cases are explained in the sections that follow:

static void runCommand(int32_t cmd) {
    switch (cmd) {
        case CMD_FILE_NEW:
            newFile();
            break;

        case CMD_FILE_OPEN:
            openFile();
            break;

        case CMD_FILE_SAVE:
            saveFile();
            break;

        case CMD_FILE_SAVE_AS:
            saveAs();
            break;

        case CMD_FILE_EXIT:
            // As the close box does it: onClose asks about changes, and
            // the window may be gone when this returns
            dvxRequestWindowClose(sAc, sWin, WinCloseUserE);
            return;

        case CMD_EDIT_UNDO:
            wgtTextAreaUndo(sText);
            break;

        case CMD_EDIT_CUT:
            wgtTextAreaCut(sText);
            break;

        case CMD_EDIT_COPY:
            wgtTextAreaCopy(sText);
            break;

        case CMD_EDIT_PASTE:
            wgtTextAreaPaste(sText);
            break;

        case CMD_EDIT_SELECT_ALL:
            wgtTextAreaSelectAll(sText);
            break;

        // DVX has already turned a check item's mark on or off, and
        // checked a radio item (unchecking the others of its group)
        case CMD_VIEW_TOOLBAR:
            wgtSetVisible(sToolbar, wmMenuItemIsChecked(sWin->menuBar, cmd));
            break;

        case CMD_VIEW_STATUS_BAR:
            wgtSetVisible(sStatusBar, wmMenuItemIsChecked(sWin->menuBar, cmd));
            break;

        case CMD_VIEW_LINE_NUMBERS:
            wgtTextAreaSetShowLineNumbers(sText, wmMenuItemIsChecked(sWin->menuBar, cmd));
            break;

        case CMD_HELP_CONTENTS:
            shellOpenHelpFile(sAc, sCtx->helpFile, NULL);
            break;

        case CMD_HELP_ABOUT:
            dvxInfoBox(sAc, "About " TINYEDIT_TITLE, TINYEDIT_ABOUT_TEXT);
            break;

        default:
            // Tab Width's radio items
            if (cmd >= CMD_VIEW_TAB_FIRST && cmd < CMD_VIEW_TAB_FIRST + DVX_ARRAY_LEN(sTabWidths)) {
                wgtTextAreaSetTabWidth(sText, sTabWidths[cmd - CMD_VIEW_TAB_FIRST]);
            }
            break;
    }

    // A toolbar button takes the keyboard focus when it is clicked: give
    // it back to the text area
    wgtSetFocused(sText);
}

The last line is there for the toolbar. A toolbar button takes the keyboard focus when it is clicked, like any button, so after Save the user’s typing would go to the button; wgtSetFocused gives the focus back to the text area. File › Exit returns before it, since the window may be gone by then.

6.3. Building a Menu Bar

A window’s menu bar is made with wmAddMenuBar(win), which returns its MenuBarT (also in win→menuBar) and takes CHROME_MENU_HEIGHT (20) pixels from the top of the content area. A window has one menu bar; a second wmAddMenuBar replaces the first. Build the menu bar with the window, before wgtInitWindow as the SDK’s template does: wmAddMenuBar only changes the content area’s size, and lays nothing out again.

wmAddMenu(bar, label) adds a menu to the bar and returns its MenuT, and these fill a menu, in order:

Call Adds

wmAddMenuItem(menu, label, id)

An item that sends id to onMenu.

wmAddMenuCheckItem(menu, label, id, checked)

An item with a check mark that turns on and off (Section 6.4).

wmAddMenuRadioItem(menu, label, id, checked)

One of a group of items of which one is checked.

wmAddMenuSeparator(menu)

A line between groups of items.

wmAddSubMenu(menu, label)

An item that opens another menu, which it returns.

A label is copied into the item, at most 31 characters (MAX_MENU_LABEL is 32 with the NUL; a longer one is cut). An & marks the next letter as the access key: Alt+F opens &File, and N chooses &New in the open File menu. A tab character splits the label in two, and the part after the tab is drawn at the right edge of the menu: "&Save\tCtrl+S". That text is only text. It makes no key do anything; the shortcut itself is an accelerator (Section 6.7), a key a control handles, or one of DVX’s own keys, and the label only tells the user about it. dvxAccelFormat writes a key and its modifiers in the form menus use (Ctrl+Shift+S, F5), for a program whose keys can change.

The menu bar owns its menus, items, and submenus, and destroying the window frees them all. wmAddMenuBar, wmAddMenu, and wmAddSubMenu return NULL when memory runs out. The wmAdd* calls accept a NULL bar or menu and do nothing with it, so a chain of them needs no check after each call; a menu that could not be made simply has no items. TinyEdit builds its bar in one function, which checks once and fails as a whole:

// The menu bar.  A tab in a label starts the key text shown at the right;
// it is only text: the keys themselves are the accelerator table's (Ctrl+N,
// Ctrl+O, Ctrl+S), the text area's (the Edit keys), and DVX's (F1).
static bool buildMenus(void) {
    MenuBarT *bar  = wmAddMenuBar(sWin);
    MenuT    *file = bar ? wmAddMenu(bar, "&File") : NULL;
    MenuT    *edit = bar ? wmAddMenu(bar, "&Edit") : NULL;
    MenuT    *view = bar ? wmAddMenu(bar, "&View") : NULL;
    MenuT    *help = bar ? wmAddMenu(bar, "&Help") : NULL;

    if (!file || !edit || !view || !help) {
        return false;
    }

    wmAddMenuItem(file, "&New\tCtrl+N", CMD_FILE_NEW);
    wmAddMenuItem(file, "&Open...\tCtrl+O", CMD_FILE_OPEN);
    wmAddMenuItem(file, "&Save\tCtrl+S", CMD_FILE_SAVE);
    wmAddMenuItem(file, "Save &As...", CMD_FILE_SAVE_AS);
    wmAddMenuSeparator(file);
    wmAddMenuItem(file, "E&xit", CMD_FILE_EXIT);

    wmAddMenuItem(edit, "&Undo\tCtrl+Z", CMD_EDIT_UNDO);
    wmAddMenuSeparator(edit);
    wmAddMenuItem(edit, "Cu&t\tCtrl+X", CMD_EDIT_CUT);
    wmAddMenuItem(edit, "&Copy\tCtrl+C", CMD_EDIT_COPY);
    wmAddMenuItem(edit, "&Paste\tCtrl+V", CMD_EDIT_PASTE);
    wmAddMenuSeparator(edit);
    wmAddMenuItem(edit, "Select &All\tCtrl+A", CMD_EDIT_SELECT_ALL);

    wmAddMenuCheckItem(view, "&Toolbar", CMD_VIEW_TOOLBAR, true);
    wmAddMenuCheckItem(view, "&Status Bar", CMD_VIEW_STATUS_BAR, true);
    wmAddMenuCheckItem(view, "&Line Numbers", CMD_VIEW_LINE_NUMBERS, false);
    wmAddMenuSeparator(view);

    MenuT *tabs = wmAddSubMenu(view, "Tab &Width");

    if (!tabs) {
        return false;
    }

    for (int32_t i = 0; i < DVX_ARRAY_LEN(sTabWidths); i++) {
        char label[TINYEDIT_LABEL_MAX];

        snprintf(label, sizeof(label), "&%ld Spaces", (long)sTabWidths[i]);
        wmAddMenuRadioItem(tabs, label, CMD_VIEW_TAB_FIRST + i, sTabWidths[i] == TINYEDIT_TAB_DEFAULT);
    }

    wmAddMenuItem(help, "&Contents\tF1", CMD_HELP_CONTENTS);
    wmAddMenuSeparator(help);
    wmAddMenuItem(help, "&About " TINYEDIT_TITLE "...", CMD_HELP_ABOUT);
    return true;
}

6.3.1. Menus and the Keyboard

The keyboard reaches every menu without any code: Alt with a menu’s access key opens it, and F10 opens the first menu of the bar. In an open menu, Up and Down move the highlight, passing over separators, Enter chooses the highlighted item if it is enabled, an item’s access key chooses it at once (or opens its submenu), Right opens a submenu or the next menu of the bar, Left closes a submenu or opens the previous menu, and Esc closes one level. A letter that is no item’s access key opens the menu of the bar that has it. Alt with a letter, while a menu is open, closes the menu first, then opens the menu with that letter or, when no menu title has it, acts as the access key of the window’s control. While a menu is open it takes every other key; no control and no accelerator sees one.

Alt with a letter goes to the menu bar’s titles before the window’s controls: a menu titled &File makes Alt+F useless as a control’s access key in that window. Give controls letters the menu titles do not use.

6.4. Check Items, Radio Items, and Submenus

A check item shows a check mark when it is on. Choosing it turns the mark on or off, and DVX does that before it calls onMenu, so the handler reads the new state with wmMenuItemIsChecked(bar, id) and acts on it. A radio item is one of a group: radio items next to each other in one menu form a group, a separator or any other kind of item ends it, and choosing one checks it and unchecks the rest of the group, again before onMenu. To set a mark from code, use wmMenuItemSetChecked(bar, id, checked), which keeps a radio group to one check. A shortcut key or a toolbar button with the item’s ID does not change the mark: only choosing the item does.

wmAddSubMenu(menu, label) adds an item, with an arrow at its right, that opens another menu beside it, and returns that menu to fill like any other. Submenus can hold submenus. TinyEdit’s View menu has three check items and a Tab Width submenu of radio items, one for each width in sTabWidths:

    wmAddMenuCheckItem(view, "&Toolbar", CMD_VIEW_TOOLBAR, true);
    wmAddMenuCheckItem(view, "&Status Bar", CMD_VIEW_STATUS_BAR, true);
    wmAddMenuCheckItem(view, "&Line Numbers", CMD_VIEW_LINE_NUMBERS, false);
    wmAddMenuSeparator(view);

    MenuT *tabs = wmAddSubMenu(view, "Tab &Width");

    if (!tabs) {
        return false;
    }

    for (int32_t i = 0; i < DVX_ARRAY_LEN(sTabWidths); i++) {
        char label[TINYEDIT_LABEL_MAX];

        snprintf(label, sizeof(label), "&%ld Spaces", (long)sTabWidths[i]);
        wmAddMenuRadioItem(tabs, label, CMD_VIEW_TAB_FIRST + i, sTabWidths[i] == TINYEDIT_TAB_DEFAULT);
    }

Their cases in runCommand show the menu’s state on the window: the toolbar and status bar are hidden and shown with wgtSetVisible, which lays the window out again, and the text area takes the tab width. The radio items' IDs are a range, handled in the default case:

        // DVX has already turned a check item's mark on or off, and
        // checked a radio item (unchecking the others of its group)
        case CMD_VIEW_TOOLBAR:
            wgtSetVisible(sToolbar, wmMenuItemIsChecked(sWin->menuBar, cmd));
            break;

        case CMD_VIEW_STATUS_BAR:
            wgtSetVisible(sStatusBar, wmMenuItemIsChecked(sWin->menuBar, cmd));
            break;

        case CMD_VIEW_LINE_NUMBERS:
            wgtTextAreaSetShowLineNumbers(sText, wmMenuItemIsChecked(sWin->menuBar, cmd));
            break;
        default:
            // Tab Width's radio items
            if (cmd >= CMD_VIEW_TAB_FIRST && cmd < CMD_VIEW_TAB_FIRST + DVX_ARRAY_LEN(sTabWidths)) {
                wgtTextAreaSetTabWidth(sText, sTabWidths[cmd - CMD_VIEW_TAB_FIRST]);
            }
            break;

wgtTextAreaSetTabWidth repaints the text area, as wgtTextAreaSetShowLineNumbers does, so the case needs no more.

6.5. Enabling and Graying Items

An item that cannot do anything now is grayed: drawn dim, and impossible to choose with the mouse or the keyboard. wmMenuItemSetEnabled(bar, id, enabled) grays an item of the menu bar, or enables it again, finding it by its ID in any menu or submenu of the bar.

The right time to decide is just before the user sees the menu, and DVX says when that is. onMenuOpen(win, menu) runs before a menu of the window’s bar, or one of its submenus, opens, with the menu about to open; the menu opens after it returns, showing what the callback did to it. It runs for menus opened with the mouse and with the keyboard, and not for context menus. (A menu-bar menu with no items opens nothing, so its onMenuOpen is all its title does: a title that is a command.) TinyEdit updates its Edit items there, whichever menu is opening, since it costs little:

// A menu of the menu bar, or a submenu of one, is about to open; its items
// can still change.
static void onMenuOpen(WindowT *win, MenuT *menu) {
    (void)win;
    (void)menu;
    updateEditItems();
}

Cut and Copy need a selection and Paste needs text on the clipboard. The TextArea’s header has no call for the selection’s length, but its generic interface has the property, SelLength, which wgtGetProp reads (Chapter 5 describes the generic interface); dvxClipboardGet returns NULL when the clipboard is empty:

// Cut and Copy need a selection, Paste text on the clipboard.  The
// TextArea's selection length is a property of its generic interface.
static void updateEditItems(void) {
    WgtValueT selLength;
    int32_t   clipLength = 0;

    wgtGetProp(sText, "SelLength", &selLength);

    bool hasSelection = wgtValueToInt(&selLength) > 0;
    bool hasClip      = dvxClipboardGet(&clipLength) != NULL;

    setEditItem(CMD_EDIT_CUT, hasSelection);
    setEditItem(CMD_EDIT_COPY, hasSelection);
    setEditItem(CMD_EDIT_PASTE, hasClip);
}

setEditItem grays an item in the Edit menu and in the context menu, which has the same IDs. wmMenuItemSetEnabled takes a menu bar; for a menu that belongs to no bar, wmMenuItemSetEnabledInMenu(menu, id, enabled) does the same, searching its submenus too (wmMenuFindItemInMenu finds such an item for anything else):

// One Edit command enabled or grayed, in the Edit menu and in the
// context menu, which belongs to no menu bar.
static void setEditItem(int32_t cmd, bool enabled) {
    wmMenuItemSetEnabled(sWin->menuBar, cmd, enabled);
    wmMenuItemSetEnabledInMenu(sCtxMenu, cmd, enabled);
}
Important
Graying an item does not gray the command. An accelerator key and a toolbar button with the same ID still call onMenu when the item is grayed. Write each command so that running it when it cannot work does no harm, or test the condition again in runCommand. TinyEdit’s commands are harmless: Cut with nothing selected does nothing.

Whole menus of the bar change through dvxApp.h, which repaints the bar: dvxSetMenuEnabled(ctx, win, menu, enabled) grays a menu’s title, so it does not open; dvxSetMenuVisible(ctx, win, menu, visible) takes a menu off the bar or puts it back (a hidden menu can still be shown as a context menu); and dvxSetMenuCaption(ctx, win, menu, caption) renames one. wmMenuItemSetLabel(item, label) renames an item. Items can also be added and removed while the program runs (wmAddMenuItem, wmRemoveMenuItem, wmClearMenuItems, which free the submenus of the items they remove), but call dvxCloseMenu(ctx, menu) first if the menu might be open, since the open menu’s state points into its items.

6.6. Context Menus

A context menu is a menu that opens at the mouse pointer on a right click, with commands for the thing clicked. It is a MenuT that belongs to no menu bar: wmCreateMenu() makes an empty one, which the wmAdd* calls fill like any other. The program owns it, since one menu may serve several windows: destroying a window does not free it, and wmFreeMenu(menu) does, with its submenus (call dvxCloseMenu first if it may be open).

To have DVX open it, set a widget’s contextMenu or the window’s. A right click in a window’s content area goes to the widget under the mouse first (its onMouseDown runs, with the button), and then DVX opens the context menu of that widget or, failing that, of the nearest container above it that has one, or else the window’s. A right press on a control’s scroll bar or column heading opens no context menu, and none opens when the press’s onMouseDown closed the window. The menu opens at the mouse pointer, moved as needed to stay on the screen, and its items call the window’s onMenu. TinyEdit gives its text area a menu of Edit commands, with the Edit menu’s IDs so runCommand handles them unchanged:

// The text area's right-click menu.  Its items use the Edit menu's
// command IDs, so onMenu handles them the same way.
static void buildContextMenu(void) {
    sCtxMenu = wmCreateMenu();

    if (!sCtxMenu) {
        return;
    }

    wmAddMenuItem(sCtxMenu, "Cu&t", CMD_EDIT_CUT);
    wmAddMenuItem(sCtxMenu, "&Copy", CMD_EDIT_COPY);
    wmAddMenuItem(sCtxMenu, "&Paste", CMD_EDIT_PASTE);
    wmAddMenuSeparator(sCtxMenu);
    wmAddMenuItem(sCtxMenu, "Select &All", CMD_EDIT_SELECT_ALL);
    sText->contextMenu = sCtxMenu;
}

A context menu gets no onMenuOpen. The widget’s onMouseDown runs before the menu opens, so TinyEdit updates the items there:

// A right click calls the text area's onMouseDown before it opens the
// context menu, which gets no onMenuOpen: its items are brought up to
// date here.
static void onTextMouseDown(WidgetT *w, int32_t button, int32_t x, int32_t y) {
    (void)w;
    (void)button;
    (void)x;
    (void)y;
    updateEditItems();
}

dvxShowContextMenu(ctx, win, menu, x, y) opens a menu at a screen position from code, sending its items to win’s `onMenu. DVX opens context menus only for the right mouse button; a program that wants a key for one (Shift+F10 is the usual) adds an accelerator for it and calls dvxShowContextMenu from its command. For check and radio items in a context menu, wmMenuItemSetCheckedInMenu(menu, id, checked) does what wmMenuItemSetChecked does for a bar.

6.7. Shortcut Keys

A shortcut key runs a command without the menu: Ctrl+S saves. DVX calls them accelerators. They live in a table: dvxCreateAccelTable() makes an empty one, dvxAddAccel(table, key, modifiers, id) adds a key, and the table goes in the window’s accelTable. When the window has the keyboard focus and a key in its table is pressed, DVX calls the window’s onMenu with the key’s command ID:

    // Shortcut keys: each fires onMenu with its command ID, before the
    // focused control sees the key.  The Edit keys are left to the text
    // area, which handles them itself.
    sAccel = dvxCreateAccelTable();
    dvxAddAccel(sAccel, 'N', ACCEL_CTRL, CMD_FILE_NEW);
    dvxAddAccel(sAccel, 'O', ACCEL_CTRL, CMD_FILE_OPEN);
    dvxAddAccel(sAccel, 'S', ACCEL_CTRL, CMD_FILE_SAVE);
    sWin->accelTable = sAccel;

key is a character (a letter in either case means the same key), a digit, or a KEY_* constant from dvxTypes.h for the other keys (KEY_F5, KEY_DELETE, KEY_INSERT, KEY_ENTER, …​). modifiers is ACCEL_CTRL, ACCEL_SHIFT, and ACCEL_ALT combined with |, or 0. Ctrl and Alt always count. Shift counts with Ctrl or Alt and with keys that are not characters, so Ctrl+S and Ctrl+Shift+S are different shortcuts, as are F5 and Shift+F5; a character typed without Ctrl or Alt matches whether or not Shift was held, since the character itself says that. dvxRemoveAccel(table, id) removes every key of a command.

A key goes through DVX in this order, and the first that takes it ends the trip:

  1. DVX’s own keys: Alt+Tab, Alt+F4, Ctrl+Esc, Ctrl+F12, Ctrl+Shift+F12, Alt+Space, F1, F10, and Ctrl+Alt+Del. No program gets these; dvxSystemKeyUse says what each does.

  2. System-wide hotkeys (dvxRegisterHotkey, Chapter 8), unless a menu or a modal window is open.

  3. Alt with a letter: the menu bar’s titles, then the access keys of the window’s controls (an open menu is closed first).

  4. An open menu, which takes every key.

  5. Esc, when a drop-down list is open: it closes the list.

  6. The accelerator table of the window that has the focus.

  7. Tab and Shift+Tab, which move the focus between controls.

  8. The window’s onKey; in a window with widgets, the default and cancel buttons and then the control that has the focus.

An accelerator therefore takes its key from every control in the window. That is right for Ctrl+S, which no control uses, and wrong for Ctrl+C, which a text control uses to copy: an accelerator for Ctrl+C would leave no text field in the window able to copy with the keyboard. TinyEdit puts the Edit keys in its menu labels and leaves the keys to the text area, which handles Ctrl+Z, Ctrl+X, Ctrl+C, Ctrl+V, and Ctrl+A itself; F1 is DVX’s, which opens the help of the program whose window has the focus.

Only the focused window’s table is checked, so a program with several windows gives each the table it needs (one table may serve several windows). The table belongs to the program: destroying the window does not free it, and dvxFreeAccelTable(table) does, after the window is gone. TinyEdit frees its table and its context menu in appShutdown (Section 4.12):

// The shell calls appShutdown, when a program has one, after the program's
// last window has closed and before it unloads the program.  Destroying the
// window freed its menu bar but not the accelerator table or the context
// menu: those are the program's to free.
void appShutdown(void) {
    dvxFreeAccelTable(sAccel);
    wmFreeMenu(sCtxMenu);
}

6.8. Toolbars

A toolbar is a strip of buttons below the menu bar for the commands used most. In DVX it is a widget, wgtToolbar(parent) from toolbar/toolbar.h: a horizontal box drawn as a raised bar, with two pixels of padding and spacing, which holds whatever widgets you put in it. Make it the first child of the window’s root, so it sits at the top of the content area, right under the menu bar:

static void buildToolbar(WidgetT *root) {
    sToolbar = wgtToolbar(root);
    addToolButton(sToolbar, TINYEDIT_RES_NEW, "New (Ctrl+N)", CMD_FILE_NEW);
    addToolButton(sToolbar, TINYEDIT_RES_OPEN, "Open (Ctrl+O)", CMD_FILE_OPEN);
    addToolButton(sToolbar, TINYEDIT_RES_SAVE, "Save (Ctrl+S)", CMD_FILE_SAVE);
}

Toolbar buttons are usually picture buttons, wgtImageButton from imageButton/imgBtn.h, though plain buttons (wgtButton) with short labels work too, and wgtVSeparator (from separator/separatr.h) draws a line between groups. wgtImageButton(parent, pixels, w, h, pitch) takes pixels in the display’s pixel format and owns them from then on (it frees them if it fails); wgtImageButtonFromFile(parent, path) loads an image file. TinyEdit carries its 16 by 16 pictures as icon resources in its own .app file, so dvxResLoadIcon gives it the pixels, and gives each button a tooltip, the text that appears when the mouse rests on it. wgtSetTooltip keeps the pointer, not a copy, so the text must last as long as the button; a string literal does:

// A toolbar button showing icon resource resName of our own .app file.
// The button takes the pixels; its command ID rides in userData, and tip
// (a string that outlives the button) is its tooltip.
static void addToolButton(WidgetT *toolbar, const char *resName, const char *tip, int32_t cmd) {
    int32_t  w      = 0;
    int32_t  h      = 0;
    int32_t  pitch  = 0;
    uint8_t *pixels = dvxResLoadIcon(sAc, sCtx->appPath, resName, &w, &h, &pitch);
    WidgetT *button = wgtImageButton(toolbar, pixels, w, h, pitch);

    if (button) {
        button->onClick  = onToolClick;
        button->userData = (void *)(intptr_t)cmd;
        wgtSetTooltip(button, tip);
    }
}

The resources are named in tinyedit.res, with the program’s icon:

icon32      icon    icon32.bmp
tbnew       icon    new.bmp
tbopen      icon    open.bmp
tbsave      icon    save.bmp

TinyEdit’s View menu hides and shows the toolbar with wgtSetVisible; the controls below it move up to take its place. Like every widget call, wgtToolbar and wgtImageButton go through the widget’s interface, which is missing when the widget is not installed; Chapter 5 shows how to check.

6.9. Status Bars

A status bar runs along the bottom of a window and shows what the program is doing or what state it is in. wgtStatusBar(parent), from statusBar/statBar.h, is a horizontal box that draws a sunken one-pixel panel around each of its children; the children are usually labels. Make it the last child of the window’s root. Give the panel that should take the spare width a weight of WGT_WEIGHT_FILL, and a panel that should keep its width when its text is short or empty a minimum width (wgtChars measures it in characters):

// Two panels: a message that takes the spare width, and the file's state
// in a panel that keeps its width when it is empty.
static void buildStatusBar(WidgetT *root) {
    sStatusBar = wgtStatusBar(root);
    sMessage   = wgtLabel(sStatusBar, "Ready.");
    sState     = wgtLabel(sStatusBar, "");

    if (sMessage) {
        sMessage->weight = WGT_WEIGHT_FILL;
    }

    if (sState) {
        sState->minW = wgtChars(TINYEDIT_STATE_CHARS);
    }
}

To change a panel, change its label with wgtSetText. That measures and lays out the whole window again and repaints it at the next frame, so do it when the text changes, not on every key; wgtSetText returns at once when the text is the same. TinyEdit’s message panel takes text formatted like printf:

// The status bar's message, printf style.
static void setStatus(const char *format, ...) {
    char    text[TINYEDIT_TEXT_MAX];
    va_list args;

    va_start(args, format);
    vsnprintf(text, sizeof(text), format, args);
    va_end(args);
    wgtSetText(sMessage, text);
}

Its second panel, and the window’s title, show the file’s state. showState runs on every change to the text, and costs nothing after the first, since neither dvxSetTitle nor wgtSetText does anything when the text is the same:

// The title names the file; the status bar's second panel says whether
// it has changes not saved.  Neither call repaints anything when its text
// is unchanged, so this costs nothing after the first change.
static void showState(void) {
    char title[TINYEDIT_TEXT_MAX];

    snprintf(title, sizeof(title), "%s - %s", TINYEDIT_TITLE, sPath[0] ? platformPathBaseName(sPath) : TINYEDIT_UNTITLED);
    dvxSetTitle(sAc, sWin, title);
    wgtSetText(sState, sModified ? "Modified" : "");
}
// The first change after a load or save marks the file modified.
static void onTextChange(WidgetT *w) {
    (void)w;
    sModified = true;
    showState();
}

6.10. The Rest of TinyEdit

The parts of TinyEdit that are not menus are short, and use calls other chapters cover in full.

The Edit commands call the text area’s own Undo, Cut, Copy, Paste, and Select All, which are what its keys do: wgtTextAreaUndo, wgtTextAreaCut, wgtTextAreaCopy, wgtTextAreaPaste, and wgtTextAreaSelectAll (textInput/textInpt.h; the wgtTextInput forms of them work on a text area too):

        case CMD_EDIT_UNDO:
            wgtTextAreaUndo(sText);
            break;

        case CMD_EDIT_CUT:
            wgtTextAreaCut(sText);
            break;

        case CMD_EDIT_COPY:
            wgtTextAreaCopy(sText);
            break;

        case CMD_EDIT_PASTE:
            wgtTextAreaPaste(sText);
            break;

        case CMD_EDIT_SELECT_ALL:
            wgtTextAreaSelectAll(sText);
            break;

A DOS text file’s lines end in CR LF, and a TextArea’s lines end in LF, so TinyEdit drops the CRs when it loads a file and puts them back when it saves one. platformReadFile reads a whole file into memory it allocates; platformWriteFile writes a whole file all or nothing, through a temporary copy, so a full disk leaves the old file as it was (Chapter 10 has the details). A TextArea holds at most the maxLen characters it was created with (0 means TEXTAREA_DEFAULT_MAX_LEN, 65,536), and cuts longer text, so TinyEdit makes one of TINYEDIT_MAX_TEXT characters and refuses a larger file instead:

// Reads a DOS text file into the text area.  The file's lines end in
// CR LF and the text area's in LF, so the CRs are dropped.
static bool loadFile(const char *path) {
    int32_t len  = 0;
    char   *text = platformReadFile(path, &len);
    int32_t kept = 0;

    if (!text) {
        showError("%s could not be read.", path);
        return false;
    }

    for (int32_t i = 0; i < len; i++) {
        if (text[i] != '\r') {
            text[kept++] = text[i];
        }
    }

    text[kept] = '\0';

    if (kept > TINYEDIT_MAX_TEXT) {
        free(text);
        showError("%s is too large for TinyEdit.", path);
        return false;
    }

    wgtSetText(sText, text);
    free(text);
    setFile(path);
    setStatus("Opened %s.", platformPathBaseName(path));
    return true;
}
// Saves the text as a DOS text file, its lines ending in CR LF.
// platformWriteFile writes all or nothing: a new copy is written and then
// swapped in, so a full disk leaves the old file as it was.
static bool writeFile(const char *path) {
    const char *text  = wgtGetText(sText);
    int32_t     len   = (int32_t)strlen(text);
    int32_t     lines = 0;

    for (int32_t i = 0; i < len; i++) {
        lines += (text[i] == '\n') ? 1 : 0;
    }

    char   *out = (char *)malloc((size_t)(len + lines + 1));
    int32_t pos = 0;

    if (!out) {
        showError("There is not enough memory to save %s.", path);
        return false;
    }

    for (int32_t i = 0; i < len; i++) {
        if (text[i] == '\n') {
            out[pos++] = '\r';
        }

        out[pos++] = text[i];
    }

    bool written = platformWriteFile(path, out, pos);

    free(out);

    if (!written) {
        showError("%s could not be saved.", path);
        return false;
    }

    setFile(path);
    setStatus("Saved %s.", platformPathBaseName(sPath));
    return true;
}

Before File › New, File › Open…​, and closing the window throw the text away, okToDiscard asks with dvxPromptSave, which shows the standard Yes, No, and Cancel question and returns DVX_SAVE_YES, DVX_SAVE_NO, or DVX_SAVE_CANCEL. The window’s onClose uses it, so the close gadget, Alt+F4, File › Exit (which calls dvxRequestWindowClose), and DVX’s own exit all ask; a Cancel keeps the window, and with it the program:

// Before the text is replaced or the window closes: changes not saved
// are saved, thrown away, or kept (Cancel: false), as the user chooses.
static bool okToDiscard(void) {
    if (!sModified) {
        return true;
    }

    switch (dvxPromptSave(sAc, TINYEDIT_TITLE)) {
        case DVX_SAVE_YES:
            return saveFile();

        case DVX_SAVE_NO:
            return true;

        default:
            return false;
    }
}
// The close box, Alt+F4, the system menu's Close, File > Exit, and DVX
// closing every program on its way out.  A window kept open (Cancel)
// keeps the program running.
static void onClose(WindowT *win) {
    if (okToDiscard()) {
        dvxDestroyWindow(sAc, win);
    }
}

appMain puts it together. The menu bar comes before wgtInitWindow; the window’s handlers come after it (Section 4.3); and the focus goes to the text area at the end, since a window’s first paint gives the focus to its first control that can take it, which would be the toolbar’s New button:

int32_t appMain(DxeAppContextT *ctx) {
    sCtx = ctx;
    sAc  = ctx->shellCtx;
    sWin = dvxCreateWindowCentered(sAc, TINYEDIT_TITLE, TINYEDIT_WIN_W, TINYEDIT_WIN_H, true);

    if (!sWin) {
        return -1;
    }

    // The menu bar first: it takes its height from the content area
    WidgetT *root = buildMenus() ? wgtInitWindow(sAc, sWin) : NULL;

    if (root) {
        buildToolbar(root);
        sText = wgtTextArea(root, TINYEDIT_MAX_TEXT);
    }

    if (!sText) {
        dvxDestroyWindow(sAc, sWin);
        return -1;
    }

    buildStatusBar(root);
    buildContextMenu();

    // After wgtInitWindow, which installs handlers of its own
    sWin->onClose    = onClose;
    sWin->onMenu     = onMenu;
    sWin->onMenuOpen = onMenuOpen;

    // Shortcut keys: each fires onMenu with its command ID, before the
    // focused control sees the key.  The Edit keys are left to the text
    // area, which handles them itself.
    sAccel = dvxCreateAccelTable();
    dvxAddAccel(sAccel, 'N', ACCEL_CTRL, CMD_FILE_NEW);
    dvxAddAccel(sAccel, 'O', ACCEL_CTRL, CMD_FILE_OPEN);
    dvxAddAccel(sAccel, 'S', ACCEL_CTRL, CMD_FILE_SAVE);
    sWin->accelTable = sAccel;

    sText->onChange    = onTextChange;
    sText->onMouseDown = onTextMouseDown;
    wgtTextAreaSetTabWidth(sText, TINYEDIT_TAB_DEFAULT);

    setFile("");

    // The first control that can take the focus would get it: the New button
    wgtSetFocused(sText);
    return 0;
}

Chapter 7. Dialog Boxes

A dialog box asks the user one thing and gives back the answer: a yes or a no, a line of text, a file name, a color. dvxDlg.h has the standard ones, ready to call, and a small kit for building your own from widgets. Every one of them is modal and blocking: the call shows the box, waits until the user dismisses it, and returns the answer as its value, so the code that asks reads straight through.

Function Shows Returns

dvxMessageBox

A message, an icon, and one of five button sets

The ID_* value of the button

dvxErrorBox, dvxInfoBox

A message with the error or information icon and OK

ID_OK

dvxButtonBox

A message, an icon, and up to six buttons you name

The index of the button

dvxPromptSave

“Save changes?” with Yes, No, and Cancel

DVX_SAVE_*

dvxInputBox

A prompt and a text box

true and the text, or false

dvxIntInputBox

A prompt and a number box with up and down arrows

true and the number, or false

dvxChoiceDialog

A prompt and a list

true and the index chosen, or false

dvxFileDialog

The Open, Save As, and folder dialogs

true and the path, or false

dvxColorDialog

A color picker

true and the color, or false

dvxFontDialog

A font picker

true and the font, or false

dvxDialogCreate …​ dvxDialogRun

Your own widgets, with OK and Cancel

true for OK, false for Cancel

This chapter builds a program that opens each of them, then explains how a dialog box runs, what each one does with every argument, and how to build one of your own. The full declarations are in “dvxDlg.h — Modal Dialogs” in the DVX C Library Reference.

7.1. The Dialogs Program

The example dialogs is one window of buttons, grouped in frames, and a Result box. The two lists at the top choose the button set and the icon of a message box; every other button opens one dialog box; the Result box shows what the box gave back. Build it and install it as you did hello in Chapter 2:

$ cd src/cGuide/examples/dialogs
$ make
$ make install DVX_DIR=/path/to/dvx
The Dialogs window with frames for message boxes, input boxes, files and folders, and color, font, and custom dialogs, and a Result box
Figure 11. The Dialogs program

The window is built in appMain the usual way (Chapter 5). The message box’s two lists are filled from tables that pair each label with the flag it stands for, and the flag is kept as the list item’s data, so the button’s callback reads it back without a second table to keep in step:

static const DialogsChoiceT sButtonSets[] = {
    { "OK",              MB_OK          },
    { "OK, Cancel",      MB_OKCANCEL    },
    { "Yes, No",         MB_YESNO       },
    { "Yes, No, Cancel", MB_YESNOCANCEL },
    { "Retry, Cancel",   MB_RETRYCANCEL }
};

static const DialogsChoiceT sIcons[] = {
    { "None",        0               },
    { "Information", MB_ICONINFO     },
    { "Warning",     MB_ICONWARNING  },
    { "Error",       MB_ICONERROR    },
    { "Question",    MB_ICONQUESTION }
};

// What dvxMessageBox and dvxPromptSave return, by value
static const char *const sIdNames[] = {
    [ID_OK]     = "ID_OK",
    [ID_CANCEL] = "ID_CANCEL",
    [ID_YES]    = "ID_YES",
    [ID_NO]     = "ID_NO",
    [ID_RETRY]  = "ID_RETRY"
};

static const char *const sSaveNames[] = {
    [DVX_SAVE_YES]    = "DVX_SAVE_YES",
    [DVX_SAVE_NO]     = "DVX_SAVE_NO",
    [DVX_SAVE_CANCEL] = "DVX_SAVE_CANCEL"
};
    WidgetT *msgFrame = wgtFrame(root, "Message Boxes");
    WidgetT *flagRow  = wgtHBox(msgFrame);

    wgtLabel(flagRow, "&Buttons:");
    sButtonsDd = wgtDropdown(flagRow);
    wgtLabel(flagRow, "&Icon:");
    sIconDd = wgtDropdown(flagRow);
    fillDropdown(sButtonsDd, sButtonSets, DVX_ARRAY_LEN(sButtonSets));
    fillDropdown(sIconDd, sIcons, DVX_ARRAY_LEN(sIcons));
    addButtonRow(msgFrame, sMessageButtons, DVX_ARRAY_LEN(sMessageButtons));

The other three frames are rows of buttons made by addButtonRow from tables of labels and callbacks. Every callback ends by calling showResult, which formats a line into the read-only Result box. The rest of this chapter takes the callbacks one dialog at a time.

7.2. How a Dialog Box Runs

Each standard dialog creates a window with widgets, makes it the modal window, and then runs DVX’s event loop itself, calling dvxUpdate until the user answers. When the user does, it destroys the window and returns. Nothing about this is hidden from you, and four consequences follow from it.

Only the dialog takes input, in all of DVX: the modal window is the desktop’s, not your program’s. While it is up, clicks on every other window (other programs' too) and on the desktop are ignored, the dialog is kept in front with the keyboard focus, Alt+F4 closes only the dialog, and no system-wide hotkey fires (Section 8.8). Ctrl+Esc still opens the Task Manager, and it comes up modal over the dialog, so the user can end a program that hangs behind one; when the Task Manager closes, the dialog is the modal window again, and when the user ends the dialog’s program, the Task Manager becomes an ordinary window. So show a dialog only in answer to something the user did, and never leave one up while your program waits for something else.

Everything else keeps running. Each dvxUpdate is a whole frame: windows paint, timers fire, and the other programs' tasks run. That includes your program: a Timer widget of yours keeps calling its callback while you wait in dvxMessageBox, and anything that callback changes has changed when the call returns. Keep the state a dialog depends on out of the reach of your timers, or check it again afterwards.

Dialogs stack. A dialog may open another — the file dialog asks “Do you want to replace it?” with a message box, and your own dialog’s OK may show an error box — and when the inner one closes, the outer one is the modal window again.

A dialog can be taken away. If your program is ended (from the Task Manager, say) while one of its dialog boxes is up, the box goes and the call returns as if the user had canceled. Your code after the call may still run while the program is taken down, so it must not count on its windows being there for long.

A program with a main loop of its own (Chapter 3) calls the dialogs the same way. The call blocks its task until the user answers, while DVX and the other programs go on.

The standard dialogs follow the Windows keyboard rules. Enter presses the default button (OK, or the first button) unless the control with the focus uses Enter itself: a button with the focus presses itself, an open drop-down list takes its choice, and a multi-line text box starts a new line. Esc presses the cancel button (Cancel, or the last button). The close gadget, the window menu’s Close, and Alt+F4 cancel. Alt and an underlined letter press that button or move to that control, and Tab moves through the controls.

7.3. Message Boxes

dvxMessageBox shows a message with an icon and a row of buttons, and returns which button the user chose:

int32_t dvxMessageBox(AppContextT *ctx, const char *title, const char *message, int32_t flags);

flags is a button set ORed with an icon, the encoding of the Windows MessageBox call:

Flag Value Buttons, or icon

MB_OK

0x00

OK

MB_OKCANCEL

0x01

OK Cancel

MB_YESNO

0x02

Yes No

MB_YESNOCANCEL

0x03

Yes No Cancel

MB_RETRYCANCEL

0x04

Retry Cancel

MB_ICONINFO

0x10

An “i” in a circle

MB_ICONWARNING

0x20

An exclamation mark

MB_ICONERROR

0x30

An “X” in a circle

MB_ICONQUESTION

0x40

A question mark in a circle

MB_BUTTON_MASK (0x0F) and MB_ICON_MASK (0xF0) take the two fields apart. With no icon flag the box has none, and an unknown button set shows OK.

The result is one of ID_OK (1), ID_CANCEL (2), ID_YES (3), ID_NO (4), or ID_RETRY (5): the button pressed. Enter presses the first button (or the one Tab has moved the focus to) and Esc the last, so Esc gives ID_OK in an MB_OK box and ID_NO in an MB_YESNO box. Closing the box gives ID_CANCEL whatever its buttons are, including a Yes/No box, which has no Cancel button: test for the answer that does something (r == ID_YES), not for the one that does not.

The message is word-wrapped to the box, which is 320 pixels wide inside (wider when its buttons need it), and a '\n' in it starts a new line. The box grows to the height of the message, so keep messages to a few lines. A NULL title leaves the title bar empty, and a NULL message returns ID_CANCEL without showing anything. The box plays the desktop sound of its icon (Control Panel’s Sounds page), or the default sound when it has none.

The dialogs example’s Show Message button shows whatever the two lists say:

static void onMessageBox(WidgetT *w) {
    int32_t buttons = wgtDropdownGetItemData(sButtonsDd, wgtDropdownGetSelected(sButtonsDd));
    int32_t icon    = wgtDropdownGetItemData(sIconDd, wgtDropdownGetSelected(sIconDd));
    int32_t id      = dvxMessageBox(sCtx->shellCtx, "Message Box", DIALOGS_MESSAGE, buttons | icon);

    (void)w;
    showResult("dvxMessageBox: %s", nameOf(sIdNames, DVX_ARRAY_LEN(sIdNames), id));
}
A message box with a question mark icon, its message, and Yes, No, and Cancel buttons
Figure 12. A message box with the Yes, No, and Cancel buttons and the Question icon

Try closing a Yes/No box with its close gadget: the Result box says ID_CANCEL.

Two shorthands cover the common case of telling the user something. dvxErrorBox(ctx, title, message) is MB_OK | MB_ICONERROR with the title “Error” when title is NULL, and dvxInfoBox(ctx, title, message) is MB_OK | MB_ICONINFO with the title “Information”. Both return ID_OK, or ID_CANCEL when the user closed the box instead of pressing OK.

if (!saveNotes()) {
    dvxErrorBox(ac, "Notes", "The notes could not be saved: the disk is full.");
}

7.3.1. Buttons of Your Own

When the five button sets do not fit the question, dvxButtonBox takes the labels:

int32_t dvxButtonBox(AppContextT *ctx, const char *title, const char *message, int32_t iconFlags, const char * const *labels, int32_t count);

labels holds count labels, 1 to DVX_BUTTON_BOX_MAX (6), each with & before its access key. iconFlags is one MB_ICON* value or 0 (any button bits in it are ignored). The result is the index of the button chosen. Enter chooses the first button, and Esc and closing the box choose the last, so make the last one the answer that changes nothing. A bad argument (a NULL context, message, or label array, or a count out of range) returns -1 without showing anything.

static void onButtonBox(WidgetT *w) {
    int32_t count = DVX_ARRAY_LEN(sReplaceLabels);
    int32_t pick  = dvxButtonBox(sCtx->shellCtx, "Replace", "README.TXT is already there.\nReplace it?", MB_ICONQUESTION, sReplaceLabels, count);

    (void)w;
    showResult("dvxButtonBox: %" PRId32 " (%s)", pick, pick >= 0 ? sReplaceLabels[pick] : "bad arguments");
}

The box is sized for buttons 80 pixels wide, which holds a label of up to eight characters of the system font. Keep the labels that short, or let one at most run a little longer, as the example’s Yes to All does; see Section 7.8.

7.3.2. Asking to Save Changes

dvxPromptSave(ctx, title) is the question a program with unsaved work asks before it closes or opens something else: “Save changes?” with the question icon and Yes, No, and Cancel. title is only the window’s title (“Save” when NULL); the message is always the same. It returns DVX_SAVE_YES (1), DVX_SAVE_NO (2), or DVX_SAVE_CANCEL (3), which is also what Esc and closing the box give.

static void onPromptSave(WidgetT *w) {
    int32_t answer = dvxPromptSave(sCtx->shellCtx, DIALOGS_TITLE);

    (void)w;
    showResult("dvxPromptSave: %s", nameOf(sSaveNames, DVX_ARRAY_LEN(sSaveNames), answer));
}

In a program with a document, the window’s onClose is where it is asked. The window is destroyed only when the user did not cancel and, for Yes, the save worked:

static void onClose(WindowT *win) {
    int32_t answer = sDirty ? dvxPromptSave(sCtx->shellCtx, NOTES_TITLE) : DVX_SAVE_NO;

    if (answer == DVX_SAVE_CANCEL || (answer == DVX_SAVE_YES && !saveNotes())) {
        return;
    }

    dvxDestroyWindow(sCtx->shellCtx, win);
}

7.4. Asking for Text, a Number, or a Choice

dvxInputBox asks for a line of text:

bool dvxInputBox(AppContextT *ctx, const char *title, const char *prompt, const char *defaultText, char *outBuf, int32_t outBufSize);

The prompt is word-wrapped above the text box and may hold '\n'. The text box starts with defaultText (none when NULL), all of it selected, as in Windows: typing replaces it, Enter keeps it, and End or an arrow key goes on from it. It takes at most outBufSize - 1 characters (4096 at most), so whatever the user types fits. OK copies the text into outBuf and returns true; Cancel, Esc, or closing the box returns false and leaves outBuf alone. An outBufSize below 2 returns false at once, without showing anything. The title is “Input” when NULL.

The example offers the last answer the next time. It reads into a local buffer and copies the answer only when there is one:

static void onText(WidgetT *w) {
    char text[DIALOGS_TEXT_MAX];

    (void)w;

    if (!dvxInputBox(sCtx->shellCtx, "Text", "What is your name?", sName, text, sizeof(text))) {
        showResult("dvxInputBox: canceled");
        return;
    }

    // The next time the box opens, it offers this answer
    snprintf(sName, sizeof(sName), "%s", text);
    showResult("dvxInputBox: \"%s\"", text);
}

dvxIntInputBox asks for a whole number in a number box (a Spinner widget) with up and down arrows:

bool dvxIntInputBox(AppContextT *ctx, const char *title, const char *prompt, int32_t defaultVal, int32_t minVal, int32_t maxVal, int32_t step, int32_t *outVal);

The box starts at defaultVal; the arrows, Up, and Down move it by step; and whatever is typed is held to minVal .. maxVal, so the number returned is always in range. OK stores it in *outVal and returns true; Cancel leaves *outVal alone. Because defaultVal is passed by value, the same variable can be both the starting value and the result:

static void onNumber(WidgetT *w) {
    (void)w;

    if (dvxIntInputBox(sCtx->shellCtx, "Number", "How many copies?", sCopies, DIALOGS_COPIES_MIN, DIALOGS_COPIES_MAX, DIALOGS_COPIES_STEP, &sCopies)) {
        showResult("dvxIntInputBox: %" PRId32, sCopies);
    } else {
        showResult("dvxIntInputBox: canceled");
    }
}

dvxChoiceDialog shows a list and returns the index of the item chosen:

bool dvxChoiceDialog(AppContextT *ctx, const char *title, const char *prompt, const char **items, int32_t itemCount, int32_t defaultIdx, int32_t *outIdx);

defaultIdx is the item selected at first (-1, or any index out of range, for none). A double click on an item, or Enter in the list, chooses it at once; OK with no item selected does nothing, and the box stays up. The list uses items only while the box is up, so a local array will do. It returns false for Cancel and for bad arguments (NULL items or outIdx, or no items). The title is “Choose” when NULL.

static void onList(WidgetT *w) {
    int32_t count = DVX_ARRAY_LEN(sPlanets);
    int32_t pick  = -1;

    (void)w;

    if (dvxChoiceDialog(sCtx->shellCtx, "List", "Choose a planet:", sPlanets, count, DIALOGS_PLANET_START, &pick)) {
        showResult("dvxChoiceDialog: %" PRId32 " (%s)", pick, sPlanets[pick]);
    } else {
        showResult("dvxChoiceDialog: canceled");
    }
}

7.5. File and Folder Dialogs

One call shows the Open, Save As, and folder dialogs:

bool dvxFileDialog(AppContextT *ctx, const char *title, int32_t flags, const char *initialDir, const FileFilterT *filters, int32_t filterCount, char *outPath, int32_t outPathSize);

flags chooses the kind:

Flag Value Meaning

FD_OPEN

0x00

Open a file: only a file that exists is taken. A name that is not one shows “_name_ does not exist. Check the file name and try again.” and the dialog stays up.

FD_SAVE

0x01

Save a file: a file that exists is taken only after “_name_ already exists. Do you want to replace it?” is answered Yes.

FD_FOLDER

0x02

Choose a folder, one that exists or a new one (the caller makes it).

FD_CREATE

0x04

With FD_OPEN: a name that is not a file is taken after “_name_ does not exist. Do you want to create it?” is answered Yes. The caller makes the file.

FD_NAME

0x08

With FD_OPEN or FD_SAVE: outPath holds a file name to suggest, such as UNTITLED.TXT.

The Save As dialog with its path, drive list, file list, filter list, and file name box
Figure 13. The Save As dialog in the program’s user folder, with UNTITLED.TXT suggested

The dialog has a fixed size. From the top: a Path box showing the folder and a Drive list beside it; the list of the folder’s subfolders (in brackets, first, with [..] for the folder above) and files, sorted without regard to case; a Filter list, when there are filters; and the File name box (Folder name with FD_FOLDER), which has the keyboard focus at first. A click on a file puts its name in the File name box, and a double click opens a folder or takes the file. The user can also type a folder into the Path box and press Enter, or type a name with a folder or a drive in front of it (..\NOTES.TXT, D:\WORK\A.TXT) into the File name box, and the dialog goes to that folder and takes the name there. A drive that cannot be read (an empty floppy drive) says “Drive A: is not ready.” and leaves the dialog where it was. Names are checked against the rules of the disk they are on, so an 8.3 disk refuses a long name.

The title is “Open”, “Save As”, or “Choose a Folder” when NULL. initialDir is where the dialog starts, the current folder when NULL. It returns true with the full path in outPath, or false when the user canceled. The path is built from the folder shown and the name, with DOS’s \ separators, so when initialDir was relative and the user did not change folders, the path is relative to DVX’s current folder too; use it as it is. A path that does not fit outPathSize is dropped and the call returns false as if canceled, so give it DVX_MAX_PATH bytes. Without FD_NAME, outPath is only written, so it need not be set first.

7.5.1. Filters

A filter is a FileFilterT, whose one field is the label shown in the Filter list. The pattern is the part of the label in parentheses: one or more patterns with * and ?, separated by semicolons, matched without regard to case. A label with no parentheses is its own pattern when it has a wildcard in it, and matches every file when it has none.

static const FileFilterT sFilters[] = {
    { "Text Files (*.txt)" },
    { "All Files (*.*)" }
};

The first filter is in effect when the dialog opens, and the list shows at most 16. In a Save As dialog, a name typed without a dot gets the first real extension of the filter in effect: with the filters above, README is saved as README.txt while Text Files is chosen, and stays README under All Files. Folders are always listed, whatever the filter. FD_FOLDER lists folders only, and ignores the filters.

7.5.2. Where to Start

A program’s files belong in its own folder in the user folder, DxeAppContextT.userDir (for Program Manager, USER\APPS\KPUNCH\PROGMAN; Chapter 10), never beside the program, in a folder DVX only reads. The folder may not exist yet: shellEnsureUserDir makes it and returns 0, or returns -1 when it cannot. The example starts every file dialog there:

// The program's own folder in the user folder, made if it is not there
// yet; NULL (the current folder) when it cannot be made.
static const char *startFolder(void) {
    return shellEnsureUserDir(sCtx) == 0 ? sCtx->userDir : NULL;
}
// One of the file dialogs, starting in the program's user folder; suggest
// (with FD_NAME) is the name the File name box starts with.
static void runFileDialog(const char *what, int32_t flags, const FileFilterT *filters, int32_t filterCount, const char *suggest) {
    char path[DVX_MAX_PATH];

    snprintf(path, sizeof(path), "%s", suggest ? suggest : "");

    if (dvxFileDialog(sCtx->shellCtx, NULL, flags, startFolder(), filters, filterCount, path, sizeof(path))) {
        showResult("%s: %s", what, path);
    } else {
        showResult("%s: canceled", what);
    }
}

The three buttons differ only in their flags:

runFileDialog("Open", FD_OPEN, sFilters, DVX_ARRAY_LEN(sFilters), NULL);
runFileDialog("Save As", FD_SAVE | FD_NAME, sFilters, DVX_ARRAY_LEN(sFilters), DIALOGS_UNTITLED);
runFileDialog("Folder", FD_FOLDER, NULL, 0, NULL);

With FD_NAME the File name box starts with the suggestion, selected, so Enter takes it and typing replaces it. With FD_FOLDER, OK returns the folder shown when the Folder name box is empty, and the folder of that name in it (or the path typed, when it is a full one) when it is not. That folder need not exist yet; the program makes it (platformMkdirRecursive, Chapter 10). A name that is a file is refused. An initialDir that does not exist yet opens at the nearest folder above it that does, with the rest typed in already, so OK alone returns initialDir unchanged: the way to let the user confirm or change a folder the program is about to make.

7.6. Colors and Fonts

dvxColorDialog(ctx, title, &rgb) shows a palette of 48 basic colors, a slider and a number box (0 to 255) for each of red, green, and blue, and a sample of the color. rgb is a uint32_t in the layout 0x00RRGGBB: it holds the color the dialog starts with and receives the one chosen. On Cancel it is left alone. DVX_RGB(r, g, b) builds a color in that layout, and DVX_RGB_RED, DVX_RGB_GREEN, and DVX_RGB_BLUE take one apart (dvxVideo.h). The title is “Color” when NULL.

The example colors its sample text. A widget’s fgColor and bgColor hold 0x00RRGGBB with WGT_COLOR_SET added (0 means the color scheme’s color, so black needs the flag to be told from none):

static void onColor(WidgetT *w) {
    (void)w;

    if (!dvxColorDialog(sCtx->shellCtx, "Sample Color", &sColor)) {
        showResult("dvxColorDialog: canceled");
        return;
    }

    sSample->fgColor = sColor | WGT_COLOR_SET;
    wgtInvalidatePaint(sSample);
    showResult("dvxColorDialog: 0x%06" PRIX32, sColor);
}
Note
DVX BASIC’s colors are &HBBGGRR, as Visual Basic’s are. A library that hands colors to BASIC converts with wgtBasicColor (dvxWgt.h).

dvxFontDialog(ctx, title, flags, &choice) shows lists of the font families, the four styles (Regular, Bold, Italic, Bold Italic), and the sizes the family has in that style; Underline and Strikeout boxes; a License button for the font’s license; and a sample in the font chosen. A DvxFontChoiceT names a font the way wgtSetFont and dvxFontOpen take one: family (up to FONT_FAMILY_MAX characters with the NUL), size in pixels, and style, the FONT_STYLE_* bits, the underline and strikeout lines included. It holds the starting font (a family DVX does not have starts on System, and the size nearest the one given is selected) and receives the one chosen, and is left alone on Cancel. DVX_FONT_DLG_FIXED in flags offers only fixed-pitch families, for a text editor or a terminal. The title is “Font” when NULL.

The example starts from the sample’s own font, which wgtFont and dvxFontFamilyOf (dvxText.h) describe, and sets the one chosen. A bigger font makes the sample taller, so the window is fitted to its widgets again (Chapter 4):

static void onFont(WidgetT *w) {
    AppContextT       *ac  = sCtx->shellCtx;
    const BitmapFontT *cur = wgtFont(sSample);
    DvxFontChoiceT     choice;

    (void)w;
    snprintf(choice.family, sizeof(choice.family), "%s", dvxFontFamilyOf(cur));
    choice.size  = cur->pixelSize;
    choice.style = cur->style;

    if (!dvxFontDialog(ac, "Sample Font", 0, &choice)) {
        showResult("dvxFontDialog: canceled");
        return;
    }

    if (!wgtSetFont(sSample, choice.family, choice.size, choice.style)) {
        dvxErrorBox(ac, DIALOGS_TITLE, "There is not enough memory for that font.");
        return;
    }

    // The sample may be taller now
    dvxFitWindow(ac, sWin);
    showResult("dvxFontDialog: %s, %" PRId32 " pixels", choice.family, choice.size);
}

Fonts themselves — what families DVX has, opening one, drawing with it — are in Chapter 9.

7.7. Dialog Boxes of Your Own

When a dialog needs more than one answer, build it from widgets with five calls that give it everything the standard dialogs have: it is modal and blocking, Enter chooses OK, Esc and closing it cancel, a dialog it opens stacks on it, and it ends cleanly if your program is ended meanwhile.

typedef bool (*DvxDialogOkFnT)(WindowT *dlg, void *userCtx);

WindowT *dvxDialogCreate(AppContextT *ctx, const char *title, int32_t contentW);
WidgetT *dvxDialogAddField(WindowT *dlg, const char *label, int32_t labelW, int32_t maxLen, const char *value);
void     dvxDialogAddOkCancel(WindowT *dlg, const char *okLabel, DvxDialogOkFnT onOk, void *userCtx);
void     dvxDialogEnd(WindowT *dlg, bool accepted);
bool     dvxDialogRun(AppContextT *ctx, WindowT *dlg);

dvxDialogCreate makes the dialog’s window, with an empty widget root in dlg→widgetRoot, and returns NULL when it cannot. Put any widgets you like under the root. dvxDialogAddField adds the common row: a label labelW pixels wide and a text box of up to maxLen characters, starting with value, which fills the rest of the row. It returns the text box, whose parent is the row, so a Browse…​ button can go after it with wgtButton(box→parent, "&Browse…​"). Give every field’s label the same labelW and the boxes line up. dvxDialogAddOkCancel, called after your widgets are in, adds OK (labeled okLabel, or "&OK" when NULL) and Cancel at the right below them, and makes them the dialog’s default and cancel buttons. dvxDialogRun fits the window to its widgets (contentW wide, or wider when the widgets need it), centers it, runs it until it ends, destroys it, and returns true when it ended with OK.

The dialogs example’s Custom…​ asks for a name and an age. The dialog’s state is a structure on the stack of the callback that runs it, which is safe because dvxDialogRun does not return until the dialog is gone:

static void onCustom(WidgetT *w) {
    AppContextT  *ac  = sCtx->shellCtx;
    WindowT      *dlg = dvxDialogCreate(ac, DIALOGS_FORM_TITLE, DIALOGS_FORM_W);
    DialogsFormT  form;

    (void)w;

    if (!dlg) {
        return;
    }

    memset(&form, 0, sizeof(form));
    form.nameBox = dvxDialogAddField(dlg, "&Name:", DIALOGS_FORM_LABEL_W, DIALOGS_NAME_MAX - 1, "");
    form.ageBox  = dvxDialogAddField(dlg, "&Age:", DIALOGS_FORM_LABEL_W, DIALOGS_AGE_LEN, "");
    dvxDialogAddOkCancel(dlg, NULL, onFormOk, &form);

    // dvxDialogRun fits the dialog to its widgets, so the width it keeps
    // comes from them: the name box is made wide enough for a name
    if (form.nameBox) {
        form.nameBox->minW = wgtChars(DIALOGS_NAME_CHARS);
    }

    wgtSetFocused(form.nameBox);

    if (dvxDialogRun(ac, dlg)) {
        showResult("Custom: %s, age %" PRId32, form.name, form.age);
    } else {
        showResult("Custom: canceled");
    }
}

The onOk function runs when the user chooses OK, while the widgets still exist. It copies their values out and returns true to let the dialog close, or tells the user what is wrong and returns false to keep it open. It never runs for Cancel. Here it checks both fields, and puts the focus in the one to fix:

// The custom dialog's OK.  Both fields are checked before the dialog
// closes; a wrong one is reported, gets the focus, and keeps it open.
static bool onFormOk(WindowT *dlg, void *userCtx) {
    DialogsFormT *form    = (DialogsFormT *)userCtx;
    AppContextT  *ac      = sCtx->shellCtx;
    const char   *ageText = dvxSkipWs(wgtGetText(form->ageBox));
    char         *end     = NULL;
    int32_t       age     = (int32_t)strtol(ageText, &end, DIALOGS_DECIMAL);

    (void)dlg;

    if (dvxCopyTrimmed(form->name, sizeof(form->name), wgtGetText(form->nameBox)) == 0) {
        dvxErrorBox(ac, DIALOGS_FORM_TITLE, "Type a name.");
        wgtSetFocused(form->nameBox);
        return false;
    }

    if (end == ageText || *dvxSkipWs(end) != '\0' || age < DIALOGS_AGE_MIN || age > DIALOGS_AGE_MAX) {
        char msg[DIALOGS_MSG_MAX];

        snprintf(msg, sizeof(msg), "Type an age from %d to %d.", DIALOGS_AGE_MIN, DIALOGS_AGE_MAX);
        dvxErrorBox(ac, DIALOGS_FORM_TITLE, msg);
        wgtSetFocused(form->ageBox);
        return false;
    }

    form->age = age;
    return true;
}

A few rules go with the kit:

  • Every dialog dvxDialogCreate made must be run, even one you no longer want: its state is freed by dvxDialogRun.

  • The dialog keeps its state in the window’s userData and installs its own onKey and onClose. Leave those three alone; use userCtx for your own data.

  • contentW is the dialog’s least width: dvxDialogCreate makes it the root’s minW, and dvxDialogRun keeps it, growing the dialog only when a row needs more. A widget’s minimum width, as the example gives the name box with wgtChars, can widen it further.

  • wgtSetFocused before dvxDialogRun chooses where the keyboard starts. Without it, the first control that takes the focus gets it.

A widget of your own can end the dialog too. dvxDialogEnd(dlg, true) acts like OK (your onOk runs first and can refuse), and dvxDialogEnd(dlg, false) like Cancel. A list whose double click should choose its item is the usual case:

static void onListDblClick(WidgetT *w) {
    dvxDialogEnd(w->window, true);
}

Use it only on a dialog made by dvxDialogCreate.

7.7.1. Default and Cancel Buttons in Any Window

The Enter and Esc rules are not special to dialogs. dvxSetWindowButtons(win, defaultBtn, cancelBtn) gives any window with widgets a default button, which Enter presses unless the control with the focus uses Enter itself, and a cancel button, which Esc presses once no menu or drop-down list is open. Either may be NULL, and a disabled or hidden button is not pressed. The keys run the button’s onClick directly. This is the widget layer’s work, so it needs a window whose onKey is the one wgtInitWindow installed, or a hook that calls it (Section 8.5). A search window, for example, makes Find its default button so the user can type and press Enter:

dvxSetWindowButtons(sWin, findBtn, closeBtn);

7.7.2. A Modal Window That Does Not Wait

The dialogs above block their caller. A window can also be modal without blocking anything: dvxModalBegin(ctx, win) makes it the window that takes all input, dvxModalEnd(ctx, win) lets go, and between the two your code runs in callbacks as usual. This suits a window that must be answered first while your program goes on working in its callbacks, such as a progress window with a Cancel button whose work runs on a timer (Chapter 11). Remember that it holds the whole desktop, as a dialog does:

dvxModalBegin(ac, sProgressWin);

// ... later, in the Cancel button's onClick or when the work is done:
dvxModalEnd(ac, sProgressWin);
dvxDestroyWindow(ac, sProgressWin);

Each dvxModalBegin needs its dvxModalEnd. Modal windows stack, so the window that was modal before is modal again after. A modal window that is hidden or destroyed stops being modal by itself, which is how the dialogs survive a program being ended. Chapter 4 has more on windows that work together.

7.8. Things to Know

Two behaviors are worth knowing when you use these dialogs:

  • dvxButtonBox measures its buttons' labels: its box widens to fit its row of buttons, however long their labels are.

  • dvxFileDialog never returns a path cut short. When the chosen path does not fit outPathSize, it says “The path is too long.” (in a box titled Invalid Filename, or Invalid Folder for the folder dialog) and stays open, so true always means outPath holds the whole path, and false that the user canceled. With a buffer of DVX_MAX_PATH bytes it never comes to that.

Chapter 8. The Keyboard, the Mouse, and the Clipboard

DVX reads the keyboard and the mouse once a frame, in its event loop, and hands what it finds to callbacks: the focused window’s, and through the widget layer, the focused widget’s or the widget under the pointer’s. Nothing waits for input and nothing queues it for later; your callback runs, returns, and the loop goes on. This chapter follows a key and a mouse event from the hardware to your code, shows what each callback receives and in what order, and then covers mouse pointers, the clipboard, and dragging.

Most programs never look at a raw key: a text box edits, a button clicks, a list scrolls, and the program hears about it through onChange and onClick (Chapter 5). Read this chapter when you need more: a shortcut, a filter on what can be typed, a window you draw yourself, or a mouse drag.

8.1. The Keys Program

The example keys lists the events its window gets, newest last. Its window has a text box, a Capitals check box, a white pad, two lines that follow the mouse, the list, and three buttons that use the clipboard. Build and install it as usual:

$ cd src/cGuide/examples/keys
$ make
$ make install DVX_DIR=/path/to/dvx
The Keys window with Hi typed, the pad, the window and pad mouse lines, and a log of key and mouse events
Figure 14. The Keys program after typing Hi and a click on its pad

Type a letter in the text box and the list grows by five lines: the window’s onKey, the text box’s KeyDown and KeyPress, and, when the key goes up, the window’s onKeyUp and the text box’s KeyUp. Click the pad and it says MouseDown, MouseUp, and Click. The rest of the chapter explains each line. The program uses the widgets of Chapter 5 and a ListBox as its log; its one helper of interest adds a line and keeps the newest in view:

// Add a line to the end of the list, keeping the last KEYS_LOG_MAX, and
// scroll it into view.
static void logLine(const char *fmt, ...) {
    char    line[KEYS_LINE_MAX];
    va_list args;

    va_start(args, fmt);
    vsnprintf(line, sizeof(line), fmt, args);
    va_end(args);

    wgtListBoxAddItem(sLog, line);

    if (wgtListBoxGetItemCount(sLog) > KEYS_LOG_MAX) {
        wgtListBoxRemoveItem(sLog, 0);
    }

    wgtListBoxSetTopIndex(sLog, wgtListBoxGetItemCount(sLog) - 1);
}

8.2. Key Codes

DVX reads typed keys from the PC BIOS, which reports each keystroke as a character and a scan code, and turns the pair into one int32_t key code (dvxTypes.h):

  • A key that types a character gives the character, 0x01 to 0xFF: 'a' or 'A' as Shift says, '7', '%'. So do the keys with ASCII codes of their own: KEY_ENTER (0x0D), KEY_TAB (0x09), KEY_BACKSPACE (0x08), KEY_ESCAPE (0x1B), and KEY_SPACE (0x20). Ctrl with a letter gives its control code, 0x01 for Ctrl+A to 0x1A for Ctrl+Z (KEY_CTRL_A, KEY_CTRL_C, KEY_CTRL_V, KEY_CTRL_X, and KEY_CTRL_Z are defined). KEY_IS_ASCII(key) is true for all of these.

  • Every other key gives KEY_EXT_FLAG (0x100) ORed with its BIOS scan code: KEY_F1 to KEY_F12, KEY_UP, KEY_DOWN, KEY_LEFT, KEY_RIGHT, KEY_HOME, KEY_END, KEY_PGUP, KEY_PGDN, KEY_INSERT, and KEY_DELETE. The gray navigation keys and the keypad’s (with Num Lock off) give the same codes.

  • Shift, Ctrl, or Alt with a function key, and Shift or Alt with a gray navigation key, give the plain key’s code; the modifier is in the modifier argument. Shift+F5 is KEY_F5 with Shift, and Alt+Up is KEY_UP with Alt.

  • Alt with a letter or digit types nothing, so it gives KEY_EXT_FLAG and the BIOS’s code for the combination: Alt+A is 0x11E. platformAltScanToChar(key & ~KEY_EXT_FLAG) gives back 'a'.

  • A few combinations have BIOS codes of their own: Ctrl+Left and Ctrl+Right are KEY_CTRL_LEFT and KEY_CTRL_RIGHT, Ctrl+Home and Ctrl+End are KEY_CTRL_HOME and KEY_CTRL_END, Ctrl+Enter is 0x0A, and Ctrl+Backspace is 0x7F (KEY_ASCII_DEL, not KEY_DELETE). The Keys program shows the code of any key you press.

Shift, Ctrl, and Alt pressed alone type nothing, so they give no key code.

The program names the codes it logs with a table and the ranges above:

// A key code's name: a named key, F1 to F12, a printable character, or
// Ctrl and a letter; "" for any other code (an Alt+letter press, the
// scan code of a character key going up).
static void keyName(int32_t key, char *out, int32_t outSize) {
    out[0] = '\0';

    if (key >= KEY_F1 && key <= KEY_F10) {
        snprintf(out, outSize, "F%" PRId32, key - KEY_F1 + 1);
        return;
    }

    for (int32_t i = 0; i < DVX_ARRAY_LEN(sKeyNames); i++) {
        if (sKeyNames[i].key == key) {
            snprintf(out, outSize, "%s", sKeyNames[i].name);
            return;
        }
    }

    if (key >= KEY_ASCII_PRINT_FIRST && key <= KEY_ASCII_PRINT_LAST) {
        snprintf(out, outSize, "'%c'", (char)key);
    } else if (key >= KEY_CTRL_A && key <= KEY_CTRL_Z) {
        snprintf(out, outSize, "Ctrl+%c", (char)(key - KEY_CTRL_A + 'A'));
    }
}

8.2.1. Modifiers

Each key comes with the state of the modifier keys, the BIOS shift-state byte: KEY_MOD_SHIFT (0x03, either Shift; KEY_MOD_LSHIFT 0x02 and KEY_MOD_RSHIFT 0x01 tell them apart), KEY_MOD_CTRL (0x04), and KEY_MOD_ALT (0x08). DVX passes only these bits: the BIOS’s toggles above them (Scroll Lock, Num Lock, Caps Lock, and Insert) are left out, so mod == KEY_MOD_CTRL is true for Ctrl alone whatever the lock keys are. Test single bits (mod & KEY_MOD_CTRL) when other modifiers may be held too.

ctx→keyModifiers holds the same byte as of the last frame, for code that is not handed one.

8.3. Who Gets a Key

A typed key goes to the window with the focus, but DVX and the window’s menus see it first. The first of these that wants the key takes it, and nothing after it sees the key:

  1. The window switcher: Alt+Tab and Shift+Alt+Tab open it, and while it is up it takes every key.

  2. Alt+F4 asks the focused window to close (only the dialog’s, while a dialog is up; Chapter 7).

  3. Ctrl+Esc opens the Task Manager, even over a dialog (Section 7.2).

  4. A window in game input mode, or one that has taken the whole screen, gets every other key in its onKey, unless a menu is open (Section 8.9).

  5. Ctrl+F12 saves a picture of the screen, and Ctrl+Shift+F12 one of the focused window.

  6. F1 opens help (Chapter 20).

  7. F10 opens the window’s menu bar, or the one its menuWinId names (Chapter 4), and does nothing in a window with neither.

  8. The keyboard Move and Size modes of the window menu take every key while they run.

  9. Alt+Space opens the window menu, which then takes its keys.

  10. System-wide hotkeys (Section 8.8), but not while a menu or a dialog is up.

  11. Alt and a letter: the menu bar title with that access key, else the control with it (a label’s passes to the control after it; Chapter 5). A letter no one has goes on down the list. With a menu open, the menu is closed first.

  12. An open menu takes every key (Chapter 6).

  13. Esc closes an open drop-down list.

  14. The window’s accelerator table: Ctrl+S and the like, which call onMenu (Chapter 6). A table on a window without onMenu does nothing.

  15. Tab and Shift+Tab move the focus to the next or the previous control. The key goes on to onKey only when the control with the focus takes Tab itself (a text area set to capture tabs), or the focus has nowhere to go: the window has no widgets, or only one that can take the focus, or none.

  16. The window’s onKey.

The keys DVX keeps in steps 1 to 3, 5 to 7, and 9 are kept with any other modifier added too (Ctrl+Alt+F4 closes a window), except F1 and F10, which are kept only alone; Shift+F1 reaches your program. Ctrl+Alt+Del restarts the computer and reaches nothing. dvxSystemKeyUse(key, mods) says what DVX does with a key it keeps ("closes the active window") and returns NULL for any other key, for a program that lets the user choose a shortcut and must refuse these.

In a window with widgets, onKey is the widget layer’s (Section 8.4), which goes on:

  1. Enter presses the window’s default button, unless the control with the focus uses Enter itself, and Esc presses its cancel button (dvxSetWindowButtons, Section 7.7.1).

  2. The control with the focus gets the key: its onKeyDown, then its onKeyPress if the key is a character, and then the control acts on it.

A key the focused control does not use is dropped. Keys do not bubble up to the control’s containers or back to the window.

8.3.1. Keys Going Up

The BIOS reports only keys going down. DVX also watches the keyboard itself (it chains the keyboard interrupt) and reports each key going up to the focused window’s onKeyUp(win, scancode, mod), after that frame’s typed keys. Its code is always KEY_EXT_FLAG ORed with the key’s scan code. For the keys whose KEY_* constant is built from a scan code — the arrows, the function keys, Home, Delete, and the rest — that is the same value onKey got, so KEY_UP goes down and KEY_UP comes up. For a key that types a character it is not: A goes down as 'a' (0x61) and comes up as 0x11E, and Enter goes down as KEY_ENTER (0x0D) and comes up as KEY_SCAN_ENTER ORed with KEY_EXT_FLAG (0x11C). Shift, Ctrl, and Alt come up too (Left Shift as 0x12A, either Ctrl as 0x11D), though they never went down as far as onKey was concerned, and mod is the modifier state as DVX passes the release on. The keys DVX keeps from every program (Alt+Tab, Alt+F4, and Ctrl+Esc) report nothing at all. A key released after the focus moved goes to the window that has the focus then.

Use onKeyUp for what happens while a key is held, matching it to the press by scan code, and onKey for what was typed.

8.4. Keys in Widgets

Three callbacks of a widget hear the keys it gets while it has the focus:

void (*onKeyDown)(WidgetT *w, int32_t keyCode, int32_t shift);
void (*onKeyPress)(WidgetT *w, int32_t keyAscii);
void (*onKeyUp)(WidgetT *w, int32_t keyCode, int32_t shift);

onKeyDown gets every key that reaches the widget, with the key code (Section 8.2) and the modifier byte (Section 8.2.1). onKeyPress follows it for a key that is a character (KEY_IS_ASCII). Both run before the widget acts on the key, as KeyDown and KeyPress do in Visual Basic, so they see the widget as it was. onKeyUp gets the window’s key releases, with the codes of Section 8.3.1, while the widget has the focus. A disabled or hidden widget, or one in a disabled or hidden container, gets nothing.

The Keys program logs all three for its text box:

static void onInputKeyDown(WidgetT *w, int32_t keyCode, int32_t shift) {
    (void)w;
    logKey("KeyDown", keyCode, shift);
}


// With Capitals checked, a small letter is typed as a capital: the text
// box acts on the key wgtKeyReplace gives it instead.
static void onInputKeyPress(WidgetT *w, int32_t keyAscii) {
    (void)w;
    logKey("KeyPress", keyAscii, 0);

    if (wgtCheckboxIsChecked(sCaps) && keyAscii >= 'a' && keyAscii <= 'z') {
        wgtKeyReplace(keyAscii - 'a' + 'A');
    }
}


static void onInputKeyUp(WidgetT *w, int32_t keyCode, int32_t shift) {
    (void)w;
    logKey("KeyUp", keyCode, shift);
}

wgtKeyReplace(key), called from onKeyDown or onKeyPress, changes the key the widget acts on: with Capitals checked, onKeyPress hands the text box 'A' for 'a', and the capital is what appears. wgtKeyReplace(0) cancels the key, so the widget does nothing with it (and after onKeyDown, no onKeyPress follows). Outside those two callbacks it does nothing. A text box that takes only digits needs one test:

static void onDigitsKeyPress(WidgetT *w, int32_t keyAscii) {
    (void)w;

    if (keyAscii >= KEY_ASCII_PRINT_FIRST && keyAscii <= KEY_ASCII_PRINT_LAST && (keyAscii < '0' || keyAscii > '9')) {
        wgtKeyReplace(0);
    }
}

It tests the printable range so that Backspace, Enter, and the control keys (Ctrl+C and the rest) still work. A filter on keys cannot catch a paste: check the text in onChange or when it is used as well.

8.5. Seeing a Window’s Keys First

wgtInitWindow makes a window’s widgets work by installing its own handlers in the window: onPaint, onMouse, onKey, onKeyUp, onResize, onFocus, and onBlur. To see the window’s keys or mouse before its widgets do, save the handler it installed, put yours in its place, and call the saved one from yours. Do it after wgtInitWindow, which would otherwise overwrite yours:

    // Hook the window's key and mouse handlers in front of the ones
    // wgtInitWindow installed, which the hooks call in turn.
    sWidgetKey          = sWin->onKey;
    sWidgetKeyUp        = sWin->onKeyUp;
    sWidgetMouse        = sWin->onMouse;
    sWin->onKey         = onWinKey;
    sWin->onKeyUp       = onWinKeyUp;
    sWin->onMouse       = onWinMouse;
    sWin->onCursorQuery = onWinCursor;
// Every key the window gets, before the widgets do: logged, then handed
// to the widget layer's handler.
static void onWinKey(WindowT *win, int32_t key, int32_t mod) {
    logKey("onKey", key, mod);
    sWidgetKey(win, key, mod);
}


static void onWinKeyUp(WindowT *win, int32_t scancode, int32_t mod) {
    logKey("onKeyUp", scancode, mod);
    sWidgetKeyUp(win, scancode, mod);
}

Your hook gets every key that came down the list of Section 8.3 as far as onKey. It can act on the key and return without passing it on, and then no widget sees it. This is how the Keys program’s list shows onKey before KeyDown for every key, and why Tab and Alt+C (the check box’s access key) leave no onKey line: DVX used them before the window’s turn came. The functions the hooks call are also declared, as widgetOnKey, widgetOnKeyUp, and widgetOnMouse, in dvxWgtP.h, the header for writing widgets (Chapter 19); saving the pointer works without it, and goes on working whatever handler was there.

onCursorQuery and onClose are not installed by wgtInitWindow, so the program sets them directly. The window’s focus handlers have their own rule: a replacement onFocus or onBlur must call widgetOnFocus or widgetOnBlur (declared in dvxWgt.h), or the widgets lose track of the focus (Section 8.7).

8.6. Windows Without Widgets

A window that draws its content itself (Chapter 9) and has no widget tree gets the keys in its own onKey(win, key, mod) and onKeyUp(win, scancode, mod), with the codes above. It also handles everything the widget layer would have: it shows its own focus and selection, and there are no default or cancel buttons, no access keys of controls, and no double clicks (Section 8.10.3). Tab and Shift+Tab reach its onKey like any other key, since there is no widget tree to move the focus in (step 15 of the list).

8.7. Focus

Two things have the focus. One window has it, the active one in front, whose title bar shows it, and it gets the keys. In that window, one widget has it, and gets the keys the window passes on. wgtSetFocused(w) gives the focus to a widget (it refuses one that is disabled, hidden, or in a disabled container), and wgtGetFocused() returns the widget that has it, in any window, or NULL. A click on a control that can take the focus gives it the focus; a click on one that cannot — a label, a picture, a canvas, empty space — leaves the focus where it was, and so does a click on the window’s title bar, frame, or menu bar. Tab goes through the controls in the order they are in the widget tree (Chapter 5).

A widget’s onFocus(w) runs when it gets the focus and onBlur(w) when it loses it:

static void onInputBlur(WidgetT *w) {
    (void)w;
    logLine("LostFocus");
}


static void onInputFocus(WidgetT *w) {
    (void)w;
    logLine("GotFocus");
}

When the window loses the focus to another window, its focused widget gets onBlur, and when the window gets the focus back, the same widget gets it back with onFocus: watch the Keys list while you click another window and then the Keys window again. A text box’s selection survives the trip, so an Edit menu command can still act on it. Validate a field in onBlur only if you can live with that: the user switching to another program also blurs it.

A window’s own onFocus(win) and onBlur(win) run when the window gets and loses the focus; in a window with widgets, chain them to widgetOnFocus and widgetOnBlur as described above. Raising and focusing windows from code is in Chapter 4.

8.8. Shortcuts That Work Everywhere

A window’s accelerator table (Chapter 6) works while that window has the focus. A hotkey works whichever window has the focus, or none:

typedef void (*DvxHotkeyFnT)(void *userCtx);

int32_t dvxRegisterHotkey(AppContextT *ctx, int32_t key, int32_t modifiers, DvxHotkeyFnT fn, void *userCtx);
bool    dvxUnregisterHotkey(AppContextT *ctx, int32_t hotkeyId);

key and modifiers are given as for dvxAddAccel: a character or a KEY_* code, and ACCEL_CTRL, ACCEL_ALT, and ACCEL_SHIFT (the same bits as KEY_MOD_*). Letters match in either case. When the key is pressed, fn(userCtx) runs, before the focused window’s menu keys and accelerators, but not while a menu or a dialog is up. A hotkey needs Ctrl or Alt unless it is a function or navigation key (one with KEY_EXT_FLAG), so hotkeys cannot eat typing. The call returns the hotkey’s id, or DVX_HOTKEY_NONE (0) when it refuses: a bad key, a NULL function, a key DVX keeps, or one that is already a hotkey. A hotkey belongs to the program that registered it, and DVX removes it when the program ends. Program Manager’s shortcut keys are hotkeys, so take care not to claim a combination a user is likely to have given a program.

sNoteKey = dvxRegisterHotkey(ac, 'N', ACCEL_CTRL | ACCEL_ALT, onNoteHotkey, NULL);

if (sNoteKey == DVX_HOTKEY_NONE) {
    dvxLog("notes: Ctrl+Alt+N is taken");
}

8.9. Game Input and Held Keys

A game wants every key and wants to know which keys are down, not what was typed. Setting win→gameInput = true gives it both while the window has the focus: every key but Alt+Tab, Ctrl+Esc, and Alt+F4 goes to onKey (no help, menus, access keys, accelerators, or hotkeys), and onRawKey(win, evt) gets each key going down and up as a RawKeyEventT: the keyboard’s scan code, whether it came behind the 0xE0 prefix (the gray keys, right Ctrl and Alt), whether it went down, whether it is a typematic repeat, and the modifiers. In this code, left and right Shift, Ctrl, and Alt are keys of their own, and a key’s code does not change with the modifiers. When the window loses the focus, onRawKey gets a release for every key still down. platformKeyIsDown(KEY_RAW_CODE(scan, extended)) asks whether a key is down now. The game library (game.h) builds held keys and frame pacing on these; Chapter 17 shows them in use.

8.10. The Mouse

DVX polls the mouse driver once a frame for the pointer’s position and buttons, and compares them with the last frame’s to find presses, releases, and moves. A button is MOUSE_LEFT (1), MOUSE_RIGHT (2), or MOUSE_MIDDLE (4) in a mask of the buttons held. The user’s settings — speed, the double-click interval, the wheel’s direction and step — come from Control Panel; a program reads them (ctx→dblClickMs, ctx→wheelStep) but leaves them alone. ctx→mouseX, ctx→mouseY, and ctx→mouseButtons hold the pointer’s screen position and buttons as of the last frame, for code that needs them outside a mouse callback, such as placing a pop-up menu at the pointer.

8.10.1. Mouse Events in Widgets

Five callbacks of a widget hear the mouse when it is over the widget:

void (*onClick)(WidgetT *w);
void (*onDblClick)(WidgetT *w);
void (*onMouseDown)(WidgetT *w, int32_t button, int32_t x, int32_t y);
void (*onMouseUp)(WidgetT *w, int32_t button, int32_t x, int32_t y);
void (*onMouseMove)(WidgetT *w, int32_t button, int32_t x, int32_t y);

x and y are relative to the widget: (0, 0) is its top-left corner, or the first pixel inside the border of a widget that has one drawn in, such as a canvas, so on a canvas they are the drawing’s coordinates. In onMouseDown and onMouseUp, button is which button: MOUSE_LEFT (1), MOUSE_RIGHT (2), or MOUSE_MIDDLE (4), the numbers Visual Basic uses. In onMouseMove it is the mask of the buttons held, with the same bits, and 0 for a plain move.

The Keys program’s pad logs them:

static void onPadClick(WidgetT *w) {
    (void)w;
    logLine("Click");
}


static void onPadDblClick(WidgetT *w) {
    (void)w;
    logLine("DblClick");
}


// The canvas's own mouse callback: the left press (drag false) captures
// the mouse, and every move until the button goes up comes here (drag
// true), wherever the pointer is.
static void onPadDrag(WidgetT *w, int32_t cx, int32_t cy, bool drag) {
    (void)w;

    if (drag) {
        setLabel(sPadStatus, "Pad: %" PRId32 ", %" PRId32 " (captured)", cx, cy);
    }
}


static void onPadMouseDown(WidgetT *w, int32_t button, int32_t x, int32_t y) {
    (void)w;
    logLine("MouseDown button %" PRId32 " at %" PRId32 ", %" PRId32, button, x, y);
}


static void onPadMouseMove(WidgetT *w, int32_t button, int32_t x, int32_t y) {
    (void)w;
    (void)button;
    setLabel(sPadStatus, "Pad: %" PRId32 ", %" PRId32, x, y);
}


static void onPadMouseUp(WidgetT *w, int32_t button, int32_t x, int32_t y) {
    (void)w;
    logLine("MouseUp   button %" PRId32 " at %" PRId32 ", %" PRId32, button, x, y);
}
    sInput->weight     = WGT_WEIGHT_FILL;
    sInput->onKeyDown  = onInputKeyDown;
    sInput->onKeyPress = onInputKeyPress;
    sInput->onKeyUp    = onInputKeyUp;
    sInput->onFocus    = onInputFocus;
    sInput->onBlur     = onInputBlur;
    sInput->onScroll   = onInputScroll;

    sPad->onClick     = onPadClick;
    sPad->onDblClick  = onPadDblClick;
    sPad->onMouseDown = onPadMouseDown;
    sPad->onMouseUp   = onPadMouseUp;
    sPad->onMouseMove = onPadMouseMove;
    wgtCanvasSetMouseCallback(sPad, onPadDrag);

Click the pad and the list says MouseDown button 1, then MouseUp button 1, then Click. When onClick comes depends on the widget:

  • Most widgets, a canvas, a label, a picture, a frame, a text box, get onClick at the release, after onMouseUp, as in Visual Basic, and only when the left button comes up over the widget that was pressed. The press holds the mouse: its onMouseUp goes to the widget pressed, wherever the release is.

  • Buttons, check boxes, and option buttons get it when the left button comes up over them, so moving off before letting go cancels the click, as in Windows. Space and their access keys click them too.

  • The lists (ListBox, ListView, TreeView, ComboBox, Dropdown) get it when the user picks an item, after onMouseDown, and after onChange when the pick changed the selection; picking with the keys raises it too. A press that picks nothing gives no onClick.

  • A press of any button on a control’s own furniture, its scroll bars, the corner between them, or a list’s column headings and their borders, gives no onClick, onDblClick, onMouseDown, or onMouseUp, and no onMouseMove comes while it is held, as Visual Basic raises none there; the control just scrolls or sorts.

A second press of the left button within the user’s double-click interval (500 ms unless changed in Control Panel) and less than 4 pixels from the first is a double click. A widget with an onDblClick gets it at that press, with no onMouseDown, and the release then gives only onMouseUp: a double click is onMouseDown, onMouseUp, onClick, onDblClick, onMouseUp. A widget without onDblClick gets a second click instead. A third quick press is another double click, and a press on a control’s content just after one on its scroll bar or heading never is. So a widget that does one thing on a click and another on a double click gets both, click first, and should make the click’s action one that the double click can build on: select, then open.

The right button gives onMouseDown and onMouseUp with button 2 to the widget under the pointer, which is also how context menus open: a widget or window with a contextMenu shows it on the right press, without any code (Chapter 6). The middle button gives button 4, and unlike the others it does not bring its window to the front.

8.10.2. Capturing the Mouse

While a button is held, where do the moves go? For most widgets, nowhere special: onMouseMove goes to whatever widget is under the pointer at the time, so a widget sees a drag only while the pointer stays on it, though the left release comes back to the widget that was pressed (Section 8.10.1). The widgets that track a drag — buttons waiting for the release, sliders, scroll panes, text boxes selecting text, lists, splitters, and a canvas that has a mouse callback — capture the mouse on a left press: from then on they get every move and the release, wherever the pointer goes, until the button comes up.

A program’s way to capture is the Canvas widget’s mouse callback, wgtCanvasSetMouseCallback(w, fn). The left press calls fn(w, x, y, false) and captures the mouse, each move until the release calls fn(w, x, y, true), and the release goes to the canvas’s onMouseUp. The Keys program’s pad shows the captured position, which goes negative or past the pad’s size when you drag outside it; release outside the pad and MouseUp still says button 1, from the pad. While the canvas has the mouse, its onMouseMove is not called: the callback gets the moves. A drawing program uses it for strokes (Chapter 9).

8.10.3. The Mouse at the Window Level

Under the widgets, the window gets the raw mouse in onMouse(win, x, y, buttons): x and y relative to the window’s content area, and buttons the mask of the buttons held. There are no presses or releases as such; compare buttons with the last call’s to find them. The Keys program shows it on its first status line, then passes the call on:

// The mouse as the window sees it: content coordinates and the buttons
// held.  The window with the focus gets every move, wherever the pointer
// is.
static void onWinMouse(WindowT *win, int32_t x, int32_t y, int32_t buttons) {
    setLabel(sWinStatus, "Window: %" PRId32 ", %" PRId32 " buttons %s%s%s", x, y, (buttons & MOUSE_LEFT) ? "L" : "-", (buttons & MOUSE_MIDDLE) ? "M" : "-", (buttons & MOUSE_RIGHT) ? "R" : "-");
    sWidgetMouse(win, x, y, buttons);
}

The rules for which window gets the call are the window-level capture:

  • A left or right press goes to the window under the pointer, and only on its content area; a press on a window that is not in front brings it to the front, gives it the focus, and is then delivered to it as well.

  • Every move goes to the focused window, wherever the pointer is: outside the window, x and y are negative or past its size. So does the left button’s release. A window that saw the press therefore sees the whole drag.

  • The right button’s release, and the middle button going down or up, go to the window under the pointer.

  • While a dialog is up (Section 7.2), only the dialog gets any of them.

A window without widgets finds the presses and releases itself, comparing each call’s buttons with the last call’s:

static void onCanvasMouse(WindowT *win, int32_t x, int32_t y, int32_t buttons) {
    bool pressed  = (buttons & MOUSE_LEFT) && !(sLastButtons & MOUSE_LEFT);
    bool released = !(buttons & MOUSE_LEFT) && (sLastButtons & MOUSE_LEFT);

    sLastButtons = buttons;

    if (pressed) {
        startStroke(win, x, y);
    } else if (released) {
        endStroke(win, x, y);
    } else if (buttons & MOUSE_LEFT) {
        continueStroke(win, x, y);
    }
}

It times its own double clicks too: platformClock() gives the time of a press in ticks, and ctx→dblClickTicks is the user’s double-click interval in the same ticks.

8.10.4. The Wheel

The wheel goes to the focused window, never the one under the pointer, and to the widget with the focus in it. A list, a text area, or a scroll pane scrolls by itself: the lists scroll their view without moving the selection, other scrolling widgets get Up or Down keys (the user’s wheel step, 3 unless changed, per notch), and failing all that, the window’s scroll bar moves. In every case the focused widget’s onScroll(w, delta) runs too, delta being the notches turned: positive toward the user (down the page), with the user’s reverse setting already applied. The Keys program’s text box, which does not scroll, logs it:

static void onInputScroll(WidgetT *w, int32_t delta) {
    (void)w;
    logLine("Scroll    %+" PRId32, delta);
}

A window without widgets hears the wheel only as its own scroll bar moving (its onScroll, Chapter 4). The wheel works when the DOS mouse driver supports the CuteMouse wheel interface; with an older driver there is none.

8.11. Mouse Pointers

DVX draws the mouse pointer itself, as one of eight 16 by 16 shapes compiled into it (dvxCur.h); a program chooses among them and cannot add its own.

Shape Value Used for

CURSOR_ARROW

0

Everything else

CURSOR_RESIZE_H

1

Resizing left and right: window edges, splitters, column dividers

CURSOR_RESIZE_V

2

Resizing up and down

CURSOR_RESIZE_DIAG_NWSE

3

A window’s top-left and bottom-right corners

CURSOR_RESIZE_DIAG_NESW

4

Its top-right and bottom-left corners

CURSOR_BUSY

5

The hourglass (dvxSetBusy)

CURSOR_CROSSHAIR

6

Placing or drawing something

CURSOR_NO_DROP

7

A drag that cannot drop here (Section 8.13)

DVX chooses the pointer each time the mouse moves. Over a window’s content it asks the window’s onCursorQuery(win, x, y) first, with content coordinates; a shape greater than 0 is used. Otherwise the widget under the pointer chooses (a splitter shows its resize arrows), and otherwise it is the arrow. Because CURSOR_ARROW is 0, returning it means “no opinion”, which is what you want for the parts of the window you do not care about. The Keys program shows the crosshair over its pad; widget positions are in the same content coordinates, so the test is a rectangle:

// The crosshair over the pad; 0 elsewhere leaves the pointer to the
// widgets under it (the arrow, or a splitter's resize arrows).
static int32_t onWinCursor(WindowT *win, int32_t x, int32_t y) {
    (void)win;

    if (x >= sPad->x && x < sPad->x + sPad->w && y >= sPad->y && y < sPad->y + sPad->h) {
        return CURSOR_CROSSHAIR;
    }

    return 0;
}

The pointer changes only when the mouse moves, so a program whose answer changes while the mouse is still (a tool chosen with a key) sees the new pointer at the next move.

dvxSetBusy(ctx, true) shows the hourglass and blocks all input, in every program, until dvxSetBusy(ctx, false); keys typed meanwhile are thrown away. It shows at once, so it can bracket a short operation that does not return to the event loop, such as writing a large file. Anything longer belongs on a task, with a progress bar and a Cancel button (Chapter 11).

8.12. The Clipboard

DVX has one clipboard, shared by every program it runs (they all live in one DOS process), and it holds text:

bool        dvxClipboardCopy(const char *text, int32_t len);
const char *dvxClipboardGet(int32_t *outLen);
void        dvxClipboardClear(void);

dvxClipboardCopy copies len bytes of text into the clipboard, replacing what was there, and returns true; copying nothing (NULL text or a len of 0 or less) empties it. It returns false when memory runs out, and the clipboard is then empty, never still holding what was copied before. dvxClipboardGet returns the clipboard’s text, with a NUL after it and its length in *outLen (outLen may be NULL), or NULL when the clipboard is empty. The pointer is the clipboard’s own: read it or copy it before anything else can copy to the clipboard, and never free it or write to it. dvxClipboardClear empties the clipboard. The bytes are kept as given, so they may hold anything, but text widgets mark a line end with '\n', and a single-line text box drops the line ends from what it pastes.

The Keys program’s Copy Log puts its list on the clipboard, one line each, and says so when the clipboard could not take it:

// The whole list, one line each, onto the clipboard.
static void onCopyLog(WidgetT *w) {
    int32_t count = wgtListBoxGetItemCount(sLog);
    size_t  total = 1;
    char   *text  = NULL;
    size_t  len   = 0;

    (void)w;

    for (int32_t i = 0; i < count; i++) {
        total += strlen(wgtListBoxGetItem(sLog, i)) + 1;
    }

    text = (char *)malloc(total);

    if (!text) {
        dvxErrorBox(sCtx->shellCtx, KEYS_TITLE, "There is not enough memory to copy the list.");
        return;
    }

    for (int32_t i = 0; i < count; i++) {
        const char *item    = wgtListBoxGetItem(sLog, i);
        size_t      itemLen = strlen(item);

        memcpy(text + len, item, itemLen);
        len         += itemLen;
        text[len++]  = '\n';
    }

    // Copying nothing (an empty list) empties the clipboard.  Out of
    // memory, the clipboard is left empty.
    bool copied = dvxClipboardCopy(text, (int32_t)len);

    free(text);

    if (!copied) {
        dvxErrorBox(sCtx->shellCtx, KEYS_TITLE, "The clipboard could not hold the list.");
        return;
    }

    logLine("Copied %" PRId32 " lines", count);
}

and Paste shows what the clipboard holds:

// What the clipboard holds: its size and the start of its first line.
static void onPaste(WidgetT *w) {
    int32_t     len  = 0;
    const char *clip = dvxClipboardGet(&len);

    (void)w;

    if (!clip) {
        logLine("Clipboard is empty");
        return;
    }

    int32_t show = (int32_t)strcspn(clip, "\r\n");

    logLine("Clipboard %" PRId32 " bytes: %.*s", len, (int)DVX_MIN(show, KEYS_CLIP_SHOW), clip);
}

Copy the list, click the text box, and press Ctrl+V: the text box pastes from the same clipboard, the lines run together, as much as its 80 characters hold.

Text boxes and text areas handle Ctrl+X, Ctrl+C, Ctrl+V, Ctrl+A, and Ctrl+Z themselves. For an Edit menu, wgtTextInputCut, wgtTextInputCopy, wgtTextInputPaste, wgtTextInputSelectAll, and wgtTextInputUndo (textInput/textInpt.h) do the same for a text box or a text area, and a text area has them under its own names too, wgtTextAreaCut and the rest, as TinyEdit uses them (Section 6.10).

An accelerator table that claims Ctrl+C for the window takes the key from all of them (Section 8.3).

The clipboard does not hold pictures. A program that moves pictures between its windows keeps them itself, and one that hands a picture to another program saves it to a file (dvxSaveImage, Chapter 9).

8.13. Dragging and Dropping

DVX has no drag-and-drop protocol between programs, and no widget drops onto another. Two things do exist. The list widgets can let the user drag their own items into a new order (wgtListBoxSetReorderable, Chapter 5). And DVX draws the feedback for a drag that your program runs itself:

void dvxDragOutlineShow(AppContextT *ctx, int32_t w, int32_t h, int32_t offX, int32_t offY);
void dvxDragImageShow(AppContextT *ctx, const uint8_t *pixels, int32_t w, int32_t h, int32_t pitch, bool hasKey, uint32_t keyColor);
void dvxDragCursorSet(AppContextT *ctx, int32_t cursorId);
void dvxDragFeedbackHide(AppContextT *ctx);

dvxDragOutlineShow shows a dotted outline w by h pixels that follows the pointer over every window, its top-left corner (offX, offY) from the pointer: usually the dragged object’s size, and where it was grabbed. dvxDragImageShow shows a picture centered on the pointer instead, in the display’s pixel format (as dvxLoadImage gives one; Chapter 9), which must stay valid until it is hidden; with hasKey, pixels of keyColor are transparent. Only one is shown at a time. dvxDragCursorSet sets the pointer during the drag, CURSOR_NO_DROP where a drop cannot land and CURSOR_ARROW where it can, and dvxDragFeedbackHide ends it all and gives the pointer back.

The program does the rest with the mouse events above. The press starts the drag. The window that saw the press gets every move and the left release, wherever the pointer goes (Section 8.10.3), so its onMouse can follow the whole drag; in a window with widgets, hook it (Section 8.5), because the widgets get the moves only while the pointer is over them. Each move decides whether a drop can land under the pointer and sets the pointer to say so, and the release hides the feedback and drops, or does nothing. Dropping on another of the program’s own windows means finding the window under the pointer: wmHitTest(&ctx→stack, ctx→mouseX, ctx→mouseY, &part) returns its index in ctx→stack.windows, or -1 for the desktop (“dvxWm.h — Layer 4: Window Manager” in the DVX C Library Reference). A drag that starts on a widget measures the outline from the widget’s place on the screen:

// In the source widget's onMouseDown: an outline of w where it lies,
// held by the point that was grabbed
WindowT *win = w->window;

dvxDragOutlineShow(ac, w->w, w->h, win->x + win->contentX + w->x - ac->mouseX, win->y + win->contentY + w->y - ac->mouseY);
sDragging = true;

DVX BASIC’s Drag, DragOver, and DragDrop are built this way, on these four calls.

8.14. Things to Know

A few behaviors that the sections above describe are worth keeping in mind:

  • A key’s onKeyUp code differs from its onKey code for keys that type characters.

  • For most widgets the order is Visual Basic’s: onMouseDown, onMouseUp, then onClick when the release is over the widget; buttons click on the release, and lists on the pick.

  • A press on a scroll bar or a list’s column heading fires no mouse event at all.

Chapter 9. Drawing, Images, and Fonts

Everything DVX shows is drawn by the processor into memory, a pixel at a time or a row at a time, and copied to the screen (Section 3.8). A program that wants more than widgets draws the same way, with the same calls DVX’s own widgets use. This chapter covers where a program draws, the Canvas widget, the DisplayT every drawing call draws into and its clip rectangle, the drawing calls, colors and the screen’s pixel formats, fonts and text, pictures from files, off-screen bitmaps, getting what was drawn onto the screen, and what is fast on a 486. Its example, sketch, is a small drawing program: draw with the mouse, add text and pictures, undo, and save the drawing.

The Sketch window with a thin black line, a thick red line, and a medium blue line on its canvas, and the pen in the status line
Figure 15. Sketch with strokes in black, red, and blue, in three pen sizes

9.1. Where a Program Draws

A program draws into one of four places:

  • A Canvas widget, in a window of widgets. The canvas keeps a picture of its own in memory, shows it, reports the mouse, and has calls for lines, rectangles, circles, and text. This is the usual choice, and Sketch’s.

  • The content buffer of a window without widgets. The window’s onPaint callback draws its content (Section 9.9).

  • A widget of your own, whose paint method draws it wherever it sits in a window (Chapter 19).

  • The whole screen, in a video mode of the program’s own: DVX’s full-screen mode, for games (Chapter 17).

Each of these is a buffer of pixels in the screen’s pixel format, and the same drawing calls work on all of them, through a DisplayT that describes the buffer (Section 9.3).

9.2. The Sketch Program

Sketch is one window: a menu bar, a canvas of 320 x 240 pixels, and a status line (a Label) below it. Hold the left button down on the canvas and move the mouse to draw. The Pen menu chooses the pen’s color (white is an eraser) and its size. Edit › Text…​ asks for a line of text and draws it centered where the mouse was last pressed, in a font Edit › Font…​ chooses. File › Insert Picture…​ puts a picture file on the canvas, made smaller to fit when it is too big. Edit › Undo takes back the last change. File › Save writes the drawing to SKETCH.PNG in the program’s user folder, and the next start of Sketch opens it again.

Build it and install it like hello (Section 2.11). It is a callback-only program: appMain builds the window and returns.

9.2.1. Building the Window

sCtx = ctx;
sAc  = ctx->shellCtx;
sWin = dvxCreateWindowCentered(sAc, SKETCH_TITLE, SKETCH_WIN_W, SKETCH_WIN_H, false);

if (!sWin) {
    return -1;
}

sWin->onClose = onClose;
sWin->onMenu  = onMenu;

WidgetT *root = buildMenus() ? wgtInitWindow(sAc, sWin) : NULL;

if (!root) {
    closeWindow();
    return -1;
}

root->spacing = wgtPixels(SKETCH_SPACING);

The window is not resizable: the canvas has a fixed size, and the window is fitted to it at the end of appMain. buildMenus makes the menu bar (Chapter 6 explains menus, and the Pen menu’s radio items in particular). Then the widgets:

sCanvas = wgtCanvas(root, SKETCH_CANVAS_W, SKETCH_CANVAS_H);
sStatus = wgtLabel(root, "");
sFont   = dvxFontOpen(sFontChoice.family, sFontChoice.size, sFontChoice.style);

if (!sCanvas || !sStatus || !sFont) {
    closeWindow();
    return -1;
}

wgtCanvasSetMouseCallback(sCanvas, onCanvasMouse);
wgtCanvasSetPenSize(sCanvas, sSizes[sSize].pixels);

wgtCanvas(parent, w, h) (header canvas/canvas.h) makes a canvas whose drawing is w by h pixels, in the screen’s pixel format, white at first. It returns NULL when a size is 0 or less or memory runs out. The drawing is framed by a sunken border CANVAS_BORDER_WIDTH (2) pixels wide, so the widget’s minimum size is the drawing’s plus 4 in each direction; wgtCanvasSetBorderStyle(w, CANVAS_BORDER_NONE) takes the border away. The drawing does not grow or shrink with the widget: a layout that gives the widget more room fills the rest with the window’s background. (wgtCanvasSetAlign docks a canvas to an edge of its container, Visual Basic’s PictureBox Align; the drawing then follows the widget’s width or height there.) wgtSetBackdrop(canvas, true) makes a canvas the backdrop of its container instead, a picture behind the container’s other widgets: it is not laid out with them but covers the container’s whole box, paints before them, and keeps its drawing at the container’s size as that changes, the new part in the color behind it; a press on it is the container’s, and when it repaints, the widgets over it repaint too. A DVX BASIC form’s drawing is made that way. wgtSetBackdrop(w, false) makes it an ordinary child again.

The pen starts black and 1 pixel wide. Sketch gives the canvas its mouse callback and the pen size it chose, and opens the font for its text (Section 9.6.4). Then it shows the pen in the status line, opens the drawing saved last time, and fits the window:

setCanUndo(false);
showPen();
openSaved();
dvxFitWindow(sAc, sWin);
return 0;

9.2.2. Drawing with the Mouse

// The left button went down on the canvas (drag false), or the mouse moved
// while it is held (drag true).  x and y are canvas coordinates; while the
// button is held the canvas has the mouse, so they can lie outside it.
// Each call draws a line from the last point, so a quick move leaves no
// gaps, and a press draws a dot (a line from the point to itself).
static void onCanvasMouse(WidgetT *w, int32_t x, int32_t y, bool drag) {
    if (!drag) {
        undoSave();
        wgtCanvasSetPenColor(w, penPixel(&sAc->display));
        sLastX = x;
        sLastY = y;
        sMarkX = x;
        sMarkY = y;
    }

    wgtCanvasDrawLine(w, sLastX, sLastY, x, y);
    sLastX = x;
    sLastY = y;
}

wgtCanvasSetMouseCallback(w, fn) gives the canvas void fn(WidgetT *w, int32_t x, int32_t y, bool drag). A press of the left button on the canvas calls it with drag false, and the canvas then has the mouse until the button comes up: each frame in which the mouse moved calls it again with drag true and where the mouse is then. The coordinates are the drawing’s own, (0, 0) at its top-left corner, inside the border; a drag that leaves the canvas gives coordinates below 0 or past its size. The release does not call it (the canvas’s onMouseUp gets the release; Section 8.10.2), and neither do the other buttons.

A move is reported once a frame, so two calls can be many pixels apart when the mouse moves fast. Sketch therefore draws a line from the last point to the new one each time; a press draws a line from the point to itself, which is a dot. At the start of each stroke it saves the drawing for Undo and sets the pen’s color.

wgtCanvasDrawLine(w, x0, y0, x1, y1) draws with the pen: a line found by Bresenham’s method, with a dot of the pen’s size at every step, so wide lines have round ends and joints. Its ends may lie anywhere; the line is clipped to the drawing first, so only the part on the canvas costs anything. Like every drawing call of the canvas, it also asks for the canvas to be painted again (Section 9.10). The pen’s dot is a filled circle 2 x (size / 2) + 1 pixels across, computed when the size is set: in the current DVX an even size draws the same dot as the odd size above it (4 as 5), so Sketch’s sizes are odd.

9.2.3. Choosing the Pen

Sketch keeps each pen color as 0x00RRGGBB, with its menu label and its name for the status line:

// A pen color: its menu item, its name in the status line, and the color
// as 0x00RRGGBB, packed for the screen when it is drawn with
typedef struct {
    const char *label;
    const char *name;
    uint32_t    rgb;
} SketchColorT;

// A pen size: its menu item and its width in pixels
typedef struct {
    const char *label;
    int32_t     pixels;
} SketchSizeT;

static const SketchColorT sColors[] = {
    { "&Black",          "Black", SKETCH_BLACK },
    { "&Red",            "Red",   SKETCH_RED   },
    { "&Green",          "Green", SKETCH_GREEN },
    { "B&lue",           "Blue",  SKETCH_BLUE  },
    { "&White (Eraser)", "White", SKETCH_WHITE }
};

static const SketchSizeT sSizes[] = {
    { "&Thin",   SKETCH_PEN_THIN   },
    { "&Medium", SKETCH_PEN_MEDIUM },
    { "T&hick",  SKETCH_PEN_THICK  }
};

static const FileFilterT sFilters[] = {
    { "Pictures (" DVX_IMAGE_PATTERNS ")" },
    { "All Files (*.*)" }
};

static DxeAppContextT *sCtx        = NULL;
static AppContextT    *sAc         = NULL;
static WindowT        *sWin        = NULL;
static WidgetT        *sCanvas     = NULL;
static WidgetT        *sStatus     = NULL;
static BitmapFontT    *sFont       = NULL;                    // the text's font, held open
static uint8_t        *sUndo       = NULL;                    // the drawing before the last change
static int32_t         sUndoBytes  = 0;                       // the size of sUndo
static bool            sCanUndo    = false;
static int32_t         sColor      = 0;                       // the pen: an index into sColors
static int32_t         sSize       = 0;                       // and one into sSizes
static int32_t         sLastX      = 0;                       // the stroke's last point
static int32_t         sLastY      = 0;
static int32_t         sMarkX      = SKETCH_CANVAS_W / 2;     // the last press, where text goes
static int32_t         sMarkY      = SKETCH_CANVAS_H / 2;
static DvxFontChoiceT  sFontChoice = { SKETCH_FONT_FAMILY, SKETCH_FONT_SIZE, SKETCH_FONT_STYLE };

A canvas draws with colors packed for the screen’s pixel format (Section 9.5), which wgtCanvasSetPenColor takes as they are. Sketch packs the pen’s color when a stroke starts, not when the color is chosen:

// The pen's color packed for d's pixel format.  A packed color is good for
// the video mode it was packed in, and the user can change the mode while
// Sketch runs, so Sketch keeps 0x00RRGGBB and packs when it draws.
static uint32_t penPixel(const DisplayT *d) {
    return packColorRgb(d, sColors[sColor].rgb);
}

The Pen menu’s items are two ranges of command IDs, one per entry of sColors and sSizes, handled in the default case of onMenu. The menu checks the radio item itself (Section 6.4); Sketch records the choice, sets a new size on the canvas, and shows the pen:

default:
    if (menuId >= CMD_PEN_COLOR_FIRST && menuId < CMD_PEN_COLOR_FIRST + DVX_ARRAY_LEN(sColors)) {
        sColor = menuId - CMD_PEN_COLOR_FIRST;
    } else if (menuId >= CMD_PEN_SIZE_FIRST && menuId < CMD_PEN_SIZE_FIRST + DVX_ARRAY_LEN(sSizes)) {
        sSize = menuId - CMD_PEN_SIZE_FIRST;
        wgtCanvasSetPenSize(sCanvas, sSizes[sSize].pixels);
    }

    showPen();
    break;
static void showPen(void) {
    char text[SKETCH_STATUS_MAX];

    snprintf(text, sizeof(text), "Pen: %s, size %" PRId32, sColors[sColor].name, sSizes[sSize].pixels);
    setStatus(text);
}

9.2.4. The Canvas’s Calls

The canvas’s calls draw on its drawing with the pen and clip to it, so any coordinates are safe:

Call Does

wgtCanvasClear(w, color)

Fills the drawing with a packed color.

wgtCanvasSetPenColor(w, color)

Sets the pen’s packed color.

wgtCanvasSetPenSize(w, size)

Sets the pen’s size in pixels, at most 255; a size below 1 is ignored. A line draws a round dot exactly size pixels across at each of its points (a 2 x 2 square for 2). It affects lines only.

wgtCanvasDrawLine(w, x0, y0, x1, y1)

A line with the pen.

wgtCanvasDrawRect(w, x, y, width, height)

A rectangle’s outline, 1 pixel wide in the pen’s color whatever its size.

wgtCanvasFillRect(w, x, y, width, height)

A filled rectangle in the pen’s color.

wgtCanvasFillCircle(w, cx, cy, radius)

A filled circle in the pen’s color, 2 x radius + 1 pixels across.

wgtCanvasSetPixel(w, x, y, color), wgtCanvasGetPixel(w, x, y)

One pixel, in a packed color of its own; reading one outside the drawing gives 0.

wgtCanvasDrawText(w, x, y, text), wgtCanvasDrawTextScaled(w, x, y, text, scale)

Text in the pen’s color, in the canvas’s font (its own from wgtSetFont, else its container’s; Section 9.6), over what is there. The scaled form makes each pixel of the font a scale x scale block, for titles.

wgtCanvasResize(w, newW, newH)

A new white drawing of that size; what was drawn is lost.

wgtCanvasLoad(w, path), wgtCanvasLoadData(w, data, len, name)

Replaces the drawing with a picture (Section 9.7), and the drawing takes the picture’s size. 0, or -1 when it cannot be read.

wgtCanvasSave(w, path)

Saves the drawing (Section 9.7.3). 0 or -1.

wgtCanvasGetDisplay(w, &d)

A DisplayT aimed at the drawing, for every other drawing call (Section 9.3).

The canvas’s lines and circles are its own: the drawing layer has none (Section 9.4). The reference lists the canvas’s calls, and the PictureBox properties and methods DVX BASIC sees (“Canvas” in the DVX C Library Reference).

Note
wgtCanvasResize and wgtCanvasLoad change the widget’s size and lay its window out again, but they do not resize the window. Fit it again (dvxFitWindow) when it should follow.

9.3. DisplayT and the Clip Rectangle

Every drawing call takes a DisplayT * that says where to draw:

Field Holds

width, height

The buffer’s size in pixels.

pitch

Bytes from the start of one row to the start of the next. Step from row to row by the pitch, never by the width times the bytes per pixel.

format

The pixel format (PixelFormatT, Section 9.5).

backBuf

The pixels. Every drawing call draws here. Video memory is reached only by DVX’s platform layer, so a DisplayT a program makes is its backBuf alone.

palette

The 256 colors of an 8-bit mode (768 bytes, red, green, blue), NULL in the others.

clipX, clipY, clipW, clipH

The clip rectangle: no call draws outside it.

Where a program gets one:

  • wgtCanvasGetDisplay(canvas, &d): a canvas’s drawing. It returns false for a widget that is not a canvas.

  • dvxContentDisplay(ac, win, &d): a window’s content buffer (Section 9.9).

  • A widget’s paint method is given one (Chapter 19).

  • Your own bitmap: a copy of the screen’s with the buffer, size, pitch, and clip changed (Section 9.8).

  • dvxExclusiveDisplay(ac): the whole screen in full-screen mode (Chapter 17).

The screen’s own, ac->display, belongs to the compositor. Read the screen’s size and pixel format there, but never draw into it: the compositor builds that picture from the windows, and draws over whatever it finds there.

Coordinates are the buffer’s own: (0, 0) is the top-left pixel of the canvas’s drawing or of the window’s content area, whichever the DisplayT describes, and x grows to the right and y down.

The drawing calls also take a const BlitOpsT *: the two routines every fill and copy comes down to, spanFill(dst, color, count) and spanCopy(dst, src, count), chosen for the screen’s bytes per pixel when the mode was set (on DOS, rep stosl and rep movsl loops), with bytesPerPixel beside them. dvxGetBlitOps(ac) gives them. Every buffer a program draws into is in the screen’s format, so these serve them all, except the full screen of a program’s own mode, which has its own (dvxExclusiveBlitOps).

9.3.1. The Clip Rectangle

The clip rectangle confines drawing. Every call clips to it, by rows and runs rather than pixel by pixel, and a call wholly outside it does next to nothing. The DisplayT a program gets clips to the whole buffer. setClipRect(d, x, y, w, h) sets it to a rectangle (in the buffer’s coordinates, cut to the buffer, not to the clip there before), and resetClipRect(d) makes it the whole buffer again. A long text in a box of its own, for example, is cut at the box’s edge:

void drawInBox(DisplayT *d, const BlitOpsT *ops, const BitmapFontT *font, int32_t boxX, int32_t boxY, int32_t boxW, int32_t boxH, const char *text, uint32_t fg, uint32_t bg) {
    RectT saved = { d->clipX, d->clipY, d->clipW, d->clipH };

    setClipRect(d, boxX, boxY, boxW, boxH);
    drawText(d, ops, font, boxX, boxY, text, fg, bg, true);
    setClipRect(d, saved.x, saved.y, saved.w, saved.h);
}

The clip is a field of the DisplayT, not a state of DVX: change it on a DisplayT you were given and put it back, as above, since the code that gave it to you clips with it too.

9.4. The Drawing Calls

The drawing layer (dvxDraw.h, which dvxApp.h includes) holds no state of its own: everything a call needs, the buffer, the colors, the font, comes as arguments. Colors are packed for the screen’s format (Section 9.5). The calls in groups:

Group Calls

Rectangles and lines

rectFill(d, ops, x, y, w, h, color), the workhorse; drawHLine(d, ops, x, y, w, color) and drawVLine(d, ops, x, y, h, color); drawRectOutline (a 1-pixel outline); drawFocusRect (a dotted one, the focus mark).

Bevels

drawBevel(d, ops, x, y, w, h, &style): a raised or sunken frame, filled with a face color unless the face is BEVEL_NO_FILL; drawPressableBevel for a button that is up or down.

Text

drawText, drawTextN (a count of characters), drawChar, drawTextStyled (underline, strike-through), drawTextAccel (& marks an underlined access key), drawTextScaled, drawTermRow (a row of terminal cells); and the measuring calls of Section 9.6.2.

Pictures

rectCopy (a rectangle of pixels in the screen’s format), rectCopyTransparent (skipping a key color), rectCopyGrayscale (gray, for a disabled look), drawScaled (scaled to any size), drawMaskedBitmap (1-bit masks, the mouse pointers).

DVX’s own parts

drawArrowGlyph, drawScrollbar, drawScrollbarArrow, drawScrollbarArrowButton, for widgets that look like DVX’s.

Pixels

pixelGet(src, bpp) and pixelPut(dst, color, bpp), inline: one packed pixel read or written at an address.

A BevelStyleT holds a highlight color for the top and left edges, a shadow color for the bottom and right, the face inside, and the width in pixels (DVX’s bevels are 2). The macros build one from the color scheme: BEVEL_RAISED(colors, width) and BEVEL_SUNKEN(colors, face, width) swap highlight and shadow, so they are never backwards. BEVEL_NO_FILL (0xFFFFFFFF, never a packed color) leaves the inside alone; 0 is black and fills.

drawText(d, ops, font, x, y, text, fg, bg, opaque) draws a string with its line’s top-left corner at (x, y): the baseline of the letters is font->ascent rows below. With opaque the box behind the text, the text’s width by the font’s line height, is filled with bg first; without it only the pixels of the letters are drawn, in fg, over what is there. The text is bytes of code page 437, the PC’s own character set: every byte has a character, the line-drawing ones included.

rectCopy(d, ops, dstX, dstY, src, srcPitch, srcX, srcY, w, h) copies a w by h rectangle from (srcX, srcY) of a buffer in the screen’s format to (dstX, dstY), clipped, a row at a time (one copy when both buffers are exactly that wide). The source and the destination must not overlap. rectCopyTransparent takes one more argument, a key color whose pixels it skips. drawScaled(d, dstX, dstY, dstW, dstH, src, srcW, srcH, srcPitch, keyed, key) scales by nearest neighbor: each pixel it draws is the source pixel at the same fraction of the way across and down, and with keyed the pixels of key are skipped. It takes no BlitOpsT.

The drawing layer has no diagonal lines, circles, or polygons; a canvas draws lines and circles on its own drawing (Section 9.2.4). The reference describes every call (“dvxDraw.h — Layer 2: Drawing Primitives” in the DVX C Library Reference).

9.5. Colors and Pixel Formats

DVX runs in a mode of 8, 15, 16, or 32 bits per pixel, the one the user chose on Control Panel’s Video page. Pixels are stored as they are shown, so drawing never converts a pixel: a color is packed into the mode’s format once, before it is drawn.

Depth Bytes A pixel is

8

1

An index into a palette of 256 colors.

15

2

Five bits each of red, green, and blue.

16

2

Five bits of red, six of green, and five of blue.

32

4

Eight bits each of red, green, and blue, and a byte that is not used.

d->format, a PixelFormatT, describes the format: bitsPerPixel and bytesPerPixel, and for each channel its mask, shift, and number of bits (redMask, redShift, redBits, and so on).

packColor(d, r, g, b) packs a color given as three channels from 0 to 255; packColorRgb(d, rgb) packs one written 0x00RRGGBB, as DVX_RGB(r, g, b) makes it. unpackColor(d, color, &r, &g, &b) goes back. What each format does with a color:

  • In 15 and 16 bits, packColor drops the low bits of each channel; it does not round. So colors that differ only there pack the same, and unpacking gives the color as the screen shows it (black, white, and full channels exactly).

  • In 8 bits, it gives the nearest of the palette’s colors: a 6 x 6 x 6 cube of colors (each channel 0, 51, 102, 153, 204, or 255), 16 grays, and 8 colors for DVX’s own chrome (the last 16 entries are black and unused). The desktop’s palette is fixed; a program cannot change it (a full-screen program has a palette of its own, Chapter 17). Pictures are mapped pixel by pixel to the nearest color, without dithering, so photographs look posterized.

A packed color belongs to the mode it was packed for, and the user can change the mode while your program runs. The content buffers of the windows are made again, and their contents painted again, in the new format; a color the program keeps packed is now wrong. So keep colors as 0x00RRGGBB and pack them when you draw, as Sketch’s penPixel does: packColor costs a few shifts. A bitmap the program keeps is in the old format too, and of the old size in bytes; Sketch makes its undo bitmap again when that size changes (Section 9.8). What DVX keeps itself in the screen’s format, it converts at a change of depth before anything draws or paints again: a canvas’s drawing and its pen’s color, the pictures of Image and ImageButton widgets and their key colors, and the windows' icons (a widget class does it in its WGT_METHOD_ON_FORMAT_CHANGE handler, Section 19.3). A program’s own pixels it does not: make them again, or convert them with convertColor(from, d, color) and convertPixels(from, d, src, w, h, pitch, &outPitch) (dvxVideo.h), keeping the PixelFormatT they were made in to say from. A cache of pictures in the screen’s format can key them on pixelFormatKey(&d→format), which differs for every format, 15 and 16 bits included.

To draw in the user’s colors, use the color scheme: dvxGetColors(ac) gives a ColorSchemeT of packed colors, among them contentBg and contentFg (a window’s background and text), windowFace, windowHighlight, and windowShadow (the 3-D look), menuHighlightBg and menuHighlightFg (a selection), and desktop. When the colors change (the user’s Control Panel, a theme, dvxSetColor), DVX paints every window again, so read the scheme when you paint rather than keeping copies. dvxGetColor(ac, id, &r, &g, &b) gives a scheme color’s channels.

A widget’s own colors, fgColor and bgColor, are 0x00RRGGBB with WGT_COLOR_SET added, 0 meaning the scheme’s color (Section 7.6). wgtColorPixel(d, color, fallback) packs one, giving fallback when it is 0; wgtBackColor(w, d, colors) gives the background a widget shows (its own, else its container’s, else the scheme’s). DVX BASIC writes colors the other way round, &HBBGGRR as in Visual Basic; a library or widget that takes colors from BASIC converts them with wgtBasicColor (Chapter 19).

9.6. Fonts and Text

9.6.1. What a Font Is

Every font in DVX is a BitmapFontT: bitmaps of the 256 characters of code page 437, at one size and in one style, made in advance. DVX never scales a font or renders an outline at run time. The fields a program reads:

Field Holds

charHeight

The line height in pixels: lines of text are this far apart.

ascent

The rows from the top of a line to the baseline.

charWidth

In a fixed-pitch font, every character’s width. In a proportional one, the width of the digit 0, for sizing a field "so many characters wide"; measure real text with textWidth.

pixelSize

The size the font was made at.

style

The FONT_STYLE_* bits it has: FONT_STYLE_BOLD, FONT_STYLE_ITALIC, FONT_STYLE_UNDERLINE, FONT_STYLE_STRIKE.

flags

FONT_FLAG_PROPORTIONAL when its characters differ in width, FONT_FLAG_SYNTH_BOLD or FONT_FLAG_SYNTH_ITALIC when the style was made from another face, FONT_FLAG_GRAY when it is smoothed (Section 9.6.5).

The system font is the PC’s own 8 x 16 font, built into DVX (dvxFont8x16, dvxFont.h). It is the font of the GUI, dvxGetFont(ac), and the fastest to draw: its characters are 8 pixels wide, a byte a row. A widget’s font is wgtFont(w): its own, set with wgtSetFont, else its container’s, else the system font. Other fonts come from dvxFontOpen.

9.6.2. Measuring Text

Measure text; never count its characters. textWidth(font, text) is a string’s width in pixels and textWidthN(font, text, count) the width of its first count characters; textWidthAccel leaves out the & of an access key. Its height is font->charHeight. calcCenteredText(font, x, y, w, h, text, &outX, &outY) gives where to draw a text to center it in a rectangle.

textWrap(font, text, maxW, lineFn, userData) breaks a text into lines no wider than maxW pixels, at spaces and at CR, LF, or CR LF (a word wider than that is cut), calls lineFn(line, length, index, userData) for each line (the line is not terminated), and returns how many there are. With NULL for lineFn it only counts them, which gives the text’s height: lines times charHeight. Drawing a wrapped text is a callback that draws each line on its row:

typedef struct {
    DisplayT          *d;
    const BlitOpsT    *ops;
    const BitmapFontT *font;
    int32_t            x;
    int32_t            y;
    uint32_t           fg;
} WrapDrawT;


static void wrapLine(const char *line, int32_t len, int32_t index, void *userData) {
    WrapDrawT *wd = (WrapDrawT *)userData;

    drawTextN(wd->d, wd->ops, wd->font, wd->x, wd->y + index * wd->font->charHeight, line, len, wd->fg, wd->fg, false);
}
textWrap(wd.font, text, maxW, wrapLine, &wd);

9.6.3. Families, Sizes, and Styles

Fonts come in families ("DejaVu Sans"), each with up to four faces (regular, bold, italic, and bold italic) at the pixel sizes they were made at, in the FONTS folder. dvxFontOpen(family, pixelSize, style) (dvxText.h) gives a font:

  • the face that the bold and italic bits of style (FONT_STYLE_BOLD, FONT_STYLE_ITALIC) ask for; a face the family lacks is made from the nearest one it has, bold by thickening, italic by slanting;

  • at the size it has that is nearest pixelSize: it never scales;

  • with FONT_STYLE_UNDERLINE and FONT_STYLE_STRIKE, lines that every call drawing text with the font draws;

  • and the system font for NULL, "", or a family that is not there.

It returns NULL only when memory runs out. Fonts are shared and counted: the same family, size, and style opened again is the same font, and dvxFontClose(font) gives up one hold on it. The font’s memory is DVX’s, not the program’s, but the holds are yours: DVX does not close the fonts a program left open when it ends, so close each one you open. (dvxFontClose ignores NULL and fonts that did not come from dvxFontOpen.)

Which families there are depends on the PC. Setup installs DejaVu Sans, DejaVu Sans Mono, and DejaVu Serif, or no fonts at all, and the More Fonts add-on others, so a program must look right in the system font too. Fonts a package installs are there at once, without restarting DVX. To see what there is:

int32_t sizes[FONT_SIZES_MAX];
int32_t count = dvxFontFamilyCount();

for (int32_t i = 0; i < count; i++) {
    const char *family = dvxFontFamilyName(i);
    int32_t     n      = dvxFontSizes(family, FONT_STYLE_REGULAR, sizes, FONT_SIZES_MAX);

    dvxLog("%s: %ld sizes from %ld pixels, %s", family, (long)n, (long)(n > 0 ? sizes[0] : 0), dvxFontFamilyFixed(family) ? "fixed pitch" : "proportional");
}

dvxFontFamilyName(i) names family i, "System" first and then the others in alphabetical order. dvxFontSizes(family, style, sizes, max) fills sizes with the sizes the face for style has, smallest first, and returns how many there are (no face has more than FONT_SIZES_MAX). dvxFontFamilyFixed says whether every face of a family is fixed-pitch, and dvxFontFamilyOf(font) names a font’s family.

Sketch’s Font command lets the user choose with the font dialog (Section 7.6), opens the font chosen, and gives up the old one. The status line names the font Sketch got, which is not always the one asked for:

// The font dialog starts on the font chosen last.  The font opened can
// differ from the one asked for (the nearest size the family has, or the
// system font when the family is not installed), so the status line names
// the one Sketch got.
static void chooseFont(void) {
    DvxFontChoiceT choice = sFontChoice;
    char           text[SKETCH_STATUS_MAX];

    if (!dvxFontDialog(sAc, NULL, 0, &choice)) {
        return;
    }

    BitmapFontT *font = dvxFontOpen(choice.family, choice.size, choice.style);

    if (!font) {
        setStatus("Not enough memory for that font.");
        return;
    }

    dvxFontClose(sFont);
    sFont       = font;
    sFontChoice = choice;
    snprintf(text, sizeof(text), "Font: %.*s, %" PRId32 " pixels", SKETCH_NAME_SHOWN, dvxFontFamilyOf(sFont), sFont->pixelSize);
    setStatus(text);
}

For text a widget draws, set the widget’s font instead: wgtSetFont(w, family, size, style) opens it, holds it while the widget has it, and lays the window out again; the widgets inside a container use the container’s font unless they have their own. A canvas’s wgtCanvasDrawText draws in the canvas’s font, so wgtSetFont on a canvas chooses that too (Chapter 5).

9.6.4. Text in Sketch

// The text is centered on the last point pressed: textWidth and the font's
// line height say how big it is.  It is drawn on the canvas's own pixels,
// through the DisplayT the canvas gives, so the canvas is told to repaint.
static void insertText(void) {
    char     text[SKETCH_TEXT_MAX];
    DisplayT d;

    if (!dvxInputBox(sAc, "Text", "The text to draw where you last clicked:", NULL, text, sizeof(text)) || !wgtCanvasGetDisplay(sCanvas, &d)) {
        return;
    }

    int32_t  x     = sMarkX - textWidth(sFont, text) / 2;
    int32_t  y     = sMarkY - sFont->charHeight / 2;
    uint32_t color = penPixel(&d);

    undoSave();
    drawText(&d, dvxGetBlitOps(sAc), sFont, x, y, text, color, color, false);
    wgtInvalidatePaint(sCanvas);
}

dvxInputBox asks for the text (Chapter 7). The text is centered on the last point pressed, measured with textWidth and the font’s line height, and drawn with drawText on the canvas’s own pixels, through the DisplayT that wgtCanvasGetDisplay gives. Drawing that way does not tell the canvas, so wgtInvalidatePaint asks for the repaint. The text is drawn transparent (opaque false), over the drawing; fg and bg are both the pen’s color, since bg is not used.

9.6.5. Smoothed Text

A font’s size can come smoothed too: each pixel at one of four levels, from none to full, drawn as that blend of the text’s color and the pixel under it. DVX smooths text when the user wants it (Control Panel’s Video page; on at first) and the screen has more than 8 bits per pixel, in the sizes the font’s files have smoothed; at 8 bits per pixel there is nothing to blend with, and text is drawn from the font’s plain sizes. Because the blend reads the pixel under the text, draw a background before the text that stands on it.

When smoothing is turned on or off, DVX builds every open font again in place: the same pointer, new glyphs, perhaps new widths, and a new serial. A program that keeps measurements of text (column widths, line breaks) records the font they were made with in a FontStampT (fontStampSet(&stamp, font)) and measures again when fontStampIs(&stamp, font) is false. Every window is laid out and painted again afterward.

9.6.6. Fonts a Program Carries

A program can bring fonts of its own: .DFN files, which the SDK’s mkfont makes from TrueType, Type 1, and bitmap fonts (Chapter 20). A font resource in the program’s .res file is the easy way:

title       font    TITLE.DFN

The shell adds the program’s font resources when it loads it and removes them when it ends; meanwhile dvxFontOpen finds the family by the name inside the file. Only that program sees it. Where its family is installed too, the program’s own faces and sizes come first, and the installed family fills in what it lacks. dvxFontAddFile(owner, path) and dvxFontAddMemory(owner, data, length, name) add a font while the program runs; owner is the program’s ID (ctx->appId). A font goes with its license: dvxFontLicence(font) returns the notice and license text the .DFN carries, from malloc (free it), and the font dialog shows it.

9.7. Images

9.7.1. Loading Pictures

dvxLoadImage(ac, path, &w, &h, &pitch) (dvxApp.h) reads a BMP, PNG, JPEG, or GIF file (the first picture of an animated GIF) and returns its pixels in the screen’s format, w by h, pitch bytes a row, in a buffer from malloc that the caller frees with dvxFreeImage. It returns NULL when the file cannot be read or is not a picture. A file that is not a picture but a DVX program, widget, or library gives that module’s icon. A PNG’s transparency is dropped (Section 9.7.2 keeps it). DVX_IMAGE_PATTERNS (dvxApp.h) is the one list of those formats, as file name patterns ("*.bmp;*.png;..."): put it in a file dialog’s filter, as Sketch’s { "Pictures (" DVX_IMAGE_PATTERNS ")" } does, or test a name with platformFilterMatch(name, DVX_IMAGE_PATTERNS), and a format DVX learns later is offered too.

dvxLoadImageFromMemory(ac, data, len, &w, &h, &pitch) reads a picture file’s bytes in memory, such as a resource’s. dvxResLoadIcon(ac, path, name, &w, &h, &pitch) does both steps for a picture resource of a module file, often the program’s own:

int32_t  w;
int32_t  h;
int32_t  pitch;
uint8_t *logo = dvxResLoadIcon(sAc, sCtx->appPath, "logo", &w, &h, &pitch);

if (logo) {
    rectCopy(d, dvxGetBlitOps(sAc), x, y, logo, pitch, 0, 0, w, h);
    dvxFreeImage(logo);
}

dvxImageInfo(path, &w, &h) reads only a picture file’s header: whether it is a picture DVX reads, and its size (either pointer may be NULL). dvxImageInfoFromMemory does the same for bytes in memory. Sketch uses it before it spends the memory and the time a picture costs:

// Draw the picture in the file at path on the canvas, centered, and made
// smaller to fit (keeping its shape) when it is bigger.  False when it
// cannot be read.
static bool drawPicture(const char *path) {
    DisplayT d;
    int32_t  w;
    int32_t  h;
    int32_t  pitch;

    if (!wgtCanvasGetDisplay(sCanvas, &d)) {
        return false;
    }

    dvxSetBusy(sAc, true);
    uint8_t *pixels = dvxLoadImage(sAc, path, &w, &h, &pitch);
    dvxSetBusy(sAc, false);

    if (!pixels) {
        return false;
    }

    int32_t fitW = w;
    int32_t fitH = h;

    if (fitW > d.width) {
        fitH = DVX_MAX(1, fitH * d.width / fitW);
        fitW = d.width;
    }

    if (fitH > d.height) {
        fitW = DVX_MAX(1, fitW * d.height / fitH);
        fitH = d.height;
    }

    drawScaled(&d, (d.width - fitW) / 2, (d.height - fitH) / 2, fitW, fitH, pixels, w, h, pitch, false, 0);
    dvxFreeImage(pixels);
    wgtInvalidatePaint(sCanvas);
    return true;
}


// dvxImageInfo reads only the file's header: what the picture is and how
// big, before Sketch spends the memory and the time to decode it.  The
// dialog starts in the program's user folder, made first when it is not
// there yet (the current folder when it cannot be).
static void insertPicture(void) {
    const char *start = shellEnsureUserDir(sCtx) == 0 ? sCtx->userDir : NULL;
    char        path[DVX_MAX_PATH];
    int32_t     w;
    int32_t     h;

    if (!dvxFileDialog(sAc, "Insert Picture", FD_OPEN, start, sFilters, DVX_ARRAY_LEN(sFilters), path, sizeof(path))) {
        return;
    }

    if (!dvxImageInfo(path, &w, &h)) {
        setStatus("That file is not a picture DVX reads.");
        return;
    }

    if ((int64_t)w * h > SKETCH_PICTURE_MAX) {
        setStatus("That picture is too big to insert.");
        return;
    }

    undoSave();
    setStatus(drawPicture(path) ? "Picture inserted." : "Could not read that picture.");
}

Decoding is slow and takes memory. While a picture loads, DVX holds the decoded colors (3 bytes a pixel) and the screen-format copy at once: a 1024 x 768 picture at 32 bits per pixel needs about 5.5 MB for a moment, more than a small PC has. A large JPEG takes seconds on a 486. Called in a callback, on the shell’s task, the loaders decode in one go and DVX waits; dvxSetBusy(ac, true) puts up the hourglass at once and holds the input until dvxSetBusy(ac, false). Called on a program’s own task (a main-loop program; Section 3.4), they decode a part at a time and let DVX run a frame every 32 KB read, so DVX and the other programs go on; the caller’s own code waits for the end.

drawPicture then fits the picture in the canvas: no change when it fits, else the largest size of the same shape that does, centered. drawScaled does the scaling while it draws, and the decoded copy is freed at once: Sketch draws it once.

9.7.2. Drawing and Scaling Pictures

A picture in the screen’s format is drawn with rectCopy at its own size, with drawScaled at any other (nearest neighbor: fast and blocky, with no smoothing), or with rectCopyGrayscale grayed. drawScaled computes each row’s source pixels by stepping, without a division per pixel, but it does the work again every time: a picture shown at another size on every paint is cheaper scaled once into an off-screen bitmap (Section 9.8) and copied from there.

Transparency is a key color. dvxLoadImageAlpha(ac, data, len, &w, &h, &pitch, &hasKey, &key) loads a picture from memory keeping its transparency: each pixel less than half opaque becomes the key color, magenta (255, 0, 255) packed for the screen. hasKey says whether any pixel was transparent, and key is the packed key. rectCopyTransparent and drawScaled with keyed then skip those pixels:

uint32_t size  = 0;
uint8_t *bytes = (uint8_t *)dvxResLoadData(sCtx->appPath, "sprite", &size);
int32_t  w;
int32_t  h;
int32_t  pitch;
bool     hasKey;
uint32_t key;
uint8_t *pixels = bytes ? dvxLoadImageAlpha(sAc, bytes, (int32_t)size, &w, &h, &pitch, &hasKey, &key) : NULL;

free(bytes);

if (pixels) {
    if (hasKey) {
        rectCopyTransparent(d, dvxGetBlitOps(sAc), x, y, pixels, pitch, 0, 0, w, h, key);
    } else {
        rectCopy(d, dvxGetBlitOps(sAc), x, y, pixels, pitch, 0, 0, w, h);
    }

    dvxFreeImage(pixels);
}

The key is a packed color, so in 8, 15, and 16 bits an opaque pixel close to magenta packs to the same value and becomes transparent too: keep pictures with transparency free of colors near magenta.

9.7.3. Saving Pictures

dvxSaveImage(ac, pixels, w, h, pitch, path) saves pixels in the screen’s format: a BMP file when path ends in .bmp (in any case), a PNG file otherwise. It returns 0, or -1 when the file cannot be written. The picture is encoded in memory and the file written whole, so a failed save leaves a file that was there as it was. A PNG file is usually far smaller than a BMP file, and takes longer to write on a 486.

The same in other forms: wgtCanvasSave(canvas, path) saves a canvas’s drawing; dvxWindowScreenshot(ac, win, path) a window’s content, even covered by other windows, since it is the window’s own buffer; and dvxScreenshot(ac, path) the whole screen. dvxBufferToRgb(d, pixels, w, h, pitch) converts pixels to bytes of red, green, and blue, from malloc, for code that wants colors rather than pixels (an encoder of another format, printing).

Sketch saves in its folder in the user folder, which may not exist yet: shellEnsureUserDir makes it, and shellUserPath joins a name to it (Chapter 10). Saving shows the hourglass, like loading:

// The program's user folder may not exist yet: shellEnsureUserDir makes
// it.  wgtCanvasSave writes a PNG file (a BMP file for a name ending in
// .bmp).
static void savePicture(void) {
    int32_t result = -1;

    if (shellEnsureUserDir(sCtx) == 0) {
        char path[DVX_MAX_PATH];

        shellUserPath(sCtx, SKETCH_FILE, path, sizeof(path));
        dvxSetBusy(sAc, true);
        result = wgtCanvasSave(sCanvas, path);
        dvxSetBusy(sAc, false);
    }

    setStatus(result == 0 ? "Saved as " SKETCH_FILE "." : "Could not save the drawing.");
}

At its start, Sketch draws the drawing saved last time, when there is one:

// The drawing saved last time, when there is one.
static void openSaved(void) {
    char path[DVX_MAX_PATH];

    shellUserPath(sCtx, SKETCH_FILE, path, sizeof(path));

    if (dvxImageInfo(path, NULL, NULL) && drawPicture(path)) {
        setStatus("Opened " SKETCH_FILE ".");
    }
}

It draws the file through drawPicture, so the canvas keeps its size whatever the file holds. (wgtCanvasLoad would replace the drawing with the picture, at the picture’s size.)

9.7.4. The Image and ImageButton Widgets

To show a picture in a window of widgets, use an Image widget (image/image.h; Section 5.6.7). wgtImageFromFile(parent, path) loads the file; wgtImage(parent, pixels, w, h, pitch) shows pixels you have, in the screen’s format, and takes them over: the widget frees them, and when wgtImage fails it has already freed them, so never free them yourself. wgtImageSetData gives it other pixels the same way (the old ones are freed), wgtImageLoadFile and wgtImageLoadData another picture, and wgtImageSetTransparent(w, true, key) a key color. The widget is as big as its picture and draws it grayed when it is disabled; wgtImageSetStretch(w, true) lets it be smaller, scaling the picture down to fit. An ImageButton (imageButton/imgBtn.h) is a button with a picture and the same calls, wgtImageButtonSetTransparent and wgtImageButtonSetStretch among them. The reference has both (“Image” in the DVX C Library Reference, “ImageButton” in the DVX C Library Reference).

9.8. Off-Screen Bitmaps

An off-screen bitmap is a buffer of pixels in the screen’s format that is not shown: w x h x bytes per pixel, in rows of w x bytes per pixel (its pitch). dvxLoadImage returns one; a program can also allocate one. Copy it onto a canvas or a window with rectCopy and the other picture calls. To draw on it, give it a DisplayT: a copy of the screen’s, for its pixel format and palette, with the buffer, the size, the pitch, and the clip changed. Sketch’s:

// A DisplayT aimed at an off-screen bitmap of w x h pixels in the screen's
// pixel format, so that every drawing call can draw on it.  The clip
// rectangle is the whole bitmap.
static void bitmapDisplay(uint8_t *pixels, int32_t w, int32_t h, DisplayT *out) {
    *out         = sAc->display;
    out->backBuf = pixels;
    out->width   = w;
    out->height  = h;
    out->pitch   = w * sAc->display.format.bytesPerPixel;
    resetClipRect(out);
}

Sketch’s Undo is an off-screen bitmap the size of the canvas. Each change copies the canvas to it first, and Undo copies it back. The bitmap is allocated the first time it is needed, and again when its size in bytes changes, since the user can choose a mode of another depth while Sketch runs (Section 9.5):

// The canvas's DisplayT, and one for the undo bitmap: the canvas's size in
// the screen's pixel format.  The bitmap is made the first time, and made
// again when its size in bytes changes (the user chose a mode of another
// depth), when what it held is of no more use.  False when the canvas has
// no pixels or memory runs out.
static bool undoDisplays(DisplayT *canvas, DisplayT *undo) {
    if (!wgtCanvasGetDisplay(sCanvas, canvas)) {
        return false;
    }

    int32_t bytes = canvas->width * canvas->height * sAc->display.format.bytesPerPixel;

    if (bytes != sUndoBytes) {
        free(sUndo);
        sUndo      = (uint8_t *)malloc((size_t)bytes);
        sUndoBytes = sUndo ? bytes : 0;
        setCanUndo(false);
    }

    bitmapDisplay(sUndo, canvas->width, canvas->height, undo);
    return sUndo != NULL;
}


// Copy the undo bitmap back onto the canvas.
static void undoRestore(void) {
    DisplayT canvas;
    DisplayT undo;

    if (!undoDisplays(&canvas, &undo) || !sCanUndo) {
        return;
    }

    rectCopy(&canvas, dvxGetBlitOps(sAc), 0, 0, undo.backBuf, undo.pitch, 0, 0, undo.width, undo.height);
    wgtInvalidatePaint(sCanvas);
    setCanUndo(false);
    setStatus("Undone.");
}


// Copy the canvas to the undo bitmap, before a change.
static void undoSave(void) {
    DisplayT canvas;
    DisplayT undo;

    if (!undoDisplays(&canvas, &undo)) {
        return;
    }

    rectCopy(&undo, dvxGetBlitOps(sAc), 0, 0, canvas.backBuf, canvas.pitch, 0, 0, canvas.width, canvas.height);
    setCanUndo(true);
}

Both copies are one rectCopy of the whole drawing, and since both buffers are exactly the drawing’s width, rectCopy copies them as one span. That is 300 KB at 32 bits per pixel, once for each stroke; a deeper undo would keep several such bitmaps, or only the rectangles the changes touched.

An off-screen bitmap is the program’s memory, counted against it, and lives until the program frees it. Sketch frees its undo bitmap, and gives up its font, when its window closes; the canvas’s own pixels go with the canvas:

// The canvas and its pixels go with the window.  What Sketch allocated
// itself, the undo bitmap and the font it holds, it gives back here.
static void closeWindow(void) {
    dvxDestroyWindow(sAc, sWin);
    dvxFontClose(sFont);
    free(sUndo);
    sWin       = NULL;
    sCanvas    = NULL;
    sStatus    = NULL;
    sFont      = NULL;
    sUndo      = NULL;
    sUndoBytes = 0;
}

Off-screen bitmaps also serve to build a picture once that takes long to draw (text in many fonts, a scaled picture, a chart) and copy it on each paint, and to save a part of the screen’s picture to put back later.

9.9. Drawing in a Window Without Widgets

A window without wgtInitWindow is the program’s to draw (Section 4.11). Its onPaint(win, dirtyArea) draws the content area into the window’s content buffer, through the DisplayT dvxContentDisplay gives:

static void onPaint(WindowT *win, RectT *dirtyArea) {
    const ColorSchemeT *colors = dvxGetColors(sAc);
    const BlitOpsT     *ops    = dvxGetBlitOps(sAc);
    DisplayT            d;

    (void)dirtyArea;
    dvxContentDisplay(sAc, win, &d);
    rectFill(&d, ops, 0, 0, d.width, d.height, colors->contentBg);
    drawText(&d, ops, dvxGetFont(sAc), RAW_MARGIN, RAW_MARGIN, "Painted by onPaint", colors->contentFg, colors->contentBg, false);
}
win->onPaint = onPaint;
dvxInvalidateWindow(sAc, win);

DVX calls onPaint when it needs the whole content again, with dirtyArea the whole content area:

  • in dvxInvalidateWindow(ac, win), at once, before the call returns; the whole window is then composited at the next frame. That is how the program paints first, and after any change.

  • when the window’s size changes (the user, maximizing and restoring, dvxResizeWindow) and when the video mode changes: at once, after onResize, into a new buffer that starts white;

  • again whenever the colors or the fonts change.

The content buffer keeps what was drawn between paints, so a program can also draw into it at any time and tell the compositor which part changed: dvxInvalidateRect(ac, win, x, y, w, h), in content coordinates, has that rectangle composited at the next frame, the part of it inside the content area. It does not call onPaint. Dots where the mouse is pressed, say:

static void onMouse(WindowT *win, int32_t x, int32_t y, int32_t buttons) {
    DisplayT d;

    if (!(buttons & MOUSE_LEFT)) {
        return;
    }

    dvxContentDisplay(sAc, win, &d);
    rectFill(&d, dvxGetBlitOps(sAc), x, y, RAW_DOT, RAW_DOT, dvxGetColors(sAc)->contentFg);
    dvxInvalidateRect(sAc, win, x, y, RAW_DOT, RAW_DOT);
}

But the buffer is DVX’s to throw away: a new size or mode replaces it and calls onPaint, which must draw everything again. The dots above vanish when the window is resized, since nothing remembers them. A program that draws this way keeps what it shows, as data or as an off-screen bitmap that onPaint copies in; that is what a canvas does for you. A window without widgets also does without what the widget layer gives: focus, Tab, access keys, and double clicks (Section 8.10.3).

9.10. Invalidating and Repainting

Nothing a program draws reaches the screen before the next frame, which runs after the code that drew it returns (Section 3.6). Drawing changes a buffer; the program then says what changed, and the frame paints and composites it:

What changed Call What DVX does

A widget, through its own calls (wgtSetText, the canvas’s calls)

Nothing: the call asks.

Whatever the change needs.

A canvas’s pixels, through its DisplayT

wgtInvalidatePaint(canvas)

Paints the canvas at the next frame.

A widget’s look, not its size

wgtInvalidatePaint(w)

Paints that widget at the next frame, and composites only it.

A widget’s size or the widgets in a window

wgtInvalidate(w)

Lays the whole window out at once, and paints all of it at the next frame.

A window without widgets, all of it

dvxInvalidateWindow(ac, win)

Calls onPaint at once, and composites the window at the next frame.

Part of such a window’s content buffer

dvxInvalidateRect(ac, win, x, y, w, h)

Composites that rectangle, clipped to the content area, at the next frame.

A window of widgets paints at most once a frame, however many times it was invalidated, so invalidating after each change costs nothing more; dvxInvalidateWindow, which paints at once, is the exception. A callback that runs long shows nothing new until it returns, except what dvxSetBusy shows: it composites the screen at once, so the hourglass is up before the slow part starts. A long job is better split up or put on a task (Chapter 11).

9.11. What Is Fast on a 486

Drawing is memory traffic, and on a 486 memory is slow and video memory slower. What makes a program fast:

  • Fewer pixels. A change travels through several buffers: drawn into the canvas or a content buffer, copied into the window’s content buffer (a canvas copies all of its drawing whenever it is painted), copied into the screen’s backbuffer, and copied across the bus to video memory, the slowest step. While Sketch’s pen moves, each frame copies its 320 x 240 canvas three times, about 900 KB at 32 bits per pixel. Make a canvas as big as its drawing needs, and invalidate one widget rather than the window.

  • Rows, not pixels. rectFill, drawHLine, rectCopy, and text go a row at a time through spanFill and spanCopy, string instructions that write 4 bytes at a time. pixelPut tests the pixel size on every pixel, and wgtCanvasSetPixel adds a call through the canvas’s table and a bounds test to that. When you write pixels yourself, find each row’s address once, decide the pixel size once outside the loop, and fill runs with ops->spanFill.

  • Text in runs. drawText and drawTextN clip once and draw a whole string; never draw a string a drawChar at a time. The system font is the fastest; a loaded font is slower, and the partial pixels of smoothed text, which are blended, slower again. Measure a text once and keep the width (with a FontStampT).

  • Integers. Keep floating point out of loops that run per pixel, and divisions too: a division costs some 40 cycles on a 486. Step instead, as drawScaled and the canvas’s lines do, or multiply by a reciprocal computed once.

  • The pen’s size. A canvas line draws a whole dot at every step, so its cost is its length times the dot’s rows; a 255-pixel pen is slow even for short lines.

  • Decode once. Load, decode, and scale a picture when it arrives, and keep the result; never in a paint. Save PNG files when the user asks, not on every change.

  • Memory. Every bitmap costs w x h x bytes per pixel as long as it exists, and so does every window’s content buffer: at 32 bits per pixel, twice what it costs at 16. A small PC has a few MB for everything.

Measure on the real thing or the emulator, not on the build machine: platformMicros() before and after, and the difference in DVX.LOG (Chapter 22).

Chapter 10. Files, Folders, and Settings

A DVX program reads and writes files with the C library it already knows: fopen, fread, fprintf, opendir, and the rest come from the copy of DJGPP’s library inside DVX.EXE (Section 3.2). What this chapter adds is what DOS and DVX expect of them: how paths are written and joined, which folder each kind of file belongs in, how a program keeps its settings, how to write a file so that a full disk or a crash never leaves half of it, and the libraries DVX has for the rest: the file operations library for listings and copies, file associations for opening documents, and the calls for long file names.

The example, notes, is a notepad that remembers: it keeps its text and its window’s place and size between runs, and it backs its files up to a folder the user chooses.

10.1. The Notes Program

Notes is one window: a text area, a status bar, and a File menu with Save, Back Up…​, and Exit. What you type is kept in NOTES.TXT and the window’s place in NOTES.INI, both in the program’s own folder in the user folder. The text is saved when the window closes, when you choose File › Save, and every half minute while you type. The first time Notes runs it has no NOTES.TXT yet, so it shows a welcome text that it ships in its DATA folder.

The Notes window with its welcome text
Figure 16. Notes on its first start, showing the welcome text from its DATA folder
The Notes window with a new line at the end and the status bar saying where the notes were saved
Figure 17. Notes after a line typed and File, Save: the status bar names the folder the notes are kept in

The program begins with its names. Besides the usual headers it includes dvxPrefs.h, for the settings calls, and fileOps.h, the file operations library’s header, which is on the SDK’s include path like every library’s:

#define NOTES_TITLE       "Notes"
#define NOTES_WIN_W       400
#define NOTES_WIN_H       300
#define NOTES_MIN_W       160
#define NOTES_MIN_H       120
#define NOTES_MAX_TEXT    32768
#define NOTES_SAVE_MS     30000
#define NOTES_MSG_MAX     (DVX_MAX_PATH + FILEOPS_MSG_MAX)
#define NOTES_UNSET       INT32_MIN

// The program's files: two in its user folder, one in its DATA folder
#define NOTES_TEXT_FILE   "NOTES.TXT"
#define NOTES_INI_FILE    "NOTES.INI"
#define NOTES_FIRST_FILE  "WELCOME.TXT"

// NOTES.INI: one section of the window's place
#define NOTES_SECTION     "window"
#define NOTES_KEY_X       "x"
#define NOTES_KEY_Y       "y"
#define NOTES_KEY_W       "width"
#define NOTES_KEY_H       "height"
#define NOTES_KEY_MAX     "maximized"

// Menu command IDs
#define CMD_FILE_SAVE     100
#define CMD_FILE_BACKUP   101
#define CMD_FILE_EXIT     102
#define CMD_HELP_CONTENTS 200

The files are named in 8.3 form, which every DOS disk takes (Section 10.8). The program keeps its paths in static buffers of DVX_MAX_PATH (260) bytes, DOS’s longest path:

// Where the window is and how big, as NOTES.INI keeps it
typedef struct {
    int32_t x;
    int32_t y;
    int32_t w;
    int32_t h;
    bool    maximized;
} NotesPlaceT;

static DxeAppContextT *sCtx     = NULL;
static AppContextT    *sAc      = NULL;
static WindowT        *sWin     = NULL;
static WidgetT        *sText    = NULL;
static WidgetT        *sStatus  = NULL;
static bool            sChanged = false;
static char            sTextPath[DVX_MAX_PATH];
static char            sIniPath[DVX_MAX_PATH];
static char            sSaveError[FILEOPS_MSG_MAX];

The rest of this chapter takes the program apart, a topic at a time.

10.2. Paths

A DOS path is a drive letter, a colon, and folder names separated by backslashes: C:\DVX\APPS. DJGPP’s C library takes a forward slash as well, and DVX goes further: every path DVX handles treats / and \ as the same separator (platformPathIsSep), on DOS and in DVX’s Linux test build alike, so a path your program writes as "APPS/LOCAL/NOTES" works exactly like "APPS\\LOCAL\\NOTES". What a user sees should have backslashes, as on any DOS system. DVX_PATH_SEP is the separator as a string literal ("\\" on DOS) for building paths from pieces, and platformPathNative(path) rewrites a path’s separators in place before you show it. The C library’s own answers need it: getcwd returns c:/dvx.

Every program runs with the same current folder: the DVX folder, where DVX.EXE is. A relative path is relative to it, which is why DxeAppContextT.appPath and userDir are relative (APPS\LOCAL\NOTES\NOTES.APP, USER\APPS\LOCAL\NOTES) and work as they are. DVX is one DOS program, so all its programs share that one current folder: never change it. A chdir in one program would move every other program’s relative paths, and DVX’s own.

Build paths with the platform layer’s functions (dvxPlat.h) instead of snprintf and string tests. They agree with each other on the separators, the drive letters, and case:

Function Does

platformPathJoin(out, size, dir, name)

dir and name with one separator between them, every separator native. An empty dir, or an absolute name, gives name alone. false when the result does not fit.

platformPathBaseName(path)

A pointer to the last part of path: the file name (after a drive too: C:A.TXT gives A.TXT). Never NULL.

platformPathDirName(path, out, size)

The folder part, a root keeping its separator (C:\X.TXT gives C:\), or . when there is none.

platformPathParent(path, out, size)

The folder holding path, a trailing separator ignored; false for a root.

platformPathAbsolute(path, out, size)

path made absolute against the current folder (the DVX folder).

platformPathIsAbsolute(path)

True for a path that starts with a separator or a drive letter.

platformPathSame(a, b)

True when two paths name the same place by DOS rules: either separator, any case, a trailing separator ignored.

platformPathIsUnder(path, dir)

The rest of path after dir when it lies in dir ("" for dir itself), else NULL.

dvxHasExt(name, ext)

True when name ends with ext (".txt"), in any case.

platformPathSame and platformPathIsUnder compare text, so USER\APPS and C:\DVX\USER\APPS are different to them. Bring two paths to the same form before you compare them; Notes makes its folder absolute before it copies it, because the copy job checks the destination against the source that way (Section 10.6.2). platformSameFile(a, b) asks DOS instead, for two existing files.

The drives are platformDriveList(out, max), which fills PlatformDriveT entries (the root, such as C:\, and whether the drive is fixed, removable, or remote) without touching a disk, so an empty floppy drive costs nothing to list; platformDiskSpace(path, &total, &free) gives a disk’s size and free space in bytes. An empty floppy drive or a write-protected disk does not stop DVX with DOS’s “Abort, Retry, Fail” question: DVX answers Fail for every program, and the C call that touched the drive returns its error. platformDriveErrno(path, err) tells a drive with no disk in it (ENXIO) from a file that is not there.

10.3. Where a Program’s Files Go

DVX keeps files apart by who writes them. The DVX folder holds what Setup installed, which DVX only reads: it may be on a CD-ROM, and an upgrade replaces it. Everything written while DVX runs goes in the user folder:

Folder Holds

SYSTEM

DVX’s own tools and files, and the shipped DVX.INI and ASSOC.INI.

LIBS, WIDGETS

The libraries and widgets, a folder for each.

APPS\<vendor>\<program>

Each program, its help file, and its DATA folder: the files the program ships, read-only.

SHARED

Fonts, sounds, themes, wallpapers, MIDI instrument banks, and screen savers for every program. Only packages put files here: DVX’s own, and add-ons, each in a folder of its vendor’s.

USER

The user folder: DVX.INI, ASSOC.INI (the user’s changes to the shipped one), DVX.LOG, the user’s own fonts, sounds, themes, wallpapers, banks, and savers, DOWNLOAD, and APPS\<program path>, a folder for each program’s settings and saved files.

The user folder is USER in the DVX folder unless the DVXUSER environment variable names another: a second disk, a folder of each person’s on a network. When it cannot be written (DVX on a CD-ROM), DVX uses a folder named DVXUSER in the TEMP folder instead, and says so. platformUserDir() is the user folder in force, and platformUserPath(out, size, rel) joins a name to it. That is the one folder to back up.

10.3.1. The Program’s Own Folder

A program’s settings and the files it saves go in its own folder in the user folder, DxeAppContextT.userDir. The shell works it out from the program’s path before appMain runs (platformAppUserDir):

  • A program in the DVX folder gets the user folder plus its own folder’s path: APPS\LOCAL\NOTES\NOTES.APP gets USER\APPS\LOCAL\NOTES.

  • A program kept in the user folder (a DVX BASIC project run from the IDE, say) gets APPS and its path in there: USER\PROJECTS\TODO\TODO.APP gets USER\APPS\PROJECTS\TODO.

  • A program anywhere else, or right in the user folder, gets USER\APPS\<name>, its file name without the extension.

The folder is not made until the program asks: shellEnsureUserDir(ctx) makes it, with any folders above it, and returns 0, or -1 when it cannot. shellUserPath(ctx, name, out, size) joins a file name to it. Notes does both first thing in appMain, so every save after can count on the folder:

int32_t appMain(DxeAppContextT *ctx) {
    NotesPlaceT place;

    sCtx = ctx;
    sAc  = ctx->shellCtx;

    // The program's folder is made now, so every save can count on it
    shellUserPath(ctx, NOTES_TEXT_FILE, sTextPath, sizeof(sTextPath));
    shellUserPath(ctx, NOTES_INI_FILE, sIniPath, sizeof(sIniPath));

    if (shellEnsureUserDir(ctx) != 0) {
        dvxLog("notes: cannot make %s", ctx->userDir);
    }

Two copies of a program that allows several (multiInstance, Section 11.5.2) share one userDir, since it comes from the program’s path. If both write the same file, the last one to save wins.

10.3.2. The DATA Folder

Files a program ships with it, too large or too many for resources (levels, pictures, sample documents), go in a DATA folder beside the .app. Name them in the Makefile with DATA, before the include, and make package copies them there (Appendix A):

SDK_DIR ?= ../../../../bin/sdk
KIND     = app
NAME     = notes
DATA     = welcome.txt

include $(SDK_DIR)/sdk.mk

shellDataPath(ctx, name, out, size) is the path of one of them: APPS\LOCAL\NOTES\DATA\WELCOME.TXT. It sets out to "" when the path does not fit. The DATA folder is part of the installed program, so treat it as read-only: Notes reads its welcome text from there and writes its own copy of the notes to its user folder. Small files can be resources instead, read with dvxResRead (Section 2.8).

10.3.3. Where Not to Write

A program writes only in its own user folder, in a folder the user chose (with a file dialog, Section 7.5), and in the user folder’s kinds of shared files when that is its job. It never writes:

  • In the DVX folder: not beside its .app, not in DATA, not in SYSTEM. The DVX folder may be read-only, and an upgrade or a removal replaces or deletes it with everything in it.

  • In SHARED. Only packages install there.

  • In another program’s folder in the user folder. Those files are that program’s business, and their format can change with its next version.

The fonts, sounds, themes, wallpapers, instrument banks, and screen savers are kinds of file both SHARED and the user folder have a folder for (DvxKindE). A program finds one by name with platformKindFind(out, size, kind, name), which looks in the user’s folder first, so a user’s file of the same name wins, and a program that makes such a file, as a theme editor does, saves it in the user’s folder, platformKindDir(out, size, kind, true).

When the user folder cannot be written and there is no TEMP folder to use instead, platformIsReadOnly() is true and nothing can be saved: settings saves are kept in memory until DVX exits (DVX tells the user once), and other files fail to save as on any read-only disk. A program that saves files can say so up front by checking it.

10.4. Reading and Writing Files

A DOS text file’s lines end in CR LF. DJGPP’s stdio opens files in text mode unless the mode has a b, and in text mode it turns CR LF into LF as it reads and LF into CR LF as it writes, so fgets and fprintf work as on Linux; open binary files with "rb" and "wb". The widgets keep text with LF line ends.

For a file read whole, platformReadFile(path, &len) returns its contents in a block from malloc with a terminating zero after the last byte, and its length, or NULL when it is missing or cannot be read; the caller frees it. It reads in binary mode, so a text file comes back with its CRs, which platformStripLineEndings(buf, len) removes in place, returning the new length. Notes reads its text that way:

// The notes from NOTES.TXT, or at the first start (no NOTES.TXT yet) the
// text the program ships in its DATA folder, or nothing.  False when
// NOTES.TXT is there but cannot be read, or holds more than the text area
// can: the program then leaves it alone instead of saving over it.
static bool loadText(void) {
    char           first[DVX_MAX_PATH];
    PlatformStampT stamp;
    int32_t        len      = 0;
    bool           firstRun = !platformFileStamp(sTextPath, &stamp);

    shellDataPath(sCtx, NOTES_FIRST_FILE, first, sizeof(first));

    char *text = platformReadFile(firstRun ? first : sTextPath, &len);

    if (!text) {
        return firstRun;
    }

    // A DOS text file's lines end in CR LF, a text area's in LF
    len = platformStripLineEndings(text, len);

    bool fits = len <= NOTES_MAX_TEXT;

    if (fits) {
        wgtSetText(sText, text);
    }

    free(text);
    return fits;
}

platformFileStamp(path, &stamp) is true when path is a file, and gives its size and time (PlatformStampT; compare two only for equality, to tell whether a file changed). It costs one DOS directory search, where stat makes several calls, tens of milliseconds on a slow disk. Notes uses it to tell its first start, when NOTES.TXT is not there, from a NOTES.TXT that cannot be read. The difference matters: a program that took an unreadable file for a missing one would show its welcome text and then save it over the user’s notes. For the same reason Notes refuses a file larger than its text area holds (a wgtSetText would cut it, and the next save would lose the rest) and does not start, leaving the file alone.

10.4.1. Writing a File Safely

A file written in place is half old and half new while the write runs, and a full disk, a removed floppy, or a fault in the middle leaves it that way. DVX’s writes go around it: the new contents go to a scratch file beside the old one, which takes the old file’s place only once all of it is written. platformWriteFile(path, data, len) does that for a block of bytes and returns false, with the old file as it was, when anything failed; it also refuses to replace a read-only file. TinyEdit saves through it (Chapter 6).

For text, fileOpsSaveText (fileOps.h) writes the same way and turns every line end, LF or CR LF, into CR LF on the way, so a text area’s text goes to disk as a DOS text file with no copying of your own:

// NOTES.TXT, when the text changed since it was last saved.
// fileOpsSaveText writes each line end as CR LF into a scratch file beside
// NOTES.TXT, which takes its place only once all of it is written, so a
// full disk leaves the last save as it was.  On failure sSaveError says
// why, for the caller to show.
static bool saveText(void) {
    FileOpsSaveStepE failed;
    const char      *text = wgtGetText(sText);

    if (!sChanged) {
        return true;
    }

    if (!fileOpsSaveText(sTextPath, text, (int32_t)strlen(text), NULL, NULL, &failed, sSaveError, sizeof(sSaveError))) {
        setStatus("Not saved: %s", strerror(errno));
        return false;
    }

    sChanged = false;
    setStatus("Saved in %s.", sCtx->userDir);
    return true;
}

fileOpsSaveText(path, text, len, pump, ctx, &failed, err, errSize) returns true, or false with errno set, the step that failed in failed (FileOpsSaveOpenE, FileOpsSaveWriteE, or FileOpsSaveReplaceE), and a message for the user in err, at most FILEOPS_MSG_MAX (320) bytes: “Cannot save” and the path on one line, the reason on the next. The scratch file is gone either way. pump, with ctx, is called every so often while a long text is written, with no file open, so a program can keep DVX running meanwhile (Section 11.2); NULL is none. Notes keeps the message for whoever shows it and puts a short form, from strerror(errno), in its status bar.

A file written a piece at a time, with fopen and fwrite, can be made safe the same way. platformScratchFile(out, size, path, PLATFORM_TMP_EXT) makes the scratch file and gives its name (NOTES.$TX for NOTES.TXT, still an 8.3 name; a numbered one such as NOTES.$00 when something has that name already, so a file that was there is never written over), and after a successful fclose, platformReplaceFile(tmpPath, path) swaps it in, with the old file parked under the PLATFORM_BAK_EXT name (NOTES.~TX, or a numbered one) until the new one is in place. platformCanReplaceFile(path) checks first that the swap will be allowed, so a long write is not wasted on a read-only file.

The platform layer has a few more whole-file calls: platformCopyFile(src, dst) copies a file and removes a partial copy when it fails (errno ENOSPC for a full disk), platformRename(old, new) renames, also to the same name in other letters, which DOS with long names otherwise refuses, and platformMkdirRecursive(path) makes a folder and the ones above it, like mkdir -p, returning 0 or -1. platformWalkDir(dir, fn, ctx) calls fn for every file below a folder.

DOS reports a disk that refuses a change badly: a create on a write-protected floppy fails with ENOENT, and a delete on a CD-ROM with EINVAL. Before you report a failed create, delete, rename, or new folder, pass errno through platformChangeErrno(path, made, err), which turns those into EACCES when the folder is there, so the message the user sees says the disk refused.

10.5. Settings Files

A program’s settings go in an INI file in its user folder, which dvxPrefs.h reads and writes. The format is the familiar one; this is a NOTES.INI as Notes writes it:

[window]
x = 112
y = 84
width = 400
height = 300
maximized = false

prefsLoad(path) reads a file into a new handle, a PrefsHandleT *. A file that is not there gives an empty handle, not an error, and the handle remembers the path for saving, so a program’s first run needs no code of its own: every getter returns the default it is given. Notes reads its window’s place that way:

// The window's last place from NOTES.INI.  A missing file gives an empty
// handle and a missing key its default, so the first start needs no code
// of its own.
static void loadPlace(NotesPlaceT *place) {
    PrefsHandleT *prefs = prefsLoad(sIniPath);

    place->x         = prefsGetInt(prefs, NOTES_SECTION, NOTES_KEY_X, NOTES_UNSET);
    place->y         = prefsGetInt(prefs, NOTES_SECTION, NOTES_KEY_Y, NOTES_UNSET);
    place->w         = prefsGetInt(prefs, NOTES_SECTION, NOTES_KEY_W, NOTES_WIN_W);
    place->h         = prefsGetInt(prefs, NOTES_SECTION, NOTES_KEY_H, NOTES_WIN_H);
    place->maximized = prefsGetBool(prefs, NOTES_SECTION, NOTES_KEY_MAX, false);
    prefsClose(prefs);
}
Call Does

prefsGetString(h, section, key, default)

The value, or default. The pointer stays valid until the key changes or the handle is closed.

prefsGetInt(h, section, key, default)

The value as a decimal number, or default when the key is missing or does not start with one.

prefsGetBool(h, section, key, default)

True for true, yes, or 1, false for false, no, or 0, in any case; anything else gives default.

prefsSetString, prefsSetInt, prefsSetBool

Set a key, making the section and the key when they are new; a bool is written as true or false.

prefsRemove(h, section, key)

Remove a key.

prefsKeyName(h, section, index)

The name of a section’s keys in turn, NULL past the last: for a list of any length.

prefsSave(h)

Write the file the handle was loaded from.

prefsSaveAs(h, path)

Write it to path instead.

prefsClose(h)

Free the handle. It does not save.

Section and key names match in any case, and when a key appears twice the first one wins. Lines the program does not change, comments included, are written back as they were; a new key goes after the last key of its section; every line is written with CR LF. Each call accepts a NULL handle (the getters return their defaults, the others do nothing), so a program need not test for the one failure prefsLoad has, running out of memory.

Saving is all or nothing, through a scratch file as above. prefsSave also refuses, returning false, when the file was there but could not be read when it was loaded: the handle holds none of its settings, and saving it would replace the user’s file with defaults. prefsLoadFailed(h) tells you that happened. Notes saves the window’s place by loading the file afresh, setting its keys, and saving, so a comment or a key the user typed into NOTES.INI stays:

// The window's place into NOTES.INI.  A maximized window keeps the place
// it goes back to in preMaxX and the rest, which is the one to save.
// prefsLoad reads the file as it is now, so a comment or a key typed in by
// hand stays, and prefsSave writes it all or nothing.  A place that
// cannot be saved is only logged: the notes matter, the place does not.
static void savePlace(void) {
    const WindowT *win   = sWin;
    PrefsHandleT  *prefs = prefsLoad(sIniPath);
    bool           max   = win->maximized;

    prefsSetInt(prefs, NOTES_SECTION, NOTES_KEY_X, max ? win->preMaxX : win->x);
    prefsSetInt(prefs, NOTES_SECTION, NOTES_KEY_Y, max ? win->preMaxY : win->y);
    prefsSetInt(prefs, NOTES_SECTION, NOTES_KEY_W, max ? win->preMaxW : win->w);
    prefsSetInt(prefs, NOTES_SECTION, NOTES_KEY_H, max ? win->preMaxH : win->h);
    prefsSetBool(prefs, NOTES_SECTION, NOTES_KEY_MAX, max);

    if (!prefsSave(prefs)) {
        dvxLog("notes: cannot save %s", sIniPath);
    }

    prefsClose(prefs);
}

A maximized window’s x, y, w, and h describe it maximized; the place it goes back to is in preMaxX, preMaxY, preMaxW, and preMaxH, and that is the place to keep, with the flag. A minimized window keeps its place in x and y.

A settings file is text that anyone can edit, and the screen it was saved on may not be the screen now: the user may have chosen a smaller video mode since. So Notes keeps the size between a minimum and the screen before it opens the window, and centers a window it has no place for. dvxCreateWindow keeps a window’s position on the screen by itself, but not its size:

// A settings file is text anyone can edit, and the screen may be smaller
// than it was (another video mode), so the size is kept between
// NOTES_MIN_W x NOTES_MIN_H and the screen; dvxCreateWindow then keeps the
// window on the screen.  A place never saved is centered.
static void fitPlace(NotesPlaceT *place) {
    const DisplayT *screen = &sAc->display;

    place->w = DVX_MIN(DVX_MAX(place->w, NOTES_MIN_W), screen->width);
    place->h = DVX_MIN(DVX_MAX(place->h, NOTES_MIN_H), screen->height);

    if (place->x == NOTES_UNSET || place->y == NOTES_UNSET) {
        place->x = (screen->width - place->w) / 2;
        place->y = (screen->height - place->h) / 2;
    }
}

DVX’s own settings are in DVX.INI in the user folder (platformDvxIniPath()). Keep your program’s settings in a file of its own rather than in DVX.INI. To read one of DVX’s settings, prefsDvxIniShared() gives a handle to DVX.INI that is parsed again only when the file changed; do not change it, close it, or keep it past the call that uses it.

Two more calls are worth knowing. prefsSetSecret stores a password so that it cannot be read at a glance, and prefsGetSecret reads it back; that is obfuscation, not encryption, since anyone with DVX’s code can undo it. prefsApplyChanges(h, before, after) is for a settings window with OK and Cancel: it applies to a fresh load of the file only the keys the user changed in the window, so a change another program made to the same file meanwhile is kept. The reference has the rest (“dvxPrefs.h — Preferences System” in the DVX C Library Reference).

10.5.1. Saving When the Window Closes

The window’s onClose saves both files. When the text cannot be saved (the disk is full, the floppy is gone), the user decides whether to close anyway, so the notes are never lost without a word:

// Closing saves.  When the text cannot be saved, the user chooses: close
// anyway, losing the changes, or keep the window and try again later.
static void onClose(WindowT *win) {
    savePlace();

    if (!saveText()) {
        char msg[NOTES_MSG_MAX];

        snprintf(msg, sizeof(msg), "%s\n\nClose Notes anyway? Your changes will be lost.", sSaveError);

        if (dvxMessageBox(sAc, NOTES_TITLE, msg, MB_YESNO | MB_ICONWARNING) != ID_YES) {
            return;
        }
    }

    dvxDestroyWindow(sAc, win);
    sWin = NULL;
}

Saving on close is not enough by itself. A fault ends a program without calling anything of its own, and End Task calls only its appShutdown (Section 2.9), so Notes also saves every NOTES_SAVE_MS while there are changes, from a Timer (Section 11.1), and File › Save saves at once:

// Every NOTES_SAVE_MS: the text, if it changed.  A failure shows in the
// status bar; the next tick tries again.
static void onSaveTimer(WidgetT *w) {
    (void)w;
    saveText();
}

// File > Save, and Back Up before it copies: both files now, and a text
// that cannot be saved said in a message box.
static bool saveNow(void) {
    savePlace();

    if (!saveText()) {
        dvxErrorBox(sAc, NOTES_TITLE, sSaveError);
        return false;
    }

    return true;
}

saveText returns at once when nothing changed, so a quiet Timer writes nothing. The rest of appMain builds the window from the place it read, loads the text, and maximizes the window when it was maximized; the menu bar goes first and the window’s handlers go after wgtInitWindow, as always (Chapter 4):

loadPlace(&place);
fitPlace(&place);
sWin = dvxCreateWindow(sAc, NOTES_TITLE, place.x, place.y, place.w, place.h, true);

if (!sWin) {
    return -1;
}

// The menu bar first; the widgets top to bottom.  The Timer takes no
// room and shows nothing.
WidgetT *root = buildMenus() ? wgtInitWindow(sAc, sWin) : NULL;

sText = root ? wgtTextArea(root, NOTES_MAX_TEXT) : NULL;

WidgetT *bar       = root ? wgtStatusBar(root) : NULL;
WidgetT *saveTimer = root ? wgtTimer(root, NOTES_SAVE_MS, true) : NULL;

sStatus = bar ? wgtLabel(bar, "") : NULL;

if (!sText || !sStatus || !saveTimer) {
    dvxDestroyWindow(sAc, sWin);
    return -1;
}

if (!loadText()) {
    char msg[NOTES_MSG_MAX];

    dvxDestroyWindow(sAc, sWin);
    snprintf(msg, sizeof(msg), "%s could not be read, or holds more than Notes can show. It is left as it is.", sTextPath);
    dvxErrorBox(sAc, NOTES_TITLE, msg);
    return -1;
}

sStatus->weight     = WGT_WEIGHT_FILL;
sText->onChange     = onTextChange;
saveTimer->onChange = onSaveTimer;
sWin->onClose       = onClose;
sWin->onMenu        = onMenu;

if (place.maximized) {
    dvxMaximizeWindow(sAc, sWin);
}

wgtSetFocused(sText);
return 0;

10.6. The File Operations Library

The file operations library (fileops.lib, fileOps.h) is what DVX’s File Manager and Setup are built on, and any program can use it: folder listings, attributes and dates, names and paths, and jobs that copy, move, or delete any number of files and folders with progress and questions for the user. It is part of every DVX installation, and DVX loads it when a program first needs it, if nothing has loaded it before.

10.6.1. Listing a Folder

fileOpsListDir(dir, filter, &entries, &count) reads a folder into an array of FileOpsEntryT (the name, the size in bytes as a uint64_t, the time, and whether it is a folder). filter is a list of wildcard patterns separated by ;, ,, or blanks ("*.txt;*.doc"); files that match none of them are left out, folders always stay, and NULL or "*.*" keeps everything. . and .. are never listed. fileOpsListSort puts the folders first and sorts by name, size, type, or date, and fileOpsListFree frees the array:

FileOpsEntryT *entries = NULL;
int32_t        count   = 0;

if (fileOpsListDir(sCtx->userDir, "*.txt", &entries, &count)) {
    fileOpsListSort(entries, count, FileOpsSortNameE, false);

    for (int32_t i = 0; i < count; i++) {
        dvxLog("%s%s", entries[i].name, entries[i].isDir ? " (folder)" : "");
    }

    fileOpsListFree(entries, count);
}

For showing a listing, fileOpsFormatSize writes a size as 1,234,567, fileOpsFormatDate a time as YYYY-MM-DD HH:MM, and fileOpsTypeName an entry’s type as File Manager shows it. fileOpsGetAttr and fileOpsSetAttr read and set the DOS attributes (FILEOPS_ATTR_READONLY, HIDDEN, SYSTEM, and ARCHIVE), and fileOpsTreeSize totals a folder’s bytes, files, and folders. The C library’s opendir and readdir work too.

10.6.2. Copying, Moving, and Deleting

A job copies, moves, deletes, or measures any number of files and folders, with everything inside them. Make one with fileOpsJobCreate(op, destDir), where op is FileOpsCopyE, FileOpsMoveE, FileOpsDeleteE, or FileOpsMeasureE (which counts and changes nothing) and destDir is the folder to copy or move into; add each file or folder with fileOpsJobAddSource(job, path), which is false when it is not there. Then step it: each fileOpsJobStep(job) does one bounded piece of work, part of a folder read, one 8 KB chunk of one file (FILEOPS_COPY_CHUNK), or one delete, and returns what happened:

Result Meaning

FileOpsStepBusyE

More to do: call again.

FileOpsStepAskE

A file to copy or move is there already, or a file to delete is read-only. fileOpsJobMessage(job) is the question; answer it with fileOpsJobAnswer(job, answer): FileOpsAnswerYesE, FileOpsAnswerAllE (yes to this one and every one after), FileOpsAnswerNoE, or FileOpsAnswerCancelE.

FileOpsStepErrorE

Something failed; fileOpsJobMessage(job) says what. Answer FileOpsAnswerRetryE, FileOpsAnswerSkipE, or FileOpsAnswerCancelE.

FileOpsStepDoneE

Finished.

FileOpsStepCancelledE

Stopped by a Cancel answer or by fileOpsJobCancel(job).

Until a question is answered, every step returns it again. fileOpsJobProgress(job, &progress) fills a FileOpsProgressT with the files and bytes done and to do, the percent done, and the path being worked on, for a progress bar. A copy keeps each file’s date and attributes; a move renames an item in one go when it can; a delete removes the files before their folders. Copying a folder into itself, or a file onto itself, is an error the job reports rather than a mess it makes. fileOpsJobFree(job) frees the job, and a job that did not finish closes its files and removes the file it was partly through copying.

A job of a few files can run to its end in one call: fileOpsJobRun(job, &callbacks) steps it until it is done or canceled, calling callbacks.progress after each step (return false to cancel) and callbacks.ask for each question. With no ask, it answers No to every file that is there already and skips every error. Notes’s File › Back Up…​ copies its own folder into a folder the user chooses:

// File > Back Up: the notes saved, then the program's folder (NOTES.TXT
// and NOTES.INI) copied into a folder the user chooses, as a folder of the
// same name.  The job compares paths as text, so the source is made a full
// path like the one the dialog returns.
static void backUp(void) {
    char              dest[DVX_MAX_PATH];
    char              source[DVX_MAX_PATH];
    FileOpsCallbacksT callbacks = { .ask = askJob };

    if (!saveNow() || !dvxFileDialog(sAc, "Back Up To", FD_FOLDER, NULL, NULL, 0, dest, sizeof(dest))) {
        return;
    }

    // A folder typed in the dialog may be new: the program makes it
    if (platformMkdirRecursive(dest) != 0) {
        setStatus("Cannot make %s: %s", dest, strerror(errno));
        return;
    }

    FileOpsJobT *job   = fileOpsJobCreate(FileOpsCopyE, dest);
    bool         ready = job && platformPathAbsolute(sCtx->userDir, source, sizeof(source)) && fileOpsJobAddSource(job, source);

    if (!ready) {
        setStatus("Cannot back up to %s.", dest);
    } else if (fileOpsJobRun(job, &callbacks) == FileOpsStepDoneE) {
        setStatus("Backed up to %s.", dest);
    } else {
        setStatus("Back up canceled.");
    }

    fileOpsJobFree(job);
}

A folder chosen with FD_FOLDER may be one the user typed that is not there yet, so the program makes it. The source is made absolute because the job checks for a copy into itself by comparing the two paths as text, and the dialog returns a full path. The questions go to the user through dvxButtonBox, whose index picks the answer:

// A copy job's two kinds of question, as button labels and the answer
// each button gives.  The last button is the one Esc chooses.
static const char *const    sAskLabels[]    = { "&Yes", "&All", "&No", "Cancel" };
static const FileOpsAnswerE sAskAnswers[]   = { FileOpsAnswerYesE, FileOpsAnswerAllE, FileOpsAnswerNoE, FileOpsAnswerCancelE };
static const char *const    sErrorLabels[]  = { "&Retry", "&Skip", "Cancel" };
static const FileOpsAnswerE sErrorAnswers[] = { FileOpsAnswerRetryE, FileOpsAnswerSkipE, FileOpsAnswerCancelE };

// The copy job's questions, answered by the user: a file that is there
// already (Yes, All, No, or Cancel), or an error (Retry, Skip, or Cancel).
// dvxButtonBox returns the index of the button chosen.
static FileOpsAnswerE askJob(FileOpsJobT *job, FileOpsStepE kind, const char *message, void *ctx) {
    (void)job;
    (void)ctx;

    if (kind == FileOpsStepAskE) {
        return sAskAnswers[dvxButtonBox(sAc, NOTES_TITLE, message, MB_ICONQUESTION, sAskLabels, DVX_ARRAY_LEN(sAskLabels))];
    }

    return sErrorAnswers[dvxButtonBox(sAc, NOTES_TITLE, message, MB_ICONERROR, sErrorLabels, DVX_ARRAY_LEN(sErrorLabels))];
}

fileOpsJobRun does not return until the job is done, and DVX does nothing else meanwhile. That is fine for Notes’s two small files and wrong for a folder of hundreds: step a large job from a task or a Timer instead, a few steps at a time, and show its progress between them, as Section 11.2 shows for a long computation. Free a job on every path, the one where the window closes in the middle included: DVX frees a program’s windows when it ends, but not the jobs it left.

10.7. File Associations

A file association says which program opens a type of document: .TXT files in Notepad, .BMP files in the Image Viewer. The list DVX ships is SYSTEM\ASSOC.INI, and the user’s changes to it (made on Control Panel’s File Types page) are ASSOC.INI in the user folder; a program sees the two together through shellAssoc.h. Each entry is an extension and a program path from the DVX folder, with an optional argument template after a comma, where %1 stands for the document:

[associations]
TXT = apps/kpunch/notepad/notepad.app
FRM = apps/kpunch/dvxbasic/dvxbasic.app,%1

To open a document the way Program Manager and File Manager do, call shellAssocOpenDocument(ctx, path): it starts the program set for the document’s extension with the document as its argument, and returns false when the type has no program or the program does not start. shellAssocCommand(path, program, programSize, args, argsSize) gives the program and the argument string without starting anything, and shellAssocLookup(ext, out, size) the stored value for an extension (with or without the dot, in any case); both are false when the type has no association, or its program is not installed. shellRunProgram (Section 11.6) opens a document too, and shows the user what went wrong when it cannot.

A program that opens a kind of document of its own can register it with shellAssocSet(ext, program), where program is its own path (sCtx->appPath) with any template; the change goes to the user’s ASSOC.INI at once. Take the type only when nobody has it (shellAssocLookup is false): the user’s choice of program for a type belongs to the user. shellAssocRemove(ext) takes an association out of the user’s file.

A program started for a document finds the document’s path as the first argument of DxeAppContextT.args, in double quotes when it has blanks in it. Section 11.5 shows how to read it.

10.8. Long File Names

Plain DOS names are 8.3: up to eight characters, a dot, and up to three more, in one case, without blanks. Where a long-name driver is running (Windows, or DOSLFN on plain DOS), names can be up to 255 characters, with blanks and lower case, and DJGPP’s C library uses the long-name calls by itself: fopen, rename, mkdir, stat, and readdir take and return long names. Whether a drive takes them depends on the driver; platformLongNames(path) says for the drive that holds path.

So write programs that work either way:

  • Give the files your program makes 8.3 names, as Notes does with NOTES.TXT and NOTES.INI. Without long names, DOS cuts a longer name down to 8.3 instead of refusing it, and two long names can end up as one short one.

  • Check a name the user types with platformValidateFilename(dir, name), which applies the rules of the disk dir is on, long or 8.3, and returns NULL or a sentence saying what is wrong (fileOpsValidateName is the same with the reason copied into a buffer). The file dialogs already do this.

  • A long name can have blanks in it, so a command line puts it in double quotes. dvxArgAppend adds an argument that way and dvxNextArg reads it back whole (Section 11.5).

  • A DOS program that knows only 8.3 names gets a file’s short name, platformShortPath(path, out, size), which on a drive with long names gives the 8.3 alias of every part of an existing path (Section 11.7).

A program’s own module and folder names are always 8.3 (newProject.sh refuses anything longer), since DVX must load them on any disk.

10.9. Things to Know

  • shellUserPath and shellDataPath return nothing, and when the joined path does not fit in outSize they set the buffer to "", never to a path cut short. With buffers of DVX_MAX_PATH bytes that does not happen in practice.

  • fileOpsListDir returns false, with errno set to ENOMEM and nothing to free, when memory runs out partway through a folder; it never returns part of a list.

Chapter 11. Timers, Tasks, and Other Programs

Part I set the rule every DVX program lives by: nothing may block (Section 3.5). This chapter is about doing things over time without breaking it: work that comes back every so often (timers), work that takes long (tasks, and how to keep the screen alive and the user in charge while it runs), and the program’s place among the others (its command line, starting other programs and DOS programs, screen savers, and the Task Manager).

The example, primes, counts the prime numbers up to a limit the user chooses. With a limit of ten million that takes minutes on a 486, and DVX goes on working the whole time: the count runs on a task, shows its progress, and stops when the user clicks Cancel.

11.1. Timers

The usual timer is the Timer widget (timer/timer.h): an invisible widget in a window’s widget tree that calls its onChange callback when its interval has passed. wgtTimer(parent, intervalMs, repeat) makes one; with repeat true it fires every intervalMs milliseconds, with false once. It takes no room in the layout, and it is freed with its window like any widget. Notes saves its text from one:

WidgetT *saveTimer = wgtTimer(root, NOTES_SAVE_MS, true);

saveTimer->onChange = onSaveTimer;

A new Timer is running. The other calls are macros of the widget’s header:

Call Does

wgtTimerStop(w)

Stop it.

wgtTimerStart(w)

Start it, counting the interval from now.

wgtTimerIsRunning(w)

Whether it runs.

wgtTimerSetInterval(w, ms)

A new interval, counted from now. An interval of 0 or less never fires.

wgtTimerGetInterval(w)

The interval.

wgtTimerSetRepeat(w, repeat), wgtTimerGetRepeat(w)

Repeating or one-shot, from the next time it fires.

A one-shot Timer is stopped just before its callback runs, so the callback can start it again for another round.

How a Timer behaves follows from where it is checked:

  • Timers are checked once a frame, in the shell’s event loop, on the shell’s task (Section 3.6). The callback runs there, with the program that owns the window as the running program, so what it allocates is counted to it. It runs whatever your program is doing otherwise: during a dialog box of yours too, since the box runs frames (Section 7.2).

  • The interval is measured with platformClock(), which on DOS is the C library’s clock(), and DJGPP counts that from the BIOS clock: 18.2 ticks a second. So an interval comes out as a whole number of those ticks, about 55 ms each, and no Timer fires more than about 18 times a second, whatever interval it asks for.

  • A Timer that comes due late, because a frame was slow, fires once, and its next interval counts from then. Timers do not catch up, so do not count ticks to tell the time: read a clock.

  • The callback is a callback like any other: it must return promptly (Section 3.5).

11.1.1. Clocks

To measure time, read a clock (dvxPlat.h):

  • platformMicros() is a 64-bit count of microseconds since DVX started its timer, always rising, for timing work and pacing loops; ticker used it (Section 3.7). On a 486, which has no time-stamp counter, each call reads the timer chip’s count through I/O ports with interrupts off, which is cheap but not free, so a tight loop should not read it on every pass (Primes reads it every 256 numbers).

  • platformClock() is the clock the Timers use: platformClockHz() ticks a second, with PLATFORM_MS_TO_TICKS(ms) and PLATFORM_TICKS_TO_MS(ticks) to convert. It is a uint32_t that wraps, so compare two readings by subtracting them, never with <.

  • dvxIdleMs(ctx) is the milliseconds since the last key or mouse input, the one the screen saver waits on.

  • The C library’s time and localtime give the date and the time of day, from DOS.

11.1.2. Idle Handlers

For work that should run as often as DVX has nothing else to do, such as polling a device, register an idle handler: shellRegisterIdle(fn, ctx) calls fn(ctx) on every frame that painted nothing, and at least every 20 ms while frames keep painting, whichever program is in front. It runs as the program that registered it. Keep it short, and remove it with shellUnregisterIdle(fn, ctx) when it is no longer wanted, in appShutdown at the latest; the shell also drops a program’s handlers when the program ends. Program Manager runs its Startup group from one.

11.1.3. Interrupt Timers

For the few jobs that must run at a steady rate however busy the programs are, such as feeding a sound device, DVX has timers that run inside the timer interrupt: platformTimerAdd(hz, fn, userData, ownerAppId) calls fn(userData) hz times a second (1 to PLATFORM_TIMER_MAX_HZ, 1000), and platformTimerRemove(id) stops it. There are 16 of them for all of DVX (PLATFORM_TIMER_SLOTS). The callback runs with interrupts disabled, on a small interrupt stack, in the middle of whatever code was running: it may set flags, fill a buffer, or write I/O ports, and nothing else. No C library, no DVX call, no DOS, no floating point, and every byte of its code and data must be locked in memory with platformLockRegion, since a page fault there is fatal. Pass ctx->appId as ownerAppId, and the shell removes the timer when the program ends. The game library’s gameTimerAdd does that for you (Chapter 17). A program’s ordinary work never needs one.

11.2. Long Work

Some work takes seconds or minutes: a computation, a search through a disk, a big copy. It must not run in one piece inside a callback, since DVX does nothing else until the callback returns. There are three good ways to do it:

  • In slices on a Timer. A callback-only program does a little of the work at each tick of a repeating Timer, a few milliseconds' worth, and keeps its place in static variables. This is simple and needs no task, but Timers fire at most about 18 times a second, so the work gets only a fraction of the machine even when nothing else wants it. It suits light work in the background.

  • On a task of the program’s own. shellAppTaskStart runs a function of a callback-only program on a task of its own, which yields every so often; the rest of the program goes on in its callbacks as before. The work gets most of the processor, and the screen stays alive. Primes does this.

  • In a main loop. A program whose whole life is continuous work, such as a game or a terminal, is a main-loop program (hasMainLoop) and does its work in its loop (Section 3.4).

There is a fourth way, which works but should not be used: a callback that runs the work in a loop and calls dvxUpdate now and then, so the screen repaints. The screen does stay alive, but the shell’s own main loop is stuck under the callback until it returns: programs that end are not reaped, Exit DVX and requests to close a program wait, a DOS program waits to run, and the screen saver does not start. And after DVX_HUNG_APP_MS (5 seconds) in one callback, the Task Manager shows the program as Not responding, and its End Task abandons the callback at its next frame, as a fault would, with nothing saved. A dialog box is the one sanctioned exception (Section 3.6).

For an operation of a second or two that cannot be split, such as a single large write, show the hourglass with dvxSetBusy (Chapter 8) and let it block.

11.3. The Primes Program

Primes is a small window: a spinner for the limit, a progress bar, a line of status, a Low priority check box, and Start and Cancel buttons.

The Primes window with the count limit, an empty progress bar, its status line, the Low priority check box, and Start and Cancel buttons
Figure 18. Primes, ready to count
The Primes window with a full progress bar and the number of primes found
Figure 19. Primes after a count to a million
#define PRIMES_TITLE          "Primes"
#define PRIMES_WIN_W          340
#define PRIMES_WIN_H          200
#define PRIMES_SPACING        6
#define PRIMES_TEXT_MAX       96
#define PRIMES_LIMIT_CHARS    12    // the spinner, buttons included: 8 digits and the caret
#define PRIMES_STATUS_CHARS   46    // the longest status: "664579 primes up to 10000000, in 9999 seconds."
#define PRIMES_BUTTON_CHARS   8

// The limits a count may have, and the spinner's
#define PRIMES_LIMIT_MIN      2
#define PRIMES_LIMIT_MAX      10000000
#define PRIMES_LIMIT_START    1000000
#define PRIMES_LIMIT_STEP     100000
#define PRIMES_ARG_MAX        16
#define PRIMES_RADIX          10

// The arithmetic: 2 is the one even prime; odd divisors start at 3
#define PRIMES_FIRST_PRIME    2
#define PRIMES_FIRST_ODD      3
#define PRIMES_ODD_STEP       2

// The task: its name, its stack, how long it runs before it yields, and
// how many numbers it tries between looks at the clock
#define PRIMES_TASK_NAME      "primes"
#define PRIMES_TASK_STACK     TS_DEFAULT_STACK_SIZE
#define PRIMES_SLICE_US       20000
#define PRIMES_CHECK_EVERY    256

// A ProgressBar shows 0 to 100
#define PRIMES_PERCENT_FULL   100
static DxeAppContextT *sCtx       = NULL;
static AppContextT    *sAc        = NULL;
static WindowT        *sWin       = NULL;
static WidgetT        *sLimit     = NULL;
static WidgetT        *sBar       = NULL;
static WidgetT        *sStatus    = NULL;
static WidgetT        *sLowPri    = NULL;
static WidgetT        *sStartBtn  = NULL;
static WidgetT        *sCancelBtn = NULL;
static bool            sRunning   = false;
static bool            sStopAsked = false;
static uint32_t        sCountTo   = 0;

It is a callback-only program that runs once, with the defaults:

SHELL_APP_DESCRIPTOR(
    .name          = PRIMES_TITLE,
    .hasMainLoop   = false,
    .multiInstance = false,
    .stackSize     = SHELL_STACK_DEFAULT,
    .priority      = TS_PRIORITY_NORMAL
);

appMain builds the window. The limit comes from a spinner, which keeps its value between its limits however the user types; Start is the window’s default button and Cancel its cancel button (Section 7.7.1), so Enter starts a count and Esc stops one. The two lines that set onNewArgs are for the command line (Section 11.5):

sCtx = ctx;
sAc  = ctx->shellCtx;
sWin = dvxCreateWindowCentered(sAc, PRIMES_TITLE, PRIMES_WIN_W, PRIMES_WIN_H, false);

if (!sWin) {
    return -1;
}

sWin->onClose = onClose;

WidgetT *root    = wgtInitWindow(sAc, sWin);
WidgetT *limits  = root ? wgtHBox(root) : NULL;
WidgetT *caption = limits ? wgtLabel(limits, "Count up to:") : NULL;

sLimit  = limits ? wgtSpinner(limits, PRIMES_LIMIT_MIN, PRIMES_LIMIT_MAX, PRIMES_LIMIT_STEP) : NULL;
sBar    = root ? wgtProgressBar(root) : NULL;
sStatus = root ? wgtLabel(root, "Choose a number, then click Start.") : NULL;
sLowPri = root ? wgtCheckbox(root, "&Low priority") : NULL;

WidgetT *buttons = root ? wgtHBox(root) : NULL;

sStartBtn  = buttons ? wgtButton(buttons, "&Start") : NULL;
sCancelBtn = buttons ? wgtButton(buttons, "Cancel") : NULL;

if (!caption || !sLimit || !sBar || !sStatus || !sLowPri || !sStartBtn || !sCancelBtn) {
    dvxDestroyWindow(sAc, sWin);
    return -1;
}

root->spacing       = wgtPixels(PRIMES_SPACING);
buttons->align      = AlignEndE;
sLimit->minW        = wgtChars(PRIMES_LIMIT_CHARS);
sStatus->minW       = wgtChars(PRIMES_STATUS_CHARS);
sLowPri->onChange   = onLowPriChange;
sStartBtn->minW     = wgtChars(PRIMES_BUTTON_CHARS);
sStartBtn->onClick  = onStartClick;
sCancelBtn->minW    = wgtChars(PRIMES_BUTTON_CHARS);
sCancelBtn->onClick = onCancelClick;
ctx->onNewArgs      = onNewArgs;
ctx->newArgsCtx     = ctx;
wgtSpinnerSetValue(sLimit, PRIMES_LIMIT_START);
dvxSetWindowButtons(sWin, sStartBtn, sCancelBtn);
setRunning(false);
dvxFitWindow(sAc, sWin);
// While a count runs, Cancel works and Start and the limit do not.
static void setRunning(bool running) {
    sRunning = running;
    wgtSetEnabled(sStartBtn, !running);
    wgtSetEnabled(sLimit, !running);
    wgtSetEnabled(sCancelBtn, running);
}

11.3.1. Starting the Work on a Task

Start calls startCount:

// A count to the spinner's limit, on a task of the program's own.
// shellAppTaskStart makes the task at TS_PRIORITY_NORMAL and returns its
// ID at once; countPrimes starts at the shell's next yield.
static void startCount(void) {
    sCountTo   = (uint32_t)wgtSpinnerGetValue(sLimit);
    sStopAsked = false;

    if (shellAppTaskStart(sAc, PRIMES_TASK_NAME, PRIMES_TASK_STACK, countPrimes, NULL) < 0) {
        dvxErrorBox(sAc, PRIMES_TITLE, "The count could not be started.");
        return;
    }

    applyPriority();
    setRunning(true);
    wgtProgressBarSetValue(sBar, 0);
    wgtSetText(sStatus, "Counting...");
}

shellAppTaskStart(ctx, name, stackSize, fn, arg) makes a task that belongs to the running program and runs fn(arg) on it. It returns the task’s ID at once; the task starts at the shell’s next yield, and ends when fn returns. While it runs, the task is part of the program: it runs with the program as the running program, so its allocations and windows are the program’s; the program is not ended while it runs, even with no window left; a fault in it ends the program, as a fault in a callback would; and End Task ends it with the program. A program has one such task at a time: the call returns -1 while one runs, as it does when no task can be made. stackSize 0 means the default, TS_DEFAULT_STACK_SIZE (32 KB); the task starts at TS_PRIORITY_NORMAL whatever the descriptor says, since the descriptor’s priority is only for a main-loop program’s task.

11.3.2. The Loop and the Yield

The task’s function is the whole count:

// The task's whole life.  It runs on its own stack, as the program, and
// keeps the processor until it yields: every PRIMES_SLICE_US it shows its
// progress and calls tsYield, and the shell, the other programs, and its
// own window's callbacks run before it gets its next turn.  Cancel and
// the close gadget set sStopAsked, which the loop sees after the yield.
static void countPrimes(void *arg) {
    uint32_t limit = sCountTo;
    uint32_t found = 0;
    uint32_t n     = PRIMES_FIRST_PRIME;
    uint64_t start = platformMicros();
    uint64_t slice = start;

    (void)arg;

    for (; n <= limit && !sStopAsked; n++) {
        found += isPrime(n) ? 1 : 0;

        if (n % PRIMES_CHECK_EVERY == 0 && platformMicros() - slice >= PRIMES_SLICE_US) {
            showProgress(n, found);
            tsYield();
            slice = platformMicros();
        }
    }

    finishCount(n > limit, found, platformMicros() - start);
}
// Trial division by the odd numbers up to the square root: slow on
// purpose.  d <= n / d is d * d <= n without the overflow.
static bool isPrime(uint32_t n) {
    if (n % PRIMES_ODD_STEP == 0) {
        return n == PRIMES_FIRST_PRIME;
    }

    for (uint32_t d = PRIMES_FIRST_ODD; d <= n / d; d += PRIMES_ODD_STEP) {
        if (n % d == 0) {
            return false;
        }
    }

    return n >= PRIMES_FIRST_ODD;
}

The task has the processor until it calls tsYield. So the loop yields once it has run for PRIMES_SLICE_US (20 ms): the shell then runs a frame, which reads the mouse and the keyboard, runs the callbacks (Cancel's among them), and paints, and the other tasks get their turns. The slice is the trade-off: shorter keeps the screen smoother, longer gives the count more of the machine. The loop looks at the clock only every PRIMES_CHECK_EVERY numbers, since platformMicros costs I/O on a 486.

Before each yield the task shows its progress. Changing widgets from the task is safe: tasks switch only at a yield, so while the task runs no other code does, and it never finds a widget half changed. Neither call paints at once; each marks what changed, and the shell’s next frame, which comes as soon as the task yields, paints it:

// Runs on the count's task, between slices.  Neither call repaints
// anything at once: they mark what changed, and the shell paints it in
// its next frame, which comes as soon as the task yields.
static void showProgress(uint32_t n, uint32_t found) {
    char text[PRIMES_TEXT_MAX];

    snprintf(text, sizeof(text), "%" PRIu32 " primes so far, at %" PRIu32 ".", found, n);
    wgtSetText(sStatus, text);
    wgtProgressBarSetValue(sBar, (int32_t)((uint64_t)n * PRIMES_PERCENT_FULL / sCountTo));
}

Canceling is a flag. The buttons' callbacks and the close gadget’s run on the shell’s task, while the count waits in tsYield; they set sStopAsked, and the loop sees it when it gets its next turn:

// The buttons and the close gadget run on the shell's task, while the
// count waits in tsYield.  They only ask it to stop.
static void onCancelClick(WidgetT *w) {
    (void)w;
    sStopAsked = true;
}


// Closing while counting: the window goes at once, and the count ends at
// its next turn without touching a widget (finishCount sees sWin NULL).
// The shell ends the program when its task has ended and no window is
// left.
static void onClose(WindowT *win) {
    sStopAsked = true;
    dvxDestroyWindow(sAc, win);
    sWin = NULL;
}


static void onLowPriChange(WidgetT *w) {
    (void)w;
    applyPriority();
}

Closing the window while the count runs destroys the window, widgets and all, as soon as the callback has returned. That is safe because the task looks at sStopAsked before it touches anything after its yield: it leaves the loop, and finishCount sees sWin gone and touches nothing. The shell ends the program once the task has ended and no window is left. Exit DVX closes the window the same way, and End Task ends the task where it waits, in tsYield, which is safe for the same reason as everything else here: the task is never in the middle of anything when another task runs.

// The count ended: finished, or stopped by Cancel or by the close gadget.
// When the window is gone (sWin NULL) its widgets are too, and the task
// only ends; the shell then ends the program.
static void finishCount(bool finished, uint32_t found, uint64_t micros) {
    char text[PRIMES_TEXT_MAX];

    sRunning = false;

    if (!sWin) {
        return;
    }

    if (finished) {
        snprintf(text, sizeof(text), "%" PRIu32 " primes up to %" PRIu32 ", in %" PRIu32 " seconds.", found, sCountTo, (uint32_t)(micros / PLATFORM_US_PER_SEC));
        wgtProgressBarSetValue(sBar, PRIMES_PERCENT_FULL);
    } else {
        snprintf(text, sizeof(text), "Canceled after %" PRIu32 " primes.", found);
    }

    wgtSetText(sStatus, text);
    setRunning(false);
}

11.3.3. Priority

Low priority changes how many turns the count gets:

// The count's share of turns.  shellAppSetPriority changes the program's
// own task, which for a callback-only program is the shellAppTaskStart
// task while it runs; with none running it does nothing and returns
// false, and startCount applies the box again.
static void applyPriority(void) {
    shellAppSetPriority(sCtx->appId, wgtCheckboxIsChecked(sLowPri) ? TS_PRIORITY_LOW : TS_PRIORITY_NORMAL);
}

shellAppSetPriority(appId, priority) sets the priority of a program’s own task: a main-loop program’s task, or a callback-only program’s shellAppTaskStart task while it runs. It returns false when the program has none, so the check box can be changed at any time, and startCount applies it to each new task. shellAppGetPriority(appId) reads it (SHELL_NO_PRIORITY for none). At TS_PRIORITY_LOW the count gets one turn in a round where the shell’s task gets eleven, so it slows down and the screen and the other programs get more of the machine; at TS_PRIORITY_NORMAL it gets six (Section 11.4).

11.4. Tasks and Their Scheduler

Tasks come from libtasks (taskSwch.h): each is a stack and a saved set of registers, and one runs at a time until it calls tsYield (Section 3.5). The scheduler gives each ready task priority + 1 turns, called credits, per round and goes round the tasks in order; when no ready task has a credit left, every one gets its credits again. A higher priority means more turns, never all of them:

Priority Turns a round Used by

TS_PRIORITY_LOW (0)

1

Work that should give way.

TS_PRIORITY_NORMAL (5)

6

Programs' tasks, by default.

TS_PRIORITY_HIGH (10)

11

The shell’s own task.

Any value from 0 to 10 is allowed. A turn lasts until the task yields, however long that is, so a task’s share of the processor depends on how long its turns are as much as on how many it gets. The shell’s turns are short, about one frame each.

A task’s own calls are tsYield, tsCurrentId() (the running task’s ID; the shell’s task is TS_MAIN_TASK_ID, 0), tsGetPriority(id) and tsSetPriority(id, priority) (TS_OK, or a negative TS_ERR_* code), and tsGetName(id). A main-loop program can change its own priority from its loop with tsSetPriority(tsCurrentId(), priority), or from anywhere with shellAppSetPriority (in a callback, tsCurrentId() is the shell’s task). tsPause, tsResume, tsKill, and tsExit are the shell’s: a program’s task ends by returning from its function.

A task a program makes with tsCreate belongs to that program: it runs as the program that made it, so what it allocates and the windows it opens are the program’s, and the shell kills it when the program ends, however it ends. But it is not the program’s work in the shell’s eyes: it does not keep a callback-only program running. hasMainLoop and shellAppTaskStart make the tasks the shell manages; use them.

11.4.1. Stacks

A task’s stack is a block from malloc, counted to the program, of the size the program asks for: the descriptor’s stackSize for a main-loop program (SHELL_STACK_DEFAULT, 0, for the default), or the stackSize argument of shellAppTaskStart. The default is TS_DEFAULT_STACK_SIZE (32 KB), and a smaller request than TS_MIN_STACK_SIZE (4 KB) gets that. Nothing guards the end of the stack: a task that uses more than it has writes over whatever memory lies below the block, without a fault, and the damage shows up later and elsewhere. Keep large arrays out of a task’s local variables (make them static, or allocate them), and ask for a larger stack for deep recursion. A program’s callbacks do not run on its task’s stack: they run on the shell’s, whatever kind the program is.

11.5. The Command Line

A program’s command line is in DxeAppContextT.args when appMain runs: the text after the program’s name, "" when there is none, at most SHELL_ARGS_MAX - 1 (1,023) characters. Where it comes from:

  • The Run dialog (Program Manager’s File › Run…​ and the Task Manager’s Run…​) and shellRunCommand: what the user typed after the program.

  • A Program Manager item’s arguments. An argument that names a file in the item’s working folder arrives joined to that folder’s path (shellResolveArgs), since every program shares the DVX folder as its current folder.

  • A document opened through its file type: the document’s path, or what the association’s template makes of it (Section 10.7).

  • DVX /RUN=program arguments at the DOS prompt, and another program’s shellRunProgram or shellLoadAppWithArgs (Section 11.6).

  • The shell itself: a screen saver gets /S, and the help viewer file topic from F1.

Arguments are separated by blanks, and one with blanks in it is in double quotes: a long file name such as "C:\MY DOCS\LETTER.TXT". dvxNextArg(p, out, outSize, &quoted) copies the next argument of p into out without its quotes, sets quoted when it had them, and returns the text after it, or NULL when nothing but blanks is left. The shell splits command lines with it, and DVX’s own programs read theirs with it (DVX BASIC’s COMMAND$ too), so they all agree on what an argument is. Primes takes the first argument as its limit:

// The first argument of a command line as a limit, when it is a number
// from PRIMES_LIMIT_MIN to PRIMES_LIMIT_MAX.  dvxNextArg takes one
// argument at a time, quoted or not, the way every DVX program reads its
// command line.
static bool limitFromArgs(const char *args, uint32_t *limit) {
    char  arg[PRIMES_ARG_MAX];
    char *end    = NULL;
    bool  quoted = false;

    if (!dvxNextArg(args, arg, sizeof(arg), &quoted)) {
        return false;
    }

    uint32_t value = (uint32_t)strtoul(arg, &end, PRIMES_RADIX);

    if (end == arg || *end != '\0' || value < PRIMES_LIMIT_MIN || value > PRIMES_LIMIT_MAX) {
        return false;
    }

    *limit = value;
    return true;
}

To walk every argument, loop until dvxNextArg returns NULL:

const char *p      = ctx->args;
bool        quoted = false;
char        arg[DVX_MAX_PATH];

while ((p = dvxNextArg(p, arg, sizeof(arg), &quoted)) != NULL) {
    dvxLog("argument: %s", arg);
}

The other way, dvxArgAppend(buf, bufSize, pos, arg) appends one argument to a command line being built, in quotes when it has blanks, and returns the new length, or -1 when it does not fit (and -1 passed back in as pos stays -1, so a chain of appends needs one check at the end).

11.5.1. Acting on the Command Line at Start

Primes counts at once when its command line gives a limit. shellAppTaskStart works in appMain, so appMain sets the spinner and starts the count itself, after the window is built; the task runs from the shell’s next yield, once appMain has returned:

// A limit on the command line starts a count at once: the task is made
// now, and runs from the shell's next yield, after appMain returns.
if (limitFromArgs(ctx->args, &limit)) {
    wgtSpinnerSetValue(sLimit, (int32_t)limit);
    startCount();
}

Run it from Program Manager’s File › Run…​ with APPS\LOCAL\PRIMES\PRIMES.APP 5000000, or start DVX with DVX /RUN=APPS\LOCAL\PRIMES\PRIMES.APP 5000000.

11.5.2. One Copy or Several

The descriptor’s multiInstance decides what a second start does. With false, as in Primes, the program runs once; a second start finds it running and, unless the program takes new arguments, says so, naming the program’s file (“PRIMES.APP is already running.”). A program takes them by setting onNewArgs, with newArgsCtx for its own use, in DxeAppContextT in appMain. A second start then calls onNewArgs(newArgsCtx, args) with the new command line ("" when it has none), and raises the program’s window; the starter gets the running program’s ID. The callback runs as the program, inside the call that made the second start. Primes counts to the new limit unless it is still counting:

// Primes runs once (multiInstance false).  Started again, from the Run
// dialog or a Program Manager item, it is handed the new command line
// here, and the shell raises its window, instead of the shell saying that
// it is already running.
static void onNewArgs(void *ctx, const char *args) {
    uint32_t limit = 0;

    (void)ctx;

    if (!limitFromArgs(args, &limit)) {
        return;
    }

    if (sRunning) {
        wgtSetText(sStatus, "Still counting: Cancel the count first.");
        return;
    }

    wgtSpinnerSetValue(sLimit, (int32_t)limit);
    startCount();
}

With multiInstance true, every start after the first loads a copy of its own: the shell copies the .app file to a scratch file in the TEMP folder (in the user folder when there is no TEMP), loads that, and deletes it when the copy ends. Each copy has its own static data, its own windows, and its own ID, and the shell does not call onNewArgs for a second start. (DVX’s help viewer is the exception: it allows several copies, yet F1 and shellOpenHelpFile hand the one already open its new arguments through onNewArgs.) All the copies have the same appPath (the real file’s), so they read the same resources, and the same userDir, so they share their settings files (Section 10.3.1). When there is nowhere to put a copy (no TEMP and a user folder that cannot be written), the program runs once.

11.6. Starting Other Programs

shellRunProgram(ctx, program, args, folder) (shellRun.h) starts another program the way Program Manager does:

  • A .app file is loaded and started with args. folder, when it is not NULL, is the working folder an item would have: arguments that name files in it are joined to its path.

  • A DOS program, an .EXE, .COM, or .BAT file (shellIsDosProgram), is set to run with DVX stepped aside (Section 11.7).

  • Anything else is a document, opened in the program its file type is associated with (Section 10.7).

It shows the user what went wrong, a missing file, a document type with no program, a program that would not load, and returns the new program’s ID, SHELL_RUN_DOS (0) for a DOS program set to run, or -1. Paths are relative to the DVX folder, or absolute:

int32_t id = shellRunProgram(ac, "APPS\\KPUNCH\\NOTEPAD\\NOTEPAD.APP", "C:\\AUTOEXEC.BAT", NULL);

shellRunCommand(ctx, command) takes a whole command line, the program first (in quotes when it has blanks), and runs it with shellRunProgram. shellLoadAppWithArgs(ctx, path, args) is the step underneath for a .app alone: no documents, no DOS programs, no working folder. shellRunDialog shows the standard Run dialog over a history you keep, and gives back the command the user chose for you to run.

A callback-only program’s appMain runs inside the call that starts it, so by the time shellRunProgram returns, its window is up; a main-loop program’s starts at the next yield. Either way the new program is on its own from then on. A single-copy program that is running already is handed the arguments, as above, or refuses.

To keep track of a program you started, keep its ID. shellGetRunningApp(id) returns its ShellAppT (with name and path) while it runs, and NULL once it has ended; test it from a Timer to know when the user has finished with it. IDs are reused, so check that path is still the program’s. shellRunningAppCount() and shellRunningAppId(index) walk every running program, and shellAppFindByPath(path) finds one by its file. shellActivateApp(ctx, id) brings a program’s window to the front, as the Task Manager’s Switch To does; shellMinimizeApp(ctx, id) minimizes the windows it opens as it starts (Program Manager’s Run Minimized). shellRequestAppClose(id) asks a program to close the way Exit DVX asks, its save questions and all, and shellEndTask(ctx, id) ends it at once, as End Task does. Use the last one only for what End Task is for: a program that has stopped responding.

11.7. Running DOS Programs

DVX can run a DOS program, but not beside its own programs: the DOS program needs the screen, the keyboard, and memory, and DVX steps aside while it runs. shellRunDos(program, args, folder, pause) asks for that. It only records the request; the shell carries it out from its main loop, where it is safe to close programs:

  1. If programs other than Program Manager (the desktop) are running, a question names them, and each is asked to close as Exit DVX would ask it, with its own question about unsaved work. That includes the program that asked. A No, or a program that keeps its window, cancels the run.

  2. DVX is normally started by DVX.COM, a small real-mode program that starts DVX.EXE. Then DVX leaves memory altogether: it writes a batch file that runs the program and exits, DVX.COM runs the batch file with almost all of DOS’s memory free, and starts DVX again when the program ends. That start of DVX comes back to the desktop without its start-up sound, its Welcome window, or Program Manager’s Startup group.

  3. When DVX.EXE was started by itself, the program runs with DVX still in memory, which leaves it less.

program is a path, or a bare name the command interpreter finds on the PATH; folder is where it runs (NULL for the program’s own folder, or the current one for a bare name). With pause true, “Press any key to return to DVX.” waits once the program ends, so what it printed can be read.

A program that wants the DOS program’s result runs it with shellRunDosFor(appId, program, args, folder, pause) instead: the program that asks (appId, its own ctx->appId) is not asked to close, and DVX stays in memory for the run. shellRunDosDone(appId, &rc) turns true once the run is over, with the DOS program’s exit code in rc, or -1 when it did not run (the user kept the other programs, or it could not be started). The run happens in the shell’s main loop, after your callback has returned, so ask from a Timer or from a main loop, never by waiting in the callback that asked:

// In a main-loop program
int32_t rc = -1;

shellRunDosFor(ctx->appId, "C:\\UTIL\\PKZIP.EXE", "-a BACKUP.ZIP *.TXT", ctx->userDir, false);

while (!shellRunDosDone(ctx->appId, &rc)) {
    tsYield();
}

Under both is dvxRunDos(ctx, program, args, folder, pause) (dvxApp.h), which runs the program at once, with DVX in memory, and returns its exit code, or -1 with errno (ENOENT, ENOMEM, or E2BIG for a command line longer than DOS takes). It asks no program anything, and nothing of DVX runs while the DOS program does: not the other programs, not their connections or their sound. Prefer the shell’s calls.

Two DOS limits apply. A command tail, what follows the program’s name, holds at most 126 characters (DVX_DOS_TAIL_MAX). And a DOS program may know only 8.3 names: give it a file’s short name, platformShortPath(path, out, size), as shellRunProgram does for a document it opens in a DOS program. A library that drives hardware itself lets go of it while a DOS program runs through a suspend hook (platformSuspendHookAdd; Chapter 18).

11.8. Screen Savers

A screen saver is an ordinary program kept in a SAVERS folder instead of APPS: SHARED\SAVERS for those DVX and add-on packages install, or the user’s own USER\SAVERS. Program Manager does not list it. The user chooses one, and the wait, on Control Panel’s Desktop page (DVX.INI [desktop] saver and saverWait, from 1 to 60 minutes, 10 when unset). When no key or mouse input has come for the wait (dvxIdleMs), the shell starts the saver with the argument /S (SHELL_SAVER_ARGS), unless a dialog box is open or a program has the whole screen.

A saver in C is a main-loop program that opens a window, takes the whole screen with dvxExclusiveBegin (Chapter 17), and draws frames, paced with the game library’s gameFrameWait, until its window’s onClose sets a flag; then it destroys the window and returns from appMain. It needs no input handling: at the first key or mouse input after its first second (SHELL_SAVER_GRACE_MS), the shell asks its windows to close, and that input goes to the saver, never to the program underneath. A saver still running three seconds later (SHELL_SAVER_END_MS) is ended. The name Control Panel lists is the program’s name resource. DVX’s source tree has one, src/savers/kpunch/starfld.

make install puts a program in APPS, where a saver is not found. Copy the built .app into the user folder’s SAVERS folder instead (USER\SAVERS in the DVX folder unless DVXUSER names another user folder; make it if it is not there), then choose it on Control Panel’s Desktop page, where Test starts it at once.

11.9. The Task Manager

Ctrl+Esc opens the Task Manager from anywhere, even when Program Manager is not running, and over a dialog box, modal over it (Section 7.2); shellOpenTaskManager(ctx) opens it from code. It lists every running program in six columns:

Column Shows

Name

The descriptor’s name.

Title

The title of one of the program’s visible windows.

File

The .app file’s name.

Type

Task for a program with a task of its own: a main-loop program, or a callback-only one while its shellAppTaskStart task runs, as Primes’s does while it counts. Callback for one that runs only in callbacks.

Memory

What the program has allocated and not freed (Section 3.9), its task’s stack included.

Status

Running, or Not responding: the program has been inside one of its window callbacks for DVX_HUNG_APP_MS (5 seconds) without a dialog box of its own open.

The Memory, Type, and Status columns are checked again every second while the Task Manager is open.

Switch To (or a double click) brings the program’s window to the front. End Task ends the program at once (shellEndTask): its windows are destroyed, its tasks are killed where they wait, and its unsaved work is lost. Then its appShutdown runs, unless the program faulted or is not responding. A program that is not responding, stuck in a callback that runs frames itself, has that callback abandoned at its next frame, as a fault would abandon it, and goes without its appShutdown. Ending Program Manager is exiting DVX, so for it End Task asks first. Run…​ is the Run dialog. The status bar shows how many programs are running and the machine’s memory in use.

What the Task Manager can do for a program depends on the program yielding. A main-loop program that never yields, or a callback that loops without returning and without running frames, stops all of DVX, and with it the Task Manager: there is nothing left running to open it with (Section 3.5). A program that yields can always be ended, which is one more reason to keep turns and callbacks short.

Chapter 12. Printing

DVX prints through one library, PRINT.LIB, which every program shares: Notepad, Image Viewer, Icon Editor, the Control Panel’s Printer page, and DVX BASIC’s LPRINT and Printer object all go through it. It prints the way DOS programs did, with no spooler and no printer drivers to install: it sends bytes to a parallel port, to a serial port, or into a file, while DVX keeps running. Plain text goes to any printer; pictures and drawn pages go to Epson, HP, PostScript, and Apple printers as dot graphics. Its header is print.h, which sdk.mk puts on the include path, and the library is part of DVX itself, loaded when the first program that uses it starts.

The library comes in layers, and a program uses as few of them as it needs:

Layer Calls For

Settings

printSettingsLoad, PrintSettingsT

The printer the user chose, which every program shares

Ready-made printing

printUiText, printUiImageFile, printUiWindow, printUiDocOpen

Printing with DVX’s dialogs, messages, and Printing window, in a call or two

Dialogs

printDialog, printPageSetupDialog

Asking where to print, how many copies, which pages; the page layout of text

Jobs

printJobOpen, printJobWrite, printJobClose, PrintHooksT

Bytes to a port or a file, with your own handling of printer problems

Text

printTextJob, PrintPageSetupT, PrintTextInfoT

Plain text laid out on pages, with headers, footers, and page numbers

Documents

printDocOpen, printDocPage, printDocPicture, printFontOpen, printVec*

Pages of pictures, drawings, and type on printers that print graphics

This chapter builds a program that uses all of them, then explains each. The reference lists every function (“Printing Library” in the DVX C Library Reference).

12.1. The PrintIt Program

The example printit opens a text file, shows it in a read-only text area, and prints it three ways from its File menu:

  • Print prints the text the way Notepad does, with one call: the Print dialog, the user’s page setup, and DVX’s messages.

  • Print Listing lays the pages out itself, with the file’s name and the date at the top of every page and “Page 3 of 7” at the bottom, and runs the print job itself, with its own Printing window and Cancel button.

  • Print Cover Page draws one page of large type, a band at a time, on a printer that prints graphics.

Page Setup opens DVX’s Page Setup dialog. The three print commands are grayed until a file is open. Build and install printit as you did hello in Chapter 2.

The PrintIt window with its File menu open: Open, the grayed Print, Print Listing, and Print Cover Page, Page Setup, and Exit
Figure 20. PrintIt’s File menu, before a file is open: the print commands are grayed

The program keeps the file in memory, in sText, with its path and its name for the header:

static DxeAppContextT *sCtx       = NULL;
static AppContextT    *sAc        = NULL;
static WindowT        *sWin       = NULL;
static MenuBarT       *sMenuBar   = NULL;
static WidgetT        *sView      = NULL;
static WidgetT        *sStatus    = NULL;
static WindowT        *sProgress  = NULL;
static bool            sCancelled = false;
static char           *sText      = NULL;
static int32_t         sTextLen   = 0;
static const char     *sTitle     = "";
static char            sPath[DVX_MAX_PATH];
// Reads the whole file into memory, where the print commands find it.
// Its lines may end in CR LF or in LF: the text area wants LF alone and
// the print library takes either, so the CRs are dropped.
static void loadFile(const char *path) {
    int32_t len  = 0;
    char   *text = platformReadFile(path, &len);
    int32_t kept = 0;
    char    status[PRINTIT_TEXT_MAX];

    if (!text) {
        dvxErrorBox(sAc, PRINTIT_TITLE, "The file could not be read.");
        return;
    }

    for (int32_t i = 0; i < len; i++) {
        if (text[i] != '\r') {
            text[kept++] = text[i];
        }
    }

    text[kept] = '\0';
    free(sText);
    sText    = text;
    sTextLen = kept;
    snprintf(sPath, sizeof(sPath), "%s", path);
    sTitle = platformPathBaseName(sPath);
    snprintf(status, sizeof(status), "%s: %ld bytes", sPath, (long)sTextLen);
    wgtSetText(sView, sText);
    wgtSetText(sStatus, status);
    enablePrinting(true);
}

platformReadFile returns the whole file from malloc, with a NUL after it, and its length; the program owns the buffer. The print calls take lines that end in LF or in CR LF, and the text area wants LF alone, so the CRs go. The text area shows at most its buffer, the PRINTIT_VIEW_MAX (64 KB) characters printit gives wgtTextArea (with maxLen 0 it would hold only 256); the print commands print sText, all of it.

12.2. The Printer and Its Settings

DVX has one printer, chosen by the user on the Control Panel’s Printer page and kept in the [printer] section of the user’s DVX.INI. A program does not ask the user which printer model they have; it reads the settings when it prints:

PrintSettingsT settings;

printSettingsLoad(&settings);   // DVX.INI [printer], defaults for what is missing
Member Holds

dest

Where output goes, a PrintDestE: PrintDestLpt1E to PrintDestLpt3E, PrintDestCom1E to PrintDestCom4E, or PrintDestFileE

model

The printer model, a PrintModelE (below)

filePath

The file printed into when dest is PrintDestFileE

page

The page setup for text, a PrintPageSetupT (Section 12.4)

baud, handshake

A serial printer’s speed and how it says it is busy (PrintHandshakeE: none, XON / XOFF, or a hardware line)

Anything missing from DVX.INI takes its default (printSettingsDefaults): LPT1, the text-only model, the file PRINTER.PRN, 9600 baud, and the default page setup. A page setup that does not pass printPageSetupProblem is replaced by the default one as a whole.

The destinations behave as follows:

  • LPT1 to LPT3, the parallel ports, through the BIOS printer service (INT 17h). The library sends a byte only when the port’s status says the printer is ready, so the BIOS never sits in a busy wait of its own.

  • COM1 to COM4, for serial printers such as the ImageWriter II, through DVX’s serial library: the port opens when the job starts, at the speed and handshake in the settings, 8 data bits, no parity, and 1 stop bit. An interrupt handler sends from a buffer, and closing the job waits until the buffer has drained.

  • File: output goes into a file, created or emptied. A name without a folder, such as the default PRINTER.PRN, is in DVX’s user folder (printFilePath gives the full path), since DVX’s own folder may be on a CD-ROM; any other path is used as it is. Printing to a file is how you test printing without a printer.

The model decides what the library can send. Text prints on every model; pictures need a model with a driver, and the default model has none:

Model Graphics Notes

PrintModelTextE

None

Any printer, text only. The default.

PrintModelEpson9E, PrintModelEpson9ColorE

120 x 72 dpi

Epson ESC/P 9-pin, black or a four-color ribbon

PrintModelEpson24E, PrintModelEpson24ColorE

180 x 180 dpi

Epson ESC/P 24-pin, black or a four-color ribbon

PrintModelLaserJetE

150 dpi

HP LaserJet (PCL)

PrintModelLaserJet300E

300 dpi

HP LaserJet III, DeskJet, and later

PrintModelDeskJet500CE, PrintModelDeskJetColorE

300 dpi

HP DeskJet 500C (cyan, magenta, yellow), 550C and later (with black)

PrintModelPostScriptE, PrintModelPostScriptColorE

300 dpi

PostScript Level 2; can also draw vector pages (Section 12.7.4)

PrintModelImageWriterE, PrintModelImageWriterColorE

144 x 144 dpi

Apple ImageWriter II, black or the color ribbon

printModelChoices, printDestChoices, and printHandshakeChoices are tables of the labels the user sees and the spellings in DVX.INI, indexed by the enums; printModelLabel(model) and printDestLabel(dest) return one label.

The PostScript models' driver is a file of its own, DRIVERS\PS.DRV beside the library, which a user may not have. printModelProblem(model) returns NULL when DVX can print on the model, else a sentence for the user saying the driver is missing. Check it before you print on a model yourself: a PostScript printer expects PostScript, which only the driver writes, so without it the printout would come out wrong. The ready-made calls check it for you.

Treat the settings as the user’s. printSettingsSave, printDeviceStore, and printSerialStore write them, but they are for programs whose job is the settings, like the Control Panel; any other program reads them and offers the Page Setup dialog (Section 12.3.2).

12.3. Printing Text in One Call

The Print command of printit, like Notepad’s, is one call in onMenu:

static void onMenu(WindowT *win, int32_t menuId) {
    (void)win;

    switch (menuId) {
        case CMD_FILE_OPEN:
            openFile();
            break;

        case CMD_FILE_PRINT:
            printUiText(sAc, sText, sTitle, true);
            break;

        case CMD_FILE_LISTING:
            printListing();
            break;

        case CMD_FILE_COVER:
            printCover();
            break;

        case CMD_FILE_PAGE_SETUP:
            printPageSetupDialog(sAc);
            break;

        case CMD_FILE_EXIT:
            closeWindow();
            break;

        case CMD_HELP_CONTENTS:
            shellOpenHelpFile(sAc, sCtx->helpFile, NULL);
            break;

        case CMD_HELP_ABOUT:
            dvxInfoBox(sAc, "About " PRINTIT_TITLE, PRINTIT_ABOUT_TEXT);
            break;

        default:
            break;
    }
}

printUiText(ctx, text, title, askFirst) prints text, a C string, on the printer in the settings, with the user’s page setup, and with title as the file name in the page setup’s header and footer (the code &f, Section 12.4). Step by step:

  1. It reads the settings, and when the model’s driver is missing it tells the user and returns false.

  2. With askFirst, it shows the Print dialog (Section 12.3.1), with the number of pages the text takes; Cancel returns false.

  3. It opens a job on the destination chosen, with DVX’s own hooks: a Retry / Cancel box for printer problems, and a modal Printing window with a Cancel button when the printer keeps the program waiting (Section 12.5.1). When the job cannot be opened, it tells the user why (“This computer has no port LPT2.”) and returns false.

  4. It prints the copies and the page range chosen, closes the job, and tells the user “The document could not be printed.” when that failed for any reason but the user’s Cancel.

It returns true when everything was printed. Without askFirst the text goes to the printer in the settings at once, one copy of every page. printUiTextChoice(ctx, text, title, &choice) is the same without the dialog, for a program that fills a PrintChoiceT itself (Section 12.3.1) or kept the user’s last answer; a NULL choice is the printer in the settings, every page, one copy. printUiTextSetup(ctx, text, title, &choice, &page) is printUiTextChoice with a page setup of the program’s own instead of the user’s (NULL for the user’s); a setup that printPageSetupProblem refuses is told to the user and nothing is printed. For output a program formats itself, printUiJobOpen(ctx, title, &choice) opens a job at the choice’s destination, a port or a file (NULL for the settings' printer), with the same messages and Printing window, for printJobWrite or printTextJob and then printJobClose (Section 12.5).

The call returns only when the printing is done. While it waits for the printer, its hooks keep DVX running, so other programs go on and the Printing window takes clicks, but the call itself does not return early: on a slow dot-matrix printer that is minutes.

12.3.1. The Print Dialog

printDialog(ctx, title, pageCount, &choice) shows DVX’s common Print dialog and returns true when the user chose Print, with the answer in choice. title is the window’s title, “Print” when NULL.

The dialog starts from the settings and holds, from the top:

  • Print to: LPT1 to LPT3, COM1 to COM4, or File. File name and its Browse…​ button are enabled only for File; Browse…​ opens a Save dialog titled Print to File, in the folder of the file named.

  • Copies: 1 to PRINT_COPIES_MAX (99).

  • Pages, only when pageCount is above 0: All (n), or These pages from one page to another.

  • The printer model, as a line of text. The model is not chosen here: it is the Control Panel’s.

Print refuses File with no file name and a first page after the last one, with a message, and leaves the dialog up. The choice is for this print only; nothing is saved to DVX.INI.

PrintChoiceT member Holds

dest, filePath

The destination chosen, and the file name for PrintDestFileE

copies

1 or more

firstPage, lastPage

The range, from 1; firstPage 0 means all pages, as it always is when the dialog had no page count

choice is zeroed first, so after Cancel it holds nothing useful.

12.3.2. The Page Setup Dialog

printPageSetupDialog(ctx) shows DVX’s Page Setup dialog, which edits the page setup in the settings: the lines per page (0 for the printer’s usual length), the characters per line, the four margins, the tab width, the header and the footer, and whether long lines wrap or are cut off. OK checks the values with printPageSetupProblem, says what is wrong and stays open when they do not work together, and otherwise saves them to DVX.INI. The call returns true when the user chose OK and the page setup was saved; when it could not be saved, the user is told.

The page setup belongs to every program that prints text, Notepad and BASIC’s LPRINT among them, so printit offers the dialog rather than a page setup of its own.

12.4. Laying Out Text

The library lays out plain text in lines and columns of the printer’s own characters, as DOS programs printed, and it does the same for every model. A PrintPageSetupT describes the page:

Member Meaning

linesPerPage

Lines on a page, 10 to 200, or 0 for the model’s usual length: PRINT_LINES_STANDARD (66, 11 inches at 6 lines an inch), or PRINT_LINES_LASER (60) on the HP and PostScript models

columns

Characters across the page, 20 to 255 (80 by default)

marginTop, marginBottom

Lines above and below the text (3 by default). The header is printed in the middle line of the top margin, the footer in the middle line of the bottom margin; a margin of 0 has neither.

marginLeft, marginRight

Columns left blank at each side (5 by default)

tabWidth

Columns between tab stops, 1 to 16 (8 by default)

wrap

true: a line too long is broken at its last blank before the right margin (a word longer than a line is split); false: it is cut off

header, footer

The header and footer, with the codes below (79 characters at most). The defaults are &f and Page &p.

The header and footer may hold these codes:

Code Becomes

&f

The title (PrintTextInfoT.title): the file name

&p, &n

The page number, and the number of pages

&d, &t

The date (YYYY-MM-DD) and the time (HH:MM), today’s and now unless PrintTextInfoT.date and .time give others

&l, &c, &r

What follows goes at the left, in the center, or at the right; text before any of them is centered

&&

One &

printFormatHeader(fmt, &info, page, pages, width, out, outSize) expands a header for one page, should you want to show it before printing.

The listing’s page is the user’s, with a header and footer of the program’s own and at least a line of margin for each:

// The listing's page: the file name at the left of the header and the
// date and time at its right, "Page n of m" in the middle of the footer.
// A header or footer is printed in the middle line of its margin, so each
// of those margins needs a line at least.
#define PRINTIT_HEADER         "&l&f&r&d &t"
#define PRINTIT_FOOTER         "&cPage &p of &n"
#define PRINTIT_MARGIN_MIN     1
// The listing's page: the user's page setup (lines and characters per
// page, margins, tabs, and wrapping), with PrintIt's own header and
// footer and room for them.  NULL when it can be printed on the printer
// in the settings, else why not.
static const char *pageLayout(PrintSettingsT *settings, PrintPageSetupT *page) {
    printSettingsLoad(settings);
    *page              = settings->page;
    page->marginTop    = DVX_MAX(page->marginTop, PRINTIT_MARGIN_MIN);
    page->marginBottom = DVX_MAX(page->marginBottom, PRINTIT_MARGIN_MIN);
    snprintf(page->header, sizeof(page->header), "%s", PRINTIT_HEADER);
    snprintf(page->footer, sizeof(page->footer), "%s", PRINTIT_FOOTER);

    const char *problem = printPageSetupProblem(page);

    return problem ? problem : printModelProblem(settings->model);
}

printPageSetupProblem(&page) returns NULL when a page setup works, and otherwise a sentence for the user: the values out of their ranges, or margins that leave no line or fewer than 10 columns for the text. It also refuses a header or footer without its terminating zero. Call it on a page setup of your own before printing with it, to tell the user what is wrong: printTextJob refuses a setup it refuses, sending nothing and returning false, and printTextPageCount returns 0 for one. The sentence is in a static buffer, valid until the next call, as is the one printModelProblem returns; pageLayout returns whichever applies.

printTextPageCount(text, len, &page, model) returns the number of pages the text takes, at least 1. The model matters because a usual page is 60 lines on the HP and PostScript printers and 66 on the others; printPageLines(&page, model) returns the lines a page has. The listing passes the count to the Print dialog:

static void printListing(void) {
    PrintSettingsT  settings;
    PrintPageSetupT page;
    PrintChoiceT    choice;
    char            err[PRINT_MSG_MAX];
    const char     *problem = pageLayout(&settings, &page);

    if (problem) {
        dvxErrorBox(sAc, PRINTIT_TITLE, problem);
        return;
    }

    if (!printDialog(sAc, "Print Listing", printTextPageCount(sText, sTextLen, &page, settings.model), &choice)) {
        return;
    }

12.5. Print Jobs

A job is one printout’s way to the printer: printJobOpen opens the destination, and every byte goes through it until printJobClose. The listing opens its own, on the destination the user chose:

PrintHooksT hooks = { .ask = onPrinterProblem, .idle = onPrinterIdle };
PrintJobT  *job   = printJobOpen(choice.dest, choice.filePath, &hooks, err, sizeof(err));

if (!job) {
    dvxErrorBox(sAc, PRINTIT_TITLE, err);
    return;
}

if (!progressOpen()) {
    printJobCancel(job);
    printJobClose(job);
    dvxErrorBox(sAc, PRINTIT_TITLE, "There is not enough memory to print.");
    return;
}

printJobOpen(dest, filePath, &hooks, err, errSize) returns the job, which the caller must close with printJobClose. It returns NULL, with a sentence for the user in err (PRINT_MSG_MAX bytes is enough), when the job cannot start: the port does not exist (“This computer has no port LPT2.”), a serial port cannot be opened (“The port COM1 cannot be opened. Another program may be using it.”), or the file cannot be made (“Cannot create the file …​”). filePath is used only for PrintDestFileE, through printFilePath. hooks may be NULL, and so may any of its members.

If printit cannot make its Printing window, it gives up the job: printJobCancel marks it canceled, so nothing more is sent and printJobClose does not wait for the printer, and printJobClose frees it.

12.5.1. Hooks: Asking and Waiting

A printer is slow, and it can be off, off line, or out of paper. The job never waits for it without calling one of its hooks, and never waits forever:

Hook Called

ask(ctx, message)

For a problem: the printer is out of paper, off line, or reports an error; it has been busy for PRINT_BUSY_TIMEOUT_MS (10 seconds) without taking a byte; it did not answer a byte; a serial printer’s buffer stopped draining; or a write to the file fell short (the disk is full). message says which, for the user (“The printer on LPT1 is out of paper. Load paper, then choose Retry.”). Return PrintAnswerRetryE to try the same byte again, or PrintAnswerCancelE to cancel the job. With no ask, the first problem cancels it. Every problem is also logged to DVX.LOG.

idle(ctx)

While the printer is busy, after every PRINT_YIELD_BYTES (256) bytes sent to a port or 4096 written to a file, and at least every PRINT_POLL_MS (50 ms) of work that sends little (laying out pages, drawing a band). Return false to cancel the job. With no idle, the job calls tsYield.

finished(ctx, closing)

When a write during which idle ran returns (closing is false), and when the job is freed (closing is true). DVX’s own hooks hide their Printing window there.

ctx is the hooks' ctx member, passed back to each. A canceled job sends nothing more: every later write fails at once, and so does printTextJob.

Here are the listing’s two hooks:

// The job's idle hook, called while the printer is busy and between
// pieces of the output: one frame of DVX's event loop keeps the screen,
// the other programs, and the Printing window going.  False cancels the
// job.
static bool onPrinterIdle(void *ctx) {
    (void)ctx;
    return dvxUpdate(sAc) && !sCancelled;
}


// The job's ask hook: the printer is off line, out of paper, or not
// answering, or the disk is full.  message says which, for the user.
static PrintAnswerE onPrinterProblem(void *ctx, const char *message) {
    (void)ctx;

    if (dvxMessageBox(sAc, "Printer", message, MB_RETRYCANCEL | MB_ICONWARNING) == ID_RETRY) {
        return PrintAnswerRetryE;
    }

    return PrintAnswerCancelE;
}

The idle hook is where a program decides what DVX does while it prints. printit prints from a menu callback, which runs on the shell’s task (Section 3.6): the shell’s event loop is under the callback and runs only when something calls dvxUpdate. tsYield, the default, lets other tasks run but not the shell’s loop, so the screen would freeze, and nothing could take a click on Cancel, until the print was done. So the hook runs one frame of the event loop, as a modal dialog box does, and the job’s waits become the dialog’s loop. dvxUpdate returns false when DVX is shutting down, and that cancels the job too. (A program with a main loop that prints from its own task can leave idle NULL: its tsYield lets the shell’s loop run.)

The ask hook shows a message box, which runs the event loop itself until the user answers.

12.5.2. The Printing Window

Running the event loop from inside a callback lets the user reach the program’s own window, and from it the Print command again, in the middle of a print. The listing prevents that with a modal Printing window, made before the job starts and destroyed after it ends:

static void progressClose(void) {
    dvxModalEnd(sAc, sProgress);
    dvxDestroyWindow(sAc, sProgress);
    sProgress = NULL;
}


// The Printing window: modal, so while the job runs inside the Print
// Listing command the user can only watch it or cancel it.
static bool progressOpen(void) {
    char text[PRINTIT_TEXT_MAX];

    snprintf(text, sizeof(text), "Printing %s...", sTitle);
    sCancelled = false;
    sProgress  = dvxCreateWindowCentered(sAc, "Printing", PRINTIT_PROGRESS_W, PRINTIT_PROGRESS_H, false);

    WidgetT *root   = sProgress ? wgtInitWindow(sAc, sProgress) : NULL;
    WidgetT *label  = root ? wgtLabel(root, text) : NULL;
    WidgetT *cancel = label ? wgtButton(root, "&Cancel") : NULL;

    if (!cancel) {
        progressClose();
        return false;
    }

    root->spacing      = wgtPixels(PRINTIT_SPACING);
    cancel->onClick    = onCancelClick;
    sProgress->modal   = true;
    sProgress->onClose = onProgressClose;
    dvxSetWindowButtons(sProgress, NULL, cancel);
    dvxFitWindow(sAc, sProgress);
    dvxModalBegin(sAc, sProgress);
    return true;
}

While it is modal it is the only window in DVX that takes input (Section 4.10). Its Cancel button and its close gadget only set a flag, which the next call of the idle hook returns; the job then stops, and the code that started it closes the window:

static void onCancelClick(WidgetT *w) {
    (void)w;
    sCancelled = true;
}

// The Printing window's close gadget cancels too; the window goes when
// the job has stopped.
static void onProgressClose(WindowT *win) {
    (void)win;
    sCancelled = true;
}

DVX’s own hooks, which printUiText, printUiJobOpen, and the other ready-made calls use, do the same: their Printing window appears at the job’s first wait and goes when the job is closed. Only on a job from printUiOpenPort (Section 12.6) does it wait until a write has waited half a second, and go after each write, so that LPRINT of a line or two never flashes a window.

12.5.3. Printing the Text

With the job open and the window up, one call prints every page, and printJobClose ends the job:

PrintTextInfoT info      = { .title = sTitle, .firstPage = choice.firstPage, .lastPage = choice.lastPage, .copies = choice.copies };
bool           ok        = printTextJob(job, settings.model, sText, sTextLen, &page, &info);
bool           cancelled = printJobCancelled(job);

ok = printJobClose(job) && ok;
progressClose();

if (!ok && !cancelled) {
    dvxErrorBox(sAc, PRINTIT_TITLE, "The listing could not be printed.");
}

dvxLog("printit: listing of %s %s", sPath, ok ? "printed" : "not printed");

printTextJob(job, model, text, len, &page, &info) prints len bytes of text on the pages page describes:

  • Lines end in LF or CR LF, and a form feed in the text starts a new page.

  • Each printed line starts with marginLeft blanks and ends with CR LF; tabs become blanks to the next tab stop; other control characters print as blanks; trailing blanks are dropped.

  • Every page ends with a form feed, which ejects it. A text with no lines still prints one page, with its header and footer.

  • For the Epson, HP, and ImageWriter models the printer’s reset command goes first (on the HP models, and the ImageWriter, last as well), so the printer starts from its own defaults. On a PostScript model the pages are written in PostScript, in Courier sized so that the columns fill 8 inches and the lines 10.

PrintTextInfoT says what this printout is: title for &f; date and time for &d and &t (NULL for today and now); firstPage and lastPage, from 1 (0 for the first or the last); and copies (0 or 1 for one). The pages are counted first, for &n and the range. Copies print one after another, each a complete set.

printTextJob returns false when the job failed or was canceled. printJobClose(job) waits until a serial printer has taken what it holds, closes the port or the file, logs “Print: finished, 5120 bytes to LPT1” (or “stopped after”), frees the job, and returns true when everything was sent. The job is gone after it, so ask printJobCancelled first: a user’s Cancel needs no error message.

12.6. Sending Bytes of Your Own

A job is also a plain byte stream. printJobWrite(job, data, len) sends len bytes and printJobPuts(job, text) a string; each returns once every byte was taken, or false when the job is canceled. Nothing is translated: end lines with CR LF and pages with a form feed, and any escape codes are yours and the printer’s. The quickest job is printUiOpenPort(ctx, port), which opens one with DVX’s hooks (the Retry box, and the Printing window after half a second of waiting) on a printer port: LPT1 to LPT3 (port 0 to 2), COM1 to COM4 (3 to 6), or, with PRINT_PORT_DEFAULT, the destination in the settings, a file included. Any other number, the file destination’s among them, gives NULL; printUiJobOpen opens a file of the program’s choosing. DVX BASIC’s LPRINT is built on it:

PrintJobT *job = printUiOpenPort(ac, PRINT_PORT_DEFAULT);

if (job) {
    printJobPuts(job, "Total: 42\r\n\f");
    printJobClose(job);
}

printUiOpenPort returns NULL when it cannot open the job, and only logs the reason; tell the user yourself.

Below the jobs are the ports. printPortPresent(port) says whether a port exists (0 to 2 are LPT1 to LPT3, 3 to 6 are COM1 to COM4); printPortStatus(port) returns a parallel port’s BIOS status bits (PRINT_STATUS_PAPER_OUT, PRINT_STATUS_SELECTED, PRINT_STATUS_NOT_BUSY, and the rest); and printStatusProblem turns status bits into the sentence the ask hook gets. printJobBytes(job) is the count sent so far. printJobPoll(job) calls the idle hook when 50 ms have passed since it last ran: call it in long work of your own between writes, and stop when it returns false.

12.7. Pictures and Drawn Pages

Pictures, drawings, and type in any font print as dot graphics, on any model but the text-only one. A document is a sequence of such pages on a job. Each page is the whole printable area, 8 inches across and 10 down, and the program draws it in RGB at the printer’s resolution; the library turns the colors into the printer’s inks, dithers them, and sends the printer’s graphics commands.

Two calls print a picture with no drawing at all: printUiImageFile(ctx, path, title, askFirst) prints a BMP, PNG, JPEG, or GIF file, and printUiWindow(ctx, win, askFirst) prints a window’s contents. Each scales the picture to the largest size that fits the page, keeping its shape, prints one page for each copy, and tells the user about any problem, a text-only printer included. They return true when the page printed.

printModelPage(model, &info) returns false for a model that prints only text and otherwise fills a PrintPageInfoT (info may be NULL to ask only that):

Member Holds

dpiX, dpiY

Dots per inch across and down; they differ on the 9-pin Epsons (120 by 72)

widthDots, heightDots

The printable area in dots: 8 by 10 inches

color

true when the printer prints in color, else in black (from the brightness)

vector

true on a PostScript printer, which can draw a page itself (Section 12.7.4)

12.7.1. The Cover Page

The cover page shows the steps of a document:

// One cover page on the printer in the settings.  printUiDocOpen tells
// the user why when it cannot open one (a printer that prints text only,
// say), and shows the Printing window until printUiDocClose.
static void printCover(void) {
    CoverT         cover;
    PrintPageInfoT page;
    PrintDocT     *doc = printUiDocOpen(sAc, sTitle, NULL);

    if (!doc) {
        return;
    }

    memset(&cover, 0, sizeof(cover));
    printDocInfo(doc, &page);

    if (coverOpen(&cover, &page)) {
        printDocPage(doc, drawCoverBand, &cover);
    } else {
        dvxErrorBox(sAc, PRINTIT_TITLE, "There is not enough memory for the cover page's type.");
        printDocCancel(doc);
    }

    coverClose(&cover);
    printUiDocClose(sAc, doc);
}

printUiDocOpen(ctx, title, choice) opens a document on the printer in the settings, at the destination of choice, a Print dialog’s answer, or of the settings when choice is NULL. Before it opens anything it tells the user, and returns NULL, when the model’s driver is missing or the model prints text only (“The printer model chosen in the Control Panel prints text only. …​”), and when the job cannot be opened. Its job has DVX’s hooks, and the Printing window shows from the first wait to printUiDocClose. The copies are yours: print each page as many times as you want copies. printDocInfo(doc, &info) gives the document’s PrintPageInfoT.

printUiDocClose(ctx, doc) ends the document and closes its job, telling the user when it failed for any reason but a Cancel, and returns true when every page printed. printDocCancel(doc) cancels the document’s job, as printJobCancel does a job: printit uses it when it cannot open its fonts, so that nothing more is sent and closing it brings no message. printDocCancelled(doc) tells whether the job was canceled, by the program, by the user’s Cancel, or by the Retry box’s.

Without DVX’s hooks, the same is printDocOpen(job, model) on a job of your own: it takes the job over, so printDocClose(doc) closes it, and it closes the job itself and returns NULL for a text-only model or when memory runs out.

12.7.2. Drawing a Page in Bands

A page at 300 dpi is 2400 by 3000 dots, over 21 million bytes in RGB, so the library never asks for it whole. printDocPage(doc, fn, ctx) calls the page’s band function, a PrintBandFnT, again and again, top down, for a few rows at a time:

// The page's band function: rows y0 .. y0 + rows - 1 of the page, width
// dots across, three bytes (red, green, blue) a dot, white when it is
// called.  Everything is drawn in every band; what falls outside the band
// is skipped.
static bool drawCoverBand(void *ctx, uint8_t *rgb, int32_t width, int32_t y0, int32_t rows) {
    const CoverT *cover  = (const CoverT *)ctx;
    int32_t       top    = DVX_MAX(cover->ruleY, y0);
    int32_t       bottom = DVX_MIN(cover->ruleY + cover->ruleH, y0 + rows);

    printFontDraw(cover->titleFont, cover->titleX, cover->titleY, sTitle, cover->titleLen, PRINTIT_INK, rgb, width, y0, rows);
    printFontDraw(cover->noteFont, cover->noteX, cover->noteY, sPath, cover->noteLen, PRINTIT_INK, rgb, width, y0, rows);

    // The rule's rows in this band, black: all three bytes 0
    for (int32_t y = top; y < bottom; y++) {
        memset(rgb + ((y - y0) * width + cover->ruleX) * PRINTIT_RGB_BYTES, 0, (size_t)cover->ruleW * PRINTIT_RGB_BYTES);
    }

    return true;
}

Each call fills rows y0 to y0 + rows - 1 of the page into rgb: width dots across (the page’s widthDots), three bytes a dot, red first, rows width * 3 bytes apart. The band comes white, so the function draws only what is not white. Return false to stop the page, which then fails. Between calls the library dithers the rows, sends them, and calls the job’s idle hook, so the program’s band function is called many times per page and knows nothing about which call is the last.

So the band function must be able to draw any part of the page on any call. The usual way is a description of the page, worked out once before printDocPage, which every call draws all of, each piece clipped to the band:

// The cover page: the file's name in 36-point bold a third of the way
// down, a rule under it an inch in from each side and 1/36 inch (two
// points) thick, and the file's path under that in 12-point type.  Type
// sizes are in decipoints (tenths of a point), colors are 0xRRGGBB.
#define PRINTIT_COVER_FAMILY   "DejaVu Sans"
#define PRINTIT_TITLE_SIZE     360
#define PRINTIT_NOTE_SIZE      120
#define PRINTIT_TITLE_DOWN     3
#define PRINTIT_RULE_INSET     1
#define PRINTIT_RULE_PER_INCH  36
#define PRINTIT_INK            0x000000
#define PRINTIT_RGB_BYTES      3
// What the cover page's band function needs, worked out once per page:
// positions are in the printer's dots from the top left of the printable
// area.
typedef struct {
    PrintFontT *titleFont;
    PrintFontT *noteFont;
    int32_t     titleLen;
    int32_t     titleX;
    int32_t     titleY;
    int32_t     noteLen;
    int32_t     noteX;
    int32_t     noteY;
    int32_t     ruleX;
    int32_t     ruleY;
    int32_t     ruleW;
    int32_t     ruleH;
} CoverT;
// The cover's fonts and where everything goes on docPage, the page of the
// printer in the settings.  False when a font could not be opened.
static bool coverOpen(CoverT *cover, const PrintPageInfoT *docPage) {
    PrintPageInfoT page = *docPage;

    // DVX's own letters, drawn into the bands.  On a PostScript printer
    // (vector set) the fonts would be the printer's own, which only
    // printVecText draws.
    page.vector      = false;
    cover->titleFont = printFontOpen(&page, PRINTIT_COVER_FAMILY, PRINTIT_TITLE_SIZE, FONT_STYLE_BOLD);
    cover->noteFont  = printFontOpen(&page, PRINTIT_COVER_FAMILY, PRINTIT_NOTE_SIZE, FONT_STYLE_REGULAR);

    if (!cover->titleFont || !cover->noteFont) {
        return false;
    }

    cover->titleLen = (int32_t)strlen(sTitle);
    cover->titleX   = (page.widthDots - printFontWidth(cover->titleFont, sTitle, cover->titleLen)) / 2;
    cover->titleY   = page.heightDots / PRINTIT_TITLE_DOWN;
    cover->ruleX    = page.dpiX * PRINTIT_RULE_INSET;
    cover->ruleW    = page.widthDots - cover->ruleX - cover->ruleX;
    cover->ruleY    = cover->titleY + printFontHeight(cover->titleFont);
    cover->ruleH    = page.dpiY / PRINTIT_RULE_PER_INCH;
    cover->noteLen  = (int32_t)strlen(sPath);
    cover->noteX    = cover->ruleX;
    cover->noteY    = cover->ruleY + cover->ruleH + printFontHeight(cover->noteFont);
    return true;
}

Positions are in dots, worked out from dpiX and dpiY rather than assumed, since the printers differ: the rule an inch in from each side is 120 dots in on a 9-pin Epson and 300 on a LaserJet III. printDocPage returns false when the band function did, the job failed or was canceled, or memory ran out; after a failure every later page of the document fails at once.

A picture you have in memory is a page with one call: printDocPicture(doc, rgb, w, h, pitch) prints w by h pixels of RGB, rows pitch bytes apart, scaled to the largest size that fits the page and keeping its shape.

The library dithers each band to the printer’s inks with an ordered pattern: 4 by 4 on the dot-matrix printers and the 150 dpi LaserJet, 8 by 8 at 300 dpi. A black-only printer prints the brightness; a color printer prints cyan, magenta, and yellow from the red, green, and blue, and, with black ink as well, black for what the three have in common. Draw in colors and leave the printer’s limits to the library.

12.7.3. Type on a Page

A page can carry type in any font family DVX has (Chapter 9), at any size:

  • printFontOpen(&page, family, decipoints, style) opens family (NULL or "" for the system font) at a size in decipoints, tenths of a point (120 is 12 points), in a style of FONT_STYLE_* bits, underline and strike-through included, for the resolution of page. It returns NULL when memory runs out or the size is 0 or less. printFontClose gives it up and accepts NULL.

  • printFontWidth(font, text, len) is the width of len characters in dots; printFontHeight(font) the distance from one line to the next, and printFontAscent(font) from the top of a line to its baseline.

  • printFontDraw(font, x, y, text, len, color, rgb, width, y0, rows) draws text, with the top of its line at x, y on the page, into the band a band function is filling, in color (0xRRGGBB), skipping what is outside the band. printFontSpans gives the same text as runs of dots to a function of yours, for painting them some other way.

The type is made from DVX’s own fonts, which hold the faces at fixed pixel sizes. The library picks the family’s smallest size at least as tall as the type in dots, else its largest, and scales it to the size, across and down apart. The DejaVu families of DVX’s base font set, when the user installed it, carry sizes made for printing, up to 100 pixels (24 points at 300 dpi, 40 at 180), so they print crisp; other families, and larger type, are scaled up and smoothed. A family that is not installed prints in the system font, scaled up.

One rule matters on PostScript printers. When page.vector is set, printFontOpen gives the printer’s own Helvetica, Times, or Courier instead, which measures as the printer prints it and draws only on a vector page: printFontDraw draws nothing with it. That is why coverOpen clears vector in its copy of the page. For DVX’s letters in bands, clear it; for the printer’s own, draw a vector page.

12.7.4. Vector Pages on PostScript Printers

A PostScript printer can draw a page itself, from lines, shapes, and its own type, sharper at any size and much smaller to send than dots. When PrintPageInfoT.vector is set, printVecBegin(doc) starts such a page and printVecEnd(doc) prints it; between them, each drawing call goes to the printer as it is made. Coordinates are the page’s dots (y down), colors 0xRRGGBB (gray on the black-only model), widths in dots:

Call Draws

printVecLine(doc, x0, y0, x1, y1, color, width, dash)

A line; dash is a 16-step pattern from its top bit, 0xFFFF for solid

printVecRect(doc, x0, y0, x1, y1, color, fill)

A filled box, corners included

printVecEllipse, printVecEllipseFill

An ellipse’s outline or an arc of it, or a filled ellipse

printVecDot(doc, x, y, color, width)

A round dot

printVecText(doc, font, x, y, text, len, color)

Text in a font opened for the page, the printer’s own

printVecImage(doc, rgb, w, h, sx, sy, sw, sh, dx, dy, dw, dh)

Part of a picture, stretched by the printer

A fill is a PrintFillE: solid, or lines one dot wide every PRINT_HATCH_DOTS (8) dots across, down, diagonal, or crossed. printVecBegin returns false, and the drawing calls do nothing, on any other printer and on a document that failed; while a vector page is open, printDocPage and printDocPicture refuse. printVecEnd returns false when the page did not print, and printDocClose ends a vector page left open. A cover page drawn this way would be:

if (page.vector && printVecBegin(doc)) {
    PrintFontT *font = printFontOpen(&page, PRINTIT_COVER_FAMILY, PRINTIT_TITLE_SIZE, FONT_STYLE_BOLD);   // Helvetica Bold

    printVecText(doc, font, x, y, sTitle, (int32_t)strlen(sTitle), PRINTIT_INK);
    printVecRect(doc, ruleX, ruleY, ruleX + ruleW - 1, ruleY + ruleH - 1, PRINTIT_INK, PrintFillSolidE);
    printVecEnd(doc);
    printFontClose(font);
}

12.8. When a Program Ends While Printing

DVX holds every open job and document for the program that opened it. When a program ends with one still open, ended from Task Manager, ended after a fault, or simply without closing it, DVX cancels the job and closes it as it cleans up after the program, so the port is free for the next printout and the buffers are freed. A program that ends normally closes its own: printit ends only through its window’s close, and every print command closes its job before it returns.

12.9. Testing Without a Printer

Print to a file. Choose File in the Print dialog, or as the destination on the Control Panel’s Printer page, and the output lands in PRINTER.PRN in DVX’s user folder, byte for byte what the printer would get: plain text with CR LF line ends and form feeds for the text-only model, which you can open in Notepad, and the printer’s commands for the others. On a PC, a real printer on LPT1 needs nothing more.

To test the problems, printSetPortOps(&ops) replaces the port layer with your own PrintPortOpsT: functions that say whether a port exists, report its status bits, and take a byte, so a test can play a printer that is busy, off line, or out of paper and see that its hooks behave. printSetPortOps(NULL) puts the real ports back. The replacement is for the whole library, every program’s jobs included, so use it only in a test.

12.10. Things to Remember

  • Read the printer from the settings; leave choosing it to the Control Panel and the page setup to the Page Setup dialog.

  • printUiText, printUiImageFile, and printUiWindow are a whole print each, messages included.

  • A job opened with printJobOpen is yours to close with printJobClose, which frees it; ask printJobCancelled before that.

  • A callback that prints runs the event loop from its idle hook, behind a modal window with a Cancel button.

  • Check a page setup of your own with printPageSetupProblem, and a model with printModelProblem, before printing.

  • Pictures need a model that prints them: printModelPage says. Draw pages in bands, from a description worked out before printDocPage.

  • On a PostScript printer, clear vector in the page you open fonts for, or draw a vector page.

Chapter 13. Databases

DVX’s databases are SQLite databases: single files, read and written with SQL, by a copy of SQLite (version 3.53.4) built for DOS into the library DVXSQL.LIB. The library wraps SQLite in a small C interface, dvxSql.h, whose connections and result sets are numbers rather than pointers, so that DVX BASIC can use the same calls. Two widgets sit on top of it: the Data control, which reads a table into memory and writes the user’s changes back, and the DBGrid, which shows a Data control’s rows as a table.

The library and the two widgets are an optional part of DVX, Databases, which the user chooses in Setup. This chapter builds an address book that uses all three, then explains each: the SQL calls first, then the widgets. The reference has every function (“dvxSql — SQL Database Interface” in the DVX C Library Reference, “DataCtrl” in the DVX C Library Reference, and “DbGrid” in the DVX C Library Reference). The SQL itself is SQLite’s, which this chapter does not teach.

13.1. The Contacts Program

The example contacts is an address book: a grid of contacts at the top, the Data control’s bar of arrow buttons under it, text boxes for the current contact’s name, telephone number, and e-mail address, and buttons to add, save, and delete contacts. Its File menu also exports the book to a text file. Build and install it as you did hello in Chapter 2; DVX must have the Databases part.

The Contacts window with three contacts in a grid, Bob O’Brien selected, the Data control bar, and his name, phone, and e-mail in text boxes
Figure 21. Contacts with Bob O’Brien’s row chosen: the DBGrid, the Data control, and the bound text boxes

The program talks to the database in two ways. Its own connection, opened when it starts and closed when its window closes, makes the table, adds a few contacts the first time, and exports the book. The Data control has connections of its own, and through them reads the table and writes the user’s changes. The program’s state:

static DxeAppContextT *sCtx      = NULL;
static AppContextT    *sAc       = NULL;
static WindowT        *sWin      = NULL;
static WidgetT        *sData     = NULL;
static WidgetT        *sGrid     = NULL;
static WidgetT        *sFields[CONTACTS_FIELDS];
static int32_t         sDb       = 0;
static bool            sRefused  = false;
static char            sDbPath[DVX_MAX_PATH];

13.2. Opening a Database

A program’s database belongs in its own folder in the user folder (Chapter 10), which may not exist yet. contacts keeps CONTACTS.DB there:

// CONTACTS.DB in the program's user folder, made the first time with its
// table and a few contacts.  False, after telling the user, when it
// cannot be opened or set up.
static bool openDatabase(void) {
    if (shellEnsureUserDir(sCtx) != 0) {
        dvxErrorBox(sAc, CONTACTS_TITLE, "The program's folder in the user folder could not be made.");
        return false;
    }

    shellUserPath(sCtx, CONTACTS_DB_FILE, sDbPath, sizeof(sDbPath));
    sDb = dvxSqlOpen(sDbPath);

    if (sDb == 0) {
        char msg[CONTACTS_MSG_MAX];

        snprintf(msg, sizeof(msg), "%s could not be opened: %s", sDbPath, dvxSqlError(0));
        dvxErrorBox(sAc, CONTACTS_TITLE, msg);
        return false;
    }

    int32_t count = execSql(CONTACTS_SCHEMA) ? queryNumber(CONTACTS_COUNT_SQL) : -1;

    if (count < 0 || (count == 0 && !addSamples())) {
        dvxErrorBox(sAc, CONTACTS_TITLE, "The address book could not be set up. DVX.LOG says why.");
        return false;
    }

    return true;
}

dvxSqlOpen(path) opens the database file, creating it when it does not exist, and returns a database handle, a number above 0. It returns 0 when it cannot open the file or memory runs out, and then dvxSqlError(0) says why, for example “unable to open database file (No such file or directory)”. Handles are small numbers that the library reuses once closed; never use one after closing it. The library and its tables of handles are shared by every program in DVX.

SQLite here runs on a small file layer written for DOS, and a few things about the files follow from it:

  • Journals have 8.3 names. While a change is being written, SQLite keeps a rollback journal beside the database. DVX names it itself: the database’s name with an extension of N and two characters worked out from the database’s own extension, so CONTACTS.DB gets CONTACTS.NJG, and CONTACTS.DB and CONTACTS.DAT in one folder each have their own. The few pairs of extensions that would give the same journal name are refused when the second is opened (dvxSqlError(0) says why). A file that has a journal’s name but is not a journal is never written over or deleted. Never delete a journal left behind by a crash: the next open uses it to undo the half-written change.

  • Paths are made absolute. A relative name is joined to the current folder, \ and / both work, and every spelling of a file is the same database.

  • Locking is inside DVX only. Any number of connections may read a database at once and one may write. Two programs, or a program and its Data control, share a file safely; a write that meets another connection’s write, or a commit that meets another connection’s open query, fails with “database is locked”. Nothing is locked at the DOS level.

  • Pages are small. A new database has 1 KB pages and each connection caches up to 512 KB of them. Temporary tables and sorts are kept in memory.

13.3. Running Statements

dvxSqlExec(db, sql) runs SQL that returns no rows, CREATE, INSERT, UPDATE, DELETE, BEGIN, and the rest, and returns true when it worked. Every statement in sql runs, one after another, in this one call; the first that fails stops it, and the ones before it have run. contacts runs every statement through a function that logs the error when there is one:

// dvxSqlExec, logging why when it fails
static bool execSql(const char *sql) {
    bool ok = dvxSqlExec(sDb, sql);

    if (!ok) {
        dvxLog("contacts: %s: %s", sql, dvxSqlError(sDb));
    }

    return ok;
}

The table is made with CREATE TABLE IF NOT EXISTS, which does nothing when the table is there, so the same statement serves the first run and every one after:

#define CONTACTS_DB_FILE      "CONTACTS.DB"
#define CONTACTS_EXPORT_FILE  "CONTACTS.TXT"
#define CONTACTS_TABLE        "contacts"
#define CONTACTS_KEY          "id"
#define CONTACTS_NAME         "name"
#define CONTACTS_SQL_MAX      512
#define CONTACTS_ESC_MAX      (CONTACTS_FIELD_MAX * 2 + 1)    // every character a quote, doubled
#define CONTACTS_SCHEMA       "CREATE TABLE IF NOT EXISTS contacts (id INTEGER PRIMARY KEY, name TEXT NOT NULL, phone TEXT, email TEXT)"
#define CONTACTS_COUNT_SQL    "SELECT COUNT(*) FROM contacts"
#define CONTACTS_INSERT_SQL   "INSERT INTO contacts (name, phone, email) VALUES ('%s', '%s', '%s')"
#define CONTACTS_EXPORT_SQL   "SELECT name, phone, email FROM contacts ORDER BY name COLLATE NOCASE"
#define CONTACTS_EXPORT_LINE  "%-24s  %-16s  %s\r\n"

id INTEGER PRIMARY KEY makes id the row’s own number, which SQLite assigns when an INSERT leaves it out. After a dvxSqlExec that worked, dvxSqlAffectedRows(db) returns the number of rows the most recent INSERT, UPDATE, or DELETE on the handle changed; it returns 0 for an invalid handle.

SQLite is built with a few options that show in its SQL:

  • Double quotes always mean a name: write text in single quotes. SELECT "abc" fails with “no such column: abc”.

  • There are no JSON functions, no write-ahead log (PRAGMA journal_mode = WAL leaves the database in the rollback journal mode), and no loadable extensions.

  • LIKE never matches a BLOB.

13.4. Values in Statements

dvxSql.h has no bound parameters: a value goes into a statement as text. A string goes between single quotes, and every single quote in it must be doubled, or O’Brien ends the string early and the rest of the name becomes SQL. dvxSqlEscape(src, dst, dstSize) does the doubling:

// One INSERT.  dvxSql has no bound parameters: a value goes into the
// statement's text, between single quotes, escaped (its quotes doubled)
// so that a name such as O'Brien neither breaks the statement nor changes
// what it does.
static bool insertContact(const ContactT *contact) {
    char name[CONTACTS_ESC_MAX];
    char phone[CONTACTS_ESC_MAX];
    char email[CONTACTS_ESC_MAX];
    char sql[CONTACTS_SQL_MAX];

    if (dvxSqlEscape(contact->name, name, sizeof(name)) < 0 || dvxSqlEscape(contact->phone, phone, sizeof(phone)) < 0 || dvxSqlEscape(contact->email, email, sizeof(email)) < 0) {
        return false;
    }

    snprintf(sql, sizeof(sql), CONTACTS_INSERT_SQL, name, phone, email);
    return execSql(sql);
}

dvxSqlEscape writes src with its single quotes doubled into dst and returns the length written, or -1 when dst is too small (or an argument is NULL); then dst is not a complete string, so stop. Room for twice the length plus one always suffices, which is how CONTACTS_ESC_MAX is sized. Escape every string that did not come from your own source code, typed by the user or read from a file, and put it only between single quotes.

The escaping covers strings. Put a number in a statement with %ld from an integer you hold, never from text you were given, and never build a table or column name from the user’s input at all: there is no escaping for names.

13.5. Transactions

The first time it runs, contacts adds three contacts, inside a transaction:

typedef struct {
    const char *name;
    const char *phone;
    const char *email;
} ContactT;

// The contacts a new address book starts with
static const ContactT sSamples[] = {
    { "Alice Archer", "555-0101", "alice@example.com" },
    { "Bob O'Brien",  "555-0102", "bob@example.com"   },
    { "Carol Chen",   "555-0103", "carol@example.com" }
};
// A new address book's first contacts, in one transaction: one journal
// and one update of the file for all of them rather than one for each,
// and none of them at all if one fails.
static bool addSamples(void) {
    if (!execSql("BEGIN")) {
        return false;
    }

    for (int32_t i = 0; i < DVX_ARRAY_LEN(sSamples); i++) {
        if (!insertContact(&sSamples[i])) {
            execSql("ROLLBACK");
            return false;
        }
    }

    return execSql("COMMIT");
}

A transaction is SQL, so it is dvxSqlExec of BEGIN, then the changes, then COMMIT to keep them all or ROLLBACK to undo them all. Without one, each statement is a transaction of its own, and each costs a journal file made, written, and deleted, and the database file updated, on a FAT disk that may be a floppy. Inside one, the journal is made once for all of them. So group the statements of one change in a transaction, both to keep the database whole and to make the change fast.

While a transaction that has written is open, no other connection can write the database, and its COMMIT fails with “database is locked” while another connection has a query open. Keep transactions short, and never leave one open while you wait for the user.

13.6. Queries and Cursors

A query’s rows come through a cursor. dvxSqlQuery(db, sql) prepares a SELECT and returns a cursor handle, above 0, positioned before the first row; it returns 0 when the SQL is wrong, empty, or only a comment, and the database’s dvxSqlError says why. Only the first statement in sql is prepared; anything after it is ignored. dvxSqlNext(rs) moves to the next row and returns true when there is one. When you are done, dvxSqlFreeResult(rs) frees the cursor. Call it for every cursor, and soon for one you do not read to its end: such a cursor keeps the database’s read lock, which blocks other connections' commits.

contacts asks its database for a single number, the number of contacts, with one function:

// The first column of a query's first row as a number; -1 when the query
// fails.
static int32_t queryNumber(const char *sql) {
    int32_t rs     = dvxSqlQuery(sDb, sql);
    int32_t number = -1;

    if (rs == 0) {
        dvxLog("contacts: %s: %s", sql, dvxSqlError(sDb));
        return -1;
    }

    if (dvxSqlNext(rs)) {
        number = dvxSqlFieldInt(rs, 0);
    }

    dvxSqlFreeResult(rs);
    return number;
}

A row’s values are read by column, numbered from 0:

Call Returns

dvxSqlFieldText(rs, col)

The value as text; "" for NULL and for an invalid handle or column

dvxSqlFieldByName(rs, name)

The same, for the column of that name, matched without regard to case; "" when there is none

dvxSqlFieldInt(rs, col)

The value as a 32-bit integer (text is converted, NULL is 0). A value beyond 32 bits is cut to its low 32; read such values with dvxSqlFieldDbl or as text.

dvxSqlFieldDbl(rs, col)

The value as a double

dvxSqlFieldCount(rs), dvxSqlFieldName(rs, col)

The number of columns, and a column’s name

dvxSqlEof(rs)

true once dvxSqlNext has passed the last row (or failed), and for an invalid handle

The text belongs to the cursor and lasts only until the next dvxSqlNext or dvxSqlFreeResult on it: copy what you keep. Since NULL and an empty string both read as "", a query that must tell them apart asks SQLite, for example with phone IS NULL as a column of its own.

The export reads every contact, sorted, and writes a line for each:

// Every contact, sorted by name, into CONTACTS.TXT in the user folder, a
// line each.  The contact on the screen is saved first: the query reads
// the database, not the Data control's copy of the rows.
static void exportContacts(void) {
    char    path[DVX_MAX_PATH];
    char    msg[CONTACTS_MSG_MAX];
    int32_t count = 0;

    wgtDataCtrlUpdate(sData);
    shellUserPath(sCtx, CONTACTS_EXPORT_FILE, path, sizeof(path));

    int32_t rs = dvxSqlQuery(sDb, CONTACTS_EXPORT_SQL);
    FILE   *fp = rs ? fopen(path, "wb") : NULL;

    if (!fp) {
        snprintf(msg, sizeof(msg), "The contacts could not be exported: %s", rs ? "the file could not be made." : dvxSqlError(sDb));
        dvxSqlFreeResult(rs);
        dvxErrorBox(sAc, CONTACTS_TITLE, msg);
        return;
    }

    while (dvxSqlNext(rs)) {
        fprintf(fp, CONTACTS_EXPORT_LINE, dvxSqlFieldByName(rs, CONTACTS_NAME), dvxSqlFieldByName(rs, "phone"), dvxSqlFieldByName(rs, "email"));
        count++;
    }

    // dvxSqlNext is false at the end and on an error.  dvxSqlQuery cleared
    // the database's error, so an error there now came from a step.
    bool readOk  = dvxSqlError(sDb)[0] == '\0';
    bool writeOk = fclose(fp) == 0;

    dvxSqlFreeResult(rs);

    if (readOk && writeOk) {
        snprintf(msg, sizeof(msg), "%ld contacts were written to %s.", (long)count, path);
        dvxInfoBox(sAc, CONTACTS_TITLE, msg);
    } else {
        snprintf(msg, sizeof(msg), "Not every contact could be written to %s: %s", path, readOk ? "the disk may be full." : dvxSqlError(sDb));
        dvxErrorBox(sAc, CONTACTS_TITLE, msg);
    }
}

dvxSqlNext returns false both at the end and when a step fails, a disk error in the middle of a table, for instance. The two are told apart by the database’s error: dvxSqlQuery clears it when it succeeds, and a failed step sets it.

13.7. Errors

dvxSqlError(db) returns the message of the last failure on a handle, SQLite’s own: “no such table: contact”, “UNIQUE constraint failed: contacts.id”, “database is locked”. When a file could not be opened, read, or written, DOS’s reason follows in parentheses. A successful dvxSqlExec or dvxSqlQuery clears it; dvxSqlNext only sets it. The text belongs to the library and lasts until the next call on the handle. For handle 0 it is the reason the last dvxSqlOpen failed, and for any other handle that is not open it is “Invalid database handle”.

“database is locked” is the one error that is not a mistake: another connection was writing, or held a query open while this one tried to commit. Try again after the other side finishes; in a program with a Data control, the other side is often the Data control (Section 13.10.1).

13.8. Long Statements

A statement runs to its end inside the call that runs it, dvxSqlExec, dvxSqlQuery, or dvxSqlNext, and the first dvxSqlNext of a sorted or grouped query reads every row it sorts. On a 486 and a large table that can be seconds, during which a callback holds up all of DVX (Section 3.6). dvxSqlSetPump(db, pump) gives a database a pump, which the library calls with the handle about every 1000 instructions of SQLite’s virtual machine while a statement runs on it (SQLite’s progress handler, not every 1000 rows); NULL removes it, and a database opens without one. Returning false from the pump stops the statement: the call fails, dvxSqlError says “interrupted”, and what the statement changed is undone (inside a transaction, an interrupted INSERT, UPDATE, or DELETE rolls back the whole transaction, as SQLite documents).

A pump in a callback-only program runs a frame of DVX’s event loop, as a print job’s idle hook does (Section 12.5.1), behind a modal window with a Cancel button:

static bool sqlPump(int32_t db) {
    (void)db;
    return dvxUpdate(sAc) && !sCancelled;
}

dvxSqlSetPump(sDb, sqlPump);

While a statement runs, the code the pump runs may use other databases as always, but calls on the busy database are refused: dvxSqlExec, dvxSqlQuery, and dvxSqlNext fail with “A statement is still running on this database”, its cursors' field functions return "" and 0, and dvxSqlFreeResult and dvxSqlClose return at once but take effect only when the statement ends. DVX BASIC gives every database its programs open a pump of this kind. (dvxSqlAbandon closes a database at once, even under a running statement whose caller is gone; it is for a run time like BASIC’s, and a C program does not need it.)

13.9. Closing a Database

dvxSqlClose(db) closes a database and frees every cursor still open on it; an invalid handle is ignored. Close what you open, as soon as you are done with it: an open connection holds a file, and a cache of up to 512 KB. When a program ends, however it ends, DVX closes the databases it left open, as it destroys its windows and releases its timers and print jobs. contacts closes its connection with its window:

// The window and the program's own connection go together.  DVX would
// close the connection when the program ends, but a program closes what
// it opens.
static void closeWindow(void) {
    dvxDestroyWindow(sAc, sWin);
    sWin = NULL;
    dvxSqlClose(sDb);
    sDb = 0;
}

13.10. The Data Control

The Data control is the widget form of a table: it reads the rows of a table or a query into memory, keeps a current row, moves among the rows from code or from its bar of four arrow buttons (first, previous, next, last, with a caption between), and writes changes to the current row back to the database. It does no drawing of the rows itself; other widgets show them. Its header is dataCtrl/dataCtrl.h, and the DBGrid’s is dbGrid/dbGrid.h.

Both widgets are part of the optional Databases part, so contacts checks for them first (Section 5.2):

sCtx = ctx;
sAc  = ctx->shellCtx;

// The Data control and the DBGrid are an optional part of DVX
if (!dvxDataCtrlApi() || !dvxDbGridApi()) {
    dvxErrorBox(sAc, CONTACTS_TITLE, "Contacts needs the Data control and the DBGrid. Run Setup and install the Databases part of DVX.");
    return -1;
}

The program also calls the SQL library directly, and that check comes earlier: without DVXSQL.LIB, the program does not load at all, and the shell’s “Failed to load” message names one of the SQL functions as an “unresolved symbol” (Section 3.2). A program that should run without the library, using it only when it is there, finds its functions with dlsym instead, as the Data control itself does. A package that needs the Databases part says so in its PKG_NEEDS (Chapter 21).

The window holds the grid, the Data control, the text boxes, and the buttons:

if (!openDatabase()) {
    closeWindow();
    return -1;
}

sWin = dvxCreateWindowCentered(sAc, CONTACTS_TITLE, CONTACTS_WIN_W, CONTACTS_WIN_H, true);

WidgetT *root = sWin ? wgtInitWindow(sAc, sWin) : NULL;

if (!root || !buildMenus()) {
    closeWindow();
    return -1;
}

sWin->onClose = onClose;
sWin->onMenu  = onMenu;
root->spacing = wgtPixels(CONTACTS_SPACING);
sGrid = wgtDbGrid(root);
sData = wgtDataCtrl(root);

bool     built   = sGrid && sData && buildFields(root);
WidgetT *buttons = built ? wgtHBox(root) : NULL;

if (!buttons) {
    closeWindow();
    return -1;
}

sGrid->weight    = WGT_WEIGHT_FILL;
buttons->spacing = wgtPixels(CONTACTS_SPACING);
addButton(buttons, "Ne&w", CMD_NEW);
addButton(buttons, "&Save", CMD_SAVE);
addButton(buttons, "&Delete", CMD_DELETE);

13.10.1. Telling It What to Read

wgtDataCtrl(parent) makes a Data control with nothing to read. What it reads is set through its properties: its C API has no calls for them, so a C program sets them with the generic wgtSetProp (Section 5.12):

// The Data control's settings are properties of its generic interface:
// its C API has no calls for them.  The text is copied.
static void setDataProp(const char *name, const char *value) {
    WgtValueT v = wgtValueStr(value);

    if (!wgtSetProp(sData, name, &v)) {
        dvxLog("contacts: the Data control refused %s", name);
    }
}
setDataProp("DatabaseName", sDbPath);
setDataProp("RecordSource", CONTACTS_TABLE);
setDataProp("KeyColumn", CONTACTS_KEY);
setDataProp("Caption", CONTACTS_TITLE);
sData->onChange   = onReposition;
sData->onValidate = onValidate;
wgtDataCtrlRefresh(sData);
Property Meaning

DatabaseName

The database file’s path

RecordSource

What to read: a table’s name, or a query, whose first word is SELECT, WITH, or VALUES, in any case. A table can be written back; a query cannot.

KeyColumn

The column that identifies a row, for writing it back; when it is empty or names no column, the first column is used

Caption

The text on the bar; when empty, the first successful Refresh sets it to RecordSource

DetailField

For a detail control, the column filtered by the master’s value (Section 13.10.6)

BOF, EOF, RecordCount, FieldCount

Read only: whether a move tried to pass the first or the last row (or there are no rows), the rows read so far, and the number of columns

AbsolutePosition

The current row, as wgtDataCtrlGetCurrentRow and wgtDataCtrlSetCurrentRow

The strings are copied, 255 characters at most. MasterSource and MasterField are there too, but only DVX BASIC’s form run time reads them.

wgtDataCtrlRefresh(w) reads the record set: SELECT * FROM the table, or the query. It saves a pending change to the current row first (and drops it if that save fails), reads the column names and the first 64 rows, makes the first row current, and fires Reposition (Section 13.10.2). The rest of the rows are read a part at a time, about 20 ms of reading each time DVX polls the widget, so a large table does not hold DVX up. A move past the rows read so far reads as far as it needs at once, and wgtDataCtrlMoveLast, wgtDataCtrlAddNew, wgtDataCtrlUpdate, and wgtDataCtrlDelete read all the rest first. Until the last row is in, the query stays open on a connection of the control’s own and holds the database’s read lock, so a commit from any other connection, your program’s included, fails with “database is locked”. Call Refresh again whenever the table may have changed under it, or after changing RecordSource.

Refresh raises no error when it fails, when the file or the table is not there or the query is wrong: the control simply has no rows and no columns, and still fires Reposition. wgtDataCtrlGetError(w) says why: every operation of the control (Refresh, the moves, wgtDataCtrlSetField, Update, AddNew, Delete, wgtDataCtrlUnload) clears it first, and one that fails leaves a sentence there, the database’s own message or the control’s (“The RecordSource is a query: its records cannot be changed.”). It is "" after one that worked, so read it right after the call you want to check. (BASIC calls it LastError.)

13.10.2. The Current Row and Reposition

The control has a current row, from 0, or -1 when there are no rows:

  • wgtDataCtrlMoveFirst, wgtDataCtrlMovePrev, wgtDataCtrlMoveNext, and wgtDataCtrlMoveLast move it, as the four buttons do. A move past either end leaves the row where it is and sets BOF or EOF.

  • wgtDataCtrlSetCurrentRow(w, row) makes a row current; a row beyond the last is ignored. wgtDataCtrlGetCurrentRow(w) returns it.

  • wgtDataCtrlGetField(w, column) returns a column of the current row by name, without regard to case, and wgtDataCtrlGetCellText(w, row, col) any row’s by number. Both return "" when there is no such row or column. wgtDataCtrlGetRowCount, wgtDataCtrlGetColCount, and wgtDataCtrlGetColName describe the rows read so far.

The values are the rows as read, as text, kept by the control; a string it returns lasts until that value changes, its row is deleted, the control reads its rows again, or it is destroyed. Reading the rows into memory is what lets the user go back and forth with no query each time, and it is also why a large table costs memory in proportion: a query that picks fewer rows costs less, but cannot be written back.

Every change of the current row, by a move, Refresh, AddNew, or Delete, fires the control’s Reposition event, which in C is its onChange. That is where a program shows the new row. contacts puts it in its text boxes, grays them when there is no row, and moves the grid’s highlight:

// The Data control's Reposition event, its onChange: the current row is
// another one, after a move, a Refresh, AddNew, or Delete.  The text
// boxes show it (setting their text fires no onChange of theirs), and the
// grid moves its highlight to it.
static void onReposition(WidgetT *w) {
    bool hasRow = wgtDataCtrlGetCurrentRow(w) >= 0;

    for (int32_t i = 0; i < CONTACTS_FIELDS; i++) {
        wgtSetText(sFields[i], wgtDataCtrlGetField(w, sColumns[i]));
        wgtSetEnabled(sFields[i], hasRow);
    }

    wgtDbGridRefresh(sGrid);
}

Setting a text box’s text does not fire its onChange, so showing the row does not count as an edit.

13.10.3. Changing Rows

The Data control keeps changes in its copy of the current row until it writes them. wgtDataCtrlSetField(w, column, value) changes a column of the current row (the value is copied); a value equal to the one there is not a change. wgtDataCtrlUpdate(w) writes the changed row back: with an UPDATE of the changed columns, finding the row by the value its KeyColumn had when it was read (so a changed key is written, not used to find the row), or with an INSERT for a row AddNew made. Each write opens the database, runs the statement, and closes it again.

The Data control also writes the current row by itself, before every move and AddNew: a change is never lost by moving away from it, since a move whose save fails does not happen. (Refresh saves first too, but drops the change when the save fails.) So the safest way to edit is to give every edit to the control the moment it happens. contacts builds its text boxes in a loop, each knowing its column’s index:

// The edited columns, in the order of the text boxes, with the boxes'
// labels and the grid's column headings
static const char *const sColumns[CONTACTS_FIELDS] = { CONTACTS_NAME, "phone", "email" };
static const char *const sLabels[CONTACTS_FIELDS]  = { "&Name:", "&Phone:", "&E-mail:" };
static const char *const sHeaders[CONTACTS_FIELDS] = { "Name", "Phone", "E-mail" };
// A row for each column: its label and a text box, which knows its index
// (userData) and sends every edit to the Data control (onFieldChange).
static bool buildFields(WidgetT *root) {
    for (int32_t i = 0; i < CONTACTS_FIELDS; i++) {
        WidgetT *row   = wgtHBox(root);
        WidgetT *label = row ? wgtLabel(row, sLabels[i]) : NULL;

        sFields[i] = label ? wgtTextInput(row, CONTACTS_FIELD_MAX) : NULL;

        if (!sFields[i]) {
            return false;
        }

        row->spacing         = wgtPixels(CONTACTS_SPACING);
        label->minW          = wgtChars(CONTACTS_LABEL_CHARS);
        sFields[i]->onChange = onFieldChange;
        sFields[i]->userData = (void *)(intptr_t)i;
    }

    return true;
}

and each edit goes straight to the Data control:

// Every edit goes into the Data control's copy of the current row at
// once, which marks the row changed: the Data control saves it before
// any move, however the user leaves the box.
static void onFieldChange(WidgetT *w) {
    wgtDataCtrlSetField(sData, sColumns[(intptr_t)w->userData], wgtGetText(w));
}

Waiting for the text box to lose the focus would be too late. When the user clicks a row of the grid or one of the Data control’s buttons, DVX lets the clicked widget handle the press first, which moves the current row, and fires the text box’s onBlur only after that, by which time Reposition has filled the box with the next row.

Before every operation that leaves the current row, a move, AddNew, Delete, wgtDataCtrlSetCurrentRow, Refresh, or wgtDataCtrlUnload, and before an Update of a changed row, the control fires its Validate event, its onValidate, as Visual Basic’s Data control does. wgtDataCtrlGetValidateAction(w) says which operation is coming, a DataActionE with Visual Basic’s numbers (DataActionMoveFirstE to DataActionMoveLastE, DataActionAddNewE, DataActionUpdateE, DataActionDeleteE, DataActionBookmarkE for wgtDataCtrlSetCurrentRow, DataActionCloseE for Refresh, and DataActionUnloadE), and wgtDataCtrlGetValidateSave(w) whether the row has changes to write. The handler returns false, or sets the action to DataActionCancelE with wgtDataCtrlSetValidateAction, to cancel: the operation does not happen, and the row stays as it is, changed and unsaved (a Refresh or an unload goes on all the same, and drops the change). It may also turn a move or AddNew into another one with wgtDataCtrlSetValidateAction, and wgtDataCtrlSetValidateSave(w, false) drops the row’s changes and lets the operation go on. contacts insists on a name, except before a Delete or when there is nothing to write:

// The Data control's Validate event, before every operation that leaves
// the current row and before an Update of a changed one: false cancels
// the operation, and the row stays on the screen, unsaved.  Every contact
// needs a name, but a Delete, or a row with no change to save, needs
// none.
static bool onValidate(WidgetT *w) {
    if (wgtDataCtrlGetValidateAction(w) == DataActionDeleteE || !wgtDataCtrlGetValidateSave(w) || wgtDataCtrlGetField(w, CONTACTS_NAME)[0]) {
        return true;
    }

    sRefused = true;
    dvxMessageBox(sAc, CONTACTS_TITLE, "Every contact needs a name. Type one, or delete the contact.", MB_OK | MB_ICONWARNING);
    return false;
}

While onValidate runs, the control refuses its moves, AddNew, Refresh, Update, and wgtDataCtrlUnload, since each would save, and so validate, the same row again; Delete still works.

A write can also fail in the database: the file is read-only, another connection holds it locked, a constraint fails. The row then stays changed and unsaved, every move stays refused until the write succeeds or the row is deleted, and wgtDataCtrlGetError has the database’s message, for the program to show.

A query RecordSource cannot be written: Update, Delete, and AddNew are refused, with the reason in wgtDataCtrlGetError, and a change to a row is dropped when the current row moves.

13.10.4. Adding and Deleting

wgtDataCtrlAddNew(w) saves the current row, then adds a blank row after the last (reading the whole record set first), makes it current, and fires Reposition. The new row is written, with an INSERT, by the next Update or move. When saving the current row fails, AddNew does nothing.

The INSERT names the columns that have a value, with the values as text, and leaves the empty ones out (a row with none is DEFAULT VALUES), so the database fills them: an INTEGER PRIMARY KEY left empty gets the next number. The control then reads the saved row back, by its rowid, so the new row shows the key and the defaults the database gave it. contacts only puts the cursor in the first box when it adds a row:

// AddNew saves the contact on the screen, adds a blank row, and moves to
// it; when that save is refused it does nothing, and the row on the
// screen, which has an id, is still the current one.  The new row has no
// id until it is saved: the Data control leaves its empty columns out of
// the INSERT, so SQLite numbers it, and reads the saved row back.
static void newContact(void) {
    wgtDataCtrlAddNew(sData);

    if (!wgtDataCtrlGetField(sData, CONTACTS_KEY)[0]) {
        wgtSetFocused(sFields[0]);
    }
}

A row the database has read always has an id, so an empty id after AddNew means the new row is current, and AddNew was not refused. The id column is hidden in the grid; the user never sees it.

wgtDataCtrlDelete(w) deletes the current row from the database and from the control’s rows, makes the row after it current (or the one before, when it was the last), and fires Reposition. A new row that was never saved is only dropped; when the database refuses the DELETE, nothing changes. It asks no questions, so the program asks:

static void deleteContact(void) {
    if (wgtDataCtrlGetCurrentRow(sData) >= 0 && dvxMessageBox(sAc, CONTACTS_TITLE, "Delete this contact?", MB_YESNO | MB_ICONQUESTION) == ID_YES) {
        wgtDataCtrlDelete(sData);
    }
}

13.10.5. Before the Window Closes

Destroying a Data control throws away a change it has not written, with no Validate. wgtDataCtrlUnload(w), called before the window is destroyed, does what Visual Basic does when a form unloads: Validate, with DataActionUnloadE, and then the change is written, or dropped when Validate cancels or the write fails, and the window closes all the same. contacts wants to stay open when the name is missing, so it writes the current row with Update instead, and closes only when Validate did not refuse:

// The close gadget, Alt+F4, File > Exit, and DVX closing every program.
// The contact on the screen is saved first, since destroying the Data
// control throws away what it has not written.  A save Validate refuses
// keeps the window open.
static void requestClose(void) {
    sRefused = false;
    wgtDataCtrlUpdate(sData);

    if (!sRefused) {
        closeWindow();
    }
}

The menu commands and the buttons share one dispatcher, and Save is a plain Update:

static void runCommand(int32_t cmd) {
    switch (cmd) {
        case CMD_NEW:
            newContact();
            break;

        case CMD_SAVE:
            wgtDataCtrlUpdate(sData);
            break;

        case CMD_DELETE:
            deleteContact();
            break;

        case CMD_EXPORT:
            exportContacts();
            break;

        case CMD_EXIT:
            requestClose();
            break;

        case CMD_HELP_CONTENTS:
            shellOpenHelpFile(sAc, sCtx->helpFile, NULL);
            break;

        case CMD_HELP_ABOUT:
            dvxInfoBox(sAc, "About " CONTACTS_TITLE, CONTACTS_ABOUT_TEXT);
            break;

        default:
            break;
    }
}

13.10.6. Master and Detail

Two Data controls can show related tables, such as customers and their orders: the detail control shows only the rows whose DetailField column holds the master value. Set DetailField on the detail control, and in the master’s onChange, give the detail the master’s current key and read again:

static void onCustomerChange(WidgetT *w) {
    wgtDataCtrlSetMasterValue(sOrders, wgtDataCtrlGetField(w, "id"));
    wgtDataCtrlRefresh(sOrders);
}

The detail control then reads SELECT * FROM its table (or its query, as a subquery) WHERE the DetailField column equals the value. An empty master value reads no rows at all, so when the master has no current row, the detail is empty.

13.11. The DBGrid

A DBGrid shows a Data control’s rows as a table: a column for each column, a heading for each, scroll bars when they are needed. It reads the rows straight from the Data control, so there is no second copy, and it shows them read-only; editing happens elsewhere, in widgets like the text boxes of contacts.

wgtDbGrid(parent) makes one, and wgtDbGridSetDataWidget(grid, data) binds it to a Data control and makes its columns from the Data control’s columns. The columns are made at that moment, so bind the grid after the Data control’s Refresh, and bind it again after a Refresh that changed the columns (a new RecordSource, say); binding the same Data control again with the same columns keeps the grid’s headings, widths, hidden columns, and sort.

wgtDbGridSetDataWidget(sGrid, sData);
wgtDbGridSetColumnVisible(sGrid, CONTACTS_KEY, false);

for (int32_t i = 0; i < CONTACTS_FIELDS; i++) {
    wgtDbGridSetColumnHeader(sGrid, sColumns[i], sHeaders[i]);
}

wgtInvalidate(root);
dvxLog("contacts: opened %s", sDbPath);
return 0;

Columns are named by their field names, without regard to case. wgtDbGridSetColumnHeader(grid, field, text) gives a column a heading other than its name (63 characters at most), wgtDbGridSetColumnVisible(grid, field, visible) hides or shows it, and wgtDbGridSetColumnWidth(grid, field, width) gives it a width in the widget size units (wgtChars(20); 0 for automatic, which fits the heading and the first 200 rows). The user can drag a column’s edge to change its width, and click a heading to sort by that column, ascending and then descending. The sort is the ListView’s (Section 5.11.1): numbers by their values, ahead of the text, which sorts without regard to case. The GridLines property (on by default) draws lines between the cells.

The grid has no selection of its own: its highlighted row is always the Data control’s current row. A click on a row, or the arrow keys, Page Up, Page Down, Home, and End, move the Data control’s current row, with the save and the Reposition that go with it; a refused save keeps the highlight where it was. The mouse wheel scrolls without moving it. Enter and a double click fire the grid’s onDblClick; onClick fires for a click on the rows (at the release, after onMouseUp) and for each row change made from the keyboard. A press on a heading, a column’s edge, or a scroll bar fires neither, nor onMouseDown. wgtDbGridGetSelectedRow(grid) and wgtDbGridSetSelectedRow(grid, row) read and move the current row through the grid, by the row’s number in the Data control, not its place in a sorted grid.

The grid follows the Data control’s rows and values by itself: rows arriving as the record set is read, an edit, an added or deleted row all show without a call. A move of the current row made anywhere else, by the Data control’s buttons or by your code, does not; call wgtDbGridRefresh(grid) from the Data control’s onChange, as contacts does in onReposition, and the highlight follows.

13.12. Things to Remember

  • Keep a program’s database in its user folder, and close every connection you open; DVX closes only what is left when the program ends.

  • Free every cursor with dvxSqlFreeResult; copy a field’s text before the next dvxSqlNext.

  • Escape every string that goes into a statement with dvxSqlEscape, and put it between single quotes.

  • Put the statements of one change in a transaction: it is all or nothing, and on DOS it is much faster.

  • Set a Data control’s DatabaseName, RecordSource, and KeyColumn with wgtSetProp, then Refresh; bind a DBGrid after the Refresh.

  • Give every edit to the Data control with wgtDataCtrlSetField as it happens; show each new current row in onChange, and refresh the grid there.

  • Save the current row before the window closes: wgtDataCtrlUnload, or wgtDataCtrlUpdate and a check of Validate to keep the window open.

  • The Data control raises nothing when it fails: read wgtDataCtrlGetError right after the call where it matters.

Chapter 14. Networking and the Web

DVX speaks TCP/IP. Its networking library gives programs the BSD socket API, the same calls and headers a C programmer uses on Linux, over a network card’s DOS packet driver. On top of the sockets sit two smaller libraries: an HTTP client that runs a request a step at a time, and a JSON reader. This chapter explains how the network runs under DVX, what is different about sockets there, how to wait for the network without stopping DVX, and how to use the HTTP and JSON libraries, and builds httpget, a program that fetches a web address and shows the reply and its JSON fields. The reference describes every call (“Networking Library” in the DVX C Library Reference and the sections after it).

DVX has no TLS. Everything a program sends and receives over the network travels in the clear, and the HTTP library takes only http:// addresses: an https:// address fails with a message saying DVX has no encryption. Section 14.9 says what that means for a program.

14.1. The Network Under DVX

DOS has no network of its own. A network card is reached through its packet driver, a small DOS program loaded before DVX (NE2000.COM 0x60 3 0x300, for example, for an NE2000 card at I/O address 300h on IRQ 3), which puts the card behind a software interrupt. The networking library finds the driver on interrupts 60h to 80h, or on the one the settings name, and runs a TCP/IP stack (lwIP, built without threads) over it. Any card with a packet driver works.

The settings are in DVX.INI, section [network], and the user edits them on Control Panel’s Network page: DHCP or a fixed address, the name servers, the computer’s name, and the packet driver’s interrupt. DHCP is the default. A program does not start the network: it starts itself, with those settings, the first time any program creates a socket or looks up a name. Without a packet driver it still runs, for 127.0.0.1 only, so programs on one computer can talk to each other; anything else fails with ENETUNREACH.

The stack does its work when DVX lets it: from the shell’s idle time (Section 3.5), and inside every socket call. The card’s interrupt puts each frame it receives into a ring of 16 frames; the stack takes them out later. When DVX is too busy to come back for them, frames are lost (the status counts them) and TCP sends them again. Code that keeps DVX busy makes the network slow for every program.

Networking is an optional part of DVX: the user chooses it in Setup or adds it with Software. It holds the networking library, the HTTP library, and the package server’s client; the JSON library is part of every DVX. A program that calls the networking or HTTP library does not start where Networking is not installed: DVX says the program cannot be loaded and names the first function it could not find. Chapter 21 shows how a package says which parts it needs.

14.2. Building a Program That Uses the Network

The socket headers are the standard ones, sys/socket.h, netinet/in.h, netinet/tcp.h, arpa/inet.h, netdb.h, sys/select.h, poll.h, and sys/ioctl.h, with an errno.h that adds the network error codes to the C library’s. DJGPP’s C library has no sockets, so the SDK has its own versions of these headers in include/net, with dvxNet.h, the networking library’s own header. They replace C library headers of the same name, so sdk.mk puts that folder on the include path only for a project that asks, with NET = 1 before the include:

SDK_DIR ?= ../../../../bin/sdk
KIND     = app
NAME     = httpget
NET      = 1

include $(SDK_DIR)/sdk.mk

The HTTP and JSON headers, http.h and json.h, are on every project’s include path and need no setting; httpget sets NET = 1 for dvxNet.h. Nothing else is needed: no library to link, and no .dep file. The calls are left open when the module is linked, and DVX loads the HTTP and JSON libraries the first time a program needs them (Section 3.2).

14.3. Sockets

Sockets work as they do on BSD and Linux, with the same names, arguments, and results. A socket is an ordinary file descriptor, so read, write, and close work on it, as do fcntl(fd, F_SETFL, O_NONBLOCK), ioctl(fd, FIONBIO, &on), ioctl(fd, FIONREAD, &n), select, and poll. Code from a Unix program mostly compiles and runs as it is. What differs:

Area Under DVX

Families

IPv4 only. AF_INET6, sockaddr_in6, and sockaddr_storage are defined so code written for both compiles, but socket(AF_INET6, …​) fails with EAFNOSUPPORT. SOCK_STREAM and SOCK_DGRAM; no raw sockets.

Ownership

A socket belongs to the program that created it (an accepted one to the program that accepted it). When a program ends, however it ends, DVX closes every socket it left open and drops its unfinished name lookups.

Limits

At most 32 sockets at a time in all of DVX, every program’s together, and room in the stack for 16 TCP connections. A listen backlog is capped at SOMAXCONN (16).

Errors

errno.h adds the network codes (ECONNREFUSED, ETIMEDOUT, EINPROGRESS, and the rest; EWOULDBLOCK is EAGAIN). The C library’s strerror does not know them: netErrorText(err) (dvxNet.h) gives plain words for any of them, and for a failed lookup’s EAI_ code.

Names

getaddrinfo looks names up with the configured name servers (or the DHCP server’s) and knows the common service names (http, telnet, ftp, and others). There are no reverse lookups: gethostbyaddr and getnameinfo give the address as text. gethostname gives the computer’s name from the settings.

Options

SO_REUSEADDR, SO_KEEPALIVE, SO_BROADCAST, SO_RCVTIMEO, SO_SNDTIMEO, and TCP_NODELAY work. The buffer sizes are fixed (SO_RCVBUF and SO_SNDBUF read 5840 for TCP, 8192 for UDP), SO_LINGER is accepted and reads as off, and MSG_OOB fails with EOPNOTSUPP. There are no signals: MSG_NOSIGNAL is accepted, and a send on a closed connection returns an error.

Closing

close starts an orderly close and returns; the close finishes in the background. Closing with received data unread resets the connection, as on BSD.

Descriptors

dup and dup2 refuse sockets (EOPNOTSUPP). An accepted socket blocks even when the listening one does not, as on Linux.

One more difference has no counterpart on Unix: while DVX runs a DOS program, the stack stops and lets go of the packet driver, which the DOS program may want, and every socket of every program loses its connection (Section 14.9). The stack starts again the next time a program uses it.

14.4. Waiting Without Stopping DVX

A socket call that has to wait, a blocking connect, accept, recv, a send with a full buffer, select or poll with a timeout, or a name lookup with getaddrinfo or gethostbyname, does not stop DVX the way sleep would. It waits in a loop that runs the network stack and calls tsYield, again and again, until it can return (Section 3.5). Where that leaves your program depends on which task is waiting:

  • On a main-loop program’s own task, a blocking call is acceptable. While it waits, the shell runs its frames, other programs run, and your windows' callbacks run too, on the shell’s task. The loop itself waits, so a callback that sets a flag (a Cancel button) is not seen until the call returns: give blocking sockets a timeout (SO_RCVTIMEO, SO_SNDTIMEO).

  • In a callback, never. The callback runs on the shell’s task, so the task that yields is the shell’s own: other programs' tasks run, but no frame does. No input is read, nothing is painted, and the mouse pointer stops until the call returns, which for a server that does not answer is many seconds. A name lookup waits up to 30 seconds for a name server before it gives up.

Right after the network starts, DHCP needs a moment to get an address. Blocking connect and sendto calls, and name lookups, wait for it, up to 20 seconds, instead of failing, so a program started together with DVX can connect at once. A non-blocking socket does not wait.

So a callback-only program uses non-blocking sockets, and looks at them from a Timer (Chapter 11) with poll or select and a timeout of 0, which never waits. Connecting takes two steps: connect on a non-blocking socket returns EINPROGRESS at once, and the socket becomes writable when the connection is made or has failed, after which SO_ERROR says which. Here sFd is a static int, -1 while there is no socket:

// Start connecting to addr (network byte order) and port: returns at once.
static bool connectStart(uint32_t addr, uint16_t port) {
    struct sockaddr_in to;
    int                on = 1;

    memset(&to, 0, sizeof(to));
    to.sin_family      = AF_INET;
    to.sin_port        = htons(port);
    to.sin_addr.s_addr = addr;
    sFd                = socket(AF_INET, SOCK_STREAM, 0);

    if (sFd < 0) {
        return false;
    }

    if (ioctl(sFd, FIONBIO, &on) == 0 && (connect(sFd, (struct sockaddr *)&to, sizeof(to)) == 0 || errno == EINPROGRESS)) {
        return true;
    }

    close(sFd);
    sFd = -1;
    return false;
}


// One look, from a Timer: 1 connected, 0 not yet, -1 failed (errno says why).
static int32_t connectCheck(void) {
    struct pollfd pfd = { sFd, POLLOUT, 0 };
    int           err = 0;
    socklen_t     len = sizeof(err);

    if (poll(&pfd, 1, 0) == 0) {
        return 0;
    }

    if (getsockopt(sFd, SOL_SOCKET, SO_ERROR, &err, &len) != 0 || err != 0) {
        errno = err;
        return -1;
    }

    return 1;
}

After that, each tick reads what has come: recv on a non-blocking socket returns the bytes there are, 0 when the other side has closed, or -1 with EWOULDBLOCK when nothing has arrived yet. send takes what fits in the stack’s buffer and returns that count, or -1 with EWOULDBLOCK when it is full; keep the rest and offer it again at the next tick.

14.4.1. Looking Up a Name Without Waiting

getaddrinfo waits for the name server, so dvxNet.h has a lookup that does not. netLookupStart(&lk, name) starts looking up a name or a dotted address, starting the network if it is not running. netLookupPoll(&lk, &addr) takes one look and returns at once: NET_LOOKUP_BUSY while the lookup goes on, 0 with the address in network byte order, or a negative EAI_ code from netdb.h that netErrorText (or gai_strerror) puts in words. Once it has ended it says the same again. The NetLookupT is the program’s, and must stay where it is until the lookup ends, so it is a static or a member of something that lives that long. A lookup also waits, a look at a time, for DHCP’s first address, so the connection started from its result goes at once. With sLookup a static NetLookupT, a Timer’s callback calls:

// One look at the lookup netLookupStart(&sLookup, host) began, from a Timer.
static void lookupTick(void) {
    uint32_t addr = 0;
    int32_t  rc   = netLookupPoll(&sLookup, &addr);

    if (rc == NET_LOOKUP_BUSY) {
        return;
    }

    if (rc != 0) {
        dvxLog("lookup: %s", netErrorText(rc));
        return;
    }

    connectStart(addr, HTTP_PORT);
}

netLookupCancel(&lk) gives up a lookup that has not ended. The HTTP library and the connection library’s Telnet both look names up this way.

14.4.2. Blocking Calls on a Task

On a main-loop program’s task, the ordinary blocking calls make the simplest code. Each one waits while DVX runs on, and the receive timeout keeps a silent server from holding the loop for ever (struct timeval is in sys/time.h):

// On a main-loop program's own task: each call that waits lets DVX run.
static bool blockingGet(const char *host, char *buf, int32_t size) {
    static const char request[] = "GET / HTTP/1.0\r\n\r\n";
    struct addrinfo   hints;
    struct addrinfo  *res  = NULL;
    struct timeval    wait = { WAIT_SECONDS, 0 };
    int               fd   = -1;
    ssize_t           n    = -1;

    memset(&hints, 0, sizeof(hints));
    hints.ai_family   = AF_INET;
    hints.ai_socktype = SOCK_STREAM;

    if (getaddrinfo(host, "http", &hints, &res) != 0) {
        return false;
    }

    fd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);

    if (fd >= 0 && setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &wait, sizeof(wait)) == 0 && connect(fd, res->ai_addr, res->ai_addrlen) == 0 && send(fd, request, sizeof(request) - 1, 0) > 0) {
        n = recv(fd, buf, (size_t)size - 1, 0);
    }

    if (n < 0) {
        dvxLog("%s: %s", host, netErrorText(errno));
    }

    if (fd >= 0) {
        close(fd);
    }

    freeaddrinfo(res);
    buf[n > 0 ? n : 0] = '\0';
    return n > 0;
}

14.5. Network Settings and Status

netGetStatus(&status) fills a NetStatusT with the network’s state as Control Panel shows it: state (NetStoppedE, NetNoDriverE, NetConfiguringE while it waits for a DHCP server, or NetUpE), message, the state in plain words (such as “No packet driver found: load one (for example NE2000.COM) before DVX”), the address, mask, gateway, and name servers, the host name, the packet driver’s name, interrupt, and hardware address, the packet and byte counters, rxDropped (frames lost while DVX was too busy to take them), and the number of open sockets. netStateText(state) gives the words for a state. When a connection fails, the network’s state is often the real reason, and httpget shows it.

netStart starts the network with the saved settings and returns NET_OK or a NET_ERR_ code; the socket calls call it themselves, so a program rarely does. netStop and netRestart end the connections of every socket of every program: leave them to Control Panel. A program that edits the settings itself has NetConfigT and the netConfig calls (“Network Settings and Status” in the DVX C Library Reference).

14.6. The HTTP Library

The HTTP library is an HTTP/1.1 client: a GET, a POST, or any other method, to a web server, run a step at a time. A request is a state machine over a non-blocking socket. httpPoll does one bounded piece of the work, starting the name lookup or the connection, sending, or reading at most 4 KB of the reply, and returns; it never waits. A program calls it from a Timer or from its main loop until the request ends, and draws its progress in between. DVX’s package client uses it to reach the package server.

Call Does

httpCreate(method, url)

Makes a request (HttpT); NULL when memory runs out. A bad address is found out by httpStart.

httpHeaderAdd(h, name, value)

Adds a header to send, before the start.

httpBodySet(h, data, len, type), httpBodyFile(h, path, type)

A body to send: a copy of data, or a file sent a piece at a time as the socket takes it.

httpSaveTo(h, path, resume)

The reply’s body to a file instead of memory (Section 14.6.1).

httpTimeoutSet(h, ms)

Gives up after ms without progress: connecting, or between pieces of the reply. HTTP_TIMEOUT_DEFAULT_MS (30 seconds) to start with.

httpStart(h, nowMs)

Starts the request; false, with the reason in httpMessage, for an address that is not http://.

httpPoll(h, nowMs)

Does the next piece: HttpBusyE (call again), HttpDoneE (the server answered), or HttpFailedE (no answer).

httpProgress(h, &done, &total)

Bytes of the body so far, and the whole, HTTP_SIZE_UNKNOWN until the server says (Content-Length).

httpStatus, httpHeader(h, name), httpBody(h, &len), httpUrl

The reply: its status, a header by name in any case ("" when it has none), the body in memory, and the address it came from after redirects.

httpMessage(h)

Why the request failed.

httpFree(h)

Frees the request, closing its connection; at any time, finished or not.

The nowMs the calls take is a millisecond clock, which may wrap; the library only compares differences. Pass PLATFORM_TICKS_TO_MS(platformClock()) (dvxPlat.h), DVX’s clock in milliseconds; the connection and transfer libraries take the same.

Any status is an answer: httpPoll returns HttpDoneE for a 404 or a 500 as for a 200, and the program decides what the status means. HttpFailedE is for no answer at all: an address that is not http://, a name that cannot be found, no connection, silence past the timeout, a reply that is not HTTP, or one cut short. httpMessage then says which, in a sentence a program can show, such as “Cannot find example.org on the network.”

The reply’s body may come with a Content-Length, in chunks, or until the server closes the connection; the library handles all three. It goes to memory, up to HTTP_MEMORY_MAX (1 MB), past which the request fails, so save anything larger to a file. Once httpPoll has returned HttpDoneE, httpBody returns the body ended with a NUL, its length in len (a body may hold NUL bytes of its own); the text belongs to the request and goes when httpFree frees it. A body that went to a file is "". Before the request is done, and after a failure, httpBody returns "" with len 0. Redirects (301, 302, 303, 307, and 308) are followed, HTTP_REDIRECTS_MAX (5) at most; after a 303, and after a 301 or 302 of a POST, the request goes on as a GET without its body, as browsers do. A redirect to an https:// address fails.

Each request sends Host, a User-Agent of DVX/ and the version, Accept-Encoding: identity (the library does not decompress), and Connection: close: a request is one connection, and a redirect makes a new one. A body gets its Content-Length, and so does any POST or PUT. To send JSON, quote the text that goes into it with jsonQuote (Section 14.7). httpBodySet copies the body, so a buffer on the stack will do, and httpFree accepts NULL:

static HttpT *postName(const char *name) {
    char   quoted[NAME_QUOTED_MAX];
    char   body[BODY_MAX];
    HttpT *h = httpCreate("POST", "http://example.com/api/greet");

    jsonQuote(name, quoted, (int32_t)sizeof(quoted));
    snprintf(body, sizeof(body), "{\"name\": %s}", quoted);

    if (!h || !httpBodySet(h, body, (int32_t)strlen(body), "application/json") || !httpStart(h, nowMs())) {
        httpFree(h);
        return NULL;
    }

    return h;   // httpPoll it from a Timer, as for a GET
}

14.6.1. Downloading to a File

httpSaveTo(h, path, resume) sends the body to a file instead of memory. Only a 2xx reply’s body is written to it: any other status’s body, an error page, goes to memory and leaves the file as it was. With resume, a file already there is kept and the rest asked for with a Range request. A server that resumes answers 206, and the rest is appended; one that will not answers 200, and the file starts again; 416 means the file was already whole, and it is left alone. httpProgress counts the part already there, so a progress bar does not start from nothing:

static HttpT *download(const char *url, const char *path) {
    HttpT *h = httpCreate("GET", url);

    if (!h) {
        return NULL;
    }

    httpSaveTo(h, path, true);
    httpTimeoutSet(h, DOWNLOAD_TIMEOUT_MS);
    httpStart(h, nowMs());
    return h;   // httpPoll it to the end, then check the file
}

Nothing on the way protects a download (Section 14.9). Check a file before you use it, by its size and a hash from a source you trust: the cryptography library has SHA-256 (secSha256, Section 15.7), and DVX’s package library checks every package that way, with a signature over it.

14.7. The JSON Library

The JSON library reads a JSON document into memory and finds values in it by path; it also quotes text for JSON of your own. jsonParse(text, len, err, errSize) reads len bytes and returns the document, a JsonDocT, or NULL when the text is not JSON, nests arrays and objects deeper than JSON_DEPTH_MAX (64), or memory runs out. err then holds the reason with its line, such as “Line 3: expected , or } in an object”; JSON_ERR_MAX bytes hold any. jsonFree frees the document and everything in it.

A document is a set of nodes numbered from 0, the root, and every value is one: a node is an int32_t. A member of an object is the node of its value, with the member’s name attached. The calls that read a node accept any node, including JSON_NO_NODE (-1), which stands for one that is not there, and give a harmless answer for the wrong kind:

Call Returns

jsonType(doc, node)

JsonNullE, JsonBoolE, JsonNumberE, JsonStringE, JsonArrayE, or JsonObjectE; JsonNoneE for no node.

jsonText(doc, node)

A string’s text; "" for anything else.

jsonNumber(doc, node)

A number’s value, a double; 0 for anything else.

jsonBool(doc, node)

True for true only.

jsonCount(doc, node)

An array’s items or an object’s members; 0 for anything else.

jsonChild(doc, node, index)

Item or member index, in document order; JSON_NO_NODE past the end.

jsonKey(doc, node)

A member’s name; "" for anything else.

The text jsonText and jsonKey return belongs to the document and lasts until jsonFree. Strings are decoded into DVX’s text, code page 437: the escapes, \u escapes (surrogate pairs included), and UTF-8 sequences become their characters, and a character code page 437 does not have becomes ?. Numbers are double, exact for integers up to 253.

jsonFind(doc, node, path) finds a node from another by a path of member names joined by ., with [index] for an array’s items: packages[3].version, [0], or "" for the node itself. Members match by exact name, the first when a name repeats; a name holding . or [ is reached with jsonChild and jsonKey instead. A path that leads nowhere gives JSON_NO_NODE, so a chain of lookups needs no checks until the end.

There is no writer for whole documents: build them with snprintf. jsonQuote(text, out, outSize) writes text as a JSON string, quotes and escapes included, with control characters and every character from 128 up as \u escapes of its Unicode code point, so the result is plain ASCII. Like snprintf, it returns the length it needs without the NUL and cuts the text short when outSize is smaller, so a call with a NULL buffer and size 0 measures.

14.8. The HTTP Get Program

httpget asks a web server for an address and shows the reply: its status, content type, and size in the status bar, the body as text, and, when the body is JSON, the root’s fields in a list, with a Path box that shows the value a path leads to as you type it. It is a callback-only program, and a Timer widget runs the request.

The HTTP Get window with its address box, Get button, Reply box, JSON list, Path box, and status bar
Figure 22. HTTP Get as it starts, ready to fetch its address
#include "dvxApp.h"
#include "dvxNet.h"
#include "dvxPlat.h"
#include "dvxWgt.h"
#include "shellApp.h"
#include "http.h"
#include "json.h"
#include "box/box.h"
#include "button/button.h"
#include "label/label.h"
#include "listView/listView.h"
#include "statusBar/statBar.h"
#include "textInput/textInpt.h"
#include "timer/timer.h"

dvxNet.h is for the network’s status; the HTTP and JSON libraries need only their own headers. The program keeps its widgets, the request under way (sRequest, NULL when there is none), and the parsed reply in statics:

static DxeAppContextT *sCtx     = NULL;
static WindowT        *sWin     = NULL;
static WidgetT        *sUrl     = NULL;    // the Address box
static WidgetT        *sGet     = NULL;    // Get, or Stop while a request runs
static WidgetT        *sBody    = NULL;    // the reply, as text
static WidgetT        *sFields  = NULL;    // a JSON reply's top-level fields
static WidgetT        *sPath    = NULL;
static WidgetT        *sValue   = NULL;    // what the path leads to
static WidgetT        *sStatus  = NULL;
static WidgetT        *sTimer   = NULL;    // runs while there is a request
static HttpT          *sRequest = NULL;    // the request under way, or NULL
static JsonDocT       *sDoc     = NULL;    // the reply, parsed, when it is JSON
static uint32_t        sShown   = 0;       // body bytes the status bar shows

The window is an Address row with a Get button, a Reply frame holding a read-only text area, a JSON frame holding the list, the Path box, and a label for its value, and a status bar. Get is the window’s default button, so Enter in the Address box starts a request (Section 7.7.1). The last widget is the Timer:

bar     = wgtStatusBar(root);
sStatus = bar ? wgtLabel(bar, "") : NULL;
sTimer  = wgtTimer(root, HTTPGET_POLL_MS, true);

if (!sStatus || !sTimer) {
    closeWindow();
    return -1;
}

// A new Timer runs at once: this one waits for a request
wgtTimerStop(sTimer);
sTimer->onChange = onTick;

wgtTimer(parent, intervalMs, repeat) makes a Timer, a widget with nothing to show, which calls its onChange callback every intervalMs milliseconds. A new Timer is running, so this one is stopped at once, to wait for a request. The interval is as short as the Timer allows: DVX’s clock advances with the BIOS timer tick, about 18 times a second, so the Timer calls onTick at most that often, whatever the interval.

14.8.1. Starting and Running the Request

// A GET of the address typed, run by the Timer from here on.  httpStart
// fails only for an address that is not http://: everything else that can
// go wrong is found out while the request runs.
static void startRequest(void) {
    clearReply();
    sRequest = httpCreate("GET", wgtGetText(sUrl));

    if (!sRequest || !httpHeaderAdd(sRequest, "Accept", HTTPGET_ACCEPT)) {
        endRequest();
        showStatus("There is not enough memory");
        return;
    }

    if (!httpStart(sRequest, nowMs())) {
        wgtSetText(sBody, httpMessage(sRequest));
        endRequest();
        showStatus("Not an http:// address");
        return;
    }

    sShown = 0;
    wgtSetText(sGet, "&Stop");
    showStatus("Connecting");
    wgtTimerStart(sTimer);
}

httpCreate copies the method and the address. httpHeaderAdd asks for JSON (a server may ignore it). httpStart checks the address and returns at once; nothing has gone over the network yet. From here the Timer runs the request, and nowMs is the clock both calls take:

// The millisecond clock the http library runs on (it may wrap)
static uint32_t nowMs(void) {
    return PLATFORM_TICKS_TO_MS(platformClock());
}
// The Timer's tick: one step of the request.  httpPoll does a bounded
// piece of the work and returns, so the tick is short and DVX goes on.
static void onTick(WidgetT *w) {
    (void)w;

    switch (httpPoll(sRequest, nowMs())) {
        case HttpBusyE:
            showProgress();
            return;

        case HttpDoneE:
            showReply();
            break;

        case HttpFailedE:
            showFailure();
            break;
    }

    endRequest();
}

Each tick is one httpPoll, and each httpPoll returns at once. The first ticks start the name lookup and look at it; later ones start the connection, see it made, send the request, and read the reply, at most 4 KB a tick. At 18 ticks a second that is at most about 70 KB a second, which is plenty for a JSON reply; a program that downloads large files calls httpPoll more often, from a main loop or several times a tick. Between ticks DVX runs as usual: the window moves, the other programs run, and the user can type in the Path box or press Stop.

// The bytes of the body so far, when they changed: the total too when
// the server said it (Content-Length).
static void showProgress(void) {
    uint32_t done  = 0;
    uint32_t total = 0;

    httpProgress(sRequest, &done, &total);

    if (done == sShown) {
        return;
    }

    sShown = done;

    if (total == HTTP_SIZE_UNKNOWN) {
        showStatus("%" PRIu32 " bytes", done);
    } else {
        showStatus("%" PRIu32 " of %" PRIu32 " bytes", done, total);
    }
}

While the request is busy, the status bar counts the body’s bytes, and their total when the server sent a Content-Length. It changes the text only when the count changed: wgtSetText with the same text does nothing, but formatting it 18 times a second for nothing would be waste.

14.8.2. The End of a Request

When httpPoll stops saying busy, the server has answered or the request has failed. Either way, endRequest follows:

// The end of a request, finished or not: the Timer stops, and httpFree
// closes the connection (or drops the name lookup) and frees the rest.
static void endRequest(void) {
    wgtTimerStop(sTimer);
    httpFree(sRequest);
    sRequest = NULL;
    wgtSetText(sGet, "&Get");
}

httpFree closes the connection if it is still open, or drops the name lookup if it was still going, and frees everything the request held, the reply included. The same function serves Stop, which gives a request up at any point:

// Get starts a request; while one runs, the same button is Stop.
static void onGetClick(WidgetT *w) {
    (void)w;

    if (!sRequest) {
        startRequest();
        return;
    }

    endRequest();
    showStatus("Stopped");
}

A failure shows httpMessage in the Reply box, with the network’s own state under it, which often explains the failure better: a name that “cannot be found” because no packet driver was loaded, or because DHCP has not answered yet.

// No answer: httpMessage says why, and the network's own state (no packet
// driver, still waiting for DHCP) often says why underneath.
static void showFailure(void) {
    NetStatusT net;
    char       text[HTTPGET_PROBLEM_MAX];

    netGetStatus(&net);
    snprintf(text, sizeof(text), "%s\n\nNetwork: %s", httpMessage(sRequest), net.message);
    wgtSetText(sBody, text);
    showStatus("No answer");
}

An answer shows its status line in the status bar and its body in the Reply box, and is parsed as JSON. A text area holds at most what its buffer holds (64 KB for this one) and stops at a NUL byte, so httpget shows text replies, not files:

// The server answered (with any status: 404 is an answer too).  The body
// is in memory, NUL-terminated; it is shown, and parsed as JSON.
static void showReply(void) {
    int32_t     len  = 0;
    const char *body = httpBody(sRequest, &len);
    char        err[JSON_ERR_MAX];

    showStatus("%" PRId32 " %.*s, %" PRId32 " bytes", httpStatus(sRequest), HTTPGET_TYPE_SHOWN, httpHeader(sRequest, HTTPGET_TYPE_FIELD), len);
    wgtSetText(sBody, body);
    sDoc = jsonParse(body, len, err, (int32_t)sizeof(err));

    if (!sDoc) {
        char text[JSON_ERR_MAX + HTTPGET_NAME_MAX];

        snprintf(text, sizeof(text), "Not JSON: %s", err);
        wgtSetText(sValue, text);
        return;
    }

    fillFields();
    showPathValue();
}

httpHeader copies a header’s value into a buffer of the request, good until the next httpHeader call; %.*s keeps a long content type from widening the status bar.

14.8.3. Showing the JSON

A document that parsed fills the list with its root’s fields, the members of an object or the items of an array, each with its type and value:

// The root's fields (an object's members, or an array's items) in the
// list: name, type, and value.
static void fillFields(void) {
    bool    object = jsonType(sDoc, HTTPGET_JSON_ROOT) == JsonObjectE;
    int32_t count  = jsonCount(sDoc, HTTPGET_JSON_ROOT);

    for (int32_t i = 0; i < count; i++) {
        int32_t node = jsonChild(sDoc, HTTPGET_JSON_ROOT, i);
        char    name[HTTPGET_NAME_MAX];
        char    value[HTTPGET_CELL_MAX];

        if (object) {
            snprintf(name, sizeof(name), "%s", jsonKey(sDoc, node));
        } else {
            snprintf(name, sizeof(name), "[%" PRId32 "]", i);
        }

        describeNode(node, value, (int32_t)sizeof(value));
        wgtListViewAddItem(sFields, name);
        wgtListViewSetCell(sFields, i, HTTPGET_COL_TYPE, sTypeNames[jsonType(sDoc, node)]);
        wgtListViewSetCell(sFields, i, HTTPGET_COL_VALUE, value);
    }
}
// A node's value in words: a string's text, a number, true or false, or
// how many items or fields an array or object holds.  A null, or a node
// that is not there, has no value beyond its type.
static void describeNode(int32_t node, char *out, int32_t outSize) {
    switch (jsonType(sDoc, node)) {
        case JsonStringE:
            snprintf(out, (size_t)outSize, "%s", jsonText(sDoc, node));
            break;

        case JsonNumberE:
            snprintf(out, (size_t)outSize, "%g", jsonNumber(sDoc, node));
            break;

        case JsonBoolE:
            snprintf(out, (size_t)outSize, "%s", jsonBool(sDoc, node) ? "true" : "false");
            break;

        case JsonArrayE:
            snprintf(out, (size_t)outSize, "%" PRId32 " items", jsonCount(sDoc, node));
            break;

        case JsonObjectE:
            snprintf(out, (size_t)outSize, "%" PRId32 " fields", jsonCount(sDoc, node));
            break;

        case JsonNullE:
        case JsonNoneE:
            out[0] = '\0';
            break;
    }
}

describeNode asks for the node’s type and reads it with the call that fits. The names of the types come from a table indexed by JsonTypeE, beside the list’s columns (a ListView keeps the pointer to its columns, so they are static):

// The list's columns: the ListView keeps the pointer, so they are static.
static const ListViewColT sColumns[HTTPGET_COLS] = {
    { "Name",  wgtChars(HTTPGET_NAME_CHARS), ListViewAlignLeftE },
    { "Type",  wgtChars(HTTPGET_TYPE_CHARS), ListViewAlignLeftE },
    { "Value", HTTPGET_COL_AUTO,             ListViewAlignLeftE }
};

// What each JsonTypeE is called on the screen
static const char *const sTypeNames[] = {
    [JsonNoneE]   = "not found",
    [JsonNullE]   = "null",
    [JsonBoolE]   = "boolean",
    [JsonNumberE] = "number",
    [JsonStringE] = "string",
    [JsonArrayE]  = "array",
    [JsonObjectE] = "object"
};

The Path box’s onChange fires at every edit, and calls showPathValue, so the value follows the typing. A path that leads nowhere is JSON_NO_NODE, which every call accepts, so there is nothing to check:

// What the Path box leads to from the root, as it is typed.
static void showPathValue(void) {
    char    value[HTTPGET_SHOWN_MAX];
    char    text[HTTPGET_SHOWN_MAX + HTTPGET_NAME_MAX];
    int32_t node;

    if (!sDoc) {
        return;
    }

    node = jsonFind(sDoc, HTTPGET_JSON_ROOT, wgtGetText(sPath));
    describeNode(node, value, (int32_t)sizeof(value));
    snprintf(text, sizeof(text), "%s %s", sTypeNames[jsonType(sDoc, node)], value);
    wgtSetText(sValue, text);
}

14.8.4. Trying It

Build and install httpget as in Section 1.6. It needs a network card with its packet driver loaded before DVX (in an emulator, an emulated NE2000 with NE2000.COM), and a server that answers plain http://. The address it starts with, http://httpbin.org/json, returns a small JSON document whose path slideshow.slides[1].title leads to a string. To test without the Internet, serve a folder from the build machine with any web server, such as python3 -m http.server 8000 in a folder that holds a .json file, and fetch http://address:8000/file.json, where address is the build machine’s address as DVX’s network sees it.

14.9. Things to Know

  • Nothing DVX sends over the network is encrypted. Anyone on the path can read an HTTP request and its reply, and change them. Send nothing secret, and check what you download, by a hash or a signature from a source you trust, before you use it. The secure link (Section 15.6) encrypts a connection to a computer that speaks it, not to a web server. A program that must send a secret to a server of its own can seal it itself with the cryptography library, as the package client does for an account (pkgSeal.h: the server proves its key with a signature the program already trusts, and each request and reply is sealed with keys the two agree on).

  • The network is a resource every program shares: 32 sockets and 16 TCP connections in all, and one ring of received frames. Close sockets when you are done with them, and keep callbacks short, or every program’s connections slow down.

  • When the stack stops (while a DOS program runs, or for netStop and netRestart), every socket’s connection ends, and DVX tells no program. The descriptor stays the program’s until the program closes it, so its number is never given to a file or socket opened meanwhile, and every other call on it fails with ENETDOWN. Treat ENETDOWN as the end of the connection, close the socket, and open a new one. Handle errors on every call, not only when connecting.

  • A request in progress is the program’s to finish or free. Free it in onClose, as httpget does: DVX closes the sockets of a program that ends, but the memory it left allocated stays allocated (Section 3.9).

  • DVX BASIC programs reach the same libraries through net.bas, http.bas, and json.bas (the DVX BASIC Programming Guide). A library of yours that hands a socket to BASIC code can use the networking library’s BASIC handles (“Networking from BASIC” in the DVX C Library Reference).

Chapter 15. Serial Ports, Modems, and Secure Links

The serial port was the PC’s way to reach other computers long before network cards, and DVX supports it in layers: an interrupt-driven UART driver, a connection library that puts a serial line, a modem, a secure link, and Telnet behind one interface, a packet layer and an encrypted secure link over it, file transfers by XMODEM, YMODEM, and ZMODEM, and the Terminal control, an ANSI terminal in a widget. DVX’s Terminal program is built from these parts. This chapter goes up the layers and builds chat, a two-way chat over a serial line, plain or encrypted. The reference describes every call (“Serial Stack” in the DVX C Library Reference and the sections after it).

15.1. The Layers

Library Header Does Comes with

serial

rs232.h

The UART driver: COM1 to COM4, interrupt-driven, with ring buffers and flow control.

Every DVX

conn

conn.h

Connections: a serial line, a modem with a dialer, a secure link, or Telnet, opened and polled the same way.

Communications

seclink

packet.h, secLink.h

Reliable packets over a byte stream, and the encrypted, authenticated secure link over them.

Communications

crypto

security.h, secHash.h, secCurve.h

Hashes, keys, encryption, signatures, and random numbers.

Every DVX

xfer

xfer.h

File transfers by XMODEM, XMODEM-1K, YMODEM, and ZMODEM, over any byte stream.

Communications

AnsiTerm

ansiTerm/ansiTerm.h

The Terminal control: an ANSI terminal screen with scrollback.

Communications

Communications is an optional part of DVX, chosen in Setup or added with Software; Telnet, and the secure link over a network, also need Networking (Chapter 14). A program that calls a library the computer does not have does not start: DVX names the function it could not find. Every header is on the include path of every project, so a program includes conn.h or rs232.h by name, and links nothing: DVX loads each library the first time a program needs it.

15.2. The UART Driver

The serial library drives the PC’s UARTs directly. rs232Open(com, bps, dataBits, parity, stopBits, handshake) opens one of four ports, RS232_COM1 (0) to RS232_COM4 (3), and returns RS232_SUCCESS (0) or a negative RS232_ERR_ code. Opening does a good deal:

  • It takes the port’s I/O address from the BIOS’s table of serial ports (at 0040:0000), unless rs232SetBase(com, base) has given one before: that is the way to open a port the BIOS does not list, or lists wrong (rs232SetBase refuses a port that is open, with RS232_ERR_ALREADY_OPEN). A port with no address, or an address where nothing answers, cannot be opened (RS232_ERR_NO_UART).

  • It probes the UART: an 8250, a 16450, a 16550 (whose FIFO is not reliable), or a 16550A, whose 16-byte FIFO it turns on, interrupting at 8 bytes received. rs232GetUartType says which it found.

  • It finds the port’s interrupt line by making the UART interrupt and watching the interrupt controller, and falls back to IRQ 4 for COM1 and COM3 and IRQ 3 for COM2 and COM4. rs232GetIrq says which it uses, and rs232SetIrq moves an open port to another.

  • It installs one interrupt handler for all open ports, which moves bytes between each UART and two 2048-byte rings, one for each direction, in memory locked against paging.

  • It sets the line and raises DTR and RTS.

The speed must be one a UART’s divisor gives exactly: 50, 75, 110, 150, 300, 600, 1200, 1800, 2400, 3600, 4800, 7200, 9600, 19200, 38400, 57600, or 115200 bps; any other is RS232_ERR_INVALID_BPS. Data bits are 5 to 8, parity 'N', 'O', 'E', 'M', or 'S' (in either case), and stop bits 1 or 2.

The handshake is the flow control: RS232_HANDSHAKE_NONE, RS232_HANDSHAKE_XONXOFF, RS232_HANDSHAKE_RTSCTS, or RS232_HANDSHAKE_DTRDSR. The interrupt handler does it by itself: when the receive ring is 80% full, it tells the other side to stop, and when it has drained to 20%, to go on. Without flow control, bytes that arrive while the ring is full are lost, so a program that may fall behind (and every program falls behind while DVX is busy) uses RTS/CTS when the cable and the other end have it.

Reading and writing never wait, with one exception:

  • rs232Read(com, buf, len) takes up to len bytes from the receive ring and returns how many, 0 when there are none.

  • rs232WriteBuf(com, data, len) puts up to len bytes in the transmit ring and returns how many fit; the interrupt handler sends them.

  • rs232Write(com, data, len) is the exception: it writes straight to the UART and waits for each byte to leave, which at 9600 bps is about a millisecond a byte, with all of DVX stopped. Use rs232WriteBuf.

The modem lines are there too: rs232GetDcd, rs232GetCts, rs232GetDsr, and the ring indicator bit of rs232GetMsr; rs232SetDtr and rs232SetRts; rs232GetLsr for the errors seen on received data (overrun, parity, framing, break); and rs232SetBreak to hold a break, which the caller times. rs232Close(com) lets the port and its interrupt go, but leaves DTR and RTS as they are, so that closing a port never hangs up a modem by accident. To hang up, drop DTR first:

static const char probe[] = "ATI\r";
char              buf[READ_MAX];
int32_t           n;
int32_t           rc = rs232Open(RS232_COM2, 19200, 8, 'N', 1, RS232_HANDSHAKE_RTSCTS);

if (rc != RS232_SUCCESS) {
    dvxLog("COM2 did not open: %" PRId32, rc);
    return;
}

dvxLog("COM2: UART type %" PRId32 ", IRQ %" PRId32, rs232GetUartType(RS232_COM2), rs232GetIrq(RS232_COM2));
rs232WriteBuf(RS232_COM2, probe, (int32_t)sizeof(probe) - 1);

// Later, from a Timer or a loop: what has come in (0 when nothing has)
n = rs232Read(RS232_COM2, buf, (int32_t)sizeof(buf));

// At the end: drop DTR to hang a modem up, then let the port go
rs232SetDtr(RS232_COM2, false);
rs232Close(RS232_COM2);

A port is one program’s at a time: opening one that is open, in your program or another (Terminal, say), fails with RS232_ERR_ALREADY_OPEN. An open port belongs to the program that opened it: when the program ends, however it ends (by Task Manager, or by a fault, too), DVX closes a port it left open, so the next program can open it. Close the port yourself on every way out that your code sees all the same, as soon as you are done with it.

15.3. Connections

Most programs do not use the UART driver directly. The connection library gives one interface to four kinds of byte stream, and every call in it returns at once:

Type Behavior

ConnSerialE

A COM port with the given speed, data bits, parity, stop bits, and flow control. Open at once.

ConnModemE

The COM port, then the modem’s init string (it waits for OK), then the dial prefix and the phone number. CONNECT opens the connection; BUSY, NO ANSWER, and NO CARRIER dial again after redialDelay seconds, up to redialCount more times; NO DIAL TONE and ERROR end it. Once the carrier (DCD) has been seen, losing it ends the connection. What the modem says is also delivered as received data. An empty phone number opens the port for typing AT commands yourself.

ConnSecureE

The secure link (Section 15.6): the key exchange runs in the background, authenticated when a passphrase is set, and only encrypted, authenticated data on channel 0 is delivered. With host empty it runs on the COM port, which may not use XON/XOFF flow control (the frames carry those bytes as data); with host set it runs over a TCP connection to host and tcpPort.

ConnTelnetE

TCP to host and tcpPort, with Telnet’s option negotiation: the host may echo and suppress go-ahead, binary both ways, terminal type ANSI, and the window size from connSetWindowSize (80 x 25 until then). Needs Networking.

A connection is a ConnT from connCreate(). Fill a ConnConfigT from connConfigDefaults (a serial line on COM1 at 9600 bps, 8 data bits, no parity, 1 stop bit, no flow control; for a modem ATZ, ATDT, three redials 30 seconds apart; TCP port 23) and change what you need. Then:

  • connOpen(c, &cfg, nowMs) copies the settings and starts: it opens the port, starts dialing, the key exchange, or the name lookup, and returns CONN_OK, or CONN_ERR_PARAM, CONN_ERR_PORT, or CONN_ERR_NO_NET (Telnet or a network secure link without Networking). connErrorText puts a code in words; connStatus has the details.

  • connPoll(c, nowMs) moves the connection along: dials, runs the key exchange, moves received bytes into the connection’s 16 KB receive buffer, sends what is queued, and runs the timers. Call it as often as you can, on every pass of a loop or every frame. nowMs is the millisecond clock of Section 14.6, PLATFORM_TICKS_TO_MS(platformClock()).

  • connRead(c, buf, max) takes up to max received bytes and returns how many. connWrite(c, data, len) queues bytes in the 8 KB send buffer and returns how many it took: 0 while the connection is not open, or when the buffer is full. connPending says how many queued bytes have not been sent.

  • connState(c) is ConnClosedE, ConnOpeningE (dialing, or the key exchange), or ConnOpenE. connStatus(c) says in words what is happening, or why the connection ended (“Connected to COM1 at 9600 bps”, “Dialing 555-0100 (try 1 of 4)”, “COM2 could not be opened: it is already in use”), and connStatusSerial(c) changes whenever that text does, so a program can tell when to show it again.

  • connClose(c) ends the connection; for a serial line or a modem, it drops DTR, which makes a modem hang up, and closes the port. connDestroy(c) closes and frees.

  • connSendBreak(c, nowMs) holds a break for 300 ms on a serial or modem line (connCanBreak(type) says whether a type can); connTypeAvailable(type) is false for Telnet when Networking is not installed.

A modem that dials, for example:

ConnConfigT cfg;

connConfigDefaults(&cfg);
cfg.type        = ConnModemE;
cfg.comPort     = RS232_COM2;
cfg.bps         = 57600;
cfg.flow        = RS232_HANDSHAKE_RTSCTS;
cfg.redialCount = 5;
snprintf(cfg.initString, sizeof(cfg.initString), "%s", "AT&F");
snprintf(cfg.phone, sizeof(cfg.phone), "%s", "555-0100");
connOpen(conn, &cfg, nowMs());

A host name, for Telnet or a network secure link, is looked up while connPoll runs, with the networking library’s lookup that does not wait (Section 14.4.1). Every failure after connOpen (a name not found, a refused connection, no answer in 30 seconds, a lost line) ends the connection with the reason in connStatus.

15.4. The Chat Program

chat talks with another computer over a serial line. You choose the port and its speed, and whether to use the secure link, and connect; what the other computer sends appears in a transcript, a Terminal control, and what you type in the Message box goes to it when you press Enter. The other end can be another DVX running chat, or any terminal program at the same speed.

The Chat window with the port and speed lists, a Connect button, the secure link check box and passphrase box, the terminal, and a message box with a Send button
Figure 23. Chat before it connects: the port, speed, and secure link settings above the Terminal control

Unlike httpget, chat is a main-loop program (Section 3.4). A connection has to be polled all the time it is open, and a loop that polls on every pass, as fast as DVX gives it turns, keeps up with a fast line better than a Timer’s 18 ticks a second:

SHELL_APP_DESCRIPTOR(
    .name          = CHAT_TITLE,
    .hasMainLoop   = true,
    .multiInstance = false,
    .stackSize     = SHELL_STACK_DEFAULT,
    .priority      = TS_PRIORITY_NORMAL
);
static AppContextT *sAc          = NULL;
static WindowT     *sWin         = NULL;
static ConnT       *sConn        = NULL;
static WidgetT     *sPortList    = NULL;
static WidgetT     *sSpeedList   = NULL;
static WidgetT     *sConnectBtn  = NULL;    // Connect, or Disconnect
static WidgetT     *sSecureBox   = NULL;
static WidgetT     *sPassBox     = NULL;
static WidgetT     *sTerm        = NULL;    // the transcript
static WidgetT     *sMessageBox  = NULL;
static WidgetT     *sSendBtn     = NULL;
static uint32_t     sShownSerial = 0;       // connStatusSerial of the news last shown
static bool         sQuit        = false;
static bool         sPeerLine    = false;   // the other side's text left a line unfinished
static bool         sAfterCr     = false;   // the last byte received was a CR

// The speeds offered: the Speed list is made from this table
static const int32_t sSpeeds[] = { 1200, 2400, 9600, 19200, 38400, 57600, 115200 };

15.4.1. The Window

The Connection frame has the Port and Speed lists and the Connect button on one line, and the Secure link check box and the passphrase on the next. The lists are filled from the numbers, not from a second table of names, so an item’s index is all the program needs:

// The Connection frame: the port, its speed, and Connect on one line; the
// secure link and its passphrase on the next.  The lists are filled from
// RS232_NUM_PORTS and sSpeeds, so an item's index is its port number, or
// its speed's index in sSpeeds.
static bool buildConnection(WidgetT *root) {
    WidgetT *frame = wgtFrame(root, "Connection");
    WidgetT *top   = frame ? wgtHBox(frame) : NULL;
    WidgetT *under = top ? wgtHBox(frame) : NULL;
    char     name[CHAT_NAME_MAX];

    sPortList   = (under && wgtLabel(top, "&Port:")) ? wgtDropdown(top) : NULL;
    sSpeedList  = (sPortList && wgtLabel(top, "&Speed:")) ? wgtDropdown(top) : NULL;
    sConnectBtn = sSpeedList ? wgtButton(top, "&Connect") : NULL;
    sSecureBox  = sConnectBtn ? wgtCheckbox(under, "S&ecure link") : NULL;
    sPassBox    = (sSecureBox && wgtLabel(under, "Passp&hrase:")) ? wgtPasswordInput(under, CONN_PASS_MAX - 1) : NULL;

    if (!sPassBox) {
        return false;
    }

    top->padding         = wgtPixels(0);
    under->padding       = wgtPixels(0);
    sConnectBtn->minW    = wgtChars(CHAT_BUTTON_CHARS);
    sConnectBtn->onClick = onConnectClick;

    for (int32_t port = RS232_COM1; port < RS232_NUM_PORTS; port++) {
        snprintf(name, sizeof(name), "COM%" PRId32, port + CHAT_COM_BASE);
        wgtDropdownAddItem(sPortList, name);
    }

    for (int32_t i = 0; i < DVX_ARRAY_LEN(sSpeeds); i++) {
        snprintf(name, sizeof(name), "%" PRId32, sSpeeds[i]);
        wgtDropdownAddItem(sSpeedList, name);

        if (sSpeeds[i] == CHAT_DEFAULT_BPS) {
            wgtDropdownSetSelected(sSpeedList, i);
        }
    }

    wgtDropdownSetSelected(sPortList, RS232_COM1);
    return true;
}

CONN_PASS_MAX includes the terminating NUL, so the passphrase box takes one character less. Under the frame is the transcript, and under it the Message box and Send, the window’s default button, disabled until a connection is open. appMain builds them:

// The Terminal control is a widget module of its own: without it,
// dvxAnsiTermApi() is NULL, and wgtAnsiTerm would call through NULL.
if (!dvxAnsiTermApi()) {
    dvxErrorBox(sAc, CHAT_TITLE, CHAT_NO_TERMINAL);
    return -1;
}

sConn = connCreate();
sWin  = sConn ? dvxCreateWindowCentered(sAc, CHAT_TITLE, CHAT_WIN_W, CHAT_WIN_H, false) : NULL;

if (!sWin) {
    connDestroy(sConn);
    return -1;
}

sWin->onClose = onClose;
root          = wgtInitWindow(sAc, sWin);
sTerm         = (root && buildConnection(root)) ? wgtAnsiTerm(root, CHAT_TERM_COLS, CHAT_TERM_ROWS) : NULL;

if (!sTerm || !buildMessage(root)) {
    endChat();
    return -1;
}

dvxFitWindow(sAc, sWin);
showLine(CHAT_COLOR_NOTE, CHAT_PREFIX_NOTE, CHAT_WELCOME);

The Terminal control is a widget module, and a widget module can be missing or fail to load, so chat checks for its API table before it calls wgtAnsiTerm, which would call through a NULL table (Section 5.2). The connection exists before the window and is closed after it. The window is made a fixed size and fitted to its widgets: the transcript is 60 columns by 15 rows, whatever the window’s size.

15.4.2. The Loop

while (!sQuit) {
    pollConnection();
    tsYield();
}

endChat();
return 0;
// One pass of the loop's work: move the connection along, show what has
// arrived, and report the connection's news when there is some.
static void pollConnection(void) {
    uint8_t buf[CHAT_READ_MAX];

    connPoll(sConn, nowMs());

    for (int32_t n = connRead(sConn, buf, CHAT_READ_MAX); n > 0; n = connRead(sConn, buf, CHAT_READ_MAX)) {
        showIncoming(buf, n);
    }

    if (connStatusSerial(sConn) != sShownSerial) {
        showState();
    }
}

Each pass calls connPoll, takes everything that has arrived, and shows it, and then tsYield lets DVX run. When the connection’s status text has changed, the loop shows it:

// The connection's status changed: show the news, and set the controls
// for the new state (the settings only while closed, Send only while open).
static void showState(void) {
    ConnStateE state  = connState(sConn);
    bool       closed = state == ConnClosedE;

    sShownSerial = connStatusSerial(sConn);
    showLine(CHAT_COLOR_NOTE, CHAT_PREFIX_NOTE, connStatus(sConn));
    wgtSetText(sConnectBtn, closed ? "&Connect" : "&Disconnect");
    wgtSetEnabled(sPortList, closed);
    wgtSetEnabled(sSpeedList, closed);
    wgtSetEnabled(sSecureBox, closed);
    wgtSetEnabled(sPassBox, closed);
    wgtSetEnabled(sSendBtn, state == ConnOpenE);
}

Every change of state comes with a new status, so this one function keeps the controls right: the settings can change only while the connection is closed, Send works only while it is open, and Connect becomes Disconnect while a connection is open or opening.

15.4.3. Line Ends and Colors

What arrives goes to the transcript with wgtAnsiTermWrite, which interprets it as a terminal does. One thing needs care: computers end lines differently. A terminal program sends CR when the user presses Enter, another chat sends CR LF, and some systems send LF alone. A terminal moves to the start of the line on CR and down a line on LF, so chat turns each kind of line end into CR LF. The LF of a CR LF is dropped, even when its CR came in the read before:

// Bytes from the other computer, into the transcript.  A terminal program
// ends a line with CR, another Chat with CR LF, some systems with LF:
// each becomes the transcript's CR LF.  Anything else goes through as it
// is, ANSI escape sequences included.
static void showIncoming(const uint8_t *data, int32_t len) {
    uint8_t out[CHAT_READ_MAX * 2];
    int32_t n = 0;

    for (int32_t i = 0; i < len; i++) {
        bool lfOfCrLf = data[i] == CHAT_LF && sAfterCr;

        sAfterCr = data[i] == CHAT_CR;

        if (lfOfCrLf) {
            continue;
        }

        if (data[i] == CHAT_CR || data[i] == CHAT_LF) {
            out[n++]  = CHAT_CR;
            out[n++]  = CHAT_LF;
            sPeerLine = false;
        } else {
            out[n++]  = data[i];
            sPeerLine = true;
        }
    }

    wgtAnsiTermWrite(sTerm, out, n);
}

Everything else goes through as it is, ANSI escape sequences included, so a line the other side colors arrives in color. chat colors its own lines that way, with SGR sequences (ESC [1;33m is bright yellow, ESC [0m the default), and starts each on a line of its own:

#define CHAT_TITLE        "Chat"
#define CHAT_WIN_W        480                       // before it is fitted to its widgets
#define CHAT_WIN_H        400
#define CHAT_TERM_COLS    60
#define CHAT_TERM_ROWS    15
#define CHAT_BUTTON_CHARS 12                        // Connect and Disconnect both fit
#define CHAT_COM_BASE     1                         // RS232_COM1 (0) is COM1
#define CHAT_DEFAULT_BPS  9600
#define CHAT_MESSAGE_MAX  200                       // characters in a message
#define CHAT_LINE_MAX     (CHAT_MESSAGE_MAX + 32)   // a line sent or shown, with its line end and colors
#define CHAT_READ_MAX     256                       // bytes taken from the connection at a time
#define CHAT_NAME_MAX     16                        // "COM4", "115200"
#define CHAT_NO_TERMINAL  "Chat needs the Terminal control, which comes with the Communications part of DVX."
#define CHAT_WELCOME      "Choose a port and its speed, then click Connect."
#define CHAT_NO_ROOM      "The message did not all fit in the send buffer."
#define CHAT_ESC          "\x1b"
#define CHAT_COLOR_SENT   CHAT_ESC "[1;33m"         // bright yellow: what you sent
#define CHAT_COLOR_NOTE   CHAT_ESC "[0;36m"         // cyan: news of the connection
#define CHAT_COLOR_RESET  CHAT_ESC "[0m"
#define CHAT_NEWLINE      "\r\n"
#define CHAT_CR           '\r'
#define CHAT_LF           '\n'
#define CHAT_PREFIX_SENT  "> "
#define CHAT_PREFIX_NOTE  "* "
// A line of our own in the transcript, in color: a message we sent, or
// news of the connection.  It starts on a line of its own.
static void showLine(const char *color, const char *prefix, const char *text) {
    char    line[CHAT_LINE_MAX];
    int32_t len = (int32_t)snprintf(line, sizeof(line), "%s%s%s%s" CHAT_COLOR_RESET CHAT_NEWLINE, sPeerLine ? CHAT_NEWLINE : "", color, prefix, text);

    sPeerLine = false;
    wgtAnsiTermWrite(sTerm, (const uint8_t *)line, DVX_MIN(len, (int32_t)sizeof(line) - 1));
}

15.4.4. Connecting and Sending

The callbacks run on the shell’s task, between turns of the loop. They call the connection library directly: its calls never wait, and only one task runs at a time, so the loop is never in the middle of a call when a callback runs.

// Connect opens a connection with the settings chosen; while one is open,
// or opening, the same button closes it.  connOpen only starts the work:
// the loop's connPoll carries it on, and showState reports how it went.
static void onConnectClick(WidgetT *w) {
    ConnConfigT cfg;
    int32_t     rc;

    (void)w;

    if (connState(sConn) != ConnClosedE) {
        connClose(sConn);
        return;
    }

    connConfigDefaults(&cfg);
    cfg.comPort = RS232_COM1 + wgtDropdownGetSelected(sPortList);
    cfg.bps     = sSpeeds[wgtDropdownGetSelected(sSpeedList)];

    if (wgtCheckboxIsChecked(sSecureBox)) {
        cfg.type = ConnSecureE;
        snprintf(cfg.passphrase, sizeof(cfg.passphrase), "%s", wgtGetText(sPassBox));
    }

    rc = connOpen(sConn, &cfg, nowMs());

    // connOpen copied the settings: wipe this copy of the passphrase
    secSecureZero(cfg.passphrase, (int)sizeof(cfg.passphrase));

    if (rc == CONN_OK) {
        wgtSetFocused(sMessageBox);
    }
}

connOpen returns before anything has happened on the line: a serial line is open at once, but a secure link has its key exchange still to run. The loop’s connPoll carries it on, and the new status arrives through showState. A failure to open the port also arrives that way, with the reason. The settings were copied, so the copy of the passphrase on the stack is wiped with secSecureZero from the cryptography library, which the compiler cannot leave out as it can a memset of memory about to go out of scope. The connection library wipes its own copy once the key exchange has it.

// Send queues the message with a CR LF line end and shows it in the
// transcript.  connWrite takes what fits in the connection's send buffer
// and returns at once; connPoll sends it on.
static void onSendClick(WidgetT *w) {
    const char *text = wgtGetText(sMessageBox);
    char        line[CHAT_LINE_MAX];
    int32_t     len;

    (void)w;

    if (text[0] == '\0') {
        return;
    }

    len = (int32_t)snprintf(line, sizeof(line), "%s" CHAT_NEWLINE, text);

    if (connWrite(sConn, (const uint8_t *)line, len) < len) {
        showLine(CHAT_COLOR_NOTE, CHAT_PREFIX_NOTE, CHAT_NO_ROOM);
        return;
    }

    showLine(CHAT_COLOR_SENT, CHAT_PREFIX_SENT, text);
    wgtSetText(sMessageBox, "");
}

connWrite queues the line and returns. A line longer than the room left in the send buffer is not all taken: chat says so rather than pretend it was sent. On a serial line that does not happen at chat speeds; on a secure link whose other end has stopped answering, the buffer fills and stays full.

15.4.5. The End

The window’s onClose only sets sQuit, as in ticker (Section 3.7); the loop ends at its next turn and calls endChat, which closes the connection before the window goes:

// The end, normal or not: the connection closes (DTR drops, so a modem
// hangs up, and the port is free for the next program) and is freed; then
// the window goes.
static void endChat(void) {
    connDestroy(sConn);
    dvxDestroyWindow(sAc, sWin);
}

connDestroy closes the port, so the next program, or the next chat, can open it. If chat is ended by force (End Task, or a fault), none of this runs, and DVX closes the connection, and with it the port, as the program ends (Section 15.2).

15.4.6. Trying It

Build and install chat as in Section 1.6. It needs a serial line with something at the other end:

  • Two PCs running DVX, joined by a null-modem cable, each running chat at the same speed. Without flow control, a three-wire cable is enough.

  • One PC running chat, and a terminal program on another computer at the same speed, 8 data bits, no parity, and 1 stop bit (minicom or screen on Linux, for example).

  • Emulators: two copies of an emulator whose serial ports are joined, such as DOSBox’s nullmodem serial setting, which joins two DOSBox windows over TCP.

For the secure link, both ends must run chat with Secure link checked and the same passphrase (or both none), and connect within 30 seconds of each other: the side that waits longer gives up (“The host did not answer the secure link”). A passphrase that does not match ends both with “The passphrase does not match the host’s”. A plain chat facing a secure one shows the secure one’s frames as noise.

15.5. The Terminal Control

The Terminal control, the AnsiTerm widget, is a terminal screen: wgtAnsiTerm(parent, cols, rows) makes one of cols by rows characters (80 by 25 for 0, at most 512 each way), in a fixed-pitch font (a proportional font is replaced by the system font), with the code page 437 characters and the 16 CGA colors of a DOS text screen. It understands the ANSI and VT100 sequences DOS bulletin boards use: cursor movement, erasing, scrolling regions, colors (SGR), a few DEC private modes, and ANSI music. Lines that scroll off the top go to a scrollback of 500 lines (wgtAnsiTermSetScrollback changes it), which the user pages through with Shift+PgUp and Shift+PgDn or the mouse wheel. The user can select text with the mouse and copy it with Ctrl+C.

wgtAnsiTermWrite(w, data, len) feeds bytes to the terminal. It parses up to 4 KB at once and keeps the rest of a longer text, in order, to parse 4 KB a frame, so a long text never holds DVX up. wgtAnsiTermClear clears the screen.

A terminal can also run a link itself. wgtAnsiTermSetComm(w, ctx, readFn, writeFn) gives it a read function and a write function, each called with ctx. DVX polls every terminal once a frame, and the terminal then calls readFn and parses what it returns; what the user types (arrows and the other special keys as VT100 sequences), a paste with Ctrl+V, and the terminal’s answers to a host’s questions go to writeFn. With a connection, that is a whole terminal program in two small functions, and no loop or Timer of its own:

// DVX polls the terminal once a frame, and the terminal calls this to read:
// move the connection along first, then hand over what it received.
static int32_t termRead(void *ctx, uint8_t *buf, int32_t len) {
    ConnT *conn = (ConnT *)ctx;

    connPoll(conn, nowMs());
    return connRead(conn, buf, len);
}


// What the user types and pastes, and the terminal's answers to the host
static int32_t termWrite(void *ctx, const uint8_t *data, int32_t len) {
    return connWrite((ConnT *)ctx, data, len);
}
wgtAnsiTermSetComm(term, conn, termRead, termWrite);
wgtAnsiTermSetScrollback(term, SCROLLBACK_LINES);

The terminal also has events of its own, which a C program gets through the widget’s onEvent(w, name, args, argc): ANSITERM_EVT_BELL for a BEL character, ANSITERM_EVT_MUSIC with an ANSI music string to play (the music library’s musicMmlPlay plays it; Chapter 16), and, when there is no write function, ANSITERM_EVT_SEND with the bytes the terminal has for the host, for a program that sends them its own way. The bytes are a string value that may hold NUL bytes, so its length comes from wgtValueLen:

// With no write callback, what the terminal has for the host comes here
static void onTermEvent(WidgetT *w, const char *name, WgtValueT *args, int32_t argc) {
    (void)w;

    if (strcmp(name, ANSITERM_EVT_SEND) == 0 && argc == 1) {
        dvxLog("%" PRId32 " bytes for the host", wgtValueLen(&args[0]));
    }
}

Later features are in a second table, dvxAnsiTermExApi(), which is NULL with an older widget: wgtAnsiTermCopy copies the selection to the clipboard (for an Edit menu), wgtAnsiTermSetPalette replaces the 16 colors, and wgtAnsiTermSetMusic turns ANSI music off, which makes ESC [M always Delete Line.

A terminal keeps Tab and Enter for itself, since a host may want them, so the user cannot Tab out of one, and a window’s default button does not take Enter from it. Give the widget after it an access key: in chat, Alt+M moves to the Message box.

15.6. Packets and the Secure Link

The secure link is an encrypted, authenticated connection between two programs that both speak it: two copies of a DVX program, or DVX and the SDK’s secproxy on a Linux computer. It has two layers, both in the seclink library. Most programs use it through the connection library’s ConnSecureE, as chat does; this section is for programs that use it directly.

15.6.1. The Packet Layer

The packet layer (packet.h) makes a serial line reliable. It cuts the data into packets of up to PKT_MAX_PAYLOAD (255) bytes, frames each with a flag byte and byte stuffing, as HDLC does, checks it with a CRC-16, and sends it again until the other side acknowledges it, with up to PKT_DEFAULT_WINDOW (4) packets in flight (1 to PKT_MAX_WINDOW, 8). pktOpen(com, window, callback, ctx) runs over an open COM port, one connection a port; pktOpenStream runs over any byte stream given as a PktStreamT of non-blocking read and write functions, such as a TCP socket. pktPoll receives, delivers each good packet, in order, to the callback, and resends what was lost; call it often. It reports the link lost (PKT_ERR_DISCONNECTED) when the other side has been silent for PKT_LINK_TIMEOUT_MS (30 seconds) with packets waiting. pktSend(conn, data, len, false) queues a packet or returns PKT_ERR_TX_FULL when the window is full.

The secure link (secLink.h) runs over the packet layer. secLinkOpen(com, bps, dataBits, parity, stopBits, handshake, callback, ctx) opens the COM port and the packet layer together (XON/XOFF flow control cannot work: the frames carry those bytes as data); secLinkOpenStream(&stream, callback, ctx) runs over a byte stream, which stays yours to close. Then:

  • secLinkSetPassphrase(link, pass) sets the passphrase both sides must share, or clears it (NULL or ""). Only its SHA-256 is kept.

  • secLinkHandshakeStart(link) starts the key exchange, and secLinkHandshakeStep(link) moves it on, a slice at a time: SECLINK_PENDING while it runs, SECLINK_SUCCESS once the link is ready, or the error that ended it (SECLINK_ERR_AUTH for a passphrase that does not match, SECLINK_ERR_HANDSHAKE, SECLINK_ERR_TIMEOUT). The time limit is the caller’s to keep (SECLINK_HANDSHAKE_TIMEOUT_MS, 30 seconds, is the library’s own).

  • secLinkSend(link, data, len, channel, encrypt, false) sends up to SECLINK_MAX_PAYLOAD (237) bytes on a channel from 0 to 127, sealed when encrypt is true (which needs a finished key exchange). It returns SECLINK_ERR_SEND at once when the window is full.

  • secLinkPoll(link) receives: it checks and decrypts each frame and hands the plaintext to the callback with its channel and whether it came encrypted. A frame that fails its check is dropped and counted (secLinkGetDropped).

  • secLinkClose(link) wipes the keys and closes the packet layer and, for secLinkOpen, the port.

The library also has calls that wait: secLinkHandshake, which runs the whole exchange, secLinkSend with block true, secLinkSendBuf, and the packet layer’s pktSend with block true and pktWaitSpace. They wait by polling in a loop, up to 30 seconds (the handshake), or until 15 seconds pass without an acknowledgment (PKT_SEND_TIMEOUT_MS, a send), and between two polls they give the other tasks a turn (pktYield, which in DVX is tsYield; pktSetYield replaces it). On a program’s own task, DVX runs on while they wait, as it does through a blocking socket call (Section 14.4). In a callback, on the shell’s task, the other programs' tasks run, but DVX itself does not: nothing paints and no input is read until the call returns. So a callback-only program uses the step and the non-blocking forms:

// Plaintext of each frame that arrived and checked out
static void onFrame(void *ctx, const uint8_t *data, int len, uint8_t channel, bool encrypted) {
    (void)ctx;

    if (encrypted && channel == MY_CHANNEL) {
        dvxLog("%d bytes on my channel: %02X...", len, data[0]);
    }
}
uint32_t started = nowMs();

sLink = secLinkOpen(RS232_COM1, 115200, 8, 'N', 1, RS232_HANDSHAKE_RTSCTS, onFrame, NULL);

if (!sLink || secLinkSetPassphrase(sLink, passphrase) != SECLINK_SUCCESS || secLinkHandshakeStart(sLink) < 0) {
    secLinkClose(sLink);
    sLink = NULL;
    return;
}

// Each pass of the loop, or each Timer tick:
if (!secLinkIsReady(sLink)) {
    int rc = secLinkHandshakeStep(sLink);

    if (rc < 0 || (rc == SECLINK_PENDING && nowMs() - started > SECLINK_HANDSHAKE_TIMEOUT_MS)) {
        secLinkClose(sLink);
        sLink = NULL;
    }
} else if (secLinkPoll(sLink) < 0) {
    secLinkClose(sLink);
    sLink = NULL;
} else if (secLinkSend(sLink, data, len, MY_CHANNEL, true, false) == SECLINK_ERR_SEND) {
    // the window is full: send it again next time
}

The SDK’s bin/secproxy is the far end that DVX’s Terminal program uses: a Linux program that takes one secure link, from a serial device (--serial /dev/ttyS0, with --speed and --rtscts) or on a TCP port (2323 unless told otherwise), runs the key exchange (with the passphrase from --passphrase-file or the DVX_SECLINK_PASSPHRASE environment variable, never the command line), waits for the user to press Enter, and then relays channel 0 to a Telnet host as plain Telnet. secproxy.md in the SDK describes it. A program of yours can be its client with ConnSecureE: a terminal program’s data is relayed as it is, so whatever you send on channel 0 reaches the Telnet host.

15.6.3. What the Secure Link Protects

The key exchange is X25519. Each side sends a fresh public key, both compute the shared secret, and HKDF-SHA256, salted with the SHA-256 of the passphrase (or 32 zero bytes without one), makes a key for each direction and a confirmation key. Each side then sends an HMAC, under the confirmation key, of both sides' opening messages, public keys included, which the other checks: a different passphrase, a passphrase on one side only, or a changed key fails the exchange with SECLINK_ERR_AUTH. Every encrypted frame is sealed with XChaCha20-Poly1305 under its direction’s key, with a 64-bit frame counter, never sent, as its nonce, and the frame’s type and channel bytes authenticated with it. What that gives you:

  • Secrecy and integrity of the data. No one on the line can read an encrypted frame, and a frame changed, replayed, or inserted fails its check and is dropped.

  • Forward secrecy. Each side’s X25519 secret is wiped as soon as the keys are made, so a later theft of a computer does not open recorded sessions.

  • Authentication, with a passphrase. The same passphrase on both sides proves each side knows it, which shuts out a man in the middle. A side with a passphrase refuses a side without one, so an attacker cannot talk it down to none.

  • No downgrade of a channel. Once the first key exchange is done, clear frames are accepted only on channels marked plaintext with secLinkSetChannelPlain, even after a reset or a failed re-key, which someone on the line can cause.

What it does not give you:

  • Authentication without a passphrase. Without one, the link is encrypted but anyone who can sit in the middle of the line can run two key exchanges and relay, reading everything.

  • Protection for a weak passphrase. The passphrase is hashed once, not stretched, and anyone who takes part in a key exchange, an attacker in the middle included, gets a confirmation value against which guesses can be tested offline, as fast as a computer can run SHA-256 and HKDF. Use a long random passphrase.

  • Privacy of the traffic’s shape. The packet layer’s framing, sequence numbers, and CRCs, each frame’s type and channel, and the lengths and timing of frames are visible on the line.

  • Anything outside the link. Clear frames sent before the first key exchange, and channels marked plaintext, are not protected. secproxy relays to its Telnet host in the clear: the link covers only the line between DVX and the proxy.

  • Service. Anyone on the line can garble it, reset the packet layer, or cut it.

  • The computer itself. DVX has one address space and no memory protection (Section 3.1): any program running on the computer can read another’s keys and data.

  • Keys better than their random numbers. The keys come from the cryptography library’s generator (Section 15.7), which the shell seeds. On a CPU without a time-stamp counter, the hardware entropy it gathers alone is guessable; the seed file and the user’s input timings are what make the keys unpredictable there.

And none of it applies to the network: there is no TLS, and an HTTP request is not encrypted (Section 14.9).

15.7. The Cryptography Library

The cryptography library (crypto) has the primitives the secure link and the package library are built from, for programs and libraries of yours:

Header Calls For

secHash.h

secSha256, secHmacSha256, secHkdf, and incremental forms; secConstTimeEqual

SHA-256, HMAC-SHA256, and HKDF-SHA256; comparing MACs in time that does not depend on where they differ.

secCurve.h

secX25519, secX25519PublicKey, the SecX25519JobT calls; secAeadLock, secAeadUnlock; secEd25519KeyPair, secEd25519Sign, secEd25519Check

X25519 key exchange, XChaCha20-Poly1305 authenticated encryption, and Ed25519 signatures (from Monocypher).

security.h

secRngBytes, secRngAddEntropy; secSecureZero; secDh…​, secCipher…​

Random bytes, wiping key material, and, for older uses, 1024-bit Diffie-Hellman and XTEA in CTR mode.

For new code, agree on keys with X25519 and HKDF, encrypt with XChaCha20-Poly1305, and sign with Ed25519. XTEA in CTR mode encrypts but does not authenticate: a changed byte decrypts to a wrong byte without a word, so use it only under a MAC. secAeadLock encrypts in place and writes a 16-byte tag; secAeadUnlock decrypts only when the tag checks out, and otherwise leaves the data alone. A key and nonce pair must never seal two different messages, and a random 24-byte nonce is safe:

uint8_t key[SEC_AEAD_KEY_SIZE];
uint8_t nonce[SEC_AEAD_NONCE_SIZE];
uint8_t tag[SEC_AEAD_TAG_SIZE];

secRngBytes(key, (int32_t)sizeof(key));
secRngBytes(nonce, (int32_t)sizeof(nonce));
secAeadLock(key, nonce, NULL, 0, data, len, tag);

// ... keep or send the nonce, data, and tag; later:
if (!secAeadUnlock(key, nonce, NULL, 0, data, len, tag)) {
    dvxLog("changed, or the wrong key: data is as it was");
}

secSecureZero(key, (int)sizeof(key));

Public-key work is slow on a 486: an X25519 takes about a sixth of a second, a Diffie-Hellman exponentiation about a second, and either one stops DVX for that long. A program that must stay responsive does it a slice at a time, secX25519JobStart and secX25519JobStep (about 20 ms a step) or secDhStep, from a Timer or a loop, as the secure link does. Hashing and symmetric encryption are fast enough to do at once.

secRngBytes comes from a SHA-256 generator over an entropy pool. The shell seeds it: it loads SECLINK.RND, a seed file in the user folder, when the library loads (and writes it again at once, so a seed is never used twice), feeds it the timings of the user’s keys and mouse, and saves a fresh seed when DVX exits. A program can add entropy of its own with secRngAddEntropy. Wipe every buffer that held a key with secSecureZero when you are done with it.

15.8. File Transfers

The transfer library sends and receives files by XMODEM, XMODEM-1K, YMODEM, and ZMODEM over any byte stream, and, like the rest, never waits. A transfer is an XferT from xferCreate(); it reads and writes through an XferIoT, three functions and a context: read (the bytes there are, 0 when none), write (the bytes taken), and pending (bytes taken but not yet sent, or NULL). Over a connection, they are the connection’s calls:

static int32_t xferRead(void *ctx, uint8_t *buf, int32_t maxLen) {
    return connRead((ConnT *)ctx, buf, maxLen);
}


static int32_t xferWrite(void *ctx, const uint8_t *data, int32_t len) {
    return connWrite((ConnT *)ctx, data, len);
}


static int32_t xferPending(void *ctx) {
    return connPending((const ConnT *)ctx);
}

xferStartReceive(x, proto, &io, &opt, target, nowMs) starts receiving: into the file target for XMODEM, into the folder target for YMODEM and ZMODEM, which name their files. xferStartSend(x, proto, &io, &opt, paths, count, nowMs) sends count files (XMODEM sends the first). Both copy the XferIoT, and return false, with the reason in the progress’s message, when the transfer cannot start. XferOptionsT (from xferOptionsDefaults) says what to do with a file that already exists, how much a ZMODEM sender may send before it waits (rxWindow), whether ZMODEM escapes every control character, and whether a ZMODEM sender asks to resume partial files:

XferIoT      io = { conn, xferRead, xferWrite, xferPending };
XferOptionsT opt;

xferOptionsDefaults(&opt);
opt.exists = XferExistRenameE;
sXfer      = xferCreate();

if (sXfer && !xferStartReceive(sXfer, XferZmodemE, &io, &opt, folder, nowMs())) {
    dvxLog("%s", xferProgress(sXfer)->message);
}

Then xferPoll(x, nowMs) moves it along, on every pass or every frame, and returns its status: XferRunningE, XferAskingE, XferDoneE, XferFailedE, or XferCancelledE. While a transfer runs, it reads the connection: the program keeps calling connPoll, but not connRead. xferProgress(x) gives an XferProgressT for a progress window: the file’s name, its size and the bytes done, the batch’s, the retries, and, at the end, a message saying how it ended. xferCancel sends the cancel sequence and ends the transfer:

XferStatusE st;

connPoll(conn, nowMs());
st = xferPoll(sXfer, nowMs());

if (st != XferRunningE && st != XferAskingE) {
    dvxLog("%s", xferProgress(sXfer)->message);
    xferDestroy(sXfer);
    sXfer = NULL;
}

A file that arrives is never written over silently. Its name is made safe first (no path, no drive, no DOS device name; a long name where the disk takes them, an 8.3 name where it does not), and when a file of that name exists, exists decides: rename the new one (NAME~1.EXT), resume a shorter one (ZMODEM), overwrite, skip, or ask. Asking pauses the transfer in XferAskingE, with the two sizes in the progress, until the program calls xferAnswer(x, action, nowMs) with the user’s choice. A failed or canceled XMODEM or YMODEM download deletes its partial file; ZMODEM keeps it, so the transfer can be resumed. Files are limited to 2 GB.

A terminal starts a ZMODEM download by itself when the host starts sending: feed each received byte to xferDetectFeed(&detect, byte) (an XferDetectT zeroed to start), and when it returns true, start a ZMODEM receive. On a serial line without flow control, set rxWindow to what the line’s buffers hold, so a slow frame on your side never loses data; Terminal uses 2 KB.

15.9. Things to Know

  • Serial ports, packet connections, secure links, connections, and file transfers belong to the program that opened them, and DVX closes what a program leaves open when it ends, however it ends. (A secure link’s port is let go and its keys are wiped.) Close them in your program’s own way out all the same (onClose, the end of the loop).

  • Every call in these libraries that takes a nowMs takes the same clock, PLATFORM_TICKS_TO_MS(platformClock()), which wraps; they compare only differences.

  • Poll often. The UART’s rings hold 2 KB each way: at 115200 bps that is less than a fifth of a second of data, and without flow control what does not fit is lost.

  • A DVX BASIC program has the same libraries in conn.bas and xfer.bas, and the Terminal control in its toolbox (the DVX BASIC Programming Guide).

Chapter 16. Sound and Music

DVX plays sound on whatever the computer has: a Sound Blaster, a Windows Sound System card, a Gravis UltraSound, a DAC on the printer port, the PC speaker, or nothing at all. Two libraries do it. The sound library (audio.h, AUDIO.LIB) drives the hardware and mixes: samples, tones, note queues, streams a program feeds, volume, the FM chip, and the MIDI port. The music library (music.h, MUSIC.LIB) is built on it and plays music: tracker modules, MIDI files, live MIDI, tunes in QBasic’s music macro language, and long WAV and VOC files. Any number of programs play at once through one mixer, and everything a program opened is stopped and released when it ends, however it ends. This chapter’s example, jukebox, plays a module and a MIDI file and four kinds of sound effect. Chapter 17 puts the same calls to work in a game.

The Jukebox window with its music controls showing the module playing, its sound effect buttons, volume and pan sliders, and the sound device in the status bar
Figure 24. Jukebox playing its module

16.1. The Sound Hardware

The sound library loads with DVX, but it looks for hardware only when the first program opens sound. Its drivers are modules of their own, *.DRV files in LIBS\KPUNCH\AUDIO\DRIVERS, and it tries them in order: the one DVX.INI names in [audio] driver (unless that is auto, the default), then the others from the highest priority down. The first whose hardware is found and starts playing is kept, and the others are unloaded:

Driver Priority Device

wss

110 (AUDIO_PRIORITY_CODEC)

A Windows Sound System card (an AD1848 codec or one like it), tried before the Sound Blaster mode the same card often has.

sb

100 (AUDIO_PRIORITY_CARD)

The Sound Blaster family, from the first Sound Blaster to the Sound Blaster 16, at the port, interrupt, and DMA channels the BLASTER variable gives (without it, a Sound Blaster 16 is looked for at 220h and 240h).

gus

90 (AUDIO_PRIORITY_GUS)

A Gravis UltraSound, after a Sound Blaster beside it, which then plays the sampled sound and leaves the UltraSound’s voices to music.

lpt

50 (AUDIO_PRIORITY_LPT)

A DAC on the printer port: a Covox, a Disney Sound Source, or a Stereo-on-1.

speaker

20 (AUDIO_PRIORITY_SPEAKER)

The PC speaker. It plays tones only, on the timer chip, unless [audio] speakerPcm is true; then it plays everything, at a large cost in processor time.

null

0 (AUDIO_PRIORITY_NULL)

No device. It plays nothing, but voices run their course and end as on a real card.

Beside the device, the library opens the synthesizers it finds, one of each kind: the FM chip of an AdLib or a Sound Blaster (opl, an OPL2 or OPL3), a wavetable synthesizer (awe for a Sound Blaster AWE32 or AWE64, gus or guswt for an UltraSound), and the MPU-401 MIDI port (mpu401, looked for only when [audio] midi or midiIn is mpu401, since an unused port would play nothing).

All sound goes through one mixer. It works in 16-bit integers at the rate the device achieved (22,050 Hz unless [audio] rate asks for another), resamples every sound to that rate by linear interpolation, and clips the sum. It runs from the card’s own interrupt, or from the timer service for a device without one, so sound keeps playing however busy the programs are. At most a limited number of voices play at once: [audio] voices, 16 by default (AUDIO_VOICES_DEFAULT) and at most 32 (AUDIO_VOICES_MAX). When no voice has played for 10 seconds, the output closes so that it costs no processor time, and the next sound opens it again; an open stream or note queue counts as playing, even while it is silent (Section 16.5).

All of this is the user’s to choose, on the Sounds page of Control Panel; a program takes the device it gets. Ask about it with audioGetInfo:

[cols="2,5",options="header"]

AudioInfoT member Holds

driver, description

The driver’s short name (sb, speaker, null) and a description for people, such as “Sound Blaster 16 (DSP 4.05)”; empty while no device runs.

rate, bits, channels

What the device plays: the rate it achieved (a card may not give exactly the rate asked for), 8 or 16 bits, mono or stereo.

voiceLimit

Voices mixed at once.

running

A device is running: some sound context is open.

hasDac, hasTone, hasSynth

It plays sampled sound; it plays tones on a hardware tone generator (the PC speaker); it has a hardware synthesizer.

canRecord, recSources

It records, and from which inputs (Section 16.12).

audioGetStats gives the mixer’s counters since the device started (AudioStatsT): blocks and frames mixed, stream frames that were due before they were written (underruns), samples clipped, voices dropped by the voice limit, and the voices playing now, in all of DVX.

16.2. The Jukebox Program

jukebox is a callback-only program: a window of widgets whose buttons play sound. Its Music frame loads a tune and plays, pauses, stops, and loops it, with its own volume; its Sound Effects frame plays a recorded sound (Coin), a burst of noise (Boom), a short tune (Jingle), and a sound the program makes as it plays (Siren), at a volume and a pan the user sets. A Timer widget shows the music’s position four times a second, and the status bar names the device. The program has no loop: the shell’s idle time keeps the sound fed (Section 16.13).

Two tunes come with it, as files of its DATA folder, and the Coin sound travels inside jukebox.app as a resource:

SDK_DIR ?= ../../../../bin/sdk
KIND     = app
NAME     = jukebox
DATA     = jukebox.mod theme.mid

include $(SDK_DIR)/sdk.mk
icon32      icon    icon32.bmp
name        text    "Jukebox"
author      text    "Scott Duensing"
description text    "Music and sound effects"
coin        binary  coin.wav

DATA lists files that make package copies into a DATA folder beside the module, where the program finds them with shellDataPath (Chapter 10). JUKEBOX.MOD is a short four-channel module made for this book, and THEME.MID is the game template’s MIDI tune. The headers it needs are audio.h and music.h, each in a folder of its own on the include path:

#include "dvxApp.h"
#include "dvxDlg.h"
#include "dvxPlat.h"
#include "dvxRes.h"
#include "dvxWgt.h"
#include "shellApp.h"
#include "audio.h"
#include "music.h"
#include "box/box.h"
#include "button/button.h"
#include "checkbox/checkbox.h"
#include "label/label.h"
#include "slider/slider.h"
#include "statusBar/statBar.h"
#include "timer/timer.h"

#include <inttypes.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>

16.2.1. Opening Sound

// The program's sound context, and the Coin sound from the program's own
// file, decoded once.  On a computer without sound the null driver plays
// nothing, and all of this works the same.
static void soundOpen(void) {
    DvxResHandleT *res  = dvxResOpen(sCtx->appPath);
    uint32_t       size = 0;
    void          *coin = res ? dvxResRead(res, JUKEBOX_RES_COIN, &size) : NULL;

    dvxResClose(res);
    sAudio = audioOpen();

    if (sAudio) {
        int32_t rc = audioSampleLoadMem(sAudio, coin, size, &sCoin);

        if (rc != AUDIO_OK) {
            dvxLog("jukebox: the Coin sound: %s", audioErrorText(rc));
        }

        audioSetEndFn(sAudio, onSoundEnd, NULL);
    }

    free(coin);
}

audioOpen() gives the program an audio context, an AudioCtxT. Everything the program plays belongs to a context, and the first context opened in DVX starts the sound device. A program may open several; each belongs to the program that was running when it was opened, and DVX closes them all when that program ends, normally, by End Task, or by a fault, so no sound outlives its program. audioClose(ctx) stops every voice of the context and frees its samples, streams, and note queues; it accepts NULL.

audioOpen returns NULL only when memory runs out or no driver at all could start. A computer without sound hardware gets the null driver, so the program opens sound, plays, and hears its end notifications as everywhere else; there is nothing to test for. Jukebox still checks, and builds no Sound Effects frame without a context.

The functions that return int32_t return AUDIO_OK (0) or a voice ID (above 0) on success and a negative AUDIO_ERR_* code on failure, such as AUDIO_ERR_NO_VOICE (the voice limit was reached and this sound would have been the quietest) or AUDIO_ERR_FORMAT (not a WAV or VOC file). audioErrorText(code) says what a code means. Every call takes NULL for its context, sample, stream, note queue, or recording: it does nothing and returns AUDIO_ERR_ARG (AUDIO_ERR_VOICE for a voice of no context), 0, or false. None of the sound library’s functions may be called from an interrupt, a timer callback included, except the few of the FM chip, the MIDI port, and the wavetable synthesizer that say so.

Jukebox closes what it opened when its window closes, which ends the sound at once rather than when the shell reaps the program:

// Everything the program opened is closed for it when it ends anyway;
// closing it here ends the sound at once.  audioClose frees the
// context's samples, streams, and note queues with it.
static void onClose(WindowT *win) {
    tuneFree();
    audioClose(sAudio);
    sAudio  = NULL;
    sCoin   = NULL;
    sJingle = NULL;
    sSiren  = NULL;
    dvxDestroyWindow(sAc, win);
    sWin = NULL;
}

16.3. Samples and Voices

A sample is a sound in memory, an AudioSampleT, loaded once and played as often as wanted:

  • audioSampleLoad(ctx, path, &sample) reads a WAV or VOC file. WAV files hold uncompressed PCM, 8-bit unsigned or 16-bit signed, mono or stereo, at 4,000 to 48,000 Hz (AUDIO_RATE_MIN to AUDIO_RATE_MAX); the other chunks are skipped. VOC files may hold 8-bit and 16-bit sound blocks, silence, and the extended blocks. A compressed file gives AUDIO_ERR_UNSUPPORTED and a damaged one AUDIO_ERR_CORRUPT.

  • audioSampleLoadMem(ctx, data, size, &sample) reads the same from memory: a resource, as Jukebox’s Coin sound is.

  • audioSampleCreate(ctx, pcm, frames, &fmt, &sample) makes one from raw PCM frames in the AudioFormatT fmt: rate in Hz, bits 8 (unsigned) or 16 (signed, little-endian), and channels 1 or 2 (stereo interleaved left, right).

A sample is decoded into memory as 16-bit frames and pinned there for the mixer’s interrupt, so an 8-bit file takes twice its size in memory for as long as the sample exists. Keep samples for short sounds; play a long recording with the music library, which reads a WAV or VOC file from the disk as it plays (Section 16.8). audioSampleInfo gives a sample’s format and length in frames, and audioSampleFree stops the voices playing it and frees it (audioClose frees all of a context’s).

// A sample plays on a new voice each time, so quick presses overlap.
static void onCoin(WidgetT *w) {
    (void)w;

    int32_t voice = audioPlay(sCoin, AUDIO_VOLUME_MAX, wgtSliderGetValue(sPan), false);

    if (voice < 0) {
        dvxLog("jukebox: coin: %s", audioErrorText(voice));
    }
}

audioPlay(sample, volume, pan, loop) starts the sample on a new voice and returns the voice’s ID; each press of Coin starts another voice, so quick presses overlap. A voice is one sound playing, and its ID is the handle on it until it ends:

Setting Range

volume

0 (silent) to AUDIO_VOLUME_MAX (256).

pan

AUDIO_PAN_LEFT (-256) to AUDIO_PAN_RIGHT (256). The center, AUDIO_PAN_CENTER, plays at full volume on both sides; panning turns the other side down.

pitch

A speed in 256ths: AUDIO_PITCH_NORMAL (256) plays at the recorded speed, twice that an octave higher; AUDIO_PITCH_MIN (64) to AUDIO_PITCH_MAX (1024).

audioVoiceSetVolume, audioVoiceSetPan, audioVoiceSetPitch, audioVoicePause, and audioVoiceStop change a playing voice, and audioVoiceIsPlaying asks whether it still plays; each takes the context and the voice ID, and gives AUDIO_ERR_VOICE for a voice that has ended or belongs to another context. audioVoicePause(ctx, voice, true) holds a sample’s or a stream’s voice where it is, silent, until it is called with false; for a tone or a note queue it gives AUDIO_ERR_ARG. audioStopAll(ctx) stops the context’s samples and tones (its streams and note queues play on). audioPlayFile(ctx, path, volume, pan, loop) loads a file and plays it in one call, freeing the sample when the voice ends: handy for a sound played once, wasteful for one played often.

The voice limit counts every voice of every program. When it is reached, a new sample or tone stops the quietest sample or tone playing, if the new one is louder; otherwise the new one is refused with AUDIO_ERR_NO_VOICE. Streams and note queues are never dropped, and a new one is refused while the limit is reached. Music never stops another sound to make room.

16.3.1. When a Sound Ends

// A voice of the program's context ended.  The Siren's stream has played
// all it was given: close it.  The call comes in the shell's idle time,
// never from an interrupt, so it may do anything.
static void onSoundEnd(AudioCtxT *ctx, int32_t voice, AudioEndE reason, void *userData) {
    (void)ctx;
    (void)userData;

    if (sSiren && voice == audioStreamVoice(sSiren)) {
        dvxLog("jukebox: siren ended (%s)", reason == AUDIO_END_FINISHED ? "finished" : "stopped");
        audioStreamClose(sSiren);
        sSiren = NULL;
    }
}

audioSetEndFn(ctx, fn, userData) asks for a call when a voice of the context ends, with its ID and why: AUDIO_END_FINISHED (it played to its end, or its tone’s length), AUDIO_END_STOPPED (audioVoiceStop, audioStopAll, or its sample or stream was freed), or AUDIO_END_DROPPED (the voice limit made room for a louder sound). The call comes from audioPump, in the shell’s idle time, as the program that owns the context: never from an interrupt, so it may call anything, open and close sounds included. The mixer works a little ahead of what the card is playing, so the call can come just before the last of the sound is heard.

16.4. Tones

// A noise tone, panned once it plays: the voice id it returns is the
// handle on it.
static void onBoom(WidgetT *w) {
    (void)w;

    int32_t voice = audioTone(sAudio, AUDIO_WAVE_NOISE, BOOM_HZ, AUDIO_VOLUME_MAX, BOOM_MS);

    if (voice > 0) {
        audioVoiceSetPan(sAudio, voice, wgtSliderGetValue(sPan));
    }
}

audioTone(ctx, wave, hz, volume, ms) plays a tone made by the mixer, with no sample: a square wave (AUDIO_WAVE_SQUARE), a triangle (AUDIO_WAVE_TRIANGLE), or noise (AUDIO_WAVE_NOISE), at hz from 20 to 20,000 (AUDIO_TONE_MIN_HZ, AUDIO_TONE_MAX_HZ), for ms milliseconds, or until stopped when ms is 0. For noise, hz is how fast the noise changes: higher sounds brighter. It returns a voice ID like any other, so Boom pans its noise once it plays, and audioVoiceSetFrequency changes a tone’s pitch while it sounds (a siren, a falling bomb).

Where a tone plays depends on the hardware. On a computer with an FM chip, a square or triangle tone plays on a free FM voice (unless [audio] fmTones is false), and in the mixer when every FM voice is taken. On the PC speaker in its usual mode, the timer chip sounds the loudest square or triangle tone playing, and noise is silent. Its ID, volume, pan, and end call work the same everywhere.

16.5. Note Queues

// The notes and rests follow each other to the sample, however late the
// program queues the next.  The queue is opened when it is needed, and
// onTick closes it once it has played.
static void onJingle(WidgetT *w) {
    (void)w;

    if (!sJingle && audioNotesOpen(sAudio, AUDIO_WAVE_SQUARE, AUDIO_VOLUME_MAX, &sJingle) != AUDIO_OK) {
        return;
    }

    for (int32_t i = 0; i < JINGLE_NOTES; i++) {
        audioNotesAdd(sJingle, sJingleHz[i] * AUDIO_MILLIHZ_PER_HZ, JINGLE_NOTE_MS * US_PER_MS);
        audioNotesAdd(sJingle, 0, JINGLE_REST_MS * US_PER_MS);
    }

    audioVoiceSetPan(sAudio, audioNotesVoice(sJingle), wgtSliderGetValue(sPan));
}

A tune made of tones wants each note to last exactly as long as asked, however late the program gets round to queuing the next. A note queue does that: audioNotesOpen(ctx, wave, volume, &notes) opens one, and audioNotesAdd(notes, milliHz, us) appends a tone of milliHz thousandths of a hertz (0 for a rest) lasting us microseconds. The queue plays its entries back to back, each to the output frame, counting from when the queue last fell silent, so a long tune does not drift. Up to AUDIO_NOTES_MAX (256) entries may wait; one more gives AUDIO_ERR_BUSY, and audioNotesSpace says how many fit. audioNotesSetTone(notes, wave, level) sets the waveform and loudness of the entries added after it, so a tune can change both as it goes. The queue plays on a voice of its own, audioNotesVoice(notes), for its volume and pan; it plays in the mixer or on the PC speaker, never on the FM chip. The music library plays QBasic’s PLAY and SOUND this way.

// Four times a second: the music's position, and the voices playing in
// all of DVX.  An open note queue holds a voice, and keeps the sound
// device running, even while it is silent: close the Jingle's once it has
// played.
static void onTick(WidgetT *w) {
    AudioStatsT stats;
    char        text[JUKEBOX_TEXT_MAX];

    (void)w;
    tuneShow();

    if (sJingle && audioNotesQueued(sJingle, NULL) == 0) {
        audioNotesClose(sJingle);
        sJingle = NULL;
    }

    audioGetStats(&stats);
    snprintf(text, sizeof(text), "Voices: %" PRIu32, stats.playing);
    wgtSetText(sVoices, text);
}

A queue’s voice plays for as long as the queue is open, silent while it is empty, so it counts against the voice limit, and it keeps the sound device from closing after its 10 seconds of silence. audioNotesQueued(notes, &tones) counts the entries not yet finished (0 once the queue has gone quiet), and Jukebox’s timer closes the queue then, opening it again at the next Jingle. A game that plays jingles all through, while its music keeps the device running anyway, can keep one queue open from start to end, as Chapter 17 does. audioNotesClear silences a queue and forgets what it holds.

16.6. Streams

A sample must exist before it plays. A stream is sound the program makes or reads while it plays: speech decoded from a file, a synthesizer, the output of an emulator. Siren makes a square wave whose pitch sweeps up and down:

// A pull stream: the library calls sirenFill whenever the stream has room.
// A second press starts it again.
static void onSiren(WidgetT *w) {
    AudioFormatT fmt = { SIREN_RATE, SIREN_BITS, SIREN_CHANNELS };

    (void)w;
    audioStreamClose(sSiren);
    sSiren            = NULL;
    sSirenState.frame = 0;
    sSirenState.total = SIREN_RATE * SIREN_MS / MS_PER_SEC;
    sSirenState.phase = 0;

    int32_t rc = audioStreamOpen(sAudio, &fmt, 0, sirenFill, &sSirenState, &sSiren);

    if (rc != AUDIO_OK) {
        dvxLog("jukebox: siren: %s", audioErrorText(rc));
        return;
    }

    audioVoiceSetPan(sAudio, audioStreamVoice(sSiren), wgtSliderGetValue(sPan));
}

audioStreamOpen(ctx, &fmt, bufferMs, fill, userData, &stream) opens a stream in the format fmt, at any rate from 4,000 to 48,000 Hz, with a buffer of bufferMs milliseconds (0 for AUDIO_STREAM_MS_DEFAULT, 250; at least 20 and at most 2,000), rounded up to a power of two frames. It plays at once on a voice of its own, audioStreamVoice(stream), starting at full volume in the center, and plays silence until there is sound to play. A stream comes in two kinds:

  • A push stream (fill is NULL): the program writes frames with audioStreamWrite(stream, pcm, frames), which takes as many as fit and returns how many. audioStreamSpace says how many frames of room are left, and audioStreamQueued how many are waiting to play.

  • A pull stream: the library calls fill(stream, buf, frames, userData) whenever the buffer has room, and the function writes up to frames frames in the stream’s format into buf and returns how many it wrote. Fewer is fine, even none: the rest is asked for later.

// Up to frames 16-bit mono frames of a square wave whose pitch rises and
// falls in a triangle, all in integers.  The last call ends the stream:
// its voice ends once what it holds has played.
static uint32_t sirenFill(AudioStreamT *stream, void *buf, uint32_t frames, void *userData) {
    SirenT  *s     = (SirenT *)userData;
    int16_t *out   = (int16_t *)buf;
    uint32_t sweep = SIREN_RATE * SIREN_SWEEP_MS / MS_PER_SEC;
    uint32_t half  = sweep / 2;
    uint32_t made  = 0;

    while (made < frames && s->frame < s->total) {
        uint32_t at   = s->frame % sweep;
        uint32_t ramp = at < half ? at : sweep - at;
        uint32_t hz   = SIREN_LOW_HZ + (SIREN_HIGH_HZ - SIREN_LOW_HZ) * ramp / half;

        s->phase    = (s->phase + hz * SIREN_PHASE_ONE / SIREN_RATE) % SIREN_PHASE_ONE;
        out[made++] = (int16_t)(s->phase < SIREN_PHASE_HALF ? SIREN_AMPLITUDE : -SIREN_AMPLITUDE);
        s->frame++;
    }

    if (s->frame >= s->total) {
        audioStreamEnd(stream);
    }

    return made;
}

The fill function runs from audioPump, in the shell’s idle time, as the program that owns the stream: not in an interrupt, so it may read files, allocate, and call DVX. A pump fills a stream in pieces, and stops once the stream holds 100 ms of sound and the pump has run for 15 ms, so a slow fill function does not hold DVX up. audioStreamEnd(stream) says no more frames will come after those written; a fill function may call it with its last ones, as sirenFill does. The fill function is not asked again, and once the stream has played what it holds, its voice ends as a sample’s does, with AUDIO_END_FINISHED; onSoundEnd above closes it then with audioStreamClose. A stream that is not ended and runs dry plays silence and counts underruns (AudioStatsT.underruns) until it is closed. audioStreamFlush(stream) drops what it holds and has not played, so a seek or a stop is heard at once.

Like a note queue, an open stream holds its voice and keeps the device running while it is silent. Close a stream when it has played.

16.7. Volume

Four volumes multiply, each from 0 to 256 (AUDIO_VOLUME_MAX, MUSIC_VOLUME_MAX):

Volume Set with Covers

Master

audioSetMasterVolume(volume)

All sound in DVX. It is the user’s, set on Control Panel’s Sounds page ([audio] volume, in percent, when the device starts; audioPercentToVolume converts). A program reads it and leaves it alone.

Context

audioSetVolume(ctx, volume)

Everything one context plays; Jukebox’s effects slider.

Voice

audioVoiceSetVolume(ctx, voice, volume) and the volume given to audioPlay, audioTone, and audioNotesOpen

One voice.

Music

musicSetVolume(music, volume)

One music; Jukebox’s music slider.

// The Sound Effects frame: a button for each effect, the effects' volume
// (the program's context), and the pan they play at.
static bool buildEffects(WidgetT *root) {
    WidgetT *frame   = wgtFrame(root, "Sound Effects");
    WidgetT *buttons = frame ? wgtHBox(frame) : NULL;
    WidgetT *coin    = buttons ? wgtButton(buttons, "&Coin") : NULL;
    WidgetT *boom    = buttons ? wgtButton(buttons, "&Boom") : NULL;
    WidgetT *jingle  = buttons ? wgtButton(buttons, "&Jingle") : NULL;
    WidgetT *siren   = buttons ? wgtButton(buttons, "S&iren") : NULL;

    if (!siren) {
        return false;
    }

    coin->onClick   = onCoin;
    boom->onClick   = onBoom;
    jingle->onClick = onJingle;
    siren->onClick  = onSiren;
    sEffectVol      = labeledSlider(frame, "Volume:", 0, AUDIO_VOLUME_MAX, AUDIO_VOLUME_MAX);
    sPan            = labeledSlider(frame, "Pan:", AUDIO_PAN_LEFT, AUDIO_PAN_RIGHT, AUDIO_PAN_CENTER);

    if (!sEffectVol || !sPan) {
        return false;
    }

    sEffectVol->onChange = onEffectVolume;
    return true;
}

A program’s music does not play through the program’s context: the music library plays every music through one context of its own, so audioSetVolume leaves a program’s music alone, and musicSetVolume is the only volume a music has besides the master.

16.8. Music

The music library plays what a program would otherwise need a player for. Jukebox’s Module button loads the module from its DATA folder:

// The tunes the program ships are in its DATA folder.
static void onModuleTune(WidgetT *w) {
    char path[DVX_MAX_PATH];

    (void)w;
    shellDataPath(sCtx, JUKEBOX_MODULE_FILE, path, sizeof(path));
    tuneLoad(path);
}
// Load a music file (the library tells the kind by its contents) and
// play it.  Where it plays is decided at its first musicPlay.
static void tuneLoad(const char *path) {
    int32_t rc;

    tuneFree();
    rc = musicLoad(path, &sMusic);

    if (rc == MUSIC_OK) {
        musicSetEndFn(sMusic, onMusicEnd, NULL);
        musicSetVolume(sMusic, wgtSliderGetValue(sMusicVol));
        rc = musicPlay(sMusic, wgtCheckboxIsChecked(sLoop));
    }

    tuneShow();

    if (rc != MUSIC_OK) {
        char text[JUKEBOX_TEXT_MAX];

        snprintf(text, sizeof(text), "%s cannot be played: %s", path, musicErrorText(rc));
        dvxLog("jukebox: %s", text);
        dvxErrorBox(sAc, JUKEBOX_TITLE, text);
    }
}

musicLoad(path, &music) loads a music file and musicLoadMem(data, size, &music) one in memory (copied), telling the kind by the contents, not the name: a WAV or VOC file, a Standard MIDI File (or an RMID file around one), and anything else is offered to the module player. A module or a MIDI file is read whole; a long one is read in pieces, and the other tasks get turns between them. A WAV or VOC file loaded by its path is read from the disk as it plays, so a long recording needs no memory; a sound file loaded from memory is decoded into memory. The errors are MUSIC_ERR_* codes, which musicErrorText turns into text: MUSIC_ERR_OPEN (the file could not be read), MUSIC_ERR_FORMAT (not music DVX plays), MUSIC_ERR_UNSUPPORTED (a compressed sound file), MUSIC_ERR_CORRUPT, MUSIC_ERR_NO_MEMORY, MUSIC_ERR_NO_DEVICE (no sound device), and, for MIDI, MUSIC_ERR_BANK (no instrument bank to play it with). Nothing plays until musicPlay.

A music belongs to the program that loaded it, and DVX stops and frees it when the program ends. musicFree(music) stops and frees it sooner. It accepts NULL, and so does every other music call (those that return a code return MUSIC_ERR_ARG), which is why Jukebox’s buttons need no test for a music not loaded:

static void tuneFree(void) {
    musicFree(sMusic);
    sMusic = NULL;
}

16.8.1. Playing, Pausing, and Stopping

// musicPlay plays from the music's position: where a pause left it, or the
// start after a load, a stop, or its end.  It also takes the Loop box, which
// may have changed during a pause.
static void onPlay(WidgetT *w) {
    (void)w;
    musicPlay(sMusic, wgtCheckboxIsChecked(sLoop));
    tuneShow();
}

static void onPause(WidgetT *w) {
    (void)w;
    musicPause(sMusic);
    tuneShow();
}

static void onStop(WidgetT *w) {
    (void)w;
    musicStop(sMusic);
    tuneShow();
}

// Looping changes at once: musicPlay on a music that plays only sets it.
static void onLoop(WidgetT *w) {
    if (musicIsPlaying(sMusic)) {
        musicPlay(sMusic, wgtCheckboxIsChecked(w));
    }
}

musicPlay(music, loop) plays from the music’s position: the start after a load or a stop, where a pause left it, and the start again after a music has played to its end. With loop it starts over at its end until stopped; called on a music that is playing, it only changes loop. The first musicPlay decides where the music plays (Section 16.8.2), so it, too, can fail: with MUSIC_ERR_NO_DEVICE or MUSIC_ERR_BANK. musicPause silences a playing music and holds its place, and musicResume goes on from there; each returns MUSIC_ERR_ARG when the music is not playing, or not paused. musicStop stops and goes back to the start, and musicIsPlaying is true only while the music plays (not stopped, paused, or finished).

musicGetPosition and musicSetPosition take milliseconds. A MIDI file’s new position replays the instruments and controllers set before it, without its notes; a module goes to the start of the pattern that holds that time; a sound file goes to that very frame.

// A music that does not loop played to its end.
static void onMusicEnd(MusicT *music, void *userData) {
    (void)music;
    (void)userData;
    tuneShow();
}

musicSetEndFn(music, fn, userData) asks for a call when a music that does not loop plays to its end. Like the sound library’s, the call comes in the shell’s idle time, as the program that owns the music, never from an interrupt.

// What the music is, where it plays, and how far it has played.
static void tuneShow(void) {
    MusicInfoT  info;
    char        text[JUKEBOX_TEXT_MAX];
    const char *state;

    if (!sMusic) {
        wgtSetText(sTuneInfo, "No music loaded");
        wgtSetText(sTunePos, "");
        return;
    }

    musicGetInfo(sMusic, &info);
    snprintf(text, sizeof(text), "%s%s%s on %s", info.title, info.title[0] ? " - " : "", sKindNames[info.kind], info.where == MUSIC_OUT_NONE ? "nothing yet" : info.output);
    wgtSetText(sTuneInfo, text);
    state = info.playing ? "Playing" : info.paused ? "Paused" : "Stopped";
    snprintf(text, sizeof(text), "%" PRIu32 ":%02" PRIu32 " / %" PRIu32 ":%02" PRIu32 "   %s", info.positionMs / MS_PER_SEC / SEC_PER_MIN, info.positionMs / MS_PER_SEC % SEC_PER_MIN, info.lengthMs / MS_PER_SEC / SEC_PER_MIN, info.lengthMs / MS_PER_SEC % SEC_PER_MIN, state);
    wgtSetText(sTunePos, text);
}

musicGetInfo(music, &info) fills a MusicInfoT: title (a module’s own title, or the name of a MIDI file’s first track; empty for a sound file), kind (a MusicKindE: module, MIDI file, live MIDI, or sound file), where and output (where it plays, as a MusicOutputE and as text for people, such as “OPL3 FM synthesizer at 388h”), lengthMs and positionMs, and the flags playing, paused, and looping.

16.8.2. Where Music Plays

Each kind of music plays where it plays best:

  • Modules (MOD, S3M, XM, and IT) are played by libxmp-lite, in a module of its own (LIBS\KPUNCH\MUSIC\PLAYERS\XMP.DRV) that the library loads when a module is loaded and lets go a minute after the last one is freed. A module plays on a wavetable synthesizer’s own voices when there is one, no other music is using it, and the module fits in its memory (MUSIC_OUT_WAVE); with [audio] modules = software, or otherwise, it is mixed in software into a stream, 16-bit stereo at the device’s rate, made up to 400 ms ahead (MUSIC_OUT_STREAM), on any device that plays sampled sound. The whole module is held in memory. libxmp works out pitches in floating point, so on a 486SX, which has no math coprocessor, modules are slow; and a module mixed in software takes a good share of a 486’s time.

  • MIDI files (types 0, 1, and 2) are played by DVX’s own sequencer on the best synthesizer there is, chosen by [audio] midi at the first musicPlay: with auto, a wavetable synthesizer with a General MIDI SoundFont when there is one and it is free (MUSIC_OUT_WAVE), else the FM chip with a General MIDI instrument bank (MUSIC_OUT_FM), else the library’s FM software synthesizer, which sounds like the chip and plays on any device that plays sampled sound (MUSIC_OUT_SOFTWARE); with mpu401, an external synthesizer on the MPU-401 port when the port was found and is free (MUSIC_OUT_MPU401), else as with auto. The other choices, fm, software, and softwave (the SoundFont mixed in software, MUSIC_OUT_SOFTWAVE), narrow the choice. On the synthesizers the song is timed by the timer service, 500 times a second, so it keeps time however busy the programs are. When the FM chip runs out of voices, the extra notes play on the software synthesizer.

  • Sound files (WAV and VOC) always play on a stream at their own rate (MUSIC_OUT_STREAM), with everything a module has: pause, position, and loop.

The instruments MIDI plays with are the user’s choice too: [audio] midiBank names an OP2 bank for the FM synthesizers (DVX ships Freedoom’s GENMIDI bank and two others), and [audio] soundFont a SoundFont for a wavetable synthesizer. musicSetBank(music, bank) plays one MIDI music with another bank, named the same way ("" for the standard OP2 bank, NULL for the user’s choices again), before its first musicPlay.

The MPU-401 port and the wavetable synthesizer each play one music at a time; another MIDI music meanwhile plays on the FM chip or the software synthesizer. Any number of musics play together on streams, from any number of programs.

16.9. Live MIDI and Music Macros

A program can also play MIDI note by note, a dynamic game score or an instrument of its own. musicMidiOpen(&music) opens a music with no file that plays at once, on the synthesizer a MIDI file would use, and the channel messages go to it:

#define DEMO_CHANNEL     0      // MIDI channels are 0 to 15; 9 is percussion
#define DEMO_FLUTE       73     // General MIDI program 74, counted from 0
#define DEMO_MIDDLE_C    60
#define DEMO_VELOCITY    100

MusicT *keys = NULL;

if (musicMidiOpen(&keys) == MUSIC_OK) {
    musicMidiProgram(keys, DEMO_CHANNEL, DEMO_FLUTE);
    musicMidiNoteOn(keys, DEMO_CHANNEL, DEMO_MIDDLE_C, DEMO_VELOCITY);
}

// ... and later, from a timer or a key going up:
musicMidiNoteOff(keys, DEMO_CHANNEL, DEMO_MIDDLE_C);

musicMidiNoteOn, musicMidiNoteOff, musicMidiProgram, musicMidiControl, and musicMidiPitchBend (-8,192 to 8,191) take channels 0 to 15 and data 0 to 127, and return MUSIC_ERR_ARG for a value out of range or a music that is not MIDI. They work on a MIDI file that is playing too, so a game can change its score’s instruments or add notes to it. musicMidiSend(music, status, data1, data2) sends any channel message as MIDI input brings it, so what a keyboard plays can be heard as it comes (Section 16.11).

Tunes can be written in QBasic’s music macro language, the language of BASIC’s PLAY, with notes A to G, octaves (O, <, >), lengths (L), rests (P), tempo (T), and DVX’s own I, which plays the notes after it on a General MIDI instrument:

MusicMmlT *tune = NULL;

if (musicMmlOpen(&tune) == MUSIC_OK) {
    musicMmlPlay(tune, "T140 O3 L8 CDEC CDEC EFG4 EFG4");
}

musicMmlOpen opens a queue for the program, and musicMmlPlay checks the whole string and queues its notes (MUSIC_ERR_MACRO, with nothing queued, for a mistake anywhere), returning at once. Tones play on a note queue and instrument notes as small MIDI musics, one after another. musicMmlTone queues one tone (QBasic’s SOUND), musicMmlQueued counts the notes still to play, and musicMmlStop silences the queue. QBasic’s foreground and background modes (MF, MB) only change what musicMmlBusy answers, which is whether a program that follows QBasic should still wait; a C program waits for nothing. musicLoadMacro(macro, &music) instead turns a macro into a MIDI music, played, paused, and freed like a MIDI file. music.h lists the whole language.

16.10. The FM Chip

A program with music code of its own can program the FM chip directly. Its two-operator voices, 9 on an OPL2 and 18 on an OPL3, are shared by every program: audioFmAlloc(ctx) takes one and returns its ID (AUDIO_ERR_NO_VOICE when all are taken, AUDIO_ERR_NO_SYNTH without a chip), audioFmWrite(ctx, voice, reg, value) sets a register of the voice’s channel, and audioFmFree(ctx, voice) keys it off and gives it back. The registers are numbered as for the first channel of an OPL2 (AUDIO_FM_*), and the library adds the channel’s offsets and bank. Voices are handed out least recently freed first, so a released note’s tail is the last to be cut. audioFmGetInfo describes the chip: its voices, how many are free, and whether it is an OPL3, whose voices can be panned. A note of an organ-like sound:

#define ORGAN_CHAR       0x21   // sustaining, frequency multiple 1
#define ORGAN_MOD_LEVEL  0x10   // modulator 12 dB down: a little brightness
#define ORGAN_CAR_LEVEL  0x00   // carrier at full level
#define ORGAN_ATTACK     0xF4   // attack rate 15, decay rate 4
#define ORGAN_SUSTAIN    0x24   // sustain level 2 (6 dB down), release rate 4
#define ORGAN_FEEDBACK   0x08   // feedback 4, frequency modulation
#define ORGAN_FNUM_SHIFT 20     // hz = fnum * AUDIO_FM_CHIP_HZ * 2^block / 2^20
#define ORGAN_LOW_MASK   0xFF

// Start a note of hz on a voice of the FM chip; the voice ID, or an
// AUDIO_ERR_* code.  audioFmFree ends the note.
static int32_t organNoteOn(AudioCtxT *ctx, uint32_t hz) {
    int32_t  voice = audioFmAlloc(ctx);
    uint32_t block = 0;
    uint32_t fnum  = 0;

    if (voice < 0) {
        return voice;
    }

    // The lowest block whose frequency number fits
    while (block < AUDIO_FM_BLOCK_MAX && (((uint64_t)hz << (ORGAN_FNUM_SHIFT - block)) / AUDIO_FM_CHIP_HZ) > AUDIO_FM_FNUM_MAX) {
        block++;
    }

    fnum = (uint32_t)DVX_MIN(((uint64_t)hz << (ORGAN_FNUM_SHIFT - block)) / AUDIO_FM_CHIP_HZ, AUDIO_FM_FNUM_MAX);
    audioFmWrite(ctx, voice, AUDIO_FM_MOD_CHAR, ORGAN_CHAR);
    audioFmWrite(ctx, voice, AUDIO_FM_CAR_CHAR, ORGAN_CHAR);
    audioFmWrite(ctx, voice, AUDIO_FM_MOD_LEVEL, ORGAN_MOD_LEVEL);
    audioFmWrite(ctx, voice, AUDIO_FM_CAR_LEVEL, ORGAN_CAR_LEVEL);
    audioFmWrite(ctx, voice, AUDIO_FM_MOD_ATTACK, ORGAN_ATTACK);
    audioFmWrite(ctx, voice, AUDIO_FM_CAR_ATTACK, ORGAN_ATTACK);
    audioFmWrite(ctx, voice, AUDIO_FM_MOD_SUSTAIN, ORGAN_SUSTAIN);
    audioFmWrite(ctx, voice, AUDIO_FM_CAR_SUSTAIN, ORGAN_SUSTAIN);
    audioFmWrite(ctx, voice, AUDIO_FM_FEEDBACK, ORGAN_FEEDBACK);
    audioFmWrite(ctx, voice, AUDIO_FM_FNUM_LOW, (uint8_t)(fnum & ORGAN_LOW_MASK));
    audioFmWrite(ctx, voice, AUDIO_FM_KEY_BLOCK, (uint8_t)(AUDIO_FM_KEY_ON | (block << AUDIO_FM_BLOCK_SHIFT) | (fnum >> AUDIO_FM_FNUM_HI_SHIFT)));
    return voice;
}

On an OPL3 a feedback value with neither output bit (AUDIO_FM_OUT_LEFT, AUDIO_FM_OUT_RIGHT) plays on both sides. A program that wants the whole chip, for a player written for one, takes it with audioFmRawAcquire(ctx): the other programs' FM voices are silenced and taken back (their tones go on in the mixer), new ones are refused, and audioFmRawWrite(ctx, reg, value) sets any register, numbered as the bank (1 on an OPL3 only, else 0) times AUDIO_FM_BANK_REGS plus the index. A second program asking gets AUDIO_ERR_BUSY. audioFmRawRelease, or closing the context, gives the chip back. audioFmAlloc, audioFmFree, audioFmWrite, and audioFmRawWrite may also be called from a timer callback (Section 17.5.1), which is how a player keeps time; give the chip and its voices back as soon as the program no longer needs them.

16.11. The MIDI Port

The MPU-401 port, in UART mode, drives an external synthesizer such as a Roland MT-32 or SC-55. It is there only when the user set [audio] midi = mpu401 (or midiIn), and it belongs to one program at a time: audioMidiAcquire(ctx) takes it (AUDIO_ERR_BUSY while another program has it, AUDIO_ERR_NO_SYNTH without one), audioMidiPut(ctx, byte) sends a byte, and audioMidiRelease gives it back, as closing the context does. audioMidiPut returns AUDIO_ERR_BUSY when the port cannot take a byte yet; keep the byte and send it again later, never in a loop that waits. It may be called from a timer callback. audioMidiGetInfo says whether there is a port, and whether it is in use. A program that only wants its MIDI music heard on the port needs none of this: the music library sends MIDI files there when the user chose it.

With [audio] midiIn = mpu401 the port also brings in what a keyboard plays. One program reads it at a time: audioMidiInOpen(ctx) starts (AUDIO_ERR_NO_SYNTH without MIDI input, AUDIO_ERR_BUSY while another program reads it), and audioMidiInRead(ctx, &msg) gives the next whole message, oldest first, as an AudioMidiMsgT: its status, data bytes, length, and ms, when it came, in milliseconds since the input was opened. Running status is filled in, and clock, active sensing, and system exclusive messages are left out. A timer reads the port 1,000 times a second into a buffer of 1,024 bytes, and audioMidiInLost counts what was dropped because the program read too late. Hand a message to musicMidiSend to hear it, and to musicMidiRecordAdd to record it: musicMidiRecordNew, musicMidiRecordAdd, and musicMidiRecordSave write a Standard MIDI File, a tick a millisecond, all or nothing. DVX’s Sound Recorder does both.

16.12. The Rest of the Sound Library

The reference describes the other parts of audio.h (“Sound Library” in the DVX C Library Reference):

  • The wavetable synthesizer (audioWt…​): sample memory and voices of an AWE32, AWE64, or UltraSound, shared by every program. A program allocates memory, uploads 16-bit samples, takes a voice, and starts it on a note described in SoundFont units (AudioWtVoiceT, made plain by audioWtNoteInit); the chip does what its flags say it can, and the program does the rest by updating the voice as the note goes on.

  • Recording (audioRec…​): audioRecOpen records from the card’s microphone, line, or CD input into memory for audioRecRead, and audioRecFile into a WAV file that takes the place of the old one only when it is complete. One recording runs at a time in DVX, and since most cards record or play but not both, nothing plays meanwhile: voices playing hold where they are, and new ones are refused with AUDIO_ERR_BUSY. audioWavHeader writes the header of a WAV file for a program that writes its own.

  • Desktop sounds: the sounds DVX plays for its own events (starting, message boxes, windows opening and closing), files chosen on Control Panel’s Sounds page. The sound library plays them on a context of its own. A program plays one with dvxPlaySound(event) (dvxApp.h, a DvxSoundE such as SoundErrorE), and the default beep with dvxBeep().

  • Settings: the functions Control Panel uses to read and write the [audio] keys (audioSetting…​).

  • Drivers: audioDrv.h describes a sound driver (AudioDriverT, AUDIO_DRIVER) and a synthesizer driver (AudioSynthDriverT), for a card DVX does not drive yet. Driver code runs in interrupts, with the rules of Section 17.5.1.

16.13. Keeping Sound Fed

Sampled sound is mixed in the card’s interrupt, so a sample, a tone, or a note queue plays on however busy DVX is. Everything else needs program time, which the libraries take in the shell’s idle time: the end calls, the pull streams' fill functions, a module rendered into its stream, the software synthesizer, a WAV or VOC file read from the disk, the music macro queues. The shell runs its idle handlers when a frame has painted nothing, and at least every 20 ms while frames keep painting (Section 3.5). The streams' buffers cover the gaps: 250 ms by default, 400 ms for a module or a sound file, 150 ms for the software synthesizer.

So the rule of Section 3.5 is also a rule for sound: nothing may block. A callback that runs for half a second starves every stream in DVX, and the user hears it as a gap; audioGetStats counts the frames that were due and missing (underruns). A callback-only program such as Jukebox needs nothing more. A program with a main loop that keeps DVX busy, redrawing every frame as a game does, should call musicPump() once a frame (it runs audioPump() first, so a program without music calls audioPump() instead): each call delivers the end calls and fills the streams at once. Neither may be called from an interrupt.

16.14. Things to Know

  • Every voice, sample, stream, note queue, music, FM voice, and port a program holds is released when it ends, however it ends. Closing them sooner ends the sound sooner and frees the memory and the voices for others.

  • A stream, a note queue, and a music that plays on a stream (every music once it has played, except MIDI on the MPU-401 port and a module on a wavetable synthesizer) hold a voice while they are open, silent or not, and keep the device running; close and free them when done.

  • Samples are decoded to 16 bits and pinned in memory; long sounds belong in the music library, which streams WAV and VOC files from the disk.

  • The mixer and the voice limit belong to all of DVX: a sound can be refused, or dropped for a louder one, because of what other programs play. Check the voice IDs you get.

  • MIDI plays differently on every synthesizer, and a module plays in floating point; test on the hardware your users have, or on an emulator that has it (Chapter 22).

  • Nothing in audio.h or music.h may be called from an interrupt, except the FM, MIDI port, and wavetable calls that say so.

Chapter 17. Games

A game in DVX is a program with a main loop of its own (Section 3.4). DVX gives it a task: appMain runs the game, draws into the game’s window, and waits for each frame on the high-resolution clock while the other programs go on running. Nothing in DVX stops for a game. The desktop, the other programs, Task Manager, and help all stay at hand, and the player can switch away with Alt+Tab at any moment. A game may also take the whole screen in a video mode of its own, and the other programs run on behind it.

This chapter builds bounce, a small brick-breaking game grown from the SDK’s game template, and covers what a game needs from DVX: the game library (game.h: frame pacing, held keys, timers, and 8-bit colors), game input, joysticks (joystick.h), a screen of its own and its palette, the whole screen, sound, data files and saved games, and, last, how to port a game library written for DOS. The sound and music calls are the subject of Chapter 16.

The Bounce window with rows of colored bricks and the paddle, its score and lives in the title bar
Figure 25. Bounce in its window, ready for the first ball

17.1. Starting from the Template

The SDK has a template for a C game and one for a DVX BASIC game:

$ DVX-SDK/newProject.sh game myGame
$ DVX-SDK/newProject.sh basicgame myGame

The C template is a small but complete game: collect as many coins as you can in 30 seconds. It has a game input window; a 320 x 200 screen of 8-bit color numbers with its own palette, drawn scaled into the window on a desktop of any color depth, or on the whole screen with Alt+Enter; frame pacing; the arrow keys and a joystick; a sound effect and a MIDI tune carried inside the .app as resources, and tones at the end of a round; the best score saved in the program’s user folder; and its help file and icon. It is an app project like any other (Section 1.3).

bounce began as that template. It keeps the template’s window, screen, palette, presenting, full-screen mode, sound loading, and saved score nearly line for line, and replaces the game: a paddle at the bottom, a ball, and six rows of bricks to break with it, three balls a game, and a faster ball at each new wall. Along the way it adds a raw key event (Space launches the ball), an analog joystick (the paddle moves as far as the stick is pushed), a background with bricks in it to put back behind moving sprites, and tones panned to where the ball is. Its files are the template’s: bounce.c, bounce.res (with the template’s coin.wav and music.mid), bounce.dhs, icon32.bmp, and the Makefile.

17.2. The Shape of a Game

// A game runs its own loop, so it gets its own task (hasMainLoop).
SHELL_APP_DESCRIPTOR(
    .name          = BOUNCE_TITLE,
    .hasMainLoop   = true,
    .multiInstance = false,
    .stackSize     = SHELL_STACK_DEFAULT,
    .priority      = TS_PRIORITY_NORMAL
);

hasMainLoop = true gives the game a task with the default stack at normal priority (Section 2.2). The whole game is appMain:

int32_t appMain(DxeAppContextT *ctx) {
    GameFramePacerT pacer;

    sCtx = ctx;
    sAc  = ctx->shellCtx;

    if (!windowCreate()) {
        return -1;
    }

    paletteInit();
    lutSync();
    loadBest();
    gameNew();

    if (joyCount() > 0) {
        JoyInfoT info;

        sJoy = joyOpen(sAc, 0);
        joyGetInfo(0, &info);
        dvxLog("bounce: joystick '%s'", info.name);
    }

    soundLoad();
    dvxLog("bounce: started, %dx%d at %" PRId32 "x on a %" PRId32 "-bit desktop", FB_W, FB_H, sScale, dvxGetDisplay(sAc)->format.bitsPerPixel);
    gameFrameInit(&pacer, FRAME_HZ);

    while (!sQuit) {
        uint32_t   missed = gameFrameWait(&pacer);
        GameInputT in;

        // The music's sound and every end call are made here too (musicPump
        // runs audioPump), so they keep up while the game keeps DVX busy.
        musicPump();
        readInput(&in);

        if (lutSync()) {
            dirtyAdd(0, 0, FB_W, FB_H);
        }

        GameRectT oldPaddle = { sGame.paddleX, PADDLE_Y, PADDLE_W, PADDLE_H };
        GameRectT oldBall   = ballRect();

        // Everything stands still while the game is paused or over, or
        // another window is active: nothing is drawn then.
        if (!sPaused && !sGame.over && sWin->focused) {
            gameUpdate(&in, missed < STEPS_MAX ? missed + 1 : STEPS_MAX);
            ballGlow();
            drawSprites(&oldPaddle, &oldBall);
        }

        present();
    }

    saveBest();
    soundShutdown();
    joyClose(sJoy);
    dvxDestroyWindow(sAc, sWin);
    sWin = NULL;
    dvxLog("bounce: ended");
    return 0;
}

It makes the window, the palette, and a new game, opens the first joystick and the sound, and then loops, once a frame, until sQuit is set:

  1. gameFrameWait gives the processor to the rest of DVX until the next frame is due, and returns how many frames went by unseen (Section 17.5).

  2. musicPump makes the music’s sound and delivers the sound library’s end calls now, rather than waiting for the shell’s idle time, which comes only every 20 ms while a game paints every frame (Section 16.13).

  3. readInput reads the keys and the joystick once (Section 17.3).

  4. lutSync notices a new video mode, and the whole frame is drawn again for it (Section 17.6).

  5. While the game is running and its window has the focus, gameUpdate moves everything as far as the frames that went by call for, and drawSprites draws the result into the game’s own framebuffer.

  6. present copies what changed into the window, or to the whole screen.

The window’s callbacks run on the shell’s task, between two turns of the loop, never during one (Section 3.4). onClose only sets the flag:

// The loop sees the flag at its next turn, and ends.
static void onClose(WindowT *win) {
    (void)win;
    sQuit = true;
}

When the loop ends, the game saves its best score, closes its sound and its joystick, destroys its window, and returns, which ends the program. Exit DVX closes the window as the close gadget does, so the game ends the same way. End Task ends the task where it stands, in gameFrameWait; DVX then releases what the program held (its window, sounds, music, joystick handles, and timers), but the game saves nothing, which is one reason to save a score when it is made rather than at the end.

17.2.1. The Game’s Window

// A window whose content area is the framebuffer at the largest whole
// scale that fits the screen.
static bool windowCreate(void) {
    int32_t frameW = 2 * CHROME_TOTAL_SIDE;
    int32_t frameH = CHROME_TOTAL_TOP + CHROME_MENU_HEIGHT + CHROME_TOTAL_BOTTOM;
    int32_t scaleW = (sAc->display.width - frameW) / FB_W;
    int32_t scaleH = (sAc->display.height - frameH) / FB_H;

    sScale = clampRange(DVX_MIN(scaleW, scaleH), 1, SCALE_MAX);
    sWin   = dvxCreateWindowCentered(sAc, BOUNCE_TITLE, FB_W * sScale + frameW, FB_H * sScale + frameH, false);

    if (!sWin) {
        return false;
    }

    sWin->gameInput = true;
    sWin->onClose   = onClose;
    sWin->onKey     = onKey;
    sWin->onRawKey  = onRawKey;
    sWin->onMenu    = onMenu;
    sWin->onPaint   = onPaint;

    MenuBarT *menuBar  = wmAddMenuBar(sWin);
    MenuT    *gameMenu = menuBar ? wmAddMenu(menuBar, "&Game") : NULL;
    MenuT    *helpMenu = menuBar ? wmAddMenu(menuBar, "&Help") : NULL;

    if (gameMenu) {
        wmAddMenuItem(gameMenu, "&New Game\tF2", CMD_GAME_NEW);
        wmAddMenuCheckItem(gameMenu, "&Pause\tP", CMD_GAME_PAUSE, false);
        wmAddMenuCheckItem(gameMenu, "&Music", CMD_GAME_MUSIC, true);
        wmAddMenuCheckItem(gameMenu, "&Full Screen\tAlt+Enter", CMD_GAME_FULL, false);
        wmAddMenuSeparator(gameMenu);
        wmAddMenuItem(gameMenu, "E&xit", CMD_GAME_EXIT);
    }

    if (helpMenu) {
        wmAddMenuItem(helpMenu, "&Contents\tF1", CMD_HELP_CONTENTS);
        wmAddMenuSeparator(helpMenu);
        wmAddMenuItem(helpMenu, "&About " BOUNCE_TITLE "...", CMD_HELP_ABOUT);
    }

    // The frame was sized from the chrome constants; make the content
    // area exactly the scaled framebuffer whatever the menu bar took.
    int32_t wantW = FB_W * sScale;
    int32_t wantH = FB_H * sScale;

    if (sWin->contentW != wantW || sWin->contentH != wantH) {
        dvxResizeWindow(sAc, sWin, sWin->w + wantW - sWin->contentW, sWin->h + wantH - sWin->contentH);
    }

    return true;
}

The window’s content area is exactly the framebuffer at the largest whole scale that fits the screen, at most SCALE_MAX: the scale comes from the display’s size less the window’s frame (CHROME_TOTAL_SIDE, CHROME_TOTAL_TOP, CHROME_TOTAL_BOTTOM, and the menu bar’s CHROME_MENU_HEIGHT, from dvxTypes.h), and once the menu bar is in place dvxResizeWindow corrects the frame so that the content area is exactly the size wanted. The window cannot be resized, since a whole scale would not survive it. It has no widgets: its onPaint draws its content (Section 9.9). The title bar shows the score, the lives, the level, and what to do next, through dvxSetTitle:

// Score, lives, level, and what to do next in the title bar.
static void titleUpdate(void) {
    char        title[MAX_TITLE_LEN];
    char        best[BOUNCE_BEST_MAX];
    const char *tail = best;

    snprintf(best, sizeof(best), "Best %" PRId32, sGame.best);

    if (sGame.over) {
        tail = "Game over, F2 to play again";
    } else if (sPaused) {
        tail = "Paused";
    } else if (sGame.held) {
        tail = "Space to launch";
    }

    snprintf(title, sizeof(title), BOUNCE_TITLE " - Score %" PRId32 " - Lives %" PRId32 " - Level %" PRId32 " - %s", sGame.score, sGame.lives, sGame.level, tail);
    dvxSetTitle(sAc, sWin, title);
}

17.3. Game Input

17.3.1. Game Input Windows

A window with gameInput set gets the keyboard to itself while it has the focus (Section 8.9). DVX keeps three keys, so the player can always switch away, open Task Manager, or close the game:

Key Always does

Alt+Tab

Switches to the next window.

Ctrl+Esc

Opens Task Manager.

Alt+F4

Closes the window (its onClose).

Every other key goes to onKey, with F1, F10, Alt and a letter, the window’s accelerators, and DVX’s hotkeys among them: none of them opens help or a menu. The game decides what they do; the window’s menus still work with the mouse.

// In a game input window every key but Alt+Tab, Ctrl+Esc and Alt+F4
// comes here, F1 included: the game decides what it does.  Alt+Enter
// comes as the Enter key's scan code (from either Enter key) or as Enter.
static void onKey(WindowT *win, int32_t key, int32_t mod) {
    (void)win;

    if ((mod & KEY_MOD_ALT) && (key == KEY_ENTER || key == (KEY_SCAN_ENTER | KEY_EXT_FLAG))) {
        fullSet(!sFull);
        return;
    }

    switch (key) {
        case KEY_F1:
            shellOpenHelpFile(sAc, sCtx->helpFile, NULL);
            break;

        case KEY_F2:
            gameNew();
            break;

        case 'p':
        case 'P':
            setPaused(!sPaused);
            break;

        default:
            break;
    }
}

Because F1 comes to the game, the game opens its help itself, with shellOpenHelpFile and the program’s helpFile. Alt+Enter, from either Enter key, arrives with KEY_MOD_ALT as the Enter key’s scan code with KEY_EXT_FLAG (KEY_SCAN_ENTER | KEY_EXT_FLAG), since the BIOS gives Alt+Enter no character, or, on a BIOS that does give one, as Enter (KEY_ENTER); test for both. The key that completes one of the three kept keys (Esc with Ctrl held, Tab or F4 with Alt held) never reaches the game, by any route, but the Ctrl or Alt before it does, since nothing can tell what will follow it. A game that takes any key to mean “go on” therefore sees the Alt of Alt+Tab.

17.3.2. Held Keys

// The paddle's way from the arrow keys, else from the joystick's first
// axis, as far over as the stick is pushed.  With no joystick plugged in
// DVX offers a keyboard joystick made from the same keys, which is why the
// keys win rather than adding up.  A press while the game waits is
// dropped, not kept for later.
static void readInput(GameInputT *in) {
    JoyStateT st;
    bool      joy  = sJoy >= 0 && joyRead(sJoy, &st) && st.connected;
    int32_t   keys = (gameKeyIsDown(sWin, KEY_RAW_RIGHT) ? 1 : 0) - (gameKeyIsDown(sWin, KEY_RAW_LEFT) ? 1 : 0);

    in->paddleDx = keys * PADDLE_SPEED;
    in->launch   = sLaunchAsked || (joy && joyButtonWentDown(sJoy, JOY_LAUNCH_BUTTON));
    sLaunchAsked = false;

    if (joy && keys == 0) {
        in->paddleDx = st.axes[JOY_PADDLE_AXIS] * PADDLE_SPEED / JOY_AXIS_MAX;
    }
}

gameKeyIsDown(win, rawCode) is true while the key is held down and win has the keyboard focus. Keys are named by raw code: a key’s PC set-1 scan code, with KEY_RAW_EXT added for the keys the keyboard sends behind an 0xE0 prefix (the gray arrows and navigation keys, the right Ctrl and Alt, the keypad’s Enter and /). dvxTypes.h names a few (KEY_RAW_UP, KEY_RAW_LCTRL, KEY_RAW_RSHIFT), and KEY_RAW_CODE(scan, extended) makes the rest from the KEY_SCAN_* codes, which for letters, digits, and punctuation are the same set-1 codes. A key’s raw code does not change with the modifiers, and left and right Shift, Ctrl, and Alt are keys of their own. A DOS game’s table of scan codes therefore carries over as it is.

The table of held keys belongs to DVX: platformKeyIsDown(rawCode) reads it without asking about the focus, platformKeyStateGet copies all 256 entries, and platformKeyStateClear marks every key up (a key still held reads as down again at its next repeat). When the focus moves away from a game input window, the window’s onRawKey hears a release for every key still held, and the table starts over, so no key stays stuck down; a key already held when the window gets the focus is seen once it repeats.

Bounce reads its input once a frame, at the top of the loop, and the paddle moves at a fixed speed while an arrow is held. Its rule that the keys win over the joystick is not a matter of taste: when no joystick is plugged in, DVX offers a keyboard joystick made from the same keys (Section 17.4), and adding the two would move the paddle twice as fast.

17.3.3. Raw Key Events

// Each key going down and up.  Space launches the ball when it goes down,
// not when it repeats; the loop takes the flag at its next frame.
static void onRawKey(WindowT *win, const RawKeyEventT *evt) {
    (void)win;

    if (evt->down && !evt->repeat && !evt->extended && evt->scancode == KEY_SCAN_SPACE) {
        sLaunchAsked = true;
    }
}

A held key says what is down now; an action that should happen once per press wants the key going down. onRawKey(win, evt), called only for a game input window, gets every key going down and up as a RawKeyEventT: its scancode and extended flag (together, its raw code), whether it went down or up, whether it is a typematic repeat of a key already down, and the modifiers as the held-key table has them just after it. Bounce launches the ball on Space going down and ignores the repeats, so holding Space launches it once. Like every window callback, onRawKey runs on the shell’s task, so it sets a flag and the loop takes it at its next frame. onKey gets typed keys as in any window, with Shift and the keyboard layout applied: keep them in a queue of the game’s own if the game reads text.

17.3.4. The Mouse

A window without widgets gets the mouse through onMouse(win, x, y, buttons), in content-area pixels (Section 8.10.3). A game that draws at a scale divides by it and clamps the result to its screen. On the whole screen onMouse gets whole-screen coordinates instead, and DVX draws no pointer (Section 17.7).

17.4. Joysticks

The joystick library (joystick.h, JOYSTICK.LIB) puts every game controller behind one interface. Its drivers are loaded the first time a program asks for devices: the game port (joyport, up to two joysticks, or one with four axes and four buttons, as the user chooses) and the keyboard joystick (joykeys), which stands in when no other device is found. joyCount() says how many devices there are, up to JOY_MAX_DEVICES (8), and joyGetInfo(device, &info) describes one: its name for people, its ID (the driver’s name and a unit number, such as gameport0), how many axes, buttons, and hats it has, which axes answer (axisPresent), and its capabilities: JOY_CAP_CALIBRATE for analog axes, JOY_CAP_KEYBOARD for the keyboard joystick.

joyOpen(ctx, device) gives the program a handle on a device, or -1 when there is no such device or all JOY_MAX_HANDLES (32) are open. The handle belongs to the program and is closed when it ends; joyClose closes it sooner, and does nothing for -1. joyRead(handle, &state) fills a JoyStateT:

Member Holds

axes[]

Each axis from JOY_AXIS_MIN (-32,768) to JOY_AXIS_MAX (32,767), calibrated, with 0 in a dead zone round the center.

buttons

Bit n set: button n is down, or went down since this handle last read it. A quick tap between two reads is not lost: it reads as down once.

hats[]

JOY_HAT_CENTERED (-1), or the direction pushed in degrees, clockwise from up.

connected

False when the device stopped answering; everything then reads neutral.

joyButtonPressed(handle, button) asks the same of one button. joyButtonWentDown(handle, button) asks only whether the button went down since the last time this function asked about it, with a count of its own, apart from `joyRead’s: that is the call for an action once per press, as Bounce’s launch. Read a joystick once a frame. A digital game compares an axis with a threshold, as the template does; Bounce scales it, so the paddle moves as far as the stick is pushed (an analog stick) or at full speed (a digital pad, or the keyboard joystick).

The keyboard joystick has two axes from the arrow keys and four buttons from Left Ctrl, Space, Left Shift, and Z, unless the user chose other keys. It reads neutral for a handle whose program has no window with the focus, so keys typed into another program do not steer the game.

A program that waits for input rather than looping, a menu screen or a joystick tester, can have the changes delivered as events: joySetEventFn(handle, fn, userData) calls fn with a JoyEventT when an axis moves by at least JOY_EVENT_AXIS_STEP or reaches the center or an end, when a button goes down or up, and when a hat moves. joyPump delivers them, in the shell’s idle time or when a program calls it, as the program that owns the handle, never in an interrupt.

Calibration, the dead zone, the game port’s mode, the keyboard joystick’s keys, and the polling rate are the user’s, set on Control Panel’s Game Controllers page and kept in DVX.INI [joystick]; joystick.h has the calls that page uses, and joyRescan looks for devices again (only while no handle is open). The devices are polled only while some handle is open, at most [joystick] pollHz times a second (60 by default): a timer marks a poll due, and the reading happens outside the interrupt, the next time a program reads or the shell is idle. A game port poll waits for the stick’s timers to run out, for up to 3 ms (JOYPORT_TIMEOUT_US) at each poll, so close the handle when the game no longer needs the stick. Never read the game port directly. A new kind of controller gets a driver of its own (JoyDriverT, JOY_DRIVER; “Joystick Library” in the DVX C Library Reference).

17.5. Frame Pacing and Time

gameFrameInit(&pacer, hz) starts a frame clock at hz frames a second (1 to GAME_FRAME_MAX_HZ, 1,000; a rate out of range is clamped), with frame 0 beginning now. gameFrameWait(&pacer), once a frame, gives the processor to the other tasks (tsYield) until the next frame is due, so call it only from a program with its own loop, never from a callback. Frame n begins at the start plus n / hz seconds, worked out from the frame number each time, so the rate never drifts however long the game runs. It yields at least once even when the frame is already due, so a game too slow for its rate cannot keep the processor for good.

gameFrameWait returns how many frames were missed: 0 when the game is on time, or, when the frame after the next one has already begun because the game was busy, the frames that ended unseen, which are skipped rather than caught up (pacer.missed keeps the total, and pacer.frame is the frame number). A frame that starts late but within its own time counts as on time. Moving everything by the frames that went by keeps the game at the same speed on a slower machine:

// Move the paddle and the ball steps frames' worth.  The ball moves a
// frame at a time, so it never jumps over a brick or the paddle.
static void gameUpdate(const GameInputT *in, uint32_t steps) {
    sGame.paddleX = clampRange(sGame.paddleX + in->paddleDx * (int32_t)steps, 0, FB_W - PADDLE_W);

    if (sGame.held && in->launch) {
        sGame.held   = false;
        sGame.ballDx = sGame.paddleX + PADDLE_W / 2 < FB_W / 2 ? sGame.speed / 2 : -sGame.speed / 2;
        sGame.ballDy = -sGame.speed;
        titleUpdate();
    }

    for (uint32_t s = 0; s < steps && !sGame.held; s++) {
        ballStep();
    }

    if (sGame.held) {
        sGame.ballX = (sGame.paddleX + (PADDLE_W - BALL_SIZE) / 2) * FIX_ONE;
        sGame.ballY = (PADDLE_Y - BALL_SIZE) * FIX_ONE;
    }

    if (sGame.bricksLeft == 0) {
        levelNext();
    }
}

The loop passes missed + 1 steps, at most STEPS_MAX (4), so a long stall (a dialog box of another program, a disk that spun up) slows the game for a moment rather than teleporting the ball. The paddle moves all its steps at once, but the ball moves a step at a time, so that it never jumps over a brick or the paddle:

// One frame of the ball's flight.  It moves across, then down, and each
// time turns back from what it ran into: a wall, a brick, or the paddle.
static void ballStep(void) {
    GameRectT paddle = { sGame.paddleX, PADDLE_Y, PADDLE_W, PADDLE_H };
    GameRectT r;

    sGame.ballX += sGame.ballDx;

    if (sGame.ballX < 0 || sGame.ballX > BALL_X_MAX) {
        sGame.ballX  = clampRange(sGame.ballX, 0, BALL_X_MAX);
        sGame.ballDx = -sGame.ballDx;
        tonePlay(AUDIO_WAVE_TRIANGLE, WALL_TONE_HZ, WALL_TONE_MS);
    }

    r = ballRect();

    if (brickHit(&r)) {
        sGame.ballX  -= sGame.ballDx;
        sGame.ballDx  = -sGame.ballDx;
    }

    sGame.ballY += sGame.ballDy;

    if (sGame.ballY < 0) {
        sGame.ballY  = 0;
        sGame.ballDy = -sGame.ballDy;
        tonePlay(AUDIO_WAVE_TRIANGLE, WALL_TONE_HZ, WALL_TONE_MS);
    }

    r = ballRect();

    if (brickHit(&r)) {
        sGame.ballY  -= sGame.ballDy;
        sGame.ballDy  = -sGame.ballDy;
    } else if (sGame.ballDy > 0 && rectsOverlap(&r, &paddle)) {
        // Where it meets the paddle sets its angle: the middle sends it
        // straight up, the ends off to the side.
        int32_t offset = r.x + BALL_SIZE / 2 - (sGame.paddleX + PADDLE_W / 2);

        sGame.ballDx = clampRange(sGame.speed * offset / (PADDLE_W / 2), -sGame.speed, sGame.speed);
        sGame.ballDy = -sGame.speed;
        sGame.ballY  = (PADDLE_Y - BALL_SIZE) * FIX_ONE;
        tonePlay(AUDIO_WAVE_SQUARE, PADDLE_TONE_HZ, PADDLE_TONE_MS);
    } else if (r.y >= FB_H) {
        ballLost();
    }
}

The ball’s place and speed are in 256ths of a pixel (FIX_SHIFT), integers that move smoothly at any speed; there is no floating point anywhere in the game, which on a 486 would cost more than it is worth.

platformMicros() is the clock under all of this, a 64-bit count of microseconds that never goes backward; use it for any game time (milliseconds are platformMicros() / 1000). There is no vertical retrace to wait for in a window: the game’s window is composited with the rest of the desktop, and its frame rate is a virtual one. 60 and 70 frames a second both work; take the rate the game was designed for. (On the whole screen there is a retrace, Section 17.7.) gameFrameNext(&pacer, &missed) does what gameFrameWait does without the waiting, returning when the next frame begins, for a program that waits its own way; the DVX BASIC runtime runs FRAMEWAIT on it.

17.5.1. The Timer Service

Work that must happen at a steady rate however busy the programs are, a music player of the game’s own or a sequencer to the millisecond, belongs to the timer service: one timer interrupt that calls up to 16 functions (PLATFORM_TIMER_SLOTS, shared with DVX’s own libraries: the sound, the music, and the joysticks use some), each at its own rate of up to 1,000 times a second. DVX speeds the interrupt up only as far as the fastest function needs, and keeps the DOS clock at its usual rate. gameTimerAdd(ctx, hz, fn, userData) adds a function for the calling program, and the timer is removed when the program ends, however it ends; platformTimerRemove(id) removes it sooner, and when it returns the function is not running and will not run again. It returns -1 when hz is out of range or every slot is taken.

The function runs inside the timer interrupt, with interrupts disabled, on a small stack, and the rules are strict: keep it to a few dozen microseconds; call nothing of the C library, DVX, or DOS; use no floating point; and touch only code and data pinned in memory with platformLockRegion, since a page fault there is fatal. Setting a flag or a counter, filling a buffer, and writing I/O ports are what it is for:

#define TICK_HZ          1000
#define TICK_LOCK_BYTES  64     // onTick's code, pinned for the interrupt

static volatile uint32_t sTicks = 0;
static int32_t           sTimer = -1;

// Inside the timer interrupt: count, and nothing more.
static void onTick(void *userData) {
    (void)userData;
    sTicks++;
}

// In appMain, before the loop:
platformLockRegion((const void *)onTick, TICK_LOCK_BYTES, true);
platformLockRegion((const void *)&sTicks, sizeof(sTicks), false);
sTimer = gameTimerAdd(sAc, TICK_HZ, onTick, NULL);

// ... and after it:
platformTimerRemove(sTimer);
platformUnlockRegion((const void *)&sTicks, sizeof(sTicks), false);
platformUnlockRegion((const void *)onTick, TICK_LOCK_BYTES, true);

The game’s loop reads sTicks as it likes. Data the loop and the interrupt both change needs platformIrqSave() and platformIrqRestore(state) around the few instructions that change it. A game never reprograms the timer chip or hooks the timer interrupt itself: DVX owns both.

17.6. The Screen

A window’s content buffer is in the desktop’s pixel format, which the user chooses: 8, 15, 16, or 32 bits per pixel (Section 9.5). A game that must look the same everywhere draws into a framebuffer of its own instead, here 320 x 200 bytes, each a color number in a palette of 256 colors the game chooses, and converts only what changed into the content buffer each frame.

17.6.1. The Game’s Palette and the Color Table

static void paletteInit(void) {
    static const uint8_t fixed[][PAL_CHANNELS] = {
        [COL_BLACK]           = { 0, 0, 0 },
        [COL_PADDLE]          = { 80, 200, 255 },
        [COL_PADDLE_EDGE]     = { 255, 255, 255 },
        [COL_BALL]            = { 255, 255, 96 },
        [COL_BRICK_FIRST]     = { 232, 64, 64 },
        [COL_BRICK_FIRST + 1] = { 240, 144, 48 },
        [COL_BRICK_FIRST + 2] = { 232, 216, 64 },
        [COL_BRICK_FIRST + 3] = { 80, 200, 80 },
        [COL_BRICK_FIRST + 4] = { 64, 176, 232 },
        [COL_BRICK_FIRST + 5] = { 160, 96, 232 }
    };

    memset(sGamePal, 0, sizeof(sGamePal));
    memcpy(sGamePal, fixed, sizeof(fixed));

    for (int32_t i = 0; i < SKY_SHADES; i++) {
        uint8_t *c = &sGamePal[(COL_SKY_FIRST + i) * PAL_CHANNELS];

        c[PAL_RED]   = (uint8_t)(SKY_TOP_R + (SKY_BOTTOM_R - SKY_TOP_R) * i / (SKY_SHADES - 1));
        c[PAL_GREEN] = (uint8_t)(SKY_TOP_G + (SKY_BOTTOM_G - SKY_TOP_G) * i / (SKY_SHADES - 1));
        c[PAL_BLUE]  = (uint8_t)(SKY_TOP_B + (SKY_BOTTOM_B - SKY_TOP_B) * i / (SKY_SHADES - 1));
    }
}

The palette is 768 bytes, red, green, and blue for each of PAL_ENTRIES (256) colors (dvxPal.h). Bounce uses a few fixed colors, one for each row of bricks, and a 50-step gradient for the sky. For each game color the game keeps the desktop pixel that shows it, and builds the table again when the desktop changes:

// Desktop pixels for game colors first .. first + count - 1.
static void lutSetRange(int32_t first, int32_t count) {
    const DisplayT *d = dvxGetDisplay(sAc);

    for (int32_t i = first; i < first + count; i++) {
        const uint8_t *c = &sGamePal[i * PAL_CHANNELS];

        sLut[i] = d->palette ? gamePalNearest(d->palette, c[PAL_RED], c[PAL_GREEN], c[PAL_BLUE]) : packColor(d, c[PAL_RED], c[PAL_GREEN], c[PAL_BLUE]);
    }
}


// Rebuild the whole table when the desktop's pixel format or 256-color
// palette changed (the user can change the video mode while the game
// runs).  True when it did: everything must be drawn again.
static bool lutSync(void) {
    const DisplayT *d = dvxGetDisplay(sAc);

    if (d->format.bitsPerPixel == sLutBits && (!d->palette || memcmp(sDeskPal, d->palette, PAL_BYTES) == 0)) {
        return false;
    }

    sLutBits = d->format.bitsPerPixel;

    if (d->palette) {
        memcpy(sDeskPal, d->palette, PAL_BYTES);
    }

    lutSetRange(0, PAL_ENTRIES);
    return true;
}

At 15, 16, and 32 bits per pixel packColor makes the pixel: exactly at 32 bits, and with the low bits of each channel dropped at 15 and 16. At 8 bits every window shares the desktop’s one palette, a 6 x 6 x 6 cube of colors, a ramp of 16 grays, and the colors of DVX’s own frames, and a program cannot change it, so gamePalNearest(pal, r, g, b) finds the nearest of its colors (the smallest distance in red, green, and blue; the lowest index on a tie). Gradients come out banded on a 256-color desktop; design for it, or say in the game’s help that it looks best at 15 bits or more. The user can change the video mode while the game runs; lutSync, once a frame, compares the depth and the palette with what the table was made for, and a change draws the whole frame again.

gamePalNearest searches all 256 entries, fine for a table of 256 game colors. A game that maps many colors, a picture in true color for example, uses a GamePalCacheT instead, about 37 KB (allocate it): gamePalCacheInit(cache, pal) records the palette, gamePalCacheLookup(cache, r, g, b) finds the nearest entry for the color’s 15-bit cell once and remembers it, and gamePalCacheSync(cache, pal), once a frame, starts over when the palette changed:

GamePalCacheT *cache = (GamePalCacheT *)malloc(sizeof(GamePalCacheT));
const uint8_t *pal   = dvxGetDisplay(ac)->palette;    // NULL above 8 bits

if (cache && pal) {
    gamePalCacheInit(cache, pal);
    pixel = gamePalCacheLookup(cache, r, g, b);
}

17.6.2. Drawing and Putting Back

// Put the background back where the paddle and the ball were and draw
// them where they are.
static void drawSprites(const GameRectT *oldPaddle, const GameRectT *oldBall) {
    GameRectT ball = ballRect();

    fbBackground(oldPaddle);
    fbBackground(oldBall);
    fbFill(sGame.paddleX, PADDLE_Y, PADDLE_W, PADDLE_H, COL_PADDLE_EDGE);
    fbFill(sGame.paddleX + PADDLE_EDGE, PADDLE_Y + PADDLE_EDGE, PADDLE_W - 2 * PADDLE_EDGE, PADDLE_H - 2 * PADDLE_EDGE, COL_PADDLE);
    fbFill(ball.x, ball.y, ball.w, ball.h, COL_BALL);
    dirtyAdd(oldPaddle->x, oldPaddle->y, oldPaddle->w, oldPaddle->h);
    dirtyAdd(oldBall->x, oldBall->y, oldBall->w, oldBall->h);
    dirtyAdd(sGame.paddleX, PADDLE_Y, PADDLE_W, PADDLE_H);
    dirtyAdd(ball.x, ball.y, ball.w, ball.h);
}

Bounce draws with fbFill, a rectangle of one color cut to the framebuffer, and keeps a list of the rectangles that changed. Before a moving sprite is drawn in its new place, what lay behind it is put back: the sky and, since a new game or level can put bricks back where the ball was, the part of any standing brick:

// Put back what lies behind a sprite: the sky, and the part of any
// standing brick inside r (a new game or level puts bricks back where the
// ball was).
static void fbBackground(const GameRectT *r) {
    int32_t rowFirst;
    int32_t rowLast;
    int32_t colFirst;
    int32_t colLast;

    fbSky(r->x, r->y, r->w, r->h);

    if (!brickSpan(r, &rowFirst, &rowLast, &colFirst, &colLast)) {
        return;
    }

    for (int32_t row = rowFirst; row <= rowLast; row++) {
        for (int32_t col = colFirst; col <= colLast; col++) {
            GameRectT b      = brickRect(row, col);
            int32_t   left   = DVX_MAX(r->x, b.x);
            int32_t   top    = DVX_MAX(r->y, b.y);
            int32_t   right  = DVX_MIN(r->x + r->w, b.x + b.w);
            int32_t   bottom = DVX_MIN(r->y + r->h, b.y + b.h);

            if (sGame.bricks[row][col]) {
                fbFill(left, top, right - left, bottom - top, (uint8_t)(COL_BRICK_FIRST + row));
            }
        }
    }
}
// The rows and columns of bricks r reaches; false when it lies above or
// below them all.  Only those bricks need looking at.
static bool brickSpan(const GameRectT *r, int32_t *rowFirst, int32_t *rowLast, int32_t *colFirst, int32_t *colLast) {
    if (r->y >= BRICKS_BOTTOM || r->y + r->h <= BRICKS_TOP) {
        return false;
    }

    *rowFirst = clampRange((r->y - BRICKS_TOP) / BRICK_H, 0, BRICK_ROWS - 1);
    *rowLast  = clampRange((r->y + r->h - 1 - BRICKS_TOP) / BRICK_H, 0, BRICK_ROWS - 1);
    *colFirst = clampRange((r->x - BRICKS_LEFT) / BRICK_W, 0, BRICK_COLS - 1);
    *colLast  = clampRange((r->x + r->w - 1 - BRICKS_LEFT) / BRICK_W, 0, BRICK_COLS - 1);
    return true;
}

brickSpan turns a rectangle into the rows and columns of bricks it can touch, so both this and the collision test look at four bricks at most rather than sixty. The list of changes holds up to DIRTY_MAX rectangles; more than that, and the whole frame goes:

// Remember a rectangle to copy to the window this frame, cut to the
// framebuffer; with too many, the whole screen goes.
static void dirtyAdd(int32_t x, int32_t y, int32_t w, int32_t h) {
    int32_t right  = DVX_MIN(x + w, FB_W);
    int32_t bottom = DVX_MIN(y + h, FB_H);

    x = DVX_MAX(x, 0);
    y = DVX_MAX(y, 0);

    if (right <= x || bottom <= y) {
        return;
    }

    if (sDirtyCount == DIRTY_MAX) {
        sDirty[0]   = (GameRectT){ 0, 0, FB_W, FB_H };
        sDirtyCount = 1;
        return;
    }

    sDirty[sDirtyCount++] = (GameRectT){ x, y, right - x, bottom - y };
}

17.6.3. Presenting a Frame

// Copy this frame's changed rectangles to the window and tell DVX.  On
// the whole screen the whole frame goes to the screen instead.
static void present(void) {
    if (sDirtyCount > 0 && dvxExclusivePresent8(sAc, sFb, FB_W, FB_H, FB_W)) {
        sDirtyCount = 0;
        return;
    }

    for (int32_t i = 0; i < sDirtyCount; i++) {
        const GameRectT *r = &sDirty[i];

        presentRect(r);
        dvxInvalidateRect(sAc, sWin, r->x * sScale, r->y * sScale, r->w * sScale, r->h * sScale);
    }

    sDirtyCount = 0;
}


// Framebuffer rectangle -> content buffer, scaled, cut to the window.
static void presentRect(const GameRectT *r) {
    if (!sWin->contentBuf) {
        return;
    }

    int32_t bpp   = dvxGetDisplay(sAc)->format.bytesPerPixel;
    int32_t pitch = sWin->contentPitch;
    int32_t right = DVX_MIN(r->x + r->w, sWin->contentW / sScale);
    int32_t lines = DVX_MIN(r->y + r->h, sWin->contentH / sScale);
    int32_t count = right - r->x;

    if (count <= 0) {
        return;
    }

    size_t bytes = (size_t)(count * sScale * bpp);

    for (int32_t row = r->y; row < lines; row++) {
        uint8_t *dst = sWin->contentBuf + row * sScale * pitch + r->x * sScale * bpp;

        expandRow(dst, &sFb[row * FB_W + r->x], count, bpp);

        for (int32_t s = 1; s < sScale; s++) {
            memcpy(dst + s * pitch, dst, bytes);
        }
    }
}

present expands each changed rectangle through the color table into the window’s content buffer (win→contentBuf, win→contentPitch bytes from one row to the next, contentW by contentH pixels), repeating each pixel sScale times across and each row sScale times down, and then tells DVX with dvxInvalidateRect, in content pixels, so that the next frame composites it (Section 9.9). It clips to the content area, and does nothing while contentBuf is NULL. expandRow writes one row, with a loop for each pixel size, chosen once per row:

// One framebuffer row to desktop pixels, each repeated sScale times.
static void expandRow(uint8_t *dst, const uint8_t *src, int32_t count, int32_t bytesPerPixel) {
    switch (bytesPerPixel) {
        case 1:
            for (int32_t i = 0; i < count; i++) {
                memset(dst, (uint8_t)sLut[src[i]], (size_t)sScale);
                dst += sScale;
            }

            break;

        case 2: {
            uint16_t *d = (uint16_t *)dst;

            for (int32_t i = 0; i < count; i++) {
                uint16_t v = (uint16_t)sLut[src[i]];

                for (int32_t s = 0; s < sScale; s++) {
                    *d++ = v;
                }
            }

            break;
        }

        default: {
            uint32_t *d = (uint32_t *)dst;

            for (int32_t i = 0; i < count; i++) {
                uint32_t v = sLut[src[i]];

                for (int32_t s = 0; s < sScale; s++) {
                    *d++ = v;
                }
            }

            break;
        }
    }
}
// DVX asks for the whole content buffer (first show, a video mode
// change): copy the whole framebuffer.  DVX puts it on the screen
// afterwards.
static void onPaint(WindowT *win, RectT *dirty) {
    GameRectT all = { 0, 0, FB_W, FB_H };

    (void)win;
    (void)dirty;
    lutSync();
    presentRect(&all);
}

onPaint converts the whole framebuffer, without invalidating: DVX calls it when the window is first shown and after a video mode change, when the content buffer has been made again, and composites the window itself afterward. Copying only what changed matters: at twice the size on a 16-bit desktop, a whole 320 x 200 frame is 256,000 pixels, 512,000 bytes, to convert, and as many to composite and copy to the screen.

17.6.4. Palette Animation

// Palette animation: only the ball's palette entry changes, so only its
// desktop pixel is looked up again.  On the whole screen at 8 bits per
// pixel the new color goes to the DAC at once.
static void ballGlow(void) {
    uint32_t phase = sGame.frame++ % BALL_GLOW_PERIOD;
    uint32_t tri   = phase < BALL_GLOW_PERIOD / 2 ? phase : BALL_GLOW_PERIOD - phase;
    uint8_t  glow  = (uint8_t)(BALL_GLOW_MIN + BALL_GLOW_RANGE * tri / (BALL_GLOW_PERIOD / 2));

    sGamePal[COL_BALL * PAL_CHANNELS + PAL_BLUE] = glow;
    lutSetRange(COL_BALL, 1);
    dvxExclusiveSetPalette(sAc, sGamePal, COL_BALL, 1);
}

Changing the colors rather than the pixels (color cycling, fades, a glowing ball) works at every depth: change the game palette’s entries, look up just those entries again, and redraw the pixels that use them. Bounce’s ball is redrawn every frame anyway. On the whole screen at 8 bits per pixel the palette is the screen’s own, and dvxExclusiveSetPalette changes the colors at once, without redrawing anything. A game whose hardware chose a palette for each scan line keeps one color table for each palette and picks the table for each row.

17.7. The Whole Screen

// Alt+Enter: the whole screen at 320x200 (or the nearest mode DVX has),
// or back to the window.  The other programs run on either way.
static void fullSet(bool on) {
    if (on && dvxExclusiveBegin(sAc, sWin, FB_W, FB_H, FULL_BPP, fullChanged, NULL) != DVX_EXCL_OK) {
        dvxLog("bounce: no full-screen mode");
        on = false;
    }

    if (!on && sFull) {
        dvxExclusiveEnd(sAc, sWin);
        dirtyAdd(0, 0, FB_W, FB_H);
    }

    sFull = on;
    wmMenuItemSetChecked(sWin->menuBar, CMD_GAME_FULL, on);
}
// Full screen came, went away for a while (another window has the focus:
// the game draws in its window again), or ended.
static void fullChanged(WindowT *win, ExclusiveStateE state, void *userData) {
    (void)win;
    (void)userData;

    if (state == ExclusiveEndedE) {
        sFull = false;
        wmMenuItemSetChecked(sWin->menuBar, CMD_GAME_FULL, false);
    }

    if (state == ExclusiveActiveE) {
        dvxExclusiveSetPalette(sAc, sGamePal, 0, PAL_ENTRIES);
    }

    dvxLog("bounce: full screen %s", state == ExclusiveActiveE ? "on" : state == ExclusiveSuspendedE ? "suspended" : "ended");
    dirtyAdd(0, 0, FB_W, FB_H);
}
Bounce filling the whole screen with its bricks and paddle
Figure 26. Bounce on the whole screen

A game can take the whole screen in a video mode of its own, as Bounce does with Alt+Enter. Every other program keeps running while it does: their windows go on painting into their own buffers, their timers fire, their sound plays, and the desktop is drawn again, as it is then, when the game lets go.

  • dvxExclusiveBegin(ac, win, width, height, bpp, onChange, userData) sets the smallest video mode of at least width by height, at bpp bits per pixel when there is one (0: any depth), raises and focuses win, and returns DVX_EXCL_OK, or DVX_EXCL_ERR_MODE (no mode could be set), DVX_EXCL_ERR_BUSY (another window has the screen), or DVX_EXCL_ERR_ARGS. At 8 bits, a request that fits 320 x 200 gets the VGA’s mode 13h, and one that fits 320 x 240 the VGA’s Mode X (square pixels, and two pages, so a whole frame is shown from the next retrace and never tears), unless the card has a VESA mode no larger with a linear framebuffer. Either way the game draws into an ordinary linear backbuffer. The mode may be larger than asked for.

  • The window must have the focus. When it loses it (Alt+Tab, Ctrl+Esc, a dialog box, another program’s window coming forward), the desktop comes back and onChange hears ExclusiveSuspendedE; when the window has the focus again the mode is set again and it hears ExclusiveActiveE, before dvxExclusiveBegin returns the first time too. Draw the whole frame then: the screen starts black. If the mode cannot be set again, it hears ExclusiveEndedE, and the full screen is over.

  • While the game has the screen, every key but Alt+Tab, Ctrl+Esc, and Alt+F4 goes to its window, as in a game input window; DVX draws no mouse pointer, and onMouse gets whole-screen coordinates.

  • dvxExclusivePresent8(ac, fb, w, h, pitch) shows a picture of palette numbers on the whole screen, scaled by the largest whole factor that fits and centered on black, in any pixel format; it returns false when the game does not have the screen (suspended, or not full screen), and Bounce’s present then draws into the window as usual. Its palette is the one dvxExclusiveSetPalette(ac, pal, first, count) gave, which dvxExclusiveBegin resets to the desktop’s; hence fullChanged sets the whole palette at ExclusiveActiveE. At 8 bits per pixel the palette goes to the hardware at once.

  • To draw the screen itself rather than present a picture, draw into dvxExclusiveDisplay(ac)→backBuf (DVX’s drawing calls work on it, with dvxExclusiveBlitOps(ac); Section 9.3) and call dvxExclusiveFlush(ac, rect), or NULL for all of it. dvxExclusiveWaitRetrace() waits for the vertical retrace before a flush, so the frame is not torn. dvxExclusiveDisplay returns NULL while the game does not have the screen.

  • dvxExclusiveEnd(ac, win) gives the screen back, without an onChange call. Closing the window, the program ending, and End Task give it back too.

  • dvxExclusiveMirror(ac, win, onChange, userData) instead shows the window’s own content on the whole screen, its widgets or what it draws into its content buffer, scaled and centered the same way, in the desktop’s pixel format, and kept up to date as the window paints; the mouse works on it as in the window, with its pointer drawn.

17.8. Sound in a Game

// The sound device, the brick sound and the music, from our own .app
// file's resources.  Any of them may be missing: the game plays on.
static void soundLoad(void) {
    DvxResHandleT *res        = dvxResOpen(sCtx->appPath);
    uint32_t       brickSize  = 0;
    uint32_t       musicSize  = 0;
    void          *brick      = res ? dvxResRead(res, RES_BRICK, &brickSize) : NULL;
    void          *tune       = res ? dvxResRead(res, RES_MUSIC, &musicSize) : NULL;
    AudioInfoT     info;
    MusicInfoT     musicInfo;

    dvxResClose(res);
    sAudio = audioOpen();

    if (sAudio) {
        audioNotesOpen(sAudio, AUDIO_WAVE_SQUARE, JINGLE_VOLUME, &sJingle);
        audioSampleLoadMem(sAudio, brick, brickSize, &sBrickSound);
    }

    if (tune && musicLoadMem(tune, musicSize, &sMusic) == MUSIC_OK) {
        musicSetVolume(sMusic, MUSIC_VOLUME);
        musicApply();
    }

    free(brick);
    free(tune);
    audioGetInfo(&info);
    musicGetInfo(sMusic, &musicInfo);
    dvxLog("bounce: sound %s, music on %s", info.running ? info.description : "off", sMusic ? musicInfo.output : "nothing");
}

A game plays sound on whatever the computer has, and nothing fails for want of hardware: with none, the null driver plays nothing and the game goes on silently (Section 16.1). Bounce takes its brick sound and its tune from its own .app file’s resources, opens a note queue for its jingles and keeps it open for the whole game (its music keeps the sound device running anyway), and starts the music. Each broken brick plays the sample panned to where the brick was:

// Break the first brick r touches, if any.
static bool brickHit(const GameRectT *r) {
    int32_t rowFirst;
    int32_t rowLast;
    int32_t colFirst;
    int32_t colLast;

    if (!brickSpan(r, &rowFirst, &rowLast, &colFirst, &colLast)) {
        return false;
    }

    for (int32_t row = rowFirst; row <= rowLast; row++) {
        for (int32_t col = colFirst; col <= colLast; col++) {
            GameRectT b = brickRect(row, col);

            if (!sGame.bricks[row][col] || !rectsOverlap(r, &b)) {
                continue;
            }

            sGame.bricks[row][col] = 0;
            sGame.bricksLeft--;
            sGame.score += (BRICK_ROWS - row) * BRICK_POINTS;
            fbSky(b.x, b.y, b.w, b.h);
            dirtyAdd(b.x, b.y, b.w, b.h);
            audioPlay(sBrickSound, BRICK_VOLUME, panAt(b.x + b.w / 2), false);
            titleUpdate();
            return true;
        }
    }

    return false;
}

The walls and the paddle play short tones, panned to the ball, and the jingles for a lost ball, a new wall, and the end of the game go on the note queue, which plays each note for exactly its length while the game goes on:

// A note queue plays the notes one after the other, each for exactly its
// length, while the game goes on.
static void jinglePlay(const uint32_t *hz, int32_t count) {
    for (int32_t i = 0; i < count; i++) {
        audioNotesAdd(sJingle, hz[i] * AUDIO_MILLIHZ_PER_HZ, JINGLE_NOTE_MS * US_PER_MS);
    }
}

The music plays while it is switched on and the game is not paused; musicPlay resumes a paused music where it stopped. Sampled sound plays from the card’s interrupt however busy the game is, but the end calls, streams, modules, and the software synthesizer are made in program time, which is why the game’s loop calls musicPump() once a frame (Section 16.13). Chapter 16 covers the rest: streams for sound the game makes as it goes, tones to change while they play (audioVoiceSetFrequency), live MIDI for a score that follows the game, and the FM chip for a music driver of the game’s own.

17.9. Data Files and Saved Games

DOS has one current directory for everything, so a game never relies on it. Its context has the paths it needs:

Member What it is Use it for

appPath

The program’s .app file.

dvxResOpen: resources inside the .app.

appDir

The folder the .app is in.

Its DATA folder: game data, read-only.

userDir

The program’s own folder in the user folder.

Saved games, high scores, options.

helpFile

The program’s .hlp file.

shellOpenHelpFile (F1).

  • Small data (sounds, a tune, a title picture) can travel inside the .app as resources, listed in NAME.res as binary and read with dvxResOpen(ctx→appPath) and dvxResRead, as Bounce carries its sound and music (Chapter 20). The game is then one file.

  • Bigger data goes in the DATA folder beside the .app: list the files in the Makefile’s `DATA setting, and make package puts them there (Section 16.2). Build their paths with shellDataPath(ctx, "LEVEL1.DAT", path, size). DVX never writes there.

  • Saved games belong in userDir, which DVX keeps apart from the program files, so a reinstall never overwrites them and a backup of the user folder keeps them: USER\APPS\LOCAL\BOUNCE for Bounce. Make it with shellEnsureUserDir(ctx) before the first write, and build the names with shellUserPath(ctx, "SAVE1.DAT", path, size) (Chapter 10).

  • For settings and scores, prefsLoad and prefsSaveAs read and write INI files safely: a save that fails leaves the old file as it was.

  • Use 8.3 file names, and check platformDiskSpace before a big save.

static void loadBest(void) {
    char path[DVX_MAX_PATH];

    shellUserPath(sCtx, SAVE_FILE, path, sizeof(path));

    PrefsHandleT *prefs = prefsLoad(path);

    sGame.best = prefs ? prefsGetInt(prefs, SAVE_SECTION, SAVE_KEY_BEST, 0) : 0;
    prefsClose(prefs);
}
// A new best score lives in the program's own user folder
// (USER\APPS\...), which DVX keeps apart from the program files.
static void saveBest(void) {
    char path[DVX_MAX_PATH];

    if (sGame.score <= sGame.best) {
        return;
    }

    sGame.best = sGame.score;
    shellEnsureUserDir(sCtx);
    shellUserPath(sCtx, SAVE_FILE, path, sizeof(path));

    PrefsHandleT *prefs = prefsLoad(path);

    if (!prefs) {
        return;
    }

    prefsSetInt(prefs, SAVE_SECTION, SAVE_KEY_BEST, sGame.best);
    dvxLog("bounce: best score %" PRId32 " %s", sGame.best, prefsSaveAs(prefs, path) ? "saved" : "could not be saved");
    prefsClose(prefs);
}

17.10. Packaging and Ending

A game is packaged like any program (Chapter 21): make package lays out pkg/ as the files go into the DVX folder, the .app with its DATA folder and its help, and makes the .dpk that Software installs. Every game should have its own help file, since F1 in a game input window goes to the game: open it from the game’s F1 and from Help › Contents. A game built on a static library of its own links it in with the Makefile’s `LIBS setting (LIBS = port/libgame.a; Appendix A).

Close the game’s window and return from appMain. Every sound, music, joystick handle, timer, and the whole screen the program held is released when it ends, however it ends, so a crash or End Task leaves nothing playing. exit() and abort() end only the game, as End Task does: its windows close, its timers are removed, and DVX keeps running. The functions the game gave atexit are its own: exit() runs them first, and so does a normal end, after appShutdown; abort() and _exit() drop them. Returning from appMain is still the cleanest way out. malloc and free work as usual, and DVX counts the game’s memory (Section 3.9).

17.11. Games in DVX BASIC

newProject.sh basicgame NAME starts a game in DVX BASIC, which does what the C template does in a few dozen lines. A Timer fires once and runs the game loop; FRAMEWAIT rate waits for the next frame while the desktop and the program’s forms go on running; GameKeyDown says whether a key is held, FrameMissed() counts the frames FRAMEWAIT skipped, QBasic’s STICK and STRIG read joysticks, and BEEP, SOUND, and PLAY make sound, PLAY "MB …​" in the background so the game does not wait. The declaration files game.bas, sound.bas, music.bas, and joystick.bas (in the SDK’s include/basic) give BASIC the rest of these libraries. The DVX BASIC Programming Guide teaches them.

17.12. Porting a Game Library to DVX

A game written for DOS or another system usually sits on a game library that owns the screen, the keyboard, the timer, and the sound card. Bringing such a library to DVX means mapping each of those onto DVX’s calls in this chapter, and replacing what DVX does not allow, such as exiting the process, blocking loops, and direct hardware. Section B.4, in the appendix on porting C code, goes through the whole job: the model to aim for, a map from the usual library calls to DVX’s, what to watch for, and a checklist.

Part III: Extending DVX

Chapter 18. Writing a Library

A library is a module of functions that programs, widgets, and other libraries call as if the functions were linked into them. DVX loads a library the first time something needs it and keeps it until DVX exits, so one copy of its code and its data serves every program that runs. This chapter builds TextStat, a library that counts the words, lines, and sentences of text: its C interface and its code, tsdemo, a C program that uses it, and textstat.bas, the declarations that give it to DVX BASIC. On the way it covers what a library exports, when and how DVX loads it, the .dep file, the binary interface a library promises its callers, state that several programs share, and how numbers and strings cross between BASIC and C.

18.1. When to Write a Library

Write a library for code that more than one module uses: a file format, a protocol, a device, an engine of any kind. The programs then stay thin windows over it, and a fix in the library reaches all of them at once. DVX is built this way: the network, the databases, printing, sound, the packages, and the help files are libraries, which programs such as Software, Terminal, and the help viewer use.

Write one, too, for something DVX BASIC programs need from C. A BASIC program reaches C code only through a library (Section 18.9), whether for speed (a loop over every byte of a file or every pixel of a picture), for hardware, or for a C library you port.

Do not write one for code only one program uses: put it in the program, which may have as many .c files as you like. Do not write one for a part of the user interface either: that is a widget (Chapter 19). And know the costs. A library stays loaded, with all its memory, until DVX exits. Its exported names share one name space with every other module. And its interface is a promise: modules compiled against its header depend on it not changing (Section 18.6).

18.2. The Library Template

newProject.sh library NAME makes a library project:

File What it is

Makefile

KIND = library.

NAME.c

The functions, and DVX_ABI_STAMP(NAME).

NAME.h

The public header that callers include, with a version constant, NAME_VERSION.

NAME.dep

The libraries to load before this one, one per line; the template lists libdvx (Section 18.5.1).

NAME.bas

The DVX BASIC declarations of the functions BASIC may call.

NAME.dhs

The library’s help, which DVX adds to its own (Section 18.10).

NAME.res, icon32.bmp

Resources that name the module: its name, author, and description, and an icon.

make builds NAME.lib, with the resources appended, and NAME.hlp. Three of the template’s functions show the kinds of value a BASIC program passes: two numbers in and a number out (tplNameAdd), a string in and a string out (tplNameGreet), and bytes in and out (tplNameXor).

TextStat is laid out the same way with two changes: its C code is in two files, textstat.c for the C interface and textstatBas.c for the functions BASIC calls, and its .res has no icon, since nothing in DVX shows a library’s. The book’s copy is in examples/textstat; build it as you built hello (Section 1.5):

SDK_DIR ?= ../../../../bin/sdk
KIND     = library
NAME     = textstat

include $(SDK_DIR)/sdk.mk

18.3. The C Interface

The header is what a caller compiles against. TextStat’s has a version, a structure, and four functions:

// The version of this interface: raised when functions are added, so a
// caller can compare it with the library it got (textStatVersion).
#define TEXTSTAT_VERSION 1

// What has been counted so far.  The caller owns it (on its stack, in
// its data), so its size and layout are part of the interface.
typedef struct {
    int32_t chars;       // characters, line ends not counted
    int32_t words;       // runs of characters between white space
    int32_t wordChars;   // the characters of the words
    int32_t lines;       // lines, the empty ones included
    int32_t sentences;   // runs of . ! ? that end a word
    uint8_t prev;        // the last character counted (0: none yet)
} TextStatT;

// Count text (a C string) after what stats holds already: a word or a
// line may continue from one call to the next.
void    textStatAdd(TextStatT *stats, const char *text);

// The average length of a word in characters; 0 when there are no words.
double  textStatAverage(const TextStatT *stats);

// Start stats with nothing counted.
void    textStatInit(TextStatT *stats);

// TEXTSTAT_VERSION of the library that is loaded.  BASIC calls it too.
int32_t textStatVersion(void);

A caller makes a TextStatT where it likes, usually on its stack, starts it with textStatInit, and adds text to it with textStatAdd, all at once or a piece at a time. The library keeps nothing of the caller’s between calls, so any number of programs can count at once, each with its own TextStatT.

The counting is one pass over the text:

// One pass, one character at a time.  Everything the next call needs to
// carry on (are we in a word? at the start of a line?) follows from the
// last character counted, so that is all TextStatT keeps.
void textStatAdd(TextStatT *stats, const char *text) {
    for (const uint8_t *p = (const uint8_t *)text; *p; p++) {
        uint8_t c      = *p;
        uint8_t prev   = stats->prev;
        bool    inWord = prev != 0 && !isSpace(prev);

        stats->lines += (prev == 0 || prev == '\n') ? 1 : 0;
        stats->chars += (c == '\r' || c == '\n') ? 0 : 1;

        if (!isSpace(c)) {
            stats->words += inWord ? 0 : 1;
            stats->wordChars++;
        }

        stats->sentences += (isEnd(c) && inWord && !isEnd(prev)) ? 1 : 0;
        stats->prev       = c;
    }
}

Everything the next call needs in order to go on, such as whether the last piece ended in the middle of a word or at the end of a line, follows from the last character counted, so prev is the only state the structure carries besides the counts. A line starts at the first character and after every line end, so an empty line counts and a last line without a line end counts too. A sentence ends where a run of ., !, or ? ends a word, which is a rule of thumb: “3.14” ends a sentence by it.

18.4. What a Library Exports

dxe3gen exports every name in the module that is not static: functions and variables alike. nm on TextStat’s objects shows them (the sections are left out):

$ i586-pc-msdosdjgpp-nm textstat.o textstatBas.o

textstat.o:
00000228 T _textstatAbiVersion
00000000 T _textStatAdd
00000180 T _textStatAverage
000001b0 T _textStatInit
00000220 T _textStatVersion

textstatBas.o:
         U _dvxMemAppIdPtr
         U _free
         U _malloc
00000000 t _onAppEnded
00000050 b _sCounters
         U _shellRegisterAppCleanup
00000320 t _sNoCounts
         U _snprintf
00000000 b _sSummary
         U _textStatAdd
00000050 T _textStatAddLine
...

The capital T lines are the exports: the four functions of the header, the functions textstatBas.c gives BASIC, and textstatAbiVersion, the stamp (Section 18.6). The lower-case lines are the module’s own: its static functions and data, which nothing else can reach. The U lines are what the library needs from elsewhere, connected as it loads, like any module’s: malloc and snprintf from DVX.EXE, shellRegisterAppCleanup from the shell (Section 3.2).

Every module’s exports share one name space, so give each exported name a prefix of the library’s own, as TextStat’s textStat and DVX’s sql, json, and http are, and make everything else static. An exported variable can be read and written by any module that declares it extern; export functions instead, so the variable’s layout and its rules stay the library’s.

A module calls another module’s function by its name, like any C function, and DVX connects the call when it loads the caller. To use a function only when it is there, look it up at run time instead: dlsym(NULL, name) finds a name in DVX.EXE or any module, and loads the library that exports it if no one has yet; platformLoadedSymbol(name) (dvxPlat.h) finds it only in what is already loaded. Both take the name as DJGPP spells it, with its leading underscore, which DVX_SYM("textStatAdd") adds at compile time. dvxLibraryLoaded(name) (dvxApp.h) asks whether a library is installed, by its base name ("textstat"), loading it if it is. A module that loads another module calls platformModuleOpen (dvxPlat.h), never dlopen, which DVX.EXE does not export to modules.

18.5. How DVX Loads a Library

When DVX starts, it finds every .lib file under LIBS and reads each one’s table of exported names, without loading it, into an index (Section 3.2). It loads at once only the libraries that run code as they load, then the shell and every widget, with what each of them needs. Every other library waits until something needs one of its names:

  • A module DVX is loading calls one of its functions. Starting tsdemo, which calls textStatAdd, loads textstat.lib first.

  • Code looks a name up with dlsym(NULL, …​). Every DVX BASIC call to a library works that way (Section 18.9), and so does dvxLibraryLoaded.

The log records each load, and at the end of the start how many libraries wait (the numbers depend on what is installed):

Loader: 44 modules loaded; 16 libraries load when first used
...
Loading: LIBS\local\textstat\textstat.lib
Shell: loaded 'TextStat Demo' (id=2, mainLoop=no, entry=0x..., desc=0x...)

What follows for a library:

  • Nothing in it runs until something calls it. Its static data is initialized as it loads, as a C program’s is; anything more it needs, it sets up on its first call.

  • The memory DVX allocates to load it belongs to DVX, not to the program whose call needed it.

  • It stays loaded, and its static data with it, until DVX exits; there is no unloading. A new version of a library takes effect when DVX starts again.

  • A library with a constructor, a function declared __attribute__((constructor)), is one that runs code as it loads, so DVX loads it as it starts, before the screen is set up and before any program runs. That is for a library that must be part of DVX from the start: DVX’s sound library’s constructor, for one, registers the idle handler that feeds its sound streams and a cleanup hook for programs that end (Section 18.7). Its destructor, if it has one, runs when DVX exits.

A library can fail to load: its file is damaged, it was built for another DVX (Section 18.6), or a library its .dep file names is not installed. Any library outside DVX’s own folder (LIBS\KPUNCH) is an add-on, and DVX does without an add-on it cannot load:

  • A failure that shows as DVX starts (a damaged file, a file named like another module, a library loaded at the start that cannot be) leaves the add-on out. DVX logs why and shows a box titled Add-ons when it is up, naming it and the reason.

  • A failure on first use is logged (“FAILED:”, the file, and the reason), and DVX does not try that library again until it restarts. The module that needed it does not load: DVX refuses to start a program that calls the library (“Failed to load” and the reason), and a BASIC program’s call to it raises error 453 (Section 18.9).

A library of DVX’s own that cannot be loaded as DVX starts stops DVX. DVX /SAFE (or Shift held down while DVX starts) loads no add-on libraries or widgets at all, which gets DVX past one that misbehaves.

18.5.1. The .dep File

A library’s or a widget’s .dep file (DVX reads none beside a program) has the module’s base name and the extension .dep, and names the modules to load before it, one base name per line, in any case; blank lines and lines that start with # are ignored. make package copies it beside the module with DOS line ends. TextStat’s names the one library whose functions it calls, the shell (for shellRegisterAppCleanup):

dvxshell

DVX loads the modules a .dep file names before the module itself, and refuses the module, naming the one that is missing, when one of them is not installed or cannot be loaded. A library whose functions a module calls is loaded first in any case, .dep or not, as the module is connected; the .dep file makes the order explicit for code that runs as a module loads (a constructor, a widget’s wgtRegister), lets a widget wait for another widget, and turns a missing library into a message that names it. List every library whose functions your module calls; the template lists libdvx, the windowing core.

18.6. The Binary Interface

The stamp records which binary interface of DVX the library was built for:

// The binary interface this library was built for, which DVX checks as
// it loads it.  The argument is the file's base name in lower case.
DVX_ABI_STAMP(textstat);

DVX_ABI_STAMP(textstat) defines the exported constant textstatAbiVersion, whose value is the DVX_ABI_VERSION of the headers the library was compiled with. As DVX loads a library or a widget, it looks for <base name>AbiVersion, the base name being the file’s name without its extension, in lower case, and compares the value with its own. A module without one, or with another value, is refused as made for a different version of DVX; DVX.LOG says which, with the numbers. So write the stamp once, at file scope, in one of the module’s source files, and keep its argument the file’s name: a library renamed without its stamp has none. When DVX’s number changes, rebuild the library with the new SDK (Section 3.11).

DVX’s stamp covers DVX’s interface. Your library’s interface is yours to keep, and every module compiled against your header depends on it in the same way: the parameters and the result of each function, and the layout of each structure the header shows, are compiled into the caller. So:

  • Never change a function’s parameters or its result, and never remove a function. A program built against the old header would call the new function wrongly, and nothing would notice. Add a function with a new name instead.

  • Never change a structure a caller allocates or reads. TextStatT lives on the caller’s stack, its size compiled into the caller; a newer library that wrote one more field would write past the end of an older caller’s. To count something more, add a structure and functions for it. A library that expects to grow can give callers only a pointer to a structure it keeps private, as TextStat does for BASIC (Section 18.7).

  • Raise TEXTSTAT_VERSION with every function you add.

The version is for callers that can do without a newer function. A C program that calls a function the installed library does not have never starts: DVX cannot connect the call, and refuses to load the program. A DVX BASIC program, though, finds each function when it first calls it, so it can ask textStatVersion() first and leave alone what the library lacks, and so can C code that looks newer functions up with dlsym. Here is the function, and the About box of tsdemo (Section 18.8), which compares the version it was built for with the one installed:

// The header's TEXTSTAT_VERSION as this library was built: a caller
// compiled against a newer header sees a smaller number here.
int32_t textStatVersion(void) {
    return TEXTSTAT_VERSION;
}

// TEXTSTAT_VERSION is the header's, compiled into this program;
// textStatVersion() asks the library DVX loaded.
static void showAbout(void) {
    char text[TSDEMO_ABOUT_MAX];

    snprintf(text, sizeof(text), TSDEMO_TITLE "\n\nBuilt for TextStat %d; TextStat %ld is installed.", TEXTSTAT_VERSION, (long)textStatVersion());
    dvxInfoBox(sCtx->shellCtx, "About " TSDEMO_TITLE, text);
}

A program that cannot run without a library says so in its package, so that Software installs the library with it: PKG_NEEDS="local.textstat=1.0.0" names the library’s package and the oldest version that will do (Chapter 21).

18.7. State That Programs Share

A library is loaded once, so there is one copy of its static data, and every program that calls it sees the same copy. Two calls never run at the same time: DVX’s tasks take turns only when one yields (Section 3.5). But a library function that yields, or calls something that does (tsYield, a dialog box, anything that runs the event loop), lets other programs run before it returns, and one of them may call the library meanwhile. Write such a function so that a second call while the first waits does no harm.

A result in a static buffer is fine: it is the caller’s until the next call, by any program. textStatSummary returns one, and says so:

// The counts as a line of text, in a buffer every program shares: it
// stays valid until the next call, and BASIC copies it as soon as this
// returns.
const char *textStatSummary(int32_t h) {
    const TextStatT *s = statsOf(h);

    snprintf(sSummary, sizeof(sSummary), "%ld words, %ld lines, %ld sentences", (long)s->words, (long)s->lines, (long)s->sentences);
    return sSummary;
}

State that belongs to one program needs more. TextStat’s functions for BASIC (Section 18.9) keep a counter, a TextStatT, for the program that asks, and give it a handle: a small number naming it. The library’s table of counters is static, shared by every program, so each counter records its owner:

#define TEXTSTAT_HANDLES_MAX  32     // counters, all programs together
#define TEXTSTAT_NO_HANDLE    0      // what textStatNew returns when it cannot
#define TEXTSTAT_SUMMARY_MAX  80     // textStatSummary's text, with its NUL

// One counter: its counts (NULL: the slot is free) and its program
typedef struct {
    TextStatT *stats;
    int32_t    owner;
} CounterT;

// One copy of each, shared by every program that calls the library
static CounterT        sCounters[TEXTSTAT_HANDLES_MAX];
static char            sSummary[TEXTSTAT_SUMMARY_MAX];
static const TextStatT sNoCounts;    // what a bad handle reads

The owner is the program whose code is running when the counter is made. DVX keeps that program’s ID where its memory allocator reads it, *dvxMemAppIdPtr (dvxMem.h), and a library can read it too. Every function that takes a handle finds the counter through counterOf, which refuses a handle that is out of range, free, or another program’s: handles are small numbers, and a program that passes a wrong one must not reach another program’s counter.

// The program whose code is running: the one calling.  DVX keeps its ID
// where the memory allocator can read it, and so can a library.
static int32_t callerId(void) {
    return *dvxMemAppIdPtr;
}


static void counterFree(CounterT *c) {
    free(c->stats);
    c->stats = NULL;
}


// The calling program's counter h, or NULL: a handle out of range, free,
// or another program's.
static CounterT *counterOf(int32_t h) {
    CounterT *c = (h > TEXTSTAT_NO_HANDLE && h <= TEXTSTAT_HANDLES_MAX) ? &sCounters[h - 1] : NULL;

    return (c && c->stats && c->owner == callerId()) ? c : NULL;
}

A program may end without freeing its counters: its author forgot, Task Manager ended it, it crashed. DVX does not free the memory a program leaves (Section 3.9), so the library must. shellRegisterAppCleanup(fn) (shellApp.h) has the shell call fn with the ID of each program that ends, however it ends, after its windows are gone:

// The shell calls this as each program ends, however it ends (closed,
// ended by Task Manager, crashed): what that program left is freed now,
// or it never would be.
static void onAppEnded(int32_t appId) {
    for (int32_t i = 0; i < TEXTSTAT_HANDLES_MAX; i++) {
        if (sCounters[i].stats && sCounters[i].owner == appId) {
            counterFree(&sCounters[i]);
        }
    }
}

textStatNew registers the hook each time it makes a counter. Registering a function that is registered already does nothing, so no flag is needed:

// A counter for the calling program: its handle, 1 and up, or
// TEXTSTAT_NO_HANDLE when the table is full or memory ran out.  The
// TextStatT is the caller's memory (malloc charges it to the program
// running), and the cleanup hook frees it if the program never does.
// Registering the hook again changes nothing, so no flag is needed.
int32_t textStatNew(void) {
    int32_t i = 0;

    while (i < TEXTSTAT_HANDLES_MAX && sCounters[i].stats) {
        i++;
    }

    if (i == TEXTSTAT_HANDLES_MAX) {
        return TEXTSTAT_NO_HANDLE;
    }

    sCounters[i].stats = (TextStatT *)malloc(sizeof(TextStatT));

    if (!sCounters[i].stats) {
        return TEXTSTAT_NO_HANDLE;
    }

    textStatInit(sCounters[i].stats);
    sCounters[i].owner = callerId();
    shellRegisterAppCleanup(onAppEnded);
    return i + 1;
}

A table of its own, with its own cleanup hook, suits TextStat, whose handles also stop one program from reaching another’s counter. For an object that only needs closing when its program ends without closing it, a file, a port, a job, dvxBas.h (in the SDK’s include/core) has a shorter way that needs no link to the shell: basHold(releaseFn, obj), when the object opens, holds it for the running program, and the shell calls releaseFn(obj) if that program ends, however it ends, before closing it; basHoldEnd(obj), first thing in the library’s own close function, lets go of it. releaseFn runs after the program’s windows and tasks are gone, so it must not call the program’s code, and must not wait. DVX’s own libraries close a program’s databases, serial ports, connections, and print jobs this way. The same header has the handle tables (BasHandlesT, made with BAS_HANDLES) and the string results (BasTextT) that DVX’s own libraries give their BASIC programs; its comments describe them all.

A library’s memory is counted the way a program’s is (Section 3.9): malloc charges a block to the program whose code is running. That is right for a counter, which Task Manager then shows as its program’s. It is wrong for memory the library keeps for itself, such as a cache that outlives every program, which would be charged to whichever program happened to call first. dvxMemSetApp(id) makes another ID the running one and returns the one before; allocate the library’s own memory as DVX_MEM_SYSTEM, DVX itself, and put the old ID back:

static uint8_t *sCache = NULL;

bool cacheEnsure(void) {
    if (!sCache) {
        int32_t prev = dvxMemSetApp(DVX_MEM_SYSTEM);

        sCache = (uint8_t *)malloc(DEMO_CACHE_SIZE);
        dvxMemSetApp(prev);
    }

    return sCache != NULL;
}

The same goes for what a library registers with the shell during a program’s call. The shell records the running program as the owner of an idle handler (shellRegisterIdle) and drops the handler when that program ends; a library that needs one for good registers it in DVX’s name the same way, or from a constructor, which runs when no program is running.

18.8. A C Program That Uses It

tsdemo counts what you type: a text box, and under it a line of counts that changes as the text does.

The TextStat Demo window with two lines of text and the counts of words, lines, sentences, and characters a word below
Figure 27. The TextStat demo, counting with the textstat library

A program that uses a library needs the library’s header to compile, and nothing else: the library itself is connected when DVX loads the program. The header is in the library’s project folder, so tsdemo adds that folder to the include path in its Makefile:

SDK_DIR ?= ../../../../bin/sdk
KIND     = app
NAME     = tsdemo

# The TextStat library's header, in its project folder beside this one.
# override: a CFLAGS given on the make command line adds to this one
# instead of replacing it.
override CFLAGS += -I../textstat

include $(SDK_DIR)/sdk.mk

The path is relative to the program’s folder: the two projects sit side by side, here and in the SDK’s samples/c, where the book’s examples are copied. override makes the addition stick when you give make a CFLAGS of your own: make CFLAGS=-g compiles with -g -I../textstat, where a plain CFLAGS += would be replaced by the command line’s. For a library somewhere else, change the path; a project without the line can be given the folder on the command line instead, as make CFLAGS=-I../mathx (Section 1.5).

The program includes the header like any other:

#include "dvxApp.h"
#include "dvxDlg.h"
#include "dvxWgt.h"
#include "dvxWm.h"
#include "shellApp.h"
#include "label/label.h"
#include "textInput/textInpt.h"
#include "textstat.h"

and counts the text box’s whole text every time it changes:

// The whole text, counted again at every change: one pass over a few
// kilobytes, quick even on a 486.  The TextStatT is on the stack; the
// library keeps nothing of the program's between calls.
static void onTextChange(WidgetT *w) {
    TextStatT stats;
    char      line[TSDEMO_LINE_MAX];

    textStatInit(&stats);
    textStatAdd(&stats, wgtGetText(w));
    snprintf(line, sizeof(line), "%ld words, %ld lines, %ld sentences, %.1f characters a word", (long)stats.words, (long)stats.lines, (long)stats.sentences, textStatAverage(&stats));
    wgtSetText(sCounts, line);
}

The window is built as in Part II’s programs: a text area that takes the window’s extra room, and a label for the counts, which the program fills once by calling its own change handler before it lays the window out.

WidgetT *root = wgtInitWindow(ac, sWin);
WidgetT *text = root ? wgtTextArea(root, TSDEMO_TEXT_MAX) : NULL;

sCounts = root ? wgtLabel(root, "") : NULL;

if (!text || !sCounts) {
    closeWindow();
    return -1;
}

text->onChange = onTextChange;
onTextChange(text);
wgtInvalidate(root);

nm tsdemo.o lists textStatAdd, textStatAverage, textStatInit, and textStatVersion as undefined (U), beside dvxCreateWindowCentered and the rest. When the user starts tsdemo, DVX finds those four in its index of library exports and loads textstat.lib before the program. When TextStat is not installed, DVX refuses to start tsdemo, naming the function it could not find.

18.9. Giving DVX BASIC the Library

A DVX BASIC program calls C through declarations: a DECLARE LIBRARY block that names the library and declares each function BASIC may call, with BASIC’s types. A library’s declarations go in a .bas file that BASIC programmers add to their projects. TextStat’s:

' textstat.bas -- DVX BASIC declarations for the TextStat library
' (textstat.lib).  Add this file to a project to count the words, lines,
' and sentences of text.
'
' A counter is a handle: textStatNew makes one (0 when no more can be
' made), textStatAddLine counts a line with it, and the other functions
' read what it counted.  textStatFree ends it; the counters a program
' leaves are freed when the program ends.

DECLARE LIBRARY "textstat"
    ' The version of the library installed
    DECLARE FUNCTION textStatVersion() AS LONG

    ' A new counter: its handle, or 0 when no more can be made
    DECLARE FUNCTION textStatNew() AS LONG

    ' Count a line of text, and the line end after it
    DECLARE SUB textStatAddLine(BYVAL h AS LONG, BYVAL text AS STRING)

    ' What the counter has counted
    DECLARE FUNCTION textStatWords(BYVAL h AS LONG) AS LONG
    DECLARE FUNCTION textStatLines(BYVAL h AS LONG) AS LONG
    DECLARE FUNCTION textStatSentences(BYVAL h AS LONG) AS LONG

    ' The average length of a word, in characters
    DECLARE FUNCTION textStatAvgWord(BYVAL h AS LONG) AS DOUBLE

    ' The counts as a line of text
    DECLARE FUNCTION textStatSummary$(BYVAL h AS LONG) AS STRING

    ' End a counter
    DECLARE SUB textStatFree(BYVAL h AS LONG)
END DECLARE

A BASIC program finds each function by its name the first time it calls it: the run time looks the name up with dlsym(NULL, …​) among everything DVX has loaded, which loads the library that exports it if nothing has yet, and keeps the address for the calls that follow. So a BASIC program needs no .dep file, and it does not fail to start when a library is missing: it runs until it first calls a function that is not there, which raises error 453, “External function not found: textStatNew”. The name in quotes after DECLARE LIBRARY says which library the functions come from; what finds each function is the function’s own name, one more reason to make exported names unique.

A BASIC name may end in a type character: $ for a string, and %, &, !, #, and @ for the numeric types. The run time looks a declared function up without it, so textStatSummary$ calls the C function textStatSummary. Give string functions the $, as BASIC’s own string functions have it (LEFT$, MID$); the C name never has one. BASIC ignores case, so a program may write TextStatNew for textStatNew, but the declaration’s spelling is the one looked up, so write it exactly as the C name is.

18.9.1. Numbers and Strings Across the Boundary

The compiler converts every argument to the type its parameter is declared with, and the run time passes it in C’s calling convention. Declare each function with these types, and write the C function to match:

BASIC type C parameter C result

Long

int32_t

int32_t

Integer

int32_t, the value sign-extended

int16_t: only the low 16 bits are kept

Byte

int32_t or uint8_t

uint8_t

Boolean

int32_t: True is -1, False 0

bool

Single

float

float

Double

double

double

Date

double, the date’s serial number

double

Currency

int64_t, the amount times 10,000

Not allowed: return a Double

String

const char *

const char *

BINARY STRING

const uint8_t * and int32_t (two parameters)

const uint8_t *, and a last parameter int32_t *outLen

Take a Boolean as an int32_t and test it for nonzero: BASIC’s True arrives as -1, and a C bool parameter holding -1 is not a bool the compiler expects. Declare Integer only for values that fit in 16 bits: an Integer result is cut to its low 16 bits.

Every argument is passed by value, whether the declaration says BYVAL, BYREF, or neither, so a C function cannot change a BASIC variable. Return the value, or give the program a handle and functions to read what it names, as TextStat does.

A string argument arrives as a pointer to a private copy of its bytes, ended by a zero byte, which stays valid until the function returns. Copy what the library keeps. A string declared AS STRING is text: C sees it up to its first zero byte. A string result is a const char * that BASIC copies as soon as the function returns, and NULL returns an empty string. Return a static buffer, as textStatSummary does, or memory the library keeps; never memory that the caller should free, because BASIC frees nothing of the library’s.

For bytes that may include zeros (a packet, a sample, encrypted data), declare BINARY STRING. Each such parameter becomes two C parameters at its place, the bytes and their count, and a BINARY STRING result adds one last C parameter, int32_t *outLen, where the function stores the length of the bytes it returns (a NULL result, a negative length, or a length never stored give an empty string). The library template’s tplNameXor shows both:

// tplNameXor$(BYVAL bytes AS BINARY STRING, BYVAL key AS LONG) AS BINARY STRING
const uint8_t *tplNameXor(const uint8_t *data, int32_t len, int32_t key, int32_t *outLen);

A call takes at most 16 arguments. A function a BASIC program calls runs on the program’s own task (every BASIC program has one, Section 3.4), so it may take its time and yield, with the care Section 18.7 describes.

18.9.2. Using It from BASIC

A BASIC programmer adds textstat.bas to a project like any module: in DVX BASIC, copy it into the project’s folder and choose File › Add File…​; in a project built with the SDK’s bascomp, list it in the .dbp file’s [Modules], by its path. Then the functions are there to call. This one counts a text file a line at a time:

Sub CountFile(ByVal path As String)
    Dim h As Long
    Dim lineText As String

    h = textStatNew()

    If h = 0 Then
        MsgBox "No counter is free."
        Exit Sub
    End If

    Open path For Input As #1

    Do While Not EOF(1)
        Line Input #1, lineText
        textStatAddLine h, lineText
    Loop

    Close #1
    MsgBox path & ": " & textStatSummary$(h)
    textStatFree h
End Sub

LINE INPUT drops each line’s line end, so textStatAddLine counts the line and then a line end of its own; without it, the last word of each line and the first of the next would count as one:

// BASIC reads a file a line at a time (LINE INPUT), without the line
// ends, so this counts the line and then the line end.  text is BASIC's
// copy of the string, valid until this function returns.
void textStatAddLine(int32_t h, const char *text) {
    CounterT *c = counterOf(h);

    if (c) {
        textStatAdd(c->stats, text);
        textStatAdd(c->stats, "\n");
    }
}

make package does not package a library’s .bas file: hand it out with the library. (DATA = textstat.bas in the library’s Makefile puts it in a DATA folder in the installed library’s folder, where a BASIC programmer can copy it from.) The DVX BASIC Language Reference describes DECLARE LIBRARY from the BASIC side.

18.10. The Library’s Help

A library’s help is for the programmers who use it. textstat.dhs puts one page in DVX’s help, under Technical Reference (for Developers), Libraries:

.section Technical Reference (for Developers)|Libraries
.topic lib.textstat
.title TextStat Library
.toc 0 TextStat Library
.index TextStat
...

make only checks it, as DVX’s own compile will see it, and writes no help file (it records the check in textstat.hck): the help compiler stops at an error, naming the file and line. What is installed is the source: make package copies it beside the library as TEXTSTAT.DHS, and DVX compiles every .DHS file under LIBS and WIDGETS into its own help when it starts and finds a module or a help source there new, changed, or gone. So a new library’s help, and a new version’s changed help, show from the next start. A library’s DVX BASIC help, a .bhs file beside its .dhs, goes into the DVX BASIC help the same way. Chapter 20 describes the help source format.

18.11. Installing and Testing

make install copies the library, its .dep file, and its help into the DVX folder:

$ cd textstat
$ make install DVX_DIR=/path/to/dvx
$ cd ../tsdemo
$ make install DVX_DIR=/path/to/dvx

textstat.lib, textstat.dep, and TEXTSTAT.DHS land in LIBS\LOCAL\TEXTSTAT\ (LOCAL is the VENDOR; mind the case of the folder names, Section 1.6). DVX looks for libraries only as it starts, so start DVX again after installing or replacing a library; a program can be replaced without that. Then:

  • Start TextStat Demo, type some text, and choose Help › About TextStat Demo…​. DVX.LOG shows textstat.lib loading just before the program.

  • Try a BASIC program with textstat.bas in it, such as one that calls CountFile above.

  • Take the library away (or start DVX with /SAFE) and start TextStat Demo again: DVX refuses it. A BASIC program runs until its first call to the library, which raises error 453.

dvxLog works in a library as in a program. A fault in library code is a fault in the program that called it: DVX ends that program and goes on, and the library stays loaded, in whatever state the fault left its data (Section 3.10). Chapter 22 covers the log and crash reports.

Chapter 19. Writing a Widget

Every widget DVX has, from the Label to the ListView, is a module that registers itself as DVX starts, and yours works the same way: once installed, a widget of yours is a widget like the others, which C programs create through their headers and DVX BASIC programs put on their forms from the toolbox. This chapter builds the Meter, a level meter: a column of lights that shows a level, with a mark the user moves and an event of its own when the level goes above the mark. It explains the widget class and its handlers (painting, the minimum size, the mouse, the keys, the focus), the C API table, the BASIC interface, the toolbox icon and the help, the helper libraries DVX’s own widgets share, and a program, mtrdemo, that uses the Meter. The last section goes the other way: using a control written in DVX BASIC from C. Chapter 5 explains widgets from a program’s side, Chapter 9 the drawing calls, and Chapter 8 the keys and the mouse; this chapter builds on all three.

The Meter Demo window with the meter lit to red above its yellow mark, the Input level slider, the mark and overload count, and a Reset Peak button
Figure 28. The Meter widget in its demo program, the level above the mark

19.1. The Widget Template

newProject.sh widget NAME makes a widget project:

File What it is

Makefile

KIND = widget.

NAME.c

The widget: its class, its C API table, its BASIC interface, and wgtRegister, which registers the three.

NAME.h

The public header: the API table’s type, the accessor that finds the table, and a macro for each function.

NAME.res, icon24.bmp

Resources: icon24, the picture DVX BASIC’s toolbox shows, and name, its tooltip.

NAME.dhs

The widget’s developer help, which DVX adds to its own help.

NAME.bhs

The control’s DVX BASIC help, which DVX adds to the DVX BASIC help.

make builds NAME.wgt, with the resources appended, and NAME.hlp, both help sources compiled together to check them. The template’s widget shows a line of text in a box with a flat, raised, or sunken border: a widget with text, a property, and a method.

The Meter, in examples/meter, has the same files. It is built like any project:

SDK_DIR ?= ../../../../bin/sdk
KIND     = widget
NAME     = meter

include $(SDK_DIR)/sdk.mk

19.2. The Module

A widget’s source starts like this:

#define METER_IMPL

#include "dvxWgtP.h"
#include "meter.h"

#include <stdbool.h>
#include <stdint.h>

// The binary interface this widget was built for; the argument is the
// file's base name in lower case (meter.wgt).
DVX_ABI_STAMP(meter);

dvxWgtP.h is the header for widget modules. Beside dvxWgt.h, which programs use, it has what only a widget needs: widgetAlloc and the other calls that make and link widgets, the state the event dispatcher shares with the widgets (which widget has the focus, which has captured the mouse), and helpers for scroll bars, layout, presses, and events. METER_IMPL, defined before meter.h is included, keeps the header’s macros out of the widget’s own source, so its functions can have the names the macros give programs (Section 19.9).

DVX_ABI_STAMP(meter) records the binary interface of DVX the widget was built for, as a library’s stamp does (Section 18.6): the argument is the file’s base name in lower case, and DVX refuses a widget whose stamp is missing or differs.

Each widget’s own state lives in a structure of the module’s, which the widget’s data points to. Nothing outside the module sees it, so it may change from one version of the widget to the next:

// Each Meter's own data, at w->data.  Nothing outside this file sees it,
// so it can change from one version of the widget to the next.
typedef struct {
    int32_t level;      // 0 to maxLevel: what the lights show
    int32_t maxLevel;   // 1 to METER_MAX_LIMIT
    int32_t mark;       // 0 to maxLevel: the lights above it are red
    int32_t peak;       // the highest level since the last resetPeak
    bool    over;       // the level is above the mark (Overload fired)
} MeterDataT;

// The class's type ID, from wgtRegisterClass
static int32_t sTypeId = -1;

DVX loads every widget module when it starts, after the libraries that load at the start and the shell, and calls its wgtRegister once:

// DVX calls this once, as it starts, after loading meter.wgt.
void wgtRegister(void) {
    sTypeId = wgtRegisterClass(&sClass);
    wgtRegisterApi(METER_TYPE, &sApi);
    wgtRegisterIface(METER_TYPE, &sIface);
    wgtIfaceSetType(METER_TYPE, sTypeId);
}

wgtRegisterClass adds the class (Section 19.3) to DVX’s table of classes and returns its type ID, which every Meter carries in its type field. wgtRegisterApi publishes the C API table (Section 19.9) and wgtRegisterIface the BASIC interface (Section 19.10), each under the type name, and wgtIfaceSetType ties the interface to the class, so that DVX can find the interface from any Meter. Those are the module’s only two exports, wgtRegister and the stamp: everything else in meter.c is static, reached through the tables. wgtRegister runs while DVX starts, before there is a screen or any program, so it registers and does nothing else.

A widget has three names: the type name the tables are registered under ("meter", lower case), the control name BASIC programs use (Meter), and its file’s base name (meter.wgt). The names are global. A widget that registers a type name another widget has registered is refused, and DVX logs it (“Widget: API 'meter' is registered already; the second registration is refused”): the first registration stays. Of two widgets with one control name, BASIC finds the one registered first; and an add-on file named like one of DVX’s own modules is not loaded at all. Use one word for all three, and one no other widget uses. METER_TYPE in meter.h is the type name, written once for the module and its callers.

A module may register several classes, each with its table and interface: DVX’s box.wgt registers the VBox, the HBox, and the Frame. A program can also register a class of its own while it runs; what is registered while a program’s code runs belongs to that program, and DVX releases it when the program ends. A widget other programs and BASIC can use is a module.

19.3. The Class

A WidgetClassT is a widget type’s behavior: its flags and a table of handlers that DVX calls for every widget of the type.

// FOCUSABLE: Tab stops here, and the keys come to meterOnKey.
// SCROLLABLE: the wheel turns into Up and Down keys while it has the
// focus.  A handler left out is a slot left NULL: DVX skips it.
static const WidgetClassT sClass = {
    .version  = WGT_CLASS_VERSION,
    .flags    = WCLASS_FOCUSABLE | WCLASS_SCROLLABLE,
    .handlers = {
        [WGT_METHOD_PAINT]          = (void *)meterPaint,
        [WGT_METHOD_CALC_MIN_SIZE]  = (void *)meterCalcMinSize,
        [WGT_METHOD_ON_MOUSE]       = (void *)meterOnMouse,
        [WGT_METHOD_ON_KEY]         = (void *)meterOnKey,
        [WGT_METHOD_ON_DRAG_UPDATE] = (void *)meterOnDragUpdate,
    }
};

version is always WGT_CLASS_VERSION, DVX’s binary interface number; wgtRegisterClass refuses a class with another. handlers is indexed by fixed method numbers, WGT_METHOD_PAINT and the rest, and a slot left out is NULL, which DVX skips (or for which it does something by default). The slots a widget fills most:

Slot Handler Called

WGT_METHOD_PAINT

void (w, d, ops, font, colors)

To draw the widget (Section 19.6).

WGT_METHOD_CALC_MIN_SIZE

void (w, font)

When the window is measured: set calcMinW and calcMinH (Section 19.5).

WGT_METHOD_LAYOUT

void (w, font)

After the widget is placed, for a container to place its children.

WGT_METHOD_ON_MOUSE

void (w, root, vx, vy)

For a press of the left button on the widget (Section 19.7).

WGT_METHOD_ON_DRAG_UPDATE, _ON_DRAG_END

void (w, root, x, y)

For each move, and the release, after the widget captured the mouse.

WGT_METHOD_ON_KEY

void (w, key, mod)

For a key that reaches the widget while it has the focus.

WGT_METHOD_ON_FOCUS, _ON_BLUR

void (w)

When it gains or loses the focus, before its onFocus or onBlur.

WGT_METHOD_ON_WHEEL

bool (w, delta)

For the wheel, before the default handling; true takes it.

WGT_METHOD_ON_ACCEL_ACTIVATE

void (w, root)

When the user types its access key.

WGT_METHOD_GET_TEXT, _SET_TEXT

const char *(w), void (w, text)

For wgtGetText and wgtSetText.

WGT_METHOD_GET_CURSOR_SHAPE

int32_t (w, vx, vy)

For the mouse pointer over the widget: a CURSOR_* shape, or 0 for the default.

WGT_METHOD_POLL

void (w, win)

Every frame, for a class with WCLASS_NEEDS_POLL (a terminal reading its port).

WGT_METHOD_DESTROY

void (w)

As the widget is destroyed: free what it holds.

WGT_METHOD_HIT_CHROME

bool (w, vx, vy)

To ask whether a point is on the widget’s chrome, its own scroll bars, the corner between them, or a list’s column headings: a press there fires none of the program’s mouse callbacks (Section 19.7).

WGT_METHOD_ON_FORMAT_CHANGE

void (w, from)

After the screen changed to another pixel format, from the old one: convert the pixels and packed colors the widget keeps in the display’s format (convertPixels, convertColor; Section 9.5).

WGT_METHOD_MIN_PERCENT

int32_t (w, across)

The class’s own minimum along one axis (across is the width) as a percentage, 0 to 100, of the container’s inner size; 0 is none. Like a percentage minW or minH it counts as 0 when the layout measures, and is given only from the room to spare; when the widget also has a percentage minimum, the larger wins (wclsMinPercent, widgetMinPercent). A BASIC UserControl whose header says Width = 50% uses it.

dvxWgt.h lists the rest, each with its signature: a container’s GET_LAYOUT_METRICS, a drop-down’s PAINT_OVERLAY and CLOSE_POPUP, and others the widget layer asks of a few classes. The numbers never change; new ones are added at the end.

The flags tell the dispatcher and the layout what kind of widget it is. The ones a new widget is likely to need:

Flag Meaning

WCLASS_FOCUSABLE

It takes the keyboard focus: Tab stops on it, and its keys come to ON_KEY.

WCLASS_SCROLLABLE

While it has the focus, the wheel sends it Up and Down keys.

WCLASS_HAS_TEXT

Its data starts with a const char * that it owns: destroying the widget frees it (Section 19.4).

WCLASS_PRESS_RELEASE

It is clicked as a button is: a press and a release over it, with the widgetPressable helpers of dvxWgtP.h.

WCLASS_SWALLOWS_TAB, WCLASS_SWALLOWS_ENTER

Tab, or Enter, comes to it instead of moving the focus or pressing a window’s default button.

WCLASS_NEEDS_POLL

WGT_METHOD_POLL is called every frame.

WCLASS_HORIZ_CONTAINER, WCLASS_PAINTS_CHILDREN

A container that lays its children out in a row, or that paints them itself.

19.4. Creating a Widget

A widget’s create function makes the WidgetT and its data:

// A new Meter, the last child of parent.  widgetAlloc makes the WidgetT
// and links it into the tree; the data is the widget's own.  Both are
// freed with the widget: with no WGT_METHOD_DESTROY handler, DVX frees
// w->data itself.
static WidgetT *wgtMeter(WidgetT *parent, int32_t maxLevel) {
    WidgetT *w = widgetAlloc(parent, sTypeId);

    if (!w) {
        return NULL;
    }

    MeterDataT *md = (MeterDataT *)calloc(1, sizeof(MeterDataT));

    if (!md) {
        widgetAllocRollback(w);
        return NULL;
    }

    md->maxLevel = clampInt(maxLevel, 1, METER_MAX_LIMIT);
    md->mark     = md->maxLevel;
    w->data      = md;
    return w;
}

widgetAlloc(parent, type) allocates a WidgetT of the class type, visible, enabled, with weight 0 and the default padding and spacing, and makes it the last child of parent; it returns NULL for a type that is not registered or when memory runs out. The data is the widget’s to allocate. When that fails, widgetAllocRollback takes the half-made widget out of the tree and frees it. Set any default that differs from the WidgetT defaults here: a widget that should fill its row starts with w->weight = WGT_WEIGHT_FILL, as a Slider does. The Meter keeps weight 0, so in a row it is as narrow as its minimum and as tall as the row.

Both allocations are counted against the program that creates the widget, and freed with the widget. A class without a WGT_METHOD_DESTROY handler needs nothing more: DVX frees w->data itself (and, with WCLASS_HAS_TEXT, the text its first field points to first). A widget that holds more, such as a buffer or a picture, has a destroy handler that frees all of it, w->data included.

A widget that shows a text it owns, as the template’s does, makes its data a structure whose first field is const char *text, sets WCLASS_HAS_TEXT, and creates itself with widgetAllocWithText(parent, type, sizeof(data), text), which also copies the text and finds its access key. widgetTextGet and widgetTextSet (dvxWgtP.h) are then its GET_TEXT and SET_TEXT handlers, so that wgtGetText, wgtSetText, and BASIC’s Caption work on it.

19.5. Minimum Size and Layout

The layout measures every widget, bottom up, by calling its CALC_MIN_SIZE handler, which sets the widget’s natural minimum in calcMinW and calcMinH, in pixels (Section 5.4). The layout then adds the program’s minW and maxW hints and the box’s rules on its own, and gives the widget its place in x, y, w, and h.

// Room for METER_MIN_LIGHTS lights.  A meter in a row is as tall as the
// row, and every METER_LIGHT_STEP pixels more shows one light more.
static void meterCalcMinSize(WidgetT *w, const BitmapFontT *font) {
    (void)font;
    w->calcMinW = METER_LIGHT_W + 2 * METER_INSET;
    w->calcMinH = METER_MIN_LIGHTS * METER_LIGHT_STEP - METER_LIGHT_GAP + 2 * METER_INSET;
}

The handler gets the font the widget draws with, its own or its container’s; size anything that holds text by it (font->charWidth, font->charHeight, textWidth), so the widget grows with a larger font. The Meter has no text, so its minimum is a number of lights in pixels. Keep the handler cheap and free of side effects: it runs whenever the window is measured. When something changes the minimum (new text, say), call wgtInvalidate(w), which measures and lays out the window again; when only the picture changes, wgtInvalidatePaint(w) (Section 5.4.6).

A widget with no children needs no LAYOUT handler: its parent places it. A container measures and places its children. DVX’s boxes use the box layout of dvxWgtP.h, widgetCalcMinSizeBox and widgetLayoutBox, as their CALC_MIN_SIZE and LAYOUT handlers, with a GET_LAYOUT_METRICS handler where the box has a border or a title (a Frame); a container of your own can do the same.

19.6. Painting

The PAINT handler draws the widget into the window’s content buffer, with the drawing calls of Chapter 9:

// Every pixel of the widget's rectangle is drawn, and nothing outside it:
// a paint that repaints only this widget leaves the rest of the window
// as it was, and the clip rectangle is the window's, not the widget's.
static void meterPaint(WidgetT *w, DisplayT *d, const BlitOpsT *ops, const BitmapFontT *font, const ColorSchemeT *colors) {
    (void)font;
    const MeterDataT *md      = (const MeterDataT *)w->data;
    bool              enabled = widgetIsEnabledChain(w);   // itself, its containers, and its window
    uint32_t          back    = wgtColorPixel(d, w->bgColor, packColorRgb(d, METER_RGB_BACK));
    uint32_t          lowOn   = enabled ? wgtColorPixel(d, w->fgColor, packColorRgb(d, METER_RGB_LOW)) : colors->windowShadow;
    uint32_t          highOn  = enabled ? packColorRgb(d, METER_RGB_HIGH) : colors->windowShadow;
    uint32_t          lowOff  = packColorRgb(d, METER_RGB_LOW_OFF);
    uint32_t          highOff = packColorRgb(d, METER_RGB_HIGH_OFF);
    int32_t           innerH  = meterInnerH(w);
    int32_t           bottom  = w->y + w->h - METER_INSET;
    int32_t           levelPx = meterPixels(md, md->level, innerH);
    int32_t           markPx  = meterPixels(md, md->mark, innerH);
    int32_t           peakPx  = meterPixels(md, md->peak, innerH);
    BevelStyleT       frame   = BEVEL_SUNKEN(colors, back, METER_BEVEL_W);

    // The frame, its inside filled with the background
    drawBevel(d, ops, w->x, w->y, w->w, w->h, &frame);

    // The lights from the bottom up; b is a light's height above the bottom
    for (int32_t b = 0; b + METER_LIGHT_H <= innerH; b += METER_LIGHT_STEP) {
        bool     high = b >= markPx;
        bool     lit  = b < levelPx || (b < peakPx && peakPx <= b + METER_LIGHT_STEP);
        uint32_t on   = high ? highOn : lowOn;
        uint32_t off  = high ? highOff : lowOff;

        rectFill(d, ops, w->x + METER_INSET, bottom - b - METER_LIGHT_H, w->w - 2 * METER_INSET, METER_LIGHT_H, lit ? on : off);
    }

    // The mark: a line across the meter at its level
    drawHLine(d, ops, w->x + METER_BEVEL_W, bottom - markPx, w->w - 2 * METER_BEVEL_W, packColorRgb(d, METER_RGB_MARK));

    if (w == sFocusedWidget) {
        drawFocusRect(d, ops, w->x, w->y, w->w, w->h, colors->contentFg);
    }
}

It gets the DisplayT of the content buffer, the blit routines, the widget’s font, and the color scheme. The rules:

  • Draw at the widget’s place. x, y, w, and h are in the content buffer’s coordinates, a window’s scroll position included; draw from (w->x, w->y), not from (0, 0).

  • Draw every pixel of the rectangle. When only some widgets need painting, DVX paints only them, over what the buffer held; a widget that leaves pixels alone leaves the old picture there. The Meter’s bevel fills its inside before the lights go on top.

  • Draw nothing outside it. The clip rectangle is the window’s, or a scrolling container’s, not the widget’s: a pixel outside the rectangle lands on a neighbor.

  • Use the scheme and the widget’s colors. colors holds the user’s scheme, packed for the screen (Section 9.5). fgColor and bgColor are the program’s colors for the widget (BASIC’s ForeColor and BackColor), 0 when it set none: wgtColorPixel(d, color, fallback) packs one or gives the fallback. The Meter’s own colors are 0x00RRGGBB constants, packed with packColorRgb on each paint, since the user can change the video mode, and with it the pixel format, while the widget exists.

  • Show the state. Draw a disabled widget grayed, and the widget with the focus (w == sFocusedWidget) with a focus mark, here drawFocusRect. A widget is disabled when it is, or a container it is in, or its window (Section 5.8): widgetIsEnabledChain(w) (dvxWgtP.h) says, where w->enabled is only the widget’s own flag. DVX repaints the widgets inside a container whose state changes. DVX repaints a widget when it gains or loses the focus.

The handler draws what the widget’s data says. Code that changes the data asks for a repaint with wgtInvalidatePaint(w), and DVX calls PAINT once in the next frame, however many times it was asked. A paint is called often, so keep it to drawing: no allocation, no file access, and as few pixels as the widget needs (Section 9.11). The Meter draws one rectangle per light, each a fill of whole rows.

19.7. The Mouse, the Keys, and the Focus

DVX calls ON_MOUSE when the left button goes down over an enabled widget, with the point in the same coordinates as the widget’s x and y:

// A press with the left button: the meter takes the focus, moves the mark
// to the level under the pointer, and captures the mouse, so the moves
// that follow go to meterOnDragUpdate until the button goes up, wherever
// the pointer is.  Both pointers are set before meterMoveMark, whose
// handlers may destroy the widget: DVX clears them when it does.
static void meterOnMouse(WidgetT *w, WidgetT *root, int32_t vx, int32_t vy) {
    (void)root;
    (void)vx;
    sFocusedWidget = w;
    sDragWidget    = w;
    meterMoveMark(w, meterLevelAt(w, vy));
}

A class takes the focus by setting sFocusedWidget to the widget in this handler: the dispatcher cleared the focus before the call and fires the onBlur and onFocus callbacks for the change after it. Setting sDragWidget captures the mouse: until the button goes up, every move goes to the widget’s ON_DRAG_UPDATE, wherever the pointer is, and the release to ON_DRAG_END (the Meter has none). After the handler returns, DVX repaints the widget and fires the program’s onMouseDown, with the point relative to the widget; its onClick comes at the release, after onMouseUp, when the release is over the widget (Section 8.10.1).

A press on a widget’s own furniture, a scroll bar it draws or a heading, is its chrome: the program’s mouse callbacks fire for none of it, as Visual Basic raises no mouse events there. A class says which points are chrome with a HIT_CHROME handler, which DVX asks before the press is handled, for any button; a class without one calls widgetPressOnChrome() in its ON_MOUSE handler for the left press it is handling (a scroll-bar press through widgetScrollbarPressStep is chrome by itself). Call it before multiClickDetect, which tells a widget that counts its own presses whether this press is the second of a double click: a press on content right after one on chrome never is.

// While the button is down after meterOnMouse, every move comes here, in
// content coordinates.
static void meterOnDragUpdate(WidgetT *w, WidgetT *root, int32_t x, int32_t y) {
    (void)root;
    (void)x;
    meterMoveMark(w, meterLevelAt(w, y));
}

The mark follows the pointer through meterLevelAt, the inverse of the pixel arithmetic the paint uses:

// The level at content row y: the inverse of meterPixels.  A widget may be
// laid out smaller than its minimum (a capped size), so innerH is tested
// before it divides.
static int32_t meterLevelAt(const WidgetT *w, int32_t y) {
    const MeterDataT *md         = (const MeterDataT *)w->data;
    int32_t           innerH     = meterInnerH(w);
    int32_t           fromBottom = w->y + w->h - METER_INSET - y;

    if (innerH <= 0) {
        return 0;
    }

    return clampInt((int32_t)((int64_t)fromBottom * md->maxLevel / innerH), 0, md->maxLevel);
}

A WCLASS_FOCUSABLE widget gets the keys that reach it while it has the focus. The window takes some first (Tab, menu and access keys, and Enter and Esc in a window with default and cancel buttons; Section 8.3), and the program’s onKeyDown and onKeyPress see each key before the class does, and may change or cancel it (Section 8.4). Then ON_KEY gets it, with a key code of Section 8.2 and the modifiers. A key the class does not use is dropped; keys do not go on to the widget’s containers.

// Up and Down move the mark one level, Page Up and Page Down a tenth of
// Max, and Home and End to 0 and Max.  The wheel sends Up and Down
// (WCLASS_SCROLLABLE).  Other keys are not the meter's: Tab and the
// access keys never reach it.
static void meterOnKey(WidgetT *w, int32_t key, int32_t mod) {
    (void)mod;
    const MeterDataT *md   = (const MeterDataT *)w->data;
    int32_t           page = DVX_MAX(md->maxLevel / METER_PAGE_DIV, 1);

    switch (key) {
        case KEY_UP:
            meterMoveMark(w, md->mark + 1);
            break;

        case KEY_DOWN:
            meterMoveMark(w, md->mark - 1);
            break;

        case KEY_PGUP:
            meterMoveMark(w, md->mark + page);
            break;

        case KEY_PGDN:
            meterMoveMark(w, md->mark - page);
            break;

        case KEY_HOME:
            meterMoveMark(w, 0);
            break;

        case KEY_END:
            meterMoveMark(w, md->maxLevel);
            break;

        default:
            break;
    }
}

With WCLASS_SCROLLABLE, the wheel turns into these same keys while the widget has the focus: Down for a turn that scrolls down and Up for one that scrolls up, as many for each notch as the user’s wheel setting says. So the Meter needs no ON_WHEEL handler. A class that wants the wheel otherwise implements ON_WHEEL and returns true for what it takes.

Mouse and keys end in one function, which changes the mark and tells the program:

// The user moved the mark: repaint, onChange, and then Overload when the
// level is now above it.  A mark that did not move does nothing, so a
// drag that holds still or a key at the end of the range fires nothing.
static void meterMoveMark(WidgetT *w, int32_t mark) {
    MeterDataT *md      = (MeterDataT *)w->data;
    int32_t     clamped = clampInt(mark, 0, md->maxLevel);

    if (clamped == md->mark) {
        return;
    }

    md->mark = clamped;
    wgtInvalidatePaint(w);

    if (widgetFireChange(w)) {
        meterCheckOver(w);
    }
}

19.8. Firing Events

A widget reports to the program through the callbacks every widget has (Section 5.7). Most of them DVX’s dispatcher fires on its own: onClick, the mouse callbacks, the key callbacks, onFocus, and onBlur. A class fires onChange itself, when the user changes its value, through widgetFireChange(w), which calls w->onChange if the program set it.

An event the callbacks do not cover is the widget’s own: wgtFireEvent(w, name, args, argc) hands it to w->onEvent by name, with its arguments as WgtValueT values (the universal names, Click, Change, and the rest, go to their own callbacks instead). The Meter’s is Overload, with the level:

// Fires Overload when the level has just gone above the mark: once each
// time it crosses, whether the level rose or the mark came down.  over is
// set first, so a handler that sets the level again does not fire it
// twice.  The handler may destroy widgets, w among them, so every caller
// does this last.
static void meterCheckOver(WidgetT *w) {
    MeterDataT *md  = (MeterDataT *)w->data;
    bool        was = md->over;
    WgtValueT   arg = wgtValueInt(md->level);

    md->over = md->level > md->mark;

    if (md->over && !was) {
        wgtFireEvent(w, METER_EVT_OVERLOAD, &arg, 1);
    }
}

meter.h names it, METER_EVT_OVERLOAD, so a program compares names against the same string the widget fires. Overload fires when the user moves the mark below the level, and also inside the program’s own call when wgtMeterSetLevel takes the level past the mark, which few events of DVX’s widgets do (Section 5.7). That is why it fires on the crossing only, once each time: a handler that sets the level again does not fire it again.

A program’s handler may do anything, destroy widgets included, this one among them. widgetFireChange and wgtFireEvent return false when a handler destroyed any widget; after that, do not touch the widget. So fire events last, as meterMoveMark does: it fires onChange, and only if no widget was destroyed goes on to meterCheckOver, which fires Overload as the last thing it does.

19.9. The API Table

Programs reach a widget’s functions through a table the widget registers: a structure of function pointers whose first member is a WgtApiHeaderT. meter.h declares it:

typedef struct {
    WgtApiHeaderT header;
    WidgetT *(*create)(WidgetT *parent, int32_t maxLevel);
    int32_t  (*getLevel)(const WidgetT *w);
    void     (*setLevel)(WidgetT *w, int32_t level);
    int32_t  (*getMark)(const WidgetT *w);
    void     (*setMark)(WidgetT *w, int32_t mark);
    int32_t  (*getMax)(const WidgetT *w);
    void     (*setMax)(WidgetT *w, int32_t maxLevel);
    int32_t  (*getPeak)(const WidgetT *w);
    void     (*resetPeak)(WidgetT *w);
} MeterApiT;

and meter.c fills it:

// The C API (meter.h): the header first, create right after it.
static const MeterApiT sApi = {
    .header    = WGT_API_HEADER(MeterApiT),
    .create    = wgtMeter,
    .getLevel  = wgtMeterGetLevel,
    .setLevel  = wgtMeterSetLevel,
    .getMark   = wgtMeterGetMark,
    .setMark   = wgtMeterSetMark,
    .getMax    = wgtMeterGetMax,
    .setMax    = wgtMeterSetMax,
    .getPeak   = wgtMeterGetPeak,
    .resetPeak = wgtMeterResetPeak
};

WGT_API_HEADER(MeterApiT) fills the header with DVX’s binary interface number and the table’s size. The create function comes right after the header, always: code that creates widgets by name, as BASIC’s form runtime does, calls it there without knowing the table’s type (WgtApiPrefixT).

The rest of the header is for the caller:

// Consumer side: the accessor and the macros.  meter.c defines METER_IMPL
// so its functions keep their own names.
#ifndef METER_IMPL

// The table, or NULL when no Meter widget is installed (or it was built
// for another DVX, or is older than this header).  Found once, then kept.
static inline const MeterApiT *dvxMeterApi(void) {
    static const MeterApiT *sApi;

    if (!sApi) {
        sApi = (const MeterApiT *)wgtGetApi(METER_TYPE, sizeof(MeterApiT));
    }

    return sApi;
}

#define wgtMeter(parent, maxLevel)    dvxMeterApi()->create(parent, maxLevel)
#define wgtMeterGetLevel(w)           dvxMeterApi()->getLevel(w)
#define wgtMeterSetLevel(w, level)    dvxMeterApi()->setLevel(w, level)
#define wgtMeterGetMark(w)            dvxMeterApi()->getMark(w)
#define wgtMeterSetMark(w, mark)      dvxMeterApi()->setMark(w, mark)
#define wgtMeterGetMax(w)             dvxMeterApi()->getMax(w)
#define wgtMeterSetMax(w, maxLevel)   dvxMeterApi()->setMax(w, maxLevel)
#define wgtMeterGetPeak(w)            dvxMeterApi()->getPeak(w)
#define wgtMeterResetPeak(w)          dvxMeterApi()->resetPeak(w)

#endif // METER_IMPL

dvxMeterApi asks wgtGetApi for the table once and keeps it, and each macro calls through it, so a program writes wgtMeter(row, 100) as if it were a function. wgtGetApi(name, size) returns NULL when no widget registered the name, and also, logging why, when the table was built for another DVX or is shorter than size, the size of the table the caller was compiled with.

That last test is the table’s version rule. A program compiled with an older meter.h, whose table was shorter, gets a newer, longer table and uses its first members, which mean what they meant. A program compiled with a newer header asks for more than an older widget has and gets NULL. So add members only at the end, and never change, remove, or reorder one, nor any type or constant in the header a program compiles in. The widget’s data and its class are its own, and change as they like.

The functions behind the table check that they were given a Meter, since a program can pass them any widget:

// The API's functions check that w is a Meter (VALIDATE_WIDGET): a
// program can hand them any widget.  The class's handlers need no check;
// DVX calls them only for Meters.
static int32_t wgtMeterGetLevel(const WidgetT *w) {
    VALIDATE_WIDGET(w, sTypeId, 0);

    return ((const MeterDataT *)w->data)->level;
}

VALIDATE_WIDGET(w, type, value) returns value from the function when w is NULL or of another type, and VALIDATE_WIDGET_VOID returns from a void one. The setters clamp what they are given:

// The level, clamped to 0 to Max.  The same level again does nothing, so
// a program may set it as often as it reads it.  The peak follows the
// level up.
static void wgtMeterSetLevel(WidgetT *w, int32_t level) {
    VALIDATE_WIDGET_VOID(w, sTypeId);
    MeterDataT *md      = (MeterDataT *)w->data;
    int32_t     clamped = clampInt(level, 0, md->maxLevel);

    if (clamped == md->level) {
        return;
    }

    md->level = clamped;
    md->peak  = DVX_MAX(md->peak, clamped);
    meterUpdate(w);
}

19.10. The BASIC Interface

The interface describes the widget to DVX BASIC: the control’s name, its properties, its methods, and its events, each by name, and how to create one. With it registered, the widget is in the form designer’s toolbox, a .frm file can hold one, and BASIC code can use it like any control. The generic calls of dvxWgt.h use it too (wgtGetProp, wgtSetProp, wgtCallMethod, wgtCreateByName; Section 5.12), so C programs can reach a widget by name.

// The BASIC interface.  Max comes first: a form sets its properties in
// this order, so the range is there before Mark and Level are checked
// against it.  Peak has no setter: it is read-only.
static const WgtPropDescT sProps[] = {
    { "Max",   WGT_IFACE_INT, (void *)wgtMeterGetMax,   (void *)wgtMeterSetMax, NULL, false },
    { "Mark",  WGT_IFACE_INT, (void *)wgtMeterGetMark,  (void *)basSetMark,     NULL, true },
    { "Level", WGT_IFACE_INT, (void *)wgtMeterGetLevel, (void *)basSetLevel,    NULL, true },
    { "Peak",  WGT_IFACE_INT, (void *)wgtMeterGetPeak,  NULL,                   NULL, false }
};

static const WgtMethodDescT sMethods[] = {
    { "ResetPeak", WGT_SIG_VOID, (void *)wgtMeterResetPeak }
};

// The events every control has (Click, Change, GotFocus, the keys, and
// the mouse) are the form runtime's; only the widget's own are listed.
static const WgtEventDescT sEvents[] = {
    { METER_EVT_OVERLOAD, "Level As Long" }
};

static const WgtIfaceT sIface = {
    .basName      = "Meter",
    .props        = sProps,
    .propCount    = DVX_ARRAY_LEN(sProps),
    .methods      = sMethods,
    .methodCount  = DVX_ARRAY_LEN(sMethods),
    .events       = sEvents,
    .eventCount   = DVX_ARRAY_LEN(sEvents),
    .createArgs   = { METER_DEFAULT_MAX },
    .defaultEvent = METER_EVT_OVERLOAD,
    .createSig    = WGT_CREATE_PARENT_INT
};

A property is a WgtPropDescT: its BASIC name, its type, a getter, a setter, the names of an enumerated property’s values, and whether the setter is checked. A property without a setter is read-only, and one without a getter write-only. The signatures of the functions follow the type:

Type BASIC Getter Setter

WGT_IFACE_INT

Long

int32_t (const WidgetT *)

void (WidgetT *, int32_t)

WGT_IFACE_BOOL

Boolean

bool (const WidgetT *)

void (WidgetT *, bool)

WGT_IFACE_FLOAT

Single

float (const WidgetT *)

void (WidgetT *, float)

WGT_IFACE_DOUBLE

Double

double (const WidgetT *)

void (WidgetT *, double)

WGT_IFACE_STRING

String

const char *(const WidgetT *)

void (WidgetT *, const char *)

WGT_IFACE_ENUM

a number or a name

int32_t (const WidgetT *)

void (WidgetT *, int32_t)

A checked setter returns bool instead of void: false refuses the value and changes nothing, and BASIC raises error 380, Invalid property value. The Meter’s C setters clamp, which suits C callers; its BASIC setters refuse a value outside the range, as Visual Basic’s controls do:

// BASIC's Level = level: refused outside 0 to Max (the program gets error
// 380, Invalid property value), as Visual Basic's controls refuse a
// value outside their range.  The C setter clamps instead.
static bool basSetLevel(WidgetT *w, int32_t level) {
    if (level < 0 || level > wgtMeterGetMax(w)) {
        return false;
    }

    wgtMeterSetLevel(w, level);
    return true;
}


// BASIC's Mark = mark, refused outside 0 to Max as Level is.
static bool basSetMark(WidgetT *w, int32_t mark) {
    if (mark < 0 || mark > wgtMeterGetMax(w)) {
        return false;
    }

    wgtMeterSetMark(w, mark);
    return true;
}

An enumerated property’s enumNames is a NULL-terminated array of the names of its values 0, 1, 2, …​, which the property sheet offers and which wgtSetProp accepts in place of a number; the template’s Style is one. A string a getter returns belongs to the widget and must stay valid until the next call on it.

A method is a WgtMethodDescT: its name, a signature, and the function. The signature, a WGT_SIG_* constant, says how DVX calls the function: WGT_SIG_VOID is void fn(WidgetT *), WGT_SIG_INT is void fn(WidgetT *, int32_t), WGT_SIG_RET_STR_INT is const char *fn(const WidgetT *, int32_t), and dvxWgt.h lists the rest, among them WGT_SIG_DYNAMIC, which takes any arguments as WgtValueT values. Several methods may share a name with different numbers of arguments, and a call takes the one its arguments fit.

An event is a WgtEventDescT: its name and its parameters as BASIC writes them, which the IDE copies into the handler it makes for the event. List only the widget’s own events. The ones every control has, Click, DblClick, Change, GotFocus, LostFocus, the key events, and the mouse events, the form runtime connects to the universal callbacks itself, so the Meter’s onChange is BASIC’s Change event with nothing more.

The rest of WgtIfaceT:

Field Meaning

basName

The control’s name in BASIC: in a .frm file’s Begin line, in the toolbox, and to wgtCreateByName.

createSig, createArgs

How BASIC, and wgtCreateByName, call the create function: WGT_CREATE_PARENT_INT is create(parent, createArgs[0]), so a Meter on a form starts with a Max of 100. A widget whose create function takes a picture (WGT_CREATE_PARENT_DATA) is created with none, and gets its picture later through its properties.

defaultEvent

The event the form designer opens when the control is double-clicked; Click when it is NULL.

namePrefix

The prefix of the names the designer gives new controls (Meter1, Meter2); basName when NULL.

isContainer

Other controls can be put inside it.

noVisual

It shows nothing while the program runs (a Timer); the designer keeps it in a tray of its own.

dyn

Hooks for a widget whose properties are not C functions, such as a control written in BASIC; NULL for a C widget.

The properties every control has, Name, Left, Top, Width, Height, Visible, Enabled, ForeColor, BackColor, the font, and the rest, belong to the form runtime, which sets the WidgetT fields for them; list only the widget’s own. Put the properties in the order a form should set them: the runtime sets them in the order of the .frm file, which the designer writes in the interface’s order, so the Meter’s Max comes before the Mark and the Level that are checked against it.

BASIC writes colors as Visual Basic does, &HBBGGRR, where DVX’s are 0xRRGGBB. ForeColor and BackColor are converted for you. A property of the widget’s own that takes a color converts it with wgtColorFromBasic and wgtColorToBasic (dvxWgt.h).

A DVX BASIC program uses the Meter like any control. Here a scroll bar sets the level, and a label reports the events:

Begin Form Form1
    Caption = "Levels"
    Layout  = HBox
    Begin Meter Meter1
        Max  = 100
        Mark = 80
    End
    Begin HScrollBar HScroll1
        Max = 100
    End
    Begin Label Label1
        Caption = "No overload yet"
    End
End

Sub HScroll1_Change()
    Meter1.Level = HScroll1.Value
End Sub

Sub Meter1_Overload(Level As Long)
    Label1.Caption = "Overload at " & Level & ", peak " & Meter1.Peak
End Sub

Sub Meter1_Change()
    Label1.Caption = "Mark moved to " & Meter1.Mark
End Sub

19.11. The Toolbox Icon and the Help

DVX BASIC’s form designer shows a widget in its toolbox by two resources in the widget’s file:

# meter.res -- resources appended to meter.wgt by dvxres.  DVX BASIC's
# form designer shows icon24 in its toolbox, with name as its tooltip.

icon24      icon    icon24.bmp
name        text    "Meter"
author      text    "Scott Duensing"
description text    "A level meter"

icon24 is the toolbox picture, a 24 x 24 BMP like the template’s icon24.bmp, and name is its tooltip. A file that registers several widgets has one pair for each, in the order their interfaces are registered: icon24 and name for the first, icon24-2 and name-2 for the second, and so on. The other resources, author and description, say what the module is.

A widget has two help files. meter.dhs, the developer help, joins DVX’s help under Technical Reference (for Developers), Widgets, as the pages of DVX’s own widgets do: the C API, the macros, and the table. meter.bhs, the BASIC help, joins the DVX BASIC help as the control’s page: its properties, methods, and events, as a BASIC programmer sees them. make compiles both into meter.hlp only to check them; make package puts the sources beside the widget as METER.DHS and METER.BHS, and DVX compiles them into its two help files when it starts and finds a different number of libraries or widgets than before (Section 18.10). Chapter 20 describes the format.

19.12. The Shared Helpers

DVX’s own widgets share three libraries that widgets of yours can use too. Each has a header in the SDK and a page in the reference; list the library in your widget’s .dep file, as DVX’s widgets do:

Library Header What it has

texthelp

texthelp/textHelp.h

Text editing: the caret’s blink, one selection at a time across widgets, word boundaries, the single-line editor that TextInput, Spinner, and ComboBox embed, and the multi-line editor of TextArea, with their keys, mouse, painting, clipboard, and undo (“Text Help Library” in the DVX C Library Reference).

listhelp

listhelp/listHelp.h

Lists: a list of strings it owns, single and multiple selection, drag to reorder, the drop-down popup list (its geometry, painting, keys, and scroll bar), type-ahead search, and the measuring of items, for ListBox, ListView, Dropdown, and ComboBox (“List Helper Library” in the DVX C Library Reference).

richtext

richtext/richText.h

Styled text: runs of fonts, sizes, styles, and colors over paragraphs, and RTF in and out, for the RichEdit widget (“Styled Text Library” in the DVX C Library Reference).

The clipboard and the counting of double clicks are in the core, in dvxWgtP.h. A text widget of yours that embeds the editor of texthelp gets the keys, selection, and undo of DVX’s own text boxes, which users expect.

19.13. A Program That Uses It

mtrdemo puts the Meter beside a slider that sets its level, with the slider’s caption, two labels, and a button that resets the peak. Its Makefile adds the widget’s folder to the include path, for meter.h, the same way the Makefile of tsdemo adds TextStat’s (Section 18.8):

SDK_DIR ?= ../../../../bin/sdk
KIND     = app
NAME     = mtrdemo

# The Meter widget's header, in its project folder beside this one
override CFLAGS += -I../meter

include $(SDK_DIR)/sdk.mk

The Meter is an add-on: a user may not have it, and DVX skips it if it cannot load it. Unlike a library’s functions, a widget’s are called through its table, so mtrdemo loads and starts without the widget, and must check before it calls a macro, which would call through NULL:

sCtx = ctx;
AppContextT *ac = ctx->shellCtx;

// The widget is an add-on that may not be installed: without its
// table, every wgtMeter macro would call through NULL.
if (!dvxMeterApi()) {
    dvxErrorBox(ac, MTRDEMO_TITLE, "The Meter widget is not installed.");
    return -1;
}

Then it builds the window:

// The meter at the left of a row, as tall as the row; the controls
// in a column beside it, taking the width that is left
WidgetT *root  = wgtInitWindow(ac, sWin);
WidgetT *row   = root ? wgtHBox(root) : NULL;
WidgetT *side  = NULL;
WidgetT *input = NULL;
WidgetT *reset = NULL;

sMeter = row ? wgtMeter(row, MTRDEMO_MAX) : NULL;
side   = row ? wgtVBox(row) : NULL;

if (side) {
    wgtLabel(side, "&Input level:");
    input      = wgtSlider(side, 0, MTRDEMO_MAX);
    sMarkLabel = wgtLabel(side, "");
    sOverLabel = wgtLabel(side, "");
    reset      = wgtButton(side, "Reset &Peak");
}

if (!sMeter || !input || !sMarkLabel || !sOverLabel || !reset) {
    closeWindow();
    return -1;
}

The meter is the first child of an HBox, with weight 0: it is as narrow as its minimum and as tall as the row, and the row, with weight, takes the window’s extra height, so making the window taller shows more lights. The column beside it takes the extra width. Then the callbacks, the mark, and the window’s size:

row->weight      = WGT_WEIGHT_FILL;
row->spacing     = wgtPixels(MTRDEMO_GAP);
side->weight     = WGT_WEIGHT_FILL;
input->onChange  = onInput;
reset->onClick   = onResetPeak;
sMeter->onChange = onMeterChange;
sMeter->onEvent  = onMeterEvent;

wgtMeterSetMark(sMeter, MTRDEMO_MARK);
showNumber(sMarkLabel, "Mark: ", MTRDEMO_MARK);
showNumber(sOverLabel, "Overloads: ", sOverloads);
dvxFitWindow(ac, sWin);
return 0;

The callbacks use the Meter as they would any widget: onChange for the user’s moves of the mark, and onEvent for its own event, compared by name:

// The slider moved: the meter shows its value.
static void onInput(WidgetT *w) {
    wgtMeterSetLevel(sMeter, wgtSliderGetValue(w));
}


// The user moved the meter's mark (the universal onChange).
static void onMeterChange(WidgetT *w) {
    showNumber(sMarkLabel, "Mark: ", wgtMeterGetMark(w));
}


// The meter's own events come to onEvent by name, with their arguments.
static void onMeterEvent(WidgetT *w, const char *name, WgtValueT *args, int32_t argc) {
    (void)w;

    if (strcmp(name, METER_EVT_OVERLOAD) == 0 && argc > 0) {
        sOverloads++;
        showNumber(sOverLabel, "Overloads: ", sOverloads);
        dvxLog("mtrdemo: overload at level %ld", (long)wgtValueToInt(&args[0]));
    }
}


static void onResetPeak(WidgetT *w) {
    (void)w;
    wgtMeterResetPeak(sMeter);
}

19.14. Installing and Testing

make install puts meter.wgt, METER.DHS, and METER.BHS in WIDGETS\LOCAL\METER\ in the DVX folder (with the widget’s .dep file, when it has one):

$ cd meter
$ make install DVX_DIR=/path/to/dvx
$ cd ../mtrdemo
$ make install DVX_DIR=/path/to/dvx

DVX loads widgets only as it starts, so start DVX again after installing or replacing a widget. DVX.LOG lists it among the modules it found and logs Loading: WIDGETS\local\meter\meter.wgt. If it cannot be loaded, DVX starts without it and says so in the Add-ons box, with the reason; DVX /SAFE starts DVX with no add-on widgets at all. Then:

  • Start Meter Demo. Move the slider past the mark, and back, and past it again: each crossing adds an overload, and the log has a line for each. Drag the mark, use the keys and the wheel on the meter, and Tab to it and away: the focus mark comes and goes.

  • Make the window taller and shorter: the meter shows more lights and fewer.

  • Open DVX BASIC: the Meter is in the toolbox, with its icon and tooltip. Draw one on a form, set Max and Mark in the property sheet, and double-click it for an Overload handler.

  • Take the widget away and start Meter Demo: it says the widget is not installed.

If wgtGetApi refuses the table (built for another DVX, or older than the program’s header), DVX.LOG says so with the numbers.

19.15. Using a Control Written in DVX BASIC

A control can also be written in DVX BASIC, as a UserControl: newProject.sh control NAME makes a project of one, and make compiles it into NAME.wgt, a file that holds the compiled control and its resources and no C code. Installed in WIDGETS like a C widget, it is in the toolbox for BASIC programs, and C programs can use it too, through its interface: it has no API table and no header, so wgtGetApi finds nothing, and a program creates it by name and uses its properties, methods, and events by name (Section 5.12). For the template’s control, made with newProject.sh control dial, which shows a Title, counts its clicks in a read-only Count, has a Reset method, and raises Click and Changed(ByVal Count As Integer):

// RaiseEvent Click: Click is one of the universal events, so it comes to
// onClick
static void onDialClick(WidgetT *w) {
    WgtValueT count;

    if (wgtGetProp(w, "Count", &count)) {
        dvxLog("dial: clicked, count %ld", (long)count.i);
    }
}


// RaiseEvent Changed(mCount): an event of the control's own
static void onDialEvent(WidgetT *w, const char *name, WgtValueT *args, int32_t argc) {
    (void)w;

    if (strcmp(name, "Changed") == 0 && argc > 0) {
        dvxLog("dial: count is now %ld", (long)wgtValueToInt(&args[0]));
    }
}


WidgetT *makeDial(WidgetT *root) {
    // The first control written in BASIC that is created loads the BASIC
    // run-time library, which runs it
    WidgetT  *dial  = wgtCreateByName("Dial", root);
    WgtValueT title = wgtValueStr("Clicks");

    if (!dial) {
        return NULL;
    }

    wgtSetProp(dial, "Title", &title);           // Property Let Title
    wgtCallMethod(dial, "Reset", NULL, 0, NULL); // Public Sub Reset
    dial->onClick = onDialClick;
    dial->onEvent = onDialEvent;
    return dial;
}

A file of controls written in BASIC is run by the DVX BASIC run-time library, basrt. As DVX starts, it registers each installed control file’s controls by name only, without loading the library (DVX.LOG says so: “BASIC control Dial (…​): the BASIC run-time library loads when it is first used”), so lists of the widgets and lookups by name find them. The library loads the first time something needs a control’s real interface: the first wgtCreateByName or wgtGetIface of one, from C or from a BASIC form, or the first DVX BASIC program the user runs; the creation then goes on as for any widget. wgtCreateByName returns NULL only when the control is not installed or the library cannot load. wgtIfaceIsLater(name) says whether a name is still waiting for its library.

The control’s Public variables and Property Get and Let procedures are its properties, its Public subs and functions its methods, and its Event declarations its events. The values convert by BASIC’s types: Integer, Long, and Byte are WGT_IFACE_INT, Boolean is WGT_IFACE_BOOL, Single is WGT_IFACE_FLOAT, Double and Currency are WGT_IFACE_DOUBLE, and String, Date, and Variant are WGT_IFACE_STRING; an Enum numbered 0, 1, 2, …​ is WGT_IFACE_ENUM. A method returns its function’s value, or WGT_IFACE_NONE for a sub. An event raised with one of the universal names (Click, DblClick, Change, the key and mouse events) comes to the matching callback, and only when the control’s code raises it; any other comes to onEvent, and the arguments onEvent changes go back to the control’s code, as ByRef arguments do, except those the event declares ByVal.

All the controls of such a file run their code in one copy of DVX BASIC’s machine, shared by every program that uses them, and that code never yields. While it runs, a call from another task is refused: a paint keeps the old picture, and an event is dropped. Keep a control’s code short, as a widget’s handlers are. The DVX BASIC Programming Guide describes writing UserControls.

Chapter 20. Help Files, Resources, and Fonts

A DVX module carries more than its code. A program brings its help, which F1 opens; its icon, its name, and the description Program Manager shows; data it reads while it runs; and perhaps a font of its own. A widget or a library brings help that becomes part of DVX’s own. This chapter covers all of it: help files (the source format, the help compiler, context help, and how a widget’s or library’s help joins the system help), resources (the .res file, the dvxres tool, and reading resources at run time), and fonts (making them with mkfont, carrying one in a program, and installing them for every program).

The example, fortune, keeps everything it needs inside its own .app file.

20.1. The Fortune Program

Fortune shows a saying, a different one each day, in a small bitmap font of its own. Next (or File › Next Saying) shows the next one, and the window grows or shrinks to fit it. File › Font License…​ opens a second window with the notice and license that the font carries. F1 opens Fortune’s help at the topic of the window that has the focus.

The Fortune window with a saying and a Next button
Figure 29. Fortune, its saying in the font it carries
The Font License window with the Cozette font’s license text and OK and Help buttons
Figure 30. The Font License window, its text from the font Fortune carries

The project holds:

File What it is

fortune.c

The program.

fortune.res

Its resources: the icon, the texts Program Manager shows, the sayings, and the font.

sayings.txt

The sayings, one a line. It is not installed: it becomes the sayings resource.

cozette.dfn

Cozette, a 13-pixel bitmap font made with mkfont (Section 20.6.1). It becomes the cozette resource.

icon32.bmp

The icon.

fortune.dhs

The help source: three topics.

Makefile

The usual three settings, and the package settings of Chapter 21.

The program begins with its names. Each resource, help topic, and font the code asks for by name has a #define:

#define FORTUNE_TITLE         "Fortune"
#define FORTUNE_WIN_W         320
#define FORTUNE_WIN_H         120
#define FORTUNE_LIC_TITLE     "Font License"
#define FORTUNE_LIC_W         440
#define FORTUNE_LIC_H         320
#define FORTUNE_SPACING       6
#define FORTUNE_SAYING_CHARS  44
#define FORTUNE_SAYINGS_MAX   64
#define FORTUNE_DAY_SECONDS   86400
#define FORTUNE_LINE_ENDS     "\r\n"
#define FORTUNE_TEXT_MAX      128
#define FORTUNE_ABOUT_MAX     (FORTUNE_TEXT_MAX * 3)

// Resources (fortune.res)
#define FORTUNE_RES_SAYINGS   "sayings"
#define FORTUNE_RES_DESC      "description"
#define FORTUNE_RES_AUTHOR    "author"

// The sayings' font, a font resource of the program's
#define FORTUNE_FONT_FAMILY   "Cozette"
#define FORTUNE_FONT_SIZE     13

// Help topics (fortune.dhs)
#define FORTUNE_TOPIC_START   "fortune.overview"
#define FORTUNE_TOPIC_MAIN    "fortune.window"
#define FORTUNE_TOPIC_LICENSE "fortune.license"

// Menu command IDs
#define CMD_FILE_NEXT         100
#define CMD_FILE_LICENSE      101
#define CMD_FILE_EXIT         102
#define CMD_HELP_CONTENTS     200
#define CMD_HELP_ABOUT        201
static DxeAppContextT *sCtx         = NULL;
static AppContextT    *sAc          = NULL;
static WindowT        *sWin         = NULL;
static WindowT        *sLicWin      = NULL;
static WidgetT        *sSaying      = NULL;
static char           *sSayingText  = NULL;
static int32_t         sSayingCount = 0;
static int32_t         sCurrent     = 0;
static const char     *sSayings[FORTUNE_SAYINGS_MAX];
static char            sAuthor[FORTUNE_TEXT_MAX];
static char            sDescription[FORTUNE_TEXT_MAX];

appMain reads the resources before it makes a window, and declines to start when they are missing; then it hands the shell its help callback (Section 20.3):

sCtx = ctx;
sAc  = ctx->shellCtx;

if (!loadResources()) {
    dvxErrorBox(sAc, FORTUNE_TITLE, "The sayings are missing from the program's file.");
    free(sSayingText);
    return -1;
}

ctx->onHelpQuery = onHelpQuery;

The window is built as in hello (Chapter 2). Each step is taken only when the one before it worked, and when one fails, onClose destroys whatever was made and frees the sayings:

sWin = dvxCreateWindowCentered(sAc, FORTUNE_TITLE, FORTUNE_WIN_W, FORTUNE_WIN_H, false);

WidgetT *root = (sWin && buildMenus()) ? wgtInitWindow(sAc, sWin) : NULL;

sSaying = root ? wgtLabel(root, "") : NULL;

WidgetT *next = sSaying ? wgtButton(root, "&Next") : NULL;

if (!next) {
    onClose(sWin);
    return -1;
}

sWin->onClose = onClose;
sWin->onMenu  = onMenu;
root->spacing = wgtPixels(FORTUNE_SPACING);
next->onClick = onNextClick;
// The main window's close box and File > Exit: the Font License window
// goes too, then the main window, and with it the program.
static void onClose(WindowT *win) {
    closeLicense();
    dvxDestroyWindow(sAc, win);
    sWin = NULL;
    free(sSayingText);
    sSayingText = NULL;
}

dvxDestroyWindow ignores NULL, so onClose needs no tests: it serves for a window not made, a license window not open, and the end of the program alike. The rest of the program is taken apart in the sections below: its help, its resources, and its font.

20.2. Help Files

A help file is compiled. You write its source, a .dhs file of text and directives, and the help compiler, dvxhlpc, turns it into a .hlp file: the topics, the table of contents, the keyword index, a search index of the topics' words, and the pictures, all in one file. DVX Help, the viewer, shows it: the table of contents on the left, a topic on the right, Back and Forward, the Index, and Search. A program’s help is for the people who use the program, so write it as a user’s guide: what the program does and how to use it, in plain words.

20.2.1. The Source Format

A .dhs file is plain text, read a line at a time. A line with a period in its first column is a directive; a line with # in its first column is a comment; every other line is text. Here is the first of Fortune’s three topics:

.topic fortune.overview
.title Fortune
.toc 0 Fortune
.default
.index Fortune
.index Sayings

.h1 Fortune

.image icon32.bmp right

Fortune shows a saying when it starts, a different one each day. Choose Next
for another.

The sayings are shown in a font that comes with Fortune, so they look the same
on every PC. The font's license says who made it and what you may do with it.

.link fortune.window The Fortune Window
.link fortune.license The Font License Window

Everything belongs to a topic, one page of the help. .topic starts one and gives it an ID, a word without blanks by which links, the table of contents, and context help find it. The directives after it, up to the next .topic, describe the topic and fill it:

Directive Does

.topic id

Starts a topic. IDs are compared exactly, case included. Use the program’s name as a prefix (fortune.window), so that IDs stay unique.

.title text

The topic’s title: DVX Help shows it in its window’s title bar and in the list of search results. Give every topic one.

.toc depth text

An entry in the table of contents for this topic (Section 20.2.3).

.index keyword

An entry in the keyword index for this topic; a topic may have any number.

.default

Makes this the topic the file opens at when no topic is asked for. Without one, the first topic is the default.

Text lines are joined into paragraphs, and an empty line ends a paragraph. Do not break lines to a width: the viewer wraps each paragraph to the width of its window, so one paragraph a line is the natural way to write it. Text before a file’s first .topic is ignored, and any directive there but .include and .section is an error.

The other directives make the content of the page:

Directive Makes

.h1 text, .h2, .h3

A heading of level 1 (on a colored bar), 2 (underlined), or 3 (plain).

.list, .item text, .endlist

A bulleted list. Each .item starts an item; text lines after it continue the item.

.table …​ .endtable

A block shown exactly as it is written, line for line and never wrapped: a table is columns lined up with spaces.

.code …​ .endcode

The same, for code and anything else typed. A word after .code is ignored: DVX’s own help sources name a listing’s language there (.code text for a diagram) for the printed books made from them.

.note [info|tip|warning] …​ .endnote

A callout box with a colored bar; info when no kind is given.

.link id text

A link, on a line of its own, to the topic id, showing text (Section 20.2.2).

.image file [left|center|right]

A picture (BMP, PNG, JPEG, or GIF), at the left unless another place is given. The compiler copies the picture into the .hlp file.

.hr

A horizontal rule.

Fortune’s other two topics use most of them:

.topic fortune.window
.title The Fortune Window
.toc 1 The Fortune Window
.index Next
.index Next Saying

.h1 The Fortune Window

The window shows one saying, and grows or shrinks to fit it.

.list
.item Choose Next, or Next Saying on the File menu, to see the next saying.
.item Press F1 for this help.
.endlist

.h2 Menus

.table
  Menu    Command          What it does
  ----    -------          ------------
  File    Next Saying      Show the next saying.
  File    Font License     Show the license of Fortune's font.
  File    Exit             Close Fortune.
  Help    Contents         Open Fortune's help.
  Help    About Fortune    Say what Fortune is and who wrote it.
.endtable

.note tip
After the last saying, Fortune starts again at the first.
.endnote

A few rules follow from reading a line at a time:

  • Inside .code and .table, every line is kept as it is, # and leading periods included: only .endcode or .endtable ends the block. Everywhere else a line that starts with a period is a directive, so a sentence cannot begin a line with one: the compiler warns of an “unknown directive” and drops the line. Start the line with another word.

  • Search finds the words of titles, paragraphs, headings, list items, notes, code blocks, tables, and the text of links. Give the names a reader will look for (a command, a menu, a function) an .index entry too, which Search matches and the Index lists.

  • A .code or .table block still open at the end of a file is closed there, with a warning; a .list or .note simply ends with the file, or with the next .topic.

  • A line may be up to 4,094 characters, and a paragraph up to 65,535 bytes.

A .link is a line of its own in the topic, underlined, which DVX Help follows on a click, or on Enter or Space once Tab has reached it. Its target must be a topic compiled into the same help file, before or after the link: dvxhlpc stops with an error, naming the file and line, for a link to an ID it does not have. Links cannot reach into another help file; name the other file’s topic in words instead. A .link line inside a .code block is example text, and is not checked.

20.2.3. The Table of Contents and the Index

The table of contents is a tree, built from the .toc lines in the order they come. .toc 0 is an entry at the top level, .toc 1 an entry under the last .toc 0 before it, and so on down: the depth is one digit, 0 to 9. Not every topic needs an entry; a topic only links reach is fine. Fortune’s overview is at the top and its two window topics under it.

The keyword index is every .index line of the file, sorted alphabetically without regard to case. DVX Help’s Index lists them, and choosing one opens its topic. Several topics may share a keyword.

20.2.4. Several Files: .include and .section

dvxhlpc takes any number of source files and makes one help file of them: each file starts afresh (no topic current, no block open), and links may cross from one to another. Within a file, .include file reads another file in place, as if its lines were there; a relative name is relative to the including file, and includes may nest 16 deep.

.section name matters to help assembled from many authors' files, such as DVX’s system help (Section 20.4). It files the .toc entries that follow it, to the end of its file, under a heading name in the table of contents; .section a|b nests the heading b under a, to any depth. Entries filed under no section come first, then each section with everything filed under it, in the order the sections first appear. A program’s own help, written as one file, has no need of it.

20.2.5. Compiling with dvxhlpc

make compiles NAME.dhs (with NAME.bhs for a widget) into NAME.hlp whenever the source has changed. The compiler is the SDK’s bin/dvxhlpc:

$ dvxhlpc [-o OUTPUT.hlp] [-i IMAGEDIR] [--html OUTPUT.html] [--ids IDS.txt] \
      [--joins IDS.txt] [--quiet] INPUT.dhs [@LISTFILE] ...
Option Does

-o file

The help file to write. Without it, nothing is written: the sources are only checked.

-i dir

The folder .image names are relative to; the current folder by default. sdk.mk gives none, so the pictures of a program’s help are found in its project folder, as Fortune’s icon is.

--html file

Also writes the help as one HTML file (with a sidebar table of contents, and the pictures inside it), to read on the build machine.

--ids file

Also writes the topic IDs compiled, one a line.

--joins file

Checks help that is to join another help file, whose topic IDs file lists (as --ids writes them): a link to one of those topics is allowed, a topic ID among them is an error, and so is a picture. sdk.mk checks a widget’s or library’s help this way (Section 20.4).

--quiet

Leaves out the progress lines.

@file

Reads more input file names from file, one a line; blank lines and lines starting with # are skipped.

An error names the file and the line, among the progress lines, a missing picture’s and a topic ID given twice (with both places) among them; a warning does too (warning: fortune.dhs:12: unknown directive .frobnicate), and does not stop the compile. A mistyped link in Fortune’s overview gives:

dvxhlpc: DVX Help Compiler
Pass 1: Parsing 1 input file(s)...
  parsing fortune.dhs
error: fortune.dhs:46: link to missing topic 'fortune.windows'
  3 topic(s), 3 TOC entries, 7 index entries, 1 image(s)
Aborting due to 1 error(s).

After any error the compiler writes nothing, and the .hlp file from before stays as it was. A picture that cannot be read is an error too. The --html output is the quickest way to proofread help: dvxhlpc -o /tmp/check.hlp --html fortune.html fortune.dhs, and open fortune.html in a browser.

Note
The compiler does not check that topic IDs are unique. When two topics share one, links and context help reach the first.

On DVX itself the same compiler is SYSTEM\DVXHLPC.EXE for the DOS prompt, and the Help Editor (both come with the Developer Tools part of DVX) edits and compiles help in a window.

20.3. Context Help

F1 belongs to the shell. When the user presses it, the shell finds the program that owns the focused window and opens that program’s help, through DxeAppContextT:

  1. If the program set onHelpQuery, the shell calls it, with helpQueryCtx as its argument, so the program can set the topic for what the user is doing now.

  2. If helpFile is not empty, the shell opens DVX Help on that file at helpTopic (a buffer of SHELL_HELP_TOPIC_MAX, 128 bytes; empty for the file’s default topic). A topic the file does not have opens the default topic instead.

  3. If helpFile is empty, F1 opens DVX’s own help, as it does over a window that belongs to no program.

The shell sets helpFile before appMain runs, to NAME.hlp beside NAME.app when that file is there; that is why hello needed no code for F1. A program whose help is elsewhere, or named otherwise, sets helpFile itself in appMain. helpTopic starts empty.

There are two ways to keep helpTopic right. A program can set it whenever the user moves to another part of it: a page of a tab control, a window, a mode. Or it can work it out only when it is needed, in onHelpQuery, which is less code and never out of date. Fortune does that:

// F1 in one of the program's windows: the shell calls this, then opens
// helpFile at helpTopic.  The topic is that of the window with the
// focus; a message box of the program's gets the main window's.
static void onHelpQuery(void *ctx) {
    (void)ctx;

    const WindowT *focused = dvxGetFocusedWindow(sAc);
    const char    *topic   = (sLicWin && focused == sLicWin) ? FORTUNE_TOPIC_LICENSE : FORTUNE_TOPIC_MAIN;

    snprintf(sCtx->helpTopic, sizeof(sCtx->helpTopic), "%s", topic);
}

dvxGetFocusedWindow(sAc) returns the window with the focus, the one the keyboard goes to, or NULL; it may be another program’s, so compare it with the program’s own windows. The shell calls onHelpQuery only when one of the program’s windows has the focus, but that window may be a message box the program opened (About, say), so the code compares it with the windows it knows and gives anything else the main window’s topic. onHelpQuery runs on the shell’s task, as the program’s callbacks do, and should only set the topic: the shell opens the help when it returns.

A program with many windows, or a window with many parts, can map them to topics the same way: the focused widget is wgtGetFocused(), and a window’s userData is the program’s to use, though DVX’s own dialog boxes use theirs, so test the window before trusting it.

20.3.1. Opening Help from Code

shellOpenHelpFile(ac, helpFile, topicId) opens DVX Help from code, as a Help menu does: if DVX Help is running, the help is shown in its window, which comes to the front; otherwise a new DVX Help starts. topicId is one of the help file’s topic IDs, or NULL for its default topic. A NULL or empty helpFile opens DVX’s own help (and the topic is not used). Fortune’s Help › Contents and the Help button of its license window both open a topic:

// The license window's Help button: DVX Help at the license's topic of
// the program's help file.
static void onLicenseHelpClick(WidgetT *w) {
    (void)w;
    shellOpenHelpFile(sAc, sCtx->helpFile, FORTUNE_TOPIC_LICENSE);
}

The shell passes the help file and the topic to DVX Help as a command line, each one argument, in quotes when it has blanks in it (dvxArgAppend; Section 11.5), so a help file with a long name needs nothing more. (hello’s Help › Contents passes `NULL for the default topic; Section 2.8.) shellOpenHelp(ac, args) takes such a command line as it is, for a program that already has one.

20.3.2. Help in a Window of Your Own

The viewer is not the only way to show help. The HelpView widget (helpView/helpView.h) shows one topic of a help file in a pane of your window, as DVX Help draws it, and calls the program back when the user follows a link; the help file library (hlpFile.h) opens a .hlp file and reads its topics, table of contents, and index, and searches it. A program can use them for a help pane, or for showing its own documents written in the help format. The reference describes both (“HelpView” in the DVX C Library Reference, “Help File Library” in the DVX C Library Reference).

20.4. Help for Widgets and Libraries

A program carries its compiled help. A widget or a library carries its help sources instead, because its help is part of DVX’s: the system help (APPS\KPUNCH\PROGMAN\DVXHELP.HLP, which Program Manager’s Help menu opens, and whose Technical Reference documents every library and widget) and the DVX BASIC help. make package puts NAME.DHS (and a widget’s NAME.BHS) beside the module, and DVX compiles them into its help files itself:

  • When DVX starts, it compares the modules and help sources in LIBS and WIDGETS, the help sources in APPS with the .HCF files there that name each help file’s sources, and the pictures in each .HCF file’s picture folder (its imagedir), by their paths, sizes, and times, with what it recorded the last time (the [help] section of DVX.INI). A file rewritten at the same size within two seconds keeps its time (DOS keeps a file’s time to two seconds), so it is not seen as changed; neither is a source outside those three folders until something else changes, nor a picture of help whose .HCF file names no imagedir (its pictures are then looked for in the DVX folder, which DVX does not search) until that help’s sources change. When something is new, changed, or gone, it compiles again, before the desktop appears, each help file whose sources changed: the system help from DVX’s user guide and every .DHS file under LIBS and WIDGETS, and the DVX BASIC help from its own sources and every .BHS file under WIDGETS and LIBS. The sources go in a fixed order, each folder’s files sorted by name, so a rebuild gives the same help every time. The title screen shows the progress.

  • In that compile a .link to a topic that is not there is shown as plain text instead of failing, so a library that is removed never breaks the help that linked to it, and a topic ID given twice keeps the first. When the sources still do not compile together, DVX compiles each on its own, leaves out the ones that fail (logging the compiler’s messages in DVX.LOG, and naming an add-on’s in its Add-ons box), and builds the help from the rest. A help file that cannot be built at all keeps its old contents, and DVX tries again the next time it starts, three times in all; then it waits for the next change.

  • DVX does not rebuild its help when the DVX folder or the user folder cannot be written, and on its very first start it takes the help files as they were installed, unless an add-on’s source is among them.

The template’s help shows what a widget’s or library’s source should begin with:

.section Technical Reference (for Developers)|Libraries
.topic lib.tplname
.title TplName Library
.toc 0 TplName Library
.index TplName
.index tplNameAdd

.section files the topic beside DVX’s own libraries (a widget’s says |Widgets), and the .toc 0 entry becomes an entry in that list. The topic ID must not be one that any other part of the system help uses, so keep to the templates' forms, lib.name and widget.name (and ctrl.name in a widget’s .bhs), with names that are yours. Give every function, macro, and type a reader may look for an .index entry: the tables that list them are not searched.

Three things work differently from a program’s help, all because the sources are compiled together on the user’s PC:

  • make checks your sources as DVX’s compile will see them, against the topic IDs of DVX’s own help, which the SDK carries (dvxhlpc --joins), and writes no help file: it records the check in NAME.hck. A link to one of DVX’s topics is allowed, but a topic ID DVX’s help has already is an error.

  • A picture cannot be used, and make says so: make package does not ship the image files, and DVX’s compile looks for pictures in its own folders, never in yours.

  • DVX notices a new library or widget, a new version of one, or one removed, by its file’s size and time, so the new help appears at the next start.

The widget’s BASIC help, its .bhs file, is the subject of Chapter 19; a library’s DVX BASIC declarations are documented in its .dhs (Chapter 18).

20.5. Resources

A resource is a named piece of data appended to a module file, after the code. The DXE3 loader never reads past the module’s own sections, so the resources cost nothing until something reads them, and they travel with the file: nothing can get separated from the program. Program Manager reads a program’s name, description, and icon from its resources without loading it; the DVX BASIC toolbox reads a widget’s; and the program reads its own.

At the end of the file is a footer (the magic DVXR, where the directory starts, and how many entries it has) and, before it, the directory: an entry for each resource with its name (up to 31 characters), its type, and where its data is. The layout is in dvxRes.h (“dvxRes.h — Resource System” in the DVX C Library Reference).

20.5.1. The .res File

sdk.mk builds a module’s resources from NAME.res, a list of them, one a line, after it links the module. Fortune’s:

icon32      icon    icon32.bmp
name        text    "Fortune"
author      text    "Scott Duensing"
description text    "A saying for the day, in a font of its own"
sayings     binary  sayings.txt
cozette     font    cozette.dfn

Each line is a name, a type, and the data, separated by blanks. Blank lines, and lines whose first character other than a blank is #, are skipped.

Type Data

icon (or image)

A picture file: BMP, PNG, JPEG, or GIF. It is stored as the file is, and decoded when it is shown.

text

A string in double quotes (or, without quotes, the rest of the line). It is stored with its terminating zero. There are no escapes, so a text resource is one line; the closing quote is the last one on the line.

binary

A file of any kind, stored byte for byte.

font

A .DFN font file (Section 20.6), which dvxres checks is one.

In the file’s directory the four types are DVX_RES_ICON, DVX_RES_TEXT, DVX_RES_BINARY, and DVX_RES_FONT (dvxRes.h). A file is named relative to the folder make runs in, the project’s. The name is the program’s to choose (up to 31 characters, no blanks), but some names mean something to DVX:

Name Type Read by

icon32

icon

Program Manager: the program’s icon, 32 x 32 pixels. dvxResLoadIcon reads it for a window’s icon (Chapter 4).

name

text

Program Manager: the program’s name (up to 63 characters). Without it, Program Manager shows the file name.

description

text

Program Manager: shown in its status bar for the selected program and in its list view (up to 127 characters).

icon24, name

icon, text

A widget’s: its picture in the DVX BASIC toolbox, and its tooltip there (Chapter 19).

any

font

The shell, which adds every font resource of a program for it when it starts (Section 20.6.3).

author in the templates is read by nothing in DVX: it is there for people who list the resources.

sdk.mk rebuilds the module when NAME.res changes or any file it names does (dvxres deps NAME.res lists them), so a change to Fortune’s sayings.txt or cozette.dfn is in the next make.

20.5.2. Reading Resources

A program reads its own resources through a handle on its own file, ctx->appPath:

Call Does

dvxResOpen(path)

Reads the directory of path and returns a handle (DvxResHandleT *), or NULL when the file cannot be read or has no resources.

dvxResFind(h, name)

The directory entry (const DvxResDirEntryT *) of the resource name, with its type and size, or NULL when there is none. The entry stays valid until dvxResClose.

dvxResRead(h, name, &size)

The resource’s data in a block from malloc, which the caller frees, and its size; NULL when there is no such resource. The block holds the data exactly: a text resource ends in its zero, any other has none added.

dvxResReadText(h, name, buf, size)

A text resource copied into buf, cut to fit and ended with a zero. False when there is no such resource (buf is not touched) or it cannot be read (buf is "").

dvxResClose(h)

Frees the handle. NULL is ignored.

The handle holds the directory in memory, not an open file: each read opens the file again. A program that reads several resources opens one handle for them all, and closes it when it is done. Fortune reads everything as it starts:

// Everything the program reads from its own file, through one handle:
// the sayings, and the two texts the About box shows.  False when the
// file has no resources, or no sayings.
static bool loadResources(void) {
    DvxResHandleT *res = dvxResOpen(sCtx->appPath);

    if (!res) {
        return false;
    }

    bool ok = loadSayings(res);

    dvxResReadText(res, FORTUNE_RES_DESC, sDescription, sizeof(sDescription));
    dvxResReadText(res, FORTUNE_RES_AUTHOR, sAuthor, sizeof(sAuthor));
    dvxResClose(res);
    return ok;
}

The sayings are a binary resource, so the copy has no terminating zero. Fortune grows the block by one byte for it, then cuts it into lines in place; the lines stay in that block until the program ends:

// The sayings resource is sayings.txt byte for byte: a saying a line,
// and no terminating zero.  The copy dvxResRead returns is grown by a
// byte for one, and each line end becomes the end of a string.
static bool loadSayings(DvxResHandleT *res) {
    uint32_t size = 0;
    char    *data = (char *)dvxResRead(res, FORTUNE_RES_SAYINGS, &size);
    char    *text = data ? (char *)realloc(data, size + 1) : NULL;

    if (!text) {
        free(data);
        return false;
    }

    text[size]  = '\0';
    sSayingText = text;

    for (char *line = strtok(text, FORTUNE_LINE_ENDS); line && sSayingCount < FORTUNE_SAYINGS_MAX; line = strtok(NULL, FORTUNE_LINE_ENDS)) {
        sSayings[sSayingCount++] = line;
    }

    return sSayingCount > 0;
}

realloc is DVX’s tracking allocator’s, like malloc and free (Chapter 3), and strtok is safe here because nothing else can run until loadSayings returns. The About box shows the two texts:

// Help > About: the description and author resources, read as the
// program started.
static void showAbout(void) {
    char text[FORTUNE_ABOUT_MAX];

    snprintf(text, sizeof(text), "%s\n\n%s\n\nBy %s", FORTUNE_TITLE, sDescription, sAuthor);
    dvxInfoBox(sAc, "About " FORTUNE_TITLE, text);
}

For a single resource, dvxApp.h has calls that open, read, and close in one: dvxResLoadText(path, name, buf, size), dvxResLoadData(path, name, &size), and dvxResLoadIcon(ac, path, name, &w, &h, &pitch), which decodes a picture resource into the display’s pixel format (free it with dvxFreeImage). dvxResLoadIconData(path, &size) returns the bytes of any DVX file’s icon: its icon32, or else its icon24.

dvxResAppend and dvxResRemove change the resources of a file; DVX’s Resource Editor uses them. A program never changes its own file: the DVX folder may be read-only, and a file changed after it was installed no longer matches its package, so removing the package leaves it behind unless the user agrees to delete it (Section 21.6). Data a program writes goes in its user folder (Chapter 10).

20.5.3. The dvxres Tool

sdk.mk runs dvxres build, but the tool does more, on any DVX module file. It is bin/dvxres in the SDK and SYSTEM\DVXRES.EXE on DVX (with the Developer Tools part):

Command Does

dvxres build file list.res

Replaces all of the file’s resources with those list.res names. An error names the line; a resource name given twice is one.

dvxres deps list.res

Lists the files list.res names, one a line, as sdk.mk uses them to know when to rebuild.

dvxres list file

Lists the resources: name, type, and size.

dvxres get file name [out]

Writes the data of one resource to out, or to standard output.

dvxres add file name type data

Adds one resource, or replaces the one of that name; data is the text, or the file.

dvxres strip file

Removes every resource.

$ dvxres list fortune.app
Resources in fortune.app (6 entries):
  Name                            Type     Size
  ------------------------------- -------- --------
  icon32                          icon     3126
  name                            text     8
  author                          text     15
  description                     text     43
  sayings                         binary   610
  cozette                         font     4814
Note
dvxres build does not check that the names in a .res file are different, and with two resources of one name, which of them dvxResRead finds is not defined. Give each its own.

20.5.4. Resources in Widgets and Libraries

A widget’s .res gives the DVX BASIC toolbox its picture and tooltip: icon24, a 24 x 24 picture, and name. A file that registers several widget types gives the second its icon24-2 and name-2, and so on (Chapter 19). The loader records each widget file’s path under the names its BASIC interfaces were registered with (wgtRegisterIface), and wgtIfaceGetPath(name) returns it, which is how the toolbox finds the file to read.

A library’s resources (the template gives it an icon, a name, an author, and a description) identify the file to anyone who lists them; DVX itself reads nothing from them. Font resources are added only for programs: a font that a widget or library needs is installed as a font package, for every program (Section 20.6.4).

20.6. Fonts

Every font DVX draws is a bitmap font, made in advance: DVX never draws an outline (Chapter 9). A .DFN file holds one family in one style (regular, bold, italic, or bold italic) at every pixel size it comes in, each a set of bitmaps of the 256 characters of code page 437, perhaps with a smoothed copy too, and the notice and license text of the font it was made from. To know the families, DVX reads only each file’s header and its list of sizes; a size’s bitmaps are read when something first draws or prints in it. The reference describes the format (“Font System” in the DVX C Library Reference); the SDK has no header for it.

20.6.1. Making Fonts with mkfont

The SDK’s bin/mkfont makes .DFN files from TrueType, OpenType, Type 1, BDF, and PCF fonts, rendering every size once on the build machine (with a copy of FreeType built into it, so the result does not depend on the machine). It works from a manifest, an INI file that lists the fonts to make and how:

$ mkfont MANIFEST SOURCEDIR OUTDIR
$ mkfont -p FONT.DFN SHEET.BMP

The first form makes every font the manifest lists, from files under SOURCEDIR, into OUTDIR as NAME.DFN. The second draws every size of a font into a picture, with the characters the font lacks marked in red: look at it before you ship a font. Fortune’s cozette.dfn was made from the BDF source of Cozette, an MIT-licensed bitmap font, with this manifest:

[fonts]
COZETTE = Cozette

[licences]
COZETTE = cozette/LICENSE

[COZETTE]
style   = regular
licence = COZETTE
source  = cozette/cozette.bdf
sizes   = native
$ mkfont cozette.ini fontsrc out
COZETTE   1 sizes,  0 smoothed, missing   1: 00

[fonts] lists the files to make: each key is a file’s base name (one to eight capitals, digits, _, or -), and each value the family name people see (up to 31 characters). [licences] names each license and the text file (or files) under SOURCEDIR it is made of; every font must name one. Each font then has a section of its own:

Key Meaning

style

regular, bold, italic, or bolditalic.

licence

A key of [licences]: the text the file carries.

source

The font file, under SOURCEDIR. source1, source2, and so on add files for other sizes, each with its own sizes1, smooth1, …​

sizes

The pixel sizes to make for the screen (1 to 127), or native for a bitmap font, which has its own.

smooth

Sizes (or all) also made smoothed, two bits a pixel, for screens of more than 256 colors; each must be one of sizes.

print

Sizes made for printing, none of them one of sizes (Chapter 12).

hinting

native (the font’s own), auto (FreeType’s), or none. Italics often look better with auto.

graycut

Sizes (or all) whose 1-bit glyphs are cut from the smoothed rendering, for a face whose own 1-bit hinting draws it too light.

boxdraw

true: DVX draws the box, block, and shade characters itself.

chars

Only these characters, as hex codes and ranges (20-7E A9); the rest are marked missing.

weight

The weight of a variable font to make.

encoding

cp437 for a font that numbers its glyphs in code page 437; unicode otherwise.

A file holds at most 64 sizes in all (its screen sizes, smoothed sizes, and print sizes together). A bitmap font has only its own sizes, smoothed or printed in none. Any mistake stops mkfont with a message that names the font. Each line it prints lists the characters a font lacks at some size; DVX fills those in from DejaVu Sans (DejaVu Sans Mono for a fixed-pitch face) or the system font when it draws. Cozette lacks only character 0, which a C string cannot hold.

A family’s four styles are four files that share the family name, their base names the family’s short form plus B (bold), I (italic), or Z (bold italic): ACMESANS, ACMESANB, ACMESANI, ACMESANZ. The page Making Fonts, under Technical Reference and SDK Quick Start in DVX’s help, has more on choosing sizes for the screen and for printing.

20.6.2. Licenses

Ship only fonts whose license allows them to be converted and given away (the SIL Open Font License, Apache, MIT, the Bitstream Vera license, public domain), and read what the license says about the name of a converted copy: some reserve the original’s name. A .DFN carries its notice (the family, the style, the files it was made from, and their copyright notices) and the full text of its license, made ASCII with DOS line ends, so the license goes wherever the font goes. The Font dialog’s License button shows it, and dvxFontLicence(font) returns it: the notice, a blank line, and the license, in a block from malloc that the caller frees, or NULL for the system font. Fortune shows it in a window:

// The Font License window: the notice and license the sayings' font
// carries, which dvxFontLicence reads from where the font came from (here
// the program's own file).  When it is open already, it comes forward.
static void openLicense(void) {
    if (sLicWin) {
        dvxRaiseWindow(sAc, sLicWin);
        return;
    }

    char *text = dvxFontLicence(wgtFont(sSaying));

    if (!text) {
        dvxErrorBox(sAc, FORTUNE_TITLE, "The sayings are in the system font, which has no license text.");
        return;
    }

    // Its lines end in CR LF; a text area's in LF
    int32_t len = platformStripLineEndings(text, (int32_t)strlen(text));

    sLicWin = dvxCreateWindowCentered(sAc, FORTUNE_LIC_TITLE, FORTUNE_LIC_W, FORTUNE_LIC_H, true);

    WidgetT *root = sLicWin ? wgtInitWindow(sAc, sLicWin) : NULL;
    WidgetT *area = root ? wgtTextArea(root, len) : NULL;
    WidgetT *row  = area ? wgtHBox(root) : NULL;
    WidgetT *ok   = row ? wgtButton(row, "OK") : NULL;
    WidgetT *help = ok ? wgtButton(row, "&Help") : NULL;

    if (help) {
        sLicWin->onClose = onLicenseClose;
        root->spacing    = wgtPixels(FORTUNE_SPACING);
        area->weight     = WGT_WEIGHT_FILL;
        ok->onClick      = onLicenseOkClick;
        help->onClick    = onLicenseHelpClick;
        wgtSetText(area, text);
        wgtSetReadOnly(area, true);
        dvxSetWindowButtons(sLicWin, ok, ok);
    } else {
        closeLicense();
    }

    free(text);
}

The text’s lines end in CR LF, and a text area’s in LF, so platformStripLineEndings removes the CRs in place and returns the new length, which is also the most the text area needs to hold: the maxLen of wgtTextArea, without which a text area holds 256 characters. wgtSetReadOnly lets the user scroll and select but not type, and dvxSetWindowButtons makes OK the window’s default and cancel button: Esc presses it, and so does Enter while the focus is not in the text area, which keeps Enter for itself.

20.6.3. A Font the Program Carries

A font resource is the simplest way for a program to bring its own font. When the shell starts a program, before appMain, it adds every font resource in the program’s file as a font of that program’s alone, and when the program ends it removes them. Meanwhile the program opens it by its family name, like any font (Chapter 9), and other programs never see it. Fortune gives the label that shows the sayings its font:

sSaying->minW = wgtChars(FORTUNE_SAYING_CHARS);
wgtLabelSetWordWrap(sSaying, true);
wgtSetFont(sSaying, FORTUNE_FONT_FAMILY, FORTUNE_FONT_SIZE, FONT_STYLE_REGULAR);

const char *family = dvxFontFamilyOf(wgtFont(sSaying));

if (strcmp(family, FORTUNE_FONT_FAMILY) != 0) {
    dvxLog("fortune: no %s font, so the sayings are in %s", FORTUNE_FONT_FAMILY, family);
}

wgtSetFont opens the font at the size nearest the one asked for, holds it while the label has it, and closes it with the label. wgtChars makes the label’s width 44 characters of its own font, so the width follows the font, and a word-wrapped label is as tall as its lines. When the family is not there (the resource was left out, or the font in it could not be read), the label gets the system font, and dvxFontFamilyOf says so; Fortune logs it and goes on in the system font.

Each saying changes the label’s height, so the window is fitted to it every time:

// Saying index (counting on from the last one round to the first) in the
// label, and the window fitted to it: a word-wrapped label is as tall as
// its lines.
static void showSaying(int32_t index) {
    sCurrent = index % sSayingCount;
    wgtSetText(sSaying, sSayings[sCurrent]);
    dvxFitWindow(sAc, sWin);
}

A font too large to carry in the .app can go in the program’s DATA folder (Chapter 10), added while the program runs with dvxFontAddFile(ctx->appId, path); dvxFontAddMemory adds one from memory. Fonts added for the program’s ID go when it ends, as font resources do. A program’s own face comes first where an installed family has the same name: Cozette is also one of DVX’s More Fonts, and a Fortune on a PC that has them still draws with its own copy.

20.6.4. Fonts for Every Program

Fonts for every program to use are installed in the FONTS folder of SHARED, each vendor’s in a folder of its own, by a package of kind font: SHARED\FONTS\ACME\ACMESANS.DFN. They appear in the Font dialog and in dvxFontOpen the next time DVX starts: DVX reads the font folders once, and again only when a program calls dvxFontRescan, which Software does not. A face may come in several files of the same family and style, each adding sizes the others lack, but one file a face is the way to ship: its sizes cannot drift apart. sdk.mk does not make font packages; Section 21.9 shows how to make one with dvxpkg.

Chapter 21. Packaging and Publishing

A module reaches other people’s DVX as a package: one .DPK file that DVX’s Software program installs, records, upgrades, and removes again, along with whatever else the module needs. sdk.mk makes one from every project. This chapter covers what goes into a package and how it describes itself, the packages it needs, signing and the trust DVX gives a signature, installing, versions and updates, and publishing on the package server, where every DVX can find it. The example is fortune, the program of Chapter 20, whose Makefile carries package settings.

21.1. make package

make package builds the module and its help, then does three things:

  1. It lays out pkg/ exactly as the files go into the DVX folder.

  2. It writes a template, pkg.ini, from the package settings, and has dvxpkg build make NAME.dpk from the template and pkg/.

  3. It removes the template.

make install does the same and then copies pkg/ into the DVX folder (Chapter 1). What pkg/ holds depends on the kind of module:

KIND Folder Files

app, basic

pkg/apps/<VENDOR>/<NAME>/

NAME.app, NAME.hlp, and a DATA folder with the files DATA names.

widget, control

pkg/widgets/<VENDOR>/<NAME>/

NAME.wgt, NAME.DHS, NAME.BHS, and NAME.dep, each when the project has it.

library

pkg/libs/<VENDOR>/<NAME>/

NAME.lib, NAME.DHS, and NAME.dep, each when the project has it.

A program carries its compiled help, a widget or library its help sources, which DVX compiles into its own help (Section 20.4). DATA names files or folders, copied whole into the module’s DATA folder (Chapter 10). A .dep file is copied with DOS line ends (Chapter 18). Nothing else goes in: a library’s header and its DVX BASIC declarations are for the programmers who use it, not for the PCs that run it.

VENDOR (local unless you set it) is the folder under APPS, WIDGETS, or LIBS the module goes in, and the first half of the package’s ID: the ID is VENDOR.NAME in lower case, so VENDOR is one to eight letters, digits, or _. local is for trying things out. Choose a short name of your own for everything you hand out, and keep it: on the package server an ID belongs to whoever published it first (Section 21.8). With VENDOR=acme:

$ make package VENDOR=acme
...
mkdir -p pkg/apps/acme/fortune
cp fortune.app pkg/apps/acme/fortune/
cp fortune.hlp pkg/apps/acme/fortune/
...
.../dvxpkg build pkg.ini pkg fortune.dpk  || { rm -f pkg.ini; exit 1; }
acme.fortune 1.0.0 (app): Fortune
  A saying for the day, in a font of its own.
  built for ABI 10
  2 file(s), 20 KB
  not signed
rm -f pkg.ini

21.2. The Package File

A .DPK file is a ZIP archive, read from front to back. Its first entry is PACKAGE.INI, the manifest; the second, when the package is signed, is PACKAGE.SIG; then come the files, named relative to the DVX folder with / between the parts. Fortune’s manifest (each file’s SHA-256, 64 hexadecimal digits, is shortened here):

[package]
format = 1
id = acme.fortune
name = Fortune
version = 1.0.0
kind = app
summary = A saying for the day, in a font of its own.
licence = MIT
abi = 10

[files]
apps/acme/fortune/fortune.app = 13845 f0608aadb1740de1...30d5ebcccf8
apps/acme/fortune/fortune.hlp = 6525 843fcbf18fcb82af...913d2ab541b9

[package] describes the package; id, name, version, kind, and format are required, and each text is at most 127 characters:

Key Meaning

format

The manifest’s format, 1. A DVX refuses a package of a later format, which needs a newer DVX.

id

vendor.name, each part one to eight of a-z, 0-9, and _.

name

What Software shows.

version

major.minor.patch (Section 21.7).

kind

What the package installs, and so the folders it may put files in (Section 21.9).

summary, publisher, author, licence, homepage

Shown in Software’s details.

dvx

The oldest DVX the package runs on; any when it is missing.

abi

For programs, libraries, widgets, and screen savers: the binary interface version (DVX_ABI_VERSION) they were built for. dvxpkg build writes its own, which is the SDK’s, so it matches the modules built with that SDK.

[depends] lists the packages this one needs (Section 21.3), and [files] every file, with its size and SHA-256. The build writes [files] and checks that every file is listed once and every listed file is in the package; DVX checks each file’s size and SHA-256 against it as it installs. So the manifest describes all of the package, and one signature of the manifest’s bytes covers everything in it (Section 21.4).

sdk.mk writes the manifest from its package settings:

Setting Key Default

PKG_TITLE

name

The module’s name resource, or NAME as the Makefile writes it (fortune) when it has none.

PKG_VERSION

version

1.0.0.

PKG_SUMMARY

summary

The module’s description resource; the key is left out when it has none.

PKG_PUBLISHER, PKG_AUTHOR, PKG_LICENCE, PKG_HOMEPAGE

publisher, author, licence, homepage

None: the key is left out.

PKG_DVX

dvx

None: any DVX. The oldest DVX the package runs on, major.minor.patch.

PKG_NEEDS

[depends]

None (Section 21.3).

PKG_KEY

(the signature)

None: the package is not signed (Section 21.4).

Settings that belong to the project go in its Makefile, before the include, as Fortune’s do; the command line overrides them, which suits VENDOR and PKG_KEY:

SDK_DIR ?= ../../../../bin/sdk
KIND     = app
NAME     = fortune

# The add-on package make package makes
PKG_TITLE   = Fortune
PKG_VERSION = 1.0.0
PKG_SUMMARY = A saying for the day, in a font of its own.
PKG_LICENCE = MIT

include $(SDK_DIR)/sdk.mk

The package’s title and summary come from the program’s name and description resources (Section 20.5.1), which Program Manager shows, unless PKG_TITLE and PKG_SUMMARY say otherwise, so the two are alike unless you make them differ. (PKG_LICENCE and the licence key are spelled the British way, as the code spells them.) A setting may hold blanks and apostrophes: PKG_PUBLISHER="Pat’s Games" is fine.

The SDK’s bin/dvxpkg reads packages too. dvxpkg info NAME.dpk shows what a package says about itself, as make package does at its end; dvxpkg check NAME.dpk checks the package as DVX does before installing it (the manifest, the kind’s folders, every file against the manifest) and prints the manifest when it passes; dvxpkg describe NAME.dpk makes the same check and then prints what the package is as DVX read it, a field=value line each (what the package server goes by: it reads no manifest itself). A manifest line may hold no control character but a tab: a line with a stray carriage return or a NUL in it is refused. On DVX, SYSTEM\DVXPKG.EXE takes the same commands. The package library behind all of them, and its file format, are in the reference (“Package Library” in the DVX C Library Reference).

21.3. Dependencies

A package that cannot work without another says so with PKG_NEEDS: a list of package IDs, each with the oldest version that will do.

$ make package PKG_NEEDS="acme.cards=1.0 acme.dice=2.1"

A version may leave out its last parts: 1.0 is 1.0.0. Software installs a package only when everything it needs is installed in a version that will do, or is installed with it: from a file, the packages in the same folder as the one chosen; from the package server, the server’s. So hand out the packages yours needs beside it, in one folder.

PKG_NEEDS and a .dep file are different things. A .dep file tells DVX’s loader which modules to load before a library or widget, by their file names (Chapter 18); PKG_NEEDS tells Software which packages must be installed, by their package IDs. A library built on another library of yours has both.

21.3.1. DVX’s Optional Parts

DVX is packages too. kpunch.dvx is DVX itself (the loader, the shell, the core libraries and widgets, the everyday programs) and is always there. The optional parts that Setup offers, and Software adds or removes, are bundles: packages with no files of their own, each needing its members, one package for each module. A module of yours that calls a part’s library names the library’s package:

Part Bundle Members

Networking

kpunch.net

kpunch.dvxnet (sockets), kpunch.http, kpunch.pkgnet

Databases

kpunch.data

kpunch.dvxsql, kpunch.datactrl, kpunch.dbgrid

Communications

kpunch.comm

kpunch.conn, kpunch.seclink, kpunch.xfer, kpunch.ansiterm, kpunch.terminal

Media

kpunch.media

kpunch.player, kpunch.recorder

DVX BASIC

kpunch.basic

kpunch.dvxbasic, kpunch.basdev

Developer Tools

kpunch.devtools

kpunch.iconed, kpunch.resedit, kpunch.helpedit, kpunch.pkgbuild, kpunch.widshow

Demos

kpunch.demos

kpunch.dvxdemo, kpunch.basdemo

The libraries not listed here (sound, music, printing, JSON, the serial driver, the file operations, and the rest) are part of kpunch.dvx. A package names the packages of the libraries its own code calls. Every one of DVX’s packages has DVX’s version, so a program that calls the HTTP library and the socket library says:

PKG_NEEDS = kpunch.http=1.0.0 kpunch.dvxnet=1.0.0

with the version of the DVX release whose SDK built it (DVX_VERSION_TEXT in dvxTypes.h). Where Networking is not installed, Software then says what is missing instead of installing a program that cannot start, or, from the package server, fetches it too.

A module that can do without a part does not call the part’s functions directly, since a direct call makes the module impossible to load without the library (Chapter 3). It asks dvxLibraryLoaded("dvxsql"), which loads the library if it is installed, and finds the functions by name with dlsym when it is there (Chapter 18); such a module needs no PKG_NEEDS for the part.

21.4. Signing

A signature tells the people who install a package that it came from you and has not changed since. Make a pair of keys once, on the build machine:

$ dvxpkg keygen "Acme Software" acme
secret key: acme.SEC (keep it private)
public key: acme.KEY (id a0147ddc7e5b4f28)

Both are small INI files with the key’s name and ID: acme.KEY holds the public key, acme.SEC the secret one. The keys are Ed25519, and a key’s ID is the first eight bytes of its public key’s SHA-256, so a signature names the key that made it.

PKG_KEY signs the package as it is made: dvxpkg signs the manifest’s bytes and puts the signature in the package, as PACKAGE.SIG.

$ make package VENDOR=acme PKG_KEY=../acme.SEC
...
acme.fortune 1.0.0 (app): Fortune
  A saying for the day, in a font of its own.
  built for ABI 10
  2 file(s), 20 KB
  signed by key a0147ddc7e5b4f28

dvxpkg sign NAME.dpk acme.SEC signs a package made earlier, and with -d writes the signature beside it as NAME.SIG instead. dvxpkg verify checks every file against the manifest and, given public keys, which of them signed it:

$ dvxpkg verify fortune.dpk acme.KEY
fortune.dpk: every file matches its manifest
signed by Acme Software (key a0147ddc7e5b4f28)

Give acme.KEY to the people who install your packages. Keep acme.SEC private, and keep a copy of it somewhere safe: anyone who has it can sign packages as you, and without it you cannot sign the updates of the packages you signed with it (Section 21.7).

21.5. Trust

DVX trusts two sets of keys: those in SYSTEM\KEYS, which are DVX’s own, and those in the KEYS folder of the user folder, the publishers the user chose to trust. Software’s File › Trust a Publisher’s Key…​ copies a .KEY file there. Then DVX’s rules are:

  • A package signed by a key DVX trusts is installed, and Software names the key.

  • A package that is not signed, or is signed by a key DVX does not trust, is marked so; Software installs it only when the user goes ahead anyway, and DVXPKG install only with -y.

  • A package whose ID’s vendor is kpunch must be signed by DVX’s own key.

  • When the installed version of a package was signed by a key DVX trusted, a new version must be signed by the same key, or by DVX’s; nobody else can replace it.

  • A package from the package server must be signed by DVX’s own key, whoever published it (Section 21.8). A package from the server that is not signed by it is never installed.

Software records how each package was signed when it installed it, and its Package › Details…​ shows it.

21.6. Installing

The user installs a package with Software: File › Install from File…​, then the .DPK file (opening a .DPK file in File Manager does the same). Before anything is installed, Software shows the plan: each package that will go in (the one chosen and what it needs from beside it), whether each is new, an upgrade, or the same version again (which repairs it), who signed each, and the disk space it takes. Then:

  1. Each package’s files are unpacked under scratch names beside where they go, each checked against the manifest.

  2. When all of them are in, they are swapped into place; the files they replace are kept until every swap is done, and put back if one fails.

  3. The files of an older version that the new one does not have are removed.

  4. The package’s record is written: SYSTEM\PACKAGES\<vendor>\<name>.INI, its manifest as installed, how it was signed, and whether the user chose it or it came with another.

Software refuses a package, saying why, when it needs a package that is neither installed nor beside it, needs a newer DVX, was built for another binary interface, is older than the version installed, would put a file where another package has one, or breaks the signing rules. A program is in Program Manager’s Installed Programs as soon as it is installed. A library or widget works from the next time DVX starts, since DVX loads them only as it starts.

Package › Remove…​ removes a package: the packages that need it go too, or nothing does, and the packages that came only with it are offered for removal. The files are deleted, and the folders that leaves empty. A file changed since it was installed is left in place, and Software asks whether to delete it as well. When an add-on keeps DVX from starting, DVX /SAFE (or Shift held as DVX starts) starts it without any add-on libraries or widgets, so Software can remove it; SYSTEM\DVXPKG.EXE remove VENDOR.NAME does it at the DOS prompt.

At the DOS prompt, in the DVX folder, DVXPKG installs, removes, and lists packages too:

C:\DVX>SYSTEM\DVXPKG install FORTUNE.DPK
C:\DVX>SYSTEM\DVXPKG list
C:\DVX>SYSTEM\DVXPKG remove acme.fortune

install takes -y for a package no trusted key signed, remove takes -f to remove the packages that need it and the files changed since they were installed, and each takes -r DIR for a DVX folder other than the current one.

make install is for development: it copies files, and writes no record, so Software does not list the module and cannot remove it. Installing the .dpk later takes the files over. Try a package as its users will get it, through Software, before you hand it out.

21.7. Versions and Updates

A version is major.minor.patch, each a number from 0 to 65535, compared part by part. Raise PKG_VERSION for every version you hand out. Software compares the version of a package with the version installed: a later one is an upgrade, the same one a reinstall, which repairs the installed files, and an earlier one is refused (“A newer version of Fortune (1.1.0) is installed.”). An upgrade removes what the old version had and the new one does not, leaving any of those files the user changed (Software asks about them).

Who may replace a package is fixed by how it was installed (Section 21.5). A version installed with your signature, by a user who trusts your key, can be replaced only by one signed with the same key, or by DVX’s. A package installed from the package server was signed by DVX’s key, so its updates come from the server as well.

A program, library, or widget runs only on the DVX whose binary interface it was built for (Chapter 3). When a DVX release changes DVX_ABI_VERSION, Software refuses the packages built for the old one (“was made for a different version of DVX”), and when DVX itself is updated through Software, it names the add-ons the new version would leave unable to load before it installs anything. Rebuild with the new release’s SDK, raise the version, and hand it out again.

21.8. Publishing on the Package Server

Software’s Available and Updates pages list what the package server offers: DVX’s own server, or one the user chose in File › Package Server…​. Publishing a package there makes it available to every DVX that reaches the server, and offers each new version to everyone who has an older one.

You need an account on the server. In DVX, Software makes it: in File › Package Server…​, type your email address and the password you want, choose Create Account…​, and type the password again when asked; the server mails the address a code, such as ABCD-EFGH, which you type into the window Software shows. From the build machine, the same two requests make it, the second with the code from the mail:

$ curl -H "Content-Type: application/json" \
    -d '{"email":"you@example.com","password":"PASSWORD"}' \
    http://SERVER/v1/account/register
$ curl -H "Content-Type: application/json" \
    -d '{"email":"you@example.com","code":"ABCD-EFGH"}' \
    http://SERVER/v1/account/verify

A forgotten password is reset the same way: Forgot Password…​ in the same window, or POST /v1/account/recover with the email, then POST /v1/account/reset with the email, the code from the mail, and the new password. A program of your own does all four with the package server library (pkgNetRegisterStart, pkgNetVerifyStart, pkgNetRecoverStart, and pkgNetResetStart; PkgNetRegister and the rest in BASIC).

Then publish from DVX or from the build machine:

  • In DVX, give the account’s email and password in Software’s File › Package Server…​ (making the account there saves them), and choose File › Publish a Package…​ and the .DPK file. Software’s Published page lists every version you have sent and its review: waiting, published, turned down (with the reviewer’s note saying why), or withdrawn.

  • From the build machine, sign in for a session token, then send the package with it. GET /v1/mine with the same token lists your versions and their reviews:

$ curl -H "Content-Type: application/json" \
    -d '{"email":"you@example.com","password":"PASSWORD"}' \
    http://SERVER/v1/account/login
$ curl -H "Authorization: Bearer TOKEN" \
    -H "Content-Type: application/octet-stream" \
    --data-binary @fortune.dpk http://SERVER/v1/upload

The first answers with the session’s token; the second with the package’s id, its version, and the state pending.

The server checks every upload as DVX checks a package before installing it (with the same dvxpkg check), and holds it for review. Its operator reviews it and signs the approved package with DVX’s repository key, on a computer of their own: the server never holds that key. Then the package is in the catalog, at its newest approved version, and every DVX that has an older version is offered the update. The server’s rules:

  • An ID belongs to the account that first uploaded it; later versions must come from the same account. IDs of the vendor kpunch are DVX’s own, and only the operator uploads them.

  • A version is uploaded once: send a fix as a new version.

  • DVX installs from the server only what DVX’s repository key signed, whatever else the package carries. Your own signature is not needed there, but the catalog shows which key signed each version, so people can tell publishers apart; and a signed package can also be handed out as a file.

  • DVX reaches the server over plain HTTP: nothing is trusted for the way it arrived, only for its signature, and a package that does not match it is refused.

  • What your account sends (its email, password, and session) is sealed for the server, which must show a sealing key that DVX’s repository key signed; Software does not sign in to a server that cannot. The package itself is public and goes unsealed, with its SHA-256 inside what is sealed. The server takes an account’s requests no other way.

  • A withdrawn package is no longer listed or downloaded; the copies installed keep working and are no longer offered updates.

dvxpkg check NAME.dpk before an upload saves a round trip: it is the check the server makes. The server’s interface is described in server/README.md in the DVX source tree, and the client library that Software uses in the reference (“Package Server Library” in the DVX C Library Reference).

21.9. Other Kinds of Package

sdk.mk makes packages of programs, widgets, and libraries. Every other kind is made with dvxpkg build from a template and a folder laid out like the DVX folder, or on DVX itself with Package Builder (in Developer Tools). Each kind may put files only in its own folders:

Kind Folder Holds

app

APPS\<vendor>\<name>

A program, its help, its DATA.

library, widget

LIBS\<vendor>\<name>, WIDGETS\<vendor>\<name>

A library or a widget.

help

APPS\<vendor>\<name>, or beside a library or widget of its name

Help files.

font

SHARED\FONTS\<vendor>

Fonts for every program (Section 20.6.4).

bank

SHARED\BANKS\<vendor>

MIDI instrument banks.

theme, wallpaper

SHARED\THEMES\<vendor>, SHARED\WPAPER\<vendor>

Color themes and desktop pictures.

sound

SHARED\SOUNDS\<vendor>

Sounds.

saver

SHARED\SAVERS\<vendor>

A screen saver: a program, so its package has an abi. sdk.mk makes one for a program with SAVER = 1 (Section A.1).

bundle

(none)

No files: the packages it needs are its contents.

Every kind but bundle may also put files in SYSTEM, such as a program for the DOS prompt that goes with it, but not in SYSTEM\KEYS or SYSTEM\PACKAGES, which are DVX’s; and no package may put a file where another package has one. Nothing a package installs goes in the user folder.

The template is a manifest without its format and [files], which the build writes, and without abi for a code kind, which the build adds. A package of Fortune’s font, for every program:

$ mkdir -p stage/SHARED/FONTS/ACME
$ cp COZETTE.DFN stage/SHARED/FONTS/ACME/
$ cat font.ini
[package]
id = acme.cozette
name = Cozette
version = 1.0.0
kind = font
summary = A small bitmap font.
$ dvxpkg build font.ini stage cozette.dpk acme.SEC
acme.cozette 1.0.0 (font): Cozette
  A small bitmap font.
  1 file(s), 5 KB
  signed by key a0147ddc7e5b4f28

dvxpkg build TEMPLATE FOLDER OUT.DPK [KEY.SEC] puts every file under the folder into the package, named from the folder, and refuses one outside the kind’s folders. The same way adds a file to a program’s package that sdk.mk would not: run make package, put the file into pkg/ where it goes (pkg/SYSTEM/ACMETOOL.EXE), and run dvxpkg build on pkg/ with a template of your own. A screen saver is a program, built as one, and packaged this way with the kind saver, its .app in SHARED\SAVERS\<vendor>.

21.10. Before You Publish

  • VENDOR is your own, the same for everything you publish, and PKG_TITLE, PKG_SUMMARY, and PKG_PUBLISHER are set.

  • PKG_VERSION is higher than any version you handed out before.

  • The module was built with the SDK of the DVX release it is for.

  • PKG_NEEDS lists every package it needs, DVX’s optional parts included.

  • The program’s name, description, and icon32 resources are right, and its help is complete; a widget’s or library’s help compiles without pictures and links only to its own topics.

  • It is signed with PKG_KEY, and the .SEC file is backed up.

  • dvxpkg check passes, and the package installs with Software on a DVX that has not seen it, runs, and removes cleanly.

Chapter 22. Debugging and Performance

The SDK has no debugger. A DVX program runs inside DVX on a DOS machine, real or emulated, and you debug it from the outside: with the lines it writes to the log, with the crash report DVX writes when it faults, with what DVX says when it refuses a module, and with the cross compiler’s own tools on the build machine. This chapter shows each of them on a program that fails on purpose, then covers hung programs, memory leaks, testing on emulators and real PCs, making a program fast enough for a 486, and the rules that keep modules compatible with DVX. (A DVX BASIC program has a debugger in the DVX BASIC IDE; see the DVX BASIC Programming Guide.)

22.1. The Bug Hunt Program

Bug Hunt is a window with a line of status and five buttons, each of which makes one kind of trouble:

Button What it does

Memory in Use

Shows and logs how many bytes the program has allocated.

Leak a Block

Allocates 10 KB and loses the pointer.

Time Log Lines

Times 20 calls of dvxLog and shows how long they took.

Divide by Zero

Divides by zero. The processor faults, and DVX ends the program.

Hang

Stays in its callback, running frames itself, for a second longer than Task Manager waits before it calls a program Not responding.

The Bug Hunt window with Memory in Use, Leak a Block, Time Log Lines, Divide by Zero, and Hang buttons
Figure 31. Bug Hunt, a program with a bug behind each button
#include "dvxApp.h"
#include "dvxMem.h"
#include "dvxPlat.h"
#include "dvxWgt.h"
#include "shellApp.h"
#include "button/button.h"
#include "label/label.h"

#include <inttypes.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>

#define BUGHUNT_TITLE      "Bug Hunt"
#define BUGHUNT_WIN_W      240
#define BUGHUNT_WIN_H      220
#define BUGHUNT_SPACING    6
#define BUGHUNT_TEXT_MAX   64
#define BUGHUNT_LEAK_BYTES 10240
#define BUGHUNT_LOG_LINES  20
#define BUGHUNT_DIVIDEND   100
#define BUGHUNT_US_PER_MS  1000

// The hang lasts a second longer than DVX waits before it calls a
// program Not responding.
#define BUGHUNT_HANG_EXTRA_MS 1000
#define BUGHUNT_HANG_US       ((DVX_HUNG_APP_MS + BUGHUNT_HANG_EXTRA_MS) * BUGHUNT_US_PER_MS)

// One button of the window: its label and its callback.
typedef struct {
    const char *label;
    void      (*onClick)(WidgetT *w);
} BugButtonT;

// ============================================================
// Prototypes
// ============================================================

static void closeWindow(void);
static void onClose(WindowT *win);
static void onDivideClick(WidgetT *w);
static void onHangClick(WidgetT *w);
static void onLeakClick(WidgetT *w);
static void onMemoryClick(WidgetT *w);
static void onTimeClick(WidgetT *w);
static void showStatus(const char *text);
static void showUsage(void);
int32_t     appMain(DxeAppContextT *ctx);

static DxeAppContextT  *sCtx     = NULL;
static WindowT         *sWin     = NULL;
static WidgetT         *sStatus  = NULL;
static bool             sHanging = false;
static volatile int32_t sDivisor = 0;   // volatile: divided by at run time, never folded away

static const BugButtonT sButtons[] = {
    { "&Memory in Use",  onMemoryClick },
    { "&Leak a Block",   onLeakClick   },
    { "&Time Log Lines", onTimeClick   },
    { "&Divide by Zero", onDivideClick },
    { "&Hang",           onHangClick   }
};

// ============================================================
// App descriptor
// ============================================================

SHELL_APP_DESCRIPTOR(
    .name          = BUGHUNT_TITLE,
    .hasMainLoop   = false,
    .multiInstance = false,
    .stackSize     = SHELL_STACK_DEFAULT,
    .priority      = TS_PRIORITY_NORMAL
);

It is a callback-only program built like hello (Chapter 2): a table gives each button its label and its callback, and appMain makes them in a loop. sDivisor is volatile so that the compiler, which could otherwise see that it is never anything but 0, has to load it and divide at run time: a division by a known zero is undefined behavior, which the compiler may do anything with. The sections below show the buttons' code as they explain each kind of trouble. Build it with CFLAGS=-g (Section 22.3.2), install it, and keep DVX.LOG open on the build machine if your DVX folder is visible there.

22.2. The Log

dvxLog(fmt, ...) (dvxPlat.h) formats like printf and appends the result, with a newline, to DVX.LOG in the user folder (Section 2.7.1). The line gets no time stamp and no name, so begin each with your program’s name, as the examples do (bughunt: ...), to find your lines among DVX’s. A program has nowhere else to write: standard output and standard error go to the DOS console, which DVX’s graphics screen hides (Section B.3.2).

DVX.LOG is in the user folder: USER in the DVX folder, or the folder the DVXUSER environment variable names, or a folder in TEMP when DVX’s disk cannot be written; one of the first lines of the log, Loader: user folder path or a line saying why it moved, names it. Each start of DVX empties the log, except the start that comes back after a DOS program, which carries it on; so copy the log somewhere else before you start DVX again after a problem. The log is kept under 512 KB (PLATFORM_LOG_FILE_MAX): past that, only its newest lines are kept. When nothing can be written at all, DVX keeps the last 16 KB of the log in memory instead.

dvxLog opens the file, appends the line, and closes the file every time. That is what makes it useful after a crash, since every line written before the crash is in the file, and it is also what makes it slow: each line is several DOS calls. Bug Hunt’s Time Log Lines measures it:

// Times BUGHUNT_LOG_LINES calls of dvxLog, which opens, appends to, and
// closes DVX.LOG on every call, and logs the result once.
static void onTimeClick(WidgetT *w) {
    char     text[BUGHUNT_TEXT_MAX];
    uint64_t start = platformMicros();

    (void)w;

    for (int32_t i = 0; i < BUGHUNT_LOG_LINES; i++) {
        dvxLog("bughunt: timing line %" PRId32, i);
    }

    uint32_t elapsed = (uint32_t)(platformMicros() - start);

    snprintf(text, sizeof(text), "%" PRId32 " log lines: %" PRIu32 " us", (int32_t)BUGHUNT_LOG_LINES, elapsed);
    dvxLog("bughunt: %s", text);
    showStatus(text);
}

Run it on the machine you are writing for and see what a line costs there. Log events, not loops: a line when something happens, a summary at the end of a long job, never a line per pass of a loop that runs many times a second. Never log from a timer callback that runs in the timer interrupt (Section 11.1): it may not call the C library at all.

22.2.1. What DVX Writes There

DVX’s own lines tell you what happened to your module. The ones that matter to a program’s author:

Line Means

Loading: path

A library or widget was loaded, at the start or when first needed.

FAILED: path: reason (indented)

A library or widget was not loaded (Section 22.4).

Loader: n modules loaded; m libraries load when first used

The start is over.

DVX Shell ready.

The desktop is up.

Module: path at 0xaddress (n bytes)

A module (a library, a widget, or a program) was loaded at that address. A crash report places a fault by these lines.

Shell: loaded 'name' (id=n, mainLoop=no, entry=0xaddress, desc=0xaddress)

A program started: its ID, its kind (mainLoop=yes for a main-loop program), and where its appMain and appDescriptor are in memory this time. The line is written before appMain runs.

Shell: 'name' appMain returned n, unloading

appMain returned something other than 0.

DXE load failed: Failed to load file: and the reason on the next line

A program was refused (Section 22.4).

DXE ABI mismatch: path was built for DVX ABI n, this system is ABI m

A program built with another release’s SDK was refused.

Widget: API 'name' refused: …​

wgtGetApi refused a widget’s table (Section 22.9).

Shell: reaped app 'name'

A program ended normally.

Shell: 'name' called exit (status n); ending it

The program called exit or abort (status 3).

Shell: force-killed app 'name'

A program was ended by force: End Task, a fault, or exit.

Memory: program n ended with m bytes still allocated to it; …​

The program ended without freeing everything it allocated (Section 22.6.1).

Shell: kill of 'name' deferred until its code unwinds

End Task was asked for while the program’s code was still running in a callback (Section 22.5).

Shell: 'name' was ended in code that does not return; discarding it

That code was running frames itself, and was abandoned at its next frame.

Shell: 'name' has no window left and none had an onClose; ending it

A main-loop program whose windows had no onClose lost its last window.

=== CRASH === and the lines after it

A fault (Section 22.3).

22.3. Crash Reports

DVX catches three of the processor’s faults: a reference to memory the program may not use (SIGSEGV: a page fault, a general protection fault, or a stack fault), a division by zero (SIGFPE), and an instruction the processor does not have (SIGILL). When one happens in a program’s code, DVX writes a crash report to the log, ends the program that was running, and tells the user in a box titled Application Error (Section 3.10). Bug Hunt’s Divide by Zero makes one:

// A division by zero: the processor faults on the division, DVX writes a
// crash report to DVX.LOG and ends the program.  The log line after the
// division never runs.
static void onDivideClick(WidgetT *w) {
    (void)w;

    int32_t quotient = BUGHUNT_DIVIDEND / sDivisor;

    dvxLog("bughunt: quotient %" PRId32, quotient);
}

22.3.1. Reading a Crash Report

A report reads like this; the addresses are different on every run, and the lines that loaded and started the program come earlier in the log:

Module: ...\bughunt.app at 0x00351c40 (... bytes)
Shell: loaded 'Bug Hunt' (id=2, mainLoop=no, entry=0x00351fb0, desc=0x00352190)
...
=== CRASH ===
Signal: 289 (SIGFPE (floating point exception))
EIP: 0x00351c73  CS: 0x...
EIP is in ...\bughunt.app at offset 0x00000033
EAX: 0x00000064  EBX: 0x...  ECX: 0x00000000  EDX: 0x00000000
ESI: 0x...  EDI: 0x...  EBP: 0x...  ESP: 0x...
DS: 0x...  ES: 0x...  FS: 0x...  GS: 0x...  SS: 0x...
EFLAGS: 0x...
Current app ID: 2
App name: Bug Hunt
App path: ...
Has main loop: no
Task ID: 0
Recovering from crash, killing app 2
  • Signal is DJGPP’s number for the signal: 291 for SIGSEGV, 289 for SIGFPE, and 290 for SIGILL. A SIGSEGV is named for the processor’s exception: SIGSEGV (page fault), no memory at the address (a NULL pointer, say); SIGSEGV (general protection fault), an address outside DVX’s memory (a stray pointer far out of range); or SIGSEGV (stack fault). The report calls every SIGFPE a floating point exception, but an integer division by zero raises it too, as here.

  • EIP is the address of the instruction that faulted. The other registers are as they were at that instruction: here EAX holds the dividend, 100, and ECX the divisor, 0.

  • EIP is in names the module the instruction is in, its file as the Module: line gave it, and the offset of the instruction from the start of the module: where to look (Section 22.3.2). An address in no module is in DVX.EXE itself: EIP is in no module (DVX.EXE itself, or memory no module holds).

  • The lines after EFLAGS name the program DVX ended: its ID (the id= of its Shell: loaded line), its name, its file, its kind, and its task (0 for the shell’s own task, where callbacks run). When no program was running, the report says Current app ID: 0 and Crashed in shell (task 0) instead; once the desktop is up, DVX then goes on without ending anything.

The report has no stack trace and no dump of memory. What it has is enough to find the instruction.

22.3.2. Finding the Faulting Line

A module is loaded at a different address each time, so the EIP means nothing by itself. Its offset in the module does, and the EIP is in line gives it: a module is loaded as one block, laid out as dxe3gen linked it, its code first. A program of one source file has that file’s code first, laid out as in its object file, so the offset is an address in the object file; a program of several is linked first (Section 22.3.3).

The cross compiler’s tools are in the bin folder of the DJGPP installation ($DJGPP_PREFIX/bin): put it on your PATH, or name them in full. Build with debugging information first. -g puts it in the object files and changes nothing else: dxe3gen leaves it out of the module, which comes out byte for byte the same. So build every version you run or give out with it, and keep its object files (make clean first when the objects were built without it, since make does not notice a change of flags):

$ make clean
$ make CFLAGS=-g

For the report above, the offset is 0x33. addr2line turns it into a function and a line of the source, and objdump -S shows the instructions there with the source lines between them:

$ i586-pc-msdosdjgpp-addr2line -f -s -p -e bughunt.o 0x33
onDivideClick at bughunt.c:135
$ i586-pc-msdosdjgpp-objdump -d -S --start-address=0x20 --stop-address=0x40 bughunt.o
...
    int32_t quotient = BUGHUNT_DIVIDEND / sDivisor;
  2b:	8b 0d 08 00 00 00    	mov    0x8,%ecx
  31:	31 d2                	xor    %edx,%edx
  33:	f7 f9                	idiv   %ecx
...

(These are the numbers of the book’s build of bughunt; yours are the same when you build the same source with the same SDK.) The instruction at 0x33 divides by ECX, and the report says ECX was 0. Without -g, i586-pc-msdosdjgpp-nm -n bughunt.o still lists the functions in address order, and the function the offset falls in is the last one that starts at or before it; objdump -d then shows the instructions. Do not expect the functions in the order of the source: the compiler arranges them as it likes, and folds small static functions into their callers.

22.3.3. A Program of Several Files

With several source files, the module holds each object’s code one after another, in the order the build gave them to dxe3gen (the order of the .o files on the dxeGen.sh line make prints), and then the libraries of LIBS. Link them the way dxe3gen does, with DJGPP’s own dxe.ld script, in the same order, and use the result as above:

$ i586-pc-msdosdjgpp-ld -r -T $DJGPP_PREFIX/i586-pc-msdosdjgpp/lib/dxe.ld \
    -o whole.lnk main.o tools.o view.o
$ i586-pc-msdosdjgpp-addr2line -f -s -p -e whole.lnk 0x...

whole.lnk has the same layout as the module, and with -g the debugging information of all three files. A library or a widget is found the same way.

22.3.4. Faults Outside Your Code

When the EIP is in line names another module, a widget’s or a library’s, or no module (DVX.EXE itself), the processor was in code that is not yours, called by your program. The report names your program all the same, since it was the running program, and DVX ends it. Such a fault nearly always comes from what your program passed: a widget or a window that was already destroyed, NULL where a pointer was needed, a buffer shorter than the size given with it, a string without its terminating zero. The lines your program logged before the crash say how far it got. Log before and after the calls you suspect, and run it again.

22.3.5. Errors That Do Not Fault

Most memory errors are not faults. DVX keeps the processor’s limit check on its memory (it uses no DJGPP near pointers, and reaches video memory only through its platform layer), so a pointer that strays outside DVX’s memory altogether, into DOS’s memory, the interrupt vectors, or the screen, faults with a general protection fault, and the report places it. But every program shares DVX’s memory, and a stray pointer that lands inside it does not fault: a write through it changes whatever is there, another of your variables, the C library’s records of the heap, a widget of another program, DVX itself. The damage shows later, often as a fault in code that did nothing wrong, and the report then names whatever program was running at the time. When faults appear in unrelated places, suspect a write past the end of a buffer, a use of memory after free, and a task’s stack that is too small (a task that overflows its stack writes below it without a fault; Section 11.4.1).

assert ends only your program: a failed assertion is logged (Assertion failed: test, file file, line n, function name), and the program ends as abort ends it, its atexit functions not run. A check of your own that logs and calls abort does the same with a message of your choosing, and stays in a build made with NDEBUG:

// A failed check is logged, and abort() ends this program (not DVX).
static void check(bool ok, const char *what, int32_t line) {
    if (!ok) {
        dvxLog("myprog: check failed: %s (line %" PRId32 ")", what, line);
        abort();
    }
}

#define MYPROG_CHECK(cond) check((cond), #cond, __LINE__)

22.4. Refused Modules

Because a module’s outside references are resolved only when DVX loads it (Section 3.2), a build that succeeds can still make a module DVX will not load. DVX says so in a box and in the log. For a program, as it starts:

Message Cause

“Failed to load file:” and “unresolved symbol: name”

The module calls a function, or uses a variable, that nothing has: not DVX.EXE, not a loaded module, not a library on the disk. The name is the first one missing, as DJGPP spells it, with a leading underscore (_strndup). It is misspelled, it is a C library function DVX.EXE does not give modules (Section B.2), it belongs to a library that is not installed, or it belongs to a library DVX tried and failed to load: look for a FAILED line earlier in the log. i586-pc-msdosdjgpp-nm -u on the objects lists every name a module needs, to check before you copy it anywhere.

“file: missing appDescriptor”

No SHELL_APP_DESCRIPTOR, or it was made static.

“file: missing appMain”

No appMain, or it was made static. The log has it too (DXE symbol error:).

“This program was built for a different version of DVX and cannot run.”

It was built with the SDK of another DVX release (Section 22.9). The log has both numbers.

“Failed to create task for application.”

A main-loop program whose task could not be made: its priority is outside 0 to 10, or there is not enough memory for its stack. The log says which: Shell: cannot make a task for 'name' (priority n, stack n bytes): error n.

“file is already running.”

The program runs once (multiInstance is false), has no onNewArgs, and is running.

A library or widget of yours (an add-on: any module outside DVX’s own KPUNCH folders) that DVX cannot load at the start is left out, with an indented line FAILED: path: reason in the log and, once the desktop is up, a box titled Add-ons that says “path was not loaded: reason.” (A module of DVX’s own that cannot be loaded stops DVX instead, with a message in text mode.) The reasons:

Reason Cause

“its file is damaged, or it needs something this DVX does not have”

The DXE3 loader refused it; the line before the FAILED line, dlopen: reason, says why, usually “unresolved symbol: name”.

“it was made for a different version of DVX”

Its ABI stamp differs from DVX’s, or it has none. The log says which: ABI: path was built for DVX ABI n, this system is ABI m, or ABI: path has no ABI stamp (symbol); …​, which is also what a stamp that does not match the file’s name gives (Section 22.9).

“it needs name, which is not installed”

Its .dep file names a module DVX does not have.

“it needs path, which was not loaded”

A module its .dep file names failed in turn.

“it needs files that in turn need it or each other, so none of them can be loaded”

The .dep files make a circle.

“path has the same name”

Another module has the same base name: one of DVX’s own, or an add-on found first. Rename yours (and its stamp).

DVX /SAFE leaves every add-on out, for when one keeps DVX from starting (Section 1.6). A library that is not needed at the start is loaded when something first uses one of its names; if it fails then, the log gets its FAILED line, DVX does not try it again until it restarts, and whatever needed it is refused with “unresolved symbol”. A widget that loads but has no wgtRegister is logged (No _wgtRegister in and its name), and a widget’s table that wgtGetApi refuses is logged as Widget: API 'name' refused: …​; the program that asked gets NULL from the widget’s accessor (Section 5.2).

22.5. Hung Programs

A program that stops responding is one of three kinds, and what you can do about it depends on which:

What the program’s code does What you see What ends it

Never returns and never yields: an endless loop in a callback, a main loop without tsYield, or a call that waits without yielding (a DOS call that waits for a device)

All of DVX stops: nothing paints, the mouse pointer freezes (DVX draws it), and no key does anything, Ctrl+Esc included.

Only its own return, or restarting the computer.

Yields, but never finishes: a loop that yields while it waits for something that never happens

DVX runs. Task Manager shows the program as Running.

End Task, which ends its task at its tsYield at once.

Runs frames inside a callback: calls dvxUpdate in a loop

DVX runs, though the shell’s main loop waits under the callback: programs that end are not cleaned up, and Exit DVX waits. After DVX_HUNG_APP_MS (5 seconds) Task Manager shows the program as Not responding.

The callback’s return, or End Task, which hides and destroys the program’s windows at once and, at the callback’s next frame, abandons the callback, as a fault would, and ends the program.

Not responding means only the third kind: DVX counts the time a program has been in one of its window callbacks, and a program waiting in a dialog box of its own is never counted as hung. Bug Hunt’s Hang is that kind:

// Stays in this callback for BUGHUNT_HANG_US, running frames itself so
// the screen stays alive.  After DVX_HUNG_APP_MS in one callback, Task
// Manager shows the program as Not responding.  A real program must not
// do this: the shell's own main loop waits under the callback.
static void onHangClick(WidgetT *w) {
    AppContextT *ac    = sCtx->shellCtx;
    uint64_t     start = platformMicros();

    (void)w;

    if (sHanging) {
        return;
    }

    sHanging = true;
    showStatus("Hanging...");
    dvxLog("bughunt: hang started");

    while (platformMicros() - start < BUGHUNT_HANG_US) {
        dvxUpdate(ac);
    }

    sHanging = false;
    dvxLog("bughunt: hang ended");
    showStatus("The hang is over.");
}

Click Hang, then Ctrl+Esc: the screen and the mouse go on working, and about five seconds after the click Task Manager’s Status column says Not responding (it checks once a second). Click End Task while it does: the window vanishes at once, the log shows Shell: kill of 'Bug Hunt' deferred until its code unwinds and then Shell: 'Bug Hunt' was ended in code that does not return; discarding it, and the program ends at the loop’s next frame, the rest of the callback never run, as after a fault: nothing it would have saved or freed is. That is why a real program does long work on a task or in pieces on a Timer instead (Section 11.2). sHanging keeps a second click on Hang from starting a loop inside the loop, and showStatus checks sWin because the window may have been closed while the loop ran.

The first kind is the dangerous one, since it leaves nothing to look with. Its usual causes are a missing tsYield on some path through a main loop and a wait written as a loop that does not yield. sleep, usleep, and delay let the other tasks run when a program’s own task calls them, but in a callback they stop all of DVX for as long as they wait; so do the secure link’s and the packet layer’s blocking sends and handshake, which keep the other programs' tasks going but not DVX itself (Section 15.6.2). The last lines in DVX.LOG show where the program was when it stopped, so log before and after each wait you suspect. Task Manager itself is described in Section 11.9.

22.6. Memory and Leaks

Every block a program allocates is counted to it (Section 3.9): the program’s own malloc calls, and what DVX allocates on its behalf, such as its windows' content buffers, its widgets, and a main-loop program’s stack. dvxMemGetAppUsage(appId) (dvxMem.h) gives the total, in bytes, without the 16 bytes of DVX’s header each block also has:

// What the program has allocated and not freed, in bytes: its blocks,
// its window's content buffer, and its widgets.
static void showUsage(void) {
    char text[BUGHUNT_TEXT_MAX];

    snprintf(text, sizeof(text), "Memory in use: %" PRIu32 " bytes", dvxMemGetAppUsage(sCtx->appId));
    dvxLog("bughunt: %s", text);
    showStatus(text);
}

Task Manager’s Memory column shows the same total, in KB or MB, checked again every second.

22.6.1. Finding a Leak

A leak is memory a program allocates and never frees. Bug Hunt’s Leak a Block makes one:

// The block's address is logged and then forgotten, so nothing can free
// it: it is counted to the program while the program runs, and stays
// allocated after the program ends, until DVX exits.
static void onLeakClick(WidgetT *w) {
    (void)w;

    void *block = malloc(BUGHUNT_LEAK_BYTES);

    dvxLog("bughunt: leaked %" PRIu32 " bytes at %p", (uint32_t)BUGHUNT_LEAK_BYTES, block);
    showUsage();
}

Click Memory in Use, then Leak a Block a few times: the total grows by about 10 KB with each click, and nothing brings it down again. To find a leak in a real program, log the total at a point the program comes back to in the same state, such as after a document is closed or after a dialog box is dismissed, then do the same thing several times. The first time may leave memory that stays (a cache filled, a font loaded); a total that grows each time the same amount is a leak. Halve the steps between two figures until you find the one that leaks. The usual leaks are a copy that a function returns for you to free (dvxResRead, platformReadFile, a list of files), a block freed on the normal path but not on an error path, and what a program keeps for its window but does not free when the window closes.

A leak outlives the program. When the program ends, DVX starts its count over, so Task Manager stops showing it, but the blocks stay allocated until DVX exits (Section 3.9), and DVX.LOG says how much was left: Memory: program 2 ended with 10240 bytes still allocated to it; they stay until DVX exits. A leak that costs little in one run costs it again in every run of the program, and in a session of hours the machine runs short.

22.6.2. What DVX Releases When a Program Ends

However a program ends, normally, by End Task, by exit, or by a fault, DVX releases some of what it had and not the rest:

Released Not released
  • Its windows, with their widgets, menus, and content buffers

  • The widget classes it registered, its hotkeys, and the fonts it carried

  • Interrupt timers registered with its ID (platformTimerAdd with ctx->appId, gameTimerAdd)

  • The idle handlers and desktop-update callbacks it registered

  • Its own tasks: a main-loop program’s, a shellAppTaskStart task, and the tasks it made with tsCreate

  • Its sockets, the sound contexts it opened (audioOpen), the music it loaded, its joystick handles, and its print jobs

  • Its databases, serial ports, packet connections, secure links, connections, and file transfers

  • Every block it allocated and did not free (DVX.LOG says how much)

  • Files it left open: each holds one of DOS’s few file handles until DVX exits

  • Interrupt timers registered with an owner of 0

The program’s appShutdown, and then the functions it gave atexit, run when it ends normally, and also when End Task or Exit DVX ends it, after its tasks are stopped. They do not run after a fault, for a program that is not responding, or when End Task had to wait for the program’s code to return; exit runs the atexit functions, but not appShutdown (Section B.3.1). So close and free in the program’s own way out, onClose or the end of its loop, and in appShutdown; what a fault leaves stays until DVX exits.

22.7. Testing on Emulators and Real PCs

You cannot run DVX on the build machine, so you test on a DOS machine: an emulator for most of the work, and real PCs before you give a program out. Emulators differ from a PC, and from each other, in ways that hide bugs. Test on more than one.

22.7.1. DOSBox

DOSBox (DOSBox Staging, DOSBox-X) is the quickest to work with: it can mount a folder of the build machine as drive C:, so make install puts a program where DVX finds it, and DVX.LOG can be read from the build machine while DVX runs. It emulates a DOS PC’s behavior, not its timing:

  • Its speed is whatever its cycles setting says, for a protected-mode program such as DVX usually far faster than a 486. A program that is quick in DOSBox may crawl on a 486; set the cycles low to come nearer to one.

  • Its serial ports (a null modem over TCP, an emulated modem) pass bytes without a UART’s timing and never lose one to an overrun. A program that reads its port too rarely, which loses data on a real UART at high speeds, works in DOSBox.

  • Its processor may not report a fault as a real one does: a stray pointer outside DVX’s memory, a general protection fault on a real processor, can come out of DOSBox as a page fault. Read the EIP is in line, not only the signal’s name.

  • Its mouse driver reports absolute positions faithfully, but while the emulator does not have the host’s mouse captured it can stop counting the relative movement (mickeys) that real mouse drivers report. DVX’s own mouse code copes with both kinds of driver, so a program sees the same events either way, as long as it takes the mouse from DVX’s events and never from the mouse driver.

22.7.2. 86Box

86Box emulates the hardware of a real PC: a particular processor at its own speed, a real video card’s VESA BIOS, a sound card, and serial ports with a 16550 UART running at the real baud rate. It is the closest thing to a real PC without one. Set it up as a 486 to see how fast your program is there. Serial overruns happen in 86Box as they do on hardware (in the project’s experience, serial bugs that lose data show up in 86Box and not in DOSBox), and its mouse driver behaves like a real one: relative movement, and in VESA modes an absolute position the driver confines to a small area. How files get into it depends on how its DOS is set up: when it sees a folder of the build machine, make install works as with DOSBox; when it runs from a disk image, put a program in with a package (make package makes the .dpk; Software installs it) or with whatever copies files onto the image.

22.7.3. Real PCs

A real PC has what no emulator promises: its own video card’s VESA BIOS (a linear framebuffer or only a banked window, its own list of modes and color depths), its own sound card and mouse driver, the memory it has (DVX’s floor is 4 MB), a particular DOS and perhaps no long file names (Section 10.8), and a disk of its own speed.

22.7.4. A Checklist

Before you give a program out, run it:

  • In 256 colors and in a high-color mode, at 640 x 480 (the smallest screen DVX runs in) and larger.

  • With and without the hardware it can use: a sound card, a joystick, a network card, a printer.

  • With other programs running, and while they work (a program playing music, a terminal receiving).

  • Ended every way: its own close, Exit DVX, End Task, and a DOS program run from Program Manager (which closes it first); then check that DVX, the sound, the serial ports, and the network still work for the next program, and start it again.

  • Several times in a row, with Task Manager’s Memory column, or your own log of dvxMemGetAppUsage, checked each time (Section 22.6.1).

  • On the slowest machine you mean to support.

22.8. Performance on a 486

DVX’s floor is a 486DX, and its own code is written to be quick there. Yours should be too: the user’s whole machine waits while it runs (Section 3.5).

22.8.1. Measuring

Measure on the machine you are writing for, or on 86Box set up as one, never on the build machine. platformMicros() (dvxPlat.h) is a 64-bit count of microseconds; take it before and after the work and log the difference once, as Time Log Lines does. clock() advances only about 18 times a second, too coarse for anything shorter than a second. Measure before you change anything: on a 486 the time goes to different places than on a modern machine, mostly to memory and to DOS.

22.8.2. The Screen

Every change on the screen travels through several buffers (Section 3.8), so the first thing to look at in a slow program is how much it repaints, and how often. Section 9.10 and Section 9.11 cover drawing itself; for widgets:

  • wgtInvalidatePaint repaints one widget; wgtInvalidate lays the whole window out and repaints all of it. Use the first when only a widget’s look changed.

  • Setting a widget’s text (wgtSetText) is a wgtInvalidate: the whole window is laid out and repainted. A label, a button, a check box, or an option button ignores the text it already has, but other widgets take it again, so set text only when it changes, and a few times a second at most for progress text. A progress bar’s value repaints only the bar.

  • A window paints at most once a frame, however many changes it had, so batch changes and let the frame paint them.

22.8.3. Long Work

A loop on a task yields after a slice of time, not after every step: each yield runs a whole frame of the shell’s, and a step much shorter than a frame spends most of the machine on frames. Read the clock every so many steps rather than on every one; on a 486, platformMicros reads the timer chip, which is slow I/O. primes shows both (Section 11.3.2). And a Timer fires at most about 18 times a second, so work done in slices on a Timer gets only a part of the machine (Section 11.2).

22.8.4. Files and DOS

Every file call goes to DOS, which means a switch from protected mode to real mode and back, and DOS’s own slow work on a slow disk. So:

  • Read and write in large blocks. platformReadFile reads a whole file into memory in one go; fread into a buffer of many KB beats fgetc in a loop, though the C library’s buffering makes fgets on a text file acceptable.

  • Open a file once, not once per record.

  • Do not stat every entry of a folder listing: on DOS each stat searches the folder again, which makes the listing quadratic. readdir gives most entries' type (platformDirEntryIsDir uses it, and falls back to stat only when it must).

  • Log sparingly (Section 22.2).

22.8.5. Arithmetic

A 486DX has a floating-point unit, but it is slow next to the integer unit, and converting a double to an integer costs more than the arithmetic: the compiler has to change the FPU’s rounding mode around each conversion. Keep floating point out of loops that run per pixel or per sample, use integers or fixed point there, and replace a division in a loop by a multiplication or a step (Section 9.11). 64-bit integer division and modulo are calls into a helper function, much slower than 32-bit ones.

22.8.6. Memory

A small PC has a few MB for DVX and every program together. Each window’s content buffer costs its width x height x bytes per pixel for as long as the window exists, twice as much at 32 bits per pixel as at 16. Each block from malloc costs 16 bytes of DVX’s header besides the C library’s own, so thousands of tiny blocks waste a good part of what they hold: allocate arrays, not a block per item. And free what you are done with, since what a program keeps, every other program does without.

22.9. The Binary Interface Rules

A module is compiled against DVX’s headers, and DVX refuses a module built against another release’s (Section 3.11). The rules that follow from that:

  • Build every module with the SDK of the DVX release it will run on.

  • When DVX_ABI_VERSION (dvxTypes.h) changes, rebuild every module you have. It changes when DVX changes something a compiled module depends on: the size, member order, or member types of a public structure or a widget’s API table; a WGT_METHOD_* slot number or the meaning of a slot of WidgetClassT; the parameters, return type, or contract of a public function, or its removal; or the value of a public constant that modules compile in (array sizes in public structures, flag bits, message and event codes). A new function, constant, or structure does not change it.

  • Every library and widget writes DVX_ABI_STAMP(name) once, at file scope, where name is the module’s file name in lower case without its extension: the loader looks for nameAbiVersion by the file’s name. A renamed file needs its stamp renamed, or the loader finds none.

  • A widget class’s version is WGT_CLASS_VERSION, the same number; wgtRegisterClass refuses another and logs Widget: class version n rejected (expected m).

Your own libraries and widgets have interfaces that other modules compile against in the same way, and the same care keeps them working (Chapter 18, Chapter 19):

  • A library’s exported functions are its interface. Never change a function’s parameters or return type once others use it: add a new function, and raise your library’s own version constant so callers can check for it: the library template has one, TPLNAME_VERSION, with a function that returns it, tplNameVersion, both renamed for your library by newProject.sh.

  • A widget’s API table begins with its WgtApiHeaderT (.header = WGT_API_HEADER(type)). Callers pass the size of the table they were compiled with to wgtGetApi, which refuses a smaller one. Add members only at the end.

Keep everything that is not part of an interface static. Every name a module does not make static is exported, and visible to every module loaded after it; when a module and DVX.EXE both have a name, the module’s is the one later modules get. A program with a global function of its own called log, for example, would become the log of every program started after it, and when it ended, those programs would be left calling code that is gone. A program exports appDescriptor, appMain, and appShutdown if it has one, and nothing else.

Appendix A: The SDK Build Settings

Every SDK project’s Makefile sets a few variables and includes sdk.mk, which holds all the rules (Section 1.4). This appendix lists every variable and target sdk.mk has, with its default. Set a variable in the Makefile before the include line, since sdk.mk reads some of them as it is read; one given on the make command line (make VENDOR=acme) overrides the Makefile and the defaults; and one in the environment counts where sdk.mk gives only a default (?=) or nothing at all.

A.1. Project Settings

These describe the project. The three required ones are in every template’s Makefile; the others go there when the project needs them.

Variable Default Meaning

SDK_DIR

None (required)

The SDK’s folder, the one that holds sdk.mk. The templates give it relative to the project with ?=, so the command line or the environment can override it.

KIND

None (required)

What the project makes: app, widget, library, basic (a DVX BASIC program), or control (a control written in DVX BASIC). Anything else stops make with “sdk.mk: KIND must be app, widget, library, basic or control, not 'kind'”. The game and basicgame templates are app and basic projects.

NAME

None (required)

The module’s base name: a letter, then letters and digits, eight characters at most. It names the module, its help file, its package, and the files sdk.mk looks for (NAME.res, NAME.dhs).

NET

Off

1 for a module that uses sockets: include/net (sys/socket.h, netdb.h, errno.h, and the rest) goes on the include path ahead of the C library’s headers (Section 14.2). Any other value is off.

DATA

Empty

Files or folders the program reads at run time, too big or too many to be resources. make package copies them into a DATA folder beside the module, where the program finds them with shellDataPath (Section 10.3.2).

LIBS

Empty

Static libraries (.a files, built with the same DJGPP) linked into the module after its objects: a game library ported to DVX, for example. A C module only.

SAVER

Off

1 for a screen saver, a program (KIND app or basic) that DVX starts with /S after the wait: make package puts it in SHARED\SAVERS\<VENDOR>, where Control Panel lists it, without its help (a saver shows none), and the package’s kind is saver. For any other KIND, make stops with “sdk.mk: SAVER = 1 is for a program (KIND app or basic), not KIND kind”.

CFLAGS

Empty

Compiler options added after the SDK’s own: -g for debugging information (Section 22.3.2), -Ifolder for the header of a library of yours, -Dname=value. sdk.mk never sets it, so a CFLAGS in your shell’s environment is used too; clear it if it holds options for another compiler.

A.2. Build Settings

These say where things are on the build machine. They are meant for the command line or the environment.

Variable Default Meaning

DJGPP_PREFIX

SDK_DIR/../../toolchains/djgpp, the toolchain folder of the DVX source tree the SDK was built in

The DJGPP cross compiler’s installation: the folder that holds bin/i586-pc-msdosdjgpp-gcc (Section 1.2). The default applies only when the variable is not set at all; set but empty, it names no compiler.

VENDOR

local

The vendor folder the module installs under: APPS\<VENDOR>\<NAME>, WIDGETS\<VENDOR>\<NAME>, or LIBS\<VENDOR>\<NAME>. It is also the first half of the package’s name, vendor.name in lower case, so it is 1 to 8 letters, digits, or underscores (Chapter 21).

DVX_DIR

Empty

The DVX folder, as the build machine sees it, that make install copies into. make install without it stops with “Set DVX_DIR to the DVX directory, e.g. make install DVX_DIR=/path/to/dvx”.

A.3. Package Settings

These fill in the package make package makes, NAME.dpk, the add-on package DVX’s Software program installs (Chapter 21). The publisher, author, license, home page, and oldest DVX go into the package only when they are set. Any value may hold blanks and apostrophes.

Variable Default Meaning

PKG_TITLE

The module’s name resource, else NAME

The name Software shows.

PKG_VERSION

1.0.0

The version, major.minor.patch. Raise it for each version you give out.

PKG_SUMMARY

The module’s description resource

A line about the package, shown in Software’s details.

PKG_PUBLISHER

Empty

Who publishes it.

PKG_AUTHOR

Empty

Who wrote it.

PKG_LICENCE

Empty

Its license. The variable is spelled LICENCE, as the manifest’s key is.

PKG_HOMEPAGE

Empty

Its web page.

PKG_DVX

Empty (any)

The oldest DVX the package runs on, major.minor.patch.

PKG_NEEDS

Empty

The packages it needs, each id=oldest version, separated by spaces: PKG_NEEDS="acme.cards=1.0 acme.dice=2.1".

PKG_KEY

Empty (unsigned)

The secret key file to sign the package with. dvxpkg keygen "Your Name" BASE makes BASE.SEC, the secret key, and BASE.KEY, the public key you give out.

A.4. Targets

Target Does

all (the default)

Builds the module (NAME.app, NAME.wgt, or NAME.lib) with its resources, and its help: a program’s compiled into NAME.hlp; a widget’s or library’s checked as DVX’s own compile will see it (dvxhlpc --joins with the topic IDs of DVX’s help, in the SDK’s help folder), which NAME.hck records. For a C module: compiles each .c file, links the objects and LIBS with dxe3gen into NAME.dxe, renames that to the module, and appends the resources NAME.res lists with dvxres. For a BASIC project: bascomp NAME.dbp -o module -release. Then dvxhlpc -o NAME.hlp on NAME.dhs (and NAME.bhs, if there is one).

package

Builds, then lays out pkg/ exactly as the files go into the DVX folder (Section A.6) and makes NAME.dpk from it with dvxpkg, signed when PKG_KEY is set.

install

Packages, then copies the contents of pkg/ into DVX_DIR with dvxpkg copy, into the folders already there whatever the case of their names.

clean

Removes the objects and their .d files, the module, NAME.dxe, NAME.hlp, NAME.hck, pkg/, pkg.ini, and NAME.dpk.

Help is optional: a project without NAME.dhs or NAME.bhs builds and packages without it. Each template has one.

Before it compiles a C file, sdk.mk checks that the compiler is there; without it, make stops with “DJGPP cross compiler not found: path” and how to set DJGPP_PREFIX. The check is a target of its own, sdkToolchain, which the rules use; you never need to name it.

A.5. The Files It Uses

sdk.mk finds a project’s files by name; there is no list to keep.

Files Used for

*.c

The module’s source: every C file in the folder (C kinds).

NAME.res

The resources appended to the module (C kinds), if the file is there.

NAME.dhs, NAME.bhs

The help sources: NAME.bhs is a widget’s or control’s help for DVX BASIC.

NAME.dep

The modules a library or widget needs loaded before it, one name a line (Chapter 18), if the file is there.

NAME.dbp, *.frm, *.bas, *.ctl

A BASIC project and its forms, modules, and controls (BASIC kinds).

The files NAME.res names

Any of them changed rebuilds the module (C kinds); dvxres deps NAME.res lists them.

*.bmp, *.wav, *.voc, *.mid, *.mod, *.s3m, *.xm, *.it

Files a BASIC project takes in: a change to one rebuilds the module.

The build also writes name.o and name.d (dependency information, so a changed header rebuilds what includes it) for each .c file, NAME.dxe for a moment while it links, and pkg.ini, the package’s manifest, for a moment while it packages.

A.6. What a Package Holds

make package puts the module in pkg/top/VENDOR/NAME/, where top follows the kind:

KIND Module top Also in the folder

app

NAME.app

apps

NAME.hlp, which F1 opens.

basic

NAME.app

apps

The same.

widget

NAME.wgt

widgets

The help sources, in upper case (NAME.DHS, NAME.BHS): DVX compiles them into its own help when it starts and finds them new or changed (Section 20.4).

control

NAME.wgt

widgets

The same.

library

NAME.lib

libs

The same.

A screen saver (SAVER = 1) goes in pkg/shared/savers/VENDOR/ instead, the module with no folder of its own and no help. For every kind, the folder also gets the DATA folder when DATA is set, and NAME.dep when there is one, copied with DOS line ends. The package’s kind, in its manifest, is saver for a screen saver, app for app and basic, widget for widget and control, and library for library; its ID is vendor.name in lower case.

Note
The folders in pkg/ are named in lower case (apps/local/hello). DOS does not mind, and make install copies into the folders of DVX_DIR whatever the case of their names, so a Linux folder whose DVX tree is named in upper case gets no second, lower-case tree (Section 1.6).

A.7. Names sdk.mk Uses Itself

sdk.mk sets these for its own rules. A project has no reason to change them, but they are ordinary make variables, and the tools can be pointed elsewhere on the command line (make DVXRES=/opt/dvx/bin/dvxres):

Variable Value

DJGPP_TRIPLE

i586-pc-msdosdjgpp, the prefix of the cross compiler’s tools.

CC

$(DJGPP_PREFIX)/bin/i586-pc-msdosdjgpp-gcc.

DXE3GEN

dxe3gen from the DJGPP installation, run through the SDK’s bin/dxeGen.sh, which runs it in a scratch folder of its own so that parallel builds (make -j) do not overwrite each other’s temporary files.

DVXRES, DVXHLPC, BASCOMP, DVXPKG

The SDK’s bin/dvxres, bin/dvxhlpc, bin/bascomp, and bin/dvxpkg.

SDK_CFLAGS

The SDK’s compiler options: -O2 -Wall -Wextra -Werror -march=i486 -mtune=i586 -MMD -MP -I., then -I for include/net when NET is 1, then -I for every other folder of include but include/basic (Section 1.5).

SDK_INCLUDE, SDK_NET_INC, SDK_INC_DIRS

The SDK’s include folder, its net folder, and its header folders.

SRCS, OBJS

The .c files, and their .o files.

SYS_HELP_SRC, BAS_HELP_SRC, HELP_SRCS, HELP

NAME.dhs and NAME.bhs, if they exist, and both; NAME.hlp for a program, NAME.hck for a widget or library, nothing without help.

SDK_HELP_DIR, SYS_HELP_IDS, BAS_HELP_IDS

The SDK’s help folder, and in it dvxhelp.ids and dvxbasic.ids, the topic IDs of DVX’s system help and DVX BASIC help, which a widget’s or library’s help is checked against.

RES, RES_FILES, DEP, ASSETS

NAME.res if it exists, and the files it names (dvxres deps); NAME.dep if it exists; the asset files of a BASIC project (Section A.5).

MODULE

NAME.app, NAME.wgt, or NAME.lib, by KIND.

PKG_ROOT, PKG_TOP, PKG_DIR

pkg; apps, widgets, or libs; and pkg/top/VENDOR/NAME (pkg/shared/savers/VENDOR for a saver).

PKG_TEMPLATE, PKG_FILE

pkg.ini, the manifest written for dvxpkg; NAME.dpk.

PKG_ID, PKG_KIND, PKG_FIELDS

The package’s ID and kind (Section A.6), and the list of optional manifest fields and the PKG_ variables that fill them.

Appendix B: Porting C Code to DVX

A DVX module is 32-bit protected-mode C, compiled by GCC for DJGPP, so the language is the C you know: int, long, and pointers are 32 bits; char is signed; long double is the x87’s 80-bit type, 12 bytes in memory; wchar_t is 16 bits; and, as in every i386 C ABI, a double or a long long inside a structure is aligned to 4 bytes, not 8, which matters when you read a binary file whose layout a 64-bit program wrote. Portable code compiles as it is. What changes is the world around it: there is no main and no console, DVX gives a module most of the C library, some of it in versions of its own, nothing may block, and DVX, the C library, and every other program share one address space and one copy of everything. This appendix lists what the C library offers a module, what to replace, and how to port a game library.

B.1. The Shape of a Program

A DVX program has no main. The shell calls appMain (Section 2.3), and the program is one of two kinds (Section 3.4):

  • A program built around a loop of its own (a game, a terminal, a simulation, most programs that were written for DOS) becomes a main-loop program (hasMainLoop = true). Its loop runs on its own task and calls tsYield on every pass. The quickest port renames the old main (CFLAGS = -Dmain=oldMain in the Makefile, before the include) and calls it from appMain, then puts a tsYield in each of its loops, or in the function that waits for the next frame.

  • A program that waits for the user is better rewritten as a callback-only program: its windows, widgets, and menus call it, and it keeps nothing running between calls.

argc and argv become one string, ctx->args, which dvxNextArg splits a word at a time (Section 11.5). The program’s own file is ctx->appPath, and its folder ctx->appDir. A main-loop program’s return value from appMain is not used; a callback-only program returns 0 to stay running.

B.2. The C Library

DVX.EXE holds DJGPP’s C library and gives modules most of it: the functions in its table of exports (sDxeExportTable in src/libs/kpunch/libdvx/platform/dvxPlatformDos.c of DVX’s source). A module that uses any other C library function, or variable, compiles and links without a word, since dxe3gen leaves outside names to be resolved when the module loads, and is then refused by DVX: “unresolved symbol: name” (Section 22.4). DJGPP’s headers declare far more than DVX gives, so the compiler cannot warn you. i586-pc-msdosdjgpp-nm -u on your objects lists every outside name they use; check each that is not DVX’s own against the tables below.

The C library functions a module may call, as the export table groups them (those marked * are DVX’s own versions, described in Section B.3.1 and Section B.3.2):

Group Functions

Memory

malloc, calloc, realloc, free, strdup, and strndup, all DVX’s counting versions (Section 3.9)

Strings and memory

basename, bcmp, bcopy, bzero, dirname, ffs, index, memccpy, memchr, memcmp, memcpy, memicmp, memmove, memset, rindex, stpcpy, stpncpy, strcasecmp, strcat, strchr, strcmp, strcoll, strcpy, strcspn, strerror, strerror_r, stricmp, strlcat, strlcpy, strlen, strlwr, strncasecmp, strncat, strncmp, strncpy, strnicmp, strnlen, strpbrk, strrchr, strsep, strspn, strstr, strtok, strtok_r, strupr, strxfrm, swab

Characters

isalnum, isalpha, isascii, isblank, iscntrl, isdigit, isgraph, islower, isprint, ispunct, isspace, isupper, isxdigit, toascii, tolower, toupper

Conversion

abs, atof, atoi, atol, atoll, div, ecvt, fcvt, gcvt, imaxabs, imaxdiv, itoa, labs, ldiv, llabs, lldiv, mblen, mbstowcs, mbtowc, strtod, strtof, strtoimax, strtol, strtold, strtoll, strtoul, strtoull, strtoumax, wcstombs, wctomb

Formatted I/O

asnprintf, asprintf, dprintf, fprintf, fputs, fscanf, perror, printf, puts, scanf, snprintf, sprintf, sscanf, vasnprintf, vasprintf, vdprintf, vfprintf, vfscanf, vprintf, vscanf, vsnprintf, vsprintf, vsscanf

Character I/O

fgetc, fgets, fputc, getc, getchar, gets*, putc, putchar, ungetc

Files

clearerr, fclose, fdopen, feof, ferror, fflush, fgetpos, fileno, fopen, fread*, freopen, fseek, fseeko, fsetpos, ftell, ftello, fwrite, mkdtemp, mkstemp, remove, rename, rewind, setbuf, setvbuf, tempnam, tmpfile, tmpnam

Low-level I/O

open, close, read*, write, lseek, llseek, fstat, fsync, ftruncate, truncate, dup, dup2, fcntl, isatty, pipe, umask, _chmod

Folders and the file system

opendir, readdir, rewinddir, seekdir, telldir, closedir, findfirst, findnext, mkdir, rmdir, access, chdir, chmod, fnmatch, getcwd, lstat, realpath, stat, unlink, utime

Time

asctime, asctime_r, clock, ctime, ctime_r, difftime, gettimeofday, gmtime, gmtime_r, localtime, localtime_r, mktime, strftime, time, tzname, tzset; sleep, usleep, and delay*, which let the other tasks run while a program’s own task waits in them, but stop all of DVX when a callback calls them (Section 3.5)

Process and environment

exit, abort, _exit, and _Exit, which end only the calling program; atexit; getenv, putenv, setenv, unsetenv; system, which is refused; getpid

Sorting, searching, random numbers

qsort, bsearch, lfind, lsearch; POSIX regular expressions, regcomp, regexec, regerror, regfree; rand, srand, random, srandom, and the drand48 family (drand48, erand48, jrand48, lcong48, lrand48, mrand48, nrand48, seed48, srand48)

Locale

setlocale and localeconv, for the C locale

Jumps and signals

setjmp, longjmp, sigsetjmp, siglongjmp, signal*, raise

Math

The double and the float functions: acos, acosh, asin, asinh, atan, atan2, atanh, cbrt, ceil, copysign, cos, cosh, drem, erf, erfc, exp, exp10, exp2, expm1, fabs, finite, floor, fmod, frexp, hypot, ilogb, ldexp, log, log10, log1p, log2, logb, modf, nan, nextafter, pow, pow10, pow2, remainder, rint, round, scalb, scalbn, significand, sin, sincos, sinh, sqrt, tan, tanh, trunc, and lrint, llrint, lround, llround; the float version of each with f after its name (sqrtf, atan2f), except exp10, exp2, pow10, pow2, and sincos; long double versions of finite, modf, nan, rint, round, trunc, lrint, llrint, lround, and llround (with l after the name); isnan, isinf, fpclassify, and signbit (through __fpclassifyd, __signbitd, and their kin); HUGE_VAL, HUGE_VALF, HUGE_VALL, and NAN

errno

The variable itself

Modules

dlsym, dlclose*, dlerror, dlregsym

The rest of the table serves code the compiler writes and DVX’s own needs: GCC’s helpers for 64-bit integer arithmetic and shifts (__divdi3, __moddi3, __udivdi3, __umoddi3, __divmoddi4, __udivmoddi4, __muldi3, __ashldi3, __ashrdi3, __lshrdi3, __negdi2, __cmpdi2, __ucmpdi2), for conversions between integers and floating point (__fixdfdi, __fixsfdi, __fixxfdi, the unsigned __fixuns... forms, __floatdidf, __floatdisf, __floatdixf, and the unsigned __floatun... forms), for the bit builtins (__popcountsi2, __clzsi2, __ctzsi2, __ffssi2, __paritysi2, __clrsbsi2, __bswapsi2, and their 64-bit di2 forms) and __builtin_powi (__powidf2 and its kin), thread-local variables (__emutls_get_address), DJGPP’s internals that its headers' macros use (__dj_ctype_flags and the case tables, __dj_stdin, __dj_stdout, __dj_stderr, __dj_assert (DVX’s: a failed assert ends only the program), __dj_huge_val, __dj_huge_valf, __dj_huge_vall, __dj_nan, __djgpp_exception_state_ptr, the __FSEXT_* file-system extension calls, _lfn_gen_short_fname, _preserve_fncase), the DPMI and interrupt calls DVX’s serial library uses (__dpmi_allocate_dos_memory, __dpmi_free_dos_memory, __dpmi_get_segment_base_address, __dpmi_lock_linear_region, __dpmi_unlock_linear_region, _go32_dpmi_allocate_iret_wrapper, _go32_dpmi_free_iret_wrapper, _go32_dpmi_get_protected_mode_interrupt_vector, _go32_dpmi_set_protected_mode_interrupt_vector, _go32_info_block), and the dynamic arrays DVX’s code is built on (stbds_*, whose header the SDK does not ship). The table also holds DVX’s own functions that live in DVX.EXE: dvxLog, the memory calls of dvxMem.h (dvxStrndup among them), the string and argument helpers (dvxNextArg, dvxArgAppend, dvxSkipWs, dvxTrimRight, dvxCopyTrimmed, dvxHasExt, dvxStrAppendf, dvxStrAppendfCut), dvxReadDir and dvxReadDirFree (whose list ends with a NULL), and the platform* functions of dvxPlat.h (“platform/dvxPlat.h — Platform Layer” in the DVX C Library Reference), platformAtExitRun and platformModuleClose (a module’s dlclose) among them.

A module built with NET = 1 gets the socket API as well, from DVX’s network library: socket, connect, bind, listen, accept, send, recv, sendto, recvfrom, shutdown, select, poll, getaddrinfo and the other name calls, setsockopt and getsockopt, ioctl, and the byte-order and address functions (Section 14.3). That library supplies its own fcntl, which knows sockets.

B.2.1. What Is Not There

Among the functions DVX does not give modules, these are the ones ported code most often uses:

Missing Instead

fmin, fmax, fdim, fma

A comparison, or the arithmetic itself.

The Bessel and gamma functions: j0, j1, jn, y0, y1, yn, gamma, lgamma, their _r and float versions

Link DJGPP’s math library into the module: LIBS = $(DJGPP_PREFIX)/i586-pc-msdosdjgpp/lib/libm.a in its Makefile (Appendix A). What it needs besides is in DVX.EXE.

The complex-number functions and their helpers (__muldc3 and its kin)

Real arithmetic on the two parts.

popen, nanosleep

There are no pipes to other programs. For a wait, a Timer, or a loop that yields (Section B.3).

int86, intdos, __dpmi_int, __dpmi_simulate_real_mode_interrupt, dosmemget, dosmemput

No module calls DOS or the BIOS directly. DVX’s libraries do that work (Section B.3.3).

__djgpp_nearptr_enable, __djgpp_conventional_base

DVX uses no near pointers (Section B.3.3).

spawn and exec calls, fork

shellRunDos, shellRunDosFor, and shellRunProgram (Section 11.7).

dlopen

Call the library’s functions: DVX loads a library the first time a module uses one of its names.

htonl, htons, ntohl, ntohs

They are the network library’s, for a module built with NET = 1 (Section 14.2).

The conio console calls (getch, kbhit, cprintf)

Key events, and the window (Section B.3.2).

The compiler adds calls of its own too: __builtin_popcount calls __popcountsi2, and a printf of a plain string ending in a newline becomes a call to puts. DVX has the helpers GCC calls, but the nm -u check catches any it does not. A static library you link into a module with LIBS (Appendix A) needs the same check, since its objects call the C library as yours do.

B.2.2. One C Library for Everything

There is one copy of the C library in DVX, and every module uses it. Its state is shared:

  • errno, the buffer strtok keeps its place in, the static results of localtime, gmtime, ctime, asctime, and strerror, and the state of rand belong to all of DVX. Tasks switch only when one yields (Section 3.5), so code that uses them between two yields is safe; code that keeps one across a tsYield, or across a call that runs the event loop, such as a dialog box, may find another program’s value there. Copy what you need first. Another program’s srand reseeds your rand: a program that needs a repeatable sequence keeps a generator of its own.

  • The current directory is DVX’s folder for every program, and DVX finds its own files from it. Never change it with chdir; build full paths from ctx->appDir, ctx->userDir, and the other folders (Section 10.3).

  • The environment is DVX’s, and the DOS programs DVX runs inherit it. setenv and putenv change it for everyone.

  • DOS has few file handles, and every program’s open files and sockets draw on them. Close a file when you are done with it; DVX does not close what a program leaves open (Section 22.6.2).

B.3. What to Replace

The rest of porting is replacing what a DVX program must not do with what it does instead:

Code that uses Uses under DVX

Threads (pthread_create, a thread per connection or per job)

Tasks: a main-loop program’s own, or one shellAppTaskStart task for a callback-only program (Chapter 11). They switch only when the running one yields, so shared data needs no locks, but every loop must yield.

Blocking I/O: a read that waits for data, a connect that waits for an answer

Polling. Sockets are made non-blocking, or wait on a task, where a blocking call yields while it waits (Section 14.4). A serial port is read for what has arrived, often (Section 15.2). Reading a file on a disk is quick enough to do at once.

sleep, usleep, delay in a callback, a busy loop that waits

A Timer widget, for a callback-only program (Section 11.1); on a task, sleep and its kin as they are, or a loop that calls tsYield until platformMicros says the time has come; gameFrameWait, for a game’s frames (Chapter 17).

alarm, setitimer, SIGALRM

A Timer widget, or for work that must run at a steady rate however busy DVX is, an interrupt timer: platformTimerAdd or gameTimerAdd (Section 11.1).

printf and fprintf(stderr, ...) for messages, perror

dvxLog for what the author needs (Section 22.2), and a dialog box or the window for what the user needs (Section B.3.2).

Reading the keyboard: getch, kbhit, fgets(stdin)

Key events (Chapter 8), or the game library’s held keys (gameKeyIsDown).

POSIX paths: / as the root, ~ and $HOME, /tmp, names of any length

DVX’s paths: drive letters, \ shown to the user and / accepted (Section 10.2); the program’s user folder (ctx->userDir, shellUserPath) for what it saves and its DATA folder (shellDataPath) for what it ships (Section 10.3); platformTempDir for scratch files; and names that may be limited to 8.3 (Section 10.8).

chdir and paths relative to the current directory

Full paths built with platformPathJoin from the folders above.

system, spawn, exec, fork

shellRunDos and its kin to run a DOS program, shellRunProgram to start a DVX program or open a document (Section 11.6, Section 11.7).

Cleanup at the end of main

onClose, the end of the main loop, or appShutdown; atexit works too (Section B.3.1).

Direct hardware

DVX’s libraries (Section B.3.3).

B.3.1. Ending, Exiting, and Signals

exit, abort, _exit, and _Exit in a module end only the program that calls them, the way a fault does, without a message: its appShutdown does not run, and DVX logs Shell: 'name' called exit (status n); ending it (status 3 for abort). They never end DVX. A failed assert is logged (Assertion failed: test, file file, line n, function name) and ends the program as abort does.

atexit is DVX’s version: the functions a program gives it belong to that program. exit runs them, newest first, before it ends the program, and so does every end that runs appShutdown, after it: a normal end, and End Task or Exit DVX while the program responds (Section 2.9). abort, _exit, _Exit, a fault, and End Task of a program that is not responding drop them. Ported code can keep its atexit calls; clean up in the program’s own way out as well, onClose or the end of its loop, since a fault runs nothing.

signal sets a handler for all of DVX.EXE, not for your program. DVX’s crash recovery is the handler of SIGSEGV, SIGFPE, and SIGILL, and DVX refuses a module’s handler for them: signal returns SIG_ERR with errno set to EINVAL, and logs it. Do not set a handler for SIGINT either (DVX turns off Ctrl+C at the start). There are no SIGALRM, SIGPIPE, or other Unix signals to wait for.

setjmp and longjmp work within your own code. Never longjmp out of a callback into code that called DVX, or from one task to another: DVX keeps track of the callbacks under way, and a jump past it leaves that record wrong.

system is refused: it returns -1 with errno set to ENOSYS, and logs the command (system(NULL), which asks whether there is a command interpreter, returns 0). Run from there, a DOS command would find DVX’s keyboard and timer handlers in place and the screen in a graphics mode. Use shellRunDos or dvxRunDos, which let go of the hardware first and take it back after (Section 11.7).

B.3.2. The Console

A DVX program has no console. stdout and stderr are DOS’s console, which DVX’s graphics screen covers: what a program writes there is not seen, and DOS may draw it over the screen as stray characters (DVX sends its own help compiler’s messages to the log for that reason). stdin is DOS’s keyboard, which DVX reads itself: a module’s getchar, gets, scanf, and vscanf give end of file at once, and so do fgetc, getc, fgets, fread, fscanf, vfscanf, and read on a stdin that is the console. So:

  • Write diagnostics with dvxLog, which goes to DVX.LOG; turn printf debugging into dvxLog calls (they take the same format).

  • Show the user messages in dialog boxes (Chapter 7) or in the program’s window: a label, a status bar, or a text area for a stream of output.

  • Take input from the window: key events, a text box, an input box (dvxInputBox).

A program written around a terminal can keep its shape with the Terminal control, AnsiTerm, an ANSI terminal in a widget (Section 15.5).

B.3.3. The Hardware

Code written for DOS often programs the hardware: the VGA’s registers and memory, the timer chip, the keyboard’s interrupt, the UART, the sound card, the game port, the mouse driver through INT 33h. Under DVX the hardware belongs to DVX, which shares it among the programs, and a module cannot call DOS or the BIOS (Section B.2.1). Nor can it reach memory outside DVX’s own through a pointer: DVX enables no DJGPP near pointers, so __djgpp_nearptr_enable and __djgpp_conventional_base are not there, and a pointer into DOS’s memory or the screen faults (Section 22.3.5). Code that writes video memory directly draws into a backbuffer instead, a window’s content buffer or, on the whole screen, dvxExclusiveDisplay()’s `backBuf, and shows it with dvxExclusiveFlush or dvxExclusivePresent8 (Chapter 17); a DisplayT has no pointer to the screen. Conventional memory, the BIOS’s data area say, is read and written through a selector, with _farpeekb and the other sys/farptr.h calls on _dos_ds. inportb and outportb still compile, as instructions, and still reach the ports, which is why they must not be used on a device DVX drives. Use DVX’s libraries instead:

Hardware Under DVX

Video memory, video modes, the palette

A window’s content (Chapter 9); the whole screen in a mode of the program’s own with DVX’s full-screen calls, dvxExclusiveBegin and its kin, which set the palette and wait for the vertical retrace too (Chapter 17).

The timer chip, the timer interrupt

Timers (Section 11.1) and platformMicros. Never reprogram the timer chip or hook its interrupt.

The keyboard interrupt, the BIOS keyboard

Key events, onRawKey and gameKeyIsDown for held keys (Chapter 8). Never hook the keyboard interrupt.

The mouse driver

Mouse events (Section 8.10).

A UART

The serial library, rs232.h (Section 15.2): one owner per port.

A sound card, the PC speaker, an FM chip, a MIDI port

The sound and music libraries, audio.h and music.h (Chapter 16).

The game port

The joystick library, joystick.h, with the user’s calibration (Chapter 17).

The printer port

The print library (Chapter 12).

A network card’s packet driver

The socket API (Chapter 14).

B.4. Porting a Game Library

Portable game libraries for DOS-era machines keep everything that touches the machine behind a small hardware layer: start and stop, show a frame, set the palette, read the input, wait for the next frame, play sound, and find files. A port to DVX replaces that layer. Everything above it, the drawing code, sprite compilers that write x86 code into memory, the data formats built for DOS, works unchanged: a DVX program is 32-bit x86 code in the same flat memory as a DOS program built with the same compiler.

B.4.1. The Model: a Window, a Task, and a Frame Rate

The game becomes a main-loop program: appMain calls the game’s main, renamed (-Dmain=gameMain). The library’s start-up creates a window whose content area is the game’s screen at a whole scale, and its frame wait yields until the next frame on DVX’s clock. In a window the game shares the screen with the desktop, so there is no mode change, no palette hardware, and no vertical retrace; each frame, the port converts the library’s back buffer into the window’s content buffer through a table of the palette’s colors. On the whole screen the game has its own mode, its own palette, and the retrace, while the other programs run on. The game library and the game template show both (Chapter 17).

B.4.2. Mapping the Hardware Layer

Each piece of a game library’s hardware layer has a counterpart in DVX:

Hardware layer DVX

Start-up

SHELL_APP_DESCRIPTOR with hasMainLoop, dvxCreateWindowCentered, gameInput

Shut-down

dvxDestroyWindow, then return from appMain

Error text, a debug log

dvxLog (DVX.LOG)

Show the back buffer

Convert through the color table into win->contentBuf, then dvxInvalidateRect; onPaint converts the whole screen

Show it on the whole screen

dvxExclusivePresent8, or dvxExclusiveDisplay and dvxExclusiveFlush

Whole screen on and off

dvxExclusiveBegin, dvxExclusiveEnd

The palette

packColor, gamePalNearest, GamePalCacheT; on the whole screen, dvxExclusiveSetPalette

A palette per scan line

One color table per palette, chosen for each row

Wait for the vertical blank

gameFrameInit, gameFrameWait; on the whole screen, dvxExclusiveWaitRetrace

Frame counter, frame rate

GameFramePacerT.frame, and the rate given to gameFrameInit

Milliseconds

platformMicros() / 1000

Held keys

onRawKey, gameKeyIsDown, platformKeyStateGet

Typed characters

onKey

Mouse

onMouse

Joystick

joyCount, joyOpen, joyRead

A periodic interrupt callback

gameTimerAdd, platformLockRegion

A critical section

platformIrqSave, platformIrqRestore

Audio start and stop

audioOpen, audioClose

Sound effect slots

audioSampleCreate, audioSampleLoadMem, audioPlay, audioVoiceSetPan, audioVoiceStop

Streamed sound

audioStreamOpen, audioStreamWrite

Tracker modules

musicLoadMem, musicPlay, musicStop, musicIsPlaying

Tone and noise voices

audioTone, audioVoiceSetFrequency, audioVoiceSetVolume, audioNotesOpen, audioFmAlloc

Audio work each frame

audioPump, musicPump

The read-only data folder

shellDataPath, or the program’s resources: dvxResOpen, dvxResRead

The save folder

DxeAppContextT.userDir, shellEnsureUserDir, shellUserPath

Free disk space

platformDiskSpace

Memory

malloc, free

A serial port

The serial library (rs232Open)

exit()

Ends only the game, after its atexit functions

B.4.3. Notes on the Mapping

  • Start-up: make the window one the user cannot resize, with a content area of the game’s screen at the largest whole scale that fits the display, and give it onClose and onPaint. audioOpen succeeds on a PC without sound hardware too (DVX’s null driver plays to no one); NULL (out of memory, or no driver could start) is not an error either: the game goes on without sound.

  • Shut-down: close what the port opened and return. What is left is released when the program ends, however it ends: sounds, music, joystick handles, and the interrupt timers gameTimerAdd made.

  • Showing a frame: convert the rows that changed through the color table into the content buffer, scaled, and invalidate only them; onPaint converts the whole screen.

  • Palette: scale 12-bit or 18-bit colors to 0 to 255 per channel before looking them up. Never touch the VGA’s palette registers: other programs share the screen. On the whole screen, dvxExclusiveSetPalette sets them, and puts the desktop’s palette back when the game lets go.

  • Vertical blank: there is none in a window. The frame rate is a virtual one: use the rate the library reports (60 or 70 frames a second), and cut the frame counter to the library’s width. On the whole screen, dvxExclusiveWaitRetrace waits for the real one.

  • Keyboard: raw key codes are set 1 scan codes, with KEY_RAW_EXT for the keys sent after 0xE0, so a DOS port’s scan code table maps directly. Never hook the keyboard interrupt.

  • Mouse: divide content-area pixels by the scale, and keep the result inside the game’s screen.

  • Joystick: axes run from -32768 to 32767 after calibration and the dead zone; divide them down to the library’s range, or compare with a threshold for a digital stick. Buttons are bits. Never read the game port: its calibration belongs to Control Panel.

  • Timer callbacks run inside the timer interrupt: no C library, no DVX calls, no floating point, and code and data locked with platformLockRegion. Never reprogram the timer chip or hook its interrupt.

  • Sound effects: DVX’s 8-bit samples are unsigned; flip the top bit of signed 8-bit data, or convert it to 16 bits. A stream’s fill function runs in the program’s time, not in an interrupt.

  • Files: a library’s fixed DATA and save folders become paths built at run time, with shellDataPath and shellUserPath. remove deletes a saved game.

  • Serial: a COM port has one owner, so the port uses DVX’s serial library rather than programming the UART.

  • exit ends only the game. Functions given to atexit run then, and at the game’s normal end, so a library’s atexit cleanup can stay.

B.4.4. Things to Decide

  • Shared or static: built as a DVX library (.lib), loaded the first time a game uses it, the port is shared by every game, but its global state (the stage, the key table) means one game at a time. Linked into each game’s .app (with LIBS; Appendix A), each game has its own copy, several can run at once, and nothing is loaded while no game runs.

  • Paths: a library that opens DATA/... or writes saves to a fixed folder needs a root given at run time: the DATA folder and userDir, not paths compiled in.

  • Speed: every frame costs a conversion and a composite. Show only what changed; use a scale of 1 on a 486 and larger scales on faster machines.

  • Tearing: there is no vertical retrace in a window. On the whole screen there is (dvxExclusiveWaitRetrace), but games that change registers in the middle of a frame (raster effects) still need rework.

  • The whole screen: offer it (Alt+Enter is the custom) and handle ExclusiveSuspendedE by drawing in the window again: the player can switch to the desktop with Alt+Tab at any time.

  • The 256-color desktop: only the nearest colors are available there. Say so in the game’s help if it needs 15-bit color or more.

B.4.5. Checking a Port

The library’s own drawing tests (hashes of the back buffer after each drawing call) should give the same answers under DVX as on DOS, since the drawing code is the same. Then test with a 256-color desktop and a 16-bit one; with and without a sound card and a joystick; with other programs running; and ended by End Task and by exit as well as by its own Quit, after which DVX, the sound, and the timer must be as they were (Section 22.7.4).

Index

# A B C D E F G H I J K L M N O P R S T U V W X Y Z

#

A

B

C

D

E

F

G

H

I

J

K

L

M

N

O

P

R

S

T

U

V

W

X

Y

Z