File: forms.tcl

package info (click to toggle)
pfm 2.0.8-4
  • links: PTS
  • area: main
  • in suites: sid
  • size: 1,036 kB
  • sloc: tcl: 5,486; sql: 4,835; makefile: 4; sh: 1
file content (1983 lines) | stat: -rw-r--r-- 73,160 bytes parent folder | download | duplicates (4)
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
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
# forms.tcl

image create bitmap ::img::arrow_left \
    -file [file join $::config::installDir arrow-left.xbm] \
    -foreground #000000
image create bitmap ::img::arrow_right \
    -file [file join $::config::installDir arrow-right.xbm] \
    -foreground #000000
image create bitmap ::img::arrow_home \
    -file [file join $::config::installDir arrow-home.xbm] \
    -foreground #000000
image create bitmap ::img::arrow_end \
    -file [file join $::config::installDir arrow-end.xbm] \
    -foreground #000000


class FormWindow {
    protected common windowList {}
    public variable window {}
    protected variable parent
    public variable formName
    protected variable noteBook
    protected variable formDef
    protected variable attribDef
    protected variable attribList
    protected variable modAttribList
    protected variable tabList {}
    protected variable tabObject

    proc closeAllWindows {} {
        foreach window $windowList {
            destroy $window
        }
        return
    }

    constructor {c_parent c_formName} {
        set parent $c_parent
        set formName $c_formName
        setupWindow
        return
    }

    destructor {
        foreach tab $tabList {
            delete object $tab
        }
        set indexDeleted [lsearch -exact $windowList $window]
        set windowList [lreplace $windowList $indexDeleted $indexDeleted]
        return
    }

    protected method setupWindow {} {
        set window [toplevel [appendToPath $parent [namespace tail $this]]]
        lappend windowList $window
        wm geometry $window [join $::geometry::form {x}]
        set noteBook [ttk::notebook $window.nb -takefocus 0]
        set tabOpen [OpenTab "#auto" $noteBook $this]
        addNotebookTab $noteBook [$tabOpen cget -widget] tabOpen
        lappend tabList $tabOpen
        set tabObject([$tabOpen cget -widget]) $tabOpen
        pack $noteBook -side top -expand 1 -fill both
        pack [ttk::sizegrip ${window}.sg] -side top -anchor e
        ttk::notebook::enableTraversal $noteBook
        bind $noteBook <<NotebookTabChanged>> [list $this onTabChange]
        set tpOnly [bindToplevelOnly $window <Destroy> [list delete object $this]]
        bind $tpOnly <Configure> {set ::geometry::form {%w %h}}
        return
    }

    public method removeTab {removedTab} {
        set indexDeleted [lsearch -exact $tabList $removedTab]
        if {$indexDeleted >= 0} then {
            set tabList [lreplace $tabList $indexDeleted $indexDeleted]
        }
        delete object $removedTab
        if {[llength $tabList] == 0} then {
            destroy $window
        } else {
            [lindex $tabList end] setTabLock 0
        }
        return
    }

    public method deleteTabsAbove {tab} {
        set thisTabIdx [lsearch -exact $tabList $tab]
        foreach tabAbove [lrange $tabList [expr $thisTabIdx + 1] end] {
            delete object $tabAbove
        }
        set tabList [lrange $tabList 0 $thisTabIdx]
        return
    }

    public method newFormTab {newFormName formDefDict history} {
        [lindex $tabList end] setTabLock 1
        set newTab [FormTab "#auto" $noteBook $this $newFormName \
            $formDefDict $history]
        lappend tabList $newTab
        set widget [$newTab cget -widget]
        set tabObject($widget) $newTab
        $noteBook add $widget -text $newFormName
        $noteBook select $widget
        return
    }

    public method getTabList {} {
        return $tabList
    }

    public method onTabChange {} {
        set selectedTab $tabObject([$noteBook select])
        focus [$noteBook select]
        $selectedTab tabSelected
        return
    }

    public method setMenubar {menubar} {
        $window configure -menu $menubar
        return
    }

    public method setTitle {title} {
        wm title $window $title
        return
    }

}

class GenTab {
    public variable widget
    protected variable parent
    protected variable formWindow
    public variable formWinPath
    protected variable formName
    protected variable menubar
    protected variable mnForm
    protected variable title
    protected variable tabLock 0
    protected variable tabStatus
    protected variable btnCloseTab
    protected variable btnUnlockTab
    protected variable tabStatBar

    constructor {c_parent c_formWindow c_formName} {
        set parent $c_parent
        set formWindow $c_formWindow
        set formName $c_formName
        set formWinPath [$formWindow cget -window]
        set widget [ttk::frame [appendToPath $parent [namespace tail $this]] \
            -takefocus 0]
        set tabStatBar [ttk::frame $widget.sb]
        set tabStatus [ttk::label $tabStatBar.lbl -text {} \
            -foreground {red3}]
        set btnCloseTab [defineButton $tabStatBar.btnClose $widget \
            btnCloseTab [list $this closeTab]]
        $btnCloseTab configure -style SButton
        set btnUnlockTab [defineButton $tabStatBar.btnUnlock $widget \
            btnUnlockTab [list $this unlockTab]]
        $btnUnlockTab configure -style SButton
        $btnUnlockTab state {disabled}
        grid $tabStatus -column 0 -row 0
        grid $btnUnlockTab -column 1 -row 0 -pady {5 5}
        grid $btnCloseTab -column 2 -row 0 -pady {5 5}
        grid columnconfigure $tabStatBar 0 -weight 1
        pack $tabStatBar -side top -fill x
        set menubar [menu [appendToPath $formWinPath \
            mb[namespace tail $this]] -tearoff 0]
        set mnForm [menu $menubar.mnForm -tearoff 0]
        addMenuItem $mnForm mnuUnlockTab command [list $this unlockTab]
        $mnForm entryconfigure 0 -state disabled -accelerator {Esc}
        addMenuItem $mnForm mnuCloseTab command [list $this closeTab]
        $mnForm entryconfigure 1 -accelerator {Esc}
        $mnForm add separator
        addMenuItem $mnForm mnuCloseForm command [list destroy $formWinPath]
        addMenuItem $menubar mnuForm cascade $mnForm
        set title "pfm - [$::dbObject cget -dbname]: $formName"
        bind $widget <KeyPress-Escape> [list $this onEscape]
        return
    }

    destructor {
        # $formWindow tabDestroyed [namespace tail $this]
        destroy $widget
        return
    }

    public method tabSelected {} {
        $formWindow setMenubar $menubar
        $formWindow setTitle $title
        return
    }

    public method onEscape {} {
        if {!$tabLock} then {
            closeTab
        } else {
            unlockTab
        }
        return
    }

    public method unlockTab {} {
        $formWindow deleteTabsAbove [namespace tail $this]
        setTabLock 0
        return
    }

    public method closeTab {} {
        $formWindow removeTab [namespace tail $this]
        return
    }

    public method setTabLock {state} {
        set tabLock $state
        if {$state} then {
            $tabStatus configure -text [mc lbTabLocked]
            $btnCloseTab state {disabled}
            $btnUnlockTab state {!disabled}
            $mnForm entryconfigure 0 -state normal
            $mnForm entryconfigure 1 -state disabled
        } else {
            $tabStatus configure -text {}
            $btnCloseTab state {!disabled}
            $btnUnlockTab state {disabled}
            $mnForm entryconfigure 0 -state disabled
            $mnForm entryconfigure 1 -state normal
        }
        $this propagateTabLock $state
        return
    }

}

class OpenTab {
    inherit GenTab
    protected variable formDef
    protected variable attribDef
    protected variable attribList
    protected variable modAttribList
    protected variable whereSelected 1
    protected variable txt
    protected variable btnRun
    protected variable rbWhere
    protected variable rbOrderby
    protected variable pasteValueMenu 0
    protected variable listBoxList {}

    constructor {c_parent c_formWindow} \
        {GenTab::constructor $c_parent $c_formWindow [$c_formWindow cget -formName]} {
        getFormDef $::dbObject $formName $formWinPath formDef
        getAttribDef $::dbObject $formName $formWinPath \
            attribDef attribList modAttribList
        setupWidget
    }

    destructor {
        deleteAllListBoxes
    }

    protected method setupWidget {} {
        # define menus
        set mnPasteName [menu $menubar.mnPasteName -tearoff 0]
        foreach attrib $attribList {
            $mnPasteName add command -label $attrib \
                -command [list $this pasteName $attrib]
        }
        set mnPasteValue [menu $menubar.mnPasteValue -tearoff 0]
        set pasteValueMenu 0
        foreach attrib $attribList {
            if {$attribDef($attrib,typeofget) in {tgLink tgList}} then {
                $mnPasteValue add command -label $attrib \
                    -command [list $this pasteValue $attrib]
                set pasteValueMenu 1
            }
        }
        addMenuItem $menubar mnuPasteName cascade $mnPasteName
        addMenuItem $menubar mnuPasteValue cascade $mnPasteValue
        if {!$pasteValueMenu} then {
            $menubar entryconfigure 2 -state disabled
        }
        set frmQuery [ttk::frame $widget.frmquery]
        foreach field {Query Where Orderby} {
            set txt($field) [text $frmQuery.txt$field -width 1 -height 1 \
                -wrap word]
            set vsb($field) [ttk::scrollbar $frmQuery.vsb$field \
                -orient vertical -command [list $txt($field) yview]]
            $txt($field) configure -yscrollcommand [list $vsb($field) set]
        }
        $txt(Query) configure -takefocus 0
        $txt(Query) insert end "SELECT $formDef(sqlselect)\n"
        $txt(Query) insert end "FROM $formDef(sqlfrom)\n"
        if {$formDef(groupby) ne {}} then {
            $txt(Query) insert end "GROUP BY $formDef(groupby)\n"
        }
        if {$formDef(sqllimit) ne {}} then {
            $txt(Query) insert end "LIMIT $formDef(sqllimit)\n"
        }
        $txt(Query) configure -state disabled \
            -background $::readonlyBackground
        if {$formDef(sqlorderby) ne {}} then {
            $txt(Orderby) insert end $formDef(sqlorderby)
        }
        set rbWhere [ttk::radiobutton $frmQuery.rbWhere \
            -text WHERE -underline 0 -variable [scope whereSelected] \
            -value 1 -command [list focus $txt(Where)] -takefocus 0]
        if {$formDef(groupby) ne {}} then {
            $rbWhere configure -text HAVING
        }
        set rbOrderby [ttk::radiobutton $frmQuery.rbOrderby \
            -text {ORDER BY} -underline 0 -variable [scope whereSelected] \
            -value 0 -command [list focus $txt(Orderby)] -takefocus 0]
        grid $txt(Query) -column 0 -columnspan 2 -row 0 -sticky wens
        grid $vsb(Query) -column 2 -row 0 -sticky ns
        grid $rbWhere -column 0 -row 1 -sticky n
        grid $txt(Where) -column 1 -row 1 -sticky wens
        grid $vsb(Where) -column 2 -row 1 -sticky ns
        grid $rbOrderby -column 0 -row 2 -sticky n
        grid $txt(Orderby) -column 1 -row 2 -sticky wens
        grid $vsb(Orderby) -column 2 -row 2 -sticky ns
        grid columnconfigure $frmQuery 1 -weight 1
        grid rowconfigure $frmQuery 0 -weight 2
        foreach row {1 2} {
            grid rowconfigure $frmQuery $row -weight 1
        }
        bind $txt(Where) <FocusIn> [list set [scope whereSelected] 1]
        bind $txt(Orderby) <FocusIn> [list set [scope whereSelected] 0]
        focus $txt(Where)
        set btnRun [defineButton $frmQuery.btnRun $widget btnRun \
            [list $this onRun]]
        grid $btnRun -column 0 -columnspan 3 -row 3 -sticky e \
            -pady {10 10} -padx {10 10}
        pack $frmQuery -side top -expand 1 -fill both
        # The following makes $widget receive all events that are sent
        # to its children. This makes it possible to bind keyboard
        # shortcuts that apply to the frame of this tab only
        recursiveAppendTag $widget $widget
        if {$formDef(groupby) ne {}} then {
            bind $widget <Alt-KeyPress-h> \
                [list $rbWhere instate {!disabled} [list $rbWhere invoke]]
        } else {
            bind $widget <Alt-KeyPress-w> \
                [list $rbWhere instate {!disabled} [list $rbWhere invoke]]
        }
        bind $widget <Alt-KeyPress-o> \
            [list $rbOrderby instate {!disabled} [list $rbOrderby invoke]]
        return
    }

    public method propagateTabLock {state} {
        if {$state} then {
            $rbWhere state {disabled}
            $rbOrderby state {disabled}
            $txt(Where) configure -state disabled
            $txt(Orderby) configure -state disabled
            $btnRun state {disabled}
            $menubar entryconfigure 1 -state disabled
            $menubar entryconfigure 2 -state disabled
        } else {
            $rbWhere state {!disabled}
            $rbOrderby state {!disabled}
            $txt(Where) configure -state normal
            $txt(Orderby) configure -state normal
            $btnRun state {!disabled}
            $menubar entryconfigure 1 -state normal
            if {$pasteValueMenu} then {
                $menubar entryconfigure 2 -state normal
            }
        }
        return
    }

    public method onRun {} {
        deleteAllListBoxes
        set formDef(sqlwhere) [string trim [$txt(Where) get 1.0 end]]
        set formDef(sqlorderby) [string trim [$txt(Orderby) get 1.0 end]]
        setTabLock 1
        set history [dict create from {} link {} to [mc histOpenForm $formName]]
        $formWindow newFormTab $formName [array get formDef] [list $history]
        return
    }

    public method pasteName {attrib} {
        if {$whereSelected} then {
            $txt(Where) insert insert "\"${attrib}\""
        } else {
            $txt(Orderby) insert insert "\"${attrib}\""
        }
        return
    }

    public method pasteValue {attrib} {
        switch -- $attribDef($attrib,typeofget) {
            tgLink {
                set query $attribDef($attrib,sqlselect)
            }
            tgList {
                set query "SELECT value, description FROM pfm_value "
                append query "WHERE valuelist = '$attribDef($attrib,valuelist)' "
                append query "ORDER BY value"
            }
            default {
                set query {}
            }
        }
        if {[$::dbObject select_query_list $query numTuples headerList valueList errMsg]} then {
            set lsbTitle [mc selectValueFor $attrib]
            set lsb [ListBox "#auto" $formWinPath $lsbTitle $headerList \
                $valueList 0]
            lappend listBoxList [list $lsb $attrib]
            if {[$lsb wait result]} then {
                if {$attribDef($attrib,typeofattrib) eq {taQuoted}} then {
                    set value "'[lindex $result 0]'"
                } else {
                    set value [lindex $result 0]
                }
                if {$whereSelected} then {
                    $txt(Where) insert insert $value
                } else {
                    $txt(Orderby) insert insert $value
                }
            }
            set lsbToRemove [lsearch -exact -index 0 $listBoxList $lsb]
            set listBoxList [lreplace $listBoxList $lsbToRemove $lsbToRemove]
        } else {
            pfm_message $errMsg $formWinPath
        }
        return
    }

    public method deleteAllListBoxes {} {
        foreach lsb $listBoxList {
            [lindex $lsb 0] destroyWindow
        }
        return
    }

}

class FormTab {
    inherit GenTab
    protected variable formDef
    protected variable history
    protected variable attribDef
    protected variable attribList
    protected variable modAttribList
    protected variable linkDef
    protected variable lastLink
    protected variable frmHistory
    protected variable txtHistory
    protected variable canvas
    protected variable frmForm
    protected variable frmButtons
    protected variable btnArray
    protected variable btnSelect
    protected variable txtMessages
    protected variable control
    protected variable formState {browse}
    protected variable statusbar
    protected variable sbNr
    protected variable sbStatus
    protected variable buffer
    protected variable record
    protected variable recordIdx
    protected variable textEditList
    protected variable listBoxList
    protected variable matchCase 0
    protected variable searchPattern
    protected variable searchAttribute
    protected variable searchFrame {}


    constructor {c_parent c_formWindow c_formName formDefDict c_history} \
        {GenTab::constructor $c_parent $c_formWindow $c_formName} {
        array set formDef $formDefDict
        set history $c_history
        set textEditList(0) {}
        set textEditList(1) {}
        set listBoxList {}
        getAttribDef $::dbObject $formName $formWinPath \
            attribDef attribList modAttribList
        getLinkDef $::dbObject $formName $formWinPath linkDef lastLink
        # Bug 1070:
        # "record" is a Tcl array which always contains the current
        # record. Originally, the array elements record($attrib) were
        # bound to the entry widgets of the form and the element names
        # were the attribute names. However, a bug in Itcl caused the
        # attribute value not to be displayed if the attribute name
        # consists of more than one word. Therefore, the following work
        # around is implemented. Instead of record($attrib),
        # record($recordIdx($attrib)) is bound to the form's entry
        # widgets where recordIdx acts as a conversion table which maps
        # the attribute names ($attrib) to integers.
        # recordIdx is initialised here.
        set index 1
        foreach attrib $attribList {
            set recordIdx($attrib) $index
            incr index
        }
        setupWidget
        set buffer [FormBuf "#auto" [array get formDef] [array get attribDef] \
            $this $attribList $modAttribList]
        $buffer getFirstRecord record recNr status
        updateStatusBar $recNr $status
        return
    }

    destructor {
        delete object $buffer
        deleteAllTextEdits 0
        deleteAllTextEdits 1
        deleteAllListBoxes
        return
    }

    public method propagateTabLock {state} {
        if {$state} then {
            if {$formDef(view) eq {f}} then {
                foreach op {Update Add Delete} {
                    $btnArray($op) state {disabled}
                }
            }
            disableBrowseMenus
            for {set link 0} {$link <= $lastLink} {incr link} {
                $btnArray($link) state {disabled}
            }

            bind $widget <KeyPress-Next> {}
            bind $widget <KeyPress-Prior> {}
            bind $widget <KeyPress-Right> {}
            bind $widget <KeyPress-Left> {}
            bind $widget <KeyPress-Home> {}
            bind $widget <KeyPress-End> {}
            foreach btn {Home Prev Next End} {
                $btnArray($btn) state {disabled}
            }
            bind $widget <KeyPress-F3> {}
            if {$searchFrame ne {}} then {
                foreach op {FindNext Hide} {
                    $btnArray($op) state {disabled}
                }
            }
        } else {
            if {$formDef(view) eq {f}} then {
                foreach op {Update Add Delete} {
                    $btnArray($op) state {!disabled}
                }
            }
            for {set link 0} {$link <= $lastLink} {incr link} {
                $btnArray($link) state {!disabled}
            }
            enableBrowseMenus
            bind $widget <KeyPress-Next> [list $this nextRecord]
            bind $widget <KeyPress-Prior> [list $this prevRecord]
            bind $widget <KeyPress-Right> [list $this nextRecord]
            bind $widget <KeyPress-Left> [list $this prevRecord]
            bind $widget <KeyPress-Home> [list $this firstRecord]
            bind $widget <KeyPress-End> [list $this lastRecord]
            foreach btn {Home Prev Next End} {
                $btnArray($btn) state {!disabled}
            }
            bind $widget <KeyPress-F3> [list $this searchForRecord]
            if {$searchFrame ne {}} then {
                foreach op {FindNext Hide} {
                    $btnArray($op) state {!disabled}
                }
            }
        }
        return
    }

    public method mouseWheel {platform arg} {
        switch $platform {
            windows {
                if {$arg < 0} then {
                    set direction 1
                } else {
                    set direction -1
                }
            }
            unix {
                set direction $arg
            }
        }
        set mouse_x [winfo pointerx $formWinPath]
        set mouse_y [winfo pointery $formWinPath]
        set x1 [winfo rootx $frmForm]
        set y1 [winfo rooty $frmForm]
        set x2 [expr $x1 + [winfo width $frmForm]]
        set y2 [expr $y1 + [winfo height $frmForm]]
        if {($x1 <= $mouse_x) && ($mouse_x <= $x2) && \
            ($y1 <= $mouse_y) && ($mouse_y <= $y2)} then {
            $canvas yview scroll $direction unit
        }
        return
    }

    public method scrollForm {i} {

        # Scroll form such that attribute i is visible in the middle
        # of the form.
        #
        # Let: n1 be index of first visible attribute before scrolling
        #      n2 be index of last visible attribute before scrolling
        #      nn1 be index of first visible attribute after scrolling
        #      nn2 be index of last visible attribute after scrolling
        #      f1 = 1st fraction returned by yview before scrolling (known)
        #      f2 = 2nd fraction returned by yview before scrolling (known)
        #      nf1 = 1st fraction to be given to yview for scrolling
        #      nf2 = 2nd fraction returned by yview after scrolling
        #      n = nr of attributes on form (known)
        #      i = index of attribute with input focus (arg of function)
        #      s = number of visible attributes on screen
        # Known data:
        #     n, f1, f2, i
        # To be calculated:
        #     nf1
        # Calculation:
        #     f1 = (y-coord of first visible horizontal line)
        #                                     /(height of canvas)
        #        = (n1 + 1)/(n + 2)
        #     f2 = (y-coord of last visible horizontal line)
        #                                     /(height of canvas)
        #        = (n2 + 1)/(n + 2)
        #     -- to take into account the empty space at top and bottom
        #     -- we assume 2 dummy attributes, one at top (index "-1"),
        #     -- one at bottom (index "n")
        #     n1 = (n + 2) * f1 - 1
        #     n2 = (n + 2) * f2 - 1
        #     s = n2 - n1 + 1
        #       = (n + 2) * (f2 - f1) + 1   (1)
        #     Afters scrolling, same relationship:
        #     nn1 = (n + 2) * nf1 - 1
        #     nn2 = (n + 2) * nf2 - 1
        #     s = (n + 2) * (nf2 - nf1) + 1  (2)
        #     After scrolling we want i to be in the middle between nn1 and nn2
        #     i = (nn1 + nn2)/2
        #       = (nf1 + nf2) * (n + 2)/2 - 1 (3)
        #     s we can calculate with (1)
        #     From (2) and (3) it follows:
        #     nf1 = (2*i - s + 3)/(2 * (n + 2))

        set n [llength $attribList]
        set yviewList [$canvas yview]
        set f1 [lindex $yviewList 0]
        set f2 [lindex $yviewList 1]
        set s [expr ($n + 2) * ($f2 - $f1) + 1.0]
        set nf1 [expr (2.0*$i - $s + 3.0)/(2.0 * ($n + 2.0))]
        if {$nf1 < 0} then {
            set nf1 0
        }
        if {$nf1 > 1} then {
            set nf1 1
        }
        $canvas yview moveto $nf1
        return
    }

    public method showError {message} {
        $txtMessages configure -state normal
        $txtMessages insert end "${message}\n" red
        $txtMessages see end
        $txtMessages configure -state disabled
        bell
        return
    }

    public method showQuery {intro query result resultColor} {
        $txtMessages configure -state normal
        $txtMessages insert end "${intro}\n" blue
        $txtMessages insert end "${query}\n"
        $txtMessages insert end "${result}\n" $resultColor
        $txtMessages see end
        $txtMessages configure -state disabled
        if {$resultColor eq {red}} then {
            bell
        }
        return
    }

    public method firstRecord {} {
        if {(!$tabLock) && ($formState eq {browse})} then {
            $buffer getFirstRecord record recNr status
            updateStatusBar $recNr $status
            updateAllTextEdits 1
        }
        return
    }

    public method lastRecord {} {
        if {(!$tabLock) && ($formState eq {browse})} then {
            $buffer getLastRecord record recNr status
            updateStatusBar $recNr $status
            updateAllTextEdits 1
        }
        return
    }

    public method nextRecord {} {
        if {(!$tabLock) && ($formState eq {browse})} then {
            $buffer getNextRecord record recNr status
            updateStatusBar $recNr $status
            updateAllTextEdits 1
        }
        return
    }

    public method prevRecord {} {
        if {(!$tabLock) && ($formState eq {browse})} then {
            $buffer getPrevRecord record recNr status
            updateStatusBar $recNr $status
            updateAllTextEdits 1
        }
        return
    }

    public method onExpand {attrib} {
        if {$formState eq {browse}} then {
            set readOnly 1
        } else {
            set readOnly 0
        }
        set textEdit [TextEdit "#auto" $formWinPath $attrib \
            $record($recordIdx($attrib)) $readOnly]
        lappend textEditList($readOnly) [list $textEdit $attrib]
        $textEdit defineCallBack \
            [list $this textEditCallBack $textEdit $attrib $readOnly]
        return
    }

    public method textEditCallBack {textEdit attrib readOnly} {
        $textEdit getText record($recordIdx($attrib))
        set itemToRemove [lsearch -exact -index 0 \
            $textEditList($readOnly) $textEdit]
        set textEditList($readOnly) [lreplace $textEditList($readOnly) \
            $itemToRemove $itemToRemove]
        return
    }

    public method onUpdate {} {
        if {[$buffer getStatus] ni {statAfterLast statNotAdded statDeleted}} then {
            # deleteAllTextEdits 1
            set reloaded [$buffer reloadRecord record recNr status]
            updateStatusBar $recNr $status
            updateAllTextEdits 1
            if {$reloaded} then {
                setFormState update
            } else {
                pfm_message [mc reloadFailed] $formWinPath
            }
        }
        return
    }

    public method onAdd {} {
        # deleteAllTextEdits 1
        foreach attrib $modAttribList {
            if {$attribDef($attrib,default) ne {}} then {
                if {[string index $attribDef($attrib,default) 0] eq {=}} then {
                    set query [string range $attribDef($attrib,default) 1 end]
                    if {[$::dbObject select_query_list $query numTuples \
                            namesList tuples errMsg]} then {
                        showQuery [mc getDefaultValue $attrib] \
                            $query [mc queryOK] green
                        if {$numTuples == 1} then {
                            set record($recordIdx($attrib)) [lindex $tuples 0 0]
                        } else {
                            showError [mc defaultNumTuplesErr $attrib $numTuples]
                        }
                    } else {
                        showQuery [mc getDefaultValue $attrib] \
                            $query $errMsg red
                    }
                } else {
                    set record($recordIdx($attrib)) $attribDef($attrib,default)
                }
            }
        }
        setFormState add
        return
    }

    public method onDelete {} {
        if {[$buffer getStatus] ni {statAfterLast statNotAdded statDeleted}} then {
            # deleteAllTextEdits 1
            set reloaded [$buffer reloadRecord record recNr status]
            updateStatusBar $recNr $status
            if {$status ni {statAfterLast statNotAdded statDeleted}} then {
                set arg [dict create \
                    parent $formWinPath \
                    title [mc questionDeleteTitle] \
                    message [mc questionDeleteMessage] \
                    msgWidth 400 \
                    defaultButton btnNo \
                    buttonList {btnYes btnNo}]
                set dlg [GenDialog "#auto" $arg]
                if {[$dlg wait] eq {btnYes}} then {
                    $buffer deleteRecord record recNr status
                    updateStatusBar $recNr $status
                    updateAllTextEdits 1
                }
            }
        }
        return
    }

    public method onOK {} {
        if {[llength $textEditList(0)] > 0} then {
            set attributes {}
            foreach item $textEditList(0) {
                append attributes "[lindex $item 1]\n"
            }
            pfm_message [mc editWindowsOpen $attributes] $formWinPath
        } else {
            if {[llength $listBoxList] > 0} then {
                set attributes {}
                foreach item $listBoxList {
                    append attributes "[lindex $item 1]\n"
                }
                pfm_message [mc listBoxOpen $attributes] $formWinPath
            } else {
                switch -- $formState {
                    "update" {
                        $buffer updateRecord record
                        $buffer reloadRecord record recNr status
                        updateStatusBar $recNr $status
                        updateAllTextEdits 1
                    }
                    "add" {
                        if {[$buffer addRecord record]} then {
                            $buffer reloadRecord record recNr status
                            updateStatusBar $recNr $status
                            updateAllTextEdits 1
                        } else {
                            updateStatusBar {} statNotAdded
                            updateAllTextEdits 1
                        }
                    }
                }
                setFormState browse
            }
        }
        return
    }

    public method onCancel {} {
        deleteAllListBoxes
        deleteAllTextEdits 0
        setFormState browse
        $buffer getCurRecord record recNr status
        updateStatusBar $recNr $status
        return
    }

    public method onSelect {attrib} {
        switch -- $attribDef($attrib,typeofget) {
            tgLink {
                set query $attribDef($attrib,sqlselect)
            }
            tgList {
                set query "SELECT value, description FROM pfm_value "
                append query "WHERE valuelist = '$attribDef($attrib,valuelist)' "
                append query "ORDER BY value"
            }
            default {
                set query {}
            }
        }
        if {[$::dbObject select_query_list $query numTuples headerList valueList errMsg]} then {
            set lsbTitle [mc selectValueFor $attrib]
            set selected [lsearch -exact -index 0 $valueList $record($recordIdx($attrib))]
            if {$selected < 0} then {
                set selected 0
            }
            set lsb [ListBox "#auto" $formWinPath $lsbTitle $headerList \
                $valueList $selected]
            lappend listBoxList [list $lsb $attrib]
            if {[$lsb wait result]} then {
                set record($recordIdx($attrib)) [lindex $result 0]
            }
            set lsbToRemove [lsearch -exact -index 0 $listBoxList $lsb]
            set listBoxList [lreplace $listBoxList $lsbToRemove $lsbToRemove]
        } else {
            pfm_message $errMsg $formWinPath
        }
        return
    }

    public method followLink {link} {
        if {!$tabLock && \
            ([$buffer getStatus] ni {statDeleted statAfterLast statNotAdded})} then {
            set from $formName
            set displayValues {}
            foreach attrib $linkDef($link,displayattrib) {
                lappend displayValues $record($recordIdx($attrib))
            }
            set displayValues [join $displayValues {, }]
            append from " (${displayValues})"
            set to "$linkDef($link,toform)"
            set newEntry [dict create from $from link \
                $linkDef($link,linkname) to $linkDef($link,toform)]
            set newhistory $history
            lappend newhistory $newEntry
            array unset toformDef
            if {[getFormDef $::dbObject $linkDef($link,toform) \
                    $formWinPath toformDef]} then {
                set toformDef(sqlwhere) [expandSqlWhere $link]
                # Next statement added for bug 1072
                set toformDef(sqlorderby) $linkDef($link,orderby)
                $formWindow newFormTab $linkDef($link,toform) \
                    [array get toformDef] $newhistory
            }
        }
        return
    }

    public method onSearch {attrib} {
        if {$searchFrame eq {}} then {
            set searchFrame [setupsearchbar $frmHistory $attrib]
            pack $searchFrame -side top -fill x
        } else {
            set searchAttribute $attrib
        }
        return
    }

    public method onSearchHide {} {
        if {$searchFrame ne {}} then {
            destroy $searchFrame
            set searchFrame {}
            focus [tk_focusNext [focus]]
        }
        return
    }

    public method searchForRecord {} {
        if {($formState eq {browse}) && ($searchFrame ne {}) && !$tabLock} then {
            $buffer searchRecord $searchAttribute \
                "*${searchPattern}*" $matchCase
            $buffer getCurRecord record recNr status
            updateStatusBar $recNr $status
            updateAllTextEdits 1
        }
        return
    }

    public method onHelp {} {
        set query "SELECT help FROM pfm_form WHERE name = '${formName}'"
        if {[$::dbObject select_query_list $query numTuples \
                names tuples errMsg]} then {
            if {$numTuples == 1} then {
                set txtEdit [TextEdit "#auto" $formWinPath \
                    [mc formHelp $formName] [lindex $tuples 0 0] 1]
            }
        } else {
            pfm_message $errMsg $formWinPath
        }
        return
    }

    protected method setupWidget {} {
        setupMenus
        set vpanes [ttk::panedwindow $widget.vpanes -orient vertical]
        set frmHistory [historyPane $vpanes]
        set hpanes [ttk::panedwindow $vpanes.hpanes -orient horizontal]
        set frmForm [formPane $hpanes]
        set frmLink [linkPane $hpanes]
        $hpanes add $frmForm -weight 6
        $hpanes add $frmLink -weight 1
        set frmMessages [messagePane $vpanes]
        $vpanes add $frmHistory -weight 1
        $vpanes add $hpanes -weight 3
        $vpanes add $frmMessages -weight 1
        pack $vpanes -side top -expand 1 -fill both
        recursiveAppendTag $widget $widget
        update
        set bbox [$canvas bbox all]
        set rightEdge [expr [lindex $bbox 2] + 20]
        set bottomEdge [expr [lindex $bbox 3] + 20]
        $canvas configure -scrollregion [list 0 0 $rightEdge $bottomEdge]
        bind $widget <KeyPress-Next> [list $this nextRecord]
        bind $widget <KeyPress-Prior> [list $this prevRecord]
        bind $widget <KeyPress-Right> [list $this nextRecord]
        bind $widget <KeyPress-Left> [list $this prevRecord]
        bind $widget <KeyPress-Home> [list $this firstRecord]
        bind $widget <KeyPress-End> [list $this lastRecord]
        bind $widget <KeyPress-Up> {focus [tk_focusPrev [focus]]}
        bind $widget <KeyPress-Down> {focus [tk_focusNext [focus]]}
        showHistory
        return
    }

    protected method setupMenus {} {
        set mnRecord [menu $menubar.record -tearoff 0]
        foreach op {Update Add Delete} {
            addMenuItem $mnRecord mnu${op}Record command [list $this on$op]
        }
        set mnGoTo [menu $menubar.goto -tearoff 0]
        foreach dir {next prev first last} {
            addMenuItem $mnGoTo mnuGoTo$dir command [list $this ${dir}Record]
        }
        $mnGoTo entryconfigure 0 -accelerator {PgDn}
        $mnGoTo entryconfigure 1 -accelerator {PgUp}
        $mnGoTo entryconfigure 2 -accelerator {Home}
        $mnGoTo entryconfigure 3 -accelerator {End}
        set mnSearch [menu $menubar.search -tearoff 0]
        foreach attrib $attribList {
            $mnSearch add command -label $attrib \
                -command [list $this onSearch $attrib]
        }
        $mnSearch add separator
        $mnSearch add checkbutton \
            -label [lindex [mcunderline mnuSearchCase] 0] \
            -underline [lindex [mcunderline mnuSearchCase] 1] \
            -variable [scope matchCase] -onvalue 1 -offvalue 0 \
            -indicatoron 1 -selectcolor black
        $mnSearch add separator
        addMenuItem $mnSearch mnuSearchHide command [list $this onSearchHide]
        addMenuItem $menubar mnuRecordMenu cascade $mnRecord
        addMenuItem $menubar mnuGoToMenu cascade $mnGoTo
        addMenuItem $menubar mnuSearchMenu cascade $mnSearch
        addMenuItem $menubar mnuFormHelp command [list $this onHelp]
        if {$formDef(view) eq {t}} then {
            $menubar entryconfigure 1 -state disabled
        }
        return
    }

    protected method enableBrowseMenus {} {
        if {$formDef(view) eq {f}} then {
            $menubar entryconfigure 1 -state normal
        }
        foreach item {2 3} {
            $menubar entryconfigure $item -state normal
        }
        return
    }

   protected method disableBrowseMenus {} {
        foreach item {1 2 3} {
            $menubar entryconfigure $item -state disabled
        }
        return
    }

    protected method historyPane {parent} {
        set frm [ttk::frame $parent.frmhistory]
        set frm2 [ttk::frame $frm.frm2]
        set txtHistory [text $frm2.txt -width 1 -height 1 \
            -takefocus 0 -state disabled]
        set vsbHistory [ttk::scrollbar $frm2.vsb -orient vertical \
            -command [list $txtHistory yview]]
        $txtHistory configure -yscrollcommand [list $vsbHistory set]
        $txtHistory tag configure blue -foreground {medium blue}
        $txtHistory tag configure red -foreground {red3}
        $txtHistory tag configure green -foreground {green4}
        pack $txtHistory -side left -expand 1 -fill both
        pack $vsbHistory -side left -fill y
        pack $frm2 -side top -expand 1 -fill both
        return $frm
    }

    protected method formPane {parent} {
        global tcl_platform
        set frmForm [ttk::frame $parent.frmform -borderwidth 1 -relief raised]
        # relief modified
        set statusbar [ttk::frame $frmForm.sb]
        set frmRecNr [ttk::frame $statusbar.frmRecNr]
        set btnArray(Home) [ttk::button $frmRecNr.btnHome -image ::img::arrow_home \
            -command [list $this firstRecord] -style SButton -takefocus 0]
        set btnArray(Prev) [ttk::button $frmRecNr.btnPrev -image ::img::arrow_left \
            -command [list $this prevRecord] -style SButton -takefocus 0]
        set sbNr [ttk::label $frmRecNr.sbnr -text {0/0} \
            -background white]
        set btnArray(Next) [ttk::button $frmRecNr.btnNext -image ::img::arrow_right \
            -command [list $this nextRecord] -style SButton -takefocus 0]
        set btnArray(End) [ttk::button $frmRecNr.btnEnd -image ::img::arrow_end \
            -command [list $this lastRecord] -style SButton -takefocus 0]
        pack $btnArray(Home) -side left
        pack $btnArray(Prev) -side left
        pack $sbNr -side left -padx {8 8}
        pack $btnArray(Next) -side left
        pack $btnArray(End) -side left
        set sbForm [ttk::label $statusbar.sbform -text $formName \
            -foreground {medium blue}]
        set sbStatus [ttk::label $statusbar.sbStatus -text {state}]
        grid $frmRecNr -column 0 -row 0 -sticky w
        grid $sbForm -column 1 -row 0
        grid $sbStatus -column 2 -row 0 -sticky e
        grid columnconfigure $statusbar 0 -weight 1
        grid columnconfigure $statusbar 1 -weight 1
        grid columnconfigure $statusbar 2 -weight 1
        set frmBody [ttk::frame $frmForm.frmbody -borderwidth 2 \
            -relief sunken]
        set canvas [canvas $frmBody.canvas -width 100 -height 100]
        set canvsb [ttk::scrollbar $frmBody.vsb -orient vertical \
            -command [list $canvas yview]]
        $canvas configure -yscrollcommand [list $canvsb set]
        set embWindow [formControls $canvas]
        $canvas create window 20 20 -window $embWindow -anchor nw
        pack $canvas -side left -expand 1 -fill both
        pack $canvsb -side left -fill y
        pack $statusbar -side top -fill x
        pack $frmBody -side top -expand 1 -fill both
        if {$formDef(view) eq {f}} then {
            set frmButtons [ttk::frame $frmForm.frmbtns]
            foreach op {Update Add Delete OK Cancel} {
                set btnArray($op) [defineButton $frmButtons.btn$op $widget btn$op \
                    [list $this on$op]]
                $btnArray($op) configure -style SButton
            }
            set col 0
            foreach op {Update Add Delete} {
                grid $btnArray($op) -column $col -row 0 -pady {5 5}
                incr col
            }
            foreach op {OK Cancel} {
                $btnArray($op) state {disabled}
            }
            grid anchor $frmButtons center
            pack $frmButtons -side top -fill x
        }
        switch -- $tcl_platform(platform) {
            "windows" {
                bind $widget <MouseWheel> [list $this mouseWheel windows %D]
            }
            "unix" -
            default {
                # On X Window system, mouse wheel sends <4> and <5> events.
                bind $widget <4> [list $this mouseWheel unix -1]
                bind $widget <5> [list $this mouseWheel unix 1]
            }
        }
        return $frmForm
    }

    protected method formControls {parent} {
        set frame [ttk::frame $parent.controls]
        set row 0
        foreach attrib $attribList {
            set lbl [ttk::label $frame.lbl$row -text $attrib -takefocus 0]
            set record($recordIdx($attrib)) {}
            set control($attrib) [entry $frame.ent$row -width 35 \
                -textvariable [scope record($recordIdx($attrib))]]
            $control($attrib) configure -state {readonly}
            bind $control($attrib) <FocusIn> [list $this scrollForm $row]
            set btn [defineButton $frame.btn$row $control($attrib) \
                btnExpand [list $this onExpand $attrib]]
            $btn configure -style SButton
            if {$attribDef($attrib,typeofget) in {tgList tgLink}} then {
                set btnSelect($attrib) [defineButton $frame.sel$row \
                    $control($attrib) btnSelect \
                    [list $this onSelect $attrib]]
                $btnSelect($attrib) state {disabled}
                $btnSelect($attrib) configure -style SButton
                bind $control($attrib) <KeyPress-Return> \
                    [list $btnSelect($attrib) instate {!disabled} \
                        [list $btnSelect($attrib) invoke]]
                grid $lbl -column 0 -row $row -sticky w
                grid $control($attrib) -column 1 -row $row -sticky wens
                grid $btnSelect($attrib) -column 2 -row $row -sticky we
                grid $btn -column 3 -row $row
            } else {
                grid $lbl -column 0 -row $row -sticky w
                grid $control($attrib) -column 1 -columnspan 2 \
                    -row $row -sticky wens
                grid $btn -column 3 -row $row
            }
            incr row
        }
        focus $control([lindex $attribList 0])
        return $frame
    }

    protected method linkPane {parent} {
        set frmLink [ttk::frame $parent.frmlink -borderwidth 1 -relief raised]
        # relief modified
        set frmTitle [ttk::frame $frmLink.frmtitle]
        set lbTitle [ttk::label $frmTitle.lbl -text [mc lbLinks]]
        pack $lbTitle -side top
        set linksBody [ttk::frame $frmLink.body -borderwidth 2 \
            -relief sunken]
        for {set link 0} {$link<= $lastLink} {incr link} {
            set btnNr [expr $link + 1]
            set btnArray($link) [ttk::button $linksBody.btn$btnNr \
                -text "${btnNr}: $linkDef($link,linkname)" \
                -takefocus 0 -style LButton -underline 0 \
                -command [list $this followLink $link]]
            grid $btnArray($link) -column 0 -row $link -sticky we
            if {$btnNr < 10} then {
                bind $widget <Alt-KeyPress-$btnNr> \
                    [list after 200 [list $btnArray($link) instate {!disabled} \
                        [list $btnArray($link) invoke]]]
            }
        }
        grid anchor $linksBody center
        pack $frmTitle -side top -fill x
        pack $linksBody -side top -expand 1 -fill both
        return $frmLink
    }

    protected method messagePane {parent} {
        set frmMessages [ttk::frame $parent.frmmsg]
        set txtMessages [text $frmMessages.txt -width 1 -height 1 -takefocus 0]
        set vsb [ttk::scrollbar $frmMessages.vsb -orient vertical \
            -command [list $txtMessages yview]]
        $txtMessages configure -yscrollcommand [list $vsb set]
        $txtMessages tag configure blue -foreground {medium blue}
        $txtMessages tag configure red -foreground {red3}
        $txtMessages tag configure green -foreground {green4}
        pack $txtMessages -side left -expand 1 -fill both
        pack $vsb -side left -fill y
        return $frmMessages
    }

    protected method setupsearchbar {parent attrib} {
        set searchAttribute $attrib
        set frm [ttk::frame $parent.frmsearch]
        set searchFor [ttk::label $frm.lb1 -text [mc lbSearchFor]]
        set searchEntry [entry $frm.entry \
            -textvariable [scope searchPattern]]
        set searchIn [ttk::label $frm.lb2 -text [mc lbSearchIn]]
        set searchCombo [ttk::combobox $frm.combo -values $attribList \
            -textvariable [scope searchAttribute] -takefocus 0]
        set btnArray(FindNext) [defineButton $frm.btnFindNext $widget \
            btnFindNext [list $this searchForRecord]]
        $btnArray(FindNext) configure -style SButton
        bind $widget <KeyPress-F3> [list $this searchForRecord]
        set btnCase [defineCheckbutton $frm.btncase $widget \
            btnMatchCase {} [scope matchCase] 1 0]
        set btnArray(Hide) [defineButton $frm.btnHide $widget \
            btnHide [list $this onSearchHide]]
        $btnArray(Hide) configure -style SButton
        recursiveAppendTag $frm $widget
        grid $searchIn -column 0 -row 0 -sticky w
        grid $searchCombo -column 1 -row 0 -sticky we
        grid $searchFor -column 2 -row 0 -sticky w
        grid $searchEntry -column 3 -row 0 -sticky we
        grid $btnArray(FindNext) -column 4 -row 0 -sticky e
        grid $btnCase -column 5 -row 0 -sticky w
        grid $btnArray(Hide) -column 6 -row 0 -sticky w
        grid columnconfigure $frm {1 3} -weight 1
        bind $searchEntry <KeyPress-Return> [list $this searchForRecord]
        focus $searchEntry
        return $frm
    }

    protected method updateStatusBar {recNr status} {
        $sbNr configure -text $recNr
        setRecordStatus $status
        return
    }

    protected method setRecordStatus {status} {
        switch -- $status {
            "statUpdated" -
            "statAdded" -
            "statDeleted" {
                set colour {green4}
            }
            "statUpdating" -
            "statAdding" {
                set colour {red3}
            }
            "statNotAdded" -
            "statAfterLast" {
                set colour {medium blue}
            }
            "statNotModified" -
            default {
                set colour {black}
            }
        }
        $sbStatus configure -text [mc $status] -foreground $colour
        return
    }

    protected method expandSqlWhere {link} {
        set expandWhere $linkDef($link,sqlwhere)
        set first [string first "\$(" $expandWhere]
        while {$first >= 0} {
            set last [string first ")" $expandWhere $first]
            set parName [string range $expandWhere [expr $first + 2] [expr $last -1]]
            if {[info exists record($recordIdx($parName))]} then {
                set parameter [string map {' ''} $record($recordIdx($parName))]
                set expandWhere [string replace $expandWhere $first $last $parameter]
            } else {
                pfm_message \
                    [mc expandSqlWhereErr $linkDef($link,linkname) $parName $formName] \
                     $formWinPath
            }
            set first [string first "\$(" $expandWhere $last]
        }
        return $expandWhere
    }

    protected method showHistory {} {
        $txtHistory configure -state normal
        $txtHistory delete 1.0 end
        set indent {}
        # first entry doesn't have 'from' and 'link'. Therefore, next loop
        # starts from 2nd entry
        foreach entry [lrange $history 1 end] {
            set from [dict get $entry from]
            $txtHistory insert end "${indent}${from}\n" blue
            set link [dict get $entry link]
            $txtHistory insert end \
                "${indent}    | ${link}\n${indent}    v\n" green
            append indent {    }
        }
        # The 'to' only has to be printed for the last entry. Therefoe,
        # it is outside the previous loop
        set lastEntry [lindex $history end]
        $txtHistory insert end "${indent}[dict get $lastEntry to]" blue
        $txtHistory see end
        $txtHistory configure -state disabled
        return
    }

    protected method setFormState {newstate} {
        set formState $newstate
        switch -- $newstate {
            "browse" {
                disableEditButtons
                disableEditControls
                enableLinkButtons
                enableBrowseMenus
            }
            "update" {
                setRecordStatus statUpdating
                disableLinkButtons
                enableEditButtons
                enableEditControls
                disableBrowseMenus
            }
            "add" {
                setRecordStatus statAdding
                disableLinkButtons
                enableEditButtons
                enableEditControls
                disableBrowseMenus
            }
        }
        return
    }

    protected method disableLinkButtons {} {
        for {set link 0} {$link <= $lastLink} {incr link} {
            $btnArray($link) state {disabled}
        }
        return
    }

   protected method enableLinkButtons {} {
        for {set link 0} {$link <= $lastLink} {incr link} {
            $btnArray($link) state {!disabled}
        }
        return
    }

    protected method disableEditButtons {} {
        foreach op {OK Cancel} {
            $btnArray($op) state {disabled}
            if {$btnArray($op) in [grid slaves $frmButtons]} then {
                grid forget $btnArray($op)
            }
        }
        bind $widget <KeyPress-Escape> [list $this onEscape]
        set col 0
        foreach op {Update Add Delete} {
            $btnArray($op) state {!disabled}
            if {$btnArray($op) ni [grid slaves $frmButtons]} then {
                grid $btnArray($op) -column $col -row 0 -pady {5 5}
                incr col
            }
        }
        for {set link 0} {$link <= $lastLink} {incr link} {
            $btnArray($link) state {!disabled}
        }
        return
    }

   protected method enableEditButtons {} {
        foreach op {Update Add Delete} {
            $btnArray($op) state {disabled}
            if {$btnArray($op) in [grid slaves $frmButtons]} then {
                grid forget $btnArray($op)
            }
        }
        set col 0
        foreach op {OK Cancel} {
            $btnArray($op) state {!disabled}
            if {$btnArray($op) ni [grid slaves $frmButtons]} then {
                grid $btnArray($op) -column $col -row 0 -pady {5 5}
            }
            incr col
        }
        bind $widget <KeyPress-Escape> [list $this onCancel]
        for {set link 0} {$link <= $lastLink} {incr link} {
            $btnArray($link) state {disabled}
        }
        return
    }

    protected method enableEditControls {} {
        foreach attrib $modAttribList {
            if {$attribDef($attrib,typeofget) ni {tgList tgLink tgReadOnly}} {
                $control($attrib) configure -state normal
            } else {
                if {$attribDef($attrib,typeofget) ne {tgReadOnly}} then {
                    $btnSelect($attrib) state {!disabled}
                }
            }
        }
        return
    }

    protected method disableEditControls {} {
       foreach attrib $modAttribList {
            if {$attribDef($attrib,typeofget) ni {tgList tgLink tgReadOnly}} {
                $control($attrib) configure -state readonly
            } else {
                if {$attribDef($attrib,typeofget) ne {tgReadOnly}} then {
                    $btnSelect($attrib) state {disabled}
                }
            }
        }
        return
    }

    protected method updateAllTextEdits {readonly} {
        foreach item $textEditList($readonly) {
            [lindex $item 0] setText record($recordIdx([lindex $item 1]))
        }
        return
    }

    protected method deleteAllTextEdits {readOnly} {
        foreach item $textEditList($readOnly) {
            [lindex $item 0] destroyWindow
        }
        set textEditList($readOnly) {}
        return
    }

    protected method deleteAllListBoxes {} {
        foreach item $listBoxList {
            [lindex $item 0] destroyWindow
        }
        set listBoxList {}
        return
    }

}

class FormBuf {
    protected variable formDef
    protected variable attribDef
    protected variable attribList
    protected variable modAttribList
    protected variable formTab
    protected variable buffer
    protected variable status
    protected variable bufferFilled 0
    protected variable curRecord
    protected variable lastRecord
    protected variable lastChunk
    protected variable offset
    protected variable recordIdx

    constructor {c_formDef c_attribDef c_formTab c_attribList c_modAttribList} {
        array set formDef $c_formDef
        array set attribDef $c_attribDef
        set attribList $c_attribList
        set modAttribList $c_modAttribList
        set formTab $c_formTab
        # Bug 1070:
        # The same calculation is done in the constructor of class FormTab.
        # See there for more information.
        set index 1
        foreach attrib $attribList {
            set recordIdx($attrib) $index
            incr index
        }
        return
    }

    destructor {
        return
    }

    proc quoteIfNecessary {tablename} {
        # Procedure added for bug 1071
        set double "\""
        if {[string first $double $tablename] >= 0} then {
            # If tablename already contains double quotes, just leave it
            # alone
            set result $tablename
        } else {
            # replace . with "." and enclose everything in double quotes
            set dot "."
            set quotedDot "\".\""
            set result [string map [list $dot $quotedDot] $tablename]
            set result "${double}${result}${double}"
        }
        # puts stdout $result
        return $result
    }
    
    public method getFirstRecord {recordName recNrName statusName} {
        upvar $recordName record
        upvar $recNrName recNr
        upvar $statusName recordStatus
        if {(!$bufferFilled) || ($offset != 0)} then {
            loadDataChunk 0
        }
        set curRecord 0
        getCurRecord record recNr recordStatus
        return
    }

    public method getNextRecord {recordName recNrName statusName} {
        upvar $recordName record
        upvar $recNrName recNr
        upvar $statusName recordStatus
        if {$curRecord <= [expr $lastRecord - 2]} then {
            incr curRecord
        } else {
            if {!$lastChunk} then {
                loadDataChunk 1
                set curRecord 0
            } else {
                set curRecord $lastRecord
            }
        }
        getCurRecord record recNr recordStatus
        return
    }

    public method getPrevRecord {recordName recNrName statusName} {
        upvar $recordName record
        upvar $recNrName recNr
        upvar $statusName recordStatus
        if {$curRecord >= 1} then {
            incr curRecord -1
        } else {
            if {$offset > 0} then {
                loadDataChunk -1
                set curRecord [expr $lastRecord - 1]
            }
        }
        getCurRecord record recNr recordStatus
        return
    }

    public method getLastRecord {recordName recNrName statusName} {
        upvar $recordName record
        upvar $recNrName recNr
        upvar $statusName recordStatus
        while {!$lastChunk} {
            loadDataChunk 1
        }
        set curRecord [expr $lastRecord - 1]
        if {$curRecord < 0} then {
            set curRecord 0
        }
        getCurRecord record recNr recordStatus
        return
    }

    public method getCurRecord {recordName recNrName statusName} {
        upvar $recordName record
        upvar $recNrName recNr
        upvar $statusName recordStatus
        array unset record
        foreach attrib $attribList {
                set record($recordIdx($attrib)) $buffer($curRecord,$attrib)
        }
        set recordStatus $status($curRecord)
        # set recNr [expr $curRecord + $offset + 1]
        if {$lastChunk} then {
            set recNr "[expr $curRecord + $offset + 1]/[expr $lastRecord + $offset]"
        } else {
            set recNr "[expr $curRecord + $offset + 1]/?"
        }
        return
    }

    public method searchRecord {attribute pattern matchCase} {
        if {($curRecord == $lastRecord) && $lastChunk} then {
            loadDataChunk 0
            set startSearch 0
        } else {
            set startSearch [expr $curRecord + 1]
        }
        set searching 1
        while {$searching} {
            set found 0
            for {set tuple $startSearch} {$tuple < $lastRecord} {incr tuple} {
                if {$matchCase} then {
                    set found [string match $pattern \
                        $buffer($tuple,$attribute)]
                } else {
                    set found [string match -nocase $pattern \
                        $buffer($tuple,$attribute)]
                }
                if {$found} then {
                    set curRecord $tuple
                    break
                }
            }
            if {$found} then {
                set searching 0
            } else {
                if {!$lastChunk} then {
                    loadDataChunk 1
                    set startSearch 0
                } else {
                    set searching 0
                    set curRecord $lastRecord
                }
            }
        }
        return $found
    }

    public method getStatus {} {
        return $status($curRecord)
    }

    public method deleteRecord {recordName recNrName statusName} {
        upvar $recordName record
        upvar $recNrName recNr
        upvar $statusName recordStatus
        set command "DELETE FROM [quoteIfNecessary $formDef(tablename)]"
        append command "\nWHERE [identCurRecord 0]"
        if {[$::dbObject send_command $command errMsg]} then {
            foreach attrib $attribList {
                set buffer($curRecord,$attrib) {}
                set status($curRecord) statDeleted
            }
            $formTab showQuery [mc deleteRecord] $command [mc commandOK] green
        } else {
            $formTab showQuery [mc deleteRecord] $command $errMsg red
        }
        getCurRecord record recNr recordStatus
        return
    }

    public method addRecord {recordName} {
        upvar $recordName record
        set query "INSERT INTO [quoteIfNecessary $formDef(tablename)]"
        set attribSpec {}
        set valueList {}
        foreach attrib $modAttribList {
            lappend attribSpec "\"${attrib}\""
            set value $record($recordIdx($attrib))
            if {$attribDef($attrib,typeofget) eq {tgExpression}} then {
                    set value [expr $value]
            }
            if {$attribDef($attrib,typeofattrib) eq {taQuoted}} then {
                    set value "'[string map {{'} {''}} ${value}]'"
            }
            lappend valueList $value
        }
        append query " ([join $attribSpec {, }])"
        append query "\nVALUES ([join $valueList {, }])"
        if {[$::dbObject send_command $query errMsg]} then {
            set result 1
            $formTab showQuery [mc addRecord] $query [mc commandOK] green
            set curRecord $lastRecord
            incr lastRecord
            foreach attrib $modAttribList {
                set buffer($curRecord,$attrib) $record($recordIdx($attrib))
            }
            set status($curRecord) statAdded
            foreach attrib $attribList {
                set buffer($lastRecord,$attrib) {}
            }
            set status($lastRecord) statAfterLast
        } else {
            $formTab showQuery [mc addRecord] $query $errMsg red
            set result 0
        }
        return $result
    }

    public method updateRecord {recordName} {
        upvar $recordName record
        if {[transactionCommand [mc startTransaction] {START TRANSACTION}]} then {
            if {[selectForUpdate]} then {
                if {[basicUpdateRecord record]} then {
                    if {[transactionCommand [mc commitTransaction] {COMMIT}]} then {
                        set result 1
                        foreach attrib $modAttribList {
                            set buffer($curRecord,$attrib) $record($recordIdx($attrib))
                        }
                        set status($curRecord) statUpdated
                    } else {
                        set result 0
                    }
                } else {
                    set result 0
                    transactionCommand [mc rollBack] {ROLLBACK}
                }
            } else {
                set result 0
                transactionCommand [mc rollBack] {ROLLBACK}
            }
        } else {
            set result 0
        }
        return $result
    }

    protected method basicUpdateRecord {recordName} {
        upvar $recordName record
        set updateList {}
        foreach attrib $modAttribList {
            if {$record($recordIdx($attrib)) ne $buffer($curRecord,$attrib)} then {
                set value $record($recordIdx($attrib))
                if {$attribDef($attrib,typeofget) eq {tgExpression}} then {
                    set value [expr $value]
                }
                if {$attribDef($attrib,typeofattrib) eq {taQuoted}} then {
                    set value "'[string map {{'} {''}} ${value}]'"
                }
                lappend updateList "\"${attrib}\" = $value"
            }
        }
        if {[llength $updateList] > 0} then {
            set command "UPDATE [quoteIfNecessary $formDef(tablename)]"
            append command "\nSET [join $updateList {, }]"
            append command "\nWHERE [identCurRecord 0]"
            if {[$::dbObject send_command $command errMsg]} then {
                set result 1
                $formTab showQuery [mc updateRecord] $command \
                    [mc commandOK] green
            } else {
                set result 0
                $formTab showQuery [mc updateRecord] $command \
                    $errMsg red
            }
        } else {
            set result 0
            $formTab showError [mc noUpdates]
        }
        return $result
    }

    protected method selectForUpdate {} {
        set sqlattrib {}
        foreach attrib $modAttribList {
            lappend sqlattrib "\"${attrib}\""
        }
        set sqlattrib [join $sqlattrib {, }]
        set query "SELECT $sqlattrib"
        append query "\nFROM [quoteIfNecessary $formDef(tablename)]"
        append query "\nWHERE [identCurRecord 0] FOR UPDATE"
        if {[$::dbObject select_query_list $query numTuples namesList \
                resultList errMsg]} then {
            switch -- $numTuples {
                1 {
                    set idx 0
                    set result 1
                    foreach attrib $namesList {
                        if {$buffer($curRecord,$attrib) ne [lindex $resultList 0 $idx]} then {
                            set result 0
                            break
                        }
                        incr idx
                    }
                    if {$result} then {
                        $formTab showQuery [mc selectForUpdate] $query [mc queryOK] green
                    } else {
                        set idx 0
                        foreach attrib $namesList {
                            set buffer($curRecord,$attrib) [lindex $resultList 0 $idx]
                            set status($curRecord) statNotModified
                            incr idx
                        }
                        $formTab showQuery [mc selectForUpdate] $query \
                            [mc recordModified] red
                        pfm_message [mc recordModified] [$formTab cget -formWinPath]
                    }
                }
                0 {
                    set result 0
                    $formTab showQuery [mc selectForUpdate] $query \
                        [mc recordDeleted] red
                    pfm_message [mc recordDeleted] [$formTab cget -formWinPath]
                }
                default {
                    set result 0
                    $formTab showQuery [mc selectForUpdate] $query \
                        [mc wrongNumTuples $numTuples] red
                    pfm_message [mc wrongNumTuples $numTuples] \
                        [$formTab cget -formWinPath]
                }
            }
        } else {
            set result 0
            $formTab showQuery [mc selectForUpdate] $query $errMsg red
            pfm_message $errMsg [$formTab cget -formWinPath]
        }
        return $result
    }

    protected method transactionCommand {intro command} {
        if {[$::dbObject send_command $command errMsg]} then {
            $formTab showQuery $intro $command [mc commandOK] green
            set result 1
        } else {
            $formTab showQuery $intro $command $errMsg red
            set result 0
        }
        return $result
    }

    public method reloadRecord {recordName recNrName statusName} {
        upvar $recordName record
        upvar $recNrName recNr
        upvar $statusName recordStatus
        set query "SELECT $formDef(sqlselect)"
        append query "\nFROM $formDef(sqlfrom) "
        if {$formDef(groupby) eq {}} then {
            append query "\nWHERE [identCurRecord 1]"
        } else {
            append query "\nGROUP BY $formDef(groupby) "
            append query "\nHAVING [identCurRecord 1]"
        }
        if {[$::dbObject select_query_list $query numTuples namesList \
                resultList errMsg]} then {
            switch -- $numTuples {
                1 {
                    set idx 0
                    foreach attrib $namesList {
                        set buffer($curRecord,$attrib) [lindex $resultList 0 $idx]
                        incr idx
                    }
                    $formTab showQuery [mc reloadRecord] $query [mc queryOK] green
                    set result 1
                }
                0 {
                    $formTab showQuery [mc reloadRecord] $query \
                        [mc recordDeleted] red
                    foreach attrib $attribList {
                        set buffer($curRecord,$attrib) {}
                    }
                    set status($curRecord) statDeleted
                    set result 0
                }
                default {
                $formTab showQuery [mc reloadRecord] $query \
                    [mc wrongNumTuples $numTuples] red
                    set result 0
                }
            }
        } else {
            $formTab showQuery [mc reloadRecord] $query $errMsg red
            set result 0
        }
        getCurRecord record recNr recordStatus
        return $result
    }

    protected method identCurRecord {withTable} {
        set whereClause {}
        set table [quoteIfNecessary $formDef(tablename)]
        foreach pkey $formDef(pkey) {
            if {$attribDef($pkey,typeofattrib) eq {taQuoted}} then {
                set value "'[string map {{'} {''}} $buffer($curRecord,$pkey)]'"
            } else {
                set value $buffer($curRecord,$pkey)
            }
            if {$withTable} then {
                lappend whereClause "(${table}.\"${pkey}\" = $value)"
            } else {
                lappend whereClause "(\"${pkey}\" = $value)"
            }
        }
        return [join $whereClause { AND }]
    }

    protected method loadDataChunk {arg} {
        switch -- $arg {
            0 {
                set offset 0
            }
            1 {
                if {$formDef(sqllimit) ne {}} then {
                    incr offset $formDef(sqllimit)
                }
            }
            -1 {
                if {$formDef(sqllimit) ne {}} then {
                    incr offset -$formDef(sqllimit)
                    if {$offset < 0} then {
                        set offset 0
                    }
                }
            }
        }
        set query "SELECT $formDef(sqlselect)"
        append query "\nFROM $formDef(sqlfrom)"
        if {$formDef(groupby) ne {}} then {
            append query "\nGROUP BY $formDef(groupby)"
            if {$formDef(sqlwhere) ne {}} then {
                append query "\nHAVING $formDef(sqlwhere)"
            }
        } else {
            if {$formDef(sqlwhere) ne {}} then {
                append query "\nWHERE $formDef(sqlwhere)"
            }
        }
        if {$formDef(sqlorderby) ne {}} then {
            append query "\nORDER BY $formDef(sqlorderby)"
        }
        if {$formDef(sqllimit) ne {}} then {
            append query "\nLIMIT $formDef(sqllimit) OFFSET $offset"
        }
        array unset buffer
        array unset status
        if {[$::dbObject select_query $query lastRecord buffer errMsg]} then {
            if {$formDef(sqllimit) ne {}} then {
                set lastChunk [expr $lastRecord < $formDef(sqllimit)]
            } else {
                set lastChunk 1
            }
            if {[checkResult errMsg]} then {
                $formTab showQuery [mc loadDataChunk] $query [mc queryOK] green
            } else {
                $formTab showQuery [mc loadDataChunk] $query $errMsg red
            }
            set bufferFilled 1
        } else {
            set lastRecord 0
            set lastChunk 1
            $formTab showQuery [mc loadDataChunk] $query $errMsg red
            set bufferFilled 0
        }
        for {set tuple 0} {$tuple < $lastRecord} {incr tuple} {
            set status($tuple) statNotModified
        }
        foreach attrib $attribList {
            set buffer($lastRecord,$attrib) {}
        }
        set status($lastRecord) statAfterLast
        return
    }

    protected method checkResult {errMsgName} {
        upvar $errMsgName errMsg
        set result 1
        set errMsg {}
        if {$lastRecord > 0} then {
            foreach attrib $attribList {
                if {![info exists buffer(0,$attrib)]} then {
                    set result 0
                    append errMsg "[mc attribMissing $attrib]\n"
                    for {set tuple 0} {$tuple < $lastRecord} {incr tuple} {
                        set buffer($tuple,$attrib) {}
                    }
                }
            }
            foreach attrib $formDef(pkey) {
                if {![info exists buffer(0,$attrib)]} then {
                    set result 0
                    append errMsg "[mc pkeyMissing $attrib]\n"
                    for {set tuple 0} {$tuple < $lastRecord} {incr tuple} {
                        set buffer($tuple,$attrib) {}
                    }
                }
                if {$attrib ni $attribList} then {
                    append errMsg "[mc attribDefPkeyMissing $attrib]\n"
                    set attribDef($attrib,typeofattrib) taQuoted
                    set attribbDef($attrib,typeofget) tgDirect
                }
            }
        }
        return $result
    }
}