File: setupform.py

package info (click to toggle)
hplip 1.6.10-3etch1
  • links: PTS
  • area: main
  • in suites: etch
  • size: 35,140 kB
  • ctags: 10,985
  • sloc: ansic: 48,004; cpp: 40,938; python: 29,973; xml: 14,675; sh: 9,841; perl: 4,257; makefile: 786
file content (821 lines) | stat: -rw-r--r-- 30,296 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
# -*- coding: utf-8 -*-
#
# (c) Copyright 2001-2006 Hewlett-Packard Development Company, L.P.
#
# 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
#
# Author: Don Welch

# Std Lib
import sys, socket, re, gzip

# Local
from base.g import *
from base import msg, device, utils, service
from prnt import cups

try:
    from fax import fax
    fax_import_ok = True
except ImportError:
    # This can fail on Python < 2.3 due to the datetime module
    fax_import_ok = False
    log.warning("Fax setup disabled - Python 2.3+ required.")

# Qt
from qt import *
from setupform_base import SetupForm_base
from setupsettings import SetupSettings
from setupmanualfind import SetupManualFind

nickname_pat = re.compile(r'''\*NickName:\s*\"(.*)"''', re.MULTILINE)

class DeviceListViewItem(QListViewItem):
    def __init__(self, parent, device_uri, mq, c1='', c2='', c3='', c4=''):
        QListViewItem.__init__(self, parent, c1, c2, c3, c4)
        self.device_uri = device_uri
        self.mq = mq


class PPDListViewItem(QListViewItem):
    def __init__(self, parent, ppd_file, c1=''):
        QListViewItem.__init__(self, parent, ppd_file, c1)
        self.ppd_file = ppd_file


class PrinterNameValidator(QValidator):
    def __init__(self, parent=None, name=None):
        QValidator.__init__(self, parent, name)

    def validate(self, input, pos):
        input = str(input)

        if not input:
            return QValidator.Acceptable, pos

        elif input[pos-1] in ' #/':
            return QValidator.Invalid, pos

        elif input != utils.printable(input): 
            return QValidator.Invalid, pos

        elif len(input) > 50:
            return QValidator.Invalid, pos

        else:
            return QValidator.Acceptable, pos



class PhoneNumValidator(QValidator):
    def __init__(self, parent=None, name=None):
        QValidator.__init__(self, parent, name)

    def validate(self, input, pos):
        input = str(input)
        if not input:
            return QValidator.Acceptable, pos
        elif input[pos-1] not in '0123456789-(+) ':
            return QValidator.Invalid, pos
        elif len(input) > 50:
            return QValidator.Invalid, pos
        else:
            return QValidator.Acceptable, pos            



class SetupForm(SetupForm_base):
    def __init__(self, parent=None, name=None, modal=0, fl=0):
        SetupForm_base.__init__(self, parent, name, modal, fl)

        icon = QPixmap(os.path.join(prop.image_dir, 'HPmenu.png'))
        self.setIcon(icon)

        self.hpiod_sock = None
        try:
            self.hpiod_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.hpiod_sock.connect((prop.hpiod_host, prop.hpiod_port))
        except socket.error:
            log.error("Unable to connect to hpiod.")
            raise Error(ERROR_UNABLE_TO_CONTACT_SERVICE)

        self.hpssd_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            self.hpssd_sock.connect((prop.hpssd_host, prop.hpssd_port))
        except socket.error:
            print "Unable to connect to HPLIP I/O (hpssd)."
            raise Error(ERROR_UNABLE_TO_CONTACT_SERVICE)

        self.connectionTypeButtonGroup.setButton(0)
        self.bus = 'usb'
        self.device_uri = ''
        self.mq = {}
        self.prev_page = None
        self.probe_pat = re.compile(r'(.*?)\s"(.*?)"\s"(.*?)"\s"(.*?)"', re.IGNORECASE)
        self.printer_name = ''
        self.ppd_list = []
        self.location = ''
        self.desc = ''
        self.filter = 'none'
        self.search = ''
        self.ttl = 4
        self.timeout = 5
        self.printer_name_ok = False
        self.fax_name_ok = False
        self.fax_number = ''
        self.fax_name_company = ''
        self.fax_location = ''
        self.fax_desc = ''
        self.print_test_page = True
        self.printerNameLineEdit.setValidator(PrinterNameValidator(self.printerNameLineEdit))
        self.faxNumberLineEdit.setValidator(PhoneNumValidator(self.faxNumberLineEdit))
        self.setTitleFont(QFont("Helvetica", 16))
        self.setBackEnabled(self.FinishedPage, False)
        self.bg = self.printerNameLineEdit.paletteBackgroundColor()
        self.setHelpEnabled(self.ConnectionPage, False)
        self.setHelpEnabled(self.ProbedDevicesPage, False)
        self.setHelpEnabled(self.PPDPage, False)
        self.setHelpEnabled(self.PrinterNamePage, False)
        self.setHelpEnabled(self.FinishedPage, False)

        QToolTip.add(self.searchFiltersPushButton2, 
            self.__tr('Current: Filter: "%2"  Search: "%3"  TTL: %4  Timeout: %5s').arg(self.filter).arg(self.search or '').arg(self.ttl).arg(self.timeout))


    def showPage(self, page):
        orig_page = page
        log.debug("%s %s %s" % ("*"*20, "showPage(%s)" % page.name(), "*"*20))

        try:
            log.debug("%s --> %s" % (self.prev_page.name(), page.name()))
        except AttributeError:
            log.debug("--> %s" % page.name())

        if page is self.ConnectionPage: # start --> ConnectionPage
            pass

        elif page is self.ProbedDevicesPage: # ConnectionPage --> ProbedDevicesPage/EnterIPPage/DeviceNotFoundPage
            devices_found = self.updateProbedDevicesPage()

        elif page is self.PPDPage: # ProbedDevicesPage --> PPDPage
            self.updatePPDPage()

            if len(self.ppd_list) == 0:
                pass # TODO:

        elif page is self.PrinterNamePage:
            self.setDefaultPrinterName()

            if fax_import_ok and self.mq.get('fax-type', FAX_TYPE_NONE) != FAX_TYPE_NONE:
                self.faxCheckBox.setEnabled(True)
                self.faxCheckBox.setEnabled(True)
                self.faxNameLineEdit.setEnabled(True)
                self.faxNumberLineEdit.setEnabled(True)
                self.faxNameCoLineEdit.setEnabled(True)
                self.faxLocationLineEdit.setEnabled(True)
                self.faxDescriptionLineEdit.setEnabled(True)
                self.faxInfoGroupBox.setEnabled(True)
                self.setup_fax = True
                self.setDefaultFaxName()
                self.readwriteFaxInformation(True)

            else:
                self.setup_fax = False
                self.defaultFaxNamePushButton.setEnabled(False)
                self.faxCheckBox.setEnabled(False)
                self.faxNameLineEdit.setEnabled(False)
                self.faxNumberLineEdit.setEnabled(False)
                self.faxNameCoLineEdit.setEnabled(False)
                self.faxLocationLineEdit.setEnabled(False)
                self.faxDescriptionLineEdit.setEnabled(False)
                self.faxInfoGroupBox.setEnabled(False)

        elif page is self.FinishedPage:
            self.lineEdit1.setText(self.printer_name)
            self.lineEdit2.setText(self.location)
            self.lineEdit3.setText(self.desc)
            self.lineEdit4.setText(self.ppd_file)

            self.setupPrinter()

            if self.setup_fax:
                self.setupFax()
                self.readwriteFaxInformation(False)

                self.lineEdit5.setText(self.fax_name)
                self.lineEdit6.setText(self.fax_number)
                self.lineEdit7.setText(self.fax_name_company)
                self.lineEdit8.setText(self.fax_location)
                self.lineEdit9.setText(self.fax_desc)
                
                self.faxGroupBox.setEnabled(True)

            else:
                self.faxGroupBox.setEnabled(False)

            self.setFinishEnabled(self.FinishedPage, True)

        if orig_page != page:
            try:
                log.debug("%s --> %s" % (self.prev_page.name(), page.name()))
            except AttributeError:
                log.debug("--> %s" % page.name())

        self.prev_page = page
        QWizard.showPage(self, page)

        if page is self.ProbedDevicesPage: # ConnectionPage --> ProbedDevicesPage/EnterIPPage/DeviceNotFoundPage
            if not devices_found:
                self.FailureUI(self.__tr("<b>No devices found.</b><p>Please make sure your printer is properly connected and powered-on."))            


    #
    # CONNECTION TYPE PAGE
    #

    def connectionTypeButtonGroup_clicked(self,a0):
        if a0 == 0:
            self.bus = 'usb'

        elif a0 == 1:
            self.bus = 'net'

        elif a0 == 2:
            self.bus = 'par'

        log.debug(self.bus)


    def searchFiltersPushButton2_clicked(self):
        self.settingsDlg()

    #
    # FILTERS SEARCH SETTINGS
    #

    def settingsDlg(self):
        dlg = SetupSettings(self.bus, self.filter, self.search, self.ttl, self.timeout, self)
        if dlg.exec_loop() == QDialog.Accepted:
            self.filter = dlg.filter
            self.search = dlg.search
            self.ttl = dlg.ttl
            self.timeout = dlg.timeout

            t = self.__tr('Current Settings: Filter: "%2"  Search: "%3"  TTL: %4  Timeout: %5s').arg(self.filter).arg(self.search or '').arg(self.ttl).arg(self.timeout)

            QToolTip.add(self.searchFiltersPushButton2, t)
            QToolTip.add(self.searchFiltersPushButton, t)
            return True

        return False

    #
    # PROBED DEVICES PAGE
    #

    def updateProbedDevicesPage(self, devices=None, param=''):
        QApplication.setOverrideCursor(QApplication.waitCursor)

        if self.bus == 'net':
            io_str = self.__tr("network")

        elif self.bus == 'usb':
            io_str = self.__tr("USB bus")

        elif self.bus == 'par':
            io_str = self.__tr("parallel port")

        QToolTip.add(self.searchFiltersPushButton, self.__tr('Current Settings: Filter: "%2"  Search: "%3"  TTL: %4  Timeout: %5s').arg(self.filter).arg(self.search or '').arg(self.ttl).arg(self.timeout))

        log.debug("Updating probed devices list...")
        log.debug(self.bus)

        self.probedDevicesListView.clear()

        while self.probedDevicesListView.columns():
            self.probedDevicesListView.removeColumn(0)

        self.probedDevicesListView.addColumn(self.__tr("Model"))

        if self.bus == 'usb':
            self.probedDevicesListView.addColumn(self.__tr("Serial No."))

        elif self.bus == 'net':
            self.probedDevicesListView.addColumn(self.__tr("IP Address"))
            self.probedDevicesListView.addColumn(self.__tr("Host Name"))

        elif self.bus == 'par':
            self.probedDevicesListView.addColumn(self.__tr("Device"))

        self.probedDevicesListView.addColumn(self.__tr("Device URI"))

        if devices is None:
            fields, data, result_code = \
                msg.xmitMessage(self.hpssd_sock,
                                 "ProbeDevicesFiltered",
                                  None,
                                  {
                                        'bus' : self.bus,
                                        'timeout' : self.timeout,
                                        'ttl' : self.ttl,
                                        'format' : 'cups',
                                        'filter' : self.filter,
                                        'search': self.search,
                                  })

            devices = data.splitlines()
            self.probeHeadingTextLabel.setText(self.__tr("%1 device(s) found on the %1:").arg(len(devices)).arg(io_str))

        else:
            if self.bus == 'net':
                self.probeHeadingTextLabel.setText(self.__tr("%1 device(s) found on the %1 at address %2:").arg(len(devices)).arg(io_str).arg(param))

            elif self.bus == 'usb': 
                self.probeHeadingTextLabel.setText(self.__tr("%1 device(s) found on the %1 at ID %2:").arg(len(devices)).arg(io_str).arg(param))

            elif self.bus == 'par': 
                self.probeHeadingTextLabel.setText(self.__tr("%1 device(s) found on the %1 device node ID %2:").arg(len(devices)).arg(io_str).arg(param))

        log.debug(devices)

        if devices:
            row = 0
            for d in devices:
                x = self.probe_pat.search(d)
                device_uri = x.group(1) # uri
                model = x.group(2) # model
                c3 = x.group(3) # ex. model
                name = x.group(4) # name
                back_end, is_hp, bus, model, serial, dev_file, host, port = device.parseDeviceURI(device_uri)

                mq = {}
                model_ui = device.normalizeModelUIName(model)

                if self.bus == 'usb':
                    i = DeviceListViewItem(self.probedDevicesListView, device_uri, mq, model_ui, serial, device_uri)

                elif self.bus == 'net':
                    i = DeviceListViewItem(self.probedDevicesListView, device_uri, mq, model_ui, host, name, device_uri)

                elif self.bus == 'par':
                    i = DeviceListViewItem(self.probedDevicesListView, device_uri, mq, model_ui, dev_file, device_uri)

                row += 1

            i = self.probedDevicesListView.firstChild()
            self.probedDevicesListView.setCurrentItem(i)
            self.probedDevicesListView.setSelected(i, True)
            item = self.probedDevicesListView.currentItem()
            self.device_uri = item.device_uri
            self.updateModelQuery(item)
            self.setNextEnabled(self.ProbedDevicesPage, True)
            log.debug(self.device_uri)

        else:
            self.setNextEnabled(self.ProbedDevicesPage, False)
            QApplication.restoreOverrideCursor()
            return False

        QApplication.restoreOverrideCursor()
        return True

    def updateModelQuery(self, item):
        if not item.mq:
            back_end, is_hp, bus, model, serial, dev_file, host, port = device.parseDeviceURI(self.device_uri)

            mq, data, result_code = \
                msg.xmitMessage(self.hpssd_sock,
                                "ModelQuery",
                                None,
                                {
                                    'model' : model,
                                })

            item.mq = mq
            self.mq = mq

        else:
            self.mq = item.mq

        log.debug(self.mq)

    def probedDevicesListView_currentChanged(self, item):
        self.device_uri = item.device_uri
        self.updateModelQuery(item)
        log.debug(self.device_uri)

    def probeUpdatePushButton_clicked(self):
        self.updateProbedDevicesPage()

    def searchFiltersPushButton_clicked(self):
        if self.settingsDlg():
            self.updateProbedDevicesPage()

    def manualFindPushButton_clicked(self):
        dlg = SetupManualFind(self.bus, self)
        if dlg.exec_loop() == QDialog.Accepted:
            QApplication.setOverrideCursor(QApplication.waitCursor)

            cups_uri, sane_uri, fax_uri = device.makeuri(self.hpiod_sock, self.hpssd_sock, dlg.param)

            if cups_uri:
                back_end, is_hp, bus, model, serial, dev_file, host, port = device.parseDeviceURI(cups_uri)
                name = ''
                if self.bus == 'net':
                    try:
                        name = socket.gethostbyaddr(host)[0]
                    except socket.herror:
                        name = ''

                QApplication.restoreOverrideCursor()
                self.updateProbedDevicesPage(['%s "%s" "%s" "%s"' % (cups_uri, model, model, name)], dlg.param)
            else:
                QApplication.restoreOverrideCursor()
                self.updateProbedDevicesPage([], dlg.param)

    #
    # PPD
    #

    def updatePPDPage(self, ppds=None):
        QApplication.setOverrideCursor(QApplication.waitCursor)
        back_end, is_hp, bus, model, serial, dev_file, host, port = device.parseDeviceURI(self.device_uri)
        log.debug("Searching for PPDs in: %s" % sys_cfg.dirs.ppd)

        if ppds is None or not ppds:
            ppds = []

            for f in utils.walkFiles(sys_cfg.dirs.ppd, pattern="HP*ppd*;hp*ppd*", abs_paths=True):
                ppds.append(f)

        default_model = utils.xstrip(model.replace('series', '').replace('Series', ''), '_')
        stripped_model = default_model.lower().replace('hp-', '').replace('hp_', '')
        
        self.ppd_list = cups.getPPDFile(stripped_model, ppds)
        log.debug(self.ppd_list)
        self.ppdListView.clear()

        if self.ppd_list:
            for ppd in self.ppd_list:
                if ppd.endswith('.gz'):
                    nickname = gzip.GzipFile(ppd, 'r').read(4096)
                else:
                    nickname = file(ppd, 'r').read(4096)

                try:
                    desc = nickname_pat.search(nickname).group(1)
                except AttributeError:
                    desc = self.__tr("ERROR: No description available. Is this a valid PPD file?")

                PPDListViewItem(self.ppdListView, ppd, desc)

            if self.ppd_list:
                i = self.ppdListView.firstChild()
                self.ppdListView.setCurrentItem(i)
                self.ppdListView.setSelected(i, True)
                self.ppd_file = self.ppdListView.currentItem().ppd_file
                log.debug(self.ppd_file)

        else:
            self.FailureUI(self.__tr('<b>PPD not file found.</b><p>An appropriate PPD file could not be found. Please check your HPLIP install, use <i>Select Other...</i>, or download one from linuxprinting.org.'))

        QApplication.restoreOverrideCursor()

    def ppdListView_currentChanged(self,a0):
        self.ppd_file = a0.ppd_file
        log.debug(self.ppd_file)


    def otherPPDPushButton_clicked(self):
        ppd_file = unicode(QFileDialog.getOpenFileName(sys_cfg.dirs.ppd, "PPD Files (*.ppd *.ppd.gz);;All Files (*)", self, "open file dialog", "Choose a PPD file"))

        if ppd_file and os.path.exists(ppd_file):
            self.updatePPDPage([ppd_file])
        else:
            self.updatePPDPage()

    def ppdDefaultsPushButton_clicked(self):
        self.updatePPDPage()



    #
    # PRINTER/FAX INFORMATION PAGE
    #

    def setDefaultPrinterName(self):
        installed_print_devices = device.getSupportedCUPSDevices(['hp'])  
        log.debug(installed_print_devices)

        back_end, is_hp, bus, model, serial, dev_file, host, port = device.parseDeviceURI(self.device_uri)
        default_model = utils.xstrip(model.replace('series', '').replace('Series', ''), '_')

        printer_name = default_model

        # Check for duplicate names
        if self.device_uri in installed_print_devices and \
            printer_name in installed_print_devices[self.device_uri]:
                i = 2
                while True:
                    t = printer_name + "_%d" % i
                    if t not in installed_print_devices[self.device_uri]:
                        printer_name += "_%d" % i
                        break
                    i += 1

        self.printer_name_ok = True
        self.printerNameLineEdit.setText(printer_name)
        self.printerNameLineEdit.setPaletteBackgroundColor(self.bg)
        self.defaultPrinterNamePushButton.setEnabled(False)
        self.printer_name = printer_name

    def printerNameLineEdit_textChanged(self,a0):
        self.printer_name = str(a0)
        self.defaultPrinterNamePushButton.setEnabled(True)
        installed_print_devices = device.getSupportedCUPSDevices(['hp'])

        if not self.printer_name or (self.device_uri in installed_print_devices and \
            self.printer_name in installed_print_devices[self.device_uri]):
                self.setNextEnabled(self.PrinterNamePage, False)
                self.printer_name_ok = False
                
                if not self.printer_name:
                    QToolTip.add(self.printerNameLineEdit, self.__tr('You must enter a name for the printer.'))
                else:
                    QToolTip.add(self.printerNameLineEdit, self.__tr('A printer already exists with this name. Please choose a different name.'))
                
                self.printerNameLineEdit.setPaletteBackgroundColor(QColor(0xff, 0x99, 0x99))

        else:
            self.printerNameLineEdit.setPaletteBackgroundColor(self.bg)
            self.printer_name_ok = True
            if self.fax_name_ok:
                self.setNextEnabled(self.PrinterNamePage, True)

            QToolTip.remove(self.printerNameLineEdit)

        if not self.printer_name:
            self.printer_name_ok = False
            self.setNextEnabled(self.PrinterNamePage, False)

    def printerLocationLineEdit_textChanged(self, a0):
        self.location = str(a0)

    def printerDescriptionLineEdit_textChanged(self,a0):
        self.desc = str(a0)

    def faxLocationLineEdit_textChanged(self,a0):
        self.fax_location = str(a0)

    def faxDescriptionLineEdit_textChanged(self,a0):
        self.fax_desc = str(a0)
    
    def defaultPrinterNamePushButton_clicked(self):
        self.setDefaultPrinterName()
        self.defaultPrinterNamePushButton.setEnabled(False)

    def setDefaultFaxName(self):
        installed_fax_devices = device.getSupportedCUPSDevices(['hpfax'])  
        log.debug(installed_fax_devices)

        self.fax_uri = self.device_uri.replace('hp:', 'hpfax:')

        back_end, is_hp, bus, model, serial, dev_file, host, port = device.parseDeviceURI(self.fax_uri)
        default_model = utils.xstrip(model.replace('series', '').replace('Series', ''), '_')

        fax_name = default_model + "_fax"

        # Check for duplicate names
        if self.fax_uri in installed_fax_devices and \
            fax_name in installed_fax_devices[self.fax_uri]:
                i = 2
                while True:
                    t = fax_name + "_%d" % i
                    if t not in installed_fax_devices[self.fax_uri]:
                        fax_name += "_%d" % i
                        break
                    i += 1

        self.fax_name_ok = True
        self.faxNameLineEdit.setText(fax_name)
        self.faxNameLineEdit.setPaletteBackgroundColor(self.bg)
        self.defaultFaxNamePushButton.setEnabled(False)
        self.fax_name = fax_name

    def faxNameLineEdit_textChanged(self, a0):
        self.fax_name = str(a0)
        self.defaultFaxNamePushButton.setEnabled(True)

        installed_fax_devices = device.getSupportedCUPSDevices(['hpfax'])

        if not self.fax_name or (self.fax_uri in installed_fax_devices and \
            self.fax_name in installed_fax_devices[self.fax_uri]):
                self.setNextEnabled(self.PrinterNamePage, False)
                self.fax_name_ok = False
                
                if not self.fax_name:
                    QToolTip.add(self.faxNameLineEdit, self.__tr('You must enter a fax name.'))
                else:
                    QToolTip.add(self.faxNameLineEdit, self.__tr('A fax already exists with this name. Please choose a different name.'))
                
                self.faxNameLineEdit.setPaletteBackgroundColor(QColor(0xff, 0x99, 0x99))
        else:
            self.fax_name_ok = True
            self.faxNameLineEdit.setPaletteBackgroundColor(self.bg)
            
            if self.printer_name_ok:
                self.setNextEnabled(self.PrinterNamePage, True)

            QToolTip.remove(self.faxNameLineEdit)

        if not self.fax_name:
            self.fax_name_ok = False
            self.setNextEnabled(self.PrinterNamePage, False)

    def faxNumberLineEdit_textChanged(self, a0):
        self.fax_number = str(a0)

    def faxNameCoLineEdit_textChanged(self, a0):
        self.fax_name_company = str(a0)

    def faxCheckBox_clicked(self):
        pass

    def faxCheckBox_toggled(self, a0):
        self.setup_fax = bool(a0)

        if not self.setup_fax and not self.fax_name_ok:
            self.setDefaultFaxName()

    def printTestPageCheckBox_toggled(self, a0):
        self.print_test_page = bool(a0)

    def defaultFaxNamePushButton_clicked(self):
        self.setDefaultFaxName()
        self.defaultFaxNamePushButton.setEnabled(False)

    def readwriteFaxInformation(self, read=True):
        try:
            QApplication.setOverrideCursor(QApplication.waitCursor)

            d = fax.FaxDevice(self.fax_uri)

            try:
                d.open()
            except Error:
                self.FailureUI(self.__tr("Unable to communicate with the device. Please check the device and try again."))
            else:
                try:
                    tries = 0
                    ok = True

                    while True:
                        tries += 1

                        try:
                            if read:
                                self.fax_number = d.getPhoneNum()
                                self.fax_name_company = d.getStationName()
                            else:
                                d.setStationName(self.fax_name_company)
                                d.setPhoneNum(self.fax_number)
                        
                        except Error:
                            self.FailureUI(self.__tr("<b>Device I/O Error</b><p>Could not communicate with device. Device may be busy."))
                            time.sleep(5)
                            ok = False

                            if tries > 12:
                                break

                        else:
                            ok = True
                            break

                finally:
                    d.close()

                if ok and read:
                    self.faxNumberLineEdit.setText(self.fax_number)
                    self.faxNameCoLineEdit.setText(self.fax_name_company)

        finally:
            QApplication.restoreOverrideCursor()

    #
    # SETUP PRINTER/FAX
    #

    def setupPrinter(self):
        QApplication.setOverrideCursor(QApplication.waitCursor)

        cups.addPrinter(self.printer_name, self.device_uri, self.location, self.ppd_file, self.desc)

        installed_print_devices = device.getSupportedCUPSDevices(['hp']) 

        log.debug(installed_print_devices)

        if self.device_uri not in installed_print_devices or \
            self.printer_name not in installed_print_devices[self.device_uri]:

            self.FailureUI(self.__tr("<b>Printer queue setup failed.</b><p>Please restart CUPS and try again."))
        else:
            service.sendEvent(self.hpssd_sock, EVENT_CUPS_QUEUES_CHANGED, device_uri=self.device_uri)

        QApplication.restoreOverrideCursor()

    def setupFax(self):
        QApplication.setOverrideCursor(QApplication.waitCursor)

        ppds = []

        for f in utils.walkFiles(sys_cfg.dirs.ppd, pattern="HP*ppd*;hp*ppd*", abs_paths=True):
            ppds.append(f)

        for f in ppds:
            if f.find('HP-Fax') >= 0:
                fax_ppd = f
                log.debug("Found PDD file: %s" % fax_ppd)
                break
        else:
            self.FailureUI(self.__tr("<b>Unable to find HP fax PPD file.</b><p>Please check you HPLIP installation and try again."))
            QApplication.restoreOverrideCursor()
            return

        cups.addPrinter(self.fax_name, self.fax_uri, self.fax_location, fax_ppd, self.fax_desc)

        installed_fax_devices = device.getSupportedCUPSDevices(['hpfax']) 

        log.debug(installed_fax_devices)

        if self.fax_uri not in installed_fax_devices or \
            self.fax_name not in installed_fax_devices[self.fax_uri]:

            self.FailureUI(self.__tr("<b>Fax queue setup failed.</b><p>Please restart CUPS and try again."))
        else:
            service.sendEvent(self.hpssd_sock, EVENT_CUPS_QUEUES_CHANGED, device_uri=self.fax_uri)

        QApplication.restoreOverrideCursor()

    def accept(self):
        if self.print_test_page:
            try:
                d = device.Device(self.device_uri)
            except Error, e:
                self.FailureUI(self.__tr("<b>Device error:</b><p>%s (%s)." % (e.msg, e.opt)))

            else:
                try:
                    d.open()
                except Error:
                    self.FailureUI(self.__tr("<b>Unable to print to printer.</b><p>Please check device and try again."))
                else:
                    if d.isIdleAndNoError():
                        d.close()

                        try:
                            d.printTestPage(self.printer_name)
                        except Error, e:
                            if e.opt == ERROR_NO_CUPS_QUEUE_FOUND_FOR_DEVICE:
                                self.FailureUI(self.__tr("<b>No CUPS queue found for device.</b><p>Please install the printer in CUPS and try again."))
                            else:
                                self.FailureUI(self.__tr("<b>Printer Error</b><p>An error occured: %s (code=%d)." % (e.msg, e.opt)))
                    else:
                        self.FailureUI(self.__tr("<b>Printer Error.</b><p>Printer is busy, offline, or in an error state. Please check the device and try again."))
                        d.close()

        self.hpiod_sock.close()
        self.hpssd_sock.close()

        QWizard.accept(self)


    def reject(self):
        self.hpiod_sock.close()
        self.hpssd_sock.close()

        QWizard.reject(self)

    def FailureUI(self, error_text):
        log.error(str(error_text))
        QMessageBox.critical(self,
                             self.caption(),
                             error_text,
                              QMessageBox.Ok,
                              QMessageBox.NoButton,
                              QMessageBox.NoButton)

    def __tr(self, s, c=None):
        return qApp.translate("SetupForm", s, c)