File: xpn.py

package info (click to toggle)
xpn 1.2.6-5
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd, squeeze, wheezy
  • size: 2,500 kB
  • ctags: 1,685
  • sloc: python: 12,693; xml: 206; makefile: 16; sh: 1
file content (2927 lines) | stat: -rwxr-xr-x 139,871 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
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
import os,shutil
#os.environ['PATH'] += ';'+os.path.join('gtk/lib')+';'+os.path.join('gtk/bin') #OLD
#os.environ['PATH'] = os.path.join('gtk/lib')+';'+os.path.join('gtk/bin')+';'+os.path.join('gtk\\lib')+';'+os.path.join('gtk\\bin')+';'+os.environ['PATH']  #NEW

#py2exe 0.6.8 problem
import email
import email.mime.text
import email.iterators
import email.generator
import email.utils
#py2exe 0.6.8 problem

import sys
import gtk
import gobject
import pango
import cPickle
import time
import re
import platform
import glob
import gettext
import locale
import webbrowser
import ConfigParser
from urllib import quote as url_quote
from optparse import OptionParser
from email.Utils import parsedate_tz, mktime_tz
from xpn_src.Groups_Pane import Groups_Pane
from xpn_src.Threads_Pane import Threads_Pane
from xpn_src.Article_Pane import Article_Pane
from xpn_src.Groups_Win import Groups_Win
from xpn_src.Config_File import Config_File
from xpn_src.Config_Win import Config_Win
from xpn_src.Edit_Win import Edit_Win
from xpn_src.Edit_Mail_Win import Edit_Mail_Win
from xpn_src.Dialogs import About_Dialog, Dialog_YES_NO, Error_Dialog, MidDialog, Dialog_OK, Dialog_Import_Newsrc
from xpn_src.Article import Article, Article_To_Send
from xpn_src.Show_Logs import Logs_Window
from xpn_src.Newsrc import ImportNewsrc, ExportNewsrc
from xpn_src.Find_Win import Find_Win, Search_Win, GlobalSearch
from xpn_src.Score import Score_Rules, Score_Win
from xpn_src.Charset_List import load_ordered_list
from xpn_src.Connections_Handler import Connection, SMTPConnection, SSLConnection
from xpn_src.UserDir import UserDir, get_wdir
from xpn_src.Outbox_Manager import Outbox_Manager
from xpn_src.KeyBindings import KeyBindings, load_shortcuts
from xpn_src.Server_Win import NNTPServer_Win
from xpn_src.Groups_Vs_ID import Groups_Vs_ID
from xpn_src.Articles_DB import Articles_DB, Groups_DB
from xpn_src.Custom_Search_Entry import Custom_Search_Entry
try:
    set()
except:
    from sets import Set as set

try:
    user_system=" ; "+platform.system()
except:
    user_system=""

NUMBER="1.2.6"
VERSION="XPN/%s (Street Spirit%s)" % (NUMBER,user_system)

gettext.NullTranslations()
gettext.install("xpn")

ui_string="""<ui>
    <menubar name='MainMenuBar'>
        <menu action='File'>
            <menuitem action='groups' />
            <separator/>
            <menuitem action='rules' />
            <separator/>
            <menuitem action='logs' />
            <separator/>
            <menuitem action='exp_newsrc' />
            <menuitem action='imp_newsrc' />
            <separator />
            <menuitem action='accelerator' />
            <separator />
            <menuitem action='conf' />
            <separator />
            <menuitem action='exit' />
        </menu>
        <menu action='Search'>
            <menuitem action='find' />
            <menuitem action='global' />
            <menuitem action='filter' />
            <separator />
            <menuitem action='search' />
        </menu>
        <menu action ='View'>
            <menu action='view_articles_opts'>
                <menuitem action='raw' />
                <menuitem action='spoiler' />
                <menuitem action='show_quote' />
                <menuitem action='show_sign' />
                <menuitem action='fixed' />
                <menuitem action='show_hide_headers' />
                <menuitem action='rot13' />
            </menu>
            <separator />
            <menu action='view_group_opts'>
                <menuitem action='show_threads' />
                <menuitem action='show_all_read_threads' />
                <menuitem action='show_threads_without_watched' />
                <menuitem action='show_read_articles' />
                <menuitem action='show_unread_articles' />
                <menuitem action='show_kept_articles' />
                <menuitem action='show_unkept_articles' />
                <menuitem action='show_watched_articles' />
                <menuitem action='show_ignored_articles' />
                <menuitem action='show_unwatchedignored_articles' />
                <menuitem action='show_score_neg_articles' />
                <menuitem action='show_score_zero_articles' />
                <menuitem action='show_score_pos_articles' />
            </menu>
        </menu>
        <menu action ='Navigate'>
            <menuitem action='group' />
            <separator />
            <menuitem action='previous' />
            <menuitem action='next' />
            <menuitem action='next_unread' />
            <menuitem action='parent' />
            <menuitem action='one_key' />
            <menuitem action='move_up' />
            <separator />
            <menuitem action='focus_groups' />
            <menuitem action='focus_threads' />
            <menuitem action='focus_article' />
            <separator />
            <menuitem action='zoom_groups' />
            <menuitem action='zoom_threads' />
            <menuitem action='zoom_article' />
        </menu>
        <menu action='Subscribed'>
            <menuitem action='gethdrs' />
            <menuitem action='gethdrssel' />
            <menuitem action='getbodies' />            
            <menuitem action='getbodiessel' />
            <separator />   
            <menuitem action='expand_row' />
            <menuitem action='collapse_row' />
            <menuitem action='expand' />
            <menuitem action='collapse' />
            <separator />
            <menu action='mark_group'>
                <menuitem action='mark' />
                <menuitem action='mark_unread_group' />
                <menuitem action='mark_download_group' />
                <menuitem action='keepall' />
                <separator />
                <menuitem action='markall' />
                <menuitem action='markall_unread' />
            </menu>
            <separator />
            <menuitem action='apply_score' />
            <separator />
            <menuitem action='groups_vs_id' />
            
        </menu>
        <menu action='Articles'>
            <menuitem action='post' />
            <menuitem action='followup' />
            <menuitem action='reply' />
            <menuitem action='outbox_manager' />
            <separator />
            <menuitem action='cancel' />
            <menuitem action='supersede' />
            <separator />
            <menu action='flags'>
                <menuitem action='mark_read' />
                <menuitem action='mark_unread' />
                <menuitem action='mark_download' />
                <menuitem action='keep' />
                <menuitem action='delete' />
                <separator />
                <menuitem action='mark_read_sub' />
                <menuitem action='mark_unread_sub' />
                <menuitem action='mark_download_sub' />
                <menuitem action='keep_sub' />
                <menuitem action='watch' />
                <menuitem action='ignore' />
                <separator />
                <menuitem action='raise_score' />
                <menuitem action='lower_score' />
                <menuitem action='set_score' />
            </menu>
        </menu>       
        <menu action='Help'>
            <menuitem action='about' />
        </menu>
    </menubar>
            
    <popup action='mark_group'>
        <menuitem action='mark' />
        <menuitem action='mark_unread_group' />
        <menuitem action='mark_download_group' />
        <menuitem action='keepall' />
        <separator />
        <menuitem action='markall' />
        <menuitem action='markall_unread' />
    </popup>
    
    <popup action='flags'>
        <menuitem action='mark_read' />
        <menuitem action='mark_unread' />
        <menuitem action='mark_download' />
        <menuitem action='keep' />
        <menuitem action='delete' />
        <separator />
        <menuitem action='mark_read_sub' />
        <menuitem action='mark_unread_sub' />
        <menuitem action='mark_download_sub' />
        <menuitem action='keep_sub' />
        <menuitem action='watch' />
        <menuitem action='ignore' />
        <separator />
        <menuitem action='raise_score' />
        <menuitem action='lower_score' />
        <menuitem action='set_score' />
    </popup>


    <toolbar name='MainToolBar'>
        <toolitem action='groups' />
        <toolitem action='gethdrs' />
        <toolitem action='getbodies' />
        <toolitem action='mark' />
        <toolitem action='markall' />
        <separator />
        <toolitem action='post' />
        <toolitem action='followup' />
        <toolitem action='reply' />
        <toolitem action='outbox_manager' />
        <separator />
        <toolitem action='previous' />
        <toolitem action='next' />
        <toolitem action='next_unread' />
        <toolitem action='rot13' />
        <separator />
        <toolitem action='expand_row' />
        <toolitem action='collapse_row' />
        <toolitem action='expand' />
        <toolitem action='collapse' />
        <separator />
        <toolitem action='rules' />
        <toolitem action='conf' />
    </toolbar>
</ui>"""

def escape(data):
    """Escape &, <, and > in a string of data.
    """

    # must do ampersand first
    data = data.replace("&", "&amp;")
    data = data.replace(">", "&gt;")
    data = data.replace("<", "&lt;")
    return data

class MainWin:
    def open_logs_win(self,object):
        self.logs_win=Logs_Window(self.window)

    def open_groups_win(self,object):
        self.win2=Groups_Win(self)
        self.win2.show()

    def open_configure_win(self,object):
        self.save_sizes()
        self.win3=Config_Win(self.conf,self)
        self.win3.show()

    def open_rules_win(self,object):
        self.score_win=Score_Win(self.score_rules,self)
        self.score_win.show()

    def open_groups_vs_id(self,object):
        self.groups_vs_id=Groups_Vs_ID(self.subscribed_groups,self)
        self.groups_vs_id.show()

    def supersede_cancel_message(self,object,mode):
        group_selected=""
        id_name=""
        model,path,iter_selected=self.groups_pane.get_first_selected_row()
        if iter_selected!=None:
            group_selected=model.get_value(iter_selected,0)
            id_name=self.get_id_for_group(group_selected)
        model,iter_selected=self.threads_pane.threads_tree.get_selection().get_selected()
        subj=""
        cp_id=ConfigParser.ConfigParser()
        cp_id.read(os.path.join(get_wdir(),"dats","id.txt"))

        if iter_selected!=None:
            #subj=model.get_value(iter_selected,1).decode("utf-8")
            article=self.threads_pane.get_article(model,iter_selected)
            subj=article.subj
            try:
                article.ngroups
            except AttributeError:
                self.statusbar.push(1,_("First you have to read the article"))
            else:
                nick=cp_id.get(id_name,"nick")
                email=cp_id.get(id_name,"email")
                user=nick+" <"+email+">"
                if article.user_agent.startswith("XPN") and user==article.from_name:
                    if mode=="Supersede":
                        self.win4=Edit_Win(self.configs,article.ngroups,article,None,self.subscribed_groups,"Supersede",server_name=self.current_server,id_name=id_name)
                        #self.win4.show()
                    else:
                        message=Dialog_YES_NO(_("Do you want to CANCEL this article?\n\nSubject: %s ""\nMessage-ID: %s") % (article.subj.encode("utf-8"),escape(article.msgid.encode("utf-8"))))

                        if message.resp:
                            canc_mess=Article_To_Send(article.ngroups,user,"cmsg cancel "+article.msgid,"",VERSION,"us-ascii",load_ordered_list(),["Cancel Message for "+article.msgid],["Control"],["cancel "+article.msgid],cp_id.get(id_name,"gen_mid"),cp_id.get(id_name,"fqdn"))
                            cancel_message=canc_mess.get_article()
                            message,articlePosted=self.connectionsPool[self.current_server].sendArticle(cancel_message)
                            if articlePosted:
                                self.statusbar.push(1,_("Cancel Article Sent: ")+message)
                            else:
                                self.statusbar.push(1,message)
                else:
                    self.statusbar.push(1,_("You can Cancel/Supersede only your articles"))

    def open_outbox_manager(self,obj):
        self.win_outbox=Outbox_Manager(self,VERSION)
        self.win_outbox.show()

    def open_edit_win(self,object,is_followup=False):
        group=""
        id_name=""
        model,path,iter_selected=self.groups_pane.get_first_selected_row()
        if iter_selected!=None:
            group=model.get_value(iter_selected,0)
            id_name=self.get_id_for_group(group)
        if is_followup:
            #this is a followup
            model,iter_selected=self.threads_pane.threads_tree.get_selection().get_selected()
            subj=""
            if iter_selected!=None:
                #subj=model.get_value(iter_selected,1).decode("utf-8")
                article=self.threads_pane.get_article(model,iter_selected)
                subj=article.subj
                group=article.original_group
                try:
                    article.ngroups
                except AttributeError:
                    self.statusbar.push(1,_("First you have to read the article"))
                else:
                    self.threads_pane.update_article_icon("fup")

                    bounds=self.article_pane.buffer.get_selection_bounds()
                    selected_text=None
                    if bounds:
                        start=bounds[0]
                        stop=bounds[1]
                        selected_text=self.article_pane.buffer.get_text(start,stop,True).decode("utf-8").split("\n")

                    newsgroups=group
                    if group!=article.ngroups:
                        #this is a crosspost
                        crosspost=True
                        newsgroups=article.ngroups
                    else:
                        crosspost=False
                    if article.fup_to!="":
                        newsgroups=article.fup_to
                        followup_to=True
                    else:
                        followup_to=False

                    if crosspost and not followup_to:
                        message=Dialog_YES_NO(_("This is a crosspost! \n Do you want to send the article only on the original newsgroup (%s) ?") % (group,))
                        if message.resp:
                            newsgroups=group
                    if followup_to:
                        if article.fup_to!="poster":
                            message=Dialog_YES_NO(_("Original Poster set \"Followup_to\" on %s,\n\nDo you want to send your article on the original newsgroup (%s) ?") % (article.fup_to,group))
                            if message.resp:
                                newsgroups=group
                        else:
                            message=Dialog_YES_NO(_("Original Poster set \"Followup_to: poster\",\n\nDo you want to reply by mail ?"))
                            if message.resp:
                                self.open_edit_mail_win(None)
                                return None
                            else:
                                newsgroups=group
                    self.win4=Edit_Win(self.configs,newsgroups,article,selected_text,self.subscribed_groups,server_name=self.current_server,id_name=id_name)
                    #self.win4.show()
        else:
            #this is a new post
            self.win4=Edit_Win(self.configs,group,None,None,self.subscribed_groups,server_name=self.current_server,id_name=id_name)
            #self.win4.show()

    def open_edit_mail_win(self,object):
        to_name=""
        id_name=""
        model,path,iter_selected=self.groups_pane.get_first_selected_row()
        if iter_selected!=None:
            group=model.get_value(iter_selected,0)
            id_name=self.get_id_for_group(group)

        model,iter_selected=self.threads_pane.threads_tree.get_selection().get_selected()
        subj=""
        if iter_selected!=None:
            #subj=model.get_value(iter_selected,1).decode("utf-8")
            article=self.threads_pane.get_article(model,iter_selected)
            subj=article.subj
            try:
                article.reply_to
            except AttributeError:
                self.statusbar.push(1,_("First you have to read the article"))
            else:
                self.threads_pane.update_article_icon("fup")
                if article.reply_to!="":
                    to_name=article.reply_to
                else:
                    to_name=article.from_name
                bounds=self.article_pane.buffer.get_selection_bounds()
                selected_text=None
                if bounds:
                    start=bounds[0]
                    stop=bounds[1]
                    selected_text=self.article_pane.buffer.get_text(start,stop,True).decode("utf-8").split("\n")

                self.win4=Edit_Mail_Win(self.configs,to_name,article,selected_text,id_name=id_name)
                self.win4.show()

    def open_about_dialog(self,object):
        self.about_dialog=About_Dialog(NUMBER)
        self.about_dialog.show()

    def delete_event(self,widget,event,data=None):
        self.mainwin_width,self.mainwin_height=self.window.get_size()
        self.mainwin_pos_x,self.mainwin_pos_y=self.window.get_position()
        return False

    def save_sizes(self):
        try:
            f=open(os.path.join(self.wdir,"dats/sizes.dat"),"rb")
        except IOError:
            sizes={}        
        else:
            sizes=cPickle.load(f)
        sizes["vpaned_pos"]=self.vpaned.get_position()
        sizes["hpaned_pos"]=self.hpaned.get_position()
        sizes["threads_col_status"]=self.threads_pane.column1.get_width()
        sizes["threads_col_subject"]=self.threads_pane.column2.get_width()
        sizes["threads_col_from"]=self.threads_pane.column3.get_width()
        sizes["threads_col_date"]=self.threads_pane.column4.get_width()
        sizes["threads_col_score"]=self.threads_pane.column5.get_width()
        sizes["groups_col1"]=self.groups_pane.column1.get_width()
        if not self.mainwin_width:
            sizes["mainwin_width"],sizes["mainwin_height"]=self.window.get_size()
        else:
            sizes["mainwin_width"]=self.mainwin_width
            sizes["mainwin_height"]=self.mainwin_height
        if not self.mainwin_pos_x:
            sizes["mainwin_pos_x"],sizes["mainwin_pos_y"]=self.window.get_position()
        else:
            sizes["mainwin_pos_x"]=self.mainwin_pos_x
            sizes["mainwin_pos_x"]=self.mainwin_pos_x
        try:
            f=open(os.path.join(self.wdir,"dats/sizes.dat"),"wb")
        except IOError:
            pass
        else:
            cPickle.dump(sizes,f,1)
            f.close()

    def save_checkmenu_options(self):
        self.configs["raw"]=str(bool(self.ui.get_widget("/MainMenuBar/View/view_articles_opts/raw").get_active()))
        self.configs["fixed"]=str(bool(self.ui.get_widget("/MainMenuBar/View/view_articles_opts/fixed").get_active()))
        self.configs["show_quote"]=str(bool(self.ui.get_widget("/MainMenuBar/View/view_articles_opts/show_quote").get_active()))
        self.configs["show_sign"]=str(bool(self.ui.get_widget("/MainMenuBar/View/view_articles_opts/show_sign").get_active()))
        self.configs["show_spoiler"]=str(bool(self.ui.get_widget("/MainMenuBar/View/view_articles_opts/spoiler").get_active()))
        self.configs["show_threads"]=str(bool(self.ui.get_widget("/MainMenuBar/View/view_group_opts/show_threads").get_active()))
        self.configs["show_all_read_threads"]=str(bool(self.ui.get_widget("/MainMenuBar/View/view_group_opts/show_all_read_threads").get_active()))
        self.configs["show_threads_without_watched"]=str(bool(self.ui.get_widget("/MainMenuBar/View/view_group_opts/show_threads_without_watched").get_active()))
        self.configs["show_read_articles"]=str(bool(self.ui.get_widget("/MainMenuBar/View/view_group_opts/show_read_articles").get_active()))
        self.configs["show_unread_articles"]=str(bool(self.ui.get_widget("/MainMenuBar/View/view_group_opts/show_unread_articles").get_active()))
        self.configs["show_kept_articles"]=str(bool(self.ui.get_widget("/MainMenuBar/View/view_group_opts/show_kept_articles").get_active()))
        self.configs["show_unkept_articles"]=str(bool(self.ui.get_widget("/MainMenuBar/View/view_group_opts/show_unkept_articles").get_active()))
        self.configs["show_watched_articles"]=str(bool(self.ui.get_widget("/MainMenuBar/View/view_group_opts/show_watched_articles").get_active()))
        self.configs["show_ignored_articles"]=str(bool(self.ui.get_widget("/MainMenuBar/View/view_group_opts/show_ignored_articles").get_active()))
        self.configs["show_unwatchedignored_articles"]=str(bool(self.ui.get_widget("/MainMenuBar/View/view_group_opts/show_unwatchedignored_articles").get_active()))
        self.configs["show_score_neg_articles"]=str(bool(self.ui.get_widget("/MainMenuBar/View/view_group_opts/show_score_neg_articles").get_active()))
        self.configs["show_score_zero_articles"]=str(bool(self.ui.get_widget("/MainMenuBar/View/view_group_opts/show_score_zero_articles").get_active()))
        self.configs["show_score_pos_articles"]=str(bool(self.ui.get_widget("/MainMenuBar/View/view_group_opts/show_score_pos_articles").get_active()))
        self.conf.write_configs()

    def update_checkmenu_options(self):
        if self.configs["raw"]=="True":
            self.ui.get_widget("/MainMenuBar/View/view_articles_opts/raw").set_active(True)
        else:
            self.ui.get_widget("/MainMenuBar/View/view_articles_opts/raw").set_active(False)
        if self.configs["fixed"]=="True":
            self.ui.get_widget("/MainMenuBar/View/view_articles_opts/fixed").set_active(True)
        else:
            self.ui.get_widget("/MainMenuBar/View/view_articles_opts/fixed").set_active(False)
        if self.configs["show_quote"]=="True":
            self.ui.get_widget("/MainMenuBar/View/view_articles_opts/show_quote").set_active(True)
        else:
            self.ui.get_widget("/MainMenuBar/View/view_articles_opts/show_quote").set_active(False)
        if self.configs["show_sign"]=="True":
            self.ui.get_widget("/MainMenuBar/View/view_articles_opts/show_sign").set_active(True)
        else:
            self.ui.get_widget("/MainMenuBar/View/view_articles_opts/show_sign").set_active(False)
        if self.configs["show_spoiler"]=="True":
            self.ui.get_widget("/MainMenuBar/View/view_articles_opts/spoiler").set_active(True)
        else:
            self.ui.get_widget("/MainMenuBar/View/view_articles_opts/spoiler").set_active(False)
        if self.configs["show_threads"]=="True":
            self.ui.get_widget("/MainMenuBar/View/view_group_opts/show_threads").set_active(True)
        else:
            self.ui.get_widget("/MainMenuBar/View/view_group_opts/show_threads").set_active(False)
        if self.configs["show_all_read_threads"]=="True":
            self.ui.get_widget("/MainMenuBar/View/view_group_opts/show_all_read_threads").set_active(True)
        else:
            self.ui.get_widget("/MainMenuBar/View/view_group_opts/show_all_read_threads").set_active(False)
        if self.configs["show_threads_without_watched"]=="True":
            self.ui.get_widget("/MainMenuBar/View/view_group_opts/show_threads_without_watched").set_active(True)
        else:
            self.ui.get_widget("/MainMenuBar/View/view_group_opts/show_threads_without_watched").set_active(False)
        if self.configs["show_read_articles"]=="True":
            self.ui.get_widget("/MainMenuBar/View/view_group_opts/show_read_articles").set_active(True)
        else:
            self.ui.get_widget("/MainMenuBar/View/view_group_opts/show_read_articles").set_active(False)
        if self.configs["show_unread_articles"]=="True":
            self.ui.get_widget("/MainMenuBar/View/view_group_opts/show_unread_articles").set_active(True)
        else:
            self.ui.get_widget("/MainMenuBar/View/view_group_opts/show_unread_articles").set_active(False)
        if self.configs["show_kept_articles"]=="True":
            self.ui.get_widget("/MainMenuBar/View/view_group_opts/show_kept_articles").set_active(True)
        else:
            self.ui.get_widget("/MainMenuBar/View/view_group_opts/show_kept_articles").set_active(False)
        if self.configs["show_unkept_articles"]=="True":
            self.ui.get_widget("/MainMenuBar/View/view_group_opts/show_unkept_articles").set_active(True)
        else:
            self.ui.get_widget("/MainMenuBar/View/view_group_opts/show_unkept_articles").set_active(False)
        if self.configs["show_watched_articles"]=="True":
            self.ui.get_widget("/MainMenuBar/View/view_group_opts/show_watched_articles").set_active(True)
        else:
            self.ui.get_widget("/MainMenuBar/View/view_group_opts/show_watched_articles").set_active(False)
        if self.configs["show_ignored_articles"]=="True":
            self.ui.get_widget("/MainMenuBar/View/view_group_opts/show_ignored_articles").set_active(True)
        else:
            self.ui.get_widget("/MainMenuBar/View/view_group_opts/show_ignored_articles").set_active(False)
        if self.configs["show_unwatchedignored_articles"]=="True":
            self.ui.get_widget("/MainMenuBar/View/view_group_opts/show_unwatchedignored_articles").set_active(True)
        else:
            self.ui.get_widget("/MainMenuBar/View/view_group_opts/show_unwatchedignored_articles").set_active(False)
        if self.configs["show_score_neg_articles"]=="True":
            self.ui.get_widget("/MainMenuBar/View/view_group_opts/show_score_neg_articles").set_active(True)
        else:
            self.ui.get_widget("/MainMenuBar/View/view_group_opts/show_score_neg_articles").set_active(False)
        if self.configs["show_score_zero_articles"]=="True":
            self.ui.get_widget("/MainMenuBar/View/view_group_opts/show_score_zero_articles").set_active(True)
        else:
            self.ui.get_widget("/MainMenuBar/View/view_group_opts/show_score_zero_articles").set_active(False)
        if self.configs["show_score_pos_articles"]=="True":
            self.ui.get_widget("/MainMenuBar/View/view_group_opts/show_score_pos_articles").set_active(True)
        else:
            self.ui.get_widget("/MainMenuBar/View/view_group_opts/show_score_pos_articles").set_active(False)
      
    def destroy(self,widget):
        for connection in self.connectionsPool.itervalues():
            connection.closeConnection()
        self.save_sorting_type()
        self.save_sizes()
        self.save_checkmenu_options()
        self.purge_groups()
        try: os.remove(os.path.join(self.wdir,"xpn.lock"))
        except: pass
        gtk.main_quit()

    def tray_activated(self,  widget):
        if self.window.get_property("is-active"):
            self.window.iconify()
            self.window.hide()
        else:
            self.window.present()
            self.window.deiconify()
            widget.set_blinking(False)

    def tray_popuped(self,  widget,  button,  timestamp):
        menu = gtk.Menu()
        menuitem = gtk.ImageMenuItem(gtk.STOCK_PREFERENCES)
        menuitem.connect("activate",  self.open_configure_win)
        menu.append(menuitem)
        menu.append(gtk.SeparatorMenuItem())
        menuitem = gtk.ImageMenuItem(gtk.STOCK_ABOUT)
        menuitem.connect('activate', self.open_about_dialog)
        menu.append(menuitem)
        menuitem = gtk.ImageMenuItem(gtk.STOCK_QUIT)
        menuitem.connect('activate', self.destroy)
        menu.append(menuitem)

        menu.show_all()
        menu.popup(None,  None,  None,  button,  timestamp)

    def save_sorting_type(self,obj=None):
        for n in range(1,5):
            col=self.threads_pane.threads_tree.get_column(n)
            if col.get_sort_indicator():
                order=col.get_sort_order()
                col_name=["Subject","From","Date","Score"][n-1]
                if order==gtk.SORT_ASCENDING:
                    ascend_order="True"
                else:
                    ascend_order="False"
                self.configs["ascend_order"]=ascend_order
                self.configs["sort_col"]=col_name
                self.conf.write_configs()

    def show_subscribed(self):
        model,path_list,iter_list=self.groups_pane.get_selected_rows()
        
        list=self.art_db.getSubscribed()
        new_list=[]
        self.subscribed_groups=[]
        groups_to_open=[group[0] for group in list]
        self.art_db.addGroups(groups_to_open)
        for group in list:
            total,unread_number=self.art_db.getArticlesNumbers(group[0])
            new_list.append((group[0],str(unread_number)+" ("+str(total)+")"))
            self.subscribed_groups.append([group[0],group[2],group[3]]) #group_name,server_name,id_name
        self.groups_pane.show_list(new_list,True)
        self.threads_pane.clear()
        self.article_pane.clear()
        if path_list:
            self.groups_pane.select_row_by_path(path_list[0])

    def show_threads(self,group,search_type=None,text=None):
        art_fup=gtk.gdk.pixbuf_new_from_file("pixmaps/art_fup.xpm")
        art_body=gtk.gdk.pixbuf_new_from_file("pixmaps/art_body.xpm")
        art_unread=gtk.gdk.pixbuf_new_from_file("pixmaps/art_unread.xpm")
        art_read=gtk.gdk.pixbuf_new_from_file("pixmaps/art_read.xpm")
        art_mark=gtk.gdk.pixbuf_new_from_file("pixmaps/art_mark.xpm")
        art_keep=gtk.gdk.pixbuf_new_from_file("pixmaps/art_keep.xpm")
        art_unkeep=gtk.gdk.pixbuf_new_from_file("pixmaps/art_unkeep.xpm")
        art_watch=gtk.gdk.pixbuf_new_from_file("pixmaps/art_watch.xpm")
        art_unwatchignore=gtk.gdk.pixbuf_new_from_file("pixmaps/art_unwatchignore.xpm")
        art_ignore=gtk.gdk.pixbuf_new_from_file("pixmaps/art_ignore.xpm")
        
        icons=(art_fup,art_body,art_unread,art_read,art_mark,art_keep,art_unkeep,art_watch,art_unwatchignore,art_ignore)

        show_read_articles=bool(self.ui.get_widget("/MainMenuBar/View/view_group_opts/show_read_articles").get_active())
        show_unread_articles=bool(self.ui.get_widget("/MainMenuBar/View/view_group_opts/show_unread_articles").get_active())
        show_kept_articles=bool(self.ui.get_widget("/MainMenuBar/View/view_group_opts/show_kept_articles").get_active())
        show_unkept_articles=bool(self.ui.get_widget("/MainMenuBar/View/view_group_opts/show_unkept_articles").get_active())
        show_watched_articles=bool(self.ui.get_widget("/MainMenuBar/View/view_group_opts/show_watched_articles").get_active())
        show_ignored_articles=bool(self.ui.get_widget("/MainMenuBar/View/view_group_opts/show_ignored_articles").get_active())
        show_unwatchedignored_articles=bool(self.ui.get_widget("/MainMenuBar/View/view_group_opts/show_unwatchedignored_articles").get_active())
        show_score_neg_articles=bool(self.ui.get_widget("/MainMenuBar/View/view_group_opts/show_score_neg_articles").get_active())
        show_score_zero_articles=bool(self.ui.get_widget("/MainMenuBar/View/view_group_opts/show_score_zero_articles").get_active())
        show_score_pos_articles=bool(self.ui.get_widget("/MainMenuBar/View/view_group_opts/show_score_pos_articles").get_active())
        show_threads=bool(self.ui.get_widget("/MainMenuBar/View/view_group_opts/show_threads").get_active())
        show_all_read_threads=bool(self.ui.get_widget("/MainMenuBar/View/view_group_opts/show_all_read_threads").get_active())
        
        show_threads_without_watched=bool(self.ui.get_widget("/MainMenuBar/View/view_group_opts/show_threads_without_watched").get_active())
        
        show_bools=(show_read_articles,show_unread_articles,show_kept_articles,show_unkept_articles,show_watched_articles,show_ignored_articles,show_unwatchedignored_articles,show_score_neg_articles,show_score_zero_articles,show_score_pos_articles,show_threads,show_all_read_threads)

        if group:
            self.window.set_title( "%s - XPN %s" % ( group, NUMBER ) )
        else:
            self.window.set_title( "XPN %s" % (NUMBER,) )

        if not group: return
        groups=[line[0] for line in self.groups_pane.model]
        if not group in groups: return 
            
        self.threads_pane.clear()
        model=self.threads_pane.new_model()

        article_tree = {}
        self.statusbar.push(1,_("Please Wait. Building Threads"))        
       
        def thread_alg_1(search_type=None,text=None):
            sort=True
            
            sorted=[]
            for xpn_article in self.art_db.getArticles(group,show_bools,False,search_type,text):
                sorted.append((xpn_article.secs,xpn_article))
                
            if sort:
                sorted.sort()
            articles=sorted
                
            for secs, xpn_article in articles:
                article_info = xpn_article.get_article_info(icons)
                nick,from_name,ref,subj,date,date_parsed=xpn_article.get_headers()
                msgid=xpn_article.msgid
                if show_threads:
                    try:
                        idx=ref.rindex("<")
                    except ValueError:
                        #Root node
                        article_tree[msgid] = (True, [], article_info)
                    else:
                        #Child node
                        last_ref=ref[idx:]
                        if last_ref in article_tree:
                            #I found the father
                            article_tree[last_ref][1].append(msgid)
                            article_tree[msgid] = (False, [], article_info)
                        else:
                            #Trying threading by subject
                            for old_article_msgid, (old_article_is_root, old_branchs, old_article_info) in article_tree.iteritems():
                                old_article_subj = old_article_info[1]
                                diff_len = len(subj) - len(old_article_subj)
                                if (old_article_subj in subj) and old_article_is_root and diff_len<=6:
                                    #Found a root article with similar subject
                                    article_tree[old_article_msgid][1].append(msgid)
                                    article_tree[msgid] = (False, [], article_info)
                                    break
                            else:
                                #In the list there aren't articles with similar subject
                                article_tree[msgid] = (True, [], article_info)
                else:
                    # we're populating "article_tree", but always with true because
                    # they're all "root nodes" (show_threads is false)
                    article_tree[msgid] = (True, [], article_info)

        def thread_alg_2(search_type=None,text=None):
            #t1=time.time()
            for xpn_article in self.art_db.getArticles(group,show_bools,False,search_type,text):
                article_info = xpn_article.get_article_info(icons)
                msgid=xpn_article.msgid
                #first create all the nodes
                article_tree[msgid] = (True, [], article_info)
            #t2=time.time()
            if show_threads:            
                for is_root,children,article_info in article_tree.itervalues():
                    xpn_article=article_info[4]
                    msgid=xpn_article.msgid
                    nick,from_name,ref,subj,date,date_parsed=xpn_article.get_headers()
                    try:
                        idx=ref.rindex("<")
                    except ValueError:
                        #Root node
                        pass
                    else:
                        #Child node
                        last_ref=ref[idx:]
                        if last_ref in article_tree:
                            #I found the father
                            article_tree[last_ref][1].append(msgid)
                            article_tree[msgid] = (False, article_tree[msgid][1], article_tree[msgid][2])

                #t3=time.time()
                #threading by subject
                orphaned=[(art_info[4].secs,art_info[4]) for mid,(is_root,children,art_info) in article_tree.iteritems() if (is_root and art_info[4].ref)]
                orphaned.sort()
                orp=orphaned[:]
                #t4=time.time()
                for secs,xpn_article in orphaned:
                    subj=xpn_article.subj
                    for is_root,children,art_info in article_tree.itervalues():
                        if is_root and not ((art_info[4].secs,art_info[4]) in orp):
                            old_xpn_article=art_info[4]
                            old_subj=old_xpn_article.subj
                            diff_len = len(subj) - len(old_subj)
                            if (old_subj in subj) and diff_len <=6:
                                article_tree[old_xpn_article.msgid][1].append(xpn_article.msgid)
                                article_tree[xpn_article.msgid] = (False, article_tree[xpn_article.msgid][1], article_tree[xpn_article.msgid][2])
                                break
                        else: continue
                    #found nothing but we can use this article as parent
                    else: #else of the for is not executed when break is called
                        orp.remove((xpn_article.secs,xpn_article))
                #t5=time.time()
                #print "Lettura degli articoli e prima passata:",t2-t1
                #print "Seconda passata, vegono riconosciuti i legami padre figlio:",t3-t2
                #print "Estrazione degli articoli orfani:", t4-t3
                #print "Terza passata, threading by subject:",t5-t4


        # here we apply all the "tree wide" filters
        def anyUnread(node):
            '''Recursive function to check if all the branch is read.'''
            (root, branchs, info) = article_tree[node]

            # if the node is unread, the whole branch has any unread
            if info[5]:  
                return True

            # if any of the sons is unread, just pass the flag to the previous call
            for branch in branchs:
                if anyUnread(branch):
                    return True

            # all my sons are read
            return False
        
        def anyWatched(node):
            (root, branchs, info) = article_tree[node]

            
            if info[11]==art_watch:  
                return True

            
            for branch in branchs:
                if anyWatched(branch):
                    return True
            
            return False

        
        
        if search_type:
            search_type=search_type.lower()
            text=text.lower()
            if search_type=="from": search_type="from_name"
            if search_type=="body": search_type="bodies.raw_body"
        
        
        try: self.configs["threading_method"]
        except KeyError: self.configs["threading_method"]="2"
        if self.configs["threading_method"]=="2": thread_alg_2(search_type,text)
        else:                                     thread_alg_1(search_type,text)


        if not show_all_read_threads:
            roots = [k for k,v in article_tree.iteritems() if v[0]]
            for article_root in roots:
                if not anyUnread(article_root):
                    del article_tree[article_root]
        

        if not show_threads_without_watched:
            roots = [k for k,v in article_tree.iteritems() if v[0]]
            for article_root in roots:
                if not anyWatched(article_root):
                    del article_tree[article_root]
        
        def walkTree(node, iter_mom):
            '''Recursive function to build the articles tree in the GTK Widget.'''
            # took the info about the article in the node
            (root, branchs, info) = article_tree[node]
            if info[5]:
                unread_in_thread = 1
            else:
                unread_in_thread = 0
            
            if info[11]==art_watch:
                watched_in_thread = 1
            else:
                watched_in_thread = 0
            
            watched_unread_in_thread = unread_in_thread and watched_in_thread

            # tell TreeStore to build a branch
            iter_new = self.threads_pane.insert(model, iter_mom, None, info)

            # build all its sons
            for branch in branchs:
                (node_iter, more_unread, more_watched, more_watched_unread) = walkTree(branch, iter_new)
                unread_in_thread += more_unread
                watched_in_thread += more_watched
                watched_unread_in_thread += more_watched_unread

            return (iter_new, unread_in_thread, watched_in_thread, watched_unread_in_thread)

        # with the help of walkTree, we'll build... well... the tree
        roots = [k for k,v in article_tree.iteritems() if v[0]]
        for article_root in roots:
            # start a branch from its root
            (root_iter, unread_in_thread, watched_in_thread, watched_unread_in_thread) = walkTree(article_root, None)

            # show how many unread items the branch has
            self.threads_pane.set_unread_in_thread(model, root_iter, unread_in_thread)
            self.threads_pane.set_unread_in_thread_visible(model, root_iter, unread_in_thread!=0)
            
            self.threads_pane.set_watched_in_thread(model, root_iter, watched_in_thread)
            self.threads_pane.set_watched_unread_in_thread(model, root_iter, watched_unread_in_thread)

        message=_("%s selected") % (group,)
        self.statusbar.push(1,message)
        self.threads_pane.set_model(model)
        #adjust sorting
        model=self.threads_pane.threads_tree.get_model()
        sort_col=self.configs["sort_col"].lower()
        sortings={"subject":1,"from":2,"date":6,"score":7}
        sort_col=sortings.get(sort_col,6)
        if self.configs["ascend_order"]=="True":
            sort_order=gtk.SORT_ASCENDING
        else:
            sort_order=gtk.SORT_DESCENDING
        model.set_sort_column_id(sort_col,sort_order)

    def get_server_for_group(self,group_name):
        server_name=""
        for group,server,id in self.subscribed_groups:
            if group==group_name: server_name=server
        return server_name

    def get_id_for_group(self,group_name):
        id_name=""
        for group,server,id in self.subscribed_groups:
            if group==group_name: id_name=id
        return id_name

    def view_group(self,*params):
        clicktype=params[-1]
        if self.configs["oneclick"]=="True" and clicktype=="doubleclick": return
        if self.configs["oneclick"]=="False" and clicktype=="oneclick": return
        if self.groups_lock==False:
            self.groups_lock=True
            model,path_list,iter_list=self.groups_pane.get_selected_rows()
            if iter_list:
                self.group_to_thread=model.get_value(iter_list[0],0)
                self.current_server=self.get_server_for_group(self.group_to_thread)
                self.article_pane.clear()
                self.show_threads(self.group_to_thread)
                self.msgids[self.group_to_thread]=None
            self.groups_lock=False
            if self.configs["expand_group"]=="True": self.expand_all_threads(None,True)

    def mark_for_download(self,article):
        '''mark article for download'''
        article.marked_for_download=not article.marked_for_download
        self.art_db.updateArticle(self.group_to_thread,article)


    def mark_subthread_for_download(self,model,root_iter,force_value=None):
        '''mark subthread for download'''
        xpn_article=self.threads_pane.get_article(model,root_iter)
        #let's mark the root article
        if force_value==True:
            if xpn_article.body==None:
                xpn_article.marked_for_download=force_value
        elif force_value==False:
            xpn_article.marked_for_download=force_value
        else:
            status=not xpn_article.marked_for_download
            if status==True:
                if xpn_article.body==None:
                    xpn_article.marked_for_download=status
            else:
                xpn_article.marked_for_download=status
        if xpn_article.marked_for_download:
            self.threads_pane.update_article_icon("download",root_iter)
        else:
            if xpn_article.is_read:
                self.threads_pane.update_article_icon("read",root_iter)
            elif xpn_article.body!=None:
                self.threads_pane.update_article_icon("body",root_iter)
            else:
                self.threads_pane.update_article_icon("unread",root_iter)
        self.art_db.updateArticle(self.group_to_thread,xpn_article)
        self.threads_pane.set_article(model,root_iter,xpn_article)
        
        iter_list=self.threads_pane.get_subthread(root_iter,model,[])
        
        for iter_child in iter_list:
            xpn_sub_article=self.threads_pane.get_article(model,iter_child)
            #watching others articles in the subthread
            if force_value==True:
                if xpn_sub_article.body==None:
                    xpn_sub_article.marked_for_download=force_value
            elif force_value==False:
                xpn_sub_article.marked_for_download=force_value
            else:
                status=xpn_article.marked_for_download
                if status==True:
                    if xpn_sub_article.body==None:
                        xpn_sub_article.marked_for_download=status
                else:
                    xpn_sub_article.marked_for_download=status
            
            if xpn_sub_article.marked_for_download:
                self.threads_pane.update_article_icon("download",iter_child)
            else:
                if xpn_sub_article.is_read:
                    self.threads_pane.update_article_icon("read",iter_child)
                elif xpn_sub_article.body!=None:
                    self.threads_pane.update_article_icon("body",iter_child)
                else:
                    self.threads_pane.update_article_icon("unread",iter_child)
            
            self.art_db.updateArticle(self.group_to_thread,xpn_sub_article)
            self.threads_pane.set_article(model,iter_child,xpn_sub_article)

        

    def mark_group_for_download(self,group):
        '''mark the whole group for download'''
        if group:
            self.art_db.markGroupForDownload(group)
            self.view_group(None,None)
    
    def keep_subthread(self, model, root_iter):
        xpn_root_article=self.threads_pane.get_article(model,root_iter)
        status= xpn_root_article.keep
        xpn_root_article.keep=not status
        if status:
            self.threads_pane.update_article_icon("unkeep",root_iter)
        else:
            self.threads_pane.update_article_icon("keep",root_iter)
        self.art_db.updateArticle(self.group_to_thread,xpn_root_article)
        self.threads_pane.set_article(model,root_iter,xpn_root_article)

        iter_list=self.threads_pane.get_subthread(root_iter,model,[])
        for iter_child in iter_list:
            xpn_sub_article=self.threads_pane.get_article(model,iter_child)
            xpn_sub_article.keep=not status
            if status:
                self.threads_pane.update_article_icon("unkeep",iter_child)
            else:
                self.threads_pane.update_article_icon("keep",iter_child)
            self.art_db.updateArticle(self.group_to_thread,xpn_sub_article)
            self.threads_pane.set_article(model,iter_child,xpn_sub_article)
    
                    

        
    def mark_subthread_read(self,model,root_iter,read):
        xpn_root_article=self.threads_pane.get_article(model,root_iter)
        if read:
            self.remove_from_unreads(xpn_root_article)
            self.threads_pane.update_article_icon("read",root_iter)
            self.threads_pane.set_is_unread(model,root_iter,False)
        else:
            self.insert_in_unreads(xpn_root_article)
            if xpn_root_article.body==None: self.threads_pane.update_article_icon("unread",root_iter)
            else: self.threads_pane.update_article_icon("body",root_iter)
            self.threads_pane.set_is_unread(model,root_iter,True)
        self.threads_pane.set_article(model,root_iter,xpn_root_article)

        iter_list=self.threads_pane.get_subthread(root_iter,model,[])
        for iter_child in iter_list:
            xpn_sub_article=self.threads_pane.get_article(model,iter_child)
            if read:
                self.remove_from_unreads(xpn_sub_article)
                self.threads_pane.update_article_icon("read",iter_child)
                self.threads_pane.set_is_unread(model,iter_child,False)
            else:
                self.insert_in_unreads(xpn_sub_article)
                if xpn_sub_article.body==None: self.threads_pane.update_article_icon("unread",iter_child)
                else: self.threads_pane.update_article_icon("body",iter_child)
                self.threads_pane.set_is_unread(model,iter_child,True)
            self.threads_pane.set_article(model,iter_child,xpn_sub_article)
                    
            
    
    def set_keep(self,article,group):
        '''set keep flag'''
        article.keep=not article.keep
        self.art_db.updateArticle(group,article)


    def set_watch(self,model,root_iter):
        #set watch flag and mark on subthread
        xpn_article=self.threads_pane.get_article(model,root_iter)
        xpn_article.watch=not xpn_article.watch
        
        show_threads=self.ui.get_widget("/MainMenuBar/View/view_group_opts/show_threads").get_active()
        
        if xpn_article.watch:
            xpn_article.ignore=False
            self.threads_pane.update_article_icon("watch",root_iter)
            self.threads_pane.update_watched_in_thread(xpn_article.watch,show_threads,True)
            self.threads_pane.update_watched_unread_in_thread(xpn_article.is_read,xpn_article.watch,show_threads,False,True,False)
        else:
            self.threads_pane.update_article_icon("unwatchignore",root_iter)
            self.threads_pane.update_watched_in_thread(xpn_article.watch,show_threads,False)
            self.threads_pane.update_watched_unread_in_thread(xpn_article.is_read,xpn_article.watch,show_threads,False,False,False)
        self.threads_pane.set_article(model,root_iter,xpn_article)
        self.art_db.updateArticle(self.group_to_thread,xpn_article)
        
        iter_list=self.threads_pane.get_subthread(root_iter,model,[])
        
        for iter_child in iter_list:
            #watching others articles in the subthread
            xpn_sub_article=self.threads_pane.get_article(model,iter_child)

            xpn_sub_article.watch=xpn_article.watch
            if xpn_sub_article.watch:
                self.threads_pane.update_article_icon("watch",iter_child)
                self.threads_pane.update_watched_in_thread(xpn_article.watch,show_threads,True)
                self.threads_pane.update_watched_unread_in_thread(xpn_article.is_read,xpn_article.watch,show_threads,False,True,False)
            else:
                self.threads_pane.update_article_icon("unwatchignore",iter_child)
                self.threads_pane.update_watched_in_thread(xpn_article.watch,show_threads,False)
                self.threads_pane.update_watched_unread_in_thread(xpn_article.is_read,xpn_article.watch,show_threads,False,False,False)
            xpn_sub_article.ignore=False
            self.art_db.updateArticle(self.group_to_thread,xpn_sub_article)
            self.threads_pane.set_article(model,iter_child,xpn_sub_article)

        self.mark_subthread_for_download(model,root_iter,xpn_article.watch)
    
    def set_ignore(self,model,root_iter):
        #set ignore flag and unmark on subthread
        xpn_article=self.threads_pane.get_article(model,root_iter)
        xpn_article.ignore=not xpn_article.ignore
        show_threads=self.ui.get_widget("/MainMenuBar/View/view_group_opts/show_threads").get_active()
        
        if xpn_article.watch:
            self.threads_pane.update_watched_in_thread(False,show_threads,False)
            self.threads_pane.update_watched_unread_in_thread(xpn_article.is_read,False,show_threads,False,False,False)
        
        if xpn_article.ignore:
            xpn_article.watch=False
            self.remove_from_unreads(xpn_article)
            self.threads_pane.update_article_icon("ignore",root_iter)
        else:
            self.insert_in_unreads(xpn_article)
            self.threads_pane.update_article_icon("unwatchignore",root_iter)
        self.threads_pane.set_article(model,root_iter,xpn_article)
        self.threads_pane.set_is_unread(model,root_iter,not xpn_article.is_read)
        
        iter_list=self.threads_pane.get_subthread(root_iter,model,[])
        
        for iter_child in iter_list:
            #watching others articles in the subthread
            xpn_sub_article=self.threads_pane.get_article(model,iter_child)
            xpn_sub_article.ignore=xpn_article.ignore
            if xpn_sub_article.ignore:
                xpn_sub_article.watch=False
                self.remove_from_unreads(xpn_sub_article)
                self.threads_pane.update_article_icon("ignore",iter_child)
            else:
                xpn_sub_article.watch=False
                self.insert_in_unreads(xpn_sub_article)
                self.threads_pane.update_article_icon("unwatchignore",iter_child)
            self.threads_pane.set_article(model,iter_child,xpn_sub_article)
            self.threads_pane.set_is_unread(model,iter_child,not xpn_sub_article.is_read)
        self.mark_subthread_for_download(model,root_iter,xpn_article.watch)

    def insert_in_unreads(self,article):
        #reinsert article in unreads
        self.groups_pane.update_read_vs_unread(article.is_read,True)
        show_threads=self.ui.get_widget("/MainMenuBar/View/view_group_opts/show_threads").get_active()
        self.threads_pane.update_unread_in_thread(article.is_read,show_threads,True)
        self.threads_pane.update_watched_unread_in_thread(article.is_read,article.watch,show_threads,True,False,True)
        
        article.is_read=False
        self.art_db.updateArticle(self.group_to_thread,article)



    def remove_from_unreads(self,article):
        #remove article from unreads
        self.groups_pane.update_read_vs_unread(article.is_read,False)
        show_threads=self.ui.get_widget("/MainMenuBar/View/view_group_opts/show_threads").get_active()
        self.threads_pane.update_unread_in_thread(article.is_read,show_threads,False)
        self.threads_pane.update_watched_unread_in_thread(article.is_read,article.watch,show_threads,False,False,True)
        article.is_read=True
        self.art_db.updateArticle(self.group_to_thread,article)

    def show_article(self,article):
        self.article_pane.delete_all()
        vadj=self.article_pane.text_scrolledwin.get_vadjustment()
        vadj.set_value(0)
        is_sign=False
        is_quote=False
        line_number=0
        mute_quote=not bool(self.ui.get_widget("/MainMenuBar/View/view_articles_opts/show_quote").get_active())
        mute_quote_text_inserted=False
        mute_sign=not bool(self.ui.get_widget("/MainMenuBar/View/view_articles_opts/show_sign").get_active())
        mute_sign_text_inserted=False

        RE_bold=r"(?:^|.)(\*.+?\*)(?=.|$)"
        RE_underline=r"(?:^|[.,:;\s(])(_.+?_)(?=[.,:;\s)]|$)"
        RE_italic=r"(?:^|[.,:;\s(])(/.+?/)(?=[.,:;\s)]|$)"
        RE_url=r"(https?://[-a-zA-Z0-9_$.+!*(),;:@%&=?~#'/]*[-a-zA-Z0-9_$+!*(@%&=?~#/])"
        RE_mid=r"(?:^|.)(?:<)([-a-zA-Z0-9_$.+!*(),;:%&=?~#'/]+@[-a-zA-Z0-9_$.+!*(),;:%&=?~#'/]+)(?:>)(?=.|$)"
        compiled_bold=re.compile(RE_bold,re.UNICODE|re.DOTALL)
        compiled_underline=re.compile(RE_underline,re.UNICODE)
        compiled_italic=re.compile(RE_italic,re.UNICODE|re.DOTALL)
        compiled_url=re.compile(RE_url)
        compiled_mid=re.compile(RE_mid)

        def quote_depth(line):
            count=0
            for char in line:
                if char==">":
                    count=count+1
                else:
                    break
            if count>3:
                count=3
            if count==0: #this prevent a warning during the mute_quote mode
                count=1
            return str(count)
        
        for line in article:
            line=line.replace("\r","") #this is needed for some strange articles
            insert_newline=True
            if len(line)>0:
                if line[0]==">":
                    is_quote=True
                elif (len(line)==2 and line[0:2]=="--") or (len(line)==3 and line[0:3]=="-- "):
                    is_sign=True
                    is_quote=False
                else:
                    is_quote=False
                tag_prefix=""
                
                if is_quote and not is_sign:
                    if mute_quote:
                        if mute_quote_text_inserted:
                            line=""
                            insert_newline=False
                        else:
                            line=_("> [...Muted Quote...]")
                            mute_quote_text_inserted=True
                    quote_level=quote_depth(line)
                    
                    self.article_pane.insert_with_tags(line,"quote"+quote_level)
                    tag_prefix="quote"+quote_level

                elif is_sign:
                    if mute_sign:
                        if mute_sign_text_inserted:
                            line=""
                            insert_newline=False
                        else:
                            line=_("[...Muted Sign...]")
                            mute_sign_text_inserted=True
                    self.article_pane.insert_with_tags(line,"sign")
                    tag_prefix="sign"
                    mute_quote_text_inserted=False

                else:
                    self.article_pane.insert_with_tags(line,"text")
                    tag_prefix="text"
                    mute_quote_text_inserted=False

                matches_bold=compiled_bold.finditer(line)
                matches_underline=compiled_underline.finditer(line)
                matches_italic=compiled_italic.finditer(line)
                matches_url=compiled_url.finditer(line)
                matches_mid=compiled_mid.finditer(line)
                
                self.apply_styles(matches_bold,tag_prefix,"_bold",line_number,1)
                self.apply_styles(matches_underline,tag_prefix,"_underline",line_number,1)
                self.apply_styles(matches_italic,tag_prefix,"_italic",line_number,1)
                self.apply_styles(matches_url,"","url",line_number,0)
                self.apply_styles(matches_mid,"","mid",line_number,1)
                
            if insert_newline:
                self.article_pane.insert("\n")
                line_number=line_number+1
        if self.ui.get_widget("/MainMenuBar/View/view_articles_opts/spoiler").get_active()==False:
            self.apply_spoiler()
        if self.ui.get_widget("/MainMenuBar/View/view_articles_opts/raw").get_active()==True:
            self.highlight_headers()

    def apply_styles(self,style_matched,tagPrefix,tagSuffix,line_number,group_number):
        for match in style_matched:
            iter_start=self.article_pane.buffer.get_start_iter()
            iter_start.set_line(line_number)
            iter_stop=iter_start.copy()
            iter_start.set_line_offset(match.start(group_number))
            iter_stop.set_line_offset(match.end(group_number))
            self.article_pane.buffer.delete(iter_start,iter_stop)
            self.article_pane.insert_with_tags_at_iter(iter_start,match.group(group_number),tagPrefix+tagSuffix)

    def highlight_headers(self):
        bounds=self.article_pane.buffer.get_bounds()
        RE_header="^.+?:"
        if bounds:
            start,stop=bounds
            text=self.article_pane.buffer.get_text(start,stop,True).decode("utf-8")
            text_splitted=text.splitlines()
            if "" in text_splitted:
                index=text_splitted.index("")
            else:
                index=0
            i=0
            headers_block=[]
            for i in range(index):
                headers_block.append(text_splitted[i])
            text='\n'.join(headers_block)
            match_header=re.compile(RE_header,re.UNICODE|re.MULTILINE).finditer(text)
            for match in match_header:
                match_start,match_stop,match_text= match.start(), match.end(), match.group()
                iter_start=self.article_pane.buffer.get_iter_at_offset(match_start)
                iter_stop=self.article_pane.buffer.get_iter_at_offset(match_stop)
                self.article_pane.buffer.delete(iter_start,iter_stop)
                self.article_pane.insert_with_tags_at_iter(iter_start,match_text,"quote1_bold")

    def apply_spoiler(self):
        bounds=self.article_pane.buffer.get_bounds()
        RE_spoiler=chr(12)+".+?"+chr(12)
        if bounds:
            start,stop=bounds
            text=self.article_pane.buffer.get_text(start,stop,True).decode("utf-8")
            matchs_spoiler=re.compile(RE_spoiler,re.UNICODE|re.DOTALL).finditer(text)
            for match in matchs_spoiler:
                match_start,match_stop,match_text= match.start(), match.end(), match.group()

                iter_start=self.article_pane.buffer.get_iter_at_offset(match_start)
                iter_stop=self.article_pane.buffer.get_iter_at_offset(match_stop)
                self.article_pane.buffer.delete(iter_start,iter_stop)
                self.article_pane.insert_with_tags_at_iter(iter_start,match_text,"spoiler")

            if divmod(text.count(chr(12)),2)[1]!=0:
                #the number of spoiler chars is an odd number
                pos=text.rindex(chr(12))
                iter_start=self.article_pane.buffer.get_iter_at_offset(pos)
                iter_stop=self.article_pane.buffer.get_end_iter()
                match_text=self.article_pane.buffer.get_text(iter_start,iter_stop)
                self.article_pane.buffer.delete(iter_start,iter_stop)
                self.article_pane.insert_with_tags_at_iter(iter_start,match_text,"spoiler")

 

    def retrieve_body(self,article_to_read,group,server_name=None,single_retrieve=True):
        if not server_name: 
            if self.current_server:
                server_name=self.current_server
            else:
                server_name=self.get_server_for_group(group)
        self.article_pane.textview.grab_focus()
        message=""
        bodyRetrieved=True
        body,bodyRetrieved,message=self.art_db.retrieveBody(article_to_read,group,server_name,self.connectionsPool,single_retrieve)
        if single_retrieve: self.statusbar.push(1,message)
        return body,bodyRetrieved

    def view_article(self,*params):
        #params=obj,path,column,clicktype
        def return_part_number(obj):
            self.part_to_show=0
            i=0
            for button in self.article_pane.multiparts_buttons:
                if obj==button:
                    self.part_to_show=i
                i=i+1
            self.view_article("oneclick")

        def get_and_show_body(article_to_read,body):
            try: article_to_read.body_parts
            except: pass
            else:
                self.article_pane.add_parts_buttons(article_to_read.body_parts)
                for button in self.article_pane.multiparts_buttons: button.connect("released",return_part_number)
                try: 
                    body=article_to_read.body_parts[self.part_to_show][1].splitlines()
                    self.article_pane.multiparts_buttons[self.part_to_show].set_active(True)
                except: body=article_to_read.body_parts[0][1].splitlines()
            if show_raw and bodyRetrieved:
                body=article_to_read.get_raw()
            self.show_article(body)

        
        clicktype=params[-1]
        treesel=self.threads_pane.threads_tree.get_selection()
        model,iter_selected=treesel.get_selected()
        show_raw=bool(self.ui.get_widget("/MainMenuBar/View/view_articles_opts/raw").get_active())
        if iter_selected!=None:
            article_to_read=self.threads_pane.get_article(model,iter_selected)
            self.msgids[self.group_to_thread]=article_to_read.msgid
            if self.configs["oneclick_article"]=="True" and clicktype=="doubleclick": return
            if self.configs["oneclick_article"]=="False" and clicktype=="oneclick":
                self.article_pane.clear()
                self.article_pane.update_headers_labels(article_to_read)
                #body=article_to_read.get_body()
                if (article_to_read.is_read) and (article_to_read.has_body):
                    body=self.art_db.getBodyFromDB(article_to_read.original_group,article_to_read)
                    bodyRetrieved=True
                    get_and_show_body(article_to_read,body)
                    self.article_pane.update_headers_labels(article_to_read)

                self.article_pane.set_face_x_face(article_to_read.face,article_to_read.x_face)
                return
            
            #self.article_pane.textview.grab_focus()
            body,bodyRetrieved=self.retrieve_body(article_to_read,article_to_read.original_group)

########AGGIUSTARE QUA###################
######QUANDO IL CORPO E' VUOTO BODY E' FALSO E IL PROGRAMMA NON VA AVANTI###########
#####PER IL MOMENTO METTO !=NONE MA E' DA VERIFICARE NEI CASI DI ERRORI###########
            if body!=None:
                self.article_pane.clear()
                if bodyRetrieved:
                    self.threads_pane.set_is_unread(model,iter_selected,False)
                    self.threads_pane.update_article_icon("read")
                    self.remove_from_unreads(article_to_read)
                    self.article_pane.update_headers_labels(article_to_read)

                get_and_show_body(article_to_read,body)
                self.article_pane.set_face_x_face(article_to_read.face,article_to_read.x_face)

            self.threads_pane.threads_tree.grab_focus()


    def view_next_article(self,obj):
        treesel=self.threads_pane.threads_tree.get_selection()
        model,iter_selected=treesel.get_selected()
        column=self.threads_pane.threads_tree.get_column(0)

        if iter_selected==None:
            iter_new=model.get_iter_first()
        else:
            path=model.get_path(iter_selected)        
            iter_new=self.threads_pane.find_next_row(model,iter_selected)
        if iter_new!=None:
            path=model.get_path(iter_new)
            self.threads_pane.threads_tree.expand_row(path,False)
            #need these 3 lines to update the view and correctly point the cursor
            self.threads_pane.threads_tree.queue_draw()
            while gtk.events_pending():
                gtk.main_iteration(False)
            self.threads_pane.threads_tree.scroll_to_cell(path,None,True,0.4,0.0)
            self.threads_pane.threads_tree.set_cursor(path,None,False)
            self.threads_pane.threads_tree.row_activated(path,column)

    def view_next_unread_article(self,obj):
        treesel=self.threads_pane.threads_tree.get_selection()
        model,iter_selected=treesel.get_selected()
        column=self.threads_pane.threads_tree.get_column(0)
        if iter_selected==None:
            iter_selected=model.get_iter_first()
        if iter_selected!=None:
            read_status=self.threads_pane.get_is_unread(model,iter_selected)
        else:
            read_status=False
        while (not read_status) and (iter_selected!=None):
            iter_selected=self.threads_pane.find_next_row(model,iter_selected)
            if iter_selected!=None:
                read_status=self.threads_pane.get_is_unread(model,iter_selected)
            else:
                read_status=False
        if read_status:
            path=model.get_path(iter_selected)
            root_path=[]
            root_path.append(path[0])
            root_path=tuple(root_path)
            self.threads_pane.threads_tree.expand_row(root_path,True)
            #need these 3 lines to update the view and correctly point the cursor
            self.threads_pane.threads_tree.queue_draw()
            while gtk.events_pending():
                gtk.main_iteration(False)
            self.threads_pane.threads_tree.grab_focus()
            self.threads_pane.threads_tree.scroll_to_cell(path,None,True,0.4,0.0)
            self.threads_pane.threads_tree.set_cursor(path,None,False)
            self.threads_pane.threads_tree.row_activated(path,column)




    def view_previous_article(self,obj):
        treesel=self.threads_pane.threads_tree.get_selection()
        model,iter_selected=treesel.get_selected()
        column=self.threads_pane.threads_tree.get_column(0)
        if iter_selected==None:
            iter_new=model.get_iter_first()
        else:
            iter_new=self.threads_pane.find_previous_row(model,iter_selected)
        if iter_new!=None:
            path=model.get_path(iter_new)
            self.threads_pane.threads_tree.set_cursor(path,None,False)
            self.threads_pane.threads_tree.row_activated(path,column)

    def view_parent_article(self,obj):
        model,iter_son=self.threads_pane.threads_tree.get_selection().get_selected()
        if iter_son!=None:
            article_son=self.threads_pane.get_article(model,iter_son)
            references=article_son.ref
            if references=="":
                self.statusbar.push(1,_("This is root article"))
            else:
                idx=references.rindex("<")
                last_ref=references[idx:]

                #First search the parent in the threaded articles
                iter_current=model.get_iter_first()
                success=False
                while iter_current!=None and not success:
                    article_mom=self.threads_pane.get_article(model,iter_current)
                    if article_mom.msgid==last_ref:
                        #It is in the threads, let's show the article selecting its row
                        path=model.get_path(iter_current)
                        self.threads_pane.threads_tree.set_cursor(path,None,False)
                        self.threads_pane.threads_tree.row_activated(path,self.threads_pane.column1)
                        self.statusbar.push(1,_("Article Found"))
                        success=True
                    else:
                        iter_current=self.threads_pane.find_next_row(model,iter_current)

                if not success:
                    #Let' search the article on the server
                    message,number=self.connectionsPool[self.current_server].getArticleNumber(article_son.original_group,last_ref)
                    self.statusbar.push(1,message)
                    if number!=-1:
                        message,headers,last=self.connectionsPool[self.current_server].getHeaders(article_son.original_group,number,number)
                        self.statusbar.push(1,message)
                        if headers:
                            number,subj,from_name,date,msgid,ref,bytes,lines,xref=headers[0]
                            #If it is not in the threaded articles, let's insert a node for this article
                            article=Article(number,msgid,from_name,ref,subj,date,self.configs["fallback_charset"],article_son.original_group,xref,bytes,lines)
                            #applying score rules
                            score=self.score_rules.apply_score_rules(article,article.original_group)
                            article.set_score(score)
                            nick,from_name,ref,subj,date,date_parsed=article.get_headers()
                            art_unread=gtk.gdk.pixbuf_new_from_file("pixmaps/art_unread.xpm")
                            art_unkeep=gtk.gdk.pixbuf_new_from_file("pixmaps/art_unkeep.xpm")

                            if score<0:
                                score_foreground="red"
                            else:
                                score_foreground="darkgreen"
                            if score==0:
                                show_score=False
                            else:
                                show_score=True     
                            
                            iter_new=self.threads_pane.insert(model,None,iter_son,[art_unread,subj,nick,date_parsed,article,True,article.secs,article.score,score_foreground,show_score,art_unkeep,])
                            path=model.get_path(iter_new)
                            self.threads_pane.threads_tree.set_cursor(path,None,False)
                            self.threads_pane.threads_tree.row_activated(path,self.threads_pane.column1)
                            self.statusbar.push(1,_("Article loaded"))
                        else:
                            self.statusbar.push(1,_("This article is not available on the server"))
                    else:
                        self.statusbar.push(1,_("This article is not available on the server"))

    def show_activity_list(self,activity_list):
        msg=_("There are new articles in watched threads: ")
        report=""
        if activity_list:
            for group,number in activity_list.iteritems():
                report+=group+": "+str(number)+"\n"
            d=Dialog_OK(msg+"\n\n"+report)

    def get_new_headers(self,obj):
        "Download new headers for the subscribed"
        subscribed=self.art_db.getSubscribed()
        activity_list=dict()
        for group in subscribed:
            s1=len(self.art_db.getWatched(group[0]))
            group[1]=self.download_headers(group[0],group[1],group[2])
            s2=len(self.art_db.getWatched(group[0]))
            if s2>s1: activity_list[group[0]]=s2-s1
        self.art_db.updateSubscribed(subscribed)
        self.statusbar.push(1,_("Download Completed"))
        model,path,iter_selected=self.groups_pane.get_first_selected_row()
        msgid_selected=self.msgids.get(self.group_to_thread,None)
        self.show_subscribed()
        if iter_selected:
            self.groups_pane.groups_list.set_cursor(path,None,False)
            self.groups_pane.groups_list.row_activated(path,self.groups_pane.groups_list.get_column(0))
        self.show_activity_list(activity_list)
        self.select_article_again(msgid_selected)
        return True #for timeout_add
        
    def select_article_again(self,msgid_selected):
        #let's select again the selected article
        if msgid_selected:
            treesel=self.threads_pane.threads_tree.get_selection()
            model,iter_selected=treesel.get_selected()
            iter_new=model.get_iter_first()
            while iter_new:
                article=self.threads_pane.get_article(model,iter_new)
                path=model.get_path(iter_new)
                if article.msgid == msgid_selected:
                    if len(path)>1: self.threads_pane.threads_tree.expand_row((path[0],),True)
                    self.threads_pane.threads_tree.scroll_to_cell(path,None,True,0.4,0.0)
                    self.threads_pane.threads_tree.set_cursor(path,None,False)
                iter_new=self.threads_pane.find_next_row(model,iter_new)

    
    def get_new_headers_selected(self,obj):
        "Dowload new headers for selected group"
        subscribed=self.art_db.getSubscribed()
        model,path_list,iter_list=self.groups_pane.get_selected_rows()
        activity_list=dict()
        msgid_selected=self.msgids.get(self.group_to_thread,None)
        for path in path_list:
            iter_selected=model.get_iter(path)
            group_name=model.get_value(iter_selected,0)
            for group in subscribed:
                if group[0]==group_name:
                    s1=len(self.art_db.getWatched(group[0]))
                    group[1]=self.download_headers(group[0],group[1],group[2])
                    s2=len(self.art_db.getWatched(group[0]))
                    if s2>s1: activity_list[group_name]=s2-s1
        self.art_db.updateSubscribed(subscribed)
        if path_list:
            self.show_subscribed()
            self.groups_pane.groups_list.set_cursor(path_list[0],None,False)
            self.groups_pane.groups_list.row_activated(path_list[0],self.groups_pane.groups_list.get_column(0))
            self.show_activity_list(activity_list)
        self.select_article_again(msgid_selected)

    def download_headers(self,group,last_number,server_name):
        first=int(last_number)+1
        #Downloading headers
        self.progressbar.set_text(_("Fetching Headers"))
        self.progressbar.set_fraction(1/float(2))
        while gtk.events_pending():
            gtk.main_iteration(False)
        if self.configs["limit_articles"]=="True":
            articles_number=int(self.configs["limit_articles_number"])
            message,total_headers,last=self.connectionsPool[server_name].getHeaders(group,first,count=articles_number)
        else:            
            message,total_headers,last=self.connectionsPool[server_name].getHeaders(group,first)
        if last!=-1:
            last_number=str(last)
        self.statusbar.push(1,message)
        if total_headers:
            self.progressbar.set_text(_("Building Articles"))
            if not self.window.get_property("is-active"):
                self.trayicon.set_blinking(True)
        else:
            self.progressbar.set_text(_("No New Headers"))
        self.progressbar.set_fraction(2/float(2))
        while gtk.events_pending():
            gtk.main_iteration(False)

        self.art_db.addHeaders(group,total_headers,server_name,self.connectionsPool)

        self.progressbar.set_fraction(0)
        self.progressbar.set_text("")
        return last_number

    def reapply_score_actions_rules(self,obj):
        subscribed=self.art_db.getSubscribed()

        j=0
        for group in subscribed:
            j=j+1
            self.progressbar.set_fraction(j/float(len(subscribed)))
            self.progressbar.set_text("%s / %s" % (j,len(subscribed)))
            self.statusbar.push(1,_("Refreshing Group %s") % group[0])
            while gtk.events_pending():
                gtk.main_iteration(False)

            for xpn_article in self.art_db.getArticles(group[0]):
                xpn_article.reset_article_score_actions()
                self.art_db.updateArticle(group[0],xpn_article)
            
            self.art_db.reapply_rules(group[0],group[2],self.connectionsPool)
                
        model,path,iter_selected=self.groups_pane.get_first_selected_row()
        if iter_selected:
            self.show_subscribed()
            self.groups_pane.groups_list.set_cursor(path,None,False)
            self.groups_pane.groups_list.row_activated(path,self.groups_pane.groups_list.get_column(0))
        self.progressbar.set_fraction(0)
        self.progressbar.set_text("")
        self.statusbar.push(1,"")

    def get_bodies(self,obj):
        "Download bodies for marked articles"
                
        subscribed=self.art_db.getSubscribed()
        
        
        i=0
        length=float(len(subscribed))
        for group in subscribed:
            i=i+1
            self.progressbar.set_fraction(i/length)
            self.download_bodies(group[0],group[2])
        self.threads_pane.clear()
        self.article_pane.clear()
        self.progressbar.set_fraction(0)
        self.progressbar.set_text("")
        self.statusbar.push(1,_("Download Completed"))
        model,path,iter_selected=self.groups_pane.get_first_selected_row()
        msgid_selected=self.msgids.get(self.group_to_thread,None)
        if iter_selected:
            self.show_subscribed()
            self.groups_pane.groups_list.set_cursor(path,None,False)
            self.groups_pane.groups_list.row_activated(path,self.groups_pane.groups_list.get_column(0))
        self.select_article_again(msgid_selected)

    def get_bodies_selected(self,obj):
        "Download bodies for marked articles in selected group"
        
        subscribed=self.art_db.getSubscribed()

        model,path_list,iter_list=self.groups_pane.get_selected_rows()
        for path in path_list:
            iter_selected=model.get_iter(path)
            group_name=model.get_value(iter_selected,0)
            for group in subscribed:
                if group[0]==group_name:
                    self.download_bodies(group[0],group[2])
        msgid_selected=self.msgids.get(self.group_to_thread,None)
        if path_list:
            self.threads_pane.clear()
            self.article_pane.clear()
            self.progressbar.set_fraction(0)
            self.progressbar.set_text("")
            self.statusbar.push(1,_("Download Completed"))
            self.groups_pane.groups_list.set_cursor(path_list[0],None,False)
            self.groups_pane.groups_list.row_activated(path_list[0],self.groups_pane.groups_list.get_column(0)) 
        self.select_article_again(msgid_selected)
        
    def download_bodies(self,group,server_name):
        self.statusbar.push(1,_("Downloading Bodies for %s") % (group,))
        marked_articles=[]
        for article in self.art_db.getArticles(group):
            if article.marked_for_download:
                marked_articles.append(article)
        #j=0
        #length=len(marked_articles)
        for article in marked_articles:
            #j=j+1
            body,bodyRetrieved=self.retrieve_body(article,group,server_name,False)
            #self.progressbar.set_fraction(j/float(length))
            #self.progressbar.set_text(_("Downloading %s of %s") % (j,length))
            while gtk.events_pending():
                gtk.main_iteration(False)
        self.art_db._commitGroups([group,])

    
    def one_key_reading(self,obj):
        #increment=80
        vadj=self.article_pane.text_scrolledwin.get_vadjustment()
        increment= vadj.page_increment * int(self.configs["scroll_fraction"]) / 100
        value= vadj.get_value()
        if value+increment+vadj.page_size<vadj.upper:
            vadj.set_value(value+increment)
        else:
            if vadj.upper-vadj.page_size==vadj.get_value():
                self.view_next_unread_article(None)
            else:
                vadj.set_value(vadj.upper-vadj.page_size)

    def one_key_move_up(self,obj):
        vadj=self.article_pane.text_scrolledwin.get_vadjustment()
        decrement= vadj.page_increment * int(self.configs["scroll_fraction"]) / 100
        value= vadj.get_value()
        if value-decrement>vadj.lower:
            vadj.set_value(value-decrement)
        else:
            vadj.set_value(vadj.lower)
        
    def expand_all_threads(self,obj,expand):
        if expand: self.threads_pane.threads_tree.expand_all()
        else: self.threads_pane.threads_tree.collapse_all()
        self.threads_pane.threads_tree.queue_draw()

    
    def expand_selected_row(self,obj,expand):
        treesel=self.threads_pane.threads_tree.get_selection()
        model,iter_selected=treesel.get_selected()
        if iter_selected:
            path=model.get_path(iter_selected)
            if expand: self.threads_pane.threads_tree.expand_row(path,True)
            else: self.threads_pane.threads_tree.collapse_row(path)
            self.threads_pane.threads_tree.queue_draw()



    def mark_group(self,obj,mark_read):
        "Mark selected groups read or unread"
        model,path_list,iter_list=self.groups_pane.get_selected_rows()
        for path in path_list:
            iter_selected=model.get_iter(path)
            group_to_mark=model.get_value(iter_selected,0)
            self.art_db.markGroupRead(group_to_mark,mark_read)
        if path_list:
            self.show_subscribed()

    def mark_all_groups(self,obj,mark_read):
        "Mark all groups read or unread"
        subscribed=self.art_db.getSubscribed()
        for group in subscribed:
            group_to_mark=group[0]
            self.art_db.markGroupRead(group_to_mark,mark_read)
        self.show_subscribed()

    def keep_group(self,obj):
        "Set keep flag on the whole selected groups"
        model,path_list,iter_list=self.groups_pane.get_selected_rows()
        for path in path_list:
            iter_selected=model.get_iter(path)
            group_to_mark=model.get_value(iter_selected,0)
            self.art_db.keepGroup(group_to_mark)
        self.show_subscribed()
 
    def rot13(self,text):
        "Rot13 the string passed"
        string_coded = ""
        dic={'a':'n','b':'o','c':'p','d':'q','e':'r','f':'s','g':'t',
             'h':'u','i':'v','j':'w','k':'x','l':'y','m':'z',
             'n':'a','o':'b','p':'c','q':'d','r':'e','s':'f','t':'g',
             'u':'h','v':'i','w':'j','x':'k','y':'l','z':'m',
             'A':'N','B':'O','C':'P','D':'Q','E':'R','F':'S','G':'T',
             'H':'U','I':'V','J':'W','K':'X','L':'Y','M':'Z',
             'N':'A','O':'B','P':'C','Q':'D','R':'E','S':'F','T':'G',
             'U':'H','V':'I','W':'J','X':'K','Y':'L','Z':'M'}
        for c in text:
            char=dic.get(c,c)
            string_coded=string_coded+char
        return string_coded

    def apply_rot13(self,obj):
        bounds=self.article_pane.buffer.get_selection_bounds()
        if bounds:
            #rot selected text
            start=bounds[0]
            stop=bounds[1]
            self.article_pane.buffer.create_mark("start_rot13",start,True)

            text=self.article_pane.buffer.get_text(start,stop,True).decode("utf-8")
            text_rotted=self.rot13(text)
            self.article_pane.buffer.delete_selection(False,False)
            self.article_pane.insert(text_rotted)

            start=self.article_pane.buffer.get_iter_at_mark(self.article_pane.buffer.get_mark("start_rot13"))
            self.article_pane.buffer.move_mark_by_name("insert",start)
        else:
            #rot the article
            bounds=self.article_pane.buffer.get_bounds()
            if bounds:
                start,stop=bounds
                text=self.article_pane.buffer.get_text(start,stop,True).decode("utf-8")
                text_rotted=self.rot13(text)
                self.show_article(text_rotted.split("\n"))


    def set_fixed_pitch(self,obj):
        monospace=pango.FontDescription("Monospace 9")
        user=pango.FontDescription(self.configs["font_name"])
        style=self.article_pane.textview.get_style().copy()
        if style.font_desc.get_family()!=monospace.get_family():
            self.article_pane.textview.modify_font(monospace)
        else:
            self.article_pane.textview.modify_font(user)


    def show_hide_headers(self,obj):
        self.article_pane.expander.set_expanded(not self.article_pane.expander.get_expanded())

    def export_newsrc(self,obj):
        def dispatch_response(dialog,id):
            if id==gtk.RESPONSE_OK:
                self.save_newsrc(None)
            if id==gtk.RESPONSE_CANCEL:
                self.file_dialog.destroy()
        self.file_dialog=gtk.FileChooserDialog(_("Select Newsrc Export Path"),None,gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER,(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_SAVE,gtk.RESPONSE_OK))
        self.file_dialog.set_local_only(True)
        #self.file_dialog.set_current_name("newsrc")
        self.file_dialog.connect("response",dispatch_response)
        path=self.file_dialog.get_current_folder()
        self.file_dialog.set_current_folder(path)
        self.file_dialog.show()

    def import_newsrc(self,obj):
        def dispatch_response(dialog,id):
            if id==gtk.RESPONSE_OK:
                self.load_newsrc(None)
            if id==gtk.RESPONSE_CANCEL:
                self.file_dialog.destroy()

        def show_hide_hidden(obj):
            self.file_dialog.set_property("show_hidden",obj.get_active())

        self.file_dialog=gtk.FileChooserDialog(_("Select Newsrc File"),None,gtk.FILE_CHOOSER_ACTION_OPEN,(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_OPEN,gtk.RESPONSE_OK))
        hidden_checkbutton=gtk.CheckButton(_("Show Hidden Files"))
        self.file_dialog.set_extra_widget(hidden_checkbutton)
        hidden_checkbutton.connect("clicked",show_hide_hidden)
        self.file_dialog.set_local_only(True)
        self.file_dialog.connect("response",dispatch_response)
        path=self.file_dialog.get_current_folder()
        self.file_dialog.set_current_folder(path)
        self.file_dialog.show()

    def save_newsrc(self,obj):
        path=self.file_dialog.get_filename()
        newsrc_file=ExportNewsrc(self.art_db)
        newsrc_file.save_newsrc(path)
        self.file_dialog.destroy()
        self.statusbar.push(1,newsrc_file.message)

    def load_newsrc(self,obj):
        path=self.file_dialog.get_filename()
        self.file_dialog.destroy()
        file_name=os.path.split(path)[1] 
        try:
            server_name=file_name[0:file_name.index(".newsrc")]        
        except:
            server_name=""
        
        d=Dialog_Import_Newsrc(_("""To correctly import a newsrc file you have to use the same server you used when you saved the file.\n
By default XPN uses a name like 'server_name.newsrc' so it is possible to know wich server was used\n
When you try to import a newsrc file XPN searches for the server name in the file name.\n\n
<b>Server To Use:</b>"""),server_name)
        if d.resp==gtk.RESPONSE_OK:
            server_name=d.server_name
            try:
                f=open(path,"rb")
            except IOError:
                self.statusbar.push(1,_("File does not exist"))
            else:
                newsrc_file=f.readlines()
                imp_newsrc=ImportNewsrc(newsrc_file,self,self.configs,server_name)
                self.show_subscribed()
                self.progressbar.set_fraction(0.0)
                self.progressbar.set_text("")
                self.statusbar.push(1,_("Newsrc successful imported"))

    def modify_keybord_shortcuts(self,obj):
        self.shortcuts_win=KeyBindings(self)

    def context_mark_read(self,obj):
        treesel=self.threads_pane.threads_tree.get_selection()
        model,iter_selected=treesel.get_selected()
        if iter_selected!=None:
            article=self.threads_pane.get_article(model,iter_selected)
            self.remove_from_unreads(article)
            self.threads_pane.update_article_icon("read")
            self.threads_pane.set_is_unread(model,iter_selected,False)
            
            next_iter=self.threads_pane.find_next_row(model,iter_selected)
            if next_iter!=None and self.configs.get("advance_on_mark","False")=="True":
                old_path=model.get_path(iter_selected)
                if not self.threads_pane.threads_tree.row_expanded(old_path):
                    self.threads_pane.threads_tree.set_cursor(old_path,None,False)
                    self.threads_pane.threads_tree.expand_row(old_path,False)
                path=model.get_path(next_iter)
                self.threads_pane.threads_tree.expand_row(path,False)
                self.threads_pane.threads_tree.scroll_to_cell(path,None,True,0.4,0.0)
                self.threads_pane.threads_tree.set_cursor(path,None,False)

    def context_mark_unread(self,obj):
        treesel=self.threads_pane.threads_tree.get_selection()
        model,iter_selected=treesel.get_selected()
        if iter_selected!=None:
            article=self.threads_pane.get_article(model,iter_selected)            
            self.insert_in_unreads(article)
            self.threads_pane.set_is_unread(model,iter_selected,True)
            if article.body==None:
                self.threads_pane.update_article_icon("unread")
            else:
                self.threads_pane.update_article_icon("body")
            next_iter=self.threads_pane.find_next_row(model,iter_selected)
            if next_iter!=None and self.configs.get("advance_on_mark","False")=="True":
                old_path=model.get_path(iter_selected)
                if not self.threads_pane.threads_tree.row_expanded(old_path):
                    self.threads_pane.threads_tree.set_cursor(old_path,None,False)
                    self.threads_pane.threads_tree.expand_row(old_path,False)
                path=model.get_path(next_iter)
                self.threads_pane.threads_tree.expand_row(path,False)
                self.threads_pane.threads_tree.scroll_to_cell(path,None,True,0.4,0.0)
                self.threads_pane.threads_tree.set_cursor(path,None,False)

    def context_keep(self,obj):
        treesel=self.threads_pane.threads_tree.get_selection()
        model,iter_selected=treesel.get_selected()
        if iter_selected!=None:
            article=self.threads_pane.get_article(model,iter_selected)
            self.set_keep(article,self.group_to_thread)
            if article.keep:
                self.threads_pane.update_article_icon("keep")
            else:
                self.threads_pane.update_article_icon("unkeep")
            next_iter=self.threads_pane.find_next_row(model,iter_selected)
            if next_iter!=None and self.configs.get("advance_on_mark","False")=="True":
                old_path=model.get_path(iter_selected)
                if not self.threads_pane.threads_tree.row_expanded(old_path):
                    self.threads_pane.threads_tree.set_cursor(old_path,None,False)
                    self.threads_pane.threads_tree.expand_row(old_path,False)
                path=model.get_path(next_iter)
                self.threads_pane.threads_tree.expand_row(path,False)
                self.threads_pane.threads_tree.scroll_to_cell(path,None,True,0.4,0.0)
                self.threads_pane.threads_tree.set_cursor(path,None,False)

    def context_delete(self,obj):
        treesel=self.threads_pane.threads_tree.get_selection()
        model,iter_selected=treesel.get_selected()
        if iter_selected!=None:
            article=self.threads_pane.get_article(model,iter_selected)
            self.art_db.deleteArticle(self.group_to_thread,article)
            if model.iter_has_child(iter_selected):
                self.threads_pane.delete_row(model,iter_selected)
                self.show_threads(self.group_to_thread)
            else:
                self.threads_pane.delete_row(model,iter_selected)
            self.groups_pane.removed_article(article.is_read)

    def context_keep_sub(self,obj):
        treesel=self.threads_pane.threads_tree.get_selection()
        model,iter_selected=treesel.get_selected()
        if iter_selected!=None:
            self.keep_subthread(model,iter_selected)

    def context_watch(self,obj):
        treesel=self.threads_pane.threads_tree.get_selection()
        model,iter_selected=treesel.get_selected()
        if iter_selected!=None:
            self.set_watch(model,iter_selected)

    def context_ignore(self,obj):
        treesel=self.threads_pane.threads_tree.get_selection()
        model,iter_selected=treesel.get_selected()
        if iter_selected!=None:
            self.set_ignore(model,iter_selected)

    def context_modify_score(self,obj,action):
        treesel=self.threads_pane.threads_tree.get_selection()
        model,iter_selected=treesel.get_selected()
        if iter_selected!=None:
            article=self.threads_pane.get_article(model,iter_selected)
            newsgroup=self.group_to_thread
            from_name=article.from_name
            self.score_win=Score_Win(self.score_rules,self)
            self.score_win.header_opt_menu.set_active(0)
            self.score_win.scope_combo.child.set_text("["+newsgroup+"]")
            self.score_win.match_type_opt_menu.set_active(0)
            self.score_win.match_value_entry.set_text(from_name.encode("utf-8"))
            self.score_win.case_checkbutton.set_active(True)
            self.score_win.score_mod_spinbutton.set_value(100)
            self.score_win.score_mod_opt_menu.set_active(action)
            self.score_win.show()
            self.score_win.notebook.set_current_page(1)

    def context_mark_download(self,obj):
        treesel=self.threads_pane.threads_tree.get_selection()
        model,iter_selected=treesel.get_selected()
        if iter_selected!=None:
            article=self.threads_pane.get_article(model,iter_selected)
            if article.body==None:
                self.mark_for_download(article)
                if article.marked_for_download:
                    self.threads_pane.update_article_icon("download")
                elif article.body!=None:
                    self.threads_pane.update_article_icon("body")
                else:
                    self.threads_pane.update_article_icon("unread")
                next_iter=self.threads_pane.find_next_row(model,iter_selected)
                if next_iter!=None and self.configs.get("advance_on_mark","False")=="True":
                    old_path=model.get_path(iter_selected)
                    if not self.threads_pane.threads_tree.row_expanded(old_path):
                        self.threads_pane.threads_tree.set_cursor(old_path,None,False)
                        self.threads_pane.threads_tree.expand_row(old_path,False)
                    path=model.get_path(next_iter)
                    self.threads_pane.threads_tree.expand_row(path,False)
                    self.threads_pane.threads_tree.scroll_to_cell(path,None,True,0.4,0.0)
                    self.threads_pane.threads_tree.set_cursor(path,None,False)

    def context_mark_download_sub(self,obj):
        treesel=self.threads_pane.threads_tree.get_selection()
        model,iter_selected=treesel.get_selected()
        if iter_selected!=None:
            self.mark_subthread_for_download(model,iter_selected)
    
    def context_mark_read_sub(self,obj,read):
        treesel=self.threads_pane.threads_tree.get_selection()
        model,iter_selected=treesel.get_selected()
        if iter_selected!=None:
            self.mark_subthread_read(model,iter_selected,read)

    
    
    def context_mark_download_group(self,obj):
        model,path_list,iter_list=self.groups_pane.get_selected_rows()
        for path in path_list:
            iter_selected=model.get_iter(path)
            group_to_mark=model.get_value(iter_selected,0)
            self.mark_group_for_download(group_to_mark)

    def threads_context_menu(self,obj,event):
        if event.button==3:
            menu=self.ui.get_widget("/flags")
            menu.popup(None,None,None,event.button,event.time)
    
    def groups_context_menu(self,obj,event):
        if event.button==3:
            menu=self.ui.get_widget("/mark_group")
            menu.popup(None,None,None,event.button,event.time)

    def find_article(self,obj):
        self.find_win=Find_Win(self)
        self.find_win.show()

    def global_search(self,obj):
        self.GlobalSearch=GlobalSearch(self)
        self.GlobalSearch.show()

    def search_in_the_article(self,obj):
        self.search_win=Search_Win(self)
        self.search_win.show()

    def connect_signals(self):
        #menuitems signals

        #groups_pane signals
        self.groups_pane.groups_list.connect("button_release_event",self.groups_context_menu)
        self.groups_pane.groups_list.connect("row_activated",self.view_group,"doubleclick")
        self.groups_pane.groups_list.get_selection().connect("changed",self.view_group,"oneclick")

        #threads_pane signals
        self.threads_pane.threads_tree.connect("button_release_event",self.threads_context_menu)
        self.threads_pane.threads_tree.connect("row_activated",self.view_article,"doubleclick")
        self.threads_pane.threads_tree.get_selection().connect("changed",self.view_article, "oneclick")
        
        self.threads_pane.column2.connect("clicked",self.save_sorting_type)
        self.threads_pane.column3.connect("clicked",self.save_sorting_type)
        self.threads_pane.column4.connect("clicked",self.save_sorting_type)
        self.threads_pane.column5.connect("clicked",self.save_sorting_type)

        
        #article_pane_signals
        self.article_pane.vbox.connect("mid_clicked",self.mid_clicked)

    def mid_clicked(self,obj,mid):
        dia=MidDialog(mid)
        if dia.resp==gtk.RESPONSE_OK:
            mid=dia.entry.get_text()
            if dia.sel[0]:
                self.find_article(None)
                self.find_win.entry_msgid.set_text(mid)
                self.find_win.checkbutton_start.set_active(True)
            elif dia.sel[1]:
                self.global_search(None)
                self.GlobalSearch.entry_msgid.set_text(mid)
            else:
                if self.article_pane.use_custom_browser:
                    launcher=webbrowser.get("xpn_launcher")
                    launcher.open("http://groups.google.com/groups?selm="+url_quote(mid))
                else:
                    webbrowser.open("http://groups.google.com/groups?selm="+url_quote(mid))
                    
    def build_panes(self):
        self.groups_pane=Groups_Pane(_("Newsgroups"),_("UnRead"),True,self.configs)
        self.threads_pane=Threads_Pane(self.configs)
        if self.configs["show_headers"]=="True":
            show_headers=True
        else:
            show_headers=False
        self.article_pane=Article_Pane(show_headers,self.configs)

    def set_sizes(self):
        try:
            f=open(os.path.join(self.wdir,"dats/sizes.dat"),"rb")
        except IOError:
            vpaned_pos=120
            hpaned_pos=200
            groups_col1_width=145
            threads_col_subject_width=415
            threads_col_from_width=201
            threads_col_date_width=95
            self.window.maximize()
        else:
            sizes=cPickle.load(f)
            f.close()
            vpaned_pos=sizes.get("vpaned_pos",120)
            hpaned_pos=sizes.get("hpaned_pos",200)
            mainwin_width=sizes.get("mainwin_width",640)
            mainwin_height=sizes.get("mainwin_height",480)
            mainwin_pos_x=sizes.get("mainwin_pos_x",0)
            mainwin_pos_y=sizes.get("mainwin_pos_y",0)
            groups_col1_width=int(sizes.get("groups_col1",145))
            threads_col_subject_width=int(sizes.get("threads_col_subject",415))
            threads_col_from_width=int(sizes.get("threads_col_from",201))
            threads_col_date_width=int(sizes.get("threads_col_date",95))
            self.window.resize(int(mainwin_width),int(mainwin_height))
            self.window.move(int(mainwin_pos_x),int(mainwin_pos_y))
        self.hpaned.set_position(int(hpaned_pos))
        self.vpaned.set_position(int(vpaned_pos))
        self.groups_pane.column1.set_fixed_width(groups_col1_width)
        self.threads_pane.column2.set_fixed_width(threads_col_subject_width)
        self.threads_pane.column3.set_fixed_width(threads_col_from_width)
        self.threads_pane.column4.set_fixed_width(threads_col_date_width)

        

    def build_layout_type_1(self,layout_number,swap=False):
        if layout_number==1:
            self.pane_1=self.groups_pane
            self.pane_2=self.threads_pane
            self.pane_3=self.article_pane
        elif layout_number==2:
            self.pane_1=self.threads_pane
            self.pane_2=self.groups_pane
            self.pane_3=self.article_pane
        elif layout_number==3:
            self.pane_1=self.article_pane
            self.pane_2=self.groups_pane
            self.pane_3=self.threads_pane
        elif layout_number==4:
            self.pane_1=self.groups_pane
            self.pane_2=self.article_pane
            self.pane_3=self.threads_pane
        elif layout_number==5:
            self.pane_1=self.threads_pane
            self.pane_2=self.article_pane
            self.pane_3=self.groups_pane
        elif layout_number==6:
            self.pane_1=self.article_pane
            self.pane_2=self.threads_pane
            self.pane_3=self.groups_pane
            
        #Vpaned
        self.vpaned=gtk.VPaned()
        self.vbox1.pack_start(self.vpaned,True,True,0)
        self.vpaned.show()

        #HPaned
        self.hpaned=gtk.HPaned()
        self.hpaned.show()

        pane_1_parent,pane_2_parent,pane_3_parent=self.unlink_panes()
        
        #Groups Pane
        self.hpaned.add(self.pane_1.get_widget())
        self.pane_1.show()

        #Threads Pane
        self.hpaned.add(self.pane_2.get_widget())
        self.pane_2.show()

        #Article Pane
        
        if not swap:
            self.vpaned.add(self.hpaned)
            self.vpaned.add(self.pane_3.get_widget())
        else:
            self.vpaned.add(self.pane_3.get_widget())
            self.vpaned.add(self.hpaned)
            
        self.pane_3.show()

        if pane_3_parent!=None and pane_2_parent!=None and pane_1_parent!=None:
            pane_3_parent.get_parent().remove(pane_3_parent)
            if pane_1_parent!=pane_3_parent:
                pane_1_parent.get_parent().remove(pane_1_parent)
            if pane_2_parent!=pane_3_parent and pane_2_parent!=pane_1_parent:
                pane_2_parent.get_parent().remove(pane_2_parent)


    def build_layout_type_2(self,layout_number,swap=False):
        if layout_number==1:
            self.pane_1=self.groups_pane
            self.pane_2=self.threads_pane
            self.pane_3=self.article_pane
        elif layout_number==2:
            self.pane_1=self.groups_pane
            self.pane_2=self.article_pane
            self.pane_3=self.threads_pane
        elif layout_number==3:
            self.pane_1=self.article_pane
            self.pane_2=self.groups_pane
            self.pane_3=self.threads_pane
        elif layout_number==4:
            self.pane_1=self.article_pane
            self.pane_2=self.threads_pane
            self.pane_3=self.groups_pane
        elif layout_number==5:
            self.pane_1=self.threads_pane
            self.pane_2=self.article_pane
            self.pane_3=self.groups_pane
        elif layout_number==6:
            self.pane_1=self.threads_pane
            self.pane_2=self.groups_pane
            self.pane_3=self.article_pane

        #HPaned
        self.hpaned=gtk.HPaned()
        self.vbox1.pack_start(self.hpaned,True,True,0)
        self.hpaned.show()

        #Vpaned
        self.vpaned=gtk.VPaned()
        self.vpaned.show()

        pane_1_parent,pane_2_parent,pane_3_parent=self.unlink_panes()
        
        #Groups Pane
        self.vpaned.add(self.pane_1.get_widget())
        self.pane_1.show()


        #Threads Pane
        self.vpaned.add(self.pane_2.get_widget())
        self.pane_2.show()

        #Article Pane
        
        if not swap:
            self.hpaned.add(self.vpaned)
            self.hpaned.add(self.pane_3.get_widget())
        else:
            self.hpaned.add(self.pane_3.get_widget())
            self.hpaned.add(self.vpaned)
            
        self.pane_3.show()

        if pane_3_parent!=None and pane_2_parent!=None and pane_1_parent!=None:
            pane_3_parent.get_parent().remove(pane_3_parent)
            if pane_1_parent!=pane_3_parent:
                pane_1_parent.get_parent().remove(pane_1_parent)
            if pane_2_parent!=pane_3_parent and pane_2_parent!=pane_1_parent:
                pane_2_parent.get_parent().remove(pane_2_parent)
    
    def build_layout_type_3(self,layout_number):
        self.build_layout_type_2(layout_number,True)
    
    def build_layout_type_4(self,layout_number):
        self.build_layout_type_1(layout_number,True)


    def purge_groups(self):
        for group in self.art_db.purgeGroups():
            self.statusbar.push(1,_("Purging Group: %s") % (group,))
            while gtk.events_pending():
                gtk.main_iteration(False)
        self.art_db.closeGroups()
        self.art_db.closeSubscribed()


    def rebuild_layout(self):
        layout_methods = {"1":self.build_layout_type_1,
                          "2":self.build_layout_type_2,
                          "3":self.build_layout_type_3,
                          "4":self.build_layout_type_4
                         }
        r,c=divmod(int(self.configs["layout"])-1,6)
        layout_builder = layout_methods.get(str(r+1), None)
        if layout_builder: layout_builder(c+1)
        else: self.build_layout_type_1(1)
        self.set_sizes()

    def unlink_panes(self):
        pane_1_parent=self.pane_1.get_widget().get_parent()
        if pane_1_parent!=None:
            pane_1_parent.remove(self.pane_1.get_widget())
        pane_2_parent=self.pane_2.get_widget().get_parent()
        if pane_2_parent!=None:
            pane_2_parent.remove(self.pane_2.get_widget())
        pane_3_parent=self.pane_3.get_widget().get_parent()
        if pane_3_parent!=None:
            pane_3_parent.remove(self.pane_3.get_widget())
        return pane_1_parent,pane_2_parent,pane_3_parent
        
    def focus_pane(self,obj,pane):
        pane.grab_focus()
        
    def zoom_pane(self,pane,button):
        buttons=[self.zoom_groups_button,self.zoom_threads_button,self.zoom_article_button]
        status=button.get_active() #mantaining status
        buttons.remove(button)
        for other_button in buttons:
            other_button.set_active(False)
        button.set_active(status)

        if button.get_active()==True:
            parent1=pane.get_widget().get_parent()
            parent2=parent1.get_parent()
            parent3=parent2.get_parent()

        pane_1_parent,pane_2_parent,pane_3_parent=self.unlink_panes()
        if self.hpaned.get_parent()==self.vbox1:
            try:self.vbox1.remove(self.hpaned)
            except:pass
        if self.vpaned.get_parent()==self.vbox1:
            try:self.vbox1.remove(self.vpaned)
            except:pass

        
        if button.get_active()==True:
            self.vbox1.pack_start(pane.get_widget(),True,True,0)
            # if type(parent1)==type(gtk.VBox()):
                # self.vbox1.pack_start(pane.get_widget(),True,True,0)
            # if type(parent2)==type(gtk.VBox()):
                # parent2.remove(parent1)
                # self.vbox1.pack_start(pane.get_widget(),True,True,0)
            # if type(parent3)==type(gtk.VBox()):
                # parent3.remove(parent2)
                # self.vbox1.pack_start(pane.get_widget(),True,True,0)
        else:
            self.rebuild_layout()
    
    def zoom_article(self,obj):
        self.zoom_pane(self.article_pane,obj)

    def zoom_groups(self,obj):
        self.zoom_pane(self.groups_pane,obj)

    def zoom_threads(self,obj):
        self.zoom_pane(self.threads_pane,obj)
    
    def toggle_zoom_button(self,obj,button):
        button.set_active(not button.get_active())

    
    def load_languages(self):
        #loading translation
        if self.configs["lang"]=="it":
            it=gettext.translation("xpn","/usr/share/locale",["it"])
            it.install()
            try:
                #trying to force GTK translation
                locale.setlocale(locale.LC_MESSAGES,"it_IT")
            except: pass
        elif self.configs["lang"]=="fr":
            fr=gettext.translation("xpn","/usr/share/locale",["fr"])
            fr.install()
            try:
                #trying to force GTK translation
                locale.setlocale(locale.LC_MESSAGES,"fr_FR")
            except: pass
        elif self.configs["lang"]=="de":
            de=gettext.translation("xpn","/usr/share/locale",["de"])
            de.install()
            try:
                #trying to force GTK translation
                locale.setlocale(locale.LC_MESSAGES,"de_DE")
            except: pass
        else:
            try:
                #trying to force GTK translation
                locale.setlocale(locale.LC_MESSAGES,"en_US")
            except: pass
    
    def create_ui(self):

        #loading icons
        def _iconset (filename):
            return gtk.IconSet (gtk.gdk.pixbuf_new_from_file (os.path.join ("pixmaps", filename)))
        self.icons=gtk.IconFactory()
        for icon_name in os.listdir("pixmaps"):
            if "." in icon_name and not icon_name.endswith(".svg"):
                self.icons.add("xpn_"+icon_name.split(".")[0], _iconset (icon_name))
        self.icons.add_default()

        
        #try:
        #    self.ui.remove_action_group(self.actiongroup) 
        #    self.ui.remove_ui(self.merge_id)
        #    self.window.remove_accel_group(self.accel_group)
        #except:
        #    pass


        self.ui = gtk.UIManager()
        self.accelgroup = self.ui.get_accel_group()
        self.actiongroup= gtk.ActionGroup("MainWindowActions")

        self.window.add_accel_group(self.accelgroup)
        mscuts=load_shortcuts("main")
        self.actions=[("File",None,_("_File")),
                ("groups","xpn_groups",_("Groups List..."),mscuts["groups"],_("Manage Groups"),self.open_groups_win),
                ("rules","xpn_score",_("Scoring and Action Rules..."),mscuts["rules"],_("Edit Scoring and Action Rules"),self.open_rules_win),
                ("logs",None,_("Server Logs..."),mscuts["logs"],None,self.open_logs_win),                       
                ("exp_newsrc",None,_("Export Newsrc..."),mscuts["exp_newsrc"],None,self.export_newsrc),
                ("imp_newsrc",None,_("Import Newsrc..."),mscuts["imp_newsrc"],None,self.import_newsrc),
                ("accelerator",None,_("Modify Keyboard Shortcuts..."),mscuts["accelerator"],None,self.modify_keybord_shortcuts),
                ("conf","xpn_conf",_("Preferences..."),mscuts["conf"],_("Preferences"),self.open_configure_win),
                ("exit","xpn_exit",_("Exit"),mscuts["exit"],None,self.destroy),
                ("Search",None,_("_Search")),
                ("find","xpn_find",_("Find Article..."),mscuts["find"],None,self.find_article),
                ("global","xpn_global_search",_("Global Search ..."),mscuts["global"],None,self.global_search),
                ("filter",None,_("Filter Articles ..."),mscuts["filter"],None,self.filter_articles),
                ("search","xpn_search",_("Search in the Body..."),mscuts["search"],None,self.search_in_the_article),
                ("View",None,_("_View")),
                ("view_articles_opts",None,_("Articles View Options")),
                ("view_group_opts",None,_("Groups View Options")),
                ("Navigate",None,_("_Navigate")),
                ("group",None,_("View Next Group"),mscuts["group"],None,self.groups_pane.view_next_group),
                ("previous","xpn_previous",_("Read Previous Article"),mscuts["previous"],_("Read Previous Article"),self.view_previous_article),
                ("next","xpn_next",_("Read Next Article"),mscuts["next"],_("Read Next Article"),self.view_next_article),
                ("next_unread","xpn_next_unread",_("Read Next Unread Article"),mscuts["next_unread"],_("Read Next Unread Article"),self.view_next_unread_article),
                ("parent",None,_("Read Parent Article"),mscuts["parent"],None,self.view_parent_article),
                ("one_key",None,_("One-Key Reading"),mscuts["one_key"],None,self.one_key_reading),
                ("move_up",None,_("One-Key Scroll Up"),mscuts["move_up"],None,self.one_key_move_up),
                ("focus_article",None,_("Focus to Article Pane"),mscuts["focus_article"],None,self.focus_pane,self.article_pane.textview),
                ("focus_groups",None,_("Focus to Groups Pane"),mscuts["focus_groups"],None,self.focus_pane,self.groups_pane.groups_list),
                ("focus_threads",None,_("Focus to Threads Pane"),mscuts["focus_threads"],None,self.focus_pane,self.threads_pane.threads_tree),
                ("zoom_article",None,_("Zoom Article Pane"),mscuts["zoom_article"],None,self.toggle_zoom_button,self.zoom_article_button),
                ("zoom_groups",None,_("Zoom Groups Pane"),mscuts["zoom_groups"],None,self.toggle_zoom_button,self.zoom_groups_button),
                ("zoom_threads",None,_("Zoom Threads Pane"),mscuts["zoom_threads"],None,self.toggle_zoom_button,self.zoom_threads_button),
                ("Subscribed",None,_("Subscribed _Groups")),
                ("gethdrs","xpn_receive_headers",_("Get New Headers in Subscribed Groups"),mscuts["gethdrs"],_("Get New Headers in Subscribed Groups"),self.get_new_headers),
                ("gethdrssel","xpn_receive_headers_selected",_("Get New Headers in Selected Groups"),mscuts["gethdrssel"],None,self.get_new_headers_selected),
                ("getbodies","xpn_receive_bodies",_("Get Marked Article Bodies in Subscribed Groups"),mscuts["getbodies"],_("Get Marked Article Bodies in Subscribed Groups"),self.get_bodies),
                ("getbodiessel","xpn_receive_bodies_selected",_("Get Marked Article Bodies in Selected Groups"),mscuts["getbodiessel"],None,self.get_bodies_selected),
                ("expand","xpn_expand_all",_("Expand All Threads"),mscuts["expand"],_("Expand All"),self.expand_all_threads,True),
                ("collapse","xpn_collapse_all",_("Collapse All Threads"),mscuts["collapse"],_("Collapse All"),self.expand_all_threads,False),
                ("expand_row","xpn_expand",_("Expand Selected SubThread"),mscuts["expand_row"],_("Expand Selected SubThread"),self.expand_selected_row,True),
                ("collapse_row","xpn_collapse",_("Collapse Selected SubThread"),mscuts["collapse_row"],_("Collapse Selected SubThread"),self.expand_selected_row,False),
                ("mark_group",None,_("Mark Group ...")),
                ("mark","xpn_mark",_("Mark Selected Groups as Read"),mscuts["mark"],_("Mark Selected Groups as Read"),self.mark_group,True),
                ("mark_unread_group",None,_("Mark Selected Groups as Unread"),mscuts["mark_unread_group"],None,self.mark_group,False),
                ("mark_download_group","xpn_mark_multiple",_("Mark Group for Retrieving"),mscuts["mark_download_group"],None,self.context_mark_download_group),
                ("keepall","xpn_art_keep",_("Keep Articles in Selected Groups"),mscuts["keepall"],None,self.keep_group),
                ("markall","xpn_mark_all",_("Mark All Groups as Read"),mscuts["markall"],_("Mark All Groups as Read"),self.mark_all_groups,True),
                ("markall_unread",None,_("Mark All Groups as Unread"),mscuts["markall_unread"],None,self.mark_all_groups,False),
                ("apply_score",None,_("Apply Scoring and Action Rules"),mscuts["apply_score"],None,self.reapply_score_actions_rules),
                ("groups_vs_id",None,_("Assign Identities to Groups"),mscuts["groups_vs_id"],None,self.open_groups_vs_id),
                ("Articles",None,_("_Articles")),
                ("show_hide_headers",None,_("Show/Hide Headers"),mscuts["show_hide_headers"],None,self.show_hide_headers),
                ("rot13","xpn_rot13",_("ROT13 Selected Text"),mscuts["rot13"],_("ROT13 Selected Text"),self.apply_rot13),
                ("flags",None,_("Flags & Score")),
                ("mark_read","xpn_art_read",_("Mark Article as Read"),mscuts["mark_read"],None,self.context_mark_read),
                ("mark_unread","xpn_art_unread",_("Mark Article as UnRead"),mscuts["mark_unread"],None,self.context_mark_unread),
                ("mark_download","xpn_art_mark",_("Mark Article for Retrieving"),mscuts["mark_download"],None,self.context_mark_download),
                ("keep","xpn_art_keep",_("Keep Article"),mscuts["keep"],None,self.context_keep),
                ("delete","xpn_art_delete",_("Delete Article"),mscuts["delete"],None,self.context_delete),
                ("mark_unread_sub",None,_("Mark SubThread as UnRead"),mscuts["mark_unread_sub"],None,self.context_mark_read_sub,False),
                ("mark_read_sub","xpn_art_read",_("Mark SubThread as Read"),mscuts["mark_read_sub"],None,self.context_mark_read_sub,True),
                ("mark_download_sub","xpn_mark_multiple",_("Mark SubThread for Retrieving"),mscuts["mark_download_sub"],None,self.context_mark_download_sub),
                ("keep_sub","xpn_art_keep",_("Keep SubThread"),mscuts["keep_sub"],None,self.context_keep_sub),
                ("watch","xpn_art_watch",_("Watch SubThread"),mscuts["watch"],None,self.context_watch),
                ("ignore","xpn_art_ignore",_("Ignore SubThread"),mscuts["ignore"],None,self.context_ignore),
                ("raise_score","xpn_raise_score",_("Raise Author Score"),mscuts["raise_score"],None,self.context_modify_score,0),
                ("lower_score","xpn_lower_score",_("Lower Author Score"),mscuts["lower_score"],None,self.context_modify_score,1),
                ("set_score","xpn_set_score",_("Set Author Score"),mscuts["set_score"],None,self.context_modify_score,2),
                ("post","xpn_post",_("Post New Article..."),mscuts["post"],_("Post New Article"),self.open_edit_win),
                ("outbox_manager","xpn_outbox",_("Open Outbox Manager"),mscuts["outbox_manager"],_("Open Outbox Manager"),self.open_outbox_manager),
                ("followup","xpn_followup",_("Follow-Up To Newsgroup..."),mscuts["followup"],_("Follow-Up To Newsgroup"),self.open_edit_win,True),
                ("reply","xpn_reply",_("Reply By Mail..."),mscuts["reply"],_("Reply by Mail"),self.open_edit_mail_win),
                ("supersede","xpn_supersede",_("Supersede Article..."),mscuts["supersede"],None,self.supersede_cancel_message,"Supersede"),
                ("cancel","xpn_cancel",_("Cancel Article..."),mscuts["cancel"],None,self.supersede_cancel_message,"Cancel"),
                ("Help",None,_("Help")),
                ("about","xpn_about",_("About..."),mscuts["about"],None,self.open_about_dialog)]
                
        for action in self.actions:
            if len(action)<7:
                self.actiongroup.add_actions([action])
            else:
                self.actiongroup.add_actions([action[0:6]],action[-1])

        self.toggle_actions=[
                ("show_threads",None,_("Show Threads"),mscuts["show_threads"],None,self.view_group,False,None,None),
                ("show_all_read_threads",None,_("Show All Read Threads"),mscuts["show_all_read_threads"],None,self.view_group,False,None,None),
                ("show_threads_without_watched",None,_("Show Threads Without Watched Articles"),mscuts["show_threads_without_watched"],None,self.view_group,False,None,None),
                ("show_read_articles",None,_("Show Read Articles"),mscuts["show_read_articles"],None,self.view_group,False,None,None),
                ("show_unread_articles",None,_("Show UnRead Articles"),mscuts["show_unread_articles"],None,self.view_group,False,None,None),
                ("show_kept_articles",None,_("Show Kept Articles"),mscuts["show_kept_articles"],None,self.view_group,False,None,None),
                ("show_unkept_articles",None,_("Show UnKept Articles"),mscuts["show_unkept_articles"],None,self.view_group,False,None,None),
                ("show_watched_articles",None,_("Show Watched Articles"),mscuts["show_watched_articles"],None,self.view_group,False,None,None),
                ("show_ignored_articles",None,_("Show Ignored Articles"),mscuts["show_ignored_articles"],None,self.view_group,False,None,None),
                ("show_unwatchedignored_articles",None,_("Show UnWatched/UnIgnored Articles"),mscuts["show_unwatchedignored_articles"],None,self.view_group,False,None,None),
                ("show_score_neg_articles",None,_("Show Articles with Score<0"),mscuts["show_score_neg_articles"],None,self.view_group,False,None,None),
                ("show_score_zero_articles",None,_("Show Articles with Score=0"),mscuts["show_score_zero_articles"],None,self.view_group,False,None,None),
                ("show_score_pos_articles",None,_("Show Articles with Score>0"),mscuts["show_score_pos_articles"],None,self.view_group,False,None,None),
                ("raw",None,_("View Raw Article"),mscuts["raw"],None,self.view_article,False),
                ("spoiler",None,_("Show Spoilered Text"),mscuts["spoiler"],None,self.view_article,False),
                ("show_quote",None,_("Show Quoted Text"),mscuts["show_quote"],None,self.view_article,False),
                ("show_sign",None,_("Show Signatures"),mscuts["show_sign"],None,self.view_article,False),
                ("fixed",None,_("Fixed Pitch Font"),mscuts["fixed"],None,self.set_fixed_pitch,False)]


        for action in self.toggle_actions: 
            if len(action)<8:
                self.actiongroup.add_toggle_actions([action])
            else:
                self.actiongroup.add_toggle_actions([action[0:7]],action[7:])

        self.ui.insert_action_group(self.actiongroup,0)
        self.merge_id = self.ui.add_ui_from_string(ui_string)
        self.ui.ensure_update()  
                
    def toolbar_search(self,obj,search_type,text):
        self.show_threads(self.group_to_thread,search_type,text)
        

    def search_focus_changed(self,obj,event,focusIn):
        if focusIn:
            #we have to disable accelerator
            self.window.remove_accel_group(self.accelgroup)
        else:
            self.window.add_accel_group(self.accelgroup)
    
    def close_filter_toolbar(self,obj):
        self.filter_toolbar.hide()
    
    def filter_articles(self,obj):
        self.filter_toolbar.show_all()
        self.cs_entry.grab_focus()
    
    def recoverPreviousInstall(self):
        '''Recover files from 1.0 installation'''

        #Looking for groups.dat files
        file_list=os.listdir(os.path.join(self.wdir,"groups_info"))
        groups_list_db=Groups_DB()
        for file_name in file_list:
            if file_name.endswith("groups.dat"):
                print "Recovering", file_name
                f=open(os.path.join(self.wdir,"groups_info",file_name))
                try: list_to_recover=cPickle.load(f)
                except: list_to_recover=[]
                f.close()
                groups_list_db.createList(list_to_recover,"",file_name.replace(".dat",".sqlitedb"))
                os.remove(os.path.join(self.wdir,"groups_info",file_name))

        #Looking for subscribed.dat files
        if "subscribed.dat" in file_list:
            print "Recovering subscribed.dat"
            f=open(os.path.join(self.wdir,"groups_info","subscribed.dat"))
            try:subscribed=cPickle.load(f)
            except:subscribed=[]
            f.close()
            
            for group in subscribed:
                self.art_db.addSubscribed(group[0],group[1],group[2],group[3])
            os.remove(os.path.join(self.wdir,"groups_info","subscribed.dat"))

            for group in subscribed:
                print "Recovering Group:", group
                import shelve
                try:art=shelve.open(os.path.join(self.wdir,"groups_info",group[0],group[0]))
                except:art=[]
                articles=dict(art)
                try:art.close()
                except:pass
                shutil.rmtree(os.path.join(self.wdir,"groups_info",group[0]))
                self.art_db.createGroup(group[0])
                for article in articles.itervalues():
                    if article.body: #This is needed for the recoverPreviousInstall function
                        article.raw_body=article.get_raw()
                        article.has_body=True
                        self.art_db._insertBody(group[0],article,False)
                    else:
                        article.raw_body=""
                        article.has_body=False
                    self.art_db.insertArticle(group[0],article)

    def __init__(self,use_home,custom_dir):
        Edit_Win.VERSION=VERSION
        Edit_Mail_Win.VERSION=VERSION
        if use_home:           
            userdir=UserDir(userHome=True)
        elif custom_dir:
            userdir=UserDir(customPath=custom_dir)
        else:
            userdir=UserDir(cwd=True)
        ret=userdir.Create()
        if ret>0 :sys.exit(ret)
        self.wdir=userdir.dir
        
        # handle the trayicon
        self.trayicon = gtk.StatusIcon()
        self.trayicon.set_tooltip_text(_("XPN Newsreader"))
        self.trayicon.set_from_file("/usr/share/pixmaps/xpn.png")
        self.trayicon.connect("activate",  self.tray_activated)
        self.trayicon.connect("popup-menu",  self.tray_popuped)

        self.conf=Config_File()
        self.configs=self.conf.get_configs()


        
        self.load_languages()
        
        try: open(os.path.join(self.wdir,"xpn.lock"),"r")
        except IOError:open(os.path.join(self.wdir,"xpn.lock"),"w")
        else: 
            #raise StandardError, "An istance of XPN is already running, if you think this is an error remove manually the file 'xpn.lock' in your XPN working directory."
            md=Dialog_YES_NO(_("An instance of XPN is already running.\n\nDo you want to open XPN anyway?"))
            if not md.resp:
                sys.exit()
        
        try: os.remove(os.path.join(self.wdir,"server_logs.dat"))
        except: pass

        try: os.remove(os.path.join(self.wdir,"error_logs.dat"))
        except: pass

        try: map(shutil.rmtree,glob.glob(os.path.join(self.wdir,"groups_info/global.search.results.*")))
        except: pass

        try: os.makedirs(os.path.join(self.wdir,"groups_info"))
        except: pass
        
        try: os.makedirs(os.path.join(self.wdir,"dats"))
        except: pass

        try: os.makedirs(os.path.join(self.wdir,"outbox/news"))
        except: pass
        try: os.makedirs(os.path.join(self.wdir,"outbox/mail"))
        except: pass

        try: os.makedirs(os.path.join(self.wdir,"draft/news"))
        except: pass
        try: os.makedirs(os.path.join(self.wdir,"draft/mail"))
        except: pass
        
        try: os.makedirs(os.path.join(self.wdir,"sent/news"))
        except: pass
        try: os.makedirs(os.path.join(self.wdir,"sent/mail"))
        except: pass
        
        self.s=None

        
        self.groups_lock=False
        self.group_to_thread=""
        self.current_server=""
        self.subscribed_groups=[]
        
        self.art_db=Articles_DB()

        self.recoverPreviousInstall()

        cp=ConfigParser.ConfigParser()
        cp.read(os.path.join(get_wdir(),"dats","servers.txt"))
        self.connectionsPool=dict()
        for server in cp.sections():
            if cp.get(server,"nntp_use_ssl")=="True":
                self.connectionsPool[server]=SSLConnection(cp.get(server,"server"),cp.get(server,"port"),cp.get(server,"auth"),cp.get(server,"username"),cp.get(server,"password"))
            else:
                self.connectionsPool[server]=Connection(cp.get(server,"server"),cp.get(server,"port"),cp.get(server,"auth"),cp.get(server,"username"),cp.get(server,"password"))


        #loading score rules
        self.score_rules=Score_Rules()

        #MainMenuBar
        self.window=gtk.Window (gtk.WINDOW_TOPLEVEL)
        self.window.connect("delete_event",self.delete_event)
        self.window.connect("destroy",self.destroy)
        self.window.set_title("XPN "+NUMBER)
        self.window.set_icon(gtk.gdk.pixbuf_new_from_file("pixmaps/xpn-icon.png"))
        self.window.set_size_request(300,200)

        self.build_panes()        

        self.zoom_article_button=gtk.ToggleButton("A")
        self.zoom_threads_button=gtk.ToggleButton("H")
        self.zoom_groups_button=gtk.ToggleButton("G")
        
        #UIManager
        self.create_ui()


        #Filter Toolbar
        se_toolitem=gtk.ToolItem()
        self.cs_entry=Custom_Search_Entry()
        self.cs_entry.connect("do_search",self.toolbar_search)
        self.cs_entry.connect("search_focus_in",self.search_focus_changed,True)
        self.cs_entry.connect("search_focus_out",self.search_focus_changed,False)
        se_toolitem.add(self.cs_entry)
        se_toolitem.show_all()
        label_toolitem=gtk.ToolItem()
        label=gtk.Label(_("Filter Articles by: "))
        label_toolitem.add(label)
        label_toolitem.show_all()
        close_tool_button=gtk.ToolButton(gtk.STOCK_CLOSE)
        try: close_tool_button.set_tooltip_text(_("Close Filter Toolbar"))
        except: pass #doesn't work with some old GTK 
        close_tool_button.connect("clicked",self.close_filter_toolbar)
        close_tool_button.show_all()
        
        self.filter_toolbar=gtk.Toolbar()
        self.filter_toolbar.set_orientation(gtk.ORIENTATION_HORIZONTAL)
        self.filter_toolbar.set_style(gtk.TOOLBAR_ICONS)
        self.filter_toolbar.insert(label_toolitem,-1)
        self.filter_toolbar.insert(se_toolitem,-1)
        self.filter_toolbar.insert(close_tool_button,-1)
        
        


        menubar=self.ui.get_widget("/MainMenuBar")
        toolbar=self.ui.get_widget("/MainToolBar")
        #toolbar.set_icon_size(gtk.ICON_SIZE_LARGE_TOOLBAR)
        toolbar.set_orientation(gtk.ORIENTATION_HORIZONTAL)
        toolbar.set_style(gtk.TOOLBAR_ICONS)

        #main vbox
        self.vbox1 = gtk.VBox(False,0)
        self.window.add(self.vbox1)
        self.vbox1.show()

        self.vbox1.pack_start(menubar,False,True,0)
        menubar.show()        

        #Handlebox
        self.vbox1.pack_start(toolbar,False,False,0)
        toolbar.show()
        
        self.vbox1.pack_start(self.filter_toolbar,False,False,0)
        

        layout_methods = {"1":self.build_layout_type_1,
                          "2":self.build_layout_type_2,
                          "3":self.build_layout_type_3,
                          "4":self.build_layout_type_4
                         }
        r,c=divmod(int(self.configs["layout"])-1,6)
        layout_builder = layout_methods.get(str(r+1), None)
        if layout_builder: layout_builder(c+1)
        else: self.build_layout_type_1(1)   # If there is no layout associated to
                                            # self.configs["layout"] then build 1


        #hbox_bottom
        hbox_bottom=gtk.HBox()
        self.vbox1.pack_end(hbox_bottom,False,False,0)
        hbox_bottom.show()

        #progressbar
        self.progressbar=gtk.ProgressBar()
        hbox_bottom.pack_start(self.progressbar,False,False,0)
        self.progressbar.show()

        #Zoom Buttons
        self.zoom_article_button.set_relief(gtk.RELIEF_NONE)
        self.zoom_threads_button.set_relief(gtk.RELIEF_NONE)
        self.zoom_groups_button.set_relief(gtk.RELIEF_NONE)
        self.zoom_article_button.connect("clicked",self.zoom_article)
        self.zoom_threads_button.connect("clicked",self.zoom_threads)
        self.zoom_groups_button.connect("clicked",self.zoom_groups)
        self.zoom_article_button.set_tooltip_text(_("Zoom Article Pane"))
        self.zoom_threads_button.set_tooltip_text(_("Zoom Headers Pane"))
        self.zoom_groups_button.set_tooltip_text(_("Zoom Groups Pane"))
        hbox_bottom.pack_start(self.zoom_article_button,False,False,0)
        hbox_bottom.pack_start(self.zoom_threads_button,False,False,0)
        hbox_bottom.pack_start(self.zoom_groups_button,False,False,0)
        self.zoom_article_button.show()
        self.zoom_threads_button.show()
        self.zoom_groups_button.show()

        separator=gtk.VSeparator()
        separator.show()
        hbox_bottom.pack_start(separator,False,False,0)


        #statusbar
        self.statusbar=gtk.Statusbar()
        hbox_bottom.pack_start(self.statusbar,True,True,0)
        self.statusbar.show()


        

        self.connect_signals()

        self.show_subscribed()

        self.update_checkmenu_options()

        monospace=pango.FontDescription("Monospace 9")
        if self.configs["use_system_fonts"]=="True":
            user=pango.FontDescription("")
        else:
            user=pango.FontDescription(self.configs["font_name"])
        if self.configs["fixed"]=="True":
            self.article_pane.textview.modify_font(monospace)
        else:
            self.article_pane.textview.modify_font(user)
        self.article_pane.textview.set_indent(5)
        self.set_sizes()
        self.mainwin_width=None  #I must use these because if I close the window with the [x]
        self.mainwin_height=None #I loose window sizes
        self.mainwin_pos_x=None
        self.mainwin_pos_y=None
        
        self.window.show()
        
        if not self.conf.found_config_file:
            dia=Dialog_YES_NO(_("Missing Config File.\n\nDo you want to Configure XPN now?"))
            if dia.resp:
                self.open_configure_win(None)        
        self.msgids=dict()
        timeout=int(self.configs.get("download_timeout",'30'))
        do_auto_download=eval(self.configs.get("automatic_download","False"))
        if do_auto_download: gobject.timeout_add(timeout*1000*60,self.get_new_headers,None)

def hook(et,ev,eb):
    import traceback
    ex_list=traceback.format_exception(et,ev,eb)
    list="".join(ex_list)
    if not ("sys.exit()" in list or "systemexit" in list.lower()):
        message="\n"+"".join(ex_list)
        log=message
        try:
            f=open(os.path.join(wdir,"error_logs.dat"),"a")
        except IOError:
            pass
        else:
            f.write(":::: "+time.ctime(time.time())+" :::: \n"+message+"\n\n")
            f.close()
        try:
            f=open(os.path.join(wdir,"error_logs.dat"),"rb")
        except IOError:
            pass
        else:
            log=f.read()
        try:
            error_dialog=Error_Dialog(unicode(message,"us-ascii","replace").encode("utf-8"),unicode(log,"us-ascii","replace").encode("utf-8"))
            error_dialog.run()
        except:
            sys.stderr.write(_('Unexpected error in the excepthook.'))
            sys.stderr.write('\n\n')
            message = message="\n"+"".join(traceback.format_exception(*sys.exc_info()))
            sys.stderr.write(message)
        else:
            error_dialog.destroy() 


parser=OptionParser(usage=_("python %prog [-d] [-cCUSTOM_DIR]\n\nWith command line options you can decide where XPN will save config files and articles.\nIf you don't use any option, the current working directory will be used.\nIf you use the '--home_dir' option, XPN will create a .xpn directory inside your home directory, and will store informations inside that directory.\nIf you use the '--custom_dir' option, XPN will create a .xpn directory inside that custom_directory.\n\nNOTE: If you set the '--home_dir' option, XPN will ignore the '--custom_dir' option (if you used it).\n\nExamples:\npython xpn.py\npython xpn.py -d\npython xpn.py --custom_dir /home/user/custom"))
parser.add_option("-d","--home_dir",action="store_true",dest="use_home",default=False,
                  help=_("use home directory to store config files and articles"))
parser.add_option("-c","--custom_dir",dest="custom_dir",
                  help=_("specify an existing directory where store config files and articles"))
options,args=parser.parse_args()

try: dir=os.path.dirname(sys.argv[0])
except: dir=""
if dir:
    try:os.chdir(dir)
    except: pass

try:
    main=MainWin(options.use_home,options.custom_dir)
    wdir=main.wdir
except:
    def eHook():
        hook(*sys.exc_info())
        gtk.main_quit()
    wdir=''
    gobject.timeout_add(100,eHook)
    gtk.main()

else:
    #reload(sys)
    #sys.setdefaultencoding("ascii")
    sys.excepthook=hook
    gtk.main()