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.
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
monospacefont. 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 inE), braces around every body,//comments, thestdint.handstdbool.htypes, named constants instead of bare numbers, a prototype for every function at the top of the file, and the functions in alphabetical order withappMainlast. 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 .
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 |
|---|---|
|
A summary of the SDK: the quick start, the folders, packaging, and the binary interface rule. |
|
The script that makes a project from a template (Section 1.3). |
|
The build rules every project’s |
|
The host tools a build runs, all Linux programs: |
|
The C headers, one folder per library: |
|
The templates |
|
Two DVX BASIC programs. |
|
The programs, widgets, and libraries this book builds, each a project ready for |
|
This book, the DVX C Library Reference, and the two DVX BASIC books, as HTML. |
|
How to run |
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
$ DVX-SDK/newProject.sh KIND NAME [DIR]
| KIND | Makes |
|---|---|
|
A C program ( |
|
A C widget ( |
|
A C library of shared functions ( |
|
A C game ( |
|
A DVX BASIC program ( |
|
A DVX BASIC game. |
|
A control written in DVX BASIC (built to |
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
| File | What it is |
|---|---|
|
Names the SDK, the kind of module, and its name, and includes |
|
The program. |
|
The resources |
|
The program’s 32 x 32 icon. |
|
The program’s help, which |
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
| Command | Does |
|---|---|
|
Builds the module with its resources ( |
|
Lays out |
|
Packages, then copies |
|
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 |
|---|---|
|
The DJGPP installation (Section 1.2). |
|
The DVX folder |
|
The folder, under |
|
Flags added after the SDK’s own: |
|
|
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
...
| Option | Why |
|---|---|
|
Optimized code: DVX’s floor is a 486. |
|
Every warning stops the build. Code with a warning does not get as far as DVX. |
|
Instructions a 486 has, scheduled for a Pentium. The module runs on any 486DX or later. |
|
Dependency files ( |
|
The project’s own folder first, then every SDK header folder (with |
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 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_DIRis the DVX folder inside it, and the program is there as soon asmake installends. -
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 copyhello.dpkand install it with DVX’s Software program ().
|
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 (F5) in Program Manager. Double-click the icon, or choose 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
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.
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.)
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;
| Header | For |
|---|---|
|
The application layer: |
|
The standard dialog boxes ( |
|
The platform layer: files, paths, time, and |
|
Resources in module files ( |
|
The widget system ( |
|
The window manager: menu bars and menus ( |
|
Programs and the shell: |
|
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 |
|---|---|
|
Filled in by the macro, always first: the binary interface version ( |
|
The program’s name, as Task Manager and the shell’s messages show it: at most 63 characters ( |
|
|
|
|
|
A main-loop program’s stack, in bytes: |
|
A main-loop program’s share of turns, |
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 |
|---|---|
|
The shell’s GUI context ( |
|
The program’s ID, as the shell numbers running programs. |
|
The path of the |
|
The folder that file is in. |
|
The program’s own folder in the user folder, for its settings and the files it saves: |
|
The arguments the program was started with, empty when there are none. |
|
The help file F1 opens: |
|
The help topic F1 opens, and a callback the shell calls on F1 so the program can set it first (Chapter 20). |
|
A callback for a program that runs once: the shell hands it the arguments of a second start instead of refusing (Chapter 11). |
The reference describes each member (“Shell Types and Constants” in the DVX C Library Reference).
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.
-
onCloseruns 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 noonCloseis simply destroyed. -
onMenuruns 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);
}
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.
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 , 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 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
-
Change the greeting in
hello.res, for example togreeting text "Hello, world!". A resource change needs no recompiling, butmakesees thathello.reschanged and buildshello.appagain with the new resources. -
Change the label’s text in
appMain, or the window’s width (HELLO_WIN_W): a C change rebuilds the object first. -
Add a menu item: a new
CMD_number, awmAddMenuItemcall, and acaseinonMenuthat shows a message withdvxInfoBox. -
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 |
|---|---|---|
|
|
A library: functions that programs, widgets, and other libraries call. The windowing core ( |
|
|
A widget: one or more widget types, registered when it loads. |
|
|
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:
-
in a module already loaded (
LIBDVX.LIB,DVXSHELL.LIB, the widgets, and the libraries); -
else among the functions and variables
DVX.EXEpublishes (when a loaded module andDVX.EXEboth have a name, the module’s is used); -
else in a library not yet loaded that exports the name, which DVX then loads first, with what its
.depfile 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.
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.
-
AppContextTis 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. -
DxeAppContextTis the program’s own, one for each running program: its ID, its paths, its arguments, its help file, andshellCtx, the pointer to the oneAppContextT(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
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.
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
tsYieldon 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, anddelayare 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
dvxInfoBoxdoes 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
-
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. -
Paint each window that asked to be painted (Section 3.8), once, however many times it asked during the frame.
-
Destroy the windows that were destroyed from inside a callback.
-
Composite the changed parts of the screen and copy them to video memory.
-
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.
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.
#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;
-
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 sincestartcome from dividing byPLATFORM_US_PER_SEC. -
Each pass first takes what the callbacks asked for: a Reset moves
startto 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.
-
tsYieldat 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 oftickercomes again and the loop checkssQuit. -
When
sQuitis set, the loop ends, destroys the window, logs a line, and returns. Returning fromappMainends 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 |
|
The shell refuses to start it: “This program was built for a different version of DVX and cannot run.” |
Library, widget |
|
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 |
Widget API table |
|
|
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 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
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.
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 |
|---|---|---|
|
The user asks to close the window: the close gadget (double-click), Alt+F4, or Close on the system menu; also |
The program. |
|
A menu item, a context-menu item, or an accelerator key is chosen. |
The program (Chapter 6). |
|
A menu of the window’s menu bar, or a submenu, is about to open. |
The program (Chapter 6). |
|
The content area changed size. |
|
|
The window gained or lost the keyboard focus. |
|
|
The content needs painting. |
|
|
The mouse moved or a button changed over the content area. |
|
|
A key was pressed or released while the window had the focus. |
|
|
A window scroll bar moved. |
The widget layer, when it first lays the window out. |
|
DVX asks which mouse pointer to show over a point. |
A program drawing its own content (Chapter 8). |
|
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, andonMenuOpenare untouched by it, so the order does not matter for those, but setting every handler in one place afterwgtInitWindowavoids the question. -
Leave
onPaint,onMouse,onKey,onKeyUp, andonScrollto the widget layer in a window with widgets. To act ononResize,onFocus, oronBluras 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.
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;
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:
-
an array of items given to
wgtListBoxSetItems,wgtDropdownSetItems, orwgtComboBoxSetItems(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
| Field | What it is |
|---|---|
|
The widget’s place and size in the window’s content, as the last layout computed them. Read them; never set them. |
|
Size hints (Section 5.4); 0 is none. |
|
How much of a box’s extra room the widget takes (Section 5.4.2). |
|
A container’s arrangement of its children (Section 5.4.5). |
|
Colors of the widget’s own (Section 5.13); 0 is the color scheme’s. |
|
A pointer of yours. |
|
Set with |
|
The callbacks (Section 5.7). |
|
Read them; change them with |
|
A name for |
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 |
|
|
Label |
|
|
Button |
|
|
TextInput, TextArea |
|
|
Checkbox |
|
|
Radio |
|
|
ListBox |
|
|
Dropdown |
|
|
ComboBox |
|
|
ListView |
|
|
TreeView |
|
|
Slider |
|
|
Spinner |
|
|
ProgressBar |
|
|
Image |
|
|
ImageButton |
|
|
Separator |
|
|
Spacer |
|
|
ScrollPane |
|
|
Splitter |
|
|
TabControl |
|
|
WrapBox |
|
|
Toolbar |
|
|
StatusBar |
|
|
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.
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).
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
| Macro | Size |
|---|---|
|
|
|
|
|
|
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);dvxFitWindowHfits only the height anddvxFitWindowWonly 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
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 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);
}
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.
5.6.2. Text Boxes
-
wgtTextInput(parent, maxLen), one line holding up tomaxLencharacters (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,Aa 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 tomaxLencharacters (0 isTEXTAREA_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 |
|---|---|
|
A button or check box is clicked (on the release), a list item is picked, or another widget is clicked (after |
|
The second press of a double click lands on the widget. |
|
The user changes the widget’s value: an edit, a toggle, a new selection, a scroll, a drag of a splitter’s bar. |
|
The widget gains or loses the keyboard focus. |
|
A key goes down while the widget has the focus, before the widget acts on it. |
|
A key with a character goes down, after |
|
A key goes up while the widget has the focus. |
|
A mouse button goes down or up over the widget, or the mouse moves over it; |
|
The mouse wheel turns while the widget has the focus. |
|
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.
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.
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.
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.
#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.
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. 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 |
|---|---|
|
An item that sends |
|
An item with a check mark that turns on and off (Section 6.4). |
|
One of a group of items of which one is checked. |
|
A line between groups of items. |
|
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.
-
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;
dvxSystemKeyUsesays what each does. -
System-wide hotkeys (
dvxRegisterHotkey, Chapter 8), unless a menu or a modal window is open. -
Alt with a letter: the menu bar’s titles, then the access keys of the window’s controls (an open menu is closed first).
-
An open menu, which takes every key.
-
Esc, when a drop-down list is open: it closes the list.
-
The accelerator table of the window that has the focus.
-
Tab and Shift+Tab, which move the focus between controls.
-
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 , , 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, (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 |
|---|---|---|
|
A message, an icon, and one of five button sets |
The |
|
A message with the error or information icon and OK |
|
|
A message, an icon, and up to six buttons you name |
The index of the button |
|
“Save changes?” with Yes, No, and Cancel |
|
|
A prompt and a text box |
|
|
A prompt and a number box with up and down arrows |
|
|
A prompt and a list |
|
|
The Open, Save As, and folder dialogs |
|
|
A color picker |
|
|
A font picker |
|
|
Your own widgets, with OK and 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 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 |
|---|---|---|
|
0x00 |
OK |
|
0x01 |
OK Cancel |
|
0x02 |
Yes No |
|
0x03 |
Yes No Cancel |
|
0x04 |
Retry Cancel |
|
0x10 |
An “i” in a circle |
|
0x20 |
An exclamation mark |
|
0x30 |
An “X” in a circle |
|
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));
}
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
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
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);
}
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");
}
}
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
bool dvxFileDialog(AppContextT *ctx, const char *title, int32_t flags, const char *initialDir, const FileFilterT *filters, int32_t filterCount, char *outPath, int32_t outPathSize);
| Flag | Value | Meaning |
|---|---|---|
|
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. |
|
0x01 |
Save a file: a file that exists is taken only after “_name_ already exists. Do you want to replace it?” is answered Yes. |
|
0x02 |
Choose a folder, one that exists or a new one (the caller makes it). |
|
0x04 |
With |
|
0x08 |
With |
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
dvxDialogCreatemade must be run, even one you no longer want: its state is freed bydvxDialogRun. -
The dialog keeps its state in the window’s
userDataand installs its ownonKeyandonClose. Leave those three alone; useuserCtxfor your own data. -
contentWis the dialog’s least width:dvxDialogCreatemakes it the root’sminW, anddvxDialogRunkeeps it, growing the dialog only when a row needs more. A widget’s minimum width, as the example gives the name box withwgtChars, can widen it further. -
wgtSetFocusedbeforedvxDialogRunchooses 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:
-
dvxButtonBoxmeasures its buttons' labels: its box widens to fit its row of buttons, however long their labels are. -
dvxFileDialognever returns a path cut short. When the chosen path does not fitoutPathSize, it says “The path is too long.” (in a box titled Invalid Filename, or Invalid Folder for the folder dialog) and stays open, sotruealways meansoutPathholds the whole path, andfalsethat the user canceled. With a buffer ofDVX_MAX_PATHbytes 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
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), andKEY_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, andKEY_CTRL_Zare 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_F1toKEY_F12,KEY_UP,KEY_DOWN,KEY_LEFT,KEY_RIGHT,KEY_HOME,KEY_END,KEY_PGUP,KEY_PGDN,KEY_INSERT, andKEY_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_F5with Shift, and Alt+Up isKEY_UPwith Alt. -
Alt with a letter or digit types nothing, so it gives
KEY_EXT_FLAGand 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_LEFTandKEY_CTRL_RIGHT, Ctrl+Home and Ctrl+End areKEY_CTRL_HOMEandKEY_CTRL_END, Ctrl+Enter is 0x0A, and Ctrl+Backspace is 0x7F (KEY_ASCII_DEL, notKEY_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.
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:
-
The window switcher: Alt+Tab and Shift+Alt+Tab open it, and while it is up it takes every key.
-
Alt+F4 asks the focused window to close (only the dialog’s, while a dialog is up; Chapter 7).
-
Ctrl+Esc opens the Task Manager, even over a dialog (Section 7.2).
-
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). -
Ctrl+F12 saves a picture of the screen, and Ctrl+Shift+F12 one of the focused window.
-
F1 opens help (Chapter 20).
-
F10 opens the window’s menu bar, or the one its
menuWinIdnames (Chapter 4), and does nothing in a window with neither. -
The keyboard Move and Size modes of the window menu take every key while they run.
-
Alt+Space opens the window menu, which then takes its keys.
-
System-wide hotkeys (Section 8.8), but not while a menu or a dialog is up.
-
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.
-
An open menu takes every key (Chapter 6).
-
Esc closes an open drop-down list.
-
The window’s accelerator table: Ctrl+S and the like, which call
onMenu(Chapter 6). A table on a window withoutonMenudoes nothing. -
Tab and Shift+Tab move the focus to the next or the previous control. The key goes on to
onKeyonly 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. -
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:
-
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). -
The control with the focus gets the key: its
onKeyDown, then itsonKeyPressif 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
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).
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
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
onClickat the release, afteronMouseUp, as in Visual Basic, and only when the left button comes up over the widget that was pressed. The press holds the mouse: itsonMouseUpgoes 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 afteronChangewhen the pick changed the selection; picking with the keys raises it too. A press that picks nothing gives noonClick. -
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, oronMouseUp, and noonMouseMovecomes 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,
xandyare 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);
}
}
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 |
|---|---|---|
|
0 |
Everything else |
|
1 |
Resizing left and right: window edges, splitters, column dividers |
|
2 |
Resizing up and down |
|
3 |
A window’s top-left and bottom-right corners |
|
4 |
Its top-right and bottom-left corners |
|
5 |
The hourglass ( |
|
6 |
Placing or drawing something |
|
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
onKeyUpcode differs from itsonKeycode for keys that type characters. -
For most widgets the order is Visual Basic’s:
onMouseDown,onMouseUp, thenonClickwhen 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.
9.1. Where a Program Draws
-
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
onPaintcallback 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. asks for a line of text and draws it centered where the mouse was last pressed, in a font chooses. puts a picture file on the canvas, made smaller to fit when it is too big. takes back the last change. 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
// 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
| Call | Does |
|---|---|
|
Fills the drawing with a packed color. |
|
Sets the pen’s packed color. |
|
Sets the pen’s size in pixels, at most 255; a size below 1 is ignored. A line draws a round dot exactly |
|
A line with the pen. |
|
A rectangle’s outline, 1 pixel wide in the pen’s color whatever its size. |
|
A filled rectangle in the pen’s color. |
|
A filled circle in the pen’s color, 2 x |
|
One pixel, in a packed color of its own; reading one outside the drawing gives 0. |
|
Text in the pen’s color, in the canvas’s font (its own from |
|
A new white drawing of that size; what was drawn is lost. |
|
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. |
|
Saves the drawing (Section 9.7.3). 0 or -1. |
|
A |
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
| Field | Holds |
|---|---|
|
The buffer’s size in pixels. |
|
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. |
|
The pixel format ( |
|
The pixels. Every drawing call draws here. Video memory is reached only by DVX’s platform layer, so a |
|
The 256 colors of an 8-bit mode (768 bytes, red, green, blue), |
|
The clip rectangle: no call draws outside it. |
-
wgtCanvasGetDisplay(canvas, &d): a canvas’s drawing. It returnsfalsefor 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 |
|
Bevels |
|
Text |
|
Pictures |
|
DVX’s own parts |
|
Pixels |
|
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,
packColordrops 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 |
|---|---|
|
The line height in pixels: lines of text are this far apart. |
|
The rows from the top of a line to the baseline. |
|
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 |
|
The size the font was made at. |
|
The |
|
|
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_UNDERLINEandFONT_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);
-
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, afteronResize, 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 ( |
Nothing: the call asks. |
Whatever the change needs. |
A canvas’s pixels, through its |
|
Paints the canvas at the next frame. |
A widget’s look, not its size |
|
Paints that widget at the next frame, and composites only it. |
A widget’s size or the widgets in a window |
|
Lays the whole window out at once, and paints all of it at the next frame. |
A window without widgets, all of it |
|
Calls |
Part of such a window’s content buffer |
|
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 throughspanFillandspanCopy, string instructions that write 4 bytes at a time.pixelPuttests the pixel size on every pixel, andwgtCanvasSetPixeladds 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 withops->spanFill. -
Text in runs.
drawTextanddrawTextNclip once and draw a whole string; never draw a string adrawCharat 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 aFontStampT). -
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
drawScaledand 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
wxhx 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 , 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 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 |
|---|---|
|
|
|
A pointer to the last part of |
|
The folder part, a root keeping its separator ( |
|
The folder holding |
|
|
|
True for a path that starts with a separator or a drive letter. |
|
True when two paths name the same place by DOS rules: either separator, any case, a trailing separator ignored. |
|
The rest of |
|
True when |
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 |
|---|---|
|
DVX’s own tools and files, and the shipped |
|
The libraries and widgets, a folder for each. |
|
Each program, its help file, and its |
|
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. |
|
The user folder: |
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.APPgetsUSER\APPS\LOCAL\NOTES. -
A program kept in the user folder (a DVX BASIC project run from the IDE, say) gets
APPSand its path in there:USER\PROJECTS\TODO\TODO.APPgetsUSER\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 inDATA, not inSYSTEM. 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 |
|---|---|
|
The value, or |
|
The value as a decimal number, or |
|
True for |
|
Set a key, making the section and the key when they are new; a bool is written as |
|
Remove a key. |
|
The name of a section’s keys in turn, |
|
Write the file the handle was loaded from. |
|
Write it to |
|
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 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 |
|---|---|
|
More to do: call again. |
|
A file to copy or move is there already, or a file to delete is read-only. |
|
Something failed; |
|
Finished. |
|
Stopped by a Cancel answer or by |
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 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.TXTandNOTES.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 diskdiris on, long or 8.3, and returnsNULLor a sentence saying what is wrong (fileOpsValidateNameis 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.
dvxArgAppendadds an argument that way anddvxNextArgreads 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).
10.9. Things to Know
-
shellUserPathandshellDataPathreturn nothing, and when the joined path does not fit inoutSizethey set the buffer to"", never to a path cut short. With buffers ofDVX_MAX_PATHbytes that does not happen in practice. -
fileOpsListDirreturnsfalse, witherrnoset toENOMEMand 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;
| Call | Does |
|---|---|
|
Stop it. |
|
Start it, counting the interval from now. |
|
Whether it runs. |
|
A new interval, counted from now. An interval of 0 or less never fires. |
|
The interval. |
|
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.
-
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’sclock(), 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
-
platformMicros()is a 64-bit count of microseconds since DVX started its timer, always rising, for timing work and pacing loops;tickerused 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, withPLATFORM_MS_TO_TICKS(ms)andPLATFORM_TICKS_TO_MS(ticks)to convert. It is auint32_tthat 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
timeandlocaltimegive 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.
shellAppTaskStartruns 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.
#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
// 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 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
// 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 |
|---|---|---|
|
1 |
Work that should give way. |
|
6 |
Programs' tasks, by default. |
|
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 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 argumentsat the DOS prompt, and another program’sshellRunProgramorshellLoadAppWithArgs(Section 11.6). -
The shell itself: a screen saver gets
/S, and the help viewerfile topicfrom 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, "ed) 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), "ed)) {
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), "ed)) != 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 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
.appfile is loaded and started withargs.folder, when it is notNULL, 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.BATfile (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:
-
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.
-
DVX is normally started by
DVX.COM, a small real-mode program that startsDVX.EXE. Then DVX leaves memory altogether: it writes a batch file that runs the program and exits,DVX.COMruns 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. -
When
DVX.EXEwas 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 |
Title |
The title of one of the program’s visible windows. |
File |
The |
Type |
Task for a program with a task of its own: a main-loop program, or a callback-only one while its |
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 |
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 |
|
The printer the user chose, which every program shares |
Ready-made printing |
|
Printing with DVX’s dialogs, messages, and Printing window, in a call or two |
Dialogs |
|
Asking where to print, how many copies, which pages; the page layout of text |
Jobs |
|
Bytes to a port or a file, with your own handling of printer problems |
Text |
|
Plain text laid out on pages, with headers, footers, and page numbers |
Documents |
|
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 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 |
|---|---|
|
Where output goes, a |
|
The printer model, a |
|
The file printed into when |
|
The page setup for text, a |
|
A serial printer’s speed and how it says it is busy ( |
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.
-
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 (printFilePathgives 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 |
|---|---|---|
|
None |
Any printer, text only. The default. |
|
120 x 72 dpi |
Epson ESC/P 9-pin, black or a four-color ribbon |
|
180 x 180 dpi |
Epson ESC/P 24-pin, black or a four-color ribbon |
|
150 dpi |
HP LaserJet (PCL) |
|
300 dpi |
HP LaserJet III, DeskJet, and later |
|
300 dpi |
HP DeskJet 500C (cyan, magenta, yellow), 550C and later (with black) |
|
300 dpi |
PostScript Level 2; can also draw vector pages (Section 12.7.4) |
|
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
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:
-
It reads the settings, and when the model’s driver is missing it tells the user and returns
false. -
With
askFirst, it shows the Print dialog (Section 12.3.1), with the number of pages the text takes; Cancel returnsfalse. -
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. -
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
pageCountis 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 |
|---|---|
|
The destination chosen, and the file name for |
|
1 or more |
|
The range, from 1; |
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 |
|---|---|
|
Lines on a page, 10 to 200, or 0 for the model’s usual length: |
|
Characters across the page, 20 to 255 (80 by default) |
|
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. |
|
Columns left blank at each side (5 by default) |
|
Columns between tab stops, 1 to 16 (8 by default) |
|
|
|
The header and footer, with the codes below (79 characters at most). The defaults are |
| Code | Becomes |
|---|---|
|
The title ( |
|
The page number, and the number of pages |
|
The date (YYYY-MM-DD) and the time (HH:MM), today’s and now unless |
|
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 |
|---|---|
|
For a problem: the printer is out of paper, off line, or reports an error; it has been busy for |
|
While the printer is busy, after every |
|
When a write during which |
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
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
marginLeftblanks 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 |
|---|---|
|
Dots per inch across and down; they differ on the 9-pin Epsons (120 by 72) |
|
The printable area in dots: 8 by 10 inches |
|
|
|
|
12.7.1. The Cover Page
// 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.
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)opensfamily(NULLor""for the system font) at a size in decipoints, tenths of a point (120is 12 points), in a style ofFONT_STYLE_*bits, underline and strike-through included, for the resolution ofpage. It returnsNULLwhen memory runs out or the size is 0 or less.printFontClosegives it up and acceptsNULL. -
printFontWidth(font, text, len)is the width oflencharacters in dots;printFontHeight(font)the distance from one line to the next, andprintFontAscent(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 atx,yon the page, into the band a band function is filling, incolor(0xRRGGBB), skipping what is outside the band.printFontSpansgives 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 |
|---|---|
|
A line; |
|
A filled box, corners included |
|
An ellipse’s outline or an arc of it, or a filled ellipse |
|
A round dot |
|
Text in a font opened for the page, the printer’s own |
|
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, andprintUiWindoware a whole print each, messages included. -
A job opened with
printJobOpenis yours to close withprintJobClose, which frees it; askprintJobCancelledbefore that. -
A callback that prints runs the event loop from its
idlehook, behind a modal window with a Cancel button. -
Check a page setup of your own with
printPageSetupProblem, and a model withprintModelProblem, before printing. -
Pictures need a model that prints them:
printModelPagesays. Draw pages in bands, from a description worked out beforeprintDocPage. -
On a PostScript printer, clear
vectorin 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 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
Nand two characters worked out from the database’s own extension, soCONTACTS.DBgetsCONTACTS.NJG, andCONTACTS.DBandCONTACTS.DATin 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.
-
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 = WALleaves the database in the rollback journal mode), and no loadable extensions. -
LIKEnever 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
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;
}
| Call | Returns |
|---|---|
|
The value as text; |
|
The same, for the column of that name, matched without regard to case; |
|
The value as a 32-bit integer (text is converted, |
|
The value as a |
|
The number of columns, and a column’s name |
|
|
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.
// 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 |
|---|---|
|
The database file’s path |
|
What to read: a table’s name, or a query, whose first word is |
|
The column that identifies a row, for writing it back; when it is empty or names no column, the first column is used |
|
The text on the bar; when empty, the first successful |
|
For a detail control, the column filtered by the master’s value (Section 13.10.6) |
|
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 |
|
The current row, as |
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
-
wgtDataCtrlMoveFirst,wgtDataCtrlMovePrev,wgtDataCtrlMoveNext, andwgtDataCtrlMoveLastmove it, as the four buttons do. A move past either end leaves the row where it is and setsBOForEOF. -
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, andwgtDataCtrlGetCellText(w, row, col)any row’s by number. Both return""when there is no such row or column.wgtDataCtrlGetRowCount,wgtDataCtrlGetColCount, andwgtDataCtrlGetColNamedescribe 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 nextdvxSqlNext. -
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, andKeyColumnwithwgtSetProp, thenRefresh; bind a DBGrid after theRefresh. -
Give every edit to the Data control with
wgtDataCtrlSetFieldas it happens; show each new current row inonChange, and refresh the grid there. -
Save the current row before the window closes:
wgtDataCtrlUnload, orwgtDataCtrlUpdateand a check of Validate to keep the window open. -
The Data control raises nothing when it fails: read
wgtDataCtrlGetErrorright 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:
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 |
|---|---|
Makes a request ( |
|
Adds a header to send, before the start. |
|
|
A body to send: a copy of |
The reply’s body to a file instead of memory (Section 14.6.1). |
|
Gives up after |
|
Starts the request; false, with the reason in |
|
Does the next piece: |
|
Bytes of the body so far, and the whole, |
|
The reply: its status, a header by name in any case ( |
|
Why the request failed. |
|
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 |
|---|---|
|
|
|
A string’s text; |
|
A number’s value, a |
|
True for |
|
An array’s items or an object’s members; 0 for anything else. |
|
Item or member |
|
A member’s name; |
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.
#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);
}
}
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
netStopandnetRestart), 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 withENETDOWN. TreatENETDOWNas 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, ashttpgetdoes: 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, andjson.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 |
|---|---|---|---|
|
|
The UART driver: COM1 to COM4, interrupt-driven, with ring buffers and flow control. |
Every DVX |
|
|
Connections: a serial line, a modem with a dialer, a secure link, or Telnet, opened and polled the same way. |
Communications |
|
|
Reliable packets over a byte stream, and the encrypted, authenticated secure link over them. |
Communications |
|
|
Hashes, keys, encryption, signatures, and random numbers. |
Every DVX |
|
|
File transfers by XMODEM, XMODEM-1K, YMODEM, and ZMODEM, over any byte stream. |
Communications |
AnsiTerm |
|
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 (rs232SetBaserefuses a port that is open, withRS232_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.
rs232GetUartTypesays 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.
rs232GetIrqsays which it uses, andrs232SetIrqmoves 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.
-
rs232Read(com, buf, len)takes up tolenbytes from the receive ring and returns how many, 0 when there are none. -
rs232WriteBuf(com, data, len)puts up tolenbytes 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. Users232WriteBuf.
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 |
|---|---|
A COM port with the given speed, data bits, parity, stop bits, and flow control. Open at once. |
|
The COM port, then the modem’s init string (it waits for |
|
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 |
|
TCP to |
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 returnsCONN_OK, orCONN_ERR_PARAM,CONN_ERR_PORT, orCONN_ERR_NO_NET(Telnet or a network secure link without Networking).connErrorTextputs a code in words;connStatushas 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.nowMsis the millisecond clock of Section 14.6,PLATFORM_TICKS_TO_MS(platformClock()). -
connRead(c, buf, max)takes up tomaxreceived 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.connPendingsays how many queued bytes have not been sent. -
connState(c)isConnClosedE,ConnOpeningE(dialing, or the key exchange), orConnOpenE.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”), andconnStatusSerial(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.
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
chatat 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 (minicomorscreenon Linux, for example). -
Emulators: two copies of an emulator whose serial ports are joined, such as DOSBox’s
nullmodemserial 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]));
}
}
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.
15.6.2. The Secure Link
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 (NULLor""). Only its SHA-256 is kept. -
secLinkHandshakeStart(link)starts the key exchange, andsecLinkHandshakeStep(link)moves it on, a slice at a time:SECLINK_PENDINGwhile it runs,SECLINK_SUCCESSonce the link is ready, or the error that ended it (SECLINK_ERR_AUTHfor 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 toSECLINK_MAX_PAYLOAD(237) bytes on a channel from 0 to 127, sealed whenencryptis true (which needs a finished key exchange). It returnsSECLINK_ERR_SENDat 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, forsecLinkOpen, 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.
secproxyrelays 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:
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
nowMstakes 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.basandxfer.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.
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 |
|---|---|---|
|
110 ( |
A Windows Sound System card (an AD1848 codec or one like it), tried before the Sound Blaster mode the same card often has. |
|
100 ( |
The Sound Blaster family, from the first Sound Blaster to the Sound Blaster 16, at the port, interrupt, and DMA channels the |
|
90 ( |
A Gravis UltraSound, after a Sound Blaster beside it, which then plays the sampled sound and leaves the UltraSound’s voices to music. |
|
50 ( |
A DAC on the printer port: a Covox, a Disney Sound Source, or a Stereo-on-1. |
|
20 ( |
The PC speaker. It plays tones only, on the timer chip, unless |
|
0 ( |
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:
AudioInfoT member |
Holds |
|---|---|
|
The driver’s short name ( |
|
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. |
|
Voices mixed at once. |
|
A device is running: some sound context is open. |
|
It plays sampled sound; it plays tones on a hardware tone generator (the PC speaker); it has a hardware synthesizer. |
|
It records, and from which inputs (Section 16.12). |
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
-
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_MINtoAUDIO_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 givesAUDIO_ERR_UNSUPPORTEDand a damaged oneAUDIO_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 theAudioFormatTfmt:ratein Hz,bits8 (unsigned) or 16 (signed, little-endian), andchannels1 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 |
pan |
|
pitch |
A speed in 256ths: |
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, ¬es) 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 (
fillisNULL): the program writes frames withaudioStreamWrite(stream, pcm, frames), which takes as many as fit and returns how many.audioStreamSpacesays how many frames of room are left, andaudioStreamQueuedhow 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 toframesframes in the stream’s format intobufand 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
| Volume | Set with | Covers |
|---|---|---|
Master |
|
All sound in DVX. It is the user’s, set on Control Panel’s Sounds page ( |
Context |
|
Everything one context plays; Jukebox’s effects slider. |
Voice |
|
One voice. |
Music |
|
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
-
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] midiat the firstmusicPlay: withauto, 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); withmpu401, an external synthesizer on the MPU-401 port when the port was found and is free (MUSIC_OUT_MPU401), else as withauto. The other choices,fm,software, andsoftwave(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 byaudioWtNoteInit); 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…):audioRecOpenrecords from the card’s microphone, line, or CD input into memory foraudioRecRead, andaudioRecFileinto 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 withAUDIO_ERR_BUSY.audioWavHeaderwrites 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, aDvxSoundEsuch asSoundErrorE), and the default beep withdvxBeep(). -
Settings: the functions Control Panel uses to read and write the
[audio]keys (audioSetting…). -
Drivers:
audioDrv.hdescribes 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.hormusic.hmay 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.
17.1. Starting from the Template
$ 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:
-
gameFrameWaitgives the processor to the rest of DVX until the next frame is due, and returns how many frames went by unseen (Section 17.5). -
musicPumpmakes 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). -
readInputreads the keys and the joystick once (Section 17.3). -
lutSyncnotices a new video mode, and the whole frame is drawn again for it (Section 17.6). -
While the game is running and its window has the focus,
gameUpdatemoves everything as far as the frames that went by call for, anddrawSpritesdraws the result into the game’s own framebuffer. -
presentcopies 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 |
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 |
|---|---|
|
Each axis from |
|
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. |
|
|
|
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);
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);
}
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 leastwidthbyheight, atbppbits per pixel when there is one (0: any depth), raises and focuseswin, and returnsDVX_EXCL_OK, orDVX_EXCL_ERR_MODE(no mode could be set),DVX_EXCL_ERR_BUSY(another window has the screen), orDVX_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
onChangehearsExclusiveSuspendedE; when the window has the focus again the mode is set again and it hearsExclusiveActiveE, beforedvxExclusiveBeginreturns the first time too. Draw the whole frame then: the screen starts black. If the mode cannot be set again, it hearsExclusiveEndedE, 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
onMousegets 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 returnsfalsewhen the game does not have the screen (suspended, or not full screen), and Bounce’spresentthen draws into the window as usual. Its palette is the onedvxExclusiveSetPalette(ac, pal, first, count)gave, whichdvxExclusiveBeginresets to the desktop’s; hencefullChangedsets the whole palette atExclusiveActiveE. 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, withdvxExclusiveBlitOps(ac); Section 9.3) and calldvxExclusiveFlush(ac, rect), orNULLfor all of it.dvxExclusiveWaitRetrace()waits for the vertical retrace before a flush, so the frame is not torn.dvxExclusiveDisplayreturnsNULLwhile the game does not have the screen. -
dvxExclusiveEnd(ac, win)gives the screen back, without anonChangecall. 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 |
|---|---|---|
|
The program’s |
|
|
The folder the |
Its DATA folder: game data, read-only. |
|
The program’s own folder in the user folder. |
Saved games, high scores, options. |
|
The program’s |
|
-
Small data (sounds, a tune, a title picture) can travel inside the
.appas resources, listed inNAME.resasbinaryand read withdvxResOpen(ctx→appPath)anddvxResRead, 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 theMakefile’s `DATAsetting, andmake packageputs them there (Section 16.2). Build their paths withshellDataPath(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\BOUNCEfor Bounce. Make it withshellEnsureUserDir(ctx)before the first write, and build the names withshellUserPath(ctx, "SAVE1.DAT", path, size)(Chapter 10). -
For settings and scores,
prefsLoadandprefsSaveAsread and write INI files safely: a save that fails leaves the old file as it was. -
Use 8.3 file names, and check
platformDiskSpacebefore 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 . 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
| File | What it is |
|---|---|
|
|
|
The functions, and |
|
The public header that callers include, with a version constant, |
|
The libraries to load before this one, one per line; the template lists |
|
The DVX BASIC declarations of the functions BASIC may call. |
|
The library’s help, which DVX adds to its own (Section 18.10). |
|
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 callstextStatAdd, loadstextstat.libfirst. -
Code looks a name up with
dlsym(NULL, …). Every DVX BASIC call to a library works that way (Section 18.9), and so doesdvxLibraryLoaded.
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 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.
TextStatTlives 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_VERSIONwith 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.
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 |
|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Not allowed: return a |
|
|
|
|
|
|
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 ; 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
$ 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 .
DVX.LOGshowstextstat.libloading just before the program. -
Try a BASIC program with
textstat.basin it, such as one that callsCountFileabove. -
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.
19.1. The Widget Template
| File | What it is |
|---|---|
|
|
|
The widget: its class, its C API table, its BASIC interface, and |
|
The public header: the API table’s type, the accessor that finds the table, and a macro for each function. |
|
Resources: |
|
The widget’s developer help, which DVX adds to its own help. |
|
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
#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 |
|---|---|---|
|
|
To draw the widget (Section 19.6). |
|
|
When the window is measured: set |
|
|
After the widget is placed, for a container to place its children. |
|
|
For a press of the left button on the widget (Section 19.7). |
|
|
For each move, and the release, after the widget captured the mouse. |
|
|
For a key that reaches the widget while it has the focus. |
|
|
When it gains or loses the focus, before its |
|
|
For the wheel, before the default handling; |
|
|
When the user types its access key. |
|
|
For |
|
|
For the mouse pointer over the widget: a |
|
|
Every frame, for a class with |
|
|
As the widget is destroyed: free what it holds. |
|
|
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). |
|
|
After the screen changed to another pixel format, |
|
|
The class’s own minimum along one axis ( |
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 |
|---|---|
|
It takes the keyboard focus: Tab stops on it, and its keys come to |
|
While it has the focus, the wheel sends it Up and Down keys. |
|
Its data starts with a |
|
It is clicked as a button is: a press and a release over it, with the |
|
Tab, or Enter, comes to it instead of moving the focus or pressing a window’s default button. |
|
|
|
A container that lays its children out in a row, or that paints them itself. |
19.4. Creating a Widget
// 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, andhare 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.
colorsholds the user’s scheme, packed for the screen (Section 9.5).fgColorandbgColorare the program’s colors for the widget (BASIC’sForeColorandBackColor), 0 when it set none:wgtColorPixel(d, color, fallback)packs one or gives the fallback. The Meter’s own colors are 0x00RRGGBB constants, packed withpackColorRgbon 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, heredrawFocusRect. A widget is disabled when it is, or a container it is in, or its window (Section 5.8):widgetIsEnabledChain(w)(dvxWgtP.h) says, wherew->enabledis 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 |
|---|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
a number or a name |
|
|
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 |
|---|---|
|
The control’s name in BASIC: in a |
|
How BASIC, and |
|
The event the form designer opens when the control is double-clicked; |
|
The prefix of the names the designer gives new controls ( |
|
Other controls can be put inside it. |
|
It shows nothing while the program runs (a Timer); the designer keeps it in a tray of its own. |
|
Hooks for a widget whose properties are not C functions, such as a control written in BASIC; |
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
# 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 |
|---|---|---|
|
|
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). |
|
|
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). |
|
|
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
MaxandMarkin the property sheet, and double-click it for anOverloadhandler. -
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 ) shows the next one, and the window grows or shrinks to fit it. 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 project holds:
| File | What it is |
|---|---|
|
The program. |
|
Its resources: the icon, the texts Program Manager shows, the sayings, and the font. |
|
The sayings, one a line. It is not installed: it becomes the |
|
Cozette, a 13-pixel bitmap font made with |
|
The icon. |
|
The help source: three topics. |
|
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 |
|---|---|
|
Starts a topic. IDs are compared exactly, case included. Use the program’s name as a prefix ( |
|
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. |
|
An entry in the table of contents for this topic (Section 20.2.3). |
|
An entry in the keyword index for this topic; a topic may have any number. |
|
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.
| Directive | Makes |
|---|---|
|
A heading of level 1 (on a colored bar), 2 (underlined), or 3 (plain). |
|
A bulleted list. Each |
|
A block shown exactly as it is written, line for line and never wrapped: a table is columns lined up with spaces. |
|
The same, for code and anything else typed. A word after |
|
A callout box with a colored bar; |
|
A link, on a line of its own, to the topic |
|
A picture (BMP, PNG, JPEG, or GIF), at the left unless another place is given. The compiler copies the picture into the |
|
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
.codeand.table, every line is kept as it is,#and leading periods included: only.endcodeor.endtableends 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
.indexentry too, which Search matches and the Index lists. -
A
.codeor.tableblock still open at the end of a file is closed there, with a warning; a.listor.notesimply 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.
20.2.2. Links
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.
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 |
|---|---|
|
The help file to write. Without it, nothing is written: the sources are only checked. |
|
The folder |
|
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. |
|
Also writes the topic IDs compiled, one a line. |
|
Checks help that is to join another help file, whose topic IDs |
|
Leaves out the progress lines. |
|
Reads more input file names from |
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. |
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:
-
If the program set
onHelpQuery, the shell calls it, withhelpQueryCtxas its argument, so the program can set the topic for what the user is doing now. -
If
helpFileis not empty, the shell opens DVX Help on that file athelpTopic(a buffer ofSHELL_HELP_TOPIC_MAX, 128 bytes; empty for the file’s default topic). A topic the file does not have opens the default topic instead. -
If
helpFileis 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 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 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
LIBSandWIDGETS, the help sources inAPPSwith the.HCFfiles there that name each help file’s sources, and the pictures in each.HCFfile’s picture folder (itsimagedir), by their paths, sizes, and times, with what it recorded the last time (the[help]section ofDVX.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.HCFfile names noimagedir(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.DHSfile underLIBSandWIDGETS, and the DVX BASIC help from its own sources and every.BHSfile underWIDGETSandLIBS. 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
.linkto 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 inDVX.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.
.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:
-
makechecks 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 inNAME.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
makesays so:make packagedoes 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 |
|---|---|
|
A picture file: BMP, PNG, JPEG, or GIF. It is stored as the file is, and decoded when it is shown. |
|
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. |
|
A file of any kind, stored byte for byte. |
|
A |
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 |
|---|---|---|
|
|
Program Manager: the program’s icon, 32 x 32 pixels. |
|
|
Program Manager: the program’s name (up to 63 characters). Without it, Program Manager shows the file name. |
|
|
Program Manager: shown in its status bar for the selected program and in its list view (up to 127 characters). |
|
|
A widget’s: its picture in the DVX BASIC toolbox, and its tooltip there (Chapter 19). |
any |
|
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.
20.5.2. Reading Resources
| Call | Does |
|---|---|
|
Reads the directory of |
|
The directory entry ( |
|
The resource’s data in a block from |
|
A text resource copied into |
|
Frees the handle. |
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 |
|---|---|
|
Replaces all of the file’s resources with those |
|
Lists the files |
|
Lists the resources: name, type, and size. |
|
Writes the data of one resource to |
|
Adds one resource, or replaces the one of that name; |
|
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 |
|---|---|
|
|
|
A key of |
|
The font file, under |
|
The pixel sizes to make for the screen (1 to 127), or |
|
Sizes (or |
|
Sizes made for printing, none of them one of |
|
|
|
Sizes (or |
|
|
|
Only these characters, as hex codes and ranges ( |
|
The weight of a variable font to make. |
|
|
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
-
It lays out
pkg/exactly as the files go into the DVX folder. -
It writes a template,
pkg.ini, from the package settings, and hasdvxpkg buildmakeNAME.dpkfrom the template andpkg/. -
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 |
|---|---|---|
|
|
|
|
|
|
|
|
|
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 |
|---|---|
|
The manifest’s format, 1. A DVX refuses a package of a later format, which needs a newer DVX. |
|
|
|
What Software shows. |
|
|
|
What the package installs, and so the folders it may put files in (Section 21.9). |
|
Shown in Software’s details. |
|
The oldest DVX the package runs on; any when it is missing. |
|
For programs, libraries, widgets, and screen savers: the binary interface version ( |
[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).
| Setting | Key | Default |
|---|---|---|
|
|
The module’s |
|
|
|
|
|
The module’s |
|
|
None: the key is left out. |
|
None: any DVX. The oldest DVX the package runs on, |
|
|
|
None (Section 21.3). |
|
(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 |
|
|
Databases |
|
|
Communications |
|
|
Media |
|
|
DVX BASIC |
|
|
Developer Tools |
|
|
Demos |
|
|
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 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 installonly with-y. -
A package whose ID’s vendor is
kpunchmust 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 shows it.
21.6. Installing
The user installs a package with Software: , 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:
-
Each package’s files are unpacked under scratch names beside where they go, each checked against the manifest.
-
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.
-
The files of an older version that the new one does not have are removed.
-
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.
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.
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.
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 . 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 , 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 (making the account there saves them), and choose and the
.DPKfile. 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/minewith 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
kpunchare 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 |
|---|---|---|
|
|
A program, its help, its |
|
|
A library or a widget. |
|
|
Help files. |
|
|
Fonts for every program (Section 20.6.4). |
|
|
MIDI instrument banks. |
|
|
Color themes and desktop pictures. |
|
|
Sounds. |
|
|
A screen saver: a program, so its package has an |
|
(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
-
VENDORis your own, the same for everything you publish, andPKG_TITLE,PKG_SUMMARY, andPKG_PUBLISHERare set. -
PKG_VERSIONis higher than any version you handed out before. -
The module was built with the SDK of the DVX release it is for.
-
PKG_NEEDSlists every package it needs, DVX’s optional parts included. -
The program’s
name,description, andicon32resources 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.SECfile is backed up. -
dvxpkg checkpasses, 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 |
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. |
#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
| Line | Means |
|---|---|
|
A library or widget was loaded, at the start or when first needed. |
|
A library or widget was not loaded (Section 22.4). |
|
The start is over. |
|
The desktop is up. |
|
A module (a library, a widget, or a program) was loaded at that address. A crash report places a fault by these lines. |
|
A program started: its ID, its kind ( |
|
|
|
A program was refused (Section 22.4). |
|
A program built with another release’s SDK was refused. |
|
|
|
A program ended normally. |
|
The program called |
|
A program was ended by force: End Task, a fault, or |
|
The program ended without freeing everything it allocated (Section 22.6.1). |
|
End Task was asked for while the program’s code was still running in a callback (Section 22.5). |
|
That code was running frames itself, and was abandoned at its next frame. |
|
A main-loop program whose windows had no |
|
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
-
Signalis DJGPP’s number for the signal: 291 forSIGSEGV, 289 forSIGFPE, and 290 forSIGILL. ASIGSEGVis named for the processor’s exception:SIGSEGV (page fault), no memory at the address (aNULLpointer, say);SIGSEGV (general protection fault), an address outside DVX’s memory (a stray pointer far out of range); orSIGSEGV (stack fault). The report calls everySIGFPEa floating point exception, but an integer division by zero raises it too, as here. -
EIPis the address of the instruction that faulted. The other registers are as they were at that instruction: hereEAXholds the dividend, 100, andECXthe divisor, 0. -
EIP is innames the module the instruction is in, its file as theModule: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 inDVX.EXEitself:EIP is in no module (DVX.EXE itself, or memory no module holds). -
The lines after
EFLAGSname the program DVX ended: its ID (theid=of itsShell: loadedline), 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 saysCurrent app ID: 0andCrashed 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 |
“file: missing appDescriptor” |
No |
“file: missing appMain” |
No |
“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 |
“file is already running.” |
The program runs once ( |
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 |
“it was made for a different version of DVX” |
Its ABI stamp differs from DVX’s, or it has none. The log says which: |
“it needs name, which is not installed” |
Its |
“it needs path, which was not loaded” |
A module its |
“it needs files that in turn need it or each other, so none of them can be loaded” |
The |
“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 |
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 |
Runs frames inside a callback: calls |
DVX runs, though the shell’s main loop waits under the callback: programs that end are not cleaned up, and Exit DVX waits. After |
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);
}
22.6.1. Finding a Leak
// 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 |
|---|---|
|
|
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 inline, 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:
-
wgtInvalidatePaintrepaints one widget;wgtInvalidatelays 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 awgtInvalidate: 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.
platformReadFilereads a whole file into memory in one go;freadinto a buffer of many KB beatsfgetcin a loop, though the C library’s buffering makesfgetson a text file acceptable. -
Open a file once, not once per record.
-
Do not
statevery entry of a folder listing: on DOS eachstatsearches the folder again, which makes the listing quadratic.readdirgives most entries' type (platformDirEntryIsDiruses it, and falls back tostatonly 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; aWGT_METHOD_*slot number or the meaning of a slot ofWidgetClassT; 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, wherenameis the module’s file name in lower case without its extension: the loader looks fornameAbiVersionby the file’s name. A renamed file needs its stamp renamed, or the loader finds none. -
A widget class’s
versionisWGT_CLASS_VERSION, the same number;wgtRegisterClassrefuses another and logsWidget: 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 bynewProject.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 towgtGetApi, 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 |
|---|---|---|
None (required) |
The SDK’s folder, the one that holds |
|
None (required) |
What the project makes: |
|
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 |
|
Off |
|
|
Empty |
Files or folders the program reads at run time, too big or too many to be resources. |
|
Empty |
Static libraries ( |
|
Off |
|
|
Empty |
Compiler options added after the SDK’s own: |
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 |
|---|---|---|
|
The DJGPP cross compiler’s installation: the folder that holds |
|
|
The vendor folder the module installs under: |
|
Empty |
The DVX folder, as the build machine sees it, that |
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 |
|---|---|---|
The module’s |
The name Software shows. |
|
|
The version, |
|
The module’s |
A line about the package, shown in Software’s details. |
|
Empty |
Who publishes it. |
|
Empty |
Who wrote it. |
|
Empty |
Its license. The variable is spelled |
|
Empty |
Its web page. |
|
Empty (any) |
The oldest DVX the package runs on, |
|
Empty |
The packages it needs, each |
|
Empty (unsigned) |
The secret key file to sign the package with. |
A.4. Targets
| Target | Does |
|---|---|
|
Builds the module ( |
|
Builds, then lays out |
|
Packages, then copies the contents of |
|
Removes the objects and their |
A.5. The Files It Uses
| Files | Used for |
|---|---|
|
The module’s source: every C file in the folder (C kinds). |
|
The resources appended to the module (C kinds), if the file is there. |
|
The help sources: |
|
The modules a library or widget needs loaded before it, one name a line (Chapter 18), if the file is there. |
|
A BASIC project and its forms, modules, and controls (BASIC kinds). |
The files |
Any of them changed rebuilds the module (C kinds); |
|
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
KIND |
Module | top |
Also in the folder |
|---|---|---|---|
|
|
|
|
|
|
|
The same. |
|
|
|
The help sources, in upper case ( |
|
|
|
The same. |
|
|
|
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 |
|---|---|
|
|
|
|
|
|
|
The SDK’s |
|
The SDK’s compiler options: |
|
The SDK’s |
|
The |
|
|
|
The SDK’s |
|
|
|
|
|
|
|
|
|
The package’s ID and kind (Section A.6), and the list of optional manifest fields and the |
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 callstsYieldon every pass. The quickest port renames the oldmain(CFLAGS = -Dmain=oldMainin theMakefile, before theinclude) and calls it fromappMain, then puts atsYieldin 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 |
|
Strings and memory |
|
Characters |
|
Conversion |
|
Formatted I/O |
|
Character I/O |
|
Files |
|
Low-level I/O |
|
Folders and the file system |
|
Time |
|
Process and environment |
|
Sorting, searching, random numbers |
|
Locale |
|
Jumps and signals |
|
Math |
The |
|
The variable itself |
Modules |
|
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
| Missing | Instead |
|---|---|
|
A comparison, or the arithmetic itself. |
The Bessel and gamma functions: |
Link DJGPP’s math library into the module: |
The complex-number functions and their helpers ( |
Real arithmetic on the two parts. |
|
There are no pipes to other programs. For a wait, a Timer, or a loop that yields (Section B.3). |
|
No module calls DOS or the BIOS directly. DVX’s libraries do that work (Section B.3.3). |
DVX uses no near pointers (Section B.3.3). |
|
|
|
|
Call the library’s functions: DVX loads a library the first time a module uses one of its names. |
|
They are the network library’s, for a module built with |
The |
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
-
errno, the bufferstrtokkeeps its place in, the static results oflocaltime,gmtime,ctime,asctime, andstrerror, and the state ofrandbelong 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 atsYield, 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’ssrandreseeds yourrand: 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 fromctx->appDir,ctx->userDir, and the other folders (Section 10.3). -
The environment is DVX’s, and the DOS programs DVX runs inherit it.
setenvandputenvchange 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
| Code that uses | Uses under DVX |
|---|---|
Threads ( |
Tasks: a main-loop program’s own, or one |
Blocking I/O: a read that waits for data, a |
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. |
|
A Timer widget, for a callback-only program (Section 11.1); on a task, |
|
A Timer widget, or for work that must run at a steady rate however busy DVX is, an interrupt timer: |
|
|
Reading the keyboard: |
Key events (Chapter 8), or the game library’s held keys ( |
POSIX paths: |
DVX’s paths: drive letters, |
|
Full paths built with |
|
|
Cleanup at the end of |
|
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 toDVX.LOG; turnprintfdebugging intodvxLogcalls (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, |
The timer chip, the timer interrupt |
Timers (Section 11.1) and |
The keyboard interrupt, the BIOS keyboard |
Key events, |
The mouse driver |
Mouse events (Section 8.10). |
A UART |
The serial library, |
A sound card, the PC speaker, an FM chip, a MIDI port |
The sound and music libraries, |
The game port |
The joystick library, |
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
| Hardware layer | DVX |
|---|---|
Start-up |
|
Shut-down |
|
Error text, a debug log |
|
Show the back buffer |
Convert through the color table into |
Show it on the whole screen |
|
Whole screen on and off |
|
The palette |
|
A palette per scan line |
One color table per palette, chosen for each row |
Wait for the vertical blank |
|
Frame counter, frame rate |
|
Milliseconds |
|
Held keys |
|
Typed characters |
|
Mouse |
|
Joystick |
|
A periodic interrupt callback |
|
A critical section |
|
Audio start and stop |
|
Sound effect slots |
|
Streamed sound |
|
Tracker modules |
|
Tone and noise voices |
|
Audio work each frame |
|
The read-only data folder |
|
The save folder |
|
Free disk space |
|
Memory |
|
A serial port |
The serial library ( |
|
Ends only the game, after its |
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
onCloseandonPaint.audioOpensucceeds 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
gameTimerAddmade. -
Showing a frame: convert the rows that changed through the color table into the content buffer, scaled, and invalidate only them;
onPaintconverts 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,
dvxExclusiveSetPalettesets 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,
dvxExclusiveWaitRetracewaits for the real one. -
Keyboard: raw key codes are set 1 scan codes, with
KEY_RAW_EXTfor 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
DATAand save folders become paths built at run time, withshellDataPathandshellUserPath.removedeletes a saved game. -
Serial: a COM port has one owner, so the port uses DVX’s serial library rather than programming the UART.
-
exitends only the game. Functions given toatexitrun then, and at the game’s normal end, so a library’satexitcleanup 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(withLIBS; 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: theDATAfolder anduserDir, 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
ExclusiveSuspendedEby 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
#
- 486, 3.1. The Machine, 9.11. What Is Fast on a 486, 22.8. Performance on a 486
- 8-bit desktop, 17.6.1. The Game’s Palette and the Color Table
- 8.3 names, 10.8. Long File Names
- 86Box, 1.6. Installing and Running, 22.7. Testing on Emulators and Real PCs, 22.7.2. 86Box
A
- ABI, 3.11. The Binary Interface, 22.9. The Binary Interface Rules
- abort, 3.10. Faults, B.3.1. Ending, Exiting, and Signals
- in games, 17.10. Packaging and Ending
- ACCEL_ALT, 6.7. Shortcut Keys
- ACCEL_CTRL, 6.7. Shortcut Keys
- ACCEL_SHIFT, 6.7. Shortcut Keys
- accelerators, 6.7. Shortcut Keys
- and controls, 6.7. Shortcut Keys
- widgets, 5.10. Access Keys
- accelKey, 5.10. Access Keys
- AccelTableT, 6.7. Shortcut Keys
- access keys, 5.10. Access Keys
- Add-ons, 18.5. How DVX Loads a Library
- add-ons
- widgets, 19.13. A Program That Uses It
- Add-ons box, 22.4. Refused Modules
- addr2line, 22.3.2. Finding the Faulting Line
- address space, 3.1. The Machine
- align, 5.4.5. Padding, Spacing, and Alignment
- ANSI escape sequences, 15.4.3. Line Ends and Colors
- AnsiTerm, 15.5. The Terminal Control
- ANSITERM_EVT_BELL, 15.5. The Terminal Control
- ANSITERM_EVT_MUSIC, 15.5. The Terminal Control
- ANSITERM_EVT_SEND, 15.5. The Terminal Control
- anti-aliasing, 9.6.5. Smoothed Text
- API tables, 19.9. The API Table
- AppContextT, 2.4. Creating the Window, 3.3. The Shell and the Two Contexts
- display, 4.2. Creating a Window, 9.3. DisplayT and the Clip Rectangle
- keyModifiers, 8.2.1. Modifiers
- appDescriptor, 2.2. The Descriptor
- AppDescriptorT, 2.2. The Descriptor
- Application Error, 3.10. Faults
- appMain, 2.3. appMain and the Program’s Context
- porting, B.1. The Shape of a Program
- return value, 4.12. Ending the Program
- appShutdown, 2.9. How the Program Ends, 4.12. Ending the Program, 10.5.1. Saving When the Window Closes
- at End Task, 22.6.2. What DVX Releases When a Program Ends
- architecture, 3. How DVX Runs Your Code
- args
- porting, B.1. The Shape of a Program
- assert, 22.3.5. Errors That Do Not Fault, B.3.1. Ending, Exiting, and Signals
- ASSOC.INI, 10.7. File Associations
- associations, 10.7. File Associations
- atexit, 3.10. Faults, B.3.1. Ending, Exiting, and Signals
- at program end, 22.6.2. What DVX Releases When a Program Ends
- audience, Who This Book Is For
- audio.lib, 16. Sound and Music
- AUDIO_END_DROPPED, 16.3. Samples and Voices
- AUDIO_ERR_NO_VOICE, 16.3. Samples and Voices
- AUDIO_ERR_VOICE, 16.3. Samples and Voices
- AUDIO_MILLIHZ_PER_HZ, 16.5. Note Queues
- AUDIO_OK, 16.2.1. Opening Sound
- AUDIO_PAN_LEFT, 16.3. Samples and Voices
- AUDIO_PAN_RIGHT, 16.3. Samples and Voices
- AUDIO_VOLUME_MAX, 16.3. Samples and Voices
- AUDIO_WAVE_NOISE, 16.4. Tones
- audioClose, 16.2.1. Opening Sound
- AudioCtxT, 16.2.1. Opening Sound
- audioDrv.h, 16.12. The Rest of the Sound Library
- AudioEndE, 16.3.1. When a Sound Ends
- AudioEndFnT, 16.3.1. When a Sound Ends
- audioErrorText, 16.2.1. Opening Sound
- AudioFillFnT, 16.6. Streams
- audioFmAlloc, 16.10. The FM Chip
- audioFmFree, 16.10. The FM Chip
- audioFmGetInfo, 16.10. The FM Chip
- audioFmRawAcquire, 16.10. The FM Chip
- audioFmWrite, 16.10. The FM Chip
- AudioFormatT, 16.3. Samples and Voices
- audioGetInfo, 16.1. The Sound Hardware
- audioGetStats, 16.1. The Sound Hardware
- audioGetVolume, 16.7. Volume
- AudioInfoT, 16.1. The Sound Hardware
- audioMidiAcquire, 16.11. The MIDI Port
- audioMidiGetInfo, 16.11. The MIDI Port
- audioMidiInOpen, 16.11. The MIDI Port
- audioMidiInRead, 16.11. The MIDI Port
- AudioMidiMsgT, 16.11. The MIDI Port
- audioMidiPut, 16.11. The MIDI Port
- audioMidiRelease, 16.11. The MIDI Port
- audioNotesAdd, 16.5. Note Queues
- audioNotesClose, 16.5. Note Queues
- audioNotesOpen, 16.5. Note Queues
- audioNotesQueued, 16.5. Note Queues
- AudioNotesT, 16.5. Note Queues
- audioOpen, 16.2.1. Opening Sound
- audioPercentToVolume, 16.7. Volume
- audioPlay, 16.3. Samples and Voices
- audioPump, 16.13. Keeping Sound Fed
- audioRecFile, 16.12. The Rest of the Sound Library
- audioRecOpen, 16.12. The Rest of the Sound Library
- audioSampleCreate, 16.3. Samples and Voices
- audioSampleLoad, 16.3. Samples and Voices
- audioSampleLoadMem, 16.3. Samples and Voices
- AudioSampleT, 16.3. Samples and Voices
- audioSetEndFn, 16.3.1. When a Sound Ends
- audioSetMasterVolume, 16.7. Volume
- audioSetVolume, 16.7. Volume
- AudioStatsT, 16.1. The Sound Hardware
- audioStreamClose, 16.6. Streams
- audioStreamEnd, 16.6. Streams
- audioStreamFlush, 16.6. Streams
- audioStreamOpen, 16.6. Streams
- audioStreamQueued, 16.6. Streams
- audioStreamSpace, 16.6. Streams
- AudioStreamT, 16.6. Streams
- audioStreamVoice, 16.6. Streams
- audioStreamWrite, 16.6. Streams
- audioTone, 16.4. Tones
- audioVoiceIsPlaying, 16.3. Samples and Voices
- audioVoicePause, 16.3. Samples and Voices
- audioVoiceSetPan, 16.3. Samples and Voices
- audioVoiceSetPitch, 16.3. Samples and Voices
- audioVoiceSetVolume, 16.3. Samples and Voices
- audioVoiceStop, 16.3. Samples and Voices
- AudioWaveE, 16.4. Tones
- audioWtAlloc, 16.12. The Rest of the Sound Library
- auto-cascade, 4.2. Creating a Window
B
- backbuffer, 3.8. The Display
- backdrop, 9.2.1. Building the Window
- basHold, 18.7. State That Programs Share
- basHoldEnd, 18.7. State That Programs Share
- BASIC
- C types, 18.9.1. Numbers and Strings Across the Boundary
- calling C, 18.9. Giving DVX BASIC the Library
- colors, 19.10. The BASIC Interface
- common properties, 19.10. The BASIC Interface
- controls from C, 19.10. The BASIC Interface
- type suffixes, 18.9. Giving DVX BASIC the Library
- basrt, 19.15. Using a Control Written in DVX BASIC
- BEGIN, 13.5. Transactions
- Bessel functions, B.2.1. What Is Not There
- BEVEL_RAISED, 9.4. The Drawing Calls
- BEVEL_SUNKEN, 9.4. The Drawing Calls
- BevelStyleT, 9.4. The Drawing Calls
- bgColor, 5.13. Tooltips, Colors, and Fonts
- binary interface, 3.11. The Binary Interface, 22.9. The Binary Interface Rules
- and packages, 21.7. Versions and Updates
- changes, 22.9. The Binary Interface Rules
- exported names, 22.9. The Binary Interface Rules
- libraries, 18.6. The Binary Interface
- widget APIs, 5.2. Widget Headers and Their APIs, 19.9. The API Table
- your own, 22.9. The Binary Interface Rules
- BINARY STRING, 18.9.1. Numbers and Strings Across the Boundary
- BitmapFontT, 9.6.1. What a Font Is
- bitmaps
- off-screen, 9.8. Off-Screen Bitmaps
- BlitOpsT, 9.3. DisplayT and the Clip Rectangle
- blocking, 3.5. Cooperative Tasks, 14.4. Waiting Without Stopping DVX
- replacing, B.3. What to Replace
- secure link, 15.6.2. The Secure Link
- BMP files, 9.7.1. Loading Pictures
- boot sequence, 3.2. Modules and the Loader
- busy pointer, 8.11. Mouse Pointers
- Button, 5.6.1. Labels and Buttons
- buttons
- default, 5.5.5. The Buttons
C
- C library, 3.2. Modules and the Loader, B.2. The C Library
- missing functions, B.2.1. What Is Not There
- shared state, B.2.2. One C Library for Everything
- calcCenteredText, 9.6.2. Measuring Text
- calcMinH, 19.5. Minimum Size and Layout
- calcMinW, 19.5. Minimum Size and Layout
- callbacks, 3.4. Two Kinds of Program
- destroying widgets, 5.7. Widget Events, 19.8. Firing Events
- never block, 14.4. Waiting Without Stopping DVX
- rules for, 4.3. Window Callbacks
- widgets, 5.7. Widget Events
- cancel button, 7.2. How a Dialog Box Runs, 7.7.1. Default and Cancel Buttons in Any Window
- Canvas, 9.2.1. Building the Window
- canvas
- drawing calls, 9.2.4. The Canvas’s Calls
- mouse callback, 9.2.2. Drawing with the Mouse
- canvas/canvas.h, 9.2.1. Building the Window
- CANVAS_BORDER_WIDTH, 9.2.1. Building the Window
- CFLAGS, 1.5. Building, A.1. Project Settings
- a library’s header, 18.8. A C Program That Uses It
- -g, 22.3.2. Finding the Faulting Line
- channels
- secure link, 15.6.2. The Secure Link
- chdir, B.2.2. One C Library for Everything
- Checkbox, 5.6.3. Check Boxes and Radio Buttons
- chrome
- CHROME_MENU_HEIGHT, 17.2.1. The Game’s Window
- CHROME_TOTAL_SIDE, 4.2. Creating a Window, 17.2.1. The Game’s Window
- CHROME_TOTAL_TOP, 4.2. Creating a Window
- cleanup hooks, 18.7. State That Programs Share
- clip rectangle, 9.3.1. The Clip Rectangle
- clipboard, 6.5. Enabling and Graying Items, 6.10. The Rest of TinyEdit, 8.12. The Clipboard
- clocks, 11.1.1. Clocks
- closing a window
- unsaved changes, 7.3.2. Asking to Save Changes
- code page 437, 9.6.1. What a Font Is
- code style, Conventions
- color cycling, 17.6.4. Palette Animation
- colors, 9.5. Colors and Pixel Formats
- BASIC, 19.10. The BASIC Interface
- choosing, 7.6. Colors and Fonts
- keeping as RGB, 9.2.3. Choosing the Pen
- pixel formats, 3.8. The Display
- scheme, 9.5. Colors and Pixel Formats
- terminal, 15.4.3. Line Ends and Colors
- widgets, 5.13. Tooltips, Colors, and Fonts
- ColorSchemeT, 9.5. Colors and Pixel Formats
- ComboBox, 5.6.4. Lists: ListBox, Dropdown, and ComboBox
- command IDs, 6.1. The Example: TinyEdit
- command line, 11.5. The Command Line
- COMMIT, 13.5. Transactions
- communications, 15. Serial Ports, Modems, and Secure Links
- Communications
- part of DVX, 15.1. The Layers
- compiler
- library calls, B.2.1. What Is Not There
- compiler flags, 1.5. Building
- compiler helpers, B.2. The C Library
- compositor, 3.8. The Display
- conn.h, 15.3. Connections
- connCanBreak, 15.3. Connections
- connClose, 15.3. Connections
- connConfigDefaults, 15.3. Connections
- ConnConfigT, 15.3. Connections
- connCreate, 15.3. Connections
- connDestroy, 15.3. Connections
- connect, 14.3. Sockets
- connection library, 15.3. Connections
- connErrorText, 15.3. Connections
- ConnModemE, 15.3. Connections
- connOpen, 15.3. Connections
- connPending, 15.3. Connections
- connPoll, 15.3. Connections
- in a loop, 15.4.2. The Loop
- connRead, 15.3. Connections
- ConnSecureE, 15.3. Connections
- connSendBreak, 15.3. Connections
- ConnSerialE, 15.3. Connections
- connState, 15.3. Connections
- ConnStateE, 15.3. Connections
- connStatus, 15.3. Connections
- connStatusSerial, 15.3. Connections
- ConnT, 15.3. Connections
- ConnTelnetE, 15.3. Connections
- connTypeAvailable, 15.3. Connections
- connWrite, 15.3. Connections
- console, B.3.2. The Console
- constructors, 18.5. How DVX Loads a Library
- containers, 5.3. Containers
- content area, 4.2. Creating a Window
- content buffers, 3.8. The Display
- contentBuf, 17.6.3. Presenting a Frame
- contentPitch, 17.6.3. Presenting a Frame
- context help, 20.3. Context Help
- context menus, 6.6. Context Menus
- contexts, 3.3. The Shell and the Two Contexts
- controls
- written in BASIC, 19.15. Using a Control Written in DVX BASIC
- convertColor, 9.5. Colors and Pixel Formats
- convertPixels, 9.5. Colors and Pixel Formats
- cooperative multitasking, 3.5. Cooperative Tasks
- coordinates
- drawing, 9.3. DisplayT and the Clip Rectangle
- counterOf, 18.7. State That Programs Share
- CR LF, 15.4.3. Line Ends and Colors
- crash reports
- reading, 22.3.1. Reading a Crash Report
- crash-safe writes, 10.4.1. Writing a File Safely
- crashes, 3.10. Faults, 22.3. Crash Reports
- CRC-16, 15.6.1. The Packet Layer
- credits, 11.4. Tasks and Their Scheduler
- critical errors, 10.2. Paths
- cross compiler, 1.2. The Host and the Cross Compiler
- cryptography library, 15.7. The Cryptography Library
- Ctrl+Esc, 11.9. The Task Manager
- current directory, B.2.2. One C Library for Everything
- current folder, 10.2. Paths
- currentAppId, 3.3. The Shell and the Two Contexts
- CURSOR_ARROW, 8.11. Mouse Pointers
- cursors, 8.11. Mouse Pointers, 13.6. Queries and Cursors
- CWSDPMI, 3.1. The Machine
D
- DATA, A.1. Project Settings
- Data control, 13.10. The Data Control
- DATA folder, 10.3.2. The DATA Folder, 16.2. The Jukebox Program, 21.1. make package
- DataActionE, 13.10.3. Changing Rows
- DatabaseName, 13.10.1. Telling It What to Read
- databases, 13. Databases
- closing, 13.9. Closing a Database
- editing, 13.10.3. Changing Rows
- errors, 13.7. Errors
- exporting, 13.6. Queries and Cursors
- files on DOS, 13.2. Opening a Database
- long statements, 13.8. Long Statements
- opening, 13.2. Opening a Database
- parameters, 13.4. Values in Statements
- queries, 13.6. Queries and Cursors
- statements, 13.3. Running Statements
- Databases part, 13. Databases
- dataCtrl.h, 13.10. The Data Control
- DBGrid, 13.11. The DBGrid
- dbGrid.h, 13.10. The Data Control
- DCD, 15.2. The UART Driver
- debugging, 22. Debugging and Performance
- crash reports, 3.10. Faults, 22.3. Crash Reports
- finding the faulting line, 22.3.2. Finding the Faulting Line
- hung programs, 22.5. Hung Programs
- layout, 5.4.6. When the Layout Runs
- memory, 22.6. Memory and Leaks
- refused modules, 22.4. Refused Modules
- the log, 2.7.1. The Log, 22.2. The Log
- DECLARE LIBRARY, 18.9. Giving DVX BASIC the Library
- .default, 20.2.1. The Source Format
- default button, 7.2. How a Dialog Box Runs, 7.7.1. Default and Cancel Buttons in Any Window
- .dep files, 3.2. Modules and the Loader, 18.5.1. The .dep File, 21.1. make package
- and PKG_NEEDS, 21.3. Dependencies
- dependencies, 18.5.1. The .dep File
- desktop sounds, 16.12. The Rest of the Sound Library
- DetailField, 13.10.6. Master and Detail
- .DFN files, 9.6.6. Fonts a Program Carries, 20.6. Fonts
- DHCP
- waiting for, 14.4. Waiting Without Stopping DVX
- .dhs files, 20.2.1. The Source Format
- dialog boxes, 7. Dialog Boxes
- color, 7.6. Colors and Fonts
- custom, 7.7. Dialog Boxes of Your Own
- default and cancel buttons, 5.5.5. The Buttons
- example program, 7.1. The Dialogs Program
- file dialogs, 7.5. File and Folder Dialogs
- font, 7.6. Colors and Fonts
- input boxes, 7.4. Asking for Text, a Number, or a Choice
- keyboard, 7.2. How a Dialog Box Runs
- message boxes, 7.3. Message Boxes
- modal, 2.8. The Callbacks, 7.2. How a Dialog Box Runs
- nested loop, 3.6. The Event Loop
- Print, 12.3.1. The Print Dialog
- dirty rectangles, 3.8. The Display
- display, 3.8. The Display
- DisplayT, 3.8. The Display, 9.1. Where a Program Draws, 9.3. DisplayT and the Clip Rectangle
- dithering, 12.7.2. Drawing a Page in Bands
- DJGPP, 1.2. The Host and the Cross Compiler
- porting to, B. Porting C Code to DVX
- DJGPP_PREFIX, 1.2. The Host and the Cross Compiler, A.2. Build Settings
- dlsym, 18.4. What a Library Exports
- DECLARE LIBRARY, 18.9. Giving DVX BASIC the Library
- documents
- opening at start, 10.7. File Associations
- dollar sign suffix, 18.9. Giving DVX BASIC the Library
- DOS, 3.1. The Machine
- DOS programs, 11.7. Running DOS Programs
- file names, 10.8. Long File Names
- limits, 11.7. Running DOS Programs
- network, 14.3. Sockets
- DOSBox, 1.6. Installing and Running, 22.7. Testing on Emulators and Real PCs, 22.7.1. DOSBox
- double click, 8.10.1. Mouse Events in Widgets
- downloads, 14.6.1. Downloading to a File
- checking, 14.6.1. Downloading to a File
- .DPK files, 21. Packaging and Publishing
- DPMI, 3.1. The Machine
- drag and drop, 8.13. Dragging and Dropping
- drawBevel, 9.4. The Drawing Calls
- drawFocusRect, 19.6. Painting
- drawing, 9. Drawing, Images, and Fonts
- calls, 9.4. The Drawing Calls
- DisplayT, 9.3. DisplayT and the Clip Rectangle
- where, 9.1. Where a Program Draws
- widgets, 19.6. Painting
- drawScaled, 9.7.2. Drawing and Scaling Pictures
- drawText, 9.4. The Drawing Calls
- drivers
- sound, 16.1. The Sound Hardware
- drives, 10.2. Paths
- Dropdown, 5.5.3. Frames and Fields, 5.6.4. Lists: ListBox, Dropdown, and ComboBox
- DTR, 15.2. The UART Driver
- DVX /RUN=, 1.6. Installing and Running
- DVX BASIC
- games, 17.11. Games in DVX BASIC
- PictureBox, 9.2.4. The Canvas’s Calls
- DVX C Library Reference, How This Book Is Organized
- DVX folder, 10.3. Where a Program’s Files Go
- DVX Help, 20.2. Help Files
- DVX SDK, Before You Start
- DVX.COM, 11.7. Running DOS Programs
- DVX.EXE, 3.2. Modules and the Loader
- exports, B.2. The C Library
- DVX.INI, 10.5. Settings Files
- audio settings, 16.1. The Sound Hardware
- help, 18.10. The Library’s Help
- network, 14.1. The Network Under DVX
- printer, 12.2. The Printer and Its Settings
- DVX.LOG, 1.6. Installing and Running, 2.7.1. The Log, 4.12. Ending the Program, 22.2. The Log
- help rebuild, 20.4. Help for Widgets and Libraries
- loading libraries, 18.5. How DVX Loads a Library
- loading widgets, 19.14. Installing and Testing
- location, 22.2. The Log
- messages, 22.2.1. What DVX Writes There
- refused modules, 18.5. How DVX Loads a Library
- refused widget APIs, 5.2. Widget Headers and Their APIs
- size, 22.2. The Log
- DVX_ABI_STAMP, 3.11. The Binary Interface, 18.6. The Binary Interface, 22.9. The Binary Interface Rules
- widgets, 19.2. The Module
- DVX_ABI_VERSION, 3.11. The Binary Interface, 22.9. The Binary Interface Rules
- DVX_ARG_QUOTE, 11.5. The Command Line
- DVX_BUTTON_BOX_MAX, 7.3.1. Buttons of Your Own
- DVX_DATA_DIR, 10.3.2. The DATA Folder
- DVX_DIR, 1.6. Installing and Running, A.2. Build Settings
- DVX_DOS_TAIL_MAX, 11.7. Running DOS Programs
- DVX_EXCL_OK, 17.7. The Whole Screen
- DVX_FONT_DLG_FIXED, 7.6. Colors and Fonts
- DVX_HUNG_APP_MS, 3.5. Cooperative Tasks, 11.2. Long Work, 22.5. Hung Programs
- DVX_IMAGE_PATTERNS, 9.7.1. Loading Pictures
- DVX_MAX_PATH, 10.2. Paths
- DVX_MEM_SYSTEM, 18.7. State That Programs Share
- DVX_PATH_SEP, 10.2. Paths
- DVX_RES_BINARY, 20.5.1. The .res File
- DVX_RES_FONT, 20.5.1. The .res File
- DVX_RES_ICON, 20.5.1. The .res File
- DVX_RES_TEXT, 20.5.1. The .res File
- DVX_RGB, 7.6. Colors and Fonts, 9.5. Colors and Pixel Formats
- DVX_SAVE_YES, 7.3.2. Asking to Save Changes
- DVX_SYM, 18.4. What a Library Exports
- dvxAccelFormat, 6.3. Building a Menu Bar
- dvxAddAccel, 6.7. Shortcut Keys
- dvxAnsiTermApi, 15.4.1. The Window
- dvxAnsiTermExApi, 15.5. The Terminal Control
- dvxArgAppend, 10.8. Long File Names, 11.5. The Command Line, 20.3.1. Opening Help from Code
- dvxBas.h, 18.7. State That Programs Share
- dvxBeep, 16.12. The Rest of the Sound Library
- dvxBufferToRgb, 9.7.3. Saving Pictures
- dvxButtonBox, 7.3.1. Buttons of Your Own, 10.6.2. Copying, Moving, and Deleting
- dvxCascadeWindows, 4.9. Several Windows in One Program
- dvxChoiceDialog, 7.4. Asking for Text, a Number, or a Choice
- dvxClipboardClear, 8.12. The Clipboard
- dvxClipboardCopy, 8.12. The Clipboard
- dvxClipboardGet, 6.5. Enabling and Graying Items, 8.12. The Clipboard
- dvxCloseMenu, 6.5. Enabling and Graying Items
- dvxColorDialog, 7.6. Colors and Fonts
- dvxContentDisplay, 4.11. Windows Without Widgets, 9.3. DisplayT and the Clip Rectangle, 9.9. Drawing in a Window Without Widgets
- dvxCreateAccelTable, 6.7. Shortcut Keys
- dvxCreateWindow, 2.4. Creating the Window, 4.2. Creating a Window
- dvxCreateWindowCentered, 2.4. Creating the Window, 4.2. Creating a Window
- dvxCur.h, 8.11. Mouse Pointers
- dvxDataCtrlApi, 13.10. The Data Control
- dvxDbGridApi, 13.10. The Data Control
- dvxDestroyWindow, 2.8. The Callbacks, 4.3.3. Closing: onClose
- dvxDialogAddField, 7.7. Dialog Boxes of Your Own
- dvxDialogAddOkCancel, 7.7. Dialog Boxes of Your Own
- dvxDialogCreate, 7.7. Dialog Boxes of Your Own
- dvxDialogEnd, 7.7. Dialog Boxes of Your Own
- DvxDialogOkFnT, 7.7. Dialog Boxes of Your Own
- dvxDialogRun, 7.7. Dialog Boxes of Your Own
- dvxDlg.h, 7. Dialog Boxes
- dvxDragCursorSet, 8.13. Dragging and Dropping
- dvxDragFeedbackHide, 8.13. Dragging and Dropping
- dvxDragImageShow, 8.13. Dragging and Dropping
- dvxDragOutlineShow, 8.13. Dragging and Dropping
- dvxDraw.h, 9.4. The Drawing Calls
- dvxErrorBox, 7.3. Message Boxes
- dvxExclusiveBegin, 11.8. Screen Savers, 17.7. The Whole Screen
- dvxExclusiveBlitOps, 17.7. The Whole Screen
- dvxExclusiveDisplay, 17.7. The Whole Screen
- dvxExclusiveEnd, 17.7. The Whole Screen
- dvxExclusiveFlush, 17.7. The Whole Screen
- dvxExclusiveMirror, 17.7. The Whole Screen
- dvxExclusivePresent8, 17.7. The Whole Screen
- dvxExclusiveSetPalette, 17.7. The Whole Screen
- dvxExclusiveWaitRetrace, 17.7. The Whole Screen
- dvxFileDialog, 7.5. File and Folder Dialogs
- dvxFitWindow, 2.7. Fitting the Window and Returning, 4.5. Fitting a Window to Its Controls, 5.4.6. When the Layout Runs
- dvxFitWindowH, 2.7. Fitting the Window and Returning, 4.5. Fitting a Window to Its Controls, 5.4.6. When the Layout Runs
- dvxFitWindowW, 4.5. Fitting a Window to Its Controls, 5.4.6. When the Layout Runs
- dvxFont8x16, 9.6.1. What a Font Is
- dvxFontAddFile, 9.6.6. Fonts a Program Carries, 20.6.3. A Font the Program Carries
- dvxFontAddMemory, 20.6.3. A Font the Program Carries
- DvxFontChoiceT, 7.6. Colors and Fonts
- dvxFontClose, 9.6.3. Families, Sizes, and Styles
- dvxFontDialog, 7.6. Colors and Fonts
- dvxFontFamilyCount, 9.6.3. Families, Sizes, and Styles
- dvxFontFamilyFixed, 9.6.3. Families, Sizes, and Styles
- dvxFontFamilyName, 9.6.3. Families, Sizes, and Styles
- dvxFontFamilyOf, 9.6.3. Families, Sizes, and Styles, 20.6.3. A Font the Program Carries
- dvxFontLicence, 20.6.2. Licenses
- dvxFontOpen, 9.6.3. Families, Sizes, and Styles
- dvxFontSizes, 9.6.3. Families, Sizes, and Styles
- dvxFreeAccelTable, 6.7. Shortcut Keys
- dvxFreeImage, 9.7.1. Loading Pictures, 20.5.2. Reading Resources
- dvxGetBlitOps, 9.3. DisplayT and the Clip Rectangle
- dvxGetColors, 9.5. Colors and Pixel Formats
- dvxGetDisplay, 4.2. Creating a Window
- dvxGetFocusedWindow, 20.3. Context Help
- dvxGetFont, 9.6.1. What a Font Is
- dvxHasExt, 10.2. Paths
- DVXHELP.HLP, 20.4. Help for Widgets and Libraries
- dvxHideWindow, 4.7. Raising, Lowering, Hiding, and Showing
- dvxhlpc, 1.5. Building, 20.2.5. Compiling with dvxhlpc
- DVXHLPC.EXE, 20.2.5. Compiling with dvxhlpc
- dvxIdleMs, 11.1.1. Clocks
- dvxImageInfo, 9.7.1. Loading Pictures
- dvxInfoBox, 2.8. The Callbacks, 7.3. Message Boxes
- dvxInputBox, 7.4. Asking for Text, a Number, or a Choice
- dvxIntInputBox, 7.4. Asking for Text, a Number, or a Choice
- dvxInvalidateRect, 4.11. Windows Without Widgets, 9.9. Drawing in a Window Without Widgets
- in games, 17.6.3. Presenting a Frame
- dvxInvalidateWindow, 4.11. Windows Without Widgets, 9.9. Drawing in a Window Without Widgets
- DvxKindE, 10.3.3. Where Not to Write
- dvxLibraryLoaded, 18.4. What a Library Exports, 21.3.1. DVX’s Optional Parts
- dvxLoadImage, 9.7.1. Loading Pictures
- dvxLoadImageAlpha, 9.7.2. Drawing and Scaling Pictures
- dvxLoadImageFromMemory, 9.7.1. Loading Pictures
- dvxLog, 2.7.1. The Log, 22.2. The Log
- cost, 22.2. The Log
- dvxLowerWindow, 4.7. Raising, Lowering, Hiding, and Showing
- dvxMalloc, 3.9. Memory
- dvxMaximizeWindow, 4.8. Minimizing, Maximizing, and Restoring
- dvxMemAppIdPtr, 18.7. State That Programs Share
- dvxMemGetAppUsage, 3.9. Memory, 22.6. Memory and Leaks
- dvxMemSetApp, 18.7. State That Programs Share
- dvxMessageBox, 7.3. Message Boxes
- dvxMeterApi, 19.9. The API Table
- dvxMinimizeWindow, 4.8. Minimizing, Maximizing, and Restoring
- dvxModalBegin, 4.10. Modal Windows, 7.2. How a Dialog Box Runs, 7.7.2. A Modal Window That Does Not Wait
- dvxModalEnd, 4.10. Modal Windows, 7.7.2. A Modal Window That Does Not Wait
- dvxMoveWindow, 4.6. Moving and Resizing from Code
- dvxNextArg, 11.5. The Command Line, B.1. The Shape of a Program
- dvxpkg, 21.2. The Package File
- build, 21.9. Other Kinds of Package
- check, 21.2. The Package File
- info, 21.2. The Package File
- install, 21.6. Installing
- keygen, 21.4. Signing
- sign, 21.4. Signing
- verify, 21.4. Signing
- DVXPKG.EXE, 21.6. Installing
- dvxPlaySound, 16.12. The Rest of the Sound Library
- dvxPrefs.h, 10.5. Settings Files
- dvxPromptSave, 6.10. The Rest of TinyEdit, 7.3.2. Asking to Save Changes
- dvxRaiseWindow, 4.7. Raising, Lowering, Hiding, and Showing
- dvxRegisterHotkey, 8.8. Shortcuts That Work Everywhere
- dvxRemoveAccel, 6.7. Shortcut Keys
- dvxRequestWindowClose, 4.3.3. Closing: onClose
- dvxres, 1.5. Building, 20.5.3. The dvxres Tool
- deps, 20.5.1. The .res File
- dvxResAppend, 20.5.2. Reading Resources
- dvxResClose, 2.8. The Callbacks, 20.5.2. Reading Resources
- dvxResFind, 20.5.2. Reading Resources
- DvxResHandleT, 20.5.2. Reading Resources
- dvxResizeWindow, 4.6. Moving and Resizing from Code
- dvxResLoadData, 20.5.2. Reading Resources
- dvxResLoadIcon, 4.4. Titles and Icons, 9.7.1. Loading Pictures, 20.5.2. Reading Resources
- dvxResLoadIconData, 20.5.2. Reading Resources
- dvxResLoadText, 2.8. The Callbacks, 20.5.2. Reading Resources
- dvxResOpen, 2.8. The Callbacks, 20.5.2. Reading Resources
- dvxResRead, 2.8. The Callbacks, 20.5.2. Reading Resources
- dvxResReadText, 2.8. The Callbacks, 20.5.2. Reading Resources
- dvxResRemove, 20.5.2. Reading Resources
- dvxRestoreWindow, 4.8. Minimizing, Maximizing, and Restoring
- dvxRunDos, 11.7. Running DOS Programs
- dvxSaveImage, 9.7.3. Saving Pictures
- dvxScreenshot, 9.7.3. Saving Pictures
- dvxSetBusy, 8.11. Mouse Pointers, 9.7.1. Loading Pictures, 11.2. Long Work
- dvxSetMenuCaption, 6.5. Enabling and Graying Items
- dvxSetMenuEnabled, 6.5. Enabling and Graying Items
- dvxSetMenuVisible, 6.5. Enabling and Graying Items
- dvxSetTitle, 4.4. Titles and Icons
- dvxSetWindowButtons, 4.10. Modal Windows, 5.5.5. The Buttons, 7.7.1. Default and Cancel Buttons in Any Window, 20.6.2. Licenses
- dvxSetWindowEnabled, 4.7. Raising, Lowering, Hiding, and Showing
- dvxSetWindowIcon, 4.4. Titles and Icons
- DVXSHELL.LIB, 3.3. The Shell and the Two Contexts
- dvxShowContextMenu, 6.6. Context Menus
- dvxShowWindow, 4.7. Raising, Lowering, Hiding, and Showing
- dvxSql
- missing, 13.10. The Data Control
- dvxSql.h, 13. Databases
- DVXSQL.LIB, 13. Databases
- dvxSqlAbandon, 13.8. Long Statements
- dvxSqlAffectedRows, 13.3. Running Statements
- dvxSqlClose, 13.9. Closing a Database
- dvxSqlEof, 13.6. Queries and Cursors
- dvxSqlError, 13.7. Errors
- dvxSqlEscape, 13.4. Values in Statements
- dvxSqlExec, 13.3. Running Statements
- dvxSqlFieldByName, 13.6. Queries and Cursors
- dvxSqlFieldCount, 13.6. Queries and Cursors
- dvxSqlFieldDbl, 13.6. Queries and Cursors
- dvxSqlFieldInt, 13.6. Queries and Cursors
- dvxSqlFieldName, 13.6. Queries and Cursors
- dvxSqlFieldText, 13.6. Queries and Cursors
- dvxSqlFreeResult, 13.6. Queries and Cursors
- dvxSqlNext, 13.6. Queries and Cursors
- dvxSqlOpen, 13.2. Opening a Database
- DvxSqlPumpFnT, 13.8. Long Statements
- dvxSqlQuery, 13.6. Queries and Cursors
- dvxSqlSetPump, 13.8. Long Statements
- dvxSystemKeyUse, 6.7. Shortcut Keys, 8.3. Who Gets a Key
- dvxText.h, 9.6.3. Families, Sizes, and Styles
- dvxTileWindows, 4.9. Several Windows in One Program
- dvxUnregisterHotkey, 8.8. Shortcuts That Work Everywhere
- dvxUpdate, 3.6. The Event Loop, 7.2. How a Dialog Box Runs, 12.5.1. Hooks: Asking and Waiting
- in a callback, 11.2. Long Work, 22.5. Hung Programs
- DVXUSER, 10.3. Where a Program’s Files Go
- dvxWgtP.h, 19.2. The Module
- dvxWindowScreenshot, 9.7.3. Saving Pictures
- dxe.ld, 22.3.3. A Program of Several Files
- DXE3, 1.5. Building, 3.2. Modules and the Loader
- exports, 18.4. What a Library Exports
- dxe3gen, 1.5. Building
- exports, 18.4. What a Library Exports
- DxeAppContextT, 2.3. appMain and the Program’s Context, 3.3. The Shell and the Two Contexts
E
- Ed25519, 21.4. Signing
- EIP, 22.3.1. Reading a Crash Report
- EIP is in, 22.3.1. Reading a Crash Report
- emulators, 1.6. Installing and Running, 22.7. Testing on Emulators and Real PCs
- encryption, 15.7. The Cryptography Library
- none for HTTP, 14. Networking and the Web, 14.9. Things to Know
- secure link, 15.6. Packets and the Secure Link
- End Task, 3.7. A Program with a Main Loop, 11.9. The Task Manager
- ENETDOWN, 14.9. Things to Know
- environment, B.2.2. One C Library for Everything
- errno
- network codes, 14.3. Sockets
- error 380, 19.10. The BASIC Interface
- error 453, 18.9. Giving DVX BASIC the Library
- event loop, 3.6. The Event Loop
- events, 8. The Keyboard, the Mouse, and the Clipboard
- widgets, 5.7. Widget Events
- EWOULDBLOCK, 14.4. Waiting Without Stopping DVX
- examples, What You Need
- bounce, 17. Games
- browser, 5.11. A Browser: TreeView, ListView, and Splitter, 5.11.1. The Data
- bughunt, 22.1. The Bug Hunt Program
- chat, 15.4. The Chat Program
- contacts, 13.1. The Contacts Program
- fortune, 20.1. The Fortune Program
- hello, 2. Your First Program
- httpget, 14.8. The HTTP Get Program
- jukebox, 16. Sound and Music
- meter, 19. Writing a Widget
- mtrdemo, 19.13. A Program That Uses It
- notes, 10.1. The Notes Program
- primes, 11.3. The Primes Program
- printit, 12.1. The PrintIt Program
- signup, 5.5. A Data-Entry Form, 5.5.1. The Form’s Widgets
- sketch, 9. Drawing, Images, and Fonts
- textstat, 18. Writing a Library
- ticker, 3.7. A Program with a Main Loop
- tsdemo, 18.8. A C Program That Uses It
- exclusive mode, 17.7. The Whole Screen
- ExclusiveStateE, 17.7. The Whole Screen
- exit, 3.10. Faults, B.3.1. Ending, Exiting, and Signals
- in games, 17.10. Packaging and Ending
- Exit DVX, 3.7. A Program with a Main Loop
- exports, 2.2. The Descriptor, 18.4. What a Library Exports
- collisions, 22.9. The Binary Interface Rules
F
- F1, 2.5. The Menu Bar, 20.3. Context Help
- in games, 17.3.1. Game Input Windows
- faults, 3.10. Faults, 22.3. Crash Reports
- in DVX code, 22.3.4. Faults Outside Your Code
- in emulators, 22.7.1. DOSBox
- FD_CREATE, 7.5. File and Folder Dialogs
- FD_FOLDER, 7.5. File and Folder Dialogs, 10.6.2. Copying, Moving, and Deleting
- FD_NAME, 7.5. File and Folder Dialogs
- FD_OPEN, 7.5. File and Folder Dialogs
- FD_SAVE, 7.5. File and Folder Dialogs
- fgColor, 5.13. Tooltips, Colors, and Fonts
- File
- Add File, 18.9.2. Using It from BASIC
- file associations, 10.7. File Associations
- file dialogs
- filters, 7.5.1. Filters
- pictures, 9.7.1. Loading Pictures
- file transfers, 15.8. File Transfers
- FileFilterT, 7.5.1. Filters
- fileops, 10.6. The File Operations Library
- fileOps.h, 10.6. The File Operations Library
- FILEOPS_ATTR_READONLY, 10.6.1. Listing a Folder
- FILEOPS_COPY_CHUNK, 10.6.2. Copying, Moving, and Deleting
- FILEOPS_MSG_MAX, 10.4.1. Writing a File Safely
- FileOpsAnswerE, 10.6.2. Copying, Moving, and Deleting
- FileOpsCallbacksT, 10.6.2. Copying, Moving, and Deleting
- FileOpsEntryT, 10.6.1. Listing a Folder
- fileOpsFormatDate, 10.6.1. Listing a Folder
- fileOpsFormatSize, 10.6.1. Listing a Folder
- fileOpsGetAttr, 10.6.1. Listing a Folder
- fileOpsJobAddSource, 10.6.2. Copying, Moving, and Deleting
- fileOpsJobAnswer, 10.6.2. Copying, Moving, and Deleting
- fileOpsJobCancel, 10.6.2. Copying, Moving, and Deleting
- fileOpsJobCreate, 10.6.2. Copying, Moving, and Deleting
- fileOpsJobFree, 10.6.2. Copying, Moving, and Deleting
- fileOpsJobMessage, 10.6.2. Copying, Moving, and Deleting
- fileOpsJobProgress, 10.6.2. Copying, Moving, and Deleting
- fileOpsJobRun, 10.6.2. Copying, Moving, and Deleting
- fileOpsJobStep, 10.6.2. Copying, Moving, and Deleting
- FileOpsJobT, 10.6.2. Copying, Moving, and Deleting
- fileOpsListDir, 10.6.1. Listing a Folder
- fileOpsListFree, 10.6.1. Listing a Folder
- fileOpsListSort, 10.6.1. Listing a Folder
- FileOpsOpE, 10.6.2. Copying, Moving, and Deleting
- FileOpsProgressT, 10.6.2. Copying, Moving, and Deleting
- FileOpsSaveStepE, 10.4.1. Writing a File Safely
- fileOpsSaveText, 10.4.1. Writing a File Safely
- fileOpsSetAttr, 10.6.1. Listing a Folder
- FileOpsStepE, 10.6.2. Copying, Moving, and Deleting
- fileOpsTreeSize, 10.6.1. Listing a Folder
- fileOpsTypeName, 10.6.1. Listing a Folder
- fileOpsValidateName, 10.8. Long File Names
- files, 10. Files, Folders, and Settings
- choosing, 7.5. File and Folder Dialogs
- errors, 10.4.1. Writing a File Safely
- handles, B.2.2. One C Library for Everything
- other helpers, 10.4.1. Writing a File Safely
- performance, 22.8.4. Files and DOS
- reading, 10.4. Reading and Writing Files
- text files, 6.10. The Rest of TinyEdit
- text mode, 10.4. Reading and Writing Files
- writing safely, 10.4.1. Writing a File Safely
- FIONBIO, 14.4. Waiting Without Stopping DVX
- fixed point, 17.5. Frame Pacing and Time
- flags
- between callbacks and a loop, 3.7. A Program with a Main Loop
- floating point
- cost, 22.8.5. Arithmetic
- flow control, 15.2. The UART Driver
- FM chip, 16.1. The Sound Hardware, 16.10. The FM Chip
- tones, 16.4. Tones
- focus, 5.9. Focus and Tab Order, 8.7. Focus
- folders
- DVX, 10.3. Where a Program’s Files Go
- listing, 10.6.1. Listing a Folder
- fonts, 9.6.1. What a Font Is, 20. Help Files, Resources, and Fonts, 20.6. Fonts
- carried, 9.6.6. Fonts a Program Carries, 20.6.3. A Font the Program Carries
- choosing, 7.6. Colors and Fonts
- families, 9.6.3. Families, Sizes, and Styles
- in DATA, 20.6.3. A Font the Program Carries
- installed, 9.6.3. Families, Sizes, and Styles
- installing, 20.6.4. Fonts for Every Program
- licenses, 20.6.2. Licenses
- making, 20.6.1. Making Fonts with mkfont
- names, 20.6.1. Making Fonts with mkfont
- printing, 12.7.3. Type on a Page
- smoothing, 9.6.5. Smoothed Text
- system font, 9.6.1. What a Font Is
- widgets, 5.13. Tooltips, Colors, and Fonts
- FontStampT, 9.6.5. Smoothed Text
- forms, 5.5. A Data-Entry Form
- Frame, 5.3. Containers, 5.5.3. Frames and Fields
- frame pacing, 17.5. Frame Pacing and Time
- framebuffer, 17.6. The Screen
- frames, 3.6. The Event Loop
- FRAMEWAIT, 17.11. Games in DVX BASIC
- full screen, 17.7. The Whole Screen
G
- game input, 17.3.1. Game Input Windows
- game loop, 17.2. The Shape of a Game
- GAME_FRAME_MAX_HZ, 17.5. Frame Pacing and Time
- gameFrameInit, 17.5. Frame Pacing and Time
- gameFrameNext, 17.5. Frame Pacing and Time
- GameFramePacerT, 17.5. Frame Pacing and Time
- gameFrameWait, 17.5. Frame Pacing and Time
- gameInput, 8.9. Game Input and Held Keys, 17.3.1. Game Input Windows
- GameKeyDown, 17.11. Games in DVX BASIC
- gameKeyIsDown, 17.3.2. Held Keys
- gamePalCacheLookup, 17.6.1. The Game’s Palette and the Color Table
- GamePalCacheT, 17.6.1. The Game’s Palette and the Color Table
- gamePalNearest, 17.6.1. The Game’s Palette and the Color Table
- games, 17. Games
- data files, 17.9. Data Files and Saved Games
- ending, 17.2. The Shape of a Game
- hardware layer, B.4.2. Mapping the Hardware Layer
- porting, 17.12. Porting a Game Library to DVX
- porting a game library, B.4. Porting a Game Library
- screen, 17.6. The Screen
- gameTimerAdd, 11.1.3. Interrupt Timers, 17.5.1. The Timer Service
- gamma functions, B.2.1. What Is Not There
- getaddrinfo, 14.3. Sockets
- GIF files, 9.7.1. Loading Pictures
- Go-Back-N, 15.6.1. The Packet Layer
- GridLines, 13.11. The DBGrid
H
- handles, 18.7. State That Programs Share
- handshaking, 15.2. The UART Driver
- hardware
- direct access, B.3.3. The Hardware
- hasMainLoop, 3.4. Two Kinds of Program
- games, 17.2. The Shape of a Game
- HBox, 5.3. Containers
- HDLC, 15.6.1. The Packet Layer
- header codes, 12.4. Laying Out Text
- headers, 1.1. What the SDK Holds
- headers and footers, 12.4. Laying Out Text
- held keys, 17.3.2. Held Keys
- Help Editor, 20.2.5. Compiling with dvxhlpc
- help files, 2.10. The Help File, 20. Help Files, Resources, and Fonts, 20.2. Help Files
- comments, 20.2.1. The Source Format
- compiling, 1.5. Building, 20.2.5. Compiling with dvxhlpc
- context help, 20.3. Context Help
- errors, 20.2.5. Compiling with dvxhlpc
- games, 17.10. Packaging and Ending
- headings, 20.2.1. The Source Format
- index, 20.2.3. The Table of Contents and the Index
- libraries, 18.10. The Library’s Help
- links, 20.2.2. Links
- lists, 20.2.1. The Source Format
- notes, 20.2.1. The Source Format
- of widgets and libraries, 20.4. Help for Widgets and Libraries
- opening, 2.8. The Callbacks, 20.3.1. Opening Help from Code
- optional, A.4. Targets
- per window, 20.3. Context Help
- rebuilding, 18.10. The Library’s Help, 20.4. Help for Widgets and Libraries
- searching, 20.2.1. The Source Format
- .section, 20.4. Help for Widgets and Libraries
- several files, 20.2.4. Several Files: .include and .section
- source format, 20.2.1. The Source Format
- table of contents, 20.2.3. The Table of Contents and the Index
- tables, 20.2.1. The Source Format
- text, 20.2.1. The Source Format
- topics, 20.2.1. The Source Format
- widgets, 19.11. The Toolbox Icon and the Help
- helpFile, 20.3. Context Help
- default, 20.3. Context Help
- helpQueryCtx, 20.3. Context Help
- helpTopic, 20.3. Context Help
- HelpView widget, 20.3.2. Help in a Window of Your Own
- HKDF, 15.6.3. What the Secure Link Protects
- .hlp files, 20.2. Help Files
- hlpfile library, 20.3.2. Help in a Window of Your Own
- hotkeys, 8.8. Shortcuts That Work Everywhere
- HTTP
- replies, 14.6. The HTTP Library
- request headers, 14.6. The HTTP Library
- status and failure, 14.6. The HTTP Library
- HTTP library, 14.6. The HTTP Library
- http.h, 14.6. The HTTP Library
- HTTP_MEMORY_MAX, 14.6. The HTTP Library
- HTTP_REDIRECTS_MAX, 14.6. The HTTP Library
- httpBody, 14.6. The HTTP Library
- httpBodyFile, 14.6. The HTTP Library
- httpBodySet, 14.6. The HTTP Library
- httpCreate, 14.6. The HTTP Library
- httpFree, 14.6. The HTTP Library
- httpHeader, 14.6. The HTTP Library
- httpHeaderAdd, 14.6. The HTTP Library
- httpMessage, 14.6. The HTTP Library
- httpPoll, 14.6. The HTTP Library
- httpProgress, 14.6. The HTTP Library
- HTTPS, 14. Networking and the Web
- httpSaveTo, 14.6. The HTTP Library
- resume, 14.6.1. Downloading to a File
- httpStart, 14.6. The HTTP Library
- HttpStateE, 14.6. The HTTP Library
- httpStatus, 14.6. The HTTP Library
- HttpT, 14.6. The HTTP Library
- httpTimeoutSet, 14.6. The HTTP Library
- httpUrl, 14.6. The HTTP Library
- hung programs, 22.5. Hung Programs
I
- icon24, 19.11. The Toolbox Icon and the Help
- idle handlers, 11.1.2. Idle Handlers, 14.1. The Network Under DVX
- Image, 5.6.7. Pictures, Lines, and Space, 9.7.4. The Image and ImageButton Widgets
- ImageButton, 5.6.7. Pictures, Lines, and Space, 9.7.4. The Image and ImageButton Widgets
- images
- cost, 9.7.1. Loading Pictures
- drawing, 9.7.2. Drawing and Scaling Pictures
- Image widget, 5.6.7. Pictures, Lines, and Space, 9.7.4. The Image and ImageButton Widgets
- loading, 9.7.1. Loading Pictures
- saving, 9.7.3. Saving Pictures
- scaling, 9.7.2. Drawing and Scaling Pictures
- toolbar buttons, 6.8. Toolbars
- transparency, 9.7.2. Drawing and Scaling Pictures
- .include, 20.2.4. Several Files: .include and .section
- include path, 1.1. What the SDK Holds
- .index, 20.2.3. The Table of Contents and the Index
- INI files, 10.5. Settings Files
- input
- which task, 3.6. The Event Loop
- input boxes, 7.4. Asking for Text, a Number, or a Choice
- Install from File, 21.6. Installing
- installing
- a library, 18.11. Installing and Testing
- a program, 1.6. Installing and Running
- a widget, 19.14. Installing and Testing
- installToolchain.sh, 1.2. The Host and the Cross Compiler
- instrument banks, 16.8.2. Where Music Plays
- INT 17h, 12.2. The Printer and Its Settings
- INTEGER PRIMARY KEY, 13.10.4. Adding and Deleting
- interrupts, 17.5.1. The Timer Service
- invalidating, 9.10. Invalidating and Repainting
- IRQ
- serial ports, 15.2. The UART Driver
J
- journal files, 13.2. Opening a Database
- joyButtonPressed, 17.4. Joysticks
- joyButtonWentDown, 17.4. Joysticks
- joyClose, 17.4. Joysticks
- joyCount, 17.4. Joysticks
- JoyEventT, 17.4. Joysticks
- joyGetInfo, 17.4. Joysticks
- JoyInfoT, 17.4. Joysticks
- joyOpen, 17.4. Joysticks
- joyPump, 17.4. Joysticks
- joyRead, 17.4. Joysticks
- joySetEventFn, 17.4. Joysticks
- JoyStateT, 17.4. Joysticks
- joystick.lib, 17.4. Joysticks
- joysticks, 17.4. Joysticks
- calibration, 17.4. Joysticks
- polling, 17.4. Joysticks
- JPEG files, 9.7.1. Loading Pictures
- JSON
- nodes, 14.7. The JSON Library
- paths, 14.7. The JSON Library
- showing, 14.8.3. Showing the JSON
- text, 14.7. The JSON Library
- writing, 14.7. The JSON Library
- JSON library, 14.7. The JSON Library
- json.h, 14.7. The JSON Library
- JSON_DEPTH_MAX, 14.7. The JSON Library
- JSON_ERR_MAX, 14.7. The JSON Library
- JSON_NO_NODE, 14.7. The JSON Library
- jsonBool, 14.7. The JSON Library
- jsonChild, 14.7. The JSON Library
- jsonCount, 14.7. The JSON Library
- JsonDocT, 14.7. The JSON Library
- jsonFind, 14.7. The JSON Library
- jsonFree, 14.7. The JSON Library
- jsonKey, 14.7. The JSON Library
- jsonNumber, 14.7. The JSON Library
- jsonParse, 14.7. The JSON Library
- jsonQuote, 14.7. The JSON Library
- jsonText, 14.7. The JSON Library
- jsonType, 14.7. The JSON Library
- JsonTypeE, 14.7. The JSON Library
K
- key codes, 8.2. Key Codes
- KEY_EXT_FLAG, 8.2. Key Codes
- KEY_IS_ASCII, 8.2. Key Codes
- KEY_MOD_ALT, 8.2.1. Modifiers
- KEY_MOD_CTRL, 8.2.1. Modifiers
- KEY_MOD_SHIFT, 8.2.1. Modifiers
- KEY_RAW_CODE, 17.3.2. Held Keys
- keyboard, 8. The Keyboard, the Mouse, and the Clipboard
- access keys, 5.10. Access Keys
- dispatch order, 8.3. Who Gets a Key
- example program, 8.1. The Keys Program
- filtering, 8.4. Keys in Widgets
- focus, 5.9. Focus and Tab Order, 8.7. Focus
- game input, 8.9. Game Input and Held Keys, 17.3.1. Game Input Windows
- hotkeys, 8.8. Shortcuts That Work Everywhere
- key codes, 8.2. Key Codes
- key releases, 8.3.1. Keys Going Up
- menus, 6.3.1. Menus and the Keyboard
- modifiers, 8.2.1. Modifiers
- order of handling, 6.7. Shortcut Keys
- shortcut keys, 6.7. Shortcut Keys
- Tab, 5.9. Focus and Tab Order
- widgets, 19.7. The Mouse, the Keys, and the Focus
- keyboard joystick, 17.4. Joysticks
- KeyColumn, 13.10.1. Telling It What to Read
- keys, 21.4. Signing
- KEYS folder, 21.5. Trust
- KIND, A.1. Project Settings
L
- Label, 5.6.1. Labels and Buttons
- LastError, 13.10.1. Telling It What to Read
- launch arguments, 11.5. The Command Line
- layout, 5. Widgets and Layout
- fixed width, 5.4.2. Weight: Sharing the Extra Room
- label column, 5.5.2. A Column of Labels
- minimum size, 5.4.1. Minimum Sizes
- padding and spacing, 5.4.5. Padding, Spacing, and Alignment
- passes, 5.4. How Layout Works
- size units, 5.4.4. Size Units
- spacing, 2.6. Widgets
- stretching, 5.4.3. Across a Box
- weight, 2.6. Widgets, 5.4.2. Weight: Sharing the Extra Room
- when it runs, 5.4.6. When the Layout Runs
- layout engine, 5.4. How Layout Works
- ld -r, 22.3.3. A Program of Several Files
- LFB, 3.8. The Display
- libraries, 18. Writing a Library
- constructors, 18.5. How DVX Loads a Library
- failing to load, 18.5. How DVX Loads a Library
- loading, 3.2. Modules and the Loader, 18.5. How DVX Loads a Library
- naming, 18.4. What a Library Exports
- optional, 18.4. What a Library Exports
- per-program state, 18.7. State That Programs Share
- refused, 22.4. Refused Modules
- shared state, 18.7. State That Programs Share
- versions, 18.6. The Binary Interface
- when to write, 18.1. When to Write a Library
- LIBS, A.1. Project Settings
- libtasks, 3.5. Cooperative Tasks, 11.4. Tasks and Their Scheduler
- libxmp-lite, 16.8.2. Where Music Plays
- line ends, 15.4.3. Line Ends and Colors
- linear framebuffer, 3.8. The Display
- .link, 20.2.2. Links
- ListBox, 5.6.4. Lists: ListBox, Dropdown, and ComboBox
- listhelp, 19.12. The Shared Helpers
- lists, 5.6.4. Lists: ListBox, Dropdown, and ComboBox
- ListView, 5.6.5. ListView and TreeView
- columns, 5.11.4. The List
- onChange, 5.11.6. Following the Selection
- sorting, 5.11.1. The Data
- ListViewColT, 5.6.5. ListView and TreeView
- live MIDI, 16.9. Live MIDI and Music Macros
- loader, 3.2. Modules and the Loader, 18.5. How DVX Loads a Library
- loading
- on demand, 18.5. How DVX Loads a Library
- logging, 1.6. Installing and Running, 22.2. The Log
- long file names, 10.8. Long File Names
- long work, 11.2. Long Work
- LPRINT, 12.6. Sending Bytes of Your Own
- LPT1, 12.2. The Printer and Its Settings
M
- magic numbers, 2.1. Headers and Definitions
- main
- porting, B.1. The Shape of a Program
- main loop, 3.7. A Program with a Main Loop
- make, 1.5. Building
- make clean, A.4. Targets
- make install, 1.6. Installing and Running, A.4. Targets
- and packages, 21.6. Installing
- library, 18.11. Installing and Testing
- widget, 19.14. Installing and Testing
- make package, 21.1. make package, A.4. Targets
- Makefile, 1.4. What a Project Holds, A. The SDK Build Settings
- manifests, 21.2. The Package File
- master-detail, 13.10.6. Master and Detail
- MAX_MENU_LABEL, 2.5. The Menu Bar, 6.3. Building a Menu Bar
- MAX_TITLE_LEN, 4.4. Titles and Icons
- MAX_WIDGET_NAME, 5.1.3. The Fields You Use
- maxH, 5.4.2. Weight: Sharing the Extra Room
- maxW, 5.4.2. Weight: Sharing the Extra Room
- memory, 3.9. Memory, 22.6. Memory and Leaks
- at program end, 3.9. Memory, 22.6.1. Finding a Leak
- bitmaps, 9.8. Off-Screen Bitmaps
- content buffers, 4.2. Creating a Window
- corruption, 22.3.5. Errors That Do Not Fault
- finding leaks, 22.6.1. Finding a Leak
- freeing, 2.9. How the Program Ends, 9.8. Off-Screen Bitmaps
- leaks, 3.9. Memory, 22.6. Memory and Leaks
- libraries, 18.7. State That Programs Share
- tracking, 3.9. Memory
- widgets, 5.1.2. Who Owns What
- memory protection, 3.1. The Machine
- MenuBarT, 6.3. Building a Menu Bar
- MenuItemT, 6.3. Building a Menu Bar
- menus, 6. Menus, Toolbars, and Shortcuts
- access keys, 2.5. The Menu Bar, 5.10. Access Keys, 6.3. Building a Menu Bar
- check items, 6.4. Check Items, Radio Items, and Submenus
- command IDs, 2.1. Headers and Definitions, 6.1. The Example: TinyEdit
- context, 6.6. Context Menus
- enabling items, 6.5. Enabling and Graying Items
- keyboard, 6.3.1. Menus and the Keyboard
- labels, 6.3. Building a Menu Bar
- menu bar, 2.5. The Menu Bar, 6.3. Building a Menu Bar
- onMenu, 6.2. One Routine for Every Command
- radio items, 6.4. Check Items, Radio Items, and Submenus
- submenus, 6.4. Check Items, Radio Items, and Submenus
- MenuT, 6.3. Building a Menu Bar
- menuWinId, 4.9. Several Windows in One Program
- message boxes, 7.3. Message Boxes
- METER_IMPL, 19.2. The Module
- MeterApiT, 19.9. The API Table
- MIDI files, 16.8.2. Where Music Plays
- MIDI input, 16.11. The MIDI Port
- MIDI port, 16.1. The Sound Hardware, 16.11. The MIDI Port
- minH, 5.4.1. Minimum Sizes
- minW, 5.4.1. Minimum Sizes
- missed frames, 17.5. Frame Pacing and Time
- mixer, 16.1. The Sound Hardware
- mkfont, 9.6.6. Fonts a Program Carries, 20.6.1. Making Fonts with mkfont
- manifest, 20.6.1. Making Fonts with mkfont
- MOD files, 16.8.2. Where Music Plays
- modal windows, 7.2. How a Dialog Box Runs
- progress, 12.5.2. The Printing Window
- without blocking, 7.7.2. A Modal Window That Does Not Wait
- modem control lines, 15.2. The UART Driver
- modems, 15.3. Connections
- modules, 3.2. Modules and the Loader, 16.8.2. Where Music Plays
- kinds, 3.2. Modules and the Loader
- layout, 22.3.3. A Program of Several Files
- linking, 1.5. Building
- refused, 22.4. Refused Modules
- mouse, 8. The Keyboard, the Mouse, and the Clipboard, 8.10. The Mouse
- canvas callback, 9.2.2. Drawing with the Mouse
- capture, 8.10.2. Capturing the Mouse
- capturing, 19.7. The Mouse, the Keys, and the Focus
- double click, 8.10.1. Mouse Events in Widgets
- without widgets, 8.10.3. The Mouse at the Window Level
- dragging, 8.10.2. Capturing the Mouse
- example program, 8.1. The Keys Program
- in emulators, 22.7.1. DOSBox
- in games, 17.3.4. The Mouse
- right button, 8.10.1. Mouse Events in Widgets
- wheel, 8.10.4. The Wheel
- mouse pointers, 8.11. Mouse Pointers
- MOUSE_LEFT, 8.10. The Mouse
- MOUSE_MIDDLE, 8.10. The Mouse
- MOUSE_RIGHT, 8.10. The Mouse
- MPU-401, 16.11. The MIDI Port
- multiClickDetect, 19.7. The Mouse, the Keys, and the Focus
- multiInstance, 2.2. The Descriptor, 11.5.2. One Copy or Several
- music, 16. Sound and Music
- loading, 16.8. Music
- ownership, 16.8. Music
- music macros, 16.9. Live MIDI and Music Macros
- music.lib, 16. Sound and Music
- MusicEndFnT, 16.8.1. Playing, Pausing, and Stopping
- musicFree, 16.8. Music
- musicGetInfo, 16.8.1. Playing, Pausing, and Stopping
- musicGetPosition, 16.8.1. Playing, Pausing, and Stopping
- MusicInfoT, 16.8.1. Playing, Pausing, and Stopping
- musicIsPlaying, 16.8.1. Playing, Pausing, and Stopping
- MusicKindE, 16.8.1. Playing, Pausing, and Stopping
- musicLoad, 16.8. Music
- musicLoadMacro, 16.9. Live MIDI and Music Macros
- musicLoadMem, 16.8. Music
- musicMidiControl, 16.9. Live MIDI and Music Macros
- musicMidiNoteOff, 16.9. Live MIDI and Music Macros
- musicMidiNoteOn, 16.9. Live MIDI and Music Macros
- musicMidiOpen, 16.9. Live MIDI and Music Macros
- musicMidiPitchBend, 16.9. Live MIDI and Music Macros
- musicMidiProgram, 16.9. Live MIDI and Music Macros
- musicMidiSend, 16.9. Live MIDI and Music Macros
- musicMmlBusy, 16.9. Live MIDI and Music Macros
- musicMmlOpen, 16.9. Live MIDI and Music Macros
- musicMmlPlay, 16.9. Live MIDI and Music Macros
- MusicOutputE, 16.8.2. Where Music Plays
- musicPause, 16.8.1. Playing, Pausing, and Stopping
- musicPlay, 16.8.1. Playing, Pausing, and Stopping
- musicPump, 16.13. Keeping Sound Fed
- musicResume, 16.8.1. Playing, Pausing, and Stopping
- musicSetBank, 16.8.2. Where Music Plays
- musicSetEndFn, 16.8.1. Playing, Pausing, and Stopping
- musicSetPosition, 16.8.1. Playing, Pausing, and Stopping
- musicStop, 16.8.1. Playing, Pausing, and Stopping
- MusicT, 16.8. Music
N
- NAME, A.1. Project Settings
- names
- looking up, 14.4.1. Looking Up a Name Without Waiting
- of exports, 18.4. What a Library Exports
- of files a program makes, 10.8. Long File Names
- of modules, 1.3. Creating a Project, 10.8. Long File Names
- widget types, 19.2. The Module
- near pointers, B.2.1. What Is Not There, B.3.3. The Hardware
- nested event loop, 3.6. The Event Loop, 12.5.1. Hooks: Asking and Waiting
- NET, 1.5. Building, A.1. Project Settings, B.2. The C Library
- sdk.mk setting, 14.2. Building a Program That Uses the Network
- NET_LOOKUP_BUSY, 14.4.1. Looking Up a Name Without Waiting
- NetConfigT, 14.5. Network Settings and Status
- netErrorText, 14.3. Sockets
- netGetStatus, 14.5. Network Settings and Status
- netLookupCancel, 14.4.1. Looking Up a Name Without Waiting
- netLookupPoll, 14.4.1. Looking Up a Name Without Waiting
- netLookupStart, 14.4.1. Looking Up a Name Without Waiting
- NetLookupT, 14.4.1. Looking Up a Name Without Waiting
- netRestart, 14.5. Network Settings and Status
- netStart, 14.5. Network Settings and Status
- netStateText, 14.5. Network Settings and Status
- NetStatusT, 14.5. Network Settings and Status
- netStop, 14.5. Network Settings and Status
- networking, 14. Networking and the Web
- blocking calls, 14.4. Waiting Without Stopping DVX
- idle time, 14.1. The Network Under DVX
- packet driver, 14.1. The Network Under DVX
- settings, 14.1. The Network Under DVX
- sockets, 14.3. Sockets
- status, 14.5. Network Settings and Status
- Networking
- part of DVX, 14.1. The Network Under DVX
- newArgsCtx, 11.5.2. One Copy or Several
- newProject.sh, 1.3. Creating a Project
- basicgame, 17.1. Starting from the Template
- control, 19.15. Using a Control Written in DVX BASIC
- game, 17.1. Starting from the Template
- library, 18.2. The Library Template
- widget, 19.1. The Widget Template
- nm, 3.2. Modules and the Loader, 18.4. What a Library Exports, 22.3.2. Finding the Faulting Line
- Not responding, 3.5. Cooperative Tasks, 11.2. Long Work, 22.5. Hung Programs
- note queues, 16.5. Note Queues
- nowMs, 14.6. The HTTP Library
O
- O_NONBLOCK, 14.4. Waiting Without Stopping DVX
- objdump, 22.3.2. Finding the Faulting Line
- off-screen bitmaps, 9.8. Off-Screen Bitmaps
- onBlur, 8.7. Focus
- window, 4.3.2. Focus: onFocus and onBlur
- onChange, 5.7. Widget Events
- onClick, 2.6. Widgets, 5.7. Widget Events, 8.10.1. Mouse Events in Widgets
- onClose, 2.4. Creating the Window, 4.3.3. Closing: onClose
- closing sound, 16.2.1. Opening Sound
- saving changes, 6.10. The Rest of TinyEdit
- onCursorQuery, 8.5. Seeing a Window’s Keys First, 8.11. Mouse Pointers
- onDblClick, 8.10.1. Mouse Events in Widgets
- onEvent, 5.7. Widget Events, 19.8. Firing Events
- terminal, 15.5. The Terminal Control
- onFocus, 8.7. Focus
- window, 4.3.2. Focus: onFocus and onBlur
- onHelpQuery, 20.3. Context Help
- onKey, 8.5. Seeing a Window’s Keys First
- onKeyDown, 8.4. Keys in Widgets
- onKeyPress, 8.4. Keys in Widgets
- onKeyUp, 8.3.1. Keys Going Up
- onMenu, 2.4. Creating the Window, 6.2. One Routine for Every Command
- onMenuOpen, 6.5. Enabling and Graying Items
- onMouse, 8.10.3. The Mouse at the Window Level
- in games, 17.3.4. The Mouse
- onMouseDown, 8.10.1. Mouse Events in Widgets
- onMouseMove, 8.10.1. Mouse Events in Widgets
- onMouseUp, 8.10.1. Mouse Events in Widgets
- onNewArgs, 11.5.2. One Copy or Several
- onPaint, 4.11. Windows Without Widgets, 9.9. Drawing in a Window Without Widgets
- in games, 17.6.3. Presenting a Frame
- onRawKey, 8.9. Game Input and Held Keys, 17.3.3. Raw Key Events
- onResize, 4.3.1. Resizing: onResize
- onScroll, 8.10.4. The Wheel
- onValidate, 5.7. Widget Events, 13.10.3. Changing Rows
- OPL2, 16.10. The FM Chip
- OPL3, 16.10. The FM Chip
- option buttons, 5.6.3. Check Boxes and Radio Buttons
- optional parts, 14.1. The Network Under DVX, 15.1. The Layers, 21.3.1. DVX’s Optional Parts
- override, 18.8. A C Program That Uses It
P
- package server, 21.8. Publishing on the Package Server
- PACKAGE.INI, 21.2. The Package File
- PACKAGE.SIG, 21.4. Signing
- packages, 21. Packaging and Publishing
- dependencies, 21.3. Dependencies
- DVX’s own, 21.3.1. DVX’s Optional Parts
- files, 21.2. The Package File
- fonts, 20.6.4. Fonts for Every Program
- format, 21.2. The Package File
- installing, 21.6. Installing
- kinds, 21.9. Other Kinds of Package
- layout, A.6. What a Package Holds
- manifest keys, 21.2. The Package File
- refused, 21.6. Installing
- removing, 21.6. Installing
- settings, A.3. Package Settings
- signing, 21.4. Signing
- template, 21.9. Other Kinds of Package
- trust, 21.5. Trust
- updates, 21.7. Versions and Updates
- versions, 21.7. Versions and Updates
- packaging
- games, 17.10. Packaging and Ending
- packColor, 9.5. Colors and Pixel Formats
- packColorRgb, 9.2.3. Choosing the Pen, 9.5. Colors and Pixel Formats, 19.6. Painting
- packet driver, 14.1. The Network Under DVX
- packet layer, 15.6. Packets and the Secure Link
- packet.h, 15.6.1. The Packet Layer
- padding, 5.4.5. Padding, Spacing, and Alignment
- page setup, 12.3.2. The Page Setup Dialog
- PAL_CHANNELS, 17.6.1. The Game’s Palette and the Color Table
- PAL_ENTRIES, 17.6.1. The Game’s Palette and the Color Table
- palette, 9.5. Colors and Pixel Formats
- palette animation, 17.6.4. Palette Animation
- paths, 10. Files, Folders, and Settings
- comparing, 10.2. Paths
- current folder, 10.2. Paths
- joining, 10.2. Paths
- porting, B.3. What to Replace
- separators, 10.2. Paths
- with blanks, 10.8. Long File Names
- PC speaker
- tones, 16.4. Tones
- pens, 9.2.2. Drawing with the Mouse
- performance, 3.1. The Machine, 22.8. Performance on a 486
- arithmetic, 22.8.5. Arithmetic
- cryptography, 15.7. The Cryptography Library
- databases, 13.5. Transactions
- drawing, 9.11. What Is Fast on a 486, 22.8.2. The Screen
- files, 22.8.4. Files and DOS
- in emulators, 22.7.1. DOSBox
- long work, 11.2. Long Work, 22.8.3. Long Work
- measuring, 22.8.1. Measuring
- memory, 22.8.6. Memory
- repainting, 22.8.2. The Screen
- pictures
- copying, 9.4. The Drawing Calls
- pixel formats, 9.5. Colors and Pixel Formats
- pixelFormatKey, 9.5. Colors and Pixel Formats
- PixelFormatT, 9.5. Colors and Pixel Formats
- pkg folder, 21.1. make package, A.6. What a Package Holds
- PKG_ settings, A.3. Package Settings
- PKG_AUTHOR, 21.2. The Package File, A.3. Package Settings
- PKG_DVX, 21.2. The Package File, A.3. Package Settings
- PKG_HOMEPAGE, 21.2. The Package File, A.3. Package Settings
- PKG_KEY, 21.4. Signing, A.3. Package Settings
- PKG_LICENCE, 21.2. The Package File, A.3. Package Settings
- PKG_NEEDS, 18.6. The Binary Interface, 21.3. Dependencies, A.3. Package Settings
- PKG_PUBLISHER, 21.2. The Package File, A.3. Package Settings
- PKG_SUMMARY, 21.2. The Package File, A.3. Package Settings
- PKG_TITLE, 21.2. The Package File, A.3. Package Settings
- PKG_VERSION, 21.2. The Package File, 21.7. Versions and Updates, A.3. Package Settings
- PKT_MAX_PAYLOAD, 15.6.1. The Packet Layer
- pktOpen, 15.6.1. The Packet Layer
- pktOpenStream, 15.6.1. The Packet Layer
- pktPoll, 15.6.1. The Packet Layer
- pktSend, 15.6.1. The Packet Layer
- pktSetYield, 15.6.2. The Secure Link
- PktStreamT, 15.6.1. The Packet Layer
- pktWaitSpace, 15.6.2. The Secure Link
- pktYield, 15.6.2. The Secure Link
- PLATFORM_BAK_EXT, 10.4.1. Writing a File Safely
- PLATFORM_LOG_FILE_MAX, 22.2. The Log
- PLATFORM_MS_TO_TICKS, 11.1.1. Clocks
- PLATFORM_TICKS_TO_MS, 11.1.1. Clocks, 14.6. The HTTP Library
- PLATFORM_TIMER_MAX_HZ, 11.1.3. Interrupt Timers
- PLATFORM_TIMER_SLOTS, 11.1.3. Interrupt Timers
- PLATFORM_TMP_EXT, 10.4.1. Writing a File Safely
- PLATFORM_US_PER_SEC, 3.7. A Program with a Main Loop, 11.1.1. Clocks
- platformAppUserDir, 10.3.1. The Program’s Own Folder
- platformCanReplaceFile, 10.4.1. Writing a File Safely
- platformChangeErrno, 10.4.1. Writing a File Safely
- platformClock, 11.1. Timers, 14.6. The HTTP Library
- platformClockHz, 11.1.1. Clocks
- platformCopyFile, 10.4.1. Writing a File Safely
- platformDiskSpace, 10.2. Paths
- platformDriveErrno, 10.2. Paths
- platformDriveList, 10.2. Paths
- PlatformDriveT, 10.2. Paths
- platformDvxIniPath, 10.5. Settings Files
- platformFileStamp, 10.4. Reading and Writing Files
- platformIrqRestore, 17.5.1. The Timer Service
- platformIrqSave, 17.5.1. The Timer Service
- platformIsReadOnly, 10.3.3. Where Not to Write
- platformKeyIsDown, 17.3.2. Held Keys
- platformKeyStateClear, 17.3.2. Held Keys
- platformKeyStateGet, 17.3.2. Held Keys
- platformKindDir, 10.3.3. Where Not to Write
- platformKindFind, 10.3.3. Where Not to Write
- platformKindReadDir, 10.3.3. Where Not to Write
- platformLoadedSymbol, 18.4. What a Library Exports
- platformLockRegion, 11.1.3. Interrupt Timers
- platformLongNames, 10.8. Long File Names
- platformMicros, 3.7. A Program with a Main Loop, 9.11. What Is Fast on a 486, 11.1.1. Clocks, 17.5. Frame Pacing and Time, 22.8.1. Measuring
- platformMkdirRecursive, 10.4.1. Writing a File Safely
- platformModuleOpen, 18.4. What a Library Exports
- platformPathAbsolute, 10.2. Paths
- platformPathBaseName, 10.2. Paths
- platformPathDirName, 10.2. Paths
- platformPathIsAbsolute, 10.2. Paths
- platformPathIsSep, 10.2. Paths
- platformPathIsUnder, 10.2. Paths
- platformPathJoin, 10.2. Paths
- platformPathNative, 10.2. Paths
- platformPathParent, 10.2. Paths
- platformPathSame, 10.2. Paths
- platformReadFile, 6.10. The Rest of TinyEdit, 10.4. Reading and Writing Files, 12.1. The PrintIt Program
- platformRename, 10.4.1. Writing a File Safely
- platformReplaceFile, 10.4.1. Writing a File Safely
- platformSameFile, 10.2. Paths
- platformScratchFile, 10.4.1. Writing a File Safely
- platformShortPath, 10.8. Long File Names, 11.7. Running DOS Programs
- PlatformStampT, 10.4. Reading and Writing Files
- platformStripLineEndings, 10.4. Reading and Writing Files, 20.6.2. Licenses
- platformSuspendHookAdd, 11.7. Running DOS Programs
- platformTimerAdd, 11.1.3. Interrupt Timers, 17.5.1. The Timer Service
- PlatformTimerFnT, 17.5.1. The Timer Service
- platformTimerRemove, 11.1.3. Interrupt Timers, 17.5.1. The Timer Service
- platformUserDir, 10.3. Where a Program’s Files Go
- platformUserPath, 10.3. Where a Program’s Files Go
- platformValidateFilename, 10.8. Long File Names
- platformWalkDir, 10.4.1. Writing a File Safely
- platformWriteFile, 6.10. The Rest of TinyEdit, 10.4.1. Writing a File Safely
- PLAY, 16.9. Live MIDI and Music Macros
- PNG files, 9.7.1. Loading Pictures
- poll, 14.4. Waiting Without Stopping DVX
- porting, B. Porting C Code to DVX
- game libraries, B.4. Porting a Game Library
- hardware, B.3.3. The Hardware
- what to replace, B.3. What to Replace
- PostScript, 12.7.4. Vector Pages on PostScript Printers
- prefsApplyChanges, 10.5. Settings Files
- prefsClose, 10.5. Settings Files
- prefsDvxIniShared, 10.5. Settings Files
- prefsGetBool, 10.5. Settings Files
- prefsGetInt, 10.5. Settings Files
- prefsGetSecret, 10.5. Settings Files
- prefsGetString, 10.5. Settings Files
- PrefsHandleT, 10.5. Settings Files
- prefsKeyName, 10.5. Settings Files
- prefsLoad, 10.5. Settings Files
- scores, 17.9. Data Files and Saved Games
- prefsLoadFailed, 10.5. Settings Files
- prefsRemove, 10.5. Settings Files
- prefsSave, 10.5. Settings Files
- prefsSaveAs, 10.5. Settings Files
- prefsSetBool, 10.5. Settings Files
- prefsSetInt, 10.5. Settings Files
- prefsSetSecret, 10.5. Settings Files
- prefsSetString, 10.5. Settings Files
- print documents, 12.7. Pictures and Drawn Pages
- print jobs, 12.5. Print Jobs
- print library, 12. Printing
- print.h, 12. Printing
- PRINT.LIB, 12. Printing
- PRINT_PORT_DEFAULT, 12.6. Sending Bytes of Your Own
- PRINT_STATUS_PAPER_OUT, 12.6. Sending Bytes of Your Own
- PrintAnswerE, 12.5.1. Hooks: Asking and Waiting
- PrintBandFnT, 12.7.2. Drawing a Page in Bands
- PrintChoiceT, 12.3. Printing Text in One Call
- printDestChoices, 12.2. The Printer and Its Settings
- PrintDestE, 12.2. The Printer and Its Settings
- printDestLabel, 12.2. The Printer and Its Settings
- printDeviceStore, 12.2. The Printer and Its Settings
- printDialog, 12.3.1. The Print Dialog
- printDocCancel, 12.7.1. The Cover Page
- printDocCancelled, 12.7.1. The Cover Page
- printDocClose, 12.7.1. The Cover Page
- printDocInfo, 12.7.1. The Cover Page
- printDocOpen, 12.7.1. The Cover Page
- printDocPage, 12.7.1. The Cover Page
- printDocPicture, 12.7.2. Drawing a Page in Bands
- PrintDocT, 12.7. Pictures and Drawn Pages
- printer models, 12.2. The Printer and Its Settings
- printer ports, 12.2. The Printer and Its Settings
- printFilePath, 12.2. The Printer and Its Settings
- PrintFillE, 12.7.4. Vector Pages on PostScript Printers
- printFontAscent, 12.7.3. Type on a Page
- printFontClose, 12.7.3. Type on a Page
- printFontDraw, 12.7.3. Type on a Page
- printFontHeight, 12.7.3. Type on a Page
- printFontOpen, 12.7.3. Type on a Page
- printFontSpans, 12.7.3. Type on a Page
- PrintFontT, 12.7.3. Type on a Page
- printFontWidth, 12.7.3. Type on a Page
- printFormatHeader, 12.4. Laying Out Text
- PrintHooksT, 12.5.1. Hooks: Asking and Waiting
- printing, 12. Printing
- bands, 12.7.2. Drawing a Page in Bands
- canceling, 12.5.2. The Printing Window
- colors, 12.7.2. Drawing a Page in Bands
- hooks, 12.5.1. Hooks: Asking and Waiting
- page layout, 12.4. Laying Out Text
- pictures, 12.7. Pictures and Drawn Pages
- PostScript fonts, 12.7.3. Type on a Page
- printer problems, 12.5.1. Hooks: Asking and Waiting
- program ended, 12.8. When a Program Ends While Printing
- settings, 12.2. The Printer and Its Settings
- testing, 12.9. Testing Without a Printer
- text, 12.3. Printing Text in One Call
- vector pages, 12.7.4. Vector Pages on PostScript Printers
- printJobBytes, 12.6. Sending Bytes of Your Own
- printJobCancel, 12.5. Print Jobs
- printJobCancelled, 12.5.3. Printing the Text
- printJobClose, 12.5.3. Printing the Text
- printJobOpen, 12.5. Print Jobs
- printJobPoll, 12.6. Sending Bytes of Your Own
- printJobPuts, 12.6. Sending Bytes of Your Own
- PrintJobT, 12.5. Print Jobs
- printJobWrite, 12.6. Sending Bytes of Your Own
- printModelChoices, 12.2. The Printer and Its Settings
- PrintModelE, 12.2. The Printer and Its Settings
- printModelLabel, 12.2. The Printer and Its Settings
- printModelPage, 12.7. Pictures and Drawn Pages
- printModelProblem, 12.2. The Printer and Its Settings
- PrintPageInfoT, 12.7. Pictures and Drawn Pages
- printPageLines, 12.4. Laying Out Text
- printPageSetupDialog, 12.3.2. The Page Setup Dialog
- printPageSetupProblem, 12.4. Laying Out Text
- PrintPageSetupT, 12.4. Laying Out Text
- PrintPortOpsT, 12.9. Testing Without a Printer
- printPortPresent, 12.6. Sending Bytes of Your Own
- printPortStatus, 12.6. Sending Bytes of Your Own
- printSerialStore, 12.2. The Printer and Its Settings
- printSetPortOps, 12.9. Testing Without a Printer
- printSettingsDefaults, 12.2. The Printer and Its Settings
- printSettingsLoad, 12.2. The Printer and Its Settings
- printSettingsSave, 12.2. The Printer and Its Settings
- PrintSettingsT, 12.2. The Printer and Its Settings
- printStatusProblem, 12.6. Sending Bytes of Your Own
- PrintTextInfoT, 12.5.3. Printing the Text
- printTextJob, 12.5.3. Printing the Text
- printTextPageCount, 12.4. Laying Out Text
- printUiDocClose, 12.7.1. The Cover Page
- printUiDocOpen, 12.7.1. The Cover Page
- printUiImageFile, 12.7. Pictures and Drawn Pages
- printUiJobOpen, 12.3. Printing Text in One Call
- printUiOpenPort, 12.6. Sending Bytes of Your Own
- printUiText, 12.3. Printing Text in One Call
- printUiTextChoice, 12.3. Printing Text in One Call
- printUiTextSetup, 12.3. Printing Text in One Call
- printUiWindow, 12.7. Pictures and Drawn Pages
- printVecBegin, 12.7.4. Vector Pages on PostScript Printers
- printVecDot, 12.7.4. Vector Pages on PostScript Printers
- printVecEllipse, 12.7.4. Vector Pages on PostScript Printers
- printVecEllipseFill, 12.7.4. Vector Pages on PostScript Printers
- printVecEnd, 12.7.4. Vector Pages on PostScript Printers
- printVecImage, 12.7.4. Vector Pages on PostScript Printers
- printVecLine, 12.7.4. Vector Pages on PostScript Printers
- printVecRect, 12.7.4. Vector Pages on PostScript Printers
- printVecText, 12.7.4. Vector Pages on PostScript Printers
- Program Manager
- Installed Programs, 1.6. Installing and Running
- programs
- callback-only, 3.4. Two Kinds of Program
- ending, 2.9. How the Program Ends, 4.12. Ending the Program, 18.7. State That Programs Share
- what is released, 22.6.2. What DVX Releases When a Program Ends
- main-loop, 3.4. Two Kinds of Program
- network, 14.4.2. Blocking Calls on a Task
- serial, 15.4. The Chat Program
- others running, 11.6. Starting Other Programs
- running once, 11.5.2. One Copy or Several
- several copies, 11.5.2. One Copy or Several
- starting, 11.6. Starting Other Programs
- what happens, 11.6. Starting Other Programs
- ProgressBar, 5.6.6. Numbers: Slider, Spinner, and ProgressBar
- projects
- creating, 1.3. Creating a Project
- files, 1.4. What a Project Holds
- properties
- of widgets, 19.10. The BASIC Interface
- protected mode, 3.1. The Machine
- publishing, 21.8. Publishing on the Package Server
R
- Radio, 5.6.3. Check Boxes and Radio Buttons
- RadioGroup, 5.3. Containers, 5.5.4. Showing a Row Only When Needed
- random numbers, 15.7. The Cryptography Library
- raw key codes, 17.3.2. Held Keys
- RawKeyEventT, 8.9. Game Input and Held Keys, 17.3.3. Raw Key Events
- read-only DVX, 10.3.3. Where Not to Write
- realloc, 20.5.2. Reading Resources
- rebuilding, 1.6. Installing and Running, 2.11. Changing the Program
- recording, 16.12. The Rest of the Sound Library
- RecordSource, 13.10.1. Telling It What to Read
- rectCopy, 9.4. The Drawing Calls
- rectCopyTransparent, 9.7.2. Drawing and Scaling Pictures
- recv, 14.3. Sockets
- non-blocking, 14.4. Waiting Without Stopping DVX
- redirects, 14.6. The HTTP Library
- repainting, 3.8. The Display, 9.10. Invalidating and Repainting
- Reposition event, 13.10.2. The Current Row and Reposition
- .res files, 20.5.1. The .res File
- resetClipRect, 9.3.1. The Clip Rectangle
- resources, 1.5. Building, 20. Help Files, Resources, and Fonts, 20.5. Resources
- font, 9.6.6. Fonts a Program Carries, 20.6.3. A Font the Program Carries
- format, 20.5. Resources
- icons, 4.4. Titles and Icons, 6.8. Toolbars
- in games, 17.9. Data Files and Saved Games
- of widgets and libraries, 20.5.4. Resources in Widgets and Libraries
- pictures, 9.7.1. Loading Pictures
- reading, 2.8. The Callbacks, 20.5.2. Reading Resources
- released at program end, 22.6.2. What DVX Releases When a Program Ends
- .res file, 20.5.1. The .res File
- widgets, 19.11. The Toolbox Icon and the Help
- richtext, 19.12. The Shared Helpers
- ROLLBACK, 13.5. Transactions
- rs232.h, 15.2. The UART Driver
- RS232_COM1, 15.2. The UART Driver
- RS232_ERR_ALREADY_OPEN, 15.2. The UART Driver
- rs232Close, 15.2. The UART Driver
- rs232GetIrq, 15.2. The UART Driver
- rs232GetUartType, 15.2. The UART Driver
- rs232Open, 15.2. The UART Driver
- rs232Read, 15.2. The UART Driver
- rs232SetBase, 15.2. The UART Driver
- rs232SetBreak, 15.2. The UART Driver
- rs232SetDtr, 15.2. The UART Driver
- rs232SetIrq, 15.2. The UART Driver
- rs232Write, 15.2. The UART Driver
- rs232WriteBuf, 15.2. The UART Driver
- RTLD_GLOBAL, 3.2. Modules and the Loader
- RTS/CTS, 15.2. The UART Driver
S
- safe start, 1.6. Installing and Running, 18.5. How DVX Loads a Library
- samples, 16.3. Samples and Voices
- samples/c, What You Need
- saved games, 17.9. Data Files and Saved Games
- SAVER, A.1. Project Settings
- saving
- as you go, 10.5.1. Saving When the Window Closes
- when to, 10.5.1. Saving When the Window Closes
- scheduler, 3.5. Cooperative Tasks
- screen savers, 11.8. Screen Savers
- installing, 11.8. Screen Savers
- packaging, A.1. Project Settings
- writing, 11.8. Screen Savers
- scrollback, 15.5. The Terminal Control
- ScrollPane, 5.3. Containers
- sdk.mk, A. The SDK Build Settings
- CFLAGS, A.1. Project Settings
- DATA, 10.3.2. The DATA Folder, 16.2. The Jukebox Program, A.1. Project Settings
- DJGPP_PREFIX, A.2. Build Settings
- DVX_DIR, A.2. Build Settings
- include path, 5.2. Widget Headers and Their APIs
- internal variables, A.7. Names sdk.mk Uses Itself
- KIND, A.1. Project Settings
- LIBS, A.1. Project Settings
- NAME, A.1. Project Settings
- NET, 14.2. Building a Program That Uses the Network, A.1. Project Settings
- package, 21.1. make package
- package settings, 21.2. The Package File
- PKG_AUTHOR, A.3. Package Settings
- PKG_DVX, A.3. Package Settings
- PKG_HOMEPAGE, A.3. Package Settings
- PKG_KEY, A.3. Package Settings
- PKG_LICENCE, A.3. Package Settings
- PKG_NEEDS, A.3. Package Settings
- PKG_PUBLISHER, A.3. Package Settings
- PKG_SUMMARY, A.3. Package Settings
- PKG_TITLE, A.3. Package Settings
- PKG_VERSION, A.3. Package Settings
- project files, A.5. The Files It Uses
- SAVER, A.1. Project Settings
- SDK_DIR, A.1. Project Settings
- settings, 1.4. What a Project Holds
- targets, 1.5. Building, A.4. Targets
- VENDOR, A.2. Build Settings
- sdk.zip, 1.1. What the SDK Holds
- SDK_DIR, A.1. Project Settings
- sdkToolchain, A.4. Targets
- sDragWidget, 19.7. The Mouse, the Keys, and the Focus
- secAeadLock, 15.7. The Cryptography Library
- secAeadUnlock, 15.7. The Cryptography Library
- secConstTimeEqual, 15.7. The Cryptography Library
- secCurve.h, 15.7. The Cryptography Library
- secEd25519Check, 15.7. The Cryptography Library
- secEd25519Sign, 15.7. The Cryptography Library
- secHash.h, 15.7. The Cryptography Library
- secHkdf, 15.7. The Cryptography Library
- secHmacSha256, 15.7. The Cryptography Library
- secLink.h, 15.6.2. The Secure Link
- SECLINK.RND, 15.7. The Cryptography Library
- SECLINK_MAX_PAYLOAD, 15.6.2. The Secure Link
- secLinkClose, 15.6.2. The Secure Link
- secLinkHandshake, 15.6.2. The Secure Link
- secLinkHandshakeStart, 15.6.2. The Secure Link
- secLinkHandshakeStep, 15.6.2. The Secure Link
- secLinkOpen, 15.6.2. The Secure Link
- secLinkOpenStream, 15.6.2. The Secure Link
- secLinkPoll, 15.6.2. The Secure Link
- secLinkSend, 15.6.2. The Secure Link
- secLinkSendBuf, 15.6.2. The Secure Link
- secLinkSetPassphrase, 15.6.2. The Secure Link
- secproxy, 15.6.2. The Secure Link
- secRngAddEntropy, 15.7. The Cryptography Library
- secRngBytes, 15.7. The Cryptography Library
- seeding, 15.7. The Cryptography Library
- secSecureZero, 15.4.4. Connecting and Sending, 15.7. The Cryptography Library
- secSha256, 15.7. The Cryptography Library
- .section, 20.2.4. Several Files: .include and .section
- secure link, 15.6. Packets and the Secure Link
- what it protects, 15.6.3. What the Secure Link Protects
- security.h, 15.7. The Cryptography Library
- secX25519, 15.7. The Cryptography Library
- secX25519JobStep, 15.7. The Cryptography Library
- select, 14.4. Waiting Without Stopping DVX
- send, 14.3. Sockets
- Separator, 5.6.7. Pictures, Lines, and Space
- serial ports, 15. Serial Ports, Modems, and Secure Links
- closing, 15.2. The UART Driver
- driver, 15.2. The UART Driver
- in emulators, 22.7.1. DOSBox
- sharing, 15.2. The UART Driver
- speeds, 15.2. The UART Driver
- serial printers, 12.2. The Printer and Its Settings
- setClipRect, 9.3.1. The Clip Rectangle
- setjmp, B.3.1. Ending, Exiting, and Signals
- settings, 10. Files, Folders, and Settings, 10.5. Settings Files
- file format, 10.5. Settings Files
- of a build, 1.5. Building
- reading defensively, 10.5. Settings Files
- sFocusedWidget, 19.7. The Mouse, the Keys, and the Focus
- SHARED, 10.3.3. Where Not to Write
- SHARED\FONTS, 20.6.4. Fonts for Every Program
- shell, 3.3. The Shell and the Two Contexts
- SHELL_APP_DESCRIPTOR, 2.2. The Descriptor
- SHELL_ARGS_MAX, 11.5. The Command Line
- SHELL_HELP_TOPIC_MAX, 20.3. Context Help
- SHELL_NO_PRIORITY, 11.3.3. Priority
- SHELL_RUN_DOS, 11.6. Starting Other Programs
- SHELL_SAVER_ARGS, 11.8. Screen Savers
- SHELL_SAVER_END_MS, 11.8. Screen Savers
- SHELL_SAVER_GRACE_MS, 11.8. Screen Savers
- SHELL_STACK_DEFAULT, 2.2. The Descriptor
- shellActivateApp, 11.6. Starting Other Programs
- shellAppFindByPath, 11.6. Starting Other Programs
- shellAppGetPriority, 11.3.3. Priority
- shellAppSetPriority, 11.3.3. Priority
- ShellAppT, 11.6. Starting Other Programs
- shellAppTaskStart, 11.3.1. Starting the Work on a Task
- from appMain, 11.5.1. Acting on the Command Line at Start
- shellAssoc.h, 10.7. File Associations
- shellAssocCommand, 10.7. File Associations
- shellAssocLookup, 10.7. File Associations
- shellAssocOpenDocument, 10.7. File Associations
- shellAssocRemove, 10.7. File Associations
- shellAssocSet, 10.7. File Associations
- shellDataPath, 10.3.2. The DATA Folder, 17.9. Data Files and Saved Games
- shellEndTask, 11.6. Starting Other Programs
- shellEnsureUserDir, 7.5.2. Where to Start, 9.7.3. Saving Pictures, 10.3.1. The Program’s Own Folder, 17.9. Data Files and Saved Games
- shellGetRunningApp, 11.6. Starting Other Programs
- shellIsDosProgram, 11.6. Starting Other Programs
- shellLoadAppWithArgs, 11.6. Starting Other Programs
- shellMain, 3.2. Modules and the Loader
- shellMinimizeApp, 11.6. Starting Other Programs
- shellOpenHelp, 20.3.1. Opening Help from Code
- shellOpenHelpFile, 2.8. The Callbacks, 20.3.1. Opening Help from Code
- shellOpenTaskManager, 11.9. The Task Manager
- shellReapApps, 2.9. How the Program Ends
- shellRegisterAppCleanup, 18.7. State That Programs Share
- shellRegisterIdle, 11.1.2. Idle Handlers, 18.7. State That Programs Share
- shellRequestAppClose, 11.6. Starting Other Programs
- shellResolveArgs, 11.6. Starting Other Programs
- shellRun.h, 11.6. Starting Other Programs
- shellRunCommand, 11.6. Starting Other Programs
- shellRunDialog, 11.6. Starting Other Programs
- shellRunDos, 11.7. Running DOS Programs
- shellRunDosDone, 11.7. Running DOS Programs
- shellRunDosFor, 11.7. Running DOS Programs
- shellRunningAppCount, 11.6. Starting Other Programs
- shellRunningAppId, 11.6. Starting Other Programs
- shellRunProgram, 11.6. Starting Other Programs
- shellSaver.h, 11.8. Screen Savers
- shellUnregisterIdle, 11.1.2. Idle Handlers
- shellUserPath, 9.7.3. Saving Pictures, 10.3.1. The Program’s Own Folder, 17.9. Data Files and Saved Games
- SIGFPE, 22.3. Crash Reports
- SIGILL, 22.3. Crash Reports
- signal
- porting, B.3.1. Ending, Exiting, and Signals
- signals, B.3.1. Ending, Exiting, and Signals
- signatures, 21.4. Signing
- SIGSEGV, 22.3. Crash Reports
- sleep, 3.5. Cooperative Tasks
- replacing, B.3. What to Replace
- Slider, 5.6.6. Numbers: Slider, Spinner, and ProgressBar
- SO_RCVTIMEO, 14.4.2. Blocking Calls on a Task
- socket, 14.3. Sockets
- sockets, 14.3. Sockets
- dropped by DVX, 14.9. Things to Know
- ownership, 14.3. Sockets
- porting, B.2. The C Library
- Software, 21.6. Installing
- sound, 16. Sound and Music
- context, 16.2.1. Opening Sound
- drivers, 16.1. The Sound Hardware
- errors, 16.2.1. Opening Sound
- idle time, 16.13. Keeping Sound Fed
- in games, 17.8. Sound in a Game
- mixer, 16.1. The Sound Hardware
- SoundFonts, 16.8.2. Where Music Plays
- Spacer, 5.4.5. Padding, Spacing, and Alignment
- spacing, 5.4.5. Padding, Spacing, and Alignment
- Spinner, 5.5.3. Frames and Fields, 5.6.6. Numbers: Slider, Spinner, and ProgressBar
- Splitter, 5.3. Containers, 5.11.2. The Splitter and Its Panes
- SQL injection, 13.4. Values in Statements
- SQLite, 13. Databases
- dialect, 13.3. Running Statements
- stack size, 11.4.1. Stacks
- starting DVX, 1.6. Installing and Running
- static buffers, 18.7. State That Programs Share
- static data
- libraries, 18.7. State That Programs Share
- static functions, 2.2. The Descriptor, 22.9. The Binary Interface Rules
- status bars, 6.9. Status Bars
- StatusBar, 5.3. Containers, 5.11.5. The Status Bar
- stderr, B.3.2. The Console
- stdin, B.3.2. The Console
- stdout, B.3.2. The Console
- streams, 16.6. Streams
- strings
- BASIC to C, 18.9.1. Numbers and Strings Across the Boundary
- swallowTab, 5.9. Focus and Tab Order
- Switch To, 11.9. The Task Manager
- symbols
- resolving, 3.2. Modules and the Loader
- system
- system help, 20.4. Help for Widgets and Libraries
- system keys, 8.3. Who Gets a Key
T
- Tab key, 5.9. Focus and Tab Order
- terminal, 15.5. The Terminal Control
- TabControl, 5.3. Containers
- Task Manager, 3.5. Cooperative Tasks, 11.9. The Task Manager
- ending a program, 22.5. Hung Programs
- memory, 3.9. Memory
- Memory column, 22.6. Memory and Leaks
- Type column, 3.4. Two Kinds of Program
- tasks, 3.5. Cooperative Tasks, 11. Timers, Tasks, and Other Programs
- canceling, 11.3.2. The Loop and the Yield
- creating, 11.4. Tasks and Their Scheduler
- instead of threads, B.3. What to Replace
- of a callback-only program, 11.3.1. Starting the Work on a Task
- of a program, 3.4. Two Kinds of Program
- priorities, 3.5. Cooperative Tasks, 11.3.3. Priority
- scheduler, 11.4. Tasks and Their Scheduler
- stacks, 11.4.1. Stacks
- time slices, 11.3.2. The Loop and the Yield, 22.8.3. Long Work
- touching widgets, 11.3.2. The Loop and the Yield
- yielding, 3.5. Cooperative Tasks, 11.3.2. The Loop and the Yield
- taskSwch.h, 3.5. Cooperative Tasks, 11.4. Tasks and Their Scheduler
- Telnet, 15.3. Connections
- templates, 1.3. Creating a Project
- app, 2. Your First Program
- game, 17.1. Starting from the Template
- library, 18.2. The Library Template
- widget, 19.1. The Widget Template
- terminal
- Terminal control, 15.5. The Terminal Control
- testing, 22.7. Testing on Emulators and Real PCs
- libraries, 18.11. Installing and Testing
- on real PCs, 22.7.3. Real PCs
- widgets, 19.14. Installing and Testing
- text
- drawing, 9.4. The Drawing Calls
- measuring, 9.6.2. Measuring Text
- text files
- line endings, 10.4. Reading and Writing Files
- TextArea, 5.6.2. Text Boxes
- clipboard commands, 6.10. The Rest of TinyEdit
- texthelp, 19.12. The Shared Helpers
- TextInput, 5.6.2. Text Boxes
- textstat.bas, 18.9. Giving DVX BASIC the Library
- textstat.h, 18.3. The C Interface
- TEXTSTAT_VERSION, 18.6. The Binary Interface
- textstatAbiVersion, 18.6. The Binary Interface
- textStatAdd, 18.3. The C Interface
- textStatAddLine, 18.9.2. Using It from BASIC
- textStatAverage, 18.3. The C Interface
- textStatInit, 18.3. The C Interface
- textStatNew, 18.7. State That Programs Share
- textStatSummary, 18.7. State That Programs Share
- TextStatT, 18.3. The C Interface
- textStatVersion, 18.6. The Binary Interface
- textWidth, 9.6.2. Measuring Text
- textWidthN, 9.6.2. Measuring Text
- textWrap, 9.6.2. Measuring Text
- the SDK, 1. Setting Up the SDK
- contents, 1.1. What the SDK Holds
- themes, 9.5. Colors and Pixel Formats
- threads, B.3. What to Replace
- timer service, 17.5.1. The Timer Service
- Timer widget, 11.1. Timers
- timers, 3.5. Cooperative Tasks, 11. Timers, Tasks, and Other Programs
- interrupt, 11.1.3. Interrupt Timers
- one-shot, 11.1. Timers
- resolution, 11.1. Timers
- running a request, 14.8. The HTTP Get Program
- short callbacks, 14.8.1. Starting and Running the Request
- Timer widget, 11.1. Timers
- when they fire, 11.1. Timers
- .title, 20.2.1. The Source Format
- TLS, 14. Networking and the Web
- .toc, 20.2.3. The Table of Contents and the Index
- tones, 16.4. Tones
- Toolbar, 5.3. Containers
- toolbars, 6.8. Toolbars
- toolbox icon, 19.11. The Toolbox Icon and the Help
- tooltips, 5.13. Tooltips, Colors, and Fonts, 6.8. Toolbars
- .topic, 20.2.1. The Source Format
- transactions, 13.5. Transactions
- TreeView, 5.6.5. ListView and TreeView, 5.11.3. The Tree
- onChange, 5.11.6. Following the Selection
- Trust a Publisher’s Key, 21.5. Trust
- TS_DEFAULT_STACK_SIZE, 11.4.1. Stacks
- TS_MAIN_TASK_ID, 11.4. Tasks and Their Scheduler
- TS_MIN_STACK_SIZE, 11.4.1. Stacks
- TS_PRIORITY_HIGH, 3.5. Cooperative Tasks, 11.4. Tasks and Their Scheduler
- TS_PRIORITY_LOW, 11.4. Tasks and Their Scheduler
- TS_PRIORITY_NORMAL, 2.2. The Descriptor, 3.5. Cooperative Tasks, 11.4. Tasks and Their Scheduler
- tsCreate, 11.4. Tasks and Their Scheduler
- tsCurrentId, 11.4. Tasks and Their Scheduler
- tsGetName, 11.4. Tasks and Their Scheduler
- tsGetPriority, 11.4. Tasks and Their Scheduler
- tsSetPriority, 11.4. Tasks and Their Scheduler
- tsYield, 3.4. Two Kinds of Program, 11.3.2. The Loop and the Yield
- socket calls, 14.4. Waiting Without Stopping DVX
U
- UART, 15.2. The UART Driver
- types, 15.2. The UART Driver
- unpackColor, 9.5. Colors and Pixel Formats
- unresolved symbols, 3.2. Modules and the Loader, 22.4. Refused Modules, B.2. The C Library
- user folder, 7.5.2. Where to Start, 9.7.3. Saving Pictures, 10.3. Where a Program’s Files Go
- databases, 13.2. Opening a Database
- of a program, 10.3.1. The Program’s Own Folder
- rules, 10.3.3. Where Not to Write
- UserControl, 19.15. Using a Control Written in DVX BASIC
- userData, 5.1.1. The Root, 5.11.3. The Tree
- usleep, 3.5. Cooperative Tasks
- replacing, B.3. What to Replace
V
- Validate event, 13.10.3. Changing Rows
- VALIDATE_WIDGET, 19.9. The API Table
- VALIDATE_WIDGET_VOID, 19.9. The API Table
- validation, 5.5.6. Checking the Fields
- VBox, 5.3. Containers
- VENDOR, 1.5. Building, 21.1. make package, A.2. Build Settings
- vertical retrace, 17.5. Frame Pacing and Time
- VESA, 3.8. The Display
- video memory
- porting, B.3.3. The Hardware
- video modes, 3.8. The Display
- changing, 9.5. Colors and Pixel Formats
- depths, 9.5. Colors and Pixel Formats
- VOC files, 16.3. Samples and Voices
- voice limit, 16.3. Samples and Voices
- voices, 16.3. Samples and Voices
- volume, 16.7. Volume
W
- WAV files, 16.3. Samples and Voices
- wavetable synthesizer, 16.1. The Sound Hardware, 16.12. The Rest of the Sound Library
- WCLASS_FOCUSABLE, 19.3. The Class
- WCLASS_HAS_TEXT, 19.3. The Class
- WCLASS_NEEDS_POLL, 19.3. The Class
- WCLASS_ONE_LINE, 5.4.2. Weight: Sharing the Extra Room
- WCLASS_PRESS_RELEASE, 19.3. The Class
- WCLASS_SCROLLABLE, 19.3. The Class
- web requests, 14.6. The HTTP Library
- weight, 2.6. Widgets, 5.4.2. Weight: Sharing the Extra Room
- defaults, 5.4.2. Weight: Sharing the Extra Room
- -Werror, 1.5. Building
- WGT_API_HEADER, 3.11. The Binary Interface, 19.9. The API Table, 22.9. The Binary Interface Rules
- WGT_CLASS_VERSION, 19.3. The Class, 22.9. The Binary Interface Rules
- WGT_COLOR_SET, 5.13. Tooltips, Colors, and Fonts, 7.6. Colors and Fonts
- WGT_GAP_DEFAULT, 5.4.5. Padding, Spacing, and Alignment
- WGT_IFACE_INT, 19.10. The BASIC Interface
- WGT_METHOD_CALC_MIN_SIZE, 19.3. The Class, 19.5. Minimum Size and Layout
- WGT_METHOD_DESTROY, 19.3. The Class, 19.4. Creating a Widget
- WGT_METHOD_LAYOUT, 19.5. Minimum Size and Layout
- WGT_METHOD_ON_DRAG_UPDATE, 19.7. The Mouse, the Keys, and the Focus
- WGT_METHOD_ON_FORMAT_CHANGE, 9.5. Colors and Pixel Formats
- WGT_METHOD_ON_KEY, 19.7. The Mouse, the Keys, and the Focus
- WGT_METHOD_ON_MOUSE, 19.7. The Mouse, the Keys, and the Focus
- WGT_METHOD_PAINT, 19.6. Painting
- WGT_SIG_VOID, 19.10. The BASIC Interface
- WGT_WEIGHT_FILL, 2.6. Widgets, 5.4.2. Weight: Sharing the Extra Room
- wgtAnsiTerm, 15.5. The Terminal Control
- wgtAnsiTermClear, 15.5. The Terminal Control
- wgtAnsiTermCopy, 15.5. The Terminal Control
- wgtAnsiTermSetComm, 15.5. The Terminal Control
- wgtAnsiTermSetPalette, 15.5. The Terminal Control
- wgtAnsiTermSetScrollback, 15.5. The Terminal Control
- wgtAnsiTermWrite, 15.5. The Terminal Control
- WgtApiHeaderT, 19.9. The API Table
- WgtApiPrefixT, 19.9. The API Table
- wgtBackColor, 9.5. Colors and Pixel Formats
- wgtButton, 2.6. Widgets, 5.6.1. Labels and Buttons
- wgtCallMethod, 5.12. Properties by Name
- wgtCanvas, 9.2.1. Building the Window
- wgtCanvasDrawLine, 9.2.2. Drawing with the Mouse
- wgtCanvasGetDisplay, 9.3. DisplayT and the Clip Rectangle
- wgtCanvasSave, 9.7.3. Saving Pictures
- wgtCanvasSetMouseCallback, 8.10.2. Capturing the Mouse, 9.2.1. Building the Window
- wgtCanvasSetPenColor, 9.2.3. Choosing the Pen
- wgtCanvasSetPenSize, 9.2.1. Building the Window
- wgtChars, 2.6. Widgets, 5.4.4. Size Units, 6.9. Status Bars, 20.6.3. A Font the Program Carries
- wgtCheckbox, 5.6.3. Check Boxes and Radio Buttons
- wgtCheckboxIsChecked, 5.6.3. Check Boxes and Radio Buttons
- wgtCheckboxSetChecked, 5.6.3. Check Boxes and Radio Buttons
- wgtColorFromBasic, 19.10. The BASIC Interface
- wgtColorPixel, 9.5. Colors and Pixel Formats, 19.6. Painting
- wgtColorToBasic, 19.10. The BASIC Interface
- wgtComboBox, 5.6.4. Lists: ListBox, Dropdown, and ComboBox
- wgtCreateByName, 5.12. Properties by Name, 19.15. Using a Control Written in DVX BASIC
- wgtDataCtrl, 13.10. The Data Control
- wgtDataCtrlAddNew, 13.10.4. Adding and Deleting
- wgtDataCtrlDelete, 13.10.4. Adding and Deleting
- wgtDataCtrlGetCellText, 13.10.2. The Current Row and Reposition
- wgtDataCtrlGetColCount, 13.10.2. The Current Row and Reposition
- wgtDataCtrlGetColName, 13.10.2. The Current Row and Reposition
- wgtDataCtrlGetCurrentRow, 13.10.2. The Current Row and Reposition
- wgtDataCtrlGetError, 13.10.1. Telling It What to Read
- wgtDataCtrlGetField, 13.10.2. The Current Row and Reposition
- wgtDataCtrlGetRowCount, 13.10.2. The Current Row and Reposition
- wgtDataCtrlGetValidateAction, 13.10.3. Changing Rows
- wgtDataCtrlGetValidateSave, 13.10.3. Changing Rows
- wgtDataCtrlMoveFirst, 13.10.2. The Current Row and Reposition
- wgtDataCtrlMoveLast, 13.10.2. The Current Row and Reposition
- wgtDataCtrlMoveNext, 13.10.2. The Current Row and Reposition
- wgtDataCtrlMovePrev, 13.10.2. The Current Row and Reposition
- wgtDataCtrlRefresh, 13.10.1. Telling It What to Read
- wgtDataCtrlSetCurrentRow, 13.10.2. The Current Row and Reposition
- wgtDataCtrlSetField, 13.10.3. Changing Rows
- wgtDataCtrlSetMasterValue, 13.10.6. Master and Detail
- wgtDataCtrlUnload, 13.10.5. Before the Window Closes
- wgtDataCtrlUpdate, 13.10.3. Changing Rows
- wgtDbGrid, 13.11. The DBGrid
- wgtDbGridGetSelectedRow, 13.11. The DBGrid
- wgtDbGridRefresh, 13.11. The DBGrid
- wgtDbGridSetColumnHeader, 13.11. The DBGrid
- wgtDbGridSetColumnVisible, 13.11. The DBGrid
- wgtDbGridSetColumnWidth, 13.11. The DBGrid
- wgtDbGridSetDataWidget, 13.11. The DBGrid
- wgtDbGridSetSelectedRow, 13.11. The DBGrid
- wgtDestroy, 5.1.2. Who Owns What
- wgtDestroyChildren, 5.1.2. Who Owns What
- wgtDropdown, 5.6.4. Lists: ListBox, Dropdown, and ComboBox
- wgtDropdownGetSelected, 5.6.4. Lists: ListBox, Dropdown, and ComboBox
- wgtDropdownSetItems, 5.6.4. Lists: ListBox, Dropdown, and ComboBox
- WgtEventDescT, 19.10. The BASIC Interface
- wgtFind, 5.1.3. The Fields You Use
- wgtFireEvent, 5.7. Widget Events, 19.8. Firing Events
- wgtFont, 9.6.1. What a Font Is
- wgtFrame, 5.3. Containers
- wgtGetApi, 2.6. Widgets, 5.2. Widget Headers and Their APIs, 19.9. The API Table
- wgtGetContext, 5.1.1. The Root
- wgtGetDebugLayout, 5.4.6. When the Layout Runs
- wgtGetFocused, 5.9. Focus and Tab Order, 8.7. Focus
- wgtGetPaddingPx, 5.4.5. Padding, Spacing, and Alignment
- wgtGetProp, 5.12. Properties by Name, 6.5. Enabling and Graying Items
- wgtGetSpacingPx, 5.4.5. Padding, Spacing, and Alignment
- wgtGetText, 5.6. The Common Widgets
- wgtHBox, 5.3. Containers
- wgtIfaceGetPath, 20.5.4. Resources in Widgets and Libraries
- wgtIfaceIsLater, 19.15. Using a Control Written in DVX BASIC
- wgtIfaceSetType, 19.2. The Module
- WgtIfaceT, 19.10. The BASIC Interface
- wgtImage, 9.7.4. The Image and ImageButton Widgets
- wgtImageButton, 6.8. Toolbars
- wgtImageButtonFromFile, 5.6.7. Pictures, Lines, and Space, 6.8. Toolbars
- wgtImageFromFile, 5.6.7. Pictures, Lines, and Space, 9.7.4. The Image and ImageButton Widgets
- wgtInitWindow, 2.6. Widgets, 5.1.1. The Root
- handlers, 8.5. Seeing a Window’s Keys First
- handlers it installs, 4.3. Window Callbacks
- wgtInvalidate, 3.8. The Display, 5.4.6. When the Layout Runs, 9.10. Invalidating and Repainting
- wgtInvalidatePaint, 3.8. The Display, 5.4.6. When the Layout Runs, 9.10. Invalidating and Repainting, 19.6. Painting
- wgtKeyReplace, 5.7. Widget Events, 8.4. Keys in Widgets
- wgtLabel, 2.6. Widgets, 5.6.1. Labels and Buttons
- wgtLabelSetAlign, 5.6.1. Labels and Buttons
- wgtLabelSetWordWrap, 5.6.1. Labels and Buttons
- wgtListBox, 5.6.4. Lists: ListBox, Dropdown, and ComboBox
- wgtListBoxAddItem, 5.6.4. Lists: ListBox, Dropdown, and ComboBox
- wgtListBoxGetSelected, 5.6.4. Lists: ListBox, Dropdown, and ComboBox
- wgtListBoxSetItems, 5.6.4. Lists: ListBox, Dropdown, and ComboBox
- wgtListView, 5.6.5. ListView and TreeView
- wgtListViewGetCell, 5.6.5. ListView and TreeView
- wgtListViewGetSelected, 5.6.5. ListView and TreeView
- wgtListViewSetColumns, 5.6.5. ListView and TreeView
- wgtListViewSetData, 5.6.5. ListView and TreeView
- wgtListViewSetSelected, 5.11.6. Following the Selection
- wgtMaskedInput, 5.6.2. Text Boxes
- WgtMethodDescT, 19.10. The BASIC Interface
- wgtPasswordInput, 5.6.2. Text Boxes, 15.4.1. The Window
- wgtPercent, 2.6. Widgets, 5.4.4. Size Units
- wgtPixels, 2.6. Widgets, 5.4.4. Size Units
- wgtProgressBar, 5.6.6. Numbers: Slider, Spinner, and ProgressBar
- wgtProgressBarSetValue, 5.6.6. Numbers: Slider, Spinner, and ProgressBar
- WgtPropDescT, 19.10. The BASIC Interface
- wgtRadio, 5.6.3. Check Boxes and Radio Buttons
- wgtRadioGroup, 5.6.3. Check Boxes and Radio Buttons
- wgtRadioGroupGetSelected, 5.6.3. Check Boxes and Radio Buttons
- wgtRadioGroupSetSelected, 5.6.3. Check Boxes and Radio Buttons
- wgtRadioSetSelected, 5.6.3. Check Boxes and Radio Buttons
- wgtRegister, 3.2. Modules and the Loader, 19.2. The Module
- wgtRegisterApi, 19.2. The Module
- wgtRegisterClass, 19.2. The Module
- wgtRegisterIface, 19.2. The Module
- wgtResolveSize, 5.4.4. Size Units
- wgtScrollPane, 5.3. Containers
- wgtScrollPaneScrollToChild, 5.3. Containers
- wgtSeparator, 5.6.7. Pictures, Lines, and Space
- wgtSetBackdrop, 9.2.1. Building the Window
- wgtSetDebugLayout, 5.4.6. When the Layout Runs
- wgtSetEnabled, 5.8. Enabling, Hiding, and Read-Only
- wgtSetFocused, 5.5.6. Checking the Fields, 5.9. Focus and Tab Order, 6.2. One Routine for Every Command, 8.7. Focus
- wgtSetFont, 5.13. Tooltips, Colors, and Fonts, 9.6.3. Families, Sizes, and Styles, 20.6.3. A Font the Program Carries
- wgtSetName, 5.1.3. The Fields You Use
- wgtSetPaddingPx, 5.4.5. Padding, Spacing, and Alignment
- wgtSetProp, 5.12. Properties by Name
- Data control, 13.10.1. Telling It What to Read
- wgtSetReadOnly, 5.8. Enabling, Hiding, and Read-Only, 20.6.2. Licenses
- wgtSetSpacingPx, 5.4.5. Padding, Spacing, and Alignment
- wgtSetText, 3.7. A Program with a Main Loop, 5.6. The Common Widgets
- cost, 22.8.2. The Screen
- wgtSetTooltip, 5.1.2. Who Owns What, 6.8. Toolbars
- wgtSetVisible, 5.5.4. Showing a Row Only When Needed, 5.8. Enabling, Hiding, and Read-Only
- wgtSlider, 5.6.6. Numbers: Slider, Spinner, and ProgressBar
- wgtSliderGetValue, 5.6.6. Numbers: Slider, Spinner, and ProgressBar
- wgtSpacer, 5.6.7. Pictures, Lines, and Space
- wgtSpinner, 5.6.6. Numbers: Slider, Spinner, and ProgressBar
- wgtSpinnerGetValue, 5.6.6. Numbers: Slider, Spinner, and ProgressBar
- wgtSplitter, 5.3. Containers
- wgtSplitterSetPos, 5.3. Containers
- wgtStatusBar, 5.11.5. The Status Bar, 6.9. Status Bars
- wgtTabControl, 5.3. Containers
- wgtTabControlSetActive, 5.3. Containers
- wgtTabPage, 5.3. Containers
- wgtTextArea, 5.6.2. Text Boxes, 6.10. The Rest of TinyEdit
- wgtTextAreaCopy, 8.12. The Clipboard
- wgtTextAreaCut, 6.10. The Rest of TinyEdit
- wgtTextInput, 5.6.2. Text Boxes
- wgtTextInputCopy, 8.12. The Clipboard
- wgtTimer, 11.1. Timers, 14.8. The HTTP Get Program
- wgtTimerGetInterval, 11.1. Timers
- wgtTimerGetRepeat, 11.1. Timers
- wgtTimerIsRunning, 11.1. Timers
- wgtTimerSetInterval, 11.1. Timers
- wgtTimerSetRepeat, 11.1. Timers
- wgtTimerStart, 11.1. Timers, 14.8. The HTTP Get Program
- wgtTimerStop, 11.1. Timers, 14.8. The HTTP Get Program
- wgtToolbar, 6.8. Toolbars
- wgtTreeItem, 5.6.5. ListView and TreeView
- wgtTreeItemSetExpanded, 5.6.5. ListView and TreeView
- wgtTreeView, 5.6.5. ListView and TreeView
- wgtTreeViewGetSelected, 5.6.5. ListView and TreeView
- wgtTreeViewSetSelected, 5.6.5. ListView and TreeView
- wgtValueInt, 5.12. Properties by Name
- wgtValueStr, 5.12. Properties by Name
- WgtValueT, 5.12. Properties by Name
- wgtValueToInt, 5.12. Properties by Name
- wgtVBox, 5.3. Containers
- wgtVSeparator, 6.8. Toolbars
- wgtWrapBox, 5.3. Containers
- WidgetAlignE, 5.4.5. Padding, Spacing, and Alignment
- widgetAlloc, 19.4. Creating a Widget
- widgetAllocRollback, 19.4. Creating a Widget
- widgetAllocWithText, 19.4. Creating a Widget
- WidgetClassT, 19.3. The Class
- widgetFireChange, 19.8. Firing Events
- widgetIsEnabledChain, 5.8. Enabling, Hiding, and Read-Only, 19.6. Painting
- widgetOnBlur, 4.3. Window Callbacks, 5.1.1. The Root
- widgetOnFocus, 4.3. Window Callbacks, 5.1.1. The Root
- widgetOnResize, 4.3. Window Callbacks, 5.1.1. The Root
- widgetPressOnChrome, 19.7. The Mouse, the Keys, and the Focus
- widgets, 5. Widgets and Layout
- API tables, 5.2. Widget Headers and Their APIs
- BASIC interface, 19.10. The BASIC Interface
- C API, 19.9. The API Table
- class, 19.3. The Class
- class flags, 19.3. The Class
- colors, 7.6. Colors and Fonts, 9.5. Colors and Pixel Formats
- containers, 5.3. Containers, 19.5. Minimum Size and Layout
- creating, 19.4. Creating a Widget
- destroying, 19.4. Creating a Widget
- enabling, 5.8. Enabling, Hiding, and Read-Only
- events, 19.8. Firing Events
- fields, 5.1.3. The Fields You Use
- fonts, 9.6.3. Families, Sizes, and Styles
- headers, 5.2. Widget Headers and Their APIs
- helper libraries, 19.12. The Shared Helpers
- hiding, 5.8. Enabling, Hiding, and Read-Only
- key events, 8.4. Keys in Widgets
- keys, 19.7. The Mouse, the Keys, and the Focus
- loading, 3.2. Modules and the Loader, 19.2. The Module
- memory, 5.1.2. Who Owns What
- minimum size, 19.5. Minimum Size and Layout
- module, 19.2. The Module
- mouse, 19.7. The Mouse, the Keys, and the Focus
- mouse events, 8.10.1. Mouse Events in Widgets
- not installed, 5.2. Widget Headers and Their APIs, 13.10. The Data Control, 19.13. A Program That Uses It
- painting, 19.6. Painting
- parent, 5.1. The Widget Tree
- properties, 5.12. Properties by Name
- refused, 22.4. Refused Modules
- registering, 19.2. The Module
- root, 2.6. Widgets, 5.1.1. The Root
- tree, 5.1. The Widget Tree
- writing, 19. Writing a Widget
- WidgetT, 5.1. The Widget Tree
- contextMenu, 6.6. Context Menus
- widgetTextGet, 19.4. Creating a Widget
- widgetTextSet, 19.4. Creating a Widget
- wild pointers, 22.3.5. Errors That Do Not Fault
- wildcards, 10.6.1. Listing a Folder
- windows, 4. Windows
- callbacks, 2.4. Creating the Window, 4.3. Window Callbacks
- closing, 4.3.3. Closing: onClose
- content area, 4.2. Creating a Window
- content buffer, 3.8. The Display
- creating, 2.4. Creating the Window, 4.2. Creating a Window
- deferred destruction, 4.3.3. Closing: onClose
- destroying, 2.8. The Callbacks, 3.6. The Event Loop, 4.3.3. Closing: onClose
- disabling, 4.7. Raising, Lowering, Hiding, and Showing
- fitting to content, 4.5. Fitting a Window to Its Controls
- focus, 4.3.2. Focus: onFocus and onBlur, 8.7. Focus
- focused, 20.3. Context Help
- for games, 17.2.1. The Game’s Window
- hiding, 4.7. Raising, Lowering, Hiding, and Showing
- icon, 4.4. Titles and Icons
- id, 4.9. Several Windows in One Program
- key events, 8.5. Seeing a Window’s Keys First
- last window, 4.12. Ending the Program
- maximizing, 4.8. Minimizing, Maximizing, and Restoring
- maximum size, 4.2.1. Resizable Windows and Size Limits
- minimizing, 4.8. Minimizing, Maximizing, and Restoring
- minimum size, 4.2.1. Resizable Windows and Size Limits
- modal, 4.10. Modal Windows
- mouse events, 8.10.3. The Mouse at the Window Level
- moving from code, 4.6. Moving and Resizing from Code
- placing on the screen, 4.2. Creating a Window
- position, 4.2. Creating a Window
- resizable, 4.2.1. Resizable Windows and Size Limits
- resizing, 4.3.1. Resizing: onResize
- resizing from code, 4.6. Moving and Resizing from Code
- restoring, 4.8. Minimizing, Maximizing, and Restoring
- saving the place, 10.5. Settings Files
- scroll bars, 5.3. Containers
- several in one program, 4.9. Several Windows in One Program
- title, 4.4. Titles and Icons
- userData, 4.3. Window Callbacks
- without widgets, 4.11. Windows Without Widgets, 8.6. Windows Without Widgets, 9.9. Drawing in a Window Without Widgets
- z-order, 4.7. Raising, Lowering, Hiding, and Showing
- WindowT, 4.2. Creating a Window
- callbacks, 4.3. Window Callbacks
- contextMenu, 6.6. Context Menus
- disabled, 4.7. Raising, Lowering, Hiding, and Showing
- modal, 4.10. Modal Windows
- WM_MAX_FROM_SCREEN, 4.2.1. Resizable Windows and Size Limits
- wmAddMenu, 2.5. The Menu Bar, 6.3. Building a Menu Bar
- wmAddMenuBar, 2.5. The Menu Bar, 6.3. Building a Menu Bar
- wmAddMenuCheckItem, 6.4. Check Items, Radio Items, and Submenus
- wmAddMenuItem, 2.5. The Menu Bar, 6.3. Building a Menu Bar
- wmAddMenuRadioItem, 6.4. Check Items, Radio Items, and Submenus
- wmAddMenuSeparator, 2.5. The Menu Bar, 6.3. Building a Menu Bar
- wmAddSubMenu, 6.4. Check Items, Radio Items, and Submenus
- wmClampWindowPos, 4.6. Moving and Resizing from Code
- wmCreateMenu, 6.6. Context Menus
- wmFreeMenu, 6.6. Context Menus
- wmMenuFindItemInMenu, 6.5. Enabling and Graying Items
- wmMenuItemIsChecked, 6.4. Check Items, Radio Items, and Submenus
- wmMenuItemSetChecked, 6.4. Check Items, Radio Items, and Submenus
- wmMenuItemSetCheckedInMenu, 6.6. Context Menus
- wmMenuItemSetEnabled, 6.5. Enabling and Graying Items
- wmMenuItemSetEnabledInMenu, 6.5. Enabling and Graying Items
- wmMenuItemSetLabel, 6.5. Enabling and Graying Items
- wmMinWindowSize, 4.2.1. Resizable Windows and Size Limits
- wmSetIconData, 4.4. Titles and Icons
- wmWindowById, 4.9. Several Windows in One Program
- WrapBox, 5.3. Containers
X
- X25519, 15.6.3. What the Secure Link Protects
- XChaCha20-Poly1305, 15.6.3. What the Secure Link Protects
- xfer.h, 15.8. File Transfers
- xferAnswer, 15.8. File Transfers
- xferCancel, 15.8. File Transfers
- xferCreate, 15.8. File Transfers
- xferDestroy, 15.8. File Transfers
- xferDetectFeed, 15.8. File Transfers
- XferExistE, 15.8. File Transfers
- XferIoT, 15.8. File Transfers
- XferOptionsT, 15.8. File Transfers
- xferPoll, 15.8. File Transfers
- xferProgress, 15.8. File Transfers
- XferProgressT, 15.8. File Transfers
- xferStartReceive, 15.8. File Transfers
- xferStartSend, 15.8. File Transfers
- XferStatusE, 15.8. File Transfers
- XMODEM, 15.8. File Transfers
- XON/XOFF, 15.2. The UART Driver
Y
- YMODEM, 15.8. File Transfers
Z
- ZMODEM, 15.8. File Transfers
- auto-start, 15.8. File Transfers