Debian Codegraph @

HOWTOs/Quad-GTK.asciidoc

raw
1
2 // vim: et:ts=4:sw=4
3
4 = The GNU APL *⎕GTK* Cookbook
5 :toc:
6 :toclevels: 4
7
8 :Author: Jürgen Sauermann, GNU APL
9 :page-width: 90em
10
11 ////
12 make window visible, then
13
14 scrot --border -d 5 -u
15
16 and move mouse to window within 5 seconds
17
18 -or- for glade XML:
19
20 { cat << ENDCAT
21 <?xml version= ...
22 ENDCAT
23 } | glade-previewer -f /dev/stdin --screenshot glad-XXX.png
24 ////
25
26 == Abstract
27
28 ⎕GTK is a GNU APL system function that allows an APL program to create and
29 control a graphical user interface (GUI). The GUI is based on Gtk+ (Gimp
30 Toolkit) version 3+ (aka. GTK 3+). This document describes, by means of
31 simple examples, how *⎕GTK* based GUIs can be created and managed from GNU APL.
32
33 == Philosophy
34
35 A modern GUI such as Gtk provides a powerful API for controlling almost every
36 aspect of the GUI. A consequence of that power is an API that consists of
37 thousands of functions. The entire Gtk API is spread over 11 different
38 libraries:
39
40 ----
41 $ pkg-config gtk+-3.0 --libs
42 -lgtk-3 -lgdk-3 -latk-1.0 -lgio-2.0 -lpangocairo-1.0 -lgdk_pixbuf-2.0
43 -lcairo-gobject -lpango-1.0 -lcairo -lgobject-2.0 -lglib-2.0
44 ----
45
46 Each library contains tens, hundreds, or even thousands of symbols. Every
47 symbol represents either a function or a variable, and the vast majority of
48 symbols in the different libraries represent functions.
49
50 .Gtk API Symbols
51 [options="header, footer"]
52 [width="60%"]
53 |===============
54 | Gtk Library | Number of Symbols
55 | libgtk-3.so | 4176
56 | libgdk-3.so | 632
57 | libatk-1.0.so | 265
58 | libgio-2.0.so | 1872
59 | libpangocairo-1.0.so | 33
60 | libgdk_pixbuf-2.0.so | 117
61 | libcairo-gobject.so | 33
62 | libpango-1.0.so | 405
63 | libcairo.so | 395
64 | libgobject-2.0.so | 427
65 | libglib-2.0.so | 1595
66 | TOTAL | 9950
67 |===============
68
69 These numbers suggest that mapping every Gtk function to a corresponding APL
70 function would create an almost unusable API at the APL level. Even the
71 approach used for ⎕FIO or ⎕SQL - using function numbers as APL axis elements -
72 reaches its limits when used with almost 10000 functions.
73
74 Now, the huge number of API functions in the different Gtk libraries contrasts
75 considerably with the moderate number of widgets (around 80) in a GUI and even
76 more with the number of actions (like clicking, marking text, typing text, etc.)
77 that a user can do with each of the widgets.
78
79 If we look at the program *glade*, which is the default tool for constructing
80 Gtk based GUIs, then we see that there are 12 top-level widgets
81 (aka. "windows"), 20 containers (widgets containing other widgets), and 36
82 control widgets (most of them variants of the same base widget, like different
83 types of buttons).
84
85 This discrepancy between the huge number of functions provided by Gtk and
86 rather small number of things that a user can do (like: click on a button,
87 select an item in a selection box, enter text in some text entry, etc.)
88 or perceive (color, font, etc.) suggests that there might be a clever way to
89 control a GUI without mapping each of the almost 10000 Gtk functions to a
90 corresponding APL function in a 1:1 fashion.
91
92 ⎕GTK uses a rigorous approach to reduce the number of functions:
93
94 * Every GUI must be described by a suitable *XML file* or *XML string*.
95 ** Suitable *XML files* can be created with the GUI construction tool *glade*
96 (which comes with GTK), while
97 ** suitable *XML strings* can be constructed programmatically in APL (see
98 workspace *SQL_GUI* which contains examples for *⎕GTK* and *⎕SQL*).
99 //-
100 This requirement reduces the need for all functions that are concerned with
101 the instantiation of the GUI elements and their properties. It also speeds
102 up the design of the GUI itself.
103
104 * To the extent possible, visual widget aspects that are usually static (i.e.
105 that do not change over time) such as colors are required to be specified
106 with CSS (Cascading Style Sheets). This requirement eliminates the need
107 for the corresponding GTK functions that would otherwise control these
108 aspects, which further reduces the number of Gtk API functions needed.
109 It also speeds up the design of the GUI itself. The downside is a somewhat
110 static look-and-feel of the GUI, because, for example, colors cannot be
111 changed after the GUI was instantiated. However, the benefit of fancy
112 dynamic GUIs (if any) seems not to justify the complexity in the API
113 that would be needed to support them.
114
115 * Implementation on demand. *⎕GTK* starts with a rather small (and therefore
116 incomplete) set of GTK widgets and events, but has a simple way to extend
117 that set. The mapping between *⎕GTK* on one side and libgtk functions and
118 events on the other side is defined in a single macro file *Gtk/Gtk_map.def*
119 that can be easily extended to accommodate new widgets and signals,
120
121 == Architecture
122
123 The philosophy above has been implemented in the following architecture.
124
125 . The Gtk GUI itself has been implemented in a separate process running the
126 program *Gtk_server*. The Gtk_server is linked with the different Gtk
127 libraries, so that Gtk itself remains outside GNU APL.
128
129 . The *Gtk_server* is started by *⎕GTK*, and after that *⎕GTK* communicates with
130 Gtk_server over a socket pair. The communication consists of a sequence of
131 TLV (Tag/Length/Value) buffers encoded with 33 ⎕CR and decoded with 34 ⎕CR
132 (aka. ¯33 ⎕CR) at the APL end. A user action (e.g. a button click) results
133 in an "event" (= a TLV buffer) received by APL while a "command" (sent from
134 APL to the Gtk_server results in some change in the GUI. However, many
135 details such as a button changing its form or its color when being pressed
136 are handled by the Gtk_server server process (one of the Gtk libraries) and
137 are not communicated to APL. The encoding and decoding of TLVs that are
138 exchanged between *apl* and *Gtk_server*) takes place inside *⎕GTK* so that
139 the APL programmer is not concerned with the details of this communication.
140
141 ----
142 ╔════════════════════════════╗
143 ║ GUI-description.xml file ║
144 ║ ↓ GUI-stylesheet.css file ║
145 ║ ↓ ↓ ║
146 ║ ↓ ↓ ┌───────────────┐ ║
147 ║ ↓ ↓ │ GTK GUI │ ║
148 ╔════════════════╗ Commands ║ ↓ ↓ └─┬─────────┬┬──┘ ║
149 ║ GNU APL ┌──╨───┐ 33⎕CR → → → socket ║┌──────────┴─┐ ┌───┼┴────┐║
150 ║ application │ ⎕GTK ├───────────────────────-----────╫┤ Gtk_server │ ┌─┴───┴────┐│║
151 ║ program.apl └───╥──┘ 34⎕CR ← ← ← pair ║└────────────┘ │ GTK libs ├┘║
152 ╚═════════════════╝ Responses, Events ║ └──────────┘ ║
153 ╚════════════════════════════╝
154 ----
155 [start=3]
156 . One Gtk_server handles a single top-level window and its children (see also
157 <<TAG_caveats, Caveats>>.
158 . For GUIs that consist of multiple top-level windows, one apl interpreter
159 process can start several Gtk_server processes.
160
161 == Development Work-flow
162
163 The architecture above leads to the following work-flow.
164
165 1. The programmer specifies the GUI by means of the *glade* GUI design tool
166 that comes with Gtk. The result is an XML file that describes the GUI. The
167 XML file can be changed later on as needed, so that the programmer can
168 start with a subset of the GUI functionality and then extend that
169 functionality in an incremental fashion.
170
171 2. The programmer writes a CSS specification for the widgets in the GUI.
172 The CSS file specifies the styling (i.e. colors. sizes etc.) of the
173 widgets. In theory, this step is optional, but in practice it is inevitable
174 for a somewhat good-looking GUI.
175
176 3. The programmer writes a brief start-up routine for the GUI in which the
177 files created in steps 1. and 2. above are loaded into the GUI.
178
179 4. The programmer displays the GUI - either at the start of the APL
180 application if the GUI shall be permanently visible or at some later time
181 if the GUI is, for example, only popped up to request input from the user
182 of the APL application. In the latter case the GUI is a single window
183 (a "modal dialog") which is polled from APL until some final action of the
184 user has occurred, while the former case the APL application has to poll
185 the GUI for events at rather short intervals. To poll *⎕GTK* at regular
186 intervals:
187
188 ----
189 ╔══════════════════════╗
190 ║ GUI Design (glade) ║ → my-application.ui
191 ╚══════════╤═══════════╝
192 │
193 ╔══════════╧═══════════╗
194 ║ Widget Details (CSS) ║ → my-application.css
195 ╚══════════╤═══════════╝
196 │
197 ╔══════════╧═══════════╗
198 ║ APL application ║ → my-application.apl
199 ║ ──────────────────── ║
200 ║ GUI start ║ → loads my-application.ui and my-application.css
201 ║ ──────────────────── ║
202 ║ GUI event loop ║ → polls and reacts to events (user actions)
203 ╚══════════════════════╝
204 ----
205
206 The example given below will be a modal dialog with the non-modal case left
207 as an exercise for the reader.
208
209 == Principles
210
211 As may have become obvious by now, there isn't much coding left to be done
212 for the APL application. After APL has started the GUI, the process running
213 GNU APL and the Gtk_server send "signals" to each other in an asynchronous
214 fashion and according to the following rules:
215
216 * Every APL application that has a GUI (and uses *⎕GTK*) starts its own
217 Gtk_server(s). In a GUI with several top-level windows, each top-level
218 window uses its own Gtk_server which is identified by an integer (handle) in
219 APL. Multiple Gtk_servers are independent of each other, and the coordination
220 of events between the windows must be performed in the APL application.
221 * GNU APL and Gtk_server then send signals (aka, TLV buffers) to each other. A
222 signal is a sequence of bytes, starting with a 4-byte tag, followed by a
223 4-byte data length, and concluded with 0 or more data bytes as indicated by
224 the signal length.
225 * The encoding of the signals is the same in both directions, but we call
226 signals from APL to Gtk_server *commands* and signals from Gtk_server to APL
227 either *responses* (if they contain the result of a prior command), or else
228 *events* (which are caused by a user's activity such as clicking a button.
229 ** Commands are used to modify the GUI in some way, for example to enter an
230 initial value into a text-entry widget.
231 ** Events are sent by the Gtk_server upon final user actions such as pushing a
232 button, or pressing ENTER after having modified the text in a text-entry
233 widget.
234 * Normally larger amounts of data are not sent in events, but in command
235 responses. Assume, for example, a user has entered some (possibly larger)
236 text into a (hypothetical) text-editor widget and leaves the text-editor.
237 The text-editor would then only send an event to APL indicating that some
238 new text is available. The new text itself, however, is not packed into that
239 event but needs to be fetched from the text-editor widget in the Gtk_server
240 by means of a corresponding retrieval command. The new text is then sent from
241 the Gtk_server to APL in the response to the retrieval command. In other
242 words, larger amounts of data are usually pulled by apl from a Gtk_server
243 rather than pushed by the Gtk_server into APL. The reasons for this approach
244 are:
245 ** the retrieval commands are usually needed anyway. It is often easier
246 to specify the initial content of a widget in *glade* than to set it from
247 the APL application and,
248 ** the events become more uniform (not differing by different types of
249 content). This, in turn, allows the same event to be used by different
250 widgets that differ only by the type of data that they produce.
251 * As a consequence, most events contain only the type of event and the widget
252 that has sent the event.
253 * Every signal is a TLV buffer whose length is dictated by the length of the
254 Value component. Such a TLV buffer is therefore already determined by an
255 integer tag and the value bytes V; the length is then ⍴V. In APL it is
256 therefore sufficient to specify only T and V as a vector TV←Tag,Value whose
257 first element Tag = ↑TV identifies a particular command or event, and the
258 rest 1↓TV is a (frequently empty) argument of that command or event. The
259 GNU APL system functions 33 ⎕CR and 34 ⎕CR have been tailored to encode and
260 decode tag/value vectors TV to/from respectively the TLV buffers exchanged
261 between APL and Gtk_server.
262 * Sending of a TLV from APL to Gtk_server is done by encoding the TLV with 33
263 ⎕FIO TLV, followed by a single write() (similar to ⎕FIO[42]) onto the
264 connection (the "Handle") between APL and Gtk_server. Sending of only part
265 of a TLV (for example, first the tag in one write() and then the length and
266 the value in a second write()) is not allowed in either direction because
267 that would hang the other side. That tags are divided into the following
268 ranges:
269 ** 1...999: commands that have no response
270 ** 1001...1999: commands that have a response (i.e. that expect a result)
271 ** -1999...-1000 error indications for commands 1000...1999. If command
272 1xxx fails in Gtk_server, then Gtk_server sends -1xxx to APL.
273 ** 2001-2999: responses (2xxx is the response for command 1xxx)
274 ** 3001-3999: event classes. They tell *⎕GTK* how to decode the data supplied
275 with the tag and how to present that data (event name, widget, possibly
276 X/Y coordinates of mouse events, etc.) to APL.
277
278 * Receiving from Gtk_server is done with a single read() call (like ⎕FIO[43])
279 from the handle followed by decoding the received bytes with 34 ⎕CR.
280
281 [icon="/usr/share/asciidoc/icons/note.png"]
282 NOTE: the details of TLV encoding and tag ranges are only mentioned for
283 completeness and are not needed by the APL programmer.
284
285 == Detailed Example
286
287 In the following, the implementation of a simple GUI will be described
288 step-by-step. The GUI will consist of a window that contains two labels (=
289 fixed texts), two text entry boxes, and a button that the user can push to end
290 the text entry.
291
292 === Step 1: Defining the GUI with Glade
293
294 Start *glade* without a filename:
295
296 ----
297 $ glade
298 ----
299
300 A window with four larger areas pops up:
301
302 image::glade-0.png[]
303
304 The four areas are:
305
306 1. A *widget selection area* on the left,
307 2. A *GUI visualization* in the middle (empty)
308 3. A *GUI structure* on the (top-) right (empty), and
309 4. A *widget property area* on the (bottom-) right (empty).
310
311 NOTE: recent *glade* versions look slightly different, for example the widget
312 selection area has been replaced by drop-down menus. However, the description
313 given here should suffice to briefly explain *glade*. For *glade alternatives*,
314 see also <<TAG_programmatically, Chapter 8 Specifying GUIs Programmatically>>
315 below.
316
317 The *widget selection area* is further divided into several widget groups named
318
319 * Actions,
320 * Toplevels,
321 * Containers,
322 * Control and Display, and
323 * GTK+ Unix Print Toplevels
324
325 [icon="/usr/share/asciidoc/icons/tip.png"]
326 TIP: If you move the mouse pointer over one of the widgets, then the widget
327 is highlighted and a tool-tip showing the type of the widget pops up.
328
329
330 === Step 1a: Add top-level Window
331
332 Drag the first widget of type *Window* from the Toplevels group and drop
333 it into the *GUI visualization area*. That is, move the mouse pointer
334 over the widget, push and hold down the left mouse button, move the mouse
335 pointer to the *GUI visualization area* in the middle, and release the
336 mouse button.
337
338 You will now see a new rectangular area in the *GUI visualization area*,
339 a widget item named *window1* in the *GUI structure*, and
340 the properties of the new widget below.
341
342 Your GUI now consists of one widget. You see the grid as child *grid1* of
343 *window1* in the *GUI structure*.
344
345 === Step 1b: Add a positioning Grid
346
347 Next, drag the widget of type *Grid* onto the *window1* in the
348 middle and enter 6 rows / 10 columns in the dialog that pops up.
349
350 This grid is a helper-widget for controlling the placement of other widgets
351 inside *window1*.
352
353 === Step 1c: Add labels and text entry widgets to the positioning Grid
354
355 Next, drag the widget of type *Label* from the "Control and Display" group
356 onto row 2, column 2 of the grid and another one of type *Label* onto row 3,
357 column 2 of the grid. Similarly, drag 2 widgets of type "Text Entry" to
358 rows 2 and 3, column 4,
359
360 Unfortunately this makes the grid uneven because the newly placed widgets are
361 larger than the fields in the grid. You can fix that by:
362
363 * selecting each widget in the *GUI structure*,
364 * selecting the *Packing* tab in the properties area, and
365 * setting the *Width* property from its default 1 to, say, 6.
366
367 That tells *glade* to use 6 grid cells instead of 1, so that the grid looks
368 almost normal again.
369
370 At this point you can change the property *label* under the *General tab* to
371 that text that the label should have. We choose *Employee* for *label2* and
372 *Position* for label2.
373
374 === Step 1d: Add an OK button and save the GUI
375
376 Finally, drag the widget of type *Button* from the *Control and Display* group
377 to row 5, column 5, then set its *width* to *2*, and its *label* to *OK*
378 (you need to scroll down in the General tab to see that property).
379
380 Then *SAVE THE GUI !!!* in *glade*'s menu-bar under *File → Save As* and give
381 it the filename *my-application.ui*.
382
383 In *glade*, the GUI should now look like this:
384
385 image::glade-1.png[]
386
387 At this point you can exit *glade*. *glade* has produced the file
388 *my-application.ui*, which is an XML file describing the GUI, Its content is
389 this:
390
391 ----
392
393 include::my-application.ui[]
394
395 ----
396
397 === Step 2: Starting the GUI from APL
398
399 The GUI is not yet finished, but we can already look at it from APL. In the
400 following we assume that:
401
402 * The GUI file is /home/eedjsa/projects/juergen/apl-1.7/HOWTOs/my-application.ui
403
404 You need to adjust these paths on your machine. Then start
405 GNU APL and enter the following:
406
407 ----
408 GUI_path ← '/home/eedjsa/projects/juergen/apl-1.7/HOWTOs/my-application.ui'
409 Handle ← *⎕GTK* GUI_path ⍝ fork Gtk_server and connect to it
410 ----
411
412 We see a new window at the top-left corner of the screen (that position can be
413 changed by window properties in *glade* later on):
414
415 image::glade-2.png[]
416
417 You can then stop the GUI with *)CLEAR* before leaving APL with *)OFF*:
418
419 ----
420 )CLEAR
421 )OFF
422 ----
423
424 === Step 3: Styling the GUI with CSS
425
426 There exist numerous functions for controlling how widgets look (colors, fonts,
427 sizes, etc). However, constructing a GUI using these functions is a tedious
428 and error-prone task.
429
430 For that reason, *⎕GTK* does not provide access to all these functions. Instead,
431 one can specify these properties by means of a standard CSS (cascading style
432 sheet) file as the (optional) left argument of dyadic *⎕GTK*:
433
434 ----
435 GUI_path ← '/home/eedjsa/projects/juergen/apl-1.7/HOWTOs/my-application.ui'
436 CSS_path ← '/home/eedjsa/projects/juergen/apl-1.7/HOWTOs/my-application.css'
437 Handle ← CSS_path *⎕GTK* GUI_path ⍝ fork Gtk_server and connect to it
438 ----
439
440 Consider the following CSS example, (file *my-application.css*):
441
442 ----
443 /* general button */
444 .BUTTON { color: #F00; background: #FFF; }
445
446 /* the OK button */
447 #OK-button { color: #F00; background: #4F4; }
448 ----
449
450 It specifies that buttons should, in general, have a white background and a
451 red foreground (= text color), but that the button with the name *"OK-button"*
452 in the XML file *my-application.ui* shall have a green background instead.
453 It is important to note that the relevant name in CSS (here: *#OK-button*)
454 is *not* the ID: in the *General* tab in *glade*, but the property
455 *Widget Name:* in the *Common* tab in *glade*.
456
457 The "general button" has no effect in our simple example because our GUI
458 has only one button and the stronger *#OK-button* clause wins over the more
459 general (and thus weaker) *.BUTTON* clause. It is useful, though, for
460 debug purposes: a white button would indicate a button that has not been
461 matched by a more specific selector (e.g. by the widget name).
462
463 With the *my-application.css* example file above we now get this:
464
465 image::glade-3.png[]
466
467 === Step 4: Managing windows
468
469 *Monadic ⎕GTK* with integer argument *0* returns a (possibly empty) integer
470 vector containing all window handles that are currently open.
471
472 *Dyadic ⎕GTK* with integer right argument *0* and integer left argument *Ah*
473 closes the window whose handle is *Ah*.
474
475 [icon="/usr/share/asciidoc/icons/note.png"]
476 NOTE: there is a summary of all *⎕GTK* syntax variants (a *⎕GTK* cheat sheet)
477 in the <<TAG_appendix, Appendix>> of this document.
478
479 ----
480 )CLEAR
481 *⎕GTK* 0 ⍝ get window handles (empty)
482
483 GUI_path ← '/home/eedjsa/projects/juergen/apl-1.7/HOWTOs/my-application.ui'
484 CSS_path ← '/home/eedjsa/projects/juergen/apl-1.7/HOWTOs/my-application.css'
485 Handle ← CSS_path *⎕GTK* GUI_path ⍝ fork Gtk_server and connect to it
486
487 *⎕GTK* 0 ⍝ get window handles (now there is one window)
488 6
489
490 6 *⎕GTK* 0 ⍝ close window handle 6
491 0
492 ----
493
494 The handle above (6) can, in theory, also be used with ⎕FIO functions like
495 fread() if you know what you are doing. This practice is, however, dangerous
496 because it might create inconsistencies between *⎕GTK* and ⎕FIO. For example,
497 closing a *⎕GTK* handle with ⎕FIO is technically possible, but usually bad
498 idea.
499
500 Please note that a window can normally be closed from two ends: from APL with
501 *Ah *⎕GTK* 0* and from the GUI via *Close* in the top-left window menu.
502 The latter may, however, close the window but leave the Gtk_server process
503 that was running the window alive. You should therefore aim at always
504 closing windows from APL, possibly by connecting window close signals to APL.
505
506 === Step 5: Managing widgets
507
508 A window is a (top-level) widget that usually contains other widgets. When you
509 place a new widget in *glade*, then *glade* assigns a unique ID to the widget
510 and makes sure that the id remains unique.
511
512 [icon="/usr/share/asciidoc/icons/caution.png"]
513 CAUTION: *⎕GTK* requires that you do not change the ID assigned by *glade* (even
514 though *glade* allows you to do that). The ID assigned by *glade* is found as
515 property *ID:* under the *General* tab and shall not be confused with the
516 *widget name:* under the *Common* tab. The *ID:* property is used in the
517 direction APL → Gtk_server to address widgets, while the *widget name:*
518 property is used in the reverse direction APL ← Gtk_server to identify the
519 widget that has sent a signal.
520
521 The ID consists of a class name followed by an instance number, for example
522 "window1", *⎕GTK* uses the class name in the ID to construct the function name
523 in GTK that shall be called.
524
525 ⎕GTK has different function signatures, which follow a simple rule:
526
527 * functions that address a GUI (opened with some .ui file) have no axis
528 argument,
529 * functions that address widgets inside a GUI have an axis argument such that
530 * the axis argument is: *H_ID ← H, ID* where H is the GUI handle and ID is
531 the ID discussed above.
532
533 All properties are strings, even though the content of some widgets can
534 only be numbers. Currently only a small subset of the many existing GTK
535 functions are implemented in *⎕GTK* and Gtk_server. However, the mapping from
536 *⎕GTK* functions to functions in libGtk can be easily extended by:
537
538 * adding new mappings to src/Gtk/Gtk_map.def
539 * recompiling and re-installing GNU APL
540
541 The second step also updates the *⎕GTK* Cheat Sheet in the Appendix below.
542 We extend our example to set the initial value of the employee to "John Doe",
543
544 ----
545 )CLEAR
546 GUI_path ← '/home/eedjsa/projects/juergen/apl-1.7/HOWTOs/my-application.ui'
547 CSS_path ← '/home/eedjsa/projects/juergen/apl-1.7/HOWTOs/my-application.css'
548 Handle ← CSS_path *⎕GTK* GUI_path ⍝ fork Gtk_server and connect to it
549
550 H_ID ← Handle, "entry1" ⍝ the Employee: entry
551 "John Doe" ⎕GTK[H_ID] "set_text" ⍝ set the entry to "John Doe"
552
553 6 *⎕GTK* 0 ⍝ close window handle 6
554 0
555 ----
556
557 The GUI now looks like this:
558
559 image::glade-4.png[]
560
561 Finally, we can read data back from widgets. The following example is rather
562 crude (just good enough to demonstrate the access to a widget's content), but
563 we will see a smarter way in the next chapter (Managing Events). For the moment
564 we simply give the user 20 seconds time to enter data in the "Position:" entry
565 and read the entry data after that time has elapsed (regardless of whether the
566 user has entered any data or not).
567
568 ----
569 )CLEAR
570 GUI_path ← '/home/eedjsa/projects/juergen/apl-1.7/HOWTOs/my-application.ui'
571 CSS_path ← '/home/eedjsa/projects/juergen/apl-1.7/HOWTOs/my-application.css'
572 Handle ← CSS_path *⎕GTK* GUI_path ⍝ fork Gtk_server and connect to it
573
574 H_ID ← Handle, "entry1" ⍝ the Employee: entry
575 "John Doe" ⎕GTK[H_ID] "set_text" ⍝ set the entry to "John Doe"
576
577 "Please enter the Position: within 20 seconds..."
578 ⊣⎕DL 20 ⍝ wait 20 seconds
579 "End of input interval"
580
581 H_ID ← Handle, "entry2" ⍝ H_ID is the Position: entry
582 ⎕GTK[H_ID] "get_text" ⍝ get the content of entry2
583
584 6 *⎕GTK* 0 ⍝ close window handle 6
585 0
586 ----
587
588 Let *B~int~* be:
589
590 * the (positive) function number B if B is a positive integer scalar, or
591 * the function number corresponding to B if B is a function name like
592 "set_text" above.
593
594 Then result of *⎕GTK[H_ID] B* is:
595
596 * *B~int~* if the corresponding Gtk function was successful but returns no data
597 (which is typical for all set_XXX() functions like set_text() above), or
598
599 * *-B~int~* if the corresponding Gtk function has failed, or
600
601 * a vector *B~int~, DATA* if the corresponding Gtk function was successful and
602 has returned the result *DATA* (which is typical for all *get_XXX()*
603 functions such as *get_text()* above).
604
605 Therefore, even though some Gtk functions (i.e. those having a C/Cpp result
606 type of *void*) do not return values, *⎕GTK* always returns a value.
607
608 == Step 6: Managing Events
609
610 In the example developed so far the transfer of data to and from widgets was
611 initiated from APL. Of course, giving a user 20 seconds time to enter some
612 data is a ridiculous approach for a serious application program. What is
613 needed instead is a way for the GUI to indicate that something of interest has
614 happened, such as the user pressing the OK button after she has finished her
615 input. Another option would have been to indicate the end of input by hitting
616 the return key.
617
618 If an application program having a GUI is written in C/Cpp, then events such
619 as pressing a button or a key on the keyboard are usually forwarded to the
620 application by means of callback functions. Whenever the events used by the
621 application change - typically accompanied by a change of the GUI - then the
622 application needs to be recompiled so that the callbacks are properly updated.
623
624 Since APL normally has no such thing as a callback function, and since we do
625 not want to recompile Gtk_server for every APL application, the following
626 approach is used:
627
628 * Gtk_server currently provides a rather small set of callback functions:
629 include::../src/Gtk/Gtk_events1.asciidoc[]
630 * in the *glade* GUI design, the "real" events (called "signals" in the Gtk
631 documentation) are connected to the above callback functions. An event
632 emitted by a widget then causes the connected callback function to be
633 called.
634 * every callback inserts a single event into an event queue inside *⎕GTK*.
635 * *⎕GTK* is then used to poll events out of the event queue. The event queue in
636 *⎕GTK* decouples the creation of an event from the handling of the event.
637
638 Note: The Gtk widget class can currently emit around 70 different signals,
639 while Gtk_server currently provides only a rather small set of callback
640 functions. This set is supposed to grow over time as the need for new callbacks
641 arises. However, the plan is *not* to end up with 70 callbacks in Gtk_server.
642
643 Technically speaking a set of callbacks is sufficient for sending and
644 identifying every signal in APL if:
645
646 * for every signal with arguments a1, a2, ... aN of type t1, t2, ... tN in Gtk
647 there is at least one matching callback in Gtk_server to which the signal
648 can be connected, and
649 * for every widget that can emit N different signals with the same argument
650 types (i.e. t1, t2, ... tN) there are N different callbacks to which these
651 signals can be connected.
652
653 In short this means that every signal can be connected to a callback and all
654 signals emitted by a widget can be connected to different callbacks. If a set
655 of callbacks satisfy the above then they:
656
657 * make Gtk_server more compact, and
658 * reduce the size of the APL function(s) decoding the events, but
659 * possibly decrease the readability of the event decoder because a signal
660 name may not reflect its true meaning.
661
662 === 6a. The life-cycle of an Event
663
664 It might be useful to briefly describe the entire life-cycle of an event.
665 Details (like how to do things) will follow after that. We use the example
666 discussed so far.
667
668 The entire life-cycle of an event is this:
669
670 . *Prerequisite:* In *glade*, the signal named *clicked* of the OK button was
671 connected to the callback function *clicked* in Gtk_server
672
673 . The user clicks the green OK button
674
675 . Gtk calls the function *clicked()* in the Gtk_server.
676
677 . function *clicked()* in the Gtk_server *send()s* the event to APL over the
678 connection between APL and Gtk_server.
679
680 . APL *read()s* the event from the connection between APL and
681 Gtk_server. and stores it into its event queue.
682
683 . the APL application polls the event out of the queue. At this point
684 the event has become an APL data structure in the APL workspace. The
685 life-time of the event ends here, but the (application-specific) processing
686 of the APL data usually continues a little further. In our example, the OK
687 button was meant to let the user tell when her input was finished, so the
688 next actions would be to read the contents of the *entry1* and *entry2*
689 widgets as already described above.
690
691 Now to the details ...
692
693 ==== 6b. Connecting Signals to Gtk_server Callback Functions
694
695 Every signal of a widget that shall be sent to APL needs to be connected in
696 *glade*:
697
698
699 * start *glade* with our example GUI file:
700
701 ----
702 $ glade my-application.ui
703 ----
704 * select the *button1* widget by clicking onto the OK button in the
705 *GUI visualization area*. The single widget *window1* in the widget
706 structure area (top-right of the *glade* window) will open and show its
707 children. One of the children - *button1* is now shown as being selected.
708
709 * select the "Signals" tab in the widget property area (bottom-right of the
710 *glade* window)
711
712 * select the row with signal "clicked", which highlights the row in blue
713
714 * click on the selected row below the column "Handler", which opens a small
715 text entry field.
716
717 * in the text entry field, enter "clicked", which is the name of the handler
718 function in Gtk_server that shall be called when widget *button1* was clicked.
719 [If you need to pass another object to the callback, then enter "clicked_1"
720 instead of "clicked" and select the object in the dialog that pops up if
721 you click on "User Data:" in the blue row, Don't do that in this example.]
722 * Finally, save the GUI in *glade*'s menu-bar under *File → Save*.
723
724 For those interested in the details, *glade* has added one line to our file
725 *my-application.ui*:
726
727 ----
728 <signal name="clicked" handler="clicked" swapped="no"/>
729 ----
730
731 At this point the *Prerequisite* for sending the clicked signal from
732 *button1* to APL is met, and steps 2-5 in the life-cycle of an event
733 happen automatically at the proper point in time, What remains is step 6.
734
735 === 6c. Polling the Event Loop in APL
736
737 The event loop can be polled from APL in two fashions: *blocking* or
738 *non-blocking*. *Blocking* means that the APL functions that do the poll
739 returns an event to APL immediately if the event has occurred already (e.g.
740 the user has clicked *button1* _before_ the event queue was polled), and
741 otherwise waits until that event has occurred. *Non-blocking* means that the
742 APL functions that do the poll _always_ return immediately, but return a
743 special event with number 0 to indicate that the event queue was empty at the
744 time when the poll function was called.
745
746 Non-blocking calls are inevitably performed in some kind of loop at APL level
747 and therefore are more complicated. Blocking calls are simpler to program but
748 stop the APL application until the next event (which may or not be the event
749 that the application is waiting for) has occurred.
750
751 Another aspect is the scope of a poll. The APL application can either poll for
752 an event from a single GUI, or for an event in any of the GUIs that were
753 started from the interpreter instance.
754
755 The invocation for a blocking poll is *Z←⎕GTK 1*; The invocation for a
756 non-blocking poll is *Z←⎕GTK 2*.
757
758 The return value *Z* of a non-blocking poll is the integer scalar 0 if the
759 event queue is empty. In all other cases Z is either a 3-element APL vector
760 *Gi,Ws,Es* or a 4-element APL vector *Gi,Ws,Es,Us* if an event with
761 *User Data:* Us is received, where:
762
763 * *G* is an integer scalar for the handle of the GUI window in which the event
764 was created,
765 * *Ws* is the name of the widget that has created the event (*button1* in our
766 example),
767 * *Es* is the name of the signal in *glade* (*clicked* in our example), and
768 * *Us* (if present) is the name of an object specified as *User Data:* in
769 *glade*.
770
771 === 6d. Waiting for a Click Event from the OK Button
772
773 We are now ready to replace the awkward 20 seconds interval in our example by a
774 more appropriate one: we give the user as much time as she needs to fill out
775 the Employee: and Position: fields until she pushes the OK-button to indicate
776 that the entry of data is complete.
777
778 Since our GUI only has one relevant event (clicking the OK button; the editing
779 of the Employee: and Position: fields is managed internally by Gtk), we keep
780 things simple and use a blocking poll of the *⎕GTK* event queue.
781 The connection from the OK-button to the GTK callback clicked() was already
782 done in Step 6b. above (and we assume that the updated my-application.ui is
783 used). All that is needed then is to replace:
784
785 ----
786 "Please enter the Position: within 20 seconds..."
787 ⊣⎕DL 20 ⍝ wait 20 seconds
788 "End of input interval
789 ----
790
791 by:
792
793 ----
794 ⊣⎕GTK 1 ⍝ wait for click on the OK button
795 ----
796
797 The example therefore becomes:
798
799 ----
800 )CLEAR
801 GUI_path ← '/home/eedjsa/projects/juergen/apl-1.7/HOWTOs/my-application.ui'
802 CSS_path ← '/home/eedjsa/projects/juergen/apl-1.7/HOWTOs/my-application.css'
803 Handle ← CSS_path *⎕GTK* GUI_path ⍝ fork Gtk_server and connect to it
804
805 H_ID ← Handle, "entry1" ⍝ the Employee: entry
806 "John Doe" ⎕GTK[H_ID] "set_text" ⍝ set the entry to "John Doe"
807
808 *⎕GTK* 1 ⍝ wait for click on the OK button
809
810 ⍝ [ at this point the user enters "Engineer" into entry2 and then pushes the OK button ]
811
812 H_ID ← Handle, "entry2" ⍝ H_ID is the Position: entry
813 ⎕GTK[H_ID] "get_text" ⍝ get the content of entry2
814
815 Handle *⎕GTK* 0 ⍝ close window handle 6
816 0
817 ----
818
819
820 === 6e. Wrap-up
821
822 The last thing to do is to put our example code into a defined function. We
823 remove the H_ID variable (which was only used to make Step 5 above explicit),
824 and we hide useless return values from *⎕GTK 1* and *⎕GTK[] "get_text"* with ⊣:
825
826 ----
827 ∇Z←get_NAME_and_POSITION;GUI_path;CSS_path;Handle
828 GUI_path ← '/home/eedjsa/projects/juergen/apl-1.7/HOWTOs/my-application.ui'
829 CSS_path ← '/home/eedjsa/projects/juergen/apl-1.7/HOWTOs/my-application.css'
830 Handle ← CSS_path *⎕GTK* GUI_path ⍝ fork Gtk_server and connect to it
831 ⊣⎕GTK 1 ⍝ wait for click on the OK button
832 Z ← ⊂1↓⎕GTK[Handle, "entry1"] "get_text" ⍝ get the content of entry1
833 Z ← Z,⊂1↓⎕GTK[Handle, "entry2"] "get_text" ⍝ get the content of entry2
834 ⊣Handle *⎕GTK* 0 ⍝ close the GUI handle
835 ∇
836 ----
837
838
839 == Step 7 (optional): Custom Drawings
840
841 Gtk provides the widget type GtkDrawingArea that can be used to create, for
842 example, a canvas onto which one can draw lines, circles, texts, and so on.
843 To simplify the drawing onto a canvas from APL, *⎕GTK* provides special
844 functions for this purpose. The simple example described in the following
845 explains the steps needed to draw a red circle onto a white background.
846
847 === 7a. The GUI
848
849 In *glade*, design a GUI with a top-level widget of type *Window* that has one
850 child of type *DrawingArea*. That child is the canvas on which the circle will
851 be drawn. In the *Common* tab of the canvas, set the property *Width request*
852 to 400 and *Height request* to 300, and store the GUI as file *circle.ui*.
853 That defines the size of the canvas, In the *Signals* tab, set the handler for
854 signal *draw* to *do_draw*. The resulting XML file *circle.ui* is then:
855
856 ----
857
858 include::circle.ui[]
859
860 ----
861
862 === 7b. APL Start-up Code
863
864 The start-up code for the GUI is similar to the previous example, except that
865 no CSS file is used:
866
867 ----
868 )CLEAR
869 GUI_path ← '/home/eedjsa/projects/juergen/apl-1.7/HOWTOs/circle.ui'
870 Handle ← *⎕GTK* GUI_path ⍝ fork Gtk_server and connect to it
871 ----
872
873 That code alone creates an empty canvas. That empty canvas can then be filled
874 by means of drawing commands as described below.
875
876
877 === 7c. APL Drawing Code
878
879 A single drawing command is a string starting with a keyword followed by
880 parameters.
881 An entire drawing is a nested vector of drawing commands. Our simple example
882 uses four drawing commands: two for filling the canvas background and two for
883 drawing the red circle. A real-world example would, of course, consist of
884 many more drawing commands. GNU APL provides two convenient methods for
885 creating vectors of strings: ⎕INP for strings entered in immediate
886 execution mode (and therefore also for apl scripts) and multi-line strings
887 inside defined functions.
888
889 Our example in immediate execution mode or in an APL scripts could use a
890 variable, say *DrawCmd*, that is constructed with ⎕INP:
891
892 ----
893
894 DrawCmd ← ⎕INP '▄'
895 background 255 255 255 ⍝ white background
896 fill -color 255 0 0 ⍝ red ellipse at 200:150 with radii 100 and 75
897 ellipse (200 150) (100 75)
898 ▄
899
900 ----
901
902 An alternative to a variable is a niladic defined function using multi-line
903 strings:
904
905 ----
906
907 ∇Z←DrawCmd
908 Z←1↓"
909 background 255 255 255 ⍝ white background
910 fill -color 255 0 0 ⍝ red ellipse at 200:150 with radii 100 and 75
911 ellipse (200 150) (100 75)"
912 ∇
913
914 ----
915
916 In both cases *DrawCmd* is a 4-element vector of strings. Once the
917 *DrawCmd* strings are constructed they are sent to the drawing area widget:
918
919 ----
920
921 H_ID ← Handle, "drawingarea1"
922 DrawCmd ⎕GTK[H_ID] "draw_commands"
923
924 ----
925
926 === 7d. Wrap-up
927
928 Putting the pieces above together we get:
929
930 ----
931 )CLEAR
932 GUI_path ← '/home/eedjsa/projects/juergen/apl-1.7/HOWTOs/circle.ui'
933 Handle ← *⎕GTK* GUI_path ⍝ fork Gtk_server and connect to it
934
935 DrawCmd ← ⎕INP '▄'
936 background 255 255 255 ⍝ white background
937 fill-color 255 0 0 ⍝ red ellipse at 200:150 with radii 100 and 75
938 ellipse (200 150) (100 75)
939 ▄
940
941 H_ID ← Handle, "drawingarea1"
942 DrawCmd ⎕GTK[H_ID] "draw_commands"
943 ----
944
945 The GUI created by the APL code above then looks like this:
946
947 image::glade-5.png[]
948
949 A slightly more advanced example that uses the same XML file *circle.ui* but
950 different drawing commands to show additional features (lines, text, objects
951 with and without borders is:
952
953 ----
954 )CLEAR
955 GUI_path ← '/home/eedjsa/projects/juergen/apl-1.7/HOWTOs/circle.ui'
956 Handle ← *⎕GTK* GUI_path ⍝ fork Gtk_server and connect to it
957
958 DrawCmd ← ⎕INP '▄'
959 background 208 208 255 ⍝ blueish background
960 line-color 0 0 0 255 ⍝ black opaque pen → areas have a border
961 line-width 200%
962 text (40 20) shapes with line-width = 200%
963 line (0 140) (400 140)
964 fill-color 0 160 0 ⍝ green rectangle...
965 rectangle (20 60) (80 100)
966 fill-color 255 255 0 ⍝ yellow circle...
967 circle (130 80) 30
968 fill-color 255 0 0 ⍝ red ellipse...
969 ellipse (250 80) (50 30)
970 fill-color 128 128 255 ⍝ blue triangle...
971 polygon (320 60) (380 60) (350 100)
972 line-color 0 0 0 0 ⍝ transparent pen → areas have no border
973 font-family monospace
974 text (40 170) shapes without a border
975 fill-color 0 160 0 ⍝ green rectangle...
976 rectangle (20 210) (60 250)
977 fill-color 255 255 0 ⍝ yellow circle...
978 circle (130 230) 30
979 fill-color 255 0 0 ⍝ red ellipse...
980 ellipse (250 230) (50 30)
981 fill-color 128 128 255 ⍝ blue triangle...
982 polygon (320 210) (380 210) (350 250)·
983 ▄
984
985 H_ID ← Handle, "drawingarea1"
986 DrawCmd ⎕GTK[H_ID] "draw_commands"
987 ----
988
989 It produces the following GUI:
990
991 image::glade-6.png[]
992
993 === 7e. Notes
994
995 The following notes may be helpful when creating custom drawings.
996
997 * The <<TAG_appendix, Appendix>> contains a <<Tag_table4, table>> that lists
998 the syntax of all drawing commands that are currently understood by *⎕GTK*.
999 * Every call of *DrawCommands ⎕GTK[] "draw_commands"* overrides the previous
1000 one. If a drawing cannot be created in one go (like above) then you need to
1001 collect pieces into a single *DrawCommands* variable *before* calling *⎕GTK*
1002 (once). The need to construct a drawing in pieces typically occurs when the
1003 drawing commands are being computed (e.g. when writing a data plotting
1004 application).
1005 * Opaque colors are specified as a 3-element vector containing the red, green,
1006 and blue component of each color. Each color component is an integer value
1007 between 0 and 255 (inclusive), The background is always opaque.
1008 * Transparent colors are specified as a 4-element vector containing the red,
1009 green, and blue component of each color (o-255), and an opacity value
1010 between 0 (fully transparent) and 100 (fully opaque).
1011 * Most graphical objects are controlled by two colors:
1012 ** A line color (called the *pen* color in other places), and
1013 ** A fill color (called "brush* color elsewhere).
1014 ** The opaqueness of the line and fill colors can be used to control how a
1015 2-dimensional object is painted:
1016 *** Fill color opacity = 0: (only) the border (in line color), or
1017 *** Line color opacity = 0: (only) the area inside the border (in fill color),
1018 or else
1019 *** a combination of the above according to the two opacity values
1020 ** A pen width of 0 has the same effect as a pen color opacity of 0, although
1021 for different reasons.
1022 * Lines are 1-dimensional and therefore have no fill color. They are painted
1023 with the line color.
1024 * To simplify the drawing of objects, colors are not assigned to
1025 individual objects, but are sent once using one of the following commands:
1026 ** *background R G B*
1027 ** *fill-color R G B [A]*
1028 ** *fill color R G B [A]*
1029 ** the optional parameter A controls the opacity
1030 * these color commands are then applied to subsequent drawing commands,
1031 * Valid font names are system-specific, but at least the generic names used in
1032 CSS2 (i.e. *serif*, *sans-serif*, *cursive*, *fantasy*, *monospace* are
1033 supposed to work,
1034
1035 [[TAG_programmatically]]
1036 == 8 Specifying GUIs Programmatically
1037
1038 A GUI builder like *glade* can give you a quick head start if you are
1039 not yet familiar with the development of GUIs with GTK. However, it also
1040 has some limitations and disadvantages, for example:
1041
1042 * not all GTK widgets or objects have an XML representation (this is actually
1043 a limitation of GTK class GtkBuilder which reads the .ui files produced by
1044 glade).
1045 * workspaces that depend on additional files (XML or CSS) are more difficult
1046 to distribute than self-contained (i.e. single-file) workspaces
1047 * regular structures like horizontally or vertically aligned sets of widgets
1048 are cumbersome to create or maintain.
1049
1050 For this reason the filename (APL string) arguments *A* and *B* of dyadic
1051 *A *⎕GTK* B* and monadic *⎕GTK B* can also be the contents of the files instead
1052 of the file names. Most *.ui* files (as produced by glade) and in particular
1053 the .css (if any) files are reasonably small. It makes therefore a lot of
1054 sense, to construct the contents (i.e. strings) of these files directly in
1055 APL rather than loading them from external files produced elsewhere. GNU APL
1056 is shipped with an example workspace *workspaces/SQL_GUI.apl* that could serve
1057 as a starting point for your own, self-contained GUI. This workspace is
1058 reasonably well documented, but some related concepts may be helpful to note
1059 before looking into the APL code of that workspace.
1060
1061 === 8.1 What glade actually does
1062
1063 In short, glade produces an XML string that is understood by *⎕GTK*. It
1064 normally stores it in some file, say *my-gui.xml*, that can later be
1065 loaded with *⎕GTK "my-gui.xml"* or with *CSS *⎕GTK* "my-gui.xml"* where
1066 CSS is a string produced elsewhere (and not of concern here).
1067
1068 Lets start with:
1069
1070 1. start *glade*,
1071 2. → Create a new project,
1072 3. → add a new *Toplevel* widget of type *GtkWindow*, and
1073 4. → select the new window and set the (topmost) property *ID*
1074 in tab *Genera* to *window1*
1075
1076 5. → *Save as* the project as *my-gui*.
1077
1078 This produces a file named *my-gui.glade* in the current directory.
1079 Opening this file with a text editor shows its content:
1080
1081 ----
1082 <?xml version="1.0" encoding="UTF-8"?>
1083 <!-- Generated with glade 3.22.1 -->
1084 <interface>
1085 <requires lib="gtk+" version="3.20"/>
1086 <object class="GtkWindow" id="window1">
1087 <property name="can_focus">False</property>
1088 <child>
1089 <placeholder/>
1090 </child>
1091 <child>
1092 <placeholder/>
1093 </child>
1094 </object>
1095 </interface>
1096 ----
1097
1098 Comparing step 4. above with line 5 of *my-gui.glade*, i.e.
1099
1100 ----
1101 <object class="GtkWindow" id="window1">
1102 ----
1103
1104 exposes the primary functionality of *glade*: producing XML templates and
1105 filling in fields in those templates according to choices made by the user (the
1106 window ID *window1* in this simple example). The two *<child>* tags with content
1107 *<placeholder/>* are used by *glade* to simplify a later replacement with
1108 other widgets and have no effect.
1109
1110 File *my-gui.glade* is already a fully functional GUI (albeit empty and thus
1111 boring) that can be used in APL via *⎕GTK*:
1112
1113 ----
1114 *⎕GTK* "my-gui.glade"
1115 6
1116 ----
1117
1118 This returns GTK handle 6 and opens the following GUI:
1119
1120 image::glade-7.png[]
1121
1122 Now, lets test the claim above: _the filename (APL string) arguments *A*
1123 and *B* of dyadic *A *⎕GTK* B* and monadic *⎕GTK B* can also be the contents
1124 of the files instead of the file names_:
1125
1126 ----
1127 )CLEAR
1128 CLEAR WS
1129
1130 XML←"""
1131 <?xml version="1.0" encoding="UTF-8"?>
1132 <!-- Generated with glade 3.22.1 -->
1133 <interface>
1134 <requires lib="gtk+" version="3.20"/>
1135 <object class="GtkWindow" id="window1">
1136 <property name="can_focus">False</property>
1137 <child>
1138 <placeholder/>
1139 </child>
1140 <child>
1141 <placeholder/>
1142 </child>
1143 </object>
1144 </interface>
1145 """
1146
1147 ⍴XML ⍝ number of nested APL strings between """ ... """
1148 14
1149
1150 *⎕GTK* 36 ⎕CR XML
1151 6
1152 ----
1153
1154 Voila, the same window as above pops up:
1155
1156 image::glade-7.png[]
1157
1158 To see why, we note the following:
1159
1160 * The text lines between the first and the second """ above constitutes a
1161 multi-line string (a non-standard GNU APL feature, see *info apl* for details).
1162 * Every line becomes a nested (string) component of the multi-line string. The
1163 multi-line string is then assigned to variable *XML*. Therefore *⍴XML*
1164 is 14 for the 14 lines of text between """ and """.
1165 * *⎕GTK B* expects B to be a simple APL vector (aka. APL string) where
1166 multiple lines are separated by newline characters and not a vector of
1167 nested APL strings. *36 ⎕CR XML* does the required conversion from
1168 nested APL strings to a simple APL string with *\n* aka. *ASCII FL* as
1169 line separator.
1170 * the XML standard treats newlines and blanks alike, therefore the string
1171 lines could have been separated by blanks (or tabs etc.) as well. However,
1172 no corrsponding ⎕CR conversion exists, so *36 ⎕CR* was used and long XML
1173 strings using \n are easier to read than those using blanks or TABs.
1174
1175
1176 All properties of the new windows, like its size, caption, etc. are set to
1177 their defaults. We will explain, by means of examples, how to change that in
1178 the following description.
1179
1180 === 8.2 Some GTK (and glade) details
1181
1182 As already mentioned, *glade* produces an XML file that describes the desired
1183 GUI on the one hand, and GTK, more precisely a GTK object (of type
1184 *GtkBuilder*) on the other. The GtkBuilder provides functions that read the
1185 XML file or string and creates (instantiates) the widget objects needed to
1186 do so. This works by means of a naming convention between the XML text file
1187 (produced by glade or, as here, by APL) and the C source files (actually C
1188 header files) that come with the GTK libraries. The GTK header files are
1189 usually installed in either */usr/include/gtk-3.0/gtk/* or else in
1190 */usr/local/include/gtk-3.0/gtk/*.
1191
1192 You can use *⎕GTK* without any C/Cpp knowledge, but looking at some of the
1193 header files (i.e. files with extension *.h*) may help in understanding the
1194 naming conventions between XML and GTK. Understanding (and following) this
1195 naming convention is essential for producing a proper XML description for
1196 a GUI.
1197
1198 In variable XML above, we have already seen the first (and so far only)
1199 GTK widget, i.e. *window*:
1200
1201 ----
1202 <object class="GtkWindow" id="window1">
1203 ...
1204 </object>
1205 ----
1206
1207 To fully understand the naming conventions we use two more widgets with
1208 compound names: *gtktextview* and *gtktreeviewcolumn*. We call the
1209 names *window*, *gtktextview*, and *gtktreeviewcolumn* the *core name*s
1210 of the widgets. Every relevant naming convention (XML uses only some of
1211 them but we will explain them all) start with the core name of a widget
1212 and produces similar looking names as described in the following sections.
1213
1214 ==== Core Name
1215
1216 A core name is a sequence of lowercase (!) ASCII characters a..z.
1217
1218 Neither digits 0..9, nor underscore (_), nor minus (-) or other non-alphabetic
1219 characters are part of a core name. These characters are instead used to derive
1220 other name variants from a core name.
1221
1222 As already mentioned, the examples discussed here use the core names *window*,
1223 *gtktextview*, and *gtktreeviewcolumn*. The other core names then follow suit.
1224 ..
1225
1226 ==== Header File Name
1227
1228 The name of the header file for *corename* is *gtkcorename.h*. Therefore, the
1229 header files in our example are: *gtkwindow.h*, *gtktextview.h*, and
1230 *gtktreeviewcolumn.h*
1231
1232 Depending on the platform, all these header files are most likely located in
1233 directory */usr/include/gtk-3.0/gtk/* or .*/usr/local/include/gtk-3.0/gtk/*,
1234 or sometimes below /opt.
1235
1236 The user is normally not concerned with these header files. They are sometimes
1237 helpful to disambiguate core names. For example, to decide (below) if
1238 *treeviewcolumn* should mean 3 words *tree-view-column* or 2 words
1239 *treeview-column*.
1240
1241 ==== Object Class
1242
1243 Every widget is an instance of an associated class which is declared in the
1244 corresponding header file. The class for *corename* is either *GtkCoreName* or
1245 GtkCorename*. In our example the class names are *GtkWidget*, *GtkTextView*,
1246 and *GtkTreeViewColumn*.
1247
1248 Confusingly, many widget not only declare the class name as described, but
1249 in addition another class with suffix *Class*. For instance both
1250 *GtkTreeViewColumn* and *GtkTreeViewColumnClass* in *gtktreeviewcolumn.h*.
1251
1252 The name variant with the *Class* suffix is not used by *⎕GTK*.
1253
1254 As of this writing it is not entirely clear if the XML attribute
1255 *class="GtkWindow"* above refers to a GTK object class or to a CSS style class
1256 (since both exist). For the moment we assume a GTK object class; GtkServer
1257 does not use it, but the *GtkBuilder* may in some way.
1258
1259 ==== Object ID
1260
1261 The <object ...> tag in XML may or may not contain the optional XML
1262 attribute *id=* (see above). In many cases the ID is not needed and should
1263 then not be mentioned in the XML. The relevant exceptions (in which cases
1264 the ID is mandatory) are:
1265
1266 * top-level windows. *⎕GTK* uses the ID of the top-level window to find the
1267 GTK object with that ID.
1268 * widgets for which APL calls widget functions (i.e. *Z←⎕GTK[H_ID]
1269 "function-name"* or *Z←A ⎕GTK[H_ID] "function-name"*.
1270
1271 The object ID of a widget consists of an *ID-prefix* and an *ID-suffix*
1272 according to these rules:
1273
1274 * The *ID-prefix* is the leading lowercase ASCII characters a..z of some name,
1275 * The *ID-suffix* is the trailing characters of that name, i.e. the suffix
1276 does NOT start with a lowercase ASCII character a..z.
1277 * The *ID-prefix* should be the same as the function name prefix explained below.
1278
1279 The purpose of the *ID-suffix* is to distinguish different instances of the
1280 same widget, e.g multiple buttons in the same window.
1281
1282 In older glade versions, the *ID-suffixes* were automatically set to 0, 1, 2,
1283 ... for multiple instances of the same widget class (but could be changed by
1284 the user). In newer glade versions the ID is left empty by default. For that
1285 reason we had to do Step 4:
1286
1287 ----
1288 → select the new window and set the (topmost) property ID in tab Genera to window1
1289 ----
1290
1291 above.
1292
1293 ==== Widget Function Prefix
1294
1295 Every widget has a number of associated functions. The same function name
1296 may be used for different widget classes. For example. many widgets have a
1297 *get_value()* function.
1298
1299 In Cpp interfaces to GTK a widget like *window* is declared in header file
1300 *window.h*, declare a *namespace Gtk*, a Cpp class *Window* inside namespace
1301 *Gtk*, and member functions fun1, fun2, ... of that class.
1302
1303 ⎕GTK uses the C interface instead and the Cpp luxury of namespaces and classes
1304 become function name prefixes. This makes
1305
1306 ----
1307 Gtk::Window::fun1(args...) in Cpp, and
1308 gtk_window_fun1(gtk_window *, args...) in C
1309 ----
1310
1311 essentially the same. Coming back to our example, the widget name prefixes are
1312 *gtk_window_*, *gtk_text_view_*, and *gtk_tree_view_column*.
1313
1314 === 8.3 How (A) ⎕GTK[H_ID] B works
1315
1316 Let:
1317
1318 ----
1319 H←⎕GTK 36 ⎕CR XML ⍝ i.e. 6 as above
1320 H_ID← H, "window1" ⍝ handle and widget ID
1321 "MY-TITLE" ⎕GTK[H_ID] "set_title" ⍝
1322 ----
1323
1324 Then the *⎕GTK* calls above hopefully do this:
1325
1326 1. The first *⎕GTK* call opens a new GUI window according to XML
1327 2. The second *⎕GTK* call splits *H_ID* into the numeric handle *H* (a
1328 connection to a separate process that handles the events of the window)
1329 and a string *ID* which is the Object ID of a widget in that window.
1330 3. The widget class (= the ID prefix *window* of the ID *window1* and the
1331 right *⎕GTK* argument (= *set_title*) are combined into the window function
1332 name *gtk_window_set_title*. This function (in the GTK library) is called
1333 and its result is returned.
1334 4. In step 3. the function arguments and the function result (if any) are
1335 trans-coded between APL values and C values. For this reason, only widget
1336 functions whose arguments and/or results are integer (including enums) or
1337 strings can be supported by *⎕GTK*. This is fortunately the case for the
1338 majority of widget functions.
1339
1340 Adding the second *⎕GTK* call to our code gives:
1341
1342 ----
1343 )CLEAR
1344 CLEAR WS
1345
1346 XML←"""
1347 <?xml version="1.0" encoding="UTF-8"?>
1348 <!-- Generated with glade 3.22.1 -->
1349 <interface>
1350 <requires lib="gtk+" version="3.20"/>
1351 <object class="GtkWindow" id="window1">
1352 <property name="can_focus">False</property>
1353 <child>
1354 <placeholder/>
1355 </child>
1356 <child>
1357 <placeholder/>
1358 </child>
1359 </object>
1360 </interface>
1361 """
1362
1363 H←⎕GTK 36 ⎕CR XML ⍝ display GUI defined by XML
1364 H_ID← H, "window1" ⍝ handle and widget ID (in XML)
1365 "MY-TITLE" ⎕GTK[H_ID] "set_title" ⍝ calls gtk_window_set_title()
1366 ----
1367
1368 and, when executed, this GUI:
1369
1370 image::glade-8.png[]
1371
1372 A little quirk in this example (which is beyond the control of *⎕GTK* or
1373 Gtk_server) is that the new window title *MY-TITLE* does not show immediately
1374 but only after the window obtains the focus again. This is most likely platform
1375 dependent.
1376
1377 At this point, two issues related to widget functions may be worthwhile
1378 to mention:
1379
1380 1. In most cases the widget function is a function of the widget itself.
1381 Sometimes, however, the desired function is not a function of the widget
1382 itself (such functions have the widget as their first argument in C), but
1383 a function of some ancestor class of the widget. The GTK documentation
1384 for a widget usually lists the ancestor(s) of the widget under the topic
1385 *Hierarchy* and/or *Ancestors*. Note that the parent/child relation in
1386 XML refers to (visual) containment ('buttons A and B are contained (placed
1387 inside) window W') while the ancestor relation refers to class containment
1388 ('GtkButton A can also call the functions of its ancestor classes, in
1389 particular of its ancestor GtkWidget').+
1390 +
1391 For example. we use widgets of class *GtkButton* for buttons, If we were
1392 interested in the state (pushed or not pushed) of some button, then we
1393 would maybe like to call the widget function that tells us, which is
1394 function *get_state_flags*. Unfortunately *get_state_flags* is not a
1395 widget function of class *GtkButton*, but a widget function of its
1396 ancestor class *GtkWidget* +
1397 +
1398 If we would try to call monadic *⎕GTK[H_ID]\'get_state_flags'* with the
1399 *H_ID* for some button, then this would ask the Gtk_server to call the
1400 C function *gtk_button_get_state_flags()*, which is wrong because no such
1401 function exists. Instead we should have asked the Gtk_server to call the
1402 C function *gtk_widget_get_state_flags()*. +
1403 +
1404 Such cases are resolved by prefixing the function name with the name of the
1405 ancestor class that actually defines the function, separated by ::.
1406 In this example, the proper APL code would have been
1407 *⎕GTK[H_ID]\'GtkWidget::get_state_flags'*. +
1408
1409 Most widget functions of interest are used to construct the GUI and return
1410 no value. Some, like *GtkWidget::get_state_flags*, do return a value. In
1411 that case the result Z is a (possibly mixed) vector. The first vector component
1412 *↑Z* is the function number (APL integer) of the function that has returned
1413 the result. The rest *1↓Z* is the result itself (an APL integer, APL Float,
1414 or a (not enclosed) string.
1415
1416
1417 === 8.4 Adding Window Properties
1418
1419 The XML for a widget in a GUI defines how the widget looks initially.
1420 In our previous example above:
1421
1422 * the top-level *window* was created with its default title *Gtk)server*,
1423 * the default title was then changed to *MY-TITLE* by calling widget function
1424 *set_title*.
1425
1426 A better approach, which works for most but maybe not all properties is
1427 to specify them in XML *before* the widget is created and not by calling
1428 a corresponding widget function *after* the widget was created. This
1429 is achieved by XML tag <property>. In the case of the window title the
1430 property is called *title* (another GTK naming convention):
1431
1432 ----
1433 <property name="title">MY-TITLE</property>
1434 ----
1435
1436 Our complete code is now (observe how MY-TITLE has moved from APL to XML:
1437
1438 ----
1439 )CLEAR
1440 CLEAR WS
1441
1442 XML←"""
1443 <?xml version="1.0" encoding="UTF-8"?>
1444 <!-- Generated with glade 3.22.1 -->
1445 <interface>
1446 <requires lib="gtk+" version="3.20"/>
1447 <object class="GtkWindow" id="window1">
1448 <property name="title">MY-TITLE</property>
1449 <property name="can_focus">False</property>
1450 <child>
1451 <placeholder/>
1452 </child>
1453 <child>
1454 <placeholder/>
1455 </child>
1456 </object>
1457 </interface>
1458 """
1459
1460 H←⎕GTK 36 ⎕CR XML ⍝ display GUI defined by XML
1461 ----
1462
1463 The GUI looks as before but the focus quirk has disappeared since
1464 the proper *MY-TITLE* was set *before* the *window* was created. Properties
1465 are somewhat widget-specific, but most widgets have at least the XML <property>
1466 tags with XML attributes *name="width_request"*, *name="height_request*",
1467 or *name="visible"*. The value of each property is the entire text between the
1468 XML start tag <property> and the corresponding XML end tag </property>.
1469
1470 WARNING: blanks in a property value are preserved and may cause problems
1471 for certain data types like numbers or the Boolean *True* and *False*.
1472
1473 Gtk widgets have a fairly large number of properties that allow for a very
1474 fine-tuned control of how the widget will behave. However, most properties
1475 have suitable default values so that in most cases only a few of them need
1476 to be specified in XML.
1477
1478
1479 === 8.5 Adding Child Widgets
1480
1481 An obvious problem with our current *window* is that it can not be closed.
1482 We can fix that by adding an OK button to it. The button itself is defined
1483 by the following XML snipplet:
1484
1485 ----
1486 <child>
1487 <object class="GtkButton">
1488 <property name="label">OK</property>
1489 <property name="visible">True</property>
1490 <property name="width_request">80</property>
1491 <property name="height_request">30</property>
1492 </object>
1493 </child>
1494
1495 ----
1496
1497 The entire code is now:
1498
1499 ----
1500 )CLEAR
1501 CLEAR WS
1502
1503 XML←"""
1504 <?xml version="1.0" encoding="UTF-8"?>
1505 <!-- Generated with glade 3.22.1 -->
1506 <interface>
1507 <requires lib="gtk+" version="3.20"/>
1508 <object class="GtkWindow" id="window1">
1509 <property name="title">MY-TITLE</property>
1510 <property name="can_focus">False</property>
1511 <property name="width_request">400</property>
1512 <property name="height_request">200</property>
1513 <child>
1514 <object class="GtkButton">
1515 <property name="label">OK</property>
1516 <property name="visible">True</property>
1517 <property name="width_request">80</property>
1518 <property name="height_request">30</property>
1519 <property name="halign">start</property>
1520 <property name="valign">start</property>
1521 </object>
1522 </child>
1523 </object>
1524 </interface>
1525 """
1526
1527 H←⎕GTK 36 ⎕CR XML ⍝ display GUI defined by XML
1528 ----
1529
1530 and produces:
1531
1532 image::glade-9.png[]
1533
1534 To explain the the above:
1535
1536 * the properties *width_request* and *height_request* specify the desired
1537 sizes of the parent widget *window1* and its (so far) anonymous child
1538 of type *GtkButton*.
1539 * the properties *halign* and *valign* of the button with value *start* tell
1540 the parent widget that the button shall be placed at the start (= horizontal
1541 left and vertical top resp.) of the parent. Without them the button
1542 would have grabbed the entire available space of the parent, making the
1543 button almost as big as the parent.
1544
1545 === 8.6 Placing Child Widgets
1546
1547 Of course the position of the button at the top left corner of the window is
1548 still somewhat unusual. We would assume that either the GtkWindow or the
1549 GtkButton class have a property or a widget function that could place the
1550 button at a different offset, say *x* pixels Right and *y* pixels down from
1551 the top-left corner. Unfortunately no such property or function exists and
1552 an attempt to specify one yields an error, e.g.:
1553
1554 ----
1555 (Gtk_server:17553): Gtk-WARNING **: 17:17:39.760: GtkWindow does not have a child property called y
1556 ----
1557
1558 GTK handles the placement of child widgets of a parent widget by means of
1559 an intermediate widget that provides the missing properties. There exist
1560 several suitable intermediate widgets (*GtkFixed*, *GtkBox*, *GtkGrid*,
1561 *GtkLayout*, ...) with different capabilities as to how the children
1562 should be placed into their common parent. We use the simplest of them:
1563 *GtkFixed*.
1564
1565 Our current XML has a two-level widget structure like:
1566
1567 ----
1568 GtkWindow ⊃ GtkButton
1569 ----
1570
1571 where A ⊃ B should mean that B is a child of A. We replace that by
1572 a three-level widget structure like this:
1573
1574 ----
1575 GtkWindow ⊃ GtkFixed ⊃ GtkButton
1576 │
1577 └──────────── <packing>
1578 <property name="x">pos_x</property>
1579 <property name="y">pos_x</property>
1580 </packing>
1581 ----
1582
1583 The widget placement belongs to class *GtkFixed*, and happens in a separate
1584 XML Tag named *<packing>*, which has properties named *x* and *y*. That
1585 is, the positions are specified _next to_ the child rather than _inside_
1586 the child (or _inside the parent_ for that matter).
1587
1588 Our APL code becomes:
1589
1590 ----
1591 )CLEAR
1592 CLEAR WS
1593
1594 XML←"""
1595 <?xml version="1.0" encoding="UTF-8"?>
1596 <!-- Generated with glade 3.22.1 -->
1597 <interface>
1598 <requires lib="gtk+" version="3.20"/>
1599 <object class="GtkWindow" id="window1">
1600 <property name="title">MY-TITLE</property>
1601 <property name="can_focus">False</property>
1602 <property name="width_request">400</property>
1603 <property name="height_request">200</property>
1604 <child>
1605 <object class="GtkFixed">
1606 <property name="visible">True</property>
1607 <child>
1608 <object class="GtkButton">
1609 <property name="label">OK</property>
1610 <property name="visible">True</property>
1611 <property name="width_request">80</property>
1612 <property name="height_request">30</property>
1613 <property name="halign">start</property>
1614 <property name="valign">start</property>
1615 </object>
1616 <packing>
1617 <property name="x">160</property>
1618 <property name="y">150</property>
1619 </packing>
1620
1621 </child>
1622 </object>
1623 </child>
1624 </object>
1625 </interface>
1626 """
1627
1628 H←⎕GTK 36 ⎕CR XML ⍝ display GUI defined by XML
1629 ----
1630
1631 And the GUI:
1632
1633 image::glade-10.png[]
1634
1635
1636 === 8.7 Adding Style
1637
1638 In the early days of HTML, a green button would have looked something
1639 like this:
1640
1641 ----
1642 <BUTTON name="Bn-OK" bgcolor="green">"OK"</BUTTON>
1643 ----
1644
1645 These days that button would maybe look more like:
1646
1647 ----
1648 <BUTTON name="Bn-OK">"OK"</BUTTON>
1649 ----
1650
1651 and some CSS file or style somewhere else would e.g. say:
1652
1653 ----
1654 #OK-button { background-color: green }
1655 ----
1656
1657 Nowadays the size of style files has grown to such an extent that it is no
1658 longer possible to specify the style of a button or other HTML widget inline
1659 as attributes of the widget.
1660
1661 This division into form on the one hand and style on the other was
1662 therefore necessary and fruitful, even though it is not entirely clear
1663 if the enormous growth of style information has pushed CSS or if CSS
1664 has pushed the growth of style information. Anyway, GTK has adopted
1665 CSS as well, although with some subtle differences:
1666
1667 * In HTML/CSS size related and position properties (like height and width)
1668 could be defined in HTML as well as in CSS. In GTK these properties can
1669 only be defined in XML but not in CSS.
1670 * In HTML/CSS style related and position properties (like colors)
1671 could be defined in HTML as well as in CSS. In GTK these properties can
1672 only be defined in CSS but not in XML.
1673
1674 The use of CSS with *⎕GTK* requires 3 things:
1675
1676 1. a suitable APL string CSS (either a filename or file content as for XML),
1677 2. dyadic *H←CSS *⎕GTK* XML* instead of monadic *H←⎕GTK XML*, and
1678 3. possibly a relation between the widgets defined in XML and the styles
1679 defined in CSS.
1680
1681 The CSS is a sequence of statements with the following simple syntax:
1682
1683 ----
1684 Selector(s) { style attributes... }
1685 ----
1686
1687 The style attributes define how a widget looks (color, borders, etc.),
1688 while the selectors define which widgets should have the style attributes.
1689 The selectors as well as the style attributes can be used in multiple CSS
1690 statements. The key to success with CSS is to keep matters simple, and
1691 therefore it is better to have fewer selectors and style attributes
1692 than more by splitting bigger statements into a sequence of smaller ones.
1693 More details can be found here:
1694
1695 https://docs.gtk.org/gtk3/css-overview.html
1696
1697 Lets start simple (with variable XML as above):
1698
1699 ----
1700 CSS ← """
1701 window { background: #FF0; }
1702
1703 /* all widgets of (style-) class button */
1704 button { color: white; background-color: blue }
1705 """
1706
1707 (36 ⎕CR CSS) *⎕GTK* (36 ⎕CR XML)
1708 ----
1709
1710 Not too surprisingly this shows:
1711
1712 image::glade-11.png[]
1713
1714 The selectors *window* and *button* in the CSS above are (style-) class
1715 selectors, which means that all widgets of the respective class will have
1716 the style (i.e. colors) above. For the top-level window that is normally
1717 not a problem because there is only one. For buttons it is more likely
1718 that there is more than one (e.g. a CANCEL button in a different color).
1719
1720 In order to have different colors for different buttons, we need a way
1721 to distinguish them. The simplest way to distinguish widgets is to give
1722 them names (in XML). Naming a widget uses the property called "name" in
1723 XML, the value of that property (e.g. *Bn-OK* below) must then be prefixed
1724 with *#* in CSS to refer to the widget with that name:
1725
1726 ----
1727 In XML:
1728 <object class="GtkButton">
1729 <property name="label">OK</property>
1730 <property name="name">Bn-OK</property>
1731 ... ──┬──
1732 </object> │
1733 │
1734 In CSS: │
1735 ┌────────────────────────────────┘
1736 │
1737 ──┴──
1738 #Bn-OK { color: #000; background-color: #3E3; } /* button */
1739 #Bn-OK label { color: #000; background-color: #3E3; } /* button label */
1740 ----
1741
1742 You may wonder why there are CSS lines for the green OK button but only one
1743 for the blue class button. The reason is a little quirk in GTK (which will
1744 probably disappear at some point in time. A *button* is a widget that has an
1745 internal sub-widget of type *label* which holds the button text. As it
1746 happens, using a widget class as CSS selector selects the widgets of that
1747 class *including their sub-widgets* while a widget name as CSS selector
1748 selects the widget(s) with that name *excluding their sub-widgets*.
1749
1750
1751 The entire application is now:
1752
1753 ----
1754 )CLEAR
1755 CLEAR WS
1756
1757 XML←"""
1758 <?xml version="1.0" encoding="UTF-8"?>
1759 <!-- Generated with glade 3.22.1 -->
1760 <interface>
1761 <requires lib="gtk+" version="3.20"/>
1762 <object class="GtkWindow" id="window1">
1763 <property name="title">MY-TITLE</property>
1764 <property name="can_focus">False</property>
1765 <property name="width_request">400</property>
1766 <property name="height_request">200</property>
1767 <child>
1768 <object class="GtkFixed">
1769 <property name="visible">True</property>
1770 <child>
1771 <object class="GtkButton">
1772 <property name="name">Bn-OK</property>
1773 <property name="label">OK</property>
1774 <property name="visible">True</property>
1775 <property name="width_request">80</property>
1776 <property name="height_request">30</property>
1777 <property name="halign">start</property>
1778 <property name="valign">start</property>
1779 </object>
1780 <packing>
1781 <property name="x">160</property>
1782 <property name="y">150</property>
1783 </packing>
1784 </child>
1785 </object>
1786 </child>
1787 </object>
1788 </interface>
1789 """
1790
1791 CSS ← """
1792 window { background: #FFF; }
1793
1794 /* all buttons of class button */
1795 button { color: white; background-color: blue }
1796 button:hover { font-weight: bold; }
1797
1798 #Bn-OK { color: #000; background-color: #3E3; } /* button */
1799 #Bn-OK label { color: #000; background-color: #3E3; } /* button label */
1800 """
1801
1802 *⎕GTK* 3 ◊ ⊣ (36 ⎕CR CSS) *⎕GTK* (36 ⎕CR XML) ◊ ⊣ ⎕DL 2.0
1803 ----
1804
1805 It produces:
1806
1807 image::glade-12.png[]
1808
1809 === 8.8 Handling Events
1810
1811 A button defined so far is alive in the sense that it changes its font weight
1812 when the mouse is moved over it (by virtue of the CSS *button:hover* style),
1813 but has no connection to APL yet. Let's say we want to close the window when
1814 the OK button is being pushed. There are then a number of possibilities how
1815 that can be achieved, each with its own characteristics in terms of
1816 functionality and simplicity.
1817
1818 More complicated situations typically require looping in APL and are then not
1819 directly usable in immediate execution mode (and consequently not in scripts).
1820
1821 ==== Direct Polling of Widgets from APL
1822
1823 Widgets like buttons or checkboxes have widget functions that can be used to
1824 determine (in an APL loop) when their state changes and to return only when
1825 a particular widget state was reached (by an action of the user):
1826
1827 ----
1828 ∇WAIT_FOR_BUTTON_DOWN H_ID;FLAGS
1829 ⍝
1830 ⍝ /usr/include/gtk-3.0/gtk/gtkenums.h : odd state flags ←→ button down
1831 ⍝
1832 LOOP: FLAGS←⎕GTK[H_ID]'GtkWidget::get_state_flags'
1833 → (2∣¯1↑FLAGS)⍴0 ⍝ return when button "pushed"
1834 ⎕DL 0.1 ◊ → LOOP ⍝ and wait if not
1835 ∇
1836 ----
1837
1838 Of course, more than one widget (Cancel button, Help button, ...) can
1839 be polled inside such a loop.
1840
1841 ==== Waiting for any Event
1842
1843 In simple cases, for example a GUI with only one (OK-) button, one can simply
1844 wait for the next *⎕GTK* event. Since only one kind of event can occur, checking
1845 the parameters of that event is mere overhead. Also, the APL code is trivial
1846 (assuming we want to close window when the button is pushed):
1847
1848 ----
1849 ⊣ *⎕GTK* 1 ⍝ blocking wait for the next GTK event; discard the result
1850 H *⎕GTK* 0 ⍝ close the window with handle H
1851 ----
1852
1853 and it may, since no APL loop is required, even be use in immediate execution
1854 mode or in APL scripts.
1855
1856 Sometimes you want to do something else while waiting for a user action, for
1857 example updating a progress bar. In that case you could use *⎕GTK 2* (the
1858 non-blocking companion of *⎕GTK 1*) in the loop.
1859
1860 By default, GTK widgets send events (signals) to each other to achieve
1861 visual effects, but these events are not forwarded to APL.
1862
1863 NOTE: As an important consequence, *⎕GTK 1* blocks forever by default.
1864
1865
1866 To change that, the XML for every widget that shall forward events such as
1867 user clicks on buttons to APL need to specify which events shall be forwarded.
1868 For example:
1869
1870 ----
1871 <object class="GtkButton">
1872 <property name="label">OK</property>
1873 <property name="name">Bn-OK</property>
1874 ...
1875 <signal name="clicked" handler="clicked"/>
1876 </object>
1877 ----
1878
1879 * The *signal=* value shall be a valid signal for the widget class (select
1880 some widget in *glade* and see *glade* tab named *Signals* to see the list
1881 of signals that the widget or its ancestors can send).
1882 * The *handler=* value is an existing signal handler in the Gtk_server:
1883 include::../src/Gtk/Gtk_events1.asciidoc[]
1884
1885 See <<Tag_table3, Table 3 in the Appendix>> for a list of handlers.
1886
1887 NOTE: The author, at least, frequently forgets the <signal ... /> entry in the
1888 XML of the object that sends the event and then wonders what is wrong.
1889
1890 Even though this method is somewhat crude, it has the advantage that
1891 no loop (which repeats if the wrong signal was received) is required
1892 and can therefore also be used in immediate execution mode without a
1893 defined function that contains the loop.
1894
1895 ==== Waiting for specific Event
1896
1897 In more complicated cases, it might be needed to decode which widget has sent
1898 which event:
1899
1900 ----
1901 LOOP: Event←⎕GTK 1 ⍝ blocking wait for next event, then decode it
1902 (H W E) ← 3↑Event ⍝ common event header
1903 → (W ≢ "Bn-OK")/LOOP ⍝ not from Bn-OK
1904 → (E ≢ "clicked")/LOOP ⍝ not button click
1905 H *⎕GTK* 0 ⍝ OK button clicked: close the window
1906 ----
1907
1908 The same <signal> line as in the example before is required. The parameters
1909 of an event are defined by the handler, but all start with the 3 described
1910 in the following example (button click).
1911
1912 The event received from a button click is a 3-item vector like this:
1913
1914 ----
1915 ┌→──────────────────┐
1916 │7 ┌→────┐ ┌→──────┐│
1917 │ │Bn-OK│ │clicked││
1918 │ └─────┘ └───────┘│
1919 └ϵ──────────────────┘
1920 ----
1921
1922 The 3 components are:
1923
1924 * The handle for the Gtk window (small integer)
1925 * the name (APL string) of the widget sending the event, and
1926 * the name (APL string) of the event.
1927
1928
1929 === 8.9 Summary
1930
1931 The sections above have hopefully touched upon all topics that may occur when
1932 designing GUIs with *⎕GTK*. By combining these simple steps it should be
1933 straightforward to construct more advanced GUIs. Before starting from scratch,
1934 though, it may be worthwhile to have a look at the workspace
1935 *workspaces/SQL_GUI.apl* which is shipped with GNU APL. This workspace
1936 contains several examples of using *⎕GTK* (and also ⎕SQL) that could be
1937 copied into your own application.
1938
1939
1940 [[TAG_appendix]]
1941 == A. Appendix
1942 === A.1 The *⎕GTK* Cheat Sheet
1943
1944 In the Table 2 below, it is assumed that:
1945
1946 ----
1947 ⍝ H is a window handle (from some H ← Zh←⎕GTK "filename.ui")
1948 ⍝ ID is a string containing the id= property of some widget in filename.ui
1949 ⍝ H_ID ← H, ID ⍝ e.g. 6,"entry1". H_ID uniquely identifies a widget
1950 ----
1951
1952 [[Tag_table2]]
1953 .⎕GTK Syntax Variants (Signatures)
1954 [options="header"]
1955 [cols="36, ^8, 64"]
1956 |===============
1957 | Syntax
1958 | Fun +
1959 (Bi)
1960 | Result/Action
1961
1962 | Zh←⎕GTK "file.ui" | -
1963 | Zh is a handle for a new window according to *glade* file file.ui (no CSS)
1964
1965 | Zh← "file.css" *⎕GTK* "file.ui" | -
1966 | Zh is a handle for a new window according to CSS file *file.css* and
1967 *glade* XML file *file.ui*
1968
1969 | Zi← *⎕GTK* 0 | -
1970 | Zi is an integer vector containing all open window handles
1971
1972 | Zi← Ah *⎕GTK* 0 | 0
1973 | close window handle Ah, return 0 on success, or errno otherwise
1974
1975 | Zi← *⎕GTK* 1 | 1
1976 | blocking poll for the next event
1977
1978 | Zi← *⎕GTK* 2 | 2
1979 | non-blocking poll for the next event (Zi≡0 means: no event)
1980
1981 | Zi←Ah *⎕GTK* 3 | 3
1982 | increment the (debug-) verbosity of Gtk_server (subject to be changed)
1983
1984 | Zi←Ah *⎕GTK* 4 | 4
1985 | decrement the (debug-) verbosity of Gtk_server (subject to be changed)
1986
1987 include::../src/Gtk/Gtk_functions.asciidoc[]
1988
1989 |===============
1990
1991 WARNING: In Table 2 above, *⎕GTK* functions with axis argument, are *widget
1992 functions*. The axis argument *H_ID* combines the numeric handle *H* (returned
1993 from some *H←⎕GTK filename.ui* with a widget id *ID* specified in that
1994 *filename.ui* as to uniquely identify a widget on the screen (either a top-level
1995 window or a widget inside some other widget). The functions without axis
1996 arguments are *generic* and control *⎕GTK* itself rather than a widget
1997 displayed by *⎕GTK*. The mandatory right argument B of almost all *⎕GTK* calls
1998 is either a function number (APL integer scalar) or a function name (APL
1999 string). The function numbers of generic functions are assigned by GNU APL
2000 and will be maintained in a backward-compatible fashion. In contrast, the
2001 numbers for widget functions, are automatically generated from the source
2002 files of the GTK libraries and are highly volatile. These numbers differ
2003 on different platforms, between different GTK library versions, and even
2004 between different SVN versions of GNU APL. For this reason (and for the sake
2005 of portability of GNU APL workspaces, you should *never use numbers for widget
2006 functions* even though they are somewhat easier to enter. BTW: the Gtk_server
2007 can be started from the command line like: *Gtk_server --numbers* and then
2008 displays the mapping between widget function numbers and function names (of
2009 that Gtk_server).
2010
2011 The functions *⎕GTK 1* and *⎕GTK 2* return an event vector according to
2012 Table 3 below. The elements of this event vector have the following meaning:
2013
2014 * *Hi* (APL integer): the handle (= Gtk_server instance) on which the event was
2015 received. The handle was returned by some *⎕GTK "file.ui"* or
2016 *CSS *⎕GTK* "file.ui").
2017 * *Ns* (nested APL string): the *Widget Name* (if provided: in glade tab
2018 *Common* or by object property *name* in XML). *""* if not provided.
2019 * *Es* (APL string): The event (callback name), for example: *"clicked"* when
2020 a button was pushed.
2021 * *Is* (APL string): The ID of the widget that has sent the event (if
2022 provided: in glade tab *General* or XML attribute *"id="* in the start tag
2023 <object ...> of the widget). *""* if not provided.
2024 * *Cs* (string): The *Gtk class* of the widget that has sent the event, for
2025 example: *"GtkButton"*.
2026 * *Xi* (APL integer): Mouse position X (pixels) of a mouse click
2027 * *Yi* (APL integer): Mouse position Y (pixels) of a mouse click
2028 * *Bi* (APL integer): Mouse button (1, 2, or 3) of a mouse click
2029 * *Li* (APL integer): Text row number of a mouse click (GtkTextView)
2030
2031 [[Tag_table3]]
2032 .⎕GTK Events
2033 [options="header"]
2034 [cols="15, 25, 45"]
2035 |===============
2036 | Callback (in *glade* or *XML*)
2037 | Items of *Z←⎕GTK 1*
2038 | APL Example of a *⎕GTK 1* Result
2039 include::../src/Gtk/Gtk_events2.asciidoc[]
2040
2041 |===============
2042
2043 [[Tag_table4]]
2044 .⎕GTK Drawing Commands
2045 [options="header"]
2046 [cols="29, 71"]
2047 |===============
2048 | Command | Effect
2049
2050 | +*background R G B*+
2051 | Set the background color of the drawing area widget. This command shall be
2052 the first command given.
2053
2054 | +*line-width W*+
2055 | set the line width that is used to draw lines and borders. W=100 (%)
2056 gives the default line width in Gtk.
2057
2058 | +*line-color R G B*+
2059 | same as *line-color R G B 100* (fully opaque color).
2060
2061 | +*line-color R G B A*+
2062 | set the line color to the color with red, green, and blue components of R,
2063 G, and B resp, and opacity A (%).
2064
2065 | +*fill-color R G B*+
2066 | same as *fill-color R G B 100* (fully opaque color).
2067
2068 | +*fill-color R G B A*+
2069 | set the fill color to the color with red, green, and blue components of R,
2070 G, and B resp. and opacity A (%).
2071
2072 | +*font-size S*+
2073 | set the font size used in subsequent *text* commands. S=100 (%) is the
2074 default font size of Gtk.
2075 | +*font-family F*+
2076 | set the font family (*serif*, *sans-serif*, *cursive*, *fantasy*,
2077 *monospace*) used in subsequent *text*
2078 commands.
2079 | +*font-slant S*+
2080 | set the font slant used in subsequent *text* commands. S is *NORMAL*,
2081 *ITALIC*, or *OBLIQUE*.
2082 | +*font-weight W*+
2083 | set the font weight used in subsequent *text* commands. W is either *NORMAL*
2084 or *BOLD*
2085 | +*line (X0 Y0) (X1 Y1)*+
2086 | draw a line from point (X0 Y0) to point (X1 Y1).
2087
2088 | +*rectangle (X0 Y0) (X1 Y1)*+
2089 | draw a rectangle with corners (X0 Y0) and (X1 Y1).
2090
2091 | +*circle (X Y) R*+
2092 | draw a circle with center (X Y) and radius R.
2093
2094 | +*ellipse (X Y) (RX RY)*+
2095 | draw an ellipse with center (X Y) and radii RX and RY.
2096
2097 | +*polygon (X0 Y0) (X1 Y1) (X2 Y2) ...*+
2098 | draw a polygon with points (X0 Y0), (X1 Y1), (X2 Y2) ...
2099
2100 | +*text (X Y) T*+
2101 | draw the text *T* at position (X Y).
2102
2103
2104 |===============
2105
2106 [[TAG_caveats]]
2107 === Caveats
2108
2109 With *glade* it is possible to design a single GUI that contains multiple
2110 top-level windows or no top-level window. However, *⎕GTK* currently supports
2111 only GUIs with one top-level widget of type "Window (the first widget in the
2112 top-level group in glade).
2113
2114
2115 === References
2116 See also:
2117
2118 https://developer.gnome.org/gtk3/stable/
2119
2120