This file is indexed.

/usr/bin/ganyremote is in ganyremote 6.3.2-1.

This file is owned by root:root, with mode 0o755.

The actual contents of the file can be viewed below.

   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
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
#! /usr/bin/python

"""
v 6.3.2

gAnyRemote
GTK-based GUI for anyRemote - a bluetooth remote for your PC.

Copyright (C) 2007-2014 Mikhail Fedotov <anyremote@mail.ru>

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. 
"""

import locale
import gettext
import getopt
import glob
import gobject
import os
import re
import pango
import pygtk
import signal
import socket
import sys
import threading
import thread
import time
import httplib
import Queue
import datetime

try:
    import appindicator
except ImportError:
    print 'Warning: No support for AppIndicator'

signal.signal(signal.SIGINT, signal.SIG_DFL)
pygtk.require('2.0')

#Translation stuff

#Get the local directory since we are not installing anything
dirpath = os.path.dirname(sys.argv[0])
local_path = os.path.realpath(os.path.join(dirpath,'mo'))

# try ../share/locale/ (Linux)
if not os.path.exists(local_path):
    local_path = os.path.realpath(os.path.join(dirpath,'../share/locale/'))

# try ../lib/locale/ (Sun)
if not os.path.exists(local_path):
    local_path = os.path.realpath(os.path.join(dirpath,'../lib/locale/'))

# last resort ... try /usr/share/locale
if not os.path.exists(local_path):
    local_path = os.path.realpath('/usr/share/locale/')

langs = []

lc = ''
encoding = ''
try:
    lc, encoding = locale.getdefaultlocale()
except ValueError, cmd:
   print 'Error: ',cmd,'\nCorrect $LANG or $LANGUAGE first !!!'
   sys.exit()

if lc:
    #If we have a default, it's the first in the list
    langs = [lc]

# Now lets get all of the supported languages on the system
language = os.environ.get('LANGUAGE', None)
if language:
    langs += language.split(":")

APP_NAME = "ganyremote"

gettext.bindtextdomain(APP_NAME, local_path)
gettext.textdomain(APP_NAME)

# Get the language to use
lang = gettext.translation(APP_NAME, local_path, languages=langs, fallback = True)

_ = lang.ugettext

#
# String constants (not all!)
#
AR_NOTINSTALLED = _('Not installed')

AR_NOINFO   = _('No information')
AR_AVAIL    = _('Available')
AR_NOTAVAIL = _('Not available')
AR_MANAGED  = _('Managed')
AR_RUNNING  = _('Running')

AR_CONN_DEV = _('Connecting to device')
AR_WAIT_OPS = _('Wait other operations to finish')
AR_SEL_DIR  = _('Directory selection')

AR_OK       = _('OK')
AR_CANCEL   = _('Cancel')
AR_ADD      = _('Add')
AR_DELETE   = _('Delete')
AR_CHOOSE   = _('Choose')
AR_ALL      = _('All')
AR_FILE     = _('File')
AR_CLOSE    = _('Close')

AR_MODE     = _('Mode')
AR_STATUS   = _('Status')
AR_APP      = _('Application')
AR_CUSTOM   = _('Custom')
AR_EXAMPLE  = _('Example')

AR_DEV_BROWSER = _("Device Browser")

AR_STOPPED  = _('anyRemote stopped')
AR_DISCONN  = _('Ready to connect on')
AR_CONNECT  = _('Connected')
AR_DOWNLOADING = _('Downloading')
AR_J2ME_CHECK  = _('Checking J2ME client updates')
AR_NO_J2ME_UPD = _('No updates for J2ME client were found.')

AR_TCP_PORT=_('TCP port')
AR_BT_PORT=_('Bluetooth channel')
AR_HTTP_PORT=_('HTTP port')

AR_CODE_J2ME_UPD = 'UPDATE_AVAIL'
AR_CODE_LOADED   = 'LOADED'

AR_FILE_DEVICES='anyremote-peers.conf'

try:
   import gtk
except ImportError:
   print _('Install PyGTK first !!!')
   sys.exit()

pybluez = True 
try:
    import bluetooth
except ImportError:
   pybluez = False

###############################################################################
#
# J2ME client uploader
# unified
#
###############################################################################
class JCUploader(threading.Thread):

    def __init__(self):
        threading.Thread.__init__(self) 

    def run(self):
        global debug,jup
        
        if debug: print 'JCUploader starting'
    
        self.run = True
        
        stopPBar()
        startPBar(AR_DOWNLOADING+' anyRemote-16.jad')
         
        ret = True
        
        jars = ["-16","-32","-48","-64","-128","","-nojsr82"]
        
        for sz in jars:
        
            for bi in ["", "b"]:
                
                # no big icons for these variants
                if bi == "b" and (sz == "" or sz == "-nojsr82"):
                    continue
                
                if self.run and ret:
                    ret = uploadJ2MEWebGui('anyRemote'+sz+bi+'.jad', True)

                if self.run and ret: 
                    ret = uploadJ2MEWebGui('anyRemote'+sz+bi+'.jar')
    
        if self.run: stopPBar()
        
        if debug: print 'JCUploader: upload done'
        
        jup = None

    def stop(self):
        global debug
        if debug: print 'stop JCUploader'
        
        self.run = False

def stopJCUploader():
    global jup
    try:
        if jup != None:
            jup.stop()
    except NameError:
        pass

##################################################################################
#
# J2ME client verifier
# unified
#
##################################################################################
class JCVerifier(threading.Thread):

    def __init__(self, force):
        threading.Thread.__init__(self) 
        self.anyway = force

    def run(self):
        global debug
        
        if debug: print 'JCVerifier starting'
        
        curdate = time.strftime("%d%m", time.gmtime())
        
        if self.anyway:
            startPBar(AR_J2ME_CHECK)
        else:
            try:
                f = open(os.environ.get("HOME")+os.sep+'.anyRemote'+os.sep+'j2me-client.checked', 'r')
                date = f.read() 
                f.close()        
                date = date.replace('\n','')
                    
                if debug: print 'JCVerifier',date,curdate
            
                if date == curdate:
                    if debug: print 'JCVerifier: already checked. Exiting'
                    self = None
                    return

            except IOError:
                pass
            
        if debug: print 'JCVerifier: check new version'

        os.system('echo \"'+curdate+'\" > $HOME/.anyRemote/j2me-client.checked')
        newver = checkJ2MEClientUpdate();
        
        if debug: print 'JCVerifier: upload done '+newver
        
        if self.anyway:    
            stopPBar()
        
        if newver == "":
            if self.anyway:
                infoMessage(AR_NO_J2ME_UPD)
        # newver == "-1" in case of connection absense
        elif newver != "-1": 
            codeMessage(AR_CODE_J2ME_UPD)
        
        self = None

##################################################################################
#
# Reader of cfg. files
# unified
#
##################################################################################
class CfgFileReader(threading.Thread):

    def __init__(self):
        global cfgFileReaderFlag
        
        threading.Thread.__init__(self) 
        
        cfgFileReaderFlag = True

    def run(self):
        global debug, cfgFileReaderFlag, cfgReader

        if debug: print 'CfgFileReader.run'
        
        clearAppsList()
        
        self.regExp  = re.compile("^[^a-zA-Z0-9]*Gui")
        self.regExpB  = re.compile("^[^a-zA-Z0-9%]*VERS[^=]*=.+$")
        self.regExpAT = re.compile("^[^a-zA-Z0-9%]*Device[^=]*=/dev/[a-zA-Z0-9]+$")
        
        t1 = datetime.datetime.now()
        
        numProcessed = 0
        for cfgDir in cfgReader.cfgDirs:
              
            if cfgDir == '':
                continue
            if debug: print 'Collect files in '+cfgDir
            
            if os.path.isfile(cfgDir):
                self.processOneFile(cfgDir)
                
                numProcessed = numProcessed+1
                codeMessage2(AR_CODE_LOADED, numProcessed)
                
            else:
                for root, dirs, files in os.walk(cfgDir):
                    
                     
                    if 'Utils' in dirs:
                       dirs.remove('Utils')
                       if debug: print 'skip dir',root+os.sep+'Utils'
                    if 'Icons' in dirs:
                       dirs.remove('Icons')
                       if debug: print 'skip dir',root+os.sep+'Icons'
                    if '.svn' in dirs:
                       dirs.remove('.svn')
                       if debug: print 'skip dir',root+os.sep+'.svn'
                    
                    for cfgFile in files:

                        nameext = cfgFile.split('.')
                        ext = nameext[len(nameext)-1]

                        if ext == 'png' or ext == 'sh' or ext == 'py' or ext == 'gz':
                            if debug: print 'Not a configuration file '+cfgFile
                            continue

                        self.processOneFile(root + os.sep + cfgFile)

                        numProcessed = numProcessed+1
                        codeMessage2(AR_CODE_LOADED, numProcessed)
        
        codeMessage2(AR_CODE_LOADED, -1)
        
        cfgFileReaderFlag = False
        
        t2 = datetime.datetime.now()
        #print "Load time ",(t2-t1)
            
    def processOneFile(self,cfgFile):
        global debug, cfgReader
        
        fd = None
        try:
            fd = open(cfgFile,'r')
        except IOError:
            pass
         
        if fd:
            aName    = None
            aInst    = ''
            aRun     = ''
            aIcon    = ''
            aType    = None
            aDesc    = ''
            aVers    = ''
            aModes   = ''
            aDevice  = ''
            aBemused = ''
        
            for line in fd:
        
                if self.regExp.match(line):
                    
                    p = re.search("^[^a-zA-Z0-9]*GuiAppName[^=]*=(.+)$", line)
                    if p != None:
                        aName = p.group(1)

                    p = re.search("^[^a-zA-Z0-9]*GuiAppBinary[^=]*=(.+)$", line)
                    if p != None:
                        aInst = p.group(1)
                    
                    p = re.search("^[^a-zA-Z0-9]*GuiAppRun[^=]*=(.+)$", line)
                    if p != None:
                        aRun = p.group(1)
               
                    p = re.search("^[^a-zA-Z0-9]*GuiAppIcon[^=]*=(.+)$", line)
                    if p != None:
                        aIcon = p.group(1)

                    p = re.search("^[^a-zA-Z0-9]*GuiAppType[^=]*=(.+)$", line)
                    if p != None:
                        aType = p.group(1)
                    
                    p = re.search("^[^a-zA-Z0-9]*GuiAppDesc[^=]*=(.+)$", line)
                    if p != None:
                        aDesc = p.group(1)

                    p = re.search("^[^a-zA-Z0-9]*GuiAppVersion[^=]*=(.+)$", line)
                    if p != None:
                        aVers = p.group(1)

                    # deprecated, use GuiAppProtocols        
                    p = re.search("^[^a-zA-Z0-9]*GuiAppModes[^=]*=(.+)$", line)
                    if p != None:
                        aModes = p.group(1)

                    p = re.search("^[^a-zA-Z0-9]*GuiAppProtocols[^=]*=(.+)$", line)
                    if p != None:
                        aModes = p.group(1)
                        
                if self.regExpAT.match(line):
                    aDevice = 'a'
                
                if self.regExpB.match(line):
                    aBemused = 1
        
            if (not aName) and (not aType):
               if debug: print 'Not a configuration file. Skip '+cfgFile
               fd.close()
               return
            
            aMode = ['Server']    
            if aModes == '': 
                if aBemused == 1:
                    aMode = ['Bemused']
                elif aDevice == 'a':
                    aMode = ['AT']
            else:
                aMode = [] 
                # not use aModes.split(',') to make more strict control
                if aModes.find('Server') >= 0:
                    aMode.append('Server')

                if aModes.find('Bemused') >= 0:
                    aMode.append('Bemused')
                
                if aModes.find('AT') >= 0:
                    aMode.append('AT')
                
                if aModes.find('iViewer') >= 0:
                    aMode.append('iViewer')
                    
            if aName == '' or aName == None:
                    aName = os.path.basename(cfgFile)
                    
            app = aInst
            isInst = 'OK'
            if aInst != '':
                cnt = aInst.count(' ')
                
                if cnt > 0: # treat this like a command to execute
                    app = getResult(aInst, 'bin')
                
                isInst = isInstalled(app)

            show  = 1
            show1 = 1
            show2 = 1
            status = AR_NOTAVAIL
            if isInst == 'OK':
                status = AR_AVAIL
                
                # check version if requested
                if aVers != '':
                    version = reqVersion(aVers)

                    if version == 'NOK':
                        isInst = 'NOK'
                        status = AR_NOTAVAIL
            
            if isInst == 'NOK' and not cfgReader.showNonavail_:
                show1 = 0
            elif isInst == AR_NOINFO:
                status = ''

            if 'Server' in aMode and not cfgReader.showSrv_:
                aMode.remove('Server')
            
            if 'AT' in aMode and not cfgReader.showAt_:
                aMode.remove('AT')
             
            if 'Bemused' in aMode and not cfgReader.showBm_:
                aMode.remove('Bemused')
        
            if 'iViewer' in aMode and not cfgReader.showIView_:
                aMode.remove('iViewer')
                    
            if len(aMode) > 0:
                show = 1
            else:
                show = 0

            if aType == 'Application' and not cfgReader.showApps_:
                show2 = 0
            elif aType == 'Custom' and not cfgReader.showCustom_:
                show2 = 0
            elif aType == 'Example' and not cfgReader.showExamples_:
                show2 = 0
            elif aType == '':
                show2 = 0
            
            if show == 1 and show1 == 1 and show2 == 1:
                if debug: print 'Proceed '+aName
                                    
                isRun = AR_NOINFO
                if aRun != '':
                    isRun  = getResult(aRun,'reader')
                
                if status == AR_AVAIL and isRun == 'OK':
                    status = AR_RUNNING
                 
                addAppToList(aName, aIcon, app, aRun, isRun, cfgFile, status, aMode, aType, aDesc)
                
                if debug: print 'Processed',cfgFile
            else:
                if debug: print 'Skip',cfgFile
                    
            fd.close()

###############################################################################        
#
# Configuration management
# unified
#
###############################################################################        

class ConfigReader:
    def saveConfig(self):
        
        cfg = os.environ.get("HOME")+os.sep+'.anyRemote'
        if not os.path.exists(cfg):
            os.mkdir(cfg)
            
        f=open(cfg + os.sep + 'anyremote-fe.conf', 'w')
        if f:
            f.write('LastCfgFile='+self.lastCfgFile_+'\n')
            
            what = 'Show='
            if self.showApps_:
                what = what + 'Apps,'
            if self.showCustom_:
                what = what + 'Custom,'
            if self.showExamples_:
                what = what + 'Examples,'
            if self.showNonavail_:
                what = what + 'NonAvail,'
            if self.showAt_:
                what = what + 'AT,'
            if self.showSrv_:
                what = what + 'Server,'
            if self.showBm_:
                what = what + 'Bemused,'
            if self.showIView_:
                what = what + 'IViewer,'
            
            f.write(what+'\n')

            ac = '0'
            if self.autoReconn_:
                ac = '1'
            f.write('AutoReconnectAT='+ac+'\n')
            
            if self.dvSrvBT_ != '':
                f.write('DeviceServerBT='+self.dvSrvBT_+'\n')
            
            if self.dvSrvTCP_ != '':
                f.write('DeviceServerTCP='+self.dvSrvTCP_+'\n')
            
            if self.dvSrvWEB_ != '':
                f.write('DeviceServerWEB='+self.dvSrvWEB_+'\n')
            
            if self.dvSrvADV_ != '':
                f.write('DeviceServerManual='+self.dvSrvADV_+'\n')
             
            useTypes = 'DeviceUseType='
            if self.dvSrvUseADV_:
                useTypes = useTypes + 'ADV'
            else:
                if self.dvSrvUseBT_:
                    useTypes = useTypes + 'BT,'
                if self.dvSrvUseTCP_:
                    useTypes = useTypes + 'TCP,'
                if self.dvSrvUseWEB_:
                    useTypes = useTypes + 'WEB,'
            f.write(useTypes+'\n')

            if self.deviceAT_ != '':
                f.write('DeviceAT='+self.deviceAT_+'\n')

            if self.deviceBm_ != '':
                f.write('DeviceBemused='+self.deviceBm_+'\n')

            if self.deviceIV_ != '':
                f.write('DeviceIViewer='+self.deviceIV_+'\n')

            tm = "%s" % (self.updateTmout_)
            f.write('UpdateTimeout='+tm+'\n')
                
            if self.autoStart_ != '':
                f.write('AutoStartFile='+self.autoStart_+'\n')

            if self.doAutoStart_:
                f.write('AutoStart=true\n')
            else:
                f.write('AutoStart=false\n') 

            dirs = 'CfgDirs='
            for d in self.cfgDirs:
                if d != '':
                    dirs = dirs +d + ';'
            f.write(dirs+'\n')
            
            if self.browseTmout_ > 0:
                tm = "%s" % (self.browseTmout_)
                f.write('DeviceBrowserTimeout='+tm+'\n')
            else:
                f.write('DeviceBrowserTimeout=-1\n')
           
            f.write('J2MEDir='+self.j2meDir_+'\n')
            
            if self.checkJ2MEUpdate_:
                f.write('CheckJ2MEUpdate=true\n')
            
            f.close()
            
        saveDevices()

    def setDefaultConfig(self):

        self.lastCfgFile_  = ''
        self.cfgDirs       = []
        self.autoStart_    = ''
        self.doAutoStart_  = False
        self.j2meDir_      = ''
        self.checkJ2MEUpdate_ = False
        self.showApps_     = True
        self.showCustom_   = False
        self.showExamples_ = False
        self.showNonavail_ = False
        self.showAt_       = False
        self.showSrv_      = True
        self.showBm_       = False
        self.showIView_    = False
        self.autoReconn_   = False
        self.dvSrvBT_      = '19'
        self.dvSrvTCP_     = '5197'
        self.dvSrvWEB_     = '5080'
        self.dvSrvADV_     = 'bluetooth:19 -log'
        self.dvSrvUseBT_   = True
        self.dvSrvUseTCP_  = True
        self.dvSrvUseWEB_  = True
        self.dvSrvUseADV_  = False
        self.deviceAT_     = 'rfcomm:'
        self.deviceBm_     = ''
        self.deviceIV_     = 'socket:5197,web:5198'

        self.updateTmout_  = 60
        self.browseTmout_  = -1
        
    def readConfig(self):
        
        # anyRemote related part
        cfg  = os.environ.get("HOME")+os.sep+'.anyRemote' + os.sep + 'anyremote-fe.conf'
        
        if os.path.exists(cfg):
            f=open(cfg, 'r')
            if f:
                for line in f:
                    line = line.replace('\n','')
 
                    if line.startswith('LastCfgFile='):
                        self.lastCfgFile_=line[12:]
                    elif line.startswith('Show='):
                        #Show=Apps,Custom,Examples
                        what = line[5:].split(',')

                        # override defaults
                        self.showApps_ = False
                        self.showSrv_  = False
                        
                        for item in what:
                            if item == 'Apps':
                                self.showApps_ = True
                            elif item == 'Custom':
                                self.showCustom_ = True
                            elif item == 'Examples':
                                self.showExamples_ = True
                            elif item == 'NonAvail':
                                self.showNonavail_ = True
                            elif item == 'AT':
                                self.showAt_ = True
                            elif item == 'Server':
                                self.showSrv_ = True
                            elif item == 'Bemused':
                                self.showBm_ = True
                            elif item == 'IViewer':
                                self.showIView_ = True
                          
                            # compatibility with old versions
                            elif item == 'All':
                                self.showSrv_      = True
                                self.showApps_     = True
                                self.showCustom_   = True
                                self.showExamples_ = True
                                self.showNonavail_ = True
                              
                    elif line.startswith('AutoReconnectAT='):
                        self.autoReconn_ = (line == 'AutoReconnectAT=1')
                    elif line.startswith('AutoStart='):
                        useM = line[10:]
                        if useM == '1' or useM == 'true' or useM == 'True':
                            self.doAutoStart_ = True
                        else:
                            self.doAutoStart_ = False
                    elif line.startswith('AutoStartFile='):
                        self.autoStart_ = line[14:]
                    elif line.startswith('DeviceServerBT='):
                        self.dvSrvBT_ = line[15:]
                    elif line.startswith('DeviceServerTCP='):
                        self.dvSrvTCP_ = line[16:]
                    elif line.startswith('DeviceServerWEB='):
                        self.dvSrvWEB_ = line[16:]
                    elif line.startswith('DeviceServerManual='):
                        self.dvSrvADV_ = line[19:]
                    elif line.startswith('DeviceUseType='):
                        what = line[14:].split(',')
                        
                        for item in what:
                            if item == 'BT':
                                self.dvSrvUseBT_  = True
                                self.dvSrvUseADV_ = False
                            elif item == 'TCP':
                                self.dvSrvUseTCP_ = True
                                self.dvSrvUseADV_ = False
                            elif item == 'WEB':
                                self.dvSrvUseWEB_ = True
                                self.dvSrvUseADV_ = False
                            elif item == 'ADV':
                                self.dvSrvUseBT_  = False
                                self.dvSrvUseTCP_ = False
                                self.dvSrvUseWEB_ = False
                                self.dvSrvUseADV_ = True
                            
                    elif line.startswith('DeviceAT='):
                        self.deviceAT_ = line[9:]
                    elif line.startswith('DeviceBemused='):
                        self.deviceBm_ = line[14:]
                    elif line.startswith('DeviceIViewer='):
                        self.deviceIV_ = line[14:]
                    elif line.startswith('CfgDirs='):
                        self.cfgDirs=line[8:].split(';')
                    elif line.startswith('UpdateTimeout='):
                        self.updateTmout_=int(line[14:])
                    elif line.startswith('DeviceBrowserTimeout='):
                        tmt=line[21:]
                        try:
                            self.browseTmout_=int(tmt)
                        except ValueError:
                            self.browseTmout_=-1

                        if self.browseTmout_ <= 0:
                            self.browseTmout_=-1
                    elif line.startswith('J2MEDir='):
                        self.j2meDir_=line[8:]
                    elif line.startswith('CheckJ2MEUpdate=true'):
                        self.checkJ2MEUpdate_=True
                        
                    # compatibility
                    elif line.startswith('JavaDir='):
                        self.j2meDir_=line[8:]
                    # compatibility
                    elif line.startswith('CheckJavaUpdate=true'):
                        self.checkJ2MEUpdate_=True

                f.close()
                
                # Try to search again
                if self.j2meDir_ == '':
                    self.j2meDir_ = getJ2MEPath()
                
        # device browser related part
        cfg  = os.environ.get("HOME")+os.sep+'.anyRemote' + os.sep + AR_FILE_DEVICES
        
        if os.path.exists(cfg) :
            f=open(cfg, 'r')
            if f:
                for line in f:
                    line = line.replace('\n','')
                    os.path.exists(cfg)
                    
                    if line.startswith('Device='):
                        deviceData=line[7:].split(',')
                        
                        # try to be backward compatible
                        if len(deviceData) < 5:
                            print 'Skip peer',deviceData[0],'because of wrong format'
                            continue

                        v1 = deviceData[0]
                        v2 = deviceData[1]
                        v3 = deviceData[2]
                        v4 = deviceData[3]
                        v5 = deviceData[4]
                        
                        addDevice(v1,v2,v3,v4,v5)
                f.close()
                
    def getConnectString(self):
        if self.dvSrvUseADV_:
            return self.dvSrvADV_
        else:
            connStr = ''

            if self.dvSrvUseTCP_ and self.dvSrvTCP_ != '':
                connStr = "socket:"+self.dvSrvTCP_
            
            sep = ''
            if connStr != '':
                sep = ','

            if self.dvSrvUseBT_ and self.dvSrvBT_ != '':
                connStr = connStr + sep + "bluetooth:"+self.dvSrvBT_

            if connStr != '':
                sep = ','
            
            if self.dvSrvUseWEB_ and self.dvSrvWEB_ != '':
                connStr = connStr + sep +  "web:"+self.dvSrvWEB_
        
            return connStr
	    
    def getConnectStatusString(self):
	
	    if cfgReader.showAt_:
                return '';
	    if cfgReader.showBm_:
                return '';
	    if cfgReader.showIView_:

	        temp = cfgReader.deviceIV_;
	        temp = temp.replace('web:',AR_HTTP_PORT+' ');
	        temp = temp.replace('socket:',AR_TCP_PORT+' ');
	        return temp;

            if self.dvSrvUseADV_:
                return ''
            else:
                connStr = ''

                if self.dvSrvUseTCP_ and self.dvSrvTCP_ != '':
        	    connStr = AR_TCP_PORT+' '+self.dvSrvTCP_

                sep = ''
                if connStr != '':
        	    sep = ', '

                if self.dvSrvUseBT_ and self.dvSrvBT_ != '':
        	    connStr = connStr + sep + AR_BT_PORT+' '+self.dvSrvBT_

                if connStr != '':
        	    sep = ', '

                if self.dvSrvUseWEB_ and self.dvSrvWEB_ != '':
        	    connStr = connStr + sep + AR_HTTP_PORT+' '+self.dvSrvWEB_

                return connStr
        
    def setAutoStartFile(self):

        for cfgDir in self.cfgDirs:
        
            if cfgDir == '':
                continue
        
            if os.path.isfile(cfgDir):
                if cfgDir.find('mediacenter.cfg') >= 0:
                    self.autoStart_ = root + os.sep + cfgFile
                    self.doAutoStart_ = True
                    return 
            else:
                for root, dirs, files in os.walk(cfgDir):
                    if 'Utils' in dirs:
                        dirs.remove('Utils')
                    if 'Icons' in dirs:
                        dirs.remove('Icons')
                    if '.svn' in dirs:
                        dirs.remove('.svn')
            
                    for cfgFile in files:
                        nameext = cfgFile.split('.')
                        ext = nameext[len(nameext)-1]
                        
                        if ext == 'png' or ext == 'sh' or ext == 'py' or ext == 'gz':
                            continue
                        
                        if cfgFile == 'mediacenter.cfg':
                            self.autoStart_ = root + os.sep + cfgFile
                            self.doAutoStart_ = True
                            return 

##################################################################################
#
# Application status updater
#
##################################################################################
class StatusUpdater(threading.Thread):

    def __init__(self, timeout):
        threading.Thread.__init__(self) 
        self.tmout = timeout

    def run(self):
        global debug, liststore
        
        self.runUpdater =  True
        
        if debug: print 'StatusUpdater',self.tmout
        
        while self.runUpdater:
            timer = 0
            
            # catch stop event without waiting full timeout
            while self.runUpdater and timer < self.tmout:
                time.sleep(0.1)
                timer = timer + 0.1
            
            if self.runUpdater:
                if debug: print 'StatusUpdater: verify start'
            
                gtk.gdk.threads_enter()
                treeiter = liststore.get_iter_first()
                gtk.gdk.threads_leave()
            
            while self.runUpdater and treeiter != None:
                gtk.gdk.threads_enter()
                aRun = liststore.get_value(treeiter, 3)
                gtk.gdk.threads_leave()
                
                if aRun != '':
                    isRun  = getResult(aRun,'updater')
                    
                    gtk.gdk.threads_enter()
                    status = liststore.get_value(treeiter, 5)
                    
                    if status == AR_MANAGED and isRun == 'NOK':
                        status = AR_AVAIL
                    elif status == AR_AVAIL and isRun == 'OK':
                        status = AR_RUNNING
                    elif status == AR_RUNNING and isRun == 'NOK':
                        status = AR_AVAIL
                    #else:
                    #    status = ''
                    
                    strIter = liststore.get_string_from_iter(treeiter)
                    
                    # PyGTK works non stable with threads_enter/threads_leave
                    #liststore.set_value(treeiter, 5, status)    
                    gtk.gdk.threads_leave()
                    
                    putToMainQueue(['UPDATE_LIST',strIter,status])
                
                gtk.gdk.threads_enter()   
                treeiter = liststore.iter_next(treeiter)
                gtk.gdk.threads_leave()
                
            if debug: print 'StatusUpdater: verify done'
                
    def stop(self):
        global debug
        
        if debug: print 'StatusUpdater: stop'
        self.runUpdater = False

##################################################################################
#
# BT communication thread
#
##################################################################################

# Beware:
# Can not run more than one command on BT adapter at once, since it could hungs 

class BtComm(threading.Thread):

    def __init__(self, jDir):
        threading.Thread.__init__(self) 
        self.midletDir = jDir

    def run(self):
        global debug, cmd_array
        
        self.keepRun = True
        
        if debug:
            print 'BtComm: run'
        
        while self.keepRun:
        
            ctype = ''
            cdata = ''
            gtk.gdk.threads_enter()
            try:
                item = cmd_array[0]
                del cmd_array[0] 
                ctype = item[0]
                cdata = item[1]
            except NameError:
                pass
            except TypeError:
                pass
            except IndexError:
                pass
            gtk.gdk.threads_leave()
            
            if debug and ctype != '':
                print 'BtComm: (#',len(cmd_array),') got command',ctype,cdata
         
            if ctype == 'scan':
                self.doScan(cdata)
            elif ctype == 'ping':
                self.doPing(cdata)
            elif ctype.startswith('pushjar'):
                self.doPush(cdata,ctype[7:],False)
            elif ctype.startswith('pushjad'):
                self.doPush(cdata,ctype[7:],True)
            elif ctype == 'info':
                self.doInfo(cdata)
            elif ctype == 'test_at':
                self.doAT(cdata)
            else:
                time.sleep(3)
                
    def setStatus(self, address, status):
        global debug, bt_devices
        
        if debug: print 'set for',address,status

        gtk.gdk.threads_enter()
        treeiter = bt_devices.get_iter_first()
        gtk.gdk.threads_leave()

        while treeiter != None:
            gtk.gdk.threads_enter()
            addr = bt_devices.get_value(treeiter, 0)
            gtk.gdk.threads_leave()
            
            if address == addr:
                gtk.gdk.threads_enter()
                if status != bt_devices.get_value(treeiter, 5):
                    bt_devices.set_value(treeiter,5,status)
                                     
                needRun = bt_devices.get_value(treeiter,4)  
                gtk.gdk.threads_leave()
                
                if status == AR_AVAIL and needRun != '':
                    if debug: 
                        print 'run anyRemote with',needRun
                    startAnyRemote(needRun)
                
                    return
            
                gtk.gdk.threads_enter()
                treeiter = bt_devices.iter_next(treeiter)
                gtk.gdk.threads_leave()

    def doScan(self,force):
        global debug
        if debug: print 'BtComm: scan devices'
                    
        timer = 0
        existing = getDevSet()
        
        # Search new devices
        nearby_devices = []
        try:
            nearby_devices = bluetooth.discover_devices(lookup_names = True)
        except bluetooth.BluetoothError,msg:
            if debug: print "BtComm: BluetoothError",msg
            
            # sleep additional 5 sec
            t2 = 0
            while self.keepRun and t2 < 5:
                time.sleep(0.1)
                t2 = t2 + 0.1
        
        if debug: print "BtComm: found %d devices" % len(nearby_devices)

        availSet = getAvailableSet()
        
        for addr,name in nearby_devices:
            if debug: print "  %s - %s" % (addr, name)
            
            channels = ''
            
            services = bluetooth.find_service(address=addr)
            
            for svc in services:
                try:
                    if debug: print addr,svc["name"],svc["port"]
                
                    if svc["name"] == 'Serial Port' or svc["name"].startswith('COM ') or svc["name"].startswith('Dial-up') or svc["name"].startswith('Dialup'):
                        
                        if channels != '':
                            channels = channels+':'
                        channels = channels+str(svc["port"])
                    
                except AttributeError, NameError:
                        pass
        
            
            if addr not in existing:
                showDetailsWin(addr, name, name, channels, '', True)
            else:
                if addr in availSet:
                    availSet.remove(addr)
                else:
                    self.setStatus(addr,AR_AVAIL)
            
        for rest in availSet:
            self.setStatus(rest, '')
        
        if debug: print 'BtComm: verify done'
        
        if force == 'T':
            stopPBar()

    def doPing(self, data):
        global debug
        if debug: print 'BtComm: ping device'
        
        putToDevWQueue(['SET_STATUS',''])
        writePBar(AR_CONN_DEV)
        
        os.system('killall -9 hcitool 2> /dev/null')
        if debug: print 'hcitool name '+data
        ret = getResult('hcitool name '+data,'browser')
        
        stopPBar()
        if (ret == ''):
            putToDevWQueue(['SET_STATUS',_('Ping failed !')])
        else:
            putToDevWQueue(['SET_STATUS',_('Ping OK !')])

    def doPush(self, data, size, usejad):
        global debug
        if debug: print 'BtComm: obex push ',data,size,usejad
        
        putToDevWQueue(['SET_STATUS',''])
        stopPBar() 
	  
        dash = '-'
        if size == '':
            dash = ''
        midlet = 'anyRemote' + dash + size + '.jar'
	
        if not os.path.exists(self.midletDir):        
            putToDevWQueue(['SET_STATUS',_('Can not find J2ME midlet ('+midlet+_(') to upload !'))])
            return
        
        path = self.midletDir + os.sep + midlet
        if not os.path.isfile(path):
            putToDevWQueue(['SET_STATUS',_('Can not find J2ME midlet ('+midlet+_(') to upload !'))])
            return
        
        sender = ''    
        suffix = ' '    
        if (isInstalled('gnome-obex-send') == 'OK'):
            sender = 'gnome-obex-send -d '
        elif (isInstalled('bluetooth-sendto') == 'OK'):
            sender = 'bluetooth-sendto --dest='
        elif (isInstalled('kbtobexclient') == 'OK'):
            sender = 'kbtobexclient'
        elif (isInstalled('bluedevil-sendfile') == 'OK'):
            sender = 'bluedevil-sendfile -u '
            suffix = ' -f '
        elif (isInstalled('blueman-sendto') == 'OK'):
            sender = 'blueman-sendto -d '
        else:
            putToDevWQueue(['SET_STATUS',_('None of bluedevil-sendfile, gnome-obex-send, bluetooth-sendto, blueman-sendto  and kbtobexclient are installed !')])
            return

        ret = getResult(sender + data + suffix + path + ' &','browser')
        
        if usejad:
            jad = 'anyRemote' + dash + size + '.jad'
            path = self.midletDir + os.sep + jad
            if not os.path.isfile(path):
                putToDevWQueue(['SET_STATUS',_('Can not find JAD file ('+jad+_(') to upload !'))])
                return
        
            ret = getResult(sender + data + suffix + path + ' &','browser')
        
    def doInfo(self,data):
        global debug
        if debug: print 'BtComm: get info'

        writePBar(AR_CONN_DEV)
        
        services = bluetooth.find_service(address=data)

        if len(services) > 0:
            print "found %d services on %s" % (len(services), data)
            print
        else:
            print "no services found"

        for svc in services:
            print "Service Name: %s"    % svc["name"]
            print "    Host:        %s" % svc["host"]
            print "    Description: %s" % svc["description"]
            print "    Provided By: %s" % svc["provider"]
            print "    Protocol:    %s" % svc["protocol"]
            print "    channel/PSM: %s" % svc["port"]
            print "    svc classes: %s "% svc["service-classes"]
            print "    profiles:    %s "% svc["profiles"]
            print "    service id:  %s "% svc["service-id"]
            print

    def getSerialPort(self,addr):
        services = bluetooth.find_service(address=addr)
        for svc in services:
            try:
                if svc["name"] == 'Serial Port' or svc["name"].startswith('COM ') or svc["name"].startswith('Dial-up') or svc["name"].startswith('Dialup'):
                    return svc["port"]
            except AttributeError, NameError:
                    pass
        return None
        
    def send_at(self,sock,cmd):
        if len(cmd) == 0: 
            return ''
        
        data = cmd+'\r'
        print "send",cmd
        
        sock.send(cmd+'\r')
        time.sleep(0.5)
        data = sock.recv(1024)

        print "got",data
        return data

    def doAT(self,data):
        global debug
        if debug: print 'BtComm: doAT'
        
        putToDevWQueue(['SET_STATUS',''])
        writePBar(AR_CONN_DEV)        
        
        port = self.getSerialPort(data)
        if debug: print 'BtComm: port',port
        
        if port == None:
            putToDevWQueue(['SET_STATUS',_('Can not get port to connect to. Is there any device available ?')])
        else:
            
            sock=bluetooth.BluetoothSocket( bluetooth.RFCOMM )
            try:
                sock.connect((data, port))
            except bluetooth.BluetoothError,msg:
                d = str(msg)
                if debug: print d
                
                stopPBar()
                if d.startswith('(111,'):
                    putToDevWQueue(['SET_STATUS',_('Connection refused')])
                return

            ret = self.send_at(sock,"ATZ")
            ret = self.send_at(sock,"ATE0")
            ret = self.send_at(sock,"AT+CMER=?")
            
            status = '' 
            if ret.find('ERROR') == -1:
                ret = ret[ret.index('+CMER'):]
                ret = (ret.split('\n'))[0]
            
                AT_CMER=ret.replace(' ','').replace('\r','')
            
                #+CMER: (0,3),(0),(0),(0,1,2),(0)        <- bad
                #+CMER: (0,3),(0,1,2),(0),(0,1,2),(0)        <- OK
                s1 = (AT_CMER.split('('))[2]
                s2 = (s1.split(')'))[0]
                
                status = AT_CMER
                if s2 == '0':
                    status = _('AT mode is not supported by phone (')+status+')'
                else:
                    status = _('AT mode could be supported by phone (')+status+')'
            else:
                    status = _('AT mode is not supported by phone (ERROR response)')
                
            putToDevWQueue(['SET_STATUS',status])
            sock.close()

        stopPBar()
   
    def stop(self):
        global debug
        if debug: print 'BtComm stop'
        self.keepRun = False

##################################################################################
#
# DeviceDetail window
#
##################################################################################

class DeviceDetail(gtk.Window):

    def __init__(self, ba, m, n, channels, cfgFile, is_new, jDir):
        global debug 
        
        gtk.Window.__init__(self)
        
        self.model     = m.replace('\n','')
        self.dname     = n.replace('\n','')
        self.btAddress = ba
        self.cfile     = cfgFile
        self.isNew     = is_new
        self.channels  = channels
        self.midletDir = jDir
        
        self.initWindow() 

    def initWindow(self):
        global debug
        
        self.connect("destroy", self.close)
        
        capt = _('Device Parameters')
        if self.isNew:
            capt = _('New device')
            
        self.set_title(capt)
        
        vbox = gtk.VBox(False, 0)
        self.add(vbox)

        ################
        hbox = addHbox(vbox)
        
        label = gtk.Label('')
        hbox.pack_start(label, 0, True, 0)

        ################
        hbox = addHbox(vbox)
        
        label = gtk.Label('  '+_('Device Name')+': '+self.model+'       ')
        hbox.pack_start(label, 0, True, 0)

        label = gtk.Label(_('BT Address')+': '+self.btAddress+'         ')
        hbox.pack_end(label, 0, True, 0)
        
        ################
        hbox = addHbox(vbox)
            
        label = gtk.Label('')
        hbox.pack_start(label, 0, True, 0)

        ################
        hbox = addHbox(vbox)

        label = gtk.Label(_('Specify Name')+': ')
        hbox.pack_start(label, 0, True, 0)

        self.pname = gtk.Entry()
        self.pname.set_max_length(64)
        hbox.pack_start(self.pname, True, True, 0)
        self.pname.set_text(self.dname)
                
        ################
        hbox = addHbox(vbox)
        
        label = gtk.Label('')
        hbox.pack_start(label, 0, True, 0)

        ################
        hbox = addHbox(vbox)

        self.run_when = gtk.CheckButton(_('Run anyRemote when discovered'), False)
        hbox.pack_start(self.run_when, 0, True, 0)
        self.run_when.set_active((self.cfile != '')) 
        self.run_when.connect('toggled', self.doWhen)
        
        # support PyGTK<2.12
        try:
            self.run_when.set_tooltip_text(_('anyRemote will start only if no other instances of anyRemote are running'))
        except AttributeError:
            pass
        
        ################
        hbox = addHbox(vbox)

        self.cfgFile = gtk.Entry()
        self.cfgFile.set_max_length(64)
        hbox.pack_start(self.cfgFile, True, True, 0)
        self.cfgFile.set_text(self.cfile)
        self.cfgFile.set_editable(False)
        self.cfgFile.set_sensitive((self.cfile != ''))
        self.cfgFile.set_position(len(self.cfile))
        
        self.choose = gtk.Button(label=AR_CHOOSE)
        self.choose.connect("clicked", self.chooseAction)
        hbox.pack_end(self.choose, False, True, 0)
        self.choose.set_sensitive((self.cfile != ''))

        ################
        self.sBar = gtk.Statusbar()
        vbox.add(self.sBar)
        vbox.set_child_packing(self.sBar, 0, 1, 0, gtk.PACK_END)
        self.cid = self.sBar.get_context_id('a')
        self.sBar.show()

        ################
        hbox = addHbox(vbox)

        label = gtk.Label('')
        hbox.pack_start(label, 0, True, 0)

        separator = gtk.HSeparator()
        vbox.pack_start(separator, False, True, 0)
        separator.show()

        ################
        hbox = gtk.HBox(False, 4)
        vbox.add(hbox)
        vbox.set_child_packing(hbox, False, True, 0, gtk.PACK_START)
                                                             
        vbox1 = gtk.VBox(False, 0)
        hbox.add(vbox1)

        vbox2 = gtk.VBox(False, 0)
        hbox.add(vbox2)

        hbox1 = gtk.HBox(False, 4)
        vbox1.add(hbox1)
        vbox1.set_child_packing(hbox, False, True, 0, gtk.PACK_START)

        hbox2 = gtk.HBox(False, 4)
        vbox2.add(hbox2)
        vbox2.set_child_packing(hbox, False, True, 0, gtk.PACK_START)

        self.btnUp = gtk.Button(label=_('Upload J2ME'))
        self.btnUp.connect("clicked", self.upload)
        hbox1.pack_start(self.btnUp, False, True, 0)
        
        label = gtk.Label(_(' with icon set '))
        hbox1.pack_start(label, 0, True, 0)
        
        dummy = gtk.Label('')
        vbox1.pack_start(dummy, 0, True, 0)

        self.sz16 = gtk.RadioButton(None,'16x16', False)
        self.sz16.set_active(True)
        hbox2.pack_start(self.sz16, 0, True, 0)
        self.sz32 = gtk.RadioButton(self.sz16,'32x32', False)
        hbox2.pack_start(self.sz32, 0, True, 0)
        self.sz48 = gtk.RadioButton(self.sz16,'48x48', False)
        hbox2.pack_start(self.sz48, 0, True, 0)
        self.sz64 = gtk.RadioButton(self.sz16,'64x64', False)
        hbox2.pack_start(self.sz64, 0, True, 0)
        self.sz128 = gtk.RadioButton(self.sz16,'128x128', False)
        hbox2.pack_start(self.sz128, 0, True, 0)
        
        self.szAll = gtk.RadioButton(self.sz16,_('with all icon sets'), False)
        vbox2.pack_start(self.szAll, 0, True, 0)

        self.sz32.set_active(True)
        self.szAll.connect("clicked", self.clicked_szAll)

        ################
        hbox = gtk.HBox(False, 4)
        vbox.add(hbox)
        vbox.set_child_packing(hbox, False, True, 0, gtk.PACK_START)
        
        
        self.uplJad = gtk.CheckButton(_('Also upload JAD'), False)
        self.uplJad.set_active(False)
        hbox.pack_start(self.uplJad, 0, True, 0)
        
        # support PyGTK<2.12
        try:
             self.uplJad.set_tooltip_text(_('Can be useful for Samsung phones'))
        except AttributeError:
            pass

        self.bigTitleIcon = gtk.CheckButton(_('use big title icon'), False)
        hbox.pack_start(self.bigTitleIcon, 0, True, 0)
        self.bigTitleIcon.connect("clicked", self.clicked_bti)

        # support PyGTK<2.12
        try:
             self.bigTitleIcon.set_tooltip_text(_('16x16 and 64x64 title icons are available'))
        except AttributeError:
            pass

        ################
        hbox = gtk.HBox(False, 4)
        vbox.add(hbox)
        vbox.set_child_packing(hbox, False, True, 0, gtk.PACK_START)

        self.noJsr82 = gtk.CheckButton(_('use version without JSR-82'), False)
        hbox.pack_start(self.noJsr82, 0, True, 0)
        self.noJsr82.connect("clicked", self.clicked_nojsr82)

        # support PyGTK<2.12
        try:
            self.noJsr82.set_tooltip_text(_('Can be used on WinMobile devices'))
        except AttributeError:
            pass
        
        if not os.path.isdir(self.midletDir): 
            self.btnUp.set_sensitive(False)
            self.bigTitleIcon.set_sensitive(False)
            self.sz16.set_sensitive(False)
            self.sz32.set_sensitive(False)
            self.sz48.set_sensitive(False)
            self.sz64.set_sensitive(False)
            self.sz128.set_sensitive(False)
            
            # support PyGTK<2.12
            try:
                self.btnUp.set_tooltip_text(_('It needs to install anyremote-j2me-client package first'))
            except AttributeError:
                pass
        
        ################
        hbox = gtk.HBox(False, 4)
        vbox.add(hbox)
        vbox.set_child_packing(hbox, False, True, 0, gtk.PACK_END)

        self.btnPing = gtk.Button(label=_('Ping'))
        self.btnPing.connect("clicked", self.ping)
        hbox.pack_start(self.btnPing, False, True, 0)

        self.btnAT = gtk.Button(label=_('Test AT'))
        self.btnAT.connect("clicked", self.test_at)
        hbox.pack_start(self.btnAT, False, True, 0)

        btn = gtk.Button(label=AR_OK)
        addIconToButton(btn,gtk.STOCK_OK)
        btn.connect("clicked", self.ok)
        hbox.pack_end(btn, False, True, 0)
        
        btn = gtk.Button(label=AR_CLOSE)
        addIconToButton(btn,gtk.STOCK_CLOSE)
        btn.connect("clicked", self.close)
        hbox.pack_end(btn, False, True, 0)
 
 
        bt = btVerify()
        if bt == 'NOK':
            if debug: print 'DeviceDetail: Bluetooth not active'

            self.btnPing.set_sensitive(False)
            self.btnAT.set_sensitive(False)
            self.btnUp.set_sensitive(False)

            # support PyGTK<2.12
            try:
                self.btnPing.set_tooltip_text(_('Bluetooth service is not active'))
                self.btnAT.set_tooltip_text(_('Bluetooth service is not active'))
            except AttributeError:
                pass

        self.set_size_request(650,320)
        self.show_all()
        
        self.isShown = True
        
        self.ddQueueTimer = gobject.timeout_add(300, self.checkQueue)

    def ok(self,w):
        global bt_devices
        
        gtk.gdk.threads_enter()
        treeiter = bt_devices.get_iter_first()
        gtk.gdk.threads_leave()
            
        while treeiter != None:
            gtk.gdk.threads_enter()
            addr = bt_devices.get_value(treeiter, 0)
            gtk.gdk.threads_leave()
            
            if self.btAddress == addr:
                gtk.gdk.threads_enter()
                if self.pname.get_text() != bt_devices.get_value(treeiter, 2):
                    bt_devices.set_value(treeiter,2,self.pname.get_text())
                    
                if self.model != bt_devices.get_value(treeiter, 1):
                    bt_devices.set_value(treeiter,1,self.model)

                cf = self.cfgFile.get_text()
                if cf != bt_devices.get_value(treeiter, 4):
                    bt_devices.set_value(treeiter,4,cf)
                gtk.gdk.threads_leave()
                
                self.close(w)
                return
            
            gtk.gdk.threads_enter()
            treeiter = bt_devices.iter_next(treeiter)
            gtk.gdk.threads_leave()

        gtk.gdk.threads_enter()
        bt_devices.append([self.btAddress,self.model,self.pname.get_text(),self.channels,self.cfgFile.get_text(),AR_AVAIL])
        gtk.gdk.threads_leave()
        
        self.close(w)

    def close(self,w):
        global debug
        self.isShown = False
        self.hide()
        try:
            gobject.source_remove(self.ddQueueTimer)
        except AttributeError, NameError:
            if debug: print 'Exception: gobject.source_remove(gui.ddQueueTimer)'

    def chooseAction(self,w):
        self.choose.set_sensitive(False)
        cfgChooser(self)

    def setupFile(self, name):
        self.cfgFile.set_text(name)
        self.cfgFile.set_sensitive(True)
        self.cfgFile.set_position(len(name))
        self.choose.set_sensitive(True)
   
    def unlockFile(self):
        self.choose.set_sensitive(True)

    def clicked_szAll(self,w):
        if self.szAll.get_active():
           self.bigTitleIcon.set_active(False)
           
    def clicked_bti(self,w):
        if self.szAll.get_active() and not self.noJsr82.get_active():
           self.bigTitleIcon.set_active(False)
           
        if not self.bigTitleIcon.get_active():
           self.noJsr82.set_active(False)
           
    def clicked_nojsr82(self,w):
        
	sensitive = (not self.noJsr82.get_active())
	
	switches = [self.szAll, self.sz16, self.sz32, self.sz48, self.sz64, self.sz128]
	for switch in switches:
	    switch.set_sensitive(sensitive)
 
        if self.noJsr82.get_active():
           self.bigTitleIcon.set_active(True)
        
    def test_at(self,w):
        global debug, cmd_array
        if debug: print 'test_at'
        stopPBar() 
        startPBar(AR_WAIT_OPS)
        queueBT('test_at',self.btAddress)

    def ping(self,w):
        global debug, cmd_array
        if debug: print _('Queue ping request')

        stopPBar() 
        startPBar(_('Wait ping results'))
        queueBT('ping',self.btAddress)
            
    def upload(self,w):
        global debug, cmd_array, pbar
        if debug: print _('Queue push request')
         
        sz = '16'   
        if self.noJsr82.get_active():
            sz = 'nojsr82'
        elif self.szAll.get_active():
            sz = ''
        else:
            if self.sz32.get_active():
                sz = '32'
            elif self.sz48.get_active():
                sz = '48'
            elif self.sz64.get_active():
                sz = '64'
            elif self.sz128.get_active():
                sz = '128'
            
            if self.bigTitleIcon.get_active():
                sz = sz+'b'
            
        stopPBar() 
        startPBar(AR_WAIT_OPS)
        
        push = 'pushjar'
        if self.uplJad.get_active():
            push = 'pushjad'
            
        queueBT(push+sz,self.btAddress)
           
    def doWhen(self,w):
        global debug
        if debug: print 'doWhen'
        
        if self.run_when.get_active():
            self.choose.set_sensitive(True)
            self.cfgFile.set_sensitive(True)
        else: 
            self.choose.set_sensitive(False)
            self.cfgFile.set_text('')
            self.cfgFile.set_sensitive(False)
            
        if debug: print 'doWhen', self.cfgFile.get_text()

    def setStatustext(self,text):
        self.sBar.pop(self.cid)
        self.sBar.push(self.cid,'  ' + text)

    def checkQueue(self):
        global ddQueue
        try:
            data = ddQueue.get(False)
            
            if data[0] == 'SET_STATUS':
                self.setStatustext(data[1])
            
        except Queue.Empty:
            pass
        return True
            
##################################################################################
#
# Progressbar
#
##################################################################################

def startPBar(text):
    putToMainQueue(['PBAR_START',text,30])

def writePBar(text):
    putToMainQueue(['PBAR_WRITE',text])

def stopPBar():
    putToMainQueue(['PBAR_STOP'])

def progress_timeout(pbobj):
    pbobj.pbar.pulse()
    return True

class PBar(gtk.Window):
    def __init__(self, text, size, filename=None):
    
        gtk.Window.__init__(self)

        self.reset   = False
         
        self.text    = text
        self.tmout   = size
        self.fname   = filename

        self.set_resizable(True)

        self.set_title('')
        self.set_border_width(0)

        vbox = gtk.VBox(False, 5)
        vbox.set_border_width(10)
        self.add(vbox)

        align = gtk.Alignment(0.5, 0.5, 0, 0)
        vbox.pack_start(align, False, False, 5)

        self.pbar = gtk.ProgressBar()
        align.add(self.pbar)
        self.timer = gobject.timeout_add (100, progress_timeout, self)
        
        self.pbar.set_pulse_step(0.05)
        self.pbar.set_text(self.text)
        self.pbar.set_orientation(gtk.PROGRESS_LEFT_TO_RIGHT)

        separator = gtk.HSeparator()
        vbox.pack_start(separator, False, False, 0)
        
        self.show_all()

    def set_text(self, t):
        self.text = t
        self.pbar.set_text(self.text)
        
    def stop(self):
        try:
            gobject.source_remove(self.timer)
        except AttributeError, NameError:
            print 'Exception: Pbar gobject.source_remove(gui.timer)'
            pass
        self.destroy()
         
##################################################################################
#
# Choose cfg. file 
#
##################################################################################
class cfgChooser (gtk.Window):

    def __init__(self, details_win):
        global debug, liststore
        
        gtk.Window.__init__(self)

        self.dw = details_win
    
        self.set_title(_('Choose application'))
        self.connect("destroy", self.closePressed)
        
        vbox = gtk.VBox(False, 0)
        self.add(vbox)
        vbox.show()

        hbox = gtk.HBox(False, 0)
        vbox.add(hbox)
        vbox.set_child_packing(hbox, 1, 1, 0, gtk.PACK_START)
        hbox.show()
        
        scrolledwin = gtk.ScrolledWindow()
        scrolledwin.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
        hbox.add(scrolledwin)
        hbox.set_child_packing(scrolledwin, 1, 1, 0, gtk.PACK_START)
        scrolledwin.show()

        self.treeview  = gtk.TreeView(liststore)
       
        self.column_app    = gtk.TreeViewColumn(AR_APP)
        self.column_mode   = gtk.TreeViewColumn(AR_MODE)
        
        self.column_app.set_resizable(True)
        self.column_mode.set_resizable(True) 

        self.column_app.set_expand(True)
        
        self.column_app.set_spacing(5)
        self.column_mode.set_spacing(5)
  
        self.treeview.append_column(self.column_app)
        self.treeview.append_column(self.column_mode)

        self.cell0 = gtk.CellRendererPixbuf()
        self.cell1 = gtk.CellRendererText()
        self.cell2 = gtk.CellRendererText()

        self.column_app.pack_start   (self.cell0, False)
        self.column_app.pack_start   (self.cell1, True)
        self.column_mode.pack_end    (self.cell2, False)
        
        self.column_app.set_attributes   (self.cell0, pixbuf=1)
        self.column_app.set_attributes   (self.cell1, text=0)
        self.column_mode.set_attributes  (self.cell2, text=6)

        self.treeview.set_search_column(0)
        self.column_app.set_sort_column_id(0)
         
        scrolledwin.add(self.treeview)
        self.treeview.connect("row_activated",  self.rowActivateAction)
        
        self.treeview.show()
        
        ################
        separator = gtk.HSeparator()
        vbox.pack_start(separator, False, True, 0)
        separator.show()
        separator = gtk.HSeparator()
        vbox.pack_start(separator, False, True, 0)
        separator.show()
  
        ################
        hbox = addHbox(vbox)

        b = gtk.Button(label=AR_OK)
        b.connect("clicked", self.okPressed)
        hbox.pack_start(b, True, True, 0)

        b = gtk.Button(label=AR_CLOSE)
        b.connect("clicked", self.closePressed)
        hbox.pack_start(b, True, True, 0)
        
        self.set_size_request(400, 300)
        
        self.show_all()

    def rowActivateAction(self, treeview, path, view_column):
        treeiter = liststore.get_iter(path)
        self.quitOk(treeiter)

    def closePressed(self, widget):
        self.dw.unlockFile()   
        self.destroy()

    def okPressed(self, widget):
    
        (model, titer) = self.treeview.get_selection().get_selected()
        self.quitOk(titer)
        
    def quitOk(self, treeiter):
        global liststore
        
        try:
            s = liststore.get_value(treeiter, 4)
        except TypeError:
            # nothing was chosen
            return
    
        self.dw.setupFile(s)   
        self.destroy()
    
##################################################################################
#
# Front-End to anyRemote
#
##################################################################################

class FrontEnd(threading.Thread):
    def __init__(self): 
        global debug
        threading.Thread.__init__(self)        
        self.isReady = False
        if debug: print 'FrontEnd init'

    def ready(self):
        return self.isReady

    def stop(self):
        global debug
        if debug: print 'FrontEnd stop'
        self.isRun = False

    def run(self):
        global port, debug
        
        self.isRun = True
        if debug: print 'FrontEnd thread is running', port

        s = None
        for res in socket.getaddrinfo('localhost', port, socket.AF_INET, socket.SOCK_STREAM, 0, socket.AI_PASSIVE):
            af, socktype, proto, canonname, sa = res
            
            try:
                s = socket.socket(af, socktype, proto)
                s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
                s.setblocking(0)
            except socket.error, msg:
                s = None
                continue
            if debug: print 'FrontEnd socket created'
                
            try:
                s.bind(sa)
                s.listen(1)
            except socket.error, msg:
                s.close()
                s = None
                continue
            if debug: print 'FrontEnd socket after listen'
            
            break
            
        if s is None:
            if debug: print 'FrontEnd could not open socket'
            sys.exit(1)


        while self.isRun:
            while self.isRun:
                self.isReady = True
                try:
                    conn, addr = s.accept()
                    if debug: print 'accept', addr
                    break
                except socket.error,msg:
                    #print 'accept err', msg
                    time.sleep(0.1)
           
            if self.isRun:
                self.processOneConnection(conn, addr)
        
        if debug: print 'Close server socket' 
        s.close()
            
    def processOneConnection(self,conn,addr):
        global gui, liststore, cmdToSend, debug
            
        if debug: print 'FrontEnd processOneConnection', addr
        
        cfgFile = getResult('ps aux |grep anyremote|grep cfg|awk \'{n=split($0,arr);print arr[n-2];}\'', 'frontend')

        if cfgFile != '':
            gtk.gdk.threads_enter()
            ti  = liststore.get_iter_first()
            while ti != None:
                fName = liststore.get_value(ti, 4)
                if fName == cfgFile:
                    strIter = liststore.get_string_from_iter(ti)
                    putToMainQueue(['UPDATE_LIST',strIter,AR_MANAGED])
                    break
                    
                ti = liststore.iter_next(ti)
                
            gtk.gdk.threads_leave()
    
            self.isConn = True
            while self.isRun and self.isConn:
            
                conn.setblocking(0)
    
                if debug: print 'FrontEnd.Connected by', addr
            
                statusMessage('D')
            
                #time.sleep(0.5)
            
                while self.isRun and self.isConn:
                        
                    time.sleep(0.2)
            
                    data = ''
                    try:
                        data = conn.recv(512)
                        if debug: print 'Got from backend ', data
                            
                        putToMainQueue(['GET_DATA',data])
                         
                        if not data: 
                            if debug: print 'FrontEnd anyRemote die?'
                            
                            putToMainQueue(['SET_STATUS','S'])
                            self.isConn = False
                            break

                    except socket.error,msg:
                        pass
                        
                    try:
                        #print 'Send to backend ???'
                        gtk.gdk.threads_enter()
                        if cmdToSend:
                            # need to syncronize with GUI thread
                            if debug: print 'Send to backend '+cmdToSend + "\n"
                            conn.sendall(cmdToSend)
                            cmdToSend = '';
                        gtk.gdk.threads_leave()
                            
                    except socket.error, NameError:
                        if debug: print 'EXCEPTION 1'
                        pass
            
                if debug: print 'Close connection'  
                conn.close()
            
            gtk.gdk.threads_enter()
            ti  = liststore.get_iter_first()
            while ti != None:
                stts = liststore.get_value(ti, 5)
                if stts == AR_MANAGED:

                    aRun = liststore.get_value(ti, 3)
                    if aRun != '':
                        isRun  = getResult(aRun,'frontend')
                    
                        status = AR_AVAIL
                        if isRun == 'OK':
                            status = AR_RUNNING
                        
                        strIter = liststore.get_string_from_iter(ti)
                        putToMainQueue(['UPDATE_LIST',strIter,status])
                        
                    else:
                        isInst = isInstalled(liststore.get_value(ti, 2))
                        
                        status = ''
                        if isInst == 'OK':
                            status = AR_AVAIL
                            
                        strIter = liststore.get_string_from_iter(ti)
                        putToMainQueue(['UPDATE_LIST',strIter,status])
                    
                ti = liststore.iter_next(ti)
            gtk.gdk.threads_leave()
                
                
##################################################################################
#
# Device browser
#
##################################################################################

class DeviceBrowser (gtk.Window):

    def __init__(self):
        global gui, debug, bt_devices, cfgReader
        
        gtk.Window.__init__(self)
    
        self.set_title(AR_DEV_BROWSER)
        self.connect("destroy", self.close)

        vbox = gtk.VBox(False, 0)
        self.add(vbox)
        
        self.createMenus(vbox)

        hbox = gtk.HBox(False, 0)
        vbox.add(hbox)
        vbox.set_child_packing(hbox, 1, 1, 0, gtk.PACK_START)
        
        scrolledwin = gtk.ScrolledWindow()
        scrolledwin.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
        hbox.add(scrolledwin)
        hbox.set_child_packing(scrolledwin, 1, 1, 0, gtk.PACK_START)

        self.treeview  = gtk.TreeView(bt_devices)
       
        self.column_name = gtk.TreeViewColumn(_('Name'))
        self.column_dnam = gtk.TreeViewColumn(_('Device Name'))
        self.column_addr = gtk.TreeViewColumn(_('Address'))
        self.column_stts = gtk.TreeViewColumn(AR_STATUS)
        
        self.column_name.set_resizable(True)
        self.column_dnam.set_resizable(True)
        self.column_addr.set_resizable(True)
        self.column_stts.set_resizable(True) 

        self.column_name.set_expand(True)
        
        self.column_name.set_spacing(5)
        self.column_dnam.set_spacing(5)
        self.column_addr.set_spacing(5)
        self.column_stts.set_spacing(5)
  
        self.treeview.append_column(self.column_name)
        self.treeview.append_column(self.column_dnam)
        self.treeview.append_column(self.column_addr)
        self.treeview.append_column(self.column_stts)

        self.cell1 = gtk.CellRendererText()
        self.cell2 = gtk.CellRendererText()
        self.cell3 = gtk.CellRendererText()
        self.cell4 = gtk.CellRendererText()

        self.column_name.pack_start(self.cell1, True)
        self.column_dnam.pack_start(self.cell2, False)
        self.column_addr.pack_start(self.cell3, False)
        self.column_stts.pack_start(self.cell4, False)
        
        self.column_name.set_attributes(self.cell1, text=2)
        self.column_dnam.set_attributes(self.cell2, text=1)
        self.column_addr.set_attributes(self.cell3, text=0)
        self.column_stts.set_attributes(self.cell4, text=5)

        self.treeview.set_search_column(0)

        self.column_name.set_sort_column_id(0)
        
        bt_devices.set_sort_column_id(0,gtk.SORT_ASCENDING)
         
        scrolledwin.add(self.treeview)
        self.treeview.connect("row_activated",  self.rowActivateAction)
        
        separator = gtk.HSeparator()
        vbox.pack_start(separator, False, True, 0)
        separator = gtk.HSeparator()
        vbox.pack_start(separator, False, True, 0)

        ################
        hbox = addHbox(vbox)
        
        self.set_size_request(420, 200)
        self.show_all()
        
        self.isShown = True

        if cfgReader.browseTmout_ > 0:
            browseDevices('F')
            self.timer = gobject.timeout_add (int(1000)*int(cfgReader.browseTmout_), timerBrowseDevices)

    def createMenus(self, vbox):
    
        self.menubar = gtk.MenuBar()
        vbox.pack_start(self.menubar, expand=False)

        topmenuitem = gtk.MenuItem(AR_FILE)
        self.menubar.add(topmenuitem)
        
        menu = gtk.Menu()
        topmenuitem.set_submenu(menu)
 
        addMenuItem(menu, _('Scan for devices'), gtk.STOCK_FIND,       self.scan)
        addMenuItem(menu, _('Details'),          gtk.STOCK_PROPERTIES, self.details)
        addMenuItem(menu, '',                    gtk.STOCK_REMOVE,     self.delete)
        addMenuItem(menu, '',                    gtk.STOCK_CLOSE,      self.close)

    def showDetails(self,ti):
        global dwin
        v1 = bt_devices.get_value(ti, 0)
        v2 = bt_devices.get_value(ti, 1)
        v3 = bt_devices.get_value(ti, 2)
        v4 = bt_devices.get_value(ti, 3)
        v5 = bt_devices.get_value(ti, 4)
        
        showDetailsWin(v1, v2, v3, v4, v5, False)

    def scan(self,w):
        stopPBar () 
        startPBar(_('Scanning'))
        browseDevices('T')

    def delete(self,w):
        global bt_devices
        
        (model, titer) = self.treeview.get_selection().get_selected()
        if titer:
            treeiter = bt_devices.remove(titer)

    def details(self,w):
        (model, titer) = self.treeview.get_selection().get_selected()
        if titer:
            self.showDetails(titer)

    def rowActivateAction(self, treeview, path, view_column):
        global bt_devices
        self.showDetails(bt_devices.get_iter(path))
                    
    def close(self,w):
        global debug
        if debug: print "DeviceBrowser.close"
        
        saveDevices()
        
        self.destroy()
        self.isShown = False
            
##################################################################################
#
# Configuration checker 
#
##################################################################################

class CfgChecker (gtk.Window):

    def __init__(self, jDir):
        global debug
    
        gtk.Window.__init__(self)

        self.j2meDir = jDir
       
        self.set_title(_('Configuration Check'))
        self.connect("destroy", self.close)
    
        if debug: print 'CfgChecker: initWindow'
     
        pbs = AR_NOTINSTALLED
        if pybluez: pbs = _('Installed')
        
        ars = isInstalled('anyremote')
        if ars == 'NOK':
            ars = AR_NOTINSTALLED
        else:
            ars = _('Installed')

        bus = isInstalled('sdptool')
        if bus == 'NOK':
            bus = AR_NOTINSTALLED
        else:
            bus = _('Installed')

        jDir = getJ2MEPath()
        jVer = ''
        ajs = _('Installed')
        if jDir == '':
            ajs = AR_NOTINSTALLED
        else:
            jVer = getJ2MEClientVersion(jDir+os.sep+'anyRemote-16.jad')
            
        if jDir == os.environ.get("HOME")+os.sep+'.anyRemote':
            ajs = _('Downloaded')

        ajs = ajs+' v.'+jVer
        
        bts = btVerify()
        if bts == 'NOK':
            bts = _('Not active')
        else:
            bts = _('Active')
    
        pkg_list = gtk.TreeStore(str,str)
        pkg_list.append(None,["anyRemote",ars])
        pkg_list.append(None,["Bluez utilities",bus])
        pkg_list.append(None,["PyBluez",pbs])
        ti = pkg_list.append(None,["anyremote-j2me-client",ajs])
       
        if jDir != self.j2meDir and jDir != '':
            pkg_list.append(ti,[_('Warning:'),_('Installation directory of anyremote-j2me-client not specified in current setup configuration !')])
 
        pkg_list.append(None,["Bluetooth service",bts])

        vbox = gtk.VBox(False, 0)
        self.add(vbox)
        
        self.createMenus(vbox)

        hbox = gtk.HBox(False, 0)
        vbox.add(hbox)
        vbox.set_child_packing(hbox, 1, 1, 0, gtk.PACK_START)
        
        scrolledwin = gtk.ScrolledWindow()
        scrolledwin.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
        hbox.add(scrolledwin)
        hbox.set_child_packing(scrolledwin, 1, 1, 0, gtk.PACK_START)

        self.treeview  = gtk.TreeView(pkg_list)
        self.treeview.expand_all()
       
        self.column_pkg  = gtk.TreeViewColumn(_('Package'))
        self.column_stat = gtk.TreeViewColumn(AR_STATUS)
        
        self.column_pkg.set_resizable(True)
        self.column_stat.set_resizable(True)

        self.column_pkg.set_expand(True)
        
        self.column_pkg.set_spacing(5)
        self.column_stat.set_spacing(5)
  
        self.treeview.append_column(self.column_pkg)
        self.treeview.append_column(self.column_stat)

        self.cell1 = gtk.CellRendererText()
        self.cell2 = gtk.CellRendererText()

        self.column_pkg.pack_start(self.cell1, True)
        self.column_stat.pack_start(self.cell2, False)
        
        self.column_pkg.set_attributes(self.cell1, text=0)
        self.column_stat.set_attributes(self.cell2, text=1)

        self.treeview.set_search_column(0)

        self.column_pkg.set_sort_column_id(0)
        
        pkg_list.set_sort_column_id(0,gtk.SORT_ASCENDING)
         
        scrolledwin.add(self.treeview)
        
        separator = gtk.HSeparator()
        vbox.pack_start(separator, False, True, 0)
        separator = gtk.HSeparator()
        vbox.pack_start(separator, False, True, 0)

        ################
        hbox = addHbox(vbox)
        
        self.set_size_request(320, 220)
        self.show_all()
        
        self.isShown = True

    def createMenus(self, vbox):
    
        self.menubar = gtk.MenuBar()
        vbox.pack_start(self.menubar, expand=False)

        topmenuitem = gtk.MenuItem(AR_FILE)
        self.menubar.add(topmenuitem)
        
        menu = gtk.Menu()
        topmenuitem.set_submenu(menu)
        
        addMenuItem(menu, '', gtk.STOCK_CLOSE, self.close)

    def close(self,w):
        self.destroy()
        self.isShown = False
            
##################################################################################
#
# Editor 
#
##################################################################################

class cfgEditor (gtk.Window):

    def __init__(self, f):
        
        gtk.Window.__init__(self)
        
        self.editedFile = f
        
        self.set_size_request(600, 700)
        self.set_resizable(True)  
        self.connect("destroy", self.closeEditWindow)
        self.set_title(_('Edit configuration file'))
        self.set_border_width(0)

        box1 = gtk.VBox(False, 0)
        self.add(box1)
       
        self.menubar = gtk.MenuBar()
        box1.pack_start(self.menubar, expand=False)
       
        topmenuitem = gtk.MenuItem(AR_FILE)
        self.menubar.add(topmenuitem)

        menu = gtk.Menu()
        topmenuitem.set_submenu(menu)
        
        addMenuItem(menu, _('Save'),    gtk.STOCK_SAVE,    self.saveFile)
        addMenuItem(menu, _('Save As'), gtk.STOCK_SAVE_AS, self.saveAs)
        addMenuItem(menu, AR_CLOSE,     gtk.STOCK_CLOSE,   self.closeEditWindow)
 
        box2 = gtk.VBox(False, 10)
        box2.set_border_width(10)
        box1.pack_start(box2, True, True, 0)

        sw = gtk.ScrolledWindow()
        sw.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
        textview = gtk.TextView()
        textview.set_editable(False);
        self.textbuffer = textview.get_buffer()
        sw.add(textview)

        box2.pack_start(sw)
        
        infile = None
        try:
            infile = open(self.editedFile, "r")
        except IOError:
            pass
            
        if infile:
            string = infile.read()
            infile.close()
            self.textbuffer.set_text(string)
            
            textview.set_editable(os.access(self.editedFile, os.W_OK))

        else:
            errorMessage(_('Can not read the file ')+self.editedFile)
            self.editedFile = ""
                
        self.show_all()

    def closeEditWindow(self, widget):
        self.destroy()

    def saveFile(self, widget):
        try:
            f=open(self.editedFile, 'w')
        
            if f:
                i1 = self.textbuffer.get_iter_at_offset(0)
                i2 = self.textbuffer.get_iter_at_offset(self.textbuffer.get_char_count())
                txt = self.textbuffer.get_text(i1, i2)
                f.write(txt)
                f.close()
                self.destroy()
        except IOError:
            errorMessage(_('Can not save the file !'))
            self.saveAs(None)

    def saveAs(self, widget):
        self.fdialog = gtk.FileChooserDialog(_('Save File As'),None,gtk.FILE_CHOOSER_ACTION_SAVE,
                                (gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_SAVE,gtk.RESPONSE_OK))
         
        self.fdialog.set_default_response(gtk.RESPONSE_OK)
        response = self.fdialog.run()
        
        if response == gtk.RESPONSE_OK:
            f = self.fdialog.get_filename()
            if f:
                self.editedFile = f
                self.saveFile(None)
        self.fdialog.destroy()

##################################################################################
#
# Main window
#
##################################################################################

class gAnyRemote(gtk.Window):

    def __init__(self, openW, cfgSet):
        global debug, guiMode, liststore, cfgReader

        gtk.Window.__init__(self)
        self.get_settings().set_long_property('gtk-menu-images', True, '')

        initVerify()

        self.notInTray = openW
        self.initTray(openW)

        self.set_title("gAnyRemote")

        self.connect("size-allocate", self.resizeEvent)

        vbox = gtk.VBox(False, 0)
        self.add(vbox)
        
        self.createMenus(vbox)

        hbox = gtk.HBox(False, 0)
        vbox.add(hbox)
        vbox.set_child_packing(hbox, 1, 1, 0, gtk.PACK_START)
        
        scrolledwin = gtk.ScrolledWindow()
        scrolledwin.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
        hbox.add(scrolledwin)
        hbox.set_child_packing(scrolledwin, 1, 1, 0, gtk.PACK_START)

        self.treeview  = gtk.TreeView() 
       
        self.column_app    = gtk.TreeViewColumn(AR_APP)
        self.column_status = gtk.TreeViewColumn(AR_STATUS)
        self.column_mode   = gtk.TreeViewColumn(AR_MODE)
        self.column_type   = gtk.TreeViewColumn(_('Type'))
        
        self.column_app.set_resizable(True)
        self.column_status.set_resizable(True)
        self.column_mode.set_resizable(True) 
        self.column_type.set_resizable(True)  

        self.column_app.set_expand(True)

        self.column_app.set_spacing(5)
        self.column_status.set_spacing(5)
        self.column_mode.set_spacing(5)
        self.column_app.set_spacing(5)

        #self.column_app.set_min_width(200)

        self.treeview.append_column(self.column_app)
        self.treeview.append_column(self.column_status)
        self.treeview.append_column(self.column_mode)
        self.treeview.append_column(self.column_type)

        self.cell0 = gtk.CellRendererPixbuf()
        self.cell1 = gtk.CellRendererText()
        self.cell2 = gtk.CellRendererText()
        self.cell3 = gtk.CellRendererText()
        self.cell4 = gtk.CellRendererText()

        self.column_app.pack_start   (self.cell0, False)
        self.column_app.pack_start   (self.cell1, True)
        self.column_status.pack_start(self.cell2, False)
        self.column_mode.pack_start  (self.cell3, False)
        self.column_type.pack_end    (self.cell4, False)
        
        self.column_app.set_attributes   (self.cell0, pixbuf=1)
        self.column_app.set_attributes   (self.cell1, text=0)
        self.column_status.set_attributes(self.cell2, text=5)
        self.column_mode.set_attributes  (self.cell3, text=6)
        self.column_type.set_attributes  (self.cell4, text=7)

        self.treeview.set_search_column(0)
        #self.treeview.set_fixed_height_mode(1)

        self.column_app.set_sort_column_id(0)
        
        liststore.set_sort_column_id(0,gtk.SORT_ASCENDING)

        scrolledwin.add(self.treeview)
        self.treeview.connect("row_activated",  self.rowActivateAction)
        self.treeview.connect("cursor_changed", self.rowSelectAction)

        self.treeview.show()
        
        separator = gtk.HSeparator()
        vbox.pack_start(separator, False, True, 0)
        separator = gtk.HSeparator()
        vbox.pack_start(separator, False, True, 0)
 
        ################
        hbox = gtk.HBox(False, 0)
        if guiMode == 'expert':
            vbox.add(hbox)
            vbox.set_child_packing(hbox, False, True, 0, gtk.PACK_START)
             
        self.entry = gtk.Entry()
        self.entry.set_max_length(512)
        
        if guiMode == 'expert':
            hbox.pack_start(self.entry, True, True, 0)

            b = gtk.Button(label=AR_CHOOSE)
            b.connect("clicked", self.openFDialog, self.entry)
            hbox.pack_end(b, False, False, 0)
                
        ################
        if debug:
            hbox = gtk.HBox(False, 0)
            vbox.add(hbox)
            vbox.set_child_packing(hbox, False, True, 0, gtk.PACK_START)
        
            self.cmd = gtk.Entry()
            self.cmd.connect('key-press-event', self.commandRun)
            self.cmd.set_max_length(512)
            hbox.pack_start(self.cmd, True, True, 0)
 
            bExec = gtk.Button(label=_('Execute Command'))
            bExec.connect("clicked", self.execCmd)
            hbox.pack_end(bExec, False, False, 0)
  
        ################
        hbox = addHbox(vbox)

        self.detailsStore = gtk.TreeStore(str)
        self.detailsHead = self.detailsStore.append(None,[_('Details')])
        self.detailsData = self.detailsStore.append(self.detailsHead,[''])
         
        self.detailsTreeview  = gtk.TreeView(self.detailsStore)
        
        self.detailsRenderer = gtk.CellRendererText()
        self.detailsRenderer.set_property('cell-background-gdk', self.get_style().bg[gtk.STATE_NORMAL])
        try:
            self.detailsRenderer.set_property('wrap-mode', pango.WRAP_WORD) #gtk.WRAP_WORD ?
        except TypeError, AttributeError:
            pass
                
        self.detailsColumn = gtk.TreeViewColumn('')
        self.detailsColumn.pack_start(self.detailsRenderer, True)
        self.detailsColumn.set_attributes(self.detailsRenderer, text=0)
        self.detailsColumn.set_sort_column_id(0)
        
        self.detailsTreeview.append_column(self.detailsColumn) 
        self.detailsTreeview.set_headers_visible(False)
        self.detailsTreeview.set_enable_search(False)
        self.detailsTreeview.get_selection().set_mode(gtk.SELECTION_NONE)

        hbox.pack_start(self.detailsTreeview, True, True, 0)

        ################
        hbox = addHbox(vbox)

        self.runBtn = gtk.Button(label=_('Start'))
        addIconToButton(self.runBtn,gtk.STOCK_EXECUTE)
        self.runBtn.connect("clicked", self.runPressed)
        hbox.pack_start(self.runBtn, True, True, 0)

        self.stopBtn = gtk.Button(label=_('Stop'))
        addIconToButton(self.stopBtn,gtk.STOCK_STOP)
        self.stopBtn.connect("clicked", self.stopPressed)
        hbox.pack_start(self.stopBtn, True, True, 0)
                                                                     
        self.sBar = gtk.Statusbar()
        vbox.add(self.sBar)
        vbox.set_child_packing(self.sBar, 0, 1, 0, gtk.PACK_END)
        self.cid = self.sBar.get_context_id('a')

        if debug:
            h = 420
        else:
            h = 390
            
        self.set_size_request(500, h)
        
        try:
            self.detailsRenderer.set_property('wrap-width', 450)
        except TypeError, AttributeError:
            pass
            
        self.set_icon(findIcon('ganyremote_small.png'))
        
        if self.notInTray:
            self.show_all()
                 
        gtk.window_set_default_icon(self.pixbufOn)
                
        self.setStatusStopped()
        
        if cfgSet == 0 or cfgReader.j2meDir_ == '':
            self.showWizard(cfgSet, cfgReader.j2meDir_)

        if cfgReader.doAutoStart_ and cfgReader.autoStart_ != '':
            gobject.timeout_add(500, self.autoStartBackend)
        
        self.frontEnd = None

        self.inQueueTimer = gobject.timeout_add(300, self.checkInputQueue)
    
    def saveConfigAction(self, action):
        self.saveCfg()

    def setAutoStartup(self, wm, isAuto):
        if wm == 'KDE':
            autopath = os.environ.get("HOME")+os.sep+'.kde'+os.sep+'Autostart'+os.sep+'ganyremote'
            if isAuto:
                if not os.path.exists(autopath):
                    os.system('ln -s `which ganyremote` '+autopath)
            else:
                os.system('rm -f '+autopath)

        elif wm == 'Gnome':  # will work for gnome > 2.14 ?
            cfgpath  = os.environ.get("HOME")+os.sep+'.config'
            autopath = cfgpath+os.sep+'autostart'
            autorun  = autopath+os.sep+'ganyremote.desktop'

            if not os.path.isdir(cfgpath):
                os.mkdir(cfgpath)
            if not os.path.isdir(autopath):
                os.mkdir(autopath)
            if isAuto:
                if not os.path.isfile(autorun):
                    f=open(autorun, 'w')
                    if f:
                        f.write('[Desktop Entry]\n')
                        f.write('Encoding=UTF-8\n')
                        f.write('Name=gAnyRemote\n')
                        f.write('Exec=ganyremote\n')
                        f.write('Icon=ganyremote\n')
                        f.write('Type=Application\n')
                        f.write('Comment=Remote control through bluetooth or IR connection\n')
                        f.write('GenericName=Remote control through bluetoth or IR connection\n')
                        f.write('Categories=Utility;\n')
                        f.close()
            else:
                os.system('rm -f '+autorun)

    def selectLastInList(self):
        global cfgReader

        gtk.gdk.threads_enter()
        if gui.treeview.get_model() == None:
            gui.treeview.set_model(liststore)
        
        ti  = liststore.get_iter_first()
        while ti != None: 
            fName = liststore.get_value(ti, 4)
            
            if fName == cfgReader.lastCfgFile_:
                try:
                     gui.treeview.get_selection().select_iter(ti)
                except AttributeError:
                    pass
                break
                
            ti = liststore.iter_next(ti)
        gtk.gdk.threads_leave()

    def populateCfgFiles(self):
        global debug, cfgFileReaderFlag, cfgReader
        if debug: print 'populateCfgFiles'
        try:
            if cfgFileReaderFlag:
                return
        except NameError:
            pass
            
        stopUpdater()
        
        cfgFileReader = CfgFileReader()
        cfgFileReader.start()

    def autoStartBackend(self):
        global cfgReader, frontEnd, cfgFileReaderFlag
        
        if cfgReader.doAutoStart_ and cfgReader.autoStart_ != '':
            if not frontEnd or not frontEnd.ready() or cfgFileReaderFlag:
                # respawn timer
                return True
    
            startAnyRemote(cfgReader.autoStart_)
        
        return False

    ##################################################################################
    #
    # Config Window related part
    #
    ##################################################################################
    
    def showBrowser(self, action):
        showBrowserWin()

    def showChkCfg(self, action):
        global cfgReader
        showChkCfgWin(cfgReader.j2meDir_)

    def showConfAction(self, action):
        self.showConfDialog()

    def showConfDialog(self):
        global bt_devices, cfgReader
        
        self.dirsChanged = False
        
        self.config = gtk.Window(gtk.WINDOW_TOPLEVEL)
        self.config.set_title(_('Preferences'))
        self.config.set_size_request(730, 300)
        self.config.connect("destroy", self.closeCfg)
       

        vbox_top = gtk.VBox(False, 0)
        self.config.add(vbox_top)
        
        notebook = gtk.Notebook()
        notebook.set_tab_pos(gtk.POS_TOP)
        vbox_top.add(notebook)
        
        vbox = gtk.VBox(False, 0)
        notebook.append_page(vbox, gtk.Label(_('General')))
        
        vbox_server = gtk.VBox(False, 0)
        notebook.append_page(vbox_server, gtk.Label(_('Server mode')))
        
        vbox_at = gtk.VBox(False, 0)
        notebook.append_page(vbox_at, gtk.Label(_('AT mode')))
        
        vbox_bm = gtk.VBox(False, 0)
        notebook.append_page(vbox_bm, gtk.Label(_('Bemused')))
        
        vbox_iv = gtk.VBox(False, 0)
        notebook.append_page(vbox_iv, gtk.Label(_('iViewer')))
 
        hbox = gtk.HBox(False, 0)
        vbox.add(hbox)
        vbox.set_child_packing(hbox, 0, 1, 0, gtk.PACK_START)

        ################
        # Common tab
        ################
          
        hsep = gtk.HSeparator()
        vbox.add(hsep)
        vbox.set_child_packing(hsep, 0, 1, 0, gtk.PACK_START)
        
        ################
        hbox = addHbox(vbox)
        
        self.autoRun = gtk.CheckButton(_('Run on startup'))
        hbox.pack_start(self.autoRun, False, False, 0)
        self.autoRun.set_active(cfgReader.doAutoStart_)
        self.autoRun.connect('toggled',  self.autoRunToggled)
        
        self.autoFile = gtk.Entry()
        self.autoFile.set_max_length(512)
        hbox.pack_start(self.autoFile, True, True, 0)
        self.autoFile.set_text(cfgReader.autoStart_)
        self.autoFile.set_editable(True)
        self.autoFile.set_sensitive(cfgReader.doAutoStart_)
        self.autoFile.set_position(len(cfgReader.autoStart_))

        self.chooseAuto = gtk.Button(label=AR_CHOOSE)
        self.chooseAuto.connect("clicked", self.chooseAutoStart)
        hbox.pack_end(self.chooseAuto, False, False, 0)
        self.chooseAuto.set_sensitive(cfgReader.doAutoStart_)

        ################
        hbox = gtk.HBox(False, 0)
        vbox.add(hbox)
        vbox.set_child_packing(hbox, 1, 1, 0, gtk.PACK_START)

        scrolledwin = gtk.ScrolledWindow()
        scrolledwin.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
        hbox.add(scrolledwin)
        hbox.set_child_packing(scrolledwin, 1, 1, 0, gtk.PACK_START)

        # support PyGTK<2.12
        try:
            scrolledwin.set_tooltip_text(_('Choose directories with configuration files and add them to the list'))
        except AttributeError:
            pass
        
        self.cfg_liststore = gtk.ListStore(str)
        self.cfg_treeview  = gtk.TreeView(self.cfg_liststore)
       
        self.column_dir = gtk.TreeViewColumn(_('Directories'))
        self.cfg_treeview.append_column(self.column_dir)
        self.cfg_cell = gtk.CellRendererText()
        self.column_dir.pack_start(self.cfg_cell, True)
        self.column_dir.set_attributes(self.cfg_cell, text=0)
        self.column_dir.set_sort_column_id(0)
        scrolledwin.add(self.cfg_treeview)
         
        ################
        hbox = gtk.HBox(False, 0)
        vbox.add(hbox)
        vbox.set_child_packing(hbox, 0, 1, 0, gtk.PACK_START)
        
        self.btnAdd = gtk.Button(label=AR_ADD)
        self.btnAdd.connect("clicked", self.addToCfgDirList)
        hbox.pack_start(self.btnAdd, False, False, 0)

        btn = gtk.Button(label=AR_DELETE)
        btn.connect("clicked", self.deleteFromCfgDirList)
        hbox.pack_start(btn, False, False, 0)

        separator = gtk.HSeparator()
        vbox.pack_start(separator, False, True, 0)

        ################
        hbox = gtk.HBox(False, 0)
        vbox.add(hbox)
        vbox.set_child_packing(hbox, 0, 1, 0, gtk.PACK_START)

        vbox1 = gtk.VBox(False, 0)
        hbox.add(vbox1)

        label = gtk.Label(_('Show in list : '))
        vbox1.pack_start(label, False, False, 0)
        label.set_alignment(0,0)

        vbox1 = gtk.VBox(False, 0)
        hbox.add(vbox1)
        
        self.showSrv = gtk.RadioButton(None,_('Server-mode'))
        vbox1.pack_start(self.showSrv, True, True, 0)
        
        self.showApps = gtk.CheckButton(_('Applications'))
        vbox1.pack_end(self.showApps, True, True, 0)
        self.showApps.set_active(cfgReader.showApps_)
        
        vbox1 = gtk.VBox(False, 0)
        hbox.add(vbox1)
        
        self.showAt = gtk.RadioButton(self.showSrv, _('AT-mode'))
        vbox1.pack_start(self.showAt, True, True, 0)
        
        self.showCustom = gtk.CheckButton(_('Custom Made'))
        vbox1.pack_end(self.showCustom, True, True, 0)
        self.showCustom.set_active(cfgReader.showCustom_)
        
        vbox1 = gtk.VBox(False, 0)
        hbox.add(vbox1)

        self.showBm = gtk.RadioButton(self.showSrv, _('Bemused-emulation'))
        vbox1.pack_start(self.showBm, True, True, 0)
        
        self.showExamples = gtk.CheckButton(_('Examples'))
        vbox1.pack_end(self.showExamples, True, True, 0)
        self.showExamples.set_active(cfgReader.showExamples_)
        
        vbox1 = gtk.VBox(False, 0)
        hbox.add(vbox1)

        self.showIView = gtk.RadioButton(self.showSrv, _('iViewer'))
        vbox1.pack_start(self.showIView, True, True, 0)
        
        self.showNonavail = gtk.CheckButton(_('Non-available'))
        vbox1.pack_end(self.showNonavail, True, True, 0)
        self.showNonavail.set_active(cfgReader.showNonavail_)
        
        self.showBm.set_active   (cfgReader.showBm_)
        self.showIView.set_active(cfgReader.showIView_)
        self.showAt.set_active   (cfgReader.showAt_)
        self.showSrv.set_active  (cfgReader.showSrv_)
        
        self.showApps.connect    ('toggled', self.filterChangedAction)
        self.showCustom.connect  ('toggled', self.filterChangedAction)
        self.showExamples.connect('toggled', self.filterChangedAction)
        self.showNonavail.connect('toggled', self.filterChangedAction)
        self.showAt.connect      ('toggled', self.filterChangedAction)
        self.showSrv.connect     ('toggled', self.filterChangedAction)
        self.showBm.connect      ('toggled', self.filterChangedAction)
        self.showIView.connect   ('toggled', self.filterChangedAction)
    
        separator = gtk.HSeparator()
        vbox.pack_start(separator, False, True, 0)

        ################
        hbox = gtk.HBox(False, 0)
        vbox.add(hbox)
        vbox.set_child_packing(hbox, 0, 1, 0, gtk.PACK_START)
        
        label = gtk.Label(_('Auto startup with'))
        hbox.pack_start(label, True, True, 0)
        
        self.autorunGnome = gtk.CheckButton(_('Gnome session'))
        hbox.pack_start(self.autorunGnome, True, True, 0)
        self.autorunGnome.set_active(os.path.exists(os.environ.get("HOME")+os.sep+'.config'+os.sep+'autostart'+os.sep+'ganyremote.desktop'))
        
        self.autorunKDE = gtk.CheckButton(_('KDE session'))
        hbox.pack_start(self.autorunKDE, True, True, 0)
        self.autorunKDE.set_active(os.path.exists(os.environ.get("HOME")+os.sep+'.kde'+os.sep+'Autostart'+os.sep+'ganyremote'))

        separator = gtk.HSeparator()
        vbox.pack_start(separator, False, True, 0)

        ################
        hbox = addHbox(vbox)

        self.updLabel = gtk.Label(_('Update application list every'))
        hbox.pack_start(self.updLabel, True, True, 0)        

        self.updateTmout = gtk.Entry()
        self.updateTmout.set_max_length(6)
        self.updateTmout.set_width_chars(2)
        hbox.pack_start(self.updateTmout, True, True, 0)
        self.updateTmout.connect('changed', self.tmoutChangedAction)
        
        # support PyGTK<2.12
        try:
            self.updateTmout.set_tooltip_text(_('Empty field means no update'))
        except AttributeError:
            pass
        
        self.secLabel1 = gtk.Label(_('sec.'))
        hbox.pack_start(self.secLabel1, True, True, 0)
        
        tm = ''
        if cfgReader.updateTmout_ > 0:
            tm = "%s" % (cfgReader.updateTmout_)
        self.updateTmout.set_text(tm)
        
        separator = gtk.VSeparator()
        hbox.pack_start(separator, False, True, 0)
       
        self.brLabel = gtk.Label(' '+_('Run device browser with timeout')+'  ')
        hbox.pack_start(self.brLabel, False, True, 0)
        self.brLabel.set_sensitive((cfgReader.browseTmout_ > 0))
        
        self.browseTmout = gtk.Entry()
        self.browseTmout.set_max_length(5)
        self.browseTmout.set_width_chars(3)
        hbox.pack_start(self.browseTmout, False, True, 0)
        self.browseTmout.connect('changed', self.dbrowseChangedAction)
        
        # support PyGTK<2.12
        try:
            self.browseTmout.set_tooltip_text(_('Empty field means no update. Beware: Android/J2ME clients could fail to connect to anyRemote when browsing is in process'))
        except AttributeError:
            pass
        
        self.secLabel2 = gtk.Label(_('sec.'))
        hbox.pack_start(self.secLabel2, True, True, 0)
        
        tm = ''
        if cfgReader.browseTmout_ > 0:
            tm = "%s" % (cfgReader.browseTmout_)
        self.browseTmout.set_text(tm)

        ################
        # Server tab
        ################
        hbox = gtk.HBox(False, 0)
        vbox_server.add(hbox)
        vbox_server.set_child_packing(hbox, False, True, 0, gtk.PACK_START)
        
        vbox2 = gtk.VBox(False, 0)
        hbox.add(vbox2)
        hbox.set_child_packing(vbox2, False, True, 0, gtk.PACK_START)
        
        self.connBT = gtk.CheckButton(_('Use Bluetooth connection, channel '))
        vbox2.pack_start(self.connBT, True, True, 0)
        
        self.connTCP = gtk.CheckButton(_('Use TCP/IP connection, port'))
        vbox2.pack_start(self.connTCP, True, True, 0)
        
        self.connWEB = gtk.CheckButton(_('Use Web Interface, port'))
        vbox2.pack_start(self.connWEB, True, True, 0)
        
        self.connMan = gtk.CheckButton(_('Specify options manually'))
        vbox2.pack_start(self.connMan, True, True, 0)
        
        self.connBT.set_active (cfgReader.dvSrvUseBT_)
        self.connTCP.set_active(cfgReader.dvSrvUseTCP_)
        self.connWEB.set_active(cfgReader.dvSrvUseWEB_)
        self.connMan.set_active(cfgReader.dvSrvUseADV_)
    
        vbox4 = gtk.VBox(False, 0)
        hbox.add(vbox4)
        hbox.set_child_packing(vbox4, True, True, 0, gtk.PACK_START)
        
        self.btData = gtk.Entry()
        self.btData.set_max_length(512)
        vbox4.pack_start(self.btData, True, True, 0)
        self.btData.set_text(cfgReader.dvSrvBT_)
        self.btData.connect('changed', self.deviceSrvChangedAction)
 
        self.tcpData = gtk.Entry()
        self.tcpData.set_max_length(512)
        vbox4.pack_start(self.tcpData, True, True, 0)
        self.tcpData.set_text(cfgReader.dvSrvTCP_)
        self.tcpData.connect('changed', self.deviceSrvChangedAction)
        
        self.webData = gtk.Entry()
        self.webData.set_max_length(512)
        vbox4.pack_start(self.webData, True, True, 0)
        self.webData.set_text(cfgReader.dvSrvWEB_)
        self.webData.connect('changed', self.deviceSrvChangedAction)
        
        self.manData = gtk.Entry()
        self.manData.set_max_length(512)
        vbox4.pack_start(self.manData, True, True, 0)
        self.manData.set_text(cfgReader.dvSrvADV_)
        self.manData.connect('changed', self.deviceSrvChangedAction)
        
        self.typeToggled(None)
        
        self.connMan.connect('toggled', self.typeToggled)
        self.connBT.connect('toggled',  self.typeToggled)
        self.connTCP.connect('toggled', self.typeToggled)
        self.connWEB.connect('toggled', self.typeToggled)
 
        ################
        hsep = gtk.HSeparator()
        vbox_server.add(hsep)
        vbox_server.set_child_packing(hsep, 0, 1, 0, gtk.PACK_START)

        ################
        hbox = gtk.HBox(False, 0)
        vbox_server.add(hbox)
        vbox_server.set_child_packing(hbox, 0, 1, 0, gtk.PACK_START)

        self.jLabel = gtk.Label(_('Upload J2ME client from '))
        hbox.pack_start(self.jLabel, False, False, 0)        
        
        self.j2meDir = gtk.Entry()
        hbox.pack_start(self.j2meDir, True, True, 0)

        self.chooseJ2ME = gtk.Button(label=AR_CHOOSE)
        self.chooseJ2ME.connect("clicked", self.chooseJ2MEDir)
        hbox.pack_start(self.chooseJ2ME, False, False, 0)

        ################
        hsep = gtk.HSeparator()
        vbox_server.add(hsep)
        vbox_server.set_child_packing(hsep, 0, 1, 0, gtk.PACK_START)
        
        ################
        hbox = gtk.HBox(False, 0)
        vbox_server.add(hbox)
        vbox_server.set_child_packing(hbox, 0, 1, 0, gtk.PACK_START)
        
        self.checkJ2ME = gtk.CheckButton(_('Check J2ME client updates at start'))
        hbox.pack_start(self.checkJ2ME, True, True, 0)
        self.checkJ2ME.set_active(cfgReader.checkJ2MEUpdate_)

        self.checkJ2MENow = gtk.Button(label=_('Check J2ME client updates'))
        self.checkJ2MENow.connect("clicked", self.checkJ2MEWeb)
        hbox.pack_end(self.checkJ2MENow, False, False, 0)
        
        ################
        hbox = gtk.HBox(False, 0)
        vbox_server.add(hbox)
        vbox_server.set_child_packing(hbox, 0, 1, 0, gtk.PACK_START)

        self.downloadJ2MENow = gtk.Button(label=_('Download J2ME client from Web'))
        self.downloadJ2MENow.connect("clicked", self.uploadJ2MEWeb)
        hbox.pack_end(self.downloadJ2MENow, False, False, 0)
         
        # support PyGTK<2.12
        try:
            self.downloadJ2MENow.set_tooltip_text(_('Files will be saved to $HOME/.anyRemote'))
        except AttributeError:
            pass

        ################
        # AT tab
        ################
        hbox = gtk.HBox(False, 0)
        vbox_at.add(hbox)
        vbox_at.set_child_packing(hbox, False, True, 0, gtk.PACK_START)
        
        label = gtk.Label(_('Use connect string')+'  ')
        hbox.pack_start(label, 0, True, 0)
        
        btAddresses = gtk.ListStore(str)

        treeiter = bt_devices.get_iter_first()
        while treeiter != None:
            v1 = bt_devices.get_value(treeiter, 0)
            v4 = bt_devices.get_value(treeiter, 3)
            
            # use channel 1 as default
            if v4 == "":
                v4 = "1"
            
            channels = v4.split(':')
            for ch in channels:
                if str(ch).isdigit():
                    row = "rfcomm:"+v1+":"+ch
                    if cfgReader.deviceAT_ != row:
                        btAddresses.append([row])
                
            treeiter = bt_devices.iter_next(treeiter)

        self.device_at = gtk.ComboBoxEntry(btAddresses)
        
        if cfgReader.deviceAT_ != "":
            btAddresses.prepend([cfgReader.deviceAT_])
            self.device_at.set_active(0)
            
        hbox.pack_start(self.device_at, True, True, 0)

        hbox = gtk.HBox(False, 0)
        vbox_at.add(hbox)
        vbox_at.set_child_packing(hbox, False, True, 0, gtk.PACK_START)

        self.autoReconn = gtk.CheckButton(_('Auto reconnect'))
        hbox.pack_start(self.autoReconn, True, True, 0)
        self.autoReconn.set_active(cfgReader.autoReconn_)

        ################
        # Bemused tab
        ################
        hbox = gtk.HBox(False, 0)
        vbox_bm.add(hbox)
        vbox_bm.set_child_packing(hbox, False, True, 0, gtk.PACK_START)
        
        label = gtk.Label(_('Use connect string')+'  ')
        hbox.pack_start(label, 0, True, 0)
        
        self.device_bm = gtk.Entry()
        self.device_bm.set_max_length(512)
        hbox.pack_start(self.device_bm, True, True, 0)
        self.device_bm.set_text(cfgReader.deviceBm_)
        self.device_bm.connect('changed', self.deviceBemusedChangedAction)

        ################
        # iViewer tab
        ################
        hbox = gtk.HBox(False, 0)
        vbox_iv.add(hbox)
        vbox_iv.set_child_packing(hbox, False, True, 0, gtk.PACK_START)
        
        label = gtk.Label(_('Use connect string')+'  ')
        hbox.pack_start(label, 0, True, 0)
        
        self.device_iv = gtk.Entry()
        self.device_iv.set_max_length(512)
        hbox.pack_start(self.device_iv, True, True, 0)
        self.device_iv.set_text(cfgReader.deviceIV_)
        self.device_iv.connect('changed', self.deviceIViewerChangedAction)

        ################
        separator = gtk.HSeparator()
        vbox_top.pack_start(separator, False, True, 0)

        hbox = gtk.HBox(False, 0)
        vbox_top.add(hbox)
        vbox_top.set_child_packing(hbox, 0, 1, 0, gtk.PACK_START)
        
        btn = gtk.Button(label=AR_OK)
        addIconToButton(btn,gtk.STOCK_OK)
        btn.connect("clicked", self.okCloseCfg)
        hbox.pack_end(btn, False, False, 0)
 
        btn = gtk.Button(label=AR_CANCEL)
        addIconToButton(btn,gtk.STOCK_CANCEL)
        btn.connect("clicked", self.closeCfg)
        hbox.pack_end(btn, False, False, 0)
        
        for d in cfgReader.cfgDirs:
            if d != '':
                self.cfg_liststore.append([d])
        
        self.j2meDir.set_text(cfgReader.j2meDir_)  
         
        self.config.show_all()
        
        self.showConfItem.set_sensitive(False)
                
    def chooseAutoStart(self,w):
        self.chooseAuto.set_sensitive(False)
        self.autoFile.set_sensitive(False)
        cfgChooser(self)

    def setupFile(self, name):
        self.autoFile.set_text(name)
        self.autoFile.set_sensitive(True)
        self.autoFile.set_position(len(name))
        self.chooseAuto.set_sensitive(True)

    def unlockFile(self):
        self.autoFile.set_sensitive(True)
        self.chooseAuto.set_sensitive(True)

    def addToCfgDirList(self, w):
        self.btnAdd.set_sensitive(False)
        
        dialog = gtk.FileChooserDialog(AR_SEL_DIR,None,gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER,
                         (gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_OPEN,gtk.RESPONSE_OK))
        dialog.set_default_response(gtk.RESPONSE_OK)
        response = dialog.run()
        
        if response == gtk.RESPONSE_OK:
            self.dirsChanged = True
            
            newPath = dialog.get_filename()

            add = True
        
            treeiter = self.cfg_liststore.get_iter_first()
            while treeiter != None:
                value = self.cfg_liststore.get_value(treeiter, 0)
                if value == newPath:
                    add = False
                    break
                treeiter = self.cfg_liststore.iter_next(treeiter)
        
            if add:
                self.cfg_liststore.append([newPath])
            
        dialog.destroy()
        self.btnAdd.set_sensitive(True)

    def deleteFromCfgDirList(self, w):
        (model, titer) = self.cfg_treeview.get_selection().get_selected()
        if titer:
           treeiter = self.cfg_liststore.remove(titer)
        self.dirsChanged = True

    def chooseJ2MEDir(self, w):
        self.chooseJ2ME.set_sensitive(False)
                
        dialog = gtk.FileChooserDialog(AR_SEL_DIR,None,gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER,
                                (gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_OPEN,gtk.RESPONSE_OK))
        dialog.set_default_response(gtk.RESPONSE_OK)
        response = dialog.run()
        
        if response == gtk.RESPONSE_OK:
            self.j2meDir.set_text(dialog.get_filename())
            
        dialog.destroy()
        
        self.chooseJ2ME.set_sensitive(True)

    def closeCfg(self, w):
        self.config.destroy()
        self.showConfItem.set_sensitive(True)

    def okCloseCfg(self, w):
        global cfgReader

        self.setAutoStartup("KDE",   self.autorunKDE.get_active())
        self.setAutoStartup("Gnome", self.autorunGnome.get_active())
        
        cfgReader.showApps_     = self.showApps.get_active()
        cfgReader.showCustom_   = self.showCustom.get_active()
        cfgReader.showExamples_ = self.showExamples.get_active()
        cfgReader.showNonavail_ = self.showNonavail.get_active()
        cfgReader.showAt_       = self.showAt.get_active()
        cfgReader.showSrv_      = self.showSrv.get_active()
        cfgReader.showBm_       = self.showBm.get_active()
        cfgReader.showIView_    = self.showIView.get_active()

        cfgReader.autoReconn_   = self.autoReconn.get_active()
        
        cfgReader.dvSrvBT_  = self.btData.get_text().strip()
        cfgReader.dvSrvTCP_ = self.tcpData.get_text().strip()
        cfgReader.dvSrvWEB_ = self.webData.get_text().strip()
        cfgReader.dvSrvADV_ = self.manData.get_text().strip()

        cfgReader.deviceAT_     = self.device_at.get_active_text().strip()
        cfgReader.deviceBm_     = self.device_bm.get_text().strip()
        cfgReader.deviceIV_     = self.device_iv.get_text().strip()
        
        cfgReader.j2meDir_      = self.j2meDir.get_text().strip()
        cfgReader.checkJ2MEUpdate_ = self.checkJ2ME.get_active()
        
        tm = self.updateTmout.get_text().strip()
        if tm == '':
            tm = '-1'
        if cfgReader.updateTmout_ != int(tm):
            cfgReader.updateTmout_ = int(tm)
            if cfgReader.updateTmout_ < 0:
                cfgReader.updateTmout_ = -1
            stopUpdater()
            startUpdater(cfgReader.updateTmout_)
        
        tm = self.browseTmout.get_text().strip()
        if tm == '':
            tm = '-1'
        if cfgReader.browseTmout_ != int(tm):
            cfgReader.browseTmout_ = int(tm)
            if cfgReader.browseTmout_ <= 0:
                cfgReader.browseTmout_ = -1
            stopBtComm()
            startBtComm(cfgReader.browseTmout_, cfgReader.j2meDir_)

        cfgReader.autoStart_   = self.autoFile.get_text().strip()
        cfgReader.doAutoStart_ = self.autoRun.get_active()

        cfgReader.cfgDirs = []
        
        treeiter     = self.cfg_liststore.get_iter_first()
        while treeiter != None:
            value = self.cfg_liststore.get_value(treeiter, 0)
            cfgReader.cfgDirs.append(value)
            treeiter = self.cfg_liststore.iter_next(treeiter)
               
        proceed = True
        if cfgReader.cfgDirs == []:
            
            dialog = gtk.MessageDialog(None, gtk.DIALOG_MODAL, gtk.MESSAGE_WARNING, gtk.BUTTONS_OK_CANCEL,
                                      _('There is no item in the list !\ngAnyRemote will not be able to manage any software !'))
            ret = dialog.run()
            if ret == gtk.RESPONSE_CANCEL:
                proceed = False
                
            dialog.destroy()

        if proceed:
            cfgReader.saveConfig() 
            self.config.destroy()
        
            self.showConfItem.set_sensitive(True)
        
            if self.dirsChanged == True:
                self.populateCfgFiles()
                self.dirsChanged = False
            
    def dbrowseChangedAction(self, editable):  
        global cfgReader
        cfgReader.browseTmout_ = self.browseTmout.get_text().strip()
        if cfgReader.browseTmout_ == '':
             self.brLabel.set_sensitive(False)
             self.secLabel2.set_sensitive(False)
        else:     
             self.brLabel.set_sensitive((cfgReader.browseTmout_ > 0))
             self.secLabel2.set_sensitive((cfgReader.browseTmout_ > 0))

    def tmoutChangedAction(self, editable):  
        global cfgReader
        cfgReader.updateTmout_ = self.updateTmout.get_text().strip()
        if cfgReader.updateTmout_ == '':
             self.updLabel.set_sensitive(False)
             self.secLabel1.set_sensitive(False)
        else:     
             self.updLabel.set_sensitive((cfgReader.updateTmout_ > 0))
             self.secLabel1.set_sensitive((cfgReader.updateTmout_ > 0))
            
    def deviceSrvChangedAction(self, editable):
        global cfgReader
        cfgReader.dvSrvBT_  = self.btData.get_text().strip()
        cfgReader.dvSrvTCP_ = self.tcpData.get_text().strip()
        cfgReader.dvSrvWEB_ = self.webData.get_text().strip()
        cfgReader.dvSrvADV_ = self.manData.get_text().strip()
   
    def deviceATChangedAction(self, editable):
        global cfgReader
        cfgReader.deviceAT_ = self.device_at.get_text().strip()
    
    def deviceBemusedChangedAction(self, editable):
        global cfgReader
        cfgReader.deviceBm_ = self.device_bm.get_text().strip()
    
    def deviceIViewerChangedAction(self, editable):
        global cfgReader
        cfgReader.deviceIV_ = self.device_iv.get_text().strip()
 
    def typeToggled(self, w):
        global cfgReader
        
        if w == self.connMan:
            cfgReader.dvSrvUseADV_ = self.connMan.get_active()
            if self.connMan.get_active():
                self.connBT.set_active(False)
                self.connTCP.set_active(False)
                self.connWEB.set_active(False)
                cfgReader.dvSrvUseBT_  = False
                cfgReader.dvSrvUseTCP_ = False
                cfgReader.dvSrvUseWEB_ = False
        
                if self.manData.get_text().strip() == '':
                    self.manData.set_text("-log -s bluetooth:19")

        if w == self.connBT:
            cfgReader.dvSrvUseBT_ = self.connBT.get_active()
            if self.connBT.get_active():
                self.connMan.set_active(False)
                cfgReader.dvSrvUseADV_ = False

                if self.btData.get_text().strip() == '':
                    self.btData.set_text("19")

        if w == self.connTCP:
            cfgReader.dvSrvUseTCP_ = self.connTCP.get_active()
            if self.connTCP.get_active():
                self.connMan.set_active(False)
                cfgReader.dvSrvUseADV_ = False

                if self.tcpData.get_text().strip() == '':
                    self.tcpData.set_text("5197")
        
 
        if w == self.connWEB:
            cfgReader.dvSrvUseWEB_ = self.connWEB.get_active()
            if self.connWEB.get_active():
                self.connMan.set_active(False)
                cfgReader.dvSrvUseADV_ = False

                if self.webData.get_text().strip() == '':
                   self.webData.set_text("5080")

        self.btData.set_sensitive(self.connBT.get_active())
        self.tcpData.set_sensitive(self.connTCP.get_active())
        self.webData.set_sensitive(self.connWEB.get_active())
        self.manData.set_sensitive(self.connMan.get_active())

    def autoRunToggled(self, w):
        self.autoFile.set_sensitive(self.autoRun.get_active())
        self.chooseAuto.set_sensitive(self.autoRun.get_active())

    def filterChangedAction(self, w):
        self.dirsChanged = True

    def uploadJ2MEWeb(self,w):
        global debug,jup,cfgReader

        try:
            if jup != None:
               if debug: print 'Uploading already active. Skip request.'
               return
        except NameError:
            pass
            
        jup = JCUploader()
        jup.start()
        
        cfgReader.j2meDir_ = os.environ.get("HOME")+os.sep+'.anyRemote'

    def checkJ2MEWeb(self,w):
        jv = JCVerifier(True)
        jv.start()

    def updateAvail(self):
        ret = yesno(self,_("New version of J2ME client is available. Would You like to download it ?"))
        if ret == gtk.RESPONSE_YES:
            self.uploadJ2MEWeb(self) 
            
    ##################################################################################
    #
    # Status related function
    #
    ##################################################################################

    def setStatustext(self,text):
        self.sBar.pop(self.cid)
        self.sBar.push(self.cid,'  ' + text)

    def setStatusValue(self, val):
        self.statusValue = val
        self.setStatustext(val)
        self.setTrayTooltip(val)

    def setTempStatus(self, val):
        self.setStatustext(val)
        
    def setStatusStopped(self):
        global debug
        if debug: print 'setStatusStopped'

        self.runBtn.set_sensitive(True)
        self.runItem.set_sensitive(True)
        self.stopBtn.set_sensitive(False)
        self.stopItem.set_sensitive(False)

        self.setTrayIcon("OFF")
        self.setStatusValue(AR_STOPPED)

    def setStatusDisconnected(self):
    
        global debug, cfgReader
        if debug: print 'setStatusDisconnected'

        self.runBtn.set_sensitive(False)
        self.runItem.set_sensitive(False)
        self.stopBtn.set_sensitive(True)
        self.stopItem.set_sensitive(True)

        self.setTrayIcon("RUN")
        self.setStatusValue(AR_DISCONN+' '+cfgReader.getConnectStatusString())

    def setStatusConnected(self):
    
        global debug
        if debug: print 'setStatusConnected'
        
        self.setTrayIcon("ON")
        self.setStatusValue(AR_CONNECT)
        
    def translateMsg(self, data):
    
        global debug
        if debug: print 'translateMsg  ' + data

        if data == '':

           return
           
        elif data == 'Exiting':
        
           self.setStatusStopped()
           return

        elif data == 'Connected':

           self.setStatusConnected()
           return

        elif data == 'Disconnected':

           self.setStatusDisconnected()
           return
        
        if data == '(Init)':

           msg = 'anyRemote initialized'

        else:
        
           # Just key press 
           self.setTrayIcon("FLASH")
           self.blinkTimer = gobject.timeout_add(200, self.resetTrayIcon)           
           
           if debug:
               msg = data
           else:
               return
        
        self.setStatustext(msg)
        
    def resetTrayIcon(self):
    
        self.setTrayIcon("ON")
        return False
                   
    def checkInputQueue(self):
        global guiQueue
        
        while True:
            try:
                data = guiQueue.get(False)

                if data[0] == 'MSG_INF':
                    message(data[1],gtk.MESSAGE_INFO)
                elif data[0] == 'MSG_ERR':
                    message(data[1],gtk.MESSAGE_INFO)
                elif data[0] == 'UPDATE_AVAIL':
                    self.updateAvail()
                elif data[0] == 'PBAR_START':
                    self.startProgressBar(data[1],data[2])
                elif data[0] == 'PBAR_STOP':
                    self.stopProgressBar()
                elif data[0] == 'PBAR_WRITE':
                    self.writeProgressBar(data[1])
                elif data[0] == 'SET_STATUS':
                    if data[1] == 'S':
                        self.setStatusStopped()
                    elif data[1] == 'D':
                        self.setStatusDisconnected()
                    elif data[1] == 'C':
                        self.setStatusConnected()
                elif data[0] == AR_CODE_LOADED:
                    cnt = int(data[1])
                    if cnt >= 0:
                        self.setTempStatus(str(data[1]))
                    else:
                        self.setStatusValue(self.statusValue) 
                        self.selectLastInList()
                        restartUpdater()

                elif data[0] == 'UPDATE_LIST':
                    treeiter = liststore.get_iter_from_string(data[1])
                    liststore.set_value(treeiter, 5, data[2])    
                elif data[0] == 'GET_DATA':
                    self.translateMsg(data[1])
             
            except Queue.Empty:
                break
            
        return True

    def startProgressBar(self,m,t):
        global pbar
        pbar = PBar(m,t)
        
    def stopProgressBar(self):
        global pbar
        try:
            pbar.stop()
        except AttributeError, NameError:
            pass

    def writeProgressBar(self,m):
        global pbar
        try:
            pbar.set_text(m)
        except AttributeError, NameError:
            pass
        
    ##################################################################################
    #
    # Tray & AppIndicator support
    #
    ##################################################################################

    def hasTray(self):
        return (self.tray != None or self.appInd != None)

    def initTray(self,openW):
        
        self.tray = None
        
        # used as window icon
        self.pixbufOn = findIcon('ganyremote_small.png')

        # Try appIndicator first
        try:
            
            self.appInd = appindicator.Indicator("gAnyRemote", "indicator-messages", appindicator.CATEGORY_APPLICATION_STATUS)

            self.appInd.set_status (appindicator.STATUS_ACTIVE)
            self.appIndMenu = gtk.Menu()
            
            item = gtk.ImageMenuItem(gtk.STOCK_ABOUT)
            item.connect('activate', self.aboutAction)
            item.show()
            self.appIndMenu.append(item)

            item = gtk.ImageMenuItem(gtk.STOCK_EXECUTE)
            item.connect('activate', self.runPressed)
            self.appIndMenu.append(item)

            item = gtk.ImageMenuItem(gtk.STOCK_STOP)
            item.connect('activate', self.stopPressed)
            self.appIndMenu.append(item)

            item = gtk.MenuItem('Minimize/Restore')
            item.connect('activate', self.showWindowAction)
            self.appIndMenu.append(item)
         
            item = gtk.ImageMenuItem(gtk.STOCK_QUIT)
            item.connect('activate', self.quitAction)
            self.appIndMenu.append(item)
            
            self.appIndMenu.show_all()
            
            self.appInd.set_menu(self.appIndMenu)
            
            # cache tray icons
            self.iconFileOn    = findTrayIconFile('ganyremote_small.png')
            self.iconFileOff   = findTrayIconFile('ganyremote_off.png')
            self.iconFileFlash = findTrayIconFile('ganyremote_flash.png')
            self.iconFileRun   = findTrayIconFile('ganyremote_light.png')
       
        except NameError:
            self.appInd = None
            
            # if no appIndicator try to use tray
            
            try:
                self.tray = gtk.StatusIcon()
                self.tray.connect('popup-menu', self.rightClickAction)
                self.tray.connect('activate',   self.trayPressAction)
                
                # cache tray icons
                self.pixbufOff   = findIcon('ganyremote_off.png')
                self.pixbufFlash = findIcon('ganyremote_flash.png')
                self.pixbufRun   = findIcon('ganyremote_light.png')
                
            except AttributeError:
                self.tray = None
                self.notInTray = True
            
            
        if self.hasTray():
            self.connect("delete_event", self.hideWindow2)
        else:
            self.connect("destroy", self.quitAction)

    def setTrayIcon(self, icon):
        
        if self.appInd:
        
            if icon == "ON":
                self.appInd.set_icon(self.iconFileOn)
            elif icon == "OFF":
                self.appInd.set_icon(self.iconFileOff)
            elif icon == "RUN":
                self.appInd.set_icon(self.iconFileRun)
            elif icon == "FLASH":
                self.appInd.set_icon(self.iconFileFlash)
            else:
                return
       
        elif self.tray: 
        
            pixbuf = None

            if icon == "ON":
                pixbuf = self.pixbufOn
            elif icon == "OFF":
                pixbuf = self.pixbufOff
            elif icon == "RUN":
                pixbuf = self.pixbufRun
            elif icon == "FLASH":
                pixbuf = self.pixbufFlash
            else:
                return

            self.tray.set_from_pixbuf(pixbuf)

    # RMB on tray icon
    def rightClickAction(self, icon, event_button, event_time):
        menu = gtk.Menu()

        item = gtk.ImageMenuItem(gtk.STOCK_ABOUT)
        item.connect('activate', self.aboutAction)
        menu.append(item)
        
        item = gtk.ImageMenuItem(gtk.STOCK_EXECUTE)
        item.connect('activate', self.runPressed)
        menu.append(item)

        item = gtk.ImageMenuItem(gtk.STOCK_STOP)
        item.connect('activate', self.stopPressed)
        menu.append(item)
        
        title = _('Restore')
        if self.get_property('visible'):
            title = _('Minimize')
        self.mainWinItem = gtk.MenuItem(title)
        self.mainWinItem.connect('activate', self.showWindowAction)
        menu.append(self.mainWinItem)

        item = gtk.ImageMenuItem(gtk.STOCK_QUIT)
        item.connect('activate', self.quitAction)
        menu.append(item)
        menu.show_all()

        menu.popup(None, None,
            gtk.status_icon_position_menu, event_button,
            event_time, icon)

    def setTrayTooltip(self, ttip):
       if self.tray: 
           self.tray.set_tooltip(ttip)

    ##################################################################################
    #
    # Button and menu handlers
    #
    ##################################################################################

    def aboutAction(self, action):
    
        try:
            dialog = gtk.AboutDialog()
            dialog.set_name("gAnyRemote v6.3.2")
            dialog.set_copyright('Copyright 2007-2014 Mikhail Fedotov')
            dialog.set_website("http://anyremote.sf.net/")
            dialog.connect ("response", lambda d, r: d.destroy())
            dialog.show()
        except AttributeError:
                infoMessage("gAnyRemote\nCopyright 2007-2014 Mikhail Fedotov\nhttp://anyremote.sf.net/")


    # open web browser on docs page if found ?
    def helpAction(self, action):
    
        app = ''
        apps = ['xdg-open', 'firefox', 'konqueror', 'chromium']
        for test in apps:
            isInst = isInstalled(test) 
            if isInst == 'OK':
                app = test
        if app == '':
            errorMessage(_('Can not find browser to show help !'))
            return

        docpath = ''
        docDirs = ['/usr/share/doc/anyremote*/*html', 
                   '/usr/share/anyremote*/*html', 
                   '/usr/share/doc/anyremote-doc', 
                   '/usr/local/share/doc/anyremote*/*html', 
                   '/usr/local/share/anyremote*/*html']

        for docDir in docDirs:
            dirv = glob.glob(docDir)
            if len(dirv) > 0 and os.path.isdir(dirv[0]):
                docpath = dirv[0]
                break
        if docpath == '':
            errorMessage(_('Can not find documentation !'))
            return
        
        cmd = app + ' ' + docpath + os.sep + 'g-shots.html &'
        if debug: print cmd
        os.system(cmd)
                    
    def trayPressAction(self, *args):
        if self.get_property('visible'):
            self.hide()
        else:
            self.show_all()

    def showWindowAction(self, *args):
        self.trayPressAction(*args)

    def quitAction(self, *args):
        try:
            gobject.source_remove(self.inQueueTimer)
        except AttributeError, NameError:
            print 'Exception: gobject.source_remove(gui.inQueueTimer)'
 
        self.quit()

    def resizeEvent(self, *args):
        (w,h)=self.get_size()
        try:
            self.detailsRenderer.set_property('wrap-width', w-50)
        except TypeError, AttributeError:
            pass
        
    def runPressed(self, widget):

        # to store last used cfg.file
        entry_text = self.entry.get_text()
        
        self.saveCfg()
        
        self.setStatusDisconnected()

        startAnyRemote(entry_text)        

    def stopPressed(self, widget):
        global debug
        
        if debug: print 'Stop anyRemote'

        self.saveCfg()
        
        # To avoid socket.error: (98, 'Address already in use') 
        # it needs to close client socket first
        killAnyRemote()
                        
        self.setStatusStopped()

    def rescanPressed(self, widget):
        self.populateCfgFiles()

    def openEditor(self, widget):
        global cfgReader
        if cfgReader.lastCfgFile_:
            e = cfgEditor(cfgReader.lastCfgFile_)
        
    def execCmd(self, w):
        global cmdToSend
        print 'Add to queue ' + self.cmd.get_text()
        cmdToSend = self.cmd.get_text() 
        
    def saveCfg(self):
        global cfgReader
        cfgReader.saveConfig()
       
    ##################################################################################
    #
    # Wizard window
    #
    ##################################################################################
    
    def showWizard(self, cfgdirs, jclient):
        
        if cfgdirs == 0:
           dialog = gtk.MessageDialog(None,
                        gtk.DIALOG_MODAL, gtk.MESSAGE_INFO, gtk.BUTTONS_OK,
                        _('This is the first time gAnyRemote runs.\nPlease specify directories with anyRemote configuration files.'))

           dialog.run()
           dialog.destroy()

           self.showConfDialog()
        
        if jclient == '': 
            ret  = yesno(self,_('Would You like to download J2ME client from the web ?'))
            if ret == gtk.RESPONSE_YES:
                self.uploadJ2MEWeb(self)
        
   
    ##################################################################################
    #
    # Main window creation
    #
    ##################################################################################

    def createMenus(self, vbox):
        global usepybluez
        
        self.menubar = gtk.MenuBar()
        vbox.pack_start(self.menubar, expand=False)

        topmenuitem = gtk.MenuItem(AR_FILE)
        self.menubar.add(topmenuitem)
        
        menu = gtk.Menu()
        topmenuitem.set_submenu(menu)

        try:
            stock_edit = gtk.STOCK_EDIT
            menuitem = gtk.ImageMenuItem(stock_edit)
        except AttributeError:
            menuitem = iconMenuItem(_('Edit'), gtk.STOCK_JUSTIFY_LEFT)

        menu.add(menuitem)
        menuitem.connect('activate', self.openEditor)
        
        self.runItem    = addMenuItem(menu, _('Start'), gtk.STOCK_EXECUTE, self.runPressed)
        self.stopItem   = addMenuItem(menu, '',         gtk.STOCK_STOP,    self.stopPressed)
        self.updateItem = addMenuItem(menu, '',         gtk.STOCK_REFRESH, self.rescanPressed)

        if self.hasTray():
            addMenuItem(menu, _('Close Window'), gtk.STOCK_CLOSE, self.hideWindow)
        
        addMenuItem(menu, '', gtk.STOCK_QUIT, self.quitAction)

        topmenuitem = gtk.MenuItem(_('Setup'))
        self.menubar.add(topmenuitem)
        
        menu = gtk.Menu()
        topmenuitem.set_submenu(menu)

        self.dbrowserItem = addMenuItem(menu, AR_DEV_BROWSER, gtk.STOCK_FIND, self.showBrowser)
        if not usepybluez:
            self.dbrowserItem.set_sensitive(False)
        self.dbrowserItem.show()
       
        self.showConfItem = addMenuItem(menu, '',   gtk.STOCK_PREFERENCES, self.showConfAction)
        
        addMenuItem(menu, _('Check Configuration'), gtk.STOCK_PROPERTIES,  self.showChkCfg)
        addMenuItem(menu, '',                       gtk.STOCK_SAVE,        self.saveConfigAction)
        
        topmenuitem = gtk.MenuItem(_('Help'))
        self.menubar.add(topmenuitem)
        
        menu = gtk.Menu()
        topmenuitem.set_submenu(menu)

        try:
            stock_about = gtk.STOCK_ABOUT
            menuitem = gtk.ImageMenuItem(stock_about)
        except AttributeError:
            menuitem = iconMenuItem(_('About'),gtk.STOCK_DIALOG_INFO)
            
        menu.add(menuitem)
        menuitem.connect('activate', self.aboutAction)

        addMenuItem(menu, '', gtk.STOCK_HELP, self.helpAction)

    def commandRun(self, w, event):
        keyname = gtk.gdk.keyval_name(event.keyval)
        if keyname == 'KP_Enter' or keyname == 'Return':
            self.execCmd(self.cmd)
            return True
        return False

    def rowActivateAction(self, treeview, path, view_column):
        global cfgReader
        treeiter = liststore.get_iter(path)

        cfgReader.lastCfgFile_ = liststore.get_value(treeiter, 4)

        self.entry.set_text(cfgReader.lastCfgFile_)
        self.runPressed(self.runBtn)

    def rowSelectAction(self, treeview):
        global cfgReader
        selection = treeview.get_selection()
        (model, treeiter) = selection.get_selected()
        cfgReader.lastCfgFile_ = liststore.get_value(treeiter, 4)
        self.entry.set_text(cfgReader.lastCfgFile_)
        
        desc = liststore.get_value(treeiter, 8)
        self.detailsStore.set_value(self.detailsData, 0, desc.replace('\\n','\n'))

    ##################################################################################
    #
    # 
    #
    ##################################################################################

    def openFDialog(self, w, entry):
        self.fdialog = gtk.FileChooserDialog(_('File selection'),None,gtk.FILE_CHOOSER_ACTION_OPEN,
                                (gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_OPEN,gtk.RESPONSE_OK))
        self.fdialog.set_filename(entry.get_text())
        self.fdialog.set_default_response(gtk.RESPONSE_OK)
        response = self.fdialog.run()
        
        if response == gtk.RESPONSE_OK:
            self.entry.set_text(self.fdialog.get_filename())
        self.fdialog.destroy()
 
    def hideWindow2(self,w,p):
        self.hideWindow(w)
        return True
        
    def hideWindow(self,w):
        self.hide()
                    
    def quit(self):
        print 'Exiting...'
        
        stopBtComm()
        stopJCUploader()
        stopPBar()
        stopUpdater()
        stopFrontend()
        self.saveCfg()
        gtk.main_quit()

##################################################################################
#
# Utilities functions
#
##################################################################################

def addHbox(vbox):
    hbox = gtk.HBox(False, 0)
    vbox.add(hbox)
    vbox.set_child_packing(hbox, False, True, 0, gtk.PACK_START)
    return hbox
def getHttp(hname,fname,tmp):
    global debug

    try:
        conn = httplib.HTTPConnection(hname,80,timeout=10)
    # old pythons (<2.6)
    except TypeError:
        conn = httplib.HTTPConnection(hname)

    try:
        conn.request("GET", fname)
    except Exception: 
        errorMessage(_('Can not establish the connection !'))
        return False
    
    r = conn.getresponse()
    
    if debug: print fname, r.status, r.reason,r.getheader('content-length')
    
    ret = True
    
    if r.status == httplib.OK:
        if debug: print 'download',fname
        
        try:
            data = r.read()
        except Exception:
            errorMessage(_('Download failed !'))
            return False

        f=open(os.environ.get("HOME")+os.sep+'.anyRemote'+fname+tmp, 'w')
        if f:
            f.write(data)
            f.close()
    else:
        if tmp == "":
            errorMessage(_('Can not download ')+hname+fname)
            ret = False
            
        
    conn.close()
    
    return ret
    
def uploadJ2MEWebGui(fname, strip=False):
 
    writePBar(_('Downloading')+' '+fname)
    
    if not getHttp("anyremote.sourceforge.net",os.sep+fname,""):
        stopPBar()
        return False
    
    if strip:
        f1 = os.environ.get("HOME")+os.sep+'.anyRemote'+os.sep+fname
        os.system('rm -f '+f1+'.tmp; cat '+f1+'|sed \'s/MIDlet-Jar-URL: http:\/\/anyremote.sourceforge.net\//MIDlet-Jar-URL: /\' > '+f1+'.tmp;mv '+f1+'.tmp '+f1);
    
    return True

def getJ2MEClientVersion(fname):
    global debug
    if debug: print 'Check version of J2ME Client from file',fname
    return getResult('cat '+fname+'|grep MIDlet-Version|tr -d \" \"|cut -f 2 -d \":\"','main')

def checkJ2MEClientUpdate():
    global debug
    
    if not getHttp("anyremote.sourceforge.net",os.sep+"anyRemote-16.jad",".check"):
        return ""
        
    newver = getJ2MEClientVersion(os.environ.get("HOME")+os.sep+'.anyRemote'+os.sep+'anyRemote-16.jad.check')
    oldver = getJ2MEClientVersion(getJ2MEPath()+os.sep+'anyRemote-16.jad')
    
    if debug: print 'compare new=',newver,' and old=',oldver
    
    nvers = newver.split('.')
    overs = oldver.split('.')
    
    l = len(nvers)
    if len(overs) > l: 
        l = len(overs)
    
    foundnew = False
    for i in range(l):
        
        if len(overs) < i:
            oi = 0
        else:
            oi = overs[i]
            
        if len(nvers) < i:
            ni = 0
        else:
            ni = nvers[i]
        
        #if debug: print '(',i,') compare new=',ni,' and old=',oi
        if ni > oi:
            foundnew = True
            break

    if (foundnew):
        return  newver
        
    return ""

def addMenuItem(menu, title, stock, callback):
    if title == '':
        menuitem = gtk.ImageMenuItem(stock)
    else:
        menuitem = iconMenuItem(title, stock)
    menu.add(menuitem)
    menuitem.connect('activate', callback)
    return menuitem

def iconMenuItem(title, stock):
    mItem = gtk.ImageMenuItem(title)
    im = gtk.Image()
    try:
        im.set_from_stock(stock, gtk.ICON_SIZE_MENU)
        mItem.set_image(im)
    except AttributeError:
        pass
    return mItem

def addIconToButton(button, stock):
 
    # on Mandriva 2008.1 it is disabled by default
    button.get_settings().set_long_property('gtk-button-images',1,'');
    try:
        im = gtk.Image()
        im.set_from_stock(stock, gtk.ICON_SIZE_BUTTON)
        button.set_image(im)
    except AttributeError:
        pass

def yesno(p,m):
    dialog = gtk.MessageDialog(p,gtk.DIALOG_MODAL,gtk.MESSAGE_INFO,gtk.BUTTONS_YES_NO, m)
    # force it to show to avoid some warnings
    dialog.show()
    dialog.set_keep_above(True)
    rid = dialog.run()
    dialog.destroy()
    return rid

def message(m,t):
    stopPBar()
    flag = 0
    if t == gtk.MESSAGE_ERROR:
        flag = gtk.DIALOG_MODAL
    dialog = gtk.MessageDialog(None,flag,t,gtk.BUTTONS_OK, m)
    dialog.show() 
    dialog.set_keep_above(True)
    dialog.run()
    dialog.destroy()

def putToDevWQueue(data):
    global ddQueue
    try:
        ddQueue.put(data)
    except Queue.Full:
        pass

def codeMessage(code):
    putToMainQueue([code])

def codeMessage2(code,val):
    putToMainQueue([code,val])

def statusMessage(val):
    putToMainQueue(['SET_STATUS',val])
    
def putToMainQueue(data):
    global guiQueue
    try:
        guiQueue.put(data)
    except Queue.Full:
        pass

def errorMessage(m):
    putToMainQueue(['MSG_ERR',m])

def infoMessage(m):
    putToMainQueue(['MSG_INF',m])

def getJ2MEPath():
    path = ''
    if os.path.exists(os.environ.get("HOME") + os.sep + '.anyRemote' + os.sep + 'anyRemote-16.jad'):
        path = os.environ.get("HOME") + os.sep + '.anyRemote'
    return path

def isInstalled(app):
    dirs = os.getenv('PATH').split(':')
    for d in dirs:
        if os.path.exists(d+os.sep+app):
            return 'OK'
    return 'NOK'

def reqVersion(cmd):
    res = getResult(cmd,'main')
    if res == 'OK':
         return 'OK'
    return 'NOK'
        
def getResult(cmd, suffix):
        
    toFile = os.environ.get("HOME") + os.sep + '.anyRemote' + os.sep + 'ganyremote-' + suffix + '.tmp'
    
    #if debug: print 'getResult: '+cmd + '> ' + toFile
    os.system(cmd + '> ' + toFile)
    line = getLineTmpFile(toFile)
    return line.replace('\n','')

def getLineTmpFile(toFile):
    fd = open(toFile,'r')
    ln = ''
    if fd:
        ln=fd.readline()
        fd.close()
    return ln
    
def clearAppsList():   
    global gui, liststore

    gtk.gdk.threads_enter()
    gui.treeview.set_model(None);
    liststore.clear()
    gtk.gdk.threads_leave()

def addAppToList(aName, aIcon, app, aRun, isRun, cfgFile, status, aMode, aType, aDesc):
    global liststore
    
    if aIcon == '':
        aIcon = 'fileopen.png'
    
    pbuf = findIcon(aIcon)
                 
    gtk.gdk.threads_enter()
    for oneMode in aMode: 
        item = liststore.append([aName, pbuf, app, aRun, cfgFile, status, _(oneMode), _(aType), aDesc])
    gtk.gdk.threads_leave()

    
#####################################################################################    

def addDevice(v1, v2, v3, v4, v5):
    global bt_devices
    bt_devices.append([v1,v2,v3,v4,v5,''])

def saveDevices():
    global bt_devices

    # anyRemote related part
    cfg = os.environ.get("HOME")+os.sep+'.anyRemote'
    if os.path.exists(cfg):
        pass
    else:
        os.mkdir(cfg)

    f=open(cfg + os.sep + AR_FILE_DEVICES, 'w')
    if f:
        treeiter     = bt_devices.get_iter_first()
        while treeiter != None:
            v0 = bt_devices.get_value(treeiter, 0)
            v1 = bt_devices.get_value(treeiter, 1)
            v2 = bt_devices.get_value(treeiter, 2)
            v3 = bt_devices.get_value(treeiter, 3)
            v4 = bt_devices.get_value(treeiter, 4)
            
            f.write('Device='+v0+','+v1+','+v2+','+v3+','+v4+'\n')

            treeiter = bt_devices.iter_next(treeiter)
        f.close()

#####################################################################################    

def startUpdater(tmout):
    global statusUpdater
    if statusUpdater == None and tmout != -1:
        statusUpdater = StatusUpdater(tmout)
        statusUpdater.start()

def stopUpdater():
    global debug, statusUpdater
    try:
        statusUpdater.stop()
        statusUpdater.join(2)
    except AttributeError, NameError:
        if debug: print 'Exception: statusUpdater.stop()'
        pass
    statusUpdater = None

def restartUpdater():
    global cfgReader
    stopUpdater()
    startUpdater(cfgReader.updateTmout_)
    
#####################################################################################    

def killAnyRemote():
    os.system('killall -2 anyremote 2> /dev/null')


def startAnyRemote(cfg_file):
    global debug, cfgReader
    
    if debug: print 'startAnyRemote',cfg_file
    
    killAnyRemote()
    
    time.sleep(0.5)

    mode = 'Server'
    if cfgReader.showAt_:
        mode = 'AT'
    if cfgReader.showBm_:
        mode = 'Bemused'
    if cfgReader.showIView_:
        mode = 'iViewer'

    log = ''
    if debug:
        log = ' -log'
   
    dev = ''
    rconn = ''
    
    if mode == 'Server':
         connStr = cfgReader.getConnectString()
         if connStr != '':
             dev = ' -s '+connStr
   
    elif mode == 'AT':
        if cfgReader.deviceAT_ != '':
            dev = ' -s '+cfgReader.deviceAT_
    
        if cfgReader.autoReconn_ != '':
            rconn = ' -a '
        
    elif mode == 'Bemused':
        if cfgReader.deviceBm_ != '':
            dev = ' -s '+cfgReader.deviceBm_
    
    elif mode == 'iViewer':
        
        if cfgReader.deviceIV_ != '':
            dev = ' -s '+cfgReader.deviceIV_
    
    else:
         if cfgReader.autoReconn_ != '':
            rcomm = ' -a '
                
    to_path = os.environ.get("HOME") + os.sep + '.anyRemote' + os.sep

    cmd = 'anyremote -fe ' + port + log + ' -f ' + cfg_file + dev + rconn + ' > '+ to_path + 'anyremote.stdout &'
    if debug: print cmd
    os.system(cmd)

def timerBrowseDevices():
    browseDevices('F')
    
def browseDevices(force):
    global debug, cmd_array
    
    if force == 'F' and ['scan','F'] in cmd_array:
        if debug: print 'Skip device scan'
    else:
        gtk.gdk.threads_enter()
        queueBT('scan',force)
        gtk.gdk.threads_leave()
    
    return True
    
def startBtComm(tmout, jDir):
    global bt, gui, usepybluez
    if usepybluez == True and bt == None: 
        bt = BtComm(jDir)
        bt.start()
        
        if tmout != '' and tmout > 0: 
            gui.timer = gobject.timeout_add (int(1000*tmout), timerBrowseDevices)

def stopBtComm():
    global debug, bt, gui
    
    try:
        gobject.source_remove(gui.timer)
    except AttributeError, NameError:
        if debug: print 'Exception: BtComm gobject.source_remove(gui.timer)'
        pass
        
    try:
        bt.stop()
        bt.join(2)
    except AttributeError, NameError:
        if debug: print 'Exception: bt.stop()'
        pass
    bt = None

def startFrontend():
    global frontEnd

    frontEnd = FrontEnd()
    frontEnd.start()

def stopFrontend():
    global frontEnd, debug

    # To avoid socket.error: (98, 'Address already in use') 
    # it needs to close client socket first
    
    killAnyRemote()

    time.sleep(0.5)

    try:
        frontEnd.stop()
    except AttributeError, NameError:
        if debug: print 'Exception: frontEnd.stop()'
        pass
    frontEnd = None

def showBrowserWin():
    global browserWin, debug
    try:
        if debug: print 'browserWin',browserWin.isShown
        if browserWin.isShown:
            return
    except AttributeError, NameError:
        pass
    browserWin = DeviceBrowser()

def showChkCfgWin(jDir):
    global chkCfgWin, debug
    try:
        if debug: print 'chkCfgWin',chkCfgWin.isShown
        if chkCfgWin.isShown:
            return
    except AttributeError, NameError:
        pass
    chkCfgWin = CfgChecker(jDir)

def showDetailsWin(addr,v2,v3,channels,cfgFile,isNew):
    global dwin, cfgReader 
    
    try:
        if dwin.isShown: 
            return
    except AttributeError, NameError:
        pass
    dwin = DeviceDetail(addr, v2, v3, channels, cfgFile, isNew, cfgReader.j2meDir_)

def getAvailableSet():

    global bt_devices

    gtk.gdk.threads_enter()
    treeiter = bt_devices.get_iter_first()
    gtk.gdk.threads_leave()

    s = []
    while treeiter != None:
        gtk.gdk.threads_enter()
        addr = bt_devices.get_value(treeiter, 0)
        st   = bt_devices.get_value(treeiter, 5)
        gtk.gdk.threads_leave()
            
        if st == AR_AVAIL:
            
            gtk.gdk.threads_enter()
            treeiter = bt_devices.iter_next(treeiter)
            gtk.gdk.threads_leave()
    
    return s

def getDevSet():

    global bt_devices

    gtk.gdk.threads_enter()
    treeiter = bt_devices.get_iter_first()
    gtk.gdk.threads_leave()

    s = []
    while treeiter != None:
        gtk.gdk.threads_enter()
        addr = bt_devices.get_value(treeiter, 0)
        s.append(addr)
        treeiter = bt_devices.iter_next(treeiter)
        gtk.gdk.threads_leave()
    
    return s

def queueBT(tag,address):
    global debug

    if debug: print 'queueBT',cmd_array
    i = len(cmd_array)-1
    if i > 0 and cmd_array[i] == ['scan','']:
        cmd_array.insert(i,[tag,address])
    else:
        cmd_array.append([tag,address]) 
   
#####################################################################################    

def findIcon(name):
    global icon_theme, debug
    
    iName = name.split('.',1)
    
    try:
        a = icon_theme
    except NameError:    
        icon_theme = gtk.icon_theme_get_default()
        icon_theme.append_search_path('/opt/kde3/share/icons') 
        icon_theme.append_search_path('/opt/gnome/share/pixmaps') 
        icon_theme.append_search_path('/opt/gnome/share/icons') 
        if debug:
            icon_theme.append_search_path('./data') 
        
        if debug:
            print 'findIcon path',icon_theme.get_search_path()
                
    try:
        pixbuf = icon_theme.load_icon(iName[0], 16, 0)
    except gobject.GError, exc:
        try:
           if debug: print 'Can not find',iName,'Use default.'
               
           pixbuf = icon_theme.load_icon("fileopen", 16, 0)
        except gobject.GError, exc:
           # Try it hard
           if debug: print 'Can not find default icon.'
           icon_file = getResult('find /usr/share/icons /usr/share/pixmaps /usr/share/app-install/icons/ /usr/local/share/pixmaps /opt/kde3/share/icons /opt/gnome/share/pixmaps /opt/gnome/share/icons . -name fileopen.png 2>/dev/null','main')
           
           if icon_file != '':
              icon_theme.append_search_path(os.path.dirname(icon_file))
              try:
                  pixbuf = icon_theme.load_icon(iName[0], 16, 0)
              except gobject.GError, exc:
                  pixbuf = None
           else:
               pixbuf = None
    
    return pixbuf

def findTrayIconFile(name):

    return getResult('find /usr/share/pixmaps ./data /usr/share/icons /usr/share/app-install/icons/ /usr/local/share/pixmaps /opt/kde3/share/icons /opt/gnome/share/pixmaps /opt/gnome/share/icons . -name '+name+' 2>/dev/null','main')

def btVerify():
    hcid = getResult('echo \'A=`ps -ef|grep hcid|grep -v grep|grep -v defunct`; if [ "x$A" == "x" ]; then echo NOK; else echo OK; fi\' | bash -f -s','main')
    if debug: print 'btVerify1',hcid
    if hcid == 'NOK':
        hcid = getResult('echo \'A=`ps -ef|grep bluetoothd|grep -v grep|grep -v defunct`; if [ "x$A" == "x" ]; then echo NOK; else echo OK; fi\' | bash -f -s','main')
        if debug: print 'btVerify2',hcid
    return hcid

def initVerify():

    tool = isInstalled('anyremote')
    if tool == 'NOK':
        errorMessage(_('anyRemote not found !\nPlease install it or correct $PATH'))

    tool = isInstalled('sdptool')
    if tool == 'NOK':
        errorMessage(_('sdptool not found !\nPlease install bluez-util'))

def usage():
    print 'ganyremote [-h|--help] [-p|--port <port>] [-d|--debug] [-t|--tray] [-e] [-n|--npybluez]'
    
##################################################################################
#
# Main function
#
##################################################################################

def main():

    global gui, cfgReader, debug, bt_devices, guiMode, guiQueue, ddQueue, port, cmdToSend, icons, runUpdater, liststore, bt_devices, bt, pbar, cmd_array, dwin, browserWin, chkCfgWin, statusUpdater, frontEnd, usepybluez
    
    try:
        opts, args = getopt.getopt(sys.argv[1:], "dnehotp:", ["debug", "expert", "help", "open", "tray", "npybluez", "port="])
    except getopt.GetoptError:
        usage()
        sys.exit(2)
        
    browserWin = None
    chkCfgWin  = None
    bt         = None
    cmd_array  = []
    cmdToSend  = ''
    debug      = False
    dwin       = None
    guiMode    = 'simple'
    frontEnd   = None
    icons      = dict()
    openWin    = True
    pbar       = None
    port       = '5050'
    runUpdater = False
    statusUpdater = None
    usepybluez = True
    bt_devices = gtk.ListStore(str,str,str,str,str,str)
    
    for o, a in opts:
        if o in ("-d", "--debug"):
            debug   = True
            guiMode = 'expert'
        if o in ("-e", "--expert"):
            guiMode = 'expert'
        if o in ("-h", "--help"):
            usage()
            sys.exit()
        if o in ("-p", "--port"):
            port = a
        if o in ("-t", "--tray"):
            openWin = False
        if o in ("-n", "--npybluez"):
            usepybluez = False

    if pybluez == False and usepybluez == True:
        print _('Install PyBluez first !\nOr run with --npybluez option')
        return

    cfg = os.environ.get("HOME")+os.sep+'.anyRemote'
    if not os.path.isdir(cfg):
        os.mkdir(cfg)
    
    cfgSet = False
    
    cfgReader = ConfigReader()
    cfgReader.setDefaultConfig()
    if os.path.exists(cfg+os.sep+'anyremote-fe.conf'):
        cfgReader.readConfig()
        cfgSet = True
    else: 
        if os.path.exists('/usr/share/anyremote/cfg-data'):
            cfgSet = True
            cfgReader.cfgDirs.append('/usr/share/anyremote/cfg-data')
        elif os.path.exists('/usr/local/share/anyremote/cfg-data'):
            cfgSet = True
            cfgReader.cfgDirs.append('/usr/local/share/anyremote/cfg-data/')
        # quick fix for ubuntu
        elif os.path.exists('/etc/anyremote/cfg-data'):
            cfgSet = 1
            cfgReader.cfgDirs.append('/etc/anyremote/cfg-data')
            
        cfgReader.j2meDir_ = getJ2MEPath()
        
        if cfgSet == 1:
           cfgReader.setAutoStartFile()

    liststore  = gtk.ListStore(str, gtk.gdk.Pixbuf, str, str, str, str, str, str, str)

    gobject.threads_init()
    
    guiQueue = Queue.Queue(0)
    ddQueue  = Queue.Queue(0)
    
    gui = gAnyRemote(openWin, cfgSet)
    gui.populateCfgFiles()
    
    if debug: 
        print 'Use translation from ',local_path
        print 'Starting backgroung threads'
        
    startUpdater(cfgReader.updateTmout_)
    startBtComm(cfgReader.browseTmout_, cfgReader.j2meDir_)
    startFrontend()
    
    if cfgReader.checkJ2MEUpdate_:
        if debug: print 'Check J2ME client updates at web'
        jv = JCVerifier(False)
        jv.start()

    gtk.main()
    
    return 0

if __name__ == "__main__":
    main()