Custom application class

The CustApp unit implements the class, which serves as the common ancestor to many kinds of TApplication classes: a GUI application in the LCL, a CGI application in FPCGI, a daemon application in daemonapp. It introduces some properties to describe the environment in which the application is running (environment variables, program command-line parameters) and introduces some methods to initialize and run a program, as well as functionality to handle exceptions.

Typical use of a descendent class is to introduce a global variable Application and use the following code:

Application.Initialize; Application.Run;

Since normally only a single instance of this class is created, and it is a TComponent descendent, it can be used as an owner for many components, doing so will ensure these components will be freed when the application terminates.

Exception support and string formatting. TComponent support Exception handling event prototype TExceptionEvent is the prototype for the exception handling events in TCustomApplication. TCustomApplication instance. Exception instance that should be handled. Ancestor class for TApplication classes.

TCustomApplication is the ancestor class for classes that whish to implement a global application class instance. It introduces several application-wide functionalities.

  • Exception handling in HandleException, ShowException, OnException and StopOnException.
  • Command-line parameter parsing in FindOptionIndex, GetOptionValue, CheckOptions and HasOption
  • Environment variable handling in GetEnvironmentList and EnvironmentVariable.

Descendent classes need to override the DoRun protected method to implement the functionality of the program.

Create a new instance of the TCustomApplication class Create creates a new instance of the TCustomApplication class. It sets some defaults for the various properties, and then calls the inherited Create. Owner component. Usually Nil. Destroys the TCustomApplication instance. Destroy simply calls the inherited Destroy. Handle an exception.

HandleException is called (or can be called) to handle the exception Sender. If the exception is not of class Exception then the default handling of exceptions in the SysUtils unit is called.

If the exception is of class Exception and the OnException handler is set, the handler is called with the exception object and Sender argument.

If the OnException handler is not set, then the exception is passed to the ShowException routine, which can be overridden by descendent application classes to show the exception in a way that is fit for the particular class of application. (a GUI application might show the exception in a message dialog.

When the exception is handled in the above manner, and the StopOnException property is set to True, the Terminated property is set to True, which will cause the Run loop to stop, and the application will exit.

ShowException StopOnException Terminated Run
Sender class calling this routine Initialize the application

Initialize can be overridden by descendent applications to perform any initialization after the class was created. It can be used to react to properties being set at program startup. End-user code should call Initialize prior to calling Run

In TCustomApplication, Initialize sets Terminated to False.

Runs the application. Run is the start of the user code: when called, it starts a loop and repeatedly calls DoRun until Terminated is set to True. If an exception is raised during the execution of DoRun, it is caught and handled to . If is set to True (which is not the default), Run will exit, and the application will then terminate. The default is to call DoRun again, which is useful for applications running a message loop such as services and GUI applications. Show an exception to the user

ShowException should be overridden by descendent classes to show an exception message to the user. The default behaviour is to call the ShowException procedure in the SysUtils unit.

Descendent classes should do something appropriate for their context: GUI applications can show a message box, daemon applications can write the exception message to the system log, web applications can send a 500 error response code.

None. ShowException
Exception object to show Terminate the application. Terminate sets the Terminated property to True. By itself, this does not terminate the application. Instead, descendent classes should in their DoRun method, check the value of the Terminated property and properly shut down the application if it is set to True. Return the index of an option.

FindOptionIndex will return the index of the option S or the long option LongOpt. Neither of them should include the switch character. If no such option was specified, -1 is returned. If either the long or short option was specified, then the position on the command-line is returned.

Depending on the value of the CaseSensitiveOptions property, the search is performed case sensitive or case insensitive.

Options are identified as command-line parameters which start with OptionChar (by default the dash ('-') character).

HasOption GetOptionValue CheckOptions CaseSensitiveOptions OptionChar
Position on commandline of option. Short option to search for. Long option to search for. Return the value of a command-line option.

GetOptionValue returns the value of an option. Values are specified in the usual GNU option format, either of

--longopt=Value

or

-c Value

is supported.

The function returns the specified value, or the empty string if none was specified.

Depending on the value of the CaseSensitiveOptions property, the search is performed case sensitive or case insensitive.

Options are identified as command-line parameters which start with OptionChar (by default the dash ('-') character).

FindOptionIndex HasOption CheckOptions CaseSensitiveOptions OptionChar
Option value, or empty string. Long option string Short option character Check whether an option was specified.

HasOption returns True if the specified option was given on the command line. Either the short option character C or the long option S may be used. Note that both options (requiring a value) and switches can be specified.

Depending on the value of the CaseSensitiveOptions property, the search is performed case sensitive or case insensitive.

Options are identified as command-line parameters which start with OptionChar (by default the dash ('-') character).

FindOptionIndex GetOptionValue CheckOptions CaseSensitiveOptions OptionChar
True if the option S or C was specified on the command-line. Long option string Short option character. Check whether all given options on the command-line are valid.

CheckOptions scans the command-line and checks whether the options given are valid options. It also checks whether options that require a valued are indeed specified with a value.

The ShortOptions contains a string with valid short option characters. Each character in the string is a valid option character. If a character is followed by a colon (:), then a value must be specified. If it is followed by 2 colon characters (::) then the value is optional.

LongOpts is a list of strings (which can be specified as an array, a TStrings instance or a string with whitespace-separated values) of valid long options.

When the function returns, if Opts is non-Nil, the Opts stringlist is filled with the passed valid options. If NonOpts is non-nil, it is filled with any non-option strings that were passed on the command-line.

The function returns an empty string if all specified options were valid options, and whether options requiring a value have a value. If an error was found during the check, the return value is a string describing the error.

Options are identified as command-line parameters which start with OptionChar (by default the dash ('-') character).

if AllErrors is True then all errors are returned, separated by a sLineBreak character.

If an error was found during the check, the return value is a string describing the error(s). FindOptionIndex GetOptionValue HasOption CaseSensitiveOptions OptionChar
Empty string or error-message List of valid short options. List of valid long options. Valid options passed to the program. Non-option strings passed to the program. Should all errors be returned, or just the first one? Return a list of environment variables. GetEnvironmentList returns a list of environment variables in List. They are in the form Name=Value, one per item in list. If NamesOnly is True, then only the names are returned. EnvironmentVariable List to return environment strings in. If True, only environment variable names will be returned. Name of the executable.

ExeName returns the full name of the executable binary (path+filename). This is equivalent to Paramstr(0)

Note that some operating systems do not return the full pathname of the binary.

ParamStr
Location of the application help file. HelpFile is the location of the application help file. It is a simple string property which can be set by an IDE such as Lazarus, and is mainly provided for compatibility with Delphi's TApplication implementation. Was Terminate called or not Terminated indicates whether Terminate was called or not. Descendent classes should check Terminated at regular intervals in their implementation of DoRun, and if it is set to True, should exit gracefully the DoRun method. Terminate Application title Title is a simple string property which can be set to any string describing the application. It does nothing by itself, and is mainly introduced for compatibility with Delphi's TApplication implementation. HelpFile Exception handling event

OnException can be set to provide custom handling of events, instead of the default action, which is simply to show the event using ShowEvent.

If set, OnException is called by the HandleEvent routine. Do not use the OnException event directly, instead call HandleEvent

ShowEvent
Is the application a console application or not ConsoleApplication returns True if the application is compiled as a console application (the default) or False if not. The result of this property is determined at compile-time by the settings of the compiler: it returns the value of the IsConsole constant. IsConsole Application location Location returns the directory part of the application binary. This property works on most platforms, although some platforms do not allow to retrieve this information (Mac OS under certain circumstances). See the discussion of Paramstr in the RTL documentation. Paramstr Params Command-line parameters Params gives access to the command-line parameters. They contain the value of the Index-th parameter, where Index runs from 0 to ParamCount. It is equivalent to calling ParamStr. ParamCount Paramstr Index of parameter to retrieve Number of command-line parameters ParamCount returns the number of command-line parameters that were passed to the program. The actual parameters can be retrieved with the Params property. Params Paramstr ParamCount Environment variable access

EnvironmentVariable gives access to the environment variables of the application: It returns the value of the environment variable EnvName, or an empty string if no such value is available.

To use this property, the name of the environment variable must be known. To get a list of available names (and values), GetEnvironmentList can be used.

GetEnvironmentList
Name of variable to retrieve Command-line switch character OptionChar is the character used for command line switches. By default, this is the dash ('-') character, but it can be set to any other non-alphanumerical character (although no check is performed on this). FindOptionIndex GetOptionValue HasOption CaseSensitiveOptions CheckOptions Are options interpreted case sensitive or not CaseSensitiveOptions determines whether FindOptionIndex and CheckOptions perform searches in a case sensitive manner or not. By default, the search is case-sensitive. Setting this property to False makes the search case-insensitive. FindOptionIndex GetOptionValue HasOption OptionChar CheckOptions Should the program loop stop on an exception StopOnException controls the behaviour of the Run and HandleException procedures in case of an unhandled exception in the DoRun code. If StopOnException is True then Terminate will be called after the exception was handled. Run HandleException Terminate Write a message to the event log Log is meant for all applications to have a default logging mechanism. By default it does not do anything, descendent classes should override this method to provide appropriate logging: they should write the message Msg with type EventType to some log mechanism such as None. Type of event Message to log Global application instance CustomApplication contains the global application instance. All descendents of should, in addition to storing an instance pointer in some variable (most likely called "Application") store the instance pointer in this variable. This ensures that, whatever kind of application is being created, user code can access the application object. Set of TEventLogType TEventLogTypes is a set of TEventType, used in to filter events that are sent to the system log. Event to filter events, before they are sent to the system log EventLogFilter can be set to a set of event types that should be logged to the system log. If the set is empty, all event types are sent to the system log. If the set is non-empty, the routine will check if the log event type is in the set, and if not, will not send the message to the system log.