Using the C/C++ version of the Toolkit. Generic Logic 3.6
Реклама
Реклама
Chapter 2
2
Using the C/C++ version of the Toolkit
2
2.1 Displaying a GLG Drawing
The first step in operating a GLG drawing from a program is to display that drawing. GLG drawings are environment and platform-independent, as are many of the aspects of controlling and modifying the drawings. The task of displaying the drawings in a display window, however, is peculiar to the windowing system and environment in use.
This chapter describes the task of creating and displaying a GLG drawing in C and C++ programs used in different windowing environments: X Windows on Unix/Linux and Windows.
This chapter contains three sections:
• The first section describes the task of loading and displaying a GLG drawing in a window in the X Windows and Linux/Unix environment using either a Motif or Xt-based GLG Wrapper widget.
• The second section of this chapter on page 34 provides information on loading and displaying
a GLG drawing on Windows.
• The third section on page 45 describes a platform-independent GLG Generic API, which
can be used for loading and displaying a GLG drawing in cross-platform way. The source code of the applications created using the Generic API is portable between Linux/Unix and
Windows environments.
The Windows version of the GLG Toolkit also includes the GLG ActiveX Control, an ActiveX component providing full GLG functionality. The GLG ActiveX control allows GLG drawings to be embedded and used in a variety of user applications and environments supporting ActiveX
controls, such as VB.NET, C++ and C#/.NET. For more information, see the Using the ActiveX
C++ applications may also use provided C++ classes to instantiate a GLG drawing as a class in a
C++ program. The GLG Toolkit provides classes for instantiating a GLG drawing in both Xt, Motif and MFC environments, as well as cross-platform classes that use GLG Generic API and may be
used in either environment. See the GLG C++ Bindings chapter on page 185 for more information.
The Java version of the toolkit uses either the GLG Java Bean or the GLG Generic API provided by the GlgObject class to load and display the drawing.
The C#/.NET version uses either the native .NET GlgControl or the GLG Generic API. Refer to
the Using the Java and C# Versions of the Toolkit chapter on page 239 for more information.
27
28
GLG Programming Reference Manual
X Windows and GLG Wrapper Widget
This section describes how to use the C/C++ version of the GLG library in the Linux/Unix and
X Windows environment. Refer to the GLG C++ Bindings chapter on page 185 for details on the
GLG C++ classes. Refer to the GLG Custom Control for Windows section on page 34 for a
description of using GLG on Windows.
The GLG Wrapper Widget is a widget wrapper around the GLG library used to embed GLG drawings into existing Xt and Motif interfaces. After the wrapper widget is instantiated in an application’s widget hierarchy, it loads and displays a GLG drawing, providing the GLG API to update the display with new data and access GLG objects in the drawing.
There are three basic steps involved in displaying a GLG drawing within an X Windows graphical environment. The first step is creating a GLG Wrapper Widget to contain the drawing. The GLG
Toolkit provides both a Motif version of this widget, which inherits its attributes from the
XmManager Motif class, and the Xt version of the widget, which inherits its attributes from the simpler Constraint class.
The two versions of the GLG Wrapper Widget are nearly identical in usage. The only difference is that the Xt version of the wrapper widget doesn’t support native Motif input objects (buttons, scrollbars, etc.), which will be displayed as empty boxes when displayed in the Xt version of the widget. Use the Motif version when Motif compliance is necessary for your application, or if your drawing includes native input widgets. If neither of these are true, you can use the Xt version. You choose whether to use the Motif or the Xt version of the GLG Wrapper Widget at link time, by specifying either the Motif or Xt-based GLG library. The Xt-based GLG library is provided for
Linux and certain other platforms. For information about linking with GLG libraries, see the
Integrating GLG Drawings into a Program chapter.
After the widget is created and the drawing displayed, a program must acquire a viewport handle
(or object ID) to use with the rest of the GLG API. Finally, when the program’s execution is completed, it must close the widget and drawing. Briefly, the tools for these steps are as follows:
• To create a GLG Wrapper Widget instance, use XtCreateWidget and specify the class variable
GlgWrapperWidgetClass and either the XtNglgDrawingFile, XtNglgDrawingObject, or
XtNglgDrawingImage resource.
• To destroy a GLG Wrapper Widget, use XtDestroyWidget and specify the widget ID of the
GLG wrapper.
• To manipulate objects in a viewport of the GLG Wrapper Widget, use
XglgGetWidgetViewport to create an object ID.
These steps are described in detail in the sections that follow.
Creating the Wrapper Widget
An application program creates a GLG Wrapper Widget the same way it creates any other widget.
Use the XtCreateWidget function from the X Toolkit, and the GlgWrapperWidgetClass from the
GLG Toolkit.
Using the C/C++ version of the Toolkit
29
Graphical objects to be displayed inside the widget are defined by a supplied GLG drawing. The drawing used for a widget defines the type of the widget and its appearance.
Synopsis
To create a GLG Wrapper Widget with the XtCreateWidget function, use the following arrangement of include files in your program:
#include <X11/StringDefs.h>
#include <X11/Intrinsic.h>
#include "GlgWrapper.h"
Create the widget with a call to the X toolkit: widget = XtCreateWidget( name, glgWrapperWidgetClass,... );
Wrapper Widget Resources
The Xt version of the GLG Wrapper Widget is a subclass of the Xt Constraint class, while the Motif version is a subclass of the XmManager class. Like other widgets, the GLG Wrapper Widget is controlled by querying and setting resources.
Warning: The resources of an X widget like the GLG Wrapper Widget are part of a different set of resources from the resources of a GLG drawing. The structure is similar, but the application is different. X resources refer to the data structure that makes up an entire screen, while the GLG resources only refer to the animated drawing. The two sets do interact; you can use the X resources of the GLG Wrapper Widget to set values for the GLG drawing resources. However, the two must not be confused.
The following sections describe the resources of the GLG Wrapper Widget. The entire list of
resources is summarized in the table on page 33.
Loading the Drawing
There are three resources of the GLG Wrapper Widget you can use to define the source of the GLG drawing to be displayed:
XtNglgDrawingFile
A character string specifying the name of the GLG drawing file.
XtNglgDrawingObject
An object ID of an already-loaded viewport object to be used by the GLG Wrapper Widget.
The drawing might have been loaded from a file or an image, or generated with the GLG
Extended API.
XtNglgDrawingImage
A long integer specifying the memory address of the drawing’s memory image. This must be used in conjunction with XtNglgImageSize, which must contain an integer defining the size of that memory image. This is acquired from the gcodegen utility.
NOTE: XtNglgDrawingImage does not work with compressed drawing files. Save drawings with the drawing compression option disabled to use them as images.
30
GLG Programming Reference Manual
One of these three resources must be defined when a GLG Wrapper Widget is created. If all three are defined, XtNglgDrawingFile is used. If the file cannot be read, a warning message is generated, then XtNglgDrawingImage is used as a fall back resource. If none of these resources are defined or none of them are readable, an Xt error message is generated.
The drawing specified by the XtNglgDrawingFile or XtNglgDrawingImage resource must have a viewport named $Widget at the top level of the drawing’s hierarchy. If this condition is not satisfied, the drawing is not recognized as a valid drawing for the GLG Wrapper Widget. The HasResources flag of the viewport should be set to YES. For information about drawing resources, see the
Structure of a GLG Drawing chapter.
The GLG Wrapper Widget manages the geometry of GLG graphical objects inside it, including any children GLG widgets represented by viewport objects. When the geometry of the widget is changed, it rubberbands all contained objects accordingly.
Setting the Drawing Resources
The GLG Wrapper Widget allows access to all the resources of the GLG drawing it contains in two different ways. After a drawing is displayed, you can use functions from the GLG API to manipulate drawing resources. The manipulation can happen either within the same process that started the
GLG Wrapper Widget or from a remote process.
You can also set initial values for drawing resources using the resources of the GLG Wrapper
Widget itself. Because the resource hierarchy of a drawing is infinitely variable, it is not feasible to allocate a separate GLG Wrapper Widget resource for every corresponding GLG drawing resource.
Instead, the wrapper widget has a fixed number of dynamic resources which are not associated with any particular drawing resource but are simply used as entry points to access the drawing resource hierarchy.
You can also use the XtSetArgs function to manipulate the drawing resources through the GLG
Wrapper Widget resources. However, this is a clumsy mechanism for an application program, and is not recommended. Using the GLG API gives an application program much finer control over when the drawing is updated and does not incur Xt resource setting overhead.
The GLG Wrapper Widget contains two sets of twenty resources, named XtNglgHResource0 to
XtNglgHResource19 and from XtNglgVResource0 to XtNglgVResource19. (The difference between
H and V resources is discussed in the H and V Resources section of the Integrating GLG Drawings
into a Program chapter.) These resources contain character strings which in turn contain the names
and values of GLG drawing resources. The strings have the following syntax:
<resource_name> <resource_type> <values>
<resource_name>
The name of the GLG drawing resource, including the complete path (omitting the
“$Widget”). For example, “XLabelGroup/XLabel4/String” accesses the text string of the fifth label on the X axis in a graph widget.
<resource_type>
The type of the resource and can be one of the following:
Using the C/C++ version of the Toolkit
31
d Indicates the resource value is represented by a single floating point number (a scalar), like a line width, a font number or a value of a data sample
s
The resource value is a string, like a text string of a label text object
g
The resource value is a set of three floating point numbers, like a geometrical point with X,
Y and Z coordinates or a color, in which case the three components represent the color's
Red, Green, and Blue values.
<values>
A value or a set of values for the resource. The values given depend on the resource type.
The following strings are examples of specifying resources:
"DataGroup/DataSample3/Value d 2.5"
"DataGroup/DataSample5/Value d 4"
"XLabelGroup/XLabel4/String s April"
"DataGroup/DataSample6/FillColor g 0.5 0 0.9"
The GLG Wrapper Widget does not need forty different dynamic resources of this type. In one sense, it would be adequate to have just one, and call it repeatedly. However, it is often useful to be able to keep the initial values of drawing resource in the X resource database, or in the X configuration files. Having many of these dynamic resources allows an application program to set several different drawing resources from the X resource database.
In the event that there are not enough GLG Wrapper Widget dynamic resources for your purpose, you can use the XtNglgHInitCB and XtNglgVInitCB callbacks to set the initial resources using functions of the GLG API.
Callback Resources
The XtNglgHInitCB callback is called after the viewport object containing the widget’s drawing has been created, but before the drawing hierarchy is created, allowing you to set H resources from the callback function itself. You can use the GLG API functions to do this, although you cannot modify the drawing itself with the Extended API from within one of these callback functions.
Setting H resources in this callback before the hierarchy is created eliminates the possible inefficiencies that arise when setting an H resource overrides an already existing part of the object hierarchy. The call_data parameter of the callback is not used.
The XtNglgVInitCB callback is called after the widget’s drawing hierarchy has been created, but before its graphical objects are drawn, allowing you to set V resources that depend on the number of objects in the hierarchy. These resources may be used to set the attributes of the created instances of objects for the initial appearance.
The XtNglgSelectCB callback is invoked after each mouse click event and provides a list of objects selected with the mouse.
The XtNglgInputCB callback is invoked after each user interaction with objects in the drawing and provides additional information which may be used to handle input events.
32
GLG Programming Reference Manual
Trace callbacks (XtNglgTraceCB and XtNglgTrace2CB) can be used in addition to the input and selection callbacks to handle low-level events. If attached, these callbacks are invoked for any native event received by any of the drawing’s viewports. The trace callback is invoked just before processing the event by the select and input callbacks, and the trace2 callback is invoked after the event has been processed.
The XtNglgHierarchyCB callback is invoked when SubWindow or SubDrawing objects in the widget’s drawing load their templates. The callback is invoked twice: before the hierarchy setup of the template and after the hierarchy setup but before the template is drawn.
For more information about the input, select, trace and hierarchy callbacks, refer to the Callback
Events chapter on page 105 of this manual.
The Motif version of the GLG Wrapper Widget also provides Motif-style XtNglgMotifSelectCB and
XtNglgMotifInputCB callbacks, which receive the GlgInputCBStruct and GlgSelectCBStruct callback structures as parameters. These structures are defined in the GlgWrapper.h include file and provide a Motif-style callback interface. The GlgInputCBStruct structure contains message_obj parameter, and the GlgSelectCBStruct structure contains the selection_list parameter, providing the
Sequence of Events
When a GLG Wrapper Widget is realized with a GLG drawing in it, the following sequence of events occurs:
1. The GLG drawing (supplied by the XtNglgDrawingFile or XtNglgDrawingImage resource) is loaded.
2. All current values of XtNglgHResource<N> resources are applied to the drawing.
3. The XtNglgHInitCB callback is invoked (if supplied).
4. The drawing hierarchy is set up.
5. All current values of XtNglgVResource<N> resources are applied to the drawing.
6. The XtNglgVInitCB callbacks is invoked (if supplied).
Setting the XtNglgDrawingFile and XtNglgDrawingImage resources after the widget has been realized loads the new drawing and discards all changes made to the old drawing. After reloading a new drawing file or image, the widget executes the same initialization sequence described above.
Note that applying the current values of the GLG Wrapper Widget resources may generate an error message if some of the drawing resources specified are not applicable for the new drawing. To avoid the error message, set the offending wrapper widget resource to NULL.
Using the C/C++ version of the Toolkit
33
Summary of GLG Wrapper Widget Resources
When creating a GlgWrapper widget instance, the following resources are retrieved from the argument list or from the resource database:
GLG Wrapper Widget Resource Summary
Name Type Default Description
XtNglgDrawingFile String
XtNglgDrawingImage XtPointer
NULL Name of the file containing a
GLG
drawing.
NULL Address of the memory image of a
GLG
drawing.
XtNglgImageSize
XtNglgHResource0
XtNglgHResource1
...
XtNglgHResource19
XtNglgVResource0
XtNglgVResource1
...
XtNglgVResource19
XtNglgHInitCB long
String
String
String
String
String
0
NULL
NULL
NULL
NULL
NULL
Size of the memory image.
Entry points for accessing
H resources of graphical objects in the drawing.
Entry points for accessing
V resources of graphical objects in the drawing.
XtNglgVInitCB
XtNglgSelectCB
String NULL
XtCallback list NULL Callback list for setting initial values of H resources using convenience functions.
XtCallback list NULL Callback list for setting initial values of V resources using convenience functions.
XtCallback list NULL Callback list for selecting objects in the widget.
XtNglgMotifSelectCB XtCallback list NULL Callback list for selecting objects in the widget, Motif-style callback structure format.
XtNglgInputCB XtCallback list NULL Callback list for the input activity in the widget.
XtNglgMotifInputCB XtCallback list NULL Callback list for the input activity in the widget, Motif-style callback structure format.
XtNglgTraceCB
XtNglgTrace2CB
XtCallback list NULL Callback list for trace callbacks.
XtCallback list NULL Callback list for trace2 callbacks.
XtNglgHierarchyCB XtCallback list NULL Callback list for hierarchy callbacks.
Obtaining a Viewport Handle
To use any of the functions from the GLG API, you must get an object ID for the main viewport of
use the XglgGetWidgetViewport function.
GlgObject XglgGetWidgetViewport( widget )
Widget widget;
34
GLG Programming Reference Manual
Parameters
widget
The Xt widget ID that specifies the GLG Wrapper Widget.
The GLG Wrapper Widget contains a viewport. The viewport manages all aspects of the drawing widget’s behavior and appearance. When accessing resources or performing any other operations on a GLG drawing, the object ID returned by XglgGetWidgetViewport is passed as a “handle” identifying the viewport. The viewport is created only after the GLG Wrapper Widget has been realized, so this function returns NULL if called before then.
Closing the Wrapper Widget
To close the GLG Wrapper Widget gracefully, use the XtDestroyWidget function from the X Toolkit.
It accepts only one argument, the widget ID returned by the XtCreateWidget function.
XtDestroyWidget( widget )
Widget widget;
GLG Custom Control for Windows
This section describes how to use the C/C++ version of the GLG library on Windows using the
Win32 API. Refer to the GLG C++ Bindings chapter on page 185 for details of the GLG C++ and
MFC classes. Refer to the Using the ActiveX Control chapter on page 209 for a description of using
the GLG ActiveX control.
The GLG Custom Control is a Windows wrapper designed for embedding GLG drawings in the programs using a Win32 API. It allows embedding GLG drawings into the Windows interface hierarchy as a custom window control (a window with a custom window type). The GLG Custom
Control manages the geometry of GLG graphical objects in it, including any child GLG widgets represented by nested viewport objects. When the geometry of the Control window changes, it proportionally resizes all the GLG objects inside it.
The first step in displaying a GLG drawing in the Windows environment is creating a window data structure to contain that drawing. This is the GLG Custom Control. After the window is created and the drawing displayed, a program must acquire a viewport handle (or object ID) which is used for updating the drawing with data via the GLG API. Finally, when the program’s execution is completed, it must close the window and drawing. Briefly, the tools for these steps are as follows:
• To create a GLG Custom Control instance, load the GLG drawing and use CreateWindow.
Other functions from the GLG API are used to set up the drawing hierarchy and display the drawing.
• To destroy a GLG Custom Control, use DestroyWindow and specify the Window ID of the control.
• To manipulate objects in a viewport of the GLG Wrapper Widget, use
GlgGetWindowViewport to obtain an object ID of the viewport.
These steps are described in detail in the sections that follow.
Using the C/C++ version of the Toolkit
35
Creating the GLG Custom Control
There are four steps involved in displaying a GLG drawing within the Microsoft Windows environment:
1. Read a GLG drawing into the program. This can be done from a file, with
GlgLoadWidgetFromFile, or from memory, with GlgLoadWidgetFromImage.
2. Use GlgSetDefaultViewport to identify the viewport to be used as the drawing widget.
3. Create a Custom Control using the drawing. This is done with the CreateWindow function from the Microsoft Windows API. The Microsoft Windows class of the GLG Custom
Control is GlgControl.
4. Use GlgInitialDraw to draw the initial drawing. You can delay this step until after you use
GlgGetWindowViewport to create a widget ID for the GLG drawing. At that point, you can use either GlgInitialDraw or a combination of GlgSetupHierarchy and GlgUpdate.
The following example shows how to create a GLG Custom Control:
#include "GlgApi.h"
HWND GlgControl;
GlgObject drawing; drawing = GlgLoadWidgetFromFile( "BarGraph.g" );
GlgSetDefaultViewport( drawing );
GlgControl = CreateWindow( "GlgControl", "GlgControlTest", WS_VISIBLE
| WS_CHILD | WS_BORDER, 50, 50, 100, 150, parent, NULL, hInstance, NULL );
(LPVOID) GlgInitialDraw( drawing );
Note that only one GLG Custom Control can be attached to each instance of the loaded drawing.
To display several copies of a drawing, you must load or copy several instances of it into memory, creating each control with the CreateWindow function.
Setting Initial Resources
A GLG drawing represents a hierarchy of graphical objects. This hierarchy is created when the drawing is used in a GLG Custom Control. If your application needs to change a resource that affects the structure of a drawing’s resource hierarchy, the most efficient way is to do it before the drawing hierarchy is created (that is, before using the drawing to create a GLG Custom Control).
For example, if you want to change the number of bars in a bar graph's drawing, you should do it before using the drawing for creating a GLG Custom Control:
HWND GlgControl;
GlgObject BarGraphDrawing;
BarGraphDrawing = GlgLoadWidgetFromFile( "BarGraph.g" );
36
GLG Programming Reference Manual
/* Setting the number of bars in the bar graph to 30. */
GlgSetDResource( BarGraphDrawing, "DataGroup/Factor", 30. );
GlgControl = CreateWindow( "GlgControl", "BarGraph Custom Control",
WS_VISIBLE | WS_CHILD | WS_BORDER, 50, 50, 100, 150, parent, NULL, hInstance, NULL );
GlgInitialDraw( BarGraphDrawing );
Resources that must be set before creating the hierarchy include factors of series objects, templates of series objects, Global attribute flags and some others. These are called H resources, and are
described in the H and V Resources section of the Integrating GLG Drawings into a Program chapter.
Some resources, like attributes of an individual instance of the series object's template, may be accessed only after the drawing hierarchy is created. These are the V resources. For example, setting an initial value of the first bar in the bar graph must be done after the bar instances are created: double GetData();
HWND GlgControl;
GlgObject BarGraphDrawing;
BarGraphDrawing = GlgLoadWidgetFromFile( "BarGraph.g" );
GlgControl = CreateWindow( "GlgControl", "BarGraph Custom Control",
WS_VISIBLE | WS_CHILD | WS_BORDER, 50, 50, 100, 150, parent, NULL, hInstance, NULL );
GlgSetupHierarchy( BarGraphDrawing );
/* Setting the value of the first data sample for the initial appearance. */
GlgSetDResource( BarGraphDrawing, "DataGroup/EntryPoint", GetData() );
GlgUpdate( BarGraphDrawing ); /* Draw control's graphics */
The rest of the resources may be changed at any time, although remember that if you want to change some resources for the initial appearance of the control, do it before the call to the GlgUpdate or
GlgInitialDraw functions.
Obtaining a Viewport Handle
To use any of the functions from the GLG API, you must get an object ID for the main viewport of
use the GlgGetWindowViewport function.
GlgObject GlgGetWindowViewport( glg_control_window )
HWND glg_control_window;
The glg_control_window argument is the Window ID returned by the CreateWindow function. If a window other than a GLG Custom Control is passed as a parameter, the result is undefined. The
viewport handle is the return value of this function.
Using the C/C++ version of the Toolkit
37
A viewport is a GLG Toolkit object which manages all aspects of the GLG Custom Control’s behavior and appearance. When accessing resources or performing any other operations on the
Control, the viewport handle is passed as a parameter to the functions of the GLG API Library.
Closing the Custom Control
At the end of a program’s execution, you should use the DestroyWindow Windows function to close the GLG Custom Control in an orderly fashion. By default, this is done for you when you exit the program.
Messages
The GLG Custom Control provides a window procedure to work with the Windows environment.
The GLG Custom Control creates its own color palette and handles palette related messages.
However, Microsoft Windows sends palette messages to the top level window only, therefore the application program must be responsible for propagating these messages to the GLG Custom
Control. A similar situation obtains with some focus messages, as shown in the example below.
An example of how messages are propagated to the GLG Custom Control is shown in the following example: extern HWND GlgControl; /* A children window. */
LRESULT CALLBACK MyWindowProc( hWnd, iMessage, wParam, lParam )
HWND hWnd;
UINT iMessage;
WPARAM wparam;
LPARAM lparam;
{ switch( iMessage )
{
/* Propagate palette messages to the Control. */ case WM_PALETTECHANGED: case WM_QUERYNEWPALETTE: if( GlgControl )
return
GlgControlWindowProc( GlgControl, iMessage, wParam, lParam );
/* Let the Control know about focus change, etc. */ case WM_SETFOCUS: case WM_KILLFOCUS: case WM_CANCELMODE: if( GlgControl )
GlgControlWindowProc( GlgControl, iMessage, wParam, lParam
); break;
... /* Some other application specific cases. */
}
38
GLG Programming Reference Manual
return DefWindowProc( hWnd, iMessage, wParam, lParam );
}
The GlgControlWindowProc function has the standard arrangement of windows procedure parameters, whose definitions can be found in Windows programming manuals. It is included in the
Windows version of the GLG API library.
Loading and Displaying a GLG Drawing using Generic API
The GLG Generic API can be used to load the drawing into a program and display it in a crossplatform way, freeing the programmer from a need to use platform-specific native integration code.
An application written using the simple GLG Generic API can be compiled and run on either
Windows or Unix/Linux without any changes to the source code. GLG demos and most of the coding examples use the GLG Generic API and may be compiled and run under both Windows and
Unix/Linux X Windows environments.
The following example loads and displays a GLG drawing using the GLG Generic API:
#include "GlgApi.h"
#include "GlgMain.h" int GlgMain( argc, argv, InitialAppContext ) int argc; char * argv[];
GlgAppContext InitialAppContext;
{
GlgObject viewport;
GlgInit( False, InitialAppContext, argc, argv ); viewport = GlgLoadWidgetFromFile( “bar1.g” );
GlgInitialDraw( viewport ); return GlgMain( InitialAppContext );
}
The GlgMain.h include file defines a cross-platform program entry point, GlgMain.
The GlgInitialDraw function creates a top-level window and displays a GLG drawing in it in a cross-platform way. This code may be compiled and run on both Unix/Linux and Windows platforms. Refer to the GLG programming examples in the examples directory for a complete example of an application that loads, displays and updates GLG drawing with data.
Alternatively, a call to GlgInitialDraw can be split into two equivalent calls, GlgSetupHierarchy and GlgUpdate, to perform any required initialization before displaying the drawing:
GlgSetDResource( viewport, “Chart/NumPlots”, 3.);
GlgSetupHierarchy( viewport ); /* Creates 3 plots in the chart. */
/* Set any required plot properties. */
GlgSetDResource( viewport, “Chart/Plots/Plot#2/LineWidth”, 3. );
GlgUpdate( viewport ); /* Display the drawing. */
Using the C/C++ version of the Toolkit
39
Refer to the The GLG Generic API section on page 45 for the list of Generic API methods, and to
the GLG C++ Bindings chapter on page 185 for information on using the C++ version of the GLG
Generic API.
Coding Examples of Displaying and Animating a GLG Drawing
Subdirectories examples_c_cpp/animation and examples_c_cpp/BarGraph2D in the GLG installation directory contain examples of loading, displaying and animating a GLG drawing using both the Generic API and the native windowing system controls:
• The version with name ending with a capital “G” uses the GLG Generic API which can be used on both X Windows (Unix/Linux) and Windows.
• The version ending with “X” shows an example using the GLG Wrapper Widget under X
Windows.
• The version ending with “W” uses the GLG Custom Control on Windows.
• The files with a “.c” extension demonstrate the C version, and files with a “.cpp” extension present the C++ version of the same example.
Compiling and running Example Programs
Visual Studio projects are provided in each directory for building demos and most of the examples on Windows. On Unix/Linux, makefiles for building demos and examples are provided in the src
2.2 Compiling and Linking GLG Programs
Building GLG Demos and Examples
Visual Studio Projects for Windows
On Windows, Visual Studio projects are provided for all GLG demos and most of the example programs. The project files are located in each demo or example directory. To build, simply open a project file in the Visual Studio, select the desired platform (Win32 or x64) and build the solution.
The sample projects use the GLG library in a form of a DLL. Refer to the Using Static GLG
Libraries section on page 42 for information about using GLG static libraries.
Makefiles for Unix/Linux
On Unix/Linux, makefiles for building demos and examples are provided in the src subdirectory of the GLG installation directory:
40
GLG Programming Reference Manual
• makefile grabs all source files in the current directory and links them in a single executable. It can be used for building demos which have source files for each demo in a separate directory.
• makefile2 may be used to compile and link individual source files, in case a current directory contains several example programs, such as the example in the examples_c_cpp/animation directory. The makefile2 file should be edited to define source files that have to be included in the build.
To build a project on Unix/Linux, copy one of the above mentioned makefiles into the project’s directory, edit it to define a path to the GLG installation directory and other platform options listed at the beginning of the makefile, then change to the project’s directory and use make to build the project using makefile: cd <project_dir> make
To use makefile2, rename makefile2 to makefile in the project directory or use the -f option: cd <project_dir> make -f makefile2
Using Constant Strings
By default, C++ bindings use constant strings. This may be changed by defining the
CONST_CHAR_PTR macro with a value of 0 before including the GlgClass.h file.
The C API uses non-constant strings by default. This can be changed by defining the
GLG_C_CONST_CHAR_PTR macro with the value of 1 before including the GlgApi.h file.
Linking with the GLG Libraries
The details of the process of linking an application program with the GLG Toolkit library depends on the operating system and windowing environment where the application will run.
X Windows on UNIX/Linux
The libglg library supplied with the GLG Toolkit contains all functions described in this guide, including the GLG Standard Library and GLG Generic API Library. There are several versions of the library for different programming environments:
• libglg.a
The Motif version of the library. On Linux, it was built using OpenMotif 2.3 to support Unicode locales. On other Unix platforms, it was built with the Motif version provided by a vendor.
• libglg_xt.a
Linux only: The Xt-based version of the library that does not use Motif. This version does not support native widgets, such as Motif sliders, buttons and toggles. The GLG version of these controls must be used with this version of the library.
Using the C/C++ version of the Toolkit
41
• libglg_x11.a
The X11 version of the library for use with the GTK and Qt integrations. This version uses an
X11 window as a drawing surface instead of an Xt or Motif widget. It still requires libXt for linking, but does not use it for graphics, which is completely X11-based.
The linking process also requires libz
1
, libjpeg
2
, libpng
3
and libfreetype
4
libraries. For applications that use map server functionality, the libglg_map map server library and the libtiff
5
library are also required. All these libraries are provided in the lib subdirectory of the GLG Toolkit installation. The
GLG libraries must be included in the link list before the X and Motif libraries. Sample makefiles provided in the src subdirectory of the GLG installation contain additional platform-dependent
libraries that may be selected by uncommenting them depending on the platform (refer to the
Makefiles for Unix/Linux section on page 39 for more information).
If a static Motif library is used instead of the default shared library, the following libraries must also be included: libXmu,
libXft, libXext and libXp. On Solaris and AIX, some extra system libraries (libnsl and libsocket for Solaris, and libiconv for AIX) must also be included, as shown in the sample makefiles.
The following line shows a sample of the link statement for the GLG program using the Standard
API and the Map Server on Linux platform:
... -lglg -lglg_map -lXm -lXt -lX11 -lz -ljpeg -lpng -ltiff \
-lfreetype -lm -ldl -lpthread ...
If an application does not use the Map Server and GIS functionality, the libglg_map library may be replaced with the libglg_map_stub stub, and the libtiff library may be omitted. The following line shows a fragment of the link statement for the GLG program using the Standard API without the
Map Server and GIS functionality:
... -lglg -lglg_map_stub -lXm -lXt -lX11 -lz -ljpeg -lpng \
-lfreetype -lm -ldl -lpthread ...
The GLG Extended Library is called libglg_ext. It requires the Standard API library (libglg) as well as all libraries described above. The following two lines show examples of linking with and without the Map Server and GIS functionality:
... -lglg_ext -lglg -lglg_map -lXm -lXt -lX11 -lz -ljpeg -lpng -ltiff \
-lfreetype -lm -ldl -lpthread ...
... -lglg_ext -lglg -lglg_map_stub -lXm -lXt -lX11 -lz -ljpeg -lpng \
-lfreetype -lm -ldl -lpthread ...
The GLG Extended Library can be omitted if an application does not use any of the Extended API functions.
The GLG Intermediate Library libglg_int may be used instead of the GLG Extended Library
libglg_ext.
1.
Copyright
© 1995-2002 Jean-loup Gailly and Mark Adler.
2.
Copyright
© 1991-1998, Thomas G. Lane, The Independent JPEG Group.
3.
Copyright
© 2004, 2006-2014 Glenn Randers-Pehrson.
4. Copyright
© 1996-2000 by David Turner, Robert Wilhelm, and Werner Lemberg, FreeType Team.
5. Copyright
© 1988-1997, Sam Leffler. Copyright © 1991-1997 Silicon Graphics, Inc.
42
GLG Programming Reference Manual
On platforms that support both the 32 and 64 bit executables, the 64 bit versions of libraries and utilities are provided in the lib_64 directory.
Windows
Using GLG DLLs
The DLL version of the GLG Standard Library is called Glg.dll. To use it, link your application with the Glg.lib library.
The GLG Intermediate Library DLL is called GlgIn.dll and includes the GLG Standard API. This means you don’t have to link with the Glg.lib if using GlgIn.dll. Link only with the GlgIn.lib library to use the Intermediate API DLL.
The GLG Extended Library DLL is called GlgEx.dll and includes the GLG Standard and Extended
APIs. This means you don’t have to link with the Glg.lib if using GlgEx.dll. Link only with the
GlgEx.lib library to use the Extended API DLL.
Using Static GLG Libraries
Under Microsoft Windows, an application can be linked with either a static or dynamic GLG library.
Two versions of static libraries are provided: one compiled with the multi-threaded DLL (/MD) option, and another compiled with the multi-threaded (/MT) option. The libraries compiled with the
/MT option use the MT suffix to differentiate them from the libraries compiled with /MD, for example: GlgLibMT.lib vs. GlgLib.lib. A version of the library matching the compilation options of the application code should be used for linking with the GLG static libraries.
The static versions of the GLG Standard API Library are called GlgLib.lib and GlgLibMT.lib.
The static versions of the GLG Intermediate Library are called GlgInLib.lib and GlgInLibMT.lib.
They also require linking with the corresponding version of the GLG Standard Library: GlgLib.lib or GlgLibMT.lib.
The static versions of the GLG Extended Library are called GlgExLib.lib and GlgExLibMT.lib.
They also require linking with the corresponding version of the GLG Standard Library: GlgLib.lib or GlgLibMT.lib.
The project files supplied with the Toolkit use dynamic linking with the GLG DLLs by default. In order to use the static version of the GLG libraries, define GLG_STATIC in your code:
#define GLG_STATIC
This must appear before the GlgApi.h file, or it may be specified as a preprocessor definition in the project’s settings.
To use the static GLG library, an application code must also include a call to the GlgInit method, passing an explicit application instance as the application context parameter. (If the dynamic library is used, this is done automatically by the DLL’s DllMain entry point.)
Using the C/C++ version of the Toolkit
43
OpenGL Libraries
The OpenGL libraries for the OpenGL renderer - libGL and libGLU - are dynamically loaded by the Toolkit and do not need to be linked in the application executable. If an application uses
OpenGL calls itself, it can link the OpenGL libraries, and the Toolkit will use the linked-in libraries.
The same application executable may be run in either the OpenGL rendering mode or the native windowing system (GDI) mode. Refer to the Command-line Options section on page 235 of the
GLG User’s Guide and Builder Reference Manual for information on the command-line options
that specify rendering mode to be used at run-time.
Refer to the OpenGL or GDI (Native Windowing System) Renderer section on page 24 of the GLG
User’s Guide and Builder Reference Manual for information on the OpenGL and GDI drivers.
If the graphics card supports OpenGL version 3.00 and above, a shader-based Core profile may be used for rendering. Refer to the OpenGL Versions, Compatibility and Core Profiles section on page
25 of the GLG User’s Guide and Builder Reference Manual for more information on OpenGL
versions.
Refer to the OpenGL Libraries section on page 27 of the GLG User’s Guide and Builder Reference
Manual for a detailed description of the libraries used by both hardware and software OpenGL
renderers.
Refer to the OpenGL Setup and Diagnostics section on page 27 of the GLG User’s Guide and
Builder Reference Manual for setup and diagnostic options of the OpenGL driver.
Qt and GTK Integration
The GLG Toolkit provides the Qt, GTK and GTKMM integration files in the integration directory which contains a separate subdirectory for each of the environments. Each subdirectory contains an integration example with a source code of a specialized GLG widget for the corresponding environment: QtGLGWidget, GTKGlgWidget and GTKMMGlgWidget. All files required to build the project are also provided.
In the Linux/Unix environment, the libglg_x11 library described above must be used with the integration, since both Qt and GTK do not use Xt.
In the Microsoft Windows environment, the standard GLG library is used with the integration.
Error Processing
All GLG library errors are reported using the default error handler. In the X Windows environment, this prints an error message on the console, and under Microsoft Windows, displays a message box with an error message. On both platforms the default handler also emits an audio beep and logs the error into the glg_error.log file.
The log file will be created in the directory specified by the following environment variables:
44
GLG Programming Reference Manual
GLG_LOG_DIR_<Major>_<Minor>
GLG_LOG_DIR
GLG_DIR_<Major>_<Minor>
GLG_DIR
The environmental variables are searched in the order they are listed above. The <Major> and
<Minor> are replaced by the major and minor version numbers, for example GLG_DIR_3_6. If neither variable is defined, the current directory will be used.
In the Java version, the errors are printed on the standard output stream (or in the Java Console when used inside of a web browser), and the errors are not logged in a file.
The C#/.NET version displays an error message box, beeps and logs the errors into the glg_error.log file, the same as the C/C++ version.
The Map Server errors are logged in the glm_error.log file, which will be created in the directory specified by the GLM_LOG_DIR_<Major>_<Minor> and GLM_LOG_DIR environment variables. If they are not set, either GLG_LOG_DIR or GLG_DIR versions of environment variables listed above are used to determine the directory in which the Map Server log file will be created. If neither environment variable is defined, the current directory is used.
To intercept errors or to change this behavior, you may install a custom error handler using the
GlgSetErrorHandler function. (This is part of the standard GLG API; see the the Animating a GLG
Drawing with Data Using the Standard API chapter.). Severe internal errors (like invalid object
handles) will still be logged into the glg_error.log file, but errors involved with the use of the GLG
Toolkit, like not being able to set or get a resource, will not.
In the X Windows environment, the XtError function is used to report widget-related errors (such as an error setting the wrapper widget’s resource). You can use XSetErrorHandler function to install a custom error handler for Xt errors. The XSetErrorHandler function can be used to install a custom error handler for X Windows errors.
Using the C/C++ version of the Toolkit
45
2.3 The GLG Generic API
If it is important for your application to be cross-platform compatible (or if you don’t want to learn another windowing API), you may use the GLG Generic API instead of the GLG Custom Control on WIndows or the GLG Wrapper Widget for Unix/Linux. It contains a generic, platform independent API for creating and manipulating a GLG Widget, as well as a small set of functions for cross-platform development. An application written using the GLG Generic API may be ported between Windows and the Unix/Linux environment by simply recompiling the code. The supplied demos and other coding examples of GLG Generic API may be compiled and run under both
Windows and X Windows Unix/Linux environments.
The GLG Generic API is a subset of the GLG Standard API that provides functions for initializing the Toolkit’s run time environment, loading a drawing and displaying it in a program using the capabilities of the native windowing system: Windows or X Windows on Unix/Linux. After loading and displaying the drawing, it is animated using the rest of the functions of the GLG Standard API,
which are also cross-platform. A coding example of using the Generic API is provided in the
Loading and Displaying a GLG Drawing using Generic API section on page 38.
Though the functions provided are all platform-independent, the GLG Generic API library is not intended as a complete cross-platform development library. Instead, it supplies a small set of functions which are sufficient for a platform-independent use of GLG drawings and the GLG
Toolkit. It is up to the application developer to write the rest of the application in a platformindependent way.
Function Summary
The GLG Generic API includes the following functions:
• GlgInitLocale sets locale.
• GlgInit initializes the Toolkit.
• GlgTerminate terminates the Toolkit and frees any allocated memory.
• GlgLoadWidgetFromFile loads a GLG Widget drawing from a file.
• GlgLoadWidgetFromImage loads a GLG Widget drawing from a generated memory image.
• GlgLoadWidgetFromObject extracts a GLG widget drawing from a GLG object.
• GlgSetupHierarchy sets up a GLG Widget’s drawing hierarchy.
• GlgResetHierarchy resets a GLG Widget’s drawing hierarchy in preparation for being dereferenced with GlgDropObject.
• GlgInitialDraw draws a GLG Widget for the first time.
• GlgMainLoop polls for events.
• GlgAddCallback adds input, selection and other callbacks to a GLG drawing.
46
GLG Programming Reference Manual
• GlgAddWorkProc adds a work procedure.
• GlgRemoveWorkProc removes an active work procedure.
• GlgAddTimeOut adds an interval timer.
• GlgRemoveTimeOut removes an active interval timer.
• GlgSleep suspends program's execution.
• GlgBell produces a bell sound.
• GlgRand generates a random number.
These functions are described in detail in the following pages.
Two functions of the GLG Extended API are often used with and are included in the GLG Generic
API:
• GlgReferenceObject increments the reference count of an object.
• GlgDropObject decrements the reference count of an object.
For description of these functions, see the GLG Intermediate and Extended API chapter.
Generic Program Entry Point
To define a cross-platform application program’s entry point both Unix/Linux and Windows environments, include the GlgMain.h header file at the beginning of the program and define the
GlgMain function in the following way:
#include "GlgApi.h"
#include "GlgMain.h" int GlgMain( argc, argv, InitialAppContext ) int argc; char * argv[];
GlgAppContext InitialAppContext;
{
GlgInit( False, InitialAppContext, argc, argv );
... /* Place code here. */
}
The defined GlgMain function will be called when the program is started. The argc and argv parameters are analogous to the corresponding parameters of the standard main() function. The
InitialAppContext parameter must be passed to the GlgInit function as shown above.
GLG Generic API Function Descriptions
In order to use any of the functions in the GLG Generic API, you must include the following header file in your program:
#include "GlgApi.h"
Using the C/C++ version of the Toolkit
47
GlgAddCallback
Adds a callback function to a GLG Widget.
void GlgAddCallback( viewport, callback_type, callback, client_data )
GlgObject viewport;
GlgCallbackType callback_type;
GlgCallbackProc callback;
GlgAnyType client_data;
Parameters
viewport
Specifies the viewport of a GLG Widget.
callback_type
Specifies the type of a callback to be added, such as GLG_SELECT_CB, GLG_INPUT_CB,
GLG_TRACE_CB, GLG_TRACE2_CB or GLG_HIERARCHY_CB. See the Callback
Events section of the Handling User Input and Other Events chapter for a description of
callback functions. There are also special callbacks used with the GLG Wrapper Widget; see
callback
Specifies a callback function to be called.
client_data
Specifies client data to be passed to the callback function when it is called. See the Callback
Events section of the Handling User Input and Other Events chapter for a description of this
data.
This function adds a selection or input callback to a GLG Widget. A callback is a user-supplied function that is called by the GLG Toolkit upon some action. A selection callback is issued when a user selects an object in the widget’s drawing area. An input callback function is invoked when a viewport input handler has received some data.
Only one callback of each callback type may be added to one widget or an individual viewport. Any subsequent invocations of this function will overwrite the previous value of the callbacks. To remove a callback, call GlgAddCallback with NULL as a value of the callback parameter.
Callbacks must be added before the drawing's hierarchy is set up. Several input and selection callbacks may be added to different viewports on different levels of the drawing hierarchy.
However, only the first encountered callback on the lowest level of the hierarchy will be called.
For details on the form and use of callback functions, see the Callback Events section of the
Handling User Input and Other Events chapter.
48
GLG Programming Reference Manual
GlgAddTimeOut
Adds an interval timer in a platform-independent way.
GlgLong GlgAddTimeOut( app_context, interval, timer_callback, client_data )
GlgAppContext app_context;
GlgLong interval;
GlgTimerProc timer_callback;
GlgAnyType client_data;
Parameters
app_context
Specifies the application context returned by the GlgInit function.
interval
Specifies the time interval in milliseconds.
timer_callback
Specifies a procedure to be called when the time expires.
client_data
Specifies the client data to be passed to the specified procedure when it is called.
This function adds a procedure which is called when the specified time interval expires. It returns the timer ID which can be used with GlgRemoveTimeOut. The interval timer is called only once and is removed immediately after it has been called. The GlgRemoveTimeOut function may be used to remove an active timeout. If you want the timer procedure to be called continuously, the timer procedure itself should call GlgAddTimeOut.
The following is a prototype for a timer procedure function: typedef void (*GlgTimerProc)( client_data, timer_id )
GlgAnyType client_data;
GlgLong * timer_id;
The timer_id parameter is the same as the one returned by the GlgAddTimeOut function. The
client_data argument is the same as the one supplied in the GlgAddTimeOut function.
GlgAddWorkProc
Adds a work procedure in a platform-independent way.
GlgLong GlgAddWorkProc( app_context, work_proc, client_data )
GlgAppContext app_context;
GlgWorkProc work_proc;
GlgAnyType client_data;
Parameters
app_context
Specifies the application context returned by the GlgInit function.
Using the C/C++ version of the Toolkit
49
work_proc
Specifies a work procedure function to be called repeatedly.
client_data
Specifies client data to be passed to the work procedure when it is called.
This function adds a work procedure to a widget. A work procedure is simply a function to be called repeatedly while the application is waiting for an event. It returns a work procedure ID that can be used by GlgRemoveWorkProc.
The following code is the prototype for a work procedure function: typedef GlgBoolean (*GlgWorkProc)( client_data )
GlgAnyType client_data;
The client_data argument provides user-defined data to the work procedure. It is defined by the call to GlgAddWorkProc.
If a work procedure returns TRUE, it is removed and will not be called again. If it returns FALSE, it will be called continuously until the application calls the GlgRemoveWorkProc function. You can register several work procedures and they will be performed one at a time. Work procedures must return quickly to avoid response time delays.
GlgBell
Produces a bell sound in a platform-independent way.
void GlgBell( viewport )
GlgObject viewport;
Parameters
viewport
Specifies a viewport object. This viewport object must be displayed; it specifies the display at which to produce the bell. On Microsoft Windows, this parameter is ignored and may be
NULL.
GlgInit
Initializes the GLG Toolkit.
GlgAppContext GlgInit( tk_initialized, app_context, argc, argv )
GlgBoolean tk_initialized;
GlgAppContext app_context; int argc; char ** argv;
Parameters
tk_initialized
Specifies whether or not X Toolkit was already initialized by the program. It allows using the
GLG Toolkit in an application that creates its own application context. If this parameter is
50
GLG Programming Reference Manual
FALSE, the X Toolkit will be initialized by the function. Otherwise, it is assumed that the program has already initialized it.
This parameter is for use only in the X Windows environment and must be FALSE on
Microsoft Windows.
app_context
For X Windows, this argument specifies the Xt application context if one has already been created by the program. If NULL is passed, an application context will be created by this function. Otherwise it uses the passed application context.
In Microsoft Windows environment, the argument specifies an application instance handle, which is supplied by a parameter of the GlgMain or WinMain program entry points. In an
MFC application, a call to AfxGetInstanceHandle function may be used to obtain application instance handle. If the GLG library is used in the form of a DLL, the application instance handle is obtained automatically and the value of NULL may be used for the argument. If a static GLG library is used, an application instance handle must be supplied explicitly.
argc
Specifies the number of command line parameters. Use zero on Microsoft Windows.
argv
Specifies the command line parameter list. NULL may be used on Microsoft Windows.
If the function creates an application context, it returns the created context, otherwise it returns the application context that was passed to it. The return value is later used with some other functions of the GLG Generic API.
In the X Windows environment, this function is not needed if the GLG is deployed in the form of the GLG Wrapper Widget, which invokes the function automatically. Under Microsoft Windows, this function has to be called only if your program is linked with the static version of the GLG API library. The dynamically linked library (DLL) version calls this function automatically. In both cases, the function may be called explicitly to process command line options recognized by the
Toolkit, such as:
-verbose generates extended diagnostic output. A verbose mode can also be set by setting the
GLG_VERBOSE environment variable to True. The output is saved in the glg_error.log file. On Unix/Linux, the output is also displayed in the terminal.
-glg-debug-opengl generates extended diagnostic output for the OpenGL driver. The output can also be activated by setting the GLG_DEBUG_OPENGL environment variable to True. The output is saved in the glg_error.log file. On Unix/Linux, the output is also displayed in the terminal.
-glg-disable-error-dialogs
Disables error and warning message dialogs on Windows. Alternatively, the dialogs can also be disabled by setting the GLG_DISABLE_ERROR_DIALOGS environment variable to True. The messages will still be logged in the glg_error.log file.
-glg-disable-opengl disables OpenGL driver in favor of the native windowing driver.
Using the C/C++ version of the Toolkit
51
-glg-enable-opengl enables OpenGL driver if present. The OpenGL driver will be used only for the viewports which have their OpenGLHint attribute set to ON.
The OpenGL driver may also be enabled or disabled by setting either the GlgOpenGLMode global configuration resource or the GLG_OPENGL_MODE environment variable to the following values:
0 - disable the OpenGL driver
1 - enable the OpenGL driver
-1 - don’t change the default setting.
GlgInitLocale
Sets the program locale.
GlgBoolean GlgInitLocale( locale ) char * locale;
Parameters
locale
Specifies program locale. The value of NULL may be passed to use the current system locale.
The function invokes setlocale( LC_ALL, locale ) and performs any other platform-dependent locale initialization activity. On Unix platforms, this function must be used before the GlgInit function.
GlgInitialDraw
Draws a GLG widget for the first time after it has been created or loaded.
void GlgInitialDraw( viewport )
GlgObject viewport;
Parameters
viewport
Specifies the viewport of a GLG Widget.
This function is used when a GLG Widget is created. Creating the widget, in this case, means constructing the internal data structures that are the widget. The widget must still be rendered with
GLGInitialDraw to be seen by a user. If the GLG Wrapper Widget is used in the X environment, this function is called automatically, and need not be explicitly called.
GlgLoadWidgetFromFile
Loads a GLG widget from a file.
GlgObject GlgLoadWidgetFromFile( filename ) char * filename;
52
GLG Programming Reference Manual
Parameters
filename
Specifies the name of the widget's drawing file.
This function loads a drawing from a file and searches the drawing for a viewport object named
“$Widget.” If the viewport is found, it references and returns a handle to it, otherwise it produces an error message and returns NULL. After the viewport has been used to create a GLG Wrapper
Widget or GLG Custom Control, it may be dereferenced using the GlgDropObject function to avoid memory leaks.
GlgLoadWidgetFromImage
Loads a GLG widget from a memory image.
GlgObject GlgLoadWidgetFromImage( image_address, image_size ) void * image_address;
GlgLong image_size;
Parameters
image_address
Specifies the address of the widget's drawing image generated by the GLG Code Generation
Utility.
image_size
Specifies the image size. This is also generated by codegen.
This function loads a drawing from the drawing image and searches the drawing for a viewport named “$Widget.” If the viewport is found, it references and returns it, otherwise it produces an error message and returns NULL. After the viewport has been used, it may be dereferenced using the GlgDropObject function.
NOTE: this function does not work with compressed drawing files. Save drawings with the drawing compression option disabled to use them with GlgLoadWidgetFromImage.
GlgLoadWidgetFromObject
Loads a widget from a GLG object.
GlgObject GlgLoadWidgetFromObject( object )
GlgObject object;
Parameters
object
Specifies a GLG object to be used as a widget's drawing.
Using the C/C++ version of the Toolkit
53
This function searches the object to be used as a drawing for a viewport named “$Widget.” If the viewport is found, it references and returns it, otherwise it produces an error message and returns
NULL. This function could be used to load a widget created by using the GLG Extended API, or to load a sub-section of an already loaded drawing. After the viewport has been used, it may be dereferenced using the GlgDropObject function.
GlgMainLoop
Implements an event polling loop in a platform independent way.
GlgLong GlgMainLoop( app_context )
GlgAppContext app_context;
Parameters
app_context
Specifies the application context returned by the GlgInit function.
On Microsoft Windows, the return value of this function may be used as the return value of the
GlgMain function.
GlgRand
Produces a random number in a platform-independent way.
double GlgRand( low, high ) double low; double high;
Parameters
low, high
Specify the low and high range of the random numbers generated.
This function produces a random number in the specified range by using the platform’s rand function.
GlgRemoveTimeOut
Removes a timer procedure.
void GlgRemoveWorkProc( timer_id )
GlgLong timer_id;
Parameters
timer_id
Specifies the ID of the timer procedure to be removed. The ID was returned by
GlgAddTimeOut.
This function removes an active timer. If the timer has already been removed and is not active, the results are undefined.
54
GLG Programming Reference Manual
GlgRemoveWorkProc
Removes a work procedure.
void GlgRemoveWorkProc( workproc_id )
GlgLong workproc_id;
Parameters
workproc_id
Specifies an id of the work procedure to be removed. The id was returned by
GlgAddWorkProc.
This function removes an active work procedure. If the work procedure has already been removed and is not active, the results are undefined.
GlgResetHierarchy
Resets the object hierarchy.
void GlgResetHierarchy( object )
GlgObject object;
Parameters
viewport
Specifies an object to be reset.
Resets the object hierarchy of a top-level viewport or drawing. This function must be called before destroying a top-level object with GlgDropObject when the object was displayed using the Generic
API. This function should not be called for viewports used in the GLG integrated containers, such as the GLG Wrapper Widget or GLG Custom Control.
Warning: Do not confuse this function with the GlgReset function of the standard API. GlgReset is used to redraw a displayed drawing and to regenerate the object hierarchy.
GlgSetupHierarchy
Provides an explicit request to set up the object hierarchy.
void GlgSetupHierarchy( object )
GlgObject object;
Parameters
object
Specifies an object to be set up.
When invoked on a drawing which has been loaded but not yet displayed, the method sets up the drawing’s object hierarchy to prepare the drawing for rendering. The drawing should contain either a top-level viewport object, or a group containing several top-level viewports.
Using the C/C++ version of the Toolkit
55
After the initial draw (when the object hierarchy has already been set up), the method can be used to set up any type of object after its resources were changed. Unlike the GlgUpdate method,
GlgSetupHierarchy sets up the object without repainting it.
GlgSleep
Suspends the application execution for a specified interval in a platform independent way.
void GlgSleep( sleep_interval )
GlgLong sleep_interval;
Parameters
sleep_interval
Specifies a sleep interval in milliseconds.
GlgTerminate
Terminates the application’s use of the GLG Toolkit.
void GlgTerminate( void )
This function destroys all created GLG structures and frees allocated memory, flushing the internal memory pools. No GLG functions may be called after a call to GlgTerminate.
56
GLG Programming Reference Manual
57
2.4 Animating a GLG Drawing with Data Using the Standard API
The GLG Application Program Interface (API) provides a way for a user’s C program to animate a
GLG drawing. The API consists of a set of functions for querying and changing the resources of a
GLG drawing. As a convenience to the programmer, it also provides some functions for frequently needed functions, such as specialized string manipulation, etc.
Note that the drawing must be displayed before it can be animated. For information on displaying
a GLG drawing from a program, see the Displaying a GLG Drawing chapter on page 27. Though
the details of displaying a drawing are platform-dependent, the functions described in this chapter are not. The syntax of the API described in this chapter is the same on X Windows or in Microsoft
Windows.
There are three flavors of the GLG API:
• The Standard API enables an application to display a GLG drawing, animate it via the use of either resources or data tags, as well as handle user interaction.
• The GLG Intermediate API is a subset of the Extended API that provides all of the Extended
API methods for manipulating the drawing, except for the methods for creating, adding or deleting objects from the drawing at run time. It is typically used for introspection (examining the content of a drawing), advanced input handling, as well as for obtaining object IDs for direct data updates, which increases update performance by shortcutting the resource namebased resource search.
• The GLG Extended API adds functionality that allows an application program to edit or create the drawing at run time.
The rest of this chapter describes functions of the GLG Standard API.
Overview
Once a GLG drawing is created and displayed, it is a simple matter to animate it. Animating a GLG drawing is done simply by manipulating its resources. This means that the only actions a program need take is to query or to set some resource value, and occasionally to redisplay the drawing with the new resource values.
The simplicity of operation means that the GLG API is quite a small one. It consists of the following functions:
• GlgSetDResource, GlgSetDResourceIf and GlgSetDTag set a scalar resource or tag. For information about the different attribute data types (geometrical, scalar, and string), see the
The Attribute Object section in the Structure of a GLG Drawing chapter.
• GlgSetGResource, GlgSetGResourceIf and GlgSetGTag set a geometrical resource or tag.
• GlgSetSResource, GlgSetSResourceIf and GlgSetSTag set a string resource or tag.
• GlgSetSResourceFromD, GlgSetSResourceFromDIf and GlgSetSTagFromD set a string resource or tag from a scalar according to a chosen format.
• GlgSetResourceFromObject Sets a resource using another object.
58
GLG Programming Reference Manual
• GlgGetDResource and GlgGetDTag return a scalar resource or tag.
• GlgGetGResource and GlgGetGTag return a geometrical resource or tag.
• GlgGetSResource and GlgGetSTag return a string resource or tag.
• GlgHasResourceObject checks if a named resource exists.
• GlgHasTagName and GlgHasTagSource check if a tag with a specified tag name or tag source exists.
• GlgCreateTagList returns a list of tags defined in the drawing.
• GlgSetZoom provides programmatic access to the integrated zooming and panning features.
• GlgSetZoomMode sets or resets the GIS or Chart zoom mode.
• GlgUpdate redisplays the drawing using the current resource values. All resource changes are stored until this function is called or until an Expose event (or paint event on Windows) is received.
• GlgPrint saves a PostScript image of the widget’s current state into a file.
• GlgWinPrint (Windows only) invokes the native Microsoft Windows printing function .
• GlgSaveImage and GlgSaveImageCustom save an image of the drawing in the JPEG or
PNG format.
• GlgReset reinitializes a widget drawing.
• GlgSendMessage sends a message to an object to request some action to be performed.
• GlgSetAlarmHandler defines a function that will process alarm messages.
• GlgSetTooltipFormatter sets a custom tooltip formatter.
• GlgGetNativeComponent returns an ID of a native windowing system component used to render the viewport.
There are a few specialized functions related to a real-time chart object:
• GlgGetNamedPlot queries a chart’s plot by its name.
• GlgAddPlot adds a plot to a chart.
• GlgDeletePlot deletes a plot from a chart.
• GlgClearDataBuffer clears accumulated data samples of a real-time chart or one of its plots.
• GlgGetDataExtent queries the extent of the data accumulated in the chart’s plots.
• GlgSetLabelFormatter attaches a custom label formatter to a stand-alone axis or an axis of a chart.
• GlgSetChartFilter attaches a custom data filter to a chart’s plot.
• GlgSetLinkedAxis links a chart’s plot or a level line level with an axis for automatic rescaling.
59
The GLG Standard API also includes the following container methods described the GLG
Intermediate and Extended API chapter:
• GlgGetElement returns the object at the specified index in a container.
• GlgGetSize queries the size of a container object.
The GlgAddCallback function is used to add callbacks for handling user input in the form of input, selection and other events. While this function is a part of the GLG Standard API, it is described in
detail in the Callback Events chapter on page 105.
GlgSetDefaultViewport is provided in the Windows version of the API and is used for setting a default drawing to be used by the GLG Wrapper Widget or GLG Custom Control.
The GLG Standard API also includes the following convenience and utility functions that simplify tasks common to GLG C programs.
• GlgGetObjectName, GlgGetObjectType and GlgGetDataType provide convenient shortcuts for querying corresponding properties of an object.
• GlgStrClone creates a copy of a string.
• GlgCreateIndexedName creates an enumerated resource name.
• GlgConcatResNames creates composite resource names from components.
• GlgConcatStrings creates a new string from two input stings.
• GlgAlloc allocates memory using the Toolkit’s memory allocator.
• GlgFree frees the memory allocated by GlgAlloc and GLG string utility functions.
• GlgSetErrorHandler replaces the GLG Toolkit error handler.
• GlgGetSelectionButton is used inside a selection callback procedure to query the mouse button that caused the selection event.
• GlgGetModifierState provides a cross-platform way to query the state of the Control and
Shift keys.
• GlgSetFocus provides a cross-platform way to set the keyboard focus.
• GlgExportStrings exports all text strings defined in the drawing into a string translation file.
• GlgImportStrings imports translated text strings from a string translation file.
• GlgExportTags exports tag names and tag sources of all tags defined in a drawing into a file.
• GlgImportTags replaces tag names and tag sources in a drawing with the information imported from a tag translation file.
• GlgChangeObject sends a change message to the object without actually changing the object’s properties, may be used to force the object to redraw.
• GlgSetBrowserObject defines the object whose resources will be displayed by the resource, tag and alarm browser widgets.
• GlgSetBrowserSelection sets a new value of a browser’s selection and filter text boxes for the resource, tag, alarm and data browser widgets after the browser has been set up.
60
GLG Programming Reference Manual
• GlgSetEditMode disables viewport’s input objects for editing.
• GlgGISConvert performs coordinate conversion from the GIS coordinates of the GIS Object to the GLG coordinates of the drawing and vise versa.
• GlgGISGetElevation returns an elevation of a specified lat/lon point on a map.
• GlgGISCreateSelection returns information about GIS features located at a specified map location.
• GlgGISGetDataset retrieves the dataset object of a GIS object.
• GlgSetLParameter and GlgGetLParameter are used to set or query values of global parameters that control memory allocation at run time.
• GlgPreAlloc is used to preallocate memory under the control of a mission-critical real-time application.
• GlgSetCursor is used to set a custom cursor for a drawing or one of its child viewports (Windows only).
• GlgFindFile may be used to find a file in the GLG search path.
• GlgError displays error and information messages.
• GlgGetMajorVersion and GlgGetMinorVersion retrieve the library’s version numbers.
Note: Several resources in a GLG drawing may affect the actual object hierarchy of the drawing.
The Factor attribute of a series object, for example, controls the number of objects that appear to be members of that series. When manipulating the resources of a drawing with the GLG API, it is useful to set the resources that affect the object hierarchy first, then call GlgUpdate, and then set the resources that only affect the value of objects in that hierarchy. For more information about this
distinction between resources, see the H and V Resources section of the Integrating GLG Drawings
Function Descriptions
To use any of the functions described in this chapter, the application program must include the function definitions from the GLG API header file. Use the following line to include these definitions:
#include "GlgApi.h"
Some resources have enumerated values. For example, the ScrollType resource of a graph may have values GLG_SCROLLED or GLG_WRAPPED. The GlgApi.h file has defined constants to use for setting these resource values.
61
Note that virtually all of the GLG API library functions have the same first argument: a GlgObject parameter called object. This argument is a handle pointing to an object in the drawing. Usually, it indicates the viewport object that is the widget in the drawing. This handle is returned by the
platform-specific display functions described in the Using the C/C++ version of the Toolkit chapter.
The object parameter may also provide an object ID of a graphical object inside the viewport.
The following describes the interfaces of the GLG Standard Library functions.
GlgAlloc
Allocates memory using the Toolkit’s memory allocator.
void * GlgAlloc( size )
GlgLong size;
Parameters
size
Specifies the size of a memory block in bytes.
The memory must be freed with GlgAlloc when it is no longer used.
GlgAddPlot
Adds a plot to a chart object.
GlgObject GlgAddPlot( object, resource_name, plot )
GlgObject object; char * resource_name;
GlgObject plot;
Parameters
object
Specifies a chart or a container object containing the chart.
resource_name
Specifies a resource name for accessing the chart inside the container. Use NULL when the
object parameter specifies the chart.
plot
Specifies an object ID of a plot object. NULL may be used to create a new plot.
62
GLG Programming Reference Manual
The function returns an object ID of the added plot on success, or NULL if it fails.
GlgChangeObject
Sends a change message to the object without actually changing the object’s properties.
void GlgChangeObject( object, resource_name )
GlgObject object; char * resource_name;
Parameters
object
If the resource_name parameter is NULL, specifies the object to send the message to. If the
resource_name parameter is not NULL, specifies the object’s parent.
resource_name
If not NULL, specifies the resource name of the object inside the parent object specified by the
object parameter.
The function may be used to force a drawable object (such as a viewport) to redraw its content. It may also be used to send a change message to the Factor attribute of a series object to force the series to recreate its instances without actually changing the value of the Factor. If a change message is sent to the ImageFile attribute of an image object, the image will reload the image file
(the image’s EnableCache attribute should be set to NO to disable cache for images that need to be reloaded).
GlgClearDataBuffer
Clears accumulated data samples of a real-time chart or one of its plots.
GlgBoolean GlgClearDataBuffer( object, resource_name )
GlgObject object; char * resource_name;
GlgObject plot;
Parameters
object
Specifies a chart, a plot or a container object containing the chart.
resource_name
If not NULL, specifies a resource name for accessing the chart or one of its plots inside the container specified by the object parameter. Use NULL when the object parameter specifies a chart or plot object.
For a Chart object, GlgClearDataBuffer discards data samples in all plots of the chart. For a Plot object, it discards only the data samples of that plot. The method returns True on success
63
GlgConcatResNames
Creates a composite resource name from two components.
char * GlgConcatResNames( resource_name1, resource_name2 ) char * resource_name1, * resource_name2;
Parameters
resource_name1
Specifies the first path component.
resource_name2
Specifies the second path component.
This function creates and returns a resource name formed by concatenating the two components with the / character between them. Either argument may be NULL, in which case the returned string will precisely equal the input value of the other argument. The string containing the returned resource name should be freed later with the GlgFree function.
For example, the following code fragment: char * resource_name; resource_name =
GlgConcatResNames( "DataGroup", "DataSample2" ); printf( "resource_name = %s\n", resource_name );
GlgFree( resource_name ); produces the following output: resource_name = DataGroup/DataSample2
Multiple calls to the GlgConcatResNames function may be used to create composite names from more than two components: char
* temp_name,
* resource_name; temp_name =
GlgConcatResNames( "DataGroup", "DataSample2" ); resource_name = GlgConcatResNames( temp_name, "Value" );
GlgFree( temp_name ) printf( "resource_name = %s\n", resource_name );
GlgFree( resource_name ); produces the following output: resource_name = DataGroup/DataSample2/Value
64
GLG Programming Reference Manual
GlgConcatStrings
Concatenates two character strings.
char * GlgConcatStrings( string1, string2 ) char * string1, string2;
Parameters
string1, string2
The strings to be concatenated.
This function creates a new string from two input strings. Either input string may be NULL, in which case the returned string is a copy of the non-NULL input string. If both strings are NULL, then NULL is returned. The output of this function must be freed with the GlgFree function. That function also understands null data, so the following code may be used without needing to check for NULL values: string3 = GlgConcatStrings( string1, string2 );
...
GlgFree( string3 );
GlgCreateIndexedName
Creates a string with a name for an enumerated resource.
char * GlgCreateIndexedName( template_name, resource_index ) char * template_name;
GlgLong resource_index;
Parameters
template_name
A character string containing the template name to be expanded. This name uses the % character to define the expansion position.
resource_index
Specifies the number to use for expanding a % character in the template name.
This function creates and returns a resource name by replacing the first (leftmost) occurrence of the
% expansion character within the template name with the number corresponding to the
resource_index parameter. If the template name does not contain the expansion character, the number is added to the end of the name. The returned expanded name should later be freed with the
GlgFree function.
65
Example
The following code fragment: char * name; int i; for( i=0; i<3; ++i )
{ name = GlgCreateIndexedName( "XLabelGroup/XLabel%/String", i ); printf( "Name: %s\n", name );
GlgFree( name );
} produces the following output:
Name: XLabelGroup/XLabel0/String
Name: XLabelGroup/XLabel1/String
Name: XLabelGroup/XLabel2/String
The GlgCreateIndexedName function may be used repeatedly if a template name has more than one expansion character. For example, the following code fragment: char * name1, * name2; name1 =
GlgCreateIndexedName( "Graph%/DataSample%/Value", 4 ); name2 = GlgCreateIndexedName( name1, 5 );
GlgFree( name1 ); printf( "Name: %s\n", name2 );
GlgFree( name2 ); produces the following output:
Name: /Graph4/DataSample5/Value
GlgCreateTagList
Creates and returns a list of tags.
GlgObject GlgCreateTagList( object, unique_tag_sources )
GlgObject object;
GlgBoolean unique_tags;
Parameters
object
An object whose tags are queried. The top level viewport may be used to query the list of tags of the whole drawing.
unique_tag_sources
If set to GlgTrue, only one instance of tags with same tag source will be added to the list. If the parameter value is set to GlgFalse, all instances with the same tag source will be reported.
66
GLG Programming Reference Manual
This function creates and returns a group containing all named tag objects, or NULL if no tags were found. Each element of the group is an attribute object whose tag field is not empty. The
GlgGetElement and GlgGetSize functions may be used within the Standard API to handle the returned group object. The returned group object must be dereferenced using the GlgDropObject function when it is no longer needed.
If an object is not a viewport, the returned list of tags will include only the tags contained inside the object. For a viewport, the tag list will contain all tags defined in the viewport’s drawing.
Example
The following code fragment prints tag information for all tags defined in the drawing: char * tag_name, * tag_source; int i, size;
GlgObject tag_list, tag_object; tag_list = GlgCreateTagList( viewport, GlgFalse ); if( tag_list )
{ size = GlgGetSize( tag_list ); for( i=0; i<size; ++i )
{ tag_object = GlgGetElement( group, i );
GlgGetSResource( tag_object, “TagName”, &tag_name );
GlgGetSResource( tag_object, “TagSource”, &tag_source ); printf( "TagName: %s, TagSource: %s\n", tag_name, tag_source );
}
GlgGropObject( tag_list );
}
GlgDeletePlot
Deletes a plot from a chart.
GlgBoolean GlgDeletePlot( object, resource_name, plot )
GlgObject object; char * resource_name;
GlgObject plot;
Parameters
object
Specifies a chart or a container object containing the chart.
resource_name
Specifies a resource name for accessing the chart inside the container. Use NULL when the
object parameter specifies the chart.
plot
Specifies the plot to delete. The GlgGetNamedPlot method may be used to obtain a plot’s object ID.
The function returns GlgTrue if the plot was successfully deleted.
67
GlgError
Displays error and information messages using the currently installed error handler.
void GlgError( error_type, message )
GlgErrorType error_type; char * message;
Parameters
error_type
Specifies the type of the message, may have the values listed below. The list includes a description of the action performed by the default error handler for each message type:
GLG_INTERNAL_ERROR reserved for the Toolkit’s internal use; generates an error message, emits an audio beep and logs the error into the glg_error.log file
GLG_USER_ERROR generates an error message and emits an audio beep; on Windows, also logs the error into the glg_error.log file
GLG_WARNING generates a warning message and emits an audio beep; on Windows, also logs the warning into the glg_error.log file
GLG_INFO on Windows, logs the message into the glg_error.log file; on Unix/Linux, prints the message on the terminal.
The location of the glg_error.log file is determined by the GLG_LOG_DIR and GLG_DIR
environment variables as described in the Error Processing section on page 43. In the Unix
environment, all messages are printed in the program standard error output regardless of their message types.
message
The message to be displayed.
GlgExportStrings
Writes all text strings defined in the drawing into a string translation file:
GlgLong GlgExportStrings( object, filename, separator1, separator2 )
GlgObject object; char * filename;
GlgLong separator1;
GlgLong separator2;
Parameters
object
Specifies a viewport or drawing object whose text strings to export.
filename
Specifies the string translation file to write.
68
GLG Programming Reference Manual
separator1, separator2
Defines characters to be used as string separators in the generated file.
The function returns the number of exported strings or -1 in case of an error. Refer to the
Localization Support chapter on page 65 of the GLG User’s Guide and Builder Reference Manual for information about the string translation file format.
GlgExportTags
Writes tag names and tag sources of all tags defined in a drawing into a file:
GlgLong GlgExportTags( object, filename, separator1, separator2 )
GlgObject object; char * filename;
GlgLong separator1;
GlgLong separator2;
Parameters
object
Specifies a viewport or drawing object whose tags to export.
filename
Specifies the tag file to write.
separator1, separator2
Defines characters to be used as string separators in the generated file.
The function uses the same file format as the GlgExportStrings function. Refer to the Localization
Support chapter on page 65 of the GLG User’s Guide and Builder Reference Manual for information about the file format.
The function returns the number of exported tags or -1 in case of an error.
GlgFindFile
Searches for a file, first in the current directory, then in the directory provided by the path parameter and then in the GLG search path. Returns a file path name if the file was found, on NULL otherwise.
void GlgFindFile( filename, path, check_glg_path ) char * filename; char * path;
GlgBoolean check_glg_path;
Parameters
filename
Specifies a relative filename to search for.
path
Specifies an additional search path to be searched before the GLG search path.
69
check_glg_path
If set to True, the GLG search path will be included in the search.
GlgFree
Frees the memory used to store character strings.
void GlgFree( pointer ) char * pointer;
Parameters
pointer
Specifies a character string that is no longer needed by the application.
This function is used to free memory allocated by GlgAlloc and GLG string utilities. This is not to be used to free the memory occupied by any GLG object (GlgObject). Use GlgDropObject and
GlgReferenceObject to manage those objects. The function checks for NULL address pointers, and will not fail or generate an error message if one is passed.
GlgGetDataExtent
Queries the minimum and maximum extent of the data accumulated in a chart or in one of its plots.
GlgBoolean GlgGetDataExtent( object, resource_name, min_max, x_extent )
GlgObject object; char * resource_name;
GlgMinMax min_max;
GlgBoolean x_extent;
Parameters
object
Specifies a chart, a plot or a container object containing the chart.
resource_name
Specifies a resource name to access the chart inside the container, or a plot inside the chart.
Use NULL when the object parameter specifies the chart or its plot.
min_max
Returned data extent. It is defined in the GlgApi.h file: typedef struct _GlgMinMax
{ double min, max;
} GlgMinMax;
x_extent
If GlgTrue, the function returns the X extent, otherwise it returns the Y extent.
70
GLG Programming Reference Manual
If the object and resource_name parameters point to a chart object, the data extent of all plots in the chart is returned. If object and resource_name point to a plot, the data extent of that plot is returned.
The object hierarchy must be set up for this function to succeed. The function returns GlgTrue on success.
GlgGetDataType
Returns the data type (GLG_D, GLG_S or GLG_G) of a data or attribute object.
GlgDataType GlgGetDataType( data_object )
GlgObject data_object;
Parameters
data_object
Specifies a data or attribute object to query.
GlgGetDResource
GlgGetDTag
Return the current value of a scalar resource or tag.
GlgBoolean GlgGetDResource( object, resource_name, d_value_ptr )
GlgObject object; char * resource_name; double * d_value_ptr;
GlgBoolean GlgGetDTag( object, tag_source, d_value_ptr )
GlgObject object; char * tag_source; double * d_value_ptr;
Parameters
object
Specifies a GLG object.
resource_name, tag_source
Specifies the name of the double resource or tag to query.
d_value_ptr
Specifies a pointer with which to return the resource or tag value.
If a scalar resource or tag with the input name exists, this function copies its current value into the address specified by d_value_ptr and returns GlgTrue, otherwise it generates an error message and returns GlgFalse.
71
GlgGetGResource
GlgGetGTag
Return the set of three values making up a geometrical resource or tag:
GlgBoolean GlgGetGResource( object, resource_name, g_value1_ptr, g_value2_ptr, g_value3_ptr )
GlgObject object; char * resource_name; double * g_value1_ptr, * g_value2_ptr, * gvalue3_ptr;
GlgBoolean GlgGetGTag( object, tag_source, g_value1_ptr, g_value2_ptr, g_value3_ptr )
GlgObject object; char * tag_source; double * g_value1_ptr, * g_value2_ptr, * gvalue3_ptr;
Parameters
object
Specifies a GLG object.
resource_name, tag_source
Specifies the name of the geometrical resource or tag to query.
g_value0_ptr, g_value1_ptr, g_value2_ptr
Specify pointers to the locations to which the XYZ or RGB values of the resource or tag are returned.
If a geometrical resource or tag with the input name exists, this function copies its current three values to the addresses specified with the g_value pointers and returns GlgTrue. Otherwise it generates an error message and returns GlgFalse.
For a geometrical point, g_value0_ptr, g_value1_ptr and g_value2_ptr are set to the X, Y and Z coordinates of the point, respectively. For a color resource or tag, they will be set to the R, G and B values of the color, respectively.
GlgGetLParameter
Sets a value of a global parameter.
GlgBoolean GlgSetLParameter( char * name, GlgLong * value ) char * name;
GlgLong value;
Parameters
name
Specifies parameter name.
value
A pointer used to return a parameter’s value.
72
GLG Programming Reference Manual
Refer to the Appendix D: Global Parameters section on page 403 for information on available
global parameters. The function returns GlgTrue on success.
GlgGetMajorVersion
GlgGetMinorVersion
Return library’s major and minor version numbers.
GlgLong GlgGetMajorVersion( void )
GlgLong GlgGetMinorVersion( void )
GlgGetModifierState
Return the state of the requested modifier key.
GlgBoolean GlgGetModifierState( modifier )
GlgModifierKey modifier;
Parameters
modifier
Specifies a modifier key to query: GLG_SHIFT_KEY or GLG_CONTROL_KEY.
GlgGetNamedPlot
Given a name of a chart’s plot, returns the plot’s object ID. The function returns NULL if a plot with the specified name was not found.
GlgObject GlgGetNamedPlot( object, resource_name, plot_name )
GlgObject object; char * resource_name; char * plot_name;
Parameters
object
Specifies a chart or a container object containing a chart.
resource_name
Specifies a resource name for accessing the chart inside the container. Use NULL when the
object parameter specifies the chart.
plot_name
Specifies the plot name.
73
GlgGetObjectName
Returns an object’s name. It returns a pointer to the internal string that should not be modified or freed.
char * GlgGetObjectName( object )
GlgObject object;
Parameters
object
Specifies an object to query.
GlgGetObjectType
Returns an object’s type (GLG_PLOYGON, GLG_TEXT, etc.).
GlgObjectType GlgGetObjectType( object )
GlgObject object;
Parameters
object
Specifies an object to query.
GlgGetSelectionButton
Queries which mouse button initiated the selection callback.
GlgLong GlgGetSelectionButton( void )
This function returns 1, 2, or 3 to indicate which button caused the callback to be invoked. It may be used only inside a selection callback function. If it is called outside of a selection callback, the return value is undefined.
GlgGetNativeComponent
Returns an ID of a native windowing system component used to render the viewport:
GlgAnyType GlgGetNativeComponent( GlgObject object, char * resource_name, GlgComponentQueryType type )
Parameters
object
Specifies a viewport or a viewport’s parent.
resource_name
Specifies a resource name for accessing the child viewport inside its parent. Use NULL when the object parameter specifies the viewport.
74
GLG Programming Reference Manual
type
Specifies the type of a component to retrieve:
GLG_WIDGET_QUERY
Returns an ID of the native component used to render the viewport: a widget ID when using libglg.a on X Windows, a window ID when using libglg_X11.a on X Windows and a window handle on Windows.
GLG_SHELL_QUERY
If the top-level window was created by the GLG library, the function returns the widget
ID of the top level shell the viewport belongs to on X Windows, or the window handle of the top-level window on Windows.
GLG_CHILD_WIDGET_QUERY
For native widgets on X Windows that use scroll panes, such as text edit and list widgets, returns a widget ID of child widget inside the pane. For these widgets,
GLG_WIDGET_QUERY returns the widget ID of the scroll pane.
GLG_V_SCROLLBAR_QUERY
GLG_H_SCROLLBAR_QUERY
Returns a widget ID of a scrollbar widget for native widgets on X Windows that use scrollbars.
GLG_DISPLAY_QUERY
On X Windows, returns the display pointer for the viewport’s widget.
GlgGetSResource
GlgGetSTag
Return the value of a string resource or tag.
GlgBoolean GlgGetSResource( object, resource_name, s_value_ptr )
GlgObject object; char * resource_name; char ** s_value_ptr;
GlgBoolean GlgGetSTag( object, tag_source, s_value_ptr )
GlgObject object; char * tag_source; char ** s_value_ptr;
Parameters
object
Specifies a GLG object.
resource_name, tag_source
Specifies the name of the string resource or tag to query.
s_value_ptr
A pointer with which to return the resource or tag value.
If a string resource or tag with the given name exists, this function copies the current resource or tag string into an internal buffer, sets the s_value_ptr to point to the buffer and returns GlgTrue.
Otherwise it returns GlgFalse.
75
Warning: The returned pointer points to GLG internal data structures and should not be modified.
The pointer is valid only immediately after a call to the GlgGetSResource function. To store the returned string, create a copy of it using the GlgStrClone function.
GlgGISConvert
Performs coordinate conversion from the GIS coordinates of the GIS Object to the GLG coordinates of the drawing and visa versa.
GlgBoolean GlgGISConvert( object, resource_name, coord_type, coord_to_lat_lon, in_point, out_point )
GlgObject object; char * resource_name;
GlgCoordType coord_type;
GlgBoolean coord_to_lat_lon;
GlgPoint * in_point;
GlgPoint * out_point;
Parameters
object
If the resource_name parameter is NULL, specifies the GIS Object whose coordinate system to use for conversion. If the resource_name parameter is not NULL, specifies a parent of the
GIS Object.
resource_name
If not NULL, specifies the resource name of the GIS Object inside the parent object specified by the object parameter.
coordinate_type
The type of the GLG coordinate system to convert to or from: GLG_SCREEN_COORD for screen coordinates or GLG_OBJECT_COORD for world coordinates.
coord_to_lat_lon
GlgTrue to convert from GLG coordinates to GIS longitude and latitude, GlgFalse to convert from GIS to GLG coordinates.
in_point
A pointer to the GlgPoint structure containing coordinate values to be converted.
out_point
A pointer to the GlgPoint structure that receives converted coordinate values.
The function returns GlgTrue if conversion succeeds. When converting from GLG to GIS coordinates, the Z coordinate is set to a negative GLG_GIS_OUTSIDE_VALUE value for points on the invisible part of the globe.
The GlmConvert function of may be used to perform coordinate conversion between GIS and GLG coordinates without the use of the GIS Object.
76
GLG Programming Reference Manual
GlgGISCreateSelection
Provides a high-level interface to the map server’s GlmGetSelection function; returns a message object containing information about GIS features located at a specified position on the map.
GlgObject GlgGISCreateSelection( object, resource_name, layers, x, y, select_labels)
GlgObject object; char * resource_name; char * layers; double x, y;
GlgLong select_labels;
Parameters
object
If the resource_name parameter is NULL, specifies the GIS Object to query. If the
resource_name parameter is not NULL, specifies a parent of the GIS Object.
resource_name
If not NULL, specifies the resource name of the GIS Object inside the parent object specified by the object parameter.
layers
A list of layers to query.
x, y
Specifies coordinates of a point in the screen coordinates of a viewport that contains the GIS object.
select_labels
Specifies the label selection mode, can have the following values (defined in the
GlmLabelSelectionMode enum in the GlmApi.h file):
• GLM_LBL_SEL_NONE - GIS features’ labels are not considered for the GIS selection.
• GLM_LBL_SEL_IN_TILE_PRECISION - enables labels to be considered for the GIS selection. For a faster selection, this option does not check labels that belong to GIS features in a different tile, but extend to the current tile.
• GLM_LBL_SEL_MAX_PRECISION - enables labels to be considered for the GIS selection and performs selection with the maximum label precision.
The layer’s settings have precedence over the select_labels parameter. The labels will be considered for selection only for the layers that do not override it by setting their LABEL
SELECTION MODE = NONE in the layer’s LIF file. If LABEL SELECTION MODE =
INTILE, the labels will always be considered using the IN_TILE precision.
The function returns a message object containing information about the selected GIS features. The message object has to be dereferenced using the GlgDropObject function when finished.
If the GIS verbosity level is set to 2000 or 2001, extended information is also written into the error log file and printed to the terminal on Linux/Unix for debugging purposes.
77
Refer to the GlmGetSelection section on page 114 of the GLG Map Server Reference Manual for information on the structure of the returned message object as well as a programming example that demonstrates how to handle it.
GlgGISGetDataset
Returns a dataset object associated with the GIS object:
GlgObject GlgGISGetDataset( object, resource_name )
GlgObject object; char * resource_name;
Parameters
object
If the resource_name parameter is NULL, specifies the GIS Object to query. If the
resource_name parameter is not NULL, specifies a parent of the GIS Object.
resource_name
If not NULL, specifies the resource name of the GIS Object inside the parent object specified by the object parameter.
The function may be invoked after the GIS object has been setup to retrieve its dataset. The dataset may be used to dynamically change attributes of individual layers displayed in the GIS object. The program can use GlgSetResource methods for changing layer attributes. Refer to the GLG Map
Server Reference Manual for information on layer attributes. The GLG GIS Demo provides an example of changing layer attributes programmatically.
GlgGISGetElevation
Returns an elevation of a lat/lon point on a map:
GlgBoolean GlgGISGetElevation( object, resource_name, layer_name, lon, lat, elevation )
GlgObject object; char * resource_name; double lon, lat; double * elevation;
Parameters
object
If the resource_name parameter is NULL, specifies the GIS Object to query. If the
resource_name parameter is not NULL, specifies a parent of the GIS Object.
resource_name
If not NULL, specifies the resource name of the GIS Object inside the parent object specified by the object parameter.
layer_name
The name of the layer with elevation data to query.
78
GLG Programming Reference Manual
lon, lat
The lon/lat coordinates of a point on the map.
elevation
A pointer to the variable of a double type that will receive the returned elevation data.
The function returns GlgFalse if the point is outside of the map in the ORTHOGRAPHIC projection or if there is no elevation data for the specified location. If the function returns GlgTrue, the elevation value is returned in the units (such as meters or feet) defined by the elevation data file.
GlgHasResourceObject
Checks if a named resource exists:
GlgBoolean GlgHasResourceObject( object, resource_name )
GlgObject object; char * resource_name;
Parameters
object
Specifies a GLG object whose resource or tag to query.
resource_name
Specifies the name of the resource object to query.
If a resource object with the input name exists, this function returns GlgTrue, otherwise it returns
GlgFalse.
GlgHasTagName
GlgHasTagSource
Check if a tag with a specified tag name or tag source exists:
GlgBoolean GlgHasTagName( object, tag_name )
GlgObject object; char * tag_name;
GlgBoolean GlgHasTagSource( object, tag_source )
GlgObject object; char * tag_source;
Parameters
object
Specifies a GLG object whose tag to query.
tag_name, tag_source
Specifies the tag name or tag source to query.
If a tag with the input tag name or tag source exists, this function returns GlgTrue, otherwise it returns GlgFalse.
79
GlgImportStrings
Replaces text strings in the drawing with the strings loaded from a string translation file:
GlgLong GlgImportStrings( object, filename )
GlgObject object; char * filename;
Parameters
object
Specifies the viewport or drawing object whose text strings to replace.
filename
Specifies the string translation file to load.
The function returns the number of imported strings or -1 in case of an error. Refer to the
Localization Support chapter on page 65 of the GLG User’s Guide and Builder Reference Manual for information about the string translation file format.
GlgImportTags
Replaces tag names and tag sources of tags in a drawing with information loaded from a tag translation file:
GlgLong GlgImportTags( object, filename )
GlgObject object; char * filename;
Parameters
object
Specifies the viewport or drawing object whose tag to change.
filename
Specifies the tags translation file to load.
The function uses the same file format as the GlgImportStrings function. Refer to the Localization
Support chapter on page 65 of the GLG User’s Guide and Builder Reference Manual for information about the file format.
The function returns the number of imported tags or -1 in case of an error.
80
GLG Programming Reference Manual
GlgOnDrawMetafile
.Provides MFC metafile output support (Windows only). Is used by the MFC container’s
OnDrawMetafile method to produce metafile for the GLG child window.
GlgBoolean GlgOnDrawMetafile( viewport, print_dc )
GlgObject viewport;
HDC print_dc;
Parameters
viewport
Specifies a viewport object.
print_dc
Specifies the printing device context for metafile output.
Returns GlgTrue if metafile generation succeeds, otherwise returns GlgFalse.
GlgOnPrint
Provides MFC printing support (Windows only). Is used by the MFC container’s OnPrint method to print GLG child window.
GlgBoolean GlgOnPrint( viewport, print_dc )
GlgObject viewport;
HDC print_dc;
Parameters
viewport
Specifies a viewport object.
print_dc
Specifies the printing device context.
Returns GlgTrue if printing succeeds, otherwise returns GlgFalse.
GlgPreAlloc
Preallocates memory under the control of mission critical real-time applications:
GlgBoolean GlgPreAlloc( size, type )
GlgLong size;
GlgPreAllocType type;
Parameters
size
Specifies the size of the memory to allocate.
type
Specifies the allocation type. The following lists available types and the meaning of the
81 corresponding size parameter:
• GLG_PREALLOC_MEMORY - allocates a specified number of spare memory blocks.
• GLG_PREALLOC_POLYGON_POINT_BUFFERS - allocates a buffer of the requested size to be used for rendering large polygons. It can be set to the maximum expected number of points in one polygon.
• GLG_PREALLOC_GRAPH_POINT_BUFFERS - allocates a buffer of the requested size used for rendering plots of real-time charts. It can be set to the maximum expected number of points in one plot.
• GLG_PREALLOC_TESS_BUFFERS - allocates a buffer of the requested size for tessellation vertices. The buffer is used by the OpenGL driver for tessellating filled polygons; it is not used by the GDI driver.
Mission-critical applications can use this function to preallocate memory on start-up and then allocate more memory as needed outside of the application’s critical sections. The
GlgGetLParameter function can be used to query the amount of spare memory in the preallocated memory blocks.
If the buffers are not preallocated, they are allocated and automatically adjusted as needed.
The function returns GlgTrue on success.
GlgPrint
Generates a PostScript output of the current state of the widget's graphics.
GlgBoolean GlgPrint( object, file, xpos, ypos, width, height, portrait, stretch )
GlgObject object; char * file; double xpos, ypos, width, height;
GlgBoolean portrait, stretch;
Parameters
object
Specifies a viewport object.
file
Specifies a filename in which to save the generated PostScript output.
xpos, ypos, width, height
Specify the rectangle on the page that will contain the Postscript output: xpos and ypos define the coordinates of the upper left corner of the rectangle, width and height define its dimensions. All coordinates are specified in the world coordinate system, which maps a rectangle defined by the points (-1000 -1000) and (1000 1000) to a page.
portrait
Specifies the orientation of the PostScript output on the page. If the value of this parameter is
GlgTrue, a portrait orientation is used. Otherwise, a landscape orientation is used.
82
GLG Programming Reference Manual
stretch
Specifies whether or not PostScript output should be stretched when mapping it to the specified rectangle. If the value of this parameter is GlgTrue, the PostScript output will be stretched to fit the rectangle exactly. This may distort printed objects. If the value is GlgFalse, the ratio of height to width of the widget will be preserved in the PostScript output. This may leave some parts of the specified rectangle blank.
This function saves a PostScript image of the current state of the drawing into the specified file. The
xpos, ypos, width, and height parameters define the PostScript page layout. The origin is defined to be in the middle of the page, the left edge of the page is at -1000, and the right edge is at 1000. The top and bottom of the page are similarly defined to be at 1000 and -1000, respectively. The xpos and
ypos parameters define the lower left corner of the drawing, while width, and height give the dimensions of the drawing area. As an example, the default page layout you get when you print a drawing by setting the PrintFile property puts the lower left corner of the drawing area at (-900 -
900), while the dimensions are 1800 by 1800. This makes the drawing about as large as it can be while still keeping a small border all the way around a page. The portrait parameter defines portrait
(TRUE) or landscape (FALSE) mode. If the stretch parameter is set to GlgFalse, the X/Y ratio of the drawing is preserved.
The drawing’s hierarchy must be set up in order to generate PostScript output. Use the GlgUpdate function before calling GlgPrint to make sure the widget is up to date. The function returns GlgTrue if PostScript output is successfully written into the file.
GlgReset
Reinitializes the widget.
GlgBoolean GlgReset( object )
GlgObject object;
Parameters
object
Specifies a viewport object.
Calling GlgReset restores all volatile resource changes to the values the resources had when the widget was first drawn. This discards currently displayed graph data, unless the data group series of a graph was exploded.
The function returns GlgTrue if the widget is successfully reinitialized; otherwise it returns
GlgFalse.
83
GlgSaveImage
GlgSaveImageCustom
Generate a JPEG image of the current state of the widget's graphics and saves it into a file:
GlgBoolean GlgSaveImage( object, resource_name, filename, format )
GlgObject object; char * resource_name; char * filename;
GlgImageFormat format;
GlgBoolean GlgSaveImageCustom( object, resource_name, filename, format, x, y, width, height, gap )
GlgObject object; char * resource_name; char * filename;
GlgImageFormat format;
GlgLong x, y, width, height, gap;
Parameters
object
Specifies a viewport object.
resource_name
Specifies the resource name of a child viewport whose image to save, or NULL to save the image of the viewport specified by the object parameter. The resource name is relative to the viewport specified by the object parameter.
filename
Specifies a filename in which to save the generated image.
format
Specifies an image format, must be GLG_JPEG or GLG_PNG.
x, y, width, height
Specifies the area of the drawing for generating an image with GlgSaveImageCustom, which can be bigger or smaller than the visible area of the viewport. The x and y parameters define the offset in screen pixels relative to the origin of the viewport’s window, which has screen coordinates of (0,0). The width and height parameters define the width and height of the generated image in screen pixels. These parameters may be obtained by querying the bounding box of either the whole drawing or of the area of the drawing for which the image needs to be generated.
If the width and height parameters are 0, the image for the whole drawing is generated using the drawing’s bounding rectangle as the image generation extent. If the viewport is zoomed in, this area may be significantly bigger than the visible area of the viewport, and the image size may be quite large. The viewport’s zoom factor defines the scaling factor for objects in the drawing when the image is saved.
gap
Specifies the padding space between the extent of the drawing and the border of the generated image in case when zero width and height parameters are specified for GlgSaveImageCustom.
84
GLG Programming Reference Manual
The GlgSaveImage function saves image of the visible part of the viewport, clipping out the parts of the drawing that extends outside of it. The GlgSaveImageCustom saves the whole drawing without such clipping (if width and height parameters are 0), or saves just the specified area of the drawing.
The drawing’s hierarchy must be set up in order to generate an image. The function returns GlgTrue if the image was successfully generated.
GlgSendMessage
Sends a message to an object to request some action to be performed.
GlgAnyType GlgSendMessage( object, resource_name, message, param1, param2, param3, param4 )
GlgObject object; char * resource_name; char * message;
GlgAnyType param1, param2, param3, param4;
Refer to the Input Objects chapter on page 205 of the GLG User’s Guide and Builder Reference
Manual for a list of messages supported by each type of the available input handlers.
Parameters
object
Specifies an object to send the message to. In most cases, it is a viewport with a GLG input handler attached, such as a button or a slider.
resource_name
If the parameter is set to NULL, the message is sent to the object specified by the object parameter. Otherwise, the message is sent to the object’s child specified by the resource name.
The resource path is relative to the object parameter. For example, to send the message to a viewport’s handler, use the viewport as the object parameter and “Handler” as the value of the
resource_name parameter.
message
A string defining the type of the message.
param1, param2, param3, param4
Message parameters whose type depends on the message type.
The function serves as an escape mechanism for actions that can not be easily accomplished by setting or querying a single resource, such us adding items to a list widget or querying a state of a multiple-selection list. For messages that execute some query, the function returns the query result, otherwise it just executes the requested action.
Refer to the Input Objects chapter on page 205 of the GLG User’s Guide and Builder Reference
Manual for the description of the function’s parameters and returned value for each of the GLG input handlers.
85
GlgSetAlarmHandler
Sets the function that will process alarm messages.
void GlgSetAlarmHandler( alarm_handler )
GlgAlarmHandler alarm_handler;
Parameters
alarm_handle
Specifies a global function that will be invoked to process all alarm messages generated by application’s drawings.
An alarm handler has the following function prototype: typedef void (*GlgAlarmHandler)( data_object, alarm_object, alarm_label, action, subaction, reserved )
GlgObject data_object;
GlgObject alarm_object; char * alarm_label; char * action; char * subaction;
GlgAnyType reserved;
The data_object parameter is the resource whose value has changed. The alarm_object parameter is the alarm attached to the data_object to monitor its value; it is the alarm that generated the alarm message. The alarm_label parameter supplies the AlarmLabel used to identify alarm_object. The
action and subaction parameters provide details about the condition that caused the alarm; refer to the Alarm Messages section on page 187 of the GLG User’s Guide and Builder Reference Manual for more information.
An alarm handler should not change object hierarchy by actions such as adding or deleting objects from the drawing or changing a factor of a series object.
GlgSetBrowserObject
Sets the object for browsing with the GLG resource, tag or alarm browser widgets.
void GlgSetBrowserObject( browser, object )
GlgObject browser;
GlgObject object;
Parameters
browser
Specifies a viewport of the browser widget.
object
Specifies an object to browse.
The browser will display the object’s resources, tags or alarms.
86
GLG Programming Reference Manual
GlgSetBrowserSelection
Sets a new value of a browser’s selection and filter text boxes for resource, tag, alarm and data browsers after the browser object has been set up. Setting a new selection will display a new list of matching entries.
void GlgSetBrowserSelection( object, resource_name, selection, filter )
GlgObject object; char * resource_name; char * selection; char * filter;
Parameters
object
Specifies a viewport of the browser widget or its parent.
resource_name
Specifies a resource path to access the browser from the parent supplied by the object parameter, or NULL if the object parameter supplies the browser’s viewport.
selection
Specifies a new selection string.
filter
Specifies a new filter string.
The browser will display a new list of matching items. Before the browser’s drawing hierarchy has been set up, the selection and filter may be set via corresponding resources. To change selection or filter after hierarchy setup, this function should be used.
GlgSetCursor
Sets a custom cursor for a drawing or one of its child viewports (Windows only).
GlgBoolean GlgSetCursor( viewport, resource_name, cursor )
GlgObject viewport; char * cursor
GlgLong cursor;
Parameters
viewport
Specifies a viewport.
resource_name
Specifies the resource name of a child viewport to set the cursor of, or NULL to set the cursor of the viewport specified by the viewport parameter. The resource name is relative to the viewport specified by the viewport parameter.
cursor
Specifies one of the predefined Windows cursor types.
87
The custom cursor will be used when the mouse moves inside the viewport the custom cursor is assigned to.
GlgSetDefaultViewport
Sets a drawing to be used by the GLG Custom Control on Windows.
void GlgSetDefaultViewport( viewport )
GlgObject viewport;
Parameters
viewport
Specifies a GLG viewport object to be used as a widget. The viewport object may be loaded using GlgLoadWidgetFromFile, GlgLoadWidgetFromImage, or GlgLoadWidgetFromObject functions. It may also be created programmatically using functions from the GLG Extended
API.
One instance of a viewport may be used to create only one GLG Custom Control since every control needs its own copy of the viewport. To create several custom controls with the same drawing, load a new instance of the drawing for each control or use GlgCopyObject to create instances of the drawing, then select them using GlgSetDefaultViewport before creating each control or widget. This function references the viewport object.
GlgSetDResource
GlgSetDResourceIf
GlgSetDTag
Set a new value for a resource or tag of type D. For information about the data types used by GLG objects, see the Structure of a GLG Drawing chapter.
GlgBoolean GlgSetDResource( object, resource_name, d_value )
GlgObject object; char * resource_name; double d_value;
GlgBoolean GlgSetDResourceIf( object, resource_name, d_value, if_changed )
GlgObject object; char * resource_name; double d_value;
GlgBoolean if_changed;
GlgBoolean GlgSetDTag( object, tag_source, d_value, if_changed )
GlgObject object; char * tag_source; double d_value;
GlgBoolean if_changed;
88
GLG Programming Reference Manual
Parameters
object
Specifies a GLG object.
resource_name, tag_source
Specifies the name of the scalar resource or tag to be set.
d_value
Specifies a new value for the resource or tag.
if_changed
If set to GlgFalse, the graphical updates will be performed even if the new value is the same as the old one (equivalent to GlgSetDResource function). Setting the parameter to GlgTrue optimizes performance of applications that set resource or tag values regardless whether the values have changed. The parameter must be set to GlgFalse when updating entry points of graphs to allow plotting straight lines when the graph’s value does not change over time.
If a scalar resource or tag with the given name exists, this function sets it to a new value and returns
GlgTrue, otherwise it prints an error message and returns GlgFalse.
GlgSetEditMode
Sets the viewport’s edit mode which disables input objects in the viewport while the drawing is being edited.
GlgBoolean GlgSetEditMode( viewport, resource_name, edit_mode )
GlgObject viewport; char * resource_name;
GlgBoolean edit_mode;
Parameters
viewport
Specifies a viewport object.
resource_name
Specifies the resource name of a child viewport to set the editing mode of, or NULL to set the editing mode of the viewport specified by the viewport parameter. The resource name is relative to the viewport specified by the viewport parameter.
edit_mode
GlgTrue to set the editing mode, or GlgFalse to reset.
If the viewport’s edit mode is turned on, the input objects in the viewport will not react to the mouse and keyboard events. The rest of the input objects outside of the viewport will still be active. The edit mode is usually set for viewports that serve as a drawing area; the edit mode ensures that the input objects do not react to mouse clicks when they are dragged with the mouse to a new position.
This is similar to the behavior of the Builder’s Drawing Area.
89
The edit mode is global and may be set only for one viewport used as a drawing area. Setting the edit mode of a new viewport resets the edit mode of the previous viewport. The viewport’s edit mode is inherited by all its child viewports. The function returns GlgTrue for success, otherwise it generates an error message and returns GlgFalse.
GlgSetErrorHandler
Replaces the GLG Toolkit error handler and returns the previous error handler.
GlgErrorHandler GlgSetErrorHandler( new_handler )
GlgErrorHandler new_handler;
Parameters
new_handler
Specifies a new error handler, supplied by the user, to be called on an error condition. This does not include internal errors of the GLG Toolkit, if any are detected: they are still reported using the default handler.
The function prototype for the new handler is as follows: void new_handler( error_message, error_type ) char * error_message;
GlgErrorType error_type;
The error_type parameter may have the following values:
GLG_INTERNAL_ERROR
GLG_USER_ERROR
GLG_WARNING
GLG_INFO
Refer to the description of the GlgError function on page 67 for more information on the error
types.
For more information about error handlers, see the Error Processing section on page 43.
GlgSetFocus
Sets the keyboard focus to the specified viewport.
void GlgSetFocus( object, resource_name )
GlgObject object; char * resource_name;
Parameters
object
Specifies a viewport object.
resource_name
Specifies the resource name of a child viewport to set the focus to, or NULL to set the focus to
90
GLG Programming Reference Manual
the viewport specified by the object parameter. The resource name is relative to the viewport specified by the object parameter.
GlgSetGResource
GlgSetGResourceIf
GlgSetGTag
Set the values of a geometrical resource or tag.
GlgBoolean GlgSetGResource( object, resource_name, g_value1, g_value2, g_value3 )
GlgObject object; char * resource_name; double g_value1, g_value2, g_value3;
GlgBoolean GlgSetGResourceIf( object, resource_name, g_value1, g_value2, g_value3, if_changed )
GlgObject object; char * resource_name; double g_value1, g_value2, g_value3;
GlgBoolean if_changed;
GlgBoolean GlgSetGTag( object, tag_sourcee, g_value1, g_value2, g_value3, if_changed )
GlgObject object; char * tag_source; double g_value1, g_value2, g_value3;
GlgBoolean if_changed;
Parameters
object
Specifies a GLG object.
resource_name, tag_source
Specifies the name of the geometrical resource or tag to be set.
g_value0, g_value1, g_value2
Specify the new XYZ or RGB values for the resource or tag.
if_changed
If set to GlgFalse, the graphical updates will be performed even if the new value is the same as the old one (equivalent to GlgSetDResource function). Setting the parameter to GlgTrue optimizes performance of applications that set resource or tag values regardless whether the values have changed. The parameter must be set to GlgFalse when updating entry points of graphs to allow plotting straight lines when the graph’s value does not change over time.
If a geometrical resource or tag with the given name exists, this function sets it to the input values and returns GlgTrue. Otherwise, the function prints an error message and returns GlgFalse.
91
GlgSetLParameter
Sets a value of a global parameter.
GlgBoolean GlgSetLParameter( char * name, GlgLong value ) char * name;
GlgLong value;
Parameters
name
Specifies parameter name.
value
Specifies parameter value.
Refer to the Appendix D: Global Parameters section on page 403 for information on available
global parameters. The function returns GlgTrue on success.
GlgSetResourceFromObject
Sets a data or matrix resource object’s value using another object.
GlgBoolean GlgSetResourceFromObject( object, resource_name, data_or_matrix_object )
GlgObject object; char * resource_name;
GlgObject data_or_matrix_object;
Sets the value of the resource specified with the object and resource name to a value defined by the
data_or_matrix_object. The object type (and data type for the data object) of the resource specified by the resource name should match the type of the data_or_matrix_object.
Note that unlike the rest of the resource functions, this function does not work from a remote process.
Also unlike the rest of the resource functions, The GlgGetResourceObject function returns NULL without generating an error message if the resource cannot be found. This allows this function to be used to query the presence or absence of an object. The rest of the functions (GlgGet/SetXResource) return GlgFalse and generate an error message, which may be intercepted by installing a custom
error handler. (See GlgSetErrorHandler, page 89.)
GlgSetSResource
GlgSetSResourceIf
GlgSetSTag
Replace the string in a string resource or tag.
GlgBoolean GlgSetSResource( object, resource_name, s_value )
GlgObject object; char * resource_name; char * s_value;
92
GLG Programming Reference Manual
GlgBoolean GlgSetSResourceIf( object, resource_name, s_value, if_changed )
GlgObject object; char * resource_name; char * s_value;
GlgBoolean if_changed;
GlgBoolean GlgSetSTag( object, tag_source, s_value, if_changed )
GlgObject object; char * tag_source; char * s_value;
GlgBoolean if_changed;
Parameters
object
Specifies a GLG object.
resource_name, tag_source
Specifies the name of the string resource or tag to be set.
s_value
Specifies the new string for the resource or tag.
if_changed
If set to GlgFalse, the graphical updates will be performed even if the new value is the same as the old one (equivalent to GlgSetDResource function). Setting the parameter to GlgTrue optimizes performance of applications that set resource or tag values regardless whether the values have changed. The parameter must be set to GlgFalse when updating entry points of graphs to allow plotting straight lines when the graph’s value does not change over time.
If a string resource or tag with the given name exists, this function creates a copy of the input string, and sets that copy as the new value of the resource or tag. The function returns GlgTrue if the resource or tag has been successfully changed, otherwise it generates an error message and returns
GlgFalse. The memory associated with the old string is automatically freed.
GlgSetSResourceFromD
GlgSetSResourceFromDIf
GlgSetSTagFromD
Replace the string in a string resource or tag with a value specified by an input number and a format string.
GlgBoolean GlgSetSResourceFromD( object, resource_name, format, d_value )
GlgObject object; char * resource_name; char * format; double d_value;
93
GlgBoolean GlgSetSResourceFromDIf( object, resource_name, format, d_value, if_changed )
GlgObject object; char * resource_name; char * format; double d_value;
GlgBoolean if_changed;
GlgBoolean GlgSetSTagFromDIf( object, tag_source, format, d_value, if_changed )
GlgObject object; char * tag_source; char * format; double d_value;
GlgBoolean if_changed;
Parameters
object
Specifies a GLG object.
resource_name, tag_source
Specifies the name of the string resource or tag to be set.
format
Specifies the format to use when setting the resource or tag string. This is a printf-style format string.
d_value
Specifies the numerical value to be converted to a string according to the format.
if_changed
If set to GlgFalse, the graphical updates will be performed even if the new value is the same as the old one (equivalent to GlgSetDResource function). Setting the parameter to GlgTrue optimizes performance of applications that set resource or tag values regardless whether the values have changed. The parameter must be set to GlgFalse when updating entry points of graphs to allow plotting straight lines when the graph’s value does not change over time.
If a string resource or tag with the input name exists, this function sets it to a new string containing the d_value parameter in the format specified with the format argument. The function returns
GlgTrue for success, otherwise it generates an error message and returns GlgFalse.
GlgSetLinkedAxis
Associates a chart's plot or a level line with an Y axis for automatic rescaling, returns GlgTrue on success.
GlgBoolean GlgSetLinkedAxis( object, resource_name, axis_object, axis_resource_name )
GlgObject object; char * resource_name;
GlgObject axis; char * axis_resource_name;
94
GLG Programming Reference Manual
Parameters
object
Specifies a plot or a level line, or a parent object containing the plot or the level line.
resource_name
Specifies a resource name for accessing the plot or the level line inside the parent. Use NULL when the object parameter specifies the plot or the level line.
axis_object
Specifies the axis to link with, or a parent of the axis.
axis_resource_name
Specifies a resource name for accessing the axis inside the parent. Use NULL when the
axis_object parameter specifies an axis.
GlgSetLabelFormatter
Attaches a custom label formatter to a stand-alone axis object or an axis of a chart, returns GlgTrue on success.
GlgBoolean GlgSetLabelFormatter( object, resource_name, formatter )
GlgObject object; char * resource_name;
GlgLabelFormatter formatter;
Parameters
object
Specifies a chart or a container object containing the chart.
resource_name
Specifies a resource name for accessing the chart inside the container. Use NULL when the
object parameter specifies the chart.
formatter
Specifies a custom label formatter.
A label formatter is a function which is invoked every time a new label string needs to be generated.
It can create and return a label string, or return NULL to use a default label string. When the created label string is no longer needed, it will be freed by the Toolkit using the GlgFree call. Therefore, it must be allocated using GlgAlloc or one of the GLG string utility functions, such as GlgStrClone or
GlgConcatStrings. All custom label formatters have the following function prototype: typedef char * (*GlgLabelFormatter)
( GlgObject object, GlgLong label_type,
GlgLong value_type, double value, time_t sec, double fractional_sec, void * reserved );
A custom label formatter is invoked with the following parameters:
95
object
The axis object the formatter is attached to.
label_type
The type of an axis label to be generated: GLG_TICK_LABEL_TYPE for major tick labels,
GLG_SELECTION_LABEL_TYPE for chart selection labels and
GLG_TOOLTIP_LABEL_TYPE for chart tooltip labels.
A label formatter may be invoked by the chart selection or chart tooltip methods if an axis label is requested by the selection or tooltip formats.
value_type
The type of the axis value: GLG_TIME_VALUE or GLG_NUMERICAL_VALUE.
value
The label’s X value or time stamp.
sec
An integer number of seconds since the Epoch corresponding to the label position (time axes only).
fractional_sec
A label’s fractional number of seconds.
reserved
Is reserved for future use, must be NULL.
GlgSetChartFilter
Attaches a custom data filter to a chart’s plot, returns GlgTrue on success.
GlgBoolean GlgSetChartFilter( object, resource_name, filter, client_data )
GlgObject object; char * resource_name;
GlgChartFilter filter; void * client_data;
Parameters
object
Specifies a chart’s plot, a chart or a container object containing the chart.
resource_name
Specifies a resource name for accessing the plot inside the container. Use NULL when the
object parameter specifies the plot.
filter
Specifies a custom data filter.
client_data
Specifies data to be passed to the custom filter.
96
GLG Programming Reference Manual
A data filter is a function which is invoked by a chart to aggregate the plot’s data. A custom data filter has the following function prototype: typedef GlgLong (*GlgChartFilter)
( GlgChartFilterCBReason reason,
GlgChartFilterData * filter_data, void * client_data );
A custom data filter is invoked with the following parameters:
reason
The reason the filter is invoked.
filter_data
Contains data passed to the filter by the chart.
client_data
Contains client data passed to the filter by the application when the filter was attached to the plot.
The src subdirectory of the GLG installation contains source code of custom filter examples for various programming environments (CustomChartFilter.c, CustomChartFilter.java and
CustomChartFilter.cs) that provide extensive self-documented examples of custom filters. Each example implements several types of custom filters (MIN_MAX, AVERAGE and DISCARD), and contains detailed explanation of all possible values of the reason parameter, as well as the fields of the filter_data structure.
GlgSetTooltipFormatter
Supplies a custom tooltip formatter, returns the previously set formatter, if any.
GlgTooltipFormatter GlgSetTooltipFormatter( formatter )
GlgTooltipFormatter formatter;
Parameters
formatter
Specifies a custom tooltip formatter.
A tooltip formatter is a function which is invoked every time a new tooltip string needs to be generated. It can create and return a tooltip string, or return NULL to use a default tooltip string.
When the tooltip string is no longer needed, it will be freed by the Toolkit using the GlgFree call.
Therefore, it must be allocated using GlgAlloc or one of the GLG string utility functions, such as
GlgStrClone or GlgConcatStrings.
A custom tooltip formatter has the following function prototype: typedef char * (*GlgTooltipFormatter)
( GlgObject viewport, GlgObject object,
GlgObject tooltip_string,
GlgLong root_x, GlgLong root_y )
A custom tooltip formatter is invoked with the following parameters:
97
viewport
The parent viewport of the object.
object
The object with the tooltip action.
tooltip_string
The data object of S (string) type containing the tooltip string.
root_x
The X coordinate of the cursor relative to the root window.
root_y
The Y coordinate of the cursor relative to the root window.
GlgSetZoom
Provides a programmatic interface to integrated zooming and panning.
GlgBoolean GlgSetZoom( object, resource_name, type, value )
GlgObject object; char * resource_name;
GlgLong type; double value;
Parameters
object
Specifies a viewport object.
resource_name
Specifies the resource name of a child viewport to zoom or pan, or NULL to zoom or pan the viewport specified by the object parameter. The resource name is relative to the viewport specified by the object parameter.
type
Specifies the type of the zoom or pan operation to perform. The value of this parameter matches the corresponding zooming and panning accelerators and may have the following values:
‘i’ - zoom in by the factor specified by the value parameter (the value of 2 is used as a default if value=0). In the Chart Zoom Mode, it zooms in only in the X/Time direction.
‘I’ - same as ‘i’, but zooms in only in the Y direction; is available only in the Chart Zoom
Mode.
‘o’ - zoom out by the factor specified by the value parameter (the value of 2 is used as a default if value=0). In the Chart Zoom Mode, it zooms out only in the X/Time direction.
‘O’ - same as ‘o’, but zooms out only in the Y direction; is available only in the Chart Zoom
Mode.
98
GLG Programming Reference Manual
‘t’ - start generic ZoomTo mode ( left-click and drag the mouse to finish, value is ignored).
In the Chart Zoom Mode, if the first point of the ZoomTo box is located within the X or
Y axis area, zooming will be performed only in the direction of the selected axis. For example, if the user defines the ZoomTo box in the X axis area, the chart will be zoomed only in the X direction.
‘_’ - start ZoomToX mode, which zooms only in the X direction and preserves the Y scale
( left-click and drag the mouse to finish, value is ignored). It is especially useful in the Chart
Zoom Mode.
‘|’ - start ZoomToY mode, which zooms only in the Y direction preserves the X scale ( leftclick and drag the mouse to finish, value is ignored). It is especially useful in the Chart
Zoom Mode.
‘@’ - start ZoomToXY mode ( left-click and drag the mouse to finish, value is ignored)
‘T’ - start custom ZoomTo mode ( left-click and drag the mouse to ZoomTo, value is ignored).
A custom zoom mode lets the user define the ZoomTo area without performing the zoom operation. An application can use the selected ZoomTo rectangle as the input to implement custom zooming or object selection logic. An application can handle Zoom
events in input callback to perform a custom zoom operation. Refer to the Appendix B:
Message Object Resources section of the GLG Programming Reference Manual for
details of the Zoom event.
‘e’ - abort ZoomTo mode, value is ignored
‘s’ - start generic dragging mode ( left-click and drag the drawing with the mouse to pan or scroll).
In the Chart Zoom Mode, if the user clicks and drags the mouse within the X or Y axis area, scrolling will be performed in the direction matching the direction of the selected axis.
‘^’ - start vertical dragging mode ( left-click and drag the drawing with the mouse to pan or scroll in the vertical direction). It is especially useful in the Chart Zoom Mode.
‘>’ - start horizontal dragging mode ( left-click and drag the drawing with the mouse to pan or scroll in the horizontal direction). It is especially useful in the Chart Zoom Mode.
‘&’ - start XY dragging mode ( left-click and drag the drawing with the mouse to pan or scroll).
‘f’ - fit the drawing to the visible area of the viewport, value is ignored (Drawing Zoom Mode only)
‘F’ - fit the area of the drawing defined by an object named GlgFitArea to the visible area of the viewport, value is ignored (Drawing Zoom Mode only)
‘n’ - reset zoom, value is ignored.
In the GIS zoom mode with map in the ORTHOGRAPHIC projection, resets zooming, but keeps the GIS center unchanged. In the RECTANGULAR projection, resets zooming and paning, but keeps the rotation angle unchanged.
In the Chart Zoom Mode, resets the Y range to fit all chart plots in the visible area of the chart in Y direction.
‘N’ - reset zoom, value is ignored.
In the Chart Zoom Mode, resets the Y range and changes the chart’s X span to show all accumulated data samples in the visible area of the chart.
‘u’ - pan up by the fraction of the widow height specified by the value parameter (the value of
0.5 is used as a default if value=0).
In the Chart Zoom Mode, scroll the chart up by a fraction of the chart’s data area height.
99
‘d’ - pan down by the fraction of the widow height specified by the value parameter (the value of 0.5 is used as a default if value=0).
In the Chart Zoom Mode, scroll the chart down by a fraction of the chart’s data area height.
‘l’ - pan left by the fraction of the widow width specified by the value parameter (the value of
0.5 is used as a default if value=0).
In the Chart Zoom Mode, scroll the chart left by a fraction of the chart’s data area width.
‘r’ - pan right by the fraction of the widow width specified by the value parameter (the value of 0.5 is used as a default if value=0).
In the Chart Zoom Mode, scroll the chart right by a fraction of the chart’s data area width.
‘x’ - pan horizontally by the distance in screen coordinates specified by the value parameter, the sign of the value defines the pan direction
‘y’ - pan vertically by the distance in screen coordinates specified by the value parameter, the sign of the value defines the pan direction
‘X’ - pan horizontally by the distance in world coordinates specified by the value parameter, the sign of the value defines the pan direction.
In the GIS Zoom Mode, pans by the latitude degrees.
In the Chart Zoom Mode, scrolls by the units of the X axis.
‘Y’ - pan vertically by the distance in world coordinates specified by the value parameter, the sign of the value defines the pan direction.
In the GIS Zoom Mode, pans by the longitude degrees.
In the Chart Zoom Mode, scrolls by the units of the first Y axis.
‘U’ - anchor on the upper edge, value is ignored (Drawing Zoom Mode only)
‘D’ - anchor on the lower edge, value is ignored (Drawing Zoom Mode only)
‘R’ - anchor on the right edge, value is ignored (Drawing Zoom Mode only)
‘L’ - anchor on the lower edge, value is ignored (Drawing Zoom Mode only)
‘A’ - rotate the drawing clockwise around X axis by the angle specified by the value parameter
(Drawing Zoom Mode only)
‘a’ - rotate the drawing counterclockwise around X axis by the angle specified by the value parameter (Drawing Zoom Mode only)
‘B’ - rotate the drawing clockwise around Y axis by the angle specified by the value parameter
(Drawing Zoom Mode only)
‘b’ - rotate the drawing counterclockwise around Y axis by the angle specified by the value parameter (Drawing Zoom Mode only)
‘C’ - rotate the drawing clockwise around Z axis by the angle specified by the value parameter
(Drawing Zoom Mode or GIS Zoom Mode with the rectangular projection only)
‘c’ - rotate the drawing counterclockwise around Z axis by the angle specified by the value parameter (Drawing Zoom Mode or GIS Zoom Mode with the rectangular projection only)
value
Specifies a value for zoom and pan operations as described above.
The function performs a specified zoom or pan operation regardless of the setting of the viewport’s
Pan and ZoomEnabled attributes. In the Drawing Zoom Mode, if the function attempts to set a very large zoom factor which would result in the overflow of the integer coordinate values used by the native windowing system, the zoom operation is not performed and the function returns GlgFalse.
100
GLG Programming Reference Manual
The left mouse button is the default button for performing the ZoomTo operation, as well as for panning and scrolling the drawing by dragging it with the mouse. These defaults can be changed by setting the GlgZoomToButton and GlgPanDragButton global configuration resources. If the default is changed, the left-click used in the description of the affected operations changes to the click with the mouse button assigned to the respective ZoomTo or Pan operation.
GlgSetZoomMode
Sets or resets a viewport’s zoom mode by supplying a GIS or Chart object to be zoomed. In the
Drawing Zoom Mode (default), the drawing displayed in the viewport is zoomed and panned. If the
GIS Zoom Mode is set, any zooming and panning operation performed by the GlgSetZoom method will zoom and pan the map displayed in the viewport’s GIS Object, instead of being applied to the viewport’s drawing. In the Chart Zoom Mode, the content of the chart is zoomed and panned.
GlgBoolean GlgSetZoom( object, resource_name, zoom_object, zoom_object_name )
GlgObject object; char * resource_name;
GlgObject zoom_object; char * zoom_object_name;
Parameters
object
Specifies a viewport object.
resource_name
Specifies the resource name of a child viewport whose zoom mode to set, or NULL to set the
Zoom Mode of the viewport specified by the object parameter. The resource name is relative to the viewport specified by the object parameter.
zoom_object
Specifies a GIS or Chart object (or its parent if zoom_object_name is not NULL).
zoom_object_name
If the parameter is NULL, the GIS or Chart object supplied by the zoom_object parameter is selected as the GIS or Chart object to be zoomed. If the parameter is not NULL, it specifies the resource name of the GIS or Chart object to be zoomed. The resource name is relative to the
zoom_object parameter, or to the viewport specified by the object and resource_name parameters if the zoom_object parameter is NULL.
The function may be invoked with zoom_object=NULL and zoom_name=NULL to reset the zoom mode to the default Drawing Zoom Mode.
GlgStrClone
Creates a copy of a character string.
char * GlgStrClone( string ) char * string;
101
Parameters
string
The string to be copied. This can be a NULL pointer, in which case the return value is also
NULL.
This function creates and returns a copy of the input string. The copy should later be freed with the
GlgFree function.
GlgUpdate
Updates a widget to show new resource values.
GlgBoolean GlgUpdate( object )
GlgObject object;
Parameters
object
Specifies a viewport to update.
All resource changes are held until the GlgUpdate function is called or until the widget window receives an expose event. (That is, it must be redrawn because another window that had obscured part of the window has been moved.) This causes the widget to redraw itself, using its new data.
The function returns GlgTrue if the widget has been successfully updated; otherwise it returns
GlgFalse.
Note: Some GLG drawing resources affect the object hierarchy of the drawing (these are the H resources), while others affect the values of objects in the hierarchy (V resources). The Factor attribute of a series affects whether or not there is a Sample5/FillColor instance object in that series.
A request to change the Factor resource to 3 might therefore conflict with a request to change the
Sample5/FillColor resource to red. Even if Factor was changed to 6 in the same batch of resource changes, the act of redrawing the series to accommodate the new attribute value might delete the color change of a series instance. To avoid these conflicts, it is advisable to execute GlgUpdate after any H resources have been changed, and before changing any other resources. For more information
about these resources, see the H and V Resources section of the Integrating GLG Drawings into a
GlgWinPrint
Invokes Microsoft Windows native printing.
void GlgWinPrint( viewport, print_dc, x,y, width, height, reserved, stretch )
GlgObject viewport;
HDC print_dc; double xpos, ypos, width, height;
GlgBoolean reserved, stretch;
102
GLG Programming Reference Manual
Parameters
viewport
Specifies the viewport whose contents are to be printed.
print_dc
The printer device context, acquired from a call to the PrintDlg function.
xpos, ypos, width, height, stretch
These arguments are used in the same way as the corresponding arguments to the GlgPrint function, described above.
Given the printer device context, this function prints the contents of a viewport and all its children viewports into that device context. It is the responsibility of the application to set the abort procedure, provide a cancel printing dialog, disable the application window during printing, and call the StartDoc, StartPage, EndDoc, and EndPage functions before and after calling this function.
These procedures and the use of these functions is described in the Win32 Programmer’s Reference.
There is no orientation parameter with the Microsoft Windows native printing. The page orientation is determined by the user through the print dialog.
The GlgWinPrint function can be used to add GLG printing output to a page which already had some output on it. In this case, that other output may set the printer device context parameters to values incompatible with the GLG output. Before calling this function, therefore, the device transformations must be reset to the state they were in right after calling the PrintDlg function.
This function is only available under the Microsoft Windows environment.
GlmConvert
A low level function that performs coordinate conversion from the GIS coordinates of a map to the
GLG coordinates of the drawing and visa versa without the help of a GLG GIS Object. Since the function does not rely on a GIS Object being displayed and set up, it may be used before the drawing is rendered or without a drawing at all.
void GlmConvert( projection, stretch, coord_type, coord_to_lat_lon, center, extent, angle, min_x, max_x, min_y, max_y, in_point, out_point )
GlgProjectionType projection;
GlgBoolean stretch;
GlgCoordType coord_type;
GlgBoolean coord_to_lat_lon;
GlgPoint * center, * extent; double angle; double min_x, max_x, min_y, max_y;
GlgPoint * in_point, * out_point;
Parameters
projection
A GIS map projection, may have values of GLG_RECTANGULAR or
GLG_ORTHOGRAPHIC.
103
stretch
Specifies if the map preserves the X/Y ratio (GlgFalse) or not (GlgTrue).
coordinate_type
The type of the GLG coordinate system to convert to or from: GLG_SCREEN_COORD for screen coordinates or GLG_OBJECT_COORD for world coordinates.
coord_to_lat_lon
GlgTrue to convert from GLG coordinates to GIS longitude and latitude, GlgFalse to convert from GIS to GLG coordinates.
center
A pointer to the GlgPoint structure containing lat/lon coordinates of the map center. The Z coordinate must be set to 0.
extent
A pointer to the GlgPoint structure containing X and Y extent of the map in the selected projection: in degrees for the rectangular projection or in meters for orthographic. The Z extent must be set to 0. Refer to the GIS Object section on page 90 of the GLG User’s Guide and
Builder Reference Manual for more details.
angle
A map rotation angle in degrees.
min_x, max_x, min_y, max_y
A map extent in the selected coordinate system. To get X/Y coordinates relative to the map image origin, use min_x=0, min_y=0, max_x=image_width, max_y=image_height
.
in_point
A pointer to the GlgPoint structure containing coordinate values to be converted.
out_point
A pointer to the GlgPoint structure that receives converted coordinate values.
When converting from X/Y to lat/lon coordinates in the orthographic projection, the Z coordinate is set to a negative value for points on the invisible part of the globe or outside the globe area, and to zero for points on the edge of the globe. The coordinates of the returned point may be outside of the visible portion of the map for all projections.
104
GLG Programming Reference Manual
105
2.5 Handling User Input and Other Events
Callback Events
A callback is a function or method that is invoked under certain conditions. For example, a callback is called each time a user selects something in a GLG drawing with the mouse. The code is supplied by the application developer.
A callback can be invoked for one of a few possible reasons:
• The user has used the mouse to select some graphical object in the drawing area of the widget, generating object selection and custom selection events.
• The user has moved the mouse over some object in the drawing, which may generate selection events as well.
• An input widget, such as button or slider, has received some input from the user. This usually arrives in the form of mouse motion or button clicking, although the text widget accepts typed input as well.
• The window has received some window event, such as a window closing request, resize event, etc.
• A SubWindow object has loaded the drawing that will be displayed in it, or a SubDrawing object has loaded its template.
• The GLG Wrapper Widget also invokes callback functions at startup, when resources are set.
• An alarm handler is a special global callback that handles alarm events. Refer to the
GlgSetAlarmHandler section on page 85 for more information.
In addition to these callbacks, the GLG Toolkit provides trace callbacks that are invoked whenever a GLG viewport receives any event. The trace callbacks are used as an escape mechanism to provide low-level access to native windowing events. There are two trace callbacks: a trace callback invoked before dispatching the event for processing, and a trace2 callback invoked after the event has been processed by the Toolkit.
Attaching Callbacks to a Viewport Object
A callbacks is attached to a viewport with the GlgAddCallback function, which takes the callback type and the callback function as parameters: void GlgAddCallback( viewport, type, callback, client data )
GlgObject viewport;
GlgCallbackType type;
GlgCallbackProc callback;
GlgAnyType client_data;
The callback type may be one of GLG_INPUT_CB, GLG_SELECT_CB, GLG_TRACE_CB,
GLG_TRACE2_CB or GLG_HIERARCHY_CB values defined in the GlgApi.h file.
106
GLG Programming Reference Manual
All callbacks use the same function prototype: typedef void (*GlgCallbackProc)( viewport, client_data, call_data )
GlgObject viewport;
GlgAnyType client_data;
GlgAnyType call_data;
Parameters
viewport
A viewport handle corresponding to the viewport to which the callback was attached.
client_data
Application defined data specified by the GlgAddCallback function.
call_data
Callback-specific data supplying information about the event which caused the callback.
A callback must be attached to a viewport before the viewport’s object hierarchy is set up (after the viewport is loaded but before it is drawn). Child viewports may have their own callbacks attached, different from the callbacks of their parent viewport. Only one callback of each type can be attached to one viewport object. To remove a callback, use NULL as a callback parameter.
Adding Callbacks to a GLG Wrapper Widget
In the Motif/Xt environment, a GLG callback can also be attached to the top level viewport of the
GLG Wrapper Widget’s drawing as an Xt callback using the XtAddCallback function. The callback types include
XtNglgSelectCB
XtNglgMotifSelectCB
XtNglgInputCB
XtNglgMotifInputCB
XtNglgTraceCB
XtNglgTrace2CB
XtNglgHierarchyCB
XtNglgHInitCB
XtNglgVInitCB
Notice that for the select and input callbacks two callback types are provided: one following the
GLG generic cross-platform format and one following the Motif calling convention. The callbacks must be added before the widget is realized and its drawing hierarchy is set up.
107
There are two widget initialization callbacks: HInit and VInit, which allow an application to initialize drawing’s resources before it is displayed in the widget. The HInit callback is invoked after the widget’s drawing is loaded, but before its hierarchy is setup. It may be used to initialize values of H resources, such as a number of instances in a series object or a number of points in a graph. The VInit callback is invoked after the hierarchy setup, but before the drawing is displayed.
It may be used for initializing V resources, such as initial data values for a graph.
The Xt callbacks use the standard XtCallbackProc prototype and pass the callback information to the application using the callback’s call_data parameter. The following description of specific callback types includes the description of Motif-style callbacks.
Selection Callback
The selection callback provides a simplified name-based interface to handle object selection. The input callback provides a more elaborate alternative for handling selection events using either object
IDs, or custom events and selection commands which can be attached to objects in the Graphics
Builder.
A selection callback is called when the user selects objects in the widget with a mouse click. If no objects are selected, the call_data parameter will be NULL. If some objects are selected by the click, the call_data parameter will contain a list of names of all selected objects. This list is a
NULL-terminated list of pointers to strings, each of which represents the complete path name of one object selected by the mouse click. If more than one object is selected, the list will contain several strings. The objects drawn on top will be listed first. The pointer to the list as well as pointers to the individual strings point to internal data structures which should not be modified.
The GlgGetSelectionButton function may be used to find out which mouse button was pressed to activate the selection callback.
The path name obtained in the selection callback may be used to query or access resources of the selected object. For example, if the fifth bar of a bar graph was selected, one of the path names will be DataGroup/DataSample4. To query the value of this data sample, concatenate this path name with “Value” using the GlgConcatResNames function and use the resulting
DataGroup/DataSample4/Value path name in a call to GlgGetDResource.
108
GLG Programming Reference Manual
The following example shows how to highlight the selected data sample of a graph with a different color in the selection callback: void Select( viewport, client_data, call_data )
GlgObject viewport;
GlgAnyType client_data;
GlgAnyType call_data;
{ int i; char
** name_array,
* name,
* resource_name; if( !name_array ) return; for( i=0; name = name_array[ i ]; ++i ) if( strstr( name, "DataGroup/DataSample" ) )
{
/* Concatenate the name of the data sample with "FillColor".
*/ resource_name = GlgConcatResNames( name, "FillColor" );
GlgSetGResource( viewport, resource_name,
1., 0., 0. );
GlgFree( resource_name );
/* Red.*/
}
}
Motif Widget Selection Callback
The Motif version of the GLG Wrapper Widget provides the Motif-style select callback
(XtNglgMotifSelectionCB) in addition to the standard GLG callback (XtNglgSelectionCB). The
call_data argument supplied to Motif version of the selection callback function is a structure defined as follows: typedef struct _GlgSelectCBStruct
{
GlgCallbackType reason;
XEvent * event;
GlgObject viewport;
/* Event that triggered the callback */
/* Viewport that received the mouse click that triggered the selection callback */
Widget widget; long num_selected;
/* Wrapper’s widget ID */
/* The length of the selection list */ char ** selection_list; /* Same as in the Xt selection callback */
} GlgSelectCBStruct;
Note that the structure contains the same list of selected objects that is sent to a callback function when using the Xt version of the Wrapper Widget.
109
Input Callback
The Toolkit translates the low-level events of the native windowing system, such as mouse moves, and mouse clicks, into high-level GLG events, such as object selection events, custom events and command actions associated with GLG objects, as well as input events such as slider moves and button presses. An input callback is the primary mechanism for handling any GLG events occurring in an application. It is invoked for several types of input activities:
• When some input activity is detected by an input widget, like moving a slider or a knob with the mouse. The widget has an input handler attached to the widget's viewport to process incoming events, and the type of the widget is defined by the type of the handler.
• When objects in the drawing are selected with the mouse over or mouse click events.
• When custom events or command actions associated with objects in the drawing are triggered in response to mouse move or click events.
• When window events occur, such as closing a top level GLG window.
To activate processing of selection and custom selection events on the mouse click and mouse move, the viewport’s ProcessMouse attribute must be set to GLG_MOUSE_CLICK or
GLG_MOUSE_MOVE_AND_CLICK, respectively. The rest of the event are always processed and do not require any additional settings.
If a system event in a viewport is translated into some GLG event, the input callback of the viewport object is invoked. If the viewport doesn’t have an input callback attached, the input callback of its closest parent with input callback is invoked. The call_data parameter of the callback contains a
message object used to pass all information about the event to the callback. This information is present in the message object in the form of named resources of the message object and may be obtained from it by using methods for querying resources (GlgGetSResource, GlgGetDResource and GlgGetGResource). The message object should be passed as the first parameter, and a resource name defining the resource to query should be passed as the second parameter. For example, the following code extracts the value of the message object’s Origin resource: char * origin;
GlgGetSResource( message_object, “Origin”, &origin );
If the input callback was invoked in response to an activation of an action or a command attached to an object, the message will also contain the ActionObject resource that may be used to access all information associated with the action or command.
110
GLG Programming Reference Manual
Motif Widget Input Callback
The Motif version of the GLG Wrapper Widget provides the Motif-style input callback
(XtNglgMotifInputCB) in addition to the standard GLG callback (XtNglgInputCB). The call_data argument supplied to Motif version of the input callback is a structure defined as follows: typedef struct _GlgInputCBStruct
{
GlgCallbackType reason;
GlgObject viewport; /* Viewport that received the event that triggered the input callback. */
Widget widget; /* Wrapper’s widget ID */
GlgObject message_obj; /* Same as in the Xt input callback */
} GlgInputCBStruct;
Note that the structure contains the same message object that is sent to a callback function when
using the Xt version of the Wrapper Widget; see the Message Object section, below.
Trace Callbacks
The trace callbacks are used as an escape mechanism to provide low-level access to native windowing events. They are invoked whenever a viewport receives a native windowing event and passes the event to the application code for processing. If a viewport object has a trace callback attached, the trace callback will be invoked for all events received by the viewport and all of its child viewports. There are two trace callbacks: the trace callback is invoked before the event is dispatched for processing, and the trace2 callback is invoked after the event has been processed.
As with the other callbacks, it is attached to a viewport with the GlgAddCallback function, or through the resources of the GLG Wrapper Widget.
The information necessary to completely identify an event may be gathered by parsing window data returned to the callback function, or by invoking functions in the GLG Standard or Extended API.
The call_data passed to these callback functions is a structure of platform-specific window data given by the following. In the X Windows environment, the call_data structure looks like this: typedef _GlgTraceCallbackStruct
{
GlgCallbackType callback_type;
GlgObject viewport;
Display display;
Window window;
XEvent * event;
XEvent * event1;
} GlgTraceCallbackStruct;
The callback structure contains enough information to determine which viewport received the event
(indicated by the viewport field), and where it is. It also contains a pointer to an XEvent structure, which may be used to provide details of the event. (The event1 pointer is reserved for future use).
111
Under Microsoft Windows, the trace callback structure looks like this: typedef _GlgTraceCallbackStruct
{
GlgCallbackType callback_type;
GlgObject viewport; void * display;
HWND widget;
HWND window;
MSG * event; void * event1;
} GlgTraceCallbackStruct;
As with the X Windows version, this structure contains information enough to identify the viewport that received the event, and to provide more detail about the event itself. (The event1 pointer is reserved for future use). The callback_type field is set to the type of the callback:
GLG_TRACE_CB or GLG_TRACE2_CB.
Hierarchy Callback
The hierarchy callback is used to get access to the drawing to be displayed in the SubWindow object before the drawing is displayed. SubWindows may be used to switch drawings displayed in them, and an application may want to install a separate input callback for each loaded drawing to handle user interaction instead of having one giant input callback that handles input events from all drawings. An input callback has to be added to the viewport of a drawing displayed in the subwindow before the drawing is set up and drawn. The hierarchy callback is invoked with the ID of the subwindow’s drawing after it is loaded but before its hierarchy is setup, making it possible to add input callbacks as well as initialize the drawing with data before it is painted on the screen.
Similarly, the hierarchy callback is also invoked for the SubDrawing objects when they load their template drawings; the callback provides an object ID of the loaded object that will be displayed in the subdrawing.
The hierarchy callback is attached to a viewport with the GlgAddCallback function. A hierarchy callback may be added to the top level viewport or any of its children viewports. If any of a subwindow’s (or subdrawing’s) parent viewports has a hierarchy callback added, the callback of the closest parent viewport will be invoked each time the subwindow loads a new drawing or the subdrawing loads its template. The hierarchy callback is invoked twice for each template drawing: the first time when the drawing is loaded but before it is set up, and the second time when the drawing is setup but before it is drawn.
The call_data passed to the hierarchy callback is a structure that provides an object ID of the
SubWindow object that triggered the callback, as well as an object ID of the viewport of the loaded drawing:
112
GLG Programming Reference Manual
typedef _GlgHierarchyCallbackStruct
{
GlgCallbackType callback_type;
GlgHierarchyCallbackType reason;
GlgObject object;
GlgObject subobject;
} GlgHierarchyCallbackStruct;
The callback_type field of the callback structure is always set to GLG_HIERARCHY_CB. The
reason field indicates when the callback is invoked: it is set to GLG_BEFORE_SETUP_CB when the callback is called before the hierarchy setup and to GLG_AFTER_SETUP_CB when it is invoked after the setup.
The object field provides an object ID of the SubWindow or SubDrawing object that triggered the callback. The subobject field contains an ID of the drawing that will be displayed in the subwindow, or ID of the object that will be shown in the subdrawing (the Instance attribute).
The source code of the SCADA Viewer demo provides an example of using the callback.
Message Object
A message object is a GLG object like any other. It is a group object, containing data in the form of named attributes just like other GLG objects. It is used to pass data to the input callbacks that may be associated with a viewport.
Any message object has the following named attributes:
Resource
Name
Format
Origin
FullOrigin
Action
SubAction
Data Type
String
String
String
String
String
Description
Defines the format of the message object and the resources present in it. It is defined by the event type and, for input messages, the type of the input handler which detected the input activity and sent the message.
It may have values such as Button, Slider, Knob,
ObjectSelection, CustomEvent.
Contains the name of the viewport that initiated the message.
Contains the full path name of the viewport that initiated an input or window message, or the full path name of the object that initiated a custom event or a command message. This resource will be set to an empty string for other types of messages.
Describes the input action occurred. It may have values such as ValueChanged, Activated, CustomEvent,
MouseClick and so on, depending on the event type.
Describes the action in more details. For example, for the slider’s ValueChanged action it describes what caused the value change and may have values such as Click or
Motion.
113
Resource
Name
Object
OrigObject
Data Type Description
GlgObject
The top-level object that triggered the Input callback, a custom event or a command action. This resource is present in all messages except the ObjectSelection message.
GlgObject
The low-level object that triggered the Input callback, a custom event or a command action. This resource is present in all messages except the ObjectSelection message.
A message object can have other resources as well, depending on the type of the event and, for input object events, the type of the input handler that generated the event. For events triggered by an
Action attached to an object, such as Command or Custom Event, the message contains the
ActionObject resource.
For events generated by input objects, such as a slider or a button, the message object includes handler-related resources of the input widget. For example, the message object coming from a GLG slider object may also contain such resources as ValueX, ValueY, Granularity, Increment,
DisableMotion and others. These resources may be queried from either the message object or the viewport object that generated the message.
Refer to the Appendix B: Message Object Resources on page 365 for a complete list of all message
types and their resources. Refer to the Input Handlers chapter of the GLG User’s Guide for a complete list of resources for each input handler type.
Examples of Using Callbacks in Application Code
The following examples demonstrate how to use GLG callbacks. Refer to the source code of the
GLG demos for additional examples.
Adding callbacks
The following code adds both selection and input callbacks to the drawing viewport object:
GlgAddCallback( drawing, GLG_SELECT_CB, SelectCB, callback_data );
GlgAddCallback( drawing, GLG_INPUT_CB, InputCB, callback_data );
Processing Selected Objects using Selection Callback
A selection callback has several parameters, one of which is a list of names of all selected objects, including complete path identifying the place of objects in the drawing hierarchy. The following example shows a selection callback which prints names of all selected objects:
114
GLG Programming Reference Manual
void SelectCB( drawing, client_data, call_data )
GlgObject drawing;
GlgAnyType client_data;
GlgAnyType call_data;
{ char ** name_ array; char * name; int i; name_array = (char **) call_data; if( !name_array )
PrintOnConsole( "Nothing was selected." ); else
for( i=0; name = name_array[ i ]; ++i )
PrintOnConsole( name );
}
The selection callback may be used with a minimal GLG configuration, such as the Basic Edition of the Graphics Builder and the GLG Standard API.
Processing Selected Objects Using Input Callback
While the select callback provides a simplified name-based interface for handling object selection, the input callback provides a more elaborate mechanism based on object IDs. Several object selection techniques are available:
• A targeted object selection via the use of a custom event or command action attached to an object at design time. When an object is selected with the mouse, the input callback is invoked with a message that contains detailed information about the action that triggered the callback.
• An ObjectSelection message that provides a list of IDs of all selected objects on the lowest level of the object hierarchy. It does not require anything to be done at design time, but uses the Intermediate API in the application code to retrieve IDs of selected objects.
The object selection event is generated when the mouse is moved over an object in the drawing, or an object is selected with a mouse click. The custom selection events and commands are generated when the selected object has a custom event or command action. The ProcessMouse attribute of the viewport object has to include a combination of the Move and Click masks to enable object selection and custom selection events on the corresponding mouse events. Refer to the Integrated Features
of the GLG Drawing chapter on page 51 of the GLG User’s Guide and Builder Reference Manual for more information on object selection and custom selection events.
The following example shows how to process selection using both types of object selection messages.
void InputCB( viewport, client_data, call_data )
GlgObject viewport;
GlgAnyType client_data;
GlgAnyType call_data;
{
GlgObject
115 message_obj, selection_array, selected_object, command, action_object, action_data; char
* format,/* Message format */
* action,/* Message action */
* selecte_object_name, /* Name of the selected object. */
* event_label, /* Event label of a custom event or command. */
* command_type; /* Type of a command to be executed on object selection. */ double button_index; /* Button that caused object selection. */ int i, size; message_obj = (GlgObject) call_data;
GlgGetSResource( message_obj, "Format", &format );
GlgGetSResource( message_obj, "Action", &action ); if( strcmp( format. “Command” ) == 0 )
{
/* This code handles command actions attached to anobject. */
/* Retrive command information using the Standard API. */
GlgGetSResource( message_obj,
“ActionObject/Command/CommandType”,&command_type );
GlgGetSResource( message_obj, "EventLabel", &event_label );
GlgGetSResource( message_obj, "Object/Name",
&selected_object_name );
/* Retrieve the object IDs of the command and the selected object using the Intermediate API. */ selected_object = GlgGetResourceObject( message_obj, "Object" ); command =
GlgGetResourceObject( message_obj, "ActionObject/Command" );
ExecuteCommand( selected_object, command_type, command );
} else if( strcmp( format, “CustomEvent” ) == 0 )
{
/* This code handles custom events attached toan object.
This code handles both custom event actions and the old-style custom events. */
GlgGetSResource( message_obj, "EventLabel", &event_label );
/* Don't process events with empty EventLabel. An event with an empty EventLabel is generated for MouseOver events when the mouse moves away from the object, and for MouseClick events when the mouse button is released.
*/ if( strcmp( event_label, "" ) == 0 )
return;
116
GLG Programming Reference Manual
/* Retrieve command and selected object (Intermediate API).
*/ selected_object = GlgGetResourceObject( message_obj, "Object" );
/* Retrieve the selected object’s name using Standard API. */
GlgGetSResource( message_obj, “Object/Name”,
&selected_object_name );
/* For the old-style MouseClick actions, query the mouse button that generated this custom selection event (0 for custom
MouseOver events). */
GlgGetDResource( message_obj, “ButtonIndex”, &button_index );
/* Prints MouseClick or MouseOver. */
PrintOnConsole2( “Custom event action: “, action );
PrintOnConsole2( “Selected object: “, selected_object_name );
/* Retrieve ActionObject resources of the message object
(Intermediate API). ActionObject will be NULL for custom events added prior to GLG v.3.5. */ action_obj =
GlgGetResourceObject( message_obj, "ActionObject" );
/* Retrieve the action’s ActionData. If present, itsproperties may be used for processing the event. */ if( action_obj ) action_data =
GlgGetResourceObject( action_obj, "ActionData" );
}
/* Handle default object selection message. */ else if( strcmp( format, "ObjectSelection" ) == 0 )
{ selection_array =
GlgGetResourceObject( message_obj, “SelectionArray” ); if( !selection_array )
{
PrintToConsole( “No objects selected by “, action ); return;
}
/* For MouseClick actions, query the mouse button that caused the the selection (0 for MouseMove events). */
GlgGetDResource( message_obj, “ButtonIndex”, &button_index ); size = GlgGetSize( selection_array ); for( i=0; i < size; ++i )
{ selected_object = GlgGetElement( selection_array, i );
GlgGetSResource( selected_object, “Name”,
&selected_object_name );
/* Print MouseMove or MouseClick. */
PrintToConsole2( “Selected by: “, action ); if( !selected_object_name || !*selected_object_name )
117
}
}
}
PrintToConsole( “Unnamed object is selected.” ); else
PrintToConsole2( “Selected object: “, selected_object_name );
The Enterprise Edition of the Graphics Builder is required to add Command actions or custom event actions to objects at design time. The GLG HMI Configurator can be also used to add Command actions to objects. The GLG Intermediate API may be used for more efficient and flexible processing of the Command and Custom Event actions in the application code. In the above example, the GlgGetResourceObject Intermediate API call is used to retrieve object ID of the selected object as well as the command object.
Handling the ObjectSelection message requires the use of the GLG Intermediate API to retrieve IDs of the selected objects.
Processing Input Object Events
There are two methods for processing user input from input objects, such as a button, a slider or a text input field, in an application code:
• using low-level input object events based on input object names
• using targeted input commands via the use of Input Command actions attached to input objects at design time. The InputAction parameter of the action object specifies the condition that triggers the input callback. When an input object receives user input, the input callback is invoked with a message that contains detailed information about the event.
The following example demonstrates a very simple input callback which terminates the application when a Quit button is pressed. The example demonstrates how to handle the default input object events, as well as an attached command actions.
void InputCB( drawing, client_data, call_data )
GlgObject drawing;
GlgAnyType client_data;
GlgAnyType call_data;
{
GlgObject message_object; char
* origin, /* Name of the input object */
* format, /* Message type */
* action, /* Reason */
* command_type; /* Command to be executed */ message_object = (GlgObject) call_data;
GlgGetSResource( message_object, "Format", &format );
/* Handle default input object events. */ if( strcmp( format, "Button" ) == 0 )
118
GLG Programming Reference Manual
{
GlgGetSResource( message_object, "Action", &action );
/* Query the name of the button that generated the message. */
GlgGetSResource( message_object, "Origin", &origin ); if( strcmp( action, "Activate" ) == 0 && strcmp( origin, "Quit" ) == 0 ) exit( 0 );
}
/* Handle command actions attached to a button. */ else if( strcmp( format, “Command” ) == 0 )
{
GlgGetSResource( message_object,
"ActionObject/Command/CommandType", &command_type ); if( strcmp( command_type, “Quit” ) == 0 ) exit( 0 );
}
}
The Enterprise Edition of the Graphics Builder is required to add Input Command actions to input objects at design time. The GLG HMI Configurator can be also used to add Input Command actions.
The GLG Intermediate API may be used for more efficient and flexible processing of the Input
Command actions in the application code.
119
Refining Input Object Selection
Default Input Object Events
The following code fragment shows an example of an input callback that uses default input object events. The code determines which of the two sliders in the drawing (the temperature slider or pressure slider) received user input, and calls the appropriate function to process the new value specified by the user.
void InputCallback( viewport, client_data, call_data )
GlgObject viewport;
GlgAnyType client_data;
GlgAnyType call_data;
{
GlgObject message_obj; char
* format,
* action,
* full_origin; double value; message_obj = (GlgObject)call_data;
/* Extract callback data from the message object. */
GlgGetSResource( message_obj, "Format", &format );
GlgGetSResource( message_obj, "Action", &action );
GlgGetSResource( message_obj, "FullOrigin", &full_origin );
/* Ignore if message came not from a slider or not a ValueChanged. */ if( strcmp( format, "Slider" ) != 0 || strcmp( action,
"ValueChanged" ) != 0 ) return;
/* Obtain the new value of the slider. */
GlgGetDResource( message_obj, "Value", &value );
/* Call an appropriate function depending on the slider name. */ if( strcmp( full_origin, "TemperatureBlock/Slider" ) == 0 )
ProcessTemperatureInput( widget, value ); else if( strcmp( full_origin, "PressureBlock/Slider" ) == 0 )
ProcessPressureInput( widget, value ); else
Error( "Unknown name." );
}
Alternatively, Input Command actions may be attached to the sliders to execute the attached command as shown below.
120
GLG Programming Reference Manual
Input Commands
The following input callback code demonstrates handling Input Command actions attached to the temperature and pressure sliders in the drawing. The code is completely generic and may be used with any drawing, since it uses the command data to execute the command without any reliance on the names of input objects in the drawing. The GLG Intermediate API is used to retrieve IDs of the input object and the command object.
void InputCallback( viewport, client_data, call_data )
GlgObject viewport;
GlgAnyType client_data;
GlgAnyType call_data;
{
GlgObject message_obj, command_obj, input_obj; char
* format,
* command_type,
* value_resource,
* tag; double value; message_obj = (GlgObject)call_data;
/* Extract callback data from the message object. */
GlgGetSResource( message_obj, "Format", &format ); if( strcmp( format, "Command" ) != 0 ) return;
GlgGetSResource( message_obj, "ActionObject/Command/CommandType",
&command_type ); if( strcmp( command_type, “WriteValueFromWidget” ) == 0 )
{ command_obj =
GlgGetResourceObject( message_obj, “ActionObject/Command” );
/* Input object that triggered the message. */ input_obj = GlgGetResourceObject( message_obj, “Object” );
/* The resource path to the input object’svalue.*/
GlgGetSResource( command, “ValueResource", &value_resource );
/* New value of input object. */
GlgGetDResource( input_obj, value_resource, &value );
/* The process controller tag to write the value to. */
GlgGetSResource( command, “OutputTagHolder/TagSource”, &tag );
}
/* Write the new value. */
SendValueToController( tag, value );
121
}
Trace Callback examples
For examples of using the trace callback, refer to the source code of the GLG Diagram demo.
Hierarchy Callback examples
For examples of using the hierarchy callback, refer to the source code of the GlgSCADAViewer demo.
122
GLG Programming Reference Manual
123
2.6 GLG Intermediate and Extended API
The GLG Standard API enables an application to display a GLG drawing and animate it by querying and setting resources. The GLG Extended API adds functionality that allows an application program to edit or create the drawing at run time. The GLG Intermediate API is a subset of the
Extended API that provides all of the Extended API methods for manipulating the drawing, except for the methods for creating, adding or deleting objects from the drawing at run time.
The GLG Intermediate API may be used to modify GLG drawings created in the GLG Graphics
Builder and to implement elaborate custom logic to handle user interaction. The Intermediate API may also be used to obtain object IDs of resources in the drawing to access them directly, eliminating the resource path parsing required by the Standard API methods and increasing update performance of large drawings. The Intermediate API provides extensive functionality for changing an object’s geometry and layout, creating and removing constraints, as well as advanced introspection capabilities for traversing the drawing and determining its content at run time.
The GLG Extended API includes all method of the Standard and Intermediate APIs and adds methods for creating, copying and adding objects to the drawing at run time. The Extended API may be used for adding objects to the drawing at run time or creating a drawing on the fly based on a configuration file. It may also be used for adding dynamics, tags and custom properties to objects at run time.
Both the Intermediate and Extended APIs are available in all deployment options supported by the
Toolkit, including C/C++, Java, C#/.NET and (on Windows) ActiveX Control.
Refer to the DEMOS and examples directories for examples of using the Intermediate and Extended
API methods in various programming environments.
Overview
Because of the abstract approach of the GLG architecture, the Extended API is small and simple, with very few functions to worry about, while still providing all the tools you need to create highly elaborate drawings. The power of the library comes from the symmetry of the architecture, where everything in a drawing is represented as a data object. This lets you use the same functions in many different combinations to obtain different effects, using the resource notation to control their actions.
There are two libraries that provide the Extended API functionality: GLG Intermediate Library and GLG Extended Library. The Intermediate Library provides all of the Extended API methods, except for the methods for creating and deleting objects at run time. The Extended Library contains all Extended API functions, including the methods for creating objects at run time.
In order to minimize the size of the API, all GLG functions are generic in the sense that some of their arguments are of the GlgAnyType type. The actual type of these parameters is determined dynamically at run time by their context (as defined by the values of the other parameters).
124
GLG Programming Reference Manual
The GLG Intermediate and Extended APIs include the following functions:
• GlgCreateObject creates a GLG object of any type
(Extended API only)
.
• GlgCopyObject creates a copy of an object
(Extended API only)
.
• GlgCloneObject creates a specialized copy (clone) of an object
(Extended API only)
.
• GlgLoadObject loads a GLG object from a file.
• GlgLoadObjectFromImage loads a GLG object from a memory image created by the GLG
Code Generation Utility.
• GlgSaveObject saves a GLG object into a file.
• GlgReferenceObject references an object.
• GlgDropObject dereferences an object.
• GlgAddObjectToTop, GlgAddObjectToBottom, GlgAddObjectAt and GlgAddObject add an object to some container object. This can be used to add an object to a group or viewport as well as to add a point to a polygon
(Extended API only)
.
• GlgDeleteTopObject, GlgDeleteBottomObject, GlgDeleteObjectAt, GlgDeleteThisObject and GlgDeleteObject delete an object from a container object
(Extended API only)
.
• GlgReorderElement changes the object’s position inside a container.
• GlgContainsObject finds if the object belongs to a container.
• GlgGetNamedObject finds a named object in a container.
• GlgGetElement returns the object at the specified index in a container.
• GlgSetElement replaces the object at the specified index in a container
(Extended API only)
.
• GlgGetIndex returns the index of the first occurrence of the object in a container.
• GlgGetStringIndex returns the index of the first occurrence of the string in a string container.
• GlgFindObject finds an object in a container.
• GlgGetSize queries the size of a container object.
• GlgSetStart initializes a container object for traversing.
• GlgIterate traverses a container object.
• GlgSetXform attaches a transformation to an object
(Extended API only)
.
• GlgGetResourceObject gets the object ID of a resource object.
• GlgSetResourceObject replaces the resource with a new object
(Extended API only)
.
• GlgCreateResourceList returns a list of an object’s resources.
• GlgGetTagObject returns a tag object with a specified tag name or tag source, or a list of tags matching the specified tag name or tag source pattern.
• GlgGetAlarmObject returns an alarm object with a specified alarm label, or a list of alarms matching the specified alarm label pattern.
• GlgConstrainObject adds constraints.
125
• GlgUnconstrainObject removes constraints.
• GlgSuspendObject suspends the object for editing.
• GlgReleaseObject releases the object after editing.
• GlgGetParent returns an object’s parent object, if one exists.
• GlgGetBoxPtr returns an object’s bounding box.
• GlgCreateSelectionNames returns the names of all the objects intersecting a given rectangle.
• GlgCreateSelectionMessage finds an object selected by a given selection criteria in a rectangular area and returns the selection information as a message.
• GlgCreateSelection returns an array of objects intersecting a given rectangle.
• GlgGetDrawingMatrix returns the matrix corresponding to the input object.
• GlgCreateInversedMatrix inverts a transformation matrix object.
• GlgTransformPoint transforms a single point.
• GlgCreatePointArray creates and returns an array containing all control points of an object.
• GlgMoveObjectBy, GlgMoveObject, GlgScaleObject, GlgRotateObject,
GlgPositionObject, GlgFitObject and GlgTransformObject transform an object in various ways.
• GlgLayoutObjects performs various alignment and layout operations.
• GlgGetMatrixData and GlgSetMatrixData query and set matrix data values.
• GlgScreenToWorld and GlgWorldToScreen convert coordinates between the screen and world coordinate systems.
• GlgTranslatePointOrigin converts screen coordinates of a point in one viewport to the screen coordinates relative to another viewport.
• GlgRootToScreenCoord converts screen coordinates relative to the root window to the screen coordinates in the specified viewport.
• GlgGetParentViewport returns a parent viewport of a GLG object.
• GlgPositionToValue returns a chart, plot or axis value corresponding to the cursor position.
• GlgCreateChartSelection returns information about a chart’s sample under the cursor.
• GlgCreateTooltipString creates and returns a tooltip string corresponding to the current cursor position on top of a chart or axis object.
Handling GLG Objects
As with the standard GLG API library, the programmer’s task is made simpler by the dynamic typing of GLG objects. Most of the functions in the Extended API operate on several different kinds of objects. The action each one takes often depends on the type of its input object.
126
GLG Programming Reference Manual
The Reference Count
Each GLG object occupies space in the computer memory. Some objects are larger than others, but all of them take up some space. In order to make certain that only objects used by a program are kept in memory, each object is equipped with a reference count. This is simply an integer with which an object keeps track of the number of operations that care about its existence. The GLG
Extended API provides functions to increase and decrease the reference count: GlgReferenceObject and GlgDropObject. When an object’s reference count reaches zero, it is deleted, and its memory reclaimed.
When an object is created, its reference count is 1. Adding the object to a group increases its reference count, making sure that the object is kept around while it is needed. If you want the object to be deleted when the group is deleted, you can decrease the reference count once that object is safely contained in the group. This restores the reference count to 1. This is the standard sequence for creating GLG objects: create object, place in group or viewport, drop reference count. If the group is deleted or exploded, its members may be deleted, unless they are referenced beforehand.
An object is “responsible” for managing the reference count of its subsidiary objects. For example, a polygon object is responsible for managing the reference counts of its attribute objects. Similarly, when an object is inserted into a container, the container increments that object’s reference count.
When the object is removed from the group, its reference count is decremented. (Note that this can cause an object to be inadvertently deleted if the group was the only current reference to the object.
If you want to remove an object from a group and put it somewhere else, you must increment its reference count before removing it.)
If these guidelines are met, any object with a reference count of zero may be safely deleted, and its memory reclaimed. This will prevent memory leaks, keeping all the system’s memory available to the application.
Using Mouse Coordinates and Pixel Mapping
The Toolkit’s rendering engine uses the OpenGL-style pixel mapping for consistent rendering across all windowing systems and programming environments. The integer pixel values are mapped to the center of the pixel, which means that the x and y coordinates of the center of the upper left pixel of a window are (0.5;0.5) instead of (0;0). When using the mouse position to obtain screen coordinates passed to the GLG functions, add GLG_COORD_MAPPING_ADJ (defined as 0.5 in
GlgApi.h) to the x and y screen coordinates of the mouse for better precision.
Function Descriptions
To use any of the functions described in this chapter, the application program must include the function definitions from the GLG API header file. Use the following line to include those definitions:
#include "GlgApi.h"
127
GlgCreateObject
Creates a GLG object of any type
(Extended API only)
.
GlgObject GlgCreateObject( type, name, data1, data2, data3, data4 )
GlgObjectType type; char * name;
GlgAnyType data1;
GlgAnyType data2;
GlgAnyType data3;
GlgAnyType data4;
Parameters
type
Specifies the type of GLG object to be created.
name
An optional argument specifying a name to be assigned to the object. This name can be used later for accessing the object and its attributes without keeping the object ID returned by
GlgCreateObject. Use NULL as the value of this parameter to create an object without a name.
The object’s name is an editable attribute of the object, so the name can be assigned or changed later using the resource access functions.
Using the object ID is the fastest method for accessing the object, but it requires keeping the object ID and referencing the object to make sure it is not destroyed while the ID is being used.
Using the object name to access the object via the resource mechanism is slightly slower, but it is fast enough for most applications and it ensures the proper use of the object ID.
data1, data2, data3, data4
Parameters which depend on the type of the object to be created. These are described below.
This function creates and returns an object of the specified type. The reference count of the created object is set to 1. Any created object has to be explicitly dereferenced when it is not needed any more or has been referenced by some other object (for example, adding an object to a group references the object). Refer to the description of the GlgReferenceObject function for the details on reference counting and object usage.
Most of the entities in the GLG Toolkit, such as graphical objects, container objects, transformations and even attributes, are objects. The GlgCreateObject function is used to create any of these objects and is probably the most complex function of the API.
128
GLG Programming Reference Manual
Using GlgCreateObject
The type parameter specifies the kind of object to be created. Its possible values and the usage of the accompanying data parameters are outlined in the table below. More detailed descriptions of their use follow the table.
The following table summarizes the usage of the data parameters:
data4
NULL
Object Type
GLG_ARC
GLG_MARKER
GLG_PARALLELOGRAM
GLG_POLYLINE
GLG_POLYSURFACE
GLG_VIEWPORT
GLG_BOX_ATTR
GLG_RENDERING
GLG_LIGHT
GLG_POLYGON
GLG_SPLINE
NULL
data1
GLG_TEXT
GLG_IMAGE
GLG_GROUP
GLG_ARRAY
GLG_LIST
GLG_REFERENCE
GLG_SERIES
GLG_SQUARE_SERIES
data2
NULL
data3
NULL number of vertices
GlgLong optional polygon default: 2 spline default: 3 string char * optional default: empty string image filename char* optional default: NULL
NULL type of group
GlgContainerType optional default: NULL template
GlgObject mandatory for all reference types
(use NULL for file references) template
GlgObject mandatory
NULL text subtype
GlgTextType optional default:
GLG_FIXED image subtype
GlgImageType optional default:
GLG_FIXED
_IMAGE number of objects
GlgLong optional default: NULL referencing type
GlgRefType optional default:
GLG_REFER
ENCE_REF
NULL
NULL
NULL
NULL
NULL
NULL
NULL
NULL
NULL
NULL
NULL
NULL
Object Type
GLG_CONNECTOR
GLG_FRAME
GLG_GIS
GLG_DATA
GLG_ATTRIBUTE
GLG_ALIAS
GLG_HISTORY
GLG_XFORM
GLG_TAG
data1
connector subtype
GlgObjectType mandatory frame subtype
GlgFrameType mandatory dataset file char * optional data type (D, S or
G)
GlgDataType mandatory data type (D, S or
G)
GlgDataType mandatory alias name char * optional default: NULL resource name mask char * optional default: NULL xform role
GlgXformRole mandatory tag name char * optional default: NULL
data2
number of points for recta-linear path or NULL optional default: 2 frame factor
GlgLong mandatory
NULL string value (S data only) char * optional default: NULL attribute role
GlgXformRole mandatory resource path char * optional default: NULL
NULL xform subtype
GlgXformType mandatory tag source char * optional default: NULL
data3
NULL
NULL
NULL
NULL
NULL
NULL
data4
NULL
NULL
NULL
NULL
NULL
NULL entry point data type (D, S or
G)
GlgDataType optional default:
GLG_D xform object
GlgObject optional default: NULL tag comment char * optional default: NULL
NULL xform object
GlgObject optional default: NULL
NULL
129
130
GLG Programming Reference Manual
Usage Summary for GlgCreateObject
Some object types, such as the attribute, font, and colortable, are not included in the table, or in the lists below. These objects types are created automatically when you create some other objects. For example, creating a polygon object automatically creates all the necessary attribute objects including the specified number of points. After a polygon object has been created, the polygon’s attribute objects may be accessed and their values may be changed through the resource mechanism.
When an object is created, it is created with default values for its attributes. After the object has been created, the attributes may be assigned values different from the default ones using the resource access functions in the standard API.
Graphical Objects
Graphical objects are displayable objects used to represent graphical shapes in the drawing.The usage of the GlgCreateObject data parameters for the graphical objects is outlined in the following list:
GLG_ARC
No data parameters are used. Use NULL for each parameter value.
GLG_CONNECTOR data1
Specifies a mandatory connector subtype (GlgObjectType) which may have the following values:
GLG_POLYGON
Recta-linear connectors
GLG_ARC
Arc connectors
data2
An optional number of control points for the recta-linear connectors (use NULL for arc connectors). The default value for the recta-linear connectors is 2, resulting in one path segment connecting the two control points. By using a value greater than two, more than one path segment is produced (i.e. using a value of 4 yields 3 path segments connecting 4 control points).
data3, data4
Not used. Use NULL for each parameter’s value.
GLG_FRAME data1
Specifies a mandatory frame subtype (GlgFrameType), which can have the following values:
GLG_1D
GLG_2D
GLG_3D
GLG_FREE
Refer to the GLG Objects chapter for the details on the frame subtypes. The point frame is the same as a free frame with only one point.
131
data2
Specifies a mandatory frame factor. The frame factor value defines the number of frame intervals, which is one smaller than the number of control points. The frame factor is a creation-time parameter and can’t be changed after the frame has been created.
data3, data4
Not used. Use NULL as the parameter’s value.
GLG_IMAGE data1
A filename (char*) of an image file in the GIF, JPEG, PNG or BMP (Windows only) format.
data2
An optional image object subtype (GlgImageType) which may have the following values:
GLG_FIXED_IMAGE
GLG_SCALED_IMAGE
Refer to the GLG Objects chapter for details on the image subtypes. The default value is
GLG_FIXED_IMAGE.
data3, data4
Not used. Use NULL for each parameter’s value.
GLG_MARKER
No data parameters are used. Use NULL for each parameter value.
GLG_PARALLELOGRAM
No data parameters are used. Use NULL for each parameter value.
GLG_POLYGON data1
Specifies an optional number of polygon points (GlgLong). If NULL is used as the parameter’s value, a default value of two (2) is used and a polygon with two points is created.
data2, data3, data4
Not used. Use NULL for each parameter’s value.
GLG_POLYLINE
No data parameters are used. Use NULL for each parameter value.
GLG_POLYSURFACE
No data parameters are used. Use NULL for each parameter value.
GLG_TEXT data1
An optional string (char*) to be assigned to the text object. The text object will create a copy of the string. Using NULL causes the default value (the empty string) to be used.
data2
The optional text object subtype (GlgTextType) which may have the following values:
GLG_FIXED_TEXT
GLG_FIT_TO_BOX_TEXT
132
GLG Programming Reference Manual
GLG_WRAPPED_TEXT
GLG_TRUNCATED_TEXT
GLG_WRAPPED_TRUNCATED_TEXT
GLG_SPACED_TEXT
Refer to the GLG Objects chapter for the details on the text subtypes. The default value is
GLG_FIXED_TEXT.
data3, data4
Not used. Use NULL for each parameter’s value.
Example: Creating a Polygon
The following example shows a fragment of code which creates a polygon with three points, sets values of some attributes, and adds the polygon to a viewport:
{
GlgObject polygon;
/* Create a polygon with 3 points named "Polygon1". */ polygon = GlgCreateObject( GLG_POLYGON, "Polygon1",
(GlgAnyType)3, 0, 0, 0 );
/* Set some of the polygon’s attributes, use the default attribute values for the rest of the attributes.
*/
GlgSetDResource( polygon, "OpenType", (double) GLG_CLOSED );
GlgSetDResource( polygon, "FillType", (double) GLG_EDGE );
GlgSetGResource( polygon, "FillColor", /* Green */ 0., 1., 0. );
/* Add the polygon to a viewport object for displaying. */
GlgAddObject( viewport, polygon, GLG_BOTTOM, 0 );
/* The group have referenced the added polygon.
Dereference the polygon to let the group manage it.
This is required since any object is created with the reference count set to 1.
*/
GlgDropObject( polygon );
}
Refer to the description of the GlgIterate function for the coding fragment showing how to set coordinates of the polygon’s points.
Also refer to the Demo directory for examples of complete programs using the GLG Extended API.
Containers and Composite Objects
A container object may hold elements of different types as defined by the creation parameters described below and may be used to keep, save, load, and copy collections of user-defined values.
A container may be used to group graphical objects in the drawing, in which case the container is a graphical object which may be added to the drawing. There are two types of containers, different in their internal representation: GLG_ARRAY (dynamic array) and GLG_LIST (linked list). There is also a GLG_GROUP type, which may be used to create a container object when the internal representation of the container is not important and whose default value is GLG_ARRAY.
133
Other GLG objects may inherit container functionality. For example, a viewport object serves as a container of graphical objects, and a polygon is a container of points.
GLG_GROUP
GLG_ARRAY
GLG_LIST data1
Specifies the type of the container’s elements and may have the following values:
GLG_OBJECT
for containers to hold GLG objects of any type or hierarchies of GLG objects. This may also be used to hold double floating values, strings or geometrical points in form of the GLG data or attribute objects. Objects are referenced when added to the container, and dereferenced when they are deleted or their container gets destroyed.
GLG_NON_DRAWABLE_OBJECT
ADVANCED: same as GLG_OBJECT, but used when the container object will not be drawn. This may be used for creating light-weight containers which are never added to the drawing to be displayed, as well as for creating custom properties that should not be setup. For example, if a group of custom properties contains drawable objects, it should not be setup to avoid the drawable objects being drawn when the custom properties are setup.
GLG_STRING
for containers to hold C character strings. The strings added to the container will be clones of the input strings. Note that the GlgFindObject and GlgIterate functions return pointers to the internal strings which must not be altered or freed.
Deleting a string from a container will automatically free it. Empty strings and
NULL pointers are allowed in the container.
GLG_LONG
for containers to hold integer values or addresses. The container’s elements will be of the longest integer type and are guaranteed to hold memory pointers. The memory pointed to by a pointer is not copied or freed automatically: this must be handled by the application which uses the container.
data2
Specifies a maximum number of objects in the group (GlgLong). This parameter is optional and is used only for GLG_GROUP and GLG_ARRAY containers. If you know the maximum number of objects in the group in advance, you may use this parameter to slightly optimize the group’s performance. If the number is not known in advance, use NULL as the parameter’s value. It will not cause an error to exceed the specified number of objects in the group at run time.
data3, data4
Not used. Use NULL as the parameter’s value.
GLG_VIEWPORT.
No data parameters are used. Use NULL for each parameter’s value.
134
GLG Programming Reference Manual
GLG_SERIES
GLG_SQUARE_SERIES data1
Specifies a mandatory template object (GlgObject). This object is replicated by the series according to the series’ factors. The series objects are created with the default value of the
Factor attribute equal to one. The same template object should not be used for more than one series.
data2, data3, data4
Not used. Use NULL as the parameter’s value.
GLG_REFERENCE data1
A mandatory template object (GlgObject) for a container or object reference. Use NULL for file reference objects.
data2
An optional reference subtype (GlgRefType) which may have the following values:
GLG_REFERENCE_REF
Template and file reference objects.
GLG_CONTAINER_REF
Container objects.
Refer to the GLG Objects chapter for details on the reference subtypes. The default value is GLG_REFERENCE_REF.
data3, data4
Not used. Use NULL for each parameter’s value.
Non-Graphical Objects
Non-graphical objects are used to keep data values as well as control a wide variety of the visible features of graphical objects. Refer to the GLG Objects chapter of the GLG User’s Guide and
Builder Reference Manual for more information. The following list outlines the usage of the
GlgCreateObject data parameters for non-graphical objects:
GLG_DATA.
data1
Specifies a mandatory data type (GlgDataType) which may have the following values:
GLG_D
D data (double)
GLG_S
S data (string)
GLG_G
G data (triplet of double values to define XYZ or RGB)
data2
Specifies an optional string value for the S data type. Use NULL for D and G data types.
data3, data4
Not used. Use NULL as the parameter’s value.
135
GLG_ATTRIBUTE.
data1
Specifies a mandatory data type (GlgDataType) which may have the following values:
GLG_D
D attribute (double)
GLG_S
S attribute (string)
GLG_G
G attribute (triplet of double values to define XYZ or RGB)
data2
Specifies a mandatory attribute role (GlgXformRole) which may have the following values:
GLG_GEOM_XR
GLG_COLOR_XR
GLG_GDATA_XR
GLG_DDATA_XR
GLG_SDATA_XR
The attribute’s role determines the type of transformations that will affect the object. Refer to the GLG Objects chapter for more information.
data3, data4
Not used. Use NULL as the parameter’s value.
GLG_ALIAS data1
Specifies the alias name (char*). This is an alternative (logical) name for accessing the resource pointed to by the alias. The default value is NULL.
data2
Specifies the resource path for the alias (char*). The default value is NULL.
data3, data4
Not used. Use NULL as the parameter’s value.
GLG_HISTORY data1
Specifies the resource name mask (char*) used to access resources to be scrolled. The default value is NULL.
data2
Not used. Use NULL as the parameter’s value.
data3
Specifies the data type of the entry point. Possible values are GLG_D, GLG_S and GLG_G.
This data type must match the data type of the resources pointed to by the resource name mask. The default value is GLG_D.
data4
Not used. Use NULL as the parameter’s value.
136
GLG Programming Reference Manual
Transformation Objects
This section details procedures for creating the transformation objects. An introduction to these objects can be found in the GLG Objects chapter.
GLG_XFORM data1
Specifies the role the transformation plays in the object hierarchy (GlgXformRole). It is a mandatory parameter and may have the following values:
GLG_GEOM_XR
- for a geometrical transformation
GLG_COLOR_XR
- for a color transformation
GLG_DDATA_XR
- for a scalar transformation.
GLG_SDATA_XR
- for a string transformation.
The data2 parameter is a mandatory parameter, and specifies the type of the transformation
(GlgXformType) and may have the following values. Its possible values vary with the value of the
data1 parameter.
The parameters used to control a transformation are set using the resource mechanism after the transformation object is created. So, for example, to create a move transformation that moves a geometric object 50 units in the X direction takes two steps. First, you create a MoveX transformation object (GLG_TRANSLATE_X_XF), and only then do you set its attributes to move the desired amount. For geometric transformations, the most commonly manipulated resource is divided into two attributes, and the transformation depends on the product of the two.
For a MoveX transformation, the two attributes are the X distance and the Factor attributes. This allows the application to scale to the data it is to receive.
The following transformations may be attached to an attribute of any type (D, S or G), and use the following values of the data2 parameter:
GLG_LIST_XF
The transformed value is selected from a list of values based on the transformation’s index attribute, which is 0-based. When a list transformation is created, the data3 parameter can be used to pass an array of values using a group containing GLG_ATTRIBUTE objects.
The type of attribute object in the group should match the type of attribute the transformation is attached to (D, S or G).
GLG_THRESHOLD_XF
The transformed value is selected from a list of values based on the transformation’s input value, which is compared with a list of thresholds. When a list transformation is created, the data3 parameter can be used to pass an array of values using a group containing
GLG_ATTRIBUTE objects. The type of attribute object in the group should match the type of attribute the transformation is attached to (D, S or G). The data4 parameter can be used to pass an array of thresholds, which is a group containing GLG_ATTRIBUTE objects of scalar (D) type.
GLG_SMAP_XF
GLG_DMAP_XF
The transformed value is selected by mapping an input key to an output value by matching the input key with the list of keys. The type of the keys is determined by the type of the transformation: D (double) or S (string). The type of the output values is determined by the
137 type of the attribute the transformation is attached to. When a transformation is created, the
data3 and data4 parameters can be used to pass a list of values and a list of keys. The lists are passed using a group containing GLG_ATTRIBUTE objects of an appropriate type.
GLG_TRANSFER_XF
This transformation is used to transfer a value from one attribute object to another. It can be used to implement a “one-way” constraint, where changes in one object affect another, but not vice versa. It has only two attributes. The first attribute is meant to be constrained to the source attribute, while the second may be used to attach a transformation to the constrained value.
GLG_IDENTITY_XF
This transformation is used to transfer a value from one attribute object to another. It is used in the internal design of the GLG Control Widgets.
For a transformation attached to a scalar (D) value, the data2 values can be:
GLG_RANGE_CONVERSION_XF
Creates a Range Conversion transformation used to map an input range to an output range of scalars. For example, if the input range is (0,1) and the output range is (100,200), then an input value of 0.5 will produce a transformed value of 150.
GLG_RANGE_CHECK_XF
Creates a Range Check transformation that changes the output value when its input value goes out of range.
GLG_TIMER_XF
Creates a Timer transformation which periodically changes a value of an object’s attribute to implement blinking or other types of animation.
GLG_DIVIDE_XF
Creates a Divide transformation used to divide an attribute value by the Divisor attribute.
GLG_LINEAR3_XF
Creates a Linear transformation that calculates the output value as a linear combination of the transformation’s parameters.
GLG_BOOLEAN_XF
Creates a Boolean transformation that sets the output value to a boolean combination of the transformation’s parameters.
For a transformation attached to a string (S) value, the data2 values can have the following values:
GLG_S_FORMAT_XF
Creates a Format S transformation. The transformed value of the string attribute is equal to an input string value formatted with a format string.
GLG_D_FORMAT_XF
Creates a Format D transformation. The transformed value of the string attribute is equal to an input scalar value formatted with a format string.
GLG_TIME_FORMAT_XF
Creates a Time Format transformation to format POSIX time values and display them as strings.
GLG_STRING_CONCAT_XF
Creates a String Concatenation transformation that concatenates several strings.
Transformations for the geometrical or color attributes can have the following values:
GLG_TRANSLATE_X_XF
138
GLG Programming Reference Manual
GLG_TRANSLATE_Y_XF
GLG_TRANSLATE_Z_XF
GLG_TRANSLATE_XYZ_XF
Create a parametric translation transformation along the specified axis or axes.
GLG_TRANSLATE_XF
Creates a parametric translation transformation defined by a vector with a start and end point.
GLG_SCALE_X_XF
GLG_SCALE_Y_XF
GLG_SCALE_Z_XF
Create a parametric scale transformation; scaling affects only the specified coordinate.
GLG_SCALE_XYZ_XF
Creates a parametric scale transformation.
GLG_ROTATE_X_XF
GLG_ROTATE_Y_XF
GLG_ROTATE_Z_XF
Create a parametric rotate transformation around the axis defined by the transformation type.
GLG_SHEAR_X_XF
GLG_SHEAR_Y_XF
GLG_SHEAR_Z_XF
Create a parametric shear transformation; the shear amount increases along the axis defined by the transformation type.
GLG_MATRIX_XF
Creates a matrix transformation. A matrix transformation is more compact than the parametric, although its action cannot be easily controlled by accessing resources. To create a matrix transformation, first create the parametric transformation which defines the desired transformations and then use this transformation as the value of the data3 parameter. The data4 parameter is not used; use NULL for its value. After the matrix transformation has been created, the parametric transformation is not needed any more and may be dropped using the GlgDropObject function. To create a complex matrix transformation, a concatenation of several transformations may be used as the data3 parameter.
Once a matrix transformation is created, it can be changed with the
SetResourceFromObject function.
GLG_CONCATENATE_XF
Creates a concatenate transformation; it may be a concatenation of two matrix, parametric, or concatenate transformations. In this case data3 and data4 should contain the two transformation objects to be linked. Since a concatenate transformation references its components, they may be dereferenced using the GlgDropObject function after the concatenate transformation has been created.
The order of the transformation objects in the argument list corresponds to the order in which the transformations are applied when the resulting concatenate transformation is used to draw any object. The object is transformed with the first transformation, then with the second. Either object may itself be a concatenate transformation object, containing two or more other transformations.
139
A transformation may be used to create several concatenate transformations. In this case the corresponding transformations of the created concatenate transformations are constrained to have the same parameter values. Use the GlgCopyObject function to create copies of the transformation before passing them to the GlgCreateObject function to avoid constraints.
GLG_PATH_XF
Creates a parametric path transformation.When a path transformation is created, the data3 parameter can be used to pass an array of path points. This array may be extracted from any polygon with its Array resource. Use a copy of the array if you don’t want the path of the transformation to be constrained to the path polygon. If the data3 parameter is NULL, a default path transformation with two points is created.
Example: Concatenate Transformation
The following fragment of code shows an example of creating a concatenate transformation. It creates a rotate and translate transformations and then combines them in a concatenate transformation:
{
GlgObject rotate_xform, move_xform;
/* Create a rotate transformation. */ rotate_xform =
GlgCreateObject( GLG_XFORM, "Rotate", GLG_GEOM_XR,
GLG_ROTATE_Z_XF, NULL, NULL );
/* Change the center of rotation from a default value (0;0;0) to the value (500; 0; 0).
*/
GlgSetGResource( rotate_xform, "XformAttr1", 500., 0., 0. );
/* Set the rotation angle to 90 degrees. */
GlgSetDResource( rotate_xform, "XformAttr2", 90. );
/* Create a translate transformation. */ move_xform =
GlgCreateObject( GLG_XFORM, "Move", GLG_GEOM_XR,
GLG_TRANSLATE_X_XF, NULL, NULL );
/* Set the move amount to 500 in world coordinates. */
GlgSetDResource( move_xform, "XformAttr2", 500. );
/* Create a concatenate transformation. */ concat_xform =
GlgCreateObject( GLG_XFORM, "Concat", GLG_GEOM_XR,
GLG_CONCATENATE_XF, rotate_xform, move_xform );
}
/* Dereference transformations; we do not need them any more. */
GlgDropObject( rotate_xform );
GlgDropObject( move_xform );
140
GLG Programming Reference Manual
Example: Matrix Transformation
The following example shows how to create a matrix transformations using the concatenate transformation from the previous example. It creates two different matrix transformations from the same concatenate transformation using different transformation parameters:
{
GlgObject matrix_xform1, matrix_xform2;
/* Set transformation parameters for the first matrix. */
GlgSetDResource( concat, "Rotate/XformAttr2", 60. ); /* Angle */
GlgSetDResource( concat, "Move/XformAttr1", 500. ); /* Amount */
/* Create the first matrix transformation. */ matrix_xform1 =
GlgCreateObject( GLG_XFORM, "Matrix", GLG_GEOM_XR,
GLG_MATRIX_XF, concat_xform, NULL );
/* Set transformation parameters for the second matrix. */
GlgSetDResource( concat, "Rotate/XformAttr2", 30. ); /* Angle */
GlgSetDResource( concat, "Move/XformAttr1", 1500. ); /* Amount */
/* Create the second matrix transformation. */ matrix_xform2 =
GlgCreateObject( GLG_XFORM, "Matrix", GLG_GEOM_XR,
GLG_MATRIX_XF, concat_xform, NULL );
/* Dereference the concatenation transformation if not needed any more.
*/
GlgDropObject( concat_xform );
}
Refer to the GLG Objects chapter for a description of all the transformation attributes.
141
GlgAddObjectToTop
GlgAddObjectToBottom
GlgAddObjectAt
Add an object to a container at the specified position: top, bottom or position defined by the index
(Extended API only)
.
GlgBoolean GlgAddObjectToTop( container, object )
GlgObject container;
GlgObject object;
GlgBoolean GlgAddObjectToBottom( container, object )
GlgObject container;
GlgObject object;
GlgBoolean GlgAddObjectAt( container, object, index )
GlgObject container;
GlgObject object;
GlgLong index;
Parameters
container
Specifies the container object.
object
Specifies the object to be added to the container object.
index
Specifies the position in a container.
These functions add an object to a container object at the specified position and return GlgTrue if the object was successfully added or GlgFalse otherwise. The container object may have different types: it may be a group, a viewport or a polygon.
If the container object is a group or viewport, you may add any graphical object to it. Any attempt to add a non-graphical object will fail and an error message will be generated. The objects at the end (the bottom) of the list are drawn last and will appear in front of other objects.
If a polygon is passed as a container object parameter to this function, you may add points to the polygon. Any attempt to add an object different from a geometrical data object will fail, generating an error message.
Note: For viewports with integrated scrolling enabled by the viewport’s Pan attribute, child viewport objects added to the bottom of the viewport object list will appear in front of the integrated scrollbars until the viewport is reset. Resetting the viewport reorders the scrollbars to be the last in the object list. To achieve proper rendering without resetting the viewport, use GlgAddObjectAt to add the child viewport at a proper position before the integrated scrollbars. If a single X or Y scrollbar is used, the position index will be list_size - 1, where list_size is the number of objects in the viewport. If both
X and Y scrollbars are active, list_size - 3 position should be used.
142
GLG Programming Reference Manual
GlgAddObject
A generic function for adding an object to a container
(Extended API only)
.
GlgBoolean GlgAddObject( container, object, access_type, pos_modifier
)
GlgObject container;
GlgObject object;
GlgAccessType access_type;
GlgPositionModifier pos_modifier;
Parameters
container
Specifies the container object.
object
Specifies the object to be added to the container object.
access_type
Specifies the position at which the object is inserted. This parameter may have the following values:
GLG_TOP
Adds the object at the beginning of the object list.
GLG_BOTTOM
Adds the object at the end of the object list.
GLG_CURRENT
Adds the object at the position defined by the last call to GlgFindObject.
pos_modifier
Used only with the GLG_CURRENT access type and may have the following values:
GLG_BEFORE
Adds object before the object defined by the last call to GlgFindObject.
GLG_AFTER
Adds input object after the object defined by the last call to GlgFindObject.
If the access type is not GLG_CURRENT, use 0 as the value of this parameter.
This function adds an object to a container object and returns GlgTrue if the object was successfully added or GlgFalse otherwise. The container object may have different types: it may be a group, a viewport or a polygon.
If the container object is a group or viewport, you may add any graphical object to it. Any attempt to add a non-graphical object will fail and an error message will be generated. The objects at the end (the bottom) of the list are drawn last and will appear in front of other objects.
If a polygon is passed as a container object parameter to this function, you may add points to the polygon. Any attempt to add an object different from a geometrical data object will fail, generating an error message.
143
A container object keeps an internal current position pointer, which is set by a successful call to the
GlgFindObject function. For a call to GlgAddObject immediately following the GlgFindObject call, the pos_modifier parameter defines where to add the new object: right before or right after the object returned by GlgFindObject. The position modifier also defines how the insert position defined by the current position pointer is adjusted after the insertion. For GLG_BEFORE, the current position is left unchanged, for GLG_AFTER it is incremented by 1. This allows you to call
GlgAddObject repeatedly after an initial call to GlgFindObject.
For example, the following sequence of calls:
GlgFindObject( container, object_B, GLG_FIND_OBJECT, 0 );
GlgAddObject( container, object_1, GLG_CURRENT, GLG_BEFORE );
GlgAddObject( container, object_2, GLG_CURRENT, GLG_BEFORE );
GlgAddObject( container, object_3, GLG_CURRENT, GLG_BEFORE ); for a group with objects:
(object_A, object_B, object_C) results in a group with the following object order:
(object_A, object_1, object_2, object_3, object_B, object_C).
The sequence of calls:
GlgFindObject( container, object_B, GLG_FIND_OBJECT, 0 );
GlgAddObject( container, object_1, GLG_CURRENT, GLG_AFTER );
GlgAddObject( container, object_2, GLG_CURRENT, GLG_AFTER );
GlgAddObject( container, object_3, GLG_CURRENT, GLG_AFTER ); for the same group results in:
(object_A, object_B, object_1, object_2, object_3, object_C).
Keep in mind that any other calls to GlgFindObject, GlgAddObject, and GlgDeleteObject may affect the current position pointer.
GlgConstrainObject
Constrains an attribute or point of an object to an attribute or point of another.
GlgBoolean GlgConstrainObject( from_attribute, to_attribute )
GlgObject from_attribute;
GlgObject to_attribute;
Parameters
from_attribute
Specifies the attribute or point object to be constrained. To obtain the object ID of the
from_attribute, the GlgGetResourceObject function must be used with a default resource name rather than a user-defined resource name as the last part of resource path. For example, the
“object1/FillColor” must be used to get the object ID of the FillColor attribute of object1, and not “object1/color1”.
144
GLG Programming Reference Manual
For objects that have a fixed number of control points (arc, text, etc.), use the default attribute name (“PointN”) to access an object’s Nth control point. For objects which do not have a fixed number of points (e.g. polygons), use the GlgGetElement or
GlgIterate function to get its points and use them as the from_attribute.
to_attribute
Specifies the attribute or point to constrain to. This object may be queried by using either the default or a user-defined resource name.
This function constrains the attribute or point specified by the from_attribute parameter to the attribute or point specified by the to_attribute parameter. If two attributes are constrained, changing the value of either attribute changes the values of both. For more information about constraining, see the Constraints section in the Structure of a GLG Drawing chapter.
If the object whose attribute (from_attribute) is being constrained has already been drawn, an error message will be generated. You should either constrain object attributes before drawing the object or use the GlgSuspendObject function to suspend drawn objects before constraining their attributes.
You cannot constrain any objects beside attribute objects (a control point is an attribute object as well). The from_attribute and to_attribute attribute objects should be of the same data subtype. That is, you cannot constrain a color attribute object (G type) to the line width attribute object (D type) because they have different data types.
If any of the conditions above are not satisfied, the function fails and returns GlgFalse. If constraining is successful, the function returns GlgTrue.
Note that constraining an attribute object causes all the attributes of the attribute object to be identical to the attributes of the object to which it is constrained, including its name, transformation and value. If a transformation is added to an attribute object, it is automatically added to all the attribute objects that are constrained to this attribute object in order to maintain the constraints.
Similarly, if the object name is changed, it is automatically changed for all the objects that are constrained to the object. These changes are permanent and remain in effect even after the constraints are removed.
GlgContainsObject
Checks if object belongs to a container.
GlgBoolean GlgContainsObject( container, object )
GlgObject container;
GlgObject object;
Parameters
container
Specifies the container object.
object
Specifies the object to search for.
This function returns GlgTrue if the object belongs to the container and GlgFalse otherwise.
145
GlgCopyObject
Creates a copy of an object
(Extended API only)
.
GlgObject GlgCopyObject( object )
GlgObject object;
Parameters
object
Specifies the object to be copied.
This function creates and returns a copy of an object. The reference count of the created copy is set to 1. The created copy must be explicitly dereferenced after it has been used to avoid memory leaks.
Refer to the description of the GlgReferenceObject function for details on reference counting.
GlgCopyObject is equivalent to using GlgCloneObject with the FULL_CLONE cloning type. Refer
to the GlgCloneObject section below for more details on cloning types.
The GlgCopyObject function may be used to create multiple instances of an object after the object has been created and its attributes have been set to the desired values. Using GlgCopyObject can also save repeated calls to the resource-setting functions.
GlgCloneObject
Creates a specialized copy (clone) of an object
(Extended API only)
.
GlgObject GlgCloneObject( object, clone_type )
GlgObject object;
GlgCloneType clone_type;
Parameters
object
Specifies the object to be cloned.
clone_type
This is an enumerated value, specifying the type of clone desired. The possible value are
GLG_FULL_CLONE, GLG_STRONG_CLONE, GLG_WEAK_CLONE,
GLG_CONSTRAINED_CLONE and GLG_SHALLOW_CLONE.
This function creates a copy of an object, according to the rules of cloning. There are four different kinds of clones available for a given object. The difference between them depends on their treatment of the original object’s attributes according to the Global flag. There is also a special shallow clone type which can be applied only to the GLG group objects.
Full Clone
A full clone is a copy of the original object. No attributes of the copy are constrained to the attributes of the original.
Constrained Clone
A constrained clone is a copy of the original object all of whose attributes are constrained to
146
GLG Programming Reference Manual
the corresponding attributes of the original.
Exception: The Constrained Clone does not constrain the attributes that have their Global flag set to NONE, such as the constrained points of the parallelogram, frame and connector objects, the Buffer attribute of the Transfer transformation and some other special attributes.
Strong Clone
A strong clone is a copy of the original object. If any of the object’s attributes are global or semi-global (have their Global flags set to GLG_GLOBAL or GLG_SEMI_GLOBAL), they will be constrained to the corresponding attribute of the original.
Weak Clone
A weak clone interprets SEMI-GLOBAL to mean the same as LOCAL. It is similar to a strong clone, but only the global attributes are constrained.
Shallow Clone
A shallow clone is a special clone type that can be applied only to the group objects. When a shallow copy of a group is created, the copy will contain the same object IDs as the original group, as opposed to the other clone types which clone elements of the group, creating new objects with new object IDs. The shallow clone may be used by a program to create a list of objects in the original group, for example for safe traversing of the list while deleting the objects from the original group.
GlgCreateInversedMatrix
Inverts a matrix object.
GlgObject GlgCreateInversedMatrix( matrix )
GlgObject matrix;
Parameters
matrix
Specifies the matrix to be inverted.
Creates and returns the matrix inverse of the input one. The returned matrix must be dereferenced using GlgDropObject when not needed any more.
This function may be used to invert the drawing transformation obtained with the
GlgGetDrawingMatrix function. While the drawing transformation converts world to screen coordinates, the inverse of it may be used to convert the screen coordinates of objects and object bounding boxes back to world coordinates.
GlgCreatePointArray
Creates and returns an array containing all of an object’s control points:.
GlgObject GlgCreatePointArray( object, type )
GlgObject object;
GlgControlPointType type;
147
Parameters
object
Specifies the object.
type
Reserved for future use, must be 0.
GlgCreateResourceList
Returns a list of an object’s resources.
GlgObject GlgCreateResourceList( object, list_named_res, list_def_attr, list_aliases )
GlgObject object;
GlgBoolean list_named_res, list_def_attr, list_aliases;
Parameters
object
The input object.
list_named_res
A boolean value indicating whether the returned list should include the input object’s named resources.
list_def_attr
A boolean value indicating whether the returned list should include the input object’s default attributes. The resource objects referred to by the default resource names are not actually included in the list. Instead a dummy scalar data object (type D) is included whose name is the same as the default attribute.
list_aliases
Indicates whether the returned list should include aliases. The resource objects referred to by the aliases are not included in the list. Instead a dummy scalar data object (type D) is included whose name is the same as the alias.
This function creates and returns the array of an object’s resources. The list_named_res, list_def_attr and list_aliases parameters let you choose whether the array should include named resources, default attributes, aliases or any combination of the above.
The returned array has one entry for each resource. The entries are not sorted and are listed in the order of the occurrence inside their category. The named resources (if any) are listed first, then default resources and finally the aliases. The returned array must be dereferenced when finished.
148
GLG Programming Reference Manual
For named resources, the entries are the object IDs of the resource objects themselves. For default resources and aliases, the entries are dummy scalar data objects named after the default attributes or aliases. For both types of entries, the name of the entry object is the name of the resource listed.
The following code fragment shows how to print the list of resources:
GlgObject object, list, list_element;
GlgLong size, i; char * name; list = GlgCreateResourceList( object, True, True, False ); if( list )
{ size = GlgGetSize( list ); for( i=0; i < size; ++i )
{ list_element = GlgGetElement( list, i);
GlgGetSResource( list_element, “Name”, name ); printf( "Resource Name: %s\n", name );
}
GlgDropObject( list );
}
The GlgCreateResourceList function returns the resource list on only one level of the resource hierarchy. To see the resource lists of the returned resources, invoke the GlgCreateResourceList recursively using one of the following techniques:
• Use GlgCreateResourceList on the resources in the returned list. This will only work for the named resources since the default resources and aliases are represented by dummy objects.
• Get the name of a resource in the returned resource list and use the GlgGetResourceObject function to obtain its object ID, then call GlgCreateResourceList with that object ID. This method is slower but will work for both named resources, default attributes and aliases.
GlgCreateSelectionMessage
Searches all objects inside the given rectangle for an action with the specified selection trigger type attached to an object and returns a selection message for the first found action:
GlgObject GlgCreateSelectionMessage( top_vp, rectangle, selected_vp, selection_type, button )
GlgObject top_vp;
GlgRectangle * rectangle;
GlgObject selected_vp;
GlgSelectionEventType selection_type;
GlgLong button;
Parameters
top_vp
The top viewport of the selection query (must be an ancestor of selected_vp).
rectangle
The bounding rectangle in screen coordinates of the selected_vp viewport. Any graphical
149 shape whose rendering intersects this rectangle is included in the search.
selected_vp
The viewport relatively to which the bounding rectangle is defined. When used with the mouse events, this is the viewport in which the mouse event occurred.
selection_type
This is an enumerated value specifying the selection type. The GLG_MOVE_SELECTION value selects custom mouse move events attached to an object, GLG_CLICK_SELECTION selects mouse click events and GLG_TOOLTIP_SELECTION selects the tooltip events.
button
The mouse button for the GLG_CLICK_SELECTION selection type.
This function may be used in a trace callback to determine whether a mouse event was meant to trigger an action attached to a graphical object in a drawing. The function returns a message equivalent to the message received in the input callback. If no matching actions were found, NULL is returned.
GlgCreateSelectionNames
Returns a list of names of objects intersecting a given rectangle.
GlgObject GlgCreateSelectionNames( top_vp, rectangle, selected_vp )
GlgObject top_vp;
GlgRectangle * rectangle;
GlgObject selected_vp;
Parameters
top_vp
The top viewport of the selection query (must be an ancestor of selected_vp).
rectangle
The bounding rectangle in screen coordinates of the selected_vp viewport. Any graphical shape whose rendering intersects this rectangle is included in the selection list.
selected_vp
The viewport relatively to which the bounding rectangle is defined. When used with the mouse events, this is the viewport in which the mouse event occurred.
This function may be used to determine whether a mouse event was meant to select graphical objects in a drawing. The function returns an array of strings containing the names of the objects that overlap with the given rectangle completely or partially. The name string is a complete resource path name (relative to the top_vp) which can be used get the object ID of the object:
150
GLG Programming Reference Manual
GlgObject selected_object = GlgGetResourceObject( top_vp, path_name );
This function may be called from a trace callback function to implement the custom handling of mouse events. For example, it may be used to implement the “hot spot” functionality, highlighting objects when the cursor moves over them. The function returns NULL if no objects intersect the input rectangle, or if none of the intersected objects have names. The GlgCreateSelection function described below may be used to handle unnamed objects.
The array returned by this function must be dereferenced with the GlgDropObject function when the program is finished using it.
GlgCreateSelection
Returns a list of the objects intersecting a given rectangle.
GlgObject GlgCreateSelection( top_vp, rectangle, selected_vp )
GlgObject top_vp;
GlgRectangle * rectangle;
GlgObject selected_vp;
Parameters
top_vp
The top viewport of the selection query (must be an ancestor of selected_vp).
rectangle
The bounding rectangle in screen coordinates of the selected_vp viewport. Any graphical shape whose rendering intersects this rectangle is included in the selection list.
selected_vp
The viewport relatively to which the bounding rectangle is defined. When used with the mouse events, this is the viewport in which the mouse event occurred.
This function is similar to the GlgCreateSelectionNames function, but it returns an array of objects instead of an array of object names. The objects in the array are listed in the reversed order compared to their drawing order, so that the objects that are at the bottom of the drawing list and are drawn on top of other objects will be listed the first in the array.
While GlgCreateSelectionNames reports both the selected objects on the bottom of the hierarchy and all their parents, this function reports only objects at the bottom and doesn’t include their parents. For example, if a polygon in a group is selected, only the polygon is reported and not the group. To get information about the parents of selected objects, use the GlgGetParent function.
The function returns NULL if no objects intersect the input rectangle. The returned array must be dereferenced with the GlgDropObject function when the program is finished using it.
151
GlgDeleteTopObject
GlgDeleteBottomObject
GlgDeleteObjectAt
Delete an object from a specified position in a container: top, bottom or a position defined by an index
(Extended API only)
.
GlgBoolean GlgDeleteTopObject( container )
GlgObject container;
GlgBoolean GlgDeleteBottomObject( container )
GlgObject container;
GlgBoolean GlgDeleteObjectAt( container, index )
GlgObject container;
Glglong index;
Parameters
container
Specifies a container object.
index
Specifies an index of the object to be deleted from the container.
These functions delete an object from the container object and returns GlgTrue if the object was successfully deleted or GlgFalse otherwise.
GlgDeleteObject
A generic function for deleting an object from a container
(Extended API only)
.
GlgBoolean GlgDeleteObject( container, reserved, access_type, pos_modifier )
GlgObject container; void * reserved;
GlgAccessType access_type;
GlgPositionModifier pos_modifier;
Parameters
container
Specifies a container object.
reserved
A reserved parameter for the future extensions; must be NULL.
access_type
Specifies the position of the object to be deleted and may have the following values:
GLG_TOP
Deletes the object at the beginning of the object list.
152
GLG Programming Reference Manual
GLG_BOTTOM
Deletes the object at the bottom of the object list.
GLG_CURRENT
Deletes the object at the position defined by the last call to GlgFindObject.
pos_modifier
Used only with the GLG_CURRENT access type. It defines how to adjust the current position after the delete operation. This parameter allows using the function repeatedly to delete several objects before or after the object defined by the previous call to the GlgFindObject function. It may have the following values:
GLG_BEFORE
Moves the current position pointer to the previous object in the list.
GLG_AFTER
Moves the current position pointer to the next object in the list.
If the access type is not GLG_CURRENT, use 0 as the value of the parameter.
This function deletes an object from the container object and returns GlgTrue if the object was successfully deleted or GlgFalse otherwise.
The object to be deleted is defined by the access_type parameter and may be the first (GLG_TOP) or the last object (GLG_BOTTOM) in the container’s object list. It may also be an object defined by the previous successful call to GlgFindObject (GLG_CURRENT).
For example, the following sequence of calls:
GlgFindObject( container, object_D, GLG_FIND_OBJECT, 0 );
GlgDeleteObject( container, NULL, GLG_CURRENT, GLG_AFTER );
GlgDeleteObject( container, NULL, GLG_CURRENT, GLG_AFTER );
GlgDeleteObject( container, NULL, GLG_CURRENT, GLG_AFTER ); for a group with objects:
(object_A, object_B, object_C, object_D, object_E, object_F, object_G
) results in deleting objects object_D, object_E, and object_F.
The sequence of calls:
GlgFindObject( container, object_B, GLG_FIND_OBJECT, 0 );
GlgDeleteObject( container, NULL, GLG_CURRENT, GLG_BEFORE );
GlgDeleteObject( container, NULL, GLG_CURRENT, GLG_BEFORE );
GlgDeleteObject( container, NULL, GLG_CURRENT, GLG_BEFORE ); for the same group deletes objects object_D, object_C, and object_B, in that order.
Keep in mind that any other calls to GlgFindObject, GlgAddObject, and GlgDeleteObject may affect the current position pointer. The current position pointer must be used immediately after the
GlgFindObject call.
153
GlgDeleteThisObject
Finds and deletes the object from a container
(Extended API only)
.
GlgBoolean GlgDeleteThisObject( container, object )
GlgObject container;
GlgObject object;
Parameters
container
Specifies a container object.
object
Specifies an object to be deleted from the container.
This function finds and deletes an object from the container object. It returns GlgTrue if the object was successfully deleted or GlgFalse if object was not found in the container.
GlgDropObject
Decrements an object’s reference count. void GlgDropObject( object )
GlgObject object;
Parameters
object
Specifies the object to be dereferenced.
This function decreases the object’s reference count by 1. If the reference count goes to 0, the object is destroyed. Destroying an object dereferences all its subsidiary objects and may destroy them as well if their reference counts become zero.
The GlgDropObject function should be used to dereference the object after creating, copying, loading or referencing the object, as was shown in the first coding example for the
GlgReferenceObject function.
GlgFindObject
A generic find function: finds an object in a container. Use GlgContainsObject,
GlgGetNamedObject, GlgGetElement or GlgGetIndex convenience functions for specialized tasks.
GlgObject GlgFindObject( container, object, search_type, reserved )
GlgObject container; void * object;
GlgSearchType search_type; void * reserved;
154
GLG Programming Reference Manual
Parameters
container
Specifies the container object.
object
Specifies the data to search for. Depending on the search type, it may be an object ID, object name, or object’s index in the container’s object list.
search_type
Specifies the search type and may have the following values:
GLG_FIND_OBJECT
Finds an object by the object ID (pass the object ID as the value of the object parameter).
GLG_FIND_BY_NAME
Find an object by its name (pass the name as the value of the object parameter).
GLG_FIND_BY_INDEX
Finds an object by its position in the container object list (pass the zero-based position index as the value of the object parameter).
Reserved
A reserved parameter for future extensions; must be NULL.
This function searches for an object based on the specified name, index, or object ID. If the object is found, the function modifies the container’s internal position pointer to point to the found object and returns the object; otherwise it leaves the position pointer intact and returns NULL. The container’s position pointer may be affected by other GlgFindObject, GlgAddObject and
GlgDeleteObject calls. Any function using the position pointer (GLG_CURRENT access type) must be called immediately after the GlgFindObject call before any other call which may affect the pointer.
GlgFitObject
Fits an object to a specified rectangular area:
GlgBoolean GlgFitObject( object, coord_type, anchoring, x, y, z )
GlgObject object;
GlgCoordType coord_type;
GlgBoolean keep_ratio;
GlgCube * box;
Parameters
object
Specifies the object to fit.
coord_type
Specifies the coordinate system to interpret the fit area in. If GLG_SCREEN_COORD is used, the area is defined in screen pixels. If GLG_OBJECT_COORD is used, the area is defined in the GLG world coordinates.
155
box
The area to fit the object to. If the Z extent of the box is 0, 2D fitting is performed and the object is not scaled in the Z dimension. If Z extent is not 0, 3D fitting is performed.
keep_ratio
If the parameter is set to GlgTrue, the function preserves the object’s X/Y ratio by using the smallest of the required X and Y scale factors for both directions. If keep_ratio is set to
GlgFalse, different scale factors may be used for X and Y scaling to fit the object to the box more precisely.
This function transforms the object to fit it to the area, calculating new control point values. The object’s hierarchy must be setup to use this function.
The following types defined in the GlgApi.h file are used: typedef struct _GlgCube
{
GlgPoint p1; /* Lower left */
GlgPoint p2; /* Upper right */
} GlgCube;
GlgGetAlarmObject
Returns a tag object with a specified alarm label, or a list of alarms matching the specified alarm label pattern.
GlgObject GlgGetAlarmObject( object, search_string, single_alarm, reserved )
GlgObject object; char * search_string;
GlgBoolean single_alarm;
GlgLong reserved;
Parameters
object
Specifies the object whose alarms to query.
search_string
Specifies a string or a pattern for the search (may include ? and * wildcards).
single_alarm
Defines a single alarm (GlgTrue) or multiple alarm (GlgFalse) mode.
reserved
Reserved for future use, must be 0.
In a single alarm mode, the function returns the alarm that has an alarm label matching the search criteria.
In the multiple alarm mode, a list containing all alarms with matching alarm labels will be returned.
The returned list must be dereferenced using GlgDropObject when it is no longer needed.
156
GLG Programming Reference Manual
GlgGetBoxPtr
Returns an object’s bounding box.
GlgCube * GlgGetBoxPtr( object )
GlgObject object;
Parameters
object
Specifies the object whose bounds are to be returned.
Returns a pointer to the object’s 3-D bounding box. The box boundaries are in absolute screen coordinates (pixels) and are valid only after the object has been drawn. (That is, after the hierarchy has been set up.) The returned pointer points to internal structures which are valid only while the object exists and should not be modified. The object box may be converted to world coordinates by using the GlgGetDrawingMatrix, GlgCreateInversedMatrix and GlgTransformPoint functions.
The following types defined in the GlgApi.h file are used: typedef struct _GlgPoint
{ double x, y, z;
} GlgPoint; typedef struct _GlgCube
{
GlgPoint p1; /* Lower left */
GlgPoint p2; /* Upper right */
} GlgCube;
GlgGetDrawingMatrix
Returns the transformation matrix attached to the input object.
GlgObject GlgGetDrawingMatrix( object )
GlgObject object;
Parameters
object
Specifies the input object.
Returns the transformation matrix for the set of all transformations attached to an input object.
Transformation matrices are only used for geometric transformations, so this function may be called only for graphical objects, like polygons and polylines. This function must be called after the object has been drawn. (That is, after its hierarchy has been set up.) The function returns the internal matrix object which is valid only immediately after the function call. The matrix should not be modified or destroyed. To prevent the matrix from being destroyed, you may reference it with
GlgReferenceObject (and dereference later), or, even better, create a copy.
157
Querying the drawing matrix of a viewport returns the drawing matrix used to position the viewport’s control points, and not the matrix used to render the objects inside it. To get the drawing matrix the viewport uses to draw objects inside it, query the drawing list of the viewport (the Array resource of the viewport) and use it as a parameter of the GlgGetDrawingMatrix function.
GlgGetElement
Returns the object at the specified position in a container.
GlgObject GlgGetElement( container, index )
GlgObject container;
GlgLong index;
Parameters
container
Specifies the container object.
index
Specifies the object position inside the container.
This function returns NULL if the specified index is invalid. While the function provides the
Extended API functionality, it is also available in the Standard API when used with the group object.
GlgGetIndex
Returns the index of the first occurrence of an object in a container.
GlgLong GlgGetIndex( container, object)
GlgObject container;
GlgObject object;
Parameters
container
Specifies the container object.
object
Specifies the object to search for.
This function returns -1 if the object wasn’t found in the container.
GlgGetMatrixData
Queries matrix coefficients: void GlgGetMatrixData( matrix, matrix_data )
GlgObject matrix;
GlgMatrixData * matrix_data;
158
GLG Programming Reference Manual
Parameters
matrix
Specifies the matrix object to query.
matrix_data
The structure to hold the matrix’s coefficients.
The GlgMatrixData data type is defined in the GlgApi.h file: typedef struct _GlgMatrixData
{ long type; double matrix[4][4];
} GlgMatrixData;
GlgGetNamedObject
Returns an object ID of the object in a container with the specified name.
GlgObject GlgGetNamedObject( container, name )
GlgObject container; char * name;
Parameters
container
Specifies the container object.
name
Specifies the object’s name.
This function returns named objects of a container with no regards to the resource hierarchy, and is different from the GlgGetResourceObject function (which returns named resources on the current level of the resource hierarchy but not necessarily the elements of the container).
This function returns NULL if the object with the specified name wasn’t found in the container.
GlgGetParent
Returns an object’s parent object, if one exists.
GlgObject GlgGetParent( object, num_parents )
GlgObject object;
GlgLong * num_parents;
Parameters
object
Specifies the object whose parents are to be returned.
159
num_parents
Used to return the number of parents attached to the input objects. If this is NULL on input, an error message will be generated if the object has more than one parent.
This function returns an ID for an object’s parent object. For constrained objects, there may be more than one parent object. In this case, the function returns an array of parent object IDs. (This may be used to check whether an object is constrained.)
The returned object ID is a pointer to an internal data structures and it should not be dereferenced.
To keep it from being destroyed when the object is destroyed, you can reference it with
GlgReferenceObject (and dereference later). If the return value is an array of parents and you want to keep it around, the safer method to keep it is to create a copy. This prevents the array’s elements from being modified by the GLG internals.
This function must be called after the hierarchy is created.
GlgGetResourceObject
Returns the ID of a resource object.
GlgObject GlgGetResourceObject( object, resource_name )
GlgObject object; char * resource_name;
Parameters
object
Specifies the object whose resources are queried.
resource_name
A character string that specifies the resource name.
This function finds and returns a named resource of an object or an object ID of the object’s attribute. The resource_name parameter should identify an object, such as an attribute object or a named object of a group. If the resource is not found, the function returns NULL. No error message is generated in this case, so this function can be used to query an object’s existence. The object ID returned by the function is not referenced and is valid only immediately after the function call.
Reference the object if the resource ID has to be stored for later use to make sure the object is not destroyed.
GlgGetSize
Queries the size of a container object.
GlgLong GlgGetSize( container )
GlgObject container;
Parameters
container
Specifies the container object.
160
GLG Programming Reference Manual
This function returns the size of a container object. For a viewport or group object, the size is the number of objects in the viewport or group. For a polygon, the size is the number of vertices. While the function provides the Extended API functionality, it is also available in the Standard API when used with the group object.
GlgGetStringIndex
Returns the index of the first occurrence of the string in a string container.
GlgLong GlgGetStringIndex( container, string)
GlgObject container; char * string;
Parameters
container
Specifies the container object.
string
Specifies the string to search for.
This function returns -1 if the string wasn’t found in the container.
GlgGetTagObject
Returns a tag object with a specified tag name or tag source, or a list of tags matching the specified tag name or tag source pattern.
GlgObject GlgGetTagObject( object, search_string, by_name, unique_tags, single_tag, tag_type_mask)
GlgObject object; char * search_string;
GlgBoolean by_name;
GlgBoolean unique_tags;
GlgBoolean single_tag;
GlgTagType tag_type_mask;
Parameters
object
Specifies the object whose tags to query.
search_string
Specifies a string or a pattern for the search (may include ? and * wildcards).
by_name
If set to GlgTrue, the search is performed by matching the tag names, otherwise the search is done by matching the tag sources. Tag sources can be used only for data tags.
unique_tags
If set to GlgTrue, only one tag instance will be listed when several tags with the same tag name or tag source exist in the drawing, otherwise all tags with the same tag name or tag source will
161 be included in the returned list. The parameter is ignored in the single tag mode.
single_tag
Defines the single tag (GlgTrue) or multiple tag (GlgFalse) mode.
tag_type_mask
Defines the type of tags to query: data tags or export tags. Tag type constants may be ORed to query tags of several types.
In a single tag mode, the function returns the first attribute that has a tag matching the search criteria.
In the multiple tag mode, a list containing all attributes with matching tags will be returned. The
unique_tags controls if only one tag is included in case there are multiple tags with the same tag name or tag source. It is ignored in the single tag mode. The returned list must be dereferenced using
GlgDropObject when it is no longer needed.
GlgIterate
Traverses the container object.
GlgObject GlgIterate( container )
GlgObject container;
Parameters
container
Specifies the container object.
Returns the next element of container. The GlgSetStart function must be used to initialize the container for iterating before Iterate is invoked the first time. The add, delete and search operations affect the iteration state and should not be performed on the container while it is being iterated.
To perform a safe iteration that is not affected by the add and delete operations, a copy of the container can be created using the GlgCloneObject function with the SHALOW_CLONE clone type. The shallow copy will return a container with a list of objects IDs, and it can be safely iterated while objects are added or deleted from the original container.
Alternatively, GlgGetElement can be used to traverse elements of the container using an element index, which is not affected by the search operations on the container.
The following coding example shows how to iterate all objects in a container using GlgIterate: int i, size;
GlgObject object; size = GlgGetSize( container ); if( size != 0 )
{
GlgSetStart( polygon ); /* Initialize traversing. */ for( i=0; i<size; ++i )
{ object = GlgIterate( container );
... /* Code to process the object */
162
GLG Programming Reference Manual
}
}
GlgLayoutObjects
Performs operations ranging from setting the object’s width and height to align and layout of groups of objects.
GlgBoolean GlgLayoutObjects( object, sel_elem, type, distance, use_box, process_subobjects )
GlgObject object;
GlgObject sel_elem;
GlgLayoutType type; double distance;
GlgBoolean use_box;
GlgBoolean process_subobjects;
Parameters
object
Specifies the object or group of objects to perform the requested operations upon.
sel_elem
Specifies the anchor object for alignment operations. If null value is specified, the first encountered object in the specified alignment direction is used.
type
Specifies the type of the layout action to perform. May have the following values:
ALIGN_LEFT
Align the left edge of elements within the group with the left edge of the anchor element.
ALIGN_RIGHT
Align the right edge of elements within the group with the right edge of the anchor element.
ALIGN_HCENTER
Align the center of elements within the group with the center of the anchor element horizontally.
ALIGN_TOP
Align the top edge of elements within the group with the top edge of the anchor element.
ALIGN_BOTTOM
Align the bottom edge of elements within the group with the bottom edge of the anchor element.
ALIGN_VCENTER
Align the center of elements within the group with the center of the anchor element vertically.
163
SET_EQUAL_VSIZE
Set the height of elements within the group to the height of the anchor.
SET_EQUAL_HSIZE
Set the width of elements within the group to the width of the anchor.
SET_EQUAL_SIZE
Set the width and height of elements within the group to the width and height of the anchor.
SET_EQUAL_VDISTANCE
Equally distributes the group's elements in vertical direction as measured by the distance between their centers.
SET_EQUAL_HDISTANCE
Equally distributes the group's elements in horizontal direction as measured by the distance between their centers.
SET_EQUAL_VSPACE
Equally distributes space gaps between group's elements in vertical direction.
SET_EQUAL_HSPACE
Equally distributes space gaps between group's elements in horizontal direction.
SET_VSIZE
If anchor is null, sets the object's height; if anchor in not null, sets the height of all elements within the group. The height is defined by the value of the distance parameter.
SET_HSIZE
If anchor is null, sets the object's width; if anchor in not null, sets the width of all elements within the group. The width is defined by the value of the distance parameter.
SET_VDISTANCE
Set vertical distance between centers of the group's elements to a value defined by the distance parameter.
SET_HDISTANCE
Set horizontal distance between centers of the group's elements to a value defined by the distance parameter.
SET_VSPACE
Sets space gaps between group's elements in vertical direction to a value defined by the distance parameter.
SET_HSPACE
Sets space gaps between group's elements in horizontal direction to a value defined by the distance parameter.
distance
The distance in screen coordinates for positioning objects, depending on the layout action.
164
GLG Programming Reference Manual
use_box
If set to GlgTrue, the object's bounding box is used to align objects, otherwise the control points will be used to determine the object’s extent.
process_subobjects
Controls how to apply the layout action if the object is a group. If set to GlgTrue, the action is applied to all objects contained in the group, otherwise the action (such as SET_HSIZE) is applied to the group itself.
The function returns GlgFalse if errors were encountered during the requested layout action.
GlgLoadObject
Loads an object from a file in GLG format.
GlgObject GlgLoadObject( filename ) char * filename;
Parameters
filename
Specifies the name of the file to load the object from.
This function loads an object from the specified file and returns the object ID. If the file is not accessible or is not in the GLG save format, an error message is generated and NULL is returned.
If the object is loaded successfully, the reference count of the returned object is set to 1. The loaded object has to be explicitly dereferenced after it has been used to avoid memory leaks. Refer to the description of the GlgReferenceObject function for details on the reference counting.
GlgLoadObjectFromImage
Loads an object from a memory image created by the GLG Code Generation Utility.
GlgObject GlgLoadObjectFromImage( image_address, image_size ) void * image_address;
GlgLong image_size;
Parameters
image_address
Specifies the address of the drawing image generated by the GLG Code Generation Utility.
image_size
Specifies the image size.
This function loads an object from the specified drawing’s memory image and returns the object ID.
If the memory is corrupted, an error message is generated and NULL is returned. If the object is loaded successfully, the reference count of the returned object is set to 1. The loaded object must be explicitly dereferenced after it has been used to avoid memory leaks. Refer to the description of the
GlgReferenceObject function for details on the reference counting. For information about the Code
Generation Utility, see the GLG Programming Tools and Utilities chapter.
165
NOTE: this function does not work with compressed drawing files. Save drawings with the drawing compression option disabled to use them with GlgLoadObjectFromImage.
GlgMoveObject
Moves an object by a move vector:
GlgBoolean GlgMoveObject( object, coord_type, start_point, end_point )
GlgObject object;
GlgCoordType coord_type;
GlgPoint * start_point;
GlgPoint * end_point;
Parameters
object
Specifies the object to be moved.
coord_type
Specifies the coordinate system for interpreting the move vector. If GLG_SCREEN_COORD is used, the move vector is in screen pixels. For example, this may be used to move the object by the number of screen pixels as defined by the mouse move. If GLG_OBJECT_COORD is used, the move vector is in the GLG world coordinates.
start_point
The start point of the move vector. If the parameter is NULL, (0,0,0) is used as the start point.
end_point
The end point of the move vector.
This function moves an object’s control points by the distance defined by the move vector, calculating new control point values. The object’s hierarchy must be setup to use this function.
The GlgPoint data type is defined in the GlgApi.h file: typedef struct _GlgPoint
{ double x, y, z;
} GlgPoint;
GlgMoveObjectBy
Moves an object by a move distance:
GlgBoolean GlgMoveObjectBy( object, coord_type, x, y, z )
GlgObject object;
GlgCoordType coord_type; double x, y, z;
Parameters
object
Specifies the object to move.
166
GLG Programming Reference Manual
coord_type
Specifies the coordinate system for interpreting the move distance. If
GLG_SCREEN_COORD is used, the move distance is in screen pixels. For example, this may be used to move the object by the number of screen pixels as defined by the mouse move. If
GLG_OBJECT_COORD is used, the move distance is specified in the GLG world coordinates.
x, y, z
The X, Y and Z move distances.
This function moves an object’s control points by the X, Y and Z distances, calculating new control point values. The object’s hierarchy must be setup to use this function.
GlgPositionObject
Positions an object at the specified location:
GlgBoolean GlgPositionObject( object, coord_type, anchoring, x, y, z )
GlgObject object;
GlgCoordType coord_type;
GlgLong anchoring; double x, y, z;
Parameters
object
Specifies the object to position.
coord_type
Specifies the coordinate system for interpreting the position. If GLG_SCREEN_COORD is used, the position is defined in screen pixels. If GLG_OBJECT_COORD is used, the position is defined in the GLG world coordinates.
anchoring
Specifies what part of the object’s bounding box will be anchored at the specified position. It’s formed as a bitwise “or” of the horizontal anchoring constant (GLG_LEFT, GLG_HCENTER or GLG_RIGHT) with the vertical anchoring constants (GLG_TOP, GLG_VCENTER or
GLG_BOTTOM). For example, using ( GLG_TOP | GLG_LEFT ) causes the upper left corner of the object’s bounding box to be positioned at the specified location.
x, y, z
The X, Y and Z coordinates of the desired object position.
This function positions the object, calculating new control point values. The object’s hierarchy must be setup to use this function.
GlgReferenceObject
Increments an object’s reference count.
GlgObject GlgReferenceObject( object )
GlgObject object;
167
Parameters
object
Specifies the object to be referenced.
This function increases the reference count of an object by 1 and returns the object’s ID. The
GlgDropObject function may be used to dereference the object when it is not needed any more.
When an object is created, its reference count is set to 1. Any object you create programmatically has to be explicitly dereferenced using the GlgDropObject function after the object has been used, otherwise memory leaks will occur. It is a good practice to dereference objects immediately after they have been added to a group or used as a part of other objects; this guarantees that you will not forget to dereference the object later. The following example illustrates this:
{
GlgObject polygon;
/* Create a polygon object with default values of the attributes.
*/ polygon = GlgCreateObject( GLG_POLYGON, NULL, NULL, NULL, NULL,
NULL );
/* Add the polygon to a group. */
GlgAddObject( group, polygon, GLG_BOTTOM, 0 );
/* Adding polygon to a group references it; we may dereference it now to let the group manage it.
*/
GlgDropObject( polygon );
}
Dereferencing an object does not necessarily destroy the object. The object may still be referenced by groups it was added to or by other objects that use it. An object may also be referenced programmatically to make sure it is kept around and is not destroyed automatically by the Toolkit.
The object is actually destroyed only when the last reference to it is dropped.
You can use the GlgReferenceObject function to keep objects around, and to make sure that an object ID is still valid. Simply use the function to increment the reference count of the object, and then decrement the count with the GlgDropObject function when the object is no longer needed.
The GlgReferenceObject function may also be used to keep an object while it is being deleted from one group and added to another group. Deleting the object from a group decrements its reference count and may destroy the object if it is not referenced by anything else. Referencing the object using GlgReferenceObject prevents the object from being destroyed. The GlgDropObject function is used after the operation is completed to return the object’s reference count to its initial state.
168
GLG Programming Reference Manual
The following code fragment illustrates this:
GlgReferenceObject( object ); /* Keeping the object around. */
/* Deleting the object from group1 automatically dereferences the object and may destroy it if it’s not referenced.
*/ if( GlgFindObject( group1, object, GLG_FIND_OBJECT, 0 ) )
GlgDeleteObject( group1, NULL, GLG_CURRENT, 0 );
/* Adding the object to the group2 automatically references it, so that it is safe to dereference it now.
*/
GlgAddObject( group2, object, GLG_BOTTOM, 0 );
GlgDropObject( object ); /* We may drop it now. */
In general, it is good practice to increment the reference count of an object before performing any operation on it and then dereference the object when the operation is complete. This provides a guarantee that the object will not be inadvertently destroyed during the operation.
GlgReleaseObject
Releases a suspended object after editing.
void GlgReleaseObject( object, suspend_info )
GlgObject object;
GlgObject suspend_info;
Parameters
object
Specifies the object to be released after it was suspended for editing.
suspend_info
Suspension information returned by the previous call to the GlgSuspendObject function.
This function releases previously suspended object and is intended to be used only with the
GlgSuspendObject function.
GlgReorderElement
Changes the object’s position inside a container.
void GlgReorderElement( container, old_index, new_index )
GlgObject object;
GlgLong old_index;
GlgLong new_index;
Parameters
container
Specifies the container object.
169
old_index
Specifies the index of an object to be reordered.
new_index
Specifies a new position for the object.
This function moves the object at the old_index to the new_index position. It returns GlgFalse if indexes are out of range.
GlgRotateObject
Rotates an object:
GlgBoolean GlgRotateObject( object, coord_type, center, x, y, z )
GlgObject object;
GlgCoordType coord_type;
GlgPoint * center; double x, y, z;
Parameters
object
Specifies the object to rotate.
coord_type
Specifies the coordinate system for interpreting the rotation center. If
GLG_SCREEN_COORD is used, the center is defined in screen pixels. If
GLG_OBJECT_COORD is used, the center is defined in the GLG world coordinates.
center
The center of rotation. If the parameter is NULL, the object is rotated relative to the center of its bounding box.
x, y, z
The X, Y and Z rotation angles.
This function rotates an object’s control points by the specified rotation angles and relative to the specified center, calculating new control point values. If more than one rotation angle is specified,
X rotation is applied the first, then Y and Z. The object’s hierarchy must be setup to use this function.
The GlgPoint data type is defined in the GlgApi.h file: typedef struct _GlgPoint
{ double x, y, z;
} GlgPoint;
170
GLG Programming Reference Manual
GlgSaveObject
Saves an object into a file.
GlgBoolean GlgSaveObject( object, filename )
GlgObject object; char * filename;
Parameters
object
Specifies the object to be saved; it may be any GLG object.
filename
Specifies the name of the file to save the object into.
This function saves the specified object and all its subsidiary objects into a file. If the file is not accessible for writing, the function returns GlgFalse, otherwise it returns GlgTrue. A GLG object of any type may be saved in this fashion and later loaded using the GlgLoadObject function. You
can use the GlgSaveFormat configuration resource described the Appendices chapter to modify the
save type.
GlgScaleObject
Scales an object:
GlgBoolean GlgScaleObject( object, coord_type, center, x, y, z )
GlgObject object;
GlgCoordType coord_type;
GlgPoint * center; double x, y, z;
Parameters
object
Specifies the object to scale.
coord_type
Specifies the coordinate system for interpreting the scale center. If GLG_SCREEN_COORD is used, the center is defined in screen pixels. If GLG_OBJECT_COORD is used, the center is defined in the GLG world coordinates.
center
The center of scaling. If the parameter is NULL, the object is scaled relative to the center of its bounding box.
x, y, z
The X, Y and Z scaling factors. Use (1,1,1) to scale the object uniformly in all dimensions.
This function scales an object’s control points by the specified scale factors and relative to the specified center, calculating new control point values. The object’s hierarchy must be setup to use this function.
171
The GlgPoint data type is defined in the GlgApi.h file: typedef struct _GlgPoint
{ double x, y, z;
} GlgPoint;
GlgScreenToWorld
Converts a point’s coordinates from the screen to the GLG world coordinate system.
GlgBoolean GlgScreenToWorld( object, inside_vp, in_point, out_point )
GlgObject object;
GlgBoolen inside_vp;
GlgPoint * in_point;
GlgPoint * out_point;
Parameters
object
Specifies the object whose world coordinate system to convert to. The world coordinate system of an object includes the effect of all drawing transformations attached to the object and all its parents.
inside_vp
For a viewport object, specifies which world coordinate system to use: the world coordinate system used to draw the viewport inside its parent viewport (inside_vp=GlgFalse), or the world coordinate system used to draw object inside the viewport (inside_vp=GlgTrue). The value of this parameter is ignored for other objects.
in_point
The point to be converted.
out_point
The point structure to hold the converted value.
The object’s hierarchy must be setup to use this function.
The GlgPoint data type is defined in the GlgApi.h file: typedef struct _GlgPoint
{ double x, y, z;
} GlgPoint;
When converting the cursor position to world coordinates, add GLG_COORD_MAPPING_ADJ to the cursor’s x and y screen coordinates for precise mapping.
GlgSetElement
Replaces the object at the specified position in a container
(Extended API only)
.
172
GLG Programming Reference Manual
GlgBoolean GlgSetElement( container, index, new_object )
GlgObject container;
GlgLong index;
GlgObject new_object;
Parameters
container
Specifies the container object.
index
Specifies the position inside the container at which the object will be replaced.
new_object
Specifies the new object.
This function returns GlgFalse if the specified index is invalid.
GlgSetMatrixData
Sets matrix coefficients: void GlgSetMatrixData( matrix, matrix_data )
GlgObject matrix;
GlgMatrixData * matrix_data;
Parameters
matrix
Specifies the matrix object.
matrix_data
The new matrix’s coefficients.
The GlgMatrixData data type is defined in the GlgApi.h file: typedef struct _GlgMatrixData
{ long type; double matrix[4][4];
} GlgMatrixData;
GlgSetResourceObject
Replaces a resource object
(Extended API only)
.
GlgBoolean GlgSetResourceObject( object, resource_name, o_value )
GlgObject object; char * filename;
GlgObject o_value;
173
Parameters
object
Specifies the object whose resource is being set or replaced.
resource_name
Specifies a default attribute name of a resource that is being set or replaced.
o_value
Specifies a new resource object.
This function sets or replaces the resource object specified by the resource name. It may be used to attach custom properties (CustomData resource), history (History resource) and aliases (Aliases resource) to the object, or to replace them with new values. A container object may be used as the
o_value to attach a list of properties or other objects. If objects have been drawn, they must be suspended with GlgSuspendObject before using GlgSetResourceObject and released with
GlgReleaseObject when finished.
This function may also be used to set or replace values of other resources. For example, it may be used instead of the GlgSetXform function to set the object’s transformation using the Xform resource name. However, GlgSetResourceObject provides direct manipulation capabilities and doesn’t do any error checking, making the user responsible for the proper handling of objects.
The function returns GlgTrue if the operation was successful.
GlgSetStart
Initializes the container object for traversing.
void GlgSetStart( container )
GlgObject container;
Parameters
container
Specifies the container object.
This function sets the current position pointer before the beginning of the object list, preparing the container object for traversing with GlgIterate.
GlgSetXform
Adds or deletes transformations attached to an object
(Extended API only)
.
GlgBoolean GlgSetXform( object, xform )
GlgObject object;
GlgObject xform;
Parameters
object
Specifies the object to which a transformation is to be attached.
174
GLG Programming Reference Manual
xform
Specifies the transformation object to be attached to the object.
This function replaces the current object’s transformation with a new one. The NULL pointer may be used as the value of the transformation parameter to just delete the existing transformation (use the Xform resource name to query the existence of the transformation with the
GlgGetResourceObject function). The function returns GlgTrue upon successful completion, and
GlgFalse for failure.
A transformation may be added only to a drawable object (such as a viewport, group, polygon, etc.) or to the object’s attributes. Any attempt to add a transformation to a non-drawable object generates an error message.
The attributes of an object differ by their data type. It is important not to try to attach a transformation of an inappropriate type to these objects. For example, GlgSetXform fails if you try to attach a string transformation to a geometrical object.
A transformation may be added to an object only before it has been drawn. To add a transformation after the object has been drawn, use the GlgSuspendObject function. Use the GlgReleaseObject when done. Adding a transformation without using the GlgSuspendObject function after the object has been drawn generates an error message.
GlgSuspendObject
Suspends an object for editing.
GlgObject GlgSuspendObject( object )
GlgObject object;
Parameters
object
Specifies an object to be suspended.
Some operations, such as attaching a transformation to an object, constraining the object’s attribute and some others, may be carried out only before the object has been drawn. If the object has been drawn and you still need to perform these operations, the GlgSuspendObject functions must be used to suspend the object for editing. If the GlgSuspendObject function is not used, any attempt to perform these modifications fails, producing an error message.
The GlgSuspendObject function may be called only for the graphical objects, such as a viewport, group, polygon, or others.
The GlgReleaseObject function must be called after the editing operations have been completed. It an object is suspended, it is not allowed to call an update function before the object has been released.
The GlgSuspendObject function returns an object which keeps suspension information. This information should be passed to the GlgReleaseObject function when the object is released.
175
GlgTransformObject
Transforms all control points of an object with an arbitrary transformation:
GlgBoolean GlgTransformObject( object, xform, coord_type, parent )
GlgObject object;
GlgObject xform;
GlgCoordType coord_type;
GlgObject parent;
Parameters
object
Specifies the object to transform.
xform
Specifies the transformation to be applied to the object’s points.
coord_type
Specifies the coordinate system to interpret the transformation in. If GLG_SCREEN_COORD is used, the parameters of the transformation are considered to be in screen pixels. For example, this may be used to move the object by the number of screen pixels as defined by the mouse move. If GLG_OBJECT_COORD is used, the transformation parameters are interpreted as GLG world coordinates.
parent
The object’s parent. It is required in the GLG_OBJECT_COORD mode, may be NULL for
GLG_SCREEN_COORD mode.
This function applies the given transformation to an object’s control points, calculating new control point values. The object’s hierarchy must be setup to use this function.
GlgTransformPoint
Transforms a single point.
void GlgTransformPoint( matrix, in_point, out_point )
GlgObject matrix;
GlgPoint * in_point;
GlgPoint * out_point;
Parameters
matrix
Specifies the matrix to be applied to the input point.
in_point
The input point to be transformed.
out_point
The transformed point.
176
GLG Programming Reference Manual
This function applies the given transformation matrix to the in_point parameter, and returns the result in out_point.
The GlgPoint data type is defined in the GlgApi.h file: typedef struct _GlgPoint
{ double x, y, z;
} GlgPoint;
GlgTranslatePointOrigin
Converts screen coordinates of a point in one viewport to the screen coordinates of another viewport.
void GlgTranslatePointOrigin( from_viewport, to_viewport, point )
GlgObject from_viewport;
GlgObject to_viewport;
GlgPoint * point;
Parameters
from_viewport
Specifies the viewport in which the point’s screen coordinates are defined.
to_viewport
Specifies the viewport whose screen coordinate system to convert to.
in_point
The point to be converted. The result is placed back into the structure pointed by this pointer.
The objects’ hierarchy must be setup to use this function.
The GlgPoint data type is defined in the GlgApi.h file: typedef struct _GlgPoint
{ double x, y, z;
} GlgPoint;
GlgRootToScreenCoord
Converts screen coordinates relative to the root window to the screen coordinates in the specified viewport.
GlgBoolean GlgRootToScreenCoord( viewport, point )
GlgObject viewport;
GlgPoint2 * point;
Parameters
viewport
Specifies the viewport whose screen coordinate system to convert to.
177
point
The point to be converted. The result is placed back into the structure pointed by this pointer.
The viewport’s hierarchy must be set up to use this function.
The GlgPoint2 data type is defined in the GlgApi.h file: typedef struct _GlgPoint2
{ double x, y;
} GlgPoint2;
GlgGetParentViewport
Returns a parent viewport of a GLG object.
GlgObject GlgGetParentViewport( object )
GlgObject object;
Parameters
object
A drawable GLG object.
The object’s hierarchy must be setup to use this function.
GlgUnconstrainObject
Unconstrains an object.
GlgBoolean GlgUnconstrainObject( attribute )
GlgObject attribute;
Parameters
attribute
Specifies the attribute or point object to be unconstrained.
This function removes any constraints applied to an attribute object. Any changes made to the object while it was constrained to another object are permanent and will be in effect even after the constraints are removed. The removal of the constraints only means that changes to this object are no longer copied to the other objects to which it was once constrained.
If any of the objects which are using this attribute object (or any objects with attributes constrained to it) have already been drawn, an error message will be produced. Use the GlgSuspendObject function to suspend drawn objects before removing constraints from their attributes.
178
GLG Programming Reference Manual
GlgWorldToScreen
Converts a point’s coordinates from the GLG world coordinate system to the screen coordinate system.
GlgBoolean GlgWorldToScreen( object, inside_vp, in_point, out_point )
GlgObject object;
GlgBoolen inside_vp;
GlgPoint * in_point;
GlgPoint * out_point;
Parameters
object
Specifies the object whose world coordinate system to convert from. The world coordinate system of an object includes the effect of all drawing transformations attached to the object and all its parents.
inside_vp
For a viewport object, specifies which world coordinate system to use: the world coordinate system used to draw the viewport inside its parent viewport (inside_vp=GlgFalse), or the world coordinate system used to draw object inside the viewport (inside_vp=GlgTrue). The value of this parameter is ignored for other objects.
in_point
The point to be converted.
out_point
The point structure to hold the converted value.
The object’s hierarchy must be setup to use this function.
The GlgPoint data type is defined in the GlgApi.h file: typedef struct _GlgPoint
{ double x, y, z;
} GlgPoint;
179
GlgPositionToValue
Returns a value corresponding to the specified position on top of a chart or an axis object.
GlgBoolean GlgPositionToValue( object, resource_name, x, y, outside_x, outside_y, value )
GlgObject object; char * resource_name; double x, y;
GlgBoolean outside_x, outside_y; double * value;
Parameters
object
If resource_name is NULL, specifies a chart, a plot or an axis object, otherwise it specifies a container object containing a chart, a plot or an axis.
resource_name
Specifies a resource path of a child chart, plot or axis object relative to the container object.
x, y
Specify a position in the screen coordinates of the parent viewport. When using the cursor position, add GLG_COORD_MAPPING_ADJ to the cursor’s x and y coordinates for precise mapping.
outside_x, outside_y
If set to GlgFalse, the function returns GlgFalse if the specified position is outside of the chart or the axis in the corresponding direction.
value
A pointer to the returned value.
For a plot, the function converts the specified position to a Y value in the Low/High range of the plot and returns the value through the value pointer.
For an axis, the function converts the specified position to the axis value and returns the value.
For a chart, the function converts the specified position to the X or time value of the chart’s X axis and returns the value.
The function returns GlgTrue on success.
180
GLG Programming Reference Manual
GlgCreateChartSelection
Selects a chart’s data sample closest to the specified position and returns a message object containing the selected sample’s information.
GlgObject GlgCreateChartSelection( object, plot, x, y, dx, dy, screen_coord, include_invalid, x_priority )
GlgObject object;
GlgObject plot; double x, y; double dx, dy;
GlgBoolean screen_coord;
GlgBoolean include_invalid;
GlgBoolean x_priority;
Parameters
object
Specifies a chart object. If the plot parameter is NULL, the function queries samples in all plots of the chart and selects the sample closest to the specified position.
plot
Specifies an optional plot object. If it is not NULL, the function queries only the samples in that plot.
x, y
Specifies the position inside the chart. If the screen_coord parameter is set to GlgTrue, the position is defined in the screen coordinates of the chart’s parent viewport. If screen_coord is set to GlgFalse, the x position is defined as an X or time value, and the y position is defined in relative coordinates in the range [0; 1] to allow the chart to process selection for plots with different ranges (0 corresponds to the Low range of each plot, and 1 to the High range).
When the mouse position is used, add GLG_COORD_MAPPING_ADJ to the x and y screen coordinates of the mouse for precise mapping.
dx, dy
Specify an extent around the point defined by the x and y parameters. The extent is defined in the same coordinates as x and y, depending on the value of the screen_coord parameter. Only the data samples located within the dx and dy distances of the specified position are considered for the selection.
screen_coord
Specifies the type of the x and y coordinates. If set to GlgTrue, the x and y parameters supply screen coordinates in the chart’s parent viewport, otherwise they supply relative coordinates.
include_invalid
If set to GlgTrue, invalid data samples are considered for selection, otherwise invalid samples are never selected.
x_priority
If set to GlgTrue, the function selects the data sample closest to the specified position in the
181 horizontal direction with no regards to its distance from the specified position in the vertical direction. If it is set to GlgFalse, a data sample with the closest distance from the specified position is selected.
The information about the selected data sample is returned in the form of a message object
described in the Chart Selection Message Object section on page 386. The function returns NULL
if no data sample matching the selection criteria was found. The returned message object must be dereferenced using the GlgDropObject function when finished.
GlgCreateTooltipString
Creates and returns a chart or axis tooltip string corresponding to the specified position in screen coordinates. The string can be used to provide cursor feedback and display information about the data sample under the current mouse position, as shown in the Real-Time Strip-Chart demo.
char * GlgCreateTooltipString( object, x, y, dx, dy, format )
GlgObject object; double x, y; double dx, dy; char * format;
Parameters
object
Specifies a chart or axis object for creating the tooltip.
x, y
Specifies a screen position on top of a chart or an axis. When using the cursor position, add
GLG_COORD_MAPPING_ADJ to the cursor’s x and y screen coordinates for precise mapping.
dx, dy
Specify the maximum extent in screen pixels around the specified position.
format
Provides a custom format for creating a tooltip string and uses the same syntax as the
TooltipFormat attributes of the chart and axis objects. If it is set to NULL or an empty string, the format provided by the TooltipFormat attribute of the chart or the axis will be used. A special “<single_line>” tag may be prepended to the format string to force the function to remove all line breaks from the returned tooltip string. A “<chart_only>” tag may also be prepended to search only for a chart tooltip and disable search for the axes’ tooltips when the function is invoked for a chart object.
If the object parameter specifies a chart, and the selected position is within the chart’s data area, the function selects a data sample closest to the specified position and returns a tooltip string containing information about the sample. The dx and dy parameters define the maximum extent for selecting a data sample, and the TooltipMode attribute of the chart defines the data sample selection mode: X or XY. The function returns NULL if no samples matching the selection criteria were found.
182
GLG Programming Reference Manual
If the object parameter specifies an axis, or if the object parameter specifies a chart and the selected position is on top of one of the chart’s axes, the function returns a tooltip string that displays the axis value corresponding to the specified position.
The returned string must be freed using the GlgFree function.
Get and Set Resource Function Extension
The GlgGet*Resource and GlgSet*Resource functions may be used to set or query the value of an attribute object directly, without searching for the resource name. To do this, pass the attribute object ID as the object parameter and use NULL as the resource_name parameter. It will set the attribute object directly, speeding up the operation by eliminating the search for the resource name.
The following example shows how to use this feature in a function that moves a polygon:
GlgBoolean GlgMovePolygon( polygon, by, direction )
GlgObject polygon; double by;
GlgLong direction;
{ long i, size;
GlgObject polygon; double x, y, z; size = GlgGetSize( polygon );
GlgSetStart( polygon ); /* Initialize traversing. */ for( i=0; i<size; ++i )
{
/* Get the next point. */ point = GlgIterate( polygon );
/* Query the point’s coordinates. */
GlgGetGResource( point, NULL, &x, &y, &z );
}
/* Move the point in the desired direction. */ switch( direction )
{ case 'x':
GlgSetGResource( point, NULL, x + by, y, z ); break; case 'y':
GlgSetGResource( point, NULL, x, y + by, z ); break; case 'z':
GlgSetGResource( point, NULL, x, y, z + by ); break; default: fprintf( stderr, "Invalid direction.\n" ); return False;
}
} return True;
183
Enabling Strong Typing
Although the dynamic typing used by the GLG Library is quite useful and tremendously flexible, some application programmers prefer to rely on their compiler to help them identify bugs at compile time. If you prefer to have strongly typed functions, you may create function wrappers with statically typed parameters for every argument type.
For example, for the generic GlgCreateObject function:
GlgObject GlgCreateObject( type, name, data1, data2, data3, data4 )
GlgObjectType type; char * name;
GlgAnyType data1;
GlgAnyType data2;
GlgAnyType data3;
GlgAnyType data4; the following strongly typed wrappers may be created:
GlgObject GlgCreatePolygon( name, num_points ) char * name; long num_points;
{ return GlgCreateObject( GLG_POLYGON, name, (GlgAnyType)num_points,
NULL, NULL, NULL );
}
GlgObject GlgCreateText( name, string ) char * name; char * string;
{ return GlgCreateObject( GLG_TEXT, name, (GlgAnyType)string, NULL,
NULL, NULL );
} and so on.
184
GLG Programming Reference Manual
185
2.7 GLG C++ Bindings
C++ bindings allow you to use the GLG Toolkit with C++ applications as a C++ class library. The bindings are implemented in such a way that every GLG object may be used as a C++ object, and other C++ classes may be derived from it as needed. The source code for the C++ bindings is provided, allowing compiling and using the bindings with any C++ compiler. The underlying GLG library does not depend on a C++ compiler used and may be used with any of them.
As with the GLG C API, the C++ bindings provide you with several ways of using them. If you are programming in a Motif or a Microsoft Windows environment, you can use native features of the corresponding platform, such as GlgWrapperC class for a Motif widget or MFC CWnd derived
GlgControlC Class on Microsoft Windows.
If you want to write a cross-platform C++ program that can be compiled without changes in ether
Linux/Unix or Windows environment, you may use GlgObjectC class, which uses the generic API and not depend on the windowing system. The InitialDraw() method of the class provides a
platform-independent API for creating a window with a GLG drawing displayed inside it.
The C++ API methods mimic the methods of the GLG C API. This chapter provides only a brief
description of each API method; refer to the Animating a GLG Drawing with Data Using the
Standard API chapter on page 57 for a detailed description of each method’s functionality. Refer to
the Handling User Input and Other Events chapter on page 105 for details of the Input callback.
Refer to the GLG Intermediate and Extended API chapter on page 123 for a detailed description of
the Intermediate and Extended API methods.
Standard, Intermediate and Extended API Macros
The C++ bindings for all GLG APIs (Standard, Intermediate and Extended) are implemented in a single source code file, GlgClass.cpp. The GlgClass.h include file provides declarations for all classes and methods used by the C++ bindings. To use methods of the Standard, Intermediate or
Extended API, the application has to link with the corresponding GLG library.
The following preprocessor macros control the use of the GLG API libraries in the C++ bindings:
GLG_CPP_STANDARD_API
Activates methods of the Standard API and disables Intermediate and Extended API methods.
GLG_CPP_INTERMEDIATE_API
Activates methods of the Standard and Intermediate APIs and disables the Extended API.
GLG_CPP_EXTENDED_API
Activates methods of the Standard, Intermediate and Extended APIs.
To enable a required API, define one of the macros before including the GlgClass.h file. Passing a defined symbol to a compiler using the -D option is the most convenient way of defining a macro.
In the Visual Studio environment, a preprocessor symbol can be defined in the project settings.
186
GLG Programming Reference Manual
Only one of the API macros should be defined. If no API macro is defined, the Extended API will be activated by default, which can result in linking errors if the program is not linked with the
Extended API library.
Handling of Constant Strings
Starting with the GLG version 3.3, strings passed as parameters to the GLG C++ methods are considered constant ( const char *
) by default to avoid compilation warnings. This is accomplished by the CONST_CHAR_PTR preprocessor macro which is defined as True by default.
The macro can be set to False for compatibility with the previous releases, or for performance optimization using writable strings where this option is available. The macro has to be defined before including the GlgClass.h file, in the same way as the API macros described above.
In the method prototypes listed below, the optional const
modifier is not shown for string and string array parameters.
C++ API Files and Libraries
The C++ API consists of the following files:
GlgClass.h
Include file, located in the GLG include directory, declares all GLG C++ classes.
GlgClass.cpp
Source file, located in the GLG source directory (named “src”), has to be compiled with the project.
stdafx.h
Include stub file, is needed on UNIX only to make the source code generic. It allows you to get around the special handling that Visual C++ provides for this file in case of precompiled headers.
No additional libraries are required for GLG C++ bindings.
Using GLG Objects
No matter which C++ API you use in your application, platform-specific or generic, you always use the main GlgObjectC C++ class. In the Motif environment, the GlgWrapperC widget class is derived from the GlgObjectC class and inherits its methods. In Microsoft Windows environment, the GlgControlC class is derived from CWnd to inherit its window functionality, but it has a viewport object of the GlgObjectC class as it’s publicly accessible attribute that provides GLG functionality.
187
The GlgObjectC class is the central class of the GLG C++ API. It keeps an object ID of the associated GLG object as one of its data members, in the same way as MFC’s CWnd class keep a window ID of the associated window.
The GlgObjectC class has several constructors, allowing several ways of creating of the associated
GLG object: by loading it from a file, loading from a generated memory image, or by referencing a named resource inside another GLG object.
There is also a default constructor with no arguments, which creates a GlgObjectC class with a
NULL GLG object. The GLG object may be associated with this instance of the class later, by using several available Load() methods, which allow loading it from a file, memory image or associating a reference of some named resource of another object. If a Load() method is used for a class instance which already has an associated GLG object, it is dissociated from the previous object and associated with the new one.
The GlgObjectC class also provides an overloaded assignment operator, which associates the left hand side class instance with a reference to the same GLG object of the right hand class instance.
Any previous associations are discarded.
There are type converters to and from GlgObject ID, which allows assigning the GlgObject ID to a class and using both the GlgObject ID and the instance of the GlgObjectC class interchangeably.
The GlgObject ID is used as a return value of some methods of the class, allowing you to avoid returning temporary instances of the class or class pointers, both of which may lead to memory leaks or dangling pointers. The GlgObject return value may then be assigned to an instance of the class as in the following example:
GlgObjectC car( “car.g” );
GlgObjectC wheel = car.GetResourceObject( “Wheel0” );
In this example, the object from “car.g” drawing file gets loaded and associated with a car class instance. Then the first wheel of the car gets associated with the wheel class instance. The above example may be rewritten using constructors only:
GlgObjectC car( “car.g” );
GlgObjectC wheel( car, “Wheel0” );
Notice that the wheel class instance is associated with an GLG object which is the part of another object. You cannot add that wheel object to the car object again, because it is already a part of it.
You can use the Copy() method to create a new copy of a wheel object and associate that new copy with the class instance: wheel.Copy(); wheel.SetResource( “Name”, “SpareWheel” ); // Use distinct name car.Add( wheel );
188
GLG Programming Reference Manual
The same thing can also be accomplished by using a copy constructor:
{
GlgObjectC spare_wheel( wheel ); spare_wheel.SetResource( “Name”, “SpareWheel” ); car.Add( spare_wheel );
}
Automatic Referencing and Dereferencing
The GlgObjectC class provides automatic referencing and dereferencing of the associated GLG object, freeing the developer from keeping track of temporary objects. For example, the
spare_wheel object in the above example gets automatically dereferenced in its destructor when it goes out of scope after being added to a car.
Some methods, such as CreateTagList, create and return a new GLG object (a list of tags in the case of CreateTagList). The return value of these methods has to be explicitly dereferenced using the
Drop method to avoid memory leaks, as shown in the following example:
GlgObjectC tag_list = drawing.CreateTagList( True ); tag_list.Drop();
ProcessTags( tag_list );
In the above example, the tag list object created by CreateTagList gets extra referenced when it is assigned to the tag_list variable. Therefore, it is safe to dereference it by calling the Drop method right after the call to CreateTagList, even though the tag list is still used in the program. The tag list will be destroyed when the tag_list variable goes out of scope (unless the tag list is referenced inside the ProcessTags method by assigning it to a global variable to keep the tag list).
In addition to the explicit Reference() and Drop() methods , the GlgObjectC class also implements overloaded increment (
++
) and decrement (
--
) operators providing the same functionality. Note that calling the Drop() method explicitly without referencing the object first may cause destruction of the object and a crash due to an invalid GLG object ID.
Comparison Operators
The IsNull() method returns TRUE if there is no GLG object associated with the class instance
(NULL GlgObjectC ID). There is also an overloaded logical negation operator which performs the same function: !object yields TRUE when the there is no associated GLG object.
Notice an interesting usage of double negation: !!object returns TRUE when there is a GLG object associated with the class instance.
The Same() method of the GlgObjectC class provides a logical equality operator: it returns TRUE if the instances of the class is associated with the same GLG object as the instance of the class passed as a parameter.
189
Using Input and Selection Callbacks
The input and selection callbacks are virtual methods of all three main GLG API classes:
GlgObjectC, GlgWrapperC and GlgControlC. To use these callbacks, derive your class from any of these classes and provide your implementation of Input() and Selection() callbacks that overrides the ones of the base class. Use the EnableCallbacks() method of the base class to enable the callbacks. Refer to the programming examples described below for more details.
Miscellaneous Utility Classes
The GlgSessionC class handles initialization of the GLG Toolkit. One instance of this class has to be created to initialize the Toolkit. In some cases the initialization may be skipped, as describer later.
In the Motif environment, the Toolkit is initialized automatically when the Create() method of the
Wrapper Widget class is invoked.
In the Microsoft Windows environment, the toolkit is initialized automatically if a .dll version of the library is used, or when a Create() method of the GlgControlC class is invoked.
In both cases, the initialization may be skipped only if there are no other GLG calls were issued before invoking the Create() method. An explicit initialization is mandatory when the Generic C++
API is used. It is always safe to use explicit initialization in either case.
The MainLoop() method of the GlgSessionC class also provides a generic interface to the window system specific event loop.
The GlgLinkC class is derived from the GlgObjectC class and provides additional ICC functionality for communicating between GLG processes using link objects. The class provides methods for establishing a link to a GLG ICC viewport server. The rest of functionality for setting resources and updating through a link is inherited from it’s base GlgObjectC class.
Programming Examples
The examples_c_cpp directory contains source code examples for both C and C++. On Windows, the examples_mfc directory contains MFC examples.
List of Classes and Methods in the GLG C++ Bindings
GlgSessionC
Provides an interface for initializing the GLG Toolkit.
Data Members:
GlgAppContext app_context;
Application context returned by GlgInit().
190
GLG Programming Reference Manual
Methods:
GlgSessionC( void );
Default constructor.
GlgSessionC( GlgBoolean initialized, GlgAppContext application_context, int argc = 0, char ** argv = NULL );
Constructor: calls GlgInit().
virtual ~GlgSessionC( void );
Destructor.
GlgAppContext GetAppContext( void );
Returns the application context.
GlgBoolean MainLoop( void );
Provides a generic interface to the event loop.
void Create( GlgBoolean initialized = False, GlgAppContext application_context = NULL, int argc = 0, char ** argv = NULL );
Calls GlgInit().
GlgObjectC
This is the main class of the GLG C++ bindings. It has the functionality of the regular and Extended
API.
Data Members:
GlgObject glg_obj;
An object ID of associated GLG object.
GlgObject suspend_obj;
Suspension information object. Is not NULL if the object was suspended for editing.
Methods:
GlgObjectC( void );
Default constructor: Creates a null object.
GlgObjectC( GlgObjectType type, char * name = NULL,
GlgAnyType data1 = NULL, GlgAnyType data2 = NULL,
GlgAnyType data3 = NULL, GlgAnyType data4 = NULL );
Constructor: creates a new object of the type using default attributes.
191
GlgObjectC( char * filename );
Constructor: loads an object from a file.
GlgObjectC( long object_data[], long object_data_size );
Constructor: loads an object from a generated memory image.
GlgObjectC( GlgObjectC& object,
GlgCloneType clone_type = GLG_FULL_CLONE );
Copy constructor: creates a copy of the object. The type of copying is defined by a clone_type parameter. Default type is GLG_FULL_CLONE.
GlgObjectC( GlgObjectC& object, char * resource_name );
Constructor: associates with a named resource object inside another and references it.
GlgObjectC( GlgObject object );
Constructor: creates a C++ class from GlgObject to allow assigning GlgObject to a GlgObjectC object class:
GlgObjectC object = GetResourceObject( ... );
GlgObjectC( GlgObjectC * object );
Constructor: creates a C++ class from a GlgObjectC pointer. This constructor is needed by some
C++ compilers for proper handling of temporary objects.
virtual ~GlgObjectC( void );
Destructor: Deletes or dereferences the GLG object.
operator GlgObject( void );
Type converter to GlgObject.
GlgObjectC& operator= ( const GlgObjectC& object );
Assignment operator: associates the GLG object and references it.
GlgObjectC& operator++( void ); // prefix ++
GlgObjectC& operator++( int ); // postfix ++
GlgObjectC& operator--( void ); // prefix --
GlgObjectC& operator--( int ); // postfix --
Overloaded ++; --, both infix and postfix. Overloaded to reference/dereference.
192
GLG Programming Reference Manual void Reference( void ); void Drop( void );
Explicit reference/dereference.
GlgBoolean Save( char * filename );
Saves the associated GLG object into a file.
GlgBoolean Load( char * filename, char * object_name = NULL );
Explicit Load(). Replaces the associated GLG object with the loaded one. Two sets of overloaded load functions: one for loading the whole drawing or its named components, and another for extracting just the “$Widget” viewport.
Loads an object from a file. If object_name is not NULL, extracts and loads just that named resource of the object.
GlgBoolean Load( void * object_data, long object_data_size, char * object_name = NULL );
Loads an object from a generated memory image.
GlgBoolean Load( GlgObjectC& object, char * object_name = NULL );
Associates with an object inside another object and references it. If object_name is NULL, uses the parameter object itself.
GlgBoolean LoadWidget( char * filename );
Loads a “$Widget” viewport from a file.
GlgBoolean LoadWidget( void * object_data, long object_data_size );
Loads a “$Widget” viewport from a generated memory image.
GlgBoolean LoadWidget( GlgObjectC& object );
Loads a “$Widget” viewport from another object.
void LoadNullObject( void );
Dissociates and sets the GLG object ID to NULL.
void Create( GlgObjectType type, char * name = NULL,
GlgAnyType data1 = NULL, GlgAnyType data2 = NULL,
GlgAnyType data3 = NULL, GlgAnyType data4 = NULL );
Replaces the current object with a created object.
void Copy( GlgCloneType clone_type = GLG_FULL_CLONE );
Replaces the current object with a copy of it.
193
GlgBoolean GetResource( char * resource_name, double * value ); // D-type
GlgBoolean GetResource( char * resource_name, char ** s_value ); // S-type
GlgBoolean GetResource( char * resource_name, double * x_value, double * y_value, double * z_value ); // G-type
GlgBoolean GetTag( char * tag_source, double * value ); // D-type
GlgBoolean GetTag( char * tag_source, char ** s_value ); // S-type
GlgBoolean GetTag( char * tag_source, double * x_value, double * y_value, double * z_value ); // G-type
Get resource or tag values.
GlgBoolean SetResource( char * resource_name, double value ); // D-type
GlgBoolean SetResource( char * resource_name, char * s_value ); // S-type
GlgBoolean SetResource( char * resource_name, double x_value, double y_value, double z_value); // G-type
GlgBoolean SetResource( char * resource_name, double value, GlgBoolean if_changed ); // D-type
GlgBoolean SetResource( char * resource_name, char * s_value, GlgBoolean if_changed ); // S-type
GlgBoolean SetResource( char * resource_name, double x_value, double y_value, double z_value, GlgBoolean if_changed ); // G-type
GlgBoolean SetTag( char * tag_source, double value, GlgBoolean if_changed );
GlgBoolean SetTag( char * tag_source, char * s_value, GlgBoolean if_changed );
// D-type
// S-type
GlgBoolean SetTag( char * tag_source, double x_value, double y_value, double z_value, GlgBoolean if_changed ); // G-type
Set resource or tag values.
GlgBoolean SetResource( char * resource_name, char * format, double value );
GlgBoolean SetResource( char * resource_name, char * format, double value,
GlgBoolean if_changed );
GlgBoolean SetTag( char * tag_source, char * format, double value, GlgBoolean if_changed );
Set S resource or tag from a double value according to the specified format.
GlgBoolean SetResource( char * resource_name, GlgObjectC& object );
Set resource from object.
GlgBoolean HasResourceObject( char * resource_name );
Checks if a named resource exists.
194
GLG Programming Reference Manual
GlgBoolean HasTagName( char * tag_name );
GlgBoolean HasTagSource( char * tag_source );
Checks if a tag with the specified tag name or tag source exists.
GlgObject CreateTagList( GlgBoolean unique_tags );
Creates and returns a list of the object’s tags.
Since the method creates a new object, its returned value must be explicitly dereferenced. This can be done by invoking the Drop method on the GlgObjectC object the return value is assigned to.
GlgObject CreateAlarmList( void );
Creates and returns a list of alarms attached to the object.
Since the method creates a new object, its returned value must be explicitly dereferenced. This can be done by invoking the Drop method on the GlgObjectC object the return value is assigned to.
GlgObject GetGlgObject( void );
Returns an object ID of the associated GLG object.
void SetGlgObject( GlgObject object );
Low-level object manipulation function: sets the associated GLG object.
GlgBoolean IsNull( void );
GlgBoolean operator!( void );
NULL check to use after Load/GetResourceObject/etc.
GlgBoolean Same( GlgObjectC& object );
Returns TRUE if the object refers to the same object ID as the parameter object.
void InitialDraw( void ); void SetupHierarchy( void ); void ResetHierarchy( void );
GlgBoolean Reset( void );
Other viewport-related GLG API functions.
GlgBoolean Sync( void );
Flushes all graphic requests and waits for their completion.
GlgBoolean Update( void );
Updates the viewport’s graphic with the new data.
195
void EnableCallback( GlgCallbackType callback_type, GlgObject callback_viewport = NULL );
Enables selection and input callbacks of the object. If callback_viewport is not NULL, adds GLG callbacks to it, otherwise adds it to this object (which must be a viewport).
virtual void Input( GlgObjectC& callback_viewport, GlgObjectC& message ); virtual void Select( GlgObjectC& callback_viewport, char ** name_array ); virtual void Trace( GlgObjectC& callback_viewport, GlgTraceCBStruct * trace_info ); virtual void Trace2( GlgObjectC& callback_viewport, GlgTraceCBStruct * trace_info ); virtual void Hierarchy( GlgObjectC& callback_viewport, GlgHierarchyCBStruct * hierarchy_info );
Virtual callback functions to be overridden by a derived class.
GlgBoolean SetZoom( char * resource_name, GlgLong type, double value )
Performs a zoom or pan operation specified by the type parameter. If the resource_name parameter is null, the viewport itself is zoomed. Otherwise, the zoom operation will be performed on its child viewport specified by the resource_name parameter. The value parameter defines the zoom factor
or pan distance. Refer to the GlgSetZoom section on page 97 for a complete list of all zoom and pan
types.
GlgBoolean SetZoomMode( char * resource_name, GlgObjectC * zoom_object, char * zoom_object_name )
Sets or resets a viewport’s zoom mode by supplying a GIS or Chart object to be zoomed. In the
Drawing Zoom Mode (default), the drawing displayed in the viewport is zoomed and panned. If the
GIS Zoom Mode is set, any zooming and panning operation performed by the GlgSetZoom method will zoom and pan the map displayed in the viewport’s GIS Object, instead of being applied to the viewport’s drawing. In the Chart Zoom Mode, the content of the chart is zoomed and panned. If the
resource_name parameter is null, the zoom mode of the viewport itself will be set. Otherwise, the zoom mode will be set for its child viewport specified by the resource_name parameter. If the
zoom_name parameter is not null, it specifies the resource path of a GIS or Chart object relative to the zoom_object parameter, or relative to the viewport if the zoom_object parameter is null. The method may be invoked with zoom_object=null and zoom_object_name=null to reset the zoom mode to the default Drawing Zoom Mode.
GlgBoolean Print( char * filename=”out.ps”, double x=-1000., double y=-1000., double width = 2000., double height = 2000.,
GlgBoolean portrait = True, GlgBoolean stretch = True );
Printing method.
GlgBoolean SaveImage( char * resource_name, char * filename, GlgImageFormat format )
Method for saving an image of the visible area of the drawing’s viewport.
196
GLG Programming Reference Manual
GlgBoolean SaveImageCustom( char * resource_name, char * filename, GlgImageFormat format,
GlgLong x, GlgLong y, GlgLong width, GlgLong height, GlgLong gap )
Method for saving an unclipped image of the whole drawing.
void MetaDraw( char * filename=”out.meta”, double x=-1000., double y=-1000., double width = 2000., double height = 2000.,
GlgBoolean portrait = True, GlgBoolean stretch = True );
GLG Metafile support.
GlgBoolean Print( CDC * dc, double x=-1000., double y=-1000., double width = 2000., double height = 2000.,
GlgBoolean portrait = True, GlgBoolean stretch = True );
MICROSOFT WINDOWS ONLY: Native windows printing, GLG controlled page layout.
void OnPrint( CDC * dc );
MICROSOFT WINDOWS ONLY: Native window printing, windows-controlled page layout.
void OnDrawMetafile( CDC * dc );
MICROSOFT WINDOWS ONLY: Native window printing with clipping disabled.
GlgAnyType SendMessage( char * resource_name, char * message, GlgAnyType param1,
GlgAnyType param2, GlgAnyType param3, GlgAnyType param4 )
Sends a message specified by the message parameter. If the resource_name parameter is null, the message is sent to the object itself. Otherwise, the message is sent to the object’s child specified by the resource_name parameter. The param<n> arguments define additional parameters of the message depending on the message type.
GlgObject GetNamedPlot( char * resource_name. char * plot_name )
Finds a chart’s plot by name and returns it’s object ID. If the resource_name parameter is NULL, a named plot of this chart is returned. Otherwise, the resource_name parameter points to a child chart of this object. The method returns NULL if a plot with the specified name has not been found.
GlgObject AddPlot( char * resource_name, GlgObject& plot )
Adds a plot to a chart object. If the resource_name parameter is NULL, the plot is added to this chart. Otherwise, the plot is added to a child chart of this object pointed to by the resource_name parameter. The plot parameter specifies the plot object to add; NULL can be used to create a new plot. The method returns the added plot object on success, or NULL on failure.
GlgBoolean DeletePlot( char * resource_name, GlgObject& plot )
Deletes a plot from a chart object. If the resource_name parameter is NULL, the plot is deleted from
this chart. Otherwise, the plot is deleted from a child chart of this object pointed to by the
resource_name parameter. The plot parameter specifies the plot object to delete. The method returns
True if the plot was successfully deleted.
197
GlgBoolean GetDataExtent( char * resource_name, GlgMinMax * min_max, GlgBoolean x_extent )
Queries the minimum and maximum extent of the data accumulated in a chart or in one of its plots.
If the resource_name parameter is NULL, the data extent of this chart or plot object is returned.
Otherwise, the resource_name parameter points to a child chart or a child plot of this object. If
x_extent is True, the X extent of the data is returned in min_max, otherwise the method returns the
Y extent of the data. GlgMinMax is defined in the GlgApi.h file: typedef struct _GlgMinMax
{ double min, max;
} GlgMinMax;
For a chart object, the method returns the data extent of all plots in the chart. For a plot, the data extent of that plot is returned. The object hierarchy must be set up for this function to succeed. The method returns True on success.
Additional Standard API Methods
Extended and Intermediate API
There are two flavors of the Extended API: GLG Intermediate API and GLG Extended API. The
Intermediate API provides all Extended API methods except for the methods for creating and deleting objects at run time. The list below describes methods of both APIs, with an availability comment for methods that are available only with the Extended API.
Intermediate and Extended API Methods
GlgObject GetResourceObject( char * resource_name );
Explicit GetResourceObject(). The return value may be assigned to a GlgObjectC class.
GlgBoolean SetResourceObject( char * resource_name, GlgObjectC& o_value );
Sets the new value of the object’s attribute specified by the resource_name
(Extended API only)
. It is used for attaching Custom Property objects and aliases.
GlgObject GetTagObject( char * search_string, GlgBoolean by_name, GlgBoolean unique_tags,
GlgBoolean single_tag )
Finds a single tag with a given tag name or tag source, or creates a list of tags matching the wildcard.
The search_string specifies either the exact tag name or tag source to search for, or a search pattern which may contain the ? and * wildcards. The by_name parameter defines the search mode: by a tag name or tag source. In the single tag mode, the first tag matching the search criteria is returned.
The unique_tags controls if only one tag is included in case there are multiple tags with the same tag name or tag source. The unique_tags flag is ignored in the single tag mode.
198
GLG Programming Reference Manual
In the single tag mode, the method returns the first attribute that has a tag matching the search criteria. In the multiple tag mode, a list containing all attributes with matching tags will be returned.
The return value may be assigned to a GlgObjectC class.
In the multiple tag mode, the method creates a new list object and its returned value must be explicitly dereferenced. This can be done by invoking the Drop method on the GlgObjectC object the return value is assigned to.
GlgObject QueryTags( GlgTagType tag_type_mask )
Returns a list of all tags of the specified tag type. Since the method creates a new list object, its returned value must be explicitly dereferenced. This can be done by invoking the Drop method on the GlgObjectC object the return value is assigned to.
GlgObject GetAlarmObject( char * search_string, GlgBoolean single_alarm )
Finds a single alarm with a given alarm label, or creates a list of alarms with alarm labels matching the specified wildcard. The search_string specifies either the exact alarm label or a search pattern which may contain the ? and * wildcards.
In the single alarm mode, the method returns the first alarm object with an alarm label matching the search criteria. In the multiple alarm mode, a list containing all alarms with matching alarm labels will be returned.
In the multiple alarm mode, the method creates a new list object and its returned value must be explicitly dereferenced. This can be done by invoking the Drop method on the GlgObjectC object the return value is assigned to.
GlgBoolean SetXform( GlgObjectC& xform );
Adds a transformation to the object
(Extended API only)
.
GlgObject GetParent( GlgLong * num_parents );
Gets a parent object or array of parents if num_parents > 1.
GlgCube * GetBoxPtr( void );
Returns 3D bounding box of an object.
GlgObject GetDrawingMatrix( void );
Returns a drawing matrix object used to render the object.
void SuspendObject( void ); void ReleaseObject( void );
Suspends or releases the object.
199
GlgObject CreateResourceList( GlgBoolean list_named, GlgBoolean list_default,
GlgBoolean list_aliases );
Returns a list of resources of the object.
Since the method creates a new object, its returned value must be explicitly dereferenced. This can be done by invoking the Drop method on the GlgObjectC object the return value is assigned to.
GlgObject CreatePointArray( GlgCoordType type );
Returns a list of resources of the object. The type parameter is reserved for a future use and must be se to 0.
Since the method creates a new object, its returned value must be explicitly dereferenced. This can be done by invoking the Drop method on the GlgObjectC object the return value is assigned to.
GlgBoolean MoveObject( GlgCoordType coord_type, GlgPoint * start_point, GlgPoint * end_point );
Moves an object by the specified vector.
GlgBoolean MoveObjectBy( GlgCoordType coord_type, double x, double y, double z );
Moves an object by the specified X, Y and Z distances.
GlgBoolean ScaleObject( GlgCoordType coord_type, GlgPoint * center, double x, double y, double z );
Scales an object relative to the center by the specified X, Y and Z scale factors.
GlgBoolean RotateObject( GlgCoordType coord_type, GlgPoint * center, double x, double y, double z );
Rotates an object around the specified center by the specified X, Y and Z angles.
GlgBoolean PositionObject( GlgCoordType coord_type, GlgLong anchoring, double x, double y, double z );
Positions an object at the specified location using the specified anchoring.
GlgBoolean FitObject( GlgCoordType coord_type, GlgCube * box, GlgBoolean keep_ratio );
Fits the object to the specified area.
GlgBoolean LayoutObjects( GlgObject sel_elem, GlgLayoutType type, double distance,
GlgBoolean use_box, GlgBoolean process_subobjects )
GlgBoolean ScreenToWorld( GlgBoolean inside_vp, GlgPoint * in_point, GlgPoint * out_point );
Converts a point coordinates from the screen to the GLG world coordinate system. The inside_vp flag must be set to GlgTrue for viewport objects to convert to the world coordinate system inside the viewport. When converting the cursor position to world coordinates, add
GLG_COORD_MAPPING_ADJ to the cursor’s x and y screen coordinates for precise mapping.
200
GLG Programming Reference Manual
GlgBoolean WorldToScreen( GlgBoolean inside_vp, GlgPoint * in_point, GlgPoint * out_point );
Converts a point coordinates from the GLG world to the screen coordinate system. The inside_vp flag must be set to GlgTrue for viewport objects to convert from the world coordinate system inside the viewport.
GlgBoolean PositionToValue( char * resource_name, double x, double y,
GlgBoolean outside_x, GlgBoolean outside_y, double * value )
Returns a value corresponding to the specified x, y position on top of a chart or an axis object. If the
resource_name parameter is null, the value corresponding to this object is returned. Otherwise, the
resource_name parameter points to a child chart, a child plot or a child axis of this object.
If outside_x or outside_y are set to True, the method returns NULL if the specified position is outside of the chart or the axis in the corresponding direction.
For a plot, the method converts the specified position to a Y value in the Low/High range of the plot and returns it via the value pointer.
For an axis, the function converts the specified position to the axis value and returns the value.
For a chart, the function converts the specified position to the X or time value of the chart’s X axis and returns the value.
When using the cursor position, add GLG_COORD_MAPPING_ADJ to the cursor’s x and y coordinates for precise mapping.
GlgObject CreateChartSelection( GlgObjectC plot, double x, double y, GlgBoolean screen_coord,
GlgBoolean include_invalid, GlgBoolean x_priority )
Selects a chart’s data sample closest to the specified x, y position and returns a message object containing the selected sample’s information. If plot contains a null GLG object, the method queries samples in all plots of the chart and selects the sample closest to the specified position. If plot contains a non-null GLG object, the method queries only the samples in that plot.
If the screen_coord parameter is set to True, the position is defined in the screen coordinates of the chart’s parent viewport. If screen_coord is set to False, the x position is defined as an X or time value, and the y position is defined in relative coordinates in the range [0; 1] to allow the chart to process selection for plots with different ranges (0 corresponds to the Low range of each plot, and
1 to the High range). When the mouse position is used, add GLG_COORD_MAPPING_ADJ to the x and y screen coordinates of the mouse for precise mapping.
The dx and dy parameters specify an extent around the point defined by the x and y parameters. The extent is defined in the same coordinates as x and y, depending on the value of the screen_coord parameter. A data sample in a chart is selected only if its x and y coordinates differ from the specified position by amounts less or equal to the values of the corresponding dx or dy parameters.
201
If include_invalid if set to True, invalid data samples are considered for selection, otherwise they are never included. If x_priority is set to True, the method selects the data sample closest to the specified position in the horizontal direction, with no regards to its distance from the specified position in the vertical direction. If x_priority is set to False, a data sample with the closest distance from the specified position is selected.
The information about the selected data sample is returned in the form of a message object
described in the Chart Selection Message Object section on page 386. The method returns NULL
if no data sample matching the selection criteria was found.
Since the method creates a new object, its returned value must be explicitly dereferenced. This can be done by invoking the Drop method on the GlgObjectC object the return value is assigned to.
char * CreateTooltipString( double x, double y, double dx, double dy, char * format )
Creates and returns a chart or axis tooltip string corresponding to the specified x, y position in screen coordinates. The string can be used to provide cursor feedback and display information about the data sample under the current mouse position, as shown in the Real-Time Strip-Chart demo.
The format parameter provides a custom format for creating a tooltip string and uses the same syntax as the TooltipFormat attributes of the chart and axis objects. If it is set to NULL or an empty string, the format provided by the TooltipFormat attribute of this chart or axis object will be used.
A special “<single_line>” tag may be prepended to the format string to force the method to remove all line breaks from the returned tooltip string.
If this object is a chart and the selected position is within the chart’s data area, the method selects a data sample closest to the specified position and returns a tooltip string containing information about the sample. The dx and dy parameters define the maximum extent in pixels around the specified position for selecting a data sample, and the TooltipMode attribute of the chart defines the data sample selection mode: X or XY. The method returns NULL if no samples matching the selected criteria were found.
If this object is an axis, or if this object is a chart and the selected position is on top of one of the chart’s axes, the function returns a tooltip string that displays the axis value corresponding to the specified position.
When using the cursor position, add GLG_COORD_MAPPING_ADJ to the cursor’s x and y screen coordinates for precise mapping.
The returned string must be freed using the GlgFree function.
Attribute Objects
GlgBoolean ConstrainObject( GlgObjectC& to_attribute );
GlgBoolean UnconstrainObject( void );
Constrains or unconstrains the attribute object.
202
GLG Programming Reference Manual
Matrix Objects
GlgObject InverseMatrix( void );
Creates and returns a new matrix.
void TransformPoint( GlgPoint * in_point, GlgPoint * out_point );
Transforms point using the GLG matrix object associated with this class instance.
void GetMatrixData( GlgMatrixData * matrix_data );
Queries matrix coefficients.
void SetMatrixData( GlgMatrixData * matrix_data );
Sets matrix coefficients.
Container Functionality
GlgBoolean IsContainer( void );
Returns TRUE if the associated GLG object is a GLG container (viewport,
void SetStart( void );
Initializes container for traversing.
GlgObject Iterate( void );
Returns the next subobject of the associated container object.
GlgLong GetSize( void );
Returns the size of the associated container object.
GlgBoolean AddToTop( GlgObjectC& object );
GlgBoolean AddToBottom( GlgObjectC& object );
GlgBoolean AddAt( GlgObjectC& object, GlgLong index );
Add object to container
(Extended API only)
.
GlgBoolean DeleteTopObject( void );
GlgBoolean DeleteBottomObject( void );
GlgBoolean DeleteObjectAt( GlgLong index );
GlgBoolean DeleteObject( GlgObjectC& object );
Delete this object from container
(Extended API only)
.
203
GlgObject ReorderElement( GlgLong old_index, GlgLong new_index );
Reorder elements of the container.
GlgBoolean ContainsObject( GlgObjectC& object );
GlgObject GetElement( GlgLong index );
GlgObject GetNamedObject( char * name );
GlgLong GetIndex( GlgObjectC& object );
GlgLong GetStringIndex( char * string );
Search functions for finding elements of a container.
void Inverse();
Inverses the order of container’s elements.
GlgLinkC
GlgLinkC is subclassed from GlgObjectC to inherit SetResource() and GetResource() and other methods. Provides methods for establishing links between GLG processes by using GLG ICC.
Some inherited methods of extended API are not implemented yet for links. Note also that there is a type converter to GlgObject that is inherited from GlgObjectC.
Methods:
GlgLinkC( void );
Default constructor: creates a null link object.
GlgLinkC( char * display_name, char * server_name );
Constructor: creates a link object and connects it to a named GLG ICC Server.
GlgLinkC( GlgObjectC& object );
Constructor: creates a link from a GlgObjectC class:
GlgObjectC some_object;
GlgLinkC link = some_object;
GlgLinkC( GlgObject object );
Constructor: creates a link from a GlgObject.
GlgLinkC( GlgLinkC& object );
Copy constructor. The server connection is not copied.
virtual ~GlgLinkC( void );
Destructor, calls GlgDestroyLink().
204
GLG Programming Reference Manual
Connect( char * display_name, char * server_name );
Establish a connection to a named GLG ICC Server.
Disconnect( void );
Explicit link closing, calls GlgDestroyLink().
GlgLinkC& operator= ( const GlgLinkC& object );
Assignment operator, the server connection is not copied.
GlgBoolean IsActive();
Interface to GlgLinkActive: returns TRUE is the link is active.
GlgControlC (Microsoft Windows Only)
MFC CWnd derived class providing a window for displaying a GLG drawing.
Data Members:
GlgObjectC viewport;
An object ID of the associated GLG viewport object with the drawing.
Methods:
GlgControlC( void );
Default constructor: creates an empty control.
virtual ~GlgControlC( void );
Destructor. Destroys the window and dereferences the viewport object.
void Create( char * drawing_file, CWnd * parent, char * control_name = “GlgControl”, CRect * in_rect = NULL, int IDC_id = 0 );
Creates a control’s window and loads drawing from a file into it.
void Create( void * drawing_image, long image_size, CWnd * parent, char * control_name = “GlgControl”, CRect * in_rect = NULL, int IDC_id = 0 );
Creates a control’s window and loads drawing from a generated memory image.
void Create( GlgObjectC& object, CWnd * parent, char * control_name = “GlgControl”, CRect * in_rect = NULL, int IDC_id = 0 );
Creates a control’s window and uses the “$Widget” viewport of another GLG object as a drawing.
void InitialDraw();
Draws the graphics the first time.
205
GlgBoolean Update( void );
Updates the displayed graphics.
void SetDrawing( char * filename );
Changes the drawing, load a new drawing from a file.
void SetDrawing( void * drawing_image, long drawing_image_size );
Changes the drawing, load a new drawing from a generated memory image.
void SetDrawing( GlgObjectC& object );
Changes the drawing, use the “$Widget” viewport of another object as a new drawing.
virtual void EnableCallback( GlgCallbackType callback_type,
GlgObject callback_viewport = NULL );
Enables selection and input callbacks of the control. If callback_viewport is not NULL, adds GLG callbacks to it, otherwise adds it to the control’s viewport.
virtual void Input( GlgObjectC& callback_viewport, GlgObjectC& message ); virtual void Select( GlgObjectC& callback_viewport, char ** name_array ); virtual void Trace( GlgObjectC& callback_viewport, GlgTraceCBStruct * trace_info ); virtual void Trace2( GlgObjectC& callback_viewport, GlgTraceCBStruct * trace_info ); virtual void Hierarchy( GlgObjectC& callback_viewport, GlgHierarchyCBStruct * hierarchy_info );
Virtual callback functions to be overridden by a derived class.
void Print( CDC * pDC, DWORD dwFlags );
Native Windows print method.
GlgObject GetViewport( void );
Returns an object ID of the control’s viewport.
GlgWrapperC (X Windows Only)
C++ wrapper around the GlgWrapper widget. It is a subclass of a GlgObjectC and inherits GLG
API and GLG Extended API from it. Note that the GetViewport() method has to be called explicitly after the widget has been realized and before any API functions are used. The GlgGetViewport() method associates a viewport object with the instance of a class. While the widget is being realized, the widget creates a viewport. The viewport is set to NULL initially and its object ID has to be obtained from the widget after the widget has been realized. Since the widget may be realized by its parent, it is difficult to encapsulate GetViewport() functionality into the GlgWrapperC class so that it is transparent to the user. Trying to do so causes a lot of code duplication and will lead to problems in the future, so invoking this call is left as the responsibility of the user.
206
GLG Programming Reference Manual
Data Members:
Widget widget;
Methods:
GlgWrapperC( void );
Default constructor: creates an empty wrapper widget with no drawing.
virtual ~GlgWrapperC( void );
Destructor. Destroys the wrapper widget. Be careful to set the widget to NULL if it is destroyed by destroying its parent to avoid XtDestroyWidget() being called with an invalid widget ID.
void Create( char * filename, Widget parent, char * widget_name = “GlgWrapper”, long width = 400, long height = 300 );
Creates the widget and loads drawing from a file into it.
void Create( void * image_data, long image_data_size, Widget parent, char * widget_name = “GlgWrapper”, long width = 400, long height = 300 );
Creates a widget and loads drawing from a generated memory image.
void Create( GlgObjectC& object, Widget parent, char * widget_name = “GlgWrapper”, long width = 400, long height = 300 );
Creates a widget and uses the “$Widget” viewport of another GLG object as a drawing.
The following collection of SetDrawing() methods change the drawing using a particular wrapper widget resource. The actual drawing displayed is still subject to the priority of a particular wrapper widget drawing resource. Setting the drawing by using one of the SetDrawing() functions may interfere with others.
void SetDrawing( char * filename );
Loads a new drawing from a file (uses XtNglgDrawingFile resource).
void SetDrawing( void * image_data, long image_data_size );
Loads a new drawing from a generated memory image ( uses XtNglgDrawingImage resource).
void SetDrawing( GlgObjectC& object );
Uses the “$Widget” viewport of another object as a new drawing (uses XtNglgDrawingObject resource).
Widget GetWidget( void );
Returns a widget id.
207
GlgObject GetViewport();
Associates a viewport object of the wrapper widget with the instance of the class after the widget has been realized.
void EnableCallback( GlgCallbackType callback_type, GlgObject callback_viewport = NULL );
Enables selection and input callbacks of the control. If callback_viewport is not NULL, adds GLG callbacks to it, otherwise adds it to the widget’s viewport.
virtual void Input( GlgObjectC& callback_viewport, GlgObjectC& message ); virtual void Select( GlgObjectC& callback_viewport, char ** name_array ); virtual void Trace( GlgObjectC& callback_viewport, GlgTraceCBStruct * trace_info ); virtual void Trace2( GlgObjectC& callback_viewport, GlgTraceCBStruct * trace_info ); virtual void Hierarchy( GlgObjectC& callback_viewport, GlgHierarchyCBStruct * hierarchy_info );
Virtual callback functions to be overridden by a derived class.
void SetXtResource( String xt_ resource_name, char * res_value ); void GetXtResource( String xt_ resource_name, char ** res_value_ptr );
Sets and gets Xt resources of string type (is primarily used with XtNglgHResource* and
XtNglgVResource* resources).
208
GLG Programming Reference Manual
Скачать
Реклама