Other Objects
*************

Timer Object
============

Timer objects can be used to make a timer that runs down toward 0 or runs up toward a pre-set value after which it starts blinking and returns itself to the application program. This can be used in many different ways, for example, to give a user a certain amount of time for completing a task, etc. Also hidden timer objects can be created. In this case the application program can take action at the moment the timer expires. For example, you can use this to show a message that remains visible until the user presses the "OK" button or until a certain amount of time has passed.

The precision of the timer is not very high. Don't count on anything better than, say, 50 milli-seconds, especially when the system is rather busy. The timer can trigger early by up to 10 ms. Run the demo timerprec.c for an actual accuracy measurement.

Adding Timer Objects
--------------------

To add a timer to a form you use the routine

     FL_OBJECT *fl_add_timer(int type, FL_Coord x, FL_Coord y,
                             FL_Coord w, FL_Coord h, const char *label);

The meaning of the parameters is as usual.

Timer Types
-----------

There are at the moment three types of timers:

FL_NORMAL_TIMER
     Visible, Shows a label in a box which blinks when the timer expires.

FL_VALUE_TIMER
     Visible, showing the time left or the elapsed time. Blinks if the timer expires.

FL_HIDDEN_TIMER
     Not visible.

Timer Interaction
-----------------

When a visible timer expires it starts blinking. The user can stop the blinking by pressing the mouse on it or by resetting the timer to 0.

The timer object is returned to the application program or its callback called when the timer expired per default. You can also switch off reporting the expiry of the timer by calling

     int fl_set_object_return(FL_OBJECT *obj, unsigned int when)

with when set to FL_RETURN_NONE. To re-enable reporting call it with one of FL_RETURN_CHANGED, FL_RETURN_END, FL_RETURN_END_CHANGED or FL_RETURN_ALWAYS.

Other Timer Routines
--------------------

To set the timer to a particular value use

     void fl_set_timer(FL_OBJECT *obj, double delay);

delay gives the number of seconds the timer should run. Use 0.0 to reset/de-blink the timer.

To obtain the time left in the timer use

     double fl_get_timer(FL_OBJECT *obj);

By default, a timer counts down toward zero and the value shown (for FL_VALUE_TIMERs) is the time left until the timer expires. You can change this default so the timer counts up and shows elapsed time by calling

     void fl_set_timer_countup(FL_OBJECT *obj, int yes_no);

with a true value for the argument yes_no.

A timer can be temporarily suspended (stopwatch) using the following routine

     void fl_suspend_timer(FL_OBJECT *obj);

and later be resumed by

     void fl_resume_timer(FL_OBJECT *obj);

Unlike fl_set_timer() a suspended timer keeps its internal state (total delay, time left etc.), so when it is resumed, it starts from where it was suspended.

Finally there is a routine that allows the application program to change the way the time is presented in FL_VALUE_TIMER:

     typedef char *(FL_TIMER_FILTER)(FL_OBJECT *obj, double secs);
     FL_TIMER_FILTER fl_set_timer_filter(FL_OBJECT *obj,
                                         FL_TIMER_FILTER filter);

The function filter receives the timer ID and the time left for count-down timers and the elapsed time for up-counting timers (in units of seconds) and should return a string representation of the time. The default filter returns the time in a hour:minutes:seconds.fraction format.

Timer Attributes
----------------

Never use FL_NO_BOX as the boxtype for FL_VALUE_TIMERs.

The first color argument (col1) to fl_set_object_color() controls the color of the timer, the second (col2) is the blinking color.

Remarks
-------

Although having different APIs and the appearance of a different interaction behaviour, the way timers and timeout callbacks work is almost identical with one exception: you can deactivate a timer by deactivating the form it belongs to. While the form is deactivated, the timers callback will not be called, even if it expires. The interaction will only resume when the form is activated again.

See timer.c for the use of timers.

XYPlot Object
=============

A xyplot object gives you an easy way to display a tabulated function generated on the fly or from an existing data file. An active xyplot is also available to model and/or change a function.

Adding XYPlot Objects
---------------------

To add an xyplot object to a form use the routine

     FL_OBJECT *fl_add_xyplot(int type, FL_Coord x, FL_Coord y,
                              FL_Coord w, FL_Coord h, const char *label);

It shows an empty box on the screen with the label per default below it.

XYPlot Types
------------

The following types are available:

FL_NORMAL_XYPLOT
     A solid line is drawn through the data points.

FL_SQUARE_XYPLOT
     Data drawn as a solid line plus squares at data points.

FL_CIRCLE_XYPLOT
     Data drawn as a solid line plus circles at data points.

FL_FILL_XYPLOT
     Data drawn as a solid line with the area under the curve filled. Only data points are drawn with. per default, stars.

FL_LINEPOINTS_XYPLOT
     Data drawn as a solid line plus, per default, stars at data point.

FL_DASHED_XYPLOT
     Data drawn as a dashed line.

FL_DOTTED_XYPLOT
     Data drawn as a dotted line.

FL_DOTDASHED_XYPLOT
     Data drawn as a dash-dot-dash line.

FL_IMPULSE_XYPLOT
     Data drawn by vertical lines.

FL_ACTIVE_XYPLOT
     Data drawn as a solid line plus squares at data points, accepting manipulations.

FL_EMPTY_XYPLOT
     Only the axes are drawn.

All xyplots per default display the curve auto-scaled to fit the plotting area. Although there is no limitation on the actual data, a non-monotonic increasing (or decreasing) x-axis might be plotted incorrectly.

XYPlots of type FL_POINTS_XYPLOT and FL_LINEPOINTS_XYPLOT are special in that the application can change the symbol drawn on the data point.

XYPlot Interaction
------------------

Only FL_ACTIVE_XYPLOT report mouse events by default. Clicking and dragging the data points (marked with little squares) will change the data and result in the object getting returned to the application (or the object's callback getting invoked). By default, the reporting happens only when the mouse is released. In some situations, reporting changes as soon as they happen might be desirable. To control when mouse events are returned use the function

     int fl_set_object_return(FL_OBJECT *obj, unsigned int when);

where when can have the folowing values:

FL_RETURN_NONE
     Never return or invoke callback.

FL_RETURN_END_CHANGED
     Return or invoke callback at end (mouse release) if one of the points has been moved to a different place. This is the default.

FL_RETURN_CHANGED
     Return or invoke callback whenever a point has been moved.

FL_RETURN_END
     Return or invoke callback at end (mouse release) regardless if a point has been moved is changed or not.

FL_RETURN_ALWAYS
     Return or invoke callback when a point has been moved or the mouse button has been release).

Please note: an object can also be in inspect mode (see function fl_set_xyplot_inspect() below). In this case the object gets returned (or its callback invoked) for all of the above settings except (FL_RETURN_NONE) when the mouse was released on top of one of the points.

To obtain the current value of the point that has changed, use the routine

     void fl_get_xyplot(FL_OBJECT *obj, float *x, float *y, int *i);

where via i the data index (starting from 0) is returned while via x and y the actual data point gets returned. If no point has changed i will be set to -1.

It is possible to switch drawing of the squares that mark an active plot on and off (default is on) using the following routine

     void fl_set_xyplot_mark_active(FL_OBJECT *obj, int yes_no);

with yes_no being set to false (0).

To set or replace the data for an xyplot, use

     void fl_set_xyplot_data(FL_OBJECT *obj, float *x, float *y, int n,
                             const char *title, const char *xlabel,
                             const char *ylabel);
     void fl_set_xyplot_data_double(FL_OBJECT *obj, double *x, double *y, int n,
                                    const char *title, const char *xlabel,
                                    const char *ylabel);

(The fl_set_xyplot_data_double() function allows to pass data of type double but which get "demoted" to float type when assigned to the xyplot object.) Here x, y is the tabulated function, and n is the number of data points. If the xyplot object being set already exists old data will be cleared. Note that the tabulated function is copied internally so you can free or do whatever you want with the x and y arrays after the function has returned. title is a title that is drawn above the XYPlot and xlabel and ylabel are the labels drawn at the x- and y-axes.

You can also load a tabulated function from a file using the routine

     int fl_set_xyplot_file(FL_OBJECT *obj, const char *filename,
                            const char *title, const char *xlabel,
                            const char *ylabel);

The data file should be an ASCII file consisting of data lines. Each data line must have two columns, indicating the (x,y) pair with a space, tab or comma separating the two columns. Lines that start with any of !, ; or # are considered to be comments and are ignored. The functions returns the number of data points successfully read or 0 if the file couldn't be opened.

To get a copy of the current XYPLot data, use

     int fl_get_xyplot_data_size(FL_OBJECT *obj);
     void fl_get_xyplot_data(FL_OBJECT *obj, float *x, *float y, int *n);

The first function returns the number of data points which the second will return. The caller must supply the space for the data returned by fl_get_xyplot_data(). The last argument of that function is again the number of points that got returned.

All XYPlot objects can be made aware of mouse clicks by using the following routine

     void fl_set_xyplot_inspect(FL_OBJECT *obj, int yes_no);

Once an XYPlot is in inspect mode, whenever the mouse is released and the mouse position is on one of the data point, the object is returned to the caller or its callback is invoked. You then can use fl_get_xyplot() to find out which point the mouse was clicked on. Note that for an object of type FL_ACTIVE_XYPLOT the data can't be modified while in inspect mode!

Another, perhaps even more general, way to obtain the values from an XYPlot is to use a posthandler or an overlay positioner. See demo xyplotall.c for the use of posthandler and positionerXOR.c for an example of reading-out xyplot values using an overlayed positioner.

Other XYPlot Routines
---------------------

There are several routines to change the appearance of an XYPlot. First of all, you can change the number of tic marks using the following routine

     void fl_set_xyplot_xtics(FL_OBJECT *obj, int major, int minor);
     void fl_set_xyplot_ytics(FL_OBJECT *obj, int major, int minor);

where major and minor are the number of tic marks to be placed on the axis and the number of divisions between major tic marks. In particular, -1 suppresses the tic marks completely while 0 restores the default settings (which is 5 for the major and 2 for the minor tic arguments).

Note that the actual scaling routine may choose a value other than that requested if it decides that this would make the plot look nicer, thus major and minor are only taken as a hint to the scaling routine. However, in almost all cases the scaling routine will not generate a major tic that differs from the requested value by more than 3.

Normally the minor tics of logarithmic scales are drawn equidistant. To have them also drawn logarithmically use the functions

     int fl_set_xyplot_log_minor_xtics(FL_OBJECT *obj, int yesno);
     int fl_set_xyplot_log_minor_ytics(FL_OBJECT *obj, int yesno);

With this enabled e.g., the minor tics between 1 and 10 (when the interval is to be divided into 5 subintervals) will be drawn at the positions 2, 4, 6, and 8 instead of at 10^0.2, 10^0.4, 10^0.6 and 10^0.8. The functions return the previous setting.

It is possible to label the major tic marks with alphanumerical characters instead of numerical values. To this end, use the following routines

     void fl_set_xyplot_alphaxtics(FL_OBJECT *obj, const char *major,
                                   const char *minor);
     void fl_set_xyplot_alphaytics(FL_OBJECT *obj, const char *major,
                                   const char *minor);

where major is a string specifying the labels with the embedded character | that specifies major divisions. For example, to label a plot with Monday, Tuesday etc, major should be given as "Monday|Tuesday|...".

Parameter minor is currently unused and the minor divisions are set to 1, i.e, no divisions between major tic marks. Naturally the number of major/minor divisions set by this routine and fl_set_xyplot_xtics() and fl_set_xyplot_ytics() can't be active at the same time and the one that gets used is the one that was set last.

The above two functions can also be used to specify non-uniform and arbitary major divisions. To achieve this you must embed the major tic location information in the alphanumerical text. The location information is introduced by the @ symbol and followed by a float or integer number specifying the coordinates in world coordinates. The entire location info should follow the label. For example, "Begin@1|3/4@0.75|1.9@1.9" will produce three major tic marks at 0.75, 1.0, and 1.9 with labels "3/4", "begin" and "1.9".

To get a gridded XYPlot use the following routines

     void fl_set_xyplot_xgrid(FL_OBJECT *obj, int xgrid);
     void fl_set_xyplot_ygrid(FL_OBJECT *obj, int ygrid);

where xgrid and ygrid can be one of the following

FL_GRID_NONE
     No grid.

FL_GRID_MAJOR
     Grid for the major divisions only.

FL_GRID_MINOR
     Grid for both the major and minor divisions.

The grid line by default is drawn using a dotted line, which you can change using the routine

     int fl_set_xyplot_grid_linestyle(FL_OBJECT *obj, int style);

where style is the line style (FL_SOLID, FL_DASH etc. See Drawing Objects, for a complete list). The function returns the old grid linestyle.

By default, the plotting area is automatically adjusted for tic labels and titles so that a maximum plotting area results. This can in certain situations be undesirable. To control the plotting area manually, the following routines can be used

     void fl_set_xyplot_fixed_xaxis(FL_OBJECT *obj, const char *lm,
                                    const char *rm)
     void fl_set_xyplot_fixed_yaxis(FL_OBJECT *obj, const char *bm,
                                    const char *tm)

where lm and rm specify the right and left margin, respectively, and bm and tm the bottom and top margins. The pixel amounts are computed using the current label font and size. Note that even for y-axis margins the length of the string, not the height, is used as the margin, thus to leave space for one line of text, a single character (say m) or two narrow characters (say ii) should be used.

To restore automatic margin computation, set all margins to NULL.

To change the size of the symbols drawn at data points, use the following routine

     void fl_set_xyplot_symbolsize(FL_OBJECT *obj, int size);

where size should be given in pixels. The default is 4.

For FL_POINTS_XYPLOT and FL_LINEPOINTS_XYPLOT (main plot or overlay), the application program can change the symbol using the following routine

     typedef void (*FL_XYPLOT_SYMBOL)(FL_OBJECT *, int id,
                                      FL_POINT *p, int n, int w, int h);
     FL_XYPLOT_SYMBOL fl_set_xyplot_symbol(FL_OBJECT *obj, int id,
                                           FL_XYPLOT_SYMBOL symbol);

where id is the overlay id (0 means the main plot, and you can use -1 to indicate all), and symbol is a pointer to the function that will be called to draw the symbols on the data point. The parameters passed to this function are the object pointer, the overlay id, the center of the symbol (p->x, p->y), the number of data points (n) and the preferred symbol size (w, h). If the type of the XYPlot corresponding to id is not FL_POINTS_XYPLOT or FL_LINESPOINTS_XYPLOT, the function will not be called.

To change for example a FL_LINEPOINTS_XYPLOT XYPlot to plot filled small circles instead of the default crosses, the following code could be used

     void drawsymbol(FL_OBJECT *obj, int id,
                     FL_POINT *p, int n, int w, int h) {
         int r = (w + h) / 4;
         FL_POINT *ps = p + n;

         for (; p < ps; p++)
             fl_circf(p->x, p->y, r, FL_BLACK);
     }

     ...
     fl_set_xyplot_symbol(xyplot, 0, drawsymbol);
     ...

If a Xlib drawing routine is used it should use the current active window (FL_ObjWin(obj)) and the current GC. Take care not to call routines inside the drawsymbol() function that could trigger a redraw of the XYPlot (such as fl_set_object_color(), fl_set_xyplot_data() etc.).

To use absolute bounds (as opposed to the bounds derived from the data), use the following routines

     void fl_set_xyplot_xbounds(FL_OBJECT *obj, double min, double max);
     void fl_set_xyplot_ybounds(FL_OBJECT *obj, double min, double max);

Data that fall outside of the range set this way will be clipped. To restore autoscaling, call the function with max and min set to exactly the same value. To reverse the axes (e.g., min at right and max at left), set min > max for that axis.

To get the current bounds, use the following routines

     void fl_get_xyplot_xbounds(FL_OBJECT *obj, float *min, float *max);
     void fl_get_xyplot_ybounds(FL_OBJECT *obj, float *min, float *max);

To replace the value of a particular point use the routine

     void fl_replace_xyplot_point(FL_OBJECT *obj, int index,
                                  double x, double y);

Here index is the index of the value to be replaced. The first value has an index of 0.

It is possible to overlay several plots together by calling

     void fl_add_xyplot_overlay(FL_OBJECT *obj, int id, float *x, float *y,
                                int npoints, FL_COLOR col);

where id must be between 1 and FL_MAX_XYPLOTOVERLAY (currently 32). This limit can be raised (or lowered) by calling the function fl_set_xyplot_maxoverlays(). Again, the data are copied to an internal buffer (old data are freed if necessary).

As for the base data, a data file can be used to specify the (x,y) function

     int fl_add_xyplot_overlay_file(FL_OBJECT *obj, int ID,
                                    const char *file, FL_COLOR col);

The function returns the number of data points successfully read. The type (FL_NORMAL_XYPLOT etc.) used in overlay plot is the same as the object itself.

To change an overlay style, use the following call

     void fl_set_xyplot_overlay_type(FL_OBJECT *obj, int id, int type);

Note that although the API of adding an overlay is similar to adding an object, an XYPlot overlay is not a separate object. It is simply a property of an already existing XYPlot object.

To get the data of an overlay, use the following routine

     void fl_get_xyplot_overlay_data(FL_OBJECT *obj, int id,
                                     float x[], float y[], int *n);

where id specifies the overlay number between 1 and FL_MAX_XYPLOTOVERLAY or the number set via fl_set_xyplot_maxoverlays() (see below). (Actually, when id is zero, this function returns the base data). The caller must supply the storage space for the data. Upon function return, n will be set to the number of data points retrieved.

Sometimes it may be more convenient and efficient to get the pointer to the data rather than a copy of the data. To this end, the following routine is available

     void fl_get_xyplot_data_pointer(FL_OBJECT *obj, int id,
                                     float **x, float **y, int *n);

Upon function return, x and y are set to point to the data storage. You're free to modify the data and redraw the XYPlot (via fl_redraw_object()). The pointers returned may not be freed.

If needed, the maximum number of overlays an object can have (which by default is 32) can be changed using the following routine

     int fl_set_xyplot_maxoverlays(FL_OBJECT *obj, int maxoverlays);

The function returns the previous maximum number of overlays. If the new number is smaller that what it was before overlays with IDs higher that the previous number are deleted.

To obtain the number of data points, use the routine

     int fl_get_xyplot_numdata(FL_OBJECT *obj, int id);

where id is the overlay ID (with 0 being the base data set).

To insert a point into an xyplot, use the following routine

     void fl_insert_xyplot_data(FL_OBJECT *obj, int id, int n,
                                double x, double y);

where id is the overlay ID; n is the index of the point after which the data new point specified by x and y is to be inserted. Set n to -1 to insert the point in front. To append to the data, set n to be equal or larger than the return value of fl_get_xyplot_numdata(obj, id).

To delete an overlay, use the following routine

     void fl_delete_xyplot_overlay(FL_OBJECT *obj, int id);

It is possible to place inset texts on an XYPlot using the following routine (up to FL_MAX_XYPLOTOVERLAY or the value set via fl_set_xyplot_maxoverlays() of such insets can be accommodated):

     void fl_add_xyplot_text(FL_OBJECT *obj, double x, double y,
                             const char *text, int align, FL_COLOR col);

where x and y are the (world) coordinates where text is to be placed and align specifies the placement options relative to the specified point (See fl_set_object_lalign() for valid options). If you for example specify FL_ALIGN_LEFT, the text will appear on the left of the point and flushed toward the point (see Fig. 21.1). This is mostly consistent with the label alignment except that now the bounding box (of the point) is of zero dimension. Normal text interpretation applies, i.e., if text starts with @ a symbol is drawn.

To remove an inset text, use the following routine

     void fl_delete_xyplot_text(FL_OBJECT *obj, const char *text);

Another kind of inset is the "keys" to the plots. A key is the combination of drawing a segment of the plot line style with a piece of text that describes what the corrsponding line represents. Obviously, keys are most useful when you have more than one plot (i.e., overlays). To add a key to a particular plot, use the following routine

     void fl_set_xyplot_key(FL_OBJECT *obj, int id, const char *keys);

where id again is the overlay ID. To remove a key, set the key to NULL. All the keys will be drawn together inside a box. The position of the keys can be set via

     void fl_set_xyplot_key_position(FL_OBJECT *obj, float x, float y,
                                     int align)

where x and y should be given in world coordinates. align specifies the alignment of the entire key box relative to the given position (see Fig.21.1).

The following routine combines the above two functions and may be more convenient to use

     void fl_set_xyplot_keys(FL_OBJECT *obj, char *keys[],
                              float x, float y, int align);

where keys specifies the keys for each plot. The last element of the array must be NULL to indicate the end. The array index is the plot id, i.e., key[0] is the key for the base plot, key[1] the key for the the first overlay etc.

To change the font the key text uses, the following routine is available

     void fl_set_xyplot_key_font(FL_OBJECT *obj, int style, int size);

Data may be interpolated using an nth order Lagrangian polynomial:

     void fl_set_xyplot_interpolate(FL_OBJECT *obj, int id, int degree,
                                    double grid);

where id is the overlay ID (use 0 for the base data set); degree is the order of the polynomial to use (between 2 and 7) and grid is the working grid onto which the data are to be interpolated. To restore the default linear interpolation, use degree set to 0 or 1.

To change the line thickness of an xyplot (base data or overlay), the follow routine is available:

     void fl_set_xyplot_linewidth(FL_OBJECT *obj, int id, int width);

Again, use a id of value 0 to indicate the base data. Setting width to zero restores the server default and typically is the fastest.

By default, a linear scale in both the x and y direction is used. To change the scaling, use the following call

     void fl_set_xyplot_xscale(FL_OBJECT *obj, int scale, double base);
     void fl_set_xyplot_yscale(FL_OBJECT *obj, int scale, double base);

where the valid scaling options for scale are qFL_LINEAR and FL_LOG, and base is used only for FL_LOG and in that case is the base of the logarithm to be used.

Use the following routine to clear an xyplot

     void fl_clear_xyplot(FL_OBJECT *obj);

This routine frees all data associated with an XYPlot, including all overlays and all inset texts. This routine does not reset all plotting options, such as line thickness, major/minor divisions etc. nor does it free all memories associated with the XYPlot, for this fl_free_object() is needed.

The mapping between the screen coordinates and data can be obtained using the following routines

     void fl_get_xyplot_xmapping(FL_OBJECT *obj, float *a, float *b);
     void fl_get_xyplot_xmapping(FL_OBJECT *obj, float *a, float *b);

where a and b are the mapping constants and are used as follows:

     screenCoord = a * data + b                 (linear scale)
     screenCoord = a * log(data) / log(p) + b   (log scale)

where p is the base of the requested logarithm.

If you need to do conversions only occasionally (for example, converting the position of a mouse click to a data point or vice versa) the following routines might be more convenient

     void fl_xyplot_s2w(FL_OBJECT *obj, double sx, double sy,
                        float *wx, float *wy);
     void fl_xyplot_w2s(FL_OBJECT *obj, double wx, double wy,
                        float *sx, float *sy);

where sx and sy are the screen coordinates and wx and wy are the world coordinates.

Finally, there's a function for returning the coordinates of the area of the object used for drawing the data (i.e., the area, when axes are displayed, which is enclosed by the axes):

     void fl_get_xyplot_screen_area(FL_OBJECT *obj,
                                    FL_COORD *llx, FL_COORD *lly,
                                    FL_COORD *urx, FL_COORD *ury);
     void fl_get_xyplot_world_area(FL_OBJECT *obj,
                                   float *llx, float *lly,
                                   float *urx, float *ury);

where via llx and lly the coordinates of the lower left hand corner and via urx and ury those of the upper right hand corner are returned. The first function returns the corner positions in screen coordinates (relative to the object), while the secoind returns them in "world" coordinates.

Per default an XYPlot object only reacts to the left mouse button. But sometimes it can be useful to modify this. To set this call

     void fl_set_xyplot_mouse_buttons(FL_OBJECT *obj,
                                      int mbuttons);

mbuttons is the bitwise OR of the numbers 1 for the left mouse button, 2 for the middle and 4 for the right mouse button.

To determine which mouse buttons an XYPlot object reacts to use

     void fl_get_xyplot_mouse_buttons(FL_OBJECT *obj,
                                      unsigned int *mbuttons);

The value returned via mbuttons is the same value as would be used in fl_set_slider_mouse_buttons().

XYPlot Attributes
-----------------

Don't use FL_NO_BOX as the boxtype of an XYPlot object that is to be changed dynamically. To change the font size and style for the tic labels, inset text etc., use fl_set_object_lsize() and fl_set_object_lstyle().

The first color argument (col1) to fl_set_object_color() controls the color of the box and the second (col2) the actual XYPlot color.

Remarks
-------

The interpolation routine is public and can be used in the application program

     int fl_interpolate(const float *inx, const float *iny, int num_in,
                        float *outx, float *outy, double grid, int ndeg);

If successful, the function returns the number of points in the interpolated function ((inx[num_in - 1] - inx[0]) / grid + 1.01), otherwise it returns -1. Upon return, outx and outy are set to the interpolated values. The caller must allocate the storage for outx and outy.

See xyplotall.c and xyplotactive.c for examples of the use of XYPlot objects. There is also an example program called xyplotover.c, which shows the use of overlays. In addition, xyplotall.c shows a way of getting all mouse clicks without necessarily using an active XYPlot.

It is possible to generate a PostScript output of an XYPlot. See the function fl_object_ps_dump() documented in Part V.

Canvas Object
=============

A canvas is a managed plain X (sub)window. It it different from the free object in that a canvas is guaranteed to be associated with a window that is not shared with any other object, thus an application program has more freedom in utilizing a canvas, such as using its own colormap or rendering double-buffered OpenGL in it etc. A canvas is also different from a raw application window because a canvas is decorated differently and its geometry is managed, e.g., you can use fl_set_object_resize() to control its position and size after its parent form is resized.

You also should be aware that when using a canvas you'll probably mostly program directly using basic Xlib functions, XForms doesn't supply much more than a few helper functions. You'll rather likely draw to it with Xlib functions and will be dealing with XEvents yourself (instead having them taken care of by XForms and cenverted to some simpler to use events that then just return the object from fl_do_forms() or invoke an associated callback function. Thus you will typically need a basic knowledge of how to program via the X11 Xlib.

Adding Canvas Objects
---------------------

Adding an object To add a canvas to a form you use the routine

     FL_OBJECT *fl_add_canvas(int type, FL_Coord x, FL_Coord y,
                              FL_Coord w, FL_Coord h, const char *label);

The meaning of the parameters is as usual. The label is not drawn but used as the window name for possible resource and playback purposes. If label is empty, the window name will be generated on the fly as flcanvasn, where n = 0, 1,....

Canvas Types
------------

The only types of canvases currently available is FL_NORMAL_CANVAS.

Canvas Interaction
------------------

The canvas class is designed to maximize the programmer's ability to deal with situations where standard form classes may not be flexible enough. With canvases, the programmer has complete control over everything that can happen to a window. It thus doesn't work like other objects that get returned by fl_do_forms() etc. or have their callbacks invoked.

Instead the user can request that for specific X events (not XForms object events like FL_PRESS, FL_KEYPRESS etc.!) callbacks are invoked that receive all information about the XEvent that led to their invocation. This obviously requires some understanding of how the X Window system works.

The interaction with a canvas is typically set up as follows. First, you register the X events you're interested in and their handlers using the following routine

     typedef int (*FL_HANDLE_CANVAS)(FL_OBJECT *obj, Window win,
                                     int win_width, int win_height,
                                     XEvent *xev, void *user_data);
     void fl_add_canvas_handler(FL_OBJECT *obj, int event,
                                FL_HANDLE_CANVAS handler, void *user_data);

where event is the XEvent type, e.g., Expose etc. The fl_add_canvas_handler() function first registers a procedure with the event dispatching system of the Forms Library, then it figures out the event masks corresponding to the event event and invokes fl_addto_selected_xevent() to solicit the event from the server. Other book keeping (e.g., drawing the box that encloses the canvas, etc.) is done by the object handler.

When a canvas handler is installed the library tries to set the correct mask for the the XEvent (which then tells the X Window system which events to pass on to the Forms Library). But since translation from an XEvent to an XEvent mask is not unique, the default translation of the XEvent to a mask may or may not match exactly the intention of the application. Two events, namely MotionNotify and ButtonPress, are likely candidates that need further clarification from the application. There are two functions to add or delete from the mask, fl_addto_selected_xevent() and fl_remove_selected_xevent().

By default, when a mouse motion handler (i.e., for the MotionNotify events) is registered, it is assumed that, while the application wants to be informed about mouse movements, it's not interested in a continous motion monitoring (tracking), thus per default MotionNotify events are requested with PointerMotionHintMask being set in the mask to reduce the number of events generated. If this is not the case and in fact the application wants to use the mouse motion as some type of graphics control, the default behavior would appear "jerky" as not every mouse motion is reported. To change the default behavior so that every mouse motion is reported, you need to call fl_remove_selected_xevent() with mask set to PointerMotionHintMask. Furthermore, the mouse motion is reported regardless if a mouse button is pressed or not. If the application is interested in mouse motion only when a mouse button is pressed fl_remove_selected_xevent() should be called with a mask of PointerMotionMask|PointerMotionHintMask.

With ButtonPress events you need to call fl_addto_selected_xevent() with a mask of OwnerGrabButtonMask if you are to add or remove other canvas handlers in the button press handler.

To remove a registered handler, use

     void fl_remove_canvas_handler(FL_OBJECT *obj, int event,
                                   FL_CANVAS_HANDLER handler);

After this function call the canvas ceases to receive the events for event. The corresponding default bits in the XEvent mask as were set by fl_add_canvas_handler() are cleared. If you added extra ones with fl_addto_selected_xevent() you should reset them using fl_remove_selected_xevent().

To obtain the window ID of a canvas, use

     Window fl_get_canvas_id(FL_OBJECT *obj);

or use the generic function (macro) (recommended)

     Window FL_ObjWin(FL_OBJECT *obj);

Of course, the window ID only has a meaning after the form/canvas is shown. When the canvas or the form the canvas is on is hidden (via fl_hide_object() or fl_hide_form()), the canvas window may be destroyed. If the canvas is shown again, a new window ID for the canvas may be created. Thus recording the canvas window ID in a static variable is not the right thing to do. It is much safer (and it doesn't add any run-time overhead) to obtain the canvas window ID via FL_ObjWin() whenever it's needed. If your application must show and hide the canvas/form repeatedly, you might consider to "unmap" the window, a way of removing the window from the screen without actually destroying it and later re-mapping the window to show it. The Xlib API functions for doing this are XUnmapWindow() and XMapWindow(). Both require two arguments. the display, which you can determine by calling fl_get_display() and the window ID, which can be obtained by using form->window if you want to (un)map a form or FL_ObjWin(obj) for a canvas.

Other Canvas Routines
---------------------

Upon canvas creation, all its window related attributes, e.g., visual, depth and colormap etc., are inherited from its parent (i.e., the window of the form the canvas belongs to). To modify any attributes of the canvas, use the following routine

     void fl_set_canvas_attributes(FL_OBJECT *obj, unsigned mask,
                                   XSetWindowAttributes *xswa);

See XSetWindowAttributes() for the definition of the structure members. Note that this routine should not be used to manipulate events.

Other functions exists that can be used to modify the color/visual property of a canvas:

     void fl_set_canvas_colormap(FL_OBJECT *obj, Colormap map);
     Colormap fl_get_canvas_colormap(FL_OBJECT *obj);
     void fl_set_canvas_visual(FL_OBJECT *obj, Visual *vi);
     void fl_set_canvas_depth(FL_OBJECT *obj, int depth);
     int fl_get_canvas_depth(FL_OBJECT *obj);

Note that changing visual or depth does not generally make sense once the canvas window is created (which happens when the parent form is shown). Also, typically if you change the canvas visual, you probably should also change the canvas depth to match the visual.

Caution should also applied when using fl_set_canvas_colormap(): when the canvas window goes away, e.g., as a result of a call of fl_hide_form(), the colormap associated with the canvas is freed (destroyed). This likely will cause problems if a single colormap is used for multiple canvases as each canvas will attempt to free the same colormap, resulting in an X error. If your application works this way, i.e., the same colormap is used on multiple canvases (via fl_set_canvas_colormap()), you should use the following routine to prevent the canvas from freeing the colormap:

     void fl_share_canvas_colormap(FL_OBJECT *obj, Colormap colormap);

This function works the same way as fl_set_canvas_colormap() except that it also sets a internal flag so the colormap isn't freed when the canvas goes away.

By default, canvases are decorated with an FL_DOWN_FRAME. To change the decoration, change the the boxtype of the canvas and the boxtype will be translated into a frame that best approximates the appearance of the request boxtype (e.g., a FL_DOWN_BOX is translated into a FL_DOWN_FRAME etc). Note that not all frame types are appropriate for decorations.

The following routine is provided to facilitate the creation of a colormap appropriate for a given visual to be used with a canvas:

     Colormap fl_create_colormap(XVisualInfo *xvinfo, int n_colors);

where n_colors indicates how many colors in the newly created colormap should be filled with XForms' default colors (to avoid flashing effects). Note however, that the colormap entry 0 is allocated with either black or white even if you specify 0 for n_colors. To prevent this from happening (so you get a completely empty colormap), set n_colors to -1. See Drawing Objects, on how to obtain the XVisualInfo for the window. Depending on the window manager, a colormap other than the default may not get installed correctly. If you're working with such a window manager, you may have to install the colormap yourself when the mouse pointer enters the canvas using XInstallColormap().

By default, objects with shortcuts appearing on the same form as the canvas will "steal" keyboard inputs if they match the shortcuts. To disable this feature, use the following routine with a false (0) value for yes_no:

     void fl_canvas_yield_to_shortcut(FL_OBJECT *obj, int yes_no);

To clear the canvas use

     void fl_clear_canvas(FL_OBJECT *obj);

If fl_set_object_color() gas been called on the object the first color passed to the function will be used to draw the background of the color, otherwise it's drawn in black.

Canvas Attributes
-----------------

Some of the attributes, such as boxtype, do not apply to the canvas class.

The first color argument (col1) to fl_set_object_color() can be used to set the background color of the canvas (by default, a canvas has no background color). The second argument (col2) controls the decoration color (if applicable).

OpenGL Canvas
-------------

Deriving specialized canvases from the general canvas object is possible. See the next subsection for general approaches how this is done. The following routines work for OpenGL (under X) as well as Mesa, a free OpenGL clone.

To add an OpenGL canvas to a form, use the following routine

     FL_OBJECT *fl_add_glcanvas(int type, FL_Coord x, FL_Coord y,
                                FL_Coord w, FL_Coord h, const char *label);

where type is the same as for a normal canvas. A "glcanvas" created this way will have the following attributes by default

     GLX_RGBA,
     GLX_DEPTH_SIZE: 1,
     GLX_RED_SIZE: 1, GLX_GREEN_SIZE: 1, GLX_BLUE_SIZE: 1,
     GLX_DOUBLEBUFFER

The application program can modify these defaults using the following routine (before the creation of glcanvases)

     void fl_set_glcanvas_defaults(const int *attributes);

See glXChooseVisual() for a list of valid attributes.

To get the current defaults use

     void fl_get_glcanvas_defaults(int *attributes);

It is also possible to change the attributes on a canvas by canvas basis by utilizing the following routine:

     void fl_set_glcanvas_attributes(FL_OBJECT *obj, const int *attributes);

Note that this routine can be used to change a glcanvas attributes on the fly even if the canvas is already visible and active.

To obtain the attributes of a particular canvas, use the following routine

     void fl_get_glcanvas_attributes(FL_OBJECT *obj, int attributes[]);

The caller must supply the space for the attribute values.

To obtain the the glx context (for whatever purposes), use

     GLXContext fl_get_glcanvas_context(FL_OBJECT *obj);

Note that by default the rendering context created by a glcanvas uses direct rendering (i.e., by-passing the Xserver). To change this default, i.e., to always render through the Xserver, use the following routine:

     void fl_set_glcanvas_direct(FL_OBJECT *obj, int yes_no);

with the argument yes_no set to false (0).

Remember that OpenGL drawing routines always draw into the window the current context is bound to. For application with a single canvas, this is not a problem. In case of multiple canvases, the canvas driver takes care of setting the proper context before invoking the expose handler. In some cases, the application may want to draw into canvases actively. In this case, explicit drawing context switching may be required. To this end, use the following routine

     void fl_activate_glcanvas(FL_OBJECT *obj);

before drawing into glcanvas object.

Finally there is a routine that can be used to obtain the XVisual information that is used to create the context

     XVisualInfo *fl_get_glcanvas_xvisualinfo(FL_OBJECT *obj);

See demo program gl.c for an example use of a glcanvas.