23 February 2021

The Include directory

After installing GFA-BASIC 32 you’ll find four directories in the installation path: Bin, Doc, Include, and Samples.

image

The \Bin directory contains the GB32 binaries, the \Doc contains the original (German) doc-files that came with GFA-BASIC 32 back in 2001 (now obsolete because everything can be found in the English CHM helpfile), the \Include contains the Windows API include files, and the \Samples directory the samples g32 files, including the new Direct2D example programs.This time we’ll focus on the \Include directory only.

What is the \Include directory for?
The purpose of the \Include directory is to collect all Windows API definitions and declarations in one directory. Because of the huge amount of Windows APIs the definitions and declarations are split into multiple smaller include library files. These GB32 Windows API include-files come both with the source code and the compiled library (lg32) file. The organization of the GB32 include files follows the way the Windows SDK presents the C/C++ include header files. For instance, the C/C++ header file winuser.h has an equivalent GB32 include file winuser.inc.lg32. All include files follow this naming convention: name.inc.lg32.
You import a GB32 include library file using the $Library command, for instance:

$Library "winuser.inc"  ' .lg32 may be omitted

By default, the line doesn’t need to specify the full path, because the location of the \Include directory is pre-selected in the Properties | Extra tab dialog box.

image

You can easily add your own paths that contain your own library files. The entire string with the specified paths is stored in “lg32paths”registry key. To add a path first type a semicolon ; after the existing path and then specify the full path after the semicolon. Once a path is part of Library paths you do no longer need to type the full path in the $Library statement. Note that libraries are searched for (1) in the current program's directory, (2) in My Documents\lg32, and (3) in the paths stored in the registry key "lg32paths".

Note The \Include directory also contains the libraries gfawinx.lg32, direct2d.lg32 and variants.lg32. These are not include files and don’t have the .inc clause in their names. These are libraries that are part of the GFA-BASIC 32 updates and need an easily accessible path.

Why multiple include files?
Each include file contains only a part of the Windows API, that way you don’t need to include a single large file with many APIs just to have a few declarations. The GB32 include files only provide the APIs that are not built-in by GFA-BASIC32. (Note that the Win32API.g32 that originally came with GB is incomplete and full of errors.) Due to the amount of new APIs that come with each new Windows version, the include files in the \Include files aren’t complete either. They do however provide more declarations and definitions than the original Win32API.g32. Some of the include files are updated with the latest APIs (most specifically APIs supported by Win7 and Windows 10) like, for instance, winuser.inc.lg32. However, many haven’t been updated for a while. They tend to get an update on a ad hoc basis; when I need new APIs I add them to the include files. It is a boring job and, because of the translation from C/C++, errors are easily made. If you need an API that isn’t in one of the include library files yet, let me know (gfabasic32@gmail.com).

Contents of an include library
By default, the GB32 Windows include files only provide function declarations (Declare statements), constant definitions, and user-defined type definitions. They don’t contain executable code and besides the Declare’s they do not contribute to the size of the program. You should know that Declare-ed DLL functions are collected in a DLL-import table that do become part of the program (executable). By spreading the Declare’s over multiple include files the DLL-import table can remain small.
There is one “include” file that does contain executable code: winmacros.lib.lg32 (note the lacking .inc clause in the name). This library contains functions for often used Windows macros that are used as functions in C/C++, but are defined as macros in the C/C++ header files. Some of these function macros are collected into winmacros.lib.lg32. Among others, the library provides (Naked) functions for GET_X_PARAM, GET_Y_PARAM, MakeLParam, MakeIntResource, etc. Please take a look at the source code in winmacros.lib.g32 for an overview of the supported functions/macros.

How to locate a specific API
How do you know in which include file a specific API (type, constant, or function) is located? It might be that GB32 already supports the API as a built-in API, only function declarations and constant definitions. GB32 does not have built-in API support for user-defined API type definitions, they always have to be defined by the program or imported from an include library. The easiest way to check if GB32 supports a specific API is by using the auto-complete feature. Just type the first letters of the function or constant and check if the auto-complete pops up with the required name. If it isn’t provided by GB32 you’ll need to check the Windows SDK documentation to see which C/C++ include file provides the declaration or definition for that API and load the equivalent GB32 .inc library file.

An example of using an API
Each topic in the Windows SDK specifies in which C/C++ header file an API function, type, or constant is declared. For instance, if and API is located in the winuser.h C/C++ header file you have a big chance of finding it in the winuser.inc.lg32 file. Let’s look at an example. Suppose your program wants to process the WM_GETMINMAXINFO message. After looking up the documentation for this message, it tells you to obtain the  MINMAXINFO structure from the lParam. However, GB32 itself does not provide a definition for the MINMAXINFO user-defined type, and you need to import the type. When you go to the SDK page that describes this type you’ll find at the bottom of the page the location of the definition of this structure: the winuser.h C/C++ header file. Now you know which GB32 include library you need: winuser.inc and the program can import that library. As it happens this structure contains members of the API type POINT, which is defined in wingdi.inc. However, you won’t need to include wingdi.inc in your program, because it is imported by winuser.inc (otherwise it couldn’t be compiled). After importing winuser.inc in your program the constants and user-defined types from wingdi.inc are available as well. So, the POINT structure is available as a user-defined type in your program.

Note winuser.inc exports the constants and type definitions of wingdi.inc, but not the function declarations. If you need an API function declared in wingdi.inc you’ll need to import wingdi.inc as well. Importing both include files won’t collide with each other.

$Library "winuser.inc"
$Library "wingdi.inc"

Although both include files export the same constants and user-defined types they are added only once to the program. Now if winuser.inc would also export the function declares from wingdi.inc the internal database of GB32 may become corrupted. Therefor, winuser.inc exports all constants and types using the $Export Const * and $Export Type * statements, but the exported $Export Decl name statements must specify each exported declare separately. This is easily done using the App+E shortcut, it inserts $Export Decl lines for each Declare in the library file.

Conclusion
You can use the Windows API inc files to import Windows APIs easily. Because the (compiled) user-defined types are imported from a library the autocomplete function has direct access to their members and is fully operational without first compiling your program.

10 December 2020

Version 2.58 December 2020 Update

A new version of GFABASIC 32 is available now. It has a better auto complete that comes with a little help box for the listbox elements. In addition, version 2.58 has support for Direct2D, for developing multiple monitor applications, and comes with a new gfawinx library with new commands and functions. James Gaite did a good job by making the English CHM helpfile up-to-date with the latest information.

Auto complete
Version 2.58 improves on auto complete by doing a better job in showing relevant elements and by providing a little help box.

This (optional) help for auto complete displays the syntax and a small description of the GFABASIC 32 commands and functions. The syntax is also copied to the statusbar and remains visible to help in using the correct syntax even after the auto complete listbox has disappeared. The help is also displayed for the program’s procedures and functions, the lg32 procedures and functions, and the declared DLL functions. Their prototypes are both visible in the help box and in the statusbar.
New parsing routines made it possible to display real time help for variables in the auto complete listbox. The help box shows whether the constant or variable is local or global and constants display their current value. While most of information is obtained while editing, the only structure that needs compiling is a type (UDT) definition. The Type name and members need to present in the internal GB database before auto complete can show its members.

Ditect2D support
Windows’ Direct2D, which is implemented as COM objects, are encapsulated in GFA-BASIC as GB32 - like commands. All the Direct2D command names start with D2, like D2Color, D2Line, D2Brush, etc. To use Direct2D include the GFA-BASIC 32 library direct2d.lg32 in your program. The library is located in the Include directory and exports GFA-BASIC like commands and functions that correspond to the set of graphic commands GFA-BASIC already offers. For instance, the syntax of D2Line mimics the behavior of the Line command, D2DefFill selects a new fill brush as DefFill does, etc.
The new English CHM helpfile plays an important role in developing Direct2D applications.

The new help provides an introduction to Direct2D programming and discusses the D2 command's. The example code presented in the help-topics are stored in the Samples/Direct2D directory. You are encouraged to step through the samples, but you should start reading with the D2GetRT topic in the help-file. D2GetRT is the base in each program to initialize Direct2D and to provide a render target (canvas) to draw on. So, it is a good place to start reading.

DPI-aware applications
To develop DPI-aware apps you'll need two monitors, one regular 96 dots-per-inch display to run the GFABASIC 32 IDE and one high-resolution display to run and test the program. In addition, the manifest of GfaWin32.exe must include the <dpiawareness> tag. For this purpose the Bin directory contains a separate dpi-manifest file that needs to be renamed to GfaWin32.exe.manifest. You can accomplish this by saving or renaming the current manifest (GfaWin32.exe.manifest) and then rename the GfaWin32.exe.dpiawaremanifest to GfaWin32.exe.manifest. See the help-file for more information on creating DPI-aware applications. It provides information for new gfawinx DPI-scaling commands that will help developing high-resolution apps, like ScaleToDpi, ScaleToDpiSng, ScaleXYWHToDpi, and WinDpi, but also LoadFormPos and SaveFormPos to handle loading and saving the application’s main form on multiple monitors.

The Large Address Aware command
When the $LargeAddressAware compiler directive is used in the code, the compiled EXE is modified to handle memory addresses above 2 GB, theoretically allowing access to up to 4 GB of virtual memory. Normally, a 32-bit application can address only the first 2 GB of memory, however on 64-bit operating systems and when the application is large address aware it can access the additional 2 GB memory that isn’t used by the OS.

The gfawinx library
The gfawinx library is the source for new GB32 commands and functions. To stress the importance of these additions they have the same syntax-color in the editor as regular GB32 commands. When a new program is started, the first thing to do is to import this library as follows:

$Library "gfawinx"

Besides the string functions, gfawinx contains several commands to support developing multiple monitor programs. A brief overview of the new commands and functions:

HexDump A debugging aid to show the contents of a piece of memory.
ErrStr Converts the information from the Err object in a single string.
Wide, Ansi Allows conversion between UNICODE and ANSI formatted strings.
Replace Replaces a string in a given string.
StrToArr Separates a delimited – any delimiter character - string into a string array.
Assoc Retrieves a file association-related string from the registry.
GetWorkArea Retrieves the work area of the monitor containing the largest area of a given window.
GetClientSize Retrieves the width and height (in pixels) of any window's client area.
ModifyStyle, ModifyExStyle Modifies the style or extended-style of a window.
SaveFormPos, LoadFormPos Saves and loads the form's position on the screen to and from the registry. Especially useful with multiple-monitor systems.
ScaleToDpi, ScaleToDpiSng Converts pixels based on a 96 dot-per-inch resolution to DPI physical pixels of the Form's display.
ScaleXYWHToDpi Scales ScaleLeft, ScaleTop, ScaleWidth, and ScaleHeight to a form's DPI.
WinDpi Returns the dots per inch (dpi) value of the display for the specified form.
GetProcAddr Returns the address of an exported function or variable from the specified dynamic-link library (DLL).
WinVer Retrieves version information about the currently running operating system (preferred way to obtain Windows’ version).
TimerQ Creates a high-resolution timer wrapped in a (minimal) COM object.

The Include directory
The Include directory contains Windows API library files ready to import in your program using the $Library command. Several include files are modified to export their Declares explicitly by their name. This was necessary because a bug in GB causes a corruption of the Declare-database if the program declared DLL-functions as well.
Their is also a winmacros.inc.lg32 file with commonly used Windows API macros. The include file provides optimized GB functions to mimic the macros from C/C++ header files.

You can download the new update here.

26 November 2020

The Naked attribute in practice

In the previous posts The Anatomy of a Procedure (1) and The Anatomy of a Procedure (2) I discussed the effect of the Naked attribute on the code generated by the compiler. Everything you want to know about the Naked attribute can be found in these posts, but – unfortunately – the posts are rather technical. If you lack any experience in assembly it might be hard to understand, so I will recap on the use of the Naked attribute in ‘layman’s’ terms here.

Naked explained
A Naked procedure is fully optimized, both in size and in performance. This comes with a penalty though, a naked procedure lacks support for dynamic variables types (String, Object, Variant, array and hash), structured exception handling, and runtime debugging (Tron, Trace). The reason for this is the lack of ‘procedure-housekeeping’ that GFA-BASIC 32 inserts in each regular procedure. In a regular procedure GB starts of by inserting a 80 bytes stackframe (68 in an EXE) to store all information necessary for housekeeping of the procedure. At the end of the procedure in insert code to restore the stack to automatically release all (dynamic) variables (even in case of a runtime error). The housekeeping code is missing in a naked procedure. Consequently, a naked procedure can execute faster, in certain cases up to 50% faster than a regular procedure. Only short procedures benefit from the Naked attribute; the executable code must be relative small compared to the code necessary to setup a stackframe of 80 bytes, as we will see. The example procedure from the previous post is a good example of a candidate for Naked, it executes 50% faster:

TestMul(2, 3)
Proc TestMul2(x As Int, y As Int) Naked
  Local tmp As Int
  tmp = x Mul y
EndProc

When the procedure grows and contains more executable code the relevance of Naked disappears. The next example shows two things. First, it declares a local dynamic string variable (which needs to be released explicitly by setting it to the ‘empty-string’). Secondly, the assignment of data to the string will allocate memory and produce code to copy the data to that memory. This is a relatively expensive operation and will reduce the possible performance gain of Naked.

Dim i%, t#
t# = Timer
For i% = 0 To 100000 : TestMul(2, 3) : Next
Debug "Normal: "; Timer - t#
t# = Timer
For i% = 0 To 100000 : TestMul2(2, 3) : Next
Debug "Naked: "; Timer - t#

Proc TestMul(x As Int, y As Int)
  Local tmp As Int, s As String = "Something"
  tmp = x Mul y
EndProc
Proc TestMul2(x As Int, y As Int) Naked
  Local tmp As Int, s As String = "Something"
  tmp = x Mul y
  s = ""
EndProc

The measured time for calling TestMul() and TestMul2() a 10000 times is

TestMul: ca 0.021 seconds
TestMul2: ca 0.019 seconds.

In this example, the time to execute the naked procedure is almost the same as executing the regular procedure. Adding a dynamic variable – and assigning it a value - to a naked procedure negates the benefit almost entirely. The code to execute is drastically increased, assigning a value to a string causes the execution of malloc() and memcopy(), and these take so much time the advantage of naked is almost gone. In addition, the string must be released which leads to an extra call of mfree(). All in all, just by adding one dynamic variable the procedure contains too much code to really benefit from Naked.

Other issues
Another disadvantage of using Naked is the issue of runtime error trapping. In case of an error the IDE stops running the program and puts the the error-line-marker on the line that calls the procedure and not inside the naked procedure.

A non-naked, regular procedure will not only trap the error, but also clears the contents of the (dynamic) local variables automatically. With naked-procedures the dynamic variables must be released explicitly. The local variables can be released using the following commands.

Local dynamic variable        Release command           
String s$ = “” or Clr s$
Variant var = Empty
Object (any COM) Set obj = Nothing
Hash Hash Erase hs[]
Array (not allowed, unless static)   If static: Erase ar()

A local array cannot be used in a naked-procedure. A local array declaration allocates an array-descriptor plus the memory required to store the array elements. Using the Erase command on a local array only releases the memory for the data, not the array-descriptor. Each time the procedure is executed a new descriptor is allocated without being released. Consequently, the program will leak memory. If you need a local array it must be static, then the descriptor is allocated only once. This is not a problem in regular procedures, of course.

Conclusion
Only short procedures that don’t use local dynamic variables are candidates for the Naked attribute.