File: BibFrame.py

package info (click to toggle)
bibus 1.5.2%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 12,488 kB
  • sloc: python: 30,790; sql: 211; makefile: 158; xml: 10; sh: 3
file content (2121 lines) | stat: -rw-r--r-- 107,252 bytes parent folder | download | duplicates (2)
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
# Copyright 2004,2005 Pierre Martineau <pmartino@users.sourceforge.net>
# This file is part of Bibus, a bibliographic database that can
# work together with OpenOffice.org to generate bibliographic indexes.
#
# Bibus 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; either version 2 of the License, or
# (at your option) any later version.
#
# Bibus 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 Bibus; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA.
#
# generated by wxGlade 0.2 on Sun Jan 19 17:05:17 2003

import wx
import webbrowser, sys, os, cPickle,copy, StringIO, shutil, imp, csv
import BIB, DnD, RefEditor, SearchMedline, Search, myToolBar, Pref, ImportFrame, RefList, KeyTree, Multi_KeyTree, StyleEditor.Styleconverter, Export.html, display_panel, time
import CodecChoice, codecs
###Mounir Errami Imports
import SearcheTBlast

class BibFrame(wx.Frame):
    def __init__(self, *args, **kwds):
        # importing the necessary connection module
        self.__loadConnectionModule()
        # default allowed actions for menus
        self.allowed = BIB.ALLOWED['rw']
        # for icons in Menu
        ap = wx.ArtProvider()
        #
        self.IdFileConnect = wx.NewId()
        self.IdFileImport = wx.NewId()
        self.IdFileImportText = wx.NewId()
        self.IdFileImportInstall = wx.NewId()
        # We load Import filters dynamically
        self.IdFileImportFilters = {}
        for fn in os.listdir(os.path.join(BIB.SOURCEDIR,'Import')):
            if fn.endswith('.py') and not fn.startswith('__'):
                self.IdFileImportFilters[wx.NewId()] = os.path.splitext(fn)[0],True
        for fn in os.listdir( os.path.join(BIB.CONFIG.getFilePath(),'Import') ):
            if fn.endswith('.py'):
                self.IdFileImportFilters[wx.NewId()] = os.path.splitext(fn)[0],False
        #  Idem for Export filters
        self.IdFileExportFilters = {}
        self.IdFileExport = wx.NewId()
        self.IdFileExportSQLite = wx.NewId()
        self.IdFileExportHtml = wx.NewId()
        self.IdFileExportInstall = wx.NewId()
        for fn in os.listdir(os.path.join(BIB.SOURCEDIR,'Export')):
            if fn.endswith('.py') and not fn.startswith('__') and fn != 'html.py':
                self.IdFileExportFilters[wx.NewId()] = os.path.splitext(fn)[0],True
        for fn in os.listdir( os.path.join(BIB.CONFIG.getFilePath(),'Export') ):
            if fn.endswith('.py'):
                self.IdFileExportFilters[wx.NewId()] = os.path.splitext(fn)[0],False
        #
        self.IdDownloadFilter = wx.NewId()    # Used to download Import/Export filters
        #
        self.IdFilePageSetup = wx.NewId()
        self.IdFilePrintPreview = wx.NewId()
        self.IdFilePrint = wx.NewId()
        self.IdFileQuit = wx.NewId()
        #
        self.IdCopy = wx.NewId()
        self.IdCut = wx.NewId()
        self.IdPaste = wx.NewId()
        self.IdSelectAll = wx.NewId()
        self.IdPref = wx.NewId()
        self.IdCleanDB = wx.NewId()
        #
        self.IdAddChild = wx.NewId()
        self.IdNewRef = wx.NewId()
        self.IdEditRef = wx.NewId()
        self.IdDelRef = wx.NewId()
        self.IdTagRef = wx.NewId()
        self.IdDupRef = wx.NewId()
        self.IdPubMedSearch = wx.NewId()
        self.IdeTBlastSearch = wx.NewId()
        self.IdSearch = wx.NewId()
        self.IdDoBackup = wx.NewId()
        self.IdDoRestore = wx.NewId()
        self.IdSwitchOOo = wx.NewId()
        self.IdShowLicense = wx.NewId()
        self.IdShowHelp = wx.NewId()
        self.IdShowWebSite = wx.NewId()
        self.IdFirstTimeWizard = wx.NewId()
        self.IdShowAbout = wx.NewId()
        #
        self.db = None            # dbBib object to access database
        # begin wx.Glade: BibFrame.__init__
        kwds["style"] = wx.DEFAULT_FRAME_STYLE
        kwds["size"] = (BIB.WIDTH,BIB.HEIGHT)
        kwds["pos"] = (BIB.WX,BIB.WY)
        wx.Frame.__init__(self, *args, **kwds)
        self.window_1 = wx.SplitterWindow(self, -1)
        self.window_1.SetMinimumPaneSize(1)
        self.window_1_pane_2 = wx.Panel(self.window_1, -1)
        self.window_2 = wx.SplitterWindow(self.window_1_pane_2, -1)
        self.window_2.SetMinimumPaneSize(2)
        self.window_2_pane_2 = wx.Panel(self.window_2, -1)
        self.window_2_pane_1 = wx.Panel(self.window_2, -1)
        
        # Setting keytree
        self.__CreateKeyTree()
        #
        self.bibframe1_statusbar = self.CreateStatusBar(3)

        # Menu Bar
        self.bibframe1_menubar = wx.MenuBar()
        self.SetMenuBar(self.bibframe1_menubar)
        wxglade_tmp_menu = wx.Menu()
        wxglade_tmp_menu.Append(self.IdFileConnect, _("Connect"), _("Connect to database"))
        wxglade_tmp_menu.AppendSeparator()
        wxglade_tmp_menu_sub = wx.Menu()
        wxglade_tmp_menu_sub.Append(self.IdFileImportText, _("Text Window"), _("Import a text file"))
        for menuid,(fn,flag) in self.IdFileImportFilters.iteritems():
            wxglade_tmp_menu_sub.Append(menuid,fn)
        wxglade_tmp_menu_sub.AppendSeparator()
        wxglade_tmp_menu_sub.Append(self.IdDownloadFilter,_("Get new filters ..."))
        wxglade_tmp_menu_sub.Append(self.IdFileImportInstall,_("Install a new filter ..."))
        wxglade_tmp_menu.AppendMenu(self.IdFileImport, _("Import"), wxglade_tmp_menu_sub, _("Import a file"))
        wxglade_tmp_menu_sub = wx.Menu()
        wxglade_tmp_menu_sub.Append(self.IdFileExportSQLite, _("SQLite"), _("Export to a SQLite database"))
        wxglade_tmp_menu_sub.Append(self.IdFileExportHtml, _("HTML"), _("Export to a HTML file"))
        for menuid,(fn,flag) in self.IdFileExportFilters.iteritems():
            wxglade_tmp_menu_sub.Append(menuid,fn)
        wxglade_tmp_menu_sub.AppendSeparator()
        wxglade_tmp_menu_sub.Append(self.IdDownloadFilter,_("Get new filters ..."))
        wxglade_tmp_menu_sub.Append(self.IdFileExportInstall,_("Install a new filter ..."))
        wxglade_tmp_menu.AppendMenu(self.IdFileExport, _("Export"), wxglade_tmp_menu_sub, _("Export a file"))
        wxglade_tmp_menu.AppendSeparator()
        # wxglade_tmp_menu.Append(self.IdDoBackup,_("Archive user data"), u"Back up all locally stored user styles, databases and settings to a single archive file")
        # wxglade_tmp_menu.Append(self.IdDoRestore,_("Restore user data from archive"), u"Retrieve user styles, databases and settings from an archive file")
        # wxglade_tmp_menu.AppendSeparator()
        wxglade_tmp_menu.Append(self.IdFilePageSetup, _("Page Setup"), _("Set printer page format"))
        wxglade_tmp_menu.Append(self.IdFilePrintPreview, _("Preview ..."), _("Preview printing"))
        item = wx.MenuItem(wxglade_tmp_menu,self.IdFilePrint,_("Print ...")+"\tCtrl-%s"%BIB.KEY_PRINT,help=_("Print references"))
        item.SetBitmap(ap.GetBitmap(wx.ART_PRINT,client=wx.ART_MENU))
        wxglade_tmp_menu.AppendItem(item)
        #wxglade_tmp_menu.Append(self.IdFilePrint, _("Print ...")+"\tCtrl-%s"%BIB.KEY_PRINT, _("Print references"))
        wxglade_tmp_menu.AppendSeparator()
        item = wx.MenuItem(wxglade_tmp_menu,self.IdFileQuit,_("Quit")+"\tCtrl-%s"%BIB.KEY_QUIT,help=_("Quit Bibus"))
        item.SetBitmap(ap.GetBitmap(wx.ART_QUIT,client=wx.ART_MENU))
        wxglade_tmp_menu.AppendItem(item)            
        #wxglade_tmp_menu.Append(self.IdFileQuit, _("Quit")+"\tCtrl-%s"%BIB.KEY_QUIT, _("Quit Bibus"))
        self.bibframe1_menubar.Append(wxglade_tmp_menu, _("File"))
        wxglade_tmp_menu = wx.Menu()
        item = wx.MenuItem(wxglade_tmp_menu,self.IdCopy,_("Copy")+"\tCtrl-%s"%BIB.KEY_COPY)
        item.SetBitmap(ap.GetBitmap(wx.ART_COPY,client=wx.ART_MENU))
        wxglade_tmp_menu.AppendItem(item)
        #wxglade_tmp_menu.Append(self.IdCopy, _("Copy")+"\tCtrl-%s"%BIB.KEY_COPY, u"")
        #
        item = wx.MenuItem(wxglade_tmp_menu,self.IdCut,_("Cut")+"\tCtrl-%s"%BIB.KEY_CUT)
        item.SetBitmap(ap.GetBitmap(wx.ART_CUT,client=wx.ART_MENU))
        wxglade_tmp_menu.AppendItem(item)
        #wxglade_tmp_menu.Append(self.IdCut, _("Cut")+"\tCtrl-%s"%BIB.KEY_CUT, u"")
        item = wx.MenuItem(wxglade_tmp_menu,self.IdPaste,_("Paste")+"\tCtrl-%s"%BIB.KEY_PASTE)
        item.SetBitmap(ap.GetBitmap(wx.ART_PASTE,client=wx.ART_MENU))
        wxglade_tmp_menu.AppendItem(item)
        #wxglade_tmp_menu.Append(self.IdPaste, _("Paste")+"\tCtrl-%s"%BIB.KEY_PASTE, u"")
        wxglade_tmp_menu_sub = wx.Menu()
        for fn in os.listdir(os.path.join(BIB.SOURCEDIR,'Export')):
            if fn.endswith('.py') and not fn.startswith('__') and fn != 'html.py':
                item = wxglade_tmp_menu_sub.AppendRadioItem(wx.NewId(),os.path.splitext(fn)[0])
                wx.EVT_MENU(self,item.GetId(),self.onClipboardFormat)
                if item.GetItemLabelText() == BIB.TEXT_CLIPBOARD: item.Check()
        #for fn in os.listdir( os.path.join(BIB.CONFIG.getFilePath(),'Export') ):
        #    if fn.endswith('.py'):
        #        wxglade_tmp_menu_sub.AppendRadioItem(wx.NewId(),os.path.splitext(fn)[0])
        wxglade_tmp_menu.AppendMenu(wx.NewId(), _("Copy format"), wxglade_tmp_menu_sub, _("Switch text clipboard format"))
        #
        wxglade_tmp_menu.AppendSeparator()
        wxglade_tmp_menu.Append(self.IdSelectAll, _("Select All")+"\tCtrl-%s"%BIB.KEY_SELECT_ALL, u"")
        wxglade_tmp_menu.AppendSeparator()
        item = wx.MenuItem(wxglade_tmp_menu,self.IdPref,_("Preferences"),help=_("Set some preferences"))
        item.SetBitmap(ap.GetBitmap(wx.ART_HELP_SETTINGS,client=wx.ART_MENU))
        wxglade_tmp_menu.AppendItem(item)
        #wxglade_tmp_menu.Append(self.IdPref, _("Preferences"), _("Set some preferences"))
        self.bibframe1_menubar.Append(wxglade_tmp_menu, _("Edit"))
        wxglade_tmp_menu = wx.Menu()
        item = wx.MenuItem(wxglade_tmp_menu,self.IdAddChild,_("Add child"),help=_("Add a child to the selected key"))
        item.SetBitmap(ap.GetBitmap(wx.ART_ADD_BOOKMARK,client=wx.ART_MENU))
        wxglade_tmp_menu.AppendItem(item)
        #wxglade_tmp_menu.Append(self.IdAddChild, _("Add child"), _("Add a child to the selected key"))
        wxglade_tmp_menu.AppendSeparator()
        item = wx.MenuItem(wxglade_tmp_menu,self.IdNewRef,_("New reference")+"\tCtrl-%s"%BIB.KEY_NEW,help=_("Add a reference associated with the selected key"))
        item.SetBitmap(ap.GetBitmap(wx.ART_NEW,client=wx.ART_MENU))
        wxglade_tmp_menu.AppendItem(item)
        #wxglade_tmp_menu.Append(self.IdEditRef, _("New reference")+"\tCtrl-%s"%BIB.KEY_NEW, _("Add a reference associated with the selected key"))
        item = wx.MenuItem(wxglade_tmp_menu,self.IdEditRef,_("Edit reference"),help=_("Edit the selected reference"))
        item.SetBitmap(ap.GetBitmap(wx.ART_EXECUTABLE_FILE,client=wx.ART_MENU))
        wxglade_tmp_menu.AppendItem(item)
        #wxglade_tmp_menu.Append(self.IdEditRef, _("Edit reference"), _("Edit the selected reference"))
        item = wx.MenuItem(wxglade_tmp_menu,self.IdDelRef,_("Delete reference")+"\tCtrl-%s"%BIB.KEY_DEL,help=_("Delete the selected reference"))
        item.SetBitmap(ap.GetBitmap(wx.ART_DELETE,client=wx.ART_MENU))
        wxglade_tmp_menu.AppendItem(item)
        #wxglade_tmp_menu.Append(self.IdDelRef, _("Delete reference")+"\tCtrl-%s"%BIB.KEY_DEL, _("Delete the selected reference"))
        item = wx.MenuItem(wxglade_tmp_menu,self.IdTagRef,_("Tag reference")+"\tCtrl-%s"%BIB.KEY_TAG,help=_("Mark the selected reference"))
        item.SetBitmap(ap.GetBitmap(wx.ART_TICK_MARK,client=wx.ART_MENU))
        wxglade_tmp_menu.AppendItem(item)
        #wxglade_tmp_menu.Append(self.IdTagRef, _("Tag reference")+"\tCtrl-%s"%BIB.KEY_TAG, _("Tag the selected reference"))
        wxglade_tmp_menu.Append(self.IdDupRef, _("Duplicate reference"), _("Make a copy of the first selected reference"))
        self.bibframe1_menubar.Append(wxglade_tmp_menu, _("Reference"))
        wxglade_tmp_menu = wx.Menu()
        item = wx.MenuItem(wxglade_tmp_menu,self.IdSearch,_("Search ...")+"\tCtrl-%s"%BIB.KEY_SEARCH,help=_("Search the database"))
        item.SetBitmap(ap.GetBitmap(wx.ART_FIND,client=wx.ART_MENU))
        wxglade_tmp_menu.AppendItem(item)
        #wxglade_tmp_menu.Append(self.IdSearch, _("Search ...")+"\tCtrl-%s"%BIB.KEY_SEARCH, _("Search the database"))
        wxglade_tmp_menu.Append(self.IdPubMedSearch, _("Pubmed search ...")+"\tCtrl-%s"%BIB.KEY_PUBMED, _("Search Pubmed on the Web"))
        wxglade_tmp_menu.Append(self.IdeTBlastSearch, _("eTBlast on PubMed ...")+"\tCtrl-%s"%BIB.KEY_ETBLAST, _("Search Pubmed with eTBlast"))
        self.bibframe1_menubar.Append(wxglade_tmp_menu, _("Search"))

        #Styles menu
        wxglade_tmp_menu = wx.Menu()
        BIB.STYLE_MENU = wxglade_tmp_menu
        self.IdOOoStyleNew = wx.NewId()
        self.IdOOoStyleEdit = wx.NewId()
        self.IdOOoStyleLoad = wx.NewId()
        self.IdOOoStyleDownload = wx.NewId()
        item = wx.MenuItem(wxglade_tmp_menu,self.IdOOoStyleNew,_("New ..."))
        item.SetBitmap(ap.GetBitmap(wx.ART_NEW,client=wx.ART_MENU))
        wxglade_tmp_menu.AppendItem(item)
        #wxglade_tmp_menu.Append(self.IdOOoStyleNew, _("New ..."), u"0")
        item = wx.MenuItem(wxglade_tmp_menu,self.IdOOoStyleEdit,_("Edit ..."))
        item.SetBitmap(ap.GetBitmap(wx.ART_EXECUTABLE_FILE,client=wx.ART_MENU))
        wxglade_tmp_menu.AppendItem(item)
        #wxglade_tmp_menu.Append(self.IdOOoStyleEdit, _("Edit ..."), u"0")
        item = wx.MenuItem(wxglade_tmp_menu,self.IdOOoStyleLoad,_("Load ..."))
        item.SetBitmap(ap.GetBitmap(wx.ART_FILE_OPEN,client=wx.ART_MENU))
        wxglade_tmp_menu.AppendItem(item)
        #wxglade_tmp_menu.Append(self.IdOOoStyleLoad, _("Load ..."), u"0")
        item = wx.MenuItem(wxglade_tmp_menu,self.IdOOoStyleDownload,_("Download styles"))
        item.SetBitmap(ap.GetBitmap(wx.ART_GO_BACK,client=wx.ART_MENU))
        wxglade_tmp_menu.AppendItem(item)        
        #wxglade_tmp_menu.Append(self.IdOOoStyleDownload, _("Download styles"), u"0")
        wxglade_tmp_menu.AppendSeparator()
        self.bibframe1_menubar.Append(wxglade_tmp_menu, _("Styles"))

        if BIB.WP == 'OOo':
            # setting OOo menu if needed
            self.doc = None        # this is the connection with OOo
            self.bibframe1_menubar.Append(self.__setOOoMenu(), _("OpenOffice.org"))
            self.WP_id = self.bibframe1_menubar.FindMenu( _("OpenOffice.org"))    # we keep the Id of the menu if we need to switch to word
        elif BIB.WP == 'mswDoc':
            # setting mswWord menu if needed
            self.bibframe1_menubar.Append(self.__setWordMenu(), _("MSWord"))
            self.WP_id = self.bibframe1_menubar.FindMenu( _("MSWord"))
        elif BIB.WP == 'Lyx':
            self.bibframe1_menubar.Append(self.__setLyxMenu(), _("LyX"))
            self.WP_id = self.bibframe1_menubar.FindMenu( _("LyX"))
        else:
            self.WP_id = None
        
        # Tools menu
        wxglade_tmp_menu = wx.Menu()
        # first connection wizzard
        wxglade_tmp_menu.Append(self.IdFirstTimeWizard, _("First Connection Wizard"), u"")
        wxglade_tmp_menu.AppendSeparator()
        # clean-up database
        wxglade_tmp_menu.Append(self.IdCleanDB, _("Clean database ..."), _("Empty Trash and DB cleanup"))
        wxglade_tmp_menu.AppendSeparator()
        # back-up
        wxglade_tmp_menu.Append(self.IdDoBackup,_("Archive user data"), u"Back up all locally stored user styles, databases and settings to a single archive file")
        wxglade_tmp_menu.Append(self.IdDoRestore,_("Restore user data from archive"), u"Retrieve user styles and databases from an archive file")
        # Easy switching between Word processors
        wxglade_tmp_menu.AppendSeparator()
        #wxglade_tmp_menu.Append(self.IdSwitchOOo,_("Word Processor"))
        wxglade_tmp_menu_sub = wx.Menu()
        for wp in ("OpenOffice.org", "Word", "LyX"):
            tmpid = wx.NewId()
            wxglade_tmp_menu_sub.Append(tmpid, wp)
            wx.EVT_MENU(self,tmpid,self.switchWP)
        wxglade_tmp_menu.AppendMenu(self.IdSwitchOOo, _("Word Processor"), wxglade_tmp_menu_sub, _("Switch Word Processor support"))
        #
        self.bibframe1_menubar.Append(wxglade_tmp_menu, _("Tools"))

        # Help menu
        wxglade_tmp_menu = wx.Menu()
        item = wx.MenuItem(wxglade_tmp_menu,self.IdShowHelp,_("Documentation"))
        item.SetBitmap(ap.GetBitmap(wx.ART_HELP,client=wx.ART_MENU))
        wxglade_tmp_menu.AppendItem(item)
        #wxglade_tmp_menu.Append(self.IdShowHelp, _("Documentation"), u"")
        wxglade_tmp_menu.Append(self.IdShowLicense, _("License"), u"")
        item = wx.MenuItem(wxglade_tmp_menu,self.IdShowWebSite,_("Bibus WEB site"))
        item.SetBitmap(ap.GetBitmap(wx.ART_GO_HOME,client=wx.ART_MENU))
        wxglade_tmp_menu.AppendItem(item)        
        #wxglade_tmp_menu.Append(self.IdShowWebSite, _("Bibus WEB site"), u"")
        # wxglade_tmp_menu.AppendSeparator()
        # wxglade_tmp_menu.Append(self.IdFirstTimeWizard, _("First Connection Wizard"), u"")
        wxglade_tmp_menu.AppendSeparator()
        wxglade_tmp_menu.Append(self.IdShowAbout, _("About"), u"")
        self.bibframe1_menubar.Append(wxglade_tmp_menu, _("Help"))
        # Menu Bar end

        #
        self.refDisplaypanel = display_panel.DisplayPanel(self.window_2_pane_2,-1,bibframe=self)
        self.reflist = RefList.RefList(self.window_2_pane_1, self)
        self.reflist.SetImageList(BIB.ARROWS,wx.IMAGE_LIST_SMALL)                    # list of images for icon in columns (sort order)
        # toolbar = just a wx.Panel since I got too many bugs with a true toolbar
        self.toolbar = self.CreateToolBar()
        #
        self.__set_properties()
        self.__do_layout()
        self.window_2.SetSashPosition( BIB.SASH_LIST )        # we have to reset to the correct position
        self.window_1.SetSashPosition( BIB.SASH_KEYTREE )    # since __do_layout() may have move it
        # end wx.Glade
        self.__set_evt_menu()
        #
        # loading dbBib module and try to connect
        #if BIB.DB_TYPE:
        #self.SetIcon(wx.Icon("Pixmaps/bibus.xpm",wx.BITMAP_TYPE_XPM))
        self.SetIcon(wx.Icon( os.path.join(BIB.SOURCEDIR,"Pixmaps/bibus.ico"), wx.BITMAP_TYPE_ICO) )
        try:
            BIB.DB_MODULE = __import__('dbBib'+BIB.DB_TYPE)
            getattr(BIB.DB_MODULE,'dbBib')    # if the module was loaded before, re-importing won't raise ImportError. We must check directly if it works
        except (ImportError,AttributeError):
            BIB.DB_MODULE = None
            wx.LogError(_("""Sorry, but I was not able to find the python module for the %s database.\nPlease check your installation""")%BIB.DB_TYPE)
        self.autoConnect()
        # other initialisations
        self.__setStyleMenu()        # populate the StyleMenu
        self.__setStartingConverter()    # set the reference formatting
        self.refDisplaypanel.resetFormat(BIB.FORMAT_DICO)

    def autoConnect(self):
        """Try to connect to a database (the last one used or default)"""
        if BIB.DB_MODULE:        # if a module is charged
            tmp_passwd = None
            db_still_valid = True
            if BIB.DB_TYPE == 'MySQL':
                name = BIB.DB_NAME
                if not BIB.STORE_PASSWD:
                    BIB.PASSWORD = wx.GetPasswordFromUser(_("Please enter password for database %s")%BIB.DB_NAME,parent=self)
            else:
                name = BIB.SQLiteFile
                # TO DO: not only check existence
                # but also if valid Bibus file
                if not os.path.exists(BIB.SQLiteFile):
                    ### print 'File does not exist...'
                    db_still_valid = False
                    # We should try to find a way to automatically 
                    # open 'connect' dialogue
            if db_still_valid:
                try:
                    #self.db=apply(eval('dbBib'+BIB.DB_TYPE+'.dbBib'),(self,BIB.USER,tmp_passwd,BIB.DB_NAME,BIB.HOST,BIB.PORT,BIB.SOCKET))
                    # the following command already generates warnings 
                    # if the file being opened is not a proper bibus db
                    self.db = BIB.DB_MODULE.dbBib(self) 
                    self.db.selectDatabase(name) # needed for creation of tmp tables
                    self.__chargeDB()
                except:
                    self.db = None
                    self.__noDB()
                if not BIB.STORE_PASSWD: BIB.PASSWORD = ''    # clear password for security
                if self.db: self.set_grants_layout()
            else:
                self.db = None
                self.__noDB()
        else:
            self.db = None
            self.__noDB()

    def __chargeDB(self):
        self.db.selectTable()
        self.keytree.setkeytree()
        self.keytree.KeySelect(self.keytree.keyAll)
        self.keytree.SelectItem(self.keytree.keyAll)
        self.SetTitle(_("Database = %s") % self.db.getDbDescription())

    def __noDB(self):
        """No active DB => clear everything"""
        self.SetTitle(_("Database = None"))
        self.keytree.DeleteAllItems()
        self.reflist.DeleteAllItems()
        self.refDisplaypanel.Clear()

    def CreateToolBar(self,id=-1,name=u'toolBar'):
        return myToolBar.myToolBar(self,id=id,name=name)
    
    def __CreateKeyTree(self):    
        # Setting keytree
        # If we are in a multi-users environment, we display multiple panels
        # one for the current user, one shared
        self.window_1_pane_1 = wx.Panel(self.window_1, -1)
        if BIB.MULTI_USER:
            self.keytree = Multi_KeyTree.Multi_KeyTree(self,self.window_1_pane_1)
        else:
            #self.keytree = Multi_KeyTree.KeyTree_Search(self,self.window_1_pane_1)    # does not work as expected. I have to find a better interface.
            self.keytree = KeyTree.KeyTree(self,self.window_1_pane_1)

    def __set_properties(self):
        # begin wx.Glade: BibFrame.__set_properties
        # self.SetTitle("bibframe1")
        # self.SetSize((-1, -1))
        self.bibframe1_statusbar.SetStatusWidths([-4,-2,-1])
        # statusbar fields
        bibframe1_statusbar_fields = [BIB.WELCOME,_("%(total_number)s reference(s) : %(number_selected)s selected")%{'total_number':self.reflist.GetItemCount(),'number_selected':self.reflist.GetSelectedItemCount()}]
        for i in range(len(bibframe1_statusbar_fields)):
            self.bibframe1_statusbar.SetStatusText(bibframe1_statusbar_fields[i], i)
        self.window_2.SplitHorizontally(self.window_2_pane_1, self.window_2_pane_2, BIB.SASH_LIST)
        self.window_1.SplitVertically(self.window_1_pane_1, self.window_1_pane_2, BIB.SASH_KEYTREE)
        # end wx.Glade
        if BIB.WP == 'OOo':
            self.bibframe1_menubar.Check(self.IdOOoHilightCitations,self.OOoHilightCit)
            self.bibframe1_menubar.Check(self.IdOOoAutoUpdate,self.OOoAutoUpdate)
            self.bibframe1_menubar.Check(self.IdOOoCreateBib,self.OOoCreateBib)

    def __layoutKeyTree(self):
        """We need to set it independently to be able to switch between rr and rw/ro/rk"""
        sizer_1 = wx.BoxSizer(wx.HORIZONTAL)
        sizer_1.Add(self.keytree, 1, wx.EXPAND, 0)
        self.window_1_pane_1.SetAutoLayout(1)
        self.window_1_pane_1.SetSizer(sizer_1)
        sizer_1.Fit(self.window_1_pane_1)
        #sizer_1.SetSizeHints(self.window_1_pane_1)

    def __do_layout(self):
        sizer_0 = wx.BoxSizer(wx.VERTICAL)
        # begin wx.Glade: BibFrame.__do_layout
        sizer_2 = wx.BoxSizer(wx.VERTICAL)
        sizer_4 = wx.BoxSizer(wx.HORIZONTAL)
        self.sizer_6 = wx.BoxSizer(wx.HORIZONTAL)
        sizer_5 = wx.BoxSizer(wx.HORIZONTAL)
        self.__layoutKeyTree()
        sizer_5.Add(self.reflist, 1, wx.EXPAND, 0)
        self.window_2_pane_1.SetAutoLayout(1)
        self.window_2_pane_1.SetSizer(sizer_5)
        sizer_5.Fit(self.window_2_pane_1)
        #sizer_5.SetSizeHints(self.window_2_pane_1)
        self.sizer_6.Add(self.refDisplaypanel, 1, wx.EXPAND, 0)
        self.window_2_pane_2.SetAutoLayout(1)
        self.window_2_pane_2.SetSizer(self.sizer_6)
        self.sizer_6.Fit(self.window_2_pane_2)
        #self.sizer_6.SetSizeHints(self.window_2_pane_2)
        sizer_4.Add(self.window_2, 1, wx.EXPAND, 0)
        self.window_1_pane_2.SetAutoLayout(1)
        self.window_1_pane_2.SetSizer(sizer_4)
        sizer_4.Fit(self.window_1_pane_2)
        #sizer_4.SetSizeHints(self.window_1_pane_2)
        sizer_2.Add(self.window_1, 1, wx.EXPAND, 0)
        #sizer_2.SetSizeHints(self)
        self.SetAutoLayout(1)
        #
        sizer_0.Add(self.toolbar,0,wx.EXPAND)
        sizer_0.Add(sizer_2,1,wx.EXPAND)
        #
        self.SetSizer(sizer_0)
        self.SetSizeHints(minH=200,minW=150)
        self.Layout()
        # end wx.Glade

    def __set_evt_menu(self):
        # file menu
        wx.EVT_MENU(self,self.IdFileQuit,self.onMenuFileQuit)
        wx.EVT_MENU(self,self.IdFileConnect,self.onMenuFileConnect)
        wx.EVT_MENU(self,self.IdFilePageSetup,self.onMenuFilePageSetup)
        wx.EVT_MENU(self,self.IdFilePrintPreview,self.onMenuFilePrintPreview)
        wx.EVT_MENU(self,self.IdFilePrint,self.onMenuFilePrint)
        wx.EVT_MENU(self,self.IdFileImportText,self.onMenuFileImportText)
        wx.EVT_MENU(self,self.IdFileImportInstall,lambda evt: self.onMenuFilterInstall(evt,"Import"))
        # Dynamic Import filters
        for idmenu in self.IdFileImportFilters.iterkeys():
            wx.EVT_MENU(self,idmenu,self.onMenuFileImport)
        #
        wx.EVT_MENU(self,self.IdFileExportSQLite,self.onMenuFileExportSQLite)
        wx.EVT_MENU(self,self.IdFileExportHtml,self.onMenuFileExportHtml)
        wx.EVT_MENU(self,self.IdDownloadFilter,self.onDownloadFilters)
        wx.EVT_MENU(self,self.IdFileExportInstall,lambda evt: self.onMenuFilterInstall(evt,"Export"))
        # Dynamic Export filters
        for idmenu in self.IdFileExportFilters.iterkeys():
            wx.EVT_MENU(self,idmenu,self.onMenuFileExport)
        #
        wx.EVT_MENU(self,self.IdAddChild,self.keytree.onMenuAddChild)
        wx.EVT_MENU(self,self.IdNewRef,self.onMenuNewRef)
        wx.EVT_MENU(self,self.IdEditRef,self.onMenuEditRef)
        wx.EVT_MENU(self,self.IdDelRef,self.onMenuDelRef)
        wx.EVT_MENU(self,self.IdTagRef,self.onMenuTagRef)
        wx.EVT_MENU(self,self.IdDupRef,self.onMenuDuplicateRef)
        wx.EVT_MENU(self,self.IdPubMedSearch,self.onMenuPubMedSearch)
        wx.EVT_MENU(self,self.IdeTBlastSearch,self.onMenueTBlastSearch)
        wx.EVT_MENU(self,self.IdSearch,self.onMenuSearch)
        # Copy/Paste
        wx.EVT_MENU(self,self.IdCopy,self.onMenuCopy)
        wx.EVT_MENU(self,self.IdCut,self.onMenuCut)
        wx.EVT_MENU(self,self.IdPaste,self.onMenuPaste)
        wx.EVT_MENU(self,self.IdSelectAll,self.onMenuSelectAll)
        wx.EVT_MENU(self,self.IdPref,self.onMenuPref)
        wx.EVT_MENU(self,self.IdCleanDB,self.onMenuCleanDB)
        # Style menu
        wx.EVT_MENU(self,self.IdOOoStyleEdit,self.onMenuOOoStyleEdit)
        wx.EVT_MENU(self,self.IdOOoStyleNew,self.onMenuOOoStyleNew)
        wx.EVT_MENU(self,self.IdOOoStyleLoad,self.onMenuOOoStyleLoad)
        wx.EVT_MENU(self,self.IdOOoStyleDownload,self.onMenuOOoStyleDownload)
        # Tools menu (currently integrated in File menu)
        wx.EVT_MENU(self,self.IdDoBackup,self.doBackup)
        wx.EVT_MENU(self,self.IdDoRestore,self.doRestore)
        # Help menu
        wx.EVT_MENU(self,self.IdShowHelp,self.showHelp)
        wx.EVT_MENU(self,self.IdShowLicense,self.showLicense)
        wx.EVT_MENU(self,self.IdShowWebSite,self.showWebSite)
        wx.EVT_MENU(self,self.IdFirstTimeWizard,self.firstTimeWizard)
        wx.EVT_MENU(self,self.IdShowAbout,self.showAbout)
        # window
        wx.EVT_CLOSE(self,self.onClose)

    def set_menu(self,key):
        """Enable and Disable menus"""
        try:
            #id = self.keytree.GetPyData(self.keytree.GetSelection())[2]
            id = self.keytree.GetPyData(key)[2]
            ref = self.reflist.GetFirstSelected()
            if self.allowed[id] & BIB.CHILD_OK: self.bibframe1_menubar.Enable(self.IdAddChild,True)
            else: self.bibframe1_menubar.Enable(self.IdAddChild,False)
            if self.allowed[id] & BIB.REF_EDIT_OK and ref != -1: self.bibframe1_menubar.Enable(self.IdEditRef,True)
            else: self.bibframe1_menubar.Enable(self.IdEditRef,False)
            if self.allowed[id] & BIB.REF_NEW_OK: self.bibframe1_menubar.Enable(self.IdNewRef,True)
            else: self.bibframe1_menubar.Enable(self.IdNewRef,False)
            if self.allowed[id] & BIB.REF_DEL_OK and ref != -1: self.bibframe1_menubar.Enable(self.IdDelRef,True)
            else: self.bibframe1_menubar.Enable(self.IdDelRef,False)
            if self.allowed[id] & BIB.REF_TAG_OK and ref != -1: self.bibframe1_menubar.Enable(self.IdTagRef,True)
            else: self.bibframe1_menubar.Enable(self.IdTagRef,False)
            if self.allowed[id] & BIB.REF_DUP_OK and ref != -1: self.bibframe1_menubar.Enable(self.IdDupRef,True)
            else: self.bibframe1_menubar.Enable(self.IdDupRef,False)
            if self.allowed[id] & BIB.EXPORT_OK: self.bibframe1_menubar.Enable(self.IdFileExport,True)
            else: self.bibframe1_menubar.Enable(self.IdFileExport,False)
            # Copy/Paste
            ClipOK = wx.TheClipboard.IsSupported(BIB.DnD_FORMAT)
            if self.allowed[id] & BIB.REF_DRAG_OK and ref != -1: self.bibframe1_menubar.Enable(self.IdCopy,True)
            else: self.bibframe1_menubar.Enable(self.IdCopy,False)
            if self.allowed[id] & BIB.REF_DEL_OK and ref != -1: self.bibframe1_menubar.Enable(self.IdCut,True)
            else: self.bibframe1_menubar.Enable(self.IdCut,False)
            if self.allowed[id] & BIB.REF_DROP_OK and ClipOK: self.bibframe1_menubar.Enable(self.IdPaste,True)
            else: self.bibframe1_menubar.Enable(self.IdPaste,False)
            # OOo menu
            if self.allowed[id] & BIB.OOo_INSERT_OK and ref != -1 and BIB.WP == 'OOo': self.bibframe1_menubar.Enable(self.IdOOoInsert,True)
            else: self.bibframe1_menubar.Enable(self.IdOOoInsert,False)
            # MSW menu
            if self.allowed[id] & BIB.OOo_INSERT_OK and ref != -1 and BIB.WP == 'mswDoc': self.bibframe1_menubar.Enable(self.IdMSWInsert,True)
            else: self.bibframe1_menubar.Enable(self.IdMSWInsert,False)
            # export
            if self.allowed[id] & BIB.EXPORT_OK: self.bibframe1_menubar.Enable(self.IdFileExport,True)
            else: self.bibframe1_menubar.Enable(self.IdFileExport,False)
            # printing
            if self.allowed[id] & BIB.REF_PRINT_OK:
                self.bibframe1_menubar.Enable(self.IdFilePrintPreview,True)
                self.bibframe1_menubar.Enable(self.IdFilePrint,True)
            else:
                self.bibframe1_menubar.Enable(self.IdFilePrintPreview,False)
                self.bibframe1_menubar.Enable(self.IdFilePrint,False)
        except:
            pass    # self.keytree.GetSelection() is invalid

    def saveJournalsAbbrev(self):
        """Save the abbreviations if we have modified them"""
        if not BIB.JOURNAL_MODIF: return
        f = os.path.join(wx.StandardPaths.Get().GetUserDataDir(),'Data',BIB.JOURNAL_FILE)
        fi = file( f, "w" )
        output = csv.writer(fi)
        output.writerows( BIB.JOURNAL.itervalues() )
        fi.close()

    def onClose(self,event):
        """Allows saving default values before exiting"""
        BIB.WX, BIB.WY = self.GetPositionTuple()
        BIB.WIDTH, BIB.HEIGHT = self.GetSizeTuple()
        BIB.SASH_LIST = self.window_2.GetSashPosition()
        if self.window_1.IsSplit(): BIB.SASH_KEYTREE = self.window_1.GetSashPosition()
        BIB.LIST_COL_SIZE = tuple( [self.reflist.GetColumnWidth(col) for col in xrange(self.reflist.GetColumnCount())] )
        if BIB.WP == 'OOo':
            BIB.OO_HILIGHT = self.OOoHilightCit
            BIB.OO_AUTO_UPDATE = self.OOoAutoUpdate
            BIB.OO_CREATE_BIB = self.OOoCreateBib
        BIB.CONFIG.writeConfig(not bool(BIB.DB_STARTUP))
        BIB.CONFIG.writeShortcuts()        # save the shortcuts
        #
        self.saveJournalsAbbrev()
        self.Destroy()

    def onMenuFileQuit(self,event):
        self.Close(True)

    def onMenuNewRef(self,event):
        selectedkey=self.keytree.GetSelection()
        key_id,user,id = self.keytree.GetPyData(selectedkey)
        if self.allowed[id] & BIB.REF_NEW_OK:
            if selectedkey == self.keytree.keyAll: selectedkey = self.keytree.keyRef    # Since we now have a Trash, keyAll cannot accept references
            editor = RefEditor.RefEditor((),self.db,selectedkey,True,self,-1,u'')        # we thus create in key Ref => will appear also in All
            editor.Show(True)

    def onMenuEditRef(self,event):
        selectedkey=self.keytree.GetSelection()
        key_id,user,id = self.keytree.GetPyData(selectedkey)
        #if self.allowed[id] & BIB.REF_EDIT_OK:
        selected = self.reflist.GetFirstSelected()
        while selected != -1:
            ref_id = self.reflist.GetItemData(selected)
            # getting the reference
            if id == BIB.ID_IMPORT_ROOT:    # we are in the import list
                ref = self.db.getRefImport(ref_id,BIB.BIB_FIELDS)
            elif id == BIB.ID_ONLINE_ROOT:    # we are in the online list
                ref = self.db.getRefOnline(ref_id,BIB.BIB_FIELDS)
            else:                            # we are in ref or query
                ref = self.db.getRef(ref_id,BIB.BIB_FIELDS)
            #
            editor = RefEditor.RefEditor(ref[0],self.db,selectedkey,self.allowed[id] & BIB.REF_EDIT_OK,self,-1,u'')
            editor.Show(True)
            selected = self.reflist.GetNextSelected(selected)

    def onMenuDelRef(self,event):
        selectedkey=self.keytree.GetSelection()
        key_id,user,id = self.keytree.GetPyData(selectedkey)
        firstselected = self.reflist.GetFirstSelected()
        selected = firstselected
        while selected != -1:
            ref_id = self.reflist.GetItemData(selected)
            self.db.delLink(key_id,ref_id)
            selected = self.reflist.GetNextSelected(selected)
        self.keytree.KeySelect(selectedkey)
        #self.set_menu(selectedkey) # not needed since it's done in KeySelect
        if self.reflist.GetFirstSelected() == -1 and firstselected != -1:
            self.reflist.Select( min(firstselected,self.reflist.GetItemCount()-1) )
            self.reflist.Focus( min(firstselected,self.reflist.GetItemCount()-1) )

    def onMenuTagRef(self,event):
        selectedkey=self.keytree.GetSelection()
        key_id,user,id = self.keytree.GetPyData(selectedkey)
        if self.allowed[id] & BIB.REF_DRAG_OK:
            keyTaggedId = self.keytree.GetPyData(self.keytree.keyTagged)[0]
            selected = self.reflist.GetFirstSelected()
            while selected != -1:
                ref_id = self.reflist.GetItemData(selected)
                self.db.writeLink( (keyTaggedId,ref_id) )
                selected = self.reflist.GetNextSelected(selected)

    def onMenuDuplicateRef(self,event):
        """We duplicate the first selected reference"""
        selected = self.reflist.GetFirstSelected()
        ref_id_old = self.reflist.GetItemData(selected)
        ref = self.db.getRef(ref_id_old,BIB.BIB_FIELDS)[0]
        ref = list(ref)
        ref[0] = None
        # we must allow insertion of duplicates
        dup_saved = BIB.DUPLICATES_TEST
        BIB.DUPLICATES_TEST = False
        ref_id = self.db.writeRef(ref)
        BIB.DUPLICATES_TEST = dup_saved
        # write link between the new ref and the current key
        key_id = self.keytree.GetPyData(self.keytree.GetSelection())[0]
        self.db.writeLink((key_id,ref_id))
        # update creator table
        #self.db.updateLastModif(ref_id)
        #
        self.updateRefList()
        self.reflist.selectItem(ref_id)

    def onMenuFileConnect(self,event):
        tmptypes = BIB.DB_TYPES[:]
        tmptypes.remove(BIB.DB_TYPE)
        tmptypes.insert(0,BIB.DB_TYPE)    # We put the current choice in first to have it selected by default
        ret = wx.GetSingleChoice(_("Please, select the database type"),_("Type of database"),tmptypes)
        if ret == "": return
        savedModule = BIB.DB_MODULE
        savedDBtype = BIB.DB_TYPE
        BIB.DB_TYPE = ret
        try:
            f, pathname, description = imp.find_module('dbBib'+BIB.DB_TYPE)
            BIB.DB_MODULE = imp.load_module('dbBib'+BIB.DB_TYPE, f, pathname, description)
            #BIB.DB_MODULE = __import__('dbBib'+BIB.DB_TYPE)
            #getattr(BIB.DB_MODULE,'dbBib')    # if the module was loaded before, re-importing won't raise ImportError. We must check directly if it works
        except ImportError:
            wx.LogError(_("""Sorry, but I was not able to find the Python module for the %s database.\nPlease check your installation""")%BIB.DB_TYPE)
            BIB.DB_MODULE = savedModule
            BIB.DB_TYPE = savedDBtype
            if f: f.close()
            return
        if f: f.close()
        #
        try:
            dbWiz = BIB.DB_MODULE.dbWizard(self)
            if not dbWiz.RunWizard(dbWiz.page1):
                BIB.DB_MODULE = savedModule
                BIB.DB_TYPE = savedDBtype
                return            # the user canceled the Wizard.
            db = dbWiz.getDbSelected()
            dbWiz.Destroy()
        except AttributeError:
            wx.LogError(_("""Sorry, but I was not able to find the Python module for the %s database.\nPlease check your installation""")%BIB.DB_TYPE)
            self.db = None
            self.__noDB()    # clear everything
            return
        #
        if db == None:
            self.db = None
            self.__noDB()
            self.showError(_("You did not select a valid database"))
        else:
            self.db = db
            self.__chargeDB()    # fill the main window with data
            self.set_grants_layout()

# setting layout depending on grants
    def set_grants_layout(self):
        grants = self.keytree.getGrants()
        self.allowed = BIB.ALLOWED[grants]
        if grants == 'rw':                                # normal read-write user
            self.refDisplaypanel.ShowKeysPage()
            self.keytree.keys_perso.Show()
            self.keytree.keys_common.Show()
            self.keytree.SelectUserTree()
            if not self.window_1.IsSplit():
                self.window_1_pane_1.Show()
                self.window_1.SplitVertically(self.window_1_pane_1, self.window_1_pane_2, BIB.SASH_KEYTREE)
        elif grants == 'ro':                            # normal read-only user with permissions to classify references
            self.refDisplaypanel.ShowKeysPage()
            self.keytree.keys_perso.Show()
            self.keytree.keys_common.Show()
            self.keytree.SelectUserTree()
            if not self.window_1.IsSplit():
                self.window_1_pane_1.Show()
                self.window_1.SplitVertically(self.window_1_pane_1, self.window_1_pane_2, BIB.SASH_KEYTREE)
        elif grants == 'rk':                            # read-only with ro on keytree
            self.refDisplaypanel.ShowKeysPage()
            self.keytree.keys_perso.Show(False)
            self.keytree.keys_common.Show()
            if not self.window_1.IsSplit():
                self.window_1_pane_1.Show()
                self.window_1.SplitVertically(self.window_1_pane_1, self.window_1_pane_2, BIB.SASH_KEYTREE)
        else:                                            # restricted read-only user
            self.refDisplaypanel.ShowKeysPage(False)
            self.keytree.keys_perso.Show(False)
            self.keytree.keys_common.Show(False)
            BIB.SASH_KEYTREE = self.window_1.GetSashPosition()
            self.window_1.Unsplit( self.window_1_pane_1 )

# setting menu depending on current grants
    def __set_ro(self):
        """Delete keys and inactivate menu for read-only users with rw on keytree"""
        self.bibframe1_menubar.Enable(self.IdFileImport,False)
        self.bibframe1_menubar.Enable(self.IdPubMedSearch,False)
        self.bibframe1_menubar.Enable(self.IdeTBlastSearch,False)
        self.toolbar.withoutPubMed()
        #self.refDisplaypanel.ShowKeysPage()
        #self.keytree.keys_perso.Show()
        #self.keytree.keys_common.Show()
        #if not self.window_1.IsSplit():
        #    self.window_1_pane_1.Show()
        #    self.window_1.SplitVertically(self.window_1_pane_1, self.window_1_pane_2, BIB.SASH_KEYTREE)
            #self.window_1.SetSashPosition(BIB.SASH_KEYTREE)

    def __set_rr(self):
        """Delete keys and inactivate menu for read-restricted users"""
        #BIB.SASH_KEYTREE = self.window_1.GetSashPosition()
        #self.window_1.Unsplit( self.window_1_pane_1 )
        self.bibframe1_menubar.Enable(self.IdFileImport,False)
        self.bibframe1_menubar.Enable(self.IdPubMedSearch,False)
        self.bibframe1_menubar.Enable(self.IdeTBlastSearch,False)
        self.toolbar.withoutPubMed()
        #self.refDisplaypanel.ShowKeysPage(False)

    def __set_rk(self):
        """Delete keys and inactivate menu for read-only users with ro on shared keytree"""
        self.bibframe1_menubar.Enable(self.IdFileImport,False)
        self.bibframe1_menubar.Enable(self.IdPubMedSearch,False)
        self.bibframe1_menubar.Enable(self.IdeTBlastSearch,False)
        self.toolbar.withoutPubMed()
        self.refDisplaypanel.ShowKeysPage()
        #self.keytree.keys_perso.Show(False)
        #self.keytree.keys_common.Show()
        #if not self.window_1.IsSplit():
        #    self.window_1_pane_1.Show()
        #    self.window_1.SplitVertically(self.window_1_pane_1, self.window_1_pane_2, BIB.SASH_KEYTREE)
            #self.window_1.SetSashPosition(BIB.SASH_KEYTREE)

    def __set_rw(self):
        """Delete keys and inactivate menu for read-write users"""
        self.bibframe1_menubar.Enable(self.IdFileImport,True)
        self.bibframe1_menubar.Enable(self.IdPubMedSearch,True)
        self.bibframe1_menubar.Enable(self.IdeTBlastSearch,True)
        self.toolbar.withPubMed()
        self.refDisplaypanel.ShowKeysPage()
        #self.keytree.keys_perso.Show()
        #self.keytree.keys_common.Show()
        #if not self.window_1.IsSplit():
        #    self.window_1_pane_1.Show()
        #    self.window_1.SplitVertically(self.window_1_pane_1, self.window_1_pane_2, BIB.SASH_KEYTREE)
            #self.window_1.GetSashPosition() )
            #self.window_1.SetSashPosition(BIB.SASH_KEYTREE)

    def set_grants(self):
        """Set settings according to db grants"""
        grants = self.keytree.getGrants()
        self.allowed = BIB.ALLOWED[grants]
        #print grants
        if grants == 'rw':                                # normal read-write user
            self.__set_rw()
        elif grants == 'ro':                            # normal read-only user with permissions to classify references
            self.__set_ro()
        elif grants == 'rk':                            # read-only with ro on keytree
            self.__set_rk()
        else:                                            # restricted read-only user
            self.__set_rr()
# end of grants settings

    def onMenuSelectAll(self,event):
        for i in xrange(self.reflist.GetItemCount()):
            self.reflist.Select(i)

    def onMenuPref(self,event):
        """Dialog for preferences"""
        #import Pref
        dpref = Pref.BibPref(self.db, self,-1,_("Preferences"))
        dpref.Show(True)
        
    def onMenuCleanDB(self,event):
        import CleanDB
        dlg = CleanDB.CleanDatabase(self.db,self)
        try:
            dlg.ShowModal()
            self.keytree.KeySelect(self.keytree.GetSelection())
        finally:
            dlg.Destroy()

    def updateRefList(self):
        """We update the view corresponding to the current key"""
        if not self.toolbar.searchtxt1.GetValue():
                self.keytree.KeySelect( self.keytree.GetSelection() )
        else:
            self.toolbar.onSearch(None)    # we update the view, taking into account current search

    def updateList(self,recordList):
        self.reflist.setList(recordList)
        self.bibframe1_statusbar.SetStatusText(_("%(total_number)s reference(s) : %(number_selected)s selected")%{'total_number':self.reflist.GetItemCount(),'number_selected':self.reflist.GetSelectedItemCount()},1)

# ----------------------------- Copy/Cut/Paste -----------------------------------------
    def __copyRefs(self):
        "Return in a  DnD.bibDataObject() the list of the selected references"
        item = self.keytree.GetSelection()
        oldkey_id,user,id = self.keytree.GetPyData(item)
        allowed=self.allowed[id]
        if allowed & BIB.REF_DRAG_OK:
            if id == BIB.ID_ONLINE_ROOT or id == BIB.ID_ONLINE:
                key = u'Online'
            elif id == BIB.ID_IMPORT_ROOT or id == BIB.ID_IMPORT:
                key = u'Import'
            else:
                key = u''
            #
            dragData = DnD.bibDragData(self.db.getDbInfo(key),BIB.DnD_REF)
            item = self.reflist.GetFirstSelected()
            if id == BIB.ID_IMPORT_ROOT:    # we are in the import list
                f = self.db.getRefImport
            elif id == BIB.ID_ONLINE_ROOT:    # we are in the online list
                f = self.db.getRefOnline
            else:                # we are in ref or query
                f = self.db.getRef
            while item != -1:
                dragData.append(tuple(apply(f,(self.reflist.GetItemData(item),BIB.BIB_FIELDS))[0]))
                # tuple is needed for sqlite since returned tuple is of class sqlite.main.PgResultSetConcreteClass
                item = self.reflist.GetNextSelected(item)
            mydrag = DnD.bibDataObject()
            mydrag.setObject(dragData)
            return mydrag
        else:
            return None

    def __formatRefsAsText_old(self,refList):
        """Return references in refList as a text"""
        tmp=[]
        for ref in refList:
            for field in BIB.BIB_FIELDS:
                if ref[BIB.BIBLIOGRAPHIC_FIELDS[field]] != '':                # non empty field
                    tmp.append( "%s: %s" %(BIB.NAME_FIELD[field],BIB.LIST_FIELD_FORMAT[field]( ref[BIB.BIBLIOGRAPHIC_FIELDS[field]] ) ) )
            tmp.append('')
        return '\n'.join(tmp)
        
    def onClipboardFormat(self,evt):
        BIB.TEXT_CLIPBOARD = self.bibframe1_menubar.GetLabel(evt.GetId())
    wx.NewId()
    def __formatRefsAsText(self,refList):
        """Return a references in refList as a text, formatted using an Export filter (refer, RIS, BibTeX, ..."""
        m = __import__('Export.%s'%BIB.TEXT_CLIPBOARD)
        m = getattr(m, BIB.TEXT_CLIPBOARD)
        text = StringIO.StringIO()
        exporter = m.exportRef(text)
        # writing record
        for ref in refList:
            exporter.write(ref)
        return text.getvalue()

    def __formatRefsAsHTML(self,refList):
        """Generate fromatted list of references according to the current OOo style"""
        text = StringIO.StringIO()
        text.write(u'<html>\n<head><META http-equiv="CONTENT-TYPE" content="text/html; charset=utf-8"></head>\n<body>\n')
        # exporter = html exporter
        exporter = Export.html.exportRef(text,BIB.FORMAT_DICO)
        for ref in refList:
            exporter.write(ref)
        text.write(u'</body>\n</html>')
        return text.getvalue()

    def onMenuCopy(self,event):
        "Copy list of the selected references. Return True on success for Cut"
        dragData = self.__copyRefs()
        if dragData and wx.TheClipboard.Open():
            mydrag = wx.DataObjectComposite()
            mydrag.Add(dragData,preferred=True)                                                # bibus format = preferred
            mydrag.Add(wx.TextDataObject(self.__formatRefsAsText(dragData.getObject()) ))        # text format
            mydrag.Add(DnD.HTMLDataObject(self.__formatRefsAsHTML(dragData.getObject()) ))    # html format
            wx.TheClipboard.SetData(mydrag)
            #wx.TheClipboard.Flush()    # needed if we want the data to be available on quit
            wx.TheClipboard.Close()
            self.set_menu(self.keytree.GetSelection())    # update menu to enable Paste if possible
            return True
        else:
            wx.TheClipboard.Close()
            return False

    def onMenuCut(self,event):
        item = self.keytree.GetSelection()
        oldkey_id,user,id = self.keytree.GetPyData(item)
        allowed=self.allowed[id]
        if allowed & BIB.REF_DEL_OK and self.onMenuCopy(event):
            # we delete the reference links
            self.onMenuDelRef(None)

    def onMenuPaste(self,event):
        item = self.keytree.GetSelection()
        newparentID,user,id = self.keytree.GetPyData(item)
        mydrag = DnD.bibDataObject()
        if wx.TheClipboard.Open() and wx.TheClipboard.GetData(mydrag):         # ask for data of the correct format
            #wx.TheClipboard.Close()
            refdragged = mydrag.getObject()
            if refdragged.format == BIB.DnD_REF:
                if refdragged.dbInfo == self.db.getDbInfo():
                    #""" The dropped data comes from the same database, table => just update the links"""
                    for ref in refdragged:
                        self.db.writeLink((newparentID,ref[0]))
                else:
                    #"""We can just copy and not move"""
                    for ref in refdragged:
                        Identifier = ref[BIB.BIBLIOGRAPHIC_FIELDS['Author']].split(',')[0].replace(' ',u'_')+ref[BIB.BIBLIOGRAPHIC_FIELDS['Year']]
                        ref = (None,Identifier)+ref[2:]
                        ref_id = self.db.writeRef(ref)
                        #self.db.modifyRef(('Identifier',),(BIB.SEP_DUP.join((ref[BIB.BIBLIOGRAPHIC_FIELDS['Identifier']],str(ref_id))),),ref_id)
                        if ref_id:
                            self.db.writeLink((newparentID,ref_id))
                #self.keytree.KeySelect(newparentID)
                self.updateList(self.db.getRefKey(newparentID,BIB.LIST_DISPLAY,BIB.LIST_ORDER,BIB.LIST_HOW,short=True))                    # update reference list
        wx.TheClipboard.Close()

# ----------------------------- File importing ------------------------------------------
    def onDownloadFilters(self,event):
        webbrowser.open("http://bibus-biblio.sourceforge.net/wiki/index.php/Import/Export_filters",new=1)
        
    def onMenuFilterInstall(self,event,typ='Import'):
        dlg = wx.FileSelector(_("Choose the %(type)s filter to install")%{'type':typ},\
                                default_extension = "py",\
                                wildcard = "Python Script (*.py)|*.py",\
                                flags = wx.FD_OPEN,\
                                parent = self)
        if dlg:
            shutil.copy(dlg,os.path.join(BIB.CONFIG.getFilePath(),typ))
            wx.MessageBox("Please restart bibus to make the filter available","Information",\
                            style = wx.OK|wx.ICON_INFORMATION,\
                            parent = self)

    def __getFile(self,question=_("Please choose the file encoding"),mode='r',enc='ascii'):
        """Get file and encoding. Return open file or None"""
        dlg = wx.FileDialog(self,_("Choose a File to import"),style = wx.FD_OPEN | wx.FD_CHANGE_DIR)
        try:
            answer = dlg.ShowModal()
            filename = dlg.GetPath()
        finally:
            dlg.Destroy()
        if answer == wx.ID_OK:
            if enc == None:
                return file(filename,mode)
            # ask for encoding. We put as default choice enc if it exists
            dlg = CodecChoice.CodecChoice(enc,self)
            try:
                answer = dlg.ShowModal()
                if answer == wx.ID_OK:
                    encod = dlg.getCodec()
                else:
                    encod = ''
            finally:
                dlg.Destroy()
            #
            if encod != u'':
                try:
                    f = codecs.open(filename,mode,encod)
                except LookupError:
                    f = open(filename,mode)
                    wx.LogError(_("Sorry but codec '%s' is not available.\nI will try to use ascii"%encod))
                return f
            else:
                return None
        else:
            return None

    def FileImport(self,mod,f):
        """ Import file, with conversion module mod
        Id = auto_generated by MySQL
        Identifier = AuthorYear => much more readable for insertion in OpenOffice than Id
        f = file or StringIO"""
        #
        if f != None:
            self.db.deleteImport()
            #if mod == "EndNoteXML":
            #    xmlImporter = m.importRef(f)
            #    records = xmlImporter.getLibrary()
            #else:records = m.importRef(f)
            for CurRecord in mod.importRef(f):
                #CurRecord = self.__newIdentifier(CurRecord)
                self.db.writeRefImport(CurRecord)
            f.close()
        self.keytree.KeySelect(self.keytree.keyImport)
        self.keytree.SelectItem(self.keytree.keyImport)

    def getImportModule(self,m,flag=True):
        if flag:
            im = __import__('Import')
            path = im.__path__
        else:
            path = [os.path.join(BIB.CONFIG.getFilePath(),'Import')]
        f, pathname, description = imp.find_module(m,path)
        return imp.load_module(m, f, pathname, description)

    def onMenuFileImport(self,event):
        m,flag = self.IdFileImportFilters[event.GetId()]
        mod = self.getImportModule(m,flag)
        #m = __import__('Import.%s'%mod)
        #m = getattr(m, mod)
        self.FileImport( mod, self.__getFile(enc=mod.DEFAULT_ENCODING))

    def onMenuFileImportText(self,event):
        """Open a window to paste then import text"""
        importf = ImportFrame.ImportFrame(self,-1,'')
        importf.Show(True)

# ----------------------------- End File importing ----------------------------------------

# --------------------------------- File Export --------------------------------------------
    def __saveFile(self,question=_("Please choose the file encoding"),mode='r',enc='latin_1'):
        """Get file and encoding. Return open file or None"""
        dlg = wx.FileDialog(self,_("Save as..."),style = wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT | wx.FD_CHANGE_DIR)
        try:
            answer = dlg.ShowModal()
            filename = dlg.GetPath()
        finally:
            dlg.Destroy()
        if answer == wx.ID_OK:
            # ask for encoding. We put as default choice enc if it exists
            dlg = CodecChoice.CodecChoice(enc,self)
            try:
                answer = dlg.ShowModal()
                if answer == wx.ID_OK:
                    encod = dlg.getCodec()
                else:
                    encod = ''
            finally:
                dlg.Destroy()
            #
            if encod != u'':
                try:
                    f = codecs.open(filename,mode,encod)
                except LookupError:
                    f = open(filename,mode)
                    wx.LogError(_("Sorry but codec '%s' is not available.\nI will try to use ascii"%encod))
                return f
            else:
                return None
        else:
            return None

    def __FileExport(self,mod,enc='latin_1'):
        """ export file, with conversion module mod"""
        # asking what we want to export
        ret = wx.GetSingleChoiceIndex(_('What do you want to export?'),_('Export'),[_('Selection'),_('Current key'),_('All')])
        if ret == -1: return
        # get the file destination
        f = self.__saveFile(_("Choose the destination file"),'w',enc)
        if f:
            # creating export converter
            exporter = mod.exportRef(f)
            # getting the references id to export
            refsId=[]
            if ret == 0:    # we export the selection
                item = self.reflist.GetFirstSelected()
                while item != -1:
                    refsId.append(self.reflist.GetItemData(item))
                    item = self.reflist.GetNextSelected(item)
            elif ret == 1:    # current key == reflist content
                for item in xrange(self.reflist.GetItemCount()):
                    refsId.append(self.reflist.GetItemData(item))
            else:            # the whole database
                tmprefs = self.db.getAllRef(self.keytree.user,collist=())
                refsId = [x[0] for x in tmprefs]
            # writing record
            for refId in refsId:
                ref = list(self.db.getRef(refId,BIB.BIB_FIELDS)[0])    # get the reference
                ref[BIB.BIBLIOGRAPHIC_FIELDS['URL']] = \
                                ref[BIB.BIBLIOGRAPHIC_FIELDS['URL']].replace("$FILES",BIB.FILES,1)
                exporter.write(ref)
            f.close()
            
    def onMenuFileExport(self,event):
        m,flag = self.IdFileExportFilters[event.GetId()]
        if flag:
            im = __import__('Export')
            path = im.__path__
        else:
            path = [os.path.join(BIB.CONFIG.getFilePath(),'Export')]
        f, pathname, description = imp.find_module(m,path)
        mod = imp.load_module(m, f, pathname, description)
        #m = __import__('Import.%s'%mod)
        #m = getattr(m, mod)
        self.__FileExport( mod, enc=mod.DEFAULT_ENCODING )

    def __saveFileHTML(self,question=_("Choose the destination file"),mode='w'):
        """Get file. Return open file or None"""
        dlg = wx.FileDialog(self,_("Save as..."),style = wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT | wx.FD_CHANGE_DIR)
        try:
            answer = dlg.ShowModal()
        finally:
            dlg.Destroy()
        if answer == wx.ID_OK:
            filename = dlg.GetPath()
            try:
                f = codecs.open(filename,mode,'utf_8')
            except LookupError:
                f = open(filename,mode)
                wx.LogError(_("Sorry but codec '%s' is not available.\nI will try to use ascii"%'utf_8'))
            return f
        else:
            return None

    def onMenuFileExportHtml(self,event):
        """ Export to an Html file with format """
        # asking what we want to export
        ret = wx.GetSingleChoiceIndex(_('What do you want to export?'),_('Export'),[_('Selection'),_('Current key'),_('All')])
        if ret == -1: return
        # get the file destination
        f = self.__saveFileHTML(_("Choose the destination file"),'w')
        if f:
            f.write(u'<html>\n<head><META http-equiv="CONTENT-TYPE" content="text/html; charset=utf-8"></head>\n<body>\n')
            # creating export converter
            exporter = Export.html.exportRef(f,BIB.FORMAT_DICO)
            # getting the references id to export
            refsId=[]
            if ret == 0:    # we export the selection
                item = self.reflist.GetFirstSelected()
                while item != -1:
                    refsId.append(self.reflist.GetItemData(item))
                    item = self.reflist.GetNextSelected(item)
            elif ret == 1:    # current key == reflist content
                for item in xrange(self.reflist.GetItemCount()):
                    refsId.append(self.reflist.GetItemData(item))
            else:            # the whole database
                tmprefs = self.db.getAllRef(self.keytree.user,collist=())
                refsId = [x[0] for x in tmprefs]
            # writing record
            for refId in refsId:
                ref = self.db.getRef(refId,BIB.BIB_FIELDS)[0]    # get the reference
                exporter.write(ref)
            f.close()

    def onMenuFileExportSQLite(self,event):
        """ Export to a sqlite database """
        # asking what we want to export
        ret = wx.GetSingleChoiceIndex(_('What do you want to export?'),_('Export'),[_('Selection'),_('Current key'),_('All')])
        if ret == -1: return
        # get the file destination
        answer = wx.FileSelector(_("Choose the name of the SQLite database"), flags = wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT | wx.FD_CHANGE_DIR )
        if answer == '': return
        # we create the database
        try:
            import dbBibSQLite
            savedFile = BIB.SQLiteFile
            BIB.SQLiteFile = answer
            # we delete the old file if it exists
            if os.path.exists( answer ):
                os.remove( answer )
            #
            db = dbBibSQLite.dbBib()
            db.createDatabase(answer,BIB.DB_TABLE_REF,BIB.DB_TABLE_KEY,BIB.DB_TABLE_LINK,BIB.DB_TABLE_QUERY,BIB.DB_TABLE_MODIF)
            #
            refsId=[]
            if ret == 0:    # we export the selection
                item = self.reflist.GetFirstSelected()
                while item != -1:
                    refsId.append(self.reflist.GetItemData(item))
                    item = self.reflist.GetNextSelected(item)
            elif ret == 1:    # current key == reflist content
                for item in xrange(self.reflist.GetItemCount()):
                    refsId.append(self.reflist.GetItemData(item))
            else:            # the whole database
                tmprefs = self.db.getAllDatabase(collist=())
                refsId = [x[0] for x in tmprefs]
            # writing records
            for refId in refsId:
                db.writeRef( self.db.getRef(refId,BIB.BIB_FIELDS)[0] )
            # we copy the rest of the database only if we export everything
            if ret == 2:
                # now we copy the keys
                for key in self.db.getAllKeys():
                    db.dumpKey( key )
                # now the Links
                for link in self.db.getAllLinks():
                    db.writeLink( link )
                # then the queries
                for query in self.db.getAllQueries():
                    db.dumpQuery( query )
                # modifs
                for modif in self.db.getAllModifs():
                    apply( db.resetCreator, modif )
                # files
                for filen in db_old.getAllFiles():
                    db.setCreator( filen )
            #
            BIB.SQLiteFile = savedFile
        except ImportError:
            wx.LogError(_("""Sorry, but I was not able to find the python module for the %s database.\nPlease check your installation""")%'SQLite')
            return

# ----------------------------- End File exporting ----------------------------------------

    def __newIdentifier(self,record):
        """Add an Identifier to a record. Identifier = AuthorYear where Author is the first author name.
        Spaces are also replaced by _"""
        record[BIB.BIBLIOGRAPHIC_FIELDS['Identifier']] = record[BIB.BIBLIOGRAPHIC_FIELDS['Author']].split(',')[0].replace(' ','_')+record[BIB.BIBLIOGRAPHIC_FIELDS['Year']]
        return record

    def onMenuPubMedSearch(self,event):
        #self.db.deleteOnline()
        search = SearchMedline.SearchMedline(self.db,self,-1,u'')
        search.Show(True)

    def onMenuSearch(self,event):
        search = Search.Search(self,self,-1,u'')
        search.Show(True)

    def onMenueTBlastSearch(self,event):
        #print "EtBlastSearch"
        #self.db.deleteOnline()
        search = SearcheTBlast.SearcheTBlast(self.db,self,-1,u'')
        search.Show(True)

# -----------------------------------------------------------------------------------------------------------------
# -------------------------------------- Printing support ---------------------------------------------------------
# -----------------------------------------------------------------------------------------------------------------
    def __getRef(self):
        keytype = self.keytree.getKeyType()
        if keytype == 'db':
            return self.db.getRef
        elif keytype == 'online':
            return self.db.getRefOnline
        elif keytype == 'import':
            return self.db.getRefImport
        else:
            print "What are we doing here ? BibFrame.__getRef"
            
    def generateHTML(self):
        """Return a HTML string = Formatted selected references"""
        # Setting the header
        BIB.PRINTER.SetHeader( """%s<hr size="2">""" % self.db.getDbDescription() )
        BIB.PRINTER.SetFooter( """<hr size="2"><center><font size="-2">@PAGENUM@/@PAGESCNT@</font></center>""" )
        # we get the references to print.
        # if 1 or more references are selected, we use the selection
        # if no selection, we print all the reference in the current refList
        text = StringIO.StringIO()
        refsId=[]
        item = self.reflist.GetFirstSelected()
        if item != -1:                    # at least 1 selection
            while item != -1:
                refsId.append(self.reflist.GetItemData(item))
                item = self.reflist.GetNextSelected(item)
        else:
            for item in xrange(self.reflist.GetItemCount()):
                refsId.append(self.reflist.GetItemData(item))
        #
        text.write(u'<html>\n<head><META http-equiv="CONTENT-TYPE" content="text/html; charset=utf-8"></head>\n<body>\n')
        # <meta http-equiv="CONTENT-TYPE" content="text/html; charset=utf-8">\n')
        getRef = self.__getRef()
        for refId in refsId:
            ref = apply(getRef,(refId,BIB.BIB_FIELDS))    # get the reference
            for field in BIB.PRINTER_FORMAT[BIB.BIB_TYPE[int(ref[0][2])]]:
                text.write(
                u"""%s%s%s <FONT COLOR=#%s>%s: </FONT>%s%s%s%s%s%s<FONT COLOR=#%s>%s</FONT>%s%s%s<br>\n""" %
                ( '<b>'*BIB.PRINTER_STYLE[0][0], '<i>'*BIB.PRINTER_STYLE[0][1], '<u>'*BIB.PRINTER_STYLE[0][2],
                 BIB.PRINTER_COLORS[0],BIB.NAME_FIELD[field],
                '</b>'*BIB.PRINTER_STYLE[0][0], '</i>'*BIB.PRINTER_STYLE[0][1], '</u>'*BIB.PRINTER_STYLE[0][2],
                '<b>'*BIB.PRINTER_STYLE[1][0], '<i>'*BIB.PRINTER_STYLE[1][1], '<u>'*BIB.PRINTER_STYLE[1][2],
                BIB.PRINTER_COLORS[1],apply(BIB.LIST_FIELD_FORMAT[field],(ref[0][BIB.BIBLIOGRAPHIC_FIELDS[field]],) ),
                '</b>'*BIB.PRINTER_STYLE[1][0], '</i>'*BIB.PRINTER_STYLE[1][1], '</u>'*BIB.PRINTER_STYLE[1][2] )
                )
                 #
            text.write( u"<p>\n" )
        text.write(u'</body>\n</html>')
        return text.getvalue()

    def generateFormattedHTML(self):
        """Generate fromatted list of references accordinf to the current OOo style"""
        # Setting the header
        BIB.PRINTER.SetHeader( """%s<hr size="2">""" % self.db.getDbDescription() )
        BIB.PRINTER.SetFooter( """<hr size="2"><center><font size="-2">@PAGENUM@/@PAGESCNT@</font></center>""" )
        # we get the references to print.
        # if 1 or more references are selected, we use the selection
        # if no selection, we print all the reference in the current refList
        text = StringIO.StringIO()
        refsId=[]
        item = self.reflist.GetFirstSelected()
        if item != -1:                    # at least 1 selection
            while item != -1:
                refsId.append(self.reflist.GetItemData(item))
                item = self.reflist.GetNextSelected(item)
        else:
            for item in xrange(self.reflist.GetItemCount()):
                refsId.append(self.reflist.GetItemData(item))
        #
        text.write(u'<html>\n<head><META http-equiv="CONTENT-TYPE" content="text/html; charset=utf-8"></head>\n<body>\n')
        # exporter = html exporter
        exporter = Export.html.exportRef(text,BIB.FORMAT_DICO)
        getRef = self.__getRef()
        for refId in refsId:
            ref = apply(getRef,(refId,BIB.BIB_FIELDS))[0]    # get the reference
            exporter.write(ref)
        text.write(u'</body>\n</html>')
        return text.getvalue()

    def onMenuFilePageSetup(self,event):
        BIB.PRINTER.PageSetup()

    def onMenuFilePrintPreview(self,event):
        if BIB.PRINTER_USE_OOo_FORMAT:
            text = self.generateFormattedHTML()
        else:
            text = self.generateHTML()
        BIB.PRINTER.PreviewText(text)

    def onMenuFilePrint(self,event):
        if BIB.PRINTER_USE_OOo_FORMAT:
            text = self.generateFormattedHTML()
        else:
            text = self.generateHTML()
        BIB.PRINTER.PrintText(text)

# -----------------------------------------------------------------------------------------------------------------
# ------------------- functions for formatting modules (needed only if pyuno installed) ---------------------------
# -----------------------------------------------------------------------------------------------------------------
    def __setStartingConverter(self):
        current = BIB.CONFIG.getCurrentStyle()
        for k,val in BIB.STYLES.iteritems():
            if val == current:
                self.selectStyle(k)
                return
        # we did not find the style saved as current in the config file/registry
        try:
            k = BIB.STYLES.keys()[0]    # we take the first key
            self.selectStyle(k)
            return
        except:
            #"No possible selection. Empty menu ?"
            BIB.STYLE_CURRENT = u''
            BIB.CONFIG.writeCurrentStyle(BIB.STYLE_CURRENT)
            self.bibframe1_statusbar.SetStatusText('',2)
            return

    def __installStylesFromDir(self,directory):
        tmp = os.listdir( directory )
        tmp.sort()
        for style in tmp:
            MenuId = wx.NewId()
            BIB.STYLE_MENU.AppendRadioItem(MenuId, style, u"")
            BIB.STYLES[MenuId] = os.path.join(directory,style)
            wx.EVT_MENU(self, MenuId, self.__selectStyle)

    def __setStyleMenu(self):
        """Populate the Style menu
            1) from the Style directory
            2) from files saved by the user and registered in the Configuration file
            """
        self.__installStylesFromDir( os.path.join(BIB.SOURCEDIR,'Format','Styles') )
        if  wx.Platform != '__WXMSW__':        # does not work under Windows since it
            BIB.STYLE_MENU.AppendSeparator()    # would start a new radio group
        # User styles
        self.__installStylesFromDir( os.path.join( wx.StandardPaths.Get().GetUserDataDir(), "Styles") )

    def selectStyle(self,menuId):
        # we select and load the style
        BIB.STYLE_MENU.Check(menuId,True)
        f = open(BIB.STYLES[menuId],'rb')
        BIB.FORMAT_DICO = StyleEditor.Styleconverter.style_convert( cPickle.load(f) )
        f.close()
        BIB.STYLE_CURRENT = BIB.STYLES[menuId]
        BIB.CONFIG.writeCurrentStyle(BIB.STYLE_CURRENT)        # save choice in config file
        self.bibframe1_statusbar.SetStatusText(os.path.basename(BIB.STYLE_CURRENT),2)

    def __selectStyle(self,evt):
        f = open(BIB.STYLES[evt.Id],'rb')
        try:
            BIB.FORMAT_DICO = StyleEditor.Styleconverter.style_convert( cPickle.load(f) )
            f.close()
            BIB.STYLE_CURRENT = BIB.STYLES[evt.Id]
            BIB.CONFIG.writeCurrentStyle(BIB.STYLE_CURRENT)        # save choice in config file
            self.bibframe1_statusbar.SetStatusText(os.path.basename(BIB.STYLE_CURRENT),2)    # status bar
            self.refDisplaypanel.resetFormat(BIB.FORMAT_DICO)                    # select the style for display
        except:
            wx.LogError(_("The selected style is not a bibus style"))
            BIB.STYLE_MENU.Delete(evt.Id)
            BIB.CONFIG.deleteStyle(BIB.STYLES[evt.Id])

# -------------------------------------------------------------------------------------------------------
# ----------------------------------- Utility to switch between OOo and Word ----------------------------
# -------------------------------------------------------------------------------------------------------
    def __loadConnectionModule(self):
        """importing the necessary connection module. OOo or mswDoc"""
        global OOo
        global mswDoc
        global lyx_remote
        if BIB.WP == 'OOo':
            try:
                if hasattr(self,'mswDoc'): del self.mswDoc
                if hasattr(self,'OOo'): del self.OOo
                if hasattr(self,'lyx_remote'): del self.lyx_remote
                if hasattr(self,'doc'): del self.doc # this is to drop the connection and force new settings
                import OOo
            except ImportError:
                BIB.WP = ''
        elif BIB.WP == 'mswDoc':
            try:
                if hasattr(self,'mswDoc'): del self.mswDoc
                if hasattr(self,'OOo'): del self.OOo
                if hasattr(self,'lyx_remote'): del self.lyx_remote
                global newProgressWin,time
                import mswDoc
                import newProgressWin
                import time
            except ImportError:
                BIB.WP = ''
        elif BIB.WP == 'Lyx':
            try:
                if hasattr(self,'mswDoc'): del self.mswDoc
                if hasattr(self,'OOo'): del self.OOo
                if hasattr(self,'lyx_remote'): del self.lyx_remote
                import lyx_remote
            except ImportError:
                BIB.WP = ''           

    def switchConnectionMenu(self):
        """Activate the connection Menu corresponding to the choice in BIB.WP"""
        self.__loadConnectionModule()
        if BIB.WP == 'OOo':
            tmp_menu = self.__setOOoMenu()
            if self.WP_id != None:
                self.bibframe1_menubar.Replace(self.WP_id,tmp_menu,_("OpenOffice.org"))
            else:
                ret = self.bibframe1_menubar.Insert(5,tmp_menu,_("OpenOffice.org"))
                if ret: self.WP_id = 5
        elif BIB.WP == 'mswDoc':
            tmp_menu = self.__setWordMenu()
            if self.WP_id != None:
                self.bibframe1_menubar.Replace(self.WP_id,tmp_menu,_("MSWord"))
            else:
                ret = self.bibframe1_menubar.Insert(5,tmp_menu,_("MSWord"))
                if ret: self.WP_id = 5
        elif BIB.WP == 'Lyx':
            tmp_menu = self.__setLyxMenu()
            if self.WP_id != None:
                self.bibframe1_menubar.Replace(self.WP_id,tmp_menu,_("LyX"))
            else:
                ret = self.bibframe1_menubar.Insert(5,tmp_menu,_("LyX"))
                if ret: self.WP_id = 5
        elif self.WP_id != None:
            self.bibframe1_menubar.Remove(self.WP_id)
            self.WP_id = None

# -------------------------------------------------------------------------------------------------------
# ------------------------------------------ Lyx Menu ---------------------------------------------------
# -------------------------------------------------------------------------------------------------------
    def __setLyxMenu(self):
        def __identifiers():
            key_id,user,id = self.keytree.GetPyData(self.keytree.GetSelection())
            allowed = self.allowed[id]
            identifiers = []
            if allowed & BIB.REF_DRAG_OK:
                item = self.reflist.GetFirstSelected()
                while item != -1:
                    identifiers.append( self.reflist.GetItemText(item) )
                    item = self.reflist.GetNextSelected(item)
            return identifiers
    
        def onMenuCopyId(event):
            identifiers = __identifiers()
            if identifiers:
                if wx.TheClipboard.Open():
                    wx.TheClipboard.Clear()
                    wx.TheClipboard.SetData(wx.TextDataObject( "\cite{%s}" %','.join(identifiers) ))
                wx.TheClipboard.Close()
                
        def onMenuLyxInsert(event):
            identifiers = __identifiers()
            if identifiers:
                lyx_remote.bibusLyx().insert( ','.join(identifiers) )
        
        
        self.IdLyxInsert = wx.NewId()
        self.IdCopyCite = wx.NewId()
        wxglade_tmp_menu = wx.Menu()
        wxglade_tmp_menu.Append(self.IdLyxInsert, _("Insert in LyX")+"\tCtrl-%s"%BIB.KEY_OO_INSERT, u"")
        wxglade_tmp_menu.Append(self.IdCopyCite, _("Insert in Clipboard")+"\tCtrl-Alt-%s"%BIB.KEY_COPYID)
        wx.EVT_MENU(self,self.IdLyxInsert,onMenuLyxInsert)
        wx.EVT_MENU(self,self.IdCopyCite,onMenuCopyId)
        return wxglade_tmp_menu

# -------------------------------------------------------------------------------------------------------
# ------------------------------------------ OpenOffice.org Menus ---------------------------------------
# -------------------------------------------------------------------------------------------------------
        # Setting OOo menu.
    def __setOOoMenu(self):
        # Menu OOo
        self.IdOOoInsert = wx.NewId()
        self.IdOOoAutoUpdate = wx.NewId()    # MenuCheck if index must be updated on Insert
        self.OOoAutoUpdate = BIB.OO_AUTO_UPDATE
        self.IdOOoFormat = wx.NewId()
        self.IdOOoGoToWriter = wx.NewId()
        self.IdOOoFinalize = wx.NewId()
        self.IdOOoHilightCitations = wx.NewId()
        self.OOoHilightCit = BIB.OO_HILIGHT    # set to true if self.IdOOoHilightCitations IsChecked = Hilight citations in OOo
        self.IdOOoCreateBib = wx.NewId()
        self.OOoCreateBib = BIB.OO_CREATE_BIB    # auto create bib if needed
        self.IdOOoCaptureCitations = wx.NewId()
        #
        wxglade_tmp_menu = wx.Menu()
        wxglade_tmp_menu.Append(self.IdOOoInsert, _("Insert Citation")+"\tCtrl-%s"%BIB.KEY_OO_INSERT, u"")
        wxglade_tmp_menu.Append(self.IdOOoFormat, _("Format Bibliography")+"\tCtrl-%s"%BIB.KEY_OO_FORMAT, u"")
        wxglade_tmp_menu.Append(self.IdOOoGoToWriter, _("GoTo Writer")+"\tCtrl-%s"%BIB.KEY_OO_GOWRITER, u"")
        wxglade_tmp_menu.Append(self.IdOOoFinalize, _("Finalize"), _("Finalize the document"))
        wxglade_tmp_menu_sub = wx.Menu()
        wxglade_tmp_menu_sub.AppendSeparator()
        wxglade_tmp_menu.Append(self.IdOOoAutoUpdate, _("Update Index on Insert"), _("Update the Bibliography automatically"),wx.ITEM_CHECK)
        wxglade_tmp_menu.Append(self.IdOOoCreateBib, _("Create Index on Insert"), _("Create the Bibliography if absent"),wx.ITEM_CHECK)
        wxglade_tmp_menu.Append(self.IdOOoHilightCitations, _("Hilight Citations"), _("Hilight citations with a yellow background"),wx.ITEM_CHECK)
        wxglade_tmp_menu.Append(self.IdOOoCaptureCitations, _("Capture Citations"),_("Capture the references absent from the database"))
        # setting events
        wx.EVT_MENU(self,self.IdOOoInsert,self.onMenuOOoInsert)
        wx.EVT_MENU(self,self.IdOOoAutoUpdate,self.onMenuOOoAutoUpdate)
        wx.EVT_MENU(self,self.IdOOoCreateBib,self.onMenuOOoCreateBib)
        wx.EVT_MENU(self,self.IdOOoFormat,self.onMenuOOoFormat)
        wx.EVT_MENU(self,self.IdOOoGoToWriter,self.onMenuOOoGoToWriter)
        wx.EVT_MENU(self,self.IdOOoFinalize,self.onMenuOOoFinalize)
        wx.EVT_MENU(self,self.IdOOoHilightCitations,self.onMenuOOoHilightCit)
        wx.EVT_MENU(self,self.IdOOoCaptureCitations,self.onMenuOOoCaptureCit)
        return wxglade_tmp_menu

    def __connectToWriter(self):
        """Try to connect to a open Writer document and return True if OK"""
        try:
            self.doc.connectToWriter(BIB.FORMAT_DICO,self.OOoHilightCit,BIB.OO_HILIGHT_COLOR,self.OOoCreateBib)    # we test if the connection is up
        except (AttributeError, OOo.bibOOo_NoConnect):
            try:
                self.doc = OOo.bibusOOo(self.db)    # connection to OOo
                self.doc.connectToWriter(BIB.FORMAT_DICO,self.OOoHilightCit,BIB.OO_HILIGHT_COLOR,self.OOoCreateBib)    # connection to OOo writer document
            except OOo.bibOOo_NoConnect,e:
                wx.LogError(_("""Cannot connect to Openoffice. See Documentation.\n%s\n%s)""") % (e.msg,e.OOo))
                return False
        return True

    def onMenuOOoInsert(self,event):
        """Inserted the selected reference in OOo. Possible only if the references are in All, Ref+children or query"""
        if not self.__connectToWriter(): return
        #
        item = self.keytree.GetSelection()
        id = self.keytree.GetPyData(item)[2]
        if id in (BIB.ID_REF,BIB.ID_REF_ROOT,BIB.ID_REF_ALL,BIB.ID_QUERY,BIB.ID_CITED,BIB.ID_TAGGED):
            item = self.reflist.GetFirstSelected()
            while item != -1:
                # ref = list(self.db.getRef(self.reflist.GetItemData(item),BIB.BIB_FIELDS[1:-1])[0])
                # list is needed for sqlite since returned tuple is of class sqlite.main.PgResultSetConcreteClass
                # ooref = self.doc.formatRef(None,ref)    # we first create and format the ref
                ooref = self.doc.formatRef( None, self.db.getRef(self.reflist.GetItemData(item),BIB.BIB_FIELDS[1:-1])[0] )
                self.doc.insertRef(ooref)        # we insert the ref in OOo
                item = self.reflist.GetNextSelected(item)
        if self.OOoAutoUpdate:
            try: self.doc.bib.update()
            except AttributeError: pass        # if self.doc.bib == None

    def onMenuOOoAutoUpdate(self,event):
        """Check menu. If checked, index is updated on insert"""
        self.OOoAutoUpdate = event.IsChecked()

    def onMenuOOoCreateBib(self,event):
        """Check menu. If checked, index is create on insert"""
        self.OOoCreateBib = event.IsChecked()

    def onMenuOOoFormat(self,event):
        """Reload references from the databases + update index"""
        if not self.__connectToWriter(): return
        self.doc.updateRef()    # we update all the ref form the db
        self.doc.updateIndex()

    def onMenuOOoGoToWriter(self,event):
        """Give focus to Writer doc"""
        if not self.__connectToWriter(): return
        self.doc.activate()

    def onMenuOOoFinalize(self,event):
        """Just to help to format Author-date before Bibus 1.0"""
        if not self.__connectToWriter(): return
        self.doc.finalize()

    def addUserStyle(self,style):
        """Add a style in the menu and return its Id"""
        # we first look if the style is already in the menu
        for menuId,filename in BIB.STYLES.iteritems():
            if filename == style:
                break
        else:
            # the file is not in the menu
            menuId = wx.NewId()
            BIB.STYLE_MENU.AppendRadioItem(menuId, os.path.basename(style), u"")
            BIB.STYLES[menuId] = style
            wx.EVT_MENU(self, menuId, self.__selectStyle)
        return menuId

    def __StyleEdit(self,filename,conv):
        import StyleEditor.FormatEditor
        editor = StyleEditor.FormatEditor.FormatEditor(self,-1,_('References formatting'),filename=filename,conv=conv)
        try:
            ret = editor.ShowModal()
            if ret == wx.ID_SAVE:    # we must reload the style because it may have changed
                try:
                    f = file( BIB.STYLE_CURRENT )
                    BIB.FORMAT_DICO = StyleEditor.Styleconverter.style_convert( cPickle.load(f) )
                    f.close()
                except:
                    wx.LogError(_("The selected style is not a bibus style"))
            elif ret == wx.ID_SAVEAS:
                filename = editor.getFileName()
                menuId = self.addUserStyle(filename)
                self.selectStyle(menuId)
        finally:
            editor.Destroy()
            self.refDisplaypanel.resetFormat(BIB.FORMAT_DICO)    # we reload the format for display

    def onMenuOOoStyleNew(self,event):
        """OOo style creation"""
        self.__StyleEdit('', None)

    def onMenuOOoStyleEdit(self,event):
        """OOo style editing"""
        filename = BIB.STYLE_CURRENT
        if os.path.dirname(filename) != os.path.join(BIB.SOURCEDIR,'Format','Styles'):
            self.__StyleEdit(filename, copy.deepcopy(BIB.FORMAT_DICO))
        else:
            wx.LogMessage(_('You cannot edit default styles\n.I have made a copy of the style for editing'))
            self.__StyleEdit('', copy.deepcopy(BIB.FORMAT_DICO))

    def onMenuOOoStyleLoad(self,event):
        """Load a style from the disk"""
        filename = wx.FileSelector(_("Please select a style file"))
        if filename:
            f = file(filename)
            basename = cPickle.load(f)['info']['name']
            f.close()
            newfilename = os.path.join( wx.StandardPaths.Get().GetUserDataDir(), "Styles", basename )
            shutil.copyfile( filename, newfilename)
            menuId = self.addUserStyle(newfilename)
            self.selectStyle(menuId)
            self.refDisplaypanel.resetFormat(BIB.FORMAT_DICO)    # we reload style for display
            
    def onMenuOOoStyleDownload(self,event):
        """Open the wiki page with user contributed styles"""
        webbrowser.open("http://bibus-biblio.sourceforge.net/wiki/index.php/Styles_repository",new=1)

    def __showIdentifiersInAll(self,Identifiers,short=False):
        """Identifiers is a list of Identifier. Display them in key 'All' as an expertSearch"""
        query,refs = self.__Identifiers2References(Identifiers, order = BIB.LIST_ORDER, short=short)
        #print  BIB.LIST_ORDER,BIB.LIST_HOW
        self.keytree.KeySelect(self.keytree.keyAll)                                # select key 'All'
        self.keytree.SelectItem(self.keytree.keyAll)
        self.updateList(refs)                                    # display the result
        self.toolbar.displaySearch(query)                        # update the toolbar query text

    def __Identifiers2References(self,Identifiers,order,short=False):
        """Identifiers is a list of Identifier. Return a List of references."""
        if Identifiers:
            Identifiers2 = [    """Identifier='%s'""" % x.replace("'","''") for x in Identifiers ] # we replace single ' by ''
            query = " OR ".join(Identifiers2)
            #query = ((""" OR Identifier='%s'"""*len(Identifiers)) %tuple(Identifiers))[4:]
        else:
            query = "NULL"
        return query,self.db.getAllRefSearch( self.keytree.user, query , BIB.LIST_DISPLAY, order, BIB.LIST_HOW, short)
        
    def onMenuOOoSelectCit(self,event):
        """Select the references cited in the current OOo document"""
        if not self.__connectToWriter(): return
        citations = [ref.Identifier for ref in self.doc]
        self.__showIdentifiersInAll(citations,short=True)

    def OOoSelectCit(self,order,short=False):
        """Return list of references cited in the current OOo document"""
        if not self.__connectToWriter(): return ()
        citations = [ref.Identifier for ref in self.doc]
        return     self.__Identifiers2References(citations,order,short)[1]

    def onMenuOOoCaptureCit(self,event):
        """Capture the references cited in the current OOo document
        if they are not present in the current database
        eventually rename them to be of the form
        Identifier=AuthorYear#Id
        Then update the current OOo document accordingly"""
        if not self.__connectToWriter(): return
        citations = self.doc.storeUnknownRef()
        self.__showIdentifiersInAll(citations)

    def onMenuOOoHilightCit(self,event):
        """Set the bibus_citation_base style to background=yellow"""
        if event.IsChecked():
            self.OOoHilightCit = True
        else:
            self.OOoHilightCit = False
        if not self.__connectToWriter():
            return
        else:
             self.doc.resetCitationStyle()

# ------------------------------
# -----------Tools (currently placed under File menu)
# ------------------------------
    def doBackup(self,evt):
        import backupUserData
        from wx.lib.dialogs import messageDialog

        userDataDir = wx.StandardPaths.Get().GetUserDataDir()
        userDocsDir = wx.StandardPaths.Get().GetDocumentsDir()

        msgstr = '''WARNING! This procedure ONLY archives style files and databases stored in the local user data folder.\n
Local user data folder: '''+userDataDir
        dlg = messageDialog(self, msgstr, _('Archive warning!'), wx.OK | wx.ICON_EXCLAMATION)

        arcstarttime=time.time()
        archivename=time.strftime('bibusbackup_%y%m%d_%H%M%S.tar', time.localtime(arcstarttime))
        dlg = wx.FileDialog(self,_("Archive all user data into file ..."),style = wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT | wx.FD_CHANGE_DIR)
        dlg.SetDirectory(userDocsDir)
        dlg.SetFilename(archivename)
        dlg.SetWildcard("TAR archive (*.tar)|*.tar")        
        try:
            answer = dlg.ShowModal()
            filename = dlg.GetPath()
        finally:
            dlg.Destroy()
        # print answer, filename
        if answer == wx.ID_OK:
            backupPathname = filename
            backupUserData.backup2tar(userDataDir,backupPathname)

    def doRestore(self,evt):
        import backupUserData
        from wx.lib.dialogs import messageDialog,scrolledMessageDialog

        userDataDir = wx.StandardPaths.Get().GetUserDataDir()
        userDocsDir = wx.StandardPaths.Get().GetDocumentsDir()

        msgstr = '''Bibus can restore files from an archive file for you. Or you can do it by hand (recommended).\n
\nTo do it by hand (which gives more control and flexibility):\n
Open the user data archive file using an appropriate archive manager (Double-clicking the file may work).\n
Extract the files you want to restore to the corresponding sub-folders in\n'''+userDataDir+'''\n
\n
Click OK to let Bibus restore archived user data from a file.\n
Otherwise, click Cancel.'''
        dlg = messageDialog(self, msgstr, _('Restore user data from archive'), wx.OK | wx.CANCEL | wx.ICON_EXCLAMATION)
        if not (dlg.returned==wx.ID_OK):
            return

        arcPathname = wx.FileSelector(message=_('Bibus user data archive file'), default_path=userDocsDir, wildcard="TAR archive (*.tar)|*.tar|Any file (*)|*")
        # print arcPathname
        if (arcPathname != ''):
            retmsg = backupUserData.restore_tar(arcPathname,userDataDir)
        else:
            retmsg = 'Operation cancelled by user...'

        msgstr=retmsg
        dlg = scrolledMessageDialog(self, msgstr, _('Archive restore'))
        
    def switchWP(self,evt):
        wp = self.bibframe1_menubar.GetLabel(evt.GetId())
        if wp == "OpenOffice.org":
            BIB.WP = "OOo"
        elif wp == "Word":
            BIB.WP = "mswDoc"
        elif wp == "LyX":
            BIB.WP = "Lyx"
        else:
            BIB.WP = ""
        self.switchConnectionMenu()
# ------------------------------------------------------------------------------------------------------------------
# -------------------------------------------------- Help menu -----------------------------------------------------
# ------------------------------------------------------------------------------------------------------------------
    def showHelp(self,evt):
        if os.path.exists(BIB.DOCPATH):
            webbrowser.open(BIB.DOCPATH,new=1)

    def showLicense(self,evt):
        from wx.lib.dialogs import ScrolledMessageDialog
        if os.path.exists(BIB.LICENCEPATH):
            f=open(BIB.LICENCEPATH,'r')
            dlg = ScrolledMessageDialog(self, f.read(), _('License'))
            f.close()
            try:
                    dlg.ShowModal()
            finally:
                    dlg.Destroy()

    def showWebSite(self,evt):
        webbrowser.open("http://bibus-biblio.sourceforge.net/",new=1)

    def firstTimeWizard(self,evt):
        import FirstStart.FirstStart
        dlg = FirstStart.FirstStart.FirstStart(self)            # help to setup a sqlite database
        try:                                        # not possible for mysql
            dlg.Run()
        finally:
            dlg.Destroy()
        #
        self.switchConnectionMenu()            # we switch the menu from OOo/word/nothing if needed
        # select the correct module for database
        try:
            BIB.DB_MODULE = __import__('dbBib'+BIB.DB_TYPE)
            getattr(BIB.DB_MODULE,'dbBib')    # if the module was loaded before, re-importing won't raise ImportError. We must check directly if it works
        except (ImportError,AttributeError):
            BIB.DB_MODULE = None
            wx.LogError(_("""Sorry, but I was not able to find the python module for the %s database.\nPlease check your installation""")%BIB.DB_TYPE)
        self.autoConnect()                        # connect to the new database

    def showAbout(self,evt):
        from wx.lib.dialogs import messageDialog
        msgstr='Bibus\nby Pierre Martineau & the Bibus Team\n\
version '+BIB.BIBUS_VERSION
        dlg = messageDialog(self, msgstr, _('About'), wx.OK)

    def showError(self,message=u''):
        wx.LogError(message)
        #dlg=wx.MessageDialog(self, message, caption = u"Error", style = wx.OK | wx.CENTRE | wx.ICON_ERROR, pos = wx.DefaultPosition)
        #try:
        #    dlg.ShowModal()
        #finally:
        #    dlg.Destroy()
# ------------------------------------------------------------------------------------------------------------------
# -------------------------------------------------- MSWORD menu -----------------------------------------------------
# ------------------------------------------------------------------------------------------------------------------
    def    __setWordMenu(self):
        # setting mswWord menu if needed
        self.IdMSWInsert = wx.NewId()
        self.IdMSWCreateBiblio = wx.NewId()
        self.IdMSWPrintConvInfo = wx.NewId()
        self.IdMSWFormatBiblio = wx.NewId()
        self.IdMSWFinalize = wx.NewId()
        self.IdMSWUpdateCitation=wx.NewId()
        self.IdMSWPreFormatCitation=wx.NewId()
        self.IdMSWPrintConvInfo=wx.NewId()
        self.IdMSWPreAll=wx.NewId()
        wxglade_tmp_menu = wx.Menu()
        wxglade_tmp_menu.Append(self.IdMSWInsert,_("Insert Citation")+"\tCtrl-%s"%BIB.KEY_OO_INSERT,u"")
        wxglade_tmp_menu.Append(self.IdMSWUpdateCitation,_("Update Citations"),u"")
        wxglade_tmp_menu.AppendSeparator()
        wxglade_tmp_menu.Append(self.IdMSWFormatBiblio,_("Update Bibliographic Index")+"\tCtrl-%s"%BIB.KEY_OO_FORMAT,u"")
        wxglade_tmp_menu.AppendSeparator()
        wxglade_tmp_menu.Append(self.IdMSWPreAll,_("Update and Pre-format all..."),u"")
        wxglade_tmp_menu.Append(self.IdMSWFinalize,_("Finalize..."),u"")
        #wxglade_tmp_menu.AppendSeparator()
        #wxglade_tmp_menu.Append(self.IdMSWPrintConvInfo,_("Debug Info"),u"")
        # setting events
        wx.EVT_MENU(self,self.IdMSWInsert,self.onMenuMSWInsert)
        wx.EVT_MENU(self,self.IdMSWFormatBiblio,self.onMenuMSWFormatBiblio)
        wx.EVT_MENU(self,self.IdMSWUpdateCitation,self.onMenuMSWUpdateCitation)
        wx.EVT_MENU(self,self.IdMSWPreAll,self.onMenuPreAll)
        wx.EVT_MENU(self,self.IdMSWFinalize,self.onMenuMSWFinalize)
        wx.EVT_MENU(self,self.IdMSWPrintConvInfo,self.onMenuPrintConvInfo)
        return wxglade_tmp_menu

    def onMenuMSWInsert(self,event):
        mswdoc = mswDoc.mswDoc()
        item = self.keytree.GetSelection()
        id = self.keytree.GetPyData(item)[2]
        if id in (BIB.ID_REF,BIB.ID_REF_ROOT,BIB.ID_REF_ALL,BIB.ID_QUERY,BIB.ID_CITED):
            item = self.reflist.GetFirstSelected()
            while item != -1:
                ref_id =self.reflist.GetItemData(item)
                ref =self.db.getRef(ref_id,BIB.BIB_FIELDS)
                mswdoc.MSWInsert(ref)
                item = self.reflist.GetNextSelected(item)
        if mswdoc.getMSWFormatter().isNumberEntries(): #And if autoUpdate
            mswdoc.updateCitationText()

####NOTE: MINIMIZING MSWORD WINDOW results into an important gain of time!!!!!!!
#### Currently it takes 45 sec to preformatte everything when win minimized otherwise it takes 3 min

    def onMenuMSWUpdateCitation(self,event):
        aDoc = mswDoc.mswDoc()
        self.updateCitationFromDatabase()
        aDoc.updateCitationText()
        aDoc.preFormatCitations()

    def onMenuMSWPreFormatCitation(self,event):
        #Need a progress gauge here (~20 sec)
        #the progress gauge here is fake and is a psychological help, so that the user doesn't worry!!!!
        msg= newProgressWin.newProgressWin("Pre-formatting. Please, keep MsWord minimized!","Please keep MsWord minimized and wait...    ")
        aDoc = mswDoc.mswDoc()
        msg.Update(0.1,"Please keep MsWord minimized and wait...\nThe process might take up to a minute")
        aDoc.minimizeWindow()
        msg.Update(0.4,"Please keep MsWord minimized and wait...\nThe process might take up to a minute")
        time.sleep(2)
        msg.Update(0.5,"Please keep MsWord minimized and wait...\nThe process might take up to a minute")
        self.updateCitationFromDatabase()
        aDoc.preFormatCitations()
        msg.Update(1,"Pre-Formatting terminated")
        aDoc.normalWindow()
        msg.Destroy()

    def onMenuMSWFormatBiblio(self,event):
        """ This function might take up to few minutes if a lot of ref are in
        That's why it is important to inform the user at this point"""
        aDoc = mswDoc.mswDoc()
        aDoc.MSWCreateBiblio()
        aDoc.formatBiblioString()

    def onMenuPreAll(self,event):
        perf = False #Turn to true if want to get the timing
        fstmsg = ""
        msg= newProgressWin.newProgressWin("Pre-formatting. Please, keep MsWord minimized!","Please wait...         ")
        prevTime = time.time()
        prevTime1=prevTime #For total time
#        print time.asctime(time.localtime(time.time()))
        msg.Update(0.05,fstmsg+"Reading document..")
        aDoc = mswDoc.mswDoc()
        #Improve speeds a lot to minimize the window before doing anything
        aDoc.minimizeWindow()
        citationFields =mswDoc.bibMSW.mswUtils.getCitationFields(aDoc.application.ActiveDocument.Fields)
        duree = time.time()-prevTime
        prevTime = time.time()
        if perf:
            print "\n\n****Bibus - MSWord Interface Performance Monitoring****"
            print "Time for initializing doc (sec.)=%s"%duree
        msg.Update(0.1,fstmsg+"Updating Bibliography...\nPlease, wait and keep MsWord minimized.")
        self.updateCitationFromDatabase()
        aDoc.MSWCreateBiblio()
        duree = time.time()-prevTime
        prevTime = time.time()

        if perf:
            print "Time for MSWCreateBiblio (sec.)", duree
        msg.Update(0.2,fstmsg+"Updating Citation text...\nPlease, wait and keep MsWord minimized.")
        aDoc.updateCitationText()
        duree = time.time()-prevTime
        prevTime = time.time()
        if perf:
            print "Time for updateCitationText (sec.) =", duree
        msg.Update(0.4,fstmsg+"Fusionning Citations...\nPlease, wait and keep MsWord minimized.")
        aFormatter = aDoc.getMSWFormatter()
        skipFormatBiblioString = False
        if aFormatter.isNumberEntries()==True and aFormatter.isSortByPosition()== False:
            aDoc.formatBiblioString()
            skipFormatBiblioString = True
        aDoc.fuseCitations(citationFields)
        duree = time.time()-prevTime
        prevTime = time.time()
        if perf:
            print "Time for fuseCitations (sec.)=", duree
        msg.Update(0.5,fstmsg+"Pre-formatting Citation text...\nPlease, wait and keep MsWord minimized.")
        citationFields = aDoc.preFormatCitations()
        duree = time.time()-prevTime
        prevTime = time.time()
        if perf:
            print "Time for preFormatCitations (sec.)=", duree
        msg.Update(0.7,fstmsg+"Formatting Bibliography...\nThe process might take few minutes (1-2)")
        if skipFormatBiblioString==False:
            aDoc.formatBiblioString()
        duree = time.time()-prevTime
        prevTime = time.time()
        if perf:
            print "Time for formatBiblioString (sec.)=", duree
        msg.Update(0.95,fstmsg+"Refreshing content..")
        if perf:
            print "****Done in Total Time (sec.)=", prevTime-prevTime1,"****"
        #aDoc.printConverterInfo()
        msg.Destroy()
        aDoc.normalWindow()

    def onMenuMSWFinalize(self,event):
        perf = False #Turn to True if want to get the timing
        aDoc = mswDoc.mswDoc()
        aDoc.finaliseDoc(self)
        fstmsg = ""
        msg= newProgressWin.newProgressWin("Pre-formatting. Please, keep MsWord minimized!","Please wait...         ")
        prevTime = time.time()
        prevTime1=prevTime #For total time
#        print time.asctime(time.localtime(time.time()))
        msg.Update(0.05,fstmsg+"Reading document..")
        aDoc = mswDoc.mswDoc()
        #Improve speeds a lot to minimize the window before doing anything
        aDoc.minimizeWindow()
        citationFields =mswDoc.bibMSW.mswUtils.getCitationFields(aDoc.application.ActiveDocument.Fields)
        duree = time.time()-prevTime
        prevTime = time.time()
        if perf:
            print "\n\n****Bibus - MSWord Interface Performance Monitoring****"
            print "Time for initializing doc (sec.)=%s"%duree
        msg.Update(0.2,fstmsg+"Updating Citation text...\nPlease, wait and keep MsWord minimized.")
        self.updateCitationFromDatabase()
        aDoc.updateCitationText()
        duree = time.time()-prevTime
        prevTime = time.time()
        if perf:
            print "Time for updateCitationText (sec.) =", duree
        msg.Update(0.3,fstmsg+"Resolving Duplicates...\nPlease, wait and keep MsWord minimized.")
        citationFields = aDoc.getMSWFormatter().addDuplicateInfo(citationFields)
        duree = time.time()-prevTime
        prevTime = time.time()
        if perf:
            print "Time for addDuplicateInfo (sec.)=", duree
        msg.Update(0.4,fstmsg+"Updating Citation Duplication...\nPlease, wait and keep MsWord minimized.")
        aDoc.updateCitationText()
        duree = time.time()-prevTime
        prevTime = time.time()
        if perf:
            print "Time for updateCitationText (sec.) =", duree
        msg.Update(0.5,fstmsg+"Fusionning Citations...\nPlease, wait and keep MsWord minimized.")
        aFormatter = aDoc.getMSWFormatter()
        skipFormatBiblioString = False
        if aFormatter.isNumberEntries()==True and aFormatter.isSortByPosition()== False:
            aDoc.MSWCreateBiblio()
            aDoc.formatBiblioString()
            skipFormatBiblioString = True
        aDoc.fuseCitations(aDoc.application.ActiveDocument.Fields)
        duree = time.time()-prevTime
        prevTime = time.time()
        if perf:
            print "Time for fuseCitations (sec.)=", duree
        msg.Update(0.6,fstmsg+"Pre-formatting Citation text...\nPlease, wait and keep MsWord minimized.")
        aDoc.preFormatCitations()
        duree = time.time()-prevTime
        prevTime = time.time()
        if perf:
            print "Time for preFormatCitations (sec.)=", duree
        msg.Update(0.7,fstmsg+"Updating Bibliography...\nPlease, wait and keep MsWord minimized.")
        if skipFormatBiblioString == False:
            aDoc.MSWCreateBiblio()
        duree = time.time()-prevTime
        prevTime = time.time()
        if perf:
            print "Time for MSWCreateBiblio (sec.)", duree
        msg.Update(0.8,fstmsg+"Formatting Bibliography...\nThe process might take few minutes (1-2)")
        if skipFormatBiblioString == False:
            aDoc.formatBiblioString()
        duree = time.time()-prevTime
        prevTime = time.time()
        if perf:
            print "Time for formatBiblioString (sec.)=", duree
        msg.Update(0.95,fstmsg+"Refreshing content..")
        if perf:
            print "****Done in Total Time (sec.)=", prevTime-prevTime1,"****"
        msg.Destroy()
        aDoc.normalWindow()

    def updateCitationFromDatabase(self):
        """ Update the citation from the citation in database, key ALL"""
        aDoc = mswDoc.mswDoc()
        mFields =  mswDoc.bibMSW.mswUtils.getCitationFields(aDoc.application.ActiveDocument.Fields)
        for aField in mFields:
            fieldRefId = mswDoc.bibMSW.mswUtils.getXmlValueFromString("Identifier",aField.Code.Text)
            ref = self.db.getRefFromIdentifier(fieldRefId,BIB.BIB_FIELDS)
            if ref==[]: continue
            #print "Ref found=", ref[0][BIB.BIBLIOGRAPHIC_FIELDS["Identifier"]]
            allRefText =mswDoc.bibMSW.mswCONST.me_MSWBIBUS_ADDIN_REF_TAG
            for t in BIB.BIB_FIELDS[:-1]:
                if unicode(ref[0][BIB.BIBLIOGRAPHIC_FIELDS[t]]) =="":
                    continue
                elif t!="BibliographicType":
                    allRefText=allRefText+"<"+str(t)+">"+unicode(ref[0][BIB.BIBLIOGRAPHIC_FIELDS[t]])+"</"+str(t)+">"
                else:
                    allRefText=allRefText+"<"+str(t)+">"+BIB.BIB_TYPE[ref[0][BIB.BIBLIOGRAPHIC_FIELDS[t]]]+"</"+str(t)+">"
            allRefText = allRefText+"<"+mswDoc.bibMSW.mswCONST.me_MSWBIBUS_CITE_RANGES+">"+"for ranges"+"</"+mswDoc.bibMSW.mswCONST.me_MSWBIBUS_CITE_RANGES+">"
            allRefText = allRefText+"<"+mswDoc.bibMSW.mswCONST.me_MSWBIBUS_CITE_DUPLICATES+"></"+mswDoc.bibMSW.mswCONST.me_MSWBIBUS_CITE_DUPLICATES+">"
            #resText is the text displayed to the user when reference is inserted ([1] or Smith et al, 2005)
            #resText depends on the style and has to be set accordingly
            #resText = "{"+ref[0][BIB.BIB_FIELDS[1]]+"}"
            resText = "{"+ref[0][1]+"}"
            aField.Code.Text= allRefText
            aField.Result.Text = resText
            aField.Data = mswDoc.bibMSW.mswCONST.me_MSWBIBUS_CITE_TAG


    def MSWSelectCit(self,order,short=False):
        """Return list of references cited in the current MSW document"""
        aDoc = mswDoc.mswDoc()
        try:
         citationFields = mswDoc.bibMSW.mswUtils.getCitationFields(aDoc.application.ActiveDocument.Fields)
        except :
            return ()
        if len(citationFields)==0:
            return ()
        #citations = [ref.Identifier for ref in self.doc]
        citations = []
        for acite in citationFields:
            citations.append(mswDoc.bibMSW.mswUtils.getXmlValueFromString("Identifier",acite.Code.Text))
        return self.__Identifiers2References(citations,order,short)[1]

    def onMenuPrintConvInfo(self,event):
        #self.updateCitationFromDatabase()
        mswDoc.mswDoc().printConverterInfo()
# end of class BibFrame