File: wx_gui.cpp

package info (click to toggle)
fityk 0.4.4-1
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 2,472 kB
  • ctags: 2,617
  • sloc: cpp: 19,705; sh: 5,965; xml: 2,325; yacc: 356; makefile: 183; lex: 178
file content (1983 lines) | stat: -rw-r--r-- 71,975 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
// This file is part of fityk program. Copyright (C) Marcin Wojdyr

// wxwindows headers, see wxwindows samples for description
#include <wx/wxprec.h>
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif

#include "common.h"
RCSID ("$Id: wx_gui.cpp,v 1.32 2005/03/04 15:13:03 wojdyr Exp $")

#include <wx/laywin.h>
#include <wx/splitter.h>
#include <wx/filedlg.h>
#include <wx/valtext.h>
#include <wx/textdlg.h>
#if wxUSE_TOOLTIPS
    #include <wx/tooltip.h>
#endif
#include <wx/cmdline.h> 
#include <wx/tipdlg.h>
#include <wx/statline.h>
#include <wx/html/htmlwin.h>
#include <wx/fs_zip.h>
#include <wx/printdlg.h>
#include <wx/image.h>
#include <wx/config.h>
#include <wx/msgout.h>
#include <algorithm>
#include <locale.h>
#include <string.h>

#include "wx_plot.h"
#include "wx_gui.h"
#include "wx_dlg.h"
#include "wx_pane.h"
#include "other.h"
#include "v_fit.h"
#include "data.h"
#include "sum.h"
#include "pcore.h"
#include "fzgbase.h" 
#include "ffunc.h"
#include "manipul.h"
#include "ui.h"
#ifdef USE_XTAL
    #include "crystal.h"
#endif //USE_XTAL

#ifndef __WXMSW__
#include "img/fityk.xpm"
#endif

//toolbars icons
#include "img/clear.xpm"     
#include "img/plusbg.xpm"  
//#include "img/spline.xpm"
#include "img/autoadd.xpm"     
#include "img/tree.xpm" 
#include "img/zoom_t.xpm"
#include "img/range_t.xpm"
#include "img/baseline_t.xpm"
#include "img/addpeak_t.xpm"
#include "img/manual.xpm"
#include "img/openfile.xpm"
#include "img/fitrun.xpm"
#include "img/fitcont.xpm"
#include "img/fitundo.xpm"
#include "img/execute.xpm"
#include "img/log.xpm"
#include "img/reset.xpm"
#include "img/dump.xpm"
#include "img/whole.xpm"
#include "img/vertic.xpm"
#include "img/leftscroll.xpm"
#include "img/rightscroll.xpm"
#include "img/backv.xpm"
#include "img/dpane.xpm"
#include "img/mouse_l.xpm"
#include "img/mouse_r.xpm"


char* app_name = "fityk"; 
char* about_html = 
"<html> <body bgcolor=white text=white>                                  "
"  <table cellspacing=3 cellpadding=4 width=100%>                        "
"   <tr bgcolor=#101010 align=center> <td>                               "
"      <h1> fityk " VERSION "</h1>                                       "
"      <h6> powered by " wxVERSION_STRING "</h6>                         "
"      <p><font size=-2>$Date: 2005/03/04 15:13:03 $</font></p>          "
"   </td> </tr>                                                          "
"   <tr> <td bgcolor=#73A183>                                            "
"     <font color=black>                                                 "
"      <b><font size=+1> <p align = center>                              "
"       Copyright (C) 2001 - 2005 Marcin Wojdyr                          "
"      </font></b><p>                                                    "
"      <font size=-1>                                                    "
"       This program is free software; you can redistribute it           "
"       and/or modify it under the terms of the GNU General Public       "
"       License, version 2, as published by the Free Software Foundation;"
"      </font> <p>                                                       "
"       Feel free to send comments, questions, patches, bugreports       "
"       and feature requests to author                                   "
"       or to <i>fityk-users</i> mailing-list.                           "
"      <p align = center> WWW: <b>fityk.sf.net</b>                       "
"     </font>                                                            "
"   </td> </tr>                                                          "
"</table> </body> </html>                                                ";

using namespace std;
FFrame *frame = NULL;
std::vector<fp> params4plot;  //TODO move it to MainPlot or other class

enum {
    ID_QUIT            = 24001 ,
    ID_H_MANUAL                ,
    ID_H_TIP                   ,
    ID_D_LOAD                  ,
    ID_D_XLOAD                 ,
    ID_D_RECENT        = 24010 , //and next ones
    ID_D_INFO          = 24130 ,
    ID_D_EDITOR                ,
    ID_D_DEVIATION             ,
    ID_D_RANGE                 ,
    ID_D_B_INFO                ,
    ID_D_B_CLEAR               ,
    ID_D_BACKGROUND            ,
    ID_D_CALIBRATE             ,
    ID_D_EXPORT                ,
    ID_D_SET                   ,
    ID_S_ADD                   ,
    ID_S_HISTORY               ,
    ID_S_INFO                  ,
    ID_S_REMOVE                ,
    ID_S_CHANGE                ,
    ID_S_VALUE                 ,
    ID_S_EXPORT                ,
    ID_S_SET                   ,
    ID_M_FINDPEAK              ,
    ID_M_SET                   ,
    ID_F_METHOD                ,
    ID_F_RUN                   ,
    ID_F_CONTINUE              ,
    ID_F_INFO                  ,
    ID_F_SET                   ,
    ID_F_M             = 24160 , // and a few next IDs
    ID_C_WAVELENGTH    = 24171 ,
    ID_C_ADD                   ,
    ID_C_INFO                  ,
    ID_C_REMOVE                ,
    ID_C_ESTIMATE              ,
    ID_C_SET                   ,
    ID_O_LOG                   ,
    ID_O_RESET                 ,
    ID_PRINT                   ,
    ID_PRINT_SETUP             ,
    ID_PRINT_PREVIEW           ,
    ID_O_INCLUDE               ,
    ID_O_REINCLUDE             ,
    ID_O_WAIT                  ,
    ID_O_DUMP                  ,
    ID_O_SET                   ,
    ID_G_MODE                  ,
    ID_G_M_ZOOM                ,
    ID_G_M_RANGE               ,
    ID_G_M_BG                  ,
    ID_G_M_ADD                 ,
    ID_G_M_PEAK                ,
    ID_G_M_PEAK_N      = 24220 ,
    ID_G_SHOW          = 24260 ,
    ID_G_S_TOOLBAR             ,
    ID_G_S_STATBAR             ,
    ID_G_S_DPANE               ,
    ID_G_S_A1                  ,
    ID_G_S_A2                  ,
    ID_G_S_IO                  ,
    ID_G_CROSSHAIR             ,
    ID_G_V_ALL                 ,
    ID_G_V_VERT                ,
    ID_G_V_SCROLL_L            ,
    ID_G_V_SCROLL_R            ,
    ID_G_V_ZOOM_PREV   = 24302 ,
    ID_G_LCONF1        = 24342 ,
    ID_G_LCONF2                ,
    ID_G_LCONFB                ,
    ID_G_SCONF                 ,
    ID_G_SCONF1                ,
    ID_G_SCONF2                ,

    ID_ft_m_zoom               ,
    ID_ft_m_range              ,
    ID_ft_m_bg                 ,
    ID_ft_m_add                ,
    ID_ft_v_pr                 ,
    ID_ft_b_with               ,
    ID_ft_f_run                ,
    ID_ft_f_cont               ,
    ID_ft_f_undo               ,
    ID_ft_s_aa                 ,
    ID_ft_dpane                ,
    ID_ft_peakchoice
};

IMPLEMENT_APP(FApp)
string get_full_path_of_help_file (const string &name);


/// command line options
static const wxCmdLineEntryDesc cmdLineDesc[] = {
    { wxCMD_LINE_SWITCH, _T("h"), _T("help"), "show this help message",
                                wxCMD_LINE_VAL_NONE, wxCMD_LINE_OPTION_HELP },
    /*
    { wxCMD_LINE_SWITCH, "v", "verbose", "be verbose", wxCMD_LINE_VAL_NONE, 0 },
    { wxCMD_LINE_SWITCH, "q", "quiet",   "be quiet", wxCMD_LINE_VAL_NONE, 0 },
    { wxCMD_LINE_OPTION, "o", "output", "output file", wxCMD_LINE_VAL_NONE, 0 },
    */
    { wxCMD_LINE_SWITCH, "V", "version", 
              "output version information and exit", wxCMD_LINE_VAL_NONE, 0 },
    { wxCMD_LINE_OPTION, "c", "cmd", "script passed in as string", 
                                                   wxCMD_LINE_VAL_STRING, 0 },
    { wxCMD_LINE_PARAM,  0, 0, "script or data file", wxCMD_LINE_VAL_STRING, 
                        wxCMD_LINE_PARAM_OPTIONAL|wxCMD_LINE_PARAM_MULTIPLE },
    { wxCMD_LINE_NONE, 0, 0, 0,  wxCMD_LINE_VAL_NONE, 0 }
};  



bool FApp::OnInit(void)
{
    setlocale(LC_NUMERIC, "C");

    // if options can be parsed
    wxCmdLineParser cmdLineParser(cmdLineDesc, argc, argv);
    if (cmdLineParser.Parse(false) != 0) {
        cmdLineParser.Usage();
        return false; //false = exit the application
    }
    else if (cmdLineParser.Found("V")) {
        wxMessageOutput::Get()->Printf("fityk version " VERSION "\n");
        return false; //false = exit the application
    } //the rest of options will be processed in process_argv()

    AL = new ApplicationLogic; 

    //global settings
#if wxUSE_TOOLTIPS
    wxToolTip::Enable (true);
    wxToolTip::SetDelay (500);
#endif
    wxConfig::DontCreateOnDemand();
    wxString pre = wxString(config_dirname) + wxFILE_SEP_PATH;
    conf_filename = pre + "config";
    alt_conf_filename = pre + "alt-config";
    wxConfigBase *config = new wxConfig("", "", pre+"wxoptions", "", 
                                        wxCONFIG_USE_LOCAL_FILE);
    wxConfig::Set(config);

    // Create the main frame window
    frame = new FFrame(NULL, -1, app_name, wxDEFAULT_FRAME_STYLE);

    frame->plot_pane->set_mouse_mode(mmd_zoom);

    wxConfigBase *cf = new wxConfig("", "", conf_filename, "", 
                                    wxCONFIG_USE_LOCAL_FILE);
    frame->read_all_settings(cf);

    frame->Show(true);

    // it does not work earlier, problems with OutputWin colors (wxGTK gtk1.2)
    frame->io_pane->read_settings(cf);
    frame->io_pane->show_fancy_dashes();
    delete cf;

    SetTopWindow(frame);

    //run initial commands (from ~/.fityk/init file)
    wxString fityk_dir = wxGetHomeDir() + wxFILE_SEP_PATH + config_dirname;
    if (!wxDirExists(fityk_dir))
        wxMkdir(fityk_dir);
    wxString startup_file_path = fityk_dir + wxFILE_SEP_PATH 
                                + startup_commands_filename;
    if (wxFileExists(startup_file_path)) {
        getUI()->execScript(startup_file_path.c_str());
    }

    process_argv(cmdLineParser);

    wxString conf_path = "/TipOfTheDay/ShowAtStartup";
    if (read_bool_from_config(wxConfig::Get(), conf_path, true)) 
        frame->OnTipOfTheDay(dummy_cmd_event);

    return true;
}


int FApp::OnExit()
{ 
    delete AL; 
    wxConfig::Get()->Write("/FitykVersion", VERSION);
    delete wxConfigBase::Set((wxConfigBase *) NULL);
    return 0;
}

bool FApp::is_fityk_script(string filename)
{
    const char *magic = "# Fityk";

    ifstream f(filename.c_str(), ios::in | ios::binary);
    if (!f) 
        return false;

    int n = filename.size();
    if (n > 4 && !filename.substr(n-4, n).compare(".fit")
            || n > 6 && !filename.substr(n-6, n).compare(".fityk"))
        return true;

    const int magic_len = strlen(magic);
    char *buffer = new char[magic_len + 1];
    for (int i = 0; i <= magic_len; ++i) buffer[i] = 0;
    f.read(buffer, magic_len);
    int cmp = strncmp(magic, buffer, magic_len);
    delete [] buffer;
    return !cmp;
}

/// parse and execute command line switches and arguments
void FApp::process_argv(wxCmdLineParser &cmdLineParser)
{
    /*
    if (cmdLineParser.Found("v"))
        verbosity++;
    if (cmdLineParser.Found("q"))
        verbosity--;
    */
    wxString cmd;
    if (cmdLineParser.Found("c", &cmd))
        getUI()->execAndLogCmd(cmd.c_str());
    //the rest of parameters/arguments are scripts and/or data files
    int data_counter = 0; //number of data files
    for (unsigned int i = 0; i < cmdLineParser.GetParamCount(); i++) {
        string par = cmdLineParser.GetParam(i).c_str();
        if (is_fityk_script(par))
            getUI()->execScript(par);
        else {
            //if there are multiple data files specified at command line,
            //open each as separate dataset in the same plot
            if (data_counter == 0) {
                getUI()->execAndLogCmd("d.load '" + par + "'");
            }
            else {
                getUI()->execAndLogCmd("d.activate ::* ; d.load '" + par + "'");
                frame->SwitchDPane(true);
            }
            data_counter++;
        }
    }
}




BEGIN_EVENT_TABLE(FFrame, wxFrame)
    EVT_IDLE (FFrame::OnIdle)

    EVT_MENU (ID_D_LOAD,        FFrame::OnDLoad)   
    EVT_MENU (ID_D_XLOAD,       FFrame::OnDXLoad)   
    EVT_MENU_RANGE (ID_D_RECENT+1, ID_D_RECENT+100, FFrame::OnDRecent)
    EVT_MENU (ID_D_EDITOR,      FFrame::OnDEditor)
    EVT_MENU (ID_D_INFO,        FFrame::OnDInfo)
    EVT_MENU (ID_D_DEVIATION  , FFrame::OnDDeviation)  
    EVT_MENU (ID_D_RANGE,       FFrame::OnDRange)
    EVT_MENU (ID_D_B_INFO,      FFrame::OnDBInfo)
    EVT_MENU (ID_D_B_CLEAR,     FFrame::OnDBClear)
    EVT_MENU (ID_D_CALIBRATE,   FFrame::OnDCalibrate)  
    EVT_MENU (ID_D_EXPORT,      FFrame::OnDExport) 
    EVT_MENU (ID_D_SET,         FFrame::OnDSet) 

    EVT_MENU (ID_S_HISTORY,     FFrame::OnSHistory)    
    EVT_MENU (ID_S_INFO,        FFrame::OnSInfo)    
    EVT_MENU (ID_S_ADD,         FFrame::OnSAdd)    
    EVT_MENU (ID_S_REMOVE,      FFrame::OnSRemove)    
    EVT_MENU (ID_S_CHANGE,      FFrame::OnSChange)    
    EVT_MENU (ID_S_VALUE,       FFrame::OnSValue)    
    EVT_MENU (ID_S_EXPORT,      FFrame::OnSExport)    
    EVT_MENU (ID_S_SET,         FFrame::OnSSet)    

    EVT_MENU (ID_M_FINDPEAK,    FFrame::OnMFindpeak)
    EVT_MENU (ID_M_SET,         FFrame::OnMSet)

    EVT_UPDATE_UI (ID_F_METHOD, FFrame::OnFMethodUpdate)
    EVT_MENU_RANGE (ID_F_M+0, ID_F_M+8, FFrame::OnFOneOfMethods)    
    EVT_MENU (ID_F_RUN,         FFrame::OnFRun)    
    EVT_MENU (ID_F_CONTINUE,    FFrame::OnFContinue)    
    EVT_MENU (ID_F_INFO,        FFrame::OnFInfo)    
    EVT_MENU (ID_F_SET,         FFrame::OnFSet)    

#ifdef USE_XTAL
    EVT_MENU (ID_C_WAVELENGTH,  FFrame::OnCWavelength)    
    EVT_MENU (ID_C_ADD,         FFrame::OnCAdd)    
    EVT_MENU (ID_C_INFO,        FFrame::OnCInfo)    
    EVT_MENU (ID_C_REMOVE,      FFrame::OnCRemove)    
    EVT_MENU (ID_C_ESTIMATE,    FFrame::OnCEstimate)    
    EVT_MENU (ID_C_SET,         FFrame::OnCSet)    
#endif

    EVT_MENU (ID_O_LOG,         FFrame::OnOLog)    
    EVT_MENU (ID_O_RESET,       FFrame::OnO_Reset)    
    EVT_MENU (ID_O_INCLUDE,     FFrame::OnOInclude)    
    EVT_MENU (ID_O_REINCLUDE,   FFrame::OnOReInclude)    
    EVT_MENU (ID_PRINT,         FFrame::OnPrint)
    EVT_MENU (ID_PRINT_SETUP,   FFrame::OnPrintSetup)
    EVT_MENU (ID_PRINT_PREVIEW, FFrame::OnPrintPreview)
    EVT_MENU (ID_O_WAIT,        FFrame::OnOWait)    
    EVT_MENU (ID_O_DUMP,        FFrame::OnODump)    
    EVT_MENU (ID_O_SET,         FFrame::OnOSet)    

    EVT_MENU (ID_G_M_ZOOM,      FFrame::OnChangeMouseMode)
    EVT_MENU (ID_G_M_RANGE,     FFrame::OnChangeMouseMode)
    EVT_MENU (ID_G_M_BG,        FFrame::OnChangeMouseMode)
    EVT_MENU (ID_G_M_ADD,       FFrame::OnChangeMouseMode)
    EVT_UPDATE_UI (ID_G_M_PEAK, FFrame::OnModePeak)
    EVT_MENU_RANGE (ID_G_M_PEAK_N+0, ID_G_M_PEAK_N+30, FFrame::OnChangePeakType)
    EVT_UPDATE_UI (ID_G_SHOW,   FFrame::OnGuiShowUpdate)
    EVT_MENU (ID_G_S_DPANE,     FFrame::OnSwitchDPane)
    EVT_MENU_RANGE (ID_G_S_A1, ID_G_S_A2, FFrame::OnSwitchAuxPlot)
    EVT_MENU (ID_G_S_IO,        FFrame::OnSwitchIOPane)
    EVT_MENU (ID_G_S_TOOLBAR,   FFrame::OnSwitchToolbar)
    EVT_MENU (ID_G_S_STATBAR,   FFrame::OnSwitchStatbar)
    EVT_MENU (ID_G_CROSSHAIR,   FFrame::OnSwitchCrosshair)
    EVT_MENU (ID_G_V_ALL,       FFrame::OnGViewAll)
    EVT_MENU (ID_G_V_VERT,      FFrame::OnGFitHeight)
    EVT_MENU (ID_G_V_SCROLL_L,  FFrame::OnGScrollLeft)
    EVT_MENU (ID_G_V_SCROLL_R,  FFrame::OnGScrollRight)
    EVT_UPDATE_UI (ID_G_V_ZOOM_PREV, FFrame::OnShowMenuZoomPrev)
    EVT_MENU_RANGE (ID_G_V_ZOOM_PREV+1, ID_G_V_ZOOM_PREV+20, 
                                FFrame::OnPreviousZoom)    
    EVT_MENU (ID_G_LCONF1,      FFrame::OnConfigRead)
    EVT_MENU (ID_G_LCONF2,      FFrame::OnConfigRead)
    EVT_MENU (ID_G_LCONFB,      FFrame::OnConfigBuiltin)
    EVT_MENU (ID_G_SCONF1,      FFrame::OnConfigSave)
    EVT_MENU (ID_G_SCONF2,      FFrame::OnConfigSave)

    EVT_MENU (ID_H_MANUAL,      FFrame::OnShowHelp)
    EVT_MENU (ID_H_TIP,         FFrame::OnTipOfTheDay)
    EVT_MENU (wxID_ABOUT,       FFrame::OnAbout)
    EVT_MENU (ID_QUIT,          FFrame::OnQuit)

//  EVT_SASH_DRAGGED_RANGE (ID_WINDOW_TOP1, ID_WINDOW_BOTTOM, 
//                            FFrame::OnSashDrag)
END_EVENT_TABLE()


    // Define my frame constructor
FFrame::FFrame(wxWindow *parent, const wxWindowID id, const wxString& title, 
                 const long style)
    : wxFrame(parent, id, title, wxDefaultPosition, wxDefaultSize, style), 
      main_pane(0), data_pane(0), status_bar(0), 
      peak_type_nr(0), toolbar(0), dxload_dialog(0), data_editor(0),
      print_data(new wxPrintData), page_setup_data(new wxPageSetupData),
#ifdef __WXMSW__
      help()
#else
      help(wxHF_TOOLBAR | wxHF_CONTENTS | wxHF_SEARCH | wxHF_BOOKMARKS 
           | wxHF_PRINT | wxHF_MERGE_BOOKS)
#endif
{
    // Load icon and bitmap
    SetIcon (wxICON (fityk));

    //sizer, splitters, etc.
    wxBoxSizer *sizer = new wxBoxSizer(wxVERTICAL);
    v_splitter = new ProportionalSplitter(this, -1, 0.8);
    main_pane = new ProportionalSplitter(v_splitter, -1, 0.7);
    plot_pane = new PlotPane(main_pane);
    io_pane = new IOPane(main_pane);
    main_pane->SplitHorizontally(plot_pane, io_pane);
    data_pane = new DataPane(v_splitter);
    data_pane->Show(false);
    v_splitter->Initialize(main_pane);
    sizer->Add(v_splitter, 1, wxEXPAND, 0);

    read_recent_data_files();
    set_menubar();

    toolbar = new FToolBar(this, -1);
    SetToolBar(toolbar);

    //status bar
    status_bar = new FStatusBar(this);
    SetStatusBar(status_bar);

    SetAutoLayout (true);
    SetSizer(sizer);
    sizer->Fit(this);
    sizer->SetSizeHints(this);


    wxFileSystem::AddHandler(new wxZipFSHandler);
    wxImage::AddHandler(new wxPNGHandler);
    string help_file = "fitykhelp.htb";
    string help_path = get_full_path_of_help_file(help_file); 
    string help_path_no_exten = help_path.substr(0, help_path.size() - 4);
    help.Initialize(help_path_no_exten.c_str());
    focus_input();
}

FFrame::~FFrame() 
{
    write_recent_data_files();
    delete print_data;
    delete page_setup_data;
}

void FFrame::OnQuit(wxCommandEvent& WXUNUSED(event))
{
    Close(true);
}


void FFrame::read_recent_data_files()
{
    recent_data_files.clear();
    wxConfigBase *c = wxConfig::Get();
    if (c && c->HasGroup("/RecentDataFiles")) {
        for (int i = 0; i < 20; i++) {
            wxString key = wxString("/RecentDataFiles/") + S(i).c_str();
            if (c->HasEntry(key))
                recent_data_files.push_back(wxFileName(c->Read(key, "")));
        }
    }
}

void FFrame::write_recent_data_files()
{
    wxConfigBase *c = wxConfig::Get();
    wxString group("/RecentDataFiles");
    if (c->HasGroup(group))
        c->DeleteGroup(group);
    int counter = 0;
    for (list<wxFileName>::const_iterator i = recent_data_files.begin(); 
         i != recent_data_files.end() && counter < 9; 
         i++, counter++) {
        wxString key = group + "/" + S(counter).c_str();
        c->Write(key, i->GetFullPath());
    }
}

void FFrame::add_recent_data_file(wxString filename)
{
    const int count = data_menu_recent->GetMenuItemCount();
    const wxMenuItemList& mlist = data_menu_recent->GetMenuItems();
    const wxFileName fn = wxFileName(filename);
    recent_data_files.remove(filename);
    recent_data_files.push_front(fn);
    int id_new = 0;
    for (wxMenuItemList::Node *i = mlist.GetFirst(); i; i = i->GetNext()) 
        if (i->GetData()->GetHelp() == fn.GetFullPath()) {
            id_new = i->GetData()->GetId();
            data_menu_recent->Delete(i->GetData());
            break;
        }
    if (id_new == 0) {
        if (count >= 15) {
            wxMenuItem *item = mlist.GetLast()->GetData();
            id_new = item->GetId();
            data_menu_recent->Delete(item);
        }
        else
            id_new = ID_D_RECENT+count+1;
    }
    data_menu_recent->Prepend(id_new, fn.GetFullName(), fn.GetFullPath());
}

void FFrame::read_all_settings(wxConfigBase *cf)
{
    read_settings(cf);
    plot_pane->read_settings(cf);
    io_pane->read_settings(cf);
    //data_pane->read_settings(cf);
}

void FFrame::read_settings(wxConfigBase *cf)
{
    // restore window layout, frame position and size
    cf->SetPath("/Frame");
    SwitchToolbar(from_config_read_bool(cf, "ShowToolbar", true));
    SwitchStatbar(from_config_read_bool(cf, "ShowStatbar", true));
    int x = cf->Read("x", 50),
        y = cf->Read("y", 50),
        w = cf->Read("w", 650),
        h = cf->Read("h", 400);
    Move(x, y);
    SetClientSize(w, h);
    v_splitter->SetProportion(from_config_read_double(cf, "VertSplitProportion",
                                                          0.8));
    SwitchDPane(from_config_read_bool(cf, "ShowDataPane", false));
    main_pane->SetProportion(from_config_read_double(cf, "MainPaneProportion",
                                                          0.7));
    SwitchIOPane(from_config_read_bool(cf, "ShowIOPane", true));
    SwitchCrosshair(from_config_read_bool(cf, "ShowCrosshair", false));
}

void FFrame::save_all_settings(wxConfigBase *cf) const
{
    cf->Write("/FitykVersion", VERSION);
    save_settings(cf);
    plot_pane->save_settings(cf);
    io_pane->save_settings(cf);
    //data_pane->save_settings(cf);
}

void FFrame::save_settings(wxConfigBase *cf) const
{
    cf->SetPath ("/Frame");
    cf->Write("ShowToolbar", toolbar != 0);
    cf->Write("ShowStatbar", status_bar != 0);
    cf->Write("VertSplitProportion", v_splitter->GetProportion());
    cf->Write("ShowDataPane", v_splitter->IsSplit());
    cf->Write("MainPaneProportion", main_pane->GetProportion());
    cf->Write("ShowIOPane", main_pane->IsSplit());
    cf->Write("ShowCrosshair", plot_pane->crosshair_cursor);
    int x, y, w, h;
    GetClientSize(&w, &h);
    GetPosition(&x, &y);
    cf->Write("x", (long) x);
    cf->Write("y", (long) y);
    cf->Write("w", (long) w);
    cf->Write("h", (long) h);
    //cf->Write ("BotWinHeight", bottom_window->GetClientSize().GetHeight()); 
}

void FFrame::set_menubar()
{
    // Make a menubar
    wxMenu* data_menu = new wxMenu;
    data_menu->Append (ID_D_LOAD,     "&Load File", "Load data from file");
    data_menu->Append (ID_D_XLOAD,    "&Load File (Custom)", 
                                    "Load data from file, with some options");
    this->data_menu_recent = new wxMenu;
    int rf_counter = 1;
    for (list<wxFileName>::const_iterator i = recent_data_files.begin(); 
         i != recent_data_files.end() && rf_counter < 16; i++, rf_counter++) 
        data_menu_recent->Append(ID_D_RECENT + rf_counter, 
                                 i->GetFullName(), i->GetFullPath());
    data_menu->Append(ID_D_RECENT, "Recent &Files", data_menu_recent); 
    data_menu->AppendSeparator();

    data_menu->Append (ID_D_EDITOR,   "&Viewer", "Open data viewer");
    data_menu->Append (ID_D_INFO,     "&Info", "Info about loaded data");
    data_menu->Append (ID_D_DEVIATION  , "Std. &Dev.", 
                                            "Change errors for data points");
    data_menu->Append (ID_D_RANGE,    "&Range", "Change active points");
    wxMenu* data_bg_menu = new wxMenu;
    data_bg_menu->Append(ID_D_B_INFO, "&Info", "Info about baseline points");
    data_bg_menu->Append(ID_D_B_CLEAR, "&Clear", "Clear all baseline points");
    data_menu->Append (ID_D_BACKGROUND, "&Background", data_bg_menu);
    data_menu->Append (ID_D_CALIBRATE, "&Calibrate",
                       "Define calibration curve (command line only)");
    data_menu->Append (ID_D_EXPORT,   "&Export", "Save data to file");
    data_menu->Append (ID_D_SET,      "&Settings", "Preferences and options");

    wxMenu* sum_menu = new wxMenu;
    sum_menu->Append (ID_S_HISTORY,   "&History", "Go back or forward"
                                                    " in change history");      
    sum_menu->Append (ID_S_INFO,      "&Info", "Info about fitted curve");      
    sum_menu->Append (ID_S_ADD,       "&Add", "Add parameter or function"); 
    sum_menu->Append (ID_S_REMOVE,    "&Remove/Freeze",
         "Remove parameter/function or avoid fitting of selected parameters");
    sum_menu->Append (ID_S_CHANGE,    "&Change", "Change value of a-parameter");
    sum_menu->Append (ID_S_VALUE,     "&Value", "Computes value of sum"
                                                    " or selected function");
    sum_menu->Append (ID_S_EXPORT,    "&Export", "Export fitted curve to file");
    sum_menu->Append (ID_S_SET,       "&Settings", "Preferences and options"); 

    wxMenu* manipul_menu = new wxMenu;
    manipul_menu->Append (ID_M_FINDPEAK, "&Find peak", 
                                       "Search for a peak (rather useless)");
    manipul_menu->Append (ID_M_SET,   "&Settings", "Preferences and options");

    wxMenu* fit_menu = new wxMenu;
    wxMenu* fit_method_menu = new wxMenu;
    fit_method_menu->AppendRadioItem (ID_F_M+0, "&Levenberg-Marquardt", 
                                                "gradient based method");
    fit_method_menu->AppendRadioItem (ID_F_M+1, "Nelder-Mead &simplex", 
                                      "old, slow but reliable method");
    fit_method_menu->AppendRadioItem (ID_F_M+2, "&Genetic Algorithm", 
                                                "almost AI");
    fit_menu->Append (ID_F_METHOD,    "&Method", fit_method_menu, 
                                            "It influences commands below");
    fit_menu->AppendSeparator();
    fit_menu->Append (ID_F_RUN,       "&Run", "Start fitting sum to data");
    fit_menu->Append (ID_F_CONTINUE,  "&Continue", "Continue fitting");      
    fit_menu->Append (ID_F_INFO,      "&Info", "Info about current fit");      
    fit_menu->Append (ID_F_SET,       "&Settings", "Preferences and options"); 

#ifdef USE_XTAL
    wxMenu* crystal_menu = new wxMenu;
    crystal_menu->Append (ID_C_WAVELENGTH, "&Wavelength", 
                    "Defines X-rays wavelengths (command line only)");
    crystal_menu->Append (ID_C_ADD,      "&Add", 
            "Add phase or plane (command line only)"); 
    crystal_menu->Append (ID_C_INFO,     "&Info", 
                            "Crystalography info (command line only)"); 
    crystal_menu->Append (ID_C_REMOVE,   "&Remove", 
                          "Remove phase or plane (command line only)");
    crystal_menu->Append (ID_C_ESTIMATE, "&Estimate peak", 
                            "Guess peak parameters (command line only)");      
    crystal_menu->Append (ID_C_SET,    "&Settings", "Preferences and options");
#endif //USE_XTAL

    wxMenu* gui_menu = new wxMenu;
    wxMenu* gui_menu_mode = new wxMenu;
    gui_menu_mode->AppendRadioItem (ID_G_M_ZOOM, "&Normal", 
                                    "Use mouse for zooming, moving peaks etc.");
    gui_menu_mode->AppendRadioItem (ID_G_M_RANGE, "&Range", 
                             "Use mouse for activating and disactivating data");
    gui_menu_mode->AppendRadioItem (ID_G_M_BG, "&Baseline", 
                                    "Use mouse for substracting background");
    gui_menu_mode->AppendRadioItem (ID_G_M_ADD, "&Peak-Add", 
                                    "Use mouse for adding new peaks");
    wxMenu* gui_menu_mode_peak = new wxMenu;
    vector<const z_names_type*> all_t = V_fzg::all_types(fType);
    for (vector<const z_names_type*>::const_iterator i = all_t.begin();
                                                         i != all_t.end(); i++)
        gui_menu_mode_peak->AppendRadioItem(ID_G_M_PEAK_N + (i - all_t.begin()),
                                            (*i)->name.c_str());
    gui_menu_mode->AppendSeparator();
    gui_menu_mode->Append (ID_G_M_PEAK, "Peak &type", gui_menu_mode_peak);
    gui_menu->Append(ID_G_MODE, "&Mode", gui_menu_mode);
    gui_menu->AppendSeparator();
    wxMenu* gui_menu_show = new wxMenu;
    gui_menu_show->AppendCheckItem (ID_G_S_TOOLBAR, "&Toolbar", 
                                    "Show/hide toolbar");
    gui_menu_show->Check(ID_G_S_TOOLBAR, true);
    gui_menu_show->AppendCheckItem (ID_G_S_STATBAR, "&Status Bar", 
                                    "Show/hide status bar");
    gui_menu_show->Check(ID_G_S_STATBAR, true);
    gui_menu_show->AppendCheckItem (ID_G_S_DPANE, "&Datasets Pane", 
                                    "Show/hide datasets pane");  
    gui_menu_show->AppendCheckItem (ID_G_S_A1, "&Auxiliary Plot 1", 
                                    "Show/hide auxiliary plot I");  
    gui_menu_show->Check(ID_G_S_A1, true);
    gui_menu_show->AppendCheckItem (ID_G_S_A2, "&Auxiliary Plot 2", 
                                    "Show/hide auxiliary plot II");  
    gui_menu_show->Check(ID_G_S_A2, false);
    gui_menu_show->AppendCheckItem (ID_G_S_IO, "&Input/Output Text Pane", 
                                    "Show/hide text input/output");  
    gui_menu_show->Check(ID_G_S_IO, true);
    gui_menu->Append(ID_G_SHOW, "S&how", gui_menu_show);
    gui_menu->AppendCheckItem(ID_G_CROSSHAIR, "&Crosshair Cursor", 
                                              "Show crosshair cursor");
    gui_menu->AppendSeparator();
    gui_menu->Append (ID_G_V_ALL, "Zoom &All", "View whole data");
    gui_menu->Append (ID_G_V_VERT, "Fit &vertically", "Adjust vertical zoom");
    gui_menu->Append (ID_G_V_SCROLL_L, "Scroll &Left", "Scroll view left");
    gui_menu->Append (ID_G_V_SCROLL_R, "Scroll &Right", "Scroll view right");

    wxMenu* gui_menu_zoom_prev = new wxMenu;
    gui_menu->Append(ID_G_V_ZOOM_PREV, "&Previous Zooms", gui_menu_zoom_prev);
    gui_menu->AppendSeparator();
    gui_menu->Append(ID_G_LCONF1, "Load &default config", 
                                                "Default configuration file");
    gui_menu->Append(ID_G_LCONF2, "Load &alt. config", 
                                            "Alternative configuration file");
    gui_menu->Append(ID_G_LCONFB, "Load &built-in config", 
                                                   "Built-in configuration");
    wxMenu* gui_menu_sconfig = new wxMenu;
    gui_menu_sconfig->Append(ID_G_SCONF1, "as default", 
                           "Save current configuration to default config file");
    gui_menu_sconfig->Append(ID_G_SCONF2, "as alternative",
                       "Save current configuration to alternative config file");
    gui_menu->Append(ID_G_SCONF, "&Save current config", gui_menu_sconfig);

    wxMenu* session_menu = new wxMenu;
    session_menu->Append (ID_O_INCLUDE,   "&Include file", 
                                            "Execute commands from a file");
    session_menu->Append (ID_O_REINCLUDE, "&Re-Include file", 
                "Reset & execute commands from the file included last time");
    session_menu->Enable (ID_O_REINCLUDE, false);
    session_menu->Append (ID_O_RESET,     "&Reset", "Reset current session");
    session_menu->AppendSeparator();
    session_menu->Append (ID_O_LOG,       "&Log to file", 
                                            "Start/stop logging to file");
    session_menu->Append (ID_O_DUMP,      "&Dump to file", 
                                         "Save current program state to file");
    session_menu->AppendSeparator();
    session_menu->Append (ID_PRINT,       "&Print...", "Print plots");
    session_menu->Append (ID_PRINT_SETUP, "Print Se&tup",
                                                    "Printer and page setup");
    session_menu->Append (ID_PRINT_PREVIEW, "Print Pre&view", "Preview"); 
    session_menu->AppendSeparator();
    session_menu->Append (ID_O_WAIT,    "&Wait", "Just wait (rather useless)");
    session_menu->AppendSeparator();
    session_menu->Append (ID_O_SET,     "&Settings", "Preferences and options");
    session_menu->AppendSeparator();
    session_menu->Append(ID_QUIT, "&Quit", "Exit the program");

    wxMenu *help_menu = new wxMenu;
    help_menu->Append(ID_H_MANUAL, "&Manual", "User's Manual");
    help_menu->Append(ID_H_TIP, "&Tip of the day", "Show tip of the day");
    help_menu->Append(wxID_ABOUT, "&About...", "Show about dialog");

    wxMenuBar *menu_bar = new wxMenuBar(wxMENU_TEAROFF);
    menu_bar->Append (session_menu, "S&ession" );
    menu_bar->Append (data_menu, "&Data" );
    menu_bar->Append (sum_menu, "&Sum" );
    menu_bar->Append (manipul_menu, "Find&Peak");
    menu_bar->Append (fit_menu, "Fi&t" );
#ifdef USE_XTAL
    menu_bar->Append (crystal_menu, "&Xtal/Diffr" );
#endif //USE_XTAL
    menu_bar->Append (gui_menu, "&GUI");
    menu_bar->Append (help_menu, "&Help");

    SetMenuBar(menu_bar);
}


    //construct GUI->Previous Zooms menu
void FFrame::OnShowMenuZoomPrev(wxUpdateUIEvent& event)
{
    static vector<string> old_zoom_hist;
    const vector<string> &zoom_hist = plot_pane->get_zoom_hist();
    if (old_zoom_hist == zoom_hist) 
        return;
    wxMenu *menu = GetMenuBar()->FindItem(ID_G_V_ZOOM_PREV)->GetSubMenu(); 
    while (menu->GetMenuItemCount() > 0) //clear 
        menu->Delete(menu->GetMenuItems().GetLast()->GetData());
    int last = zoom_hist.size() - 1;
    for (int i = last, j = 1; i >= 0 && i > last - 10; i--, j++) 
        menu->Append(ID_G_V_ZOOM_PREV + j, zoom_hist[i].c_str());
    old_zoom_hist = zoom_hist;
    event.Skip();
}
           

void FFrame::OnTipOfTheDay(wxCommandEvent& WXUNUSED(event))
{
    string tip_file = "fityk_tips.txt";
    string tip_path = get_full_path_of_help_file(tip_file); 
    int idx = wxConfig::Get()->Read("/TipOfTheDay/idx", 0L); 
    wxTipProvider *tipProvider = wxCreateFileTipProvider(tip_path.c_str(), idx);
    bool showAtStartup = wxShowTip(this, tipProvider);
    idx = tipProvider->GetCurrentTip();
    delete tipProvider;
    wxConfig::Get()->Write("/TipOfTheDay/ShowAtStartup", showAtStartup); 
    wxConfig::Get()->Write("/TipOfTheDay/idx", idx); 
}

void FFrame::OnShowHelp(wxCommandEvent& WXUNUSED(event))
{
        help.DisplayContents();
}

void FFrame::OnAbout(wxCommandEvent& WXUNUSED(event))
{
    wxDialog* dlg = new wxDialog(this, -1, wxString("About..."));
    wxBoxSizer *topsizer = new wxBoxSizer(wxVERTICAL);
    wxHtmlWindow *html = new wxHtmlWindow (dlg, -1, 
                                           wxDefaultPosition, wxSize(300, 160), 
                                           wxHW_SCROLLBAR_NEVER);
    html->SetBorders(0);
    html->SetPage(about_html);
    html->SetSize (html->GetInternalRepresentation()->GetWidth(), 
                   html->GetInternalRepresentation()->GetHeight());
    topsizer->Add (html, 1, wxALL, 10);
    topsizer->Add (new wxStaticLine(dlg, -1), 0, wxEXPAND|wxLEFT|wxRIGHT, 10);
    wxButton *bu_ok = new wxButton (dlg, wxID_OK, "OK");
    bu_ok->SetDefault();
    topsizer->Add (bu_ok, 0, wxALL | wxALIGN_RIGHT, 15);
    dlg->SetAutoLayout(true);
    dlg->SetSizer(topsizer);
    topsizer->Fit(dlg);
    dlg->ShowModal();
    dlg->Destroy();
}

void FFrame::not_implemented_menu_item (const std::string &command) const 
{
    wxMessageBox (("This menu item is only reminding about command " + command 
                    + ".\n If you don't know how to use this command,\n"
                    " look for it in the manual.").c_str(), 
                  command.c_str(), wxOK|wxICON_INFORMATION);
}

void FFrame::OnDLoad (wxCommandEvent& WXUNUSED(event))
{
    static wxString dir = ".";
    wxFileDialog fdlg (frame, "Load data from a file", dir, "",
                              "x y files (*.dat, *.xy, *.fio)"
                                          "|*.dat;*.DAT;*.xy;*.XY;*.fio;*.FIO" 
                              "|rit files (*.rit)|*.rit;*.RIT"
                              "|cpi files (*.cpi)|*.cpi;*.CPI"
                              "|mca files (*.mca)|*.mca;*.MCA"
                              "|Siemens/Bruker (*.raw)|*.raw;*.RAW"
                              "|all files (*)|*",
                              wxOPEN | wxFILE_MUST_EXIST | wxMULTIPLE);
    if (fdlg.ShowModal() == wxID_OK) {
        wxArrayString paths;
        fdlg.GetPaths(paths);
        int count = paths.GetCount();
        wxString cmd;
        for (int i = 0; i < count; ++i) {
            if (i > 0)
                cmd += " ; d.activate ::* ; "; 
            cmd += "d.load '" + paths[i] + "'";
            add_recent_data_file(paths[i]);
        }
        exec_command (cmd.c_str());
        if (count > 1)
            SwitchDPane(true);
    }
    dir = fdlg.GetDirectory();
}

void FFrame::OnDXLoad (wxCommandEvent& WXUNUSED(event))
{
    if (!dxload_dialog)
        dxload_dialog = new FDXLoadDlg(this, -1);

    string fname = my_data->get_filename();
    if (fname.empty()) {
        dxload_dialog->OnChangeButton(dummy_cmd_event);
        if (dxload_dialog->filename.empty())
            return;
    }
    else
        dxload_dialog->set_filename(fname);

    if (dxload_dialog->ShowModal() == wxID_OK) {
        exec_command (dxload_dialog->get_command());
        add_recent_data_file(dxload_dialog->filename.c_str());
    }
}

void FFrame::OnDRecent (wxCommandEvent& event)
{
    wxString s = GetMenuBar()->GetHelpString(event.GetId());
    exec_command (("d.load '" + s + "'").c_str());
    add_recent_data_file(s);
}

void FFrame::OnDEditor (wxCommandEvent& WXUNUSED(event))
{
    if (!data_editor) {
        data_editor = new DataEditorDlg(this, -1, my_data);
        data_editor->Show();
    }
    else {
        data_editor->update_data(my_data);
    }
}

void FFrame::OnDInfo (wxCommandEvent& WXUNUSED(event))
{
    exec_command ("d.info");
}

void FFrame::OnDDeviation  (wxCommandEvent& WXUNUSED(event))
{
    FDStdDevDlg *dialog = new FDStdDevDlg(this, -1);
    if (dialog->ShowModal() == wxID_OK) {
        exec_command (dialog->get_command());
    }
    dialog->Destroy();
}

void FFrame::OnDRange (wxCommandEvent& WXUNUSED(event))
{
    FDRangeDlg *dialog = new FDRangeDlg(this, -1);
    dialog->ShowModal();
    dialog->Destroy();
}

void FFrame::OnDBInfo (wxCommandEvent& WXUNUSED(event))
{
    exec_command(S("d.background")); 
}

void FFrame::OnDBClear (wxCommandEvent& WXUNUSED(event))
{
    exec_command(S("d.background !")); 
}

void FFrame::OnDCalibrate (wxCommandEvent& WXUNUSED(event))
{
    wxMessageBox (("This menu item is only reminding about command d.calibarate"
                   ".\n If you don't know how to use this command,\n"
                   " look for it in the manual.\n"
                   "By the way, is anyone using command d.calibrate?"),
                  "d.calibrate", wxOK|wxICON_INFORMATION);
}

void FFrame::OnDExport (wxCommandEvent& WXUNUSED(event))
{
    static int filter_idx = 0;
    static wxString dir = ".";
    wxFileDialog fdlg (frame, "Export data to file", dir, "",
                       "x y data (*.dat)|*.dat;*.DAT"
                       "|fityk file (*.fit)|*.fit;*.FIT",
                       wxSAVE | wxOVERWRITE_PROMPT);
    fdlg.SetFilterIndex(filter_idx);
    if (fdlg.ShowModal() == wxID_OK) 
        exec_command (("d.export '" + fdlg.GetPath() + "'").c_str());
    filter_idx = fdlg.GetFilterIndex();
    dir = fdlg.GetDirectory();
}

void FFrame::OnDSet (wxCommandEvent& WXUNUSED(event))
{
    OnXSet ("Data", 'd');
}

void FFrame::OnSHistory      (wxCommandEvent& WXUNUSED(event))
{
    if (my_sum->pars()->count_a() == 0) {
        wxMessageBox ("no parameters -- no history", "no history",
                      wxOK|wxICON_ERROR);
        return;
    }
    SumHistoryDlg *dialog = new SumHistoryDlg (this, -1);
    dialog->ShowModal();
    dialog->Destroy();
}
            
void FFrame::OnSAdd          (wxCommandEvent& WXUNUSED(event))
{
    FuncBrowserDlg *dialog = new FuncBrowserDlg(this, -1, 1);
    dialog->ShowModal();
    dialog->Destroy();
}
        
void FFrame::OnSInfo         (wxCommandEvent& WXUNUSED(event))
{
    FuncBrowserDlg *dialog = new FuncBrowserDlg(this, -1, 0);
    dialog->ShowModal();
    dialog->Destroy();
}
         
void FFrame::OnSRemove       (wxCommandEvent& WXUNUSED(event))
{
    FuncBrowserDlg *dialog = new FuncBrowserDlg(this, -1, 3);
    dialog->ShowModal();
    dialog->Destroy();
}
           
void FFrame::OnSChange       (wxCommandEvent& WXUNUSED(event))
{
    FuncBrowserDlg *dialog = new FuncBrowserDlg(this, -1, 2);
    dialog->ShowModal();
    dialog->Destroy();
}
           
void FFrame::OnSValue        (wxCommandEvent& WXUNUSED(event))
{
    FuncBrowserDlg *dialog = new FuncBrowserDlg(this, -1, 4);
    dialog->ShowModal();
    dialog->Destroy();
}
          
void FFrame::OnSExport       (wxCommandEvent& WXUNUSED(event))
{
    static int filter_idx = 0;
    static wxString dir = ".";
    wxString name = wxFileName(my_data->get_filename().c_str()).GetName();
    wxFileDialog fdlg (frame, "Export curve to file", dir, name,
                       "parameters of peaks (*.peaks)|*.peaks"
                       "|x y data (*.dat)|*.dat;*.DAT"
                       "|XFIT peak listing (*xfit.txt)|*xfit.txt;*XFIT.TXT" 
                       "|mathematic formula (*.formula)|*.formula"
                       "|fityk file (*.fit)|*.fit;*.FIT",
                       wxSAVE | wxOVERWRITE_PROMPT);
    fdlg.SetFilterIndex(filter_idx);
    if (fdlg.ShowModal() == wxID_OK) 
        exec_command (("s.export '" + fdlg.GetPath() + "'").c_str());
    filter_idx = fdlg.GetFilterIndex();
    dir = fdlg.GetDirectory();
}
           
void FFrame::OnSSet          (wxCommandEvent& WXUNUSED(event))
{
    OnXSet ("Sum", 's');
}
        
void FFrame::OnMFindpeak     (wxCommandEvent& WXUNUSED(event))
{
    exec_command ("m.findpeak ");
}
        
void FFrame::OnMSet          (wxCommandEvent& WXUNUSED(event))
{
    OnXSet ("Manipulations", 'm');
}
        

void FFrame::OnFMethodUpdate (wxUpdateUIEvent& event)
{
    int method_nr = fitMethodsContainer->current_method_number();
    GetMenuBar()->Check (ID_F_M + method_nr, true);
    event.Skip();
}

void FFrame::OnFOneOfMethods (wxCommandEvent& event)
{
    int m = event.GetId() - ID_F_M;
    exec_command ("f.method " + S(fitMethodsContainer->symbol(m)));
}
           
void FFrame::OnFRun          (wxCommandEvent& WXUNUSED(event))
{
    int r = wxGetNumberFromUser ("Run fitting method", 
                                 "Max. number of iterations", "Fit->Run", 
                                 my_fit->default_max_iterations, 0, 9999);
    if (r != -1)
        exec_command (("f.run " + S(r)).c_str());
}
        
void FFrame::OnFContinue     (wxCommandEvent& WXUNUSED(event))
{
    int r = wxGetNumberFromUser ("Continue previous fitting", 
                                 "Max. number of iterations", "Fit->Continue", 
                                 my_fit->default_max_iterations, 0, 9999);
    if (r != -1)
        exec_command (("f.continue " + S(r)).c_str());
}
             
void FFrame::OnFInfo         (wxCommandEvent& WXUNUSED(event))
{
    exec_command ("f.info");
}
         
void FFrame::OnFSet          (wxCommandEvent& WXUNUSED(event))
{
    OnXSet ("Fit (" + my_fit->method + ")", 'f');
}
        

void FFrame::OnCWavelength   (wxCommandEvent& WXUNUSED(event))
{
    not_implemented_menu_item ("c.wavelength");
}
               
void FFrame::OnCAdd          (wxCommandEvent& WXUNUSED(event))
{
    not_implemented_menu_item ("c.add");
}
        
void FFrame::OnCInfo         (wxCommandEvent& WXUNUSED(event))
{
    not_implemented_menu_item ("c.info");
}
         
void FFrame::OnCRemove       (wxCommandEvent& WXUNUSED(event))
{
    not_implemented_menu_item ("c.remove");
}
           
void FFrame::OnCEstimate     (wxCommandEvent& WXUNUSED(event))
{
    not_implemented_menu_item ("c.estimate");
}
             
void FFrame::OnCSet          (wxCommandEvent& WXUNUSED(event))
{
    OnXSet ("Crystalography", 'c');
}
        

void FFrame::OnOLog          (wxCommandEvent& WXUNUSED(event))
{
    wxFileDialog fdlg (frame, "Log to file", "", "",
                       "Log input to file (*.fit)|*.fit;*.FIT"
                       "|Log output to file (*.fit)|*.fit;*.FIT"
                       "|Log input & output (*.fit)|*.fit;*.FIT"
                       "|Stop logging to file |none.none",
                       wxSAVE);
    char m = getUI()->getLogMode();
    if (m == 'i')
        fdlg.SetFilterIndex(0);
    else if (m == 'o')
        fdlg.SetFilterIndex(1);
    else if (m == 'a')
        fdlg.SetFilterIndex(2);
    else if (m == 'n')
        fdlg.SetFilterIndex(3);
    else 
        assert (0);
    if (m != 'n')
        fdlg.SetPath(getUI()->getLogFilename().c_str());
    if (fdlg.ShowModal() == wxID_OK) {
        int mode = fdlg.GetFilterIndex();
        char *modes = "ioan";
        assert(mode >= 0 && mode < 4);
        if (mode < 3)
            exec_command ("o.log " + S(modes[mode]) 
                                    + " '" + fdlg.GetPath().c_str() + "'");
        else
            exec_command ("o.log !"); 
    }
}

void FFrame::OnO_Reset   (wxCommandEvent& WXUNUSED(event))
{
    int r = wxMessageBox ("Do you really want to reset current session \n"
                          "and lose everything you have done in this session?", 
                          "Are you sure?", 
                          wxYES_NO | wxCANCEL | wxCENTRE | wxICON_QUESTION);
    if (r == wxYES)
        exec_command ("o.include !");
}
        
void FFrame::OnOInclude      (wxCommandEvent& WXUNUSED(event))
{
    static wxString dir = ".";
    wxFileDialog fdlg (frame, "Execute commands from file", dir, "",
                              "fityk file (*.fit)|*.fit;*.FIT|all files|*",
                              wxOPEN | wxFILE_MUST_EXIST);
    if (fdlg.ShowModal() == wxID_OK) {
        exec_command (("o.include '" + fdlg.GetPath() + "'").c_str());
        last_include_path = fdlg.GetPath().c_str();
        GetMenuBar()->Enable(ID_O_REINCLUDE, true);
    }
    dir = fdlg.GetDirectory();
}
            
void FFrame::OnOReInclude    (wxCommandEvent& WXUNUSED(event))
{
    exec_command ("o.include ! '" + last_include_path + "'");
}
            
void FFrame::OnOWait         (wxCommandEvent& WXUNUSED(event))
{
    int r = wxGetNumberFromUser ("Note: Wait command has a sense only "
            "in script", "Number of seconds to wait", "", 5, 0, 60);
    if (r != -1)
        exec_command (("o.wait " + S(r)).c_str());
}
         
void FFrame::OnODump         (wxCommandEvent& WXUNUSED(event))
{
    wxFileDialog fdlg (frame, "Dump current program state to file as script", 
                                "", "", "fityk file (*.fit)|*.fit;*.FIT",
                       wxSAVE | wxOVERWRITE_PROMPT);
    if (fdlg.ShowModal() == wxID_OK) 
        exec_command (("o.dump '" + fdlg.GetPath() + "'").c_str());
}
         
void FFrame::OnOSet          (wxCommandEvent& WXUNUSED(event))
{
    OnXSet ("Other", 'o');
}
        
void FFrame::OnXSet (string name, char letter)
{
    DotSet* myset = set_class_p (letter);
    vector<string> ev, vv, tv;
    myset->expanp ("", ev);
    for (vector<string>::iterator i = ev.begin(); i != ev.end(); i++) {
        string v;
        myset->getp_core (*i, v);
        vv.push_back (v);
        string t;
        myset->typep (*i, t);
        tv.push_back (t);
    }
    string nm =  "Preferences - " + name;
    FSetDlg *dialog = new FSetDlg(this, -1, nm.c_str(), ev, vv, tv, myset);
    if (dialog->ShowModal() == wxID_OK) {
        for (unsigned int i = 0; i < ev.size(); i++) {
            string s;
            wxTextCtrl *tctrl = wxDynamicCast (dialog->tc_v[i], wxTextCtrl);
            wxCheckBox *chbox = wxDynamicCast (dialog->tc_v[i], wxCheckBox);
            wxChoice *chic = wxDynamicCast (dialog->tc_v[i], wxChoice);
            wxSpinCtrl *spinc = wxDynamicCast (dialog->tc_v[i], wxSpinCtrl);
            if (tctrl)
                s = tctrl->GetValue().Trim(true).Trim(false) .c_str();
            else if (chbox)
                s = S(chbox->GetValue());
            else if (chic)
                s = chic->GetStringSelection().c_str();
            else if (spinc)
                s = S(spinc->GetValue());
            else
                assert (0);
            if (s != vv[i]) {
                string cm = S(letter) + ".set " + ev[i] + " = " + s;
                exec_command (cm.c_str());
            }
        }
    }
    dialog->Destroy();
}

void FFrame::OnChangeMouseMode (wxCommandEvent& event)
{
    Mouse_mode_enum mode = mmd_zoom;
    switch (event.GetId()) {
        case ID_G_M_ZOOM:   
        case ID_ft_m_zoom:   
            mode = mmd_zoom;   
            GetMenuBar()->Check(ID_G_M_ZOOM, true);
            if (toolbar) toolbar->ToggleTool(ID_ft_m_zoom, true);
            break;
        case ID_G_M_RANGE:   
        case ID_ft_m_range:  
            mode = mmd_range;  
            GetMenuBar()->Check(ID_G_M_RANGE, true);
            if (toolbar) toolbar->ToggleTool(ID_ft_m_range, true);
            break;
        case ID_G_M_BG:   
        case ID_ft_m_bg:     
            mode = mmd_bg;     
            GetMenuBar()->Check(ID_G_M_BG, true);
            if (toolbar) toolbar->ToggleTool(ID_ft_m_bg, true);
            break;
        case ID_G_M_ADD:   
        case ID_ft_m_add:    
            mode = mmd_add;    
            GetMenuBar()->Check(ID_G_M_ADD, true);
            if (toolbar) toolbar->ToggleTool(ID_ft_m_add, true);
            break;  
        default: assert(0);
    }
    if (mode==mmd_bg && toolbar && toolbar->GetToolState(ID_ft_b_with)==false) {
        toolbar->ToggleTool(ID_ft_b_with, true);
        exec_command ("o.plot +");
    }
    plot_pane->set_mouse_mode(mode);
}

void FFrame::OnModePeak(wxUpdateUIEvent& event)
{
    GetMenuBar()->Check(ID_G_M_PEAK_N + peak_type_nr, true);
    event.Skip();
}

void FFrame::OnChangePeakType(wxCommandEvent& event)
{
    peak_type_nr = event.GetId() - ID_G_M_PEAK_N;
    if (toolbar) toolbar->update_peak_type();
}

void FFrame::SwitchToolbar(bool show)
{
    if (show && !GetToolBar()) {
        toolbar = new FToolBar(this, -1);
        SetToolBar(toolbar);
    }
    else if (!show && GetToolBar()){
        SetToolBar(0);
        delete toolbar; 
        toolbar = 0;
    }
    GetMenuBar()->Check(ID_G_S_TOOLBAR, show);
}

void FFrame::SwitchStatbar (bool show)
{
    if (show && !GetStatusBar()) {
        status_bar = new FStatusBar(this);
        SetStatusBar(status_bar);
        plot_pane->update_mouse_hints();
    }
    else if (!show && GetStatusBar()) {
        SetStatusBar(0);
        delete status_bar; 
        status_bar = 0;
    }
    GetMenuBar()->Check(ID_G_S_STATBAR, show);
}

void FFrame::SwitchDPane(bool show)
{
    //v_splitter->IsSplit() means data_pane is visible 
    if (show && !v_splitter->IsSplit()) {
        data_pane->Show(true);
        v_splitter->SplitVertically(main_pane, data_pane);
    }
    else if (!show && v_splitter->IsSplit()) {
        v_splitter->Unsplit();
    }
    GetMenuBar()->Check(ID_G_S_DPANE, show);
    if (toolbar) 
        toolbar->ToggleTool(ID_ft_dpane, show);
}

void FFrame::OnSwitchAuxPlot(wxCommandEvent& ev) 
{
    plot_pane->show_aux(ev.GetId() - ID_G_S_A1, ev.IsChecked());
}

void FFrame::SwitchIOPane (bool show)
{
    //main_pane->IsSplit() means io_pane is visible 
    if (show && !main_pane->IsSplit()) {
        io_pane->Show(true);
        main_pane->SplitHorizontally(plot_pane, io_pane);
    }
    else if (!show && main_pane->IsSplit()) {
        main_pane->Unsplit();
    }
    GetMenuBar()->Check(ID_G_S_IO, show);
    //if (toolbar) toolbar->ToggleTool(ID_ft_..., show);
}

void FFrame::SwitchCrosshair (bool show)
{
    plot_pane->crosshair_cursor = show;
    GetMenuBar()->Check(ID_G_CROSSHAIR, show);
}

void FFrame::OnGuiShowUpdate (wxUpdateUIEvent& event)
{
    for (int i = 0; i < 2; i++) 
        if (GetMenuBar()->IsChecked(ID_G_S_A1+i) != plot_pane->aux_visible(i))
            GetMenuBar()->Check(ID_G_S_A1+i, plot_pane->aux_visible(i));
    event.Skip();
}

void FFrame::OnGViewAll (wxCommandEvent& WXUNUSED(event))
{
    change_zoom("[]");
}

void FFrame::OnGFitHeight (wxCommandEvent& WXUNUSED(event))
{
    change_zoom(". []");
}

void FFrame::OnGScrollLeft (wxCommandEvent & WXUNUSED(event))
{
    scroll_view_horizontally(-0.5);
}

void FFrame::OnGScrollRight (wxCommandEvent & WXUNUSED(event))
{
    scroll_view_horizontally(+0.5);
}


void FFrame::OnPreviousZoom(wxCommandEvent& event)
{
    int id = event.GetId();
    string s = plot_pane->zoom_backward(id ? id - ID_G_V_ZOOM_PREV : 1);
    if (s.size()) 
        exec_command("o.plot " + s);
}

void FFrame::change_zoom(const string& s)
{
    plot_pane->zoom_forward();
    string cmd = "o.plot " + s;
    exec_command(cmd);
}

void FFrame::scroll_view_horizontally(fp step)
{
    const Rect &vw = my_core->view;
    fp diff = vw.width() * step;
    fp new_left = vw.left + diff; 
    fp new_right = vw.right + diff;
    change_zoom("[" + S(new_left) + " : " + S(new_right) + "] .");
}


void FFrame::OnConfigSave (wxCommandEvent& event)
{
    wxString name = (event.GetId() == ID_G_SCONF1 ?  wxGetApp().conf_filename 
                                               : wxGetApp().alt_conf_filename);
    wxConfigBase *config =  new wxConfig("", "", name, "", 
                                         wxCONFIG_USE_LOCAL_FILE);
    save_all_settings(config);
    delete config;
}

void FFrame::OnConfigRead (wxCommandEvent& event)
{
    wxString name = (event.GetId() == ID_G_LCONF1 ? wxGetApp().conf_filename 
                                               : wxGetApp().alt_conf_filename);
    wxConfigBase *config = new wxConfig("", "", name, "", 
                                        wxCONFIG_USE_LOCAL_FILE);
    read_all_settings(config);
    delete config;
}

void FFrame::OnConfigBuiltin (wxCommandEvent& WXUNUSED(event))
{
    wxString name = wxString(config_dirname) + wxFILE_SEP_PATH+"builtin-config";
    wxConfigBase *config = new wxConfig("", "", name, "", 
                                        wxCONFIG_USE_LOCAL_FILE);
    if (config->GetNumberOfEntries(true))
        config->DeleteAll();
    read_all_settings(config);
    delete config;
}


class FPreviewFrame : public wxPreviewFrame
{
public:
    FPreviewFrame(wxPrintPreview* preview, wxFrame* parent) 
        : wxPreviewFrame (preview, parent, "Print Preview", 
                          wxDefaultPosition, wxSize(600, 550)) {}
    void CreateControlBar() { 
        m_controlBar = new wxPreviewControlBar(m_printPreview, 
                                        wxPREVIEW_PRINT|wxPREVIEW_ZOOM, this);
        m_controlBar->CreateButtons();
        m_controlBar->SetZoomControl(110);
    }
};

void FFrame::OnPrintPreview(wxCommandEvent& WXUNUSED(event))
{
    // Pass two printout objects: for preview, and possible printing.
    wxPrintDialogData print_dialog_data (*print_data);
    wxPrintPreview *preview = new wxPrintPreview (new FPrintout(plot_pane),
                                                  new FPrintout(plot_pane), 
                                                  &print_dialog_data);
    if (!preview->Ok()) {
        delete preview;
        wxMessageBox ("There was a problem previewing.\nPerhaps your current "
                      "printer is not set correctly?", "Previewing", wxOK);
        return;
    }
    FPreviewFrame *frame = new FPreviewFrame (preview, this);
    frame->Centre(wxBOTH);
    frame->Initialize();
    frame->Show(true);
}

void FFrame::OnPrintSetup(wxCommandEvent& WXUNUSED(event))
{
    (*page_setup_data) = *print_data;

    wxPageSetupDialog page_setup_dialog(this, page_setup_data);
    page_setup_dialog.ShowModal();

    (*print_data) = page_setup_dialog.GetPageSetupData().GetPrintData();
    (*page_setup_data) = page_setup_dialog.GetPageSetupData();

}

void FFrame::OnPrint(wxCommandEvent& WXUNUSED(event))
{
    if (plot_pane->is_background_white())
        if (wxMessageBox ("Plots will be printed on white background, \n"
                            "to save ink/toner.\n"
                            "Now background of your plot on screen\n"
                            "is not white, so visiblity of lines and points\n"
                            "can be different.\n Do you want to continue?",
                          "Are you sure?", 
                          wxYES_NO|wxCANCEL|wxICON_QUESTION) 
                != wxYES)
            return;
    wxPrintDialogData print_dialog_data (*print_data);
    wxPrinter printer (&print_dialog_data);
    FPrintout printout(plot_pane);
    bool r = printer.Print(this, &printout, true);
    if (r) 
        (*print_data) = printer.GetPrintDialogData().GetPrintData();
    else if (wxPrinter::GetLastError() == wxPRINTER_ERROR)
        wxMessageBox("There was a problem printing.\nPerhaps your current "
                     "printer is not set correctly?", "Printing", wxOK);
}

const f_names_type& FFrame::get_peak_type() const
{
    return V_f::f_names[peak_type_nr];
}

void FFrame::set_status_hint(const char *left, const char *right)
{
    if (status_bar)
        status_bar->set_hint(left, right);  
}

void FFrame::output_text(OutputStyle style, const string& str)
{
    io_pane->append_text(style, str.c_str());
}

void FFrame::refresh_plots(bool refresh, bool update)
{
    plot_pane->refresh_plots(refresh, update);
}

void FFrame::draw_crosshair(int X, int Y)
{
    plot_pane->draw_crosshair(X, Y);
}

void FFrame::focus_input()
{
    io_pane->focus_input();
}

void FFrame::OnIdle(wxIdleEvent &event) 
{
    if (GetToolBar())
        toolbar->OnIdle(event);
    event.Skip();
}


//=======================================================================

void add_peak(fp height, fp ctr, fp hwhm) 
{
    const f_names_type &f = frame->get_peak_type();

    //TODO? function add_peak(f_names_type, map<string,fp>) 
    my_sum->use_param_a_for_value();
    fp center = ctr + my_sum->zero_shift(ctr);
    string cmd = "s.add ^" + S(f.type);
    vector<fp> ini 
          = V_f::get_default_peak_parameters(f, vector3(height, center, hwhm));
    for (int i = 0; i < f.psize; i++) {
        cmd += " ~" + S(ini[i]);
        const ParDefault &pd = f.pdefaults[i];
        if (pd.lower_set || pd.upper_set)  {
            cmd += " [" + (pd.lower_set ? S(pd.lower) : S()) + ":" 
                   + (pd.upper_set ? S(pd.upper) : S()) + "]";
        }
    }
    string stat = "Height: " + S(height) + " Ctr: " + S(center) 
                   + " HWHM: " + S(hwhm);
//return cmd, stat
    frame->set_status_text(stat.c_str());
    exec_command (cmd);
}


void add_peak_in_range(fp xmin, fp xmax) 
{
    fp center, height, fwhm;
    my_sum->use_param_a_for_value();
    bool r = my_manipul->estimate_peak_parameters ((xmax + xmin)/2, 
                                                   fabs(xmax - xmin)/2, 
                                                   &center, &height, 0, &fwhm);
    if (r) add_peak (height, center, fwhm/2);
}



//=====================    set  dialog    ==================

FSetDlg::FSetDlg(wxWindow* parent, const wxWindowID id, const wxString& title,
             vector<string>& names, vector<string>& vals, vector<string>& types,
             DotSet* myset)
    :  wxDialog(parent, id, title), opt_names(names), opt_values(vals)
{
    const int max_rows = 10;
    assert (names.size() == vals.size());
    wxBoxSizer *sizer0 = new wxBoxSizer (wxVERTICAL);
    wxStaticText* st = new wxStaticText (this, -1, title);
    sizer0->Add (st, 0, wxALL|wxALIGN_CENTER, 10);
    wxBoxSizer *sizer_H0 = new wxBoxSizer (wxHORIZONTAL);
    sizer0->Add (sizer_H0, 0, wxALL|wxALIGN_CENTER, 0);
    wxBoxSizer *sizer_V0 = 0;
    for (unsigned int i = 0; i < names.size(); i++) { 
        if (i % max_rows == 0) {
            sizer_V0 = new wxBoxSizer (wxVERTICAL);
            sizer_H0->Add (sizer_V0, 0, wxALL|wxALIGN_CENTER, 10);
        }
        wxBoxSizer *sizerH = new wxBoxSizer (wxHORIZONTAL);
        wxControl* tc;
        bool put_static_text = true;
        bool with_tooltip = false;

        if (types[i].find("bool") != string::npos) {//boolean type
            wxCheckBox* tc_ = new wxCheckBox (this, -1, names[i].c_str());
            tc_->SetValue (vals[i] != "0");
            tc = tc_;
            put_static_text = false;
        }
            //enumaration of strings
        else if (types[i].find("enum") != string::npos) {
            vector<string> std_choices;
            myset->expand_enum (names[i], "", std_choices);
            const int max_choice_items = 20;//it should be enough
            assert (size(std_choices) < max_choice_items);
            wxString wx_choice[max_choice_items]; 
            for (unsigned int j = 0; j < std_choices.size(); j++)
                wx_choice[j] = std_choices[j].c_str();
            wxChoice *tc_ = new wxChoice (this, -1, wxDefaultPosition, 
                                          wxDefaultSize,  
                                          std_choices.size(), wx_choice);
            tc_->SetStringSelection (vals[i].c_str());
            tc = tc_;
        }
        else if (types[i].find("integer") != string::npos) {//integer
            tc = new wxSpinCtrl(this, -1, vals[i].c_str(),
                                wxDefaultPosition, wxSize(50, -1), 
                                wxSP_ARROW_KEYS,
                                0, 999999999);
            with_tooltip = true;
        }
        else if (types[i].find("...,") != string::npos) { //integer range
            const string &t = types[i];
            string lower(t.begin(), t.begin() + t.find_first_of(','));
            string upper(t.begin() + t.find_last_of(',') + 1, t.end());
            tc = new wxSpinCtrl(this, -1, vals[i].c_str(),
                                wxDefaultPosition, wxSize(50, -1), 
                                wxSP_ARROW_KEYS,
                                atoi(lower.c_str()), atoi(upper.c_str()));
            with_tooltip = true;
        }
        else { //another type
            tc = new wxTextCtrl (this, -1, vals[i].c_str(), 
                                 wxDefaultPosition, wxSize(50, -1));
            with_tooltip = true;
        }

#if wxUSE_TOOLTIPS
        if (with_tooltip)
            tc->SetToolTip (types[i].c_str()); 
#endif
        if (put_static_text) {
            wxStaticText* st = new wxStaticText (this, -1, names[i].c_str());
            sizerH->Add (st, 0, wxALL|wxALIGN_LEFT, 5);
        }
        sizerH->Add (tc, 0, wxALL|wxALIGN_LEFT, 0);
        tc_v.push_back(tc);
        sizer_V0->Add (sizerH, 0, wxALL|wxALIGN_LEFT, 5);
    }
    sizer0->Add (new wxStaticLine(this, -1), 0, wxEXPAND|wxLEFT|wxRIGHT, 5);
    wxBoxSizer *sizerH = new wxBoxSizer (wxHORIZONTAL);
    wxButton *btOk = new wxButton (this, wxID_OK, "OK");
    sizerH->Add (btOk, 0, wxALL|wxALIGN_CENTER, 5 );
    wxButton *btCancel = new wxButton (this, wxID_CANCEL, "Cancel");
    sizerH->Add (btCancel, 0, wxALL|wxALIGN_CENTER, 5 );
    sizer0->Add (sizerH, 0, wxALL|wxALIGN_CENTER, 5);
    SetAutoLayout (true);
    SetSizer (sizer0);
    sizer0->Fit (this);
    sizer0->SetSizeHints (this);
}

//===============================================================
//                    FToolBar 
//===============================================================

BEGIN_EVENT_TABLE (FToolBar, wxToolBar)
//  EVT_IDLE (FToolBar::OnIdle)  //it doesn't work (why??); 
//                     //FToolBar::OnIdle is now called from FFrame::OnIdle
    EVT_TOOL_RANGE (ID_ft_m_zoom, ID_ft_m_add,  FToolBar::OnChangeMouseMode)
    EVT_TOOL_RANGE (ID_ft_v_pr, ID_ft_s_aa,        FToolBar::OnClickTool)
    EVT_TOOL (ID_ft_dpane, FToolBar::OnSwitchDPane)
    EVT_CHOICE (ID_ft_peakchoice, FToolBar::OnPeakChoice)
END_EVENT_TABLE()

FToolBar::FToolBar (wxFrame *parent, wxWindowID id)
        : wxToolBar (parent, id, wxDefaultPosition, wxDefaultSize,
                     wxNO_BORDER | /*wxTB_FLAT |*/ wxTB_DOCKABLE) 
{
    // mode
    Mouse_mode_enum m = frame ? frame->plot_pane->get_plot()->get_mouse_mode() 
                              : mmd_zoom;
    AddRadioTool(ID_ft_m_zoom, "Zoom", wxBitmap(zoom_t_xpm), wxNullBitmap, 
                 "Normal Mode", "Use mouse for zooming, moving peaks etc."); 
    ToggleTool(ID_ft_m_zoom, m == mmd_zoom);
    AddRadioTool(ID_ft_m_range, "Range", wxBitmap(range_t_xpm), wxNullBitmap, 
         "Data-Range Mode", "Use mouse for activating and disactivating data"); 
    ToggleTool(ID_ft_m_range, m == mmd_range);
    AddRadioTool(ID_ft_m_bg, "Background", wxBitmap(baseline_t_xpm), 
                                                                 wxNullBitmap, 
                 "Baseline Mode", "Use mouse for substracting background"); 
    ToggleTool(ID_ft_m_bg, m == mmd_bg);
    AddRadioTool(ID_ft_m_add, "Add peak", wxBitmap(addpeak_t_xpm), wxNullBitmap,
                 "Add-Peak Mode", "Use mouse for adding new peaks"); 
    ToggleTool(ID_ft_m_add, m == mmd_add);
    AddSeparator();
    // view
    AddTool (ID_G_V_ALL, "Whole", wxBitmap(whole_xpm), wxNullBitmap, 
             wxITEM_NORMAL, "View whole", 
             "Fit data in window");
    AddTool (ID_G_V_VERT, "Fit height", wxBitmap(vertic_xpm), wxNullBitmap,
            wxITEM_NORMAL, "Fit vertically",
            "Set optimal y scale"); 
    AddTool(ID_G_V_SCROLL_L,"<-- scroll",wxBitmap(leftscroll_xpm), wxNullBitmap,
            wxITEM_NORMAL, "Scroll left", "Scroll view left"); 
    AddTool(ID_G_V_SCROLL_R,"scroll -->",wxBitmap(rightscroll_xpm),wxNullBitmap,
            wxITEM_NORMAL, "Scroll right", "Scroll view right"); 
    AddTool (ID_ft_v_pr, "Back", wxBitmap(backv_xpm), wxNullBitmap, 
             wxITEM_NORMAL, "Previous view", 
             "Go to previous View");
    AddSeparator();
    //file
    AddTool (ID_O_INCLUDE, "Execute", wxBitmap(execute_xpm), wxNullBitmap,  
             wxITEM_NORMAL, "Execute script",
             "Execute (include) script from file");
    AddTool (ID_O_LOG, "Log", wxBitmap(log_xpm), wxNullBitmap,  
             wxITEM_NORMAL, "Start/Stop logging",
             "Start/Stop logging commands to file");
    AddTool (ID_O_RESET, "Reset", wxBitmap(reset_xpm), wxNullBitmap,  
             wxITEM_NORMAL, "Reset current session",
             "Reset current session");
    AddTool (ID_O_DUMP, "Dump", wxBitmap(dump_xpm), wxNullBitmap,  
             wxITEM_NORMAL, "Dump session to file",
             "Dump current session to file");
    AddSeparator();
    //data
    AddTool (ID_D_LOAD, "Load", wxBitmap(openfile_xpm), wxNullBitmap,  
             wxITEM_NORMAL, "Load file",
             "Load data from file");
    AddSeparator();
    //background
    AddTool (ID_ft_b_with, "With Bg", wxBitmap(plusbg_xpm), wxNullBitmap,  
             wxITEM_CHECK, "Plot with/without background",
             "Draw plot with added (or not) baseline");
    ToggleTool (ID_ft_b_with, my_core->plus_background);
    AddTool (ID_D_B_CLEAR, "Clear Bg", wxBitmap(clear_xpm), wxNullBitmap, 
             wxITEM_NORMAL, "Clear background", 
             "Delete all baseline points");
    AddSeparator();
    //sum
    AddTool (ID_S_INFO, "Tree", wxBitmap(tree_xpm), wxNullBitmap,
             wxITEM_NORMAL, "Show tree", "Show tree of functions");
    AddSeparator();
    peak_choice = new wxChoice(this, ID_ft_peakchoice); 
    vector<const z_names_type*> all_t = V_fzg::all_types(fType);
    for (vector<const z_names_type*>::const_iterator i = all_t.begin();
                                                         i != all_t.end(); i++)
        peak_choice->Append ((*i)->name.c_str());
    update_peak_type();
    AddControl (peak_choice);
    AddTool (ID_ft_s_aa, "add", wxBitmap(autoadd_xpm), wxNullBitmap, 
             wxITEM_NORMAL, "auto-add", "Add peak automatically");
    AddSeparator();
    //fit
    AddTool (ID_ft_f_run, "Run", wxBitmap(fitrun_xpm), wxNullBitmap,
             wxITEM_NORMAL, "Start fitting", "Start fitting sum to data");
    AddTool (ID_ft_f_cont, "Continue", wxBitmap(fitcont_xpm), wxNullBitmap,
             wxITEM_NORMAL, "Continue fitting", "Continue fitting sum to data");
    AddTool (ID_ft_f_undo, "Continue", wxBitmap(fitundo_xpm), wxNullBitmap,
             wxITEM_NORMAL, "Undo fitting", "Previous set of parameters");
    AddSeparator();
    //help
    AddTool (ID_H_MANUAL, "Help", wxBitmap(manual_xpm), wxNullBitmap,
             wxITEM_NORMAL, "Manual", "Open user manual");
    AddSeparator();
    AddTool (ID_ft_dpane, "Datasets", wxBitmap(dpane_xpm), wxNullBitmap,
             wxITEM_CHECK, "Datasets Pane", "Show/hide datasets pane");

    Realize();
}

void FToolBar::OnIdle(wxIdleEvent &event)
{
    if (GetToolState(ID_ft_b_with) != my_core->plus_background) 
        ToggleTool(ID_ft_b_with, my_core->plus_background);
    event.Skip();
}

void FToolBar::OnPeakChoice(wxCommandEvent &event) 
{
    if (frame) frame->peak_type_nr = event.GetSelection();
}

void FToolBar::update_peak_type() 
{ 
    peak_choice->SetSelection(frame ? frame->peak_type_nr : 0); 
}

//FIXME move these small functions to header file?
void FToolBar::OnChangeMouseMode (wxCommandEvent& event)
{
    frame->OnChangeMouseMode(event);
}

void FToolBar::OnSwitchDPane (wxCommandEvent& event)
{
    frame->OnSwitchDPane(event);
}

void FToolBar::OnClickTool (wxCommandEvent& event)
{
    switch (event.GetId()) {
        case ID_ft_v_pr:  
            frame->OnPreviousZoom(dummy_cmd_event);
            break;
        case ID_ft_b_with: 
            exec_command(S("o.plot ") + (event.IsChecked() ? "+" : "-")); 
            break; 
        case ID_ft_f_run : 
            exec_command("f.run"); 
            break; 
        case ID_ft_f_cont: 
            exec_command("f.continue"); 
            break; 
        case ID_ft_f_undo: 
            exec_command("s.history -1"); 
            break; 
        case ID_ft_s_aa: 
        {
            fp c, h, f;
            bool r = my_manipul->estimate_peak_parameters(0.,+INF,&c,&h,0,&f);
            if (r) 
                add_peak(h, c, f/2);
            break; 
        }
        default: assert(0);
    }
}


#ifndef HELP_DIR
#    define HELP_DIR "."
#endif

string get_full_path_of_help_file (const string &name)
{
    // filename --> path and filename
    // if there is no `name' file in HELP_DIR, we are trying a few other dirs
    wxString exedir = wxPathOnly(wxGetApp().argv[0]);
    if (!exedir.IsEmpty() && exedir.Last() != wxFILE_SEP_PATH)
            exedir += wxFILE_SEP_PATH;
    wxChar *possible_paths[] = {
        wxT(HELP_DIR),
        wxT("."),
        wxT(".."),
        wxT("doc"),
        wxT("../doc"), 
        0
    };
    for (int flag = 0; flag <= 1; ++flag) {
        for (int i = 0; possible_paths[i]; i++) {
            wxString path = !flag ? wxString(possible_paths[i])
                                  : exedir + possible_paths[i];
            if (!path.IsEmpty() && path.Last() != wxFILE_SEP_PATH) 
                path += wxFILE_SEP_PATH;
            string path_name = path.c_str() + name;
            //wxMessageBox(("Looking for \n" + path_name).c_str());
            if (wxFileExists(path_name.c_str())) 
                return path_name;
        }
    }
    return name;
}


//===============================================================
//                    FStatusBar   
//===============================================================
BEGIN_EVENT_TABLE(FStatusBar, wxStatusBar)
    EVT_SIZE(FStatusBar::OnSize)
END_EVENT_TABLE()

FStatusBar::FStatusBar(wxWindow *parent)
        : wxStatusBar(parent, -1), statbmp2(0)
{
    int widths[sbf_max] = { -1, 100, 100, 120 };
    SetFieldsCount (sbf_max, widths);
    SetMinHeight(15);
    statbmp1 = new wxStaticBitmap(this, -1, wxIcon(mouse_l_xpm));
    statbmp2 = new wxStaticBitmap(this, -1, wxIcon(mouse_r_xpm));
}

void FStatusBar::OnSize(wxSizeEvent& event)
{
    if (!statbmp2) return; 
    wxRect rect;
    GetFieldRect(sbf_hint1, rect);
    wxSize size = statbmp1->GetSize();
    int bmp_y = rect.y + (rect.height - size.y) / 2;
    statbmp1->Move(rect.x + 1, bmp_y);
    GetFieldRect(sbf_hint2, rect);
    statbmp2->Move(rect.x + 1, bmp_y);
    event.Skip();
}

void FStatusBar::set_hint(const char *left, const char *right)
{
    wxString space = wxT("    "); //TODO more sophisticated solution 
    if (left)  SetStatusText(space + wxString(left),  sbf_hint1);
    if (right) SetStatusText(space + wxString(right), sbf_hint2);
}