File: preferences_form.cpp

package info (click to toggle)
mysql-workbench 6.3.8%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 113,932 kB
  • ctags: 87,814
  • sloc: ansic: 955,521; cpp: 427,465; python: 59,728; yacc: 59,129; xml: 54,204; sql: 7,091; objc: 965; makefile: 638; sh: 613; java: 237; perl: 30; ruby: 6; php: 1
file content (2148 lines) | stat: -rw-r--r-- 79,246 bytes parent folder | download
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
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
/* 
 * Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; version 2 of the
 * License.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301  USA
 */

#include "base/ui_form.h"
#include "base/string_utilities.h"
#include "base/util_functions.h"

#include "mforms/widgets.h"
#include "mforms/sectionbox.h"
#include "mforms/textbox.h"
#include "mforms/panel.h"
#include "mforms/radiobutton.h"

#include "grtpp.h"

#include "grts/structs.h"
#include "grts/structs.app.h"
#include "grts/structs.workbench.physical.h"

#include "grt/editor_base.h"

#include "workbench/wb_context.h"
#include "workbench/wb_context_ui.h"

#include "preferences_form.h"

#include "grtdb/db_helpers.h"
#include "snippet_popover.h"

#include "grtpp_notifications.h"

#if defined(_WIN32) || defined(__APPLE__)
#define HAVE_BUNDLED_MYSQLDUMP
#endif

using namespace base;
using namespace mforms;

#include "base/drawing.h"

struct LangFontSet {
  const char *name;

  // TODO: there are a few fonts missing here.
  const char *object_title_font;
  const char *object_section_font;
  const char *object_item_font;
  const char *layer_title_font;
  const char *note_font;
};

static LangFontSet font_sets[] = {
  {"Default (Western)",
    DEFAULT_FONT_FAMILY" Bold 12",
    DEFAULT_FONT_FAMILY" Bold 11",
    DEFAULT_FONT_FAMILY" 11",
    DEFAULT_FONT_FAMILY" 11",
    DEFAULT_FONT_FAMILY" 11",
  },
#ifdef _WIN32
  {"Japanese",
    "Arial Unicode MS Bold 12",
    "Arial Unicode MS Bold 11",
    "Arial Unicode MS 11",
    "Arial Unicode MS 11",
    "Arial Unicode MS 11"
  },
  {"Korean",
    "Arial Unicode MS Bold 12",
    "Arial Unicode MS Bold 11",
    "Arial Unicode MS 11",
    "Arial Unicode MS 11",
    "Arial Unicode MS 11"
  },
  {"Simplified Chinese",
    "Arial Unicode MS Bold 12",
    "Arial Unicode MS Bold 11",
    "Arial Unicode MS 11",
    "Arial Unicode MS 11",
    "Arial Unicode MS 11"
  },
  {"Cyrillic",
    DEFAULT_FONT_FAMILY" Bold 12",
    DEFAULT_FONT_FAMILY" Bold 11",
    DEFAULT_FONT_FAMILY" 11",
    DEFAULT_FONT_FAMILY" 11",
    DEFAULT_FONT_FAMILY" 11"
  },
#elif defined(__APPLE__)
  {"Japanese",
    "Osaka Bold 12",
    "Osaka Bold 11",
    "Osaka 11",
    "Osaka 11",
    "Osaka 11"
  },
  {"Korean",
    "AppleGothic Bold 12",
    "AppleGothic Bold 11",
    "AppleGothic 11",
    "AppleGothic 11",
    "AppleGothic 11"
  },
  {"Simplified Chinese",
    "SimHei Bold 12",
    "SimHei Bold 11",
    "SimHei 11",
    "SimHei 11",
    "SimHei 11"
  },
  {"Cyrillic",
    DEFAULT_FONT_FAMILY" Bold 12",
    DEFAULT_FONT_FAMILY" Bold 11",
    DEFAULT_FONT_FAMILY" 11",
    DEFAULT_FONT_FAMILY" 11",
    DEFAULT_FONT_FAMILY" 11"
  },
#else
  {"Japanese",
    "VL Gothic Bold 12",
    "VL Gothic Bold 11",
    "VL Gothic 11",
    "VL Gothic 11",
    "VL Gothic 11"
  },
  {"Korean",
    "WenQuanYi Zen Hei Bold 12",
    "WenQuanYi Zen Hei Bold 11",
    "WenQuanYi Zen Hei 11",
    "WenQuanYi Zen Hei 11",
    "WenQuanYi Zen Hei 11"
  },
  {"Simplified Chinese",
    "WenQuanYi Zen Hei Bold 12",
    "WenQuanYi Zen Hei Bold 11",
    "WenQuanYi Zen Hei 11",
    "WenQuanYi Zen Hei 11",
    "WenQuanYi Zen Hei 11"
  },
  {"Cyrillic",
    DEFAULT_FONT_FAMILY" Bold 12",
    DEFAULT_FONT_FAMILY" Bold 11",
    DEFAULT_FONT_FAMILY" 11",
    DEFAULT_FONT_FAMILY" 11",
    DEFAULT_FONT_FAMILY" 11"
  },
#endif
  {NULL, NULL, NULL, NULL, NULL, NULL}
};

const std::string VALID_VERSION_TOOLTIP = _("Specify default target MySQL version in format MAJOR.MINOR or MAJOR.MINOR.RELEASE");
const std::string INVALID_VERSION_TOOLTIP = _("This is not valid version of MySQL.\nSpecify default target MySQL version in format MAJOR.MINOR or MAJOR.MINOR.RELEASE");

static mforms::Label *new_label(const std::string &text, bool right_align=false, bool help=false)
{
  mforms::Label *label= mforms::manage(new mforms::Label());
  label->set_text(text);
  if (right_align)
    label->set_text_align(mforms::MiddleRight);
  if (help)
    label->set_style(mforms::SmallHelpTextStyle);
  return label;
}

// ------------------------------------------------------------------------------------------------

class OptionTable : public mforms::Panel
{
  PreferencesForm *_owner;
  mforms::Table _table;
  int _rows;
  bool _help_column;
  
public:
  OptionTable(PreferencesForm *owner, const std::string &title, bool help_column)
  : mforms::Panel(mforms::TitledBoxPanel), _owner(owner), _rows(0), _help_column(help_column)
  {
    set_title(title);
    
    add(&_table);
    
    _table.set_padding(8);
    _table.set_row_spacing(12);
    _table.set_column_spacing(8);
    
    _table.set_column_count(_help_column ? 3 : 2);    
  }
  
  void add_option(mforms::View *control, const std::string &caption, const std::string &help)
  {
    _table.set_row_count(++_rows);
   
#ifdef _WIN32
    TableItemFlags descriptionFlags = mforms::HFillFlag;
    TableItemFlags helpFlags = mforms::HFillFlag | mforms::HExpandFlag;
    bool right_aligned = false;
#else
    TableItemFlags descriptionFlags = mforms::HFillFlag | mforms::HExpandFlag;
    TableItemFlags helpFlags = mforms::HFillFlag;
    bool right_aligned = true;
#endif

    mforms::Label* label = new_label(caption, right_aligned);
    _table.add(label, 0, 1, _rows-1, _rows, descriptionFlags);
    label->set_size(170, -1);
    _table.add(control, 1, 2, _rows-1, _rows, mforms::HFillFlag | mforms::HExpandFlag);
    control->set_size(150, -1);

    _table.add(new_label(help, false, true), 2, 3, _rows-1, _rows, helpFlags);
  }
  

  mforms::TextEntry *add_entry_option(const std::string &option, const std::string &caption, const std::string &tooltip)
  {
    _table.set_row_count(++_rows);

    mforms::TextEntry *entry = _owner->new_entry_option(option, false);
    entry->set_tooltip(tooltip);
    entry->set_size(80, -1);      //  Set a default size. If the size is never set, the text entry will not show if the _help_column == true
    
#ifdef _WIN32
    TableItemFlags descriptionFlags = mforms::HFillFlag;
    bool right_aligned = false;
#else
    TableItemFlags descriptionFlags = mforms::HFillFlag|mforms::HExpandFlag;
    bool right_aligned = true;
#endif

    mforms::Label* label = new_label(caption, right_aligned);
    _table.add(label, 0, 1, _rows-1, _rows, descriptionFlags);
//    label->set_size(180, -1);
    _table.add(entry, 1, 2, _rows-1, _rows, _help_column ? mforms::HFillFlag : mforms::HFillFlag|mforms::HExpandFlag);
    if (_help_column)
    {
      label = new_label(tooltip);
      label->set_style(mforms::SmallHelpTextStyle);
      _table.add(label, 2, 3, _rows-1, _rows, mforms::HFillFlag|mforms::HExpandFlag);
    }
    return entry;
  }

  mforms::CheckBox *add_checkbox_option(const std::string &option, const std::string &caption, const std::string &tooltip)
  {
    _table.set_row_count(++_rows);
    
    mforms::CheckBox *cb = _owner->new_checkbox_option(option);
    cb->set_text(caption);
    cb->set_tooltip(tooltip);
    
    _table.add(cb, 0, 3, _rows - 1, _rows, mforms::HFillFlag);
    
    return cb;
  }
};


// ------------------------------------------------------------------------------------------------

static void force_checkbox_on_toggle(mforms::CheckBox *value, mforms::CheckBox *target, bool same_value, bool disable_on_active)
{
  if (value->get_active())
  {
    target->set_active(!same_value);
    target->set_enabled(!disable_on_active);
  }
  else
  {
    //    target->set_active(same_value);
    target->set_enabled(disable_on_active);
  }
}

//----------------- PreferencesForm ----------------------------------------------------------------

PreferencesForm::PreferencesForm(wb::WBContextUI *wbui, const workbench_physical_ModelRef &model)
: Form(NULL, mforms::FormResizable), _switcher(mforms::TreeNoHeader|mforms::TreeSidebar), _hbox(true), _top_box(false), _bottom_box(true),
  _tabview(mforms::TabViewTabless), _button_box(true), _font_list(mforms::TreeFlatList)
{
  _wbui = wbui;
  _model = model;

  set_name("preferences");

  if (!model.is_valid())
    set_title(_("Workbench Preferences"));
  else
    set_title(_("Model Options"));

#ifdef _WIN32
  set_back_color(base::Color::get_application_color_as_string(base::AppColorMainBackground, false));
#endif

  _switcher.add_column(mforms::StringColumnType, "", 150);
  _switcher.end_columns();
  _switcher.signal_changed()->connect(boost::bind(&PreferencesForm::switch_page, this));

  _switcher.set_size(150, -1);
  _hbox.add(&_switcher, false, true);

  _top_box.set_padding(12);
  _top_box.set_spacing(8);

  _top_box.add(&_tabview, true, true);

  _top_box.add(&_bottom_box, false);

  _bottom_box.add_end(&_button_box, false, true);
  _button_box.set_spacing(8);
  _button_box.set_homogeneous(true);

  scoped_connect(_ok_button.signal_clicked(),boost::bind(&PreferencesForm::ok_clicked, this));
  scoped_connect(_cancel_button.signal_clicked(),boost::bind(&PreferencesForm::cancel_clicked, this));

  _cancel_button.set_text(_("Cancel"));
  _cancel_button.enable_internal_padding(true);

  _ok_button.set_text(_("OK"));
  _ok_button.enable_internal_padding(true);

  mforms::Utilities::add_end_ok_cancel_buttons(&_button_box, &_ok_button, &_cancel_button);
  
  if (_model.is_valid())
  {
    _use_global.set_text(_("Use defaults from global settings"));
#ifdef _WIN32
    if (base::Color::get_active_scheme() == ColorSchemeStandardWin7)
      _use_global.set_front_color("#FFFFFF");
    else
      _use_global.set_front_color("#000000");
#endif
    _bottom_box.add(&_use_global, true, true);
    scoped_connect(_use_global.signal_clicked(),boost::bind(&PreferencesForm::toggle_use_global, this));
  }

  mforms::TreeNodeRef node;

  if (!_model.is_valid())
  {
    add_page(NULL, _("General Editors"), create_general_editor_page());

    node = add_page(NULL, _("SQL Editor"), create_sqlide_page());
    add_page(node, _("Query Editor"), create_editor_page());
    add_page(node, _("Object Editors"), create_object_editor_page());
    add_page(node, _("SQL Execution"), create_query_page());
    node->expand();

    add_page(NULL, _("Administration"), create_admin_page());
  }

  if (_model.is_valid())
    node = NULL;
  else
    node = add_page(NULL, _("Modeling"), create_model_page());
  add_page(node, _("Defaults"), create_model_defaults_page());
  add_page(node, _("MySQL"), create_mysql_page());
  add_page(node, _("Diagram"), create_diagram_page());
  if (!_model.is_valid())
  {
    add_page(node, _("Appearance"), create_appearance_page());
    node->expand();
  }

  if (!_model.is_valid())
  {
#ifdef _WIN32
    add_page(NULL, _("Fonts & Colors"), create_fonts_and_colors_page());
#else
    // Fonts only for now in Mac/Linux
    add_page(NULL, _("Fonts"), create_fonts_and_colors_page());
#endif
    add_page(NULL, _("Others"), create_others_page());
  }


  _hbox.add(&_top_box, true, true);
  set_content(&_hbox);

  grt::DictRef info(wbui->get_wb()->get_grt());
  if (!_model.is_valid())
    info.set("options", _wbui->get_wb()->get_wb_options());
  else
  {
    info.set("model-options", _wbui->get_model_options(_model.id()));
    info.set("model", model);
  }
  grt::GRTNotificationCenter::get()->send_grt("GRNPreferencesDidCreate", grt::ObjectRef(), info);

  _switcher.select_node(_switcher.node_at_row(0));

  set_size(800, 600);
  center();
  
  show_values();
}

//--------------------------------------------------------------------------------------------------

PreferencesForm::~PreferencesForm()
{
  for (std::list<Option*>::iterator iter= _options.begin(); iter != _options.end(); ++iter)
    delete *iter;
}

//--------------------------------------------------------------------------------------------------

mforms::TreeNodeRef PreferencesForm::add_page(mforms::TreeNodeRef parent, const std::string &title, mforms::View *view)
{
  mforms::TreeNodeRef node = parent ? parent->add_child() : _switcher.add_node();
  node->set_string(0, title);
  _tabview.add_page(view, title);

  return node;
}

//--------------------------------------------------------------------------------------------------

bool PreferencesForm::versionIsValid(const std::string &text)
{
  size_t dots_count = 0;
  for (size_t i = 0; i < text.size(); i++) 
  {
    if( !(isdigit(text[i]) || text[i] == '.') )
      return false;
    if (text[i] == '.')
      dots_count++;
  }

  if( starts_with(text, ".") || ends_with(text, ".") || dots_count < 1 || dots_count > 2 )
    return false;

  GrtVersionRef version = bec::parse_version(_wbui->get_wb()->get_grt(), text);
  if( !version.is_valid() || version->majorNumber() < 5 
        || version->majorNumber() > 10 || version->minorNumber() > 20
    )
    return false;
  
  return true;
}

void PreferencesForm::version_changed()
{
  if( versionIsValid(version_entry->get_string_value()) )
  { 
    version_entry->set_back_color("#FFFFFF");
    version_entry->set_tooltip(VALID_VERSION_TOOLTIP);
  }
  else
  {
    version_entry->set_back_color("#FF5E5E");
    version_entry->set_tooltip(INVALID_VERSION_TOOLTIP);
  }
}

//--------------------------------------------------------------------------------------------------

void PreferencesForm::switch_page()
{
  int row = _switcher.get_selected_row();
  if (row >= 0)
    _tabview.set_active_tab(row);
}

//--------------------------------------------------------------------------------------------------

void PreferencesForm::show()
{
  grt::DictRef info(_wbui->get_wb()->get_grt());
  if (!_model.is_valid())
    info.set("options", _wbui->get_wb()->get_wb_options());
  else
  {
    info.set("model-options", _wbui->get_model_options(_model.id()));
    info.set("model", _model);
  }
  grt::GRTNotificationCenter::get()->send_grt("GRNPreferencesWillOpen", grt::ObjectRef(), info);
  
  if (run_modal(&_ok_button, &_cancel_button))
    info.set("saved", grt::IntegerRef(1));
  else
    info.set("saved", grt::IntegerRef(0));
  
  grt::GRTNotificationCenter::get()->send_grt("GRNPreferencesDidClose", grt::ObjectRef(), info);
}


void PreferencesForm::show_values()
{
  for (std::list<Option*>::const_iterator iter= _options.begin(); iter != _options.end(); ++iter)
    (*iter)->show_value();

  if (!_model.is_valid())
  {
    show_colors_and_fonts();
  }

  if (_model.is_valid())
  {
    std::string value;
    _wbui->get_wb_options_value(_model.id(), "useglobal", value);
    if (value == "1")
    {
      _use_global.set_active(true);
      _tabview.set_enabled(false);
    }
  }
}


void PreferencesForm::update_values()
{
  grt::AutoUndo undo(_wbui->get_wb()->get_grt(), !_model.is_valid());

  if (_model.is_valid())
  {
    _wbui->set_wb_options_value(_model.id(), "useglobal", _use_global.get_active() ? "1" : "0");
  }

  if (!_model.is_valid() || !_use_global.get_active())
  {
    for (std::list<Option*>::const_iterator iter= _options.begin(); iter != _options.end(); ++iter)
    {
      (*iter)->update_value();
    }
  }

  if (!_model.is_valid())
    update_colors_and_fonts();

  undo.end(_("Change Options"));
}


grt::DictRef PreferencesForm::get_options(bool global)
{
  if (!_model.is_valid() || global)
    return _wbui->get_wb()->get_wb_options();
  else
    return _wbui->get_model_options(_model.id());
}


void PreferencesForm::show_entry_option(const std::string &option_name, mforms::TextEntry *entry, bool numeric)
{
  std::string value;

  _wbui->get_wb_options_value(_model.is_valid() ? _model.id() : "", option_name, value);
  entry->set_value(value);
}


void PreferencesForm::update_entry_option(const std::string &option_name, mforms::TextEntry *entry, bool numeric)
{
  if (numeric)
    _wbui->set_wb_options_value(_model.is_valid() ? _model.id() : "", option_name, entry->get_string_value(), grt::IntegerType);
  else
    _wbui->set_wb_options_value(_model.is_valid() ? _model.id() : "", option_name, entry->get_string_value(), grt::StringType);
}

void PreferencesForm::show_path_option(const std::string &option_name, mforms::FsObjectSelector *entry)
{
  std::string value;
  
  _wbui->get_wb_options_value(_model.is_valid() ? _model.id() : "", option_name, value);
  entry->set_filename(value);
}

void PreferencesForm::update_path_option(const std::string &option_name, mforms::FsObjectSelector *entry)
{
  _wbui->set_wb_options_value(_model.is_valid() ? _model.id() : "", option_name, entry->get_filename(), grt::StringType);
}


void PreferencesForm::update_entry_option_numeric(const std::string &option_name, mforms::TextEntry *entry, int minrange, int maxrange)
{
  long value= base::atoi<long>(entry->get_string_value(), 0l);
  if (value < minrange)
    value= minrange;
  else if (value > maxrange)
    value= maxrange;
  
  _wbui->set_wb_options_value(_model.is_valid() ? _model.id() : "", option_name, strfmt("%li", (long)value));
}


void PreferencesForm::show_checkbox_option(const std::string &option_name, mforms::CheckBox *checkbox)
{
  std::string value;

  _wbui->get_wb_options_value(_model.is_valid() ? _model.id() : "", option_name, value);

  checkbox->set_active(base::atoi<int>(value, 0) != 0);
}


void PreferencesForm::update_checkbox_option(const std::string &option_name, mforms::CheckBox *checkbox)
{
  std::string value = checkbox->get_active() ? "1" : "0";
  _wbui->set_wb_options_value(_model.is_valid() ? _model.id() : "", option_name, value, grt::IntegerType);

#ifdef _WIN32
  // On Windows we have to write the following value also to the registry as our options are not
  // available yet when we need that value.
  if (option_name == "DisableSingleInstance")
    set_value_to_registry(HKEY_CURRENT_USER, "Software\\Oracle\\MySQL Workbench",
      "DisableSingleInstance", value.c_str());
#endif
}


void PreferencesForm::show_selector_option(const std::string &option_name, mforms::Selector *selector,
                                           const std::vector<std::string> &choices)
{
  std::string value;
  _wbui->get_wb_options_value(_model.is_valid() ? _model.id() : "", option_name, value);
  selector->set_selected((int)(std::find(choices.begin(), choices.end(), value) - choices.begin()));
}


void PreferencesForm::update_selector_option(const std::string &option_name, mforms::Selector *selector,
                                             const std::vector<std::string> &choices, const std::string &default_value, bool as_number)
{
  if (as_number)
  {
    if (selector->get_selected_index() < 0)
      _wbui->set_wb_options_value(_model.is_valid() ? _model.id() : "", option_name, default_value, grt::IntegerType);
    else
      _wbui->set_wb_options_value(_model.is_valid() ? _model.id() : "", option_name, choices[selector->get_selected_index()], grt::IntegerType);
  }
  else 
  {
    if (selector->get_selected_index() < 0)
      _wbui->set_wb_options_value(_model.is_valid() ? _model.id() : "", option_name, default_value);
    else
      _wbui->set_wb_options_value(_model.is_valid() ? _model.id() : "", option_name, choices[selector->get_selected_index()]);
  }

  if (option_name == "ColorScheme")
  {
    base::Color::set_active_scheme((base::ColorScheme)selector->get_selected_index());
    NotificationCenter::get()->send("GNColorsChanged", NULL);
  }
}


mforms::TextEntry *PreferencesForm::new_entry_option(const std::string &option_name, bool numeric)
{
  Option *option= new Option();
  mforms::TextEntry *entry= new mforms::TextEntry();

  option->view= mforms::manage(entry);
  option->show_value= boost::bind(&PreferencesForm::show_entry_option, this, option_name, entry, numeric);
  option->update_value= boost::bind(&PreferencesForm::update_entry_option, this, option_name, entry, numeric);
  _options.push_back(option);

  return entry;
}


mforms::FsObjectSelector *PreferencesForm::new_path_option(const std::string &option_name, bool file)
{
  Option *option= new Option();
  mforms::FsObjectSelector *entry= new mforms::FsObjectSelector();
  
  entry->initialize("", file ? mforms::OpenFile : mforms::OpenDirectory, "");
  
  option->view= mforms::manage(entry);
  option->show_value= boost::bind(&PreferencesForm::show_path_option, this, option_name, entry);
  option->update_value= boost::bind(&PreferencesForm::update_path_option, this, option_name, entry);
  _options.push_back(option);
  
  return entry;
}


mforms::TextEntry *PreferencesForm::new_numeric_entry_option(const std::string &option_name, int minrange, int maxrange)
{
  Option *option= new Option();
  mforms::TextEntry *entry= new mforms::TextEntry();
  
  option->view= mforms::manage(entry);
  option->show_value= boost::bind(&PreferencesForm::show_entry_option, this, option_name, entry, true);
  option->update_value= boost::bind(&PreferencesForm::update_entry_option_numeric, this, option_name, entry, minrange, maxrange);
  _options.push_back(option);
  
  return entry;  
}


mforms::CheckBox *PreferencesForm::new_checkbox_option(const std::string &option_name)
{
  Option *option= new Option();
  mforms::CheckBox *checkbox= new mforms::CheckBox();

  option->view= mforms::manage(checkbox);
  option->show_value= boost::bind(&PreferencesForm::show_checkbox_option, this, option_name, checkbox);
  option->update_value= boost::bind(&PreferencesForm::update_checkbox_option, this, option_name, checkbox);
  _options.push_back(option);

  return checkbox;
}


mforms::Selector *PreferencesForm::new_selector_option(const std::string &option_name, std::string choices_string, bool as_number)
{
  Option *option= new Option();
  mforms::Selector *selector= new mforms::Selector();

  if (choices_string.empty())
    _wbui->get_wb_options_value(_model.is_valid() ? _model.id() : "", "@"+option_name+"/Items", choices_string);

  std::vector<std::string> choices, parts= base::split(choices_string, ",");

  for (std::vector<std::string>::const_iterator iter= parts.begin();
       iter != parts.end(); ++iter)
  {
    std::vector<std::string> tmp= base::split(*iter, ":", 1);
    if (tmp.size() == 1)
    {
      selector->add_item(*iter);
      choices.push_back(*iter);
    }
    else
    {
      selector->add_item(tmp[0]);
      choices.push_back(tmp[1]);
    }
  }

  option->view= mforms::manage(selector);
  option->show_value= boost::bind(&PreferencesForm::show_selector_option, this, option_name, selector, choices);
  option->update_value= boost::bind(&PreferencesForm::update_selector_option, this, option_name, selector, choices, choices.empty() ? "" : choices[0], as_number);
  _options.push_back(option);

  return selector;
}

//--------------------------------------------------------------------------------------------------

void PreferencesForm::ok_clicked()
{
  update_values();

  mforms::Form::show(false);
}

//--------------------------------------------------------------------------------------------------

void PreferencesForm::cancel_clicked()
{
  mforms::Form::show(false);
}

//--------------------------------------------------------------------------------------------------

mforms::View *PreferencesForm::create_admin_page()
{
  mforms::Box *box= mforms::manage(new mforms::Box(false));
  box->set_spacing(8);

  {
    mforms::Panel *frame= mforms::manage(new mforms::Panel(mforms::TitledBoxPanel));
    frame->set_title(_("Data Export and Import"));
    
    mforms::Table *table= mforms::manage(new mforms::Table());
    
    table->set_padding(8);
    table->set_row_spacing(12);
    table->set_column_spacing(8);
    
    table->set_row_count(3);
    table->set_column_count(3);
    
    frame->add(table);
    
    mforms::FsObjectSelector *pathsel;
    table->add(new_label(_("Path to mysqldump Tool:"), true), 0, 1, 0, 1, mforms::HFillFlag);
    pathsel= new_path_option("mysqldump", true);
    pathsel->get_entry()->set_tooltip(_("Specifiy the full path to the mysqldump tool, which is needed for the Workbench Administrator.\nIt usually comes bundled with the MySQL server and/or client packages."));
    table->add(pathsel, 1, 2, 0, 1, mforms::HFillFlag|mforms::HExpandFlag);
#ifdef HAVE_BUNDLED_MYSQLDUMP
    table->add(new_label(_("Leave blank to use bundled version."), false, true), 2, 3, 0, 1, mforms::HFillFlag);
#else
    table->add(new_label(_("Full path to the mysqldump tool\nif it's not in your PATH."), false, true), 2, 3, 0, 1, mforms::HFillFlag);
#endif
    table->add(new_label(_("Path to mysql Tool:"), true), 0, 1, 1, 2, mforms::HFillFlag);
    pathsel= new_path_option("mysqlclient", true);
    pathsel->get_entry()->set_tooltip(_("Specifiy the full path to the mysql command line client tool, which is needed for the Workbench Administrator.\nIt usually comes bundled with the MySQL server and/or client packages."));
    table->add(pathsel, 1, 2, 1, 2, mforms::HFillFlag|mforms::HExpandFlag);
#ifdef HAVE_BUNDLED_MYSQLDUMP
    table->add(new_label(_("Leave blank to use bundled version."), false, true), 2, 3, 1, 2, mforms::HFillFlag);
#else
    table->add(new_label(_("Full path to the mysql tool\nif it's not in your PATH."), false, true), 2, 3, 1, 2, mforms::HFillFlag);
#endif

    table->add(new_label(_("Export Directory Path:"), true), 0, 1, 2, 3, mforms::HFillFlag);
    pathsel= new_path_option("dumpdirectory", false);
    pathsel->get_entry()->set_tooltip(_("Specifiy the full path to the directory where dump files should be placed by default."));
    table->add(pathsel, 1, 2, 2, 3, mforms::HFillFlag|mforms::HExpandFlag);
    table->add(new_label(_("Location where dump files should\nbe placed by default."), false, true), 2, 3, 2, 3, mforms::HFillFlag);

    box->add(frame, false);
  }
    
  return box;
}


mforms::View *PreferencesForm::create_sqlide_page()
{
  // General options for the SQL Editor
  
  mforms::Box *box= mforms::manage(new mforms::Box(false));
  box->set_spacing(8);

  {
    OptionTable *table = mforms::manage(new OptionTable(this, _("SQL Editor"), true));
    {
      mforms::CheckBox *save_workspace, *discard_unsaved;

      save_workspace = table->add_checkbox_option("workbench:SaveSQLWorkspaceOnClose",
                                                  _("Save snapshot of open editors on close"),
                                                  _("A snapshot of all open scripts is saved when the SQL Editor is closed. Next time it is opened to the same connection that state is restored. Unsaved files will remain unsaved, but their contents will be preserved."));

      {
        static const char *auto_save_intervals= "disable:0,5 seconds:5,10 seconds:10,15 seconds:15,30 seconds:30,1 minute:60,5 minutes:300,10 minutes:600,20 minutes:1200";
        mforms::Selector *sel = new_selector_option("workbench:AutoSaveSQLEditorInterval", auto_save_intervals, true);

        table->add_option(sel, _("Auto-save scripts interval:"),
                          _("Interval to perform auto-saving of all open script tabs.\nThe scripts will be restored from the last auto-saved version\nif Workbench unexpectedly quits."));
      }

      discard_unsaved = table->add_checkbox_option("DbSqlEditor:DiscardUnsavedQueryTabs",
                                                   _("Create new tabs as Query tabs instead of File"),
                                                   _("Unsaved Query tabs do not get a close confirmation, unlike File tabs.\nHowever, once saved, such tabs will also get unsaved change confirmations.\n"
                                                     "If Snapshot saving is enabled, query tabs are always autosaved to temporary files when the connection is closed."));
      save_workspace->signal_clicked()->connect(boost::bind(force_checkbox_on_toggle, save_workspace, discard_unsaved, true, true));
      (*save_workspace->signal_clicked())();

      table->add_checkbox_option("DbSqlEditor:SchemaTreeRestoreState",
                                 _("Restore expanded state of the active schema objects"),
                                 _("Re-expand (and reload) group nodes that were previously expanded in the active schema when the editor was last closed."));
    }
    box->add(table, false, true);
  }

  {
    mforms::Panel *frame= mforms::manage(new mforms::Panel(mforms::TitledBoxPanel));
    frame->set_title(_("Sidebar"));
    box->add(frame, false);
    
    mforms::Box *vbox= mforms::manage(new mforms::Box(false));
    vbox->set_padding(8);
    vbox->set_spacing(8);
    frame->add(vbox);
    
    {
      mforms::CheckBox *check = new_checkbox_option("DbSqlEditor:ShowSchemaTreeSchemaContents");
      check->set_text(_("Show Schema Contents in Schema Tree"));
      check->set_tooltip(_("Whether to show schema contents (tables, views and routine names) in "
        "schema tree."));
      vbox->add(check, false);
    }
    
    {
      mforms::CheckBox *check = new_checkbox_option("DbSqlEditor:ShowMetadataSchemata");
      check->set_text(_("Show Metadata and Internal Schemas"));
      check->set_tooltip(_("Whether to show internal schemas in the schema tree "
        "(eg INFORMATION_SCHEMA, mysql and schemas starting with '.')."));
      vbox->add(check, false);
    }
    
    {
      mforms::CheckBox *check = new_checkbox_option("DbSqlEditor:SidebarModeCombined");
      check->set_text(_("Combine Management Tools and Schema Tree"));
      check->set_tooltip(_("Check this if you want to display the management tools and the "
        "schema list in the same tab page in the sidebar. Uncheck it to have them "
	"in separate tab pages."));
      vbox->add(check, false);
    }
  }

  {
    OptionTable *otable = new OptionTable(this, _("MySQL Session"), false);
    mforms::TextEntry *entry;

    entry = otable->add_entry_option("DbSqlEditor:KeepAliveInterval",
                             _("DBMS connection keep-alive interval (in seconds):"),
                             _("Time interval between sending keep-alive messages to DBMS.\n"
                               "Set to 0 to not send keep-alive messages."));
    entry->set_size(80, -1);

    entry = otable->add_entry_option("DbSqlEditor:ReadTimeOut",
                             _("DBMS connection read time out (in seconds):"),
                             _("Max time the a query can take to return data from the DBMS"));
    entry->set_size(80, -1);

    entry = otable->add_entry_option("DbSqlEditor:ConnectionTimeOut",
      _("DBMS connection time out (in seconds):"),
      _("Maximum time to wait before a connection attempt is aborted."));
    entry->set_size(80, -1);
    box->add(otable, false, true);
  }

  {
    OptionTable *otable = new OptionTable(this, _("Other"), true);

    {
      mforms::TextEntry *entry= new_entry_option("workbench:InternalSchema", false);
      entry->set_max_length(100);
      entry->set_size(100, -1);

      otable->add_option(entry, _("Internal Workbench Schema:"),
                         _("This schema will be used by Workbench.\nto store information required on\ncertain operations."));
    }

    {
      otable->add_checkbox_option("DbSqlEditor:SafeUpdates",
                                  _("\"Safe Updates\". Forbid UPDATEs and DELETEs with no key in WHERE clause or no LIMIT clause. Requires a reconnection."),
                                  _("Enables the SQL_SAFE_UPDATES option for the session.\n"
                                    "If enabled, MySQL aborts UPDATE or DELETE statements\n"
                                    "that do not use a key in the WHERE clause or a LIMIT clause.\n"
                                    "This makes it possible to catch UPDATE or DELETE statements\n"
                                    "where keys are not used properly and that would probably change\n"
                                    "or delete a large number of rows. \n"
                                    "Changing this option requires a reconnection (Query -> Reconnect to Server)"));
    }

    box->add(otable, false, true);
  }
  return box;
}


mforms::View *PreferencesForm::create_general_editor_page()
{
  mforms::Box *box= mforms::manage(new mforms::Box(false));
  box->set_spacing(8);

  {
    mforms::Panel *frame= mforms::manage(new mforms::Panel(mforms::TitledBoxPanel));
    frame->set_title(_("SQL Parsing in Code Editors"));
    box->add(frame, false);

    mforms::Box *vbox= mforms::manage(new mforms::Box(false));
    vbox->set_padding(8);
    vbox->set_spacing(8);
    frame->add(vbox);

    {
      mforms::Box *tbox= mforms::manage(new mforms::Box(true));
      tbox->set_spacing(4);
      vbox->add(tbox, false);

      tbox->add(new_label(_("Default SQL_MODE for syntax checker:"), true), false, false);
      mforms::TextEntry *entry= new_entry_option("SqlMode", false);
      entry->set_tooltip(_(
                           "Value of SQL_MODE DBMS session variable customizes the rules and restrictions for SQL syntax and semantics. See MySQL Server reference for details.\n"
                           "This globally defined parameter determines initial value for same named parameter in each newly created model. "
                           "Model scoped same named parameter in its turn affects SQL parsing within the model, and defines the value of SQL_MODE session variable when connecting to DBMS.\n"
                           "Note: Empty value for this parameter will cause Workbench to treat SQL_MODE as empty string when parsing SQL within the model, but will leave DBMS session variable at its default value.\n"
                           "To force Workbench to reset SQL_MODE session variable as well, this parameter needs to be set to a whitespace symbol."));
      tbox->add(entry, true, true);
    }
    
    {
      mforms::CheckBox *check= new_checkbox_option("SqlIdentifiersCS");
      check->set_text(_("SQL Identifiers are Case Sensitive"));
      check->set_tooltip(_(
                           "Whether to treat identifiers separately if their names differ only in letter case."));
      vbox->add(check, false);
    }
    
    {
      mforms::Box *tbox= mforms::manage(new mforms::Box(true));
      tbox->set_spacing(4);
      vbox->add(tbox, false);
      
      tbox->add(new_label(_("Non-Standard SQL Delimiter:"), true), false, false);
      mforms::TextEntry *entry= new_entry_option("SqlDelimiter", false);
      entry->set_size(50, -1);
      entry->set_tooltip(_(
                           "SQL statement delimiter different from the normally used one (ie, shouldn't be ;). Change this only if the delimiter you normally use, specially in stored routines, happens to be the current setting."));
      tbox->add(entry, false, false);
    }
  }

  {
    OptionTable *table;

    table = mforms::manage(new OptionTable(this, _("Indentation"), true));
    box->add(table, false, true);
    table->add_checkbox_option("Editor:TabIndentSpaces", _("Tab key inserts spaces instead of tabs"), "Check if you want the tab key to indent using\nthe configured amount of spaces.");

    table->add_entry_option("Editor:IndentWidth", "Indent width:", "How many spaces to insert when indenting with the tab key.");
    table->add_entry_option("Editor:TabWidth", "Tab width:", "How many spaces wide are tab characters.");
  }
  return box;
}

//--------------------------------------------------------------------------------------------------

mforms::View *PreferencesForm::create_editor_page()
{
  mforms::Box *box= mforms::manage(new mforms::Box(false));
  box->set_spacing(8);

  {
    mforms::Panel *frame = mforms::manage(new mforms::Panel(mforms::TitledBoxPanel));
    frame->set_title(_("Productivity"));
    box->add(frame, false);

    mforms::Box *vbox= mforms::manage(new mforms::Box(false));
    vbox->set_padding(8);
    vbox->set_spacing(8);
    frame->add(vbox);

    // Code completion settings.
    {
      mforms::Box *subsettings_box = mforms::manage(new mforms::Box(false));
      subsettings_box->set_padding(40, 0, 0, 0);
      subsettings_box->set_spacing(8);
      {
        mforms::CheckBox *check = new_checkbox_option("DbSqlEditor:CodeCompletionEnabled");
        scoped_connect(check->signal_clicked(), boost::bind(&PreferencesForm::code_completion_changed,
                                                            this, check, subsettings_box));

        check->set_text(_("Enable Code Completion in Editors"));
        check->set_tooltip(_("If enabled SQL editors display a code completion list when pressing "
                             "the defined hotkey"));
        vbox->add(check, false);

      }

      {
        mforms::CheckBox *auto_start_check = new_checkbox_option("DbSqlEditor:AutoStartCodeCompletion");
        auto_start_check->set_text(_("Automatically Start Code Completion"));
        auto_start_check->set_tooltip(_("Available only if code completion is enabled. By activating "
                                        "this option code completion will be started automatically when you type something and wait "
                                        "a moment"));
        subsettings_box->add(auto_start_check, false);

        mforms::CheckBox *upper_case_check = new_checkbox_option("DbSqlEditor:CodeCompletionUpperCaseKeywords");
        upper_case_check->set_text(_("Use UPPERCASE keywords on completion"));
        upper_case_check->set_tooltip(_("Normally keywords are shown and inserted as they come from the "
                                        "code editor configuration file. With this swich they are always upper-cased instead."));
        subsettings_box->add(upper_case_check, false);

        // Set initial enabled state of sub settings depending on whether code completion is enabled.
        std::string value;
        _wbui->get_wb_options_value(_model.is_valid() ? _model.id() : "", "DbSqlEditor:CodeCompletionEnabled", value);
        subsettings_box->set_enabled(base::atoi<int>(value, 0) != 0);

        vbox->add(subsettings_box, false);
      }
    }

    {
      mforms::Box *tbox = mforms::manage(new mforms::Box(true));
      tbox->set_spacing(4);
      vbox->add(tbox, false);

      tbox->add(new_label(_("Comment type to use for comment shortcut:"), true), false, false);

      std::string comment_types = "--:--,#:#";
      mforms::Selector *selector = new_selector_option("DbSqlEditor:SQLCommentTypeForHotkey", comment_types, false);
      selector->set_size(150, -1);
      selector->set_tooltip(_("Default comment type for SQL Query editor, to be used when the comment shortcut is used."));
      tbox->add(selector, false, false);
    }

    {
      mforms::Table *table = mforms::manage(new mforms::Table());
      table->set_row_count(2);
      table->set_column_count(2);
      table->set_column_spacing(4);
      table->set_row_spacing(4);
      vbox->add(table, false);

      table->add(new_label(_("Max syntax error count:"), true), 0, 1, 0, 1, mforms::HFillFlag);
      mforms::TextEntry *entry = new_entry_option("SqlEditor::SyntaxCheck::MaxErrCount", false);
      entry->set_size(50, -1);
      entry->set_tooltip(_("Maximum number of errors for syntax checking.\n"
                           "Syntax errors aren't highlighted beyond this threshold.\n"
                           "Set to 0 to show all errors."));
      table->add(entry, 1, 2, 0, 1, mforms::HFillFlag);

      table->add(new_label(_("Max number of result sets:"), true), 0, 1, 1, 2, mforms::HFillFlag);
      entry = new_entry_option("DbSqlEditor::MaxResultsets", false);
      entry->set_size(50, -1);
      entry->set_tooltip(_("Maximum number of result sets that can be opened for a single editor."));
      table->add(entry, 1, 2, 1, 2, mforms::HFillFlag);
    }
  }

  {
    OptionTable *table;

    table = mforms::manage(new OptionTable(this, _("SQL Beautifier"), true));
    box->add(table, false, true);
    {
      table->add_checkbox_option("DbSqlEditor:Reformatter:UpcaseKeywords", _("Change keywords to UPPER CASE"), "");
    }
  }

  return box;
}

//--------------------------------------------------------------------------------------------------

mforms::View *PreferencesForm::create_object_editor_page()
{
  mforms::Box *box= mforms::manage(new mforms::Box(false));
  box->set_spacing(8);

  {
    mforms::Panel *frame = mforms::manage(new mforms::Panel(mforms::TitledBoxPanel));
    frame->set_title(_("Online DDL"));
    box->add(frame, false);

    mforms::Box *vbox = mforms::manage(new mforms::Box(false));
    vbox->set_padding(8);
    vbox->set_spacing(8);
    frame->add(vbox);

    {
      mforms::Box *line_box = mforms::manage(new mforms::Box(true));
      line_box->set_spacing(4);
      vbox->add(line_box, false);

      mforms::Label *label = new_label(_("Default algorithm for ALTER table:"), true);
      label->set_size(180, -1);
      line_box->add(label, false, false);

      std::string algorithms = "Default:DEFAULT,In place:INPLACE,Copy:COPY";
      mforms::Selector *selector = new_selector_option("DbSqlEditor:OnlineDDLAlgorithm", algorithms, false);
      selector->set_size(150, -1);
      selector->set_tooltip(_("If the currently connected server supports online DDL then use the selected "
                              "algorithm as default. This setting can also be adjusted for each alter operation."));
      line_box->add(selector, false, false);
    }
    {
      mforms::Box *line_box = mforms::manage(new mforms::Box(true));
      line_box->set_spacing(4);
      vbox->add(line_box, false);

      mforms::Label *label = new_label(_("Default lock for ALTER table:"), true);
      label->set_size(180, -1);
      line_box->add(label, false, false);

      std::string locks = "Default:DEFAULT,None:NONE,Shared:SHARED,Exclusive:EXCLUSIVE";
      mforms::Selector *selector = new_selector_option("DbSqlEditor:OnlineDDLLock", locks, false);
      selector->set_size(150, -1);
      selector->set_tooltip(_("If the currently connected server supports online DDL then use the selected "
                              "lock as default. This setting can also be adjusted for each alter operation."));
      line_box->add(selector, false, false);
    }
  }

  {
    mforms::Panel *frame = mforms::manage(new mforms::Panel(mforms::TitledBoxPanel));
    frame->set_title(_("Views"));
    box->add(frame, false);

    mforms::Box *vbox= mforms::manage(new mforms::Box(false));
    vbox->set_padding(8);
    vbox->set_spacing(8);
    frame->add(vbox);


    {
      mforms::CheckBox *check= new_checkbox_option("DbSqlEditor:ReformatViewDDL");
      check->set_text(_("Reformat DDL for Views"));
      check->set_tooltip(_("Whether to automatically reformat View DDL returned by the server. The MySQL server does not store the formatting information for View definitions."));
      vbox->add(check, false);
    }
  }

  return box;
}

//--------------------------------------------------------------------------------------------------

mforms::View *PreferencesForm::create_query_page()
{
  // Options specific for the query/script execution aspect of the SQL Editor
  
  mforms::Box *box= mforms::manage(new mforms::Box(false));
  box->set_spacing(8);

  {
    mforms::Panel *frame= mforms::manage(new mforms::Panel(mforms::TitledBoxPanel));
    frame->set_title(_("General"));
    box->add(frame, false);
    
    mforms::Box *vbox= mforms::manage(new mforms::Box(false));
    vbox->set_padding(8);
    vbox->set_spacing(8);
    frame->add(vbox);
    
    {
      mforms::Box *tbox= mforms::manage(new mforms::Box(true));
      tbox->set_spacing(4);
      vbox->add(tbox, false);
      
      tbox->add(new_label(_("Max. query length to store in history (in bytes):"), true), false, false);
      mforms::TextEntry *entry= new_entry_option("DbSqlEditor:MaxQuerySizeToHistory", false);
      entry->set_size(50, -1);
      entry->set_tooltip(_(
                           "Queries beyond specified size will not be saved in the history when executed.\n"
                           "Set to 0 to save any executed query or script"));
      tbox->add(entry, false, false);
    }
    
    
    {
      mforms::CheckBox *check= new_checkbox_option("DbSqlEditor:ContinueOnError");
      check->set_text(_("Continue SQL script execution on errors (by default)"));
      check->set_tooltip(_("Whether to continue skipping failed SQL statements when running a script."));
      vbox->add(check, false);
    }

    {
      mforms::CheckBox *check= new_checkbox_option("DbSqlEditor:AutocommitMode");
      check->set_text(_("Leave autocommit mode enabled by default"));
      check->set_tooltip(_(
                           "Toggles the default autocommit mode for connections.\nWhen enabled, each statement will be committed immediately."
                           "\nNOTE: all query tabs in the same connection share the same transaction. "
                           "To have independent transactions, you must open a new connection."));
      vbox->add(check, false);
    }

    {
      mforms::Box *tbox= mforms::manage(new mforms::Box(true));
      tbox->set_spacing(4);
      vbox->add(tbox, false);
      
      tbox->add(new_label(_("Progress status update interval (in milliseconds):"), true), false, false);
      mforms::TextEntry *entry= new_entry_option("DbSqlEditor:ProgressStatusUpdateInterval", false);
      entry->set_size(50, -1);
      entry->set_tooltip(_(
                           "Time interval between UI updates when running SQL script."));
      tbox->add(entry, false, false);
    }
  }

  {
    mforms::Panel *frame= mforms::manage(new mforms::Panel(mforms::TitledBoxPanel));
    frame->set_title(_("SELECT Query Results"));
    box->add(frame, false);
    
    mforms::Box *vbox= mforms::manage(new mforms::Box(false));
    vbox->set_padding(8);
    vbox->set_spacing(8);
    frame->add(vbox);
    
    {
      mforms::CheckBox *check= new_checkbox_option("SqlEditor:LimitRows");
      check->set_text(_("Limit Rows"));
      check->set_tooltip(_(
                           "Whether every select query to be implicitly adjusted to limit result set to specified number of rows by appending the LIMIT keyword to the query.\n"
                           "If enabled it's still possible to load entire result set by pressing \"Fetch All\" button."));
      vbox->add(check, false);
    }
    
    {
      mforms::Box *tbox= mforms::manage(new mforms::Box(true));
      tbox->set_spacing(4);
      vbox->add(tbox, false);
      
      tbox->add(new_label(_("Limit Rows Count:"), true), false, false);
      mforms::TextEntry *entry= new_entry_option("SqlEditor:LimitRowsCount", false);
      entry->set_size(50, -1);
      entry->set_tooltip(_(
                           "Every select query to be implicitly adjusted to limit result set to specified number of rows."));
      tbox->add(entry, false, false);
    }
    
    {
      mforms::Box *tbox= mforms::manage(new mforms::Box(true));
      tbox->set_spacing(4);
      vbox->add(tbox, false);
      
      tbox->add(new_label(_("Max. Field Value Length to Display (in bytes):"), true), false, false);
      mforms::TextEntry *entry= new_entry_option("Recordset:FieldValueTruncationThreshold", false);
      entry->set_size(50, -1);
      entry->set_tooltip(_(
                           "Symbols beyond specified threashold will be truncated when showing in the grid. Doesn't affect editing field values.\n"
                           "Set to -1 to disable truncation."));
      tbox->add(entry, false, false);
    }
    
    {
      mforms::CheckBox *check= new_checkbox_option("DbSqlEditor:MySQL:TreatBinaryAsText");
      check->set_text(_("Treat BINARY/VARBINARY as nonbinary character string"));
      check->set_tooltip(_(
                           "Whether to treat binary byte strings as nonbinary character strings.\n"
                           "Binary byte string values do not appear in results grid and are marked as a BLOB values that are supposed to be viewed/edited by means of BLOB editor.\n"
                           "Nonbinary character string values are shown right in results grid and can be edited with either cell's in-place editor or BLOB editor.\n"
                           "Warning: Since binary byte strings tend to contain zero-bytes in their values, turning this option on may lead to data truncation when viewing/editing.\n"
                           "Note: Application restart is needed to get new option value in affect."));
      vbox->add(check, false);
    }
    
    {
      mforms::CheckBox *check= new_checkbox_option("DbSqlEditor:IsDataChangesCommitWizardEnabled");
      check->set_text(_("Confirm Data Changes"));
      check->set_tooltip(_("Whether to show a dialog confirming changes to be made to a table recordset."));
      vbox->add(check, false);
    }
    
    /*{
     mforms::CheckBox *check= new_checkbox_option("DbSqlEditor:IsLiveObjectAlterationWizardEnabled");
     check->set_text(_("Enable Live Object Alteration Wizard"));
     check->set_tooltip(_(
     "Whether to use wizard providing more control over applying changes to live database object."));
     vbox->add(check, false);
     }*/
  }
  return box;
}


//--------------------------------------------------------------------------------------------------

/**
 * Triggered when the user switches the code completion enabled state. We use this to adjust the enabled
 * state for dependent sub options.
 */
void PreferencesForm::code_completion_changed(mforms::CheckBox *cc_box, mforms::Box *subsettings_box)
{
  subsettings_box->set_enabled(cc_box->get_active());
}

//--------------------------------------------------------------------------------------------------

mforms::View *PreferencesForm::create_model_page()
{
  mforms::Box *top_box = mforms::manage(new mforms::Box(false));
  top_box->set_spacing(8);

  OptionTable *table;

  table = mforms::manage(new OptionTable(this, _("EER Modeler"), true));
  top_box->add(table, false, true);
  {
    table->add_checkbox_option("workbench.AutoReopenLastModel", _("Automatically reopen previous model at start"), "");
    
#ifndef __APPLE__
    table->add_checkbox_option("workbench:ForceSWRendering", _("Force use of software based rendering for EER diagrams"), 
                               _("Enable this option if you have drawing problems in Workbench modeling.\nYou must restart Workbench for the option to take effect."));
#endif
    
    {    
      mforms::TextEntry *entry= new_numeric_entry_option("workbench:UndoEntries", 1, 500);
      entry->set_max_length(5);
      entry->set_size(100, -1);
      
      table->add_option(entry, _("Model undo history size:"), 
                        _("Allowed values are from 1 up.\nNote: using high values (> 100) will increase memory usage\nand slow down operation."));
    }
    
    {
      static const char *auto_save_intervals= "disable:0,10 seconds:10,15 seconds:15,30 seconds:30,1 minute:60,5 minutes:300,10 minutes:600,20 minutes:1200";    
      mforms::Selector *sel = new_selector_option("workbench:AutoSaveModelInterval", auto_save_intervals, true);
      
      table->add_option(sel, _("Auto-save model interval:"), 
                        _("Interval to perform auto-saving of the open model.\nThe model will be restored from the last auto-saved version\nif Workbench unexpectedly quits."));
    }
  }
  return top_box;
}


mforms::View *PreferencesForm::create_others_page()
{

  Box* content = manage(new Box(false));
  content->set_spacing(8);

  OptionTable *timeouts_table;

  timeouts_table = mforms::manage(new OptionTable(this, _("Timeouts"), true));
  content->add(timeouts_table, false, true);
  {

    // SSH keepalive
    {
      mforms::TextEntry *entry = new_numeric_entry_option("sshkeepalive", 0, 500);
      entry->set_max_length(5);
      entry->set_size(50, -1);

      entry->set_tooltip(_(
        "The interval in seconds without sending any data over the connection, a \"keepalive\" packet will be sent.\nThis option will apply to both SSH tunnel connections and remote management via SSH."));

      timeouts_table->add_option(entry, _("SSH KeepAlive:"),
        _("SSH keep-alive interval in seconds.\nUse 0 to disable."));
    }

    // SSH timeout
    {
      mforms::TextEntry *entry = new_numeric_entry_option("sshtimeout", 0, 500);
      entry->set_max_length(5);
      entry->set_size(50, -1);
      entry->set_tooltip(_(
        "Determines how long the process waits for a result."));

      timeouts_table->add_option(entry, _("SSH Timeout:"),
        _("SSH timeout in seconds.\nUsed only in Online Backup/Restore"));
    }

    // Fabric timeout
    {
      // Using arbitrary max value of 1 Hour for connection timeout.
      mforms::TextEntry *entry = new_numeric_entry_option("Fabric:ConnectionTimeOut", 0, 3600);
      entry->set_max_length(5);
      entry->set_size(50, -1);
      entry->set_tooltip(_(
        "The interval in seconds without sending any data over the connection, a \"keepalive\" packet will be sent.\nThis option will apply to both SSH tunnel connections and remote management via SSH."));

      timeouts_table->add_option(entry, _("Fabric Connection Timeout:"),
        _("Maximum time to wait before a connection\nattempt is aborted."));
    }

  }

#ifdef _WIN32
  OptionTable *table = mforms::manage(new OptionTable(this, _("Others"), true));
  content->add(table, false, true);
  {
    table->add_checkbox_option("DisableSingleInstance", _("Allow more than one instance of MySQL Workbench to run"), 
      _("By default only one instance of MySQL Workbench can run at the same time.\nThis is more resource friendly "
        "and necessary as multiple instances share the same files (settings etc.). Change at your own risk."));
  }
#endif

  mforms::Panel *frame= mforms::manage(new mforms::Panel(mforms::TitledBoxPanel));

  mforms::Table *ssh_table= mforms::manage(new mforms::Table());

  ssh_table->set_padding(8);
  ssh_table->set_row_spacing(12);
  ssh_table->set_column_spacing(8);

  ssh_table->set_row_count(1);
  ssh_table->set_column_count(3);
  frame->add(ssh_table);
  {
    mforms::FsObjectSelector *pathsel;
    ssh_table->add(new_label(_("Path to SSH config file:"), true), 0, 1, 0, 1, mforms::HFillFlag);
    pathsel= new_path_option("pathtosshconfig", true);
    pathsel->get_entry()->set_tooltip(_("Specifiy the full path to the SSH config file."));
    ssh_table->add(pathsel, 1, 2, 0, 1, mforms::HFillFlag|mforms::HExpandFlag);
  }

  content->add(frame, false);

  return content;
}


mforms::View *PreferencesForm::create_model_defaults_page()
{
  mforms::Box *box= mforms::manage(new mforms::Box(false));
  box->set_spacing(8);

  {
    mforms::Panel *frame= mforms::manage(new mforms::Panel(mforms::TitledBoxPanel));
    frame->set_title(_("Column Defaults"));

    mforms::Table *table= mforms::manage(new mforms::Table());

    table->set_padding(12);
    table->set_column_spacing(4);
    table->set_row_spacing(8);
    
    table->set_column_count(4);
    table->set_row_count(2);

    frame->add(table);

    mforms::TextEntry *entry;
    
    table->add(new_label(_("PK Column Name:"), true), 0, 1, 0, 1, mforms::HFillFlag);
    entry= new_entry_option("PkColumnNameTemplate", false);
    entry->set_tooltip(_("Substitutions:\n"
                         "%table% - name of the table\n"
                         "May be used as %table|upper%, %table|lower%, %table|capitalize%, %table|uncapitalize%"));
    table->add(entry, 1, 2, 0, 1, mforms::HFillFlag|mforms::HExpandFlag);

    table->add(new_label(_("PK Column Type:"), true), 2, 3, 0, 1, mforms::HFillFlag);
    entry= new_entry_option("DefaultPkColumnType", false);
    entry->set_tooltip(_("Default type for use in newly added primary key columns.\nSpecify a column type name or a user defined type.\nFlags such as UNSIGNED are not accepted."));
    table->add(entry, 3, 4, 0, 1, mforms::HFillFlag|mforms::HExpandFlag);


    table->add(new_label(_("Column Name:"), true), 0, 1, 1, 2, mforms::HFillFlag);
    entry= new_entry_option("ColumnNameTemplate", false);
    entry->set_tooltip(_("Substitutions:\n"
                         "%table% - name of the table"));
    table->add(entry, 1, 2, 1, 2, mforms::HFillFlag|mforms::HExpandFlag);
    
    table->add(new_label(_("Column Type:"), true), 2, 3, 1, 2, mforms::HFillFlag);
    entry= new_entry_option("DefaultColumnType", false);
    entry->set_tooltip(_("Default type for use in newly added columns.\nSpecify a column type name or a user defined type.\nFlags such as UNSIGNED are not accepted."));
    table->add(entry, 3, 4, 1, 2, mforms::HFillFlag|mforms::HExpandFlag);
    
    box->add(frame, false);
  }

  {
    mforms::Panel *frame= mforms::manage(new mforms::Panel(mforms::TitledBoxPanel));
    frame->set_title(_("Foreign Key/Relationship Defaults"));

    mforms::Table *table= mforms::manage(new mforms::Table());

    table->set_padding(8);

    frame->add(table);
    
    table->set_row_spacing(8);
    table->set_column_spacing(8);
    table->set_row_count(3);
    table->set_column_count(4);

    mforms::TextEntry *entry;

    table->add(new_label(_("FK Name:"), true), 0, 1, 0, 1, mforms::HFillFlag);
    entry= new_entry_option("FKNameTemplate", false);
    
#define SUBS_HELP\
  _("Substitutions:\n"\
      "%table%, %stable% - name of the source table\n"\
      "%dtable% - name of the destination table (where FK is added)\n"\
      "%column%, %scolumn% - name of the source column\n"\
      "%dcolumn% - name of the destination column\n"\
      "May be used as %table|upper%, %table|lower%, %table|capitalize% or %table|uncapitalize%"\
    )
    
    entry->set_tooltip(SUBS_HELP);
    table->add(entry, 1, 2, 0, 1, mforms::HFillFlag|mforms::HExpandFlag);

    table->add(new_label(_("Column Name:"), true), 2, 3, 0, 1, mforms::HFillFlag);
    entry= new_entry_option("FKColumnNameTemplate", false);
    entry->set_tooltip(SUBS_HELP);
    table->add(entry, 3, 4, 0, 1, mforms::HFillFlag|mforms::HExpandFlag);

    table->add(new_label(_("ON UPDATE:"), true), 0, 1, 1, 2, mforms::HFillFlag);
    table->add(new_selector_option("db.ForeignKey:updateRule"), 1, 2, 1, 2, mforms::HFillFlag|mforms::HExpandFlag);

    table->add(new_label(_("ON DELETE:"), true), 2, 3, 1, 2, mforms::HFillFlag);
    table->add(new_selector_option("db.ForeignKey:deleteRule"), 3, 4, 1, 2, mforms::HFillFlag|mforms::HExpandFlag);


    table->add(new_label(_("Associative Table Name:"), true), 0, 1, 2, 3, mforms::HFillFlag);
    entry= new_entry_option("AuxTableTemplate", false);
    entry->set_tooltip(_("Substitutions:\n"
                         "%stable% - name of the source table\n"
                         "%dtable% - name of the destination table"));
    table->add(entry, 1, 2, 2, 3, mforms::HFillFlag|mforms::HExpandFlag);

    table->add(new_label(_("for n:m relationships")), 2, 4, 2, 3, mforms::HFillFlag);

    box->add(frame, false);
  }

  return box;
}


static void show_target_version(const workbench_physical_ModelRef &model, mforms::TextEntry *entry)
{
  if (*model->catalog()->version()->releaseNumber() < 0)
    entry->set_value(base::strfmt("%li.%li", (long)*model->catalog()->version()->majorNumber(),
                                  (long)*model->catalog()->version()->minorNumber()));
  else
    entry->set_value(base::strfmt("%li.%li.%li", (long)*model->catalog()->version()->majorNumber(),
                   (long)*model->catalog()->version()->minorNumber(), (long)*model->catalog()->version()->releaseNumber()));
}

static void update_target_version(workbench_physical_ModelRef model, mforms::TextEntry *entry)
{
  GrtVersionRef version = bec::parse_version(model.get_grt(), entry->get_string_value());
  model->catalog()->version(version);
  version->owner(model);
}


mforms::View *PreferencesForm::create_mysql_page()
{
  mforms::Box *box= mforms::manage(new mforms::Box(false));
  box->set_spacing(8);

  {
    mforms::Panel *frame= mforms::manage(new mforms::Panel(mforms::TitledBoxPanel));
    frame->set_title(_("Model"));

    mforms::Table *table= mforms::manage(new mforms::Table());

    table->set_padding(8);

    frame->add(table);
    table->set_row_count(2);
    table->set_column_count(2);
    
    if (!_model.is_valid())
    {
      table->add(new_label(_("Default Target MySQL Version:"), true), 0, 1, 0, 1, 0);
      version_entry = new_entry_option("DefaultTargetMySQLVersion", false);
      version_entry->set_tooltip(VALID_VERSION_TOOLTIP);
      version_entry->signal_changed()->connect(boost::bind(&PreferencesForm::version_changed, this));
      table->add(version_entry, 1, 2, 0, 1, mforms::HExpandFlag|mforms::HFillFlag);
    }
    else
    {
      // if editing model options, display the catalog version
      Option *option= new Option();
      mforms::TextEntry *entry= new mforms::TextEntry();
      
      option->view= mforms::manage(entry);
      option->show_value= boost::bind(show_target_version, _model, entry);
      option->update_value= boost::bind(update_target_version, _model, entry);

      option->view= mforms::manage(entry);
      option->show_value= boost::bind(show_target_version, _model, entry);
      option->update_value= boost::bind(update_target_version, _model, entry);
      _options.push_back(option);
      
      table->add(new_label(_("Target MySQL Version:"), true), 0, 1, 0, 1, 0);
      table->add(entry, 1, 2, 0, 1, mforms::HExpandFlag|mforms::HFillFlag);
    }
    box->add(frame, false);
  }

  {
    mforms::Panel *frame= mforms::manage(new mforms::Panel(mforms::TitledBoxPanel));
    frame->set_title(_("Model Table Defaults"));
    
    mforms::Box *tbox= mforms::manage(new mforms::Box(true));
    
    tbox->set_padding(8);
    
    frame->add(tbox);
    
    tbox->add(new_label(_("Default Storage Engine:"), true), false, false);
    tbox->add(new_selector_option("db.mysql.Table:tableEngine"), true, true);
    
    box->add(frame, false);
  }

  {
    mforms::Panel *frame= mforms::manage(new mforms::Panel(mforms::TitledBoxPanel));
    frame->set_title(_("Forward Engineering and Synchronization"));
    
    mforms::Box *tbox= mforms::manage(new mforms::Box(true));
    mforms::TextEntry *entry;
    tbox->set_padding(8);
    
    frame->add(tbox);
    tbox->add(new_label(_("SQL_MODE to be used in generated scripts:"), true), false, false);    
    tbox->add(entry = new_entry_option("SqlGenerator.Mysql:SQL_MODE", false), true, true);
    entry->set_tooltip(_("The default value of TRADITIONAL is recommended."));
    
    box->add(frame, false);
  }

  return box;
}



mforms::View *PreferencesForm::create_diagram_page()
{
  mforms::Box *box= mforms::manage(new mforms::Box(false));
  box->set_spacing(8);

  {
    mforms::Panel *frame= mforms::manage(new mforms::Panel(mforms::TitledBoxPanel));
    frame->set_title(_("All Objects"));

    mforms::Box *vbox= mforms::manage(new mforms::Box(false));

    vbox->set_padding(8);
    vbox->set_spacing(8);

    frame->add(vbox);
    
    mforms::CheckBox *check;

    check= new_checkbox_option("workbench.physical.ObjectFigure:Expanded");
    check->set_text(_("Expand New Objects"));
    check->set_tooltip(_("Set the initial state of newly created objects to expanded (or collapsed)"));
    vbox->add(check, false);

    check= new_checkbox_option("SynchronizeObjectColors");
    check->set_text(_("Propagate Object Color Changes to All Diagrams"));
    check->set_tooltip(_("If an object figure's color is changed, all figures in all diagrams that represent the same object are also updated"));
    vbox->add(check, false);
    
    box->add(frame, false);
  }

  {
    mforms::Panel *frame= mforms::manage(new mforms::Panel(mforms::TitledBoxPanel));
    frame->set_title(_("Tables"));

    mforms::Box *vbox= mforms::manage(new mforms::Box(false));

    vbox->set_padding(8);
    vbox->set_spacing(8);

    frame->add(vbox);
    
    mforms::CheckBox *check;

    check= new_checkbox_option("workbench.physical.TableFigure:ShowColumnTypes");
    check->set_text(_("Show Column Types"));
    check->set_tooltip(_("Show the column types along their names in table figures"));
    vbox->add(check, false);

    check= new_checkbox_option("workbench.physical.TableFigure:ShowSchemaName");
    check->set_text(_("Show Schema Name"));
    check->set_tooltip(_("Show owning schema name in the table titlebar figures"));
    vbox->add(check, false);

    {
      mforms::Box *hbox= mforms::manage(new mforms::Box(true));
      mforms::TextEntry *entry= new_entry_option("workbench.physical.TableFigure:MaxColumnTypeLength", true);
      
      hbox->set_spacing(4);
      
      //label->set_size(200, -1);
      entry->set_max_length(5);
      entry->set_size(50, -1);
      
      hbox->add(new_label(_("Max. Length of ENUMs and SETs to Display:"), true), false, false);
      hbox->add(entry, false);
      
      vbox->add(hbox, false);
    }    

    check= new_checkbox_option("workbench.physical.TableFigure:ShowColumnFlags");
    check->set_text(_("Show Column Flags"));
    check->set_tooltip(_("Show column flags such as NOT NULL or UNSIGNED along their names in table figures"));
    vbox->add(check, false);

    {
      mforms::Box *hbox= mforms::manage(new mforms::Box(true));
      mforms::TextEntry *entry= new_entry_option("workbench.physical.TableFigure:MaxColumnsDisplayed", true);
      mforms::Label *descr= mforms::manage(new mforms::Label());
    
      hbox->set_spacing(4);

      //label->set_size(200, -1);
      entry->set_max_length(5);
      entry->set_size(50, -1);
      descr->set_text(_("Larger tables will be truncated."));
      descr->set_style(mforms::SmallHelpTextStyle);

      hbox->add(new_label(_("Max. Number of Columns to Display:"), true), false, false);
      hbox->add(entry, false);
      hbox->add(descr, true, true);

      vbox->add(hbox, false);
    }
    
    box->add(frame, false);
  }


  {
    mforms::Panel *frame= mforms::manage(new mforms::Panel(mforms::TitledBoxPanel));
    frame->set_title(_("Routines"));

    mforms::Box *hbox= mforms::manage(new mforms::Box(true));

    hbox->set_padding(8);
    hbox->set_spacing(4);

    frame->add(hbox);
    
    mforms::TextEntry *entry;

    hbox->add(new_label(_("Trim Routine Names Longer Than")), false);
    
    entry= new_entry_option("workbench.physical.RoutineGroupFigure:MaxRoutineNameLength", true);
    entry->set_size(60, -1);
    entry->set_max_length(3);
    hbox->add(entry, false);

    hbox->add(new_label(_("characters")), false);

    box->add(frame, false);
  }


  {
    mforms::Panel *frame= mforms::manage(new mforms::Panel(mforms::TitledBoxPanel));
    frame->set_title(_("Relationships/Connections"));

    mforms::Box *vbox= mforms::manage(new mforms::Box(false));

    vbox->set_padding(8);
    vbox->set_spacing(8);

    frame->add(vbox);
    
    mforms::CheckBox *check;

    check= new_checkbox_option("workbench.physical.Diagram:DrawLineCrossings");
    check->set_text(_("Draw Line Crossings (slow in large diagrams)"));
    vbox->add(check, false);

    check= new_checkbox_option("workbench.physical.Connection:ShowCaptions");
    check->set_text(_("Show Captions"));
    vbox->add(check, false);

    check= new_checkbox_option("workbench.physical.Connection:CenterCaptions");
    check->set_text(_("Center Captions Over Line"));
    vbox->add(check, false);

    box->add(frame, false);
  }

  return box;
}



static void show_text_option(grt::DictRef options, const std::string &option_name, mforms::TextBox *text)
{
  text->set_value(options.get_string(option_name));
}


static void update_text_option(grt::DictRef options, const std::string &option_name, mforms::TextBox *text)
{
  options.gset(option_name, text->get_string_value());
}



void PreferencesForm::change_font_option(const std::string &option, const std::string &value)
{
  std::vector<std::string>::const_iterator it;
  if ((it = std::find(_font_options.begin(), _font_options.end(), option)) != _font_options.end())
  {
    int i = (int)(it - _font_options.begin());
    _font_list.node_at_row(i)->set_string(1, value);
  }
}


void PreferencesForm::font_preset_changed()
{
  int i = _font_preset.get_selected_index();

  if (i >= 0)
  {
    _wbui->set_wb_options_value(_model.is_valid() ? _model.id() : "", "workbench.physical.FontSet:Name", font_sets[i].name);

    change_font_option("workbench.physical.TableFigure:TitleFont", font_sets[i].object_title_font);
    change_font_option("workbench.physical.TableFigure:SectionFont", font_sets[i].object_section_font);
    change_font_option("workbench.physical.TableFigure:ItemsFont", font_sets[i].object_item_font);
    change_font_option("workbench.physical.ViewFigure:TitleFont", font_sets[i].object_title_font);
    change_font_option("workbench.physical.RoutineGroupFigure:TitleFont", font_sets[i].object_title_font);
    change_font_option("workbench.physical.RoutineGroupFigure:ItemsFont", font_sets[i].object_item_font);
    change_font_option("workbench.physical.Connection:CaptionFont", font_sets[i].object_item_font);
    change_font_option("workbench.physical.Layer:TitleFont", font_sets[i].object_item_font);
    change_font_option("workbench.model.NoteFigure:TextFont", font_sets[i].object_item_font);
  }
}


mforms::View *PreferencesForm::create_appearance_page()
{
  mforms::Box *box= mforms::manage(new mforms::Box(false));
  box->set_spacing(8);
  
  {
    mforms::Panel *frame= mforms::manage(new mforms::Panel(mforms::TitledBoxPanel));
    frame->set_title(_("Color Presets"));

    mforms::Table *table= mforms::manage(new mforms::Table());

    table->set_padding(8);
    table->set_row_spacing(4);
    table->set_column_spacing(4);    
    table->set_row_count(2);
    table->set_column_count(2);

    frame->add(table);

    mforms::TextBox *text;
    
    table->add(new_label(_("Colors available when creating tables, views etc")), 0, 1, 0, 1, mforms::HFillFlag);
    text= mforms::manage(new mforms::TextBox(mforms::VerticalScrollBar));
    text->set_size(200, 100);
    table->add(text, 0, 1, 1, 2, mforms::FillAndExpand);
    
    Option *option= new Option();
    _options.push_back(option);
    option->view= text;
    option->show_value= boost::bind(show_text_option, get_options(), "workbench.model.ObjectFigure:ColorList", text);
    option->update_value= boost::bind(update_text_option, get_options(), "workbench.model.ObjectFigure:ColorList", text);
    
    table->add(new_label(_("Colors available when creating layers, notes etc")), 1, 2, 0, 1, mforms::HFillFlag);
    text= mforms::manage(new mforms::TextBox(mforms::VerticalScrollBar));
    text->set_size(200, 100);
    table->add(text, 1, 2, 1, 2, mforms::FillAndExpand);

    option= new Option();
    _options.push_back(option);
    option->view= text;
    option->show_value= boost::bind(&show_text_option, get_options(), "workbench.model.Figure:ColorList", text);
    option->update_value= boost::bind(&update_text_option, get_options(), "workbench.model.Figure:ColorList", text);


    box->add(frame, false);
  }

  {
    mforms::Panel *frame= mforms::manage(new mforms::Panel(mforms::TitledBoxPanel));
    frame->set_title(_("Fonts"));

    mforms::Box *content = mforms::manage(new mforms::Box(false));
    content->set_padding(5);
    frame->add(content);

    mforms::Box *hbox = mforms::manage(new mforms::Box(true));
    content->add(hbox, false, true);
    hbox->set_spacing(12);
    hbox->set_padding(12);

    _font_preset.signal_changed()->connect(boost::bind(&PreferencesForm::font_preset_changed, this));
    
    std::string font_name;
    _wbui->get_wb_options_value(_model.is_valid() ? _model.id() : "", "workbench.physical.FontSet:Name", font_name);
    
    for (size_t i = 0; font_sets[i].name; i++)
    {
      // skip font options that are not modeling specific
      if (base::starts_with(font_sets[i].name, "workbench.general") ||
          base::starts_with(font_sets[i].name, "workbench.scripting"))
        continue;
      _font_preset.add_item(font_sets[i].name);
      if (font_sets[i].name == font_name)
        _font_preset.set_selected(i);
    }
    hbox->add(mforms::manage(new mforms::Label("Configure Fonts For:")), false, true);
    hbox->add(&_font_preset, true, true);

    _font_list.add_column(mforms::StringColumnType, _("Location"), 150, false);
    _font_list.add_column(mforms::StringColumnType, _("Font"), 150, true);
    _font_list.end_columns();

    content->add(&_font_list, true, true);
    box->add(frame, true, true);
  }

  return box;
}

/**
 * Theming and colors page.
 */
mforms::View *PreferencesForm::create_fonts_and_colors_page()
{
  Box* content = manage(new Box(false));
  content->set_spacing(8);

  {
    OptionTable *table = new OptionTable(this, _("Fonts"), true);

    table->add_option(new_entry_option("workbench.general.Editor:Font", false),
                      _("SQL Editor:"),
                      _("Global font for SQL text editors"));

    table->add_option(new_entry_option("workbench.general.Resultset:Font", false),
                      _("Resultset Grid:"),
                      _("Resultset grid in SQL Editor"));

    table->add_option(new_entry_option("workbench.scripting.ScriptingShell:Font", false),
                      _("Scripting Shell:"),
                      _("Scripting Shell output area"));

    table->add_option(new_entry_option("workbench.scripting.ScriptingEditor:Font", false),
                      _("Script Editor:"),
                      _("Code editors in scripting shell"));

    content->add(table, false, true);
  }

#ifdef _WIN32
  {
    mforms::Panel *frame = mforms::manage(new mforms::Panel(mforms::TitledBoxPanel));
    frame->set_title(_("Color Scheme"));
    mforms::Box *hbox = mforms::manage(new mforms::Box(true));
    hbox->add(new_label(_("Select your scheme:")), false, false);
    mforms::Selector *selector = new_selector_option("ColorScheme", "", true);
    selector->set_size(250, -1);
    hbox->add(selector, true, false);
    hbox->add(new_label(_("The scheme that determines the core colors."), false, true), true, false);

    frame->add(hbox);
    content->add(frame, false, true);
  }
#endif

  return content;
}


static std::string separate_camel_word(const std::string &word)
{
  std::string result;

  for (std::string::const_iterator c= word.begin(); c != word.end(); ++c)
  {
    if (!result.empty() && *c >= 'A' && *c <= 'Z')
      result.append(" ");
    result.append(1, *c);
  }
  
  return result;
}


void PreferencesForm::show_colors_and_fonts()
{
  std::vector<std::string> options= _wbui->get_wb_options_keys("");

  _font_options.clear();
  _font_list.clear();
  
  for (std::vector<std::string>::const_iterator iter= options.begin();
       iter != options.end(); ++iter)
  {
    if (base::starts_with(*iter, "workbench.general") ||
        base::starts_with(*iter, "workbench.scripting"))
      continue;

    if (bec::has_suffix(*iter, "Font") && bec::has_prefix(*iter, "workbench."))
    {
      std::string::size_type pos= iter->find(':');
      
      if (pos != std::string::npos)
      {
        try
        {
          std::string part= iter->substr(pos + 1);
          std::string figure= base::split(iter->substr(0, pos), ".")[2];
          std::string caption;

          part= part.substr(0, part.length() - 4);

          // substitute some figure names
          figure= bec::replace_string(figure, "NoteFigure", "TextFigure");
          
          caption= separate_camel_word(figure) + " " + part;
          
          mforms::TreeNodeRef node= _font_list.add_node();
          std::string value;
          _wbui->get_wb_options_value("", *iter, value);
          node->set_string(0, caption);
          node->set_string(1, value);
          
          _font_options.push_back(*iter);
        }
        catch (...)
        {
        }
      }
    }
  }
}

//--------------------------------------------------------------------------------------------------

void PreferencesForm::update_colors_and_fonts()
{
  for (int c= _font_list.count(), i= 0; i < c; i++)
  {
    std::string value= _font_list.root_node()->get_child(i)->get_string(1);

    _wbui->set_wb_options_value("", _font_options[i], value);
  }
}

//--------------------------------------------------------------------------------------------------

void PreferencesForm::toggle_use_global()
{
  _tabview.set_enabled(!_use_global.get_active());
}

//--------------------------------------------------------------------------------------------------

static struct RegisterNotifDocs_preferences_form
{
  RegisterNotifDocs_preferences_form()
  {
    base::NotificationCenter::get()->register_notification("GRNPreferencesDidCreate",
                                                           "preferences",
                                                           "Sent when the Preferences window is created.",
                                                           "",
                                                           "options - the options dictionary being edited\n"
                                                           "or\n"
                                                           "model-options - the model specific options dictionary being changed\n"
                                                           "model-id - the object id of the model for which the options are being changed");
    
    base::NotificationCenter::get()->register_notification("GRNPreferencesWillOpen",
                                                           "preferences",
                                                           "Sent when Preferences window is about to be shown on screen.",
                                                           "",
                                                           "options - the options dictionary being edited\n"
                                                           "or\n"
                                                           "model-options - the model specific options dictionary being changed\n"
                                                           "model-id - the object id of the model for which the options are being changed");    
    
    base::NotificationCenter::get()->register_notification("GRNPreferencesDidClose",
                                                           "preferences",
                                                           "Sent after Preferences window was closed.",
                                                           "",
                                                           "saved - 1 if the user chose to save the options changed or 0 if changes were cancelled\n"
                                                           "options - the options dictionary being edited\n"
                                                           "or\n"
                                                           "model-options - the model specific options dictionary being changed\n"
                                                           "model-id - the object id of the model for which the options are being changed\n");
  }
} initdocs_preferences_form;