| Documentation: The Application Class [Remove Frame]

The FXApp Class

The application object manages the message queue, timers, chores, signal handling, GUI updating, and other system facilities. Each FOX application will have exactly one application instance. Every FOX application will start by constructing one FXApp object prior to building the GUI. Usually, the FXApp object is the last object to be deleted as well.

Using the code below, the application object will be constructed on the stack and hence is automatically destroyed when the program terminates. Also, when the application object is destroyed, all the windows and other resources it knows about are destroyed as well.

    int main(int argc,char *argv[]){

      // Make application
      FXApp application("ApplicationName","VendorName");

      // Open display
      application.init(argc,argv);

      // Make window
      MainWindow* mainwindow=new MainWindow(&application);

      // Create it
      application.create();

      // Show Window
      mainwindow->show();

      // Run
      return application.run();
      }

In the first line of code above, an application object is constructed. The constructor has two parameters, the application name, and the vendor name. The application name and vendor name are used to determine the application's registry settings.

The next line of code initializes the application object, passing in the command line arguments of the process. The application object parses its own arguments and removes them, but leaves the remaining arguments alone, to be interpreted by your own code.

The next line creates a toplevel window, passing in a pointer to the application object.

The call to the application object's create() function realizes the entire widget tree, i.e. creates the necessary resources in the system (X Server or Windows GDI), to turn what was up till that point a collection of C++ data structures into a real-life application which is able to receive events and draw on the screen.

The final call to run() starts the toplevel event loop. A typical application will not return from this loop until the user closes the application.

Event Loops

Most GUI applications have something called an event loop or message loop. Unlike batch-oriented programs which read a datafile, perform some processing, and then produce an output file, a GUI driven application spends almost all its time in an event loop, waiting for user input, determining where that input came from, and then dispatching it to the proper function to perform some processing. Unlike batch oriented programs, these functions are typically very short, and mostly take only very little time to execute, and so the user is in complete control of the application most of the time. The events a GUI program processes can be of different types:

- Keyboard input;
- Mouse movements;
- Mouse buttons;
- Inputs from other sources (e.g. network sockets, timers, signals, and so on);
- Changes in selection and clipboard ownership;
- Drag and drop events;
- Window repaint events;
- And other things which can happen to a window.

The application object is solely responsible for coordinating all these events and dispatching them to the proper destination where they are handled.

FXApp performs delayed repaints on windows; it delays issuing the repainting of windows until all other events have been performed. The theory behind this is that most events are not as time-consuming as redrawing, and also that many events cause more things to be redrawn so if we were to draw as soon as possible it might be invain. Also FXApp combines repaint rectangles so as to minimize the video card hardware setup and tear down time relative to the number of pixels drawn.

Event Queues

Certain devices, such as a moving mouse, can generate events faster than some programs can process them. To prevent losing events, events are commonly queued up, so programs can catch up as fast as they can. Likewise, the drawing commands a GUI program generates as its trying to draw buttons and other controls on the screen are also queued up, so that the X server (or GDI on Windows) can take its time to catch up.

Finally, the X Server has its own event queue and drawing queue, making for a total of four queues. All these queues allow for much faster performance of applications, as bigger chunks of data can be transmitted between the application and the X server, and fewer context switches of video card and cpu hardware are needed.

From the point of programming in FOX, the existence of these queues is for the most part hidden, but in a few cases some special functions are available that you may need to call:

FXApp::flush(sync)

This function flushes the output queue, i.e. the commands which have been already performed are pushed to the X Server, where they are executed. If we want to make sure that the display shows the correct picture, however, just pushing the commands to the X Server is not enough! Sometimes we need to make sure that these commands have been executed before we continue!
Thus, when passing TRUE to flush(), the X Server is forced to execute the commands queued up in the drawing queue prior to returning control to the caller.

Sometimes, we want to check if there are any events, but continue to do some processing if no events are available. Under normal circumstances, returning to the event loop will cause our process to block until there are events; but if there is stuff we may want to do, this is of course not desirable. We have just the right solution for this problem:

FXApp::peekEvent()

This function will return TRUE if there are any events ready to process, and FALSE if there are none. The peekEvent() function can be used when we are doing a long calculation and we want to check if the user has hit the STOP button.

Types of Event Loops

There are several types of event loops supported, each of them is appropriate for certain situations. Most commonly, application developers will however only call:

FXApp::run()

This is the top level event loop, and it will only terminate when the application is ready to call it quits. When run() finally returns, its return value is the exit value passed to stop() earlier.

FXApp::stop(code)

This function terminates the top level event loop, but also terminates all nested event loops which have been directly or indirectly invoked from this top level loop. Each nested loop is terminated with a code of zero (0), but the top level event loop is terminated with the given code.

FXApp::runOneEvent()

As the name implies, this function reads and then processes one single event, and then returns. It is primarily interesting to use in combination with peekEvent(), as peekEvent() returns TRUE if there is at least one event ready to be processed.
If there is no event ready, runOneEvent() will block until there is at least one event.

FXApp::runWhileEvents()

This function processes events while events are available. This function is useful if you are running a long calculation, and want to temporarily dip into the event stream to process some event, for example to redraw damaged windows and so on.

FXApp::runUntil(condition)

This function processes events until the variable condition, which is passed as a reference, becomes non-zero.

Modal dialogs are dialog panels which block interaction with the rest of the application until they are completed. For example, while trying to open a file, the application is unable to interact in other way with the user until some file is selected and loaded in. In FOX, the only difference between normal dialogs and modal dialogs is how they are run:- modal dialogs are run by calling:

FXApp::runModalFor(window)

This function runs a nested or recursive invocation of the event loop, i.e. it re-enters an event loop and processes events for a while, and returns only when stopModal() or stop() is called. As long as runModalFor() is running, user-input events to all other windows, except for given window and the windows owned by it, are being blocked. No user-interaction with other windows is possible until runModalFor() returns, but other windows are allowed to process other events like redrawing and resizing.
When it returns, it returns the value passed to the stopModal() function, or 0 if stop() is called to terminate the application.

However, it is quite possible, and in fact common, that one modal dialog invokes another. In that case, only the most recently invoked dialog can be interacted with.

FXApp::runModalWhileShown(window)

The function runModalWhileShown() runs until either stopModal() or stop() is called or the specified window becomes hidden. This is of interest when running popup menus or other temporary windows. If the window parameter is NULL, all input is blocked; otherwise the input to all windows except the given window (and all windows owned by the window) are blocked.

FXApp::stopModal(window,code)

Calling stopModal() causes the modal event loop with the matching window to terminate with code. However, stopModal() also causes all modal event loops which are nested more deeply to terminate with code zero (0).
FXApp::stopModal(code)
Calling stopModal() causes the innermost modal event loop with the matching window to terminate with code. This is the most common method to terminate model loops.

FXApp::isModal(window)

This function returns TRUE if a modal loop is in effect for the given window.

Modal dialogs are always run with runModalFor(). Because it is so common to construct a dialog on the stack, run it modally, and then process the inputs thus obtained, there is a convenience member function FXDialogBox::execute() which calls create(), show(), and then runModalFor() in turn. The FXDialogBox also understands several messages, for example ID_ACCEPT, ID_CANCEL, and SEL_CLOSE which call stopModal() returning a code 1, 0, and 0 respectively.
The return code of zero from FXDialogBox::execute() indicates that the dialog window was closed or cancelled. An application should typically not perform any action when a dialog is closed.

Global Application Mutex

When programming with multiple threads of control, one single thread (the Main Thread) is responsible for the User Interface, while other threads are Worker Threads churning in the background. Occasionally, the Worker Threads need to interact with the Main Thread.
This is accomplished by means of the global application mutex.
When the display is opened, the Main Thread acquires the global application Mutex. It continues to hold this Mutex while it is processing events, until the Main Thread is about to enter a blocking state.
Just before entering the blocking state, the Main Thread releases the global application Mutex. Worker Threads are then free to acquire the
global Mutex and then play around with data structures safely. As soon as an event comes in, the Main Thread wakes up and immediately reacquires the global application Mutex.
Thus, basically every message or callback in the system is performed while the global Mutex is held by the Main Thread. This ensures that no Worker Thread is simultaneously modifying some data structure when the Main Thread is also.
The Main Thread continues to hold the global Mutex until display is closed.
The global Mutex may be obtained by reference with the function:

FXApp::mutex()

This function returns a reference to the global Mutex.

Having the Mutex returned as a reference allows it to be passed directly into the FXMutexLock convenience class, which performs Mutex locking and unlocking by means of constructor and destructor.

GUI Updating

The event loop ordinarily enters a blocking system call when no events are available. However, if any windows have been marked as damaged, the system will peform repaint events that have been queued up to this point.
When no more events call for attention, and all windows have been redrawn properly, there is still just a bit more to do before entering the blocking state, and that is the GUI-Update.
The GUI-Update phase is entered just prior to blocking the user-interface. Since there is nothing else the application would be doing (after all, it is about to block for new events!), FOX takes advantage of this quiet time to iterate through all widgets in the widget tree and issue a SEL_UPDATE message to that widget's target.
The receiver of the SEL_UPDATE message typically inspects the state of the application, and decides whether the sending widget should be update to properly reflect that state.

For example, a Save Button may be grayed out when the user has not yet made any modification to a document. You can also change the values of certain controls such as Sliders, Text Fields, Check Buttons, Color Wells, and so on.
The result of this procedure is that a short time after processing a burst of events, the User Interface of your application automatically updates to reflect the state of the application.

The application determines whether a GUI-Update pass is warranted based on the return value of messages it sends. If messages are sent but aren't handled by a widget or by your application code, it doesn't need to perform an update pass. On the other hand, if there is reason to believe a message has been handled, the application automatically calls refresh() to schedule a future GUI-Update pass.

The GUI-Update pass is performed in a cyclical fashion, that is to say, each widget gets updated roughly equally often.

In a few cases, it is nice to be able to forcibly schedule a GUI-Update pass; for example, just before entering a modal dialog; because the callback handler invoking the dialog does not return until the dialog is done, an explict call to refresh() may be needed to ensure that the controls in the dialog are properly updated when the dialog is displayed. In this case you can call refresh() explicitly from the application code.

FXApp::refresh()

This function reschedules another GUI update to be performed in the future.

At other times, it may be necessary to ensure that the GUI-Update pass is performed immediately; this ensures that all the controls in the application have been updated to their current state. Since this involves having a SEL_UPDATE sent from each widget, it is of course rather expensive. Fortunately, it is not often necessary to do this:

FXApp::forceRefresh()

Calling this function will cause an immediate GUI update pass to be performed. Unlike the normal GUI update, which takes place unobstrusively one and a time, prior to blocking, forceRefresh() will not return until all windows have been refreshed. It is therefore quite expensive, and should be used only when strictly necessary.

The GUI update has no impact on the perceived speed of an application because between each pair of GUI updates performed, a check for events is performed.

Visuals

An FXVisual is a description of the pixel organization on the display. For example, some high-quality graphics cards can do 24 bits per pixel; other graphics cards may be limited to 16, 15 bits per pixel, or even just 8 bits/pixel. FOX programs can even work on 4 bit/pixel (VGA mode) and 1 bit/pixel (monochrome), although it wouldn't be as much fun!

Besides depth (number of bits/pixel), there are also other characteristics which come into play describing the pixel organization, such as colormaps, and wether or not a colormap can be written or not, and the byte and bit organization.

Colormaps are commonly used on 8-bit/pixel systems. Most hardware only supports one hardware colormap, and this must be shared among all programs on the display. Because legacy toolkits such as Motif do not deal with full colormaps very gracefully, FOX applications deliberately do not try to grab all 256 colors from the colormap, but only 125 colors. Images and Icons are dithered to get the best possible rendering given the number of colors available.

You can improve the look of your program quite easily, however, as the maximum number of colors which the default visual tries to allocate can be easily changed using a command line argyment; for example, "myapp -maxcolors 256" will start myapp in such a way as to attempt to acquire all 256 colors from the colormap.

Because other programs may already be running, the desired gamut of colors may not be available. If the exact color can not be obtained, FOX will try to find the closest color available and use that.

Normally, the FXVisual a window uses is copied from its parent. You can change this visual for each window, or you can call:

FXApp::setDefaultVisual(visual)

This function will change the default visual to be used for all toplevel windows; the child-windows will simply inherit the visual from their parent.

Alternatively, the maximum number of colors can also be set via the registry, using the maxcolors key under [SETTINGS] any number less than or equal to 256 colors may be specified, FXVisual will determine the best gamut to pick from the allowable number of colors.

Wait Cursors

Sometimes, an application needs to undertake a long task, such as e.g. loading a big file. In such cases, it is good form to present the user with some feedback to indicate that the application may be temporarily unresponsive. Common ways to do this are progress bars and changing the cursor shape to a stopwatch, or hourglass, or something like that.FXApp supports this by means of the following functions:

FXApp::beginWaitCursor()

This will change the cursor shape for all windows to the stopwatch cursor, or the cursor designated by setWaitCursor(). Calls to beginWaitCursor() and endWaitCursor() can be nested in a stack-like fashion, with only the first call to beginWaitCursor() and last call to endWaitCursor() actually changing the cursor shape.

FXApp::endWaitCursor()

A matching call to endWaitCursor() will restore the original cursor for each window.

FXApp::setWaitCursor(cursor)

This will change the cursor shape used in during a beginWaitCursor() endWaitCursor() pair.

FXApp::getWaitCursor()

This returns the current FXCursor being used as hourglass or stopwatch cursor.

The beginWaitCursor() and endWaitCursor() calls can be nested pairwise, so that a functions which bracket a long calculation by means of a beginWaitCursor/endWaitCursor pair can call upon each other.

Drag Types

Exchanging data via the Primary Selection, the Clipboard, or by means of Drag and Drop requires that all applications agree with the type of data being exchanged.
This is done by registering a Drag Type. In most cases, the name being registered should be a mime-type, such as "text/plain" or "image/gif".

Manipulating drag types is done with the following API's:

FXApp::registerDragType(name)

This will register a new drag type based on the mime type name.

FXApp::getDragTypeName(dragtype)

Obtain the name of a previously registered drag type.

The drag types must be mime types as defined in the XDND standard.

Copyright © 1997-2010 Jeroen van der Zijp