This file is indexed.

/usr/share/system-config-printer/newprinter.py is in system-config-printer-common 1.5.11-1ubuntu2.

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

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
#!/usr/bin/python3

## system-config-printer

## Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015 Red Hat, Inc.
## Authors:
##  Tim Waugh <twaugh@redhat.com>
##  Florian Festi <ffesti@redhat.com>

## 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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

# config is generated from config.py.in by configure
import config

import authconn
import cupshelpers
from OpenPrintingRequest import OpenPrintingRequest

import errno
import sys, os, tempfile, time, traceback, re, http.client
import locale
import string
import subprocess
from timedops import *
import dbus
from gi.repository import Gdk
from gi.repository import Gtk
import requests
import functools

import cups

try:
    import pysmb
    PYSMB_AVAILABLE=True
except:
    PYSMB_AVAILABLE=False

import options
from gi.repository import GObject
from gi.repository import GLib
from gui import GtkGUI
from optionwidgets import OptionWidget
from debug import *
import probe_printer
import urllib.request, urllib.parse
from smburi import SMBURI
from errordialogs import *
from PhysicalDevice import PhysicalDevice
import firewallsettings
import asyncconn
import ppdsloader
import dnssdresolve
import installpackage

import gettext
gettext.install(domain=config.PACKAGE, localedir=config.localedir)


TEXT_adjust_firewall = _("The firewall may need adjusting in order to "
                         "detect network printers.  Adjust the "
                         "firewall now?")

def validDeviceURI (uri):
    """Returns True is the provided URI is valid."""
    (scheme, rest) = urllib.parse.splittype (uri)
    if scheme is None or scheme == '':
        return False
    return True

# Both the printer properties window and the new printer window
# need to be able to drive 'class members' selections.
def moveClassMembers(treeview_from, treeview_to):
    selection = treeview_from.get_selection()
    model_from, rows = selection.get_selected_rows()
    rows = [Gtk.TreeRowReference.new(model_from, row) for row in rows]

    model_to = treeview_to.get_model()

    for row in rows:
        path = row.get_path()
        iter = model_from.get_iter(path)
        row_data = model_from.get(iter, 0)
        model_to.append(row_data)
        model_from.remove(iter)

def getCurrentClassMembers(treeview):
    model = treeview.get_model()
    iter = model.get_iter_first()
    result = []
    while iter:
        result.append(model.get(iter, 0)[0])
        iter = model.iter_next(iter)
    result.sort()
    return result

def checkNPName(printers, name):
    if not name: return False
    name = name.lower()
    for printer in printers.values():
        if not printer.discovered and printer.name.lower()==name:
            return False
    return True

def ready (win, cursor=None):
    try:
        gdkwin = win.get_window()
        if gdkwin:
            gdkwin.set_cursor (cursor)
            while Gtk.events_pending ():
                Gtk.main_iteration ()
    except:
        nonfatalException ()

def busy (win):
    ready (win, Gdk.Cursor.new(Gdk.CursorType.WATCH))

def on_delete_just_hide (widget, event):
    widget.hide ()
    return True # stop other handlers

def _singleton (x):
    """If we don't know whether getPPDs() or getPPDs2() was used, this
    function can unwrap an item from a list in either case."""
    if isinstance (x, list):
        return x[0]
    return x

def download_gpg_fingerprint(url):
    """Get GPG fingerprint from URL.

    Check that the URL is HTTPS with a valid and trusted server
    certificate, read it, extract the GPG fingerprint from it, and return
    it. Return None if the URL is invalid, not trusted, or the fingerprint
    can't be found.
    """
    if not url.startswith('https://'):
        debugprint('Not a https fingerprint URL: %s, ignoring driver' % url)
        return None

    # Possible paths of a file with a set of SSL certificates which are
    # considered trustworthy. The first one that exists will be used.
    # This is used for downloading GPG key fingerprints for
    # openprinting.org driver packages.
    ssl_cert_file_paths = [
        # Debian/Ubuntu use the ca-certificates package:
        '/etc/ssl/certs/ca-certificates.crt',

        # Fedora place the certificates in different locations:
        '/etc/ssl/certs/ca-bundle.crt',
        '/etc/pki/tls/certs/ca-bundle.crt'
        ]

    # default GPG key server
    # this is the generally recommended DNS round-robin, but usually very
    # slow:
    #gpg_key_server = 'keys.gnupg.net'
    gpg_key_server = 'hkp://keyserver.ubuntu.com:80'

    cert = None
    for f in ssl_cert_file_paths:
        if os.path.exists(f):
            cert = f
            break;

    if not cert:
        debugprint('No system SSL certificates available for trust checking')
        return None

    try:
        req = requests.get(url, verify=cert)
        content = req.content.decode("utf-8")
    except:
        debugprint('Cannot retrieve %s' % url)
        return None

    keyid_re = re.compile(r' ((?:(?:[0-9A-F]{4})(?:\s+|$)){10})$', re.M)

    m = keyid_re.search(content)
    if m:
        return m.group(1).strip().replace(' ','')

    return None

class NewPrinterGUI(GtkGUI):

    __gsignals__ = {
        'destroy':          (GObject.SignalFlags.RUN_LAST, None, ()),
        'printer-added' :   (GObject.SignalFlags.RUN_LAST, None, (str,)),
        'printer-modified': (GObject.SignalFlags.RUN_LAST, None,
                             (str,    # printer name
                              bool,)), # PPD modified?
        'driver-download-checked': (GObject.SignalFlags.RUN_LAST, None, (str,)),
        'dialog-canceled':  (GObject.SignalFlags.RUN_LAST, None, ()),
        }

    # Page numbers used to name the different stages
    PAGE_DESCRIBE_PRINTER = 0
    PAGE_SELECT_DEVICE = 1
    PAGE_SELECT_INSTALL_METHOD = 2
    PAGE_CHOOSE_DRIVER_FROM_DB = 3
    PAGE_CHOOSE_CLASS_MEMBERS = 4
    PAGE_APPLY = 5
    PAGE_INSTALLABLE_OPTIONS = 6
    PAGE_DOWNLOAD_DRIVER = 7

    # Values returned by _handlePrinterInstallationMode() and
    # related sub-functions, to know whether to continue the
    # execution of the remaining logic from calling functions
    INSTALL_RESULT_DONE = True
    INSTALL_RESULT_OPS_PENDING = False

    new_printer_device_tabs = {
        "parallel" : 0, # empty tab
        "usb" : 0,
        "bluetooth" : 0,
        "hal" : 0,
        "beh" : 0,
        "hp" : 0,
        "hpfax" : 0,
        "dnssd" : 0,
        "socket": 2,
        "lpd" : 3,
        "scsi" : 4,
        "serial" : 5,
        "smb" : 6,
        "network": 7,
        }

    def __init__(self):
        GObject.GObject.__init__ (self)
        self.language = locale.getlocale (locale.LC_MESSAGES)

        self.options = {} # keyword -> Option object
        self.changed = set()
        self.conflicts = set()
        self.device = None
        self.ppd = None
        self.remotecupsqueue = False
        self.exactdrivermatch = False
        self.installable_options = False
        self.ppdsloader = None
        self.installed_driver_files = []
        self.searchedfordriverpackages = False
        self.founddownloadabledrivers = False
        self.founddownloadableppd = False
        self.downloadable_driver_for_printer = None
        self.downloadable_printers = []
        self.nextnptab_rerun = False
        self.printers = {} # set in init()
        self.recommended_model_selected = False
        self._searchdialog = None
        self._installdialog = None

        self.getWidgets({"NewPrinterWindow":
                             ["NewPrinterWindow",
                              "ntbkNewPrinter",
                              "btnNPBack",
                              "btnNPForward",
                              "btnNPApply",
                              "spinner",
                              "entNPName",
                              "entNPDescription",
                              "entNPLocation",
                              "tvNPDevices",
                              "ntbkNPType",
                              "lblNPDeviceDescription",
                              "expNPDeviceURIs",
                              "tvNPDeviceURIs",
                              "cmbNPTSerialBaud",
                              "cmbNPTSerialParity",
                              "cmbNPTSerialBits",
                              "cmbNPTSerialFlow",
                              "btnNPTLpdProbe",
                              "entNPTLpdHost",
                              "entNPTLpdQueue",
                              "entNPTJetDirectHostname",
                              "entNPTJetDirectPort",
                              "entSMBURI",
                              "btnSMBBrowse",
                              "tblSMBAuth",
                              "rbtnSMBAuthPrompt",
                              "rbtnSMBAuthSet",
                              "entSMBUsername",
                              "entSMBPassword",
                              "btnSMBVerify",
                              "entNPTNetworkHostname",
                              "btnNetworkFind",
                              "lblNetworkFindSearching",
                              "lblNetworkFindNotFound",
                              "entNPTDevice",
                              "tvNCMembers",
                              "tvNCNotMembers",
                              "btnNCAddMember",
                              "btnNCDelMember",
                              "ntbkPPDSource",
                              "rbtnNPPPD",
                              "tvNPMakes",
                              "rbtnNPFoomatic",
                              "filechooserPPD",
                              "rbtnNPDownloadableDriverSearch",
                              "entNPDownloadableDriverSearch",
                              "btnNPDownloadableDriverSearch",
                              "btnNPDownloadableDriverSearch_label",
                              "cmbNPDownloadableDriverFoundPrinters",
                              "tvNPModels",
                              "tvNPDrivers",
                              "rbtnChangePPDasIs",
                              "rbtnChangePPDKeepSettings",
                              "scrNPInstallableOptions",
                              "vbNPInstallOptions",
                              "tvNPDownloadableDrivers",
                              "ntbkNPDownloadableDriverProperties",
                              "lblNPDownloadableDriverSupplier",
                              "cbNPDownloadableDriverSupplierVendor",
                              "lblNPDownloadableDriverLicense",
                              "cbNPDownloadableDriverLicensePatents",
                              "cbNPDownloadableDriverLicenseFree",
                              "lblNPDownloadableDriverDescription",
                              "lblNPDownloadableDriverSupportContacts",
                              "hsDownloadableDriverPerfText",
                              "hsDownloadableDriverPerfLineArt",
                              "hsDownloadableDriverPerfGraphics",
                              "hsDownloadableDriverPerfPhoto",
                              "lblDownloadableDriverPerfTextUnknown",
                              "lblDownloadableDriverPerfLineArtUnknown",
                              "lblDownloadableDriverPerfGraphicsUnknown",
                              "lblDownloadableDriverPerfPhotoUnknown",
                              "frmNPDownloadableDriverLicenseTerms",
                              "tvNPDownloadableDriverLicense",
                              "rbtnNPDownloadLicenseYes",
                              "rbtnNPDownloadLicenseNo"],
                         "WaitWindow":
                             ["WaitWindow",
                              "lblWait"],
                         "SMBBrowseDialog":
                             ["SMBBrowseDialog",
                              "tvSMBBrowser",
                              "btnSMBBrowseOk"]},

                        domain=config.PACKAGE)

        # Fill in liststores for combo-box widgets
        for (widget,
             opts) in [(self.cmbNPTSerialBaud,
                        [[_("Default"), ""],
                         ["1200", "1200"],
                         ["2400", "2400"],
                         ["4800", "4800"],
                         ["9600", "9600"],
                         ["19200", "19200"],
                         ["38400", "38400"],
                         ["57600", "57600"],
                         ["115200", "115200"]]),

                       (self.cmbNPTSerialParity,
                        [[_("Default"), ""],
                         [_("None"), "none"],
                         [_("Odd"), "odd"],
                         [_("Even"), "even"]]),

                       (self.cmbNPTSerialBits,
                        [[_("Default"), ""],
                         ["8", "8"],
                         ["7", "7"]]),

                       (self.cmbNPTSerialFlow,
                        [[_("Default"), ""],
                         [_("None"), "none"],
                         [_("XON/XOFF (Software)"), "soft"],
                         [_("RTS/CTS (Hardware)"), "hard"],
                         [_("DTR/DSR (Hardware)"), "hard"]]),

                       ]:
            store = Gtk.ListStore (str, str)
            for row in opts:
                store.append (row)

            widget.set_model (store)
            cell = Gtk.CellRendererText ()
            widget.clear ()
            widget.pack_start (cell, True)
            widget.add_attribute (cell, 'text', 0)

        # Set up some lists
        m = Gtk.SelectionMode.MULTIPLE
        s = Gtk.SelectionMode.SINGLE
        b = Gtk.SelectionMode.BROWSE
        for name, model, treeview, selection_mode in (
            (_("Members of this class"), Gtk.ListStore(str),
             self.tvNCMembers, m),
            (_("Others"), Gtk.ListStore(str), self.tvNCNotMembers, m),
            (_("Devices"), Gtk.ListStore(str), self.tvNPDevices, s),
            (_("Connections"), Gtk.ListStore(str), self.tvNPDeviceURIs, s),
            (_("Makes"), Gtk.ListStore(str, str), self.tvNPMakes,s),
            (_("Models"), Gtk.ListStore(str, str), self.tvNPModels,s),
            (_("Drivers"), Gtk.ListStore(str), self.tvNPDrivers,s),
            (_("Downloadable Drivers"), Gtk.ListStore(str),
             self.tvNPDownloadableDrivers, b),
            ):

            cell = Gtk.CellRendererText()
            column = Gtk.TreeViewColumn(name, cell, text=0)
            treeview.set_model(model)
            treeview.append_column(column)
            treeview.get_selection().set_mode(selection_mode)

        # Since some dialogs are reused we can't let the delete-event's
        # default handler destroy them
        self.SMBBrowseDialog.connect ("delete-event", on_delete_just_hide)
        self.WaitWindow_handler = self.WaitWindow.connect ("delete-event",
                                                           on_delete_just_hide)

        self.ntbkNewPrinter.set_show_tabs(False)
        self.ntbkPPDSource.set_show_tabs(False)
        self.ntbkNPType.set_show_tabs(False)
        self.ntbkNPDownloadableDriverProperties.set_show_tabs(False)

        self.spinner_count = 0

        # Set up OpenPrinting widgets.
        self.opreq = None
        self.opreq_handlers = None
        combobox = self.cmbNPDownloadableDriverFoundPrinters
        cell = Gtk.CellRendererText()
        combobox.pack_start (cell, True)
        combobox.add_attribute(cell, 'text', 0)
        if config.DOWNLOADABLE_ONLYFREE:
            for widget in [self.cbNPDownloadableDriverLicenseFree,
                           self.cbNPDownloadableDriverLicensePatents]:
                widget.hide ()
        if os.path.exists('/etc/apt/sources.list') or os.path.exists(
            '/etc/apt/sources.list.d'):
            config.packagesystem = 'deb'
            self.packageinstaller = 'apt'
        elif os.path.exists('/etc/yum.conf'):
            config.packagesystem = 'rpm'
            self.packageinstaller = 'yum'
        else:
            # No known package system, so we only load single PPDs via
            # OpenPrinting
            config.DOWNLOADABLE_ONLYPPD = True

        def protect_toggle (toggle_widget):
            active = getattr (toggle_widget, 'protect_active', None)
            if active is not None:
                toggle_widget.set_active (active)

        for widget in [self.cbNPDownloadableDriverSupplierVendor,
                       self.cbNPDownloadableDriverLicenseFree,
                       self.cbNPDownloadableDriverLicensePatents]:
            widget.connect ('clicked', protect_toggle)

        for widget in [self.hsDownloadableDriverPerfText,
                       self.hsDownloadableDriverPerfLineArt,
                       self.hsDownloadableDriverPerfGraphics,
                       self.hsDownloadableDriverPerfPhoto]:
            widget.connect ('change-value',
                            lambda x, y, z: True)

        # Device list
        slct = self.tvNPDevices.get_selection ()
        slct.set_select_function (self.device_select_function, None)
        self.tvNPDevices.set_row_separator_func (self.device_row_separator_fn, None)
        self.tvNPDevices.connect ("row-activated", self.device_row_activated)
        self.tvNPDevices.connect ("row-expanded", self.device_row_expanded)

        # Devices expander
        self.expNPDeviceURIs.connect ("notify::expanded",
                                      self.on_expNPDeviceURIs_expanded)
        self.expNPDeviceURIs.set_expanded(1)

        # SMB browser
        self.smb_store = Gtk.TreeStore (GObject.TYPE_PYOBJECT)
        self.btnSMBBrowse.set_sensitive (True)
        self.tvSMBBrowser.set_model (self.smb_store)

        # SMB list columns
        col = Gtk.TreeViewColumn (_("Share"))
        cell = Gtk.CellRendererText ()
        col.pack_start (cell, False)
        col.set_cell_data_func (cell, self.smbbrowser_cell_share, None)
        self.tvSMBBrowser.append_column (col)

        col = Gtk.TreeViewColumn (_("Comment"))
        cell = Gtk.CellRendererText ()
        col.pack_start (cell, False)
        col.set_cell_data_func (cell, self.smbbrowser_cell_comment, None)
        self.tvSMBBrowser.append_column (col)

        slct = self.tvSMBBrowser.get_selection ()
        slct.set_select_function (self.smb_select_function, None)

        self.SMBBrowseDialog.set_transient_for(self.NewPrinterWindow)

        self.tvNPDrivers.set_has_tooltip(True)
        self.tvNPDrivers.connect("query-tooltip", self.on_NPDrivers_query_tooltip)

        ppd_filter = Gtk.FileFilter()
        ppd_filter.set_name(_("PostScript Printer Description files (*.ppd, *.PPD, *.ppd.gz, *.PPD.gz, *.PPD.GZ)"))
        ppd_filter.add_pattern("*.ppd")
        ppd_filter.add_pattern("*.PPD")
        ppd_filter.add_pattern("*.ppd.gz")
        ppd_filter.add_pattern("*.PPD.gz")
        ppd_filter.add_pattern("*.PPD.GZ")
        self.filechooserPPD.add_filter(ppd_filter)

        ppd_filter = Gtk.FileFilter()
        ppd_filter.set_name(_("All files (*)"))
        ppd_filter.add_pattern("*")
        self.filechooserPPD.add_filter(ppd_filter)

        self.device_selected = -1
        self.dialog_mode = "printer"
        self.connect_signals ()
        debugprint ("+%s" % self)

    def __del__ (self):
        debugprint ("-%s" % self)

    def do_destroy (self):
        debugprint ("DESTROY: %s" % self)
        if self.SMBBrowseDialog:
            self.SMBBrowseDialog.destroy ()
            self.SMBBrowseDialog = None

        if self.NewPrinterWindow:
            self.NewPrinterWindow.destroy ()
            self.NewPrinterWindow = None

        if self.WaitWindow:
            self.WaitWindow.destroy ()
            self.WaitWindow = None

    def inc_spinner_task (self):
        if self.spinner_count == 0:
            self.spinner.show ()
            self.spinner.start ()

        self.spinner_count += 1

    def dec_spinner_task (self):
        self.spinner_count -= 1
        if self.spinner_count == 0:
            self.spinner.hide ()
            self.spinner.stop ()

    def show_IPP_Error (self, exception, message):
        debugprint ("%s: IPP error dialog (%s, %s)" % (self, repr (exception),
                                                       message))
        return show_IPP_Error (exception, message, parent=self.NewPrinterWindow)

    def option_changed(self, option):
        if option.is_changed():
            self.changed.add(option)
        else:
            self.changed.discard(option)

        if option.conflicts:
            self.conflicts.add(option)
        else:
            self.conflicts.discard(option)
        self.setDataButtonState()

        return

    def setDataButtonState(self):
        self.btnNPForward.set_sensitive(not bool(self.conflicts))

    def makeNameUnique(self, name):
        """Make a suggested queue name valid and unique."""
        name = name.replace (" ", "-")
        name = name.replace ("/", "-")
        name = name.replace ("#", "-")
        if not checkNPName (self.printers, name):
            suffix=2
            while not checkNPName (self.printers, name + "-" + str (suffix)):
                suffix += 1
                if suffix == 100:
                    break
            name += "-" + str (suffix)
        return name

    def destroy (self):
        self.emit ('destroy')

    def init(self, dialog_mode, device_uri=None, name=None, ppd=None,
             devid="", host=None, encryption=None, parent=None, xid=0):
        self.parent = parent
        if not self.parent:
            self.NewPrinterWindow.set_focus_on_map (False)

        self.dialog_mode = dialog_mode
        self._device_uri = device_uri
        self.orig_ppd = ppd
        self.devid = devid
        self._host = host
        self._encryption = encryption
        self._name = name
        if not host:
            self._host = cups.getServer ()
        if not encryption:
            self._encryption = cups.getEncryption ()

        self.options = {} # keyword -> Option object
        self.changed = set()
        self.conflicts = set()
        self.fetchDevices_conn = None
        self.ppds = None
        self.ppdsmatch_result = None
        self.printer_finder = None

        if not self._validInitParameters ():
            raise RuntimeError

        # Get a current list of printers so that we can know whether
        # the chosen name is unique.
        try:
            self.cups = authconn.Connection (parent=self.NewPrinterWindow,
                                             host=self._host,
                                             encryption=self._encryption)
        except cups.HTTPError as e:
            (s,) = e.args
            show_HTTP_Error (s, self.parent)
            return False
        except RuntimeError:
            show_HTTP_Error (-1, self.parent)
            return False
        except Exception as e:
            nonfatalException (e)
            return False

        try:
            self.printers = cupshelpers.getPrinters (self.cups)
        except cups.IPPError as e:
            (e, m) = e.args
            show_IPP_Error (e, m, parent=self.parent)
            return False

        # Initialise widgets.
        self.lblNetworkFindSearching.hide ()
        self.entNPTNetworkHostname.set_sensitive (True)
        self.entNPTNetworkHostname.set_text ('')
        self.btnNetworkFind.set_sensitive (True)
        self.lblNetworkFindNotFound.hide ()

        # Clear out any previous list of makes.
        model = self.tvNPMakes.get_model()
        model.clear()

        combobox = self.cmbNPDownloadableDriverFoundPrinters
        combobox.set_model (Gtk.ListStore (str, str))
        self.entNPDownloadableDriverSearch.set_text ('')
        label = self.btnNPDownloadableDriverSearch_label
        label.set_text (_("Search"))

        self.entNPTJetDirectPort.set_text('9100')
        self.rbtnSMBAuthPrompt.set_active(True)

        if xid != 0 and self.parent:
            self.NewPrinterWindow.show_now()
            self.NewPrinterWindow.set_transient_for (self.parent)

        if self.dialog_mode == "printer":
            self._initialisePrinterMode ()
        elif self.dialog_mode == "class":
            self._initialiseClassMode ()
        elif self.dialog_mode == "device":
            self._initialiseDeviceMode ()
        elif self.dialog_mode == "printer_with_uri":
            self._initialisePrinterWithURIMode ()
        elif self.dialog_mode == "ppd":
            self._initialisePPDMode ()
        elif self.dialog_mode == "download_driver":
            self._initialiseDownloadDriverMode ()
            return True

        if xid == 0 and self.parent:
            self.NewPrinterWindow.set_transient_for (parent)

        self.NewPrinterWindow.show()
        self.setNPButtons()
        return True

    def _validInitParameters (self):
        if self.dialog_mode in ['printer_with_uri', 'device', 'ppd']:
            return self._device_uri is not None
        elif self.dialog_mode == 'download_driver':
            return self.devid != ""
        return True

    def _initialiseClassMode (self):
        self._initialiseWidgetsForMode ("class")
        self.NewPrinterWindow.set_title (_("New Class"))

        self.fillNewClassMembers ()

        # Start on name page
        self.ntbkNewPrinter.set_current_page (self.PAGE_DESCRIBE_PRINTER)

    def _initialisePrinterMode (self):
        self._initialiseWidgetsForMode ("printer")
        self.NewPrinterWindow.set_title (_("New Printer"))

        # Start on devices page (SELECT_DEVICE, not DESCRIBE_PRINTER)
        self.ntbkNewPrinter.set_current_page (self.PAGE_SELECT_DEVICE)
        self.fillDeviceTab ()
        self.rbtnNPFoomatic.set_active (True)
        self.on_rbtnNPFoomatic_toggled (self.rbtnNPFoomatic)

    def _initialiseDeviceMode (self):
        self.NewPrinterWindow.set_title (_("Change Device URI"))
        self.ntbkNewPrinter.set_current_page (self.PAGE_SELECT_DEVICE)
        self.fillDeviceTab (self._device_uri)

    def _initialisePrinterWithURIMode (self):
        self._initialiseWidgetsForMode ("printer")
        self._initialiseDeviceFromURI ()

        self.NewPrinterWindow.set_title (_("New Printer"))

        self.ntbkNewPrinter.set_current_page (self.PAGE_SELECT_INSTALL_METHOD)
        self.rbtnNPFoomatic.set_active (True)
        self.on_rbtnNPFoomatic_toggled (self.rbtnNPFoomatic)
        self.rbtnChangePPDKeepSettings.set_active (True)

        self._initialiseAutoVariables ()
        self.nextNPTab (step = 0)

    def _initialiseDownloadDriverMode (self):
        self.NewPrinterWindow.set_title (_("Download Printer Driver"))

        self.ntbkNewPrinter.set_current_page (self.PAGE_DOWNLOAD_DRIVER)
        self.nextnptab_rerun = True
        self.nextNPTab (step = 0)

    def _initialisePPDMode (self):
        self._initialiseDeviceFromURI ()

        self.NewPrinterWindow.set_title (_("Change Driver"))

        # We'll need to know the Device ID for this device.
        if not self.devid:
            scheme = str (self._device_uri.split (":", 1)[0])
            schemes = [scheme]
            if scheme in ["socket", "lpd", "ipp"]:
                schemes.extend (["snmp", "dnssd"])
            self.fetchDevices_conn = asyncconn.Connection ()
            self.fetchDevices_conn._begin_operation (_("fetching device list"))
            self.inc_spinner_task ()
            cupshelpers.getDevices (self.fetchDevices_conn,
                                    include_schemes=schemes,
                                    reply_handler=self.change_ppd_got_devs,
                                    error_handler=self.change_ppd_got_devs)

        self.ntbkNewPrinter.set_current_page (self.PAGE_SELECT_INSTALL_METHOD)
        self.rbtnNPFoomatic.set_active (True)
        self.on_rbtnNPFoomatic_toggled (self.rbtnNPFoomatic)
        self.rbtnChangePPDKeepSettings.set_active (True)

        self._initialiseAutoVariables ()

    def _initialiseWidgetsForMode (self, mode_name):
        self.entNPName.set_text (self.makeNameUnique (mode_name))
        self.entNPName.grab_focus ()
        for widget in [self.entNPLocation,
                       self.entNPDescription,
                       self.entSMBURI, self.entSMBUsername,
                       self.entSMBPassword]:
            widget.set_text ('')

    def _initialiseDeviceFromURI (self):
        device_dict = { }
        self.device = cupshelpers.Device (self._device_uri, **device_dict)

    def _initialiseAutoVariables (self):
        self.auto_make = ""
        self.auto_model = ""
        self.auto_driver = None

    def change_ppd_got_devs (self, conn, result):
        self.fetchDevices_conn._end_operation ()
        self.fetchDevices_conn.destroy ()
        self.fetchDevices_conn = None
        self.dec_spinner_task ()
        if isinstance (result, Exception):
            current_devices = {}
        else:
            current_devices = result

        devid = None
        mm = None
        if self.devid != "":
            devid = self.devid
        else:
            device = current_devices.get (self.device.uri)
            if device:
                devid = device.id
                mm = device.make_and_model
                self.device = device

        # We'll also need the list of PPDs
        self.ntbkNewPrinter.set_current_page (self.PAGE_SELECT_INSTALL_METHOD)
        self.nextNPTab(step = 0)

    def on_ppdsloader_finished_next (self, ppdsloader):
        """
        This method is called when the PPDs loader has finished
        loading PPDs in preparation for the next screen the user will
        see, having clicked 'Forward'.  We are creating a new queue,
        and dialog_mode is either "printer" or "printer_with_uri".
        """

        self._getPPDs_reply (ppdsloader)
        if not self.ppds:
            return

        if ppdsloader._jockey_has_answered:
            self.searchedfordriverpackages = True

        debugprint ("Loaded PPDs this time; try nextNPTab again...")
        self.nextnptab_rerun = True
        if self.ntbkNewPrinter.get_current_page () == self.PAGE_SELECT_INSTALL_METHOD:
            self.nextNPTab (step = 0)
        else:
            self.nextNPTab ()

    # get PPDs

    def _getPPDs_reply (self, ppdsloader):
        exc = ppdsloader.get_error ()
        if exc:
            ppdsloader.destroy ()
            try:
                raise exc
            except cups.IPPError as e:
                (e, m) = e.args
                self.show_IPP_Error (e, m)
                return

        ppds = ppdsloader.get_ppds ()
        if ppds:
            self.ppds = ppds
            self.ppdsmatch_result = ppdsloader.get_ppdsmatch_result ()
            if ppdsloader._jockey_has_answered:
                self.installed_driver_files = ppdsloader.get_installed_files ()
        else:
            self.ppds = None
            self.ppdsmatch_result = None

        ppdsloader.destroy ()
        self.ppdsloader = None

    # Class members

    def fillNewClassMembers(self):
        model = self.tvNCMembers.get_model()
        model.clear()
        model = self.tvNCNotMembers.get_model()
        model.clear()
        try:
            self.printers = cupshelpers.getPrinters (self.cups)
        except cups.IPPError:
            self.printers = {}

        for printer in self.printers.keys():
            if not self.printers[printer].type & cups.CUPS_PRINTER_CLASS:
                model.append((printer,))

    def on_btnNCAddMember_clicked(self, button):
        moveClassMembers(self.tvNCNotMembers, self.tvNCMembers)
        self.btnNPApply.set_sensitive(
            bool(getCurrentClassMembers(self.tvNCMembers)))
        button.set_sensitive(False)

    def on_btnNCDelMember_clicked(self, button):
        moveClassMembers(self.tvNCMembers, self.tvNCNotMembers)
        self.btnNPApply.set_sensitive(
            bool(getCurrentClassMembers(self.tvNCMembers)))
        button.set_sensitive(False)

    def on_tvNCMembers_cursor_changed(self, widget):
        selection = widget.get_selection()
        if selection is None:
            return

        model_from, rows = selection.get_selected_rows()
        self.btnNCDelMember.set_sensitive(rows != [])

    def on_tvNCNotMembers_cursor_changed(self, widget):
        selection = widget.get_selection()
        if selection is None:
            return

        model_from, rows = selection.get_selected_rows()
        self.btnNCAddMember.set_sensitive(rows != [])

    # Navigation buttons

    def on_NPCancel(self, widget, event=None):
        if self.fetchDevices_conn:
            self.fetchDevices_conn.destroy ()
            self.fetchDevices_conn = None
            self.dec_spinner_task ()

        if self.ppdsloader:
            self.ppdsloader.destroy ()
            self.ppdsloader = None

        if self.printer_finder:
            self.printer_finder.cancel ()
            self.printer_finder = None
            self.dec_spinner_task ()

        self.NewPrinterWindow.hide()
        if self.opreq is not None:
            for handler in self.opreq_handlers:
                self.opreq.disconnect (handler)

            self.opreq_handlers = None
            self.opreq.cancel ()
            self.opreq = None

        self.device = None
        self.printers = {}
        self.emit ('dialog-canceled')
        return True

    def on_btnNPBack_clicked(self, widget):
        self.nextNPTab(-1)

    def on_btnNPForward_clicked(self, widget):
        self.nextNPTab()

    def installdriverpackage (self, driver):
        install_info = self._getDriverInstallationInfo (driver)
        if not install_info:
            return False

        name = install_info['name']
        repo = install_info['repo']
        keyid = install_info['keyid']

        fmt = _("Installing driver %s") % name
        self._installdialog = Gtk.MessageDialog (parent=self.NewPrinterWindow,
                                                 modal=True, destroy_with_parent=True,
                                                 type=Gtk.MessageType.INFO,
                                                 buttons=Gtk.ButtonsType.CANCEL,
                                                 text=fmt)

        self._installdialog.format_secondary_text (_("Installing ..."))
        # Add a progress bar to the message box
        dialogarea = self._installdialog.get_message_area()
        pbar = Gtk.ProgressBar()
        dialogarea.add(pbar)
        pbar.show()

        # Save a reference to the progress bar in the dialog, so that
        # we can easily reference it from do_installdriverpackage()
        self._installdialog._progress_bar = pbar

        self._installdialog.connect ("response", self._installdialog_response)
        self._installdialog.show_all ()

        # Perform the actual installation of the printer driver
        ret = self.do_installdriverpackage (name, repo, keyid)

        if self._installdialog:
            self._installdialog.hide ()
            self._installdialog.destroy ()
            self._installdialog = None

        return ret

    def do_installdriverpackage(self, name, repo, keyid):
        debugprint('Installing driver: %s; Repo: %s; Key ID: %s' %
                   (repr (name),
                    repr (repo),
                    repr (keyid)))

        # Do the installation with a command line helper script
        new_environ = os.environ.copy()
        new_environ['LC_ALL'] = "C"
        if keyid:
            args = ["install-printerdriver", name, repo, keyid]
        else:
            args = ["install-printerdriver", name, repo]
        debugprint ("Running command: " + repr(args))
        ret = True
        try:
            self.p = subprocess.Popen (args, env=new_environ, close_fds=True,
                                       stdin=subprocess.DEVNULL,
                                       stdout=subprocess.PIPE)
            # Keep the UI refreshed while we wait for
            # the drivers query to complete.
            (stdout, stderr) = (self.p.stdout, self.p.stderr)

            done = False
            pbar = self._installdialog._progress_bar
            while self.p.poll() is None:
                line = stdout.readline ().strip()
                if (len(line) > 0):
                    if line == "done":
                        done = True
                        break
                    elif line.startswith(b"P"):
                        try:
                            percentage = float(line[1:])
                            if percentage >= 0:
                                pbar.set_fraction(percentage/100)
                            else:
                                pbar.set_pulse_step(-percentage/100)
                                pbar.pulse()
                        except:
                            pass
                    else:
                        self.installed_driver_files.append(line.decode("utf-8"));
                while Gtk.events_pending ():
                    Gtk.main_iteration ()
                if not line:
                    time.sleep (0.1)
            if self.p.returncode != 0 and not done:
                ret = False
        except:
            # Problem executing command.
            ret = False

        if not ret:
            self.installed_driver_files = [];

        return ret

    def _getDriverInstallationInfo (self, driver):
        pkgs = driver.get('packages', {})
        arches = list(pkgs.keys())
        if len(arches) == 0:
            debugprint('No packages for driver')
            return None
        if len(arches) > 1:
            debugprint('Returned more than one matching architecture, please report this as a bug: %s', repr (arches))
            return None

        pkgs = pkgs[arches[0]]

        if len(pkgs) != 1:
            debugprint('Returned more than one package, this is currently not handled')
            return None
        pkg = list(pkgs.keys())[0]

        name = ''
        if pkg.endswith('.deb'):
            name = pkg.split('_')[0]
        elif pkg.endswith('.rpm'):
            name = '-'.join(pkg.split('-')[0:-2])
        else:
            raise ValueError('Unknown package type: ' + pkg)

        # require signature for binary packages; architecture
        # independent packages are usually PPDs, which we trust enough
        keyid = None
        if 'fingerprint' not in pkgs[pkg]:
            if config.DOWNLOADABLE_PKG_ONLYSIGNED and arches[0] not in ['all', 'noarch']:
                debugprint('Not installing driver as it does not have a GPG fingerprint URL')
                return None
        else:
            keyid = download_gpg_fingerprint(pkgs[pkg]['fingerprint'])
            if config.DOWNLOADABLE_PKG_ONLYSIGNED and arches[0] not in ['all', 'noarch'] and not keyid:
                debugprint('Not installing driver as it does not have a valid GPG fingerprint')
                return None


        repo = pkgs[pkg].get('repositories', {}).get(self.packageinstaller)
        if not repo:
            debugprint('Local package system %s not found in %s' %
                       (self.packageinstaller,
                        repr (pkgs[pkg].get('repositories', {}))))
            return None

        # All good: return necessary information to install the driver
        return { 'name': name, 'repo': repo, 'keyid': keyid }

    def _installdialog_response (self, dialog, response):
        self.p.terminate ()

    def nextNPTab(self, step=1):
        page_nr = self.ntbkNewPrinter.get_current_page()
        debugprint ("Next clicked on page %d" % page_nr)

        keep_going = True
        if self.dialog_mode == "printer" or self.dialog_mode == "printer_with_uri" or \
              self.dialog_mode == "ppd" or self.dialog_mode == "download_driver":
            install_result = self._handlePrinterInstallationMode (step)
            if install_result == self.INSTALL_RESULT_OPS_PENDING:
                # Do not continue if the installation process says so
                # (e.g. waiting for a CUPS to return a list of PPDs)
                keep_going = False

        if not keep_going:
            debugprint ('Interrupting execution of nextNPTab(): Operations pending')
            return

        order = self._getPagesOrderForDialogMode ()
        next_page_nr = order[order.index(page_nr)+step]

        # fill Installable Options tab
        fetch_ppd = False
        try:
            if order.index (self.PAGE_APPLY) > -1:
                # There is a copy settings page in this set
                fetch_ppd = next_page_nr == self.PAGE_APPLY and step >= 0
        except ValueError:
            fetch_ppd = next_page_nr == self.PAGE_INSTALLABLE_OPTIONS and step >= 0

        debugprint ("Will fetch ppd? %d" % fetch_ppd)
        if fetch_ppd:
            self.ppd = self.getNPPPD()
            self.installable_options = False
            if self.ppd is None:
                return

            # Prepare Installable Options screen.
            if isinstance(self.ppd, cups.PPD):
                self.fillNPInstallableOptions()
            else:
                # Put a label there explaining why the page is empty.
                ppd = self.ppd
                self.ppd = None
                self.fillNPInstallableOptions()
                self.ppd = ppd

            if not self.installable_options:
                if next_page_nr == self.PAGE_INSTALLABLE_OPTIONS:
                    # step over if empty
                    next_page_nr = order[order.index(next_page_nr)+1]

        # Step over empty Installable Options tab when moving backwards.
        if next_page_nr == self.PAGE_INSTALLABLE_OPTIONS and \
                not self.installable_options and step < 0:
            next_page_nr = order[order.index(next_page_nr)-1]

        debugprint ("Will advance to page %d" % next_page_nr)
        if step >= 0 and next_page_nr == self.PAGE_DOWNLOAD_DRIVER: # About to show downloadable drivers
            self.fillDownloadableDrivers ()

        if step >= 0 and next_page_nr == self.PAGE_DESCRIBE_PRINTER: # About to choose a name.
            # Suggest an appropriate name.
            name = None
            descr = None

            try:
                if (self.device.id and
                    not self.device.type in ("socket", "lpd", "ipp",
                                             "http", "https", "bluetooth")):
                    name = "%s %s" % (self.device.id_dict["MFG"], 
                                      self.device.id_dict["MDL"])
            except:
                nonfatalException ()

            try:
                if name is None and isinstance (self.ppd, cups.PPD):
                    mname = self.ppd.findAttr ("modelName").value
                    make, model = cupshelpers.ppds.ppdMakeModelSplit (mname)
                    if make and model:
                        name = "%s %s" % (make, model)
                    elif make or model:
                        name = "%s%s" % (make, model)
            except:
                nonfatalException ()

            if name:
                descr = name
            else:
                name = 'printer'

            name = self.makeNameUnique (name)
            self.entNPName.set_text (name)

            if descr:
                self.entNPDescription.set_text (descr)

        self.ntbkNewPrinter.set_current_page(next_page_nr)

        self.setNPButtons()


    def _getPagesOrderForDialogMode (self):
        order = []
        if self.dialog_mode == "class":
            order = [
                self.PAGE_DESCRIBE_PRINTER,
                self.PAGE_CHOOSE_CLASS_MEMBERS,
                self.PAGE_APPLY,
            ]
        elif self.dialog_mode == "download_driver":
            order = [
                self.PAGE_DOWNLOAD_DRIVER
            ]
        elif self.dialog_mode == "printer":
            if self.remotecupsqueue:
                order = [
                    self.PAGE_SELECT_DEVICE,
                    self.PAGE_DESCRIBE_PRINTER
                ]
            elif (self.founddownloadabledrivers and
                  not self.rbtnNPDownloadableDriverSearch.get_active()):
                if self.exactdrivermatch:
                    order = [
                        self.PAGE_SELECT_DEVICE,
                        self.PAGE_DOWNLOAD_DRIVER,
                        self.PAGE_INSTALLABLE_OPTIONS,
                        self.PAGE_DESCRIBE_PRINTER
                    ]
                else:
                    order = [
                        self.PAGE_SELECT_DEVICE,
                        self.PAGE_DOWNLOAD_DRIVER,
                        self.PAGE_SELECT_INSTALL_METHOD,
                        self.PAGE_CHOOSE_DRIVER_FROM_DB,
                        self.PAGE_INSTALLABLE_OPTIONS,
                        self.PAGE_DESCRIBE_PRINTER
                    ]
            elif (self.exactdrivermatch and
                  not self.rbtnNPDownloadableDriverSearch.get_active()):
                order = [
                    self.PAGE_SELECT_DEVICE,
                    self.PAGE_INSTALLABLE_OPTIONS,
                    self.PAGE_DESCRIBE_PRINTER
                ]
            elif self.rbtnNPFoomatic.get_active():
                order = [
                    self.PAGE_SELECT_DEVICE,
                    self.PAGE_SELECT_INSTALL_METHOD,
                    self.PAGE_CHOOSE_DRIVER_FROM_DB,
                    self.PAGE_INSTALLABLE_OPTIONS,
                    self.PAGE_DESCRIBE_PRINTER
                ]
            elif self.rbtnNPPPD.get_active():
                order = [
                    self.PAGE_SELECT_DEVICE,
                    self.PAGE_SELECT_INSTALL_METHOD,
                    self.PAGE_INSTALLABLE_OPTIONS,
                    self.PAGE_DESCRIBE_PRINTER
                ]
            else:
                # Downloadable driver
                order = [
                    self.PAGE_SELECT_DEVICE,
                    self.PAGE_SELECT_INSTALL_METHOD,
                    self.PAGE_DOWNLOAD_DRIVER,
                    self.PAGE_INSTALLABLE_OPTIONS,
                    self.PAGE_DESCRIBE_PRINTER
                ]
        elif self.dialog_mode == "ppd":
            if self.rbtnNPFoomatic.get_active():
                order = [
                    self.PAGE_SELECT_INSTALL_METHOD,
                    self.PAGE_CHOOSE_DRIVER_FROM_DB,
                    self.PAGE_APPLY,
                    self.PAGE_INSTALLABLE_OPTIONS
                ]
            elif self.rbtnNPPPD.get_active():
                order = [
                    self.PAGE_SELECT_INSTALL_METHOD,
                    self.PAGE_APPLY,
                    self.PAGE_INSTALLABLE_OPTIONS
                ]
            else:
                # Downloadable driver
                order = [
                    self.PAGE_SELECT_INSTALL_METHOD,
                    self.PAGE_DOWNLOAD_DRIVER,
                    self.PAGE_APPLY,
                    self.PAGE_INSTALLABLE_OPTIONS
                ]
        elif self.dialog_mode == "device":
            order = [
                self.PAGE_SELECT_DEVICE,
            ]
        else: # dialog_mode == "printer-from-uri"
            if self.remotecupsqueue:
                order = [
                    self.PAGE_DESCRIBE_PRINTER,
                ]
            elif (self.founddownloadabledrivers and
                  not self.rbtnNPDownloadableDriverSearch.get_active()):
                if self.exactdrivermatch:
                    order = [
                        self.PAGE_DOWNLOAD_DRIVER,
                        self.PAGE_INSTALLABLE_OPTIONS,
                        self.PAGE_DESCRIBE_PRINTER
                    ]
                else:
                    order = [
                        self.PAGE_DOWNLOAD_DRIVER,
                        self.PAGE_SELECT_INSTALL_METHOD,
                        self.PAGE_CHOOSE_DRIVER_FROM_DB,
                        self.PAGE_INSTALLABLE_OPTIONS,
                        self.PAGE_DESCRIBE_PRINTER
                    ]
            elif (self.exactdrivermatch and
                  not self.rbtnNPDownloadableDriverSearch.get_active()):
                order = [
                    self.PAGE_INSTALLABLE_OPTIONS,
                    self.PAGE_DESCRIBE_PRINTER
                ]
            elif self.rbtnNPFoomatic.get_active():
                order = [
                    self.PAGE_SELECT_INSTALL_METHOD,
                    self.PAGE_CHOOSE_DRIVER_FROM_DB,
                    self.PAGE_INSTALLABLE_OPTIONS,
                    self.PAGE_DESCRIBE_PRINTER
                ]
            elif self.rbtnNPPPD.get_active():
                order = [
                    self.PAGE_SELECT_INSTALL_METHOD,
                    self.PAGE_INSTALLABLE_OPTIONS,
                    self.PAGE_DESCRIBE_PRINTER
                ]
            else:
                # Downloadable driver
                order = [
                    self.PAGE_SELECT_INSTALL_METHOD,
                    self.PAGE_DOWNLOAD_DRIVER,
                    self.PAGE_INSTALLABLE_OPTIONS,
                    self.PAGE_DESCRIBE_PRINTER
                ]
        return order

    def _handlePrinterInstallationMode (self, step):
        busy (self.NewPrinterWindow)

        page_nr = self.ntbkNewPrinter.get_current_page ()
        page_nr = self.ntbkNewPrinter.get_current_page ()

        # Let's assume everything will be completed by default
        result = self.INSTALL_RESULT_DONE

        if (((page_nr == self.PAGE_SELECT_DEVICE or
              page_nr == self.PAGE_DOWNLOAD_DRIVER) and step > 0) or
            ((page_nr == self.PAGE_SELECT_INSTALL_METHOD or
              page_nr == self.PAGE_DOWNLOAD_DRIVER) and step == 0)):
            # The function below will return INSTALL_RESULT_OPS_PENDING
            # if, for some reason, it spawns an asynchronous operation
            # and needs to wait for its results before continuing.
            result = self._handlePrinterInstallationStage (page_nr, step)

        if page_nr == self.PAGE_CHOOSE_DRIVER_FROM_DB:
            if not self.device.id:
                # Choose an appropriate name when no Device ID
                # is available, based on the model the user has
                # selected.
                try:
                    model, iter = self.tvNPModels.get_selection ().\
                                  get_selected ()
                    name = model.get(iter, 0)[0]
                    name = self.makeNameUnique (name)
                    self.entNPName.set_text (name)
                except:
                    nonfatalException ()

        ready (self.NewPrinterWindow)
        return result

    def _handlePrinterInstallationStage (self, page_nr, step):
        if self.dialog_mode != "download_driver":
            uri = self.device.uri
            if uri and uri.startswith ("smb"):
                # User has selected an smb device
                uri = SMBURI (uri=uri[6:]).sanitize_uri ()
                self._installSMBBackendIfNeeded ()

        if page_nr == self.PAGE_SELECT_DEVICE or page_nr == self.PAGE_SELECT_INSTALL_METHOD:
            self._selectDeviceForInstallation (uri)
        elif page_nr == self.PAGE_DOWNLOAD_DRIVER and self.nextnptab_rerun == False:
            self._handleDriverInstallation ()

        devid = None
        if not self.remotecupsqueue or self.dialog_mode == "ppd":
            if self.dialog_mode != "download_driver":
                devid = self.device.id # ID of selected device
            if not devid:
                devid = self.devid # ID supplied at init()
            if not devid:
                devid = None

            if self.ppds is None and self.dialog_mode != "download_driver":
                self._loadPPDsForDevice (devid, uri)
                # _loadPPDsForDevice () is an asynchronous operation, so
                # let the caller know that it can't continue for now.
                return self.INSTALL_RESULT_OPS_PENDING

        self.nextnptab_rerun = False
        if page_nr == self.PAGE_SELECT_DEVICE or page_nr == self.PAGE_SELECT_INSTALL_METHOD:
            self._installHPScannerFilesIfNeeded ()

        return self._installPrinterFromDeviceID (devid, page_nr, step)

    def _installSMBBackendIfNeeded (self):
        # Does the backend need to be installed?
        if (self.nextnptab_rerun == False and not self.searchedfordriverpackages and
               (self._host == 'localhost' or self._host[0] == '/') and
               not os.access ("/usr/lib/cups/backend/smb", os.F_OK)):
            debugprint ("No smb backend so attempting install")
            try:
                pk = installpackage.PackageKit ()
                # The following call means a blocking, synchronous, D-Bus call
                pk.InstallPackageName (0, 0, "smbclient")
            except:
                nonfatalException ()

    def _selectDeviceForInstallation (self, uri):
        self._initialiseAutoVariables ()
        self.device.uri = self.getDeviceURI ()

        # Cancel the printer finder now as the user has
        # already selected their device.
        if self.fetchDevices_conn:
            self.fetchDevices_conn.destroy ()
            self.fetchDevices_conn = None
            self.dec_spinner_task ()
        if self.printer_finder:
            self.printer_finder.cancel ()
            self.printer_finder = None
            self.dec_spinner_task ()

        if (not self.device.id and
            self.device.type in ["socket", "lpd", "ipp"]):
            # This is a network printer whose model we don't yet know.
            # Try to discover it.
            self.getNetworkPrinterMakeModel ()

        # Try to access the PPD, in this case our detected IPP
        # printer is a queue on a remote CUPS server which is
        # not automatically set up on our local CUPS server
        # (for example DNS-SD broadcasted queue from Mac OS X)
        self.remotecupsqueue = None
        res = re.search (r"ipp://(\S+?)(:\d+|)/printers/(\S+)", uri)
        if res:
            resg = res.groups()
            if len (resg[1]) > 0:
                port = int (resg[1][1:])
            else:
                port = 631
            try:
                conn = http.client.HTTPConnection(resg[0], port)
                conn.request("GET", "/printers/%s.ppd" % resg[2])
                resp = conn.getresponse()
                if resp.status == 200:
                    self.remotecupsqueue = resg[2]
            except:
                pass

            # We also want to fetch the printer-info and
            # printer-location attributes, to pre-fill those
            # fields for this new queue.
            try:
                encryption = cups.HTTP_ENCRYPT_IF_REQUESTED
                c = cups.Connection (host=resg[0],
                                     port=port,
                                     encryption=encryption)

                r = ['printer-info', 'printer-location']
                attrs = c.getPrinterAttributes (uri=uri,
                                                requested_attributes=r)
                info = attrs.get ('printer-info', '')
                location = attrs.get ('printer-location', '')
                if len (info) > 0:
                    self.entNPDescription.set_text (info)
                if len (location) > 0:
                    self.device.location = location
            except RuntimeError:
                pass
            except:
                nonfatalException ()
        elif ((uri.startswith ("dnssd:") or uri.startswith("mdns:")) and
                uri.find ("/cups") != -1 and self.device.info):
            # Remote CUPS queue discovered by "dnssd" CUPS backend
            self.remotecupsqueue = self.device.info

    def _handleDriverInstallation (self):
        # Install package of the driver found on OpenPrinting
        treeview = self.tvNPDownloadableDrivers
        model, iter = treeview.get_selection ().get_selected ()
        driver = None
        if iter is not None:
            driver = model.get_value (iter, 1)
        if driver is None or driver == 0 or 'packages' not in driver:
            return

        # Find the package name, repository, and fingerprint
        # and install the package
        result = self.installdriverpackage (driver)
        if not result or len(self.installed_driver_files) == 0:
          return

        # We actually installed a package, delete the
        # PPD list to get it regenerated
        self.ppds = None

        if (self.dialog_mode != "download_driver" and
              (not self.device.id and
              (not self.device.make_and_model or self.device.make_and_model == "Unknown") and
              self.downloadable_driver_for_printer)):
            self.device.make_and_model = self.downloadable_driver_for_printer

    def _installHPScannerFilesIfNeeded (self):
        if (hasattr (self.device, 'hp_scannable') and self.device.hp_scannable and
                not os.access ("/etc/sane.d/dll.d/hpaio", os.R_OK) and
                not os.access ("/etc/sane.d/dll.d/hplip", os.R_OK)):
            debugprint ("No HPLIP sane backend so "
                        "attempting install")
            try:
                pk = installpackage.PackageKit ()
                # The following call means a blocking, synchronous, D-Bus call
                pk.InstallPackageName (0, 0, "libsane-hpaio")
            except:
                pass

    def _loadPPDsForDevice (self, devid, uri):
        debugprint ("nextNPTab: need PPDs loaded")
        p = ppdsloader.PPDsLoader (device_id=devid,
                                   device_uri=uri,
                                   parent=self.NewPrinterWindow,
                                   host=self._host,
                                   encryption=self._encryption)
        self.ppdsloader = p
        p.connect ('finished',self.on_ppdsloader_finished_next)
        p.run ()

    def _installPrinterFromDeviceID (self, devid, page_nr, step):
        ppdname = None
        self.id_matched_ppdnames = []
        try:
            if self.dialog_mode == "download_driver":
                ppdname = "download"
                status = "generic"
            elif self.remotecupsqueue:
                # We have a remote CUPS queue, let the client queue
                # stay raw so that the driver on the server gets used
                ppdname = 'raw'
                self.ppd = ppdname
                name = self.remotecupsqueue
                name = self.makeNameUnique (name)
                self.entNPName.set_text (name)
                status = "exact"
            elif (self.device.id or
                  (self.device.make_and_model and
                   self.device.make_and_model != "Unknown") or
                  devid):
                if self.device.id:
                    id_dict = self.device.id_dict
                elif devid:
                    id_dict = cupshelpers.parseDeviceID (devid)
                else:
                    id_dict = {}
                    (id_dict["MFG"],
                     id_dict["MDL"]) = cupshelpers.ppds.\
                         ppdMakeModelSplit (self.device.make_and_model)
                    id_dict["DES"] = ""
                    id_dict["CMD"] = []
                    devid = "MFG:%s;MDL:%s;" % (id_dict["MFG"],
                                                id_dict["MDL"])

                fit = self.ppds.\
                    getPPDNamesFromDeviceID (id_dict["MFG"],
                                             id_dict["MDL"],
                                             id_dict["DES"],
                                             id_dict["CMD"],
                                             self.device.uri,
                                             self.device.make_and_model)
                debugprint ("Suitable PPDs found: %s" % repr(fit))
                ppdnamelist = self.ppds.\
                    orderPPDNamesByPreference (list(fit.keys ()),
                                               self.installed_driver_files,
                                               devid=id_dict, fit=fit)
                debugprint ("PPDs in priority order: %s" % repr(ppdnamelist))
                self.id_matched_ppdnames = ppdnamelist
                ppdname = ppdnamelist[0]
                status = fit[ppdname]
            elif (self.dialog_mode == "ppd" and self.orig_ppd):
                attr = self.orig_ppd.findAttr("NickName")
                if not attr:
                    attr = self.orig_ppd.findAttr("ModelName")

                if attr and attr.value:
                    value = attr.value
                    if value.endswith (" (recommended)"):
                        value = value[:-14]

                    mfgmdl = cupshelpers.ppds.ppdMakeModelSplit (value)
                    (make, model) = mfgmdl

                    # Search for ppdname with that make-and-model
                    ppds = self.ppds.getInfoFromModel (make, model)
                    for ppd, info in ppds.items ():
                        if (_singleton (info.
                                        get ("ppd-make-and-model")) ==
                            value):
                            ppdname = ppd
                            break
                if ppdname:
                    status = "exact"
                else:
                    ppdname = 'raw'
                    self.ppd = ppdname
                    status = "generic"
            elif self.dialog_mode == "ppd":
                # Special CUPS names for a raw queue.
                ppdname = 'raw'
                self.ppd = ppdname
                status = "exact"
            else:
                (status, ppdname) = self.ppds.\
                    getPPDNameFromDeviceID ("Generic",
                                            "Printer",
                                            "Generic Printer",
                                            [],
                                            self.device.uri)
                status = "generic"
        except:
            nonfatalException ()

        if (ppdname and
            (not self.remotecupsqueue or self.dialog_mode == "ppd")):
            return self._installPrinterOrSearchForDriver (devid, ppdname, status, page_nr, step)

        # No operations are pending if reached.
        return self.INSTALL_RESULT_DONE

    def _installPrinterOrSearchForDriver (self, devid, ppdname, status, page_nr, step):
        try:
            if ppdname != "download":
                ppddict = self.ppds.getInfoFromPPDName (ppdname)
                make_model = _singleton (ppddict['ppd-make-and-model'])
                (make, model) = \
                    cupshelpers.ppds.ppdMakeModelSplit (make_model)
                self.auto_make = make
                self.auto_model = model
                self.auto_driver = ppdname
                self.fillDriverList(make, model)
            if ((status == "exact" or status == "exact-cmd") and \
                self.dialog_mode != "ppd"):
                self.exactdrivermatch = True
                if step == 0:
                    page_nr = self.PAGE_INSTALLABLE_OPTIONS;
            else:
                self.exactdrivermatch = False
                if (self.dialog_mode != "ppd" and
                    self.searchedfordriverpackages == False and
                    devid and len(devid) > 0 and
                    not (devid.find("MFG:generic;") >= 0 or
                         devid.find("MFG:Generic;") >= 0 or
                         devid.find("MFG:unknown") >= 0 or
                         devid.find("MFG:Unknown") >= 0 or
                         devid.find("MDL:unknown") >= 0 or
                         devid.find("MDL:Unknown") >= 0 or
                         devid.find("MFG:;") >= 0 or
                         devid.find("MDL:;") >= 0)):
                    # Query driver packages and PPD files on
                    # OpenPrinting
                    debugprint ("nextNPTab: No exact driver match, querying OpenPrinting")
                    debugprint ('nextNPTab: Searching for "%s"' % devid)
                    self.searchedfordriverpackages = True

                    self._searchdialog_canceled = False
                    fmt = _("Searching")
                    self._searchdialog = Gtk.MessageDialog (
                        parent=self.NewPrinterWindow,
                        modal=True,
                        destroy_with_parent=True,
                        message_type=Gtk.MessageType.INFO,
                        buttons=Gtk.ButtonsType.CANCEL,
                        text=fmt)

                    self._searchdialog.format_secondary_text (
                        _("Searching for drivers"))

                    self.opreq = OpenPrintingRequest ()
                    self._searchdialog.connect (
                        "response", self._searchdialog_response)
                    self._searchdialog.show_all ()

                    self.opreq_handlers = []
                    self.opreq_handlers.append (
                        self.opreq.connect (
                            'finished',
                            self.opreq_id_search_done))
                    self.opreq_handlers.append (
                        self.opreq.connect (
                            'error',
                            self.opreq_id_search_error))
                    self.opreq_user_search = False
                    self.opreq.searchPrinters (devid)

                    # Searching for drivers in OpenPrinting takes times, so
                    # let the caller know that it can't continue for now.
                    return self.INSTALL_RESULT_OPS_PENDING
        except:
            nonfatalException ()

        if (self.dialog_mode == "ppd" or
                (self.dialog_mode != "download_driver" and
                 not self.remotecupsqueue and page_nr != self.PAGE_DOWNLOAD_DRIVER)):
            self.fillMakeList()

        # No operations are pending if reached.
        return self.INSTALL_RESULT_DONE

    def _searchdialog_response (self, dialog, response):
        # Cancel clicked while performing openprinting search

        self.btnNPDownloadableDriverSearch.set_sensitive (True)
        self.btnNPDownloadableDriverSearch_label.set_text (_("Search"))

        self.installed_driver_files = []
        self.searchedfordriverpackages = True
        self.founddownloadabledrivers = False
        self.founddownloadableppd = False

        ready (self.NewPrinterWindow)

        # Cancel the openprinting request.
        GLib.idle_add (self.opreq.cancel)

    def opreq_id_search_done (self, opreq, printers, drivers):
        for handler in self.opreq_handlers:
            opreq.disconnect (handler)

        Gdk.threads_enter ()

        try:
            self.opreq_user_search = False
            self.opreq_handlers = None
            self.opreq = None
            self._searchdialog.hide ()
            self._searchdialog.destroy ()
            self._searchdialog = None

            # Check whether we have found something
            if len (printers) < 1:
                # No.
                ready (self.NewPrinterWindow)

                self.founddownloadabledrivers = False
                if self.dialog_mode == "download_driver":
                    self.on_NPCancel(None)
                else:
                    self.nextNPTab ()
            else:
                self.downloadable_printers = printers
                self.downloadable_drivers = drivers
                self.founddownloadabledrivers = True

                try:
                    self.NewPrinterWindow.show()
                    self.setNPButtons()
                    if not self.fillDownloadableDrivers():
                        ready (self.NewPrinterWindow)

                        self.founddownloadabledrivers = False
                        if self.dialog_mode == "download_driver":
                            self.on_NPCancel(None)
                        else:
                            self.nextNPTab ()
                    else:
                        if self.dialog_mode == "download_driver":
                            self.nextNPTab (step = 0)
                        else:
                            self.nextNPTab ()
                except:
                    nonfatalException ()
                    self.nextNPTab ()

        finally:
            Gdk.threads_leave ()

    def opreq_id_search_error (self, opreq, status, err):
        debugprint ("OpenPrinting request failed (%d): %s" % (status,
                                                              repr (err)))
        self.opreq_id_search_done (opreq, list(), dict())


    def _installSelectedDriverFromOpenPrinting(self):
        # Install package of the driver found on OpenPrinting
        treeview = self.tvNPDownloadableDrivers
        model, iter = treeview.get_selection ().get_selected ()
        driver = None
        if iter is not None:
            driver = model.get_value (iter, 1)
        if (driver is None or driver == 0 or 'packages' not in driver):
            return

        # Find the package name, repository, and fingerprint
        # and install the package
        if not self.installdriverpackage (driver) or \
                len(self.installed_driver_files) <= 0:
            return

        # We actually installed a package, delete the
        # PPD list to get it regenerated
        self.ppds = None
        if self.dialog_mode != "download_driver":
            if (not self.device.id and
                (not self.device.make_and_model or
                 self.device.make_and_model ==
                 "Unknown") and
                self.downloadable_driver_for_printer):
                self.device.make_and_model = \
                    self.downloadable_driver_for_printer

    def setNPButtons(self):
        nr = self.ntbkNewPrinter.get_current_page()

        if self.dialog_mode == "device":
            self.btnNPBack.hide()
            self.btnNPForward.hide()
            self.btnNPApply.show()
            try:
                uri = self.getDeviceURI ()
                valid = validDeviceURI (uri)
            except AttributeError:
                # No device selected yet.
                valid = False
            self.btnNPApply.set_sensitive (valid)
            return

        if self.dialog_mode == "ppd":
            if nr == self.PAGE_APPLY:
                if not self.installable_options:
                    # There are no installable options, so this is the
                    # last page.
                    debugprint ("No installable options")
                    self.btnNPForward.hide ()
                    self.btnNPApply.show ()
                else:
                    self.btnNPForward.show ()
                    self.btnNPApply.hide ()
                return
            elif nr == self.PAGE_INSTALLABLE_OPTIONS:
                self.btnNPForward.hide()
                self.btnNPApply.show()
                return
            else:
                self.btnNPForward.show()
                self.btnNPApply.hide()
            if nr == self.PAGE_SELECT_INSTALL_METHOD:
                self.btnNPBack.hide()
                self.btnNPForward.show()
                downloadable_selected = False
                if self.rbtnNPDownloadableDriverSearch.get_active ():
                    combobox = self.cmbNPDownloadableDriverFoundPrinters
                    iter = combobox.get_active_iter ()
                    if iter and combobox.get_model ().get_value (iter, 1):
                        downloadable_selected = True

                self.btnNPForward.set_sensitive(bool(
                        (self.rbtnNPFoomatic.get_active() and
                         self.tvNPMakes.get_cursor()[0] is not None) or
                        self.filechooserPPD.get_filename() or
                        downloadable_selected))
                return
            else:
                self.btnNPBack.show()

        if self.dialog_mode == "download_driver":
            self.btnNPBack.hide()
            self.btnNPForward.hide()
            self.btnNPApply.show()

            accepted = self._is_driver_license_accepted()
            self.btnNPApply.set_sensitive(accepted)
            return

        # class/printer

        if nr == self.PAGE_SELECT_DEVICE:
            valid = False
            try:
                uri = self.getDeviceURI ()
                valid = validDeviceURI (uri)
            except:
                nonfatalException ()
            self.btnNPForward.set_sensitive(valid)
            self.btnNPBack.hide ()
        else:
            self.btnNPBack.show()

        self.btnNPForward.show()
        self.btnNPApply.hide()

        if nr == self.PAGE_DESCRIBE_PRINTER:
            self.btnNPBack.show()
            if self.dialog_mode == "printer" or \
                    self.dialog_mode == "printer_with_uri":
                self.btnNPForward.hide()
                self.btnNPApply.show()
                self.btnNPApply.set_sensitive(
                    checkNPName(self.printers, self.entNPName.get_text()))
            if self.dialog_mode == "class":
                # This is the first page for the New Class dialog, so
                # hide the Back button.
                self.btnNPBack.hide ()
            if self.dialog_mode == "printer_with_uri" and \
                    (self.remotecupsqueue or \
                         (self.exactdrivermatch and \
                              not self.installable_options)):
                self.btnNPBack.hide ()
        if nr == self.PAGE_SELECT_INSTALL_METHOD:
            downloadable_selected = False
            if self.rbtnNPDownloadableDriverSearch.get_active ():
                combobox = self.cmbNPDownloadableDriverFoundPrinters
                iter = combobox.get_active_iter ()
                if iter and combobox.get_model ().get_value (iter, 1):
                    downloadable_selected = True

            self.btnNPForward.set_sensitive(bool(
                self.rbtnNPFoomatic.get_active() or
                self.filechooserPPD.get_filename() or
                downloadable_selected))
            # If we have an auto-detected printer for which there was no
            # driver found, we have already the URI and so this step is
            # not needed in the wizard. This makes manufacturer?PPD selection
            # the first step
            if self.dialog_mode == "printer_with_uri":
                self.btnNPBack.hide()
        if nr == self.PAGE_CHOOSE_DRIVER_FROM_DB:
            model, iter = self.tvNPDrivers.get_selection().get_selected()
            self.btnNPForward.set_sensitive(bool(iter))
        if nr == self.PAGE_CHOOSE_CLASS_MEMBERS:
            self.btnNPForward.hide()
            self.btnNPApply.show()
            self.btnNPApply.set_sensitive(
                bool(getCurrentClassMembers(self.tvNCMembers)))
        if nr == self.PAGE_INSTALLABLE_OPTIONS:
            if self.dialog_mode == "printer_with_uri" and \
                    self.exactdrivermatch:
                self.btnNPBack.hide ()
        if nr == self.PAGE_DOWNLOAD_DRIVER:
            accepted = self._is_driver_license_accepted()
            self.btnNPForward.set_sensitive(accepted)

    def _is_driver_license_accepted(self):
        current_page = self.ntbkNPDownloadableDriverProperties.get_current_page()
        if current_page == self.PAGE_SELECT_DEVICE:
            return self.rbtnNPDownloadLicenseYes.get_active ()

        treeview = self.tvNPDownloadableDrivers
        model, iter = treeview.get_selection ().get_selected ()
        if not iter:
            path, column = treeview.get_cursor()
            if path:
                iter = model.get_iter (path)
        return iter is not None

    def on_entNPName_changed(self, widget):
        # restrict
        text = widget.get_text()
        new_text = text
        new_text = new_text.replace("/", "")
        new_text = new_text.replace("#", "")
        new_text = new_text.replace(" ", "")
        if text!=new_text:
            widget.set_text(new_text)
        if self.dialog_mode == "printer":
            self.btnNPApply.set_sensitive(
                checkNPName(self.printers, new_text))
        else:
            self.btnNPForward.set_sensitive(
                checkNPName(self.printers, new_text))

    def fetchDevices(self, network=False, current_uri=None):
        debugprint ("fetchDevices")
        self.inc_spinner_task ()

        # Search for Bluetooth printers together with the network printers
        # as the Bluetooth search takes rather long time
        network_schemes = ["dnssd", "snmp", "driverless", "bjnp", "bluetooth"]
        error_handler = self.error_getting_devices
        if network == False:
            reply_handler = (lambda x, y:
                                 self.local_devices_reply (x, y,
                                                           current_uri))
            cupshelpers.getDevices (self.fetchDevices_conn,
                                    exclude_schemes=network_schemes,
                                    reply_handler=reply_handler,
                                    error_handler=error_handler)
        else:
            reply_handler = (lambda x, y:
                                 self.network_devices_reply (x, y,
                                                             current_uri))
            cupshelpers.getDevices (self.fetchDevices_conn,
                                    include_schemes=network_schemes,
                                    reply_handler=reply_handler,
                                    error_handler=error_handler)

    def error_getting_devices (self, conn, exc):
        # Just ignore the error.
        debugprint ("Error fetching devices: %s" % repr (exc))
        self.dec_spinner_task ()
        self.fetchDevices_conn._end_operation ()
        self.fetchDevices_conn.destroy ()
        self.fetchDevices_conn = None

    def local_devices_reply (self, conn, result, current_uri):
        self.dec_spinner_task ()

        # Now we've got the local devices, start a request for the
        # network devices.
        self.fetchDevices (network=True, current_uri=current_uri)

        # Add the local devices to the list.
        self.add_devices (result, current_uri)

    def network_devices_reply (self, conn, result, current_uri):
        self.fetchDevices_conn._end_operation ()
        self.fetchDevices_conn.destroy ()
        self.fetchDevices_conn = None

        # Add the network devices to the list.
        no_more = True
        need_resolving = {}
        for uri, device in result.items ():
            if uri.startswith ("dnssd://"):
                need_resolving[uri] = device
                no_more = False

        for uri in need_resolving.keys ():
            del result[uri]

        self.add_devices (result, current_uri, no_more=no_more)

        if len (need_resolving) > 0:
            resolver = dnssdresolve.DNSSDHostNamesResolver (need_resolving)
            self.inc_spinner_task ()
            resolver.resolve (reply_handler=lambda devices:
                                  self.dnssd_resolve_reply (current_uri,
                                                            devices))

        self.dec_spinner_task ()
        self.check_firewall ()

    def dnssd_resolve_reply (self, current_uri, devices):
        self.add_devices (devices, current_uri, no_more=True)
        self.dec_spinner_task ()
        self.check_firewall ()

    def get_hpfax_device_id(self, faxuri):
        new_environ = os.environ.copy()
        new_environ['LC_ALL'] = "C"
        new_environ['DISPLAY'] = ""
        args = ["hp-info", "-x", "-i", "-d" + faxuri]
        debugprint (faxuri + ": " + repr(args))
        try:
            p = subprocess.Popen (args, env=new_environ, close_fds=True,
                                  stdin=subprocess.DEVNULL,
                                  stdout=subprocess.PIPE,
                                  stderr=subprocess.PIPE)
            (stdout, stderr) = p.communicate ()
        except:
            # Problem executing command.
            return None

        faxtype = -1
        for line in stdout.decode ().split ("\n"):
            if line.find ("fax-type") == -1:
                continue
            res = re.search (r"(\d+)", line)
            if res:
                resg = res.groups()
                try:
                    faxtype = int(resg[0])
                except:
                    faxtype = -1
            if faxtype >= 0:
                break
        if faxtype <= 0:
            return None
        elif faxtype == 4:
            return 'MFG:HP;MDL:Fax 2;DES:HP Fax 2;'
        else:
            return 'MFG:HP;MDL:Fax;DES:HP Fax;'

    def get_hplip_scan_type_for_uri(self, uri):
        args = ["hp-query", "-k", "scan-type", "-d", uri]
        debugprint (uri + ": " + repr(args))
        try:
            p = subprocess.Popen (args, close_fds=True,
                                  stdin=subprocess.DEVNULL,
                                  stdout=subprocess.PIPE,
                                  stderr=subprocess.PIPE)
            (stdout, stderr) = p.communicate ()
            if p.returncode != 0:
                return None
        except:
            # Problem executing command.
            return None

        scan_type = stdout.decode ().strip ()
        fields = scan_type.split ("=", 1)
        if len (fields) < 2:
            return None

        value = fields[1]
        if value == '0':
            return None

        return value

    def get_hplip_uri_for_network_printer(self, host, mode):
        if mode == "print": mod = "-c"
        elif mode == "fax": mod = "-f"
        else: mod = "-c"
        args = ["hp-makeuri", mod, host]
        debugprint (host + ": " + repr(args))
        uri = None
        try:
            p = subprocess.Popen (args, close_fds=True,
                                  stdin=subprocess.DEVNULL,
                                  stdout=subprocess.PIPE,
                                  stderr=subprocess.PIPE)
            (stdout, stderr) = p.communicate ()
            if p.returncode != 0:
                return None
        except:
            # Problem executing command.
            return None

        uri = stdout.decode ().strip ()
        return uri

    def getNetworkPrinterMakeModel(self, host=None, device=None):
        """
        Try to determine the make and model for the currently selected
        network printer, and store this in the data structure for the
        printer.
        Returns (hostname or None, uri or None).
        """
        uri = None
        if device is None:
            device = self.device
        # Determine host name/IP
        if host is None:
            s = device.uri.find ("://")
            if s != -1:
                s += 3
                e = device.uri[s:].find (":")
                if e == -1: e = device.uri[s:].find ("/")
                if e == -1: e = device.uri[s:].find ("?")
                if e == -1: e = len (device.uri)
                host = device.uri[s:s+e]
        # Try to get make and model via SNMP
        if host:
            args = ["/usr/lib/cups/backend/snmp", host]
            debugprint (host + ": " + repr(args))
            stdout = None
            try:
                p = subprocess.Popen (args, close_fds=True,
                                      stdin=subprocess.DEVNULL,
                                      stdout=subprocess.PIPE,
                                      stderr=subprocess.PIPE)
                (stdout, stderr) = p.communicate ()
                if p.returncode != 0:
                    stdout = None
            except:
                # Problem executing command.
                pass

            if stdout is not None:
                try:
                    line = stdout.decode ('utf-8').strip ()
                except UnicodeDecodeError:
                    # Work-around snmp backend output encoded as iso-8859-1 (despire RFC 2571).
                    # If it's neither iso-8859-1, make a best guess by ignoring problematic bytes.
                    line = stdout.decode (encoding='iso-8859-1', errors='ignore').strip ()
                words = probe_printer.wordsep (line)
                n = len (words)
                if n < 4:
                    words.extend (['','','',''])
                    words = words[:4]
                    n = 4
                elif n > 6:
                    words = words[:6]
                    n = 6

                if n == 6:
                    (device_class, uri, make_and_model,
                     info, device_id, device_location) = words
                elif n == 5:
                    (device_class, uri, make_and_model,
                     info, device_id) = words
                elif n == 4:
                    (device_class, uri, make_and_model, info) = words

                if n == 4:
                    # No Device ID given so we'll have to make one
                    # up.
                    debugprint ("No Device ID from snmp backend")
                    (mk, md) = cupshelpers.ppds.\
                        ppdMakeModelSplit (make_and_model)
                    device.id = "MFG:%s;MDL:%s;DES:%s %s;" % (mk, md,
                                                              mk, md)
                else:
                    debugprint ("Got Device ID: %s" % device_id)
                    device.id = device_id

                device.id_dict = cupshelpers.parseDeviceID (device.id)
                device.make_and_model = make_and_model
                device.info = info
                if n == 6:
                    device.location = device_location

        return (host, uri)

    def fillDeviceTab(self, current_uri=None):
        self.device_selected = -1
        model = Gtk.TreeStore (str,                   # device-info
                               GObject.TYPE_PYOBJECT, # PhysicalDevice obj
                               bool)                  # Separator?
        other = cupshelpers.Device('', **{'device-info' :_("Enter URI")})
        physother = PhysicalDevice (other)
        self.devices = [physother]
        uri_iter = model.append (None, row=[physother.get_info (),
                                            physother, False])
        network_iter = model.append (None, row=[_("Network Printer"),
                                                None,
                                                False])
        network_dict = { 'device-class': 'network',
                         'device-info': _("Find Network Printer") }
        network = cupshelpers.Device ('network', **network_dict)
        find_nw_iter = model.append (network_iter,
                                     row=[network_dict['device-info'],
                                          PhysicalDevice (network), False])
        model.insert_after (network_iter, find_nw_iter, row=['', None, True])
        smbdev_dict = { 'device-class': 'network',
                        'device-info': _("Windows Printer via SAMBA") }
        smbdev = cupshelpers.Device ('smb', **smbdev_dict)
        find_smb_iter = model.append (network_iter,
                                     row=[smbdev_dict['device-info'],
                                          PhysicalDevice (smbdev), False])
        model.insert_after (find_nw_iter, find_smb_iter, row=['', None, True])
        self.devices_uri_iter = uri_iter
        self.devices_find_nw_iter = find_nw_iter
        self.devices_network_iter = network_iter
        self.devices_network_fetched = False
        self.tvNPDevices.set_model (model)
        self.entNPTDevice.set_text ('')
        self.expNPDeviceURIs.hide ()
        column = self.tvNPDevices.get_column (0)
        self.tvNPDevices.set_cursor (Gtk.TreePath(), column, False)

        self.current_uri = current_uri
        self.firewall = None
        debugprint ("Fetching devices")
        self.start_fetching_devices ()

    def on_firewall_read (self, data):
        f = self.firewall
        allowed = True
        try:
            ipp_allowed = f.check_ipp_client_allowed ()
            mdns_allowed = f.check_mdns_allowed ()
            allowed = (ipp_allowed and mdns_allowed)

            secondary_text = TEXT_adjust_firewall + "\n\n"
            if not ipp_allowed:
                secondary_text += ("- " +
                                   _("Allow all incoming IPP Browse packets") +
                                   "\n")
                f.add_service (firewallsettings.IPP_CLIENT_SERVICE)
            if not mdns_allowed:
                secondary_text += ("- " +
                                   _("Allow all incoming mDNS traffic") + "\n")
                f.add_service (firewallsettings.MDNS_SERVICE)

            if not allowed:
                debugprint ("Asking for permission to adjust firewall:\n%s" %
                            secondary_text)
                dialog = Gtk.MessageDialog (parent=self.NewPrinterWindow,
                                            modal=True, destroy_with_parent=True,
                                            message_type=Gtk.MessageType.QUESTION,
                                            buttons=Gtk.ButtonsType.NONE,
                                            text= _("Adjust Firewall"))
                dialog.format_secondary_markup (secondary_text)
                dialog.add_buttons (_("Do It Later"), Gtk.ResponseType.NO,
                                    _("Adjust Firewall"), Gtk.ResponseType.YES)
                dialog.connect ('response', self.adjust_firewall_response)
                dialog.show ()
        except (dbus.DBusException, Exception):
            nonfatalException ()

        if allowed:
            debugprint ("Firewall all OK, no changes needed")

    def adjust_firewall_response (self, dialog, response):
        dialog.destroy ()
        if response == Gtk.ResponseType.YES:
            ipp_server_allowed = self.firewall.check_ipp_server_allowed ()
            if not ipp_server_allowed:
                self.firewall.add_service (firewallsettings.IPP_SERVER_SERVICE)
            self.firewall.write ()

        debugprint ("Fetching network devices after firewall dialog response")
        self.fetchDevices_conn = asyncconn.Connection ()
        self.fetchDevices_conn._begin_operation (_("fetching device list"))
        self.fetchDevices (network=True)

    def start_fetching_devices (self):
        self.fetchDevices_conn = asyncconn.Connection ()
        self.fetchDevices_conn._begin_operation (_("fetching device list"))
        self.fetchDevices (network=False, current_uri=self.current_uri)
        del self.current_uri

    def add_devices (self, devices, current_uri, no_more=False):
        if current_uri:
            if current_uri in devices:
                current = devices.pop(current_uri)
            elif current_uri.replace (":9100", "") in devices:
                current_uri = current_uri.replace (":9100", "")
                current = devices.pop(current_uri)
            elif no_more:
                current = cupshelpers.Device (current_uri)
                current.info = "Current device"
            else:
                current_uri = None

        devices = list(devices.values())

        for device in devices:
            if device.type == "socket":
                # Remove default port to more easily find duplicate URIs
                device.uri = device.uri.replace (":9100", "")

        # Map generic URIs to something canonical
        def replace_generic (device):
            if device.uri == "hp:/no_device_found":
                device.uri = "hp"
            elif device.uri == "hpfax:/no_device_found":
                device.uri = "hpfax"
            return device

        devices = list(map (replace_generic, devices))

        # Mark duplicate URIs for deletion
        for i in range (len (devices) - 1):
            for j in range (i + 1, len (devices)):
                device1 = devices[i]
                device2 = devices[j]
                if device1.uri == "delete" or device2.uri == "delete":
                    continue
                if device1.uri == device2.uri:
                    # Keep the one with the longer (better) device ID
                    if (not device1.id):
                        device1.uri = "delete"
                    elif (not device2.id):
                        device2.uri = "delete"
                    elif (len (device1.id) < len (device2.id)):
                        device1.uri = "delete"
                    else:
                        device2.uri = "delete"
        devices = [x for x in devices if x.uri not in ("hp", "hpfax",
                                                       "hal", "beh", "smb", 
                                                       "scsi", "http", "bjnp",
                                                       "delete")]
        newdevices = []
        for device in devices:
            debugprint("Adding device with URI %s" % device.uri)
            if (hasattr (device, 'address')):
                debugprint("   Device address %s" % device.address)
            if (hasattr (device, 'hostname')):
                debugprint("   Device host name %s" % device.hostname)
            physicaldevice = PhysicalDevice (device)
            debugprint ("   Created physical device %s" % repr(physicaldevice))
            try:
                i = self.devices.index (physicaldevice)
                debugprint ("   Physical device %d is the same printer" % i)
                self.devices[i].add_device (device)
                debugprint ("   New physical device %s is same as physical device %d: %s" %
                            (repr(physicaldevice), i, repr(self.devices[i])))
                debugprint ("   Joining devices")
            except ValueError:
                self.devices.append (physicaldevice)
                newdevices.append (physicaldevice)
                debugprint ("   Physical device %s is a completely new device" % repr(physicaldevice))

        self.devices.sort()
        if current_uri:
            current_device = PhysicalDevice (current)
            try:
                i = self.devices.index (current_device)
                self.devices[i].add_device (current)
                current_device = self.devices[i]
            except ValueError:
                self.devices.append (current_device)
                newdevices.append (current_device)
        else:
            current_device = None

        model = self.tvNPDevices.get_model ()

        network_iter = self.devices_network_iter
        find_nw_iter = self.devices_find_nw_iter
        for newdevice in newdevices:
            device = None
            try:
                i = self.devices.index (newdevice)
                device = self.devices[i]
            except ValueError:
                debugprint("ERROR: Cannot identify new physical device with its entry in the device list (%s)" %
                           repr(newdevice))
                continue
            devs = device.get_devices ()
            network = devs[0].device_class == 'network'
            info = device.get_info ()
            if device == current_device:
                info += _(" (Current)")
            row=[info, device, False]
            if network:
                if devs[0].uri != devs[0].type:
                    # An actual network printer device.  Put this at the top.
                    iter = model.insert_before (network_iter, find_nw_iter,
                                                row=row)

                    # If this is the currently selected device we need
                    # to expand the "Network Printer" row so that it
                    # is visible.
                    if device == current_device:
                        network_path = model.get_path (network_iter)
                        self.tvNPDevices.expand_row (network_path, False)
                else:
                    # Just a method of finding one.
                    iter = model.append (network_iter, row=row)
            else:
                # Insert this local device in order.
                network_path = model.get_path (network_iter)
                iter = model.get_iter_first ()
                while model.get_path (iter) != network_path:
                    physdev = model.get_value (iter, 1)
                    if physdev > device:
                        break

                    iter = model.iter_next (iter)

                iter = model.insert_before (None, iter, row=row)

            if device == current_device:
                device_select_path = model.get_path (iter)
                self.tvNPDevices.scroll_to_cell (device_select_path,
                                                 row_align=0.5)
                column = self.tvNPDevices.get_column (0)
                self.tvNPDevices.set_cursor (device_select_path, column, False)

        connection_select_path = 0
        if current_uri:
            model = self.tvNPDeviceURIs.get_model ()
            iter = model.get_iter_first ()
            i = 0
            while iter:
                dev = model.get_value (iter, 1)
                if current_uri == dev.uri:
                    connection_select_path = i
                    break

                iter = model.iter_next (iter)
                i += 1
        elif not self.device_selected:
            # Select the device.
            column = self.tvNPDevices.get_column (0)
            self.tvNPDevices.set_cursor (Gtk.TreePath(), column, False)

            # Select the connection.
            column = self.tvNPDeviceURIs.get_column (0)
            self.tvNPDeviceURIs.set_cursor (connection_select_path, column, False)

    ## SMB browsing

    def install_python3_smbc_if_needed (self):
        global PYSMB_AVAILABLE
        global pysmb # Make the import of pysmb globally available
        # Does the SMB client library  need to be installed?
        if not PYSMB_AVAILABLE:
            debugprint ("No SMB client library present so attempting install")
            try:
                pk = installpackage.PackageKit ()
                # The following call means a blocking, synchronous, D-Bus call
                pk.InstallPackageName (0, 0, "python3-smbc")
                try:
                    import pysmb
                    PYSMB_AVAILABLE=True
                    debugprint ("SMB client successfully installed and set up.")
                except:
                    debugprint ("SMB client setup failed.")
            except:
                debugprint ("Error during installation/setup of SMB client.")
        return PYSMB_AVAILABLE

    def browse_smb_hosts(self):
        """Initialise the SMB tree store."""
        store = self.smb_store
        store.clear ()
        busy(self.SMBBrowseDialog)
        class X:
            pass
        dummy = X()
        dummy.smbc_type = pysmb.smbc.PRINTER_SHARE
        dummy.name = _('Scanning...')
        dummy.comment = ''
        store.append(None, [dummy])
        while Gtk.events_pending ():
            Gtk.main_iteration ()

        debug = 0
        if get_debugging ():
            debug = 10
        smbc_auth = pysmb.AuthContext (self.SMBBrowseDialog)
        ctx = pysmb.smbc.Context (debug=debug,
                                  auth_fn=smbc_auth.callback)
        entries = None
        try:
            while smbc_auth.perform_authentication () > 0:
                try:
                    entries = ctx.opendir ("smb://").getdents ()
                except Exception as e:
                    smbc_auth.failed (e)
        except RuntimeError as e:
            (e, s) = e.args
            if e != errno.ENOENT:
                debugprint ("Runtime error: %s" % repr ((e, s)))
        except:
            nonfatalException ()

        store.clear ()
        if entries:
            for entry in entries:
                if entry.smbc_type in [pysmb.smbc.WORKGROUP,
                                       pysmb.smbc.SERVER]:
                    iter = store.append (None, [entry])
                    i = store.append (iter)

        specified_uri = SMBURI (uri=self.entSMBURI.get_text ())
        (group, host, share, user, password) = specified_uri.separate ()
        if len (host) > 0:
            # The user has specified a server before clicking Browse.
            # Append the server as a top-level entry.
            class FakeEntry:
                pass
            toplevel = FakeEntry ()
            toplevel.smbc_type = pysmb.smbc.SERVER
            toplevel.name = host
            toplevel.comment = ''
            iter = store.append (None, [toplevel])
            i = store.append (iter)

            # Now expand it.
            path = store.get_path (iter)
            self.tvSMBBrowser.expand_row (path, 0)

        ready(self.SMBBrowseDialog)

        if store.get_iter_first () is None:
            self.SMBBrowseDialog.hide ()
            show_info_dialog (_("No Print Shares"),
                              _("There were no print shares found.  "
                                "Please check that the Samba service is "
                                "marked as trusted in your firewall "
                                "configuration."),
                              parent=self.NewPrinterWindow)

    def smb_select_function (self, selection, model, path, path_selected, data):
        """Don't allow this path to be selected unless it is a leaf."""
        iter = self.smb_store.get_iter (path)
        return not self.smb_store.iter_has_child (iter)

    def smbbrowser_cell_share (self, column, cell, model, iter, data):
        entry = model.get_value (iter, 0)
        share = ''
        if entry is not None:
            share = entry.name
        cell.set_property ('text', share)

    def smbbrowser_cell_comment (self, column, cell, model, iter, data):
        entry = model.get_value (iter, 0)
        comment = ''
        if entry is not None:
            comment = entry.comment
        cell.set_property ('text', comment)

    def on_tvSMBBrowser_row_activated (self, view, path, column):
        """Handle double-clicks in the SMB tree view."""
        store = self.smb_store
        iter = store.get_iter (path)
        entry = store.get_value (iter, 0)
        if entry and entry.smbc_type == pysmb.smbc.PRINTER_SHARE:
            # This is a share, not a host.
            self.btnSMBBrowseOk.clicked ()
            return

        if view.row_expanded (path):
            view.collapse_row (path)
        else:
            self.on_tvSMBBrowser_row_expanded (view, iter, path)

    def on_tvSMBBrowser_row_expanded (self, view, iter, path):
        """Handler for expanding a row in the SMB tree view."""
        model = view.get_model ()
        entry = model.get_value (iter, 0)
        if entry is None:
            return

        if entry.smbc_type == pysmb.smbc.WORKGROUP:
            # Workgroup
            # Be careful though: if there is a server with the
            # same name as the workgroup we will get a list of its
            # shares, not the workgroup's servers.
            try:
                if self.expanding_row:
                    return
            except:
                self.expanding_row = 1

            busy (self.SMBBrowseDialog)
            uri = "smb://%s/" % entry.name
            debug = 0
            if get_debugging ():
                debug = 10
            smbc_auth = pysmb.AuthContext (self.SMBBrowseDialog)
            ctx = pysmb.smbc.Context (debug=debug,
                                      auth_fn=smbc_auth.callback)
            entries = []
            try:
                while smbc_auth.perform_authentication () > 0:
                    try:
                        entries = ctx.opendir (uri).getdents ()
                    except Exception as e:
                        smbc_auth.failed (e)
            except RuntimeError as e:
                (e, s) = e.args
                if e != errno.ENOENT:
                    debugprint ("Runtime error: %s" % repr ((e, s)))
            except:
                nonfatalException()

            while model.iter_has_child (iter):
                i = model.iter_nth_child (iter, 0)
                model.remove (i)

            for entry in entries:
                if entry.smbc_type in [pysmb.smbc.SERVER,
                                       pysmb.smbc.PRINTER_SHARE]:
                    i = model.append (iter, [entry])
                if entry.smbc_type == pysmb.smbc.SERVER:
                    n = model.append (i)

            view.expand_row (path, 0)
            del self.expanding_row
            ready (self.SMBBrowseDialog)

        elif entry.smbc_type == pysmb.smbc.SERVER:
            # Server
            try:
                if self.expanding_row:
                    return
            except:
                self.expanding_row = 1

            busy (self.SMBBrowseDialog)
            uri = "smb://%s/" % entry.name
            debug = 0
            if get_debugging ():
                debug = 10
            smbc_auth = pysmb.AuthContext (self.SMBBrowseDialog)
            ctx = pysmb.smbc.Context (debug=debug,
                                      auth_fn=smbc_auth.callback)
            shares = []
            try:
                while smbc_auth.perform_authentication () > 0:
                    try:
                        shares = ctx.opendir (uri).getdents ()
                    except Exception as e:
                        smbc_auth.failed (e)
            except RuntimeError as e:
                (e, s) = e.args
                if e != errno.EACCES and e != errno.EPERM:
                    debugprint ("Runtime error: %s" % repr ((e, s)))
            except:
                nonfatalException()

            while model.iter_has_child (iter):
                i = model.iter_nth_child (iter, 0)
                model.remove (i)

            for share in shares:
                if share.smbc_type == pysmb.smbc.PRINTER_SHARE:
                    i = model.append (iter, [share])
                    debugprint (repr (share))

            view.expand_row (path, 0)
            del self.expanding_row
            ready (self.SMBBrowseDialog)

    def set_btnSMBVerify_sensitivity (self, on):
        self.btnSMBVerify.set_sensitive (on)

    def on_entSMBURI_changed (self, ent):
        allowed_chars = string.ascii_letters+string.digits+'_-./:%[]@'
        self.entry_changed(ent, allowed_chars)
        uri = ent.get_text ()
        (group, host, share, user, password) = SMBURI (uri=uri).separate ()
        if user:
            self.entSMBUsername.set_text (user)
        if password:
            self.entSMBPassword.set_text (password)
        if user or password:
            uri = SMBURI (group=group, host=host, share=share).get_uri ()
            ent.set_text(uri)
            self.rbtnSMBAuthSet.set_active(True)
        elif self.entSMBUsername.get_text () == '':
            self.rbtnSMBAuthPrompt.set_active(True)

        self.set_btnSMBVerify_sensitivity (bool(uri))
        self.setNPButtons ()

    def on_tvSMBBrowser_cursor_changed(self, widget):
        selection = self.tvSMBBrowser.get_selection()
        if selection is None:
            return

        store, iter = selection.get_selected()
        is_share = False
        if iter:
            entry = store.get_value (iter, 0)
            if entry:
                is_share = entry.smbc_type == pysmb.smbc.PRINTER_SHARE

        self.btnSMBBrowseOk.set_sensitive(iter is not None and is_share)

    def on_btnSMBBrowse_clicked(self, button):
        """Check whether the needed SMB client library is available and"""
        """install it if needed"""
        if not self.install_python3_smbc_if_needed(): return

        self.btnSMBBrowseOk.set_sensitive(False)

        try:
            # Note: we do the browsing from *this* machine, regardless
            # of which CUPS server we are connected to.
            f = firewallsettings.FirewallD ()
            if not f.running:
                f = firewallsettings.SystemConfigFirewall ()
            allowed = f.check_samba_client_allowed ()
            secondary_text = TEXT_adjust_firewall + "\n\n"
            if not allowed:
                dialog = Gtk.MessageDialog (parent=self.NewPrinterWindow,
                                            modal=True, destroy_with_parent=True,
                                            message_type=Gtk.MessageType.QUESTION,
                                            buttons=Gtk.ButtonsType.NONE,
                                            text=_("Adjust Firewall"))
                secondary_text += ("- " +
                                   _("Allow all incoming SMB/CIFS "
                                     "browse packets"))
                dialog.format_secondary_markup (secondary_text)
                dialog.add_buttons (_("Do It Later"), Gtk.ResponseType.NO,
                                    _("Adjust Firewall"), Gtk.ResponseType.YES)
                response = dialog.run ()
                dialog.destroy ()

                if response == Gtk.ResponseType.YES:
                    f.add_service (firewallsettings.SAMBA_CLIENT_SERVICE)
                    f.write ()
        except (dbus.DBusException, Exception):
            nonfatalException ()

        self.SMBBrowseDialog.show()
        self.browse_smb_hosts()

    def on_btnSMBBrowseOk_clicked(self, button):
        store, iter = self.tvSMBBrowser.get_selection().get_selected()
        is_share = False
        if iter:
            entry = store.get_value (iter, 0)
            if entry:
                is_share = entry.smbc_type == pysmb.smbc.PRINTER_SHARE

        if not iter or not is_share:
            self.SMBBrowseDialog.hide()
            return

        parent_iter = store.iter_parent (iter)
        domain_iter = store.iter_parent (parent_iter)
        share = store.get_value (iter, 0)
        host = store.get_value (parent_iter, 0)
        if domain_iter:
            group = store.get_value (domain_iter, 0).name
        else:
            group = ''
        uri = SMBURI (group=group,
                      host=host.name,
                      share=share.name).get_uri ()

        self.entSMBUsername.set_text ('')
        self.entSMBPassword.set_text ('')
        self.entSMBURI.set_text (uri)

        self.SMBBrowseDialog.hide()

    def on_btnSMBBrowseCancel_clicked(self, widget, *args):
        self.SMBBrowseDialog.hide()

    def on_btnSMBBrowseRefresh_clicked(self, button):
        self.browse_smb_hosts()

    def on_rbtnSMBAuthSet_toggled(self, widget):
        self.tblSMBAuth.set_sensitive(widget.get_active())

    def on_btnSMBVerify_clicked(self, button):
        """Check whether the needed SMB client library is available and"""
        """install it if needed"""
        if not self.install_python3_smbc_if_needed(): return

        uri = self.entSMBURI.get_text ()
        (group, host, share, u, p) = SMBURI (uri=uri).separate ()
        user = ''
        passwd = ''
        reason = None
        auth_set = self.rbtnSMBAuthSet.get_active()
        if auth_set:
            user = self.entSMBUsername.get_text ()
            passwd = self.entSMBPassword.get_text ()

        accessible = False
        canceled = False
        busy (self.NewPrinterWindow)
        try:
            debug = 0
            if get_debugging ():
                debug = 10

            if auth_set:
                # No prompting.
                def do_auth (svr, shr, wg, un, pw):
                    return (group, user, passwd)
                ctx = pysmb.smbc.Context (debug=debug, auth_fn=do_auth)
                try:
                    ctx.optionUseKerberos = True
                except AttributeError:
                    # requires pysmbc >= 1.0.12
                    pass

                f = ctx.open ("smb://%s/%s" % (host, share),
                              os.O_RDWR, 0o777)
                accessible = True
            else:
                # May need to prompt.
                smbc_auth = pysmb.AuthContext (self.NewPrinterWindow,
                                               workgroup=group,
                                               user=user,
                                               passwd=passwd)
                ctx = pysmb.smbc.Context (debug=debug,
                                          auth_fn=smbc_auth.callback)
                while smbc_auth.perform_authentication () > 0:
                    try:
                        f = ctx.open ("smb://%s/%s" % (host, share),
                                      os.O_RDWR, 0o777)
                        accessible = True
                    except Exception as e:
                        smbc_auth.failed (e)

                if not accessible:
                    canceled = True
        except RuntimeError as e:
            (e, s) = e.args
            debugprint ("Error accessing share: %s" % repr ((e, s)))
            reason = s
        except:
            nonfatalException()
        ready (self.NewPrinterWindow)

        if accessible:
            show_info_dialog (_("Print Share Verified"),
                              _("This print share is accessible."),
                              parent=self.NewPrinterWindow)
            return

        if not canceled:
            text = _("This print share is not accessible.")
            if reason:
                text = reason
            show_error_dialog (_("Print Share Inaccessible"), text,
                               parent=self.NewPrinterWindow)

    def entry_changed(self, entry, allowed_chars):
        "Remove all chars from entry's text that are not in allowed_chars."
        origtext = entry.get_text()
        new_text = origtext
        for char in origtext:
            if char not in allowed_chars:
                new_text = new_text.replace(char, "")
                debugprint ("removed disallowed character %s" % repr (char))
        if origtext!=new_text:
            entry.set_text(new_text)

    def on_entNPTDevice_changed(self, ent):
        allowed_chars = string.ascii_letters+string.digits+'_-./:%[]()@?=&'
        self.entry_changed(ent, allowed_chars)
        self.setNPButtons()

    def on_entNPTJetDirectHostname_changed(self, ent):
        allowed_chars = string.ascii_letters+string.digits+'_-.:%[]'
        self.entry_changed(ent, allowed_chars)
        self.setNPButtons()

    def on_entNPTJetDirectPort_changed(self, ent):
        self.entry_changed(ent, string.digits)
        self.setNPButtons()

    def on_expNPDeviceURIs_expanded (self, widget, UNUSED):
        # When the expanded is not expanded we want its packing to be
        # 'expand = false' so that it aligns at the bottom (it packs
        # to the end of its vbox).  But when it is expanded we'd like
        # it to expand with the window.
        #
        # Adjust its 'expand' packing state depending on whether the
        # widget is expanded.

        parent = widget.get_parent ()
        (expand, fill,
         padding, pack_type) = parent.query_child_packing (widget)
        expand = widget.get_expanded ()
        parent.set_child_packing (widget, expand, fill,
                                  padding, pack_type)

    def device_row_separator_fn (self, model, iter, data):
        return model.get_value (iter, 2)

    def device_row_activated (self, view, path, column):
        if view.row_expanded (path):
            view.collapse_row (path)
        else:
            view.expand_row (path, False)

    def check_firewall (self):
        view = self.tvNPDevices
        model = view.get_model ()
        if not model:
            return

        network_path = model.get_path (self.devices_network_iter)
        if not view.row_expanded (network_path):
            # 'Network' not expanded
            return

        if self.firewall is not None:
            # Already checked
            return

        if self.spinner_count > 0:
            # Still discovering devices?
            debugprint ("Skipping firewall adjustment: "
                        "discovery in progress")
            return

        # Any network printers found?
        for physdev in self.devices:
            for device in physdev.get_devices ():
                if (device.device_class == 'network' and
                    device.uri != device.type):
                    debugprint ("Skipping firewall adjustment: "
                                "network printers found")
                    return

        # If not, ask about the firewall
        try:
            if (self._host == 'localhost' or
                self._host[0] == '/'):
                self.firewall = firewallsettings.FirewallD ()
                if not self.firewall.running:
                    self.firewall = firewallsettings.SystemConfigFirewall ()

                debugprint ("Examining firewall")
                self.firewall.read (reply_handler=self.on_firewall_read)
        except (dbus.DBusException, Exception):
            nonfatalException ()

    def device_row_expanded (self, view, iter, path):
        model = view.get_model ()
        if not model or not iter:
            return

        network_path = model.get_path (self.devices_network_iter)
        if path == network_path:
            self.check_firewall ()

    def device_select_function (self, selection, model, path, *UNUSED):
        """
        Allow this path to be selected as long as there
        is a device associated with it.  Otherwise, expand or collapse it.
        """
        model = self.tvNPDevices.get_model ()
        iter = model.get_iter (path)
        if model.get_value (iter, 1) is not None:
            return True

        self.device_row_activated (self.tvNPDevices, path, None)
        return False

    def on_tvNPDevices_cursor_changed(self, widget):
        # Reset previous driver search result
        self.installed_driver_files = []
        self.searchedfordriverpackages = False
        self.founddownloadabledrivers = False
        self.founddownloadableppd = False
        self.downloadable_printers = []

        self.device_selected += 1
        path, column = widget.get_cursor ()
        if path is None:
            return

        model = widget.get_model ()
        iter = model.get_iter (path)
        physicaldevice = model.get_value (iter, 1)
        if physicaldevice is None:
            return
        show_uris = True
        for device in physicaldevice.get_devices ():
            if device.type == "parallel":
                device.menuentry = _("Parallel Port")
            elif device.type == "serial":
                device.menuentry = _("Serial Port")
            elif device.type == "usb":
                if (hasattr(device, "uri") and
                    device.uri.lower().find("fax") > -1):
                    device.menuentry = _("Fax") + " - " + _("USB")
                else:
                    device.menuentry = _("USB")
            elif device.type == "bluetooth":
                device.menuentry = _("Bluetooth")
            elif device.type == "hp":
                device.menuentry = _("HP Linux Imaging and Printing (HPLIP)")
            elif device.type == "hpfax":
                device.menuentry = _("Fax") + " - " + \
                    _("HP Linux Imaging and Printing (HPLIP)")
            elif device.type == "hal":
                device.menuentry = _("Hardware Abstraction Layer (HAL)")
            elif device.type == "socket":
                device.menuentry = _("AppSocket/HP JetDirect")
            elif device.type == "lpd":
                (scheme, rest) = urllib.parse.splittype (device.uri)
                (hostport, rest) = urllib.parse.splithost (rest)
                (queue, rest) = urllib.parse.splitquery (rest)
                if queue != '':
                    if queue[0] == '/':
                        queue = queue[1:]

                    device.menuentry = (_("LPD/LPR queue '%s'")
                                        % queue)
                else:
                    device.menuentry = _("LPD/LPR queue")

            elif device.type == "smb":
                device.menuentry = _("Windows Printer via SAMBA")
            elif device.type == "ipp":
                (scheme, rest) = urllib.parse.splittype (device.uri)
                (hostport, rest) = urllib.parse.splithost (rest)
                (queue, rest) = urllib.parse.splitquery (rest)
                if queue != '':
                    if queue[0] == '/':
                        queue = queue[1:]
                    if queue.startswith("printers/"):
                        queue = queue[9:]
                if 'driverless' in device.info:
                    drvless = "Driverless "
                    device.driverless = True
                else:
                    drvless = ""
                if queue != '':
                    device.menuentry = (("%s" + _("IPP") + " (%s)") %
                                        (drvless, queue))
                else:
                    device.menuentry = (("%s" + _("IPP")) % drvless)
            elif device.type == "http" or device.type == "https":
                device.menuentry = _("HTTP")
            elif device.type == "dnssd" or device.type == "mdns":
                (scheme, rest) = urllib.parse.splittype (device.uri)
                (name, rest) = urllib.parse.splithost (rest)
                (cupsqueue, rest) = urllib.parse.splitquery (rest)
                if cupsqueue != '' and cupsqueue[0] == '/':
                    cupsqueue = cupsqueue[1:]
                if cupsqueue == 'cups':
                    device.menuentry = _("Remote CUPS printer via DNS-SD")
                    if device.info != '':
                        device.menuentry += " (%s)" % device.info
                else:
                    protocol = None
                    if name.find("._ipp") != -1:
                        protocol = "IPP"
                    elif name.find("._printer") != -1:
                        protocol = "LPD"
                    elif name.find("._pdl-datastream") != -1:
                        protocol = "AppSocket/JetDirect"
                    if protocol is not None:
                        device.menuentry = (_("%s network printer via DNS-SD")
                                            % protocol)
                    else:
                        device.menuentry = \
                            _("Network printer via DNS-SD")
            else:
                show_uris = False
                device.menuentry = device.uri

        model = Gtk.ListStore (str,                    # URI description
                               GObject.TYPE_PYOBJECT)  # cupshelpers.Device
        self.tvNPDeviceURIs.set_model (model)

        # If this is a network device, check whether HPLIP can drive it.
        if getattr (physicaldevice, 'checked_hplip', None) != True:
            hp_drivable = False
            hp_scannable = False
            is_network = False
            remotecups = False
            host = None
            device_dict = { 'device-class': 'network' }
            if physicaldevice._network_host:
                host = physicaldevice._network_host
            for device in physicaldevice.get_devices ():
                if device.type == "hp":
                    # We already know that HPLIP can drive this device.
                    hp_drivable = True

                    # But can we scan using it?
                    if self.get_hplip_scan_type_for_uri (device.uri):
                        hp_scannable = True

                    break
                elif device.type in ["socket", "lpd", "ipp", "dnssd", "mdns"]:
                    # This is a network printer.
                    if host is None and device.type in ["socket", "lpd", "ipp"]:
                        (scheme, rest) = urllib.parse.splittype (device.uri)
                        (hostport, rest) = urllib.parse.splithost (rest)
                        if hostport is not None:
                            (host, port) = urllib.parse.splitport (hostport)
                    if host:
                        is_network = True
                        remotecups = ((device.uri.startswith('dnssd:') or \
                                       device.uri.startswith('mdns:')) and \
                                      device.uri.endswith('/cups'))
                        if (not device.make_and_model or \
                            device.make_and_model == "Unknown") and not \
                           remotecups:
                            self.getNetworkPrinterMakeModel(host=host,
                                                            device=device)
                        device_dict['device-info'] = device.info
                        device_dict['device-make-and-model'] = (device.
                                                                make_and_model)
                        device_dict['device-id'] = device.id
                        device_dict['device-location'] = device.location

            if not hp_drivable and is_network and not remotecups and \
               (not device.make_and_model or \
                device.make_and_model == "Unknown" or \
                device.make_and_model.lower ().startswith ("hp") or \
                device.make_and_model.lower ().startswith ("hewlett")):
                if (hasattr (physicaldevice, "dnssd_hostname") and \
                    physicaldevice.dnssd_hostname):
                    hpliphost = physicaldevice.dnssd_hostname
                else:
                    hpliphost = host
                hplipuri = self.get_hplip_uri_for_network_printer (hpliphost,
                                                                   "print")
                if hplipuri:
                    dev = cupshelpers.Device (hplipuri, **device_dict)
                    dev.menuentry = "HP Linux Imaging and Printing (HPLIP)"
                    physicaldevice.add_device (dev)

                    # Can we scan using this device?
                    if self.get_hplip_scan_type_for_uri (device.uri):
                        hp_scannable = True

                    # Now check to see if we can also send faxes using
                    # this device.
                    faxuri = self.get_hplip_uri_for_network_printer (hpliphost,
                                                                     "fax")
                    if faxuri:
                        faxdevid = self.get_hpfax_device_id (faxuri)
                        device_dict['device-id'] = faxdevid
                        device_dict['device-info'] = _("Fax")
                        faxdev = cupshelpers.Device (faxuri, **device_dict)
                        faxdev.menuentry = _("Fax") + " - " + \
                            "HP Linux Imaging and Printing (HPLIP)"
                        physicaldevice.add_device (faxdev)

            if hp_scannable:
                physicaldevice.hp_scannable = True
            physicaldevice.checked_hplip = True

        device.hp_scannable = getattr (physicaldevice, 'hp_scannable', None)

        # Fill the list of connections for this device.
        n = 0
        for device in physicaldevice.get_devices ():
            model.append ((device.menuentry, device))
            n += 1
        column = self.tvNPDeviceURIs.get_column (0)
        self.tvNPDeviceURIs.set_cursor (Gtk.TreePath(), column, False)
        if show_uris:
            self.expNPDeviceURIs.show_all ()
        else:
            self.expNPDeviceURIs.hide ()

    def on_tvNPDeviceURIs_cursor_changed(self, widget):
        path, column = widget.get_cursor ()
        if path is None:
            return

        model = widget.get_model ()
        iter = model.get_iter (path)
        device = model.get_value(iter, 1)
        self.device = device
        self.lblNPDeviceDescription.set_text ('')
        page = self.new_printer_device_tabs.get (device.type, self.PAGE_SELECT_DEVICE)
        self.ntbkNPType.set_current_page(page)

        debugprint("Selected connection type. URI: %s" % device.uri)
        location = ''
        type = device.type
        url = device.uri.split(":", 1)[-1]
        if page == self.PAGE_DESCRIBE_PRINTER:
            # This is the "no options" page, with just a label to describe
            # the selected device.
            if device.type == "parallel":
                text = _("A printer connected to the parallel port.")
            elif device.type == "usb":
                if (hasattr(device, "uri") and
                    device.uri.lower().find("fax") > -1):
                    device.menuentry = _("Fax") + " - " + _("USB")
                    text = _("A fax machine or the fax function "
                             "of a multi-function device connected "
                             "to a USB port.")
                else:
                    text = _("A printer connected to a USB port.")
            elif device.type == "bluetooth":
                text = _("A printer connected via Bluetooth.")
            elif device.type == "hp":
                text = _("HPLIP software driving a printer, "
                         "or the printer function of a multi-function device.")
            elif device.type == "hpfax":
                text = _("HPLIP software driving a fax machine, "
                         "or the fax function of a multi-function device.")
            elif device.type == "hal":
                text = _("Local printer detected by the "
                         "Hardware Abstraction Layer (HAL).")
            elif device.type == "dnssd" or device.type == "mdns":
                (scheme, rest) = urllib.parse.splittype (device.uri)
                (name, rest) = urllib.parse.splithost (rest)
                (cupsqueue, rest) = urllib.parse.splitquery (rest)
                if cupsqueue != '' and cupsqueue[0] == '/':
                    cupsqueue = cupsqueue[1:]
                if cupsqueue == 'cups':
                    text = _("Remote CUPS printer via DNS-SD")
                else:
                    protocol = None
                    if name.find("._ipp") != -1:
                        protocol = "IPP"
                    elif name.find("._printer") != -1:
                        protocol = "LPD"
                    elif name.find("._pdl-datastream") != -1:
                        protocol = "AppSocket/JetDirect"
                    if protocol is not None:
                        text = _("%s network printer via DNS-SD") % protocol
                    else:
                        text = _("Network printer via DNS-SD")
            else:
                text = device.uri

            self.lblNPDeviceDescription.set_text (text)
        elif device.type=="socket":
            (scheme, rest) = urllib.parse.splittype (device.uri)
            host = ''
            port = 9100
            if scheme == "socket":
                (hostport, rest) = urllib.parse.splithost (rest)
                (host, port) = urllib.parse.splitnport (hostport, defport=port)
                debugprint ("socket: host is %s, port is %s" % (host,
                                                                repr (port)))
                if device.location != '':
                    location = device.location
                else:
                    location = host
            self.entNPTJetDirectHostname.set_text (host)
            self.entNPTJetDirectPort.set_text (str (port))
        elif device.type=="serial":
            if not device.is_class:
                parts = device.uri.split("?", 1)
                if len (parts) > 1:
                    options = parts[1]
                else:
                    options = ""

                options = options.split("+")
                option_dict = {}
                for option in options:
                    name, value = option.split("=")
                    option_dict[name] = value

                for widget, name in (
                    (self.cmbNPTSerialBaud, "baud"),
                    (self.cmbNPTSerialBits, "bits"),
                    (self.cmbNPTSerialParity, "parity"),
                    (self.cmbNPTSerialFlow, "flow")):
                    if name in option_dict: # option given in URI?
                        model = widget.get_model()
                        iter = model.get_iter_first()
                        nr = 0
                        while iter:
                            value = model.get(iter,1)[0]
                            if str (value) == str (option_dict[name]):
                                break
                            iter = model.iter_next(iter)
                            nr += 1

                        if iter:
                            widget.set_active(nr)
                        else:
                            widget.set_active (0)
                    else:
                        widget.set_active(0)

        # XXX FILL TABS FOR VALID DEVICE URIs
        elif device.type=="lpd":
            self.entNPTLpdHost.set_text ('')
            self.entNPTLpdQueue.set_text ('')
            self.entNPTLpdQueue.set_completion (None)
            self.btnNPTLpdProbe.set_sensitive (False)
            if len (device.uri) > 6:
                host = device.uri[6:]
                i = host.find ("/")
                if i != -1:
                    printer = host[i + 1:]
                    host = host[:i]
                else:
                    printer = ""
                self.entNPTLpdHost.set_text (host)
                self.entNPTLpdQueue.set_text (printer)
                location = host
                self.btnNPTLpdProbe.set_sensitive (True)
        elif device.uri == "smb":
            self.entSMBURI.set_text('')
            self.btnSMBVerify.set_sensitive(False)
        elif device.type == "smb":
            self.entSMBUsername.set_text ('')
            self.entSMBPassword.set_text ('')
            self.entSMBURI.set_text(device.uri[6:])
            self.set_btnSMBVerify_sensitivity (True)
        else:
            if device.uri:
                self.entNPTDevice.set_text(device.uri)

        try:
            if len (location) == 0 and self.device.device_class == "direct":
                # Set location to the name of this host.
                if (self._host == 'localhost' or
                    self._host[0] == '/'):
                    u = os.uname ()
                    location = u[1]
                else:
                    location = self._host

            # Pre-fill location field.
            self.entNPLocation.set_text (location)
        except:
            nonfatalException ()

        self.setNPButtons()

    def on_entNPTLpdHost_changed(self, ent):
        hostname = ent.get_text()
        self.btnNPTLpdProbe.set_sensitive (len (hostname) > 0)
        self.setNPButtons()

    def on_entNPTLpdQueue_changed(self, ent):
        self.setNPButtons()

    def on_btnNPTLpdProbe_clicked(self, button):
        # read hostname, probe, fill printer names
        hostname = self.entNPTLpdHost.get_text()
        server = probe_printer.LpdServer(hostname)

        self.lblWait.set_markup ('<span weight="bold" size="larger">' +
                                 _('Searching') + '</span>\n\n' +
                                 _('Searching for printers'))
        self.WaitWindow.set_transient_for (self.NewPrinterWindow)
        self.WaitWindow.show_now ()
        busy (self.WaitWindow)
        def stop (widget, event):
            server.destroy ()
            return True

        self.WaitWindow.disconnect (self.WaitWindow_handler)
        signal = self.WaitWindow.connect ("delete-event", stop)
        printers = server.probe()
        self.WaitWindow.disconnect (signal)
        self.WaitWindow_handler = self.WaitWindow.connect ("delete-event",
                                                           on_delete_just_hide)
        self.WaitWindow.hide ()

        model = Gtk.ListStore (str)
        for printer in printers:
            model.append ([printer])

        completion = Gtk.EntryCompletion ()
        completion.set_model (model)
        completion.set_text_column (0)
        completion.set_minimum_key_length (0)
        self.entNPTLpdQueue.set_completion (completion)

    ### Find Network Printer
    def on_entNPTNetworkHostname_changed(self, ent):
        text = ent.get_text ()
        if text.find (":") != -1:
            # The user is typing in a URI.  In that case, switch to URI entry.
            ent.set_text ('')
            debugprint ("URI detected (%s) -> Enter URI" % text)
            self.entNPTDevice.set_text (text)
            model = self.tvNPDevices.get_model ()
            path = model.get_path (self.devices_uri_iter)
            self.tvNPDevices.set_cursor (path=path,
                                         start_editing=False)
            self.entNPTDevice.select_region (0, 0)
            self.entNPTDevice.set_position (-1)
            return

        allowed_chars = string.ascii_letters+string.digits+'_-.:%[]'
        self.entry_changed(ent, allowed_chars)
        s = ent.get_text ()
        self.btnNetworkFind.set_sensitive (len (s) > 0)
        self.lblNetworkFindNotFound.hide ()
        self.setNPButtons ()

    def on_btnNetworkFind_clicked(self, button):
        host = self.entNPTNetworkHostname.get_text ()

        def found_callback (new_device):
            if self.printer_finder is None:
                return

            GLib.idle_add (self.found_network_printer_callback, new_device)

        self.btnNetworkFind.set_sensitive (False)
        self.entNPTNetworkHostname.set_sensitive (False)
        self.network_found = 0
        self.lblNetworkFindNotFound.hide ()
        self.lblNetworkFindSearching.show_all ()
        finder = probe_printer.PrinterFinder ()
        self.inc_spinner_task ()
        finder.find (host, found_callback)
        self.printer_finder = finder

    def found_network_printer_callback (self, new_device):
        Gdk.threads_enter ()
        if new_device:
            self.network_found += 1
            dev = PhysicalDevice (new_device)
            try:
                i = self.devices.index (dev)

                # Adding a new URI to an existing physical device.
                self.devices[i].add_device (new_device)

                (path, column) = self.tvNPDevices.get_cursor ()
                if path:
                    model = self.tvNPDevices.get_model ()
                    iter = model.get_iter (path)
                    if model.get_value (iter, 1) == self.devices[i]:
                        self.on_tvNPDevices_cursor_changed (self.tvNPDevices)
            except ValueError:
                # New physical device.
                dev.checked_hplip = True
                self.devices.append (dev)
                self.devices.sort ()
                model = self.tvNPDevices.get_model ()
                iter = model.insert_before (None, self.devices_find_nw_iter,
                                            row=[dev.get_info (), dev, False])

                # If this is the first one we've found, select it.
                if self.network_found == 1:
                    path = model.get_path (iter)
                    self.tvNPDevices.set_cursor (path, None, False)
        else:
            self.printer_finder = None
            self.dec_spinner_task ()
            self.lblNetworkFindSearching.hide ()
            self.entNPTNetworkHostname.set_sensitive (True)
            self.btnNetworkFind.set_sensitive (True)
            if self.network_found == 0:
                self.lblNetworkFindNotFound.set_markup ('<i>' +
                                                        _("No printer was "
                                                          "found at that "
                                                          "address.") + '</i>')
                self.lblNetworkFindNotFound.show ()

        Gdk.threads_leave ()
    ###

    def getDeviceURI(self):
        if self.dialog_mode in ['printer_with_uri', 'ppd']:
            return self.device.uri

        type = self.device.type
        page = self.new_printer_device_tabs.get (type, self.PAGE_SELECT_DEVICE)
        device = type
        if page == self.PAGE_DESCRIBE_PRINTER:
            # The "no options page".  We already have the URI.
            device = self.device.uri
        elif type == "socket": # JetDirect
            host = self.entNPTJetDirectHostname.get_text()
            port = self.entNPTJetDirectPort.get_text()
            if host:
                device += "://" + host
                if port:
                    device += ":" + port
        elif type == "lpd": # LPD
            host = self.entNPTLpdHost.get_text()
            printer = self.entNPTLpdQueue.get_text()
            if host:
                device += "://" + host
                if printer:
                    device += "/" + printer
        elif type == "serial": # Serial
            options = []
            for widget, name in (
                (self.cmbNPTSerialBaud, "baud"),
                (self.cmbNPTSerialBits, "bits"),
                (self.cmbNPTSerialParity, "parity"),
                (self.cmbNPTSerialFlow, "flow")):
                model = widget.get_model ()
                iter = widget.get_active_iter()
                option = model.get_value (iter, 1)
                if option != "":
                    options.append(name + "=" + option)
            options = "+".join(options)
            device =  self.device.uri.split("?")[0] #"serial:/dev/ttyS%s"
            if options:
                device = device + "?" + options
        elif type == "smb":
            uri = self.entSMBURI.get_text ()
            (group, host, share, u, p) = SMBURI (uri=uri).separate ()
            user = ''
            password = ''
            if self.rbtnSMBAuthSet.get_active ():
                user = self.entSMBUsername.get_text ()
                password = self.entSMBPassword.get_text ()
            uri = SMBURI (group=group, host=host, share=share,
                          user=user, password=password).get_uri ()
            if uri:
                device += "://" + uri
        else:
            device = self.entNPTDevice.get_text()
        return device

    # PPD

    def on_rbtnNPFoomatic_toggled(self, widget):
        rbtn1 = self.rbtnNPFoomatic.get_active()
        rbtn2 = self.rbtnNPPPD.get_active()
        rbtn3 = self.rbtnNPDownloadableDriverSearch.get_active()
        self.tvNPMakes.set_sensitive(rbtn1)
        self.filechooserPPD.set_sensitive(rbtn2)

        if rbtn1:
            page = self.PAGE_DESCRIBE_PRINTER
        if rbtn2:
            page = self.PAGE_SELECT_DEVICE
        if rbtn3:
            page = self.PAGE_SELECT_INSTALL_METHOD
        self.ntbkPPDSource.set_current_page (page)

        if not rbtn3 and self.opreq:
            # Need to cancel a search in progress.
            for handler in self.opreq_handlers:
                self.opreq.disconnect (handler)

            self.opreq_handlers = None
            self.opreq.cancel ()
            self.opreq = None

            self.btnNPDownloadableDriverSearch.set_sensitive (True)
            self.btnNPDownloadableDriverSearch_label.set_text (_("Search"))
            # Clear printer list.
            model = Gtk.ListStore (str, str)
            combobox = self.cmbNPDownloadableDriverFoundPrinters
            combobox.set_model (model)
            combobox.set_sensitive (False)

        for widget in [self.entNPDownloadableDriverSearch,
                       self.cmbNPDownloadableDriverFoundPrinters]:
            widget.set_sensitive(rbtn3)
        self.btnNPDownloadableDriverSearch.\
            set_sensitive (rbtn3 and (self.opreq is None))

        self.setNPButtons()

    def on_filechooserPPD_selection_changed(self, widget):
        self.setNPButtons()

    def on_btnNPDownloadableDriverSearch_clicked(self, widget):
        self.searchedfordriverpackages = True
        if self.opreq is not None:
            for handler in self.opreq_handlers:
                self.opreq.disconnect (handler)

            self.opreq_handlers = None
            self.opreq.cancel ()
            self.opreq = None

        widget.set_sensitive (False)
        label = self.btnNPDownloadableDriverSearch_label
        label.set_text (_("Searching"))
        searchterm = self.entNPDownloadableDriverSearch.get_text ()
        debugprint ('Searching for "%s"' % repr (searchterm))
        self.opreq = OpenPrintingRequest ()
        self.opreq_handlers = []
        self.opreq_handlers.append (
            self.opreq.connect ('finished',
                                self.opreq_user_search_done))
        self.opreq_handlers.append (
            self.opreq.connect ('error',
                                self.opreq_user_search_error))
        self.opreq.searchPrinters (searchterm)
        self.cmbNPDownloadableDriverFoundPrinters.set_sensitive (False)

    def opreq_user_search_done (self, opreq, printers, drivers):
        for handler in self.opreq_handlers:
            opreq.disconnect (handler)

        self.opreq_user_search = True
        self.opreq_handlers = None
        self.opreq = None

        self.founddownloadabledrivers = True
        self.downloadable_printers = printers
        self.downloadable_drivers = drivers

        button = self.btnNPDownloadableDriverSearch
        label = self.btnNPDownloadableDriverSearch_label
        Gdk.threads_enter ()
        try:
            label.set_text (_("Search"))
            button.set_sensitive (True)
            model = Gtk.ListStore (str, str)
            if len (self.downloadable_printers) != 1:
                if len (self.downloadable_printers) > 1:
                    first = _("-- Select from search results --")
                else:
                    first = _("-- No matches found --")

                iter = model.append (None)
                model.set_value (iter, 0, first)
                model.set_value (iter, 1, '')

            sorted_list = []
            for printer_id, printer_name in self.downloadable_printers:
                sorted_list.append ((printer_id, printer_name))

            sorted_list.sort (key=functools.cmp_to_key(lambda x, y: cups.modelSort (x[1], y[1])))
            sought = self.entNPDownloadableDriverSearch.get_text ().lower ()
            select_index = 0
            for id, name in sorted_list:
                iter = model.append (None)
                model.set_value (iter, 0, name)
                model.set_value (iter, 1, id)
                if name.lower () == sought:
                    select_index = model.get_path (iter)[0]
            combobox = self.cmbNPDownloadableDriverFoundPrinters
            combobox.set_model (model)
            combobox.set_active (select_index)
            combobox.set_sensitive (True)
            self.setNPButtons ()
        except:
            nonfatalException()

        Gdk.threads_leave ()

    def opreq_user_search_error (self, opreq, status, err):
        debugprint ("OpenPrinting request failed (%d): %s" % (status,
                                                              repr (err)))
        self.opreq_user_search_done (opreq, list(), dict())

    def on_cmbNPDownloadableDriverFoundPrinters_changed(self, widget):
        self.setNPButtons ()

        if self.opreq is not None:
            for handler in self.opreq_handlers:
                self.opreq.disconnect (handler)

            self.opreq_handlers = None
            self.opreq.cancel ()
            self.opreq = None
            self.btnNPDownloadableDriverSearch.set_sensitive (True)
            self.btnNPDownloadableDriverSearch_label.set_text (_("Search"))

    def fillDownloadableDrivers(self):
        print ("filldownloadableDrivers")
        self.downloadable_driver_for_printer = None
        if self.opreq_user_search == True:
            widget = self.cmbNPDownloadableDriverFoundPrinters
            model = widget.get_model ()
            iter = widget.get_active_iter ()
            if iter:
                printer_id = model.get_value (iter, 1)
                printer_str = model.get_value (iter, 0)
                if printer_id == '':
                    widget.set_active (1)
                    iter = widget.get_active_iter ()
                    if iter:
                        printer_id = model.get_value (iter, 1)
                        printer_str = model.get_value (iter, 0)
                    else:
                        printer_id = None
                        printer_str = None
            else:
                printer_id = None
                printer_str = None
        else:
            printer_id, printer_str = self.downloadable_printers[0]

        if printer_id is None:
            # If none selected, show all.
            # This also happens for ID-matching.
            printer_ids = [x[0] for x in self.downloadable_printers]
        else:
            printer_ids = [printer_id]

        if printer_str:
            self.downloadable_driver_for_printer = printer_str

        model = Gtk.ListStore (str,                     # driver name
                               GObject.TYPE_PYOBJECT)   # driver data
        recommended_iter = None
        first_iter = None
        for printer_id in printer_ids:
            drivers = self.downloadable_drivers[printer_id]
            for driver in drivers.values ():
                if ((not 'ppds' in driver or
                     len(driver['ppds']) <= 0) and
                    (config.DOWNLOADABLE_ONLYPPD or
                     (not self._getDriverInstallationInfo (driver)))):
                    debugprint ("Removed invalid driver entry %s" % \
                                driver['name'])
                    continue
                iter = model.append (None)
                if first_iter is None:
                    first_iter = iter

                model.set_value (iter, 0, driver['name'])
                model.set_value (iter, 1, driver)

                if driver['recommended']:
                    recommended_iter = iter

        if first_iter is None:
            return False

        if not self.rbtnNPDownloadableDriverSearch.get_active() and \
           self.dialog_mode != "download_driver":
            iter = model.append (None)
            model.set_value (iter, 0, _("Local Driver"))
            model.set_value (iter, 1, 0)

        if recommended_iter is None:
            recommended_iter = first_iter

        treeview = self.tvNPDownloadableDrivers
        treeview.set_model (model)
        if recommended_iter is not None:
            treeview.get_selection ().select_iter (recommended_iter)
        self.on_tvNPDownloadableDrivers_cursor_changed(treeview)
        return True

    def on_rbtnNPDownloadLicense_toggled(self, widget):
        self.setNPButtons ()

    # PPD from foomatic

    def fillMakeList(self):
        self.recommended_make_selected = False
        makes = self.ppds.getMakes()
        model = self.tvNPMakes.get_model()
        model.clear()
        found = False
        if self.auto_make:
            auto_make_norm = cupshelpers.ppds.normalize (self.auto_make)
        else:
            auto_make_norm = None

        for make in makes:
            recommended = (auto_make_norm and
                           cupshelpers.ppds.normalize (make) == auto_make_norm)
            if self.device and self.device.make_and_model and recommended:
                text = make + _(" (recommended)")
            else:
                text = make

            iter = model.append((text, make,))
            if recommended:
                path = model.get_path(iter)
                self.tvNPMakes.set_cursor (path, None, False)
                self.tvNPMakes.scroll_to_cell(path, None,
                                              True, 0.5, 0.5)
                found = True

        if not found:
            self.tvNPMakes.set_cursor (Gtk.TreePath(), None, False)
            self.tvNPMakes.scroll_to_cell(0, None, True, 0.0, 0.0)

        # Also pre-fill the OpenPrinting.org search box.
        search = ''
        if self.device and self.device.id_dict:
            devid_dict = self.device.id_dict
            if devid_dict["MFG"] and devid_dict["MDL"]:
                search = devid_dict["MFG"] + " " + devid_dict["MDL"]
            elif devid_dict["DES"]:
                search = devid_dict["DES"]
            elif devid_dict["MFG"]:
                search = devid_dict["MFG"]
        if search == '' and self.auto_make is not None:
            search += self.auto_make
            if self.auto_model is not None:
                search += " " + self.auto_model
        if (search.startswith("Generic") or
            search.startswith("Unknown")):
            search = ''
        self.entNPDownloadableDriverSearch.set_text (search)

    def on_tvNPMakes_cursor_changed(self, tvNPMakes):
        path, column = tvNPMakes.get_cursor()
        if path is not None and self.ppds is not None:
            model = tvNPMakes.get_model ()
            iter = model.get_iter (path)
            self.NPMake = model.get(iter, 1)[0]
            recommended_make = (self.auto_make and
                                cupshelpers.ppds.normalize (self.auto_make) ==
                                cupshelpers.ppds.normalize (self.NPMake))
            self.recommended_make_selected = recommended_make
            self.fillModelList()

    def fillModelList(self):
        self.recommended_model_selected = False
        models = self.ppds.getModels(self.NPMake)
        model = self.tvNPModels.get_model()
        model.clear()
        selected = False
        is_auto_make = (cupshelpers.ppds.normalize (self.NPMake) ==
                        cupshelpers.ppds.normalize (self.auto_make))
        if is_auto_make:
            auto_model_norm = cupshelpers.ppds.normalize (self.auto_model)

        for pmodel in models:
            recommended = (is_auto_make and
                           cupshelpers.ppds.normalize (pmodel) ==
                           auto_model_norm)
            if self.device and self.device.make_and_model and recommended:
                text = pmodel + _(" (recommended)")
            else:
                text = pmodel

            iter = model.append((text, pmodel,))
            if recommended:
                path = model.get_path(iter)
                self.tvNPModels.set_cursor (path, None, False)
                self.tvNPModels.scroll_to_cell(path, None,
                                               True, 0.5, 0.5)
                selected = True
        if not selected:
            self.tvNPModels.set_cursor (Gtk.TreePath(), None, False)
            self.tvNPModels.scroll_to_cell(0, None, True, 0.0, 0.0)
        self.tvNPModels.columns_autosize()

    def fillDriverList(self, pmake, pmodel):
        self.NPModel = pmodel
        model = self.tvNPDrivers.get_model()
        model.clear()

        if self.device:
            devid = self.device.id_dict
        else:
            devid = None

        if (self.device and self.device.make_and_model and
            self.recommended_model_selected and
            self.id_matched_ppdnames):
            # Use the actual device-make-and-model string.
            make_and_model = self.device.make_and_model

            # and the ID-matched list of PPDs.
            self.NPDrivers = self.id_matched_ppdnames
            debugprint ("ID matched PPDs: %s" % repr (self.NPDrivers))
        elif self.ppds:
            # Use a generic make and model string for generating the
            # driver preference list.
            make_and_model = pmake + " " + pmodel
            ppds = self.ppds.getInfoFromModel(pmake, pmodel)
            ppdnames = list(ppds.keys ())

            files = self.installed_driver_files
            try:
                self.NPDrivers = self.ppds.orderPPDNamesByPreference(ppdnames,
                                                                     files,
                                                                     make_and_model,
                                                                     devid)
            except:
                nonfatalException ()
                self.NPDrivers = ppdnames

            # Put the current driver first.
            if self.auto_driver and self.device:
                drivers = []
                for driver in self.NPDrivers:
                    if driver == self.auto_driver:
                        drivers.insert (0, driver)
                    else:
                        drivers.append (driver)

                self.NPDrivers = drivers
        else:
            # No available PPDs for some reason(!)
            debugprint ("No PPDs available?")
            self.NPDrivers = []

        driverlist = []
        NPDrivers = []
        i = 0
        for ppdname in self.NPDrivers:
            ppd = self.ppds.getInfoFromPPDName (ppdname)
            driver = _singleton (ppd["ppd-make-and-model"])
            driver = driver.replace(" (recommended)", "")

            try:
                lpostfix = " [%s]" % _singleton (ppd["ppd-natural-language"])
                driver += lpostfix
            except KeyError:
                pass

            duplicate = driver in driverlist

            if (not (self.device and self.device.make_and_model) and
                self.auto_driver == ppdname):
                driverlist.append (driver)
                NPDrivers.append (ppdname)
                i += 1
                iter = model.append ((driver +
                                      _(" (Current)"),))
                path = model.get_path (iter)
                self.tvNPDrivers.get_selection().select_path(path)
                self.tvNPDrivers.scroll_to_cell(path, None, True, 0.5, 0.0)
            elif self.device and i == 0:
                driverlist.append (driver)
                NPDrivers.append (ppdname)
                i += 1
                iter = model.append ((driver +
                                      _(" (recommended)"),))
                path = model.get_path (iter)
                self.tvNPDrivers.get_selection().select_path(path)
                self.tvNPDrivers.scroll_to_cell(path, None, True, 0.5, 0.0)
            else:
                if duplicate:
                    continue
                driverlist.append (driver)
                NPDrivers.append (ppdname)
                i += 1
                model.append((driver, ))

        self.NPDrivers = NPDrivers
        self.tvNPDrivers.columns_autosize()

    def on_NPDrivers_query_tooltip(self, tv, x, y, keyboard_mode, tooltip):
        if keyboard_mode:
            path = tv.get_cursor()[0]
            if path is None:
                return False
        else:
            bin_x, bin_y = tv.convert_widget_to_bin_window_coords(x, y)
            ret = tv.get_path_at_pos (bin_x, bin_y)
            if ret is None:
                return False
            path = ret[0]

        drivername = self.NPDrivers[path[0]]
        ppddict = self.ppds.getInfoFromPPDName(drivername)
        markup = _singleton (ppddict['ppd-make-and-model'])
        if (drivername.startswith ("foomatic:")):
            markup += " "
            markup += _("This PPD is generated by foomatic.")
        tooltip.set_markup(markup)
        return True

    def on_tvNPModels_cursor_changed(self, widget):
        path, column = widget.get_cursor()
        if path is not None:
            model = widget.get_model ()
            iter = model.get_iter (path)
            pmodel = model.get(iter, 1)[0]

            # Find out if this is the auto-detected make and model
            recommended_model = (self.recommended_make_selected and
                                 self.auto_model and
                                 self.auto_model.lower () == pmodel.lower ())
            self.recommended_model_selected = recommended_model
            self.fillDriverList(self.NPMake, pmodel)
            self.on_tvNPDrivers_cursor_changed(self.tvNPDrivers)

    def on_tvNPDrivers_cursor_changed(self, widget):
        self.setNPButtons()

    def on_tvNPDownloadableDrivers_cursor_changed(self, widget):
        # Clear out the properties.
        self.lblNPDownloadableDriverSupplier.set_text ('')
        self.lblNPDownloadableDriverLicense.set_text ('')
        self.lblNPDownloadableDriverDescription.set_text ('')
        self.lblNPDownloadableDriverSupportContacts.set_text ('')
        self.rbtnNPDownloadLicenseNo.set_active (True)
        self.frmNPDownloadableDriverLicenseTerms.hide ()

        selection = widget.get_selection ()
        if selection is None:
            return

        model, iter = selection.get_selected ()
        if not iter:
            path, column = widget.get_cursor()
            if iter:
                iter = model.get_iter (path)
            else:
                return
        driver = model.get_value (iter, 1)
        if driver == 0:
            self.ntbkNPDownloadableDriverProperties.set_current_page (self.PAGE_DESCRIBE_PRINTER)
            self.setNPButtons()
            return
        self.ntbkNPDownloadableDriverProperties.set_current_page (self.PAGE_SELECT_DEVICE)
        supplier = driver.get('supplier', _("OpenPrinting"))
        vendor = self.cbNPDownloadableDriverSupplierVendor
        active = driver['manufacturersupplied']

        def set_protect_active (widget, active):
            widget.protect_active = active
            widget.set_active (active)

        set_protect_active (vendor, active)
        self.lblNPDownloadableDriverSupplier.set_text (supplier)

        license = driver.get('license', _("Distributable"))
        patents = self.cbNPDownloadableDriverLicensePatents
        free = self.cbNPDownloadableDriverLicenseFree
        set_protect_active (patents, driver['patents'])
        set_protect_active (free, driver['freesoftware'])
        self.lblNPDownloadableDriverLicense.set_text (license)

        description = driver.get('shortdescription', _("None"))
        self.lblNPDownloadableDriverDescription.set_markup (description)

        if 'functionality' in driver:
            functionality = driver['functionality']
            for field in ["Graphics", "LineArt", "Photo", "Text"]:
                key = field.lower ()
                value = None
                hs = self.__dict__.get ("hsDownloadableDriverPerf%s" % field)
                unknown = self.__dict__.get ("lblDownloadableDriverPerf%sUnknown"
                                             % field)
                if key in functionality:
                    if hs:
                        try:
                            value = int (functionality[key])
                            hs.set_range (0, 100)
                            hs.set_value (value)
                            hs.show_all ()
                            unknown.hide ()
                        except:
                            pass

                if value is None:
                    hs.hide ()
                    unknown.show_all ()

        supportcontacts = ""
        if 'supportcontacts' in driver:
            for supportentry in driver['supportcontacts']:
                if supportentry['name']:
                    supportcontact = " - " + supportentry['name']
                    supportcontact_extra = ""
                    if supportentry['url']:
                        supportcontact_extra = supportcontact_extra + \
                            supportentry['url']
                    if supportentry['level']:
                        if supportcontact_extra:
                            supportcontact_extra = supportcontact_extra + _(", ")
                        supportcontact_extra = supportcontact_extra + \
                            supportentry['level']
                    if supportcontact_extra:
                        supportcontact = supportcontact + \
                            _("\n(%s)") % supportcontact_extra
                        if supportcontacts:
                            supportcontacts = supportcontacts + "\n"
                        supportcontacts = supportcontacts + supportcontact
        if not supportcontacts:
            supportcontacts = _("No support contacts known")
        self.lblNPDownloadableDriverSupportContacts.set_text (supportcontacts)
        if 'licensetext' in driver:
            self.frmNPDownloadableDriverLicenseTerms.show ()
            terms = driver.get('licensetext', _("Not specified."))
            self.tvNPDownloadableDriverLicense.get_buffer ().set_text (terms)
        else:
            self.frmNPDownloadableDriverLicenseTerms.hide ()
        if not driver['nonfreesoftware'] and not driver['patents']:
            self.rbtnNPDownloadLicenseYes.set_active (True)
            self.rbtnNPDownloadLicenseYes.hide ()
            self.rbtnNPDownloadLicenseNo.hide ()
        else:
            self.rbtnNPDownloadLicenseNo.set_active (True)
            self.rbtnNPDownloadLicenseYes.show ()
            self.rbtnNPDownloadLicenseNo.show ()
            self.frmNPDownloadableDriverLicenseTerms.show ()
            terms = driver.get('licensetext', _("Not specified."))
            self.tvNPDownloadableDriverLicense.get_buffer ().set_text (terms)

        if 'ppds' in driver and len(driver["ppds"]) > 0:
            self.founddownloadableppd = True
        else:
            self.founddownloadableppd = False

        self.setNPButtons()

    def getNPPPD(self):
        ppd = None
        try:
            if ((self.rbtnNPFoomatic.get_active() or
                    len(self.installed_driver_files) > 0) and
                self.founddownloadableppd == False):
                model, iter = self.tvNPDrivers.get_selection().get_selected()
                nr = model.get_path(iter)[0]
                ppd = self.NPDrivers[nr]
            elif self.rbtnNPPPD.get_active():
                ppd = cups.PPD(self.filechooserPPD.get_filename())
            else:
                # PPD of the driver downloaded from OpenPrinting XXX
                treeview = self.tvNPDownloadableDrivers
                model, iter = treeview.get_selection ().get_selected ()
                driver = model.get_value (iter, 1)
                if driver != 0 and 'ppds' in driver:
                    # Only need to download a PPD.
                    if (len(driver['ppds']) > 0):
                        file_to_download = driver['ppds'][0]
                        debugprint ("ppd file to download [" + file_to_download+ "]")
                        file_to_download = file_to_download.strip()
                        if (len(file_to_download) > 0):
                            ppdurlobj = urllib.request.urlopen(file_to_download)
                            ppdcontent = ppdurlobj.read()
                            ppdurlobj.close()
                            with tempfile.NamedTemporaryFile () as tmpf:
                                tmpf.write(ppdcontent)
                                tmpf.flush ()
                                ppd = cups.PPD(tmpf.name)

        except RuntimeError as e:
            debugprint ("RuntimeError: " + repr (e))
            if self.rbtnNPFoomatic.get_active():
                # Foomatic database problem of some sort.
                err_title = _('Database error')
                err_text = _("The '%s' driver cannot be "
                             "used with printer '%s %s'.")
                model, iter = (self.tvNPDrivers.get_selection().
                               get_selected())
                nr = model.get_path(iter)[0]
                driver = self.NPDrivers[nr]
                if driver.startswith ("gutenprint"):
                    # This printer references some XML that is not
                    # installed by default.  Point the user at the
                    # package they need to install.
                    err = _("You will need to install the '%s' package "
                            "in order to use this driver.") % \
                            "gutenprint-foomatic"
                else:
                    err = err_text % (driver, self.NPMake, self.NPModel)
            elif self.rbtnNPPPD.get_active():
                # This error came from trying to open the PPD file.
                err_title = _('PPD error')
                filename = self.filechooserPPD.get_filename()
                err = _('Failed to read PPD file.  Possible reason '
                        'follows:') + '\n'
                try:
                    # We want this to be in the current natural language,
                    # so we intentionally don't set LC_ALL=C here.
                    p = subprocess.Popen (['/usr/bin/cupstestppd',
                                           '-rvv', filename],
                                          close_fds=True,
                                          stdin=subprocess.DEVNULL,
                                          stdout=subprocess.PIPE,
                                          stderr=subprocess.PIPE)
                    (stdout, stderr) = p.communicate ()
                    err += stdout.decode ()
                except:
                    # Problem executing command.
                    raise
            else:
                # Failed to get PPD downloaded from OpenPrinting XXX
                err_title = _('Downloadable drivers')
                err = _("Failed to download PPD.")

            show_error_dialog (err_title, err, self.NewPrinterWindow)
            return None

        debugprint("ppd: " + repr(ppd))

        if isinstance(ppd, str):
            self.cups._begin_operation (_("fetching PPD"))
            try:
                if ppd != "raw":
                    f = self.cups.getServerPPD(ppd)
                    ppd = cups.PPD(f)
                    os.unlink(f)
            except RuntimeError:
                nonfatalException()
                debugprint ("libcups from CUPS 1.3 not available: never mind")
            except cups.IPPError:
                nonfatalException()
                debugprint ("CUPS 1.3 server not available: never mind")

            self.cups._end_operation ()

        return ppd

    # Installable Options

    def fillNPInstallableOptions(self):
        debugprint ("Examining installable options")
        self.installable_options = False
        self.options = { }

        container = self.vbNPInstallOptions
        for child in container.get_children():
            container.remove(child)

        if not self.ppd:
            l = Gtk.Label(label=_("No Installable Options"))
            container.add(l)
            l.show()
            debugprint ("No PPD so no installable options")
            return

        # build option tabs
        for group in self.ppd.optionGroups:
            if group.name != "InstallableOptions":
                continue
            self.installable_options = True
            grid = Gtk.Grid()
            grid.set_column_spacing(6)
            grid.set_row_spacing(6)
            container.add(grid)
            rows = 0

            for nr, option in enumerate(group.options):
                if option.keyword == "PageRegion":
                    continue
                rows += 1
                o = OptionWidget(option, self.ppd, self)
                grid.attach(o.conflictIcon, 0, nr, 1, 1)

                hbox = Gtk.Box()
                if o.label:
                    a = Gtk.Alignment.new (0.5, 0.5, 1.0, 1.0)
                    a.set_padding (0, 0, 0, 6)
                    a.add (o.label)
                    grid.attach(a, 1, nr, 1, 1)
                    grid.attach(hbox, 2, nr, 1, 1)
                else:
                    grid.attach(hbox, 1, nr, 2, 1)
                hbox.pack_start(o.selector, False, False, 0)
                self.options[option.keyword] = o
        if not self.installable_options:
            l = Gtk.Label(label=_("No Installable Options"))
            container.add(l)
            l.show()
        self.scrNPInstallableOptions.hide()
        self.scrNPInstallableOptions.show_all()


    # Create new Printer
    def on_btnNPApply_clicked(self, widget):
        if self.fetchDevices_conn:
            self.fetchDevices_conn.destroy ()
            self.fetchDevices_conn = None
            self.dec_spinner_task ()

        if self.ppdsloader:
            self.ppdsloader.destroy ()
            self.ppdsloader = None

        if self.printer_finder:
            self.printer_finder.cancel ()
            self.printer_finder = None
            self.dec_spinner_task ()

        if self.dialog_mode in ("class", "printer", "printer_with_uri"):
            name = self.entNPName.get_text()
            location = self.entNPLocation.get_text()
            info = self.entNPDescription.get_text()
        else:
            name = self._name

        ppd = self.ppd

        if self.dialog_mode == "class":
            members = getCurrentClassMembers(self.tvNCMembers)
            try:
                for member in members:
                    try:
                        self.cups.addPrinterToClass(member, name)
                    except RuntimeError:
                        # Printer already in class?
                        continue
            except cups.IPPError as e:
                (e, msg) = e.args
                self.show_IPP_Error(e, msg)
                return
        elif self.dialog_mode == "printer" or \
                self.dialog_mode == "printer_with_uri":
            uri = None
            if self.device.uri:
                uri = self.device.uri
            else:
                uri = self.getDeviceURI()
            if not self.ppd: # XXX needed?
                # Go back to previous page to re-select driver.
                self.nextNPTab(-1)
                return

            # write Installable Options to ppd
            for option in self.options.values():
                option.writeback()

            busy (self.NewPrinterWindow)
            while Gtk.events_pending ():
                Gtk.main_iteration ()
            self.cups._begin_operation (_("adding printer %s") % name)
            try:
                if isinstance(ppd, str):
                    self.cups.addPrinter(name, ppdname=ppd,
                         device=uri, info=info, location=location)
                elif ppd is None: # raw queue
                    self.cups.addPrinter(name, device=uri,
                                         info=info, location=location)
                else:
                    # Note: LC_MESSAGES is used here to determine the
                    # page size instead of LC_PAPER. This is not
                    # really correct, but it's what CUPS does so to
                    # avoid confusion we'll follow that method.
                    cupshelpers.setPPDPageSize(ppd, self.language[0])
                    self.cups.addPrinter(name, ppd=ppd, device=uri,
                                         info=info, location=location)
            except cups.IPPError as e:
                (e, msg) = e.args
                ready (self.NewPrinterWindow)
                self.show_IPP_Error(e, msg)
                self.cups._end_operation()
                return
            except:
                ready (self.NewPrinterWindow)
                self.cups._end_operation()
                fatalException (1)
            self.cups._end_operation()
            ready (self.NewPrinterWindow)
        if self.dialog_mode in ("class", "printer", "printer_with_uri"):
            self.cups._begin_operation (_("modifying printer %s") % name)
            try:
                cupshelpers.activateNewPrinter (self.cups, name)
                self.cups.setPrinterLocation(name, location)
                self.cups.setPrinterInfo(name, info)
            except cups.IPPError as e:
                (e, msg) = e.args
                self.show_IPP_Error(e, msg)
                self.cups._end_operation ()
                return
            self.cups._end_operation ()
        elif self.dialog_mode == "device":
            self.cups._begin_operation (_("modifying printer %s") % name)
            try:
                uri = self.getDeviceURI()
                self.cups.addPrinter(name, device=uri)
            except cups.IPPError as e:
                (e, msg) = e.args
                self.show_IPP_Error(e, msg)
                self.cups._end_operation ()
                return
            self.cups._end_operation ()
        elif self.dialog_mode == "ppd":
            if not ppd:
                ppd = self.ppd = self.getNPPPD()
                if not ppd:
                    # Go back to previous page to re-select driver.
                    self.nextNPTab(-1)
                    return

            self.cups._begin_operation (_("modifying printer %s") % name)
            # set ppd on server and retrieve it
            # cups doesn't offer a way to just download a ppd ;(=
            raw = False
            if isinstance(ppd, str):
                if self.rbtnChangePPDasIs.get_active():
                    # To use the PPD as-is we need to prevent CUPS copying
                    # the old options over.  Do this by setting it to a
                    # raw queue (no PPD) first.
                    try:
                        self.cups.addPrinter(name, ppdname='raw')
                    except cups.IPPError as e:
                        (e, msg) = e.args
                        self.show_IPP_Error(e, msg)
                try:
                    self.cups.addPrinter(name, ppdname=ppd)
                except cups.IPPError as e:
                    (e, msg) = e.args
                    self.show_IPP_Error(e, msg)
                    self.cups._end_operation ()
                    return

                try:
                    filename = self.cups.getPPD(name)
                    ppd = cups.PPD(filename)
                    os.unlink(filename)
                except cups.IPPError as e:
                    (e, msg) = e.args
                    if e == cups.IPP_NOT_FOUND:
                        raw = True
                    else:
                        self.show_IPP_Error(e, msg)
                        self.cups._end_operation ()
                        return
            else:
                # We have an actual PPD to upload, not just a name.
                if ((not self.rbtnChangePPDasIs.get_active()) and
                    isinstance (self.orig_ppd, cups.PPD)):
                    cupshelpers.copyPPDOptions(self.orig_ppd, ppd)
                else:
                    cupshelpers.setPPDPageSize(ppd, self.language[0])

                # write Installable Options to ppd
                for option in self.options.values():
                    option.writeback()

                try:
                    self.cups.addPrinter(name, ppd=ppd)
                except cups.IPPError as e:
                    (e, msg) = e.args
                    self.show_IPP_Error(e, msg)
                    self.cups._end_operation ()
                    return

            self.cups._end_operation ()

        elif self.dialog_mode == "download_driver":
            self.nextNPTab(0);

        self.NewPrinterWindow.hide()
        if self.dialog_mode in ["printer", "printer_with_uri", "class"]:
            self.emit ('printer-added', name)
        elif self.dialog_mode == "download_driver":
            self.emit ('driver-download-checked', self.installed_driver_files)
        else:
            self.emit ('printer-modified', name, self.orig_ppd != self.ppd)

        self.device = None
        self.printers = {}

def show_help():
    print ("\nThis is the test/debug mode of the new-printer dialog of " \
           "system-config-printer.\n\n"
           "Options:\n\n"
           "  --setup-printer URI\n"
           "            Select the (detected) CUPS device URI on start up\n"
           "            and run the new-printer wizard for it.\n\n"
           "  --devid   Supply a device ID which should be used for the\n"
           "            setup of the new printer with \"--setup-printer\".\n"
           "            This can be any printer's ID, so that driver \n"
           "            selection can be tested for printers which are not\n"
           "            physically available.\n")

if __name__ == '__main__':
    import getopt
    try:
        opts, args = getopt.gnu_getopt (sys.argv[1:], '',
                                        ['setup-printer=',
                                         'devid='])
    except getopt.GetoptError:
        show_help ()
        sys.exit (1)

    setup_printer = None
    devid = ""
    for opt, optarg in opts:
        if opt == '--setup-printer':
            setup_printer = optarg
        elif opt == '--devid':
            devid = optarg

    os.environ["SYSTEM_CONFIG_PRINTER_UI"] = "ui"
    import ppdippstr
    locale.setlocale (locale.LC_ALL, "")
    ppdippstr.init ()
    set_debugging (True)
    cupshelpers.set_debugprint_fn (debugprint)

    n = NewPrinterGUI ()
    def on_signal (*args):
        Gtk.main_quit ()

    n.connect ("printer-added", on_signal)
    n.connect ("printer-modified", on_signal)
    n.connect ("dialog-canceled", on_signal)
    if setup_printer is not None:
        n.init ("printer_with_uri", device_uri=setup_printer, devid=devid)
    else:
        n.init ("printer")
    Gtk.main ()