DVX BASIC IDE Guide
-DVX BASIC is a Visual BASIC development environment for the DVX GUI System. It provides a VB3-style integrated development environment with a code editor, form designer, project system, and a full interactive debugger -- all running natively on DOS under the DVX windowing system.
+DVX BASIC is a Visual BASIC development environment for DVX. It provides a VB3-style integrated development environment with a code editor, form designer, project system, and a full interactive debugger -- all integrated into DVX itself.
This guide covers every feature of the IDE: menus, toolbar, editor, form designer, project management, debugger, and auxiliary windows.
IDE Windows
The DVX BASIC IDE is modeled after Visual Basic 3.0. It consists of several floating windows arranged on the DVX desktop:
@@ -599,7 +624,7 @@ img { max-width: 100%; }Debug Windows -- Locals, Call Stack, Watch, and Breakpoints windows that appear automatically when debugging.
-The IDE compiles BASIC source into bytecode and runs it in an integrated virtual machine (VM). Programs execute in cooperative slices (10,000 VM steps per slice), yielding to the DVX event loop between slices so the GUI remains responsive.
+The IDE compiles BASIC source into bytecode and runs it in an integrated virtual machine. Programs execute in cooperative slices, yielding to DVX between slices so the GUI remains responsive. Call DoEvents in long-running loops to keep the event loop flowing.
@@ -639,6 +664,8 @@ img { max-width: 100%; } Save File Ctrl+S Save the active file to disk. Save All Save all modified files in the project. --- + Make Executable... Compile the project and save it as a standalone .app file. Prompts for a debug or release build. + --- Remove File Remove the selected file from the project (prompts to save if modified). --- Exit Close the IDE (prompts to save unsaved changes). @@ -677,6 +704,8 @@ img { max-width: 100%; } Step Out Ctrl+Shift+F8 Run until the current SUB/FUNCTION returns. Run to Cursor Ctrl+F8 Run until execution reaches the line where the cursor is positioned. --- + Output Window to Log Checkbox: when enabled, PRINT output is also mirrored to the DVX log. Persisted in preferences. + --- Toggle Breakpoint F9 Toggle a breakpoint on the current editor line. --- Clear Output Clear the Output window. @@ -729,9 +758,12 @@ img { max-width: 100%; }Function -- lists all event handlers (procedures) for the selected object. Implemented handlers are listed first (plain text); unimplemented handlers follow in brackets (e.g., [Click]). Selecting an unimplemented event creates a new event handler stub.
The editor shows one procedure at a time. Each procedure has its own buffer, and switching between them is instantaneous. The (General) section contains module-level declarations and code.
Syntax Highlighting
-The editor applies real-time syntax coloring as you type. The following categories are highlighted in distinct colors:
+The editor applies real-time syntax coloring as you type. Seven categories are highlighted in distinct colors; the colors themselves are editable in Tools > Preferences > Colors.
Category Examples -------- -------- + Default Text Identifiers, whitespace. Keywords IF, THEN, FOR, NEXT, SUB, FUNCTION, DIM, PRINT, SELECT, CASE, DO, LOOP, WHILE, WEND, END, EXIT, CALL, GOSUB, GOTO, RETURN, DECLARE, CONST, TYPE, AND, OR, NOT, XOR, MOD, etc. - Type names INTEGER, LONG, SINGLE, DOUBLE, STRING, BOOLEAN, BYTE, TRUE, FALSE - String literals "Hello, World!" + Types INTEGER, LONG, SINGLE, DOUBLE, STRING, BOOLEAN, TRUE, FALSE + Strings "Hello, World!" Comments ' This is a comment, REM This is a comment - Numbers 42, 3.14 + Numbers 42, 3.14, &HFF Operators =, <, >, +, -, *, /, \, &
Editor Features
-
@@ -797,7 +830,7 @@ img { max-width: 100%; }
- Grid snapping -- controls snap to an 8-pixel grid (DSGN_GRID_SIZE) when placed or resized. +
- Grid snapping -- controls snap to an 8-pixel grid when placed or resized.
- Selection -- click a control to select it. The selected control is highlighted with grab handles.
- Grab handles -- 6x6 pixel handles appear on the right edge (E), bottom edge (S), and bottom-right corner (SE) of the selected control. Drag a handle to resize the control.
- Reordering -- drag a control vertically to reorder it within the form's layout (VBox/HBox). @@ -820,9 +853,9 @@ img { max-width: 100%; }
- Startup Form -- which form to show automatically when the program starts.
- Metadata -- Author, Company, Version, Copyright, Description, and Icon Path (for compiled binaries).
The Form Designer provides a visual design surface for editing .frm files. Switch to it with Shift+F7 or the Design toolbar button. It opens in a separate window showing a WYSIWYG preview of the form.
Design Surface
-
-
File list -- relative paths (8.3 DOS names) of all .bas and .frm files in the project. Each entry tracks whether it is a form file.
-Source Map
-When the project is compiled, all files are concatenated into a single source stream. A source map tracks which lines belong to which file, enabling accurate error reporting and debugger navigation across multiple files. For .frm files, an injected BEGINFORM directive is prepended to the code section.
+File list -- relative paths of all .bas and .frm files in the project. Each entry tracks whether it is a form file.
+How Projects are Compiled
+When the project is compiled, all source files are concatenated into a single source stream. The IDE tracks which lines belong to which file so error messages and debugger locations point to the correct .bas or .frm file. The code section of each .frm file is preceded by a hidden BEGINFORM marker that ties its code to its form.
Project Operations
Operation Description
--------- -----------
@@ -850,7 +883,7 @@ img { max-width: 100%; }
Toolbox
-The Toolbox (Window > Toolbox) is a floating palette of buttons, one for each available control type. Controls are loaded dynamically from the widget plugin registry -- any widget DXE that provides a basName appears in the toolbox.
+The Toolbox (Window > Toolbox) is a floating palette of buttons, one for each available control type. Every widget registered with DVX that has a BASIC name appears in the toolbox.
Click a tool to select it (the active tool name is stored in the designer state), then click on the form to place a new instance. Click the same tool again to deselect it and return to pointer mode.
Available Controls
VB Name Description
@@ -892,12 +925,12 @@ img { max-width: 100%; }
Debugger
-The DVX BASIC IDE includes a full interactive debugger. The debugger operates as a state machine with three states:
-State Description - ----- ----------- - DBG_IDLE No program loaded or running. - DBG_RUNNING Program is executing (VM running in slices). - DBG_PAUSED Execution is paused at a breakpoint or step point. The IDE GUI is fully interactive.+
The DVX BASIC IDE includes a full interactive debugger. The debugger has three states:
+State Description + ----- ----------- + Idle No program loaded or running. + Running The program is executing. + Paused Execution is paused at a breakpoint or step point. The IDE is fully interactive -- you can inspect and change variables, set or clear breakpoints, step, continue, or stop.
Starting a Debug Session
- Shift+F5 (Debug) -- compiles the project and starts execution in debug mode. Breakpoints are active but execution does not pause at the first statement. @@ -919,7 +952,7 @@ img { max-width: 100%; }
END SUB and END FUNCTION lines
Breakpoint Storage
-Each breakpoint records the project file index, the code line number within the file, the procedure index, and the procedure name (as Object.Event). When the project is compiled, breakpoints are converted to concatenated source line numbers that match the VM's OP_LINE opcodes.
+Each breakpoint records the file it belongs to, the line number within that file, and the procedure name (Object.Event). Breakpoints are stored in the project and survive compilation.
Visual Indicators
- Breakpoint lines show a red dot in the gutter. @@ -934,16 +967,16 @@ img { max-width: 100%; } Step Over Shift+F8 Execute one statement. If the statement is a SUB/FUNCTION call, execute the entire call and break at the next line in the current scope. Step Out Ctrl+Shift+F8 Run until the current SUB/FUNCTION returns to its caller. Run to Cursor Ctrl+F8 Run until execution reaches the line under the cursor. -
- The VM executes up to 10,000 steps per slice. -
- If the VM hits a breakpoint (BAS_VM_BREAKPOINT), the state transitions to DBG_PAUSED. The IDE navigates the code editor to the breakpoint line, highlights it in yellow, auto-opens the Locals and Call Stack windows, and updates all debug windows. -
- While paused, the IDE pumps dvxUpdate() continuously, keeping the GUI responsive. The user can inspect variables, modify them in the Immediate window, step, continue, or stop. +
- The program runs in short cooperative slices so the IDE remains responsive. +
- When the program hits a breakpoint, execution pauses immediately. The IDE switches to Code View, navigates to the breakpoint line, highlights it in yellow, and opens the Locals and Call Stack windows if they are not already visible. +
- While paused, you can inspect variables in Locals and Watch, evaluate expressions in the Immediate window, assign new values to variables, toggle breakpoints, step, continue, or stop.
The Debug Run Loop
-When a program is running in debug mode, the IDE enters a cooperative loop:
+Debug Run Behavior
+When a program is running under the debugger:
-
-
When the user resumes (F5/Shift+F5/F8/etc.), the state transitions back to DBG_RUNNING and the loop continues.
+Resuming (F5, Shift+F5, or any Step command) returns the program to Running state.
Stopping
-Press Esc or click the Stop toolbar button at any time to halt execution. The VM is destroyed, debug state resets to DBG_IDLE, and the IDE restores the designer windows that were hidden at run start.
+Press Esc or click the Stop toolbar button at any time to halt execution. The program is terminated, the debugger returns to Idle, and the IDE restores any designer or code windows that were hidden at the start of the run.
@@ -1034,7 +1067,7 @@ img { max-width: 100%; }LET x = 42 -- explicit assignment (see below).
Parse or runtime errors are displayed inline with an Error: prefix.
Inspecting Variables While Paused
-When the debugger is paused at a breakpoint, the Immediate window has access to the running VM's state. Global variable values are copied into the evaluation VM, so expressions like count or name$ & " test" display live values.
+When the debugger is paused at a breakpoint, the Immediate window has access to the running program's state. Expressions like count or name$ & " test" display live values.
Assigning Variables While Paused
When paused, you can modify variables in the running program directly from the Immediate window using assignment syntax:
variableName = newValue
@@ -1047,7 +1080,7 @@ img { max-width: 100%; }
Combined -- items(0).price = 9.99
-The new value is written directly into the VM's live variable slot (local, global, or form scope). A confirmation message is displayed, and the Locals and Watch windows update automatically to reflect the change.
+The new value is written directly into the running program's variable (local, global, or form scope). A confirmation message is displayed, and the Locals and Watch windows update automatically to reflect the change.
If the assignment target cannot be resolved (unknown variable, out-of-bounds index, wrong type), an error message is displayed.
Preferences
-Open via Tools > Preferences. Settings are saved to dvxbasic.ini in the app's config directory.
-Editor Section
-Setting Description Default - ------- ----------- ------- - Skip comments/strings when renaming When renaming a control or form, skip occurrences inside comments and string literals. On - Require variable declaration (OPTION EXPLICIT) When enabled, variables must be declared with DIM before use. Off - Tab width Number of spaces per tab stop (1-8). 3 - Insert spaces instead of tabs When enabled, pressing Tab inserts spaces. When disabled, inserts a real tab character. On-
New Project Defaults Section
+Open via Tools > Preferences. Settings are saved to dvxbasic.ini in the app's config directory. The dialog has two tabs.
+General Tab
+Editor Section
+Setting Description Default + ------- ----------- ------- + Skip comments/strings when renaming When renaming a control or form, skip occurrences inside comments and string literals. On + Require variable declaration (OPTION EXPLICIT) When enabled, newly created projects have OPTION EXPLICIT on by default. Off + Tab width Number of spaces per tab stop. 3 + Insert spaces instead of tabs When enabled, pressing Tab inserts spaces. When disabled, inserts a real tab character. On+
New Project Defaults Section
These fields set the default values for new project metadata:
-Field Description Default - ----- ----------- ------- - Author Default author name. (empty) - Company Default company name. (empty) - Version Default version string. 1.0 - Copyright Default copyright notice. (empty) - Description Default project description (multi-line). (empty)+
Field Description Default + ----- ----------- ------- + Author Default author name. (empty) + Publisher Default publisher/company name. (empty) + Version Default version string. 1.0 + Copyright Default copyright notice. (empty) + Description Default project description (multi-line). (empty)+
Colors Tab
+Customizes the syntax-highlighting colors used in the code editor. The left side is a list of seven color entries (Default Text, Keywords, Strings, Comments, Numbers, Operators, Types). Select an entry and adjust its red, green, and blue components using the three sliders on the right. The Preview swatch shows the current color. Changes are applied to the open editor when you click OK.
Numeric Literals
-Form Example Description - ---- ------- ----------- - Decimal integer 42 Values -32768..32767 are Integer; larger are Long - Hex integer &HFF Hexadecimal literal - Long suffix 42&, &HFF& Force Long type - Floating-point 3.14, 1.5E10 Double by default - Single suffix 3.14! Force Single type - Double suffix 3.14# Force Double type+
Form Example Description + ---- ------- ----------- + Decimal integer 42 Values -32768..32767 are Integer; larger are Long + Hex integer &HFF, &H1234 Hexadecimal literal + Integer suffix 42% Force Integer type + Long suffix 42&, &HFF& Force Long type + Floating-point 3.14, 1.5E10, 2.5D3 Any number containing a decimal point or exponent is Double by default + Single suffix 3.14! Force Single type + Double suffix 3.14# Force Double type+
Note: Both E and D can introduce an exponent (e.g. 1.5E10 and 2.5D3 are equivalent forms of a scientific-notation double).
Type Promotion
When mixing types in expressions, values are automatically promoted to a common type: Integer -> Long -> Single -> Double. Strings are not automatically converted to numbers (use VAL and STR$).
+Boolean Values
+Boolean values use -1 for True and 0 for False. Any non-zero numeric value is treated as True in a conditional context. The keywords True and False are reserved and may be used anywhere a Boolean value is expected.
Operators
-Operators listed from highest precedence (evaluated first) to lowest precedence (evaluated last).
+Operators listed from highest precedence (evaluated first) to lowest precedence (evaluated last). Parentheses override precedence and may be nested freely.
Precedence Operator Description ---------- -------- ----------- 1 (highest) ^ Exponentiation - 2 - (unary) Negation - 3 * / \ MOD Multiply, float div, integer div, modulus - 4 + - Addition, subtraction + 2 - (unary), + (unary) Negation (unary plus is a no-op) + 3 * / \ MOD Multiply, float divide, integer divide, modulus + 4 + - Addition, subtraction (+ also concatenates strings) 5 & String concatenation 6 = <> < > <= >= Comparison (returns Boolean) 7 NOT Logical/bitwise NOT 8 AND Logical/bitwise AND - 9 XOR Logical/bitwise XOR + 9 XOR Logical/bitwise exclusive-or 10 OR Logical/bitwise OR 11 EQV Logical/bitwise equivalence 12 (lowest) IMP Logical/bitwise implication+
Arithmetic Operators
+Operator Description + -------- ----------- + + Addition (or string concatenation when both operands are strings) + - Subtraction (or negation when used as a unary prefix) + * Multiplication + / Floating-point division (result is always Single or Double) + \ Integer division (result is Long, fractional part discarded) + MOD Integer modulus (remainder) + ^ Exponentiation (result is Double)+
Comparison Operators
+Comparison operators return True (-1) or False (0).
+Operator Description + -------- ----------- + = Equal to + <> Not equal to + < Less than + > Greater than + <= Less than or equal to + >= Greater than or equal to+
String comparisons are controlled by OPTION COMPARE. With OPTION COMPARE BINARY (the default) strings are compared by byte value. With OPTION COMPARE TEXT comparisons are case-insensitive.
+Logical / Bitwise Operators
+The logical operators work on Boolean values and also perform bitwise operations on integer values.
+Operator Description + -------- ----------- + NOT Logical/bitwise complement + AND Logical/bitwise AND + OR Logical/bitwise OR + XOR Logical/bitwise exclusive-or + EQV Logical/bitwise equivalence (same as NOT (a XOR b)) + IMP Logical/bitwise implication (same as (NOT a) OR b)
String Concatenation
-Use & to concatenate strings. The + operator also concatenates when both operands are strings.
+Use & to concatenate strings. The + operator also concatenates when both operands are strings. Prefer & because it does not depend on operand types.
result$ = "Hello" & " " & "World"
-result$ = firstName$ & " " & lastName$
+result$ = firstName$ & " " & lastName$
+
+' + also concatenates when both operands are strings
+greeting$ = "Hi " + name$
Statements
-Multiple statements can appear on one line separated by :. Lines can be continued with _ at the end. Comments start with ' or REM.
-Declaration Statements (DIM, REDIM, CONST, TYPE)
+Multiple statements can appear on one line separated by : (colon). A line can be continued onto the next physical line by ending it with an underscore (_) preceded by whitespace. Comments start with ' (apostrophe) or the REM keyword and run to the end of the line. The character ? is a shorthand for PRINT.
+a = 10 : b = 20 : c = a + b ' three statements on one line
+
+total = price * quantity _
+ + shipping + tax ' one statement continued across lines
+
+REM This is a comment
+' So is this
+? "Hello" ' same as PRINT "Hello"
+Declaration Statements (DIM, REDIM, CONST, TYPE, DECLARE)
Conditional Statements (IF, SELECT CASE)
Loop Statements (FOR, DO, WHILE)
Procedures (SUB, FUNCTION, DEF FN)
Flow Control (EXIT, CALL, GOTO, GOSUB, ON)
- +Declaration Statements
DIM
-Declares variables and arrays with an explicit type.
+Declares variables and arrays with an explicit type. If no type is given, the type defaults to whatever DEFtype (if any) is in effect for the variable's first letter; without a DEFtype statement the default is Single.
DIM variable AS type
DIM variable(upperBound) AS type
DIM variable(lower TO upper) AS type
@@ -1219,6 +1302,8 @@ DIM variable(dim1, dim2, ...) AS type
DIM variable AS UdtName
DIM variable AS STRING * n
DIM SHARED variable AS type
+Multiple variables can be declared at module level so their values persist between procedure calls. Arrays can have up to 8 dimensions. A variable declared with type suffix does not need the AS clause:
+Dim name$, count%, total& ' suffixes infer the types
Examples:
Dim name As String
Dim count As Integer
@@ -1227,7 +1312,8 @@ Dim matrix(1 To 10, 1 To 10) As Single
Dim Shared globalFlag As Boolean
Dim record As PersonType
Dim fixedStr As String * 20
-Note: DIM SHARED makes a variable accessible from all procedures without passing it as a parameter.+
Note: DIM SHARED at module level makes a variable accessible from every procedure without passing it as a parameter. Inside a SUB or FUNCTION, DIM declares a local variable that is recreated on each call (use STATIC to retain its value between calls).+
Fixed-length strings (STRING * n) are padded with spaces and truncated when assigned so their length is always exactly n.
REDIM
Reallocates a dynamic array, optionally preserving existing data.
REDIM array(newBounds) AS type
@@ -1235,12 +1321,15 @@ REDIM PRESERVE array(newBounds) AS type
ReDim items(newSize) As String
ReDim Preserve scores(1 To newCount) As Integer
CONST
-Declares a named constant. The value must be a literal (integer, float, string, or boolean).
-CONST name = value
+Declares a named constant. The value must be a literal (integer, long, float, string, or boolean). Constants are not variables -- you cannot assign a new value to them or pass them by reference.
+CONST name = value
+CONST name AS type = value
Const MAX_SIZE = 100
Const PI = 3.14159265
Const APP_NAME = "DVX App"
-Const DEBUG_MODE = True
+Const DEBUG_MODE = True
+Const HEADER As String = "=== Report ==="
+Constants are scoped to the file or procedure in which they are declared. Constants declared at module level are visible to all procedures in the same module.
TYPE...END TYPE
Defines a user-defined type (record/structure).
TYPE TypeName
@@ -1258,20 +1347,20 @@ p.firstName = "Scott"
p.age = 30
UDT fields can themselves be UDTs (nested types).
DECLARE
-Forward-declares a SUB or FUNCTION. Required when a procedure is called before it is defined.
-DECLARE SUB name ([BYVAL] param AS type, ...)
-DECLARE FUNCTION name ([BYVAL] param AS type, ...) AS returnType
+Forward-declares a SUB or FUNCTION. This is rarely required because the compiler supports forward references within a module, but it is still accepted for compatibility:
+DECLARE SUB name ([BYVAL] [OPTIONAL] param AS type, ...)
+DECLARE FUNCTION name ([BYVAL] [OPTIONAL] param AS type, ...) AS returnType
DECLARE LIBRARY
-Declares external native functions from a dynamically loaded library. This allows BASIC programs to call functions exported by DXE libraries.
+Declares external functions from a native library bundled with DVX. This is how BASIC programs reach operating-system services, serial ports, databases, and other native facilities. Rather than writing DECLARE LIBRARY blocks yourself, add one of the shipped include files (such as commdlg.bas or sql.bas) to your project; the include file contains the proper declarations.
DECLARE LIBRARY "libraryName"
DECLARE SUB name ([BYVAL] param AS type, ...)
DECLARE FUNCTION name ([BYVAL] param AS type, ...) AS returnType
END DECLARE
-Declare Library "rs232"
- Declare Function ComOpen(ByVal port As Integer) As Integer
- Declare Sub ComClose(ByVal port As Integer)
- Declare Sub ComSend(ByVal port As Integer, ByVal data$ As String)
+Declare Library "basrt"
+ Declare Function SQLOpen(ByVal path As String) As Integer
+ Declare Sub SQLClose(ByVal db As Integer)
End Declare
+See also: BASIC Runtime Libraries
STATIC
Declares a local variable that retains its value between calls.
STATIC variable AS type
@@ -1304,11 +1393,18 @@ udt.field = expression
LET variable = expression
The LET keyword is optional and supported for compatibility.
SWAP
-Exchanges the values of two variables.
+Exchanges the values of two variables. The variables must be the same type.
SWAP variable1, variable2
Swap a, b
+SET
+Assigns an object reference (form or control) to a variable. Required when creating a form or control with CreateForm / CreateControl so that the returned reference is stored in the variable:
+SET variable = objectExpression
+Dim frm As Long
+Set frm = CreateForm("MyForm", 320, 240)
+frm.Caption = "Built in code"
+For ordinary numeric or string assignment, SET is not used.
ERASE
-Frees the memory of an array and resets it.
+Frees the memory of a dynamic array and resets it to undimensioned state. Fixed-size arrays (declared with constant bounds) reset their elements but keep their shape.
ERASE arrayName
Procedures
SUB...END SUB
Defines a subroutine (no return value).
-SUB name ([BYVAL] param AS type, ...)
+SUB name ([BYVAL] [OPTIONAL] param AS type, ...)
statements
END SUB
Sub Greet(ByVal name As String)
Print "Hello, " & name
End Sub
-Parameters are passed ByRef by default. Use ByVal for value semantics. Use EXIT SUB to return early.
+Parameters are passed by reference by default. Use ByVal for value semantics; there is no separate ByRef keyword (omitting ByVal is the by-reference form). Use EXIT SUB to return early. A SUB is called either with or without parentheses; when used as a statement, parentheses are optional:
+Greet "World"
+Greet("World")
+Call Greet("World")
+Optional Parameters
+Mark a parameter OPTIONAL to allow callers to omit it. An optional parameter must be positioned after all required parameters and receives an empty/zero default when not supplied.
+Sub Announce(ByVal msg As String, Optional ByVal loud As Integer)
+ If loud Then
+ Print UCase$(msg)
+ Else
+ Print msg
+ End If
+End Sub
+
+Announce "hello" ' loud defaults to 0
+Announce "hello", True ' loud is -1
FUNCTION...END FUNCTION
Defines a function with a return value.
-FUNCTION name ([BYVAL] param AS type, ...) AS returnType
+FUNCTION name ([BYVAL] [OPTIONAL] param AS type, ...) AS returnType
statements
name = returnValue
END FUNCTION
@@ -1430,10 +1541,13 @@ END FUNCTION
End Function
Assign to the function name to set the return value. Use EXIT FUNCTION to return early.
DEF FN
-Defines a single-expression function.
+Defines a single-expression function. The function name begins with FN and is invoked just like a normal function. DEF FN functions cannot span multiple statements.
DEF FNname(params) = expression
Def FnSquare(x) = x * x
-Print FnSquare(5) ' prints 25
+Print FnSquare(5) ' prints 25
+
+Def FnCelsius(f As Double) = (f - 32) * 5 / 9
+Print FnCelsius(212) ' prints 100
Flow Control
@@ -1470,24 +1584,45 @@ ON expression GOSUB label1, label2, ...Input/Output Statements
Outputs text to the console or to a file channel.
-PRINT [expression] [{; | ,} expression] ...
-PRINT #channel, expression
+Writes expressions to the output window (or to a file channel).
+PRINT [expression [{; | ,} expression] ...]
+PRINT #channel, expression [; expression] ...
PRINT USING format$; expression [; expression] ...
-- ; between items -- no separator (items are concatenated)
+- ; between items -- no separator (items appear next to each other, or separated by a space for numbers)
- , between items -- advance to the next 14-column tab zone
-- Trailing ; or , suppresses the newline
+- A trailing ; or , suppresses the newline normally written at the end of the statement
? is an alias for PRINT
Special functions inside PRINT:
- SPC(n) -- print n spaces
-TAB(n) -- advance to column n
+TAB(n) -- advance to column n (first column is 1)
Print "Name:"; Tab(20); name$
-Print Using "###.##"; total
+Print "X="; x, "Y="; y ' comma = next 14-column zone
Print #1, "Written to file"
+PRINT USING
+PRINT USING formats each following expression according to a format string and prints the result. If more expressions are supplied than the format string consumes, the format string is reused from the start for each.
+ Format character Meaning
+ ---------------- -------
+ # Digit (replaced with a digit or space to pad on the left)
+ . Decimal-point position
+ , Insert thousands separator
+ + At start or end: always show a sign character
+ - At end: show a trailing minus sign only when negative
+ ** At start: fill leading spaces with asterisks
+ $$ At start: floating dollar sign
+ ^^^^ Anywhere: format the value in scientific notation
+ ! First character of a string only
+ & Entire string (variable length)
+ \ ... \ Fixed-length string field (width = 2 + number of spaces between backslashes)
+Print Using "###.##"; 3.14159 ' " 3.14"
+Print Using "$$#,##0.00"; 1234567.89 ' "$1,234,567.89"
+Print Using "**#,##0.00"; 42.5 ' "*****42.50"
+Print Using "####.####^^^^"; 0.000123 ' scientific notation
+Print Using "\ \"; "Hello" ' fixed-width 4-char: "Hell"
+Print Using "& likes &"; name$; food$
INPUT
Reads a line of text from the user or from a file channel.
INPUT variable
@@ -1510,11 +1645,11 @@ Restore
Miscellaneous Statements
Error Handling
ON ERROR GOTO label ' Enable error handler
-ON ERROR GOTO 0 ' Disable error handler
-RESUME ' Retry the statement that caused the error
-RESUME NEXT ' Continue at the next statement after the error
-ERROR n ' Raise a runtime error with error number n
-The ERR keyword returns the current error number in expressions.
+ON ERROR GOTO 0 ' Disable error handler
+RESUME ' Retry the statement that caused the error
+RESUME NEXT ' Continue at the next statement after the error
+ERROR n ' Raise a runtime error with error number n
+The ERR keyword returns the current error number in expressions (it is 0 when no error is active).
On Error GoTo ErrorHandler
Open "missing.txt" For Input As #1
Exit Sub
@@ -1522,21 +1657,39 @@ Exit Sub
ErrorHandler:
Print "Error number:"; Err
Resume Next
+Common Error Numbers
+Number Meaning + ------ ------- + 1 FOR loop error (NEXT without FOR, NEXT variable mismatch, FOR stack underflow) + 4 Out of DATA + 7 Out of memory + 9 Subscript out of range / invalid variable or field index + 11 Division by zero + 13 Type mismatch / not an array / not a TYPE instance + 26 FOR loop nesting too deep + 51 Internal error (bad opcode) + 52 Bad file number or file not open + 53 File not found + 54 Bad file mode + 58 File already exists or rename failed + 67 Too many files open + 75 Path/file access error + 76 Path not found
SHELL
-Executes an operating system command.
+Executes an operating-system command.
SHELL "command"
-When used as a function, returns the exit code of the command.
+When used as a function, SHELL returns the exit code of the command.
Shell "DIR /B"
exitCode = Shell("COPY A.TXT B.TXT")
SLEEP
-Pauses execution for a specified number of seconds.
-SLEEP seconds
+Pauses execution for the given number of seconds. With no argument, sleeps for 1 second.
+SLEEP [seconds]
RANDOMIZE
-Seeds the random number generator.
+Seeds the random number generator. Without an argument (not shown here) and without a prior RANDOMIZE, the sequence is the same on every run. Use RANDOMIZE TIMER to get a different sequence each run.
RANDOMIZE seed
RANDOMIZE TIMER ' Seed from system clock
END
-Terminates program execution immediately.
+Terminates program execution immediately. Any form that is loaded is unloaded before the program exits.
END
SEEK
Sets the file position. As a function, returns the current position.
-SEEK #channel, position ' Statement: set position
+SEEK #channel, position ' Statement: set position
pos = SEEK(channel) ' Function: get current position
File System Statements
+DVX BASIC provides statements for working with the file system -- creating, deleting, renaming, and copying files and directories, and reading or setting file attributes.
+KILL
+Deletes a file.
+KILL filename$
+Kill "temp.bak"
+NAME ... AS
+Renames (or moves) a file.
+NAME oldName$ AS newName$
+Name "draft.txt" As "final.txt"
+FILECOPY
+Copies a file. If the destination already exists it is overwritten.
+FILECOPY source$, destination$
+FileCopy "data.db", "data.bak"
+MKDIR / RMDIR
+Creates or removes a directory.
+MKDIR path$
+RMDIR path$
+MkDir App.Data & "\backups"
+RmDir "C:\OLD"
+CHDIR / CHDRIVE
+Changes the current working directory or drive.
+CHDIR path$
+CHDRIVE drive$
+ChDir "C:\DVX\PROJECTS"
+ChDrive "D"
+GETATTR / SETATTR
+GETATTR returns the attributes of a file (as a function). SETATTR sets them (as a statement). Attributes are a bitmask of the vb file-attribute constants.
+attrs = GETATTR(filename$)
+SETATTR filename$, attrs
+Constant Value Attribute + -------- ----- --------- + vbNormal 0 Normal file (no attributes set) + vbReadOnly 1 Read-only + vbHidden 2 Hidden + vbSystem 4 System file + vbDirectory 16 Entry is a directory + vbArchive 32 File has been modified since last backup+
If (GetAttr("readme.txt") And vbReadOnly) <> 0 Then
+ Print "File is read-only."
+End If
+
+SetAttr "secret.dat", vbHidden + vbReadOnly
+CURDIR$ / DIR$
+CURDIR$ returns the current directory. DIR$ returns the first file matching a pattern; subsequent calls with no arguments return additional matches (or "" when done).
+cwd$ = CURDIR$
+first$ = DIR$("*.txt")
+WHILE first$ <> ""
+ Print first$
+ first$ = DIR$ ' next match, no argument
+WEND
+FILELEN
+Returns the length of a file in bytes.
+bytes = FILELEN(filename$)
+String Functions
Function Returns Description -------- ------- ----------- - ASC(s$) Integer ASCII code of first character of s$ + ASC(s$) Integer ASCII code of the first character of s$ CHR$(n) String Character with ASCII code n - FORMAT$(value, fmt$) String Formats a numeric value using format string - HEX$(n) String Hexadecimal representation of n + FORMAT$(value, fmt$) String Formats a numeric value using a format string + HEX$(n) String Hexadecimal representation of n (uppercase, no leading &H) INSTR(s$, find$) Integer Position of find$ in s$ (1-based), 0 if not found - INSTR(start, s$, find$) Integer Search starting at position start + INSTR(start, s$, find$) Integer Search starting at position start (1-based) LCASE$(s$) String Converts s$ to lowercase LEFT$(s$, n) String Leftmost n characters of s$ - LEN(s$) Integer Length of s$ + LEN(s$) Integer Length of s$ in characters LTRIM$(s$) String Removes leading spaces from s$ - MID$(s$, start [, length]) String Substring from position start (1-based) + MID$(s$, start) String Substring from start (1-based) to end of string + MID$(s$, start, length) String Substring of length characters starting at start RIGHT$(s$, n) String Rightmost n characters of s$ RTRIM$(s$) String Removes trailing spaces from s$ SPACE$(n) String String of n spaces - STR$(n) String Converts number n to string - STRING$(n, char) String String of n copies of char + STR$(n) String Converts number n to string (leading space for non-negative) + STRING$(n, char) String String of n copies of char (char can be an ASCII code or single-character string) TRIM$(s$) String Removes leading and trailing spaces from s$ UCASE$(s$) String Converts s$ to uppercase - VAL(s$) Double Converts string s$ to a numeric value+ VAL(s$) Double Converts string s$ to a numeric value; stops at first non-numeric character +
FORMAT$
+FORMAT$ formats a numeric value using a BASIC-style format string. The format characters are the same as the ones used by PRINT USING.
+s$ = FORMAT$(value, fmt$)
+Print Format$(3.14159, "###.##") ' " 3.14"
+Print Format$(42, "00000") ' "00042"
+Print Format$(1234.5, "#,##0.00") ' "1,234.50"
+Print Format$(0.5, "PERCENT") ' "50%"
+The accepted format characters are # (digit or pad space), 0 (digit or pad zero), . (decimal point), , (thousands separator), + and - (sign placement), $$ (floating dollar sign), ** (asterisk fill), and the literal word PERCENT (multiplies by 100 and appends %). See PRINT USING for details on each.
MID$ Assignment
-MID$ can also be used on the left side of an assignment to replace a portion of a string:
-Mid$(s$, 3, 2) = "XY" ' Replace 2 characters starting at position 3
+MID$ can also be used on the left side of an assignment to replace a portion of a string without changing its length:
+Mid$(s$, start [, length]) = replacement$
+Dim s$
+s$ = "Hello, World!"
+Mid$(s$, 8, 5) = "DVX--"
+Print s$ ' Hello, DVX--!
+If length is omitted, MID$ replaces up to LEN(replacement$) characters. The target string's total length never changes -- extra characters in replacement$ are truncated and shorter replacements leave trailing characters in place.
Math Functions
Function Returns Description -------- ------- ----------- ABS(n) Double Absolute value of n - ATN(n) Double Arctangent of n (in radians) - COS(n) Double Cosine of n (radians) + ATN(n) Double Arctangent of n (result in radians) + COS(n) Double Cosine of n (n in radians) EXP(n) Double e raised to the power n - FIX(n) Integer Truncates n toward zero (removes fractional part) + FIX(n) Integer Truncates n toward zero (drops the fractional part) INT(n) Integer Largest integer less than or equal to n (floor) LOG(n) Double Natural logarithm (base e) of n - RND[(n)] Double Random number between 0 (inclusive) and 1 (exclusive) - SGN(n) Integer Sign of n: -1, 0, or 1 - SIN(n) Double Sine of n (radians) + RND[(n)] Double Random number in the range 0 <= RND < 1 + SGN(n) Integer Sign of n: -1 if negative, 0 if zero, 1 if positive + SIN(n) Double Sine of n (n in radians) SQR(n) Double Square root of n - TAN(n) Double Tangent of n (radians) - TIMER Double Number of seconds since midnight-
Note: RND with a negative argument seeds and returns. RND(0) returns the previous value. Use RANDOMIZE to seed the generator.+ TAN(n) Double Tangent of n (n in radians) + TIMER Double Seconds since midnight +
Note: RND with no argument returns the next number in the sequence. Use RANDOMIZE or RANDOMIZE TIMER to seed the generator so you don't get the same sequence each run.+
Color Functions
+The color functions work with 24-bit RGB colors packed into a Long.
+Function Returns Description + -------- ------- ----------- + RGB(r, g, b) Long Combine red, green, and blue components (0-255) into a 24-bit color + GETRED(color) Integer Red component (0-255) of a color built with RGB + GETGREEN(color) Integer Green component (0-255) of a color built with RGB + GETBLUE(color) Integer Blue component (0-255) of a color built with RGB+
Dim c As Long
+c = RGB(255, 128, 0) ' bright orange
+Print GetRed(c); GetGreen(c); GetBlue(c) ' 255 128 0
+Me.BackColor = RGB(0, 0, 128) ' dark blue background
Conversion Functions
Function Returns Description -------- ------- ----------- CDBL(n) Double Converts n to Double - CINT(n) Integer Converts n to Integer (with banker's rounding) + CINT(n) Integer Converts n to Integer (rounds half away from zero) CLNG(n) Long Converts n to Long CSNG(n) Single Converts n to Single CSTR(n) String Converts n to its String representation@@ -1641,37 +1876,44 @@ pos = SEEK(channel) ' Function: get current position
File I/O Functions
Function Returns Description -------- ------- ----------- - EOF(channel) Boolean True if file pointer is at end of file - FREEFILE Integer Next available file channel number - INPUT$(n, #channel) String Reads n characters from the file + EOF(channel) Boolean True if the file pointer is at end of file + FREEFILE Integer Next available file channel number (1..16) + INPUT$(n, #channel) String Reads exactly n characters from the file LOC(channel) Long Current read/write position in the file LOF(channel) Long Length of the file in bytes SEEK(channel) Long Current file position (function form) - LBOUND(array [, dim]) Integer Lower bound of an array dimension - UBOUND(array [, dim]) Integer Upper bound of an array dimension+ FILELEN(path$) Long Length of the named file in bytes (no OPEN needed) + GETATTR(path$) Integer File attribute bits (see vbReadOnly, vbHidden, etc.) + CURDIR$ String Current working directory + DIR$(pattern$) String First filename matching pattern, or "" + DIR$ String Next match from the last DIR$(pattern$), or "" when done + LBOUND(array [, dim]) Integer Lower bound of an array dimension (default dim = 1) + UBOUND(array [, dim]) Integer Upper bound of an array dimension (default dim = 1)
Miscellaneous Functions
Function Returns Description -------- ------- ----------- DATE$ String Current date as "MM-DD-YYYY" - TIME$ String Current time as "HH:MM:SS" - ENVIRON$(name$) String Value of environment variable name$ - ERR Integer Current runtime error number (0 if no error)+ TIME$ String Current time as "HH:MM:SS" (24-hour) + TIMER Double Seconds since midnight + ENVIRON$(name$) String Value of the environment variable; empty string if not set + ERR Integer Current runtime error number (0 if no error) + SHELL(cmd$) Integer Exit code of the command (also usable as a statement, discarding the code)
Form and Control Statements
-DVX BASIC supports Visual Basic-style forms and controls for building graphical user interfaces. Forms are defined in .frm files and loaded at runtime.
+DVX BASIC supports Visual Basic-style forms and controls for building graphical user interfaces. A form is normally designed visually in the IDE and saved as a .frm file, but forms and their controls can also be built entirely in code.
Loading and Unloading Forms
LOAD FormName
UNLOAD FormName
-LOAD creates the form and its controls in memory. UNLOAD destroys the form and frees its resources.
+LOAD creates the form and its controls in memory. It fires Form_Load when the form is first loaded. UNLOAD destroys the form, firing Form_QueryUnload (which can cancel the close) and then Form_Unload. The form name here is the literal name of the form as it appears in its .frm file.
Showing and Hiding Forms
-FormName.Show [modal]
+FormName.Show [mode]
FormName.Hide
-Me.Show [modal]
+Me.Show [mode]
Me.Hide
-Pass vbModal (1) to Show for a modal dialog.
+Pass vbModal (1) to Show for a modal dialog that blocks until the user closes it. Omit the mode for a modeless (non-blocking) window.
Form2.Show vbModal
Me.Hide
Property Access
@@ -1679,42 +1921,94 @@ Me.Hide
ControlName.Property = value
value = ControlName.Property
Text1.Text = "Hello"
-label1.Caption = "Name: " & name$
+Label1.Caption = "Name: " & name$
x = Text1.Left
Method Calls
ControlName.Method [args]
List1.AddItem "New entry"
List1.Clear
Me Keyword
-Me refers to the current form. Use it to access the form's own properties, controls, and methods from within event handlers.
+Me refers to the current form -- that is, the form whose event handler is running. Use it to access the form's own properties, controls, and methods from within event handlers, especially when the form's name may change or when the same code runs from multiple forms.
Me.Caption = "Updated Title"
Me.Text1.Text = ""
Me.Hide
+Nothing
+Nothing is a null object reference. Assign it to an object-typed variable to indicate "no object".
+Set myCtrl = Nothing
Control Arrays
Multiple controls can share a name with unique indices. Access individual controls with parenthesized indices:
Option1(0).Value = True
Label1(idx).Caption = "Item " & Str$(idx)
Me.Label1(i).Visible = True
+WITH
+The WITH block provides a shorthand for setting several properties on the same control or for making several method calls. Inside the block, begin each property or method with a dot and omit the control name.
+WITH ControlName
+ .Property1 = value1
+ .Property2 = value2
+ .Method arg1, arg2
+END WITH
+With Label1
+ .Caption = "Status: Ready"
+ .ForeColor = RGB(0, 128, 0)
+ .Visible = True
+End With
+Building Forms in Code
+In addition to loading forms from .frm files, you can build a form entirely from code with CreateForm, CreateControl, SetEvent, and RemoveControl. The returned reference should be stored with SET.
+CreateForm
+SET formVar = CreateForm(name$, width%, height%)
+Creates a new form with the given name and initial size. Returns a form reference.
+CreateControl
+SET ctrlVar = CreateControl(formRef, typeName$, ctrlName$ [, parentCtrlRef])
+Creates a control on the given form. typeName$ is the control type (e.g. "CommandButton", "Label", "TextBox"). ctrlName$ is the unique name for the new control. If a parentCtrlRef is supplied, the new control is nested inside it (useful for placing controls inside containers like HBox or Frame).
+SetEvent
+SETEVENT ctrlRef, eventName$, handlerName$
+Wires an arbitrary SUB as the handler for a control's event. The default event-handler convention (ControlName_EventName) is used automatically for controls defined in a .frm file; SetEvent is for controls you create dynamically or for reusing a single handler across multiple controls.
+RemoveControl
+REMOVECONTROL formRef, ctrlName$
+Removes a control from a form.
+Dim frm As Long
+Dim lbl As Long
+
+Set frm = CreateForm("MyDlg", 300, 200)
+frm.Caption = "Built in code"
+
+Set lbl = CreateControl(frm, "Label", "StatusLabel")
+StatusLabel.Caption = "Hello, world!"
+
+Dim btn As Long
+Set btn = CreateControl(frm, "CommandButton", "BtnClose")
+BtnClose.Caption = "Close"
+SetEvent btn, "Click", "OnCloseClick"
+
+frm.Show
+
+Sub OnCloseClick
+ Unload Me
+End Sub
DoEvents
-Yields control to the DVX event loop, allowing the GUI to process pending events. Call this in long-running loops to keep the UI responsive.
+Yields control to DVX so the GUI can process pending events. Call this in long-running loops to keep the UI responsive (otherwise the window will appear frozen).
DOEVENTS
For i = 1 To 10000
' process data
If i Mod 100 = 0 Then DoEvents
Next
MsgBox
-Displays a message box dialog. Can be used as a statement (discards result) or as a function (returns the button clicked).
-MSGBOX message$ [, flags]
-result = MSGBOX(message$ [, flags])
+Displays a message-box dialog. Can be used as a statement (discards the result) or as a function (returns the button clicked).
+MSGBOX message$ [, flags [, title$]]
+result = MSGBOX(message$ [, flags [, title$]])
+flags is the sum of a button-style constant and an icon constant. See Predefined Constants for the complete list.
MsgBox "Operation complete"
-answer = MsgBox("Continue?", vbYesNo + vbQuestion)
+answer = MsgBox("Continue?", vbYesNo + vbQuestion, "Confirm")
If answer = vbYes Then
' proceed
End If
InputBox$
-Displays an input dialog and returns the user's text entry.
+Displays an input dialog and returns the user's text entry. Returns an empty string if the user cancels.
result$ = INPUTBOX$(prompt$ [, title$ [, default$]])
-name$ = InputBox$("Enter your name:", "Name Entry", "")
+name$ = InputBox$("Enter your name:", "Name Entry", "")
+If name$ <> "" Then
+ Print "Hello, "; name$
+End If
Event Handler Convention
Event handlers are named ControlName_EventName and defined as SUBs:
Sub Command1_Click()
@@ -1729,65 +2023,70 @@ Sub Text1_Change()
Label1.Caption = "You typed: " & Text1.Text
End Sub
Common Events
-Event Description - ----- ----------- - Click Control was clicked - DblClick Control was double-clicked - Change Control value/text changed - KeyPress Key was pressed (receives key code) - KeyDown Key went down (receives key code and shift state) - KeyUp Key was released - MouseDown Mouse button pressed - MouseUp Mouse button released - MouseMove Mouse moved over control - GotFocus Control received input focus - LostFocus Control lost input focus - Form_Load Form is being loaded - Form_Unload Form is being unloaded - Form_Resize Form was resized - Timer Timer interval elapsed+
Event Description + ----- ----------- + Click Control was clicked + DblClick Control was double-clicked + Change Control value or text changed + KeyPress Printable key was pressed (receives ASCII code) + KeyDown Any key was pressed (receives key code and shift state) + KeyUp Key was released + MouseDown Mouse button pressed (receives button, X, Y) + MouseUp Mouse button released + MouseMove Mouse moved over the control + Scroll Control was scrolled (mouse wheel or scrollbar) + GotFocus Control received input focus + LostFocus Control lost input focus + Form_Load Form is being loaded (fires once, after controls are created) + Form_QueryUnload Form is about to close; set Cancel = 1 to abort + Form_Unload Form is being unloaded + Form_Resize Form was resized + Form_Activate Form gained focus + Form_Deactivate Form lost focus + Timer1_Timer Timer control interval elapsed (Timer control's default event)
SQL Functions
-DVX BASIC includes built-in SQLite database support through a set of SQL functions. All functions use database handles and result set handles (integers) returned by SQLOpen and SQLQuery.
+DVX BASIC includes SQLite database support through the sql.bas include library. Add sql.bas to your project to gain access to these functions. All functions use database handles and result-set handles (integers) returned by SQLOpen and SQLQuery.
Opening and Closing Databases
SQLOpen
-Opens a SQLite database file and returns a database handle.
-db = SQLOPEN(path$)
+Opens a SQLite database file and returns a database handle (> 0) or 0 on failure. The file is created if it does not exist.
+db = SQLOpen(path$)
db = SQLOpen(App.Data & "\mydata.db")
SQLClose
Closes an open database.
-SQLCLOSE db
+SQLClose db
Executing SQL
SQLExec
-Executes a SQL statement that does not return data (INSERT, UPDATE, DELETE, CREATE TABLE, etc.). Can be used as a statement or as a function returning a Boolean success flag.
-SQLEXEC db, sql$
-ok = SQLEXEC(db, sql$)
+Executes a SQL statement that does not return data (INSERT, UPDATE, DELETE, CREATE TABLE, etc.). Returns True on success.
+ok = SQLExec(db, sql$)
SQLExec db, "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)"
SQLExec db, "INSERT INTO users (name) VALUES ('Scott')"
ok = SQLExec(db, "DELETE FROM users WHERE id = 5")
SQLAffected
Returns the number of rows affected by the last INSERT, UPDATE, or DELETE.
-count = SQLAFFECTED(db)
+count = SQLAffected(db)
Querying Data
SQLQuery
-Executes a SELECT query and returns a result set handle.
-rs = SQLQUERY(db, sql$)
+Executes a SELECT query and returns a result-set cursor.
+rs = SQLQuery(db, sql$)
rs = SQLQuery(db, "SELECT id, name FROM users ORDER BY name")
SQLNext
-Advances to the next row in the result set. Can be used as a statement or as a function returning True if a row is available.
-SQLNEXT rs
-hasRow = SQLNEXT(rs)
+Advances the cursor to the next row. Returns True if a row is available, False when there are no more rows.
+hasRow = SQLNext(rs)
SQLEof
-Returns True if there are no more rows in the result set.
-done = SQLEOF(rs)
+Returns True if the cursor is past the last row.
+done = SQLEof(rs)
Reading Fields
-SQLField$
-Returns a field value as a string. The field can be specified by column index (0-based) or by column name.
-value$ = SQLFIELD$(rs, columnIndex)
-value$ = SQLFIELD$(rs, "columnName")
-name$ = SQLField$(rs, "name")
-first$ = SQLField$(rs, 0)
+SQLField$ / SQLFieldText$
+Returns a field value as a string. Use SQLField$ to look up by column name; use SQLFieldText$ to look up by 0-based column index.
+value$ = SQLField$(rs, columnName$)
+value$ = SQLFieldText$(rs, columnIndex)
+name$ = SQLField$(rs, "name")
+first$ = SQLFieldText$(rs, 0)
+SQLFieldName$
+Returns the column name for a given 0-based column index.
+colName$ = SQLFieldName$(rs, columnIndex)
SQLFieldInt
Returns a field value as an integer.
value = SQLFIELDINT(rs, columnIndex)
@@ -1796,26 +2095,25 @@ first$ = SQLField$(rs, 0)
value# = SQLFIELDDBL(rs, columnIndex)
SQLFieldCount
Returns the number of columns in the result set.
-count = SQLFIELDCOUNT(rs)
+count = SQLFieldCount(rs)
Result Set Cleanup
SQLFreeResult
-Frees a result set. Always call this when done iterating a query.
-SQLFREERESULT rs
+Frees a result-set cursor. Always call this when finished iterating a query.
+SQLFreeResult rs
Error Information
SQLError$
Returns the last error message for the database.
-msg$ = SQLERROR$(db)
+msg$ = SQLError$(db)
Complete SQL Example
-Dim db As Long
-Dim rs As Long
+Dim db As Integer
+Dim rs As Integer
db = SQLOpen(App.Data & "\contacts.db")
SQLExec db, "CREATE TABLE IF NOT EXISTS contacts (name TEXT, phone TEXT)"
SQLExec db, "INSERT INTO contacts VALUES ('Alice', '555-1234')"
rs = SQLQuery(db, "SELECT name, phone FROM contacts")
-Do While Not SQLEof(rs)
- SQLNext rs
+Do While SQLNext(rs)
Print SQLField$(rs, "name"); Tab(20); SQLField$(rs, "phone")
Loop
SQLFreeResult rs
@@ -1835,10 +2133,10 @@ Print "Running from: " & App.Path
INI Functions
-DVX BASIC provides built-in functions for reading and writing standard INI configuration files.
+DVX BASIC provides built-in functions for reading and writing standard INI configuration files (the same text format used by DVX system configuration).
IniRead
-Reads a value from an INI file. Returns the default value if the key is not found.
-value$ = INIREAD(file$, section$, key$, default$)
+Reads a value from an INI file. Returns the default value if the file, section, or key is not found. All four arguments are required.
+value$ = IniRead(file$, section$, key$, default$)
name$ = IniRead(App.Config & "\app.ini", "User", "Name", "Unknown")
fontSize = Val(IniRead(App.Config & "\app.ini", "Display", "FontSize", "12"))
IniWrite
@@ -1849,7 +2147,7 @@ IniWrite App.Config & "\app.ini", "Display", "FontSPredefined Constants
-The following constants are predefined by the compiler and available in all programs.
+The following constants are predefined by the compiler and available in all programs. No DIM or CONST declaration is required to use them.
MsgBox Button Style Flags
Constant Value Description -------- ----- ----------- @@ -1859,13 +2157,13 @@ IniWrite App.Config & "\app.ini", "Display", "FontS vbYesNoCancel 3 Yes, No, and Cancel buttons vbRetryCancel 4 Retry and Cancel buttons
MsgBox Icon Flags
-Add an icon flag to the button style to display an icon in the message box.
+Add an icon flag to the button style (with + or OR) to display an icon in the message box.
Constant Value Description -------- ----- ----------- - vbInformation &H10 Information icon - vbExclamation &H20 Warning icon - vbCritical &H30 Error/critical icon - vbQuestion &H40 Question mark icon+ vbInformation &H10 Information icon (i) + vbExclamation &H20 Warning icon (!) + vbCritical &H30 Error/critical icon (X) + vbQuestion &H40 Question icon (?)
MsgBox Return Values
Constant Value Description -------- ----- ----------- @@ -1878,12 +2176,43 @@ IniWrite App.Config & "\app.ini", "Display", "FontSConstant Value Description -------- ----- ----------- vbModal 1 Show form as modal dialog+File Attribute Flags
+Bit values used with GETATTR and SETATTR.
+Constant Value Description + -------- ----- ----------- + vbNormal 0 Normal file (no attributes) + vbReadOnly 1 Read-only + vbHidden 2 Hidden + vbSystem 4 System file + vbDirectory 16 Entry is a directory + vbArchive 32 File has been modified since last backupBoolean Constants
Constant Value Description -------- ----- ----------- True -1 Boolean true False 0 Boolean false
Include Libraries
+DVX ships a set of BASIC include files (.bas) in the sdk/include/basic directory. Each file is a small library of DECLARE LIBRARY wrappers around native DVX runtime functions. Add an include file to your project (the IDE's Add File command, or editing the .dbp with another tool) and the declared functions become available to your code.
+File Provides + ---- -------- + commdlg.bas File Open/Save dialogs, input dialogs, choice dialogs, save-prompt dialogs + sql.bas SQLite database access (SQLOpen, SQLQuery, SQLNext, SQLField$, etc.) + comm.bas Serial-port I/O (raw and packet) and optional encrypted links + resource.bas Read and write DVX resource blocks (icons, text, binary data) in bundled files + help.bas Compile help source files and open the DVX help viewer+
Using an Include Library
+' With commdlg.bas added to the project
+Dim path As String
+path = basFileOpen("Open a file", "Text Files (*.txt)|All Files (*.*)")
+
+If path <> "" Then
+ Print "Selected: " & path
+End If
+Note: DVX BASIC does not have an $INCLUDE directive. Libraries are added to the project so that the compiler sees their DECLARE LIBRARY blocks.+ +
Common Properties, Events, and Methods
Every control in DVX BASIC inherits a set of common properties, events, and methods. These are handled by the form runtime before dispatching to widget-specific interface descriptors.
@@ -1902,8 +2231,8 @@ IniWrite App.Config & "\app.ini", "Display", "FontS Weight Integer R/W Layout weight. 0 = fixed size, >0 = share extra space proportionally. Visible Boolean R/W Whether the control is visible. Enabled Boolean R/W Whether the control accepts user input. - BackColor Long R/W Background color as a 32-bit ARGB value. - ForeColor Long R/W Foreground (text) color as a 32-bit ARGB value. + BackColor Long R/W Background color as a 24-bit RGB value packed in a Long (use the RGB function to construct). + ForeColor Long R/W Foreground (text) color as a 24-bit RGB value packed in a Long (use the RGB function to construct). TabIndex Integer R Accepted for VB compatibility but ignored. DVX has no tab order.Common Events
These events are wired on every control loaded from a .frm file. Controls created dynamically at runtime via code only receive Click, DblClick, Change, GotFocus, and LostFocus; the keyboard, mouse, and scroll events below require the control to be defined in the .frm file.
@@ -2175,7 +2504,7 @@ End Sub Left Integer 0 Initial X position. Used when Centered is False. Top Integer 0 Initial Y position. Used when Centered is False. Layout String "VBox" Content box layout: "VBox" (vertical) or "HBox" (horizontal). - AutoSize Boolean True When True, the window shrink-wraps to fit its content. + AutoSize Boolean False When True, the window shrink-wraps to fit its content. Resizable Boolean True Whether the user can resize the window at runtime. Centered Boolean True When True, the window is centered on screen. When False, Left/Top are used.Form Events
@@ -2215,21 +2544,21 @@ End SubTerminal
-DVX Extension -- DVX Widget: ansiterm (ANSI terminal emulator)
-A VT100/ANSI terminal emulator widget. Supports ANSI escape sequences, scrollback buffer, and serial communication. Default size is 80 columns by 25 rows.
+DVX Extension -- DVX Widget: ansiterm
+A VT100/ANSI terminal emulator with a text-mode cell buffer, 16-color CGA palette, and scrollback history. Processes standard ANSI escape sequences (cursor control, erase, scroll, SGR colors, DEC private modes) typically used by DOS BBS software. Default size is 80 columns by 25 rows. Supports text selection with the mouse, Ctrl+C to copy, and Ctrl+V to send clipboard text as input.
Type-Specific Properties
Property Type Description ---------- ------- ------------------------------------------- Cols Integer Number of character columns (read-only). Rows Integer Number of character rows (read-only). - Scrollback Integer Number of scrollback lines (write-only).+ Scrollback Integer Maximum number of scrollback lines. Older lines are dropped (write-only; default 500).
Type-Specific Methods
Method Description ------ ----------- - Clear Clear the terminal screen. - Poll Process pending comm data and update the display. - Write text$ Write text (with ANSI escape processing) to the terminal.-
No default event.
+ Clear Clear the terminal screen and reset the cursor to the home position. + Poll Poll the attached communication channel for incoming bytes and feed them into the ANSI parser. + Write text$ Write a string to the terminal with full ANSI escape processing. +No default event. Uses common events only.
Serial Communication
Use the comm.bas library to connect a Terminal to a serial link:
Dim link As Integer
@@ -2237,16 +2566,26 @@ link = CommOpen(1, 115200)
CommHandshake link
CommAttach link, "Terminal1"
See comm.bas for the full communications API.
+Example
+Begin Terminal Terminal1
+ MinWidth = 640
+ MinHeight = 400
+End
+
+Sub Form_Load ()
+ Terminal1.Write "Welcome!" & Chr$(13) & Chr$(10)
+End Sub
Frame
-VB Equivalent: Frame -- DVX Widget: frame (titled VBox container)
+VB Equivalent: Frame -- DVX Widget: frame (titled container)
A container with a titled border. Child controls are placed inside the frame using VBox layout. In the .frm file, nest Begin/End blocks inside the Frame block.
Type-Specific Properties
Property Type Description -------- ------ ------------------------------------------- Caption String The title displayed in the frame border.+
No type-specific methods or events.
Container: Yes
Default Event: Click
Example
@@ -2264,32 +2603,51 @@ EndHBox
DVX Extension -- DVX Widget: hbox (horizontal layout container)
-A container that arranges its children horizontally, left to right. Use Weight on children to distribute extra space.
+A container that arranges its children horizontally, left to right. No visible border. Use Weight on children to distribute extra space proportionally.
+No type-specific properties, methods, or events.
Container: Yes
Default Event: Click
-No type-specific properties.
+Example
+Begin HBox ButtonRow
+ Spacing = 4
+ Begin CommandButton Command1
+ Caption = "OK"
+ End
+ Begin CommandButton Command2
+ Caption = "Cancel"
+ End
+End
VBox
DVX Extension -- DVX Widget: vbox (vertical layout container)
-A container that arranges its children vertically, top to bottom. No title or border. Use Weight on children to distribute extra space.
+A container that arranges its children vertically, top to bottom. No title or border. Use Weight on children to distribute extra space proportionally.
+No type-specific properties, methods, or events.
Container: Yes
Default Event: Click
-No type-specific properties.
+Example
+Begin VBox Column1
+ Spacing = 4
+ Begin Label Label1
+ Caption = "Name:"
+ End
+ Begin TextBox Text1
+ End
+End
CommandButton
VB Equivalent: CommandButton -- DVX Widget: button | Name Prefix: Command
-A push button that triggers an action when clicked. Created with wgtButton(parent, text).
+A push button that triggers an action when clicked. The Caption may include a '&' before a character to mark an accelerator key (e.g. "&OK" underlines 'O', and Alt+O activates the button).
Type-Specific Properties
Property Type Description -------- ------ ------------------------------------------- - Caption String The text displayed on the button. Use & for accelerator keys (e.g. "&OK").-
No additional type-specific properties beyond common properties and Caption.
+ Caption String The text displayed on the button. Use '&' for an accelerator key. +No type-specific methods or events.
Default Event: Click
Example
Begin Form Form1
@@ -2339,12 +2697,13 @@ Picture1.Save "output.bmp"
CheckBox
VB Equivalent: CheckBox -- DVX Widget: checkbox
-A toggle control with a label. Checked state is exposed as a Boolean.
+A toggle control with a label. The checked state is exposed as a Boolean. Supports accelerator keys (put '&' before a character in the Caption). Press Space or Enter to toggle when focused.
Type-Specific Properties
Property Type Description -------- ------- ------------------------------------------- Caption String The text displayed next to the checkbox. Value Boolean True if checked, False if unchecked.+
No type-specific methods or events.
Default Event: Click
Example
Begin CheckBox Check1
@@ -2362,37 +2721,55 @@ End Sub
ComboBox
-VB Equivalent: ComboBox -- DVX Widget: combobox (editable text field + drop-down list, max 256 chars)
-A combination of a text input and a drop-down list. The user can type text or select from the list. Supports the same AddItem/RemoveItem/Clear/List methods as ListBox.
+VB Equivalent: ComboBox -- DVX Widget: combobox (editable text field + drop-down list, default maxLen 256)
+A combination of a single-line text input and a drop-down list. The user can either type a value or pick one from the list. Selecting a list item copies its text into the edit field. Supports the same AddItem / RemoveItem / Clear / List methods as ListBox.
Type-Specific Properties
Property Type Description --------- ------- ------------------------------------------- Text String The text in the editable field. - ListIndex Integer Index of the currently selected list item (-1 = none). - ListCount Integer Number of items in the drop-down list (read-only).+ ListIndex Integer Index of the currently selected list item (-1 = user typed something not in the list).
Type-Specific Methods
-Same as ListBox: AddItem, RemoveItem, Clear, List.
- +Method Description + ------ ----------- + AddItem text$ Append an item to the drop-down list. + Clear Remove all items. + List(index%) Return the text of the item at the given index. + ListCount() Return the number of items in the list. + RemoveItem index% Remove the item at the given index.
Default Event: Click
+Example
+Begin ComboBox Combo1
+End
+
+Sub Form_Load ()
+ Combo1.AddItem "Small"
+ Combo1.AddItem "Medium"
+ Combo1.AddItem "Large"
+End Sub
+
+Sub Combo1_Change ()
+ Label1.Caption = "Selected: " & Combo1.Text
+End Sub
+
Data
-VB Equivalent: Data -- DVX Widget: data (database record navigator)
-A data access control that connects to a SQLite database and provides record navigation. Other controls can bind to a Data control via their DataSource and DataField properties.
+VB Equivalent: Data -- DVX Widget: data | Name Prefix: Data
+A data access control that connects to a SQLite database and provides record navigation. Other controls bind to a Data control via their DataSource and DataField properties. The Data control cache is populated by calling Refresh. Move operations auto-save the current row if dirty.
Type-Specific Properties
-Property Type R/W Description - ------------ ------- --- ------------------------------------------- - DatabaseName String R/W Path to the SQLite database file. - RecordSource String R/W Table name or SQL SELECT query for the recordset. - KeyColumn String R/W Primary key column name (used for UPDATE/DELETE operations). - Caption String R/W Text displayed on the navigator bar. - BOF Boolean R True if the current position is before the first record (read-only). - EOF Boolean R True if the current position is past the last record (read-only). - MasterSource String R/W Name of a master Data control (for master-detail binding). - MasterField String R/W Column in the master recordset to filter by. - DetailField String R/W Column in this recordset that matches the master field.+
Property Type Description + ------------ ------- ------------------------------------------- + DatabaseName String Path to the SQLite database file. + RecordSource String Table name or SQL SELECT query for the recordset. + KeyColumn String Primary key column name (used for UPDATE/DELETE operations). + Caption String Text displayed on the navigator bar. + BOF Boolean True if the current position is the first record or there are no records (read-only). + EOF Boolean True if the current position is past the last record or there are no records (read-only). + MasterSource String Name of a master Data control (for master-detail binding). + MasterField String Column in the master recordset to read for the filter value. + DetailField String Column in this recordset that matches the master field.
Type-Specific Methods
Method Parameters Description ------------ ---------- ------------------------------------------- @@ -2400,28 +2777,44 @@ End SubMoveLast (none) Navigate to the last record. MoveNext (none) Navigate to the next record. MovePrevious (none) Navigate to the previous record. - AddNew (none) Add a new blank record. + AddNew (none) Append a blank record and move to it. Delete (none) Delete the current record. Refresh (none) Re-query the database and reload records. Update (none) Write pending changes to the database.
Type-Specific Events
Event Parameters Description ---------- ----------------- ------------------------------------------- - Reposition (none) Fires after the current record changes (navigation). This is the default event. - Validate Cancel As Integer Fires before writing a record. Set Cancel = 1 to abort.+ Reposition (none) Fires after the current record changes. Default event. + Validate Cancel As Integer Fires before writing. Set Cancel = 1 to abort. +
Default Event: Reposition
+Example
+Begin Data Data1
+ DatabaseName = "books.db"
+ RecordSource = "titles"
+ KeyColumn = "id"
+End
+
+Begin TextBox Text1
+ DataSource = "Data1"
+ DataField = "title"
+End
+
+Sub Form_Load ()
+ Data1.Refresh
+End Sub
DBGrid
-VB Equivalent: DBGrid -- DVX Widget: dbgrid
-A data-bound grid that displays records from a Data control in a tabular format. Columns are auto-generated from the query results. Bind it using the DataSource property.
+VB Equivalent: DBGrid -- DVX Widget: dbgrid | Name Prefix: DBGrid
+A data-bound grid that displays records from a Data control in a tabular format. Columns auto-populate from the query results. Bind the grid using the DataSource property. Click a column header to sort; drag a column border to resize. Selecting a row moves the bound Data control's cursor to that row.
Type-Specific Properties
Property Type Description ---------- ------- ------------------------------------------- DataSource String Name of the Data control that supplies records. - GridLines Boolean Show or hide grid lines between cells.+ GridLines Boolean Show or hide grid lines between cells (default: True).
Type-Specific Methods
Method Parameters Description ------- ---------- ------------------------------------------- @@ -2429,8 +2822,27 @@ End Sub
Type-Specific Events
Event Parameters Description -------- ---------- ------------------------------------------- - Click (none) Fires when a cell is clicked. - DblClick (none) Fires when a cell is double-clicked. This is the default event.+ Click (none) Fires when a row is clicked. + DblClick (none) Fires when a row is double-clicked. Default event. +
Default Event: DblClick
+Example
+Begin Data Data1
+ DatabaseName = "books.db"
+ RecordSource = "titles"
+End
+
+Begin DBGrid DBGrid1
+ DataSource = "Data1"
+ GridLines = True
+End
+
+Sub Form_Load ()
+ Data1.Refresh
+End Sub
+
+Sub DBGrid1_DblClick ()
+ MsgBox "Opening row " & Str$(Data1.BOF)
+End Sub
Common Properties, Events, and Methods
@@ -2438,53 +2850,98 @@ End SubDropDown
DVX Extension -- DVX Widget: dropdown (non-editable drop-down list)
-A read-only drop-down list. Unlike ComboBox, the user cannot type free text; they can only select from the provided items. Supports AddItem/RemoveItem/Clear/List.
+A read-only drop-down list. Unlike ComboBox, the user cannot type free text; they can only select from the provided items. Supports AddItem / RemoveItem / Clear / List. Use the arrow keys to navigate and Enter to commit when the list is open.
Type-Specific Properties
Property Type Description --------- ------- ------------------------------------------- - ListIndex Integer Index of the currently selected item. - ListCount Integer Number of items (read-only).+ ListIndex Integer Index of the currently selected item (-1 = none).
Type-Specific Methods
-Same as ListBox: AddItem, RemoveItem, Clear, List.
- +Method Description + ------ ----------- + AddItem text$ Append an item to the drop-down list. + Clear Remove all items. + List(index%) Return the text of the item at the given index. + ListCount() Return the number of items in the list. + RemoveItem index% Remove the item at the given index.
Default Event: Click
+Example
+Begin DropDown DropDown1
+End
+
+Sub Form_Load ()
+ DropDown1.AddItem "Small"
+ DropDown1.AddItem "Medium"
+ DropDown1.AddItem "Large"
+ DropDown1.ListIndex = 1
+End Sub
+
+Sub DropDown1_Click ()
+ Label1.Caption = "Picked: " & DropDown1.List(DropDown1.ListIndex)
+End Sub
+
ImageButton
DVX Extension -- DVX Widget: imagebutton
-A button that displays an image instead of text. Like Image, it requires pixel data at creation time and is typically loaded via the Picture property.
+A button that displays an image instead of text. Has the same press/release behavior as CommandButton, but shows a bitmap. Typically used inside a Toolbar.
Type-Specific Properties
Property Type Description ----------- ------- ------------------------------------------- - Picture String Path to a BMP file to load (write-only). + Picture String Path to an image file to load. ImageWidth Integer Width of the loaded image in pixels (read-only). ImageHeight Integer Height of the loaded image in pixels (read-only).+
No type-specific methods or events.
Default Event: Click
+Example
+Begin Toolbar Toolbar1
+ Begin ImageButton ImageButton1
+ Picture = "icons/save.bmp"
+ End
+ Begin ImageButton ImageButton2
+ Picture = "icons/open.bmp"
+ End
+End
+
+Sub ImageButton1_Click ()
+ MsgBox "Save clicked"
+End Sub
Image
VB Equivalent: Image -- DVX Widget: image
-A static image display control. Loads BMP images from file. Cannot be placed via the designer toolbox (requires pixel data at creation time); typically created in code or loaded via the Picture property.
+A static image display control. Loads bitmap images from file. Set the Picture property at design-time (in the .frm file) or at runtime to load a file.
Type-Specific Properties
Property Type Description ----------- ------- ------------------------------------------- - Picture String Path to a BMP file to load (write-only). + Picture String Path to an image file to load. + Stretch Boolean When True, the image stretches to fill the widget; when False, shown at natural size. ImageWidth Integer Width of the loaded image in pixels (read-only). ImageHeight Integer Height of the loaded image in pixels (read-only).+
No type-specific methods or events.
Default Event: Click
+Example
+Begin Image Image1
+ Picture = "assets/logo.bmp"
+ Stretch = True
+End
+
+Sub Image1_Click ()
+ MsgBox "Size: " & Str$(Image1.ImageWidth) & "x" & Str$(Image1.ImageHeight)
+End Sub
Label
VB Equivalent: Label -- DVX Widget: label
-A static text label. Supports left, center, and right alignment.
+A static text label. Supports left, center, and right alignment. Put '&' before a character in the Caption to define an accelerator that moves focus to the next focusable control.
Type-Specific Properties
Property Type Description --------- ---- ------------------------------------------- Caption String The text displayed by the label. Alignment Enum Text alignment: Left (default), Center, or Right.+
No type-specific methods or events.
Default Event: Click
Example
Begin Label Label1
@@ -2496,26 +2953,26 @@ End
ListBox
VB Equivalent: ListBox -- DVX Widget: listbox
-A scrollable list of selectable items. Items are managed via methods (AddItem, RemoveItem, Clear). Supports single and multi-select modes.
+A scrollable list of selectable items. Items are managed via methods (AddItem, RemoveItem, Clear). Supports single and multi-select modes, drag-to-reorder, and keyboard navigation with type-ahead search.
Type-Specific Properties
Property Type Description --------- ------- ------------------------------------------- - ListIndex Integer Index of the currently selected item (-1 = no selection). - ListCount Integer Number of items in the list (read-only).+ ListIndex Integer Index of the currently selected item (-1 = no selection).
Type-Specific Methods
Method Parameters Description --------------- --------------------------------------- ------------------------------------------- AddItem Text As String Add an item to the end of the list. - RemoveItem Index As Integer Remove the item at the given index. Clear (none) Remove all items from the list. - List Index As Integer Return the text of the item at the given index. - SelectAll (none) Select all items (multi-select mode). ClearSelection (none) Deselect all items. - SetMultiSelect Multi As Boolean Enable or disable multi-select mode. - SetReorderable Reorderable As Boolean Enable or disable drag-to-reorder. IsItemSelected Index As Integer Returns True if the item at Index is selected. + List Index As Integer Return the text of the item at the given index. + ListCount (none) Return the number of items in the list. + RemoveItem Index As Integer Remove the item at the given index. + SelectAll (none) Select all items (multi-select mode). SetItemSelected Index As Integer, Selected As Boolean Select or deselect a specific item. - SetItems Items As String Bulk-load items from a pipe-delimited string (e.g. "Red|Green|Blue").+ SetItems Items As String Bulk-load items from a pipe-delimited string (e.g. "Red|Green|Blue"). Replaces existing items. + SetMultiSelect Multi As Boolean Enable or disable multi-select mode. + SetReorderable Reorderable As Boolean Enable or disable drag-to-reorder.
Default Event: Click
Example
Sub Form_Load ()
@@ -2662,7 +3119,7 @@ End Sub
Splitter
DVX Extension -- DVX Widget: splitter
-A resizable split pane. Holds exactly two child widgets separated by a draggable divider. Default orientation is vertical (top/bottom split).
+A resizable split pane. Holds exactly two child widgets separated by a draggable divider. Default orientation is vertical (vertical divider, panes side-by-side).
Type-Specific Properties
Property Type Description -------- ------- ------------------------------------------- @@ -2674,7 +3131,7 @@ End Sub
StatusBar
VB Equivalent: StatusBar -- DVX Widget: statusbar
-A horizontal container styled as a status bar, typically placed at the bottom of a form. At the C API level it accepts child widgets, but it is not registered as a container in the form runtime, so child controls cannot be nested inside it in .frm files. Set its Caption property to display status text.
+A horizontal container styled as a status bar, typically placed at the bottom of a form. At the C API level it holds child widgets (such as labels), each drawn with a sunken-panel border for the classic segmented status-bar look. It is not registered as a container in the form runtime, so child controls cannot be nested inside it in .frm files.
No type-specific properties, events, or methods.
TextArea
-VB Equivalent: TextArea (DVX extension) -- DVX Widget: textarea (multi-line text input, max 4096 chars)
+VB Equivalent: TextArea (DVX extension) -- DVX Widget: textarea (multi-line text input, default max 65536 chars)
A multi-line text editing area. This is a DVX extension with no direct VB3 equivalent (VB uses a TextBox with MultiLine=True). Supports line numbers, auto-indent, find/replace, and tab configuration.
Type-Specific Properties
Property Type R/W Description @@ -2767,7 +3224,7 @@ Print "Replaced"; count; "occurrences"
Property Type Description -------- ------- ------------------------------------------- Enabled Boolean True to start the timer, False to stop it. - Interval Integer Timer interval in milliseconds (write-only from BASIC).+ Interval Integer Timer interval in milliseconds.
Type-Specific Methods
Method Parameters Description ------ ---------- ------------------------------------------- @@ -2831,7 +3288,7 @@ Print "Items:"; TreeView1.ItemCount()
WrapBox
-DVX Extension -- DVX Widget: wrapbox
+DVX Extension -- DVX Widget: wrapbox | Name Prefix: WrapBox
A container that arranges children in a flowing layout, wrapping to the next row when the available width is exceeded. Similar to CSS flexbox with flex-wrap: wrap.
Type-Specific Properties
Property Type Description
diff --git a/docs/dvx_system_reference.html b/docs/dvx_system_reference.html
index 6f452cc..e669bd9 100644
--- a/docs/dvx_system_reference.html
+++ b/docs/dvx_system_reference.html
@@ -38,6 +38,10 @@ img { max-width: 100%; }
- dvxTypes.h -- Shared Type Definitions -
- dvxCursor.h -- Cursor Definitions +
- dvxCur.h -- Cursor Definitions +
- dvxFont.h -- Bitmap Font Data +
- dvxPal.h -- 8-bit Palette
- dvxVideo.h -- Layer 1: Video Backend
- dvxDraw.h -- Layer 2: Drawing Primitives
- dvxComp.h -- Layer 3: Compositor
- dvxWm.h -- Layer 4: Window Manager
- dvxApp.h -- Layer 5: Application API -
- dvxWidget.h -- Widget System +
- dvxWgt.h -- Widget System +
- dvxDlg.h -- Modal Dialogs +
- dvxRes.h -- Resource System +
- dvxPrefs.h -- Preferences System +
- dvxMem.h -- Memory Tracking +
- dvxWgtP.h -- Widget Plugin API +
- platform/dvxPlat.h -- Platform Layer
Welcome!
DVX (DOS Visual eXecutive) is a graphical user interface environment for DOS, designed for 486-class hardware and above. This help file covers the system architecture, core API, libraries, and widget toolkit.
+DVX (DOS Visual eXecutive) is a graphical user interface environment for DOS, designed for 486-class hardware and above. This help file covers the system architecture, the core libdvx API, the widget toolkit, and the platform abstraction layer.
+What Is libdvx?
+libdvx is the heart of DVX -- a DXE3 library that provides:
+-
+
- A VESA VBE 2.0+ video backend (LFB only, no bank switching). +
- Optimised 2D drawing primitives (rectangle fill, bevels, text, bitmap blits, cursors). +
- A dirty-rectangle compositor that minimises LFB traffic. +
- A window manager with Motif-style chrome, drag/resize, menus, and scrollbars. +
- A retained-mode widget toolkit with automatic layout. +
Modal dialog helpers, an INI preferences system, a DXE resource system, and per-app memory tracking.
+Applications written in C link against libdvx (and the widget DXEs they need) to build native DVX programs. Applications written in DVX BASIC compile to bytecode that runs on top of libdvx via the form runtime.
+Target Audience
+This document is aimed at developers writing native C code for DVX:
+-
+
- System-level contributors maintaining libdvx itself. +
- Widget authors writing new .wgt DXE modules. +
- Application authors writing .app DXE modules. +
Tool authors (e.g. the BASIC compiler/runtime) that sit on top of libdvx.
+All examples and signatures assume the DJGPP cross-compiler toolchain.
+What's Covered
+-
+
- Architecture -- Five-layer model, display pipeline, event model, build system. +
API Reference -- Every public function, struct, enum, and constant documented with parameters and return values.
+Use the table of contents on the left to navigate. The API reference is organised by header file; each function has a one-line summary, parameter table, and (where useful) a working example.
+Conventions
+-
+
- Types end in a capital T (e.g. WindowT, DisplayT, BlitOpsT). +
- Enum types end in a capital E (e.g. ColorIdE, WallpaperModeE, ScrollbarOrientE). +
- Public functions use camelCase and prefixes that identify the subsystem: dvx* (application), wm* (window manager), wgt* (widget), prefs* (preferences), draw* / rect* (drawing), dirtyList* / flush* (compositor), video* / packColor / setClipRect (video), platform* (platform layer). +
- Constants use SCREAMING_SNAKE_CASE (e.g. HIT_CONTENT, MB_OK, CURSOR_ARROW). +
Every header uses stdint.h types (int32_t, uint8_t) and stdbool.h types (bool).
+Getting Started
+If you're new to DVX, read these topics in order:
+-
+
- Architecture Overview -- The big picture, five-layer model, and the design philosophy. +
- Display Pipeline -- How the backbuffer, dirty list, and compositor work together. +
- Event Model -- How input becomes window/widget callbacks. +
- Widget System -- The retained-mode toolkit layered on the window manager. +
DXE Module System -- How apps and widgets are loaded dynamically.
+Then dip into the API Reference to find specific functions. The public entry point for any application is dvxInit / dvxRun in dvxApp.h.
+License
+DVX is distributed under the MIT License (see the copyright notice at the top of every source file). Third-party code (stb_image, stb_ds, stb_image_write in thirdparty/) is used under its own permissive license.
DVX Architecture Overview
@@ -775,7 +937,7 @@ img { max-width: 100%; }No external font or cursor files -- all bitmaps are compiled in as static const data.
The runtime environment consists of a bootstrap loader (dvx.exe) that loads core DXE libraries, widget plugins, and the shell, which in turn loads and manages DXE application modules.
@@ -784,6 +946,10 @@ img { max-width: 100%; } + + + + @@ -815,7 +981,7 @@ img { max-width: 100%; } | +------------------------------------------+ | | | | +------------------------------------------+ | - | | Platform Layer (dvxPlatform.h) | | dvxPlatformDos.c + | | Platform Layer (dvxPlat.h) | | dvxPlatformDos.c | | OS-specific: video, input, asm spans | | | +------------------------------------------+ | | | @@ -921,13 +1087,13 @@ img { max-width: 100%; }Hit Test Regions
wmHitTest() iterates the stack front-to-back and returns a hit-part identifier: HIT_CONTENT, HIT_TITLE, HIT_CLOSE, HIT_RESIZE, HIT_MENU, HIT_VSCROLL, HIT_HSCROLL, HIT_MINIMIZE, HIT_MAXIMIZE. Resize edge detection returns a bitmask of RESIZE_LEFT, RESIZE_RIGHT, RESIZE_TOP, RESIZE_BOTTOM (corners combine two edges).
Menu System
-Menus use fixed-size arrays with inline char buffers (no heap strings). Up to 8 menus per bar, items dynamically allocated. Supports cascading submenus via MenuItemT.subMenu pointer. Item types: normal, checkbox, radio. Separators are non-interactive items. The popup state (PopupStateT) tracks a stack of parent frames for cascading submenu nesting.
+Menus use fixed-size inline char buffers for labels (MAX_MENU_LABEL = 32, no heap strings). Both menus per bar and items per menu are stored in dynamic arrays that grow on demand. Supports cascading submenus via MenuItemT.subMenu pointer. Item types: normal, checkbox, radio. Separators are non-interactive items. The popup state (PopupStateT) tracks a stack of parent frames for cascading submenu nesting.
Minimized Windows
Minimized windows display as 64x64 icons at the bottom of the screen with beveled borders, similar to a classic desktop icon bar. Icons show a scaled-down preview of the window's content buffer, refreshed one per frame in a round-robin fashion to amortize the scaling cost.
Widget System
-The widget system (dvxWidget.h) is a retained-mode toolkit layered on top of the window manager. Widgets form a tree rooted at a per-window VBox container.
+The widget system (dvxWgt.h) is a retained-mode toolkit layered on top of the window manager. Widgets form a tree rooted at a per-window VBox container.
WidgetT Base Structure
Every widget shares the same WidgetT struct. The type field is a runtime-assigned integer ID. The wclass pointer references the widget's WidgetClassT vtable. Widget-specific private data is stored in w->data (opaque void*).
Tree linkage: parent, firstChild, lastChild, nextSibling. No prevSibling -- this halves pointer overhead and removal is still O(n) for typical tree depths of 5-10.
@@ -990,6 +1156,78 @@ img { max-width: 100%; }Widget Interface Descriptors (WgtIfaceT)
Each widget can register an interface descriptor that describes its BASIC-facing properties, methods, and events. These descriptors are used by the form runtime and IDE for generic dispatch and property panel enumeration. Properties have typed getters/setters (WGT_IFACE_STRING, WGT_IFACE_INT, WGT_IFACE_BOOL, WGT_IFACE_ENUM).
Modal Dialogs (dvxDlg.h)
+Pre-built modal dialog boxes block the caller and run their own event loop via dvxUpdate() until the user dismisses them. Each dialog sets ctx->modalWindow to prevent input from reaching other windows while open.
+Dialog Types
+Function Purpose + -------- ------- + dvxMessageBox Generic message box with button/icon flags (MB_OK, MB_YESNO, MB_ICONERROR, etc.) + dvxErrorBox Shortcut for MB_OK + MB_ICONERROR + dvxInfoBox Shortcut for MB_OK + MB_ICONINFO + dvxFileDialog File open/save dialog with directory navigation and filter dropdown + dvxInputBox Single-line text input with OK/Cancel + dvxIntInputBox Integer input with spinner, clamp range, and step + dvxChoiceDialog List selection with OK/Cancel + dvxPromptSave Canonical "Save changes?" Yes/No/Cancel dialog+
Flag Encoding
+dvxMessageBox flags split into two nibbles: button configuration (low) and icon type (high). This matches the Win16 MessageBox() convention so OR'd flags read naturally:
+dvxMessageBox(ctx, "Confirm", "Delete file?", MB_YESNO | MB_ICONQUESTION);
+Return values are ID_OK / ID_CANCEL / ID_YES / ID_NO / ID_RETRY.
+Resource System (dvxRes.h)
+Resources are appended to DXE3 files (.app, .wgt, .lib) after the normal DXE content. The DXE loader never reads past the DXE header, so the appended data is invisible to dlopen. Every DXE can carry its own icons, text strings, and binary data without separate resource files.
+On-Disk Layout
+[DXE3 content] -- untouched, loaded by dlopen
+[resource data entries] -- sequential, variable length
+[resource directory] -- fixed-size entries (48 bytes each)
+[footer] -- magic + directory offset + count (16 bytes)
+Readers start from the end: seek to EOF - sizeof(footer), verify the magic (DVX_RES_MAGIC = "DVXR"), then seek to the directory. Entries are sorted at open time so lookups are O(log n) via bsearch.
+Types
+Type ID Value Payload + ------- ----- ------- + DVX_RES_ICON 1 Image data (BMP or PNG, typically 16x16 or 32x32 icons) + DVX_RES_TEXT 2 Null-terminated string (localisable UI text, author, copyright) + DVX_RES_BINARY 3 Arbitrary data (app-specific)+
Runtime API
+Function Description + -------- ----------- + dvxResOpen Open a handle by reading the footer and directory + dvxResRead Look up a resource by name and read its data into a malloc'd buffer + dvxResFind Look up a resource's directory entry (no data copy) + dvxResClose Release the handle + dvxResAppend Append a new resource to a DXE file + dvxResRemove Remove a resource by name+
The dvxApp.h wrappers (dvxResLoadIcon, dvxResLoadText, dvxResLoadData) combine open + read + close for the common case.
+Preferences System (dvxPrefs.h)
+Handle-based API over classic INI files. Multiple files can be open at once. Each prefsLoad / prefsCreate returns a PrefsHandleT opaque pointer passed to subsequent calls and freed with prefsClose. The system INI lives at DVX_INI_PATH = "CONFIG\\DVX.INI".
+Usage Pattern
+PrefsHandleT *h = prefsLoad(DVX_INI_PATH);
+int32_t w = prefsGetInt(h, "video", "width", 640);
+bool sound = prefsGetBool(h, "audio", "enable", true);
+const char *bg = prefsGetString(h, "desktop", "wallpaper", "");
+
+prefsSetInt(h, "video", "width", 800);
+prefsSave(h);
+prefsClose(h);
+Boolean getters recognise "true"/"yes"/"1" and "false"/"no"/"0" (case-insensitive). If the file does not exist, prefsLoad still returns a valid empty handle with the path captured so prefsSave can write a new file.
+Per-App Memory Tracking (dvxMem.h)
+All allocations route through dvxMalloc/dvxFree wrappers that prepend a 16-byte header recording the owning app ID and allocation size. The Task Manager displays per-app memory usage, and leaks are detected at app termination.
+Transparent Interception
+DXE code does NOT need to include dvxMem.h. The DXE export table maps malloc / free / calloc / realloc / strdup to the dvxXxx wrappers, so standard C code is tracked automatically.
+Explicit use (e.g. in the Task Manager) can include dvxMem.h to call:
+Function Purpose + -------- ------- + dvxMemSnapshotLoad Baseline a newly-loaded app's memory state + dvxMemGetAppUsage Query current bytes allocated for an app + dvxMemResetApp Free every tracked allocation charged to an app+
The dvxMemAppIdPtr pointer is set by the shell to &ctx->currentAppId so the allocator always knows which app to charge.
+DXE Module System
DVX uses DJGPP's DXE3 (Dynamic eXtension) format for all loadable modules. DXE3 supports RTLD_GLOBAL symbol sharing -- symbols exported by one module are visible to all subsequently loaded modules. This is critical: widget DXEs call core API functions (e.g. rectFill, wgtInvalidate) that are exported by the core library DXE.
@@ -1127,7 +1365,7 @@ img { max-width: 100%; }Platform Layer
-All OS-specific and CPU-specific code is isolated behind dvxPlatform.h. To port DVX, implement a new dvxPlatformXxx.c against this header.
+All OS-specific and CPU-specific code is isolated behind platform/dvxPlat.h. To port DVX, implement a new dvxPlatformXxx.c against this header.
Implementations
File Target Details
---- ------ -------
@@ -1153,7 +1391,7 @@ img { max-width: 100%; }
Cross-Compilation
DVX is cross-compiled from Linux using a DJGPP cross-compiler (i586-pc-msdosdjgpp-gcc). The top-level Makefile orchestrates building all subsystems in dependency order.
make -- build everything
- ./mkcd.sh -- build + create ISO for 86Box
+ ./mkcd.sh -- build + create ISO for the target emulator
Build Targets
all: core tasks loader texthelp listhelp tools widgets shell taskmgr serial sql apps
Target Output Description
@@ -1188,7 +1426,7 @@ img { max-width: 100%; }
Places the ISO at ~/.var/app/net._86box._86Box/data/86Box/dvx.iso for 86Box to mount as CD-ROM.
+Places the ISO at the target emulator's CD-ROM mount path.
Compiler Flags
-O2 Optimization level 2
-march=i486 486 instruction set baseline
@@ -1197,7 +1435,7 @@ img { max-width: 100%; }
Directory Layout
dvxgui/
+-- core/ Core library sources (dvxVideo, dvxDraw, dvxComp, dvxWm, dvxApp, widget infra)
- | +-- platform/ Platform abstraction (dvxPlatform.h, dvxPlatformDos.c)
+ | +-- platform/ Platform abstraction (dvxPlat.h, dvxPlatformDos.c, dvxPlatformUtil.c)
| +-- thirdparty/ stb_image, stb_ds, stb_image_write
+-- loader/ Bootstrap loader (dvx.exe)
+-- tasks/ Cooperative task switcher (libtasks.lib)
@@ -1224,7 +1462,7 @@ img { max-width: 100%; }
+-- security/ DH key exchange, XTEA cipher, DRBG RNG
+-- seclink/ Encrypted channel wrapper
+-- serial/ Combined serial stack DXE
- +-- proxy/ Linux proxy (86Box <-> secLink <-> telnet)
+ +-- proxy/ Linux proxy (emulator <-> secLink <-> telnet)
+-- sql/ SQLite integration
+-- bin/ Build output (dvx.exe, libs/, widgets/, apps/, config/)
+-- obj/ Intermediate object files
@@ -1232,27 +1470,43 @@ img { max-width: 100%; }
DVX GUI API Reference
-DOS Visual eXecutive -- Complete public API documentation generated from source headers.
-The DVX GUI is built as a five-layer architecture. Each layer is defined in its own header file. This reference covers every public function, type, and constant.
-Layers
+DOS Visual eXecutive -- Complete public API documentation covering every public function, type, and constant in the libdvx headers.
+The DVX GUI is built as a five-layer architecture. Each layer is defined in its own header file. Additional headers cover dialogs, resources, preferences, memory tracking, the platform abstraction, and the widget system.
+Headers
-
-
- dvxTypes.h -- Shared type definitions -
- dvxCursor.h -- Cursor definitions -
- dvxVideo.h -- Layer 1: VESA VBE Video Backend -
- dvxDraw.h -- Layer 2: Drawing Primitives -
- dvxComp.h -- Layer 3: Dirty Rectangle Compositor -
- dvxWm.h -- Layer 4: Window Manager +
- dvxTypes.h -- Shared type definitions and constants +
- dvxCur.h -- Embedded mouse cursor bitmaps +
- dvxFont.h -- Embedded 8x16 CP437 bitmap font +
- dvxPal.h -- 8-bit mode 256-color palette +
- dvxVideo.h -- Layer 1: VESA VBE video backend +
- dvxDraw.h -- Layer 2: 2D drawing primitives +
- dvxComp.h -- Layer 3: Dirty rectangle compositor +
- dvxWm.h -- Layer 4: Window manager
- dvxApp.h -- Layer 5: Application API +
- dvxDlg.h -- Modal dialog boxes +
- dvxRes.h -- DXE-embedded resource system +
- dvxPrefs.h -- INI preferences system +
- dvxMem.h -- Per-app memory tracking +
- dvxWgt.h -- Widget system public API +
- dvxWgtP.h -- Widget plugin API
dvxWidget.h -- Widget System
+platform/dvxPlat.h -- Platform abstraction layer
dvxTypes.h -- Shared Type Definitions
-dvxCursor.h -- Cursor Definitions
-dvxVideo.h -- Layer 1: VESA VBE Video Backend
+dvxCur.h -- Cursor Definitions
+ + +dvxVideo.h -- Layer 1: Video Backend
dvxDraw.h -- Layer 2: Drawing Primitives
-dvxComp.h -- Layer 3: Dirty Rectangle Compositor
+dvxComp.h -- Layer 3: Compositor
dvxWm.h -- Layer 4: Window Manager
dvxApp.h -- Layer 5: Application API
- + + + + + + +dvxTypes.h -- Shared Type Definitions
@@ -1305,7 +1559,7 @@ img { max-width: 100%; }Field Description ----- ----------- int32_t charWidth Fixed width per glyph (always 8) - int32_t charHeight Glyph height (14 or 16) + int32_t charHeight Glyph height (16 in the bundled font) int32_t firstChar ASCII code of first glyph (typically 0) int32_t numChars Number of glyphs (typically 256) const uint8_t *glyphData Packed 1bpp data, charHeight bytes per glyph@@ -1346,7 +1600,7 @@ img { max-width: 100%; } char title[MAX_TITLE_LEN] Window title text (max 128 chars) bool visible, focused, minimized, maximized, resizable, modal Window state flags bool iconNeedsRefresh true when contentBuf changed (for minimized icon refresh) - bool needsPaint true until first onPaint call + uint8_t paintNeeded PAINT_NONE / PAINT_PARTIAL / PAINT_FULL int32_t maxW, maxH Maximum dimensions int32_t preMaxX, preMaxY, preMaxW, preMaxH Saved geometry before maximize uint8_t *contentBuf Per-window content backbuffer @@ -1362,38 +1616,49 @@ img { max-width: 100%; }
Callbacks:
Callback Description -------- ----------- - onPaint(WindowT *win, RectT *dirtyArea) Content repaint requested - onKey(WindowT *win, int32_t key, int32_t mod) Key press - onKeyUp(WindowT *win, int32_t scancode, int32_t mod) Key release - onMouse(WindowT *win, int32_t x, int32_t y, int32_t btn) Mouse event (content-relative) - onResize(WindowT *win, int32_t newW, int32_t newH) Window resized - onClose(WindowT *win) Close requested - onMenu(WindowT *win, int32_t menuId) Menu item or accelerator activated - onScroll(WindowT *win, ScrollbarOrientE orient, int32_t val) Scrollbar value changed - onCursorQuery(WindowT *win, int32_t x, int32_t y) Return CURSOR_* for hit position - onFocus(WindowT *win) Window gained focus - onBlur(WindowT *win) Window lost focus+ onPaint(WindowT *win, RectT *dirtyArea) Content repaint requested + onKey(WindowT *win, int32_t key, int32_t mod) Key press + onKeyUp(WindowT *win, int32_t scancode, int32_t mod) Key release + onMouse(WindowT *win, int32_t x, int32_t y, int32_t buttons) Mouse event (content-relative) + onResize(WindowT *win, int32_t newW, int32_t newH) Window resized + onClose(WindowT *win) Close requested + onMenu(WindowT *win, int32_t menuId) Menu item or accelerator activated + onScroll(WindowT *win, ScrollbarOrientE orient, int32_t value) Scrollbar value changed + int32_t onCursorQuery(WindowT *win, int32_t x, int32_t y) Return CURSOR_* for hit position + onFocus(WindowT *win) Window gained focus + onBlur(WindowT *win) Window lost focus
WindowStackT
Z-ordered window stack (front-to-back: index count-1 is topmost). Owns system-wide drag/resize/scroll interaction state.
-Field Description - ----- ----------- - WindowT **windows Dynamic array of window pointers - int32_t count, cap Current count and allocated capacity - int32_t focusedIdx Stack index of focused window - int32_t dragWindow, dragOffX, dragOffY Active drag state - int32_t resizeWindow, resizeEdge Active resize state +Field Description + ----- ----------- + WindowT **windows Dynamic array of window pointers + int32_t count, cap Current count and allocated capacity + int32_t focusedIdx Stack index of focused window + int32_t dragWindow, dragOffX, dragOffY Active drag state + int32_t dragStartX, dragStartY Mouse position at drag begin (for deadzone) + bool dragActive True once mouse moved past deadzone + int32_t resizeWindow, resizeEdge Active resize state int32_t scrollWindow, scrollOrient, scrollDragOff Active scroll drag stateMenuT / MenuItemT / MenuBarT
Menu system types. Fixed-size label buffers (MAX_MENU_LABEL = 32). Cascading submenus supported via MenuItemT.subMenu pointer.
-Field Description - ----- ----------- - MenuItemT.label Item text (supports & accelerator markers) - MenuItemT.id Application-defined command ID - MenuItemT.type MenuItemNormalE, MenuItemCheckE, or MenuItemRadioE - MenuItemT.separator true = horizontal divider line - MenuItemT.enabled, checked Item state - MenuItemT.subMenu Child menu for cascading (NULL if leaf) - MenuBarT.activeIdx Open popup index (-1 = none)+Field Description + ----- ----------- + MenuItemT.label Item text (supports & accelerator markers) + MenuItemT.id Application-defined command ID + MenuItemT.type MenuItemNormalE, MenuItemCheckE, or MenuItemRadioE + MenuItemT.separator true = horizontal divider line + MenuItemT.enabled, checked Item state + MenuItemT.accelKey Lowercase accelerator character (0 = none) + MenuItemT.subMenu Child menu for cascading (NULL if leaf) + MenuT.label Menu bar label (e.g. "File") + MenuT.items Dynamic array of MenuItemT + MenuT.itemCount, itemCap Current count and allocated capacity + MenuT.barX, barW Computed position/width on the menu bar + MenuT.accelKey Lowercase accelerator character (0 = none) + MenuBarT.menus Dynamic array of MenuT + MenuBarT.menuCount, menuCap Current count and allocated capacity + MenuBarT.activeIdx Open popup index (-1 = none) + MenuBarT.positionsDirty True when barX/barW need recomputationScrollbarT
Window-level scrollbar state. Managed by the WM layer, drawn after content.
Field Description @@ -1409,7 +1674,11 @@ img { max-width: 100%; } ----- ----------- AccelEntryT.key ASCII character or KEY_Fxx constant AccelEntryT.modifiers Bitmask of ACCEL_CTRL, ACCEL_SHIFT, ACCEL_ALT - AccelEntryT.cmdId Command ID passed to onMenu+ AccelEntryT.cmdId Command ID passed to onMenu + AccelEntryT.normKey Pre-normalized key (uppercased) for fast matching + AccelEntryT.normMods Pre-masked modifiers (CTRL|ALT only) for fast matching + AccelTableT.entries Dynamic array of AccelEntryT + AccelTableT.count, cap Current count and allocated capacity
VideoModeInfoT
Describes an available video mode (enumerated at init).
Field Description
@@ -1493,8 +1762,8 @@ img { max-width: 100%; }
DVX_MAX(a, b) Return the larger of two values
dvxCursor.h -- Cursor Definitions
-Embedded 16x16 mouse cursor bitmaps compiled as static const data. No external cursor files. Uses the standard AND/XOR mask encoding from the IBM VGA hardware cursor spec.
+dvxCur.h -- Cursor Definitions
+Embedded 16x16 mouse cursor bitmaps compiled as static const data. No external cursor files. Uses the standard AND/XOR mask encoding from the IBM VGA hardware cursor spec. The AND mask selects transparency (1 = transparent, 0 = opaque) and the XOR data selects black vs. white for opaque pixels.
Cursor Shape IDs
Define Value Description
------ ----- -----------
@@ -1508,7 +1777,70 @@ img { max-width: 100%; }
CURSOR_COUNT 7 Total number of cursor shapes
Data
dvxCursors[CURSOR_COUNT]
-Static const array of CursorT structs, indexed by CURSOR_xxx constants. Each entry includes the AND mask, XOR data, dimensions, and hot spot coordinates.
+Static const array of CursorT structs, indexed by CURSOR_xxx constants. Each entry includes the AND mask, XOR data (both as 16-element uint16_t arrays), dimensions (16x16), and hot spot coordinates.
+dvxCursor
+Legacy alias for backward compatibility with code that predates multi-cursor support. Equivalent to dvxCursors[CURSOR_ARROW].
+dvxFont.h -- Embedded Bitmap Font Data
+Raw glyph bitmaps for the standard 8x16 VGA ROM font covering the full IBM Code Page 437 character set (256 glyphs). Compiled in as a static const array, avoiding a real-mode INT 10h call at startup.
+Glyph format: 1 bit per pixel, 8 pixels wide, MSB = leftmost pixel. Each glyph occupies 16 consecutive bytes (one byte per scanline). The 8-pixel width means per-scanline rendering never needs bit shifting across byte boundaries.
+CP437 covers:
+-
+
- 0-31 -- Smiley, card suits, arrows, notes (classic extended ASCII glyphs) +
- 32-126 -- Printable ASCII +
- 127 -- House glyph +
- 128-175 -- Accented Latin letters, currency, fractions +
- 176-223 -- Box-drawing characters (essential for chrome gadgets) +
- 224-254 -- Greek letters, math symbols, super/subscripts +
255 -- Non-breaking space
+Data
+font8x16
+Static const uint8_t array of 256 * 16 = 4096 bytes containing the packed 1bpp glyph bitmaps, in ASCII code order.
+dvxFont8x16
+Static const BitmapFontT struct describing the 8x16 font, ready to pass to drawText/drawTextN/drawChar. Use this as the default font for all text rendering.
+Constants
+Define Value Description + ------ ----- ----------- + FONT_CHAR_WIDTH 8 Fixed glyph width in pixels (defined in dvxTypes.h)+
dvxPal.h -- 256-Color Palette for 8-bit Mode
+Defines the 256-color VGA/VESA palette used in 8-bit video modes. Layout:
+Range Purpose + ----- ------- + 0-215 6x6x6 color cube -- uniformly distributed RGB (6 levels per channel: 0, 51, 102, 153, 204, 255). Index = r*36 + g*6 + b. + 216-231 16-step grey ramp for smooth gradients + 232-239 Dedicated UI chrome colors (highlight, shadow, title bar, desktop) + 240-255 Reserved (black)+
The cube layout enables O(1) color lookup: snapping an RGB triplet to the nearest cube vertex is integer division by 51. The grey ramp and chrome slots hold colors that need exact values not available in the cube.
+Chrome Color Indices
+Define Value Description + ------ ----- ----------- + PAL_CHROME_HIGHLIGHT 232 White (bevel highlight) + PAL_CHROME_SHADOW 233 Dark grey (bevel shadow) + PAL_CHROME_ACTIVE_BG 234 Navy (focused title bar) + PAL_CHROME_INACTIVE_BG 235 Grey (unfocused title bar) + PAL_CHROME_DESKTOP 236 Steel blue (desktop) + PAL_CHROME_SELECTION 237 Navy (selection highlight) + PAL_CHROME_TEXT 238 Black (text) + PAL_CHROME_WHITE 239 Bright white+
Inline Functions
+dvxGeneratePalette
+static inline void dvxGeneratePalette(uint8_t *pal);
+Populate a 768-byte (256 * 3) RGB buffer with the default DVX 8-bit palette. Called once at init in 8-bit mode to program the DAC.
+Parameter Description + --------- ----------- + pal Output RGB buffer (768 bytes)+
dvxNearestPalEntry
+static inline uint8_t dvxNearestPalEntry(const uint8_t *pal, uint8_t r, uint8_t g, uint8_t b);
+Find the nearest palette entry for an RGB color using minimum Euclidean distance. Two-phase: snap to color cube vertex (O(1)), then scan grey ramp and chrome entries (216-239) for a closer match. Called by packColor() in 8-bit mode.
+Parameter Description + --------- ----------- + pal Active 768-byte RGB palette + r, g, b Color components (0-255)+
Returns: Palette index (0-239) of the nearest match.
dvxVideo.h -- Layer 1: VESA VBE Video Backend
@@ -1536,6 +1868,14 @@ img { max-width: 100%; } d Display context (provides pixel format) r, g, b Color components (0-255)Returns: Native pixel value suitable for direct framebuffer write.
+unpackColor
+void unpackColor(const DisplayT *d, uint32_t color, uint8_t *r, uint8_t *g, uint8_t *b);
+Reverse of packColor -- decode a native pixel value to 8-bit RGB components. For direct-color modes, reverses the shift/mask arithmetic. For 8-bit mode, looks up the palette entry at the given index.
+Parameter Description + --------- ----------- + d Display context + color Packed native pixel value + r, g, b Output: color components (0-255)
setClipRect
void setClipRect(DisplayT *d, int32_t x, int32_t y, int32_t w, int32_t h);
Set the clip rectangle on the display. All subsequent draw operations clip to this rectangle. The caller must save and restore the clip rect around scoped operations.
@@ -1592,6 +1932,18 @@ img { max-width: 100%; } srcBuf, srcPitch Source buffer and pitch srcX, srcY Source origin w, h Rectangle dimensions +rectCopyTransparent
+void rectCopyTransparent(DisplayT *d, const BlitOpsT *ops, int32_t dstX, int32_t dstY, const uint8_t *srcBuf, int32_t srcPitch, int32_t srcX, int32_t srcY, int32_t w, int32_t h, uint32_t keyColor);
+Copy with color-key transparency. Pixels matching keyColor are skipped, letting the destination show through. Used to draw image buttons and icons with transparent backgrounds.
+Parameter Description + --------- ----------- + d Display context + ops Blit operations vtable + dstX, dstY Destination position + srcBuf, srcPitch Source buffer and pitch + srcX, srcY Source origin + w, h Rectangle dimensions + keyColor Packed color treated as transparent
drawBevel
void drawBevel(DisplayT *d, const BlitOpsT *ops, int32_t x, int32_t y, int32_t w, int32_t h, const BevelStyleT *style);
Draw a beveled frame. Top/left edges in highlight color, bottom/right in shadow. Interior filled with face color if non-zero.
@@ -1904,6 +2256,20 @@ img { max-width: 100%; }Parameter Description --------- ----------- menu Menu to append separator to+
wmRemoveMenuItem
+bool wmRemoveMenuItem(MenuT *menu, int32_t id);
+Remove a menu item by command ID. Searches the menu's items array and shifts remaining items down to close the gap.
+Parameter Description + --------- ----------- + menu Menu to remove item from + id Command ID to remove+
Returns: true if a matching item was found and removed.
+wmClearMenuItems
+void wmClearMenuItems(MenuT *menu);
+Remove all items from a menu while preserving the menu itself on the menu bar. Use when rebuilding a menu's contents dynamically (e.g. a recent-files submenu).
+Parameter Description + --------- ----------- + menu Menu to empty
wmMenuItemIsChecked
bool wmMenuItemIsChecked(MenuBarT *bar, int32_t id);
Query the checked state of a menu item by command ID. Searches all menus in the bar.
@@ -2006,6 +2372,19 @@ img { max-width: 100%; } colors Color scheme stack Window stack clipTo Dirty rectangle +wmDrawVScrollbarAt
+void wmDrawVScrollbarAt(DisplayT *d, const BlitOpsT *ops, const ColorSchemeT *colors, int32_t x, int32_t y, int32_t h, int32_t scrollPos, int32_t visibleItems, int32_t totalItems);
+Draw a standalone vertical scrollbar at the given screen coordinates, without a ScrollbarT struct. Used by popup lists (dropdown, combobox) that need a scrollbar inline within a popup overlay. Thumb size and position are computed from scrollPos / visibleItems / totalItems.
+Parameter Description + --------- ----------- + d Display context + ops Blit operations vtable + colors Color scheme + x, y Screen position (top of scrollbar) + h Track height in pixels + scrollPos Current top visible item index + visibleItems Visible item count (for thumb size) + totalItems Total item count
Hit Testing
wmHitTest
int32_t wmHitTest(const WindowStackT *stack, int32_t mx, int32_t my, int32_t *hitPart);
@@ -2476,14 +2855,16 @@ img { max-width: 100%; }
mode WallpaperStretchE, WallpaperTileE, or WallpaperCenterE
Mouse Configuration
dvxSetMouseConfig
-void dvxSetMouseConfig(AppContextT *ctx, int32_t wheelDir, int32_t dblClickMs, int32_t accelThreshold);
-Configure mouse behavior.
+void dvxSetMouseConfig(AppContextT *ctx, int32_t wheelDir, int32_t dblClickMs, int32_t accelThreshold, int32_t mickeyRatio, int32_t wheelStep);
+Configure mouse behavior. Updates the in-memory AppContextT fields and programs any INT 33h settings that need driver-side adjustment.
Parameter Description --------- ----------- ctx Application context wheelDir 1 = normal, -1 = reversed dblClickMs Double-click speed in milliseconds (e.g. 500) - accelThreshold Double-speed threshold in mickeys/sec (0 = don't change)+ accelThreshold Double-speed threshold in mickeys/sec (0 = don't change) + mickeyRatio Mickeys per 8 pixels (0 = don't change, 8 = default speed) + wheelStep Lines to scroll per wheel notch (1-10, default 3)
Accelerators
dvxCreateAccelTable
AccelTableT *dvxCreateAccelTable(void);
@@ -2542,7 +2923,7 @@ img { max-width: 100%; }
Returns: Pixel buffer, or NULL on failure.
dvxLoadImageFromMemory
uint8_t *dvxLoadImageFromMemory(const AppContextT *ctx, const uint8_t *data, int32_t dataLen, int32_t *outW, int32_t *outH, int32_t *outPitch);
-Load an image from a memory buffer. Same output format as dvxLoadImage(). Caller must free with dvxFreeImage().
+Load an image from a memory buffer (typically resource data). Same output format as dvxLoadImage(). Caller must free with dvxFreeImage().
Parameter Description
--------- -----------
ctx Application context
@@ -2551,6 +2932,19 @@ img { max-width: 100%; }
outW, outH Output: image dimensions
outPitch Output: row pitch in bytes
Returns: Pixel buffer, or NULL on failure.
+dvxLoadImageAlpha
+uint8_t *dvxLoadImageAlpha(const AppContextT *ctx, const uint8_t *data, int32_t dataLen, int32_t *outW, int32_t *outH, int32_t *outPitch, bool *outHasAlpha, uint32_t *outKeyColor);
+Load an image from memory with alpha transparency. Pixels with alpha < 128 are replaced with a packed magenta key color. If any transparent pixels are found, *outHasAlpha is set to true and *outKeyColor receives the packed key color for use with rectCopyTransparent. Caller must free with dvxFreeImage.
+Parameter Description + --------- ----------- + ctx Application context + data Image data buffer + dataLen Buffer size in bytes + outW, outH Output: image dimensions + outPitch Output: row pitch + outHasAlpha Output: true if any transparent pixels found + outKeyColor Output: packed key color (valid when outHasAlpha is true)+
Returns: Pixel buffer, or NULL on failure.
dvxFreeImage
void dvxFreeImage(uint8_t *data);
Free a pixel buffer returned by dvxLoadImage() or dvxLoadImageFromMemory().
@@ -2650,7 +3044,7 @@ img { max-width: 100%; }Returns: 32-bit hash value.
dvxWidget.h -- Widget System
+dvxWgt.h -- Widget System
Retained-mode widget toolkit layered on the DVX window manager. Widgets form a tree (parent-child) rooted at a per-window VBox container. Layout is automatic: measure minimum sizes bottom-up, then allocate space top-down with flexbox-like weighted distribution. Widget types are registered dynamically at runtime via DXE plugins.
WidgetT Structure
Core widget structure. Generic across all widget types; type-specific data lives in the void *data pointer managed by each widget's DXE.
@@ -2670,7 +3064,11 @@ img { max-width: 100%; } uint32_t fgColor, bgColor Custom colors (0 = use scheme defaults) bool visible, enabled, readOnly State flags bool swallowTab Tab key goes to widget, not focus navigation + bool paintDirty Needs repaint (set by wgtInvalidatePaint) + bool childDirty A descendant needs repaint (for WCLASS_PAINTS_CHILDREN) + bool pressed WCLASS_PRESS_RELEASE: set while button is pressed char accelKey Accelerator character (0 = none) + int32_t contentOffX, contentOffY Content offset for mouse event coordinates void *userData, *data Application data and widget-private data const char *tooltip Tooltip text (NULL = none) MenuT *contextMenu Right-click menu (NULL = none) @@ -2685,9 +3083,9 @@ img { max-width: 100%; } onKeyPress(WidgetT *w, int32_t keyAscii) ASCII key press onKeyDown(WidgetT *w, int32_t keyCode, int32_t shift) Key down onKeyUp(WidgetT *w, int32_t keyCode, int32_t shift) Key up - onMouseDown(WidgetT *w, int32_t btn, int32_t x, int32_t y) Mouse button pressed - onMouseUp(WidgetT *w, int32_t btn, int32_t x, int32_t y) Mouse button released - onMouseMove(WidgetT *w, int32_t btn, int32_t x, int32_t y) Mouse moved + onMouseDown(WidgetT *w, int32_t button, int32_t x, int32_t y) Mouse button pressed + onMouseUp(WidgetT *w, int32_t button, int32_t x, int32_t y) Mouse button released + onMouseMove(WidgetT *w, int32_t button, int32_t x, int32_t y) Mouse moved onScroll(WidgetT *w, int32_t delta) Mouse wheel onValidate(WidgetT *w) Return false to cancel a writeSize Specification Macros
@@ -2840,15 +3238,16 @@ img { max-width: 100%; } availW/H Available space font Bitmap font (for character-based sizing)wgtPaint
-void wgtPaint(WidgetT *root, DisplayT *d, const BlitOpsT *ops, const BitmapFontT *font, const ColorSchemeT *colors);
+void wgtPaint(WidgetT *root, DisplayT *d, const BlitOpsT *ops, const BitmapFontT *font, const ColorSchemeT *colors, bool fullRepaint);
Paint the entire widget tree by depth-first traversal. Each widget's clip rect is set to its bounds. Overlays (popups, tooltips) are painted in a second pass on top.
-Parameter Description - --------- ----------- - root Root widget - d Display context - ops Blit operations vtable - font Bitmap font - colors Color scheme+
Parameter Description + --------- ----------- + root Root widget + d Display context + ops Blit operations vtable + font Bitmap font + colors Color scheme + fullRepaint true = repaint every widget; false = only paintDirty widgets
Debug
wgtSetDebugLayout
void wgtSetDebugLayout(AppContextT *ctx, bool enabled);
@@ -2960,13 +3359,833 @@ img { max-width: 100%; }
wclsPoll(w, win) WGT_METHOD_POLL Periodic polling
wclsQuickRepaint(w, outY, outH) WGT_METHOD_QUICK_REPAINT Fast partial repaint
wclsScrollChildIntoView(parent, child) WGT_METHOD_SCROLL_CHILD_INTO_VIEW Scroll child visible
+Method IDs
+Fixed constants used to index into WidgetClassT.handlers[]. Method IDs are stable ABI -- new methods are appended at the next sequential ID, never reordered or reused.
+ID Symbol Signature + -- ------ --------- + 0 WGT_METHOD_PAINT void (w, d, ops, font, colors) + 1 WGT_METHOD_PAINT_OVERLAY void (w, d, ops, font, colors) + 2 WGT_METHOD_CALC_MIN_SIZE void (w, font) + 3 WGT_METHOD_LAYOUT void (w, font) + 4 WGT_METHOD_GET_LAYOUT_METRICS void (w, font, pad, gap, extraTop, borderW) + 5 WGT_METHOD_ON_MOUSE void (w, root, vx, vy) + 6 WGT_METHOD_ON_KEY void (w, key, mod) + 7 WGT_METHOD_ON_ACCEL_ACTIVATE void (w, root) + 8 WGT_METHOD_DESTROY void (w) + 9 WGT_METHOD_ON_CHILD_CHANGED void (parent, child) + 10 WGT_METHOD_GET_TEXT const char *(w) + 11 WGT_METHOD_SET_TEXT void (w, text) + 12 WGT_METHOD_CLEAR_SELECTION bool (w) + 13 WGT_METHOD_CLOSE_POPUP void (w) + 14 WGT_METHOD_GET_POPUP_RECT void (w, font, contentH, popX, popY, popW, popH) + 15 WGT_METHOD_ON_DRAG_UPDATE void (w, root, x, y) + 16 WGT_METHOD_ON_DRAG_END void (w, root, x, y) + 17 WGT_METHOD_GET_CURSOR_SHAPE int32_t (w, vx, vy) + 18 WGT_METHOD_POLL void (w, win) + 19 WGT_METHOD_QUICK_REPAINT int32_t (w, outY, outH) + 20 WGT_METHOD_SCROLL_CHILD_INTO_VIEW void (parent, child) + -- WGT_METHOD_COUNT = 21, WGT_METHOD_MAX = 32+
WGT_CLASS_VERSION is bumped on breaking ABI changes. The framework rejects WidgetClassT structs whose version does not match.
+Widget Class Dispatch Table
+WidgetClassT
+typedef struct WidgetClassT {
+ uint32_t version;
+ uint32_t flags;
+ void *handlers[WGT_METHOD_MAX];
+} WidgetClassT;
+Field Description + ----- ----------- + version Must equal WGT_CLASS_VERSION at registration + flags Bitmask of WCLASS_xxx flags + handlers Array of 32 function pointers indexed by WGT_METHOD_xxx+
Size Encoding Constants
+Define Value Description + ------ ----- ----------- + WGT_SIZE_TYPE_MASK 0xC0000000 Top 2 bits: unit type selector + WGT_SIZE_VAL_MASK 0x3FFFFFFF Bottom 30 bits: numeric value + WGT_SIZE_PIXELS 0x00000000 Unit tag: pixels + WGT_SIZE_CHARS 0x40000000 Unit tag: character widths + WGT_SIZE_PERCENT 0x80000000 Unit tag: percentage of parent + WGT_WEIGHT_FILL 100 Default "flexible" weight value+
Widget Interface Descriptors
+WgtPropDescT
+Describes a BASIC-exposed property on a widget type. Used by the form runtime and IDE for generic get/set dispatch.
+Field Description + ----- ----------- + name BASIC property name (e.g. "Caption", "Value") + type Data type: WGT_IFACE_STRING, WGT_IFACE_INT, WGT_IFACE_BOOL, WGT_IFACE_FLOAT, or WGT_IFACE_ENUM + getFn Getter function pointer (NULL if write-only) + setFn Setter function pointer (NULL if read-only) + enumNames For WGT_IFACE_ENUM: NULL-terminated array of value names+
WgtMethodDescT
+Describes an invokable method on a widget type.
+Field Description + ----- ----------- + name BASIC method name (e.g. "Clear", "SetFocus") + sig Calling convention ID (WGT_SIG_xxx) + fn Function pointer+
WgtEventDescT
+Describes an event beyond the standard common set (Click, DblClick, Change, GotFocus, LostFocus).
+Field Description + ----- ----------- + name Event name (e.g. "Change", "Timer")+
WgtIfaceT
+Top-level interface descriptor registered by each widget DXE.
+Field Description + ----- ----------- + basName VB-style name (e.g. "CommandButton"), or NULL + props Array of WgtPropDescT + propCount Length of props array + methods Array of WgtMethodDescT + methodCount Length of methods array + events Array of WgtEventDescT (extras beyond common set) + eventCount Length of events array + createSig How to call the widget's create() function (WgtCreateSigE) + createArgs Default numeric args for design-time instantiation + isContainer true = widget can hold child widgets + defaultEvent Default event name for form designer + namePrefix Auto-name prefix (NULL = derive from basName)+
Property Data Type Constants
+Define Value Description + ------ ----- ----------- + WGT_IFACE_STRING 0 const char * + WGT_IFACE_INT 1 int32_t + WGT_IFACE_BOOL 2 bool + WGT_IFACE_FLOAT 3 float + WGT_IFACE_ENUM 4 int32_t with named values+
Create Function Signature Constants
+Define Value Form + ------ ----- ---- + WGT_CREATE_PARENT 0 fn(parent) + WGT_CREATE_PARENT_TEXT 1 fn(parent, const char *text) + WGT_CREATE_PARENT_INT 2 fn(parent, int32_t) + WGT_CREATE_PARENT_INT_INT 3 fn(parent, int32_t, int32_t) + WGT_CREATE_PARENT_INT_INT_INT 4 fn(parent, int32_t, int32_t, int32_t) + WGT_CREATE_PARENT_INT_BOOL 5 fn(parent, int32_t, bool) + WGT_CREATE_PARENT_BOOL 6 fn(parent, bool) + WGT_CREATE_PARENT_DATA 7 fn(parent, data, w, h, pitch) -- not auto-creatable+
WGT_MAX_CREATE_ARGS is 3.
+dvxDlg.h -- Modal Dialogs
+Pre-built modal dialog boxes that block the caller and run their own event loop via dvxUpdate() until the user dismisses them. Modal dialogs set ctx->modalWindow to prevent input from reaching other windows for the dialog's lifetime.
+Message Box Flags
+Button configurations (low nibble):
+Define Value Description + ------ ----- ----------- + MB_OK 0x0000 OK button only (default) + MB_OKCANCEL 0x0001 OK and Cancel + MB_YESNO 0x0002 Yes and No + MB_YESNOCANCEL 0x0003 Yes, No, and Cancel + MB_RETRYCANCEL 0x0004 Retry and Cancel+
Icon types (high nibble, OR with button flags):
+Define Value Description + ------ ----- ----------- + MB_ICONINFO 0x0010 Information icon + MB_ICONWARNING 0x0020 Warning icon + MB_ICONERROR 0x0030 Error icon + MB_ICONQUESTION 0x0040 Question mark icon+
Return values:
+Define Value Button pressed + ------ ----- -------------- + ID_OK 1 OK + ID_CANCEL 2 Cancel or dialog closed + ID_YES 3 Yes + ID_NO 4 No + ID_RETRY 5 Retry+
dvxMessageBox
+int32_t dvxMessageBox(AppContextT *ctx, const char *title, const char *message, int32_t flags);
+Display a modal message box. Blocks the caller by running dvxUpdate() in a loop until a button is pressed or the dialog is closed. The window is automatically destroyed on return.
+Parameter Description + --------- ----------- + ctx Application context + title Window title (NULL falls back to a generic default) + message Body text + flags MB_xxx button + icon flags, OR'd together+
Returns: ID_xxx of the button that was pressed.
+// Example: yes/no confirmation
+int32_t r = dvxMessageBox(ctx, "Save", "Save changes before closing?", MB_YESNOCANCEL | MB_ICONQUESTION);
+if (r == ID_YES) { saveFile(); }
+dvxErrorBox
+int32_t dvxErrorBox(AppContextT *ctx, const char *title, const char *message);
+Convenience wrapper for MB_OK | MB_ICONERROR. Title defaults to "Error" when NULL.
+Parameter Description + --------- ----------- + ctx Application context + title Dialog title, or NULL for "Error" + message Error message+
Returns: ID_OK.
+dvxInfoBox
+int32_t dvxInfoBox(AppContextT *ctx, const char *title, const char *message);
+Convenience wrapper for MB_OK | MB_ICONINFO.
+Parameter Description + --------- ----------- + ctx Application context + title Dialog title + message Informational message+
Returns: ID_OK.
+File Dialog
+FileFilterT
+Describes a filter entry in the file dialog's format dropdown. The glob pattern is extracted from inside the parentheses.
+Field Description + ----- ----------- + label e.g. "Text Files (*.txt)" or "Images (*.bmp;*.png;*.jpg;*.gif)"+
File Dialog Flags
+Define Value Description + ------ ----- ----------- + FD_OPEN 0x0000 File open dialog (default) + FD_SAVE 0x0001 File save dialog (with overwrite prompt)+
dvxFileDialog
+bool dvxFileDialog(AppContextT *ctx, const char *title, int32_t flags, const char *initialDir, const FileFilterT *filters, int32_t filterCount, char *outPath, int32_t outPathSize);
+Display a modal file open/save dialog. Shows a directory listing with parent/drive-letter navigation, a filename input, and an optional filter dropdown.
+Parameter Description + --------- ----------- + ctx Application context + title Window title + flags FD_OPEN or FD_SAVE + initialDir Starting directory (NULL = current working directory) + filters Array of FileFilterT, or NULL + filterCount Number of filter entries + outPath Output buffer for selected path + outPathSize Capacity of outPath buffer+
Returns: true if the user selected a file, false if cancelled or closed.
+Input Boxes
+dvxInputBox
+bool dvxInputBox(AppContextT *ctx, const char *title, const char *prompt, const char *defaultText, char *outBuf, int32_t outBufSize);
+Display a modal input box with a prompt label, text field, and OK/Cancel buttons.
+Parameter Description + --------- ----------- + ctx Application context + title Window title + prompt Prompt label above the input field + defaultText Initial text (NULL = empty) + outBuf Output buffer + outBufSize Capacity of outBuf+
Returns: true if OK was pressed, false if cancelled.
+dvxIntInputBox
+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);
+Display a modal integer input box with a spinner (up/down arrows) for clamped numeric input.
+Parameter Description + --------- ----------- + ctx Application context + title Window title + prompt Prompt label + defaultVal Initial value + minVal Minimum allowed value + maxVal Maximum allowed value + step Increment per arrow click + outVal Output: entered value+
Returns: true if OK pressed, false if cancelled.
+Choice Dialog
+dvxChoiceDialog
+bool dvxChoiceDialog(AppContextT *ctx, const char *title, const char *prompt, const char **items, int32_t itemCount, int32_t defaultIdx, int32_t *outIdx);
+Display a modal dialog with a listbox of choices. The user picks one item and clicks OK, or cancels.
+Parameter Description + --------- ----------- + ctx Application context + title Window title + prompt Prompt label above the list + items Array of choice strings + itemCount Number of items + defaultIdx Initially highlighted item (-1 = none) + outIdx Output: selected index+
Returns: true if a choice was made, false if cancelled.
+Save Prompt
+Return codes for dvxPromptSave:
+Define Value Action + ------ ----- ------ + DVX_SAVE_YES 1 Save, then proceed + DVX_SAVE_NO 2 Discard, then proceed + DVX_SAVE_CANCEL 3 Abort the operation+
dvxPromptSave
+int32_t dvxPromptSave(AppContextT *ctx, const char *title);
+Display a canonical "Save changes?" dialog with Yes/No/Cancel buttons and an appropriate question icon.
+Parameter Description + --------- ----------- + ctx Application context + title Document name for message context+
Returns: DVX_SAVE_YES, DVX_SAVE_NO, or DVX_SAVE_CANCEL.
+dvxRes.h -- DXE-Embedded Resource System
+Resources are appended to DXE3 files (.app, .wgt, .lib) after the normal DXE content. The DXE loader never reads past its own header-specified sections, so the appended resource block is invisible to dlopen. This lets each DXE carry its own icons, localized text, help content, and binary data without separate resource files.
+File Layout
+[DXE3 content] -- untouched, loaded by dlopen
+[resource data entries] -- sequential, variable length
+[resource directory] -- fixed-size entries (48 bytes each)
+[footer] -- magic + directory offset + entry count (16 bytes)
+Reading starts from the end: seek to EOF - sizeof(footer), verify the magic, then seek to the directory.
+Constants
+ Define Value Description
+ ------ ----- -----------
+ DVX_RES_ICON 1 Image data (BMP, PNG, etc.)
+ DVX_RES_TEXT 2 Null-terminated string
+ DVX_RES_BINARY 3 Arbitrary binary data (app-specific)
+ DVX_RES_MAGIC 0x52585644 Footer signature ("DVXR" little-endian)
+ DVX_RES_NAME_MAX 32 Max resource name length including null
+Structures
+DvxResDirEntryT
+Directory entry describing one resource (48 bytes on disk).
+Field Description + ----- ----------- + name Resource name (up to 32 chars, null-terminated) + type DVX_RES_ICON, DVX_RES_TEXT, or DVX_RES_BINARY + offset Absolute file offset of the data + size Data size in bytes + reserved Padding (must be zero)+
DvxResFooterT
+Footer at the very end of a DXE file with appended resources (16 bytes).
+Field Description + ----- ----------- + magic DVX_RES_MAGIC + dirOffset Absolute file offset of the resource directory + entryCount Number of directory entries + reserved Padding (must be zero)+
DvxResHandleT
+Opaque runtime handle representing an open resource block.
+Field Description + ----- ----------- + path Source file path + entries Directory entries (sorted by name for bsearch) + entryCount Number of entries+
Runtime API
+dvxResOpen
+DvxResHandleT *dvxResOpen(const char *path);
+Open a resource handle by reading the footer and directory. Returns NULL if the file has no resource block or cannot be read. Entries are sorted on open for O(log n) name lookup via bsearch.
+Parameter Description + --------- ----------- + path Path to the DXE (or any file) with appended resources+
Returns: Handle pointer, or NULL.
+dvxResRead
+void *dvxResRead(DvxResHandleT *h, const char *name, uint32_t *outSize);
+Find a resource by name and read its data into a freshly malloc'd buffer. Caller must free the returned buffer.
+Parameter Description + --------- ----------- + h Resource handle + name Resource name + outSize Output: data size in bytes+
Returns: Data buffer, or NULL if not found or I/O failed.
+dvxResFind
+const DvxResDirEntryT *dvxResFind(DvxResHandleT *h, const char *name);
+Look up a resource's directory entry by name. The returned pointer is valid until dvxResClose.
+Parameter Description + --------- ----------- + h Resource handle + name Resource name+
Returns: Pointer to directory entry, or NULL if not found.
+dvxResClose
+void dvxResClose(DvxResHandleT *h);
+Close a resource handle and free its memory.
+Parameter Description + --------- ----------- + h Handle to close+
dvxResAppend
+int32_t dvxResAppend(const char *path, const char *name, uint32_t type, const void *data, uint32_t dataSize);
+Append a resource to an existing DXE file. Preserves existing resources and adds the new one. Thin wrapper over the resource writer in tools/dvxResWrite.h.
+Parameter Description + --------- ----------- + path Target DXE path + name Resource name (up to DVX_RES_NAME_MAX - 1 chars) + type DVX_RES_ICON, DVX_RES_TEXT, or DVX_RES_BINARY + data Resource payload + dataSize Payload size in bytes+
Returns: 0 on success, -1 on failure.
+dvxResRemove
+int32_t dvxResRemove(const char *path, const char *name);
+Remove a resource from a DXE file by name. If this was the last resource, the file is truncated back to the original DXE content.
+Parameter Description + --------- ----------- + path Target DXE path + name Resource name to remove+
Returns: 0 on success, -1 if not found or I/O failed.
+See Also
+dvxResLoadIcon / dvxResLoadText / dvxResLoadData -- higher-level helpers on top of this API
+dvxPrefs.h -- INI Preferences System
+Handle-based API over classic INI files. Each prefsLoad/prefsCreate returns a PrefsHandleT that must be passed to all subsequent calls and freed with prefsClose when done. Multiple INI files can be open simultaneously.
+Constants
+Define Value Description + ------ ----- ----------- + DVX_INI_PATH "CONFIG" DVX_PATH_SEP "DVX.INI" Canonical system INI path+
Types
+PrefsHandleT
+Opaque handle representing an in-memory INI file. Fields are not exposed.
+Lifecycle
+prefsCreate
+PrefsHandleT *prefsCreate(void);
+Create an empty preferences handle with no associated file. Use this when building an INI from scratch before calling prefsSaveAs.
+Returns: New handle, or NULL on allocation failure.
+prefsLoad
+PrefsHandleT *prefsLoad(const char *filename);
+Load an INI file into a new handle. If the file does not exist, returns a valid empty handle with the path stored so prefsSave can write a new file later.
+Parameter Description + --------- ----------- + filename Path to INI file+
Returns: Handle, or NULL on allocation failure.
+prefsSave
+bool prefsSave(PrefsHandleT *h);
+Save the in-memory state back to the file that was loaded (or captured by prefsLoad for a non-existent file).
+Parameter Description + --------- ----------- + h Preferences handle+
Returns: true on success.
+prefsSaveAs
+bool prefsSaveAs(PrefsHandleT *h, const char *filename);
+Save to a specific file, overriding the handle's stored path.
+Parameter Description + --------- ----------- + h Preferences handle + filename Output file path+
Returns: true on success.
+prefsClose
+void prefsClose(PrefsHandleT *h);
+Release all memory held by the handle. Does not save -- call prefsSave first if needed.
+Parameter Description + --------- ----------- + h Handle to close+
Getters
+prefsGetString
+const char *prefsGetString(PrefsHandleT *h, const char *section, const char *key, const char *defaultVal);
+Retrieve a string value from [section]/key. The returned pointer is valid until the key is modified or the handle is closed.
+Parameter Description + --------- ----------- + h Preferences handle + section Section name (without brackets) + key Key name + defaultVal Returned if the key is not present+
Returns: Key value or defaultVal.
+prefsGetInt
+int32_t prefsGetInt(PrefsHandleT *h, const char *section, const char *key, int32_t defaultVal);
+Retrieve an integer value. Supports decimal and negative numbers.
+Parameter Description + --------- ----------- + h Preferences handle + section Section name + key Key name + defaultVal Returned if the key is absent or non-numeric+
Returns: Parsed int, or defaultVal.
+prefsGetBool
+bool prefsGetBool(PrefsHandleT *h, const char *section, const char *key, bool defaultVal);
+Retrieve a boolean value. Recognises "true"/"yes"/"1" as true and "false"/"no"/"0" as false (case-insensitive).
+Parameter Description + --------- ----------- + h Preferences handle + section Section name + key Key name + defaultVal Returned if the key is absent or unrecognised+
Returns: Parsed bool, or defaultVal.
+Setters
+prefsSetString
+void prefsSetString(PrefsHandleT *h, const char *section, const char *key, const char *value);
+Set a string value. Creates the section and key if they do not already exist.
+prefsSetInt
+void prefsSetInt(PrefsHandleT *h, const char *section, const char *key, int32_t value);
+Set an integer value (stored in decimal).
+prefsSetBool
+void prefsSetBool(PrefsHandleT *h, const char *section, const char *key, bool value);
+Set a boolean value (stored as "true"/"false").
+prefsRemove
+void prefsRemove(PrefsHandleT *h, const char *section, const char *key);
+Remove a key from a section. No-op if the key does not exist.
+dvxMem.h -- Per-App Memory Tracking
+Wraps malloc/free/calloc/realloc/strdup with a 16-byte header that records the owning app ID and allocation size. The Task Manager displays per-app memory usage, and leaks are detected when an app is terminated.
+DXE code does NOT need to include this header for tracking to work. The DXE export table maps malloc/free/calloc/realloc/strdup to these wrappers transparently. Call sites that need the explicit dvxXxx names (e.g. dvxMemGetAppUsage) or the dvxMemAppIdPtr declaration should include dvxMem.h directly.
+Globals
+dvxMemAppIdPtr
+extern int32_t *dvxMemAppIdPtr;
+Pointer to the current owning app ID. The shell points this at its currentAppId field during init so every allocation is charged to the running app. When dvxMemAppIdPtr is NULL or points to zero, allocations are charged to the shell.
+Allocation Wrappers
+dvxMalloc
+void *dvxMalloc(size_t size);
+Tracked malloc. Returns a pointer to user memory (header is hidden in front of it).
+dvxCalloc
+void *dvxCalloc(size_t nmemb, size_t size);
+Tracked calloc.
+dvxRealloc
+void *dvxRealloc(void *ptr, size_t size);
+Tracked realloc. Works correctly with tracked pointers only -- the magic header identifies them.
+dvxFree
+void dvxFree(void *ptr);
+Tracked free. Falls through to the real free() if the pointer's header magic does not match, so mixing tracked and untracked pointers is safe.
+dvxStrdup
+char *dvxStrdup(const char *s);
+Tracked strdup.
+Accounting
+dvxMemSnapshotLoad
+void dvxMemSnapshotLoad(int32_t appId);
+Record a baseline memory snapshot for the given app. Called right before app code starts so later calls to dvxMemGetAppUsage can report net growth.
+Parameter Description + --------- ----------- + appId App ID to snapshot+
dvxMemGetAppUsage
+uint32_t dvxMemGetAppUsage(int32_t appId);
+Return the total bytes currently charged to the given app ID.
+Parameter Description + --------- ----------- + appId App ID to query+
Returns: Bytes allocated for this app.
+dvxMemResetApp
+void dvxMemResetApp(int32_t appId);
+Free every tracked allocation charged to the given app. Called by the shell after an app exits or crashes to reclaim its memory.
+Parameter Description + --------- ----------- + appId App ID to flush+
dvxWgtP.h -- Widget Plugin API
+Included by widget .c files (DXE modules) to access core infrastructure for tree manipulation, focus management, scrollbar drawing, layout helpers, and shared interaction state. This header is NOT intended for application code -- use dvxWgt.h for the public widget API.
+Validation Macros
+VALIDATE_WIDGET / VALIDATE_WIDGET_VOID
+VALIDATE_WIDGET(w, wtype, retval); // returns retval on mismatch
+VALIDATE_WIDGET_VOID(w, wtype); // returns void on mismatch
+Bail out of a widget method if the widget pointer is NULL or its type does not match the expected wtype. Use at the top of every widget-specific API function.
+Core Constants
+Define Value Description + ------ ----- ----------- + DEFAULT_SPACING 4 Default pixel spacing between VBox/HBox children + DEFAULT_PADDING 4 Default internal padding for containers + SB_MIN_THUMB 14 Minimum scrollbar thumb size in pixels + WGT_SB_W 14 Widget-internal scrollbar width + KEY_MOD_SHIFT 0x03 Shift modifier bits + KEY_MOD_CTRL 0x04 Ctrl modifier bit + KEY_MOD_ALT 0x08 Alt modifier bit+
Inline Helpers
+clampInt
+static inline int32_t clampInt(int32_t val, int32_t lo, int32_t hi);
+Clamp val into the [lo, hi] range.
+drawTextEmbossed
+static inline void drawTextEmbossed(DisplayT *d, const BlitOpsT *ops, const BitmapFontT *font, int32_t x, int32_t y, const char *text, const ColorSchemeT *colors);
+Draw text twice -- once offset by (1,1) in highlight color, then overlaid in shadow color at (x,y) -- for a classic Motif-style embossed look used on disabled labels.
+drawTextAccelEmbossed
+static inline void drawTextAccelEmbossed(DisplayT *d, const BlitOpsT *ops, const BitmapFontT *font, int32_t x, int32_t y, const char *text, const ColorSchemeT *colors);
+Embossed text with & accelerator markers. Same offset logic as drawTextEmbossed, but processes & markers.
+Shared Interaction State
+Extern variables defined in widgetCore.c. These hold system-wide widget state: only one focused widget, one open popup, one pressed button at a time.
+Variable Type Purpose + -------- ---- ------- + sCursorBlinkOn bool Current state of the text cursor blink + sDblClickTicks clock_t Double-click interval in clock() ticks + sDebugLayout bool When true, draw colored debug borders around containers + sClosedPopup WidgetT* Widget whose popup just closed (suppresses re-open) + sFocusedWidget WidgetT* Currently focused widget + sKeyPressedBtn WidgetT* Button being pressed via keyboard (for release tracking) + sOpenPopup WidgetT* Currently open popup (dropdown/combo list) + sDragWidget WidgetT* Widget being dragged (any drag type) + sPollWidgetCount int32_t Count of widgets with WCLASS_NEEDS_POLL flag set + sPollWidgets WidgetT** Dynamic array of poll widgets (stb_ds) + sCursorBlinkFn fn ptr Callback invoked when the blink flips (repaints focused text)+
Core Widget Functions
+widgetAlloc
+WidgetT *widgetAlloc(WidgetT *parent, int32_t type);
+Allocate a new WidgetT, initialize its fields to defaults, link it as the last child of parent (if non-NULL), and assign its class pointer from widgetClassTable[type].
+widgetAddChild
+void widgetAddChild(WidgetT *parent, WidgetT *child);
+Append child to parent's child list. Updates parent's firstChild/lastChild and child's nextSibling pointers.
+widgetRemoveChild
+void widgetRemoveChild(WidgetT *parent, WidgetT *child);
+Unlink child from parent's child list. Does not destroy the child.
+widgetDestroyChildren
+void widgetDestroyChildren(WidgetT *w);
+Recursively destroy all descendants of w, calling each one's wclsDestroy handler.
+Focus Management
+widgetFindNextFocusable
+WidgetT *widgetFindNextFocusable(WidgetT *root, WidgetT *after);
+Find the next focusable widget in tab order after the given widget. Wraps to the beginning at the end of the tree.
+widgetFindPrevFocusable
+WidgetT *widgetFindPrevFocusable(WidgetT *root, WidgetT *before);
+Find the previous focusable widget in tab order. Wraps to the end at the beginning of the tree.
+widgetFindByAccel
+WidgetT *widgetFindByAccel(WidgetT *root, char key);
+Find a focusable widget whose accelKey (lowercase) matches the given character. Used for Alt+letter hotkeys on buttons and labels.
+Hit Testing
+widgetHitTest
+WidgetT *widgetHitTest(WidgetT *w, int32_t x, int32_t y);
+Find the deepest widget at (x, y) within w's subtree. Respects WCLASS_NO_HIT_RECURSE so certain widget types can prevent children from being hit-tested.
+Utility Queries
+widgetCountVisibleChildren
+int32_t widgetCountVisibleChildren(const WidgetT *w);
+Count children whose visible flag is true.
+widgetFrameBorderWidth
+int32_t widgetFrameBorderWidth(const WidgetT *w);
+Return the effective border width for a container widget (used to inset child layout).
+widgetIsFocusable
+bool widgetIsFocusable(int32_t type);
+True if the widget class with this type ID has the WCLASS_FOCUSABLE flag.
+widgetIsHorizContainer
+bool widgetIsHorizContainer(int32_t type);
+True if the widget class lays out children horizontally (WCLASS_HORIZ_CONTAINER).
+multiClickDetect
+int32_t multiClickDetect(int32_t vx, int32_t vy);
+Track consecutive clicks at roughly the same position within sDblClickTicks. Returns the current click count (1 for single, 2 for double, etc.).
+Clipboard
+clipboardCopy
+void clipboardCopy(const char *text, int32_t len);
+Copy text to the process-wide clipboard buffer. Same underlying storage as dvxClipboardCopy.
+clipboardGet
+const char *clipboardGet(int32_t *outLen);
+Retrieve clipboard text.
+clipboardMaxLen
+int32_t clipboardMaxLen(void);
+Return the fixed capacity of the clipboard buffer in bytes.
+Scrollbar Helpers
+ScrollHitE
+Scrollbar hit-test result.
+Value Description + ----- ----------- + ScrollHitNoneE Click fell outside the scrollbar + ScrollHitArrowDecE Up/left arrow + ScrollHitArrowIncE Down/right arrow + ScrollHitPageDecE Trough above/before the thumb + ScrollHitPageIncE Trough below/after the thumb + ScrollHitThumbE The draggable thumb+
widgetScrollbarThumb
+void widgetScrollbarThumb(int32_t trackLen, int32_t totalSize, int32_t visibleSize, int32_t scrollPos, int32_t *thumbPos, int32_t *thumbSize);
+Compute thumb position and size for a scrollbar with the given geometry. Enforces SB_MIN_THUMB.
+widgetDrawScrollbarV / widgetDrawScrollbarVEx
+void widgetDrawScrollbarV(DisplayT *d, const BlitOpsT *ops, const ColorSchemeT *colors, int32_t sbX, int32_t sbY, int32_t sbH, int32_t totalSize, int32_t visibleSize, int32_t scrollPos);
+void widgetDrawScrollbarVEx(DisplayT *d, const BlitOpsT *ops, const ColorSchemeT *colors, int32_t sbX, int32_t sbY, int32_t sbH, int32_t totalSize, int32_t visibleSize, int32_t scrollPos, int32_t barW);
+Draw a vertical scrollbar inside a widget. The Ex variant lets the caller specify bar width for non-standard scrollbars (e.g. combo popups). Standard variant uses WGT_SB_W.
+widgetDrawScrollbarH / widgetDrawScrollbarHEx
+void widgetDrawScrollbarH(DisplayT *d, const BlitOpsT *ops, const ColorSchemeT *colors, int32_t sbX, int32_t sbY, int32_t sbW, int32_t totalSize, int32_t visibleSize, int32_t scrollPos);
+void widgetDrawScrollbarHEx(DisplayT *d, const BlitOpsT *ops, const ColorSchemeT *colors, int32_t sbX, int32_t sbY, int32_t sbW, int32_t totalSize, int32_t visibleSize, int32_t scrollPos, int32_t barW);
+Draw a horizontal scrollbar inside a widget. Standard variant uses WGT_SB_W.
+widgetScrollbarHitTest
+ScrollHitE widgetScrollbarHitTest(int32_t sbLen, int32_t relPos, int32_t totalSize, int32_t visibleSize, int32_t scrollPos);
+Classify a click position along a scrollbar into ScrollHitE. sbLen is the scrollbar length, relPos is the click position along the bar.
+Layout Functions
+widgetCalcMinSizeBox / widgetCalcMinSizeTree
+void widgetCalcMinSizeBox(WidgetT *w, const BitmapFontT *font);
+void widgetCalcMinSizeTree(WidgetT *w, const BitmapFontT *font);
+Generic box-container min-size calculation (bottom-up layout pass). widgetCalcMinSizeBox handles a single VBox/HBox; widgetCalcMinSizeTree recurses through the whole subtree.
+widgetLayoutBox / widgetLayoutChildren
+void widgetLayoutBox(WidgetT *w, const BitmapFontT *font);
+void widgetLayoutChildren(WidgetT *w, const BitmapFontT *font);
+Generic box-container layout (top-down pass). widgetLayoutBox lays out a single container; widgetLayoutChildren processes each child's layout handler.
+Event Dispatch
+widgetOnPaint / widgetOnMouse / widgetOnKey / etc.
+void widgetOnPaint(WindowT *win, RectT *dirtyArea);
+void widgetOnMouse(WindowT *win, int32_t x, int32_t y, int32_t buttons);
+void widgetOnKey(WindowT *win, int32_t key, int32_t mod);
+void widgetOnKeyUp(WindowT *win, int32_t scancode, int32_t mod);
+void widgetOnResize(WindowT *win, int32_t newW, int32_t newH);
+void widgetOnScroll(WindowT *win, ScrollbarOrientE orient, int32_t value);
+void widgetOnFocus(WindowT *win);
+void widgetOnBlur(WindowT *win);
+Window-level event handlers that dispatch to individual widgets in the tree. wgtInitWindow installs these as the window's onPaint/onMouse/onKey/etc. callbacks.
+widgetManageScrollbars
+void widgetManageScrollbars(WindowT *win, AppContextT *ctx);
+Add, remove, or resize window scrollbars based on the widget tree's current min-size vs. the window content area.
+Paint Helpers
+widgetPaintOne
+void widgetPaintOne(WidgetT *w, DisplayT *d, const BlitOpsT *ops, const BitmapFontT *font, const ColorSchemeT *colors);
+Paint a single widget (sets clip rect, calls the widget's PAINT handler). Does not recurse.
+widgetPaintOverlays
+void widgetPaintOverlays(WidgetT *root, DisplayT *d, const BlitOpsT *ops, const BitmapFontT *font, const ColorSchemeT *colors);
+Paint the overlay pass: dropdown popups and tooltips drawn on top of the main tree.
+Pressable Button Helpers
+Shared state machine for WCLASS_PRESS_RELEASE widgets (Button, ImageButton). The w->pressed flag tracks the visual state; these helpers fire the widget's onClick callback on release-within-bounds.
+widgetPressableOnMouse / widgetPressableOnKey / widgetPressableOnDragUpdate / widgetPressableOnDragEnd / widgetPressableOnAccelActivate
+void widgetPressableOnMouse(WidgetT *w, WidgetT *root, int32_t vx, int32_t vy);
+void widgetPressableOnKey(WidgetT *w, int32_t key, int32_t mod);
+void widgetPressableOnDragUpdate(WidgetT *w, WidgetT *root, int32_t x, int32_t y);
+void widgetPressableOnDragEnd(WidgetT *w, WidgetT *root, int32_t x, int32_t y);
+void widgetPressableOnAccelActivate(WidgetT *w, WidgetT *root);
+Register these directly as the widget class's handlers for WGT_METHOD_ON_MOUSE, WGT_METHOD_ON_KEY, WGT_METHOD_ON_DRAG_UPDATE, WGT_METHOD_ON_DRAG_END, and WGT_METHOD_ON_ACCEL_ACTIVATE.
+Generic Text Handlers
+For widgets whose data struct has a (const char *) as its first field and the WCLASS_HAS_TEXT flag set, these implement GET_TEXT / SET_TEXT directly.
+widgetTextGet / widgetTextSet
+const char *widgetTextGet(const WidgetT *w);
+void widgetTextSet(WidgetT *w, const char *text);
+Register these directly as the widget class's handlers for WGT_METHOD_GET_TEXT and WGT_METHOD_SET_TEXT. The text is strdup'd on set and freed automatically on destroy.
+Class Table
+widgetClassTable
+extern const WidgetClassT **widgetClassTable;
+stb_ds dynamic array. Each widget DXE appends its class pointer via wgtRegisterClass() during wgtRegister(). Indexed by the runtime type ID assigned at registration.
+platform/dvxPlat.h -- Platform Abstraction Layer
+All OS-specific and CPU-specific code is isolated behind this interface. Port DVX to a new platform by implementing a new dvxPlatformXxx.c against this header. Currently the only implementation is dvxPlatformDos.c for DJGPP/DPMI.
+Platform functions must be stateless (or manage their own internal state) and must not reference AppContextT or any layer above dvxTypes.h.
+Constants
+Define Value Description + ------ ----- ----------- + DVX_MAX_PATH 260 Maximum file path length + PLATFORM_SYSINFO_MAX 4096 Maximum size of formatted system info text + DVX_PATH_SEP "\\" Native directory separator on DOS+
Types
+PlatformKeyEventT
+Keyboard event with ASCII and scancode separated. Extended keys (arrows, F-keys) have ascii == 0 and a non-zero scancode.
+Field Description + ----- ----------- + ascii ASCII value, 0 for extended/function keys + scancode PC scancode (e.g. 0x48 = Up, 0x50 = Down)+
PlatformLogFnT
+typedef void (*PlatformLogFnT)(const char *fmt, ...);
+Log function signature used by the crash handler.
+PlatformSymOverrideT
+Name/function-pointer pair for registering symbol overrides with the DXE loader.
+Field Description + ----- ----------- + name Symbol name as seen by DXEs + func Function pointer to use instead of the default+
Lifecycle
+dvxLog
+void dvxLog(const char *fmt, ...);
+Append a formatted line to dvx.log. Implemented in dvx.exe and exported to every DXE via the loader.
+platformInit
+void platformInit(void);
+One-time platform initialization. On DOS this installs signal handlers for clean shutdown on Ctrl+C/Ctrl+Break.
+platformYield
+void platformYield(void);
+Cooperative CPU yield, used between frames when the event loop has nothing to do. On DOS this calls __dpmi_yield() to be friendly to multitaskers.
+Video
+platformVideoInit / platformVideoShutdown
+int32_t platformVideoInit(DisplayT *d, int32_t requestedW, int32_t requestedH, int32_t preferredBpp);
+void platformVideoShutdown(DisplayT *d);
+Low-level video mode setup and teardown. Called by videoInit / videoShutdown.
+platformVideoEnumModes
+void platformVideoEnumModes(void (*cb)(int32_t w, int32_t h, int32_t bpp, void *userData), void *userData);
+Enumerate LFB-capable graphics modes. Invokes cb once per available mode.
+platformVideoSetPalette
+void platformVideoSetPalette(const uint8_t *pal, int32_t firstEntry, int32_t count);
+Program the VGA/VESA DAC palette registers (8-bit mode only).
+platformVideoFreeBuffers
+void platformVideoFreeBuffers(DisplayT *d);
+Free the backbuffer and palette without restoring text mode. Used when switching between graphics modes live.
+Framebuffer Flush
+platformFlushRect
+void platformFlushRect(const DisplayT *d, const RectT *r);
+Copy a rectangle from the system RAM backbuffer to the LFB. The single critical path where PCI bus write speed matters. On DOS, each scanline uses rep movsd for aligned 32-bit writes.
+Span Operations
+platformSpanFill8/16/32
+void platformSpanFill8(uint8_t *dst, uint32_t color, int32_t count);
+void platformSpanFill16(uint8_t *dst, uint32_t color, int32_t count);
+void platformSpanFill32(uint8_t *dst, uint32_t color, int32_t count);
+Fill count pixels at dst with color. Three depth variants because the fill instruction differs by size. On DOS these use inline rep stosl / rep stosw / rep stosb asm.
+platformSpanCopy8/16/32
+void platformSpanCopy8(uint8_t *dst, const uint8_t *src, int32_t count);
+void platformSpanCopy16(uint8_t *dst, const uint8_t *src, int32_t count);
+void platformSpanCopy32(uint8_t *dst, const uint8_t *src, int32_t count);
+Copy count pixels from src to dst. On DOS these use rep movsd.
+Mouse Input
+platformMouseInit
+void platformMouseInit(int32_t screenW, int32_t screenH);
+Initialize the mouse driver and constrain movement to the screen bounds.
+platformMousePoll
+void platformMousePoll(int32_t *mx, int32_t *my, int32_t *buttons);
+Poll current mouse state. Buttons is a bitmask: bit 0 = left, bit 1 = right, bit 2 = middle.
+platformMouseWheelInit / platformMouseWheelPoll
+bool platformMouseWheelInit(void);
+int32_t platformMouseWheelPoll(void);
+Detect and activate the CuteMouse Wheel API. platformMouseWheelPoll returns the accumulated delta (positive = scroll down) since the last poll.
+platformMouseSetAccel / platformMouseSetMickeys
+void platformMouseSetAccel(int32_t threshold);
+void platformMouseSetMickeys(int32_t horizMickeys, int32_t vertMickeys);
+Set the double-speed threshold and mickey-to-pixel ratio. See dvxSetMouseConfig for a higher-level interface.
+platformMouseWarp
+void platformMouseWarp(int32_t x, int32_t y);
+Move the mouse cursor to an absolute screen position. Used to clamp the cursor to window edges during resize.
+Keyboard Input
+platformKeyboardGetModifiers
+int32_t platformKeyboardGetModifiers(void);
+Return the current modifier key state in BIOS shift-state format.
+platformKeyboardRead
+bool platformKeyboardRead(PlatformKeyEventT *evt);
+Non-blocking read of the next key from the keyboard buffer. Returns true if a key was available.
+platformKeyUpInit / platformKeyUpShutdown / platformKeyUpRead
+void platformKeyUpInit(void);
+void platformKeyUpShutdown(void);
+bool platformKeyUpRead(PlatformKeyEventT *evt);
+Key-up event detection. Install/uninstall the INT 9 hook around process lifetime. platformKeyUpRead returns true if a key release was detected since the last call.
+platformAltScanToChar
+char platformAltScanToChar(int32_t scancode);
+Translate an Alt+key scancode to its corresponding ASCII character. Returns 0 for non-printable scancodes.
+System Information
+platformGetSystemInfo
+const char *platformGetSystemInfo(const DisplayT *display);
+Return a pre-formatted text string with hardware/OS information (CPU, clock, memory, video, mouse, disks). Valid for the lifetime of the process.
+platformGetMemoryInfo
+bool platformGetMemoryInfo(uint32_t *totalKb, uint32_t *freeKb);
+Query total and free physical memory.
+File System
+platformValidateFilename
+const char *platformValidateFilename(const char *name);
+Validate a filename against platform-specific rules (8.3 on DOS). Returns NULL if valid, or a human-readable error string.
+platformMkdirRecursive
+int32_t platformMkdirRecursive(const char *path);
+Create a directory and all parent directories (like mkdir -p). Existing directories are not an error.
+platformChdir
+int32_t platformChdir(const char *path);
+Change the working directory, including drive letter on DOS (calls setdisk() first when the path starts with "X:").
+platformPathDirEnd
+char *platformPathDirEnd(const char *path);
+Return a pointer to the last directory separator in path, or NULL. On DOS accepts both "/" and "\\".
+platformPathBaseName
+const char *platformPathBaseName(const char *path);
+Return a pointer to the leaf (basename) portion of path.
+platformReadFile
+char *platformReadFile(const char *path, int32_t *outLen);
+Slurp a whole file into a freshly malloc'd, NUL-terminated buffer. Caller frees. Binary-safe: the NUL is past the end of the reported length.
+platformGlobMatch
+bool platformGlobMatch(const char *pattern, const char *name);
+Simple glob pattern match. Case-insensitive. Supports * (zero or more chars) and ? (single char).
+platformLineEnding / platformStripLineEndings
+const char *platformLineEnding(void);
+int32_t platformStripLineEndings(char *buf, int32_t len);
+Return the native line ending string, or strip line-ending characters from a buffer in place.
+String Helpers
+dvxSkipWs
+const char *dvxSkipWs(const char *s);
+Advance past leading spaces and tabs. Returns s unchanged if NULL or already non-whitespace.
+dvxTrimRight
+int32_t dvxTrimRight(char *buf);
+Strip trailing spaces, tabs, carriage returns, and newlines from buf in place. Returns the new length.
+DXE Module Support
+platformRegisterDxeExports
+void platformRegisterDxeExports(void);
+Register platform and C runtime symbols with the dynamic module loader so DXE modules can resolve them at load time.
+platformRegisterSymOverrides
+void platformRegisterSymOverrides(const PlatformSymOverrideT *entries);
+Register function pointer overrides for subsequently loaded modules. entries is terminated by {NULL, NULL}.
+Crash Recovery
+platformInstallCrashHandler
+void platformInstallCrashHandler(jmp_buf *recoveryBuf, volatile int *crashSignal, PlatformLogFnT logFn);
+Install signal handlers for SIGSEGV, SIGFPE, SIGILL. On crash, logs platform-specific diagnostics via logFn, stores the signal in *crashSignal, then longjmps to recoveryBuf.
+platformLogCrashDetail
+void platformLogCrashDetail(int sig, PlatformLogFnT logFn);
+Log platform-specific crash diagnostics. Called internally from the crash handler and exposed for manual invocation.
+VGA Splash Screen
+platformSplashInit / platformSplashShutdown
+void platformSplashInit(void);
+void platformSplashShutdown(void);
+Enter/leave VGA mode 13h (320x200x256) used for the boot splash.
+platformSplashLoadRaw
+bool platformSplashLoadRaw(const char *path);
+Load and display a raw splash file (768-byte palette + 64000-byte pixel data).
+platformSplashFillRect
+void platformSplashFillRect(int32_t x, int32_t y, int32_t w, int32_t h, uint8_t color);
+Fill a rectangle on the mode 13h screen with a palette index. Used to draw the progress bar during module loading.
libtasks -- Cooperative Task Switching
Credit-based cooperative (non-preemptive) multitasking library for DOS protected mode (DJGPP/DPMI). Each task receives (priority + 1) credits per scheduling round. Tasks run round-robin, consuming one credit per turn. When all credits are exhausted, every ready task is refilled. Higher-priority tasks run proportionally more often but never starve lower ones.
-Header: tasks/taskswitch.h
+Header: libtasks/taskSwch.h
+Loaded as: bin/libs/libtasks.lib
Why Cooperative
DOS is single-threaded with no kernel scheduler. DPMI provides no preemption primitives. The DVX GUI event model is inherently single-threaded: one compositor, one input queue, one window stack. Cooperative switching lets each task yield at safe points, avoiding synchronization primitives entirely.
+Scheduling Semantics
+Task storage is a stb_ds dynamic array. Terminated slots are recycled by tsCreate so the array does not grow unboundedly. The scheduler performs a linear scan for the next Ready task whose credit count is positive; when no task has credits left, every Ready task is refilled with (priority + 1) credits and the scan restarts.
+Priority Credits per round Approximate share + -------- ----------------- ----------------- + TS_PRIORITY_LOW 1 ~4% (1 of 25 possible credits) + TS_PRIORITY_NORMAL 6 ~22% + TS_PRIORITY_HIGH 11 ~41%+
Actual share depends on the mix of priorities currently running. What the algorithm guarantees is that no ready task ever goes unscheduled -- even a priority-0 task always earns at least one turn per round.
+Stack Allocation
+Task 0 uses the caller's stack (no separate allocation). Every other task gets a heap-allocated stack of the size passed to tsCreate (or TS_DEFAULT_STACK_SIZE if 0 is passed). Stacks are freed at task termination, either via tsExit or tsKill.
Error Codes
Constant Value Description
-------- ----- -----------
@@ -2999,7 +4218,7 @@ img { max-width: 100%; }
tsInit
int32_t tsInit(void);
Initialize the task system. The calling context becomes task 0 (the main task). Task 0 is special: it cannot be killed or paused, and tsRecoverToMain() always returns control here. No separate stack is allocated for task 0; it uses the process stack directly.
-Returns: TS_OK on success, TS_ERR_INIT if already initialized.
+Returns: TS_OK on success, TS_ERR_PARAM if already initialized.
tsShutdown
void tsShutdown(void);
Shut down the task system and free all task stacks and internal storage. Safe to call even if tsInit() was never called.
@@ -3013,7 +4232,7 @@ img { max-width: 100%; }
arg Opaque argument passed to entry
stackSize Stack size in bytes (pass 0 for TS_DEFAULT_STACK_SIZE)
priority Scheduling priority (0..10; use TS_PRIORITY_* constants)
-Returns: Task ID (>= 0) on success, or a negative error code (TS_ERR_INIT, TS_ERR_PARAM, TS_ERR_NOMEM).
+Returns: Task ID (>= 0) on success, or a negative error code (TS_ERR_PARAM if not initialized or entry is NULL, TS_ERR_NOMEM if stack allocation failed).
tsYield
void tsYield(void);
Yield CPU to the next eligible ready task using credit-based round-robin. This is the sole mechanism for task switching. Every task must call this (or a GUI function that calls it) periodically, or it will monopolize the CPU.
@@ -3023,7 +4242,7 @@ img { max-width: 100%; }Parameter Description --------- ----------- taskId ID of the task to pause-
Returns: TS_OK on success, TS_ERR_PARAM on invalid ID, TS_ERR_STATE if the task is not in a pausable state.
+Returns: TS_OK on success, TS_ERR_PARAM on invalid ID, or TS_ERR_STATE if the task is the main task or not in a pausable state (not Running or Ready).
tsResume
int32_t tsResume(uint32_t taskId);
Resume a paused task. Credits are refilled so the task gets a fair share of CPU time immediately rather than waiting for the next scheduling round.
@@ -3038,7 +4257,7 @@ img { max-width: 100%; } --------- ----------- taskId ID of the task to modify priority New priority level (0..10) -Returns: TS_OK on success, TS_ERR_PARAM on invalid ID or out-of-range priority.
+Returns: TS_OK on success, TS_ERR_PARAM on invalid ID, or TS_ERR_STATE if the task is terminated.
tsGetPriority
int32_t tsGetPriority(uint32_t taskId);
Get a task's current scheduling priority.
@@ -3073,7 +4292,7 @@ img { max-width: 100%; }Parameter Description --------- ----------- taskId ID of the task to terminate-
Returns: TS_OK on success, TS_ERR_PARAM on invalid ID or illegal target (main task, self).
+Returns: TS_OK on success, TS_ERR_PARAM on invalid ID, or TS_ERR_STATE on illegal target (main task, self, or already terminated).
tsRecoverToMain
void tsRecoverToMain(void);
Crash recovery: force the scheduler back to the main task (ID 0). Call after longjmp from a signal handler that fired in a non-main task. The crashed task is NOT cleaned up by this call; call tsKill() afterward to free its resources. This exists because longjmp unwinds the crashed task's stack but the scheduler state still points to it.
@@ -3085,7 +4304,8 @@ img { max-width: 100%; }DVX Shell Library
The DVX shell library manages the lifecycle of DXE applications: loading, launching, tracking, and reaping. It provides the bridge between the DVX GUI compositor and dynamically loaded DXE3 application modules.
-Header: shell/shellApp.h
+Header: dvxshell/shellApp.h
+Loaded as: bin/libs/dvxshell.lib
App Model
The shell supports two kinds of DXE apps:
-
@@ -3100,6 +4320,21 @@ img { max-width: 100%; }
_appDescriptor AppDescriptorT Yes
_appMain int32_t (*)(DxeAppContextT *) Yes
_appShutdown void (*)(void) No
+
- hasMainLoop = false (callback-only). The shell calls appMain directly on task 0 at dlopen time. The function creates windows, registers event callbacks, and returns. After that the app has no executing thread of its own -- it exists purely through GUI callbacks dispatched by dvxUpdate. The shell reaps the app automatically when its last window closes. Best for modal tools, dialogs, and event-driven utilities. +
- 16x16 BMP for toolbar entries and list rows +
The shell resolves appDescriptor at dlopen time; if missing, the load fails with an error dialog. appMain is called immediately for callback-only apps or from the new task for main-loop apps. appShutdown, if present, is called during graceful reap (but not during force kill from crashed apps).
+Callback-Only vs Main-Loop Apps
+The app descriptor's hasMainLoop flag selects between two very different lifecycles:
+-
+
hasMainLoop = true (main-loop). The shell creates a dedicated cooperative task (via tsCreate) with the descriptor's stackSize (or TS_DEFAULT_STACK_SIZE) and priority. appMain runs in that task and can do its own work loop, calling tsYield or any GUI function that yields. The app terminates when appMain returns (the wrapper sets AppStateTerminatingE) or when forced via shellForceKillApp. Best for terminal emulators, games, and any app with continuous background work.
+Both app types use the same export interface; only the descriptor's flags differ. Apps cannot switch modes at runtime.
+Icon Conventions
+Shell-level UI (Program Manager, Task Manager) displays app icons at 16x16 and 32x32. Icons are not handled by the shell itself; each app embeds its own icons via the DVX resource system (DVX_RES_ICON):
+-
+
32x32 BMP for desktop shortcuts and Program Manager tiles
+The Program Manager reads the app's 32x32 icon resource when building shortcut tiles. Apps without an icon resource fall back to a default shell-provided bitmap.
State Machine
App slots progress through four states:
Free -> Loaded -> Running -> Terminating -> Free
@@ -3130,18 +4365,20 @@ img { max-width: 100%; }
stackSize int32_t SHELL_STACK_DEFAULT or explicit byte count for the task stack.
priority int32_t TS_PRIORITY_* value or custom priority for the task.
DxeAppContextT
-Passed as the sole argument to appMain(). Gives the app access to the shell's GUI context and its own identity.
-Field Type Description - ----- ---- ----------- - shellCtx AppContextT * The shell's GUI context (for creating windows, drawing, etc.). - appId int32_t This app's unique ID (slot index, 1-based). - appPath[DVX_MAX_PATH] char[] Full path to the .app DXE file. - appDir[DVX_MAX_PATH] char[] Directory containing the .app file (for loading resources). - configDir[DVX_MAX_PATH] char[] Writable config directory (e.g. CONFIG/APPS/KPUNCH/DVXBASIC/). - args[1024] char[] Launch arguments (empty string if none). - helpFile[DVX_MAX_PATH] char[] Help file path (for F1 context help). - helpTopic[128] char[] Current help topic ID (updated by the app at runtime).-
The appDir field is derived from the .app file path at load time so apps can find their own resources via relative paths. This is necessary because the working directory is shared by all apps in DOS.
+Passed as the sole argument to appMain(). Gives the app access to the shell's GUI context and its own identity. Heap-allocated by shellLoadApp so its address is stable across reallocations of the internal app slot table (apps may safely cache the pointer in their static globals).
+Field Type Description + ----- ---- ----------- + shellCtx AppContextT * The shell's GUI context (for creating windows, drawing, etc.). + appId int32_t This app's unique ID (slot index, 1-based). + appPath[DVX_MAX_PATH] char[] Full path to the .app DXE file. + appDir[DVX_MAX_PATH] char[] Directory containing the .app file (for loading resources). + configDir[DVX_MAX_PATH] char[] Writable config directory (e.g. CONFIG/APPS/KPUNCH/DVXBASIC/). + args[1024] char[] Launch arguments (empty string if none). + helpFile[DVX_MAX_PATH] char[] Help file path (for F1 context help). + helpTopic[128] char[] Current help topic ID (updated by the app at runtime). + onHelpQuery void (*)(void *ctx) Optional callback the shell fires on F1 so the app can refresh helpTopic from context. + helpQueryCtx void * Opaque context pointer passed to onHelpQuery.+
The appDir field is derived from the .app file path at load time so apps can find their own resources via relative paths. This is necessary because the working directory is shared by all apps in DOS. The config directory is mirrored from the app path: an app at APPS/KPUNCH/DVXBASIC/dvxbasic.app gets CONFIG/APPS/KPUNCH/DVXBASIC/.
AppStateE
Value Description
----- -----------
@@ -3187,8 +4424,8 @@ img { max-width: 100%; }
Gracefully shut down a single app. Calls the app's shutdownFn (if present), destroys all windows belonging to the app, kills its task (if any), closes the DXE handle, and frees the context. The slot returns to AppStateFreeE.
shellForceKillApp
void shellForceKillApp(AppContextT *ctx, ShellAppT *app);
-Forcibly kill an app without calling its shutdown hook. Used by the Task Manager "End Task" or when an app has crashed and cannot be trusted to run cleanup code.
-Cleanup order: windows first (removes from compositor), then task (frees stack), then DXE handle (unmaps code). Closing the DXE before destroying windows would cause callbacks into unmapped code.
+Forcibly kill an app. Used by the Task Manager "End Task" or as part of crash recovery. Calls the app's shutdownFn (if present) so it can unregister callbacks before its DXE is unmapped, then destroys all of the app's windows, kills its task (for main-loop apps), and finally closes the DXE handle.
+Cleanup order: shutdownFn first (so the app can unregister callbacks while still mapped), then windows (removes from compositor), then task (frees stack), then DXE handle (unmaps code). Closing the DXE before destroying windows would cause callbacks into unmapped code.
shellTerminateAllApps
void shellTerminateAllApps(AppContextT *ctx);
Force-kill all running apps. Called during shell shutdown. Iterates all slots and calls shellForceKillApp() on each active app.
@@ -3222,7 +4459,14 @@ shellConfigPath(ctx, "settings.ini", path, sizeof(path));
Desktop Callbacks
-The shell provides a notification mechanism for app state changes (load, reap, crash). Desktop managers register a callback to refresh their display when apps come and go.
+The shell wires several AppContextT event hooks (onCtrlEsc, onF1, onTitleChange, idleCallback) during startup and exposes them to other DXEs via function-pointer extern and registration API. Desktop managers register a callback to refresh their display when apps come and go. The Task Manager DXE registers its Ctrl+Esc handler via the shellCtrlEscFn extern pointer (see Task Manager documentation).
+Shell Event Hooks
+AppContextT field Handler Purpose + ----------------- ------- ------- + idleCallback idleYield Yields to cooperative tasks when dvxUpdate has no input events and no dirty rects. + onCtrlEsc ctrlEscHandler Invokes shellCtrlEscFn if the Task Manager DXE is loaded. + onF1 f1HelpHandler Launches the help viewer, optionally passing the focused app's helpFile and helpTopic. + onTitleChange titleChangeHandler Runs shellDesktopUpdate so Program Manager window lists refresh.
shellRegisterDesktopUpdate
void shellRegisterDesktopUpdate(void (*updateFn)(void));
Register a callback for app state change notifications. Multiple callbacks are supported. Apps typically call this during appMain() to receive notifications.
@@ -3238,7 +4482,7 @@ shellConfigPath(ctx, "settings.ini", path, sizeof(path));System Information
-Header: shell/shellInfo.h
+Header: dvxshell/shellInf.h
Thin wrapper around the platform layer's hardware detection. Gathers system information at startup, logs it, and caches the result for display in dialogs.
shellInfoInit
void shellInfoInit(AppContextT *ctx);
@@ -3251,8 +4495,28 @@ shellConfigPath(ctx, "settings.ini", path, sizeof(path));
dvxSql -- SQL Database Interface
High-level wrapper around SQLite3 for DVX applications. Manages database connections and result set cursors via integer handles so BASIC code never touches raw pointers. All handles are 1-based; 0 indicates an error or invalid handle.
Header: sql/dvxSql.h
+SQLite Wrapping
+dvxSql wraps the bundled SQLite3 amalgamation (sql/thirdparty/sqlite/examples/sqlite3.h). It manages two internal dynamic tables keyed by 1-based handles:
+-
+
- Database table: each slot holds a sqlite3 * plus a per-database error string and affected-row count. +
Cursor table: each slot holds a sqlite3_stmt *, the owning database handle, and EOF tracking.
+Growing either table doubles its capacity. Closed slots are recycled by subsequent dvxSqlOpen or dvxSqlQuery calls, keeping handle values stable for the caller.
Handle Model
-Database and cursor handles are int32_t values. A successful open or query returns a handle greater than zero. Handle 0 is reserved as the invalid/error sentinel. Closing a database automatically finalizes all cursors that belong to it.
+Database and cursor handles are int32_t values. A successful open or query returns a handle greater than zero. Handle 0 is reserved as the invalid/error sentinel. Closing a database automatically finalizes all cursors that belong to it, so callers do not need to track cursor lifetimes per-database.
+Connection Lifecycle
+-
+
- dvxSqlOpen allocates a handle and calls sqlite3_open. The database file is created if it does not exist. +
- Use dvxSqlExec for DDL and non-query DML. On success, dvxSqlAffectedRows returns the row count for the last call on this handle. +
- Use dvxSqlQuery to obtain a cursor over a SELECT. Iterate with dvxSqlNext and read columns with dvxSqlFieldText, dvxSqlFieldInt, dvxSqlFieldDbl, or dvxSqlFieldByName. +
Call dvxSqlFreeResult when the cursor is no longer needed. Call dvxSqlClose when the database is no longer needed; any cursors still open on that database are finalized automatically.
+Common Patterns
+-
+
- Parameterize user input with dvxSqlEscape before interpolating into SQL strings. +
- Check dvxSqlError(db) for the last error on a handle; its message is stable until the next operation on the same database. +
dvxSqlFieldByName matches column names case-insensitively, suitable for most real-world schemas.
@@ -3432,6 +4696,16 @@ dvxSqlExec(db, sql);Text Help Library
Shared text editing infrastructure library for DVX widget DXEs. Provides cursor blink management, cross-widget selection clearing, word boundary logic, and a complete single-line text editing engine. Used by TextInput, Spinner, ComboBox, AnsiTerm, and other widgets that need text editing behavior.
Header: texthelp/textHelp.h
+Loaded as: bin/libs/texthelp.lib
+How Widgets Use This Library
+Widget DXEs that implement text editing delegate to textHelp for the four high-cost behaviors:
+-
+
- Cursor blink. The library tracks a 250 ms blink timer in a static global and the focused widget reads sCursorBlinkOn (exposed via libdvx) when repainting. +
- Selection clearing. When a widget gains focus it calls clearOtherSelections(self) so only one widget ever has an active text selection. +
- Word boundaries. isWordChar, wordStart/wordEnd, and wordBoundaryLeft/wordBoundaryRight implement the logic for double-click word selection and Ctrl+Left/Right navigation in a uniform way. +
Single-line editing engine. widgetTextEditOnKey, widgetTextEditMouseClick, widgetTextEditDragUpdateLine, and widgetTextEditPaintLine form a pointer-parameterized implementation of keyboard, mouse, drag, and paint behaviors. Widgets (TextInput, Spinner, ComboBox, AnsiTerm) hand the library pointers to their internal buffer, cursor, scroll offset, and selection state.
+The engine is intentionally pointer-parameterized rather than struct-based so widgets can reuse it without adopting a shared state struct. Each widget owns its own buffer and state and passes pointers in on every call.
Constants
Constant Value Description -------- ----- ----------- @@ -3481,6 +4755,44 @@ dvxSqlExec(db, sql);pos int32_t Starting position (character index).
Returns the index of the first character of the word containing pos.
wordBoundaryLeft
+Finds the left word boundary for Ctrl+Left navigation. Skips non-word characters first, then skips word characters, leaving the cursor at the start of the previous word.
+int32_t wordBoundaryLeft(const char *buf, int32_t pos);
+Parameter Type Description + --------- ---- ----------- + buf const char * The text buffer to scan. + pos int32_t Starting position (character index).+
Returns the index of the previous word boundary. Returns 0 if pos is already at or before the start of the buffer.
+wordBoundaryRight
+Finds the right word boundary for Ctrl+Right navigation. Skips word characters first, then skips non-word characters, leaving the cursor at the start of the next word.
+int32_t wordBoundaryRight(const char *buf, int32_t len, int32_t pos);
+Parameter Type Description + --------- ---- ----------- + buf const char * The text buffer to scan. + len int32_t Length of the text buffer. + pos int32_t Starting position (character index).+
Returns the index of the next word boundary. Returns len if pos is already at or past the end of the buffer.
+textEditSaveUndo
+Capture a snapshot of the current buffer contents and cursor position into an undo buffer. Called by widgetTextEditOnKey before every destructive operation (insert, delete, paste, cut). Truncates to bufSize - 1 characters so the null terminator always fits.
+void textEditSaveUndo(char *buf, int32_t len,
+ int32_t cursor, char *undoBuf,
+ int32_t *pUndoLen, int32_t *pUndoCursor,
+ int32_t bufSize);
+Parameter Type Description + --------- ---- ----------- + buf char * Source buffer to snapshot. + len int32_t Current length of source contents. + cursor int32_t Current cursor position to save. + undoBuf char * Destination undo buffer. If NULL the call is a no-op. + pUndoLen int32_t * [out] Length of saved undo contents. + pUndoCursor int32_t * [out] Saved cursor position. + bufSize int32_t Size of the destination undo buffer including the null terminator.+
widgetTextEditDragUpdateLine
Called during mouse drag to extend the selection in a single-line text field. Converts a viewport-relative pixel x coordinate to a character position and updates the cursor and selection end accordingly. Auto-scrolls the text when the mouse moves past the left or right visible edge.
@@ -3613,13 +4925,15 @@ dvxSqlExec(db, sql);List Helper Library
-Shared helper routines for dropdown and list-based widget DXEs (ListBox, Dropdown, ComboBox, ListView, TreeView). Provides dropdown arrow rendering, item measurement, keyboard navigation, popup geometry calculation, and popup list painting.
+Shared helper routines for dropdown and list-based widget DXEs (ListBox, Dropdown, ComboBox, ListView). Provides dropdown arrow rendering, item measurement, keyboard navigation, popup geometry calculation, popup list painting, type-ahead search, and popup scrollbar hit testing.
Header: listhelp/listHelp.h
+Loaded as: bin/libs/listhelp.lib
Constants
-Constant Value Description - -------- ----- ----------- - DROPDOWN_BTN_WIDTH 16 Width of the dropdown arrow button in pixels. - DROPDOWN_MAX_VISIBLE 8 Maximum number of items visible in a popup list.+
Constant Value Description + -------- ----- ----------- + DROPDOWN_BTN_WIDTH 16 Width of the dropdown arrow button in pixels. + DROPDOWN_MAX_VISIBLE 8 Maximum number of items visible in a popup list before scrolling. + POPUP_SCROLLBAR_W SCROLLBAR_WIDTH Popup vertical scrollbar width (mirrors the core window-manager scrollbar width).
widgetDrawDropdownArrow
Draw the triangular dropdown arrow glyph centered at a given position.
void widgetDrawDropdownArrow(DisplayT *d, const BlitOpsT *ops,
@@ -3649,7 +4963,7 @@ dvxSqlExec(db, sql);
current Currently selected index.
count Total number of items in the list.
pageSize Number of visible items (used for PgUp/PgDn step size).
-Returns the new index, clamped to [0, count-1].
+Returns the new index, clamped to [0, count-1]. Returns -1 for unrecognized keys so callers can detect whether the key was consumed.
widgetDropdownPopupRect
Calculate the screen rectangle for a dropdown popup list, positioning it below the owning widget and clamping to screen bounds.
void widgetDropdownPopupRect(WidgetT *w, const BitmapFontT *font,
@@ -3667,7 +4981,7 @@ dvxSqlExec(db, sql);
popH Output: popup height in pixels.
The popup is sized to show up to DROPDOWN_MAX_VISIBLE items.
widgetPaintPopupList
-Render a popup item list with highlight, scrolling, and beveled border.
+Render a popup item list with highlight, scrolling, and beveled border. When itemCount exceeds DROPDOWN_MAX_VISIBLE, draws a vertical scrollbar on the right edge sized according to scrollPos.
void widgetPaintPopupList(DisplayT *d, const BlitOpsT *ops,
const BitmapFontT *font, const ColorSchemeT *colors,
int32_t popX, int32_t popY, int32_t popW, int32_t popH,
@@ -3687,21 +5001,64 @@ dvxSqlExec(db, sql);
itemCount Total number of items.
hoverIdx Index of the highlighted (hovered/selected) item, or -1 for none.
scrollPos Index of the first visible item (scroll offset).
+widgetTypeAheadSearch
+Case-insensitive type-ahead search. Scans items forward from currentIdx + 1, wrapping around, for the next item whose first character matches ch. Used by list and dropdown widgets to jump to an item based on a single keystroke.
+int32_t widgetTypeAheadSearch(char ch, const char **items,
+ int32_t itemCount, int32_t currentIdx);
+Parameter Description + --------- ----------- + ch Character to match (case-insensitive). + items Array of null-terminated item strings. + itemCount Number of items in the array. + currentIdx Currently selected index (search starts at currentIdx + 1 and wraps).+
Returns the index of the next matching item, or -1 if no match is found or itemCount is not positive.
+widgetPopupScrollbarClick
+Hit-test a popup scrollbar click. Tests whether the (x, y) coordinate falls on the popup's vertical scrollbar track; if so, updates scrollPos for up/down arrow clicks or page-up/page-down clicks in the trough. No-op on the thumb itself (callers handle drag separately).
+bool widgetPopupScrollbarClick(int32_t x, int32_t y,
+ int32_t popX, int32_t popY, int32_t popW, int32_t popH,
+ int32_t itemCount, int32_t visibleItems,
+ int32_t *scrollPos);
+Parameter Description + --------- ----------- + x Click X in the popup's coordinate space. + y Click Y in the popup's coordinate space. + popX Popup X origin. + popY Popup Y origin. + popW Popup width. + popH Popup height. + itemCount Total number of items. + visibleItems Number of visible rows in the popup. + scrollPos [in/out] Current scroll offset; updated in place when the click hits the scrollbar.+
Returns true if the click landed on the scrollbar (even if scrollPos was not changed, for example clicking the thumb), false if the click was in the item list area. When itemCount is less than or equal to DROPDOWN_MAX_VISIBLE, always returns false (there is no scrollbar).
Task Manager
-System-level task manager for DVX. Displays running applications and per-app memory usage. Always accessible via Ctrl+Esc regardless of which application is focused. Persists independently of the desktop app (Program Manager).
+System-level task manager for DVX. Displays all running applications with a six-column ListView (Name, Title, File, Type, Memory, Status) and exposes Switch To, End Task, and Run... operations. Always accessible via Ctrl+Esc regardless of which application is focused. Persists independently of the desktop app (Program Manager).
Header: taskmgr/shellTaskMgr.h
Loaded as: bin/libs/taskmgr.lib
+Integration
+The task manager is a shell-level library, not a regular DXE app. At DXE load time a GCC constructor function registers the Task Manager with the shell by setting the shellCtrlEscFn function pointer (declared extern in dvxshell/shellApp.h). The shell invokes shellCtrlEscFn on every Ctrl+Esc keystroke; if taskmgr.lib is not loaded the pointer stays NULL and Ctrl+Esc does nothing.
+The Task Manager owns its window on behalf of the shell itself (appId = 0), not any running app, which is why it survives when the desktop app terminates. It registers shellTaskMgrRefresh with shellRegisterDesktopUpdate so the list refreshes live as apps load, reap, or crash.
+Integration with libtasks
+The Task Manager reads from the shell's app slot table (shellGetApp, shellAppSlotCount, shellRunningAppCount) rather than from the libtasks scheduler directly. Each ShellAppT slot carries its cooperative task ID when hasMainLoop is true; End Task calls shellForceKillApp, which in turn calls tsKill on that task ID (for main-loop apps) after destroying the app's windows.
+Features
+-
+
- Six-column ListView showing Name, Title, File, Type (Task or Callback), Memory (from dvxMemGetAppUsage), and Status for every running app. +
- Switch To button (Alt+S): raises and focuses the selected app's topmost window, restoring it if minimized. Also triggered by double-clicking a row. +
- End Task button (Alt+E): force-kills the selected app via shellForceKillApp. +
- Run... button (Alt+R): opens a file dialog to browse for and launch a .app file. +
- Status bar showing running app count plus total and used system memory. +
Single-instance: reopening the Task Manager while it is already visible raises and focuses the existing window rather than creating a new one.
shellTaskMgrOpen
Open the Task Manager window, or raise it to the front if already open.
void shellTaskMgrOpen(AppContextT *ctx);
Parameter Description --------- ----------- - ctx Application context (from dvxInit). Required for window creation and event registration.-
Called by the shell's global Ctrl+Esc handler.
+ ctx Application context (from dvxInit). Required for window creation, stack manipulation, and registering the desktop-update callback. +Called by the shell's global Ctrl+Esc handler via the shellCtrlEscFn hook.
shellTaskMgrRefresh
-Refresh the task list display. Call this when applications are launched or terminated so the Task Manager reflects the current state.
+Rebuild the task list display from the current shell app slot table and refresh the status bar. Registered with shellRegisterDesktopUpdate at open time so it is invoked whenever the shell detects app state changes.
void shellTaskMgrRefresh(void);
Takes no parameters. Safe to call even if the Task Manager window is not currently open (the call is a no-op in that case).
secLink -- Convenience wrapper: channel multiplexing, per-packet encryption
Loaded as: bin/libs/kpunch/serial/serial.lib
+Layered Architecture
++--------------------------------------------------+
+| Application |
+| |
+| secLinkSend() -- send on channel, opt. encrypt |
+| secLinkPoll() -- receive + dispatch |
++--------------------------------------------------+
+| secLink (channel multiplex, TX/RX ciphers) |
++--------------------------------------------------+
+| packet (HDLC framing, CRC-16, Go-Back-N ARQ) |
++--------------------------------------------------+
+| security -- DH key exchange, XTEA-CTR, DRBG |
+| (used by secLink during handshake) |
++--------------------------------------------------+
+| rs232 (ISR-driven UART, 2048-byte rings) |
++--------------------------------------------------+
+| UART hardware (8250 / 16450 / 16550 / 16550A) |
++--------------------------------------------------+
+The security layer is invoked by secLink during the Diffie-Hellman handshake and for per-packet cipher operations. It has no runtime coupling to rs232 or packet, so it can be used standalone for cryptographic operations independent of the serial stack.
+RS-232 UART Driver
ISR-driven serial port driver supporting up to 4 simultaneous COM ports. A shared ISR drains UART FIFOs into per-port ring buffers (2048 bytes, power-of-2 for fast index wrapping). Flow control (XON/XOFF, RTS/CTS, DTR/DSR) operates within the ISR using watermark thresholds. All ISR data structures are DPMI-locked to prevent page faults.
Header: rs232/rs232.h
Port Constants
-Constant Value Description - -------- ----- ----------- - RS232_COM1 0 First serial port. - RS232_COM2 1 Second serial port. - RS232_COM3 2 Third serial port. - RS232_COM4 3 Fourth serial port.+
Constant Value Description + -------- ----- ----------- + RS232_COM1 0 First serial port. + RS232_COM2 1 Second serial port. + RS232_COM3 2 Third serial port. + RS232_COM4 3 Fourth serial port. + RS232_NUM_PORTS 4 Total number of supported COM ports.
Handshake Modes
Constant Value Description -------- ----- ----------- @@ -3793,28 +5171,29 @@ dvxSqlExec(db, sql);len Maximum bytes to read.
Returns the number of bytes actually read (may be less than len).
rs232Write
-Blocking polled write directly to UART transmit holding register. Bypasses the TX ring buffer. Use for small, immediate writes.
+Blocking polled write directly to UART transmit holding register. Bypasses the TX ring buffer. Polls LSR_TX_HOLD_EMPTY before writing each byte. Use for small, immediate writes where order matters (the packet layer uses this for frame transmission).
int rs232Write(int com, const char *data, int len);
-Returns RS232_SUCCESS or a negative error code.
+Returns the number of bytes actually written (may be less than len if software flow control is asserted), or a negative error code (RS232_ERR_INVALID_PORT, RS232_ERR_NOT_OPEN, RS232_ERR_NULL_PTR).
rs232WriteBuf
Non-blocking write to the transmit ring buffer. The ISR drains buffered data to the UART asynchronously.
int rs232WriteBuf(int com, const char *data, int len);
Returns the number of bytes actually queued (may be less than len if the buffer is full).
rs232Set
-Change all line parameters on an open port.
+Change all line parameters on an open port. Internally calls rs232SetBps, rs232SetData, rs232SetParity, rs232SetStop, and rs232SetHandshake in sequence. Returns RS232_SUCCESS on success or the first negative error code encountered.
int rs232Set(int com, int32_t bps, int dataBits,
char parity, int stopBits, int handshake);
Configuration Getters
Function Returns
-------- -------
rs232GetBase(com) I/O base address.
- rs232GetBps(com) Current baud rate.
- rs232GetData(com) Data bits setting.
- rs232GetParity(com) Parity character ('N', 'O', 'E', 'M', 'S').
- rs232GetStop(com) Stop bits setting.
- rs232GetHandshake(com) Handshake mode.
+ rs232GetBps(com) Current baud rate (int32_t).
+ rs232GetData(com) Data bits setting (5-8).
+ rs232GetParity(com) Parity character: 'n', 'o', 'e', 'm', or 's' (lowercase).
+ rs232GetStop(com) Stop bits setting (1 or 2).
+ rs232GetHandshake(com) Handshake mode (RS232_HANDSHAKE_*).
rs232GetIrq(com) IRQ number.
rs232GetUartType(com) Detected UART type (RS232_UART_*).
+rs232GetParity returns a lowercase character on success. Callers comparing against uppercase constants must use either both cases or tolower().
Status Getters
Function Returns -------- ------- @@ -3865,10 +5244,10 @@ dvxSqlExec(db, sql);PKT_ERR_NOT_OPEN -2 Connection is not open. PKT_ERR_WOULD_BLOCK -4 Operation would block. PKT_ERR_OVERFLOW -5 Buffer overflow. - PKT_ERR_INVALID_PARAM -6 Invalid parameter. - PKT_ERR_TX_FULL -7 Transmit window is full. + PKT_ERR_INVALID_PARAM -6 Invalid parameter (NULL handle, bad data pointer, length out of range). + PKT_ERR_TX_FULL -7 Transmit window is full (non-blocking send only). PKT_ERR_NO_DATA -8 No data available. - PKT_ERR_DISCONNECTED -9 Remote side disconnected. + PKT_ERR_DISCONNECTED -9 Serial port returned a negative read (disconnect/error).
PktRecvCallbackT
Callback type for received packets.
typedef void (*PktRecvCallbackT)(void *ctx,
@@ -3879,43 +5258,45 @@ dvxSqlExec(db, sql);
data Payload bytes (valid only during the callback).
len Payload length.
pktOpen
-Open a packetized connection over an already-open COM port.
+Open a packetized connection over an already-open COM port. Only one packet connection may exist on a given COM port at a time; a second pktOpen call on the same port returns NULL to avoid silent framing corruption.
PktConnT *pktOpen(int com, int windowSize,
PktRecvCallbackT callback, void *callbackCtx);
Parameter Description --------- ----------- com COM port index (RS232_COM1..RS232_COM4). Must already be open via rs232Open. - windowSize Sliding window size (1..PKT_MAX_WINDOW). Pass 0 for PKT_DEFAULT_WINDOW. - callback Called when a complete, CRC-verified packet is received. + windowSize Sliding window size (1..PKT_MAX_WINDOW). Pass 0 for PKT_DEFAULT_WINDOW. Values greater than PKT_MAX_WINDOW are clamped. + callback Called when a complete, CRC-verified, in-order packet is received. The data pointer is valid only during the callback. callbackCtx User pointer passed to the callback.-
Returns an opaque PktConnT handle, or NULL on failure.
+Returns an opaque PktConnT handle, or NULL on failure (invalid port, duplicate open, or allocation failure).
pktClose
-Close a packetized connection. Does not close the underlying COM port.
+Close a packetized connection and release its registry slot. Does not close the underlying COM port. The caller is responsible for calling rs232Close separately when no longer needed.
void pktClose(PktConnT *conn);
pktSend
-Send a data packet.
+Send a data packet. The payload is copied into an internal retransmit slot before transmission, so the caller may reuse the supplied buffer immediately.
int pktSend(PktConnT *conn, const uint8_t *data,
int len, bool block);
Parameter Description --------- ----------- conn Connection handle from pktOpen. - data Payload bytes (up to PKT_MAX_PAYLOAD). + data Payload bytes (1..PKT_MAX_PAYLOAD). len Payload length. - block If true, block until transmit window has space. If false, return PKT_ERR_TX_FULL when the window is full.-
Returns PKT_SUCCESS or a negative error code.
+ block If true, poll pktPoll internally until transmit window has space. If false, return PKT_ERR_TX_FULL immediately when the window is full. +Returns PKT_SUCCESS on success, PKT_ERR_INVALID_PARAM for NULL/out-of-range input, PKT_ERR_TX_FULL for a non-blocking call with a full window, or PKT_ERR_DISCONNECTED if the serial port drops during a blocking wait.
pktPoll
-Poll for incoming data, process received frames, and handle retransmits. Must be called frequently in the main loop.
+Poll for incoming data, process received frames, and handle retransmits. Must be called frequently in the main loop. The callback is invoked synchronously for each complete, CRC-verified, in-order data frame, so the caller should be prepared for reentrant pktSend calls from within the callback.
int pktPoll(PktConnT *conn);
-Returns the number of valid data packets delivered to the callback.
+Returns the number of valid data packets delivered to the callback this call, or PKT_ERR_INVALID_PARAM if conn is NULL, or PKT_ERR_DISCONNECTED if the serial layer returned a negative read.
pktReset
-Reset the connection state (sequence numbers, buffers) and send a RST frame to the remote side.
+Reset the local connection state (sequence numbers, transmit slots, RX state machine) and send a RST frame to the remote side. The remote's RST handler clears its own state and echoes a RST back. Useful for recovering from a desynchronized connection.
int pktReset(PktConnT *conn);
+Returns PKT_SUCCESS on success or PKT_ERR_INVALID_PARAM if conn is NULL.
pktCanSend
-Check whether there is room in the transmit window for another packet.
+Check whether there is room in the transmit window for another packet. Returns false when conn is NULL or the transmit window is full.
bool pktCanSend(PktConnT *conn);
pktGetPending
-Get the number of unacknowledged packets currently in the transmit window.
+Get the number of unacknowledged packets currently in the transmit window. Ranges from 0 (all sent packets acknowledged) to windowSize (window full).
int pktGetPending(PktConnT *conn);
+Returns the pending count on success, or PKT_ERR_INVALID_PARAM if conn is NULL.
Security (DH + XTEA)
@@ -3974,10 +5355,11 @@ void secCipherCrypt(SecCipherT *c, void secCipherDestroy(SecCipherT *c);Function Description -------- ----------- - secCipherCreate Allocate a cipher context with a 128-bit key. - secCipherSetNonce Set the initial counter value (nonce). Must be unique per session. - secCipherCrypt Encrypt or decrypt data in place. The counter increments automatically. - secCipherDestroy Free the cipher context.+ secCipherCreate Allocate a cipher context with a 128-bit key. Returns NULL on allocation failure or NULL key. Initial counter is zero. + secCipherSetNonce Set the initial counter value (nonce). Must be unique per session. Both the stored nonce and the running counter are set to (nonceLo, nonceHi). + secCipherCrypt Encrypt or decrypt data in place. The counter increments by one every 8 bytes (one XTEA block). + secCipherDestroy Securely zero the cipher context (key and counter state) and free its memory. +
secCipherCreate returns NULL if the key pointer is NULL or allocation fails. secCipherCrypt is a no-op when any of c/data is NULL or len <= 0.
Secure Link
@@ -3985,26 +5367,28 @@ void secCipherDestroy(SecCipherT *c);Each packet carries a one-byte header: bit 7 is the encrypted flag, bits 6..0 are the channel number. Unencrypted packets can be sent before the handshake completes (e.g., for version negotiation).
Header: seclink/secLink.h
Constants
-Constant Value Description - -------- ----- ----------- - SECLINK_MAX_PAYLOAD 254 Maximum plaintext bytes per send (PKT_MAX_PAYLOAD minus 1-byte channel header). - SECLINK_MAX_CHANNEL 127 Highest valid channel number.+
Constant Value Description + -------- ----- ----------- + SECLINK_MAX_PAYLOAD 254 Maximum plaintext bytes per send (PKT_MAX_PAYLOAD minus 1-byte channel header). + SECLINK_MAX_CHANNEL 127 Highest valid channel number. + SECLINK_NUM_CHANNELS 128 Array size needed to hold one slot per channel (SECLINK_MAX_CHANNEL + 1). + SECLINK_CHAN_BUF_SIZE 4096 Recommended per-channel receive buffer size for callers that buffer inbound data between the receive callback and an application read.
Error Codes
Constant Value Description -------- ----- ----------- SECLINK_SUCCESS 0 Operation succeeded. - SECLINK_ERR_PARAM -1 Invalid parameter. + SECLINK_ERR_PARAM -1 Invalid parameter (NULL pointer, bad channel, bad length). SECLINK_ERR_SERIAL -2 RS-232 layer error. SECLINK_ERR_ALLOC -3 Memory allocation failed. - SECLINK_ERR_HANDSHAKE -4 DH handshake failed. + SECLINK_ERR_HANDSHAKE -4 DH handshake failed (key generation, send, or disconnect during exchange). SECLINK_ERR_NOT_READY -5 Handshake not yet completed (encrypted send attempted). - SECLINK_ERR_SEND -6 Packet send failed.+ SECLINK_ERR_SEND -6 Packet send failed, or non-blocking send when window is full.
SecLinkRecvT
Receive callback type. Delivers decrypted plaintext with the channel number.
typedef void (*SecLinkRecvT)(void *ctx,
const uint8_t *data, int len, uint8_t channel);
secLinkOpen
-Open a secure serial link. Opens the COM port and packet layer internally.
+Open a secure serial link. Opens the COM port via rs232Open and creates a packet layer (default window size) with an internal receive dispatcher. The handshake must be performed separately via secLinkHandshake before encrypted data can be sent.
SecLinkT *secLinkOpen(int com, int32_t bps, int dataBits,
char parity, int stopBits, int handshake,
SecLinkRecvT callback, void *ctx);
@@ -4013,47 +5397,140 @@ void secCipherDestroy(SecCipherT *c);
com COM port index (RS232_COM1..RS232_COM4).
bps Baud rate.
dataBits Data bits per character (5-8).
- parity Parity mode ('N', 'O', 'E', 'M', 'S').
+ parity Parity mode ('N', 'O', 'E', 'M', 'S' or lowercase).
stopBits Stop bits (1 or 2).
handshake Flow control mode (RS232_HANDSHAKE_*).
- callback Called when a packet is received (plaintext, with channel).
+ callback Called when a packet is received, after decryption if applicable. Plaintext data pointer is valid only during the callback.
ctx User pointer passed to the callback.
-Returns an opaque SecLinkT handle, or NULL on failure.
+Returns an opaque SecLinkT handle, or NULL on failure (allocation failure, rs232Open error, or pktOpen error). On failure all partially initialized resources are cleaned up.
secLinkClose
-Close the link, free all resources, and close the COM port.
+Close the link and free all associated resources in reverse of open order: securely destroy TX and RX ciphers (which scrubs key material), destroy any remaining DH context, close the packet layer, close the COM port, and finally free the link struct itself. Safe to call with a NULL link (no-op).
void secLinkClose(SecLinkT *link);
secLinkHandshake
-Perform Diffie-Hellman key exchange. Blocks until both sides complete. The RNG must be seeded before calling this.
+Perform a Diffie-Hellman key exchange and derive the session cipher keys. Blocks, polling the packet layer in a loop, until both sides have swapped public keys. The RNG must be seeded (via secRngSeed, secRngGatherEntropy + secRngSeed, or secRngAddEntropy) before calling this, or the generated private key will be predictable.
int secLinkHandshake(SecLinkT *link);
-Returns SECLINK_SUCCESS or SECLINK_ERR_HANDSHAKE.
+Internally:
+-
+
- Creates a DH context via secDhCreate, generates 1024-bit keys via secDhGenerateKeys, and exports the 128-byte public key. +
- Sends the public key as a single packet via pktSend (blocking). +
Polls pktPoll until the remote's public key arrives and the internal callback completes the handshake (computes the shared secret, derives directional TX and RX cipher keys, transitions to READY, destroys the DH context for forward secrecy).
+Returns SECLINK_SUCCESS on success, SECLINK_ERR_PARAM on NULL link, SECLINK_ERR_ALLOC on DH context allocation failure, or SECLINK_ERR_HANDSHAKE for DH key generation failure, packet send failure, or serial disconnect during the exchange.
+Directional Key Derivation
+To prevent CTR-mode keystream collision, the two sides never use the same TX key. After computing the shared secret, each side derives a master XTEA key via secDhDeriveKey and then XORs it with a direction byte:
+-
+
- The side with the lexicographically lower public key uses masterKey XOR 0xAA for TX and masterKey XOR 0x55 for RX. +
The other side uses the reverse assignment.
+Both sides initialize their cipher counters to zero and advance monotonically from there.
secLinkSend
-Send data on a channel, optionally encrypted.
+Send data on a channel, optionally encrypted. Prepends a one-byte channel header (bit 7 = encrypt flag, bits 6..0 = channel number), then encrypts the payload only (never the header) when encrypt is true.
int secLinkSend(SecLinkT *link, const uint8_t *data,
int len, uint8_t channel, bool encrypt, bool block);
Parameter Description --------- ----------- link Connection handle from secLinkOpen. data Plaintext payload (1..SECLINK_MAX_PAYLOAD bytes). - len Payload length. + len Payload length. Must be in 1..SECLINK_MAX_PAYLOAD. channel Logical channel number (0..SECLINK_MAX_CHANNEL). encrypt If true, encrypt before sending (requires completed handshake). - block If true, block until the transmit window has space.-
Returns SECLINK_SUCCESS or a negative error code.
+ block If true, block until the transmit window has space. If false, return SECLINK_ERR_SEND immediately when the window is full. +Returns SECLINK_SUCCESS on success or a negative error code (SECLINK_ERR_PARAM, SECLINK_ERR_NOT_READY, SECLINK_ERR_SEND).
+Cipher counter safety: the function checks transmit window space BEFORE encrypting the payload. Encrypting first and then failing to send would advance the TX cipher counter while the data never reached the wire, permanently desynchronizing the TX cipher state from the remote's RX cipher. This ordering is critical for correctness when non-blocking sends are used.
secLinkSendBuf
Send an arbitrarily large buffer by splitting into SECLINK_MAX_PAYLOAD chunks. Always blocks until all data is sent.
int secLinkSendBuf(SecLinkT *link, const uint8_t *data,
int len, uint8_t channel, bool encrypt);
Returns SECLINK_SUCCESS or the first error encountered.
secLinkPoll
-Poll for incoming data. Decrypts encrypted packets and delivers plaintext to the receive callback.
+Poll for incoming data. Delegates to pktPoll, which drains the RS-232 ring buffer, processes received frames, checks retransmit timers, and dispatches each complete packet to an internal callback that strips the channel header, decrypts when the encrypt flag is set, and forwards plaintext to the user callback.
int secLinkPoll(SecLinkT *link);
-Returns the number of packets delivered, or a negative error code.
+Returns the number of packets delivered to the callback this call, SECLINK_ERR_PARAM if link is NULL, or one of the pktPoll error codes (PKT_ERR_DISCONNECTED, PKT_ERR_INVALID_PARAM). Must be called frequently in the main loop.
secLinkIsReady
-Check whether the handshake is complete and the link is ready for encrypted data.
+Check whether the handshake is complete and the link is ready for encrypted traffic. Cleartext sends do not require the link to be ready.
bool secLinkIsReady(SecLinkT *link);
+Returns true only when link is non-NULL and the internal state is STATE_READY (that is, secLinkHandshake has completed). Returns false on NULL or before the handshake.
secLinkGetPending
-Get the number of unacknowledged packets in the transmit window.
+Get the number of unacknowledged packets in the transmit window. Delegates directly to pktGetPending on the underlying packet connection. Useful for non-blocking send loops to decide when to throttle.
int secLinkGetPending(SecLinkT *link);
+Returns the pending count on success or SECLINK_ERR_PARAM when link is NULL.
+End-to-End Example
+Below is a complete secure BBS client that opens COM1, exchanges DH keys, and then shuttles terminal traffic over a single encrypted channel. It demonstrates the typical serial stack usage: open the link, seed the RNG, run the handshake, then enter a poll+send loop.
+#include "rs232/rs232.h"
+#include "packet/packet.h"
+#include "security/security.h"
+#include "seclink/secLink.h"
+#include <stdio.h>
+#include <string.h>
+
+#define CHAN_TERMINAL 0
+
+static void onPacket(void *ctx, const uint8_t *data,
+ int len, uint8_t channel)
+{
+ (void)ctx;
+ if (channel == CHAN_TERMINAL) {
+ fwrite(data, 1, len, stdout);
+ fflush(stdout);
+ }
+}
+
+
+int main(void) {
+ // Seed the RNG from hardware entropy plus any user-derived
+ // randomness (keyboard timing, etc.).
+ uint8_t entropy[16];
+ int got = secRngGatherEntropy(entropy, sizeof(entropy));
+ secRngSeed(entropy, got);
+
+ // Open the link at 115200 8N1 with RTS/CTS flow control.
+ SecLinkT *link = secLinkOpen(
+ RS232_COM1, 115200, 8, 'N', 1,
+ RS232_HANDSHAKE_RTSCTS,
+ onPacket, NULL);
+ if (!link) {
+ fprintf(stderr, "secLinkOpen failed\n");
+ return 1;
+ }
+
+ // Run the DH key exchange. Blocks until both sides
+ // have swapped public keys and derived cipher keys.
+ if (secLinkHandshake(link) != SECLINK_SUCCESS) {
+ fprintf(stderr, "Handshake failed\n");
+ secLinkClose(link);
+ return 1;
+ }
+
+ // Send an encrypted banner and then relay keyboard input.
+ const char *hello = "Hello, secure BBS!\r\n";
+ secLinkSend(link, (const uint8_t *)hello,
+ (int)strlen(hello), CHAN_TERMINAL, true, true);
+
+ while (!feof(stdin)) {
+ // Deliver any incoming packets to onPacket().
+ secLinkPoll(link);
+
+ // If the user typed something, forward it encrypted.
+ int ch = getchar();
+ if (ch == EOF) {
+ break;
+ }
+ uint8_t byte = (uint8_t)ch;
+ secLinkSend(link, &byte, 1, CHAN_TERMINAL, true, true);
+ }
+
+ secLinkClose(link);
+ return 0;
+}
+Notes:
+-
+
- secLinkOpen internally calls rs232Open and pktOpen. secLinkClose tears them down in reverse order. +
- The RNG must be seeded before secLinkHandshake. secRngGatherEntropy provides roughly 20 bits of hardware entropy; supplement with user interaction timing for cryptographic use. +
- secLinkPoll must be called frequently to drain the RX ring buffer, process ACKs, and dispatch received packets to the callback. +
For bulk transfers larger than SECLINK_MAX_PAYLOAD (254 bytes), use secLinkSendBuf which splits the data into chunks automatically.
BASIC Runtime Library
@@ -4391,10 +5868,10 @@ int32_t basVmGetCurrentLine(const BasVmT *vm);DVX Widget System
-Complete reference for the DVX GUI widget toolkit. All widgets are implemented as dynamically loaded DXE modules. They are created via convenience macros that wrap the per-widget API function tables. The base WidgetT structure is defined in core/dvxWidget.h; individual widget headers live in widgets/.
+Complete reference for the DVX GUI widget toolkit. All widgets are implemented as dynamically loaded DXE modules. They are created via convenience macros that wrap the per-widget API function tables. The base WidgetT structure is defined in libdvx/dvxWgt.h; individual widget headers live in widgets/.
Individual widgets are documented in their own sections. See the table of contents for the full list.
Base WidgetT (Common Properties, Events, and Operations)
-Every widget inherits from the WidgetT structure defined in core/dvxWidget.h. The fields and callbacks listed here are available on all widget types.
+Every widget inherits from the WidgetT structure defined in libdvx/dvxWgt.h. The fields and callbacks listed here are available on all widget types.
Common Properties
Field Type Description ----- ---- ----------- @@ -4461,178 +5938,328 @@ int32_t basVmGetCurrentLine(const BasVmT *vm);
AnsiTerm
-A VT100/ANSI-compatible terminal emulator widget designed for connecting to BBS systems over the serial link. Uses a traditional text-mode cell buffer (character + attribute byte pairs) with the CP437 character set and 16-color CGA palette. Supports cursor movement, screen/line erase, scrolling regions, SGR colors, and scrollback history. Communication is abstracted through read/write function pointers, allowing the terminal to work with raw serial ports, the secLink encrypted channel, or any other byte-oriented transport.
-Header: widgets/widgetAnsiTerm.h
+A VT100/ANSI-compatible terminal emulator widget designed for connecting to BBS systems over the serial link. Uses a traditional text-mode cell buffer (character + attribute byte pairs) with the CP437 character set and 16-color CGA palette. Supports cursor movement, screen/line erase, scrolling regions, SGR colors, DEC private modes, and a configurable scrollback buffer. Communication is abstracted through read/write function pointers, allowing the terminal to work with raw serial ports, the secLink encrypted channel, or any other byte-oriented transport.
+The widget renders through two paint paths: a full paint used by the normal widget pipeline, and a fast incremental repaint (wgtAnsiTermRepaint) that pushes dirty rows directly to the window content buffer for low-latency serial echo.
+Header: widgets/ansiTerm.h
Creation
WidgetT *term = wgtAnsiTerm(parent, 80, 25);
-Macros
-Macro Description - ----- ----------- - wgtAnsiTerm(parent, cols, rows) Create an ANSI terminal widget with the given column and row dimensions. - wgtAnsiTermWrite(w, data, len) Write raw bytes into the terminal's ANSI parser. data is a const uint8_t * buffer, len is the byte count. - wgtAnsiTermClear(w) Clear the terminal screen and reset the cursor to the home position. - wgtAnsiTermSetComm(w, ctx, readFn, writeFn) Attach a communication channel. readFn and writeFn are I/O callbacks; ctx is passed as their first argument. - wgtAnsiTermSetScrollback(w, maxLines) Set the maximum number of scrollback lines. Lines scrolled off the top are saved in a circular buffer. - wgtAnsiTermPoll(w) Poll the communication channel for incoming data and feed it into the ANSI parser. - wgtAnsiTermRepaint(w, outY, outH) Fast repaint path that renders dirty rows directly into the window's content buffer, bypassing the widget pipeline. Returns the dirty region via outY/outH.+
API Functions
+Function Description + -------- ----------- + WidgetT *wgtAnsiTerm(parent, cols, rows) Create an ANSI terminal widget with the given column/row dimensions. + void wgtAnsiTermWrite(w, data, len) Write raw bytes into the terminal's ANSI parser. data is a const uint8_t * buffer. + void wgtAnsiTermClear(w) Clear the terminal screen and reset the cursor to the home position. + void wgtAnsiTermSetComm(w, ctx, readFn, writeFn) Attach a communication channel. readFn and writeFn are I/O callbacks; ctx is passed as their first argument. + void wgtAnsiTermSetScrollback(w, maxLines) Set the maximum number of scrollback lines. + int32_t wgtAnsiTermPoll(w) Poll the communication channel for incoming data and feed it into the parser. Returns number of bytes consumed. + int32_t wgtAnsiTermRepaint(w, outY, outH) Fast repaint path that renders dirty rows directly into the window's content buffer, bypassing the widget pipeline. Returns the number of rows repainted and the dirty region via outY/outH.+
API Struct (wgtRegisterApi "ansiterm")
+The sApi struct exposes these function pointers:
+Slot Function + ---- -------- + create wgtAnsiTerm + write wgtAnsiTermWrite + clear wgtAnsiTermClear + setComm wgtAnsiTermSetComm + setScrollback wgtAnsiTermSetScrollback + poll wgtAnsiTermPoll + repaint wgtAnsiTermRepaint
Properties (BASIC Interface)
Property Type Access Description -------- ---- ------ ----------- Cols Integer Read-only Number of columns. Rows Integer Read-only Number of rows. - Scrollback Integer Write-only Maximum scrollback lines.+ Scrollback Integer Write-only Maximum number of scrollback lines.
Methods (BASIC Interface)
Method Description ------ ----------- Clear Clear the terminal screen. - Write Write a string into the terminal.+ Poll Process any pending bytes on the attached communication channel. + Write Write a string into the terminal (with ANSI escape processing).
Events
AnsiTerm uses the common events only. No widget-specific events are defined.
+Keyboard Shortcuts
+Within the terminal widget:
+Key Action + --- ------ + Ctrl+C Copy selection to the clipboard (when a selection exists). + Ctrl+V Send the clipboard contents to the attached write function. + Arrows Send VT100 cursor escape sequences. + Home/End Send VT100 Home/End sequences. + PgUp/PgDn/Del Send the corresponding VT100 escape sequences.
Box (VBox / HBox / Frame)
-Container widgets that arrange their children in a vertical column (VBox), horizontal row (HBox), or a titled group box (Frame). These are the primary layout building blocks. Children are laid out using a flexbox-like algorithm with weight-based extra-space distribution.
-Header: widgets/widgetBox.h
+Container widgets that arrange their children in a vertical column (VBox), horizontal row (HBox), or a titled group box (Frame). These are the primary layout building blocks. Children are laid out using a weight-based algorithm with configurable spacing, padding, and alignment.
+Frame is a labelled grouping container with a Motif-style beveled border. Its title text sits centered vertically on the top border line with a small background-filled gap behind the title, giving the classic Windows 3.1 / Motif group box appearance. Internally, Frame behaves like a VBox for layout purposes.
+The widget DXE registers three separate interface entries ("vbox", "hbox", "frame") so the form designer can create each type independently.
+Header: widgets/box.h
Creation
-Macro Description - ----- ----------- - wgtVBox(parent) Create a vertical box container. Children are stacked top to bottom. - wgtHBox(parent) Create a horizontal box container. Children are placed left to right. - wgtFrame(parent, title) Create a titled group box (a VBox with a border and label).+
WidgetT *row = wgtHBox(parent);
+WidgetT *col = wgtVBox(parent);
+WidgetT *group = wgtFrame(parent, "Options");
+API Functions
+Function Description + -------- ----------- + WidgetT *wgtVBox(parent) Create a vertical box container. Children stack top-to-bottom. + WidgetT *wgtHBox(parent) Create a horizontal box container. Children stack left-to-right. + WidgetT *wgtFrame(parent, title) Create a titled group box. Children stack vertically inside the bordered frame. The title string may include a '&' prefix for an accelerator key.+
API Struct (wgtRegisterApi "box")
+Slot Function + ---- -------- + vBox wgtVBox + hBox wgtHBox + frame wgtFrame+
The designer also registers per-type APIs: "vbox", "hbox", and "frame" each expose a single create slot.
Properties
-Box containers use the common WidgetT fields for layout control:
-Property Description - -------- ----------- - align Main-axis alignment of children. HBox: Start=left, Center=center, End=right. VBox: Start=top, Center=center, End=bottom. - spacing Gap between children (tagged size). - padding Internal padding around children (tagged size). - weight Controls how the box itself stretches within its parent.+
Box containers use the common WidgetT fields for layout control. There are no widget-specific properties registered with the interface system.
+Field Description + ----- ----------- + align Main-axis alignment of children. HBox: Start=left, Center=center, End=right. VBox: Start=top, Center=center, End=bottom. + spacing Gap between children (tagged size). + padding Internal padding around children (tagged size). + weight Controls how the box itself stretches within its parent.+
Frame text is managed via the standard wgtSetText() / wgtGetText() interface (the widget has WCLASS_HAS_TEXT). BASIC code can set its title via the generic "Caption" or "Text" property.
Events
-Containers use the common events only. No widget-specific events.
+Containers use the common events only. No widget-specific events or methods are registered.
+Default Event
+"Click" on all three types.
Button
-A push button with a text label. Fires onClick when pressed and released. Supports keyboard activation via accelerator keys.
-Header: widgets/widgetButton.h
+A push button with a text label. Fires onClick when pressed and released. Uses a two-phase press model: the button visually depresses on mouse-down and fires onClick only when the mouse is released while still inside the button bounds -- dragging the mouse off cancels the press. Supports accelerator keys via '&' prefix in the text (e.g. "&OK" underlines 'O' and binds Alt+O).
+Disabled buttons use the classic "embossed" rendering (highlight text offset by +1,+1 and shadow text at 0,0) for a chiseled appearance.
+Header: widgets/button.h
Creation
-WidgetT *btn = wgtButton(parent, "OK");
-Macro
-Macro Description - ----- ----------- - wgtButton(parent, text) Create a push button with the given label text.+
WidgetT *btn = wgtButton(parent, "&OK");
+btn->onClick = onOkClicked;
+API Functions
+Function Description + -------- ----------- + WidgetT *wgtButton(parent, text) Create a push button with the given label text. Pass NULL for no text. Text is copied into the widget.+
API Struct (wgtRegisterApi "button")
+Slot Function + ---- -------- + create wgtButton
Properties
-Uses common WidgetT properties. Set accelKey for keyboard shortcut. Use wgtSetText() / wgtGetText() to change the label.
+Uses common WidgetT properties. Label text is managed via wgtSetText() / wgtGetText(). Set accelKey for keyboard shortcut (automatically parsed from '&' prefix in the text). The button is focusable (WCLASS_FOCUSABLE) and draws a focus rectangle when it holds keyboard focus.
+No widget-specific properties are registered with the interface system. BASIC code sets the label via the generic "Caption" or "Text" property.
+Methods
+No widget-specific methods.
Events
Callback Description -------- ----------- - onClick Fires when the button is clicked (press + release).+ onClick Fires when the button is clicked (mouse press and release inside, or Space/Enter when focused). +
Default Event
+"Click" (VB basName: CommandButton, namePrefix: Command).
Canvas
-A freeform drawing surface with a fixed-size pixel buffer. Provides drawing primitives (lines, rectangles, circles, text, individual pixels) and supports save/load to BMP files. Mouse interaction is available via a callback.
-Header: widgets/widgetCanvas.h
+A freeform drawing surface with a fixed-size pixel buffer stored in the display's native pixel format. Provides drawing primitives (lines, rectangles, circles, text, individual pixels) and supports save/load to image files (BMP/PNG/etc. via dvxLoadImage/dvxSaveImage). Mouse interaction is available via a callback. The buffer is rendered to screen as a straight blit with no per-pixel conversion.
+Canvas coordinates are independent of widget position: (0,0) is the top-left of the canvas content, not the widget. The widget frames the buffer with a 2-pixel sunken bevel.
+Header: widgets/canvas.h
Creation
WidgetT *cv = wgtCanvas(parent, 320, 200);
-Macros
-Macro Description - ----- ----------- - wgtCanvas(parent, w, h) Create a canvas with the given pixel dimensions. - wgtCanvasClear(w, color) Fill the entire canvas with a solid color. - wgtCanvasSetPenColor(w, color) Set the drawing pen color. - wgtCanvasSetPenSize(w, size) Set the drawing pen size in pixels. - wgtCanvasDrawLine(w, x0, y0, x1, y1) Draw a line from (x0,y0) to (x1,y1). - wgtCanvasDrawRect(w, x, y, width, height) Draw a rectangle outline. - wgtCanvasFillRect(w, x, y, width, height) Draw a filled rectangle. - wgtCanvasFillCircle(w, cx, cy, radius) Draw a filled circle. - wgtCanvasSetPixel(w, x, y, color) Set a single pixel to the given color. - wgtCanvasGetPixel(w, x, y) Get the color of a single pixel. - wgtCanvasDrawText(w, x, y, text) Draw text at the given position using the current pen color. - wgtCanvasSetMouseCallback(w, cb) Set a mouse interaction callback. Signature: void (*cb)(WidgetT *w, int32_t cx, int32_t cy, bool drag). Receives canvas-relative coordinates and whether the mouse is being dragged. - wgtCanvasSave(w, path) Save the canvas contents to a BMP file. - wgtCanvasLoad(w, path) Load a BMP file into the canvas.-
Events
-Callback Description - -------- ----------- - onClick Fires when the canvas is clicked. - Mouse callback (via wgtCanvasSetMouseCallback) Fires on mouse down and drag with canvas-local coordinates.+
API Functions
+Function Description + -------- ----------- + WidgetT *wgtCanvas(parent, w, h) Create a canvas with the given pixel dimensions. Buffer is initialized to white. + void wgtCanvasClear(w, color) Fill the entire canvas with a packed color. + void wgtCanvasSetPenColor(w, color) Set the drawing pen color (packed display color). + void wgtCanvasSetPenSize(w, size) Set the drawing pen size in pixels (affects DrawLine dot thickness). + void wgtCanvasDrawLine(w, x0, y0, x1, y1) Draw a line using Bresenham's algorithm with the current pen color and size. + void wgtCanvasDrawRect(w, x, y, width, height) Draw a 1-pixel rectangle outline using the current pen color. + void wgtCanvasFillRect(w, x, y, width, height) Fill a rectangle using the current pen color. + void wgtCanvasFillCircle(w, cx, cy, radius) Fill a circle using the current pen color (integer sqrt; no FPU needed). + void wgtCanvasSetPixel(w, x, y, color) Set a single pixel to the given packed color. + uint32_t wgtCanvasGetPixel(w, x, y) Read a single pixel. Returns packed color. + void wgtCanvasDrawText(w, x, y, text) Draw text at the given canvas coordinates using the current pen color. + void wgtCanvasSetMouseCallback(w, cb) Set a mouse callback. Signature: void (*cb)(WidgetT *w, int32_t cx, int32_t cy, bool drag). cx/cy are canvas-relative, drag=true on mouse-move during press. + int32_t wgtCanvasSave(w, path) Save the canvas buffer to an image file. Returns 0 on success, -1 on error. + int32_t wgtCanvasLoad(w, path) Load an image file into the canvas (resizes buffer to match). Returns 0 on success, -1 on error. + void wgtCanvasResize(w, newW, newH) Resize the canvas buffer. New pixels are filled with white.+
API Struct (wgtRegisterApi "canvas")
+Slot Function + ---- -------- + create wgtCanvas + clear wgtCanvasClear + setPenColor wgtCanvasSetPenColor + setPenSize wgtCanvasSetPenSize + setMouseCallback wgtCanvasSetMouseCallback + save wgtCanvasSave + load wgtCanvasLoad + drawLine wgtCanvasDrawLine + drawRect wgtCanvasDrawRect + fillRect wgtCanvasFillRect + fillCircle wgtCanvasFillCircle + setPixel wgtCanvasSetPixel + getPixel wgtCanvasGetPixel + drawText wgtCanvasDrawText + resize wgtCanvasResize+
Properties
+Canvas has no widget-specific properties registered with the interface system. Drawing state (pen color, pen size) is managed by the API functions above.
Methods (BASIC Interface)
-Method Description - ------ ----------- - Clear Clear the canvas to a given color.+
Method Description + ------ ----------- + Clear color% Fill the entire canvas with a 0x00RRGGBB color. + DrawLine x0%, y0%, x1%, y1%, color% Draw a line between two points. + DrawRect x%, y%, w%, h%, color% Draw a rectangle outline. + DrawText x%, y%, text$ Draw text at the given position. + FillCircle cx%, cy%, radius%, color% Fill a circle. + FillRect x%, y%, w%, h%, color% Fill a rectangle. + GetPixel(x%, y%) Returns the 0x00RRGGBB color at a pixel. + Load path$ Load an image file onto the canvas. + Resize w%, h% Resize the canvas (fills new area with white). + Save path$ Save the canvas to an image file. + SetPenColor color% Set the drawing color (0x00RRGGBB). + SetPenSize size% Set the pen size in pixels. + SetPixel x%, y%, color% Set a single pixel.+
Events
+Callback Description + -------- ----------- + onClick Fires when the canvas is clicked. + Mouse callback (via wgtCanvasSetMouseCallback) Fires on mouse down and drag with canvas-local coordinates.+
Default Event
+"Click" (VB basName: PictureBox, namePrefix: Picture).
Checkbox
-A toggle control with a text label. Clicking toggles between checked and unchecked states.
-Header: widgets/widgetCheckbox.h
+A toggle control with a text label. Clicking toggles between checked and unchecked states. Fires onChange each time the state flips. Supports accelerator keys (via '&' in the text) and keyboard toggle via Space or Enter when focused.
+The check mark is drawn as an "X" pattern rather than a traditional checkmark glyph. The focus rectangle wraps the label text (not the box), matching the Windows 3.1 convention.
+Header: widgets/checkbox.h
Creation
-WidgetT *cb = wgtCheckbox(parent, "Enable logging");
-Macros
-Macro Description - ----- ----------- - wgtCheckbox(parent, text) Create a checkbox with the given label text. - wgtCheckboxIsChecked(w) Returns true if the checkbox is checked. - wgtCheckboxSetChecked(w, checked) Set the checked state programmatically.-
Events
-Callback Description - -------- ----------- - onClick Fires when clicked (after toggle). - onChange Fires when the checked state changes.+
WidgetT *cb = wgtCheckbox(parent, "Enable &logging");
+API Functions
+Function Description + -------- ----------- + WidgetT *wgtCheckbox(parent, text) Create a checkbox with the given label text. + bool wgtCheckboxIsChecked(w) Returns true if the checkbox is checked. + void wgtCheckboxSetChecked(w, checked) Set the checked state programmatically. Triggers a repaint but does NOT fire onChange.+
API Struct (wgtRegisterApi "checkbox")
+Slot Function + ---- -------- + create wgtCheckbox + isChecked wgtCheckboxIsChecked + setChecked wgtCheckboxSetChecked
Properties (BASIC Interface)
Property Type Access Description -------- ---- ------ ----------- Value Boolean Read/Write Whether the checkbox is checked.-
ComboBox
-A combination of a text input and a dropdown list. The user can either type a value or select from a list of predefined options. Unlike Dropdown, the text field is editable.
-Header: widgets/widgetComboBox.h
-Creation
-WidgetT *cb = wgtComboBox(parent, 128);
-const char *items[] = { "Arial", "Courier", "Times" };
-wgtComboBoxSetItems(cb, items, 3);
-Macros
-Macro Description - ----- ----------- - wgtComboBox(parent, maxLen) Create a combo box. maxLen is the maximum text input length. - wgtComboBoxSetItems(w, items, count) Set the dropdown items. - wgtComboBoxGetSelected(w) Get the index of the selected item (-1 if the text does not match any item). - wgtComboBoxSetSelected(w, idx) Set the selected item by index.+
Label text is managed via the standard wgtSetText() / wgtGetText() interface. BASIC code uses the generic "Caption" or "Text" property.
+Methods
+No widget-specific methods.
Events
Callback Description -------- ----------- - onChange Fires when the text or selection changes.+ onClick Fires when clicked (after the toggle has already applied). + onChange Fires when the checked state changes (mouse click or keyboard toggle). +
Default Event
+"Click" (VB basName: CheckBox).
+ComboBox
+A combination of a single-line text input and a drop-down list. The user can type a value or select one from the list. When the user picks a list item, its text is copied into the edit buffer. Supports full text editing (cursor movement, selection, clipboard, undo) via the texthelp library, and a popup overlay list via the listhelp library.
+Depends on "texthelp" and "listhelp" helper libraries (declared in combobox.dep).
+Header: widgets/comboBox.h
+Creation
+WidgetT *cb = wgtComboBox(parent, 128);
+wgtComboBoxAddItem(cb, "Arial");
+wgtComboBoxAddItem(cb, "Courier");
+wgtComboBoxAddItem(cb, "Times");
+API Functions
+Function Description + -------- ----------- + WidgetT *wgtComboBox(parent, maxLen) Create a combo box. maxLen is the maximum editable text length (0 => default 256). + void wgtComboBoxSetItems(w, items, count) Set the dropdown items from a const char ** array. Items are not copied -- caller owns them. + int32_t wgtComboBoxGetSelected(w) Get the index of the last selected item (-1 if the text was typed freely). + void wgtComboBoxSetSelected(w, idx) Select an item by index. Copies its text into the edit buffer. + void wgtComboBoxAddItem(w, text) Append an item to the owned list (strdup'd). + void wgtComboBoxRemoveItem(w, idx) Remove an owned item by index. + void wgtComboBoxClear(w) Remove all owned items and reset the selection. + const char *wgtComboBoxGetItem(w, idx) Get the text of an item by index. + int32_t wgtComboBoxGetItemCount(w) Get the total number of items.+
API Struct (wgtRegisterApi "combobox")
+Slot Function + ---- -------- + create wgtComboBox + setItems wgtComboBoxSetItems + getSelected wgtComboBoxGetSelected + setSelected wgtComboBoxSetSelected + addItem wgtComboBoxAddItem + removeItem wgtComboBoxRemoveItem + clear wgtComboBoxClear + getItem wgtComboBoxGetItem + getItemCount wgtComboBoxGetItemCount
Properties (BASIC Interface)
Property Type Access Description -------- ---- ------ ----------- - ListIndex Integer Read/Write Index of the currently selected item.+ ListIndex Integer Read/Write Index of the currently selected item (-1 if none). +
Editable text is accessible via the generic "Text" property. "ListCount" is available through the ListCount method.
+Methods (BASIC Interface)
+Method Description + ------ ----------- + AddItem text$ Append an item to the dropdown list. + Clear Remove all items and clear the selection. + List(index%) Return the text of the item at the given index. + ListCount() Return the total number of items. + RemoveItem index% Remove the item at the given index.+
Events
+Callback Description + -------- ----------- + onChange Fires when the selection or text changes.+
Default Event
+"Click" (VB basName: ComboBox).
DataCtrl
-A VB3-style Data control for database binding. Displays a visible navigation bar that connects to a SQLite database via dvxSql* functions. Reads all rows from the RecordSource query into an in-memory cache for bidirectional navigation. Fires Reposition events when the cursor moves so bound controls can update. Supports master-detail linking between Data controls.
-Header: widgets/widgetDataCtrl.h
+A VB3-style Data control for database binding. Displays a visible navigation bar (|< < > >|) that connects to a SQLite database via dvxSql* functions. Reads all rows from the RecordSource query into an in-memory cache for bidirectional navigation. Fires a Reposition event each time the current row changes so bound controls can update. Supports master-detail linking between Data controls (via MasterSource / MasterField / DetailField), INSERT via AddNew, and DELETE via Delete. UPDATEs use the KeyColumn to identify the row.
+The widget depends on the "dvxsql" library DXE; the navigation logic caches the full result set so there is no round-trip for MoveNext/MovePrev.
+Header: widgets/dataCtrl.h
Creation
WidgetT *data = wgtDataCtrl(parent);
-Macros
-Macro Description - ----- ----------- - wgtDataCtrl(parent) Create a Data control. - wgtDataCtrlRefresh(w) Re-execute the RecordSource query and rebuild the row cache. - wgtDataCtrlMoveFirst(w) Move the cursor to the first row. - wgtDataCtrlMovePrev(w) Move the cursor to the previous row. - wgtDataCtrlMoveNext(w) Move the cursor to the next row. - wgtDataCtrlMoveLast(w) Move the cursor to the last row. - wgtDataCtrlGetField(w, colName) Get the value of a column in the current row. Returns const char *. - wgtDataCtrlSetField(w, colName, value) Set the value of a column in the current row (marks the row dirty). - wgtDataCtrlUpdateRow(w) Write the current row's pending changes back to the database. - wgtDataCtrlUpdate(w) Flush all pending changes to the database. - wgtDataCtrlAddNew(w) Begin a new row. Sets dirty state; call Update to commit. - wgtDataCtrlDelete(w) Delete the current row from the database. - wgtDataCtrlSetMasterValue(w, val) Set the master-detail filter value for this control. - wgtDataCtrlGetRowCount(w) Get the total number of cached rows. - wgtDataCtrlGetColCount(w) Get the number of columns in the result set. - wgtDataCtrlGetColName(w, col) Get the name of a column by index. Returns const char *. - wgtDataCtrlGetCellText(w, row, col) Get the text of a specific cell by row and column index. Returns const char *. - wgtDataCtrlSetCurrentRow(w, row) Set the current row by index (0-based).+
Set properties (DatabaseName, RecordSource, KeyColumn, etc.) and then call dataCtrlRefresh to populate.
+API Functions
+Function Description + -------- ----------- + WidgetT *dataCtrlCreate(parent) Create a Data control. Exposed as create in the API struct. + void dataCtrlRefresh(w) Re-execute the RecordSource query and rebuild the row cache. + void dataCtrlMoveFirst(w) Move the cursor to the first row. + void dataCtrlMovePrev(w) Move the cursor to the previous row. + void dataCtrlMoveNext(w) Move the cursor to the next row. + void dataCtrlMoveLast(w) Move the cursor to the last row. + const char *dataCtrlGetField(w, colName) Get the value of a column in the current row (case-insensitive). + void dataCtrlSetField(w, colName, value) Set the value of a column in the current row. Marks the row dirty. + void dataCtrlUpdate(w) Flush pending changes (INSERT or UPDATE) to the database. + void dataCtrlUpdateRow(w) Legacy wrapper around dataCtrlUpdate. + void dataCtrlAddNew(w) Append a blank row and move the cursor to it. The row is dirty and new until Update is called. + void dataCtrlDelete(w) Delete the current row from the cache and the database. + void dataCtrlSetMasterValue(w, val) Set the master-detail filter value. Normally managed by the form runtime. + int32_t dataCtrlGetRowCount(w) Get the total number of cached rows. + int32_t dataCtrlGetColCount(w) Get the number of columns in the result set. + const char *dataCtrlGetColName(w, col) Get the name of a column by index. + const char *dataCtrlGetCellText(w, row, col) Get the text of a specific cell. + void dataCtrlSetCurrentRow(w, row) Set the current row by index. Auto-saves the previous row if dirty.+
API Struct (wgtRegisterApi "data")
+Slot Function + ---- -------- + create dataCtrlCreate + refresh dataCtrlRefresh + moveFirst dataCtrlMoveFirst + movePrev dataCtrlMovePrev + moveNext dataCtrlMoveNext + moveLast dataCtrlMoveLast + getField dataCtrlGetField + setField dataCtrlSetField + updateRow dataCtrlUpdateRow + update dataCtrlUpdate + addNew dataCtrlAddNew + delete dataCtrlDelete + setMasterValue dataCtrlSetMasterValue + getRowCount dataCtrlGetRowCount + getColCount dataCtrlGetColCount + getColName dataCtrlGetColName + getCellText dataCtrlGetCellText + setCurrentRow dataCtrlSetCurrentRow
Properties (BASIC Interface)
Property Type Access Description -------- ---- ------ ----------- @@ -4642,47 +6269,58 @@ wgtComboBoxSetItems(cb, items, 3);MasterSource String Read/Write Name of the master Data control for master-detail linking. MasterField String Read/Write Column in the master control to read for the filter value. DetailField String Read/Write Column in this table to filter by the master value. - Caption String Read/Write Text displayed on the navigation bar. - BOF Boolean Read-only True when the cursor is before the first row. - EOF Boolean Read-only True when the cursor is past the last row. + Caption String Read/Write Text displayed on the navigator bar. + BOF Boolean Read-only True when the cursor is at the first row (or no rows). + EOF Boolean Read-only True when the cursor is past the last row (or no rows).
Methods (BASIC Interface)
Method Description ------ ----------- - AddNew Begin a new row. + AddNew Append a blank row and move to it. Delete Delete the current row. - MoveFirst Move to the first row. - MoveLast Move to the last row. - MoveNext Move to the next row. - MovePrevious Move to the previous row. + MoveFirst Move the cursor to the first row. + MoveLast Move the cursor to the last row. + MoveNext Move the cursor to the next row. + MovePrevious Move the cursor to the previous row. Refresh Re-execute the query and rebuild the cache. Update Write pending changes to the database.
Events
Event Description ----- ----------- - Reposition Fires when the current row changes (navigation, refresh, etc.). Default event. - Validate Fires before writing changes. Return false to cancel.+ Reposition Fires when the current row changes. Default event. + Validate Fires before writing. Return false to cancel the write.
DbGrid
-A database grid widget that displays all records from a Data control in a scrollable, sortable table. Columns auto-populate from the Data control's column names and can be hidden, resized, and renamed by the application. Clicking a column header sorts the display. Selecting a row syncs the Data control's cursor position. The grid reads directly from the Data control's cached rows, so there is no separate copy of the data.
-Header: widgets/widgetDbGrid.h
+A database grid widget that displays all records from a Data control in a scrollable, sortable table. Columns auto-populate from the Data control's column names and can be hidden, resized (by dragging a column border), and renamed by the application. Clicking a column header sorts the display ascending/descending. Selecting a row syncs the Data control's cursor position. The grid reads directly from the Data control's cached rows, so there is no separate copy of the data.
+The grid supports alternating row shading, vertical and horizontal scrollbars, keyboard navigation (arrows, Page Up/Down, Home, End), and double-click activation (fires onDblClick).
+Header: widgets/dbGrid.h
Creation
WidgetT *grid = wgtDbGrid(parent);
-wgtDbGridSetDataWidget(grid, dataCtrl);
-Macros
-Macro Description - ----- ----------- - wgtDbGrid(parent) Create a database grid widget. - wgtDbGridSetDataWidget(w, dataWidget) Bind the grid to a Data control. The grid reads rows from this widget. - wgtDbGridRefresh(w) Re-read the Data control's state and repaint the grid. - wgtDbGridSetColumnVisible(w, fieldName, visible) Show or hide a column by field name. - wgtDbGridSetColumnHeader(w, fieldName, header) Set a display header for a column (overrides the field name). - wgtDbGridSetColumnWidth(w, fieldName, width) Set the width of a column by field name (tagged size, 0 = auto). - wgtDbGridGetSelectedRow(w) Get the index of the currently selected data row (-1 if none).+dbGridSetDataWidget(grid, dataCtrl); +
API Functions
+Function Description + -------- ----------- + WidgetT *dbGridCreate(parent) Create a database grid widget. Exposed as create in the API struct. + void dbGridSetDataWidget(w, dataWidget) Bind the grid to a Data control. Auto-populates columns from the Data control's column names. + void dbGridRefresh(w) Re-read the Data control's state and repaint the grid. Rebuilds the sort index if sorting is active. + void dbGridSetColumnVisible(w, fieldName, visible) Show or hide a column by field name. + void dbGridSetColumnHeader(w, fieldName, header) Set a display header for a column (overrides the field name). + void dbGridSetColumnWidth(w, fieldName, width) Set a column's width (tagged size, 0 = auto). + int32_t dbGridGetSelectedRow(w) Get the index of the currently selected data row (-1 if none).+
API Struct (wgtRegisterApi "dbgrid")
+Slot Function + ---- -------- + create dbGridCreate + setDataWidget dbGridSetDataWidget + refresh dbGridRefresh + setColumnVisible dbGridSetColumnVisible + setColumnHeader dbGridSetColumnHeader + setColumnWidth dbGridSetColumnWidth + getSelectedRow dbGridGetSelectedRow
Properties (BASIC Interface)
Property Type Access Description -------- ---- ------ ----------- - GridLines Boolean Read/Write Whether to draw grid lines between cells.+ GridLines Boolean Read/Write Whether to draw grid lines between cells (default: true).
Methods (BASIC Interface)
Method Description ------ ----------- @@ -4690,151 +6328,247 @@ wgtDbGridSetDataWidget(grid, dataCtrl);
Events
Event Description ----- ----------- - Click Fires when a row is clicked. + Click Fires when a row is clicked (selection change). DblClick Fires when a row is double-clicked. Default event.+
Default Event
+"DblClick" (VB basName: DBGrid, namePrefix: DBGrid).
Dropdown
-A drop-down list that displays a single selected item and expands to show all options when clicked. Read-only selection (the user cannot type into it).
-Header: widgets/widgetDropdown.h
+A drop-down list that displays a single selected item and expands to a popup list when clicked. Unlike ComboBox, the user cannot type free text -- only list items can be selected. Keyboard navigation: Down/Up to move, Enter to select, type-ahead search on printable keys. The popup overlay is rendered above all other widgets via the widget paint overlay mechanism.
+Depends on the "listhelp" helper library (declared in dropdown.dep).
+Header: widgets/dropdown.h
Creation
WidgetT *dd = wgtDropdown(parent);
-const char *items[] = { "Red", "Green", "Blue" };
-wgtDropdownSetItems(dd, items, 3);
-Macros
-Macro Description - ----- ----------- - wgtDropdown(parent) Create a dropdown list. - wgtDropdownSetItems(w, items, count) Set the list of items. items is a const char ** array. - wgtDropdownGetSelected(w) Get the index of the selected item (-1 if none). - wgtDropdownSetSelected(w, idx) Set the selected item by index.+wgtDropdownAddItem(dd, "Red"); +wgtDropdownAddItem(dd, "Green"); +wgtDropdownAddItem(dd, "Blue"); +
API Functions
+Function Description + -------- ----------- + WidgetT *wgtDropdown(parent) Create a dropdown list. + void wgtDropdownSetItems(w, items, count) Set the list from a caller-owned const char ** array. + int32_t wgtDropdownGetSelected(w) Get the index of the selected item (-1 if none). + void wgtDropdownSetSelected(w, idx) Set the selected item by index. + void wgtDropdownAddItem(w, text) Append an owned item (strdup'd). + void wgtDropdownRemoveItem(w, idx) Remove an owned item by index. + void wgtDropdownClear(w) Remove all owned items. + const char *wgtDropdownGetItem(w, idx) Get the text of an item by index. + int32_t wgtDropdownGetItemCount(w) Get the total number of items.+
API Struct (wgtRegisterApi "dropdown")
+Slot Function + ---- -------- + create wgtDropdown + setItems wgtDropdownSetItems + getSelected wgtDropdownGetSelected + setSelected wgtDropdownSetSelected + addItem wgtDropdownAddItem + removeItem wgtDropdownRemoveItem + clear wgtDropdownClear + getItem wgtDropdownGetItem + getItemCount wgtDropdownGetItemCount+
Properties (BASIC Interface)
+Property Type Access Description + -------- ---- ------ ----------- + ListIndex Integer Read/Write Index of the currently selected item (-1 if none).+
Methods (BASIC Interface)
+Method Description + ------ ----------- + AddItem text$ Append an item to the drop-down list. + Clear Remove all items. + List(index%) Return the text of the item at the given index. + ListCount() Return the total number of items. + RemoveItem index% Remove the item at the given index.
Events
Callback Description -------- ----------- onChange Fires when the selected item changes.-
Properties (BASIC Interface)
-Property Type Access Description - -------- ---- ------ ----------- - ListIndex Integer Read/Write Index of the currently selected item.+
Default Event
+"Click" (VB basName: DropDown).
ImageButton
-A clickable button that displays an image instead of text. Has press/release visual feedback like a regular button. Can be created from raw pixel data or a BMP file.
-Header: widgets/widgetImageButton.h
+A clickable button that displays an image instead of text. Has the same press/release visual feedback and focus handling as a regular Button. Can be created from raw pixel data or loaded from an image file. Typically used to populate a Toolbar.
+Header: widgets/imgBtn.h
Creation
-Macro Description - ----- ----------- - wgtImageButton(parent, data, w, h, pitch) Create an image button from raw pixel data. - wgtImageButtonFromFile(parent, path) Create an image button by loading a BMP file.-
Methods
-Macro Description - ----- ----------- - wgtImageButtonSetData(w, data, imgW, imgH, pitch) Replace the image with new raw pixel data. - wgtImageButtonLoadFile(w, path) Replace the image by loading a new file.-
Events
-Callback Description - -------- ----------- - onClick Fires when the image button is clicked (press + release).+
WidgetT *btn = wgtImageButtonFromFile(parent, "icons/save.bmp");
+btn->onClick = onSaveClicked;
+API Functions
+Function Description + -------- ----------- + WidgetT *wgtImageButton(parent, data, w, h, pitch) Create from raw pixel data (in display's native format). + WidgetT *wgtImageButtonFromFile(parent, path) Create by loading an image file. + void wgtImageButtonSetData(w, data, imgW, imgH, pitch) Replace the image with new raw pixel data. + void wgtImageButtonLoadFile(w, path) Replace the image by loading a new file.+
API Struct (wgtRegisterApi "imagebutton")
+Slot Function + ---- -------- + create wgtImageButton + fromFile wgtImageButtonFromFile + setData wgtImageButtonSetData + loadFile wgtImageButtonLoadFile
Properties (BASIC Interface)
Property Type Access Description -------- ---- ------ ----------- - Picture String Write-only Load an image from a file path. + Picture String Read/Write Setting writes a file path (loads image). Reading returns the current path. ImageWidth Integer Read-only Width of the currently loaded image in pixels. ImageHeight Integer Read-only Height of the currently loaded image in pixels.-
+
Methods
+No widget-specific BASIC methods. Setting Picture loads a new image.
+Events
+Callback Description + -------- ----------- + onClick Fires when the image button is clicked (press and release inside).+
Default Event
+"Click" (VB basName: ImageButton).
Image
-Displays a bitmap image. Can be created from raw pixel data or loaded from a BMP file on disk. The image is rendered at its natural size within the widget bounds.
-Header: widgets/widgetImage.h
+Displays a bitmap image. Can be created from raw pixel data or loaded from a file on disk (BMP/PNG/etc. via dvxLoadImage). Supports optional stretching to fill the widget and transparent color keys for chroma-key style masking.
+Header: widgets/image.h
Creation
-Macro Description - ----- ----------- - wgtImage(parent, data, w, h, pitch) Create an image widget from raw pixel data. data is a uint8_t * pixel buffer, w/h are dimensions, pitch is bytes per row. - wgtImageFromFile(parent, path) Create an image widget by loading a BMP file from disk.+
WidgetT *img = wgtImageFromFile(parent, "logo.bmp");
+// or from raw pixels:
+// WidgetT *img = wgtImage(parent, pixelData, w, h, pitch);
+API Functions
+Function Description + -------- ----------- + WidgetT *wgtImage(parent, data, w, h, pitch) Create from raw pixel data (in display's native format). + WidgetT *wgtImageFromFile(parent, path) Create by loading an image file. + void wgtImageSetData(w, data, imgW, imgH, pitch) Replace the displayed image with new raw pixel data. + void wgtImageLoadFile(w, path) Replace by loading a new file. Static but exposed via the API struct. + void wgtImageSetTransparent(w, hasTransparency, keyColor) Set chroma-key color. Pixels matching keyColor are not drawn.+
API Struct (wgtRegisterApi "image")
+Slot Function + ---- -------- + create wgtImage + fromFile wgtImageFromFile + setData wgtImageSetData + loadFile wgtImageLoadFile + setTransparent wgtImageSetTransparent+
Properties (BASIC Interface)
+Property Type Access Description + -------- ---- ------ ----------- + Picture String Read/Write Setting writes a file path (loads image). Reading returns the current path. + Stretch Boolean Read/Write When true, the image stretches to fill the widget; when false, shown at natural size. + ImageWidth Integer Read-only Width of the currently loaded image in pixels. + ImageHeight Integer Read-only Height of the currently loaded image in pixels.
Methods
-Macro Description - ----- ----------- - wgtImageSetData(w, data, imgW, imgH, pitch) Replace the displayed image with new raw pixel data. - wgtImageLoadFile(w, path) Replace the displayed image by loading a new file.+
No widget-specific BASIC methods. Setting Picture loads a new image.
Events
Callback Description -------- ----------- onClick Fires when the image is clicked.-
Properties (BASIC Interface)
-Property Type Access Description - -------- ---- ------ ----------- - Picture String Write-only Load an image from a file path. - ImageWidth Integer Read-only Width of the currently loaded image in pixels. - ImageHeight Integer Read-only Height of the currently loaded image in pixels.+
Default Event
+"Click" (VB basName: Image).
Label
-A static text label. Does not accept keyboard focus. Typically used to describe other widgets. Supports text alignment and accelerator keys (with WCLASS_FOCUS_FORWARD, the accelerator moves focus to the next focusable sibling).
-Header: widgets/widgetLabel.h
+A static text label. Does not accept keyboard focus directly, but supports accelerator keys that forward focus to the next focusable sibling (WCLASS_FOCUS_FORWARD). Useful for describing other widgets. Supports left, center, and right text alignment.
+Header: widgets/label.h
Creation
-WidgetT *lbl = wgtLabel(parent, "Name:");
-Macros
-Macro Description - ----- ----------- - wgtLabel(parent, text) Create a text label. - wgtLabelSetAlign(w, align) Set the text alignment (AlignStartE, AlignCenterE, AlignEndE).-
Properties
-Use wgtSetText() / wgtGetText() to change the text. Set accelKey for accelerator support (focus forwards to next focusable widget).
-Events
-Labels use the common events only. Typically no callbacks are set on labels.
+WidgetT *lbl = wgtLabel(parent, "&Name:");
+API Functions
+Function Description + -------- ----------- + WidgetT *wgtLabel(parent, text) Create a text label. + void wgtLabelSetAlign(w, align) Set the text alignment (AlignStartE = left, AlignCenterE = center, AlignEndE = right). + WidgetAlignE wgtLabelGetAlign(w) Get the current text alignment.+
API Struct (wgtRegisterApi "label")
+Slot Function + ---- -------- + create wgtLabel + setAlign wgtLabelSetAlign
Properties (BASIC Interface)
Property Type Access Description -------- ---- ------ ----------- Alignment Enum (Left, Center, Right) Read/Write Text alignment within the label.-
+
Label text is managed via the standard wgtSetText() / wgtGetText() interface. BASIC code uses the generic "Caption" or "Text" property. Place an '&' before a character in the caption to mark an accelerator key.
+Methods
+No widget-specific methods.
+Events
+Labels are not focusable, so they typically have no event callbacks. The common onClick callback will fire if the label is clicked.
+Default Event
+"Click" (VB basName: Label).
ListBox
-A scrollable list of text items. Supports single and multi-selection modes and drag-to-reorder.
-Header: widgets/widgetListBox.h
+A scrollable list of text items. Supports single and multi-select modes (Shift-click for range, Ctrl-click to toggle), drag-to-reorder, mouse wheel scroll, and keyboard navigation (Up/Down/PgUp/PgDn/Home/End with type-ahead search on printable keys). Depends on the "listhelp" helper library (declared in listbox.dep).
+Items can either be set from a caller-owned array (wgtListBoxSetItems) or managed internally via AddItem/RemoveItem/Clear. The two modes are mutually exclusive per widget.
+Header: widgets/listBox.h
Creation
WidgetT *lb = wgtListBox(parent);
-const char *items[] = { "Alpha", "Beta", "Gamma" };
-wgtListBoxSetItems(lb, items, 3);
-Macros
-Macro Description - ----- ----------- - wgtListBox(parent) Create a list box. - wgtListBoxSetItems(w, items, count) Set the list items. - wgtListBoxGetSelected(w) Get the index of the selected item (-1 if none). - wgtListBoxSetSelected(w, idx) Set the selected item by index. - wgtListBoxSetMultiSelect(w, multi) Enable or disable multi-selection mode. - wgtListBoxIsItemSelected(w, idx) Check if a specific item is selected (multi-select mode). - wgtListBoxSetItemSelected(w, idx, selected) Select or deselect a specific item. - wgtListBoxSelectAll(w) Select all items (multi-select mode). - wgtListBoxClearSelection(w) Deselect all items. - wgtListBoxSetReorderable(w, reorderable) Enable drag-to-reorder.+wgtListBoxAddItem(lb, "Alpha"); +wgtListBoxAddItem(lb, "Beta"); +wgtListBoxAddItem(lb, "Gamma"); +
API Functions
+Function Description + -------- ----------- + WidgetT *wgtListBox(parent) Create a list box. + void wgtListBoxSetItems(w, items, count) Set items from a caller-owned const char ** array. + int32_t wgtListBoxGetSelected(w) Get the primary selected index (-1 if none). + void wgtListBoxSetSelected(w, idx) Set the selected index. Scrolls the item into view. + void wgtListBoxSetMultiSelect(w, multi) Enable or disable multi-select mode. + bool wgtListBoxIsItemSelected(w, idx) Returns true if the item is selected (multi-select mode). + void wgtListBoxSetItemSelected(w, idx, selected) Select or deselect a specific item (multi-select mode). + void wgtListBoxSelectAll(w) Select every item (multi-select mode). + void wgtListBoxClearSelection(w) Deselect all items. + void wgtListBoxSetReorderable(w, r) Enable drag-to-reorder of items. + void wgtListBoxAddItem(w, text) Append an owned item (strdup'd). + void wgtListBoxRemoveItem(w, idx) Remove an owned item by index. + void wgtListBoxClear(w) Remove all owned items. + const char *wgtListBoxGetItem(w, idx) Get the text of an item by index. + int32_t wgtListBoxGetItemCount(w) Get the total number of items.+
API Struct (wgtRegisterApi "listbox")
+Slot Function + ---- -------- + create wgtListBox + setItems wgtListBoxSetItems + getSelected wgtListBoxGetSelected + setSelected wgtListBoxSetSelected + setMultiSelect wgtListBoxSetMultiSelect + isItemSelected wgtListBoxIsItemSelected + setItemSelected wgtListBoxSetItemSelected + selectAll wgtListBoxSelectAll + clearSelection wgtListBoxClearSelection + setReorderable wgtListBoxSetReorderable + addItem wgtListBoxAddItem + removeItem wgtListBoxRemoveItem + clear wgtListBoxClear + getItem wgtListBoxGetItem + getItemCount wgtListBoxGetItemCount+
Properties (BASIC Interface)
+Property Type Access Description + -------- ---- ------ ----------- + ListIndex Integer Read/Write Index of the currently selected item.+
Methods (BASIC Interface)
+Method Description + ------ ----------- + AddItem text$ Append an item. + Clear Remove all items. + ClearSelection Deselect all items. + IsItemSelected(index%) Returns True if the item is selected (multi-select mode). + List(index%) Return the text of the item at the given index. + ListCount() Return the total number of items. + RemoveItem index% Remove the item at the given index. + SelectAll Select all items. + SetItemSelected index%, sel Select or deselect a specific item. + SetItems spec$ Bulk-load items from a pipe-delimited string (e.g. "Red|Green|Blue"); replaces existing items. + SetMultiSelect multi Enable or disable multi-select mode. + SetReorderable r Enable or disable drag-to-reorder.
Events
Callback Description -------- ----------- onClick Fires when an item is clicked. onDblClick Fires when an item is double-clicked. onChange Fires when the selection changes.-
Properties (BASIC Interface)
-Property Type Access Description - -------- ---- ------ ----------- - ListIndex Integer Read/Write Index of the currently selected item.-
Methods (BASIC Interface)
-Method Description - ------ ----------- - SelectAll Select all items. - ClearSelection Deselect all items. - SetMultiSelect Enable or disable multi-selection. - SetReorderable Enable or disable drag-to-reorder. - IsItemSelected Check if a specific item is selected by index. - SetItemSelected Select or deselect a specific item by index.-
+
Default Event
+"Click" (VB basName: ListBox).
ListView
A multi-column list with sortable headers. Supports single and multi-selection, column alignment, header click sorting, and drag-to-reorder. Data is provided as a flat array of strings (row-major order, one string per cell).
-Header: widgets/widgetListView.h
+Header: widgets/listView.h
Creation
WidgetT *lv = wgtListView(parent);
ListViewColT cols[] = {
@@ -4883,168 +6617,243 @@ wgtListViewSetData(lv, cells, 2);
-------- ---- ------ -----------
ListIndex Integer Read/Write Index of the currently selected row.
Methods (BASIC Interface)
-Method Description - ------ ----------- - SelectAll Select all rows. - ClearSelection Deselect all rows. - SetMultiSelect Enable or disable multi-selection. - SetReorderable Enable or disable drag-to-reorder. - IsItemSelected Check if a specific row is selected by index. - SetItemSelected Select or deselect a specific row by index.-
+
Method Description
+ ------ -----------
+ AddItem text$ Add a row (sets first column text).
+ Clear Remove all rows.
+ ClearSelection Deselect all rows.
+ GetCell(row%, col%) Returns the text of a cell.
+ IsItemSelected(index%) Check if a specific row is selected.
+ RemoveItem index% Remove a row by index.
+ RowCount() Returns the number of rows.
+ SelectAll Select all rows.
+ SetCell row%, col%, text$ Set the text of a cell.
+ SetColumns spec$ Define columns from a pipe-delimited spec string ("Name,Width|Name,Width").
+ SetItemSelected idx%, sel Select or deselect a specific row by index.
+ SetMultiSelect multi Enable or disable multi-selection.
+ SetReorderable reorderable Enable or disable drag-to-reorder.
+ SetSort col%, dir% Set the sort column and direction (0=none, 1=ascending, 2=descending).
+Default Event
+"Click" (VB basName: ListView).
ProgressBar
A visual indicator of progress, displayed as a filled bar. Supports both horizontal and vertical orientations. Value ranges from 0 to 100.
-Header: widgets/widgetProgressBar.h
+Header: widgets/progress.h
Creation
Macro Description ----- ----------- wgtProgressBar(parent) Create a horizontal progress bar. wgtProgressBarV(parent) Create a vertical progress bar.-
Methods
-Macro Description - ----- ----------- - wgtProgressBarSetValue(w, value) Set the progress value (0-100). - wgtProgressBarGetValue(w) Get the current progress value.-
Events
-ProgressBar is a display-only widget. Typically no callbacks are set.
+API Functions
+Function Description + -------- ----------- + WidgetT *wgtProgressBar(parent) Create a horizontal progress bar. + WidgetT *wgtProgressBarV(parent) Create a vertical progress bar. + void wgtProgressBarSetValue(w, val) Set the progress value (0-100). Clamped to 0..maxValue. + int32_t wgtProgressBarGetValue(w) Get the current progress value.+
API Struct (wgtRegisterApi "progressbar")
+Slot Function + ---- -------- + create wgtProgressBar + createV wgtProgressBarV + setValue wgtProgressBarSetValue + getValue wgtProgressBarGetValue
Properties (BASIC Interface)
Property Type Access Description -------- ---- ------ ----------- Value Integer Read/Write Current progress value (0-100).-
+
Methods
+No widget-specific methods.
+Events
+ProgressBar is a display-only widget. Typically no callbacks are set.
+Default Event
+None. (VB basName: ProgressBar.)
Radio Button
A mutually exclusive selection control. Radio buttons must be placed inside a radio group container. Only one radio button within a group can be selected at a time.
-Header: widgets/widgetRadio.h
+Header: widgets/radio.h
Creation
WidgetT *grp = wgtRadioGroup(parent);
WidgetT *r1 = wgtRadio(grp, "Option A");
WidgetT *r2 = wgtRadio(grp, "Option B");
-Macros
-Macro Description - ----- ----------- - wgtRadioGroup(parent) Create a radio group container. - wgtRadio(parent, text) Create a radio button inside a group. - wgtRadioGroupSetSelected(w, idx) Set the selected radio button by index within the group. - wgtRadioGetIndex(w) Get the index of the currently selected radio button.+
API Functions
+Function Description + -------- ----------- + WidgetT *wgtRadioGroup(parent) Create a radio group container. + WidgetT *wgtRadio(parent, text) Create a radio button inside a group. + void wgtRadioGroupSetSelected(group, idx) Set the selected radio button by index within the group. + int32_t wgtRadioGetIndex(w) Get the index of this radio button within its group.+
API Struct (wgtRegisterApi "radio")
+Slot Function + ---- -------- + group wgtRadioGroup + create wgtRadio + groupSetSelected wgtRadioGroupSetSelected + getIndex wgtRadioGetIndex+
Properties (BASIC Interface)
+Property Type Access Description + -------- ---- ------ ----------- + Value Integer Read-only Index of this radio button within its group.+
Caption is managed via the standard wgtSetText() / wgtGetText() interface (WCLASS_HAS_TEXT).
+Methods (BASIC Interface)
+Method Description + ------ ----------- + SetSelected idx% Set the selected radio button by index within the group.
Events
Callback Description -------- ----------- onClick Fires on the radio button when clicked. onChange Fires when the selection changes.-
Properties (BASIC Interface)
-Property Type Access Description - -------- ---- ------ ----------- - Value Integer Read-only Index of the currently selected radio button in the group.-
Methods (BASIC Interface)
-Method Description - ------ ----------- - SetSelected Set the selected radio button by index.-
+
Default Event
+"Click" (VB basName: OptionButton, namePrefix: Option).
ScrollPane
A scrollable container that provides vertical and/or horizontal scrollbars when its content exceeds the visible area. Place a single child (typically a VBox or HBox) inside the scroll pane.
-Header: widgets/widgetScrollPane.h
+Header: widgets/scrlPane.h
Creation
WidgetT *sp = wgtScrollPane(parent);
WidgetT *content = wgtVBox(sp);
// add children to content...
-Macros
-Macro Description - ----- ----------- - wgtScrollPane(parent) Create a scroll pane container. - wgtScrollPaneScrollToChild(sp, child) Scroll so that the given child widget is visible. - wgtScrollPaneSetNoBorder(w, noBorder) When true, removes the border around the scroll pane.-
Events
-Callback Description - -------- ----------- - onScroll Fires when the scroll position changes.+
API Functions
+Function Description + -------- ----------- + WidgetT *wgtScrollPane(parent) Create a scroll pane container. + void wgtScrollPaneScrollToChild(sp, child) Scroll so that the given child widget is visible. + void wgtScrollPaneScrollToTop(w) Scroll back to the top-left of the content. + void wgtScrollPaneSetNoBorder(w, noBorder) When true, removes the border around the scroll pane.+
API Struct (wgtRegisterApi "scrollpane")
+Slot Function + ---- -------- + create wgtScrollPane + scrollToChild wgtScrollPaneScrollToChild + setNoBorder wgtScrollPaneSetNoBorder + scrollToTop wgtScrollPaneScrollToTop
Properties (BASIC Interface)
Property Type Access Description -------- ---- ------ ----------- NoBorder Boolean Read/Write Whether the border around the scroll pane is hidden.-
+
Methods
+No widget-specific methods.
+Events
+Callback Description + -------- ----------- + onScroll Fires when the scroll position changes.+
Default Event
+None. (VB basName: ScrollPane, namePrefix: Scroll.)
Separator
A visual dividing line used to separate groups of widgets. Available in horizontal and vertical orientations.
-Header: widgets/widgetSeparator.h
-Creation
-Macro Description - ----- ----------- - wgtHSeparator(parent) Create a horizontal separator line. - wgtVSeparator(parent) Create a vertical separator line.+
Header: widgets/separatr.h
+API Functions
+Function Description + -------- ----------- + WidgetT *wgtHSeparator(parent) Create a horizontal separator line. + WidgetT *wgtVSeparator(parent) Create a vertical separator line.+
API Struct (wgtRegisterApi "separator")
+Slot Function + ---- -------- + hSeparator wgtHSeparator + vSeparator wgtVSeparator+
Properties
+No widget-specific properties.
+Methods
+No widget-specific methods.
Events
Separator is a visual-only widget. No events.
-+
Default Event
+None. (VB basName: Line.)
Slider
A horizontal slider (track bar) for selecting an integer value within a range. The user drags the thumb or clicks the track to change the value.
-Header: widgets/widgetSlider.h
+Header: widgets/slider.h
Creation
WidgetT *sl = wgtSlider(parent, 0, 100);
-Macros
-Macro Description - ----- ----------- - wgtSlider(parent, minVal, maxVal) Create a slider with the given integer range. - wgtSliderSetValue(w, value) Set the slider value programmatically. - wgtSliderGetValue(w) Get the current slider value.-
Events
-Callback Description - -------- ----------- - onChange Fires when the slider value changes.+
API Functions
+Function Description + -------- ----------- + WidgetT *wgtSlider(parent, minVal, maxVal) Create a slider with the given integer range. + void wgtSliderSetValue(w, value) Set the slider value programmatically. + int32_t wgtSliderGetValue(w) Get the current slider value.+
API Struct (wgtRegisterApi "slider")
+Slot Function + ---- -------- + create wgtSlider + setValue wgtSliderSetValue + getValue wgtSliderGetValue
Properties (BASIC Interface)
Property Type Access Description -------- ---- ------ ----------- Value Integer Read/Write Current slider value.-
+
Methods
+No widget-specific methods.
+Events
+Callback Description + -------- ----------- + onChange Fires when the slider value changes.+
Default Event
+"Change" (VB basName: HScrollBar, namePrefix: HScroll).
Spacer
An invisible widget used for layout purposes. By default it has weight=100, so it absorbs available extra space. Useful for pushing other widgets apart or aligning them to edges.
-Header: widgets/widgetSpacer.h
+Header: widgets/spacer.h
Creation
WidgetT *row = wgtHBox(parent);
wgtButton(row, "OK");
wgtSpacer(row); // pushes Cancel to the right
wgtButton(row, "Cancel");
-Macro
-Macro Description - ----- ----------- - wgtSpacer(parent) Create an invisible spacer widget.-
Events
-Spacer is an invisible layout widget. No events.
-+
API Functions
+Function Description + -------- ----------- + WidgetT *wgtSpacer(parent) Create an invisible spacer widget.+
API Struct (wgtRegisterApi "spacer")
+Slot Function + ---- -------- + create wgtSpacer+
Properties, Methods, Events
+Spacer is an invisible layout widget. No type-specific properties, methods, or events.
+Default Event
+None. (VB basName: Spacer.)
Spinner
A numeric input with up/down buttons for incrementing and decrementing a value within a range. Supports both integer and floating-point (real) modes.
-Header: widgets/widgetSpinner.h
+Header: widgets/spinner.h
Creation
WidgetT *sp = wgtSpinner(parent, 0, 100, 1);
-Macros
-Macro Description - ----- ----------- - wgtSpinner(parent, minVal, maxVal, step) Create a spinner with the given integer range and step size. - wgtSpinnerSetValue(w, value) Set the integer value. - wgtSpinnerGetValue(w) Get the current integer value. - wgtSpinnerSetRange(w, minVal, maxVal) Set the integer range. - wgtSpinnerSetStep(w, step) Set the integer step size. - wgtSpinnerSetRealMode(w, enable) Switch to floating-point mode. - wgtSpinnerGetRealValue(w) Get the current floating-point value. - wgtSpinnerSetRealValue(w, value) Set the floating-point value. - wgtSpinnerSetRealRange(w, minVal, maxVal) Set the floating-point range. - wgtSpinnerSetRealStep(w, step) Set the floating-point step size. - wgtSpinnerSetDecimals(w, decimals) Set the number of decimal places displayed in real mode.-
Events
-Callback Description - -------- ----------- - onChange Fires when the value changes.+
API Functions
+Function Description + -------- ----------- + WidgetT *wgtSpinner(parent, minVal, maxVal, step) Create a spinner with the given integer range and step size. + void wgtSpinnerSetValue(w, value) Set the integer value. + int32_t wgtSpinnerGetValue(w) Get the current integer value. + void wgtSpinnerSetRange(w, minVal, maxVal) Set the integer range. + void wgtSpinnerSetStep(w, step) Set the integer step size. + void wgtSpinnerSetRealMode(w, enable) Switch to floating-point mode. + double wgtSpinnerGetRealValue(w) Get the current floating-point value. + void wgtSpinnerSetRealValue(w, value) Set the floating-point value. + void wgtSpinnerSetRealRange(w, minVal, maxVal) Set the floating-point range. + void wgtSpinnerSetRealStep(w, step) Set the floating-point step size. + void wgtSpinnerSetDecimals(w, decimals) Set the number of decimal places displayed in real mode.+
API Struct (wgtRegisterApi "spinner")
+Slot Function + ---- -------- + create wgtSpinner + setValue wgtSpinnerSetValue + getValue wgtSpinnerGetValue + setRange wgtSpinnerSetRange + setStep wgtSpinnerSetStep + setRealMode wgtSpinnerSetRealMode + getRealValue wgtSpinnerGetRealValue + setRealValue wgtSpinnerSetRealValue + setRealRange wgtSpinnerSetRealRange + setRealStep wgtSpinnerSetRealStep + setDecimals wgtSpinnerSetDecimals
Properties (BASIC Interface)
Property Type Access Description -------- ---- ------ ----------- @@ -5052,87 +6861,112 @@ wgtButton(row, "Cancel");RealMode Boolean Read/Write Whether floating-point mode is active. Decimals Integer Read/Write Number of decimal places displayed in real mode.
Methods (BASIC Interface)
-Method Description - ------ ----------- - SetRange Set the integer range (min, max). - SetStep Set the integer step size.-
+
Method Description + ------ ----------- + SetRange min%, max% Set the integer range. + SetStep step% Set the integer step size.+
Events
+Callback Description + -------- ----------- + onChange Fires when the value changes.+
Default Event
+"Change" (VB basName: SpinButton, namePrefix: Spin).
Splitter
A two-pane container with a draggable divider. The user drags the splitter bar to resize the two panes. Can be oriented vertically (left/right panes) or horizontally (top/bottom panes). Add exactly two children.
-Header: widgets/widgetSplitter.h
+Header: widgets/splitter.h
Creation
WidgetT *sp = wgtSplitter(parent, true); // vertical = left|right
WidgetT *left = wgtVBox(sp);
WidgetT *right = wgtVBox(sp);
-Macros
-Macro Description - ----- ----------- - wgtSplitter(parent, vertical) Create a splitter. vertical=true for left/right panes, false for top/bottom. - wgtSplitterSetPos(w, pos) Set the divider position in pixels. - wgtSplitterGetPos(w) Get the current divider position in pixels.-
Events
-Callback Description - -------- ----------- - onChange Fires when the divider position changes.+
API Functions
+Function Description + -------- ----------- + WidgetT *wgtSplitter(parent, vertical) Create a splitter. vertical=true for left/right panes (vertical divider), false for top/bottom. + void wgtSplitterSetPos(w, pos) Set the divider position in pixels from the leading edge. + int32_t wgtSplitterGetPos(w) Get the current divider position in pixels.+
API Struct (wgtRegisterApi "splitter")
+Slot Function + ---- -------- + create wgtSplitter + setPos wgtSplitterSetPos + getPos wgtSplitterGetPos
Properties (BASIC Interface)
Property Type Access Description -------- ---- ------ ----------- Position Integer Read/Write Divider position in pixels.-
+
Methods
+No widget-specific methods.
+Events
+Splitter has no widget-specific events. Common events apply.
+Default Event
+None. (VB basName: Splitter.)
StatusBar
A horizontal bar typically placed at the bottom of a window for displaying status text and informational widgets. Children are laid out horizontally.
-Header: widgets/widgetStatusBar.h
+Header: widgets/statBar.h
Creation
WidgetT *sb = wgtStatusBar(parent);
wgtLabel(sb, "Ready");
-Macro
-Macro Description - ----- ----------- - wgtStatusBar(parent) Create a status bar container.-
Properties
-Uses common container properties. Add child widgets (labels, progress bars, etc.) to populate.
-Events
-StatusBar itself has no widget-specific events. Events fire on the child widgets.
-+
API Functions
+Function Description + -------- ----------- + WidgetT *wgtStatusBar(parent) Create a status bar container.+
API Struct (wgtRegisterApi "statusbar")
+Slot Function + ---- -------- + create wgtStatusBar+
Properties, Methods, Events
+StatusBar has no widget-specific properties, methods, or events. Add child widgets (labels, progress bars, etc.) to populate.
+Default Event
+None. (VB basName: StatusBar.)
TabControl
A tabbed container that displays one page at a time with clickable tabs along the top. Each tab page is a container that holds its own child widgets.
-Header: widgets/widgetTabControl.h
+Header: widgets/tabCtrl.h
Creation
WidgetT *tabs = wgtTabControl(parent);
WidgetT *page1 = wgtTabPage(tabs, "General");
WidgetT *page2 = wgtTabPage(tabs, "Advanced");
// add children to page1, page2...
-Macros
-Macro Description - ----- ----------- - wgtTabControl(parent) Create a tab control. - wgtTabPage(parent, title) Add a tab page with the given title. Returns the page container widget. - wgtTabControlSetActive(w, idx) Set the active tab by index (0-based). - wgtTabControlGetActive(w) Get the index of the active tab.-
Events
-Callback Description - -------- ----------- - onChange Fires when the active tab changes.+
API Functions
+Function Description + -------- ----------- + WidgetT *wgtTabControl(parent) Create a tab control. + WidgetT *wgtTabPage(parent, title) Add a tab page with the given title. Returns the page container widget. + void wgtTabControlSetActive(w, idx) Set the active tab by index (0-based). + int32_t wgtTabControlGetActive(w) Get the index of the active tab.+
API Struct (wgtRegisterApi "tabcontrol")
+Slot Function + ---- -------- + create wgtTabControl + page wgtTabPage + setActive wgtTabControlSetActive + getActive wgtTabControlGetActive
Properties (BASIC Interface)
Property Type Access Description -------- ---- ------ ----------- TabIndex Integer Read/Write Index of the currently active tab (0-based).
Methods (BASIC Interface)
-Method Description - ------ ----------- - SetActive Set the active tab by index.-
+
Method Description + ------ ----------- + AddPage title$ Add a new tab page with the given title. + GetActive() Returns the index of the active tab. + SetActive idx% Set the active tab by index (0-based).+
Events
+Callback Description + -------- ----------- + onChange Fires when the active tab changes.+
Default Event
+"Click" (VB basName: TabStrip).
TextInput / TextArea
Single-line text input, password input, masked input, and multi-line text area with optional syntax colorization, line numbers, find/replace, and gutter decorators.
-Header: widgets/widgetTextInput.h
+Header: widgets/textInpt.h
Creation
Macro Description ----- ----------- @@ -5140,55 +6974,89 @@ WidgetT *page2 = wgtTabPage(tabs, "Advanced"); wgtPasswordInput(parent, maxLen) Create a password input (characters displayed as bullets). wgtMaskedInput(parent, mask) Create a masked input field. The mask string defines the input format. wgtTextArea(parent, maxLen) Create a multi-line text area.-
Methods (TextArea-specific)
-Macro Description - ----- ----------- - wgtTextAreaSetColorize(w, fn, ctx) Set a syntax colorization callback. The callback receives each line and fills a color index array. Color indices: 0=default, 1=keyword, 2=string, 3=comment, 4=number, 5=operator, 6=type/builtin, 7=reserved. - wgtTextAreaGoToLine(w, line) Scroll to and place the cursor on the given line number. - wgtTextAreaSetAutoIndent(w, enable) Enable or disable automatic indentation on newline. - wgtTextAreaSetShowLineNumbers(w, show) Show or hide line numbers in the gutter. - wgtTextAreaSetCaptureTabs(w, capture) When true, Tab key inserts a tab/spaces instead of moving focus. - wgtTextAreaSetTabWidth(w, width) Set the tab stop width in characters. - wgtTextAreaSetUseTabChar(w, useChar) When true, insert literal tab characters; when false, insert spaces. - wgtTextAreaFindNext(w, needle, caseSens, fwd) Search for the next occurrence. Returns true if found. - wgtTextAreaReplaceAll(w, needle, repl, caseSens) Replace all occurrences. Returns the number of replacements made. - wgtTextAreaSetLineDecorator(w, fn, ctx) Set a gutter line decorator callback. The callback returns a color and receives the line number, a color output pointer, and the user context. - wgtTextAreaGetCursorLine(w) Get the current cursor line number. - wgtTextAreaSetGutterClick(w, fn) Set a callback for gutter clicks (e.g. for breakpoint toggling). Callback receives the widget and line number.+
API Functions (TextArea-specific)
+Function Description + -------- ----------- + void wgtTextAreaSetColorize(w, fn, ctx) Set a syntax colorization callback. The callback receives each line and fills a color index array. + void wgtTextAreaGoToLine(w, line) Scroll to and place the cursor on the given line number. + void wgtTextAreaSetAutoIndent(w, enable) Enable or disable automatic indentation on newline. + void wgtTextAreaSetShowLineNumbers(w, show) Show or hide line numbers in the gutter. + void wgtTextAreaSetCaptureTabs(w, capture) When true, Tab key inserts a tab/spaces instead of moving focus. + void wgtTextAreaSetTabWidth(w, width) Set the tab stop width in characters. + void wgtTextAreaSetUseTabChar(w, useChar) When true, insert literal tab characters; when false, insert spaces. + bool wgtTextAreaFindNext(w, needle, caseSens, fwd) Search for the next occurrence. Returns true if found. + int32_t wgtTextAreaReplaceAll(w, needle, repl, caseSens) Replace all occurrences. Returns the number of replacements made. + void wgtTextAreaSetLineDecorator(w, fn, ctx) Set a gutter line decorator callback. Returns a color and receives the line number. + int32_t wgtTextAreaGetCursorLine(w) Get the current cursor line number. + void wgtTextAreaSetGutterClickCallback(w, fn) Set a callback for gutter clicks (e.g. for breakpoint toggling). + int32_t wgtTextAreaGetWordAtCursor(w, buf, bufSize) Copy the word under the cursor into buf. Returns its length. + void wgtTextAreaSetSyntaxColors(w, colors, count) Set the color palette used by the colorizer.+
API Struct (wgtRegisterApi "textinput")
+The combined "textinput" API exposes all four constructors plus the TextArea functions. The designer uses per-type APIs registered under the names "textbox" (single-line) and "textarea" (multi-line), each exposing only a create slot.
+Properties (BASIC Interface)
+TextBox has no widget-specific properties. Text is managed via the generic "Text" property. TextArea exposes:
+Property Type Access Description + -------- ---- ------ ----------- + CursorLine Integer Read-only Current cursor line number (0-based).+
Methods (BASIC Interface, TextArea)
+Method Description + ------ ----------- + FindNext needle$, caseSensitive, forward Search for the next occurrence. Returns True if found. + GetWordAtCursor() Returns the word under the cursor. + GoToLine line% Scroll to and position the cursor on a line. + ReplaceAll needle$, replacement$, caseSensitive Replace all occurrences. Returns the count. + SetAutoIndent enabled Enable or disable automatic indentation on newline. + SetCaptureTabs enabled When True, Tab inserts whitespace instead of moving focus. + SetShowLineNumbers show Show or hide line numbers in the gutter. + SetSyntaxMode mode$ Activate built-in syntax highlighting (e.g. "dhs", "bas"; "" to disable). + SetTabWidth width% Set the tab stop width in characters. + SetUseTabChar useChar When True, Tab inserts a literal tab; when False, spaces.
Events
Callback Description -------- ----------- onChange Fires when the text content changes. onKeyPress Fires on each key press (ASCII value). onValidate Called before committing a change. Return false to cancel.-
+
Default Event
+"Change" for both TextBox (basName: TextBox) and TextArea (basName: TextArea).
Timer
A non-visual widget that fires its onClick callback at a regular interval. Useful for animations, polling, and periodic updates. Must be explicitly started after creation.
-Header: widgets/widgetTimer.h
+Header: widgets/timer.h
Creation
WidgetT *tmr = wgtTimer(parent, 1000, true); // 1 second, repeating
tmr->onClick = onTimerTick;
wgtTimerStart(tmr);
-Macros
-Macro Description - ----- ----------- - wgtTimer(parent, intervalMs, repeat) Create a timer. intervalMs is the interval in milliseconds. repeat: true for repeating, false for one-shot. - wgtTimerStart(w) Start the timer. - wgtTimerStop(w) Stop the timer. - wgtTimerSetInterval(w, intervalMs) Change the timer interval. - wgtTimerIsRunning(w) Returns true if the timer is currently running. - wgtUpdateTimers() Global tick function. Called by the event loop to advance all active timers.+
API Functions
+Function Description + -------- ----------- + WidgetT *wgtTimer(parent, intervalMs, repeat) Create a timer. intervalMs is the interval in milliseconds. repeat: true for repeating, false for one-shot. + void wgtTimerStart(w) Start the timer. + void wgtTimerStop(w) Stop the timer. + void wgtTimerSetInterval(w, intervalMs) Change the timer interval. + int32_t wgtTimerGetInterval(w) Returns the current interval in milliseconds. + bool wgtTimerIsRunning(w) Returns true if the timer is currently running. + void wgtTimerSetEnabled(w, enabled) Start or stop the timer based on enabled flag. + void wgtUpdateTimers(void) Global tick function. Called by the event loop to advance all active timers.+
API Struct (wgtRegisterApi "timer")
+Slot Function + ---- -------- + create wgtTimer + start wgtTimerStart + stop wgtTimerStop + setInterval wgtTimerSetInterval + isRunning wgtTimerIsRunning + updateTimers wgtUpdateTimers
Events
Callback Description -------- ----------- - onClick Fires each time the timer elapses.+ onClick Fires each time the timer elapses (the BASIC layer surfaces this as the "Timer" event).
Properties (BASIC Interface)
Property Type Access Description -------- ---- ------ ----------- Enabled Boolean Read/Write Whether the timer is running. Reading returns the running state; writing starts or stops it. - Interval Integer Write-only Timer interval in milliseconds.+ Interval Integer Read/Write Timer interval in milliseconds.
Methods (BASIC Interface)
Method Description ------ ----------- @@ -5203,69 +7071,101 @@ wgtTimerStart(tmr);
Toolbar
A horizontal container for toolbar buttons and controls. Typically placed at the top of a window. Children (usually ImageButtons or Buttons) are laid out horizontally with toolbar-appropriate spacing.
-Header: widgets/widgetToolbar.h
+Header: widgets/toolbar.h
Creation
WidgetT *tb = wgtToolbar(parent);
wgtImageButtonFromFile(tb, "icons/save.bmp");
wgtImageButtonFromFile(tb, "icons/open.bmp");
-Macro
-Macro Description - ----- ----------- - wgtToolbar(parent) Create a toolbar container.-
Properties
-Uses common container properties. Add children (buttons, separators, etc.) to populate the toolbar.
-Events
-Toolbar itself has no widget-specific events. Events fire on the child widgets.
-+
API Functions
+Function Description + -------- ----------- + WidgetT *wgtToolbar(parent) Create a toolbar container.+
API Struct (wgtRegisterApi "toolbar")
+Slot Function + ---- -------- + create wgtToolbar+
Properties, Methods, Events
+Toolbar has no widget-specific properties, methods, or events. Add children (buttons, separators, etc.) to populate.
+Default Event
+None. (VB basName: Toolbar.)
TreeView
A hierarchical tree control with expandable/collapsible nodes. Supports single and multi-selection and drag-to-reorder. Tree items are added as children of the TreeView or of other tree items to create nested hierarchies.
-Header: widgets/widgetTreeView.h
+Header: widgets/treeView.h
Creation
WidgetT *tv = wgtTreeView(parent);
WidgetT *root = wgtTreeItem(tv, "Root");
WidgetT *child = wgtTreeItem(root, "Child");
-Macros
-Macro Description - ----- ----------- - wgtTreeView(parent) Create a tree view control. - wgtTreeItem(parent, text) Add a tree item as a child of the tree view or another tree item. - wgtTreeViewGetSelected(w) Get the currently selected tree item (returns WidgetT *, NULL if none). - wgtTreeViewSetSelected(w, item) Set the selected tree item. - wgtTreeViewSetMultiSelect(w, multi) Enable or disable multi-selection. - wgtTreeViewSetReorderable(w, reorderable) Enable drag-to-reorder of items. - wgtTreeItemSetExpanded(w, expanded) Expand or collapse a tree item. - wgtTreeItemIsExpanded(w) Check if a tree item is expanded. - wgtTreeItemIsSelected(w) Check if a tree item is selected (multi-select mode). - wgtTreeItemSetSelected(w, selected) Select or deselect a tree item.+
API Functions
+Function Description + -------- ----------- + WidgetT *wgtTreeView(parent) Create a tree view control. + WidgetT *wgtTreeItem(parent, text) Add a tree item as a child of the tree view or another tree item. + WidgetT *wgtTreeViewGetSelected(w) Get the currently selected tree item (NULL if none). + void wgtTreeViewSetSelected(w, item) Set the selected tree item. + void wgtTreeViewSetMultiSelect(w, multi) Enable or disable multi-selection. + void wgtTreeViewSetReorderable(w, reorderable) Enable drag-to-reorder of items. + void wgtTreeItemSetExpanded(w, expanded) Expand or collapse a tree item. + bool wgtTreeItemIsExpanded(w) Check if a tree item is expanded. + bool wgtTreeItemIsSelected(w) Check if a tree item is selected (multi-select mode). + void wgtTreeItemSetSelected(w, selected) Select or deselect a tree item.+
API Struct (wgtRegisterApi "treeview")
+Slot Function + ---- -------- + create wgtTreeView + getSelected wgtTreeViewGetSelected + setSelected wgtTreeViewSetSelected + setMultiSelect wgtTreeViewSetMultiSelect + setReorderable wgtTreeViewSetReorderable + item wgtTreeItem + itemSetExpanded wgtTreeItemSetExpanded + itemIsExpanded wgtTreeItemIsExpanded + itemIsSelected wgtTreeItemIsSelected + itemSetSelected wgtTreeItemSetSelected+
Properties
+No widget-specific properties.
+Methods (BASIC Interface)
+Method Description + ------ ----------- + AddChildItem parentIdx%, text$ Add a child node under the node at the given index. + AddItem text$ Add a root-level node. + Clear Remove all nodes. + GetItemText(index%) Returns the text of the node at the given depth-first index. + IsExpanded(index%) Returns True if the node is expanded. + IsItemSelected(index%) Returns True if the node is selected. + ItemCount() Returns the total number of nodes. + SetExpanded index%, expanded Expand or collapse the node. + SetItemSelected index%, selected Select or deselect the node. + SetMultiSelect multi Enable or disable multi-selection. + SetReorderable reorderable Enable or disable drag-to-reorder.
Events
Callback Description -------- ----------- onClick Fires when a tree item is clicked. onDblClick Fires when a tree item is double-clicked. onChange Fires when the selection changes.-
Methods (BASIC Interface)
-Method Description - ------ ----------- - SetMultiSelect Enable or disable multi-selection. - SetReorderable Enable or disable drag-to-reorder.-
+
Default Event
+"Click" (VB basName: TreeView).
WrapBox
A flow/wrap layout container that arranges children left-to-right, wrapping to the next row when the available width is exceeded. Each row's height is the maximum child height in that row. Supports configurable spacing between items and rows, and per-row alignment for short rows.
-Header: widgets/widgetWrapBox.h
+Header: widgets/wrapBox.h
Creation
WidgetT *wrap = wgtWrapBox(parent);
wgtButton(wrap, "Tag 1");
wgtButton(wrap, "Tag 2");
wgtButton(wrap, "Tag 3");
-Macro
-Macro Description - ----- ----------- - wgtWrapBox(parent) Create a wrap box container.-
Properties
+API Functions
+Function Description + -------- ----------- + wgtWrapBox(parent) Create a wrap box container. Macro that calls the registered "wrapbox" create slot.+
API Struct (wgtRegisterApi "wrapbox")
+Slot Function + ---- -------- + create wrapBoxCreate+
Properties (Common Container Fields)
WrapBox uses the common WidgetT container fields for layout control:
Property Description -------- ----------- @@ -5275,8 +7175,12 @@ wgtButton(wrap, "Tag 3");
Property Type Access Description -------- ---- ------ ----------- Alignment Enum (Left, Center, Right) Read/Write Row alignment for rows that do not fill the full width.+
Methods
+No widget-specific methods.
Events
WrapBox is a container widget. It uses the common events only. No widget-specific events are defined.
+Default Event
+"Click" (VB basName: WrapBox, namePrefix: WrapBox).