summaryrefslogtreecommitdiff
path: root/docs/src/gui/gladevcp_es.txt
blob: b9aae16d549189dbdf7c73083f2343b63dfff16d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
= Glade Virtual Control Panel

[[cha:glade-vcp]] (((Glade Virtual Control Panel)))

////
ATTENTION TRANSLATORS before translating this document copy the base document
into this copy to get the latest version. Untranslated documents are not kept
up to date with the English documents. 

Do not translate anchors or links, translate only the text of a link after the
comma.
Anchor [[anchor-name]]
Link <<anchor-name,text after the comma can be translated>>

Make sure the documents build after translating.
////

// TODO:
// - manual-example.ui layout - really bad
// - restructure faq/troubleshooting/notes section
// - check wiki vs docs
// - check other gladevcp docs branch against this
// - when emc action widgits are renamed then re-brand this chapter


:ini: {basebackend@docbook:'':ini}
:hal: {basebackend@docbook:'':hal}
:ngc: {basebackend@docbook:'':ngc}
// begin a listing of ini/hal/ngc files like so:
//[source,{ini}]
//[source,{hal}]
//[source,{ngc}]


== What is GladeVCP?

GladeVCP is an LinuxCNC component which adds the ability to add a new user
interface panel to LinuxCNC user interfaces like Axis or Touchy. Unlike
PyVCP, GladeVCP is not limitied to displaying and setting HAL pins, as
arbitrary actions can be executed in Python code - in fact, a
complete LinuxCNC user interface could be built with GladeVCP and Python.

GladeVCP users the http://glade.gnome.org/[Glade] WYSIWYG user
interface editor, which makes it easy to create visually pleasing
panels. It relies on the http://www.pygtk.org/[PyGTK] bindings to the
rich http://www.gtk.org/[GTK+] widget set, and in fact all of these
may be used in a GladeVCP application - not just the specialized
widgets for interacting with HAL and LinuxCNC, which are documented here.


=== PyVCP versus GladeVCP at a glance

Both support the creation of panels with 'HAL widgets' - user
interface elements like LED's, buttons, sliders etc whose values are
linked to a HAL pin, which in turn interfaces to the rest of LinuxCNC.

*PyVCP:*

 - widget set: uses TkInter widgets
 - user interface creation: "edit XML file / run result / evaluate looks" cycle
 - no support for embedding user-defined event handling
 - no LinuxCNC interaction beyond HAL pin I/O supported

*GladeVCP:*

 - widget set: relies on the  http://www.gtk.org/[GTK+] widget set.
 - user interface creation: uses the  http://glade.gnome.org/[Glade] WYSIWYG user interface editor
 - any HAL pin change may be directed to call back into a user-defined Python event handler
 - any GTK signal (key/button press, window, I/O, timer, network events) may be associated with user-defined handlers in Python
 - direct LinuxCNC interaction: arbitrary command execution, like initiating MDI
commands to call a G-code subroutine, plus support for status change operations through Action Widgets 
 - several independent GladeVCP panels may be run in different tabs
 - separation of user interface appearance and functionality: change appearance without touching any code

== A Quick Tour with the Example Panel

GladeVCP panel windows may be run in three different setups:

 - always visible integrated into Axis at the right side, exactly like PyVCP panels
 - as a tab in Axis and Touchy; in Axis this would create a third tab besides the Preview and DRO tabs which must be raised explicitly
 - as a standalone toplevel window, which can be iconifyed/deiconified independent of the main window.

Run the sample GladeVCP panel integrated into Axis like PyVCP as follows:

 $ cd configs/sim
 $ emc gladevcp_panel.ini

image::images/example-panel-small.png[]

Run the same panel, but as a tab inside Axis:

 $ cd configs/sim
 $ emc gladevcp_tab.ini

image::images/example-tabbed-small.png[]

To run this panel as a standalone toplevel window besides Axis, just
start Axis in the background and start gladevcp as follows:

 $ cd configs/sim
 $ emc axis.ini &
 $ gladevcp -c gladevcp -u ../gladevcp/hitcounter.py -H ../gladevcp/manual-example.hal ../gladevcp/manual-example.ui

image::images/example-float-small.png[]

To run this panel inside 'Touchy':

 $ cd configs/sim
 $ emc gladevcp_touchy.ini

image::images/touchy-tab-33.png[]


Functionally these setups are identical - they only differ in screen
real estate requirements and visibility. Since it is possible to run
several GladeVCP components in parallel (with different HAL component
names), mixed setups are possible as well - for instance a panel on
the right hand side, and one or more tabs for less-frequently used
parts of the interface.

=== Exploring the example panel

While running Axis, explore 'Show HAL Configuration' - you will find
the 'gladevcp' HAL component and may observe their pin values while
interacting with the widgets in the panel. The HAL setup can be
found in 'configs/gladevcp/manual-example.hal'.

The example panel has two frames at the bottom. The panel is
configured so that resetting ESTOP activates the Settings frame and
turning the machine on  enables the Commands frame at the bottom. The HAL
widgets in the Settings frame are linked to LEDs and labels in the
'Status' frame, and to the current and prepared tool number - play
with them to see the effect. Executing the 'T<toolnumber>' and 'M6'
commands in the MDI window will change the current and prepared tool
number fields.

The buttons in the 'Commands' frame are 'MDI Action widgets' -
pressing them will execute an MDI command in the interpreter.  The
third button 'Execute Oword subroutine' is an advanced example - it
takes several HAL pin values from the 'Settings' frame, and passes
them as parameters to the Oword subroutine. The actual parameters
received by the routine are displayed by '(DEBUG, )' commands - see
'configs/gladevcp/nc_files/oword.ngc' for the subroutine body.

To see how the panel is integrated into Axis, see the
'[DISPLAY]GLADEVCP' statements in gladevcp_panel.ui, and the
'[DISPLAY]EMBED*' and '[HAL]POSTGUI_HALFILE' statements in
gladevcp_tab.ini respectively.

=== Exploring the User Interface description

The user interface is created with the glade UI editor - to explore
it, you need to have <<gladevcp:Prerequisites, glade installed>>. To
edit the user interface, run the command

 $ glade configs/gladevcp/manual-example.ui

The center window shows the appearance of the UI. All user
interface objects and support objects are found in the right top
window, where you can select a specific widget (or by clicking on it
in the center window). The properties of the selected widget are
displayed, and can be changed, in the right bottom window.

To see how MDI commands are passed from the MDI Action widgets,
explore the widgets listed under 'Actions' in the top right window,
and in the right bottom window, unter the 'General' tab, the 'MDI
command' property.

=== Exploring the Python callback
See how a Python callback is integrated into the example:

 - in glade, see the +hits+ label widget (a plain GTK+ widget)
 - in the +button1+ widget, look at the 'Signals' tab, and find the signal 'pressed' associated with the handler 'on_button_press'
 - in ../gladevcp/hitcounter.py, see the method 'on_button_press' and see how it sets the label property in the 'hits' object

The is just touching upon the concept - the callback mechanism will be
handled in more detail in the <<gladevcp:GladeVCP_Programming,
GladeVCP Programming>> section.

== Creating and Integrating a Glade user interface

[[gladevcp:Prerequisites]]
=== Prerequisite: Glade installation
To view or modify Glade UI files, you need glade installed - it is not
needed just to run a GladeVCP panel. If the glade command is missing,
install it with the command:

 $ sudo apt-get install glade

Verify the version number to be greater than 3.6.7:

 $ glade --version
 glade3 3.6.7

=== Running Glade to create a new user interface
This section just outlines the initial LinuxCNC-specific steps. For more
information and a tutorial on glade, see http://glade.gnome.org. Some
glade tips & tricks may also be found on
http://www.youtube.com[youtube].

Either modify an existing UI component by running +glade <file>.ui+
or start a new one by just running the +glade+ command from the shell.

- If LinuxCNC was not installed from a package, the LinuxCNC shell environment needs to be set up with
+. <emcdir>/scripts/rip-environment+, otherwise glade won't find the LinuxCNC-specific widgets.
- When asked for unsaved Preferences, just accept the defaults and hit 'Close'.
- From 'Toplevel' (left pane), pick 'Window' (first icon) as top level window, which
by default will be named 'window1'. Do not change this name - GladeVCP relies on it.
- In the left tab, scroll down and expand  'HAL Python' and 'EMC Actions'.
- add a container like a HAL_Box or a HAL_Table from 'HAL Python' to the frame
- pick and place some elements like LED, button, etc. within a container

This will look like so:

image::images/glade-manual-small.png[]

Glade tends to write a lot of messages to the shell window, which
mostly can be ignored.  Select 'File→Save as', give it a name like
'myui.ui' and make sure it's saved as 'GtkBuilder' file (radio button
left bottom corner in Save dialog). GladeVCP will also process the
older 'libglade' format correctly but there is no point in using it. The
convention for GtkBuilder file extension is '.ui'.

=== Testing a panel
You're now ready to give it a try (while LinuxCNC, e.g. Axis is running) it with:

    gladevcp myui.ui

GladeVCP creates a HAL component named like the basename of the UI
file - 'myui' in this case - unless overriden by the +-c <component
name>+ option.  If running Axis, just try 'Show HAL configuration' and
inspect its pins.

You might wonder why widgets contained a 'HAL_Hbox' or 'HAL_Table' appear
greyed out (inactive). HAL containers have an associated HAL pin which
is off by default, which causes all contained widgets to render
inactive. A common use case would be to associate these container HAL
pins with +halui.machine.is-on+ or one of the +halui.mode.+ signals,
to assure some widgets appear active only in a certain state.

To just activate a container, execute the HAL command +setp gladevcp.<container-name> 1+.

=== Preparing the HAL command file
The suggested way of linking HAL pins in a GladeVCP panel is to
collect them in a separate file with extension +.hal+. This file is
passed via the +POSTGUI_HALFILE=+ option in the +HAL+ section of your
ini file.

CAUTION: Do not add the GladeVCP HAL command file to the Axis +[HAL]HALFILE=+ ini
section, this will not have the desired effect - see the following sections.

=== Integrating into Axis like PyVCP

Place the GladeVCP panel in the righthand side panel by specifying the
following in the ini file:

[source,{ini}]
----
[DISPLAY]
# add GladeVCP panel where PyVCP used to live:
GLADEVCP= -u ../gladevcp/hitcounter.py ../gladevcp/manual-example.ui

[HAL]
# HAL commands for GladeVCP components in a tab must be executed via POSTGUI_HALFILE
POSTGUI_HALFILE =  ../gladevcp/manual-example.hal

[RS274NGC]
# gladevcp Demo specific Oword subs live here
SUBROUTINE_PATH = ../gladevcp/nc_files/
----

The HAL component name of a GladeVCP application started with the  the GLADEVCP option is fixed:  +gladevcp+.
The command line actually run by Axis in the above configuration is as follows:

 halcmd loadusr -Wn gladevcp gladevcp -c gladevcp -x {XID} <arguments to GLADEVCP>

This means you may add arbitrary gladevcp options here, as long as
they dont collide with the above command line options.

[NOTE]
The +[RS274NGC]SUBROUTINE_PATH=+ option is only set so the example
panel will find the Oword subroutine for the MDI Command widget. It
might not be needed in your setup.

=== Integrating into Axis as a tab next to DRO and Preview

To do so, edit your .ini file and add to the DISPLAY and HAL sections of ini
file as follows:

[source,{ini}]
----
[DISPLAY]
# add GladeVCP panel as a tab next to Preview/DRO:
EMBED_TAB_NAME=GladeVCP demo
EMBED_TAB_COMMAND=halcmd loadusr -Wn gladevcp gladevcp -c gladevcp -x {XID} -u ../gladevcp/hitcounter.py ../gladevcp/manual-example.ui

[HAL]
# HAL commands for GladeVCP components in a tab must be executed via POSTGUI_HALFILE
POSTGUI_HALFILE =  ../gladevcp/manual-example.hal

[RS274NGC]
# gladevcp Demo specific Oword subs live here
SUBROUTINE_PATH = ../gladevcp/nc_files/
----

Note the 'halcmd loadusr' way of starting the tab command - this
assures that 'POSTGUI_HALFILE' will only be run after the HAL
component is ready. In rare cases you might run a a command here which
uses a tab but does not have an associated HAL component. Such a
command can be started without 'halcmd loadusr', and this signifies to
Axis that it does not have to wait for a HAL component since there is
none.

When changing the component name in the above example, note that the
names used in +-Wn <component>+ and +-c <component>+ must be
identical.

Try it out by running Axis - there should be a new tab called
'GladeVCP demo' near the DRO tab. Select that tab, you should see the
example panel nicely fit within Axis.

[NOTE]
Make sure the UI file is the last option passed to GladeVCP in
both the +GLADEVCP=+ and +EMBED_TAB_COMMAND=+ statements.

=== Integrating into Touchy
To do add a GladeVCP tab to 'Touchy', edit your .ini file as follows:

[source,{ini}]
----
[DISPLAY]
# add GladeVCP panel as a tab
EMBED_TAB_NAME=GladeVCP demo
EMBED_TAB_COMMAND=gladevcp -c gladevcp -x {XID} -u ../gladevcp/hitcounter.py -H ../gladevcp/gladevcp-touchy.hal  ../gladevcp/manual-example.ui

[RS274NGC]
# gladevcp Demo specific Oword subs live here
SUBROUTINE_PATH = ../gladevcp/nc_files/
----

Note the following differences to the Axis tab setup:

 - The HAL command file is slightly modified since 'Touchy' does not
 use the 'halui' components so its signals are not available and some
 shortcuts have been taken.

 - there is no 'POSTGUI_HALFILE=' ini option, but passing the HAL command file on the 'EMBED_TAB_COMMAND=' line is ok

 - the 'halcmd loaduser -Wn ...' incantation is not needed.

== GladeVCP command line options

See also 'man gladevcp' . These are the gladevcp command line options:

Usage: gladevcp [options] myfile.ui

Options:

-h, --help::
    show this help message and exit

-c NAME::
    Set component name to NAME. Default is base name of UI file

-d::
    Enable debug output

-g GEOMETRY::
     Set geometry WIDTHxHEIGHT+XOFFSET+YOFFSET. Values are in pixel units,
    XOFFSET/YOFFSET is referenced from top left of screen.
    Use -g WIDTHxHEIGHT for just setting size or -g +XOFFSET+YOFFSET for just
    position 

-H FILE::
    execute hal statements from FILE with halcmd after the
    component is set up and ready

-m MAXIMUM::
    force panel window to maximize.  Together with the -g geometry option 
    one can move the panel to a second monitor and force it to use all of the screen

-t THEME::
    set gtk theme. Default is system theme. Different panels can have different themes.
    An example theme can be found in the http://wiki.linuxcnc.org/cgi-bin/emcinfo.pl?GTK_Themes[EMC Wiki].

-x XID::
     Re-parent GladeVCP into an existing window XID instead of creating a
    new top level window

-u FILE::
    Use File's as additional user defined modules with handlers

-U USEROPT::
    pass USEROPTs to Python modules

== HAL Widget reference

GladeVcp includes a collection of Gtk widgets with attached HAL pins
called HAL Widgets, intended to control, display or otherwise interact
with the LinuxCNC HAL layer. They are intended to be used with the Glade
user interface editor. With proper installation, the HAL Widgets should
show up in Glade's 'HAL Python' widget group. Many HAL specific fields
in the Glade 'General' section have an associated mouse-over tool tip.

HAL signals come in two variants, bits and numbers. Bits are off/on
signals. Numbers can be "float", "s32" or "u32". For more information
on HAL data types see the <<sec:Hal-Data,HAL manual>>. The GladeVcp
widgets can either display the value of the signal with an indicator
widget, or modify the signal value with a control widget. Thus there
are four classes of GladeVcp widgets that you can connect to a HAL
signal. Another class of helper widgets allow you to organize and
label your panel.

 - Widgets for indicating "bit" signals: <<gladevcp:HAL_LED,HAL_LED>>
 - Widgets for controlling "bit" signals: <<gladevcp:HAL_Button,HAL_Button>>,
   <<gladevcp:HAL_RadioButton,HAL_RadioButton>>,
   <<gladevcp:HAL_CheckButton,HAL_CheckButton>>
 - Widgets for indicating "number" signals: <<gladevcp:HAL_Label,HAL_Label>>,
   <<gladevcp:HAL_ProgressBar,HAL_ProgressBar>>,
   <<gladevcp:HAL_HBar,HAL_HBar>>, <<gladevcp:HAL_VBar,HAL_VBar>>,
   <<gladevcp:HAL_Meter,HAL_Meter>>
 - Widgets for controlling "number" signals: <<gladevcp:HAL_SpinButton,HAL_SpinButton>>,
   <<gladevcp:HAL_HScale,HAL_HScale>>,
   <<gladevcp:HAL_VScale,HAL_VScale>>
 - Helper widgets: <<gladevcp:HAL_Table,HAL_Table>>, <<gladevcp:HAL_HBox,HAL_HBox>>
 - Tool Path preview: <<gladevcp:HAL_Gremlin,HAL_Gremlin>>

HAL Widgets inherit methods, properties and signals from the
underlying Gtk widgets, so it is helpful to consult the
http://www.gtk.org/[GTK+] and http://www.pygtk.org/[PyGTK bindings]
documentation as well.


=== Widget and HAL pin naming

Most HAL widgets have a single associated HAL pin with the same name
as the widget (glade: General→Name).

Exceptions to this rule currently are.

- 'HAL_Spinbutton' and 'HAL_ComboBox', which have two pins: a +<widgetname>-f+ (float) and a +<widgetname>-s+ (s32) pin
- 'HAL_ProgressBar', which has a +<widgetname>-value+ input pin, and a +<widgetname>-scale+ input pin.

=== Setting pin and widget values

As a general rule, if you need to set a HAL output widget's value from
Python code, do so by calling the underlying Gtk 'setter' (e.g.
+set_active()+, +set_value()+) - do not try to set the associated pin's
value by +halcomp[pinname] = value+ directly because the widget will not
take notice of the change!.

It might be tempting to 'set HAL widget input pins' programmatically.
Note this defeats the purpose of an input pin in the first place - it
should be linked to, and react to signals generated by other HAL
components. While there is currently no write protection on writing to
input pins in HAL Python, this doesn't make sense. You might use setp
pinname value in the associated halfile for testing though.

It is perfectly OK to set an output HAL pin's value with
+halcomp[pinname] = value+ provided this HAL pin is not associated with a
widget, that is, has been created by the
+hal_glib.GPin(halcomp.newpin(<name>,<type>,<direction>)+ method (see
GladeVCP Programming for an example).

[[gladevcp::hal-pin-changed_signal]]
=== The hal-pin-changed signal

Event-driven programming means that the UI tells your code when "something
happens" - through a callback, like when a button was pressed. The
output HAL widgets (those which display a HAL pin's value) like LED,
Bar, VBar, Meter etc, support the 'hal-pin-changed' signal which may
cause a callback into your Python code when - well, a HAL pin changes
its value. This means there's no more need for permanent polling of HAL
pin changes in your code, the widgets do that in the background and let
you know.

Here is an example how to set a +hal-pin-changed+ signal for a HAL_LED
in the Glade UI editor:

image::images/hal-pin-change-66.png[]
The example in +configs/gladevcp/examples/complex+ shows how
this is handled in Python.


[[gladevcp:HAL_Button]]
=== Button

[[gladevcp:HAL_RadioButton]]
=== RadioButton

[[gladevcp:HAL_CheckButton]]
=== CheckButton

This group of widgets are derived from various Gtk buttons and consists
of HAL_Button, HAL_ToggleButton, HAL_RadioButton and CheckButton
widgets. All of them have a single output BIT pin named identical to
the widget. Buttons have no additional properties compared to their
base Gtk classes.

 - HAL_Button: instantaneous action, does not retain state. Important
   signal: +pressed+
 - HAL_ToggleButton, HAL_CheckButton: retains on/off state. Important
   signal: +toggled+
 - HAL_RadioButton: a one-of-many group. Important signal: +toggled+ (per
   button).
 - Important common methods: +set_active()+, +get_active()+
 - Important properties: +label+, +image+


// .Buttons
Check button:
image:images/checkbutton.png[]
Radio buttons:
image:images/radiobutton.png[]
Toggle button:
image:images/button.png[]
.

[TIP]
======================================
Defining radio button groups in Glade:

- decide on default active button

- in the other button's 'General→Group' select the default active
button's name in the 'Choose a Radio Button in this project' dialog.

See +configs/gladevcp/by-widget/radiobutton+ for a GladeVCP application
and UI file for working with radio buttons.
======================================


[[gladevcp:HAL_HScale]]
=== HScale

[[gladevcp:HAL_VScale]]
=== VScale

HAL_HScale and HAL_VScale are derived from the GtkHScale and GtkVScale
respectively. They have one output FLOAT pin with name equal to widget
name. Scales have no additional properties.

To make a scale useful in Glade, add an 'Adjustment'
(General→Adjustment→New or existing adjustment) and edit the
adjustment object. It defines the default/min/max/increment 
values. Also, set adjustment 'Page size' and 'Page increment' to zero
to avoid warnings.

Example HAL_HScale:
image:images/hscale.png[]
.

[[gladevcp:HAL_SpinButton]]
=== SpinButton

HAL SpinButton is derived from GtkSpinButton and holds two pins:

<widgetname>-f::
	 out FLOAT pin
<widgetname>-s::
	 out S32 pin

To be useful, Spinbuttons need an adjustment value like scales,
see above.

Example SpinButton:
image:images/spinbutton.png[]
.

[[gladevcp:HAL_Label]]
=== Label

HAL_Label is a simple widget based on GtkLabel which represents a HAL
pin value in a user-defined format.

label_pin_type::
	The pin's HAL type  (0:S32, 1:float, 2:U32), see also the tooltip
	on 'General→HAL pin type '(note this is different from PyVCP which has
	three label widgets, one for each type).

text_template::
	Determines the text displayed - a Python
	format string to convert the pin value to text. Defaults to +%s+ (values
	are converted by the str() function) but may contain any legit as an
	argument to Pythons format() method. +
	Example: +Distance: %.03f+ will display the text and the pin value with
	3 fractional digits padded with zeros for a FLOAT pin.


[[gladevcp:HAL_HBox]]
=== Container: HAL_Box

[[gladevcp:HAL_Table]]
=== Container: HAL_Table

Compared to their Gtk counterparts they have one input BIT pin which
controls if their child widgets are sensitive or not. If the pin is low
then child widgets are inactive which is the default.

[TIP]
If you find some part of your GladeVCP application is 'grayed
out' (insensitive), see whether a container's pin is unset.

[[gladevcp:HAL_LED]]
=== LED

The hal_led simulates a real indicator LED. It has a single input BIT
pin which controls it's state: ON or OFF. LEDs have several properties
which control their look and feel:

on_color::
   a String defining ON color of LED. May be any valid
   gtk.gdk.Color name. Not working on Ubuntu 8.04.
off_color::
   String defining OFF color of LED. May be any valid
   gtk.gdk.Color name or special value `dark`. `dark` means that OFF color
   will be set to 0.4 value of ON color. Not working on Ubuntu 8.04.
pick_color_on, pick_color_off::
   Colors for ON and OFF states may be
   represented as `#RRRRGGGGBBBB` strings. These are optional properties
   which have precedence over `on_color` and `off_color`.
led_size::
   LED radius (for square - half of LED's side)
led_shape::
   LED Shape. Valid values are 0 for round, 1 for oval and 2
   for square shapes.
led_blink_rate::
   if set and LED is ON then it's blinking. Blink
   period is equal to "led_blink_rate" specified in milliseconds.

As an input widget, LED also supports the +hal-pin-changed signal+. If
you want to get a notification in your code when the LED's HAL pin was
changed, then connect this signal to a handler, for example
+on_led_pin_changed+ and provide the handler as follows:

[source,python]
----------------------------------
def on_led_pin_changed(self,hal_led,data=None):
    print "on_led_pin_changed() - HAL pin value:",hal_led.hal_pin.get()
----------------------------------

This will be called at any edge of the signal and also during program
start up to report the current value.

Example LEDs:
image:images/leds.png[]
.

[[gladevcp:HAL_ProgressBar]]
=== ProgressBar

[NOTE]
This widget might go away. Use the HAL_HBar and HAL_VBar widgets
instead.

The HAL_ProgressBar is derived from gtk.ProgressBar and has two float
HAL input pins:

<widgetname>::
	the current value to be displayed
<widgetname>-scale::
	the maximum absolute value of input

It has the following properties:

scale::
	value scale. set maximum absolute value of input. Same as
	setting the <widgetname>.scale pin. A float, range from
	-2^24 to +2^24.
green_limit::
      green zone limit lower limit
yellow_limit::
      yellow zone limit lower limit
red_limit::
      red zone limit lower limit
text_template::
      Text template to display the current value of the
      +<widgetname>+ pin. Python formatting may be used for dict
      +{"value":value}+

Example HAL_ProgressBar:
image:images/progressbar2.png[]
.

[[gladevcp:HAL_ComboBox]]
=== ComboBox

HAL_ComboBox is derived from gtk.ComboBox. It enables choice of a
value from a dropdown list.

It exports two HAL pins:

 <widgetname>-f::
		  the current value, type FLOAT
 <widgetname>-s::
		  the current value, type S32

It has the following property which can be set in Glade:

column::
	 the column index, type S32, defaults to -1, range from -1..100 .

In default mode this widgets sets the pins to the index of the chosen
list entry. So if your widget has three labels, it may only assume
values 0,1 and 2.

In column mode (column > -1), the value reported is chosen from the
ListStore array as defined in Glade. So typically your widget
definition would have two columns in the ListStore , one with text
displayed in the dropdown, and an int or float value to use for that
choice.

There's an example in
+configs/gladevcp/by-widget/combobox/combobox.{py,ui}+ which uses column
mode to pick a float value from the ListStore.

If you're confused like me about how to edit ComboBox ListStores and
CellRenderer, see http://www.youtube.com/watch?v=Z5_F-rW2cL8.


[[gladevcp:HAL_HBar]]
=== HBar


[[gladevcp:HAL_VBar]]
=== VBar

HAL Bar and VBar widgets for horizontal and vertical bars representing
float values. They have one input FLOAT hal pin. Both bars have the
following properties:

invert::
   Swap min and max direction. An inverted HBar grows from right
   to left, an inverted VBar from top to bottom.
min, max::
   Minimum and maximum value of desired range. It is not an
   error condition if the current value is outside this range.
zero::
   Zero point of range. If it's inside of min/max range then the
   bar will grow from that value and not from the left (or right) side of
   the widget. Useful to represent values that may be both positive or
   negative.
force_width, force_height::
   Forced width or height of widget. If not
   set then size will be deduced from packing or from fixed widget size
   and bar will fill whole area.
text_template::
   Like in Label sets text format for min/max/current
   values. Can be used to turn off value display.
bg_color::
   Background (inactive) color of bar.
z0_color, z1_color, z2_color::
   Colors of different value zones.
   Defaults are `green`, `yellow` and `red`. For description of zones see
   `z*_border` properties.
z0_border, z1_border::
   Define up bounds of color zones. By default
   only one zone is enabled. If you want more then one zone set
   `z0_border` and `z1_border` to desired values so zone 0 will fill from
   0 to first border, zone 1 will fill from first to second border and
   zone 2 -- from last border to 1. Borders are set as fractions, values
   from 0 to 1.

Horizontal bar:
image:images/hal_hbar.png[]
Vertical bar:
image:images/vscale.png[]
.

[[gladevcp:HAL_Meter]]
=== Meter

HAL Meter is a widget similar to PyVCP meter - it represents a float value and has 
one input FLOAT hal pin. HAL Meter has the following properties:

min, max::
   Minimum and maximum value of desired range. It is not an
   error condition if the current value is outside this range.
force_size::
   Forced diameter of widget. If not set then size will be
   deduced from packing or from fixed widget size and meter will fill all
   available space with respect to aspect ratio.
text_template::
   Like in Label sets text format for current value. Can
   be used to turn off value display.
label::
   Large label above center of meter.
sublabel::
   Small label below center of meter.
bg_color::
   Background color of meter.
z0_color, z1_color, z2_color::
   Colors of different value
   zones. Defaults are `green`, `yellow` and `red`. For description of
   zones see `z*_border` properties.
z0_border, z1_border::
   Define up bounds of color zones. By default only
   one zone is enabled. If you want more then one zone set `z0_border` and
   `z1_border` to desired values so zone 0 will fill from min to first
   border, zone 1 will fill from first to second border and zone 2 -- from
   last border to max. Borders are set as values in range min-max.

Example HAL Meters:
image:images/hal_meter.png[]
.

[[gladevcp:HAL_Gremlin]]
=== Gremlin tool path preview for .ngc files

Gremlin is a plot preview widget similar to the Axis preview window.
It assumes a running LinuxCNC environment like Axis or Touchy. To connect to
it, inspects the INI_FILE_NAME environment variable. Gremlin displays
the current .ngc file - it does monitor for changes and reloads the ngc
file if the file name in Axis/Touchy changes. If you run it in a
GladeVCP application when LinuxCNC is not running, you might get a traceback
because the Gremlin widget can't find LinuxCNC status, like the current file
name.

Gremlin does not export any HAL pins. It has the following properties:

view ::
   may be any of `x`, `y`, `z`, `p` (perspective) . Defaults to
   `z` view.
enable_dro ::
   boolean; whether to draw a DRO on the plot or not.
   Defaults to `True`.

Example:
image:images/gremlin.png[]


=== Animated function diagrams: HAL widgets in a bitmap

For some applications it might be desirable to have background image -
like a functional diagram - and position widgets at appropriate places
in that diagram. A good combination is setting a bitmap background
image, like from a .png file, making the gladevcp window fixed-size,
and use the glade Fixed widget to position widgets on this image.

The code for the below example can be found in +configs/gladevcp/animated-backdrop+:

image:images/small-screenshot.png[]

== Action Widgets reference

GladeVcp includes a collection of "canned actions" called EMC Action
Widgets for the Glade user interface editor. Other than HAL widgets,
which interact with HAL pins, EMC Actions interact with LinuxCNC and the
G-code interpreter.

EMC Action Widgets are derived from the Gtk.Action widget. The Action
widget in a nutshell:

 - it is an object available in Glade
 - it has no visual appearance by itself
 -  it's purpose: associate a visible, sensitive UI component like menu,
   toolbutton, button with a command. See these widget's 'General→Related
   Action' property.
 -  the "canned action" will be executed when the associated UI component
   is triggered (button press, menu click..)
 -  it provides an easy way to execute commands without resorting to
   Python programming.

The appearance of EMC Actions in Glade is roughly as follows:

image::images/emc-actions.png[]

Tooltip hovers provide a description.


=== EMC Action widgets

EMC Action widgets are one-shot type widgets. They implement a single action and
are for use in simple buttons, menu entries or radio/check groups.

=== EMC ToggleAction widgets

These are bi-modal widgets. They implement two actions or use a second
(usually pressed) state to indicate that currently an action is
running. Toggle actions are aimed for use in ToggleButtons,
ToggleToolButtons or toggling menu items. A simplex example is the
ESTOP toggle button.

Currently the following widgets are available:

 - The ESTOP toggle sends ESTOP or ESTOP_RESET commands to LinuxCNC depending
   on it's state.
 - The ON/OFF toggle sends STATE_ON and STATE_OFF commands.
 - Pause/Resume sends AUTO_PAUSE or AUTO_RESUME commands.

The following toggle actions have only one associated command and use
the 'pressed' state to indicate that the requested operation is
running:

 - The Run toggle sends an AUTO_RUN command and waits in the pressed
   state until the interpreter is idle again.
 - The Stop toggle is inactive until the interpreter enters the active
   state (is running G-code) and then allows user to send AUTO_ABORT
   command.
 - The MDI toggle sends given MDI command and waits for its completion in
   'pressed' inactive state.

=== The Action_MDI Toggle and Action_MDI widgets

These widgets provide a means to execute arbitrary MDI commands. The
Action_MDI widget does not wait for command completion as the
Action_MDI Toggle does, which remains disabled until command complete.

=== A simple example: Execute MDI command on button press

+configs/gladevcp/mdi-command-example/whoareyou.ui+ is a Glade UI file which conveys the basics:

Open it in Glade and study how it's done. Start Axis, and then start
this from a terminal window with `gladevcp whoareyou.ui`. See the
+hal_action_mdi1+ Action and it's +MDI command+ property - this just
executes +(MSG, "Hi, I'm an EMC_Action_MDI")+ so there should be a
message popup in Axis like so:

image::images/whoareyou.png[]

You'll notice that the button associated with the Action_MDI action is
grayed out if the machine is off, in E-Stop or the interpreter is running.
It will automatically become active when the machine is turned on and
out of E-Stop, and the program is idle.

=== Parameter passing with Action_MDI and ToggleAction_MDI widgets

Optionally, 'MDI command' strings may have parameters substituted
before they are passed to the interpreter. Parameters currently may be
names of HAL pins in the GladeVCP component. This is how it works:

 - assume you have a 'HAL SpinBox' named +speed+, and you want to pass it's
   current value as a parameter in an MDI command.
 - The HAL SpinBox will have a float-type HAL pin named speed-f (see
   HalWidgets description).
 - To substitute this value in the MDI command, insert the HAL pin name
   enclosed like so: `${pin-name}`
 - for the above HAL SpinBox, we could use `(MSG, "The speed is:
   ${speed-f}")` just to show what's happening.

The example UI file is +configs/gladevcp/mdi-command-example/speed.ui+. Here's what you get when running it:


image::images/speed.png[]

=== An advanced example: Feeding parameters to an O-word subroutine

It's perfectly OK to call an O-word subroutine in an MDI command, and
pass HAL pin values as actual parameters. An example UI file
is in +configs/gladevcp/mdi-command-example/owordsub.ui+.

Place +configs/gladevcp/nc_files/oword.ngc+ so Axis can find it, and run `gladevcp owordsub.ui` from
a terminal window. This looks like so:

image::images/oword.png[]

=== Preparing for an MDI Action, and cleaning up afterwards

The LinuxCNC G-Code interpreter has a single global set of variables, like
feed, spindle speed, relative/absolute mode and others. If you use G
code commands or O-word subs, some of these variables might get changed
by the command or subroutine - for example, a probing subroutine will
very likely set the feed value quite low. With no further precautions,
your previous feed setting will be overwritten by the probing
subroutine's value.

To deal with this surprising and undesirable side effect of a given
O-word subroutine or G-code statement executed with an LinuxCNC
ToggleAction_MDI, you might associate pre-MDI and post-MDI handlers
with a given LinuxCNC ToggleAction_MDI. These handlers are optional and
provide a way to save any state before executing the MDI Action, and to
restore it to previous values afterwards. The signal names are +mdi-command-start+
and +mdi-command-stop+; the handler names can be set in Glade like any
other handler.

Here's an example how a feed value might be saved and restored by such
handlers (note that LinuxCNC command and status channels are available as
+self.emc+ and +self.stat+ through the EMC_ActionBase class:

[source,python]
----------------------------------
    def on_mdi_command_start(self, action, userdata=None):
        action.stat.poll()
        self.start_feed = action.stat.settings[1]
    
    def on_mdi_command_stop(self, action, userdata=None):
        action.emc.mdi('F%.1f' % (self.start_feed))
        while action.emc.wait_complete() == -1:
            pass
----------------------------------

Only the Action_MDI Toggle widget supports these signals.

[NOTE]
In a later release of LinuxCNC, the new M-codes M70-M72 are available which
make it saving state before a subroutine call, and restoring state on return much easier.

=== Using the LinuxCNC Stat object to deal with status changes

Many actions depend on LinuxCNC status - is it in manual, MDI or auto mode?
is a program running, paused or idle? You cannot start an MDI command
while a G-code program is running, so this needs to be taken care of.
Many LinuxCNC actions take care of this themselves, and related buttons and
menu entries are deactivated when the operation is currently
impossible.

When using Python event handlers - which are at a lower level than
Actions - one needs to take care of dealing with status dependencies
oneself. For this purpose, there's the LinuxCNC Stat widget: to associate
LinuxCNC status changes with event handlers.

LinuxCNC Stat has no visible component - you just add it to your UI with
Glade. Once added, you can associate handlers with its following
signals:

* state-related:     emitted when E-Stop condition occurs, is reset, machine is turned on, or is turned off
  - +state-estop+
  - +state-estop-reset+
  - +state-on+,
  - +state-off+
* mode-related:    emitted when LinuxCNC enters that particular mode
  - +mode-manual+
  - +mode-mdi+
  - +mode-auto+
* interpreter-related:  emitted when the G-code interpreter changes into that mode
  - +interp-run+
  - +interp-idle+
  - +interp-paused+
  - +interp-reading+
  - +interp-waiting+



[[gladevcp:GladeVCP_Programming]]
== GladeVCP Programming

=== User Defined Actions

Most widget sets, and their associated user interface editors, support
the concept of callbacks - functions in user-written code which are
executed when 'something happens' in the UI - events like mouse clicks,
characters typed, mouse movement, timer events, window hiding and
exposure and so forth.

HAL output widgets typically map input-type events like a button press
to a value change of the associated HAL pin by means of such a -
predefined - callback. Within PyVCP, this is really the only type of event
handling supported - doing something more complex, like executing MDI
commands to call a G-code subroutine, is not supported.

Within GladeVCP, HAL pin changes are just one type of the general
class of events (called signals) in GTK+. Most widgets may originate such
signals, and the Glade editor supports associating such a signal with a
Python method or function name.

If you decide to use user-defined actions, your job is to write a
Python module whose class methods - or in the simple case, just
functions - can be referred to in Glade as event handlers. GladeVCP
provides a way to import your module(s) at startup and will
automatically link your event handlers with the widget signals as set
in the Glade UI description.

=== An example: adding custom user callbacks in Python

This is just a minimal example to convey the idea - details are laid
out in the rest of this section.

GladeVCP can not only manipulate or display HAL pins, you can also
write regular event handlers in Python. This could be used, among
others, to execute MDI commands. Here's how you do it:

Write a Python module like so and save as e.g. handlers.py:

[source,python]
----------------------------------
nhits = 0
def on_button_press(gtkobj,data=None):
    global nhits nhits += 1 gtkobj.set_label("hits: %d" % nhits)
----------------------------------

In Glade, define a button or HAL button, select the 'Signals' tab, and
in the GtkButton properties select the 'pressed' line. Enter
'on_button_press' there, and save the Glade file.

Then add the option '-u handlers.py' to the gladevcp command line. If
your event handlers are spread over several files, just add multiple
'-u <pyfilename>' options.

Now, pressing the button should change its label since it's set in the
callback function.

What the +-u+ flag does: all Python functions in this file are
collected and setup as potential callback handlers for your Gtk widgets
- they can be referenced from Glade 'Signals' tabs. The callback
handlers are called with the particular object instance as parameter,
like the GtkButton instance above, so you can apply any GtkButton
method from there.

Or do some more useful stuff, like calling an MDI command!

=== HAL value change events

HAL input widgets, like a LED, automatically associate their HAL pin state
(on/off) with the optical appearance of the widget (LED lit/dark).

Beyond this builtin functionality, one may associate a change
callback with any HAL pin, including those of predefined HAL
widgets. This fits nicely with the event-driven structure of a typical
widget application: every activity, be it mouse click, key, timer
expired, or the change of a HAL pin's value, generates a callback and
is handled by the same orthogonal mechanism.

For user-defined HAL pins not associated with a particular HAL widget,
the signal name is 'value-changed'. See the
<<gladevcp:Adding_HAL_pins,Adding HAL pins>> section below for
details.

HAL widgets come with a pre-defined signal called 'hal-pin-changed'. See the
<<gladevcp::hal-pin-changed_signal,Hal Widgets section>> for details. 


=== Programming model

The overall approach is as follows:

 - design your UI with Glade, and set signal handlers where you want
   actions associated with a widget
 - write a Python module which contains callable objects (see 'handler
   models' below)
 - pass your module's path name to gladevcp with the '-u <module>' option
 - gladevcp imports the module, inspects it for signal handlers and
   connects them to the widget tree
 - the main event loop is run.

==== The simple handler model

For simple tasks it's sufficient to define functions named after the
Glade signal handlers. These will be called when the corresponding
event happens in the widget tree. Here's a trivial example - it assumes
that the 'pressed' signal of a Gtk Button or HAL Button is linked to a
callback called 'on_button_press':

[source,python]
----------------------------------
nhits = 0
def on_button_press(gtkobj,data=None):
    global nhits
    nhits += 1
    gtkobj.set_label("hits: %d" % nhits)
----------------------------------

Add this function to a Python file and run as follows:

    gladevcp -u <myhandler>.py mygui.ui

Note communication between handlers has to go through global
variables, which does not scale well and is positively un-pythonic.
This is why we came up with the class-based handler model.

==== The class-based handler model

The idea here is: handlers are linked to class methods. The underlying
class(es) are instantiated and inspected during GladeVCP startup and
linked to the widget tree as signal handlers. So the task now is to
write:

 -  one or more several class definition(s) with one or several methods,
   in one module or split over several modules,
 -  a function 'get_handlers' in each module which will return a list of
   class instances to GladeVCP - their method names will be linked to
   signal handlers

Here is a minimum user-defined handler example module:

[source,python]
----------------------------------
class MyCallbacks :
    def on_this_signal(self,obj,data=None):
        print "this_signal happened, obj=",obj
    def get_handlers(halcomp,builder,useropts):
        return [MyCallbacks ()]
----------------------------------

Now, 'on_this_signal' will be available as signal handler to your
widget tree.

==== The get_handlers protocol

If during module inspection GladeVCP finds a function `get_handlers`,
it calls it as follows:

    get_handlers(halcomp,builder,useropts)

the arguments are:

 - halcomp - refers to the HAL component under construction
 - builder - widget tree - result of reading the UI definition (either
   referring to a GtkBuilder or libglade-type object)
 - useropts - a list of strings collected from the gladevcp 
   command line `-U <useropts>` option

GladeVCP then inspects the list of class instances and retrieves their
method names. Qualifying method names are connected to the widget tree
as signal handlers. Only method names which do not begin with an '_'
(underscore) are considered.

Note that regardless whether you're using the libglade or the new
GtkBuilder format for your Glade UI, widgets can always be referred to
as `builder.get_object(<widgetname>)`. Also, the complete list of
widgets is available as `builder.get_objects()` regardless of UI
format.

=== Initialization sequence

It is important to know in which state of affairs your `get_handlers()`
function is called so you know what is safe to do there and what not.
First, modules are imported and initialized in command line order.
After successful import, `get_handlers()` is called in the following
state:

 -  the widget tree is created, but not yet realized (no toplevel
   `window.show()` has been executed yet)
 -  the halcomp HAL component is set up and all HAL widget's pins have
   already been added to it
 -  it is safe to add more HAL pins because `halcomp.ready()` has not yet
   been called at this point, so you may add your own pins, for instance
   in the class `__init__()` method.

Once all modules have been imported and method names extracted, the
following steps happen:

 -  all qualifying method names will be connected to the widget tree with
   `connect_signals()/signal_autoconnect()` (depending on the type of UI
   imported - GtkBuilder vs the old libglade format).
 - the HAL component is finalized with halcomp.ready()
 -  if a window ID was passed as argument, the widget tree is re-parented
   to run in this window, and Glade's toplevel window1 is abandoned (see
   FAQ)
 -  if a HAL command file was passed with `-H halfile`, it is executed
   with halcmd
 - the Gtk main loop is run.

So when your handler class is initialized, all widgets are existent
but not yet realized (displayed on screen). And the HAL component isn't
ready as well, so its unsafe to access pins values in your `__init__()`
method.

If you want to have a callback to execute at program start after it is
safe to access HAL pins, then a connect a handler to the realize signal
of the top level window1 (which might be its only real purpose). At
this point GladeVCP is done with all setup tasks, the halfile has been
run, and GladeVCP is about to enter the Gtk main loop.

=== Multiple callbacks with the same name

Within a class, method names must be unique. However, it is OK to have
multiple class instances passed to GladeVCP by get_handlers() with
identically named methods. When the corresponding signal occurs, these
methods will be called in definition order - module by module, and
within a module, in the order class instances are returned by
`get_handlers()`.

=== The GladeVCP `-U <useropts>` flag

Instead of extending GladeVCP for any conceivable option which could
potentially be useful for a handler class, you may use the -U
<useroption> flag (repeatedly if you wish). This flag collects a list
of <useroption> strings. This list is passed to the get_handlers()
function (useropts argument). Your code is free to interpret these
strings as you see fit. An possible usage would be to pass them to the
Python exec function in your `get_handlers()` as follows:

[source,python]
----------------------------------
debug = 0
...
def get_handlers(halcomp,builder,useropts):
    ...
    global debug # assuming there's a global var
    for cmd in useropts:
        exec cmd in globals()
----------------------------------

This way you can pass arbitrary Python statements to your module
through the gladevcp -U option, for example:

    gladevcp -U debug=42 -U "print 'debug=%d' % debug" ...

This should set debug to 2 and confirm that your module actually did it.

=== Persistent variables in GladeVCP

A annoying aspect of GladeVCP in its earlier form and pyvcp is the
fact that you may change values and HAL pins through text entry,
sliders, spin boxes, toggle buttons etc, but their settings are not
saved and restored at the next run of LinuxCNC - they start at the default
value as set in the panel or widget definition.

GladeVCP has an easy-to-use mechanism to save and restore the state of
HAL widgets, and program variables (in fact any instance attribute of
type int, float, bool or string).

This mechanism uses the popular '.ini' file format to save and reload
persistent attributes.

==== Persistence, program versions and the signature check

Imagine renaming, adding or deleting widgets in Glade:
an .ini file lying around from a previous program version, or an
entirely different user interface, would be not be able to restore the
state properly since variables and types might have changed.

GladeVCP detects this situation by a signature which depends on all
object names and types which are saved and to be restored. In the case
of signature mismatch, a new .ini file with default settings is
generated.

=== Using persistent variables

If you want any of Gtk widget state, HAL widgets output pin's values
and/or class attributes of your handler class to be retained across
invocations, proceed as follows:

 - import the +gladevcp.persistence+ module
 - decide which instance attributes, and their default values you want to
   have retained, if any
 - decide which widgets should have their state retained
 - describe these decisions in your handler class' +__init__()+ method
   through a nested dictionary as follows:

[source,python]
----------------------------------
def __init__(self, halcomp,builder,useropts):
    self.halcomp = halcomp
    self.builder = builder
    self.useropts = useropts
    self.defaults = {
        # the following names will be saved/restored as method attributes
        # the save/restore mechanism is strongly typed - the variables type will be derived from the type of the
        # initialization value. Currently supported types are: int, float, bool, string
        IniFile.vars : { 'nhits' : 0, 'a': 1.67, 'd': True ,'c' : "a string"},
        # to save/restore all widget's state which might remotely make sense, add this:
        IniFile.widgets : widget_defaults(builder.get_objects())
        # a sensible alternative might be to retain only all HAL output widgets' state:
        # IniFile.widgets: widget_defaults(select_widgets(self.builder.get_objects(), hal_only=True,output_only = True)),
    }
----------------------------------

Then associate an .ini file with this descriptor:

[source,python]
----------------------------------
self.ini_filename = __name__ + '.ini'
self.ini = IniFile(self.ini_filename,self.defaults,self.builder)
self.ini.restore_state(self)
----------------------------------

After `restore_state()`, self will have attributes set if as running the
following:

[source,python]
----------------------------------
self.nhits = 0
self.a = 1.67
self.d = True
self.c = "a string"
----------------------------------

Note that types are saved and preserved on restore. This example
assumes that the ini file didn't exist or had the default values from
self.defaults.

After this incantation, you can use the following IniFil methods:

ini.save_state(obj)::
	 saves objs's attributes as per IniFil.vars
	 dictionary and the widget state as described in IniFile.widgets in
	 self.defaults
ini.create_default_ini()::
	 create a .ini file with default values
ini.restore_state(obj)::
	restore HAL out pins and obj's attributes as
   	saved/initialized to default as above

To save the widget and/or variable state on exit, connect a signal
handler to the +window1+ (toplevel) destroy event:

[source,python]
----------------------------------
def on_destroy(self,obj,data=None):
    self.ini.save_state(self)
----------------------------------

Next time you start the GladeVCP application, the widgets should come
up in the state when the application was closed.

=== Hand-editing .ini files

You can do that, but note that the values in self.defaults override
your edits if there is a syntax or type error in your edit. The error
is detected, a console message will hint about that happened, and the
bad inifile will be renamed to have the .BAD suffix. Subsequent bad ini
files overwrite earlier .BAD files.

[[gladevcp:Adding_HAL_pins]]
=== Adding HAL pins

If you need HAL pins which are not associated with a specific HAL
widget, add them as follows:

[source,python]
----------------------------------
import hal_glib
...
# in your handler class __init__():
self.example_trigger = hal_glib.GPin(halcomp.newpin('example-trigger', hal.HAL_BIT, hal.HAL_IN))
----------------------------------

To get a callback when this pin's value changes, associate a
+value-change+ callback with this pin, add:

[source,python]
----------------------------------
self.example_trigger.connect('value-changed', self._on_example_trigger_change)
----------------------------------

and define a callback method (or function, in this case leave out the
+self+ parameter):

[source,python]
----------------------------------
# note '_' - this method will not be visible to the widget tree
def _on_example_trigger_change(self,pin,userdata=None):
    print "pin value changed to:" % (pin.get())
----------------------------------

=== Adding timers

Since GladeVCP uses Gtk widgets which rely on the
http://www.pygtk.org/pygtk2reference/gobject-functions.html[GObject]
base class, the full glib functionally is available. Here is an
example for a timer callback:

[source,python]
----------------------------------
def _on_timer_tick(self,userdata=None):
    ...
    return True # to restart the timer; return False for on-shot
...
# demonstrate a slow background timer - granularity is one second
# for a faster timer (granularity 1 ms), use this:
# glib.timeout_add(100, self._on_timer_tick,userdata) # 10Hz
glib.timeout_add_seconds(1, self._on_timer_tick)
----------------------------------

=== Examples, and rolling your own GladeVCP application

Visit +emc2/configs/gladevcp+ for running examples and starters for your own projects.


== FAQ

[qanda]
I get an unexpected unmap event in my handler function right after startup. What's this?::
   This is a consequence of your Glade UI file
   having the window1 Visible property set to True, together with
   re-parenting the GladeVCP window into Axis or touchy. The GladeVCP
   widget tree is created, including a top level window, and then
   'reparented into Axis', leaving that toplevel window laying around
   orphaned. To avoid having this useless empty window hanging around, it
   is unmapped (made invisible), which is the cause of the unmap signal
   you get. Suggested fix: set window1.visible to False, and ignore an
   initial unmap event.
My GladeVCP program starts, but no window appears where I expect it to be?::
   The window Axis allocates for GladeVCP will obtain the 'natural
   size' of all its child widgets combined. It's the child widget's job to
   request a size (width and/or height). However, not all widgets do
   request a width greater than 0, for instance the Graph widget in its
   current form. If there's such a widget in your Glade file and it's the
   one which defines the layout you might want to set its width
   explicitly. Note that setting the window1 width and height properties
   in Glade does not make sense because this window will be orphaned
   during re-parenting and hence its geometry will have no impact on
   layout (see above). The general rule is: if you manually run a UI file
   with 'gladevcp <uifile>' and its window has reasonable geometry, it
   should come up in Axis properly as well.

I want a blinking LED, so I ticked the checkbutton to let it blink with 100msec interval. 
It wont blink, and I get a startup warning: Warning: value "0" of type `gint' is 
invalid or out of range for property `led-blink-rate' of type `gint'?::
   This seems to be a glade bug. Just type over the blink rate field, and save again - this works for me.

My gladevcp panel in Axis doesnt save state when I close Axis, although I defined 
an on_destroy handler linked to the window destroy signal:: 
   Very likely this handler is linked to window1,
   which due to reparenting isnt usable for this purpose. Please link
   the on_destroy handler to the destroy signal of an interior
   window. For instance, I have a notebook inside window1, and linked
   on_destroy to the notebooks destroy signal, and that works fine. It
   doesnt work for window1.

// FIXME this is out of date
== Troubleshooting

 -  make sure your have the development version of LinuxCNC installed. You
   don't need the axisrc file any more, this was mentioned in the old
   GladeVcp wiki page.
 -  run GladeVCP or Axis from a terminal window. If you get Python errors,
   check whether there's still a +/usr/lib/python2.6/dist-packages/hal.so+
   file lying around besides the newer
   +/usr/lib/python2.6/dist-packages/_hal.so+ (note underscore); if yes,
   remove the +hal.so+ file. It has been superseded by hal.py in the same
   directory and  confuses the import mechanism.
 -  if you're using run-in-place, do a 'make clean' to remove any
   accidentally left over hal.so file, then 'make'.
 -  if you're using 'HAL_table' or 'HAL_HBox' widgets, be aware they have
   an HAL pin associated with it which is off by default. This pin
   controls whether these container's children are active or not.

== Implementation note: Key handling in Axis

We believe key handling works OK, but since it is new code, we're
telling about it you so you can watch out for problems; please let us
know of errors or odd behavior. This is the story:

Axis uses the TkInter widget set. GladeVCP applications use Gtk
widgets and run in a separate process context. They are hooked into
Axis with the Xembed protocol. This allows a child application like
GladeVCP to properly fit in a parent's window, and - in theory - have
integrated event handling.

However, this assumes that both parent and child application properly
support the Xembed protocol, which Gtk does, but TkInter doesn't. A
consequence of this is that certain keys would not be forwarded from a
GladeVCP panel to Axis properly under all circumstances. One of these
situations was the case when an Entry, or SpinButton widget had focus:
in this case, for instance an Escape key would not have been forwarded
to Axis and cause an abort as it should, with potentially disastrous
consequences.

Therefore, key events in GladeVCP are explicitly handled, and
selectively forwarded to Axis, to assure that such situations cannot
arise. For details, see the `keyboard_forward()` function in
`lib/python/gladevcp/xembed.py`.