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

        self.installed_queues = [p.name for p in cups.getPrinters()]

        back_end, is_hp, bus, model, serial, dev_file, host, zc, 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 self.installed_print_devices and \
            printer_name in self.installed_print_devices[self.device_uri]:
                i = 2
                while True:
                    t = printer_name + "_%d" % i
                    if t not in self.installed_print_devices[self.device_uri]:
                        printer_name += "_%d" % i
                        break
                    i += 1

        self.printer_name_ok = True
        self.printerNameLineEdit.setText(printer_name)
        log.debug(printer_name)
        self.printerNameLineEdit.setPaletteBackgroundColor(self.bg)
        self.defaultPrinterNamePushButton.setEnabled(False)
        self.printer_name = printer_name
Example #2
0
    def setDefaultPrinterName(self):
        self.installed_print_devices = device.getSupportedCUPSDevices(['hp'])
        log.debug(self.installed_print_devices)

        self.installed_queues = [p.name for p in cups.getPrinters()]

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

        printer_name = default_model
        installed_printer_names = device.getSupportedCUPSPrinterNames(['hp'])
        # Check for duplicate names
        if (self.device_uri in self.installed_print_devices and printer_name in self.installed_print_devices[self.device_uri]) \
           or (printer_name in installed_printer_names):
                i = 2
                while True:
                    t = printer_name + "_%d" % i
                    if (t not in installed_printer_names) and (self.device_uri not in self.installed_print_devices or t not in self.installed_print_devices[self.device_uri]):
                        printer_name += "_%d" % i
                        break
                    i += 1

        self.printer_name_ok = True
        self.PrinterNameLineEdit.setText(printer_name)
        log.debug(printer_name)
        self.printer_name = printer_name
Example #3
0
    def setDefaultPrinterName(self):
        self.installed_print_devices = device.getSupportedCUPSDevices(['hp'])
        #self.installed_print_devices = device.getSupportedCUPSDevices('*')
        log.debug(self.installed_print_devices)

        self.installed_queues = [p.name for p in cups.getPrinters()]

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

        printer_name = default_model

        installed_printer_names = device.getSupportedCUPSPrinterNames(['hp'])
        # Check for duplicate names
        if (self.device_uri in self.installed_print_devices and printer_name in self.installed_print_devices[self.device_uri]) \
           or (printer_name in installed_printer_names):
                i = 2
                while True:
                    t = printer_name + "_%d" % i
                    if (t not in installed_printer_names) and (self.device_uri not in self.installed_print_devices or t not in self.installed_print_devices[self.device_uri]):
                        printer_name += "_%d" % i
                        break
                    i += 1

        self.printer_name_ok = True
        self.printerNameLineEdit.setText(printer_name)
        log.debug(printer_name)
        self.printerNameLineEdit.setPaletteBackgroundColor(self.bg)
        self.defaultPrinterNamePushButton.setEnabled(False)
        self.printer_name = printer_name
Example #4
0
    def addPrinterFaxList(self):  # printers=True, faxes=False):
        widget = self.getWidget()

        layout = QGridLayout(widget, 1, 1, 5, 10, "layout")

        self.printernameTextLabel = QLabel(widget, "printernameTextLabel")
        layout.addWidget(self.printernameTextLabel, 0, 0)

        self.printerComboBox = QComboBox(0, widget, "printerComboBox")
        layout.addWidget(self.printerComboBox, 0, 1)

        #print self.cur_device.device_type
        if self.cur_device.device_type == DEVICE_TYPE_PRINTER:
            self.addGroupHeading("printer_list_heading", self.__tr("Printer"))
            self.printernameTextLabel.setText(self.__tr("Printer Name:"))
        else:
            self.addGroupHeading("fax_list_heading", self.__tr("Fax"))
            self.printernameTextLabel.setText(self.__tr("Fax Name:"))

        self.printers = cups.getPrinters()
        self.cur_printer = None
        for p in self.printers:
            if p.device_uri == self.cur_device.device_uri:

                self.printerComboBox.insertItem(p.name)

                if self.cur_printer is None:
                    self.cur_printer = p.name

        if self.cur_printer is None:
            #log.error("No fax queue found")
            self.y = 0
            self.clear()

            #if printers and faxes:
            if self.cur_device.device_type == DEVICE_TYPE_PRINTER:
                self.addGroupHeading(
                    "error",
                    self.__tr("ERROR: No CUPS queue found for device."))
            else:
                self.addGroupHeading(
                    "error",
                    self.__tr("ERROR: No CUPS fax queue found for device."))

            return False

        else:
            self.connect(self.printerComboBox,
                         SIGNAL("activated(const QString&)"),
                         self.printerComboBox_activated)

            self.addWidget(widget, "printer_list")
            return True
Example #5
0
def getFaxDevice(device_uri=None,
                 printer_name=None,
                 callback=None,
                 fax_type=FAX_TYPE_NONE,
                 disable_dbus=False):

    if fax_type == FAX_TYPE_NONE:
        if device_uri is None and printer_name is not None:
            printers = cups.getPrinters()

            for p in printers:
                if p.name.lower() == printer_name.lower():
                    device_uri = p.device_uri
                    break
            else:
                raise Error(ERROR_DEVICE_NOT_FOUND)

        if device_uri is not None:
            mq = device.queryModelByURI(device_uri)
            fax_type = mq['fax-type']

    log.debug("fax-type=%d" % fax_type)

    if fax_type in (FAX_TYPE_BLACK_SEND_EARLY_OPEN,
                    FAX_TYPE_BLACK_SEND_LATE_OPEN):
        from pmlfax import PMLFaxDevice
        return PMLFaxDevice(device_uri, printer_name, callback, fax_type,
                            disable_dbus)

    elif fax_type == FAX_TYPE_SOAP:
        from soapfax import SOAPFaxDevice
        return SOAPFaxDevice(device_uri, printer_name, callback, fax_type,
                             disable_dbus)

    elif fax_type == FAX_TYPE_LEDMSOAP:
        from ledmsoapfax import LEDMSOAPFaxDevice
        return LEDMSOAPFaxDevice(device_uri, printer_name, callback, fax_type,
                                 disable_dbus)

    elif fax_type == FAX_TYPE_MARVELL:
        from marvellfax import MarvellFaxDevice
        return MarvellFaxDevice(device_uri, printer_name, callback, fax_type,
                                disable_dbus)

    elif fax_type == FAX_TYPE_LEDM:
        from ledmfax import LEDMFaxDevice
        return LEDMFaxDevice(device_uri, printer_name, callback, fax_type,
                             disable_dbus)

    else:
        raise Error(ERROR_DEVICE_DOES_NOT_SUPPORT_OPERATION)
Example #6
0
    def setDefaultPrinterName(self):
        self.installed_print_devices = device.getSupportedCUPSDevices(['hp'])
        #self.installed_print_devices = device.getSupportedCUPSDevices('*')
        log.debug(self.installed_print_devices)

        self.installed_queues = [p.name for p in cups.getPrinters()]

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

        printer_name = default_model

        installed_printer_names = device.getSupportedCUPSPrinterNames(['hp'])
        # Check for duplicate names
        if (self.device_uri in self.installed_print_devices and printer_name in self.installed_print_devices[self.device_uri]) \
           or (printer_name in installed_printer_names):
            warn_text = self.__tr(
                "<b>One or more print queues already exist for this device: %s</b>.<br> <b>Would you like to install another print queue for this device ?</b>"
                % ', '.join([
                    printer.encode('utf-8')
                    for printer in installed_printer_names
                    if printer_name in printer
                ]))
            if (QMessageBox.warning(self, self.caption(), warn_text,
                                    QMessageBox.Yes, QMessageBox.No,
                                    QMessageBox.NoButton) == QMessageBox.Yes):

                i = 2
                while True:
                    t = printer_name + "_%d" % i
                    if (t not in installed_printer_names) and (
                            self.device_uri not in self.installed_print_devices
                            or t not in self.installed_print_devices[
                                self.device_uri]):
                        printer_name += "_%d" % i
                        break
                    i += 1
            else:
                self.close()

        self.printer_name_ok = True
        self.printerNameLineEdit.setText(printer_name)
        log.debug(printer_name)
        self.printerNameLineEdit.setPaletteBackgroundColor(self.bg)
        self.defaultPrinterNamePushButton.setEnabled(False)
        self.printer_name = printer_name
Example #7
0
    def setDefaultPrinterName(self):
        self.installed_print_devices = device.getSupportedCUPSDevices(["hp"])
        # self.installed_print_devices = device.getSupportedCUPSDevices('*')
        log.debug(self.installed_print_devices)

        self.installed_queues = [p.name for p in cups.getPrinters()]

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

        printer_name = default_model

        installed_printer_names = device.getSupportedCUPSPrinterNames(["hp"])
        # Check for duplicate names
        if (
            self.device_uri in self.installed_print_devices
            and printer_name in self.installed_print_devices[self.device_uri]
        ) or (printer_name in installed_printer_names):
            warn_text = self.__tr(
                "<b>One or more print queues already exist for this device: %s</b>.<br> <b>Would you like to install another print queue for this device ?</b>"
                % ", ".join([printer.encode("utf-8") for printer in installed_printer_names if printer_name in printer])
            )
            if (
                QMessageBox.warning(
                    self, self.caption(), warn_text, QMessageBox.Yes, QMessageBox.No, QMessageBox.NoButton
                )
                == QMessageBox.Yes
            ):

                i = 2
                while True:
                    t = printer_name + "_%d" % i
                    if (t not in installed_printer_names) and (
                        self.device_uri not in self.installed_print_devices
                        or t not in self.installed_print_devices[self.device_uri]
                    ):
                        printer_name += "_%d" % i
                        break
                    i += 1
            else:
                self.close()

        self.printer_name_ok = True
        self.printerNameLineEdit.setText(printer_name)
        log.debug(printer_name)
        self.printerNameLineEdit.setPaletteBackgroundColor(self.bg)
        self.defaultPrinterNamePushButton.setEnabled(False)
        self.printer_name = printer_name
Example #8
0
    def addPrinterFaxList(self): # printers=True, faxes=False):
        widget = self.getWidget()

        layout = QGridLayout(widget,1,1,5,10,"layout")

        self.printernameTextLabel = QLabel(widget,"printernameTextLabel")
        layout.addWidget(self.printernameTextLabel,0,0)

        self.printerComboBox = QComboBox(0,widget,"printerComboBox")
        layout.addWidget(self.printerComboBox,0,1)

        #print self.cur_device.device_type
        if self.cur_device.device_type == DEVICE_TYPE_PRINTER:
            self.addGroupHeading("printer_list_heading", self.__tr("Printer"))
            self.printernameTextLabel.setText(self.__tr("Printer Name:"))
        else:
            self.addGroupHeading("fax_list_heading", self.__tr("Fax"))
            self.printernameTextLabel.setText(self.__tr("Fax Name:"))

        self.printers = cups.getPrinters()
        self.cur_printer = None
        for p in self.printers:
            if p.device_uri == self.cur_device.device_uri:

                self.printerComboBox.insertItem(p.name)

                if self.cur_printer is None:
                    self.cur_printer = p.name

        if self.cur_printer is None:
            #log.error("No fax queue found")
            self.y = 0
            self.clear()

            #if printers and faxes:
            if self.cur_device.device_type == DEVICE_TYPE_PRINTER:
                self.addGroupHeading("error", self.__tr("ERROR: No CUPS queue found for device."))
            else:
                self.addGroupHeading("error", self.__tr("ERROR: No CUPS fax queue found for device."))

            return False

        else:
            self.connect(self.printerComboBox, SIGNAL("activated(const QString&)"), self.printerComboBox_activated)

            self.addWidget(widget, "printer_list")
            return True
Example #9
0
def getFaxDevice(device_uri=None, printer_name=None, callback=None, fax_type=FAX_TYPE_NONE, disable_dbus=False):

    if fax_type == FAX_TYPE_NONE:
        if device_uri is None and printer_name is not None:
            printers = cups.getPrinters()

            for p in printers:
                if p.name.lower() == printer_name.lower():
                    device_uri = p.device_uri
                    break
            else:
                raise Error(ERROR_DEVICE_NOT_FOUND)

        if device_uri is not None:
            mq = device.queryModelByURI(device_uri)
            fax_type = mq["fax-type"]

    log.debug("fax-type=%d" % fax_type)

    if fax_type in (FAX_TYPE_BLACK_SEND_EARLY_OPEN, FAX_TYPE_BLACK_SEND_LATE_OPEN):
        from .pmlfax import PMLFaxDevice

        return PMLFaxDevice(device_uri, printer_name, callback, fax_type, disable_dbus)

    elif fax_type == FAX_TYPE_SOAP:
        from .soapfax import SOAPFaxDevice

        return SOAPFaxDevice(device_uri, printer_name, callback, fax_type, disable_dbus)

    elif fax_type == FAX_TYPE_LEDMSOAP:
        from .ledmsoapfax import LEDMSOAPFaxDevice

        return LEDMSOAPFaxDevice(device_uri, printer_name, callback, fax_type, disable_dbus)

    elif fax_type == FAX_TYPE_MARVELL:
        from .marvellfax import MarvellFaxDevice

        return MarvellFaxDevice(device_uri, printer_name, callback, fax_type, disable_dbus)

    elif fax_type == FAX_TYPE_LEDM:
        from .ledmfax import LEDMFaxDevice

        return LEDMFaxDevice(device_uri, printer_name, callback, fax_type, disable_dbus)

    else:
        raise Error(ERROR_DEVICE_DOES_NOT_SUPPORT_OPERATION)
Example #10
0
    def onDeviceChange(self, cur_device=None, updating=False):
        if cur_device is not None:
            log.debug("ScrollView.onDeviceChange(%s)" % cur_device.device_uri)
        else:
            log.debug("ScrollView.onDeviceChange(None)")

        self.cur_device = cur_device

        if self.cur_device is not None and self.cur_device.supported:
            #if not updating or not self.cur_printer:
            if not self.cur_printer:
                try:
                    cur_printer = self.cur_device.cups_printers[0]
                except IndexError:
                    log.error("Printer list empty")  # Shouldn't happen!
                    self.cur_printer = None
                    return

                #self.isFax()
                self.printers = cups.getPrinters()
                self.onPrinterChange(cur_printer)
                self.cur_printer = cur_printer

            #else:
            if 1:
                QApplication.setOverrideCursor(QApplication.waitCursor)
                try:
                    if 1:
                        #try:
                        self.fillControls()
                    #except Exception, e:
                    #    log.exception()
                finally:
                    QApplication.restoreOverrideCursor()

        else:
            log.debug("Unsupported device")
            self.y = 0
            self.clear()

            self.addGroupHeading(
                "error",
                self.__tr("ERROR: No device found or unsupported device."))
Example #11
0
    def onDeviceChange(self, cur_device=None, updating=False):
        if cur_device is not None:
            log.debug("ScrollView.onDeviceChange(%s)" % cur_device.device_uri)
        else:
            log.debug("ScrollView.onDeviceChange(None)")

        self.cur_device = cur_device

        if self.cur_device is not None and self.cur_device.supported:
            #if not updating or not self.cur_printer:
            if not self.cur_printer:
                try:
                    cur_printer = self.cur_device.cups_printers[0]
                except IndexError:
                    log.error("Printer list empty") # Shouldn't happen!
                    self.cur_printer = None
                    return
               
                #self.isFax()
                self.printers = cups.getPrinters()
                self.onPrinterChange(cur_printer)
                self.cur_printer = cur_printer

            #else:
            if 1:
                QApplication.setOverrideCursor(QApplication.waitCursor)
                try:
                    if 1:
                    #try:
                        self.fillControls()
                    #except Exception, e:
                    #    log.exception()
                finally:
                    QApplication.restoreOverrideCursor()

        else:
            log.debug("Unsupported device")
            self.y = 0
            self.clear()

            self.addGroupHeading("error", self.__tr("ERROR: No device found or unsupported device."))
Example #12
0
    def __init__(self, bus=['usb', 'par'], device_uri=None, printer_name=None,
                 parent=None, name=None, fl=0):

        QMainWindow.__init__(self,parent,name,fl)

        self.pc = None
        self.device_uri = device_uri
        self.printer_name = printer_name
        self.init_failed = False

        self.setIcon(load_pixmap('hp_logo', '128x128'))

        self.setCentralWidget(QWidget(self,"qt_central_widget"))
        self.FormLayout = QGridLayout(self.centralWidget(),1,1,11,6,"FormLayout")

        self.languageChange()

        self.resize(QSize(600,480).expandedTo(self.minimumSizeHint()))
        self.clearWState(Qt.WState_Polished)

        if self.device_uri and self.printer_name:
            log.error("You may not specify both a printer (-p) and a device (-d).")
            self.device_uri, self.printer_name = None, None

        if not self.device_uri and not self.printer_name:
            probed_devices = device.probeDevices(bus=bus, filter={'pcard-type': (operator.eq, 1)})
            cups_printers = cups.getPrinters()
            log.debug(probed_devices)
            log.debug(cups_printers)
            max_deviceid_size, x, devices = 0, 0, {}

            for d in probed_devices:
                if d.startswith('hp:'):
                    printers = []
                    for p in cups_printers:
                        if p.device_uri == d:
                            printers.append(p.name)
                    devices[x] = (d, printers)
                    x += 1
                    max_deviceid_size = max(len(d), max_deviceid_size)

            if x == 0:
                from nodevicesform import NoDevicesForm
                self.FailureUI(self.__tr("<p><b>No devices found that support photo card access.</b><p>Please make sure your device is properly installed and try again."))
                self.init_failed = True

            elif x == 1:
                log.info(log.bold("Using device: %s" % devices[0][0]))
                self.device_uri = devices[0][0]

            else:
                from choosedevicedlg import ChooseDeviceDlg
                dlg = ChooseDeviceDlg(devices)
                if dlg.exec_loop() == QDialog.Accepted:
                    self.device_uri = dlg.device_uri
                else:
                    self.init_failed = True

        self.dbus_avail, self.service, session_bus = device.init_dbus()

        self.UnloadView = ScrollUnloadView(self.service,
            self.centralWidget(), self, "UnloadView")

        self.FormLayout.addWidget(self.UnloadView,0,0)


        if not self.init_failed:
            try:
                self.cur_device = device.Device(device_uri=self.device_uri,
                                                 printer_name=self.printer_name)
            except Error, e:
                log.error("Invalid device URI or printer name.")
                self.FailureUI("<b>Invalid device URI or printer name.</b><p>Please check the parameters to hp-print and try again.")
                self.init_failed = True

            else:
                self.device_uri = self.cur_device.device_uri
                user_conf.set('last_used', 'device_uri', self.device_uri)

                log.debug(self.device_uri)

                self.statusBar().message(self.device_uri)
Example #13
0
    def __init__(self,
                 bus='cups',
                 device_uri=None,
                 printer_name=None,
                 num_copies=None,
                 contrast=None,
                 quality=None,
                 reduction=None,
                 fit_to_page=None,
                 parent=None,
                 name=None,
                 modal=0,
                 fl=0):

        QMainWindow.__init__(self, parent, name, fl)

        self.setIcon(load_pixmap('hp_logo', '128x128'))

        self.cur_device_uri = device_uri
        self.printer_name = printer_name
        self.init_failed = False
        self.num_copies = num_copies
        self.contrast = contrast
        self.quality = quality
        self.reduction = reduction
        self.fit_to_page = fit_to_page

        self.setCentralWidget(QWidget(self, "qt_central_widget"))
        self.FormLayout = QGridLayout(self.centralWidget(), 1, 1, 11, 6,
                                      "FormLayout")
        self.resize(QSize(600, 480).expandedTo(self.minimumSizeHint()))
        self.clearWState(Qt.WState_Polished)
        self.languageChange()

        if self.cur_device_uri and self.printer_name:
            log.error(
                "You may not specify both a printer (-p) and a device (-d).")
            self.FailureUI(
                self.__tr(
                    "<p><b>You may not specify both a printer (-p) and a device (-d)."
                ))
            self.cur_device_uri, self.printer_name = None, None
            self.init_failed = True

        self.cups_printers = cups.getPrinters()
        log.debug(self.cups_printers)

        if not self.cur_device_uri and not self.printer_name:
            t = device.probeDevices(bus=bus,
                                    filter={'copy-type': (operator.gt, 0)})
            probed_devices = []

            for d in t:
                if d.startswith('hp:'):
                    probed_devices.append(d)

            log.debug(probed_devices)

            max_deviceid_size, x, devices = 0, 0, {}

            for d in probed_devices:
                printers = []
                for p in self.cups_printers:
                    if p.device_uri == d:
                        printers.append(p.name)
                devices[x] = (d, printers)
                x += 1
                max_deviceid_size = max(len(d), max_deviceid_size)

            if x == 0:
                from nodevicesform import NoDevicesForm
                self.FailureUI(
                    self.__tr(
                        "<p><b>No devices found.</b><p>Please make sure your device is properly installed and try again."
                    ))
                self.init_failed = True

            elif x == 1:
                log.info(log.bold("Using device: %s" % devices[0][0]))
                self.cur_device_uri = devices[0][0]

            else:
                from choosedevicedlg import ChooseDeviceDlg
                dlg = ChooseDeviceDlg(devices)  #, ['hp'])

                if dlg.exec_loop() == QDialog.Accepted:
                    self.cur_device_uri = dlg.device_uri
                else:
                    self.init_failed = True

        self.CopyView = ScrollCopyView(None,
                                       num_copies=num_copies,
                                       contrast=contrast,
                                       quality=quality,
                                       reduction=reduction,
                                       fit_to_page=fit_to_page,
                                       parent=self.centralWidget(),
                                       form=self)

        self.FormLayout.addWidget(self.CopyView, 0, 0)

        self.cur_device = self.cur_device_uri

        if not self.init_failed:
            try:
                self.cur_device = copier.PMLCopyDevice(
                    device_uri=self.cur_device_uri,
                    printer_name=self.printer_name)
            except Error:
                log.error("Invalid device URI or printer name.")
                self.FailureUI(
                    "<b>Invalid device URI or printer name.</b><p>Please check the parameters to hp-print and try again."
                )
                self.init_failed = True

            else:

                if self.cur_device.copy_type == COPY_TYPE_NONE:
                    self.FailureUI(
                        self.__tr(
                            "<b>Sorry, make copies functionality is not implemented for this device.</b>"
                        ))
                    self.close()
                    return

                self.cur_device_uri = self.cur_device.device_uri
                user_conf.set('last_used', 'device_uri', self.cur_device_uri)

                log.debug(self.cur_device_uri)

                self.statusBar().message(self.cur_device.device_uri)

        QTimer.singleShot(0, self.InitialUpdate)
Example #14
0
                    cups.resetOptions()

                    if mime_type in ["application/x-cshell",
                                     "application/x-perl",
                                     "application/x-python",
                                     "application/x-shell",
                                     "text/plain",] and prettyprint:

                        cups.addOption('prettyprint')

                    if nup > 1:
                        cups.addOption('number-up=%d' % nup)

                    while True:

                        cups_printers = cups.getPrinters()
                        printer_state = cups.IPP_PRINTER_STATE_STOPPED
                        for p in cups_printers:
                            if p.name == printer_name:
                                printer_state = p.state

                        log.debug("Printer state = %d" % printer_state)

                        if printer_state == cups.IPP_PRINTER_STATE_IDLE:
                            log.debug("Printer name = %s file = %s" % (printer_name, path))
                            path = to_unicode(path, 'utf-8')

                            sent_job_id = cups.printFile(printer_name, path, os.path.basename(path))
                            log.info("\nRendering file '%s' (job %d)..." % (path, sent_job_id))
                            log.debug("Job ID=%d" % sent_job_id)
                            break
Example #15
0
    def executeSendFax(self):
        self.NextButton.setEnabled(False)
        self.BackButton.setEnabled(False)
        self.CheckTimer.stop()
        self.busy = True
        phone_num_list = []

        ppd_file = cups.getPPD(self.printer_name)

        if ppd_file is not None and os.path.exists(ppd_file):
            if open(ppd_file, 'rb').read().find(b'HP Fax') == -1:
                FailureUI(
                    self,
                    self.__tr(
                        "<b>Fax configuration error.</b><p>The CUPS fax queue for '%s' is incorrectly configured.<p>Please make sure that the CUPS fax queue is configured with the 'HPLIP Fax' Model/Driver."
                        % self.printer_name))
                self.close()
                return

        beginWaitCursor()

        mq = device.queryModelByURI(self.device_uri)

        self.dev = fax.getFaxDevice(self.device_uri, self.printer_name, None,
                                    mq['fax-type'])

        try:
            try:
                self.dev.open()
            except Error as e:
                log.warn(e.msg)

            try:
                self.dev.queryDevice(quick=True)
            except Error as e:
                log.error("Query device error (%s)." % e.msg)
                self.dev.error_state = ERROR_STATE_ERROR

        finally:
            self.dev.close()
            endWaitCursor()

        if self.dev.error_state > ERROR_STATE_MAX_OK and \
            self.dev.error_state not in (ERROR_STATE_LOW_SUPPLIES, ERROR_STATE_LOW_PAPER):

            FailureUI(
                self,
                self.__tr(
                    "<b>Device is busy or in an error state (code=%s)</b><p>Please wait for the device to become idle or clear the error and try again."
                    % self.dev.status_code))
            self.NextButton.setEnabled(True)
            return

        # Check to make sure queue in CUPS is idle
        self.cups_printers = cups.getPrinters()
        for p in self.cups_printers:
            if p.name == self.printer_name:
                if p.state == cups.IPP_PRINTER_STATE_STOPPED:
                    FailureUI(
                        self,
                        self.__tr(
                            "<b>The CUPS queue for '%s' is in a stopped or busy state.</b><p>Please check the queue and try again."
                            % self.printer_name))
                    self.NextButton.setEnabled(False)
                    return
                break

        log.debug("Recipient list:")

        for p in self.recipient_list:
            entry = self.db.get(p)
            phone_num_list.append(entry)
            log.debug("Name=%s Number=%s" % (entry["name"], entry["fax"]))

        log.debug("File list:")

        for f in self.file_list:
            log.debug(f)

        self.dev.sendEvent(EVENT_START_FAX_JOB, self.printer_name, 0, '')

        if not self.dev.sendFaxes(
                phone_num_list, self.file_list, self.cover_page_message,
                self.cover_page_re, self.cover_page_func,
                self.preserve_formatting, self.printer_name, self.update_queue,
                self.event_queue):

            FailureUI(
                self,
                self.__tr(
                    "<b>Send fax is active.</b><p>Please wait for operation to complete."
                ))
            self.dev.sendEvent(EVENT_FAX_JOB_FAIL, self.printer_name, 0, '')
            self.busy = False
            self.send_fax_active = False
            #self.NextButton.setEnabled(False)
            self.setCancelCloseButton()
            return

        self.send_fax_active = True
        self.setCancelCloseButton()
        self.SendFaxTimer = QTimer(self)
        self.connect(self.SendFaxTimer, SIGNAL('timeout()'),
                     self.SendFaxTimer_timeout)
        self.SendFaxTimer.start(1000)  # 1 sec UI updates
Example #16
0
    def updateInfoTable(self):
        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        self.DynamicTableWidget.clear()
        self.DynamicTableWidget.setRowCount(0)
        self.DynamicTableWidget.setColumnCount(0)
        flags = Qt.ItemIsSelectable | Qt.ItemIsEnabled

        while self.TabWidget.count() > 3:
            self.TabWidget.removeTab(3)

        self.DynamicTableWidget.clear()
        self.DynamicTableWidget.setRowCount(0)
        self.DynamicTableWidget.setColumnCount(len(self.headers))
        self.DynamicTableWidget.setHorizontalHeaderLabels(self.headers)

        #
        # Static Data
        #

        try:
            d = device.Device(self.device_uri, None)
        except Error:
            QApplication.restoreOverrideCursor()
            FailureUI(self, self.__tr("<b>Unable to open device %s.</b>"%(self.device_uri)))
            #self.close()
            return

        self.StaticTableWidget.clear()

        self.StaticTableWidget.setColumnCount(len(self.headers))
        self.StaticTableWidget.setHorizontalHeaderLabels(self.headers)

        mq_keys = list(d.mq.keys())
        mq_keys.sort()

        self.StaticTableWidget.setRowCount(len(mq_keys))

        for row, key in enumerate(mq_keys):
            i = QTableWidgetItem(QString(key))
            i.setFlags(flags)
            self.StaticTableWidget.setItem(row, 0, i)

            i = QTableWidgetItem(QString(str(d.mq[key])))
            i.setFlags(flags)
            self.StaticTableWidget.setItem(row, 1, i)

        self.StaticTableWidget.resizeColumnToContents(0)
        self.StaticTableWidget.resizeColumnToContents(1)
        self.StaticTableWidget.setSortingEnabled(True)
        self.StaticTableWidget.sortItems(0)

        #
        # Dynamic Data
        #

        try:
            try:
                d.open()
                d.queryDevice()
            except Error as e:
                QApplication.restoreOverrideCursor()
                FailureUI(self, self.__tr("<b>Unable to open device %s.</b>"%(self.device_uri)))
                #self.close()
                return

            dq_keys = list(d.dq.keys())
            dq_keys.sort()

            self.DynamicTableWidget.setRowCount(len(dq_keys))

            for row, key in enumerate(dq_keys):
                i = QTableWidgetItem(QString(key))
                i.setFlags(flags)
                self.DynamicTableWidget.setItem(row, 0, i)

                i = QTableWidgetItem(QString(str(d.dq[key])))
                i.setFlags(flags)
                self.DynamicTableWidget.setItem(row, 1, i)


            self.DynamicTableWidget.resizeColumnToContents(0)
            self.DynamicTableWidget.resizeColumnToContents(1)
            self.DynamicTableWidget.setSortingEnabled(True)
            self.DynamicTableWidget.sortItems(0)

        finally:
            d.close()

        #
        # History Table
        #

        self.HistoryTableWidget.clear()
        self.HistoryTableWidget.setRowCount(0)

        if d.device_type == DEVICE_TYPE_FAX:
            self.history_headers[1] = self.__tr("Fax")
        else:
            self.history_headers[1] = self.__tr("Printer")

        self.HistoryTableWidget.setColumnCount(len(self.history_headers))
        self.HistoryTableWidget.setHorizontalHeaderLabels(self.history_headers)

        history = d.queryHistory()
        history.reverse()
        self.HistoryTableWidget.setRowCount(len(history))

        for row, h in enumerate(history):
            dt = QDateTime()
            dt.setTime_t(int(h.timedate))
            dt = value_str(dt)

            ess = device.queryString(h.event_code, 0)

            for col, t in enumerate([dt, h.printer_name,
                           to_unicode(h.event_code), ess,
                           h.username, to_unicode(h.job_id),
                           h.title]):

                i = QTableWidgetItem(QString(t))
                i.setFlags(flags)
                self.HistoryTableWidget.setItem(row, col, i)

        self.HistoryTableWidget.resizeColumnToContents(0)
        self.HistoryTableWidget.resizeColumnToContents(1)
        self.HistoryTableWidget.setSortingEnabled(True)
        self.HistoryTableWidget.sortItems(0)

        #
        # Printer Data
        #

        printers = cups.getPrinters()

        for p in printers:
            if p.device_uri == self.device_uri:
                Tab = QWidget()
                Tab.setObjectName(QString(p.name))

                GridLayout = QGridLayout(Tab)
                GridLayout.setObjectName(QString("GridLayout-%s" % p.name))

                Table = QTableWidget(Tab)
                Table.setAlternatingRowColors(True)
                Table.setSelectionMode(QAbstractItemView.SingleSelection)
                Table.setSelectionBehavior(QAbstractItemView.SelectRows)
                Table.setVerticalScrollMode(QAbstractItemView.ScrollPerItem)
                Table.setHorizontalScrollMode(QAbstractItemView.ScrollPerPixel)
                Table.setGridStyle(Qt.DotLine)
                Table.setObjectName(QString("Table-%s" % p.name))
                GridLayout.addWidget(Table, 0, 0, 1, 1)
                self.TabWidget.addTab(Tab, QString(p.name))

                Table.setColumnCount(len(self.headers))
                Table.setHorizontalHeaderLabels(self.headers)

                cups.resetOptions()
                cups.openPPD(p.name)
                current_options = dict(cups.getOptions())

                #current_options['cups_error_log_level'] = cups.getErrorLogLevel()

                try:
                    f = open(os.path.expanduser('~/.cups/lpoptions'))
                except IOError as e:
                    log.debug(str(e))
                    current_options['lpoptions_file_data'] = QString("(%s)"%str(e))
                else:
                    text = f.read()
                    for d in text.splitlines():
                        if p.name in d:
                            current_options['lpoptions_file_data'] = d
                            break
                    else:
                        current_options['lpoptions_file_data'] = self.__tr("(no data)")

                keys = list(current_options.keys())
                keys.sort()

                Table.setRowCount(len(keys))

                for row, key in enumerate(keys):
                    i = QTableWidgetItem(QString(key))
                    i.setFlags(flags)
                    Table.setItem(row, 0, i)

                    if key == 'printer-state':
                        state = int(current_options[key])
                        if state == cups.IPP_PRINTER_STATE_IDLE:
                            i = QTableWidgetItem(self.__tr("idle (%s)"%state))
                        elif state == cups.IPP_PRINTER_STATE_PROCESSING:
                            i = QTableWidgetItem(self.__tr("busy/printing (%s)"%state))
                        elif state == cups.IPP_PRINTER_STATE_STOPPED:
                            i = QTableWidgetItem(self.__tr("stopped (%s)"%state))
                        else:
                            i = QTableWidgetItem(QString(str(state)))
                    else:
                        i = QTableWidgetItem(QString(str(current_options[key])))

                    i.setFlags(flags)
                    Table.setItem(row, 1, i)

                Table.resizeColumnToContents(0)
                Table.resizeColumnToContents(1)
                Table.setSortingEnabled(True)
                Table.sortItems(0)

        cups.closePPD()
        self.TabWidget.setCurrentIndex(0)
        QApplication.restoreOverrideCursor()
Example #17
0
    def executeSendFax(self):
        self.NextButton.setEnabled(False)
        self.BackButton.setEnabled(False)
        self.CheckTimer.stop()
        self.busy = True
        phone_num_list = []

        ppd_file = cups.getPPD(self.printer_name)

        if ppd_file is not None and os.path.exists(ppd_file):
            if open(ppd_file, 'rb').read().find(b'HP Fax') == -1:
                FailureUI(self, self.__tr("<b>Fax configuration error.</b><p>The CUPS fax queue for '%s' is incorrectly configured.<p>Please make sure that the CUPS fax queue is configured with the 'HPLIP Fax' Model/Driver."%self.printer_name))
                self.close()
                return

        beginWaitCursor()

        mq = device.queryModelByURI(self.device_uri)

        self.dev = fax.getFaxDevice(self.device_uri,
                                   self.printer_name, None,
                                   mq['fax-type'])

        try:
            try:
                self.dev.open()
            except Error as e:
                log.warn(e.msg)

            try:
                self.dev.queryDevice(quick=True)
            except Error as e:
                log.error("Query device error (%s)." % e.msg)
                self.dev.error_state = ERROR_STATE_ERROR

        finally:
            self.dev.close()
            endWaitCursor()

        if self.dev.error_state > ERROR_STATE_MAX_OK and \
            self.dev.error_state not in (ERROR_STATE_LOW_SUPPLIES, ERROR_STATE_LOW_PAPER):

            FailureUI(self, self.__tr("<b>Device is busy or in an error state (code=%s)</b><p>Please wait for the device to become idle or clear the error and try again."%self.dev.status_code))
            self.NextButton.setEnabled(True)
            return

        # Check to make sure queue in CUPS is idle
        self.cups_printers = cups.getPrinters()
        for p in self.cups_printers:
            if p.name == self.printer_name:
                if p.state == cups.IPP_PRINTER_STATE_STOPPED:
                    FailureUI(self, self.__tr("<b>The CUPS queue for '%s' is in a stopped or busy state.</b><p>Please check the queue and try again."%self.printer_name))
                    self.NextButton.setEnabled(False)
                    return
                break

        log.debug("Recipient list:")

        for p in self.recipient_list:
            entry = self.db.get(p)
            phone_num_list.append(entry)
            log.debug("Name=%s Number=%s" % (entry["name"], entry["fax"]))

        log.debug("File list:")

        for f in self.file_list:
            log.debug(f)

        self.dev.sendEvent(EVENT_START_FAX_JOB, self.printer_name, 0, '')

        if not self.dev.sendFaxes(phone_num_list, self.file_list, self.cover_page_message,
                                  self.cover_page_re, self.cover_page_func, self.preserve_formatting,
                                  self.printer_name, self.update_queue, self.event_queue):

            FailureUI(self, self.__tr("<b>Send fax is active.</b><p>Please wait for operation to complete."))
            self.dev.sendEvent(EVENT_FAX_JOB_FAIL, self.printer_name, 0, '')
            self.busy = False
            self.send_fax_active = False
            #self.NextButton.setEnabled(False)
            self.setCancelCloseButton()
            return

        self.send_fax_active = True
        self.setCancelCloseButton()
        self.SendFaxTimer = QTimer(self)
        self.connect(self.SendFaxTimer, SIGNAL('timeout()'), self.SendFaxTimer_timeout)
        self.SendFaxTimer.start(1000) # 1 sec UI updates
Example #18
0
    def __init__(self,
                 bus=['usb', 'par'],
                 device_uri=None,
                 printer_name=None,
                 parent=None,
                 name=None,
                 fl=0):

        QMainWindow.__init__(self, parent, name, fl)

        self.pc = None
        self.device_uri = device_uri
        self.printer_name = printer_name
        self.init_failed = False

        self.setIcon(load_pixmap('hp_logo', '128x128'))

        self.setCentralWidget(QWidget(self, "qt_central_widget"))
        self.FormLayout = QGridLayout(self.centralWidget(), 1, 1, 11, 6,
                                      "FormLayout")

        self.languageChange()

        self.resize(QSize(600, 480).expandedTo(self.minimumSizeHint()))
        self.clearWState(Qt.WState_Polished)

        if self.device_uri and self.printer_name:
            log.error(
                "You may not specify both a printer (-p) and a device (-d).")
            self.device_uri, self.printer_name = None, None

        if not self.device_uri and not self.printer_name:
            probed_devices = device.probeDevices(
                bus=bus, filter={'pcard-type': (operator.eq, 1)})
            cups_printers = cups.getPrinters()
            log.debug(probed_devices)
            log.debug(cups_printers)
            max_deviceid_size, x, devices = 0, 0, {}

            for d in probed_devices:
                if d.startswith('hp:'):
                    printers = []
                    for p in cups_printers:
                        if p.device_uri == d:
                            printers.append(p.name)
                    devices[x] = (d, printers)
                    x += 1
                    max_deviceid_size = max(len(d), max_deviceid_size)

            if x == 0:
                from .nodevicesform import NoDevicesForm
                self.FailureUI(
                    self.__tr(
                        "<p><b>No devices found that support photo card access.</b><p>Please make sure your device is properly installed and try again."
                    ))
                self.init_failed = True

            elif x == 1:
                log.info(log.bold("Using device: %s" % devices[0][0]))
                self.device_uri = devices[0][0]

            else:
                from .choosedevicedlg import ChooseDeviceDlg
                dlg = ChooseDeviceDlg(devices)
                if dlg.exec_loop() == QDialog.Accepted:
                    self.device_uri = dlg.device_uri
                else:
                    self.init_failed = True

        self.dbus_avail, self.service, session_bus = device.init_dbus()

        self.UnloadView = ScrollUnloadView(self.service, self.centralWidget(),
                                           self, "UnloadView")

        self.FormLayout.addWidget(self.UnloadView, 0, 0)

        if not self.init_failed:
            try:
                self.cur_device = device.Device(device_uri=self.device_uri,
                                                printer_name=self.printer_name)
            except Error as e:
                log.error("Invalid device URI or printer name.")
                self.FailureUI(
                    "<b>Invalid device URI or printer name.</b><p>Please check the parameters to hp-print and try again."
                )
                self.init_failed = True

            else:
                self.device_uri = self.cur_device.device_uri
                user_conf.set('last_used', 'device_uri', self.device_uri)

                log.debug(self.device_uri)

                self.statusBar().message(self.device_uri)

        QTimer.singleShot(0, self.initialUpdate)
Example #19
0
    def __init__(self, bus='cups', device_uri=None, printer_name=None,
                num_copies=None, contrast=None, quality=None,
                reduction=None, fit_to_page=None,
                parent=None, name=None, modal=0, fl=0):

        QMainWindow.__init__(self,parent,name,fl)

        self.setIcon(load_pixmap('hp_logo', '128x128'))

        self.cur_device_uri = device_uri
        self.printer_name = printer_name
        self.init_failed = False
        self.num_copies = num_copies
        self.contrast = contrast
        self.quality = quality
        self.reduction = reduction
        self.fit_to_page = fit_to_page

        self.setCentralWidget(QWidget(self,"qt_central_widget"))
        self.FormLayout = QGridLayout(self.centralWidget(),1,1,11,6,"FormLayout")
        self.resize(QSize(600,480).expandedTo(self.minimumSizeHint()))
        self.clearWState(Qt.WState_Polished)
        self.languageChange()

        if self.cur_device_uri and self.printer_name:
            log.error("You may not specify both a printer (-p) and a device (-d).")
            self.FailureUI(self.__tr("<p><b>You may not specify both a printer (-p) and a device (-d)."))
            self.cur_device_uri, self.printer_name = None, None
            self.init_failed = True

        self.cups_printers = cups.getPrinters()
        log.debug(self.cups_printers)

        if not self.cur_device_uri and not self.printer_name:
            t = device.probeDevices(bus=bus, filter={'copy-type': (operator.gt, 0)})
            probed_devices = []

            for d in t:
                if d.startswith('hp:'):
                    probed_devices.append(d)

            log.debug(probed_devices)

            max_deviceid_size, x, devices = 0, 0, {}

            for d in probed_devices:
                printers = []
                for p in self.cups_printers:
                    if p.device_uri == d:
                        printers.append(p.name)
                devices[x] = (d, printers)
                x += 1
                max_deviceid_size = max(len(d), max_deviceid_size)

            if x == 0:
                from nodevicesform import NoDevicesForm
                self.FailureUI(self.__tr("<p><b>No devices found.</b><p>Please make sure your device is properly installed and try again."))
                self.init_failed = True

            elif x == 1:
                log.info(log.bold("Using device: %s" % devices[0][0]))
                self.cur_device_uri = devices[0][0]


            else:
                from choosedevicedlg import ChooseDeviceDlg
                dlg = ChooseDeviceDlg(devices) #, ['hp'])

                if dlg.exec_loop() == QDialog.Accepted:
                    self.cur_device_uri = dlg.device_uri
                else:
                    self.init_failed = True


        self.CopyView = ScrollCopyView(None, num_copies=num_copies,
                                        contrast=contrast, quality=quality,
                                        reduction=reduction, fit_to_page=fit_to_page,
                                        parent=self.centralWidget(), form=self)

        self.FormLayout.addWidget(self.CopyView,0,0)

        self.cur_device = self.cur_device_uri

        if not self.init_failed:
            try:
                self.cur_device = copier.PMLCopyDevice(device_uri=self.cur_device_uri,
                                            printer_name=self.printer_name)
            except Error:
                log.error("Invalid device URI or printer name.")
                self.FailureUI("<b>Invalid device URI or printer name.</b><p>Please check the parameters to hp-print and try again.")
                self.init_failed = True

            else:

                if self.cur_device.copy_type == COPY_TYPE_NONE:
                    self.FailureUI(self.__tr("<b>Sorry, make copies functionality is not implemented for this device.</b>"))
                    self.close()
                    return

                self.cur_device_uri = self.cur_device.device_uri
                user_conf.set('last_used', 'device_uri',  self.cur_device_uri)

                log.debug(self.cur_device_uri)

                self.statusBar().message(self.cur_device.device_uri)


        QTimer.singleShot(0, self.InitialUpdate)
Example #20
0
    def __init__(self,
                 device_uri,
                 printer_name,
                 args,
                 parent=None,
                 name=None,
                 modal=0,
                 fl=0):

        QMainWindow.__init__(self, parent, name, fl)

        self.setIcon(load_pixmap('hp_logo', '128x128'))

        self.init_failed = False
        self.device_uri = device_uri
        self.dev = None
        self.printer_name = printer_name
        bus = ['cups']
        self.filename = ''
        self.username = prop.username
        self.args = args
        self.setCentralWidget(QWidget(self, "qt_central_widget"))
        self.FormLayout = QGridLayout(self.centralWidget(), 1, 1, 11, 6,
                                      "FormLayout")
        self.resize(QSize(600, 480).expandedTo(self.minimumSizeHint()))
        self.clearWState(Qt.WState_Polished)
        self.languageChange()

        #        if self.device_uri and self.printer_name:
        #            log.error("You may not specify both a printer (-p) and a device (-d).")
        #            self.FailureUI(self.__tr("<p><b>You may not specify both a printer (-p) and a device (-d)."))
        #            self.device_uri, self.printer_name = None, None
        #            self.init_failed = True

        self.cups_printers = cups.getPrinters()
        log.debug(self.cups_printers)

        if self.printer_name:
            found = False
            for p in self.cups_printers:
                if p.name == printer_name:
                    self.device_uri = p.device_uri
                    found = True
                    break

            if not found:
                self.FailureUI(
                    self.__tr(
                        "<b>Unknown printer name: %1</b><p>Please check the printer name and try again."
                    ).arg(self.printer_name))

            if found and not p.device_uri.startswith('hpfax:/'):
                self.FailureUI(
                    self.__tr(
                        "You must specify a printer that has a device URI in the form 'hpfax:/...'"
                    ))
                self.init_failed = True

        if not self.device_uri and not self.printer_name:
            t = device.probeDevices(
                bus=bus, filter={'fax-type': (operator.gt, FAX_TYPE_NONE)})
            #print t
            probed_devices = []

            for d in t:
                probed_devices.append(d.replace('hp:/', 'hpfax:/'))

            #print probed_devices

            probed_devices = utils.uniqueList(probed_devices)
            log.debug(probed_devices)

            max_deviceid_size, x, devices = 0, 0, {}

            for d in probed_devices:
                printers = []
                for p in self.cups_printers:
                    #print p.device_uri, d
                    if p.device_uri == d:
                        #print "OK"
                        printers.append(p.name)

                devices[x] = (d, printers)
                x += 1
                max_deviceid_size = max(len(d), max_deviceid_size)

            x = len(devices)

            #print devices

            if x == 0:
                from nodevicesform import NoDevicesForm
                self.FailureUI(
                    self.__tr(
                        "<p><b>No devices found.</b><p>Please make sure your device is properly installed and try again."
                    ))
                self.init_failed = True

            elif x == 1:
                log.info(log.bold("Using device: %s" % devices[0][0]))
                self.device_uri = devices[0][0]

            else:
                from chooseprinterdlg import ChoosePrinterDlg
                dlg = ChoosePrinterDlg(self.cups_printers, ['hpfax'])

                if dlg.exec_loop() == QDialog.Accepted:
                    self.device_uri = dlg.device_uri
                else:
                    self.init_failed = True

        self.dbus_avail, self.service, session_bus = device.init_dbus()

        self.FaxView = ScrollFaxView(self.service, self.centralWidget(), self)
        self.FormLayout.addWidget(self.FaxView, 0, 0)

        if not self.init_failed:
            if not self.device_uri or not self.device_uri.startswith("hpfax:"):
                log.error("Invalid device URI: %s" % repr(device_uri))
                self.FailureUI(
                    self.__tr(
                        "<b>Invalid device URI %1.</b><p>Please check the parameters to hp-print and try again."
                    ).arg(repr(device_uri)))
                self.init_failed = True

            else:
                try:
                    self.cur_device = device.Device(
                        device_uri=self.device_uri,
                        printer_name=self.printer_name)
                except Error, e:
                    log.error("Invalid device URI or printer name.")
                    self.FailureUI(
                        "<b>Invalid device URI or printer name.</b><p>Please check the parameters to hp-print and try again."
                    )
                    self.init_failed = True

                else:
                    self.device_uri = self.cur_device.device_uri
                    user_conf.set('last_used', 'device_uri', self.device_uri)

                    log.debug(self.device_uri)

                    self.statusBar().message(self.device_uri)
Example #21
0
        log.error("hp-systray cannot be run as root. Exiting.")
        sys.exit(1)

    if ui_toolkit == 'qt3':
        if not utils.canEnterGUIMode():
            log.error("%s requires Qt3 GUI and DBus support. Exiting." % __mod__)
            sys.exit(1)
    
    else:
        if not utils.canEnterGUIMode4():
            log.error("%s requires Qt4 GUI and DBus support. Exiting." % __mod__)
            sys.exit(1)

    if not force_startup:
        # Check for any hp: or hpfax: queues. If none, exit
        if not utils.any([p.device_uri for p in cups.getPrinters()], lambda x : x.startswith('hp')):
            log.warn("No hp: or hpfax: devices found in any installed CUPS queue. Exiting.")
            sys.exit(1)

    mod.lockInstance()
    
    r1, w1 = os.pipe()
    log.debug("Creating pipe: hpssd (%d) ==> systemtray (%d)" % (w1, r1))
    
    parent_pid = os.getpid()
    child_pid1 = os.fork()
    
    if child_pid1:
        # parent (UI)
        os.close(w1)
Example #22
0
    def faxButton_clicked(self):
        self.check_timer.stop()
        phone_num_list = []

        log.debug("Current printer=%s" % self.cur_printer)
        ppd_file = cups.getPPD(self.cur_printer)

        if ppd_file is not None and os.path.exists(ppd_file):
            if file(ppd_file, 'r').read().find('HP Fax') == -1:
                self.form.FailureUI(self.__tr("<b>Fax configuration error.</b><p>The CUPS fax queue for '%1' is incorrectly configured.<p>Please make sure that the CUPS fax queue is configured with the 'HPLIP Fax' Model/Driver.").arg(self.cur_printer))
                return

        QApplication.setOverrideCursor(QApplication.waitCursor)

        self.dev = fax.getFaxDevice(self.cur_device.device_uri,
                                   self.cur_printer, None,
                                   self.cur_device.mq['fax-type'])

        try:
            try:
                self.dev.open()
            except Error as e:
                log.warn(e.msg)

            try:
                self.dev.queryDevice(quick=True)
            except Error as e:
                log.error("Query device error (%s)." % e.msg)
                self.dev.error_state = ERROR_STATE_ERROR

        finally:
            self.dev.close()
            QApplication.restoreOverrideCursor()

        if self.dev.error_state > ERROR_STATE_MAX_OK and \
            self.dev.error_state not in (ERROR_STATE_LOW_SUPPLIES, ERROR_STATE_LOW_PAPER):

            self.form.FailureUI(self.__tr("<b>Device is busy or in an error state (code=%1)</b><p>Please wait for the device to become idle or clear the error and try again.").arg(self.cur_device.status_code))
            return

        # Check to make sure queue in CUPS is idle
        self.cups_printers = cups.getPrinters()
        for p in self.cups_printers:
            if p.name == self.cur_printer:
                if p.state == cups.IPP_PRINTER_STATE_STOPPED:
                    self.form.FailureUI(self.__tr("<b>The CUPS queue for '%1' is in a stopped or busy state.</b><p>Please check the queue and try again.").arg(self.cur_printer))
                    return
                break

        log.debug("Recipient list:")

        for p in self.recipient_list:
            entry = self.db.get(p)
            phone_num_list.append(entry)
            log.debug("Name=%s Number=%s" % (entry["name"], entry["fax"]))

        log.debug("File list:")


        for f in self.file_list:
            log.debug(to_unicode(f))

        self.busy = True

        self.dev.sendEvent(EVENT_START_FAX_JOB, self.cur_printer, 0, '')

        if not self.dev.sendFaxes(phone_num_list, self.file_list, self.cover_page_message,
                                  self.cover_page_re, self.cover_page_func, self.preserve_formatting,
                                  self.cur_printer, self.update_queue, self.event_queue):

            self.form.FailureUI(self.__tr("<b>Send fax is active.</b><p>Please wait for operation to complete."))
            self.dev.sendEvent(EVENT_FAX_JOB_FAIL, self.cur_printer, 0, '')
            self.busy = False
            return


        self.waitdlg = WaitForm(0, self.__tr("Initializing..."), self.send_fax_canceled, self, modal=1)
        self.waitdlg.show()

        self.send_fax_timer = QTimer(self, "SendFaxTimer")
        self.connect(self.send_fax_timer, SIGNAL('timeout()'), self.send_fax_timer_timeout)
        self.send_fax_timer.start(1000) # 1 sec UI updates
Example #23
0
    def validate(self,
                 time_flag=DEPENDENCY_RUN_AND_COMPILE_TIME,
                 is_quiet_mode=False):
        ############ Variables #######################
        self.cups_ddk_not_req = False
        self.hpmudext_avail = False
        self.ui_toolkit = sys_conf.get('configure', 'ui-toolkit')
        org_log_location = log.get_where()

        if is_quiet_mode:
            log.set_where(log.LOG_TO_FILE)

        IS_LIBUSB01_ENABLED = sys_conf.get('configure', 'libusb01-build', 'no')
        vrs = self.get_distro_data('versions_list')
        supported_distro_vrs = self.distro_version
        if self.distro_version not in vrs and len(vrs):
            supported_distro_vrs = vrs[len(vrs) - 1]
            log.warn(log.bold("%s-%s version is not supported. Using %s-%s versions dependencies to verify and install..." \
                     %(self.distro_name, self.distro_version, self.distro_name, supported_distro_vrs)))

        tui.header("SYSTEM INFO")
        Sts, Kernel_info = utils.run("uname -r -v -o")
        Sts, Host_info = utils.run("uname -n")
        Sts, Proc_info = utils.run("uname -r -v -o")
        log.info(" Kernel: %s Host: %s Proc: %s Distribution: %s %s"\
             %(Kernel_info,Host_info,Proc_info,self.distro_name, self.distro_version))
        log.info(" Bitness: %s bit\n" % utils.getBitness())
        tui.header("HPLIP CONFIGURATION")
        v = sys_conf.get('hplip', 'version')
        if v:
            home = sys_conf.get('dirs', 'home')
            log.info("HPLIP-Version: HPLIP %s" % v)
            log.info("HPLIP-Home: %s" % home)
            if self.is_auto_installer_support():
                log.info(
                    "HPLIP-Installation: Auto installation is supported for %s distro  %s version "
                    % (self.distro_name, self.distro_version))
            else:
                log.warn(
                    "HPLIP-Installation: Auto installation is not supported for %s distro  %s version "
                    % (self.distro_name, self.distro_version))

            log.info()
            log.info(
                log.bold("Current contents of '/etc/hp/hplip.conf' file:"))
            try:
                output = open('/etc/hp/hplip.conf', 'r').read()
            except (IOError, OSError) as e:
                log.error(
                    "Could not access file: %s. Check HPLIP installation." %
                    e.strerror)
                self.num_errors += 1
            else:
                log.info(output)

            log.info()
            log.info(
                log.bold(
                    "Current contents of '/var/lib/hp/hplip.state' file:"))
            try:
                output = open(os.path.expanduser('/var/lib/hp/hplip.state'),
                              'r').read()
            except (IOError, OSError) as e:
                log.info(
                    "Plugins are not installed. Could not access file: %s" %
                    e.strerror)
            else:
                log.info(output)

            log.info()
            log.info(
                log.bold("Current contents of '~/.hplip/hplip.conf' file:"))
            try:
                output = open(os.path.expanduser('~/.hplip/hplip.conf'),
                              'r').read()
            except (IOError, OSError) as e:
                log.warn("Could not access file: %s" % e.strerror)
                self.num_warns += 1
            else:
                log.info(output)

            self.scanning_enabled = utils.to_bool(
                sys_conf.get('configure', 'scanner-build', '0'))
            log.info(" %-20s %-20s %-10s %-10s %-10s %-10s %s" %
                     ("<Package-name>", " <Package-Desc>",
                      "<Required/Optional>", "<Min-Version>",
                      "<Installed-Version>", "<Status>", "<Comment>"))

            self.dependencies.update(self.hplip_dependencies)
            if time_flag == DEPENDENCY_RUN_AND_COMPILE_TIME or time_flag == DEPENDENCY_RUN_TIME:
                tui.header(" External Dependencies")
                for dep in self.dependencies:
                    if self.dependencies[dep][7] == EXTERNALDEP:
                        self.__update_deps_info(supported_distro_vrs, dep,
                                                self.dependencies[dep])

                tui.header(" General Dependencies")
                for dep in self.dependencies:
                    if self.dependencies[dep][7] == GENERALDEP:
                        self.__update_deps_info(supported_distro_vrs, dep,
                                                self.dependencies[dep])

                tui.header(" COMPILEDEP")
                for dep in self.dependencies:
                    if self.dependencies[dep][7] == COMPILEDEP:
                        self.__update_deps_info(supported_distro_vrs, dep,
                                                self.dependencies[dep])

                tui.header(" Python Extentions")
                for dep in self.dependencies:
                    if self.dependencies[dep][7] == PYEXT:
                        self.__update_deps_info(supported_distro_vrs, dep,
                                                self.dependencies[dep])

                tui.header(" Scan Configuration")
                for dep in self.dependencies:
                    if self.dependencies[dep][7] == SCANCONF:
                        self.__update_deps_info(supported_distro_vrs, dep,
                                                self.dependencies[dep])

                tui.header(" Other Dependencies")
                for dep in self.dependencies:
                    if self.dependencies[dep][7] != SCANCONF and    \
                        self.dependencies[dep][7] != PYEXT and  \
                        self.dependencies[dep][7] != COMPILEDEP and     \
                        self.dependencies[dep][7] != GENERALDEP and     \
                        self.dependencies[dep][7] != EXTERNALDEP:
                        self.__update_deps_info(supported_distro_vrs, dep,
                                                self.dependencies[dep])

            if self.scanning_enabled:
                tui.header("DISCOVERED SCANNER DEVICES")
                if utils.which('scanimage'):
                    status, output = utils.run("scanimage -L")
                    if status != 0:
                        log.error("Failed to get Scanners information.")
                    elif 'No scanners were identified' in output:
                        log.info("No Scanner found.")
                    else:
                        log.info(output)

            if device_avail:
                #if prop.par_build:
                #tui.header("DISCOVERED PARALLEL DEVICES")
                #devices = device.probeDevices(['par'])
                #if devices:
                #f = tui.Formatter()
                #f.header = ("Device URI", "Model")
                #for d, dd in devices.items():
                #f.add((d, dd[0]))
                #f.output()
                #else:
                #log.info("No devices found.")
                #if not core.have_dependencies['ppdev']:
                #log.error("'ppdecmds_to_be_runv' kernel module not loaded.")

                if prop.usb_build:
                    tui.header("DISCOVERED USB DEVICES")

                    devices = device.probeDevices(['usb'])

                    if devices:
                        f = tui.Formatter()
                        f.header = ("Device URI", "Model")

                        for d, dd in list(devices.items()):
                            f.add((d, dd[0]))

                        f.output()

                    else:
                        log.info("No devices found.")

                tui.header("INSTALLED CUPS PRINTER QUEUES")

                lpstat_pat = re.compile(r"""(\S*): (.*)""", re.IGNORECASE)
                status, output = utils.run('lpstat -v')
                log.info()

                cups_printers = []
                plugin_sts = None
                for p in output.splitlines():
                    try:
                        match = lpstat_pat.search(p)
                        printer_name = match.group(1)
                        device_uri = match.group(2)
                        cups_printers.append((printer_name, device_uri))
                    except AttributeError:
                        pass

                log.debug(cups_printers)
                if cups_printers:
                    #non_hp = False
                    for p in cups_printers:
                        printer_name, device_uri = p

                        if device_uri.startswith("cups-pdf:/") or \
                            device_uri.startswith('ipp://'):
                            continue

                        try:
                            back_end, is_hp, bus, model, serial, dev_file, host, zc, port = \
                                device.parseDeviceURI(device_uri)
                        except Error:
                            back_end, is_hp, bus, model, serial, dev_file, host, zc, port = \
                                '', False, '', '', '', '', '', '', 1

                        #print back_end, is_hp, bus, model, serial, dev_file, host, zc, port

                        log.info(log.bold(printer_name))
                        log.info(log.bold('-' * len(printer_name)))

                        x = "Unknown"
                        if back_end == 'hpfax':
                            x = "Fax"
                        elif back_end == 'hp':
                            x = "Printer"

                        log.info("Type: %s" % x)

                        #if is_hp:
                        #    x = 'Yes, using the %s: CUPS backend.' % back_end
                        #else:
                        #    x = 'No, not using the hp: or hpfax: CUPS backend.'
                        #    non_hp = True

                        #log.info("Installed in HPLIP?: %s" % x)
                        log.info("Device URI: %s" % device_uri)

                        ppd = os.path.join('/etc/cups/ppd',
                                           printer_name + '.ppd')

                        if os.path.exists(ppd):
                            log.info("PPD: %s" % ppd)
                            nickname_pat = re.compile(
                                r'''\*NickName:\s*\"(.*)"''', re.MULTILINE)
                            try:
                                f = to_string_utf8(open(ppd, 'rb').read())
                            except IOError:
                                log.warn("Failed to read %s ppd file" % ppd)
                                desc = ''
                            else:
                                try:
                                    desc = nickname_pat.search(f).group(1)
                                except AttributeError:
                                    desc = ''

                            log.info("PPD Description: %s" % desc)

                            status, output = utils.run('lpstat -p%s' %
                                                       printer_name)
                            log.info("Printer status: %s" %
                                     output.replace("\n", ""))

                            if back_end == 'hpfax' and not 'HP Fax' in desc:
                                self.num_errors += 1
                                log.error(
                                    "Incorrect PPD file for fax queue '%s'. Fax queues must use 'HP-Fax-hplip.ppd'."
                                    % printer_name)

                            elif back_end == 'hp' and 'HP Fax' in desc:
                                self.num_errors += 1
                                log.error(
                                    "Incorrect PPD file for a print queue '%s'. Print queues must not use 'HP-Fax-hplip.ppd'."
                                    % printer_name)

                            elif back_end not in ('hp', 'hpfax'):
                                log.warn(
                                    "Printer is not HPLIP installed. Printers must use the hp: or hpfax: CUPS backend for HP-Devices."
                                )
                                self.num_warns += 1

                        if device_avail and is_hp:
                            d = None
                            try:
                                try:
                                    d = device.Device(device_uri, None, None,
                                                      None, True)
                                except Error:
                                    log.error("Device initialization failed.")
                                    continue

                                plugin = d.mq.get('plugin', PLUGIN_NONE)
                                if plugin in (PLUGIN_REQUIRED,
                                              PLUGIN_OPTIONAL):
                                    if not plugin_sts:
                                        from installer import pluginhandler
                                        pluginObj = pluginhandler.PluginHandle(
                                        )
                                        plugin_sts = pluginObj.getStatus()

                                    if plugin_sts == pluginhandler.PLUGIN_INSTALLED:
                                        self.plugin_status = PLUGIN_INSTALLED
                                        if plugin == pluginhandler.PLUGIN_REQUIRED:
                                            log.info(
                                                "Required plug-in status: Installed"
                                            )
                                        else:
                                            log.info(
                                                "Optional plug-in status: Installed"
                                            )
                                    elif plugin_sts == pluginhandler.PLUGIN_NOT_INSTALLED:
                                        self.plugin_status = PLUGIN_NOT_INSTALLED
                                        if plugin == PLUGIN_REQUIRED:
                                            self.num_errors += 1
                                            log.error(
                                                "Required plug-in status: Not installed"
                                            )
                                        else:
                                            self.num_warns += 1
                                            log.warn(
                                                "Optional plug-in status: Not installed"
                                            )
                                    elif plugin_sts == pluginhandler.PLUGIN_VERSION_MISMATCH:
                                        self.num_warns += 1
                                        self.plugin_status = pluginhandler.PLUGIN_VERSION_MISMATCH
                                        log.warn(
                                            "plug-in status: Version mismatch")

                                if bus in ('par', 'usb'):
                                    try:
                                        d.open()
                                    except Error as e:
                                        log.error(e.msg)
                                        deviceid = ''
                                    else:
                                        deviceid = d.getDeviceID()
                                        log.debug(deviceid)

                                    #print deviceid
                                    if not deviceid:
                                        log.error(
                                            "Communication status: Failed")
                                        self.comm_error_devices[
                                            printer_name] = device_uri
                                        self.num_errors += 1
                                    else:
                                        log.info("Communication status: Good")

                                elif bus == 'net':
                                    try:
                                        error_code, deviceid = d.getPML(
                                            pml.OID_DEVICE_ID)
                                    except Error:
                                        pass

                                    #print error_code
                                    if not deviceid:
                                        log.error(
                                            "Communication status: Failed")
                                        self.comm_error_devices[
                                            printer_name] = device_uri
                                        self.num_errors += 1
                                    else:
                                        log.info("Communication status: Good")

                            finally:
                                if d is not None:
                                    d.close()
                        log.info()
                else:
                    log.warn("No queues found.")

            tui.header("PERMISSION")
            #            sts,avl_grps_out =utils.run('groups')
            #            sts, out = utils.check_user_groups(self.user_grps_cmd, avl_grps_out)
            #            if sts:
            #                log.info("%-15s %-30s %-15s %-8s %-8s %-8s %s"%("groups", "user-groups","Required", "-","-", "OK",avl_grps_out))
            #            else:
            #                log.info(log.red("error: %-8s %-30s %-15s %-8s %-8s %-8s %s"%("groups", "user-groups", "Required","-", "-", "MISSING", out)))
            #                self.num_errors += 1
            #                self.missing_user_grps = out

            if self.hpmudext_avail:
                lsusb = utils.which('lsusb')
                if lsusb:
                    lsusb = os.path.join(lsusb, 'lsusb')
                    status, output = utils.run("%s -d03f0:" % lsusb)

                    if output:
                        lsusb_pat = re.compile(
                            """^Bus\s([0-9a-fA-F]{3,3})\sDevice\s([0-9a-fA-F]{3,3}):\sID\s([0-9a-fA-F]{4,4}):([0-9a-fA-F]{4,4})(.*)""",
                            re.IGNORECASE)
                        log.debug(output)
                        try:
                            import hpmudext
                        except ImportError:
                            log.error(
                                "NOT FOUND OR FAILED TO LOAD! Please reinstall HPLIP and check for the proper installation of hpmudext."
                            )
                            self.num_errors += 1

                        for o in output.splitlines():
                            ok = True
                            match = lsusb_pat.search(o)

                            if match is not None:
                                bus, dev, vid, pid, mfg = match.groups()
                                #log.info("\nHP Device 0x%x at %s:%s: " % (int(pid, 16), bus, dev))
                                result_code, deviceuri = hpmudext.make_usb_uri(
                                    bus, dev)

                                if result_code == hpmudext.HPMUD_R_OK:
                                    deviceuri = to_string_utf8(deviceuri)
                                    #    log.info("    Device URI: %s" %  deviceuri)
                                    d = None
                                    try:
                                        d = device.Device(
                                            deviceuri, None, None, None, True)
                                    except Error:
                                        continue
                                    if not d.supported:
                                        continue
                                else:
                                    log.debug(
                                        "    Device URI: (Makeuri FAILED)")
                                    continue
                                printers = cups.getPrinters()
                                printer_name = None
                                for p in printers:
                                    if p.device_uri == deviceuri:
                                        printer_name = p.name
                                        break

                                devnode = os.path.join("/", "dev", "bus",
                                                       "usb", bus, dev)

                                if not os.path.exists(devnode):
                                    devnode = os.path.join(
                                        "/", "proc", "bus", "usb", bus, dev)

                                if os.path.exists(devnode):
                                    # log.debug("    Device node: %s" % devnode)
                                    st_mode, st_ino, st_dev, st_nlink, st_uid, st_gid, \
                                       st_size, st_atime, st_mtime, st_ctime =  os.stat(devnode)

                                    getfacl = utils.which('getfacl', True)
                                    if getfacl:
                                        # log.debug("%s %s" % (getfacl, devnode))
                                        status, output = utils.run(
                                            "%s %s" % (getfacl, devnode))
                                        getfacl_out_list = output.split('\r\n')

                                        out = ''
                                        for g in getfacl_out_list:
                                            if 'getfacl' not in g and '' is not g and 'file' not in g:
                                                pat = re.compile('''.*:(.*)''')
                                                if pat.search(g):
                                                    out = out + ' ' + pat.search(
                                                        g).group(1)
                                        log.info(
                                            "%-15s %-30s %-15s %-8s %-8s %-8s %s"
                                            % ("USB", printer_name, "Required",
                                               "-", "-", "OK",
                                               "Node:'%s' Perm:'%s'" %
                                               (devnode, out)))
                                    else:
                                        log.info(
                                            "%-15s %-30s %-15s %-8s %-8s %-8s %s"
                                            % ("USB", printer_name, "Required",
                                               "-", "-", "OK",
                                               "Node:'%s' Mode:'%s'" %
                                               (devnode, st_mode & 0o777)))

            selinux_file = '/etc/selinux/config'
            if os.path.exists(selinux_file):
                tui.header("SELINUX")
                try:
                    selinux_fp = open(selinux_file, 'r')
                except IOError:
                    log.error("Failed to open %s file." % selinux_file)
                else:
                    for line in selinux_fp:
                        line = re.sub(r'\s', '', line)
                        if line == "SELINUX=enforcing":
                            self.num_warns += 1
                            log.warn("%-12s %-12s %-10s %-3s %-3s %-8s %s" \
                                          %("SELinux",  "enabled", "Optional", "-", "-", "INCOMPAT", "'SELinux needs to be disabled for Plugin printers and Fax functionality.'"))
                            self.disable_selinux = True
                            break
                    if self.disable_selinux == False:
                        log.info("%-15s %-15s %-10s %-3s %-3s %-8s %s"\
                                                  %("SELinux",  "disabled", "Optional", "-", "-", "OK", "-"))

            self.smart_install_devices = smart_install.get_smartinstall_enabled_devices(
            )
            if len(self.smart_install_devices):
                tui.header("'CD-ROM'/'Smart Install' Detected Devices")
                self.num_errors += 1
                for d in self.smart_install_devices:
                    log.error("%-30s %-20s %s " %
                              (d, "CD_ROM_Enabled",
                               "Needs to disable Smart Install"))

        else:
            log.error("HPLIP not found.")
            self.num_errors += 1

        if is_quiet_mode:
            log.set_where(org_log_location)

        return self.num_errors, self.num_warns
Example #24
0
    if ui_toolkit == 'qt3':
        if not utils.canEnterGUIMode():
            log.error("%s requires Qt3 GUI and DBus support. Exiting." %
                      __mod__)
            sys.exit(1)

    else:
        if not utils.canEnterGUIMode4():
            log.error("%s requires Qt4 GUI and DBus support. Exiting." %
                      __mod__)
            sys.exit(1)

    if not force_startup:
        # Check for any hp: or hpfax: queues. If none, exit
        if not utils.any([p.device_uri for p in cups.getPrinters()],
                         lambda x: x.startswith('hp')):
            log.warn(
                "No hp: or hpfax: devices found in any installed CUPS queue. Exiting."
            )
            sys.exit(1)

    mod.lockInstance()

    r1, w1 = os.pipe()
    log.debug("Creating pipe: hpssd (%d) ==> systemtray (%d)" % (w1, r1))

    parent_pid = os.getpid()
    child_pid1 = os.fork()

    if child_pid1:
Example #25
0
    def validate(self,time_flag=DEPENDENCY_RUN_AND_COMPILE_TIME, is_quiet_mode= False):
        ############ Variables #######################
        self.cups_ddk_not_req = False
        self.hpmudext_avail = False
        self.ui_toolkit = sys_conf.get('configure','ui-toolkit')
        org_log_location = log.get_where()

        if is_quiet_mode:
            log.set_where(log.LOG_TO_FILE)

        IS_LIBUSB01_ENABLED = sys_conf.get('configure', 'libusb01-build', 'no')
        vrs =self.get_distro_data('versions_list')
        supported_distro_vrs= self.distro_version
        if self.distro_version not in vrs and len(vrs):
            supported_distro_vrs= vrs[len(vrs)-1]
            log.warn(log.bold("%s-%s version is not supported. Using %s-%s versions dependencies to verify and install..." \
                     %(self.distro_name, self.distro_version, self.distro_name, supported_distro_vrs)))
          
        tui.header("SYSTEM INFO")
        Sts, Kernel_info =utils.run("uname -r -v -o")
        Sts, Host_info =utils.run("uname -n")
        Sts, Proc_info =utils.run("uname -r -v -o")
        log.info(" Kernel: %s Host: %s Proc: %s Distribution: %s %s"\
             %(Kernel_info,Host_info,Proc_info,self.distro_name, self.distro_version))
        log.info(" Bitness: %s bit\n"%utils.getBitness())
        tui.header("HPLIP CONFIGURATION")
        v = sys_conf.get('hplip', 'version')
        if v:
            home = sys_conf.get('dirs', 'home')
            log.info("HPLIP-Version: HPLIP %s" %v)
            log.info("HPLIP-Home: %s" %home)
            if self.is_auto_installer_support():
                log.info("HPLIP-Installation: Auto installation is supported for %s distro  %s version " %(self.distro_name, self.distro_version))
            else:
                log.warn("HPLIP-Installation: Auto installation is not supported for %s distro  %s version " %(self.distro_name, self.distro_version))

            log.info()
            log.info(log.bold("Current contents of '/etc/hp/hplip.conf' file:"))
            try:
                output = open('/etc/hp/hplip.conf', 'r').read()
            except (IOError, OSError) as e:
                log.error("Could not access file: %s. Check HPLIP installation." % e.strerror)
                self.num_errors += 1
            else:
                log.info(output)

            log.info()
            log.info(log.bold("Current contents of '/var/lib/hp/hplip.state' file:"))
            try:
                output = open(os.path.expanduser('/var/lib/hp/hplip.state'), 'r').read()
            except (IOError, OSError) as e:
                log.info("Plugins are not installed. Could not access file: %s" % e.strerror)
            else:
                log.info(output)

            log.info()
            log.info(log.bold("Current contents of '~/.hplip/hplip.conf' file:"))
            try:
                output = open(os.path.expanduser('~/.hplip/hplip.conf'), 'r').read()
            except (IOError, OSError) as e:
                log.warn("Could not access file: %s" % e.strerror)
                self.num_warns += 1
            else:
                log.info(output)

            self.scanning_enabled = utils.to_bool(sys_conf.get('configure', 'scanner-build', '0'))
            log.info(" %-20s %-20s %-10s %-10s %-10s %-10s %s"%( "<Package-name>", " <Package-Desc>", "<Required/Optional>", "<Min-Version>","<Installed-Version>", "<Status>", "<Comment>"))

            self.dependencies.update(self.hplip_dependencies)
            if time_flag == DEPENDENCY_RUN_AND_COMPILE_TIME or time_flag == DEPENDENCY_RUN_TIME:
                tui.header(" External Dependencies")
                for dep in self.dependencies:
                    if self.dependencies[dep][7] == EXTERNALDEP:
                        self.__update_deps_info(supported_distro_vrs, dep, self.dependencies[dep])

                tui.header(" General Dependencies")
                for dep in self.dependencies:
                    if self.dependencies[dep][7] == GENERALDEP:
                        self.__update_deps_info(supported_distro_vrs, dep, self.dependencies[dep])

                tui.header(" COMPILEDEP")
                for dep in self.dependencies:
                    if self.dependencies[dep][7] == COMPILEDEP:
                        self.__update_deps_info(supported_distro_vrs, dep, self.dependencies[dep])

                tui.header(" Python Extentions")
                for dep in self.dependencies:
                    if self.dependencies[dep][7] == PYEXT:
                        self.__update_deps_info(supported_distro_vrs, dep, self.dependencies[dep])

                tui.header(" Scan Configuration")
                for dep in self.dependencies:
                    if self.dependencies[dep][7] == SCANCONF:
                        self.__update_deps_info(supported_distro_vrs, dep, self.dependencies[dep])

                tui.header(" Other Dependencies")
                for dep in self.dependencies:
                    if self.dependencies[dep][7] != SCANCONF and    \
                        self.dependencies[dep][7] != PYEXT and  \
                        self.dependencies[dep][7] != COMPILEDEP and     \
                        self.dependencies[dep][7] != GENERALDEP and     \
                        self.dependencies[dep][7] != EXTERNALDEP:
                        self.__update_deps_info(supported_distro_vrs, dep, self.dependencies[dep])

            if self.scanning_enabled:
                tui.header("DISCOVERED SCANNER DEVICES")
                if utils.which('scanimage'):
                    status, output = utils.run("scanimage -L")
                    if status != 0 :
                        log.error("Failed to get Scanners information.")
                    elif 'No scanners were identified' in output:
                        log.info("No Scanner found.")
                    else:
                        log.info(output)

            if device_avail:
                #if prop.par_build:
                    #tui.header("DISCOVERED PARALLEL DEVICES")
                    #devices = device.probeDevices(['par'])
                    #if devices:
                        #f = tui.Formatter()
                        #f.header = ("Device URI", "Model")
                        #for d, dd in devices.items():
                            #f.add((d, dd[0]))
                        #f.output()
                    #else:
                        #log.info("No devices found.")
                        #if not core.have_dependencies['ppdev']:
                            #log.error("'ppdecmds_to_be_runv' kernel module not loaded.")

                if prop.usb_build:
                    tui.header("DISCOVERED USB DEVICES")

                    devices = device.probeDevices(['usb'])

                    if devices:
                        f = tui.Formatter()
                        f.header = ("Device URI", "Model")

                        for d, dd in list(devices.items()):
                            f.add((d, dd[0]))

                        f.output()

                    else:
                        log.info("No devices found.")


                tui.header("INSTALLED CUPS PRINTER QUEUES")

                lpstat_pat = re.compile(r"""(\S*): (.*)""", re.IGNORECASE)
                status, output = utils.run('lpstat -v')
                log.info()

                cups_printers = []
                plugin_sts = None
                for p in output.splitlines():
                    try:
                        match = lpstat_pat.search(p)
                        printer_name = match.group(1)
                        device_uri = match.group(2)
                        cups_printers.append((printer_name, device_uri))
                    except AttributeError:
                        pass

                log.debug(cups_printers)
                if cups_printers:
                    #non_hp = False
                    for p in cups_printers:
                        printer_name, device_uri = p

                        if device_uri.startswith("cups-pdf:/") or \
                            device_uri.startswith('ipp://'):
                            continue

                        try:
                            back_end, is_hp, bus, model, serial, dev_file, host, zc, port = \
                                device.parseDeviceURI(device_uri)
                        except Error:
                            back_end, is_hp, bus, model, serial, dev_file, host, zc, port = \
                                '', False, '', '', '', '', '', '', 1

                        #print back_end, is_hp, bus, model, serial, dev_file, host, zc, port

                        log.info(log.bold(printer_name))
                        log.info(log.bold('-'*len(printer_name)))

                        x = "Unknown"
                        if back_end == 'hpfax':
                            x = "Fax"
                        elif back_end == 'hp':
                            x = "Printer"

                        log.info("Type: %s" % x)

                        #if is_hp:
                        #    x = 'Yes, using the %s: CUPS backend.' % back_end
                        #else:
                        #    x = 'No, not using the hp: or hpfax: CUPS backend.'
                        #    non_hp = True

                        #log.info("Installed in HPLIP?: %s" % x)
                        log.info("Device URI: %s" % device_uri)

                        ppd = os.path.join('/etc/cups/ppd', printer_name + '.ppd')

                        if os.path.exists(ppd):
                            log.info("PPD: %s" % ppd)
                            nickname_pat = re.compile(r'''\*NickName:\s*\"(.*)"''', re.MULTILINE)
                            try:
                                f = to_string_utf8(open(ppd, 'rb').read())
                            except IOError:
                                log.warn("Failed to read %s ppd file"%ppd)
                                desc = ''
                            else:
                                try:
                                    desc = nickname_pat.search(f).group(1)
                                except AttributeError:
                                    desc = ''

                            log.info("PPD Description: %s" % desc)

                            status, output = utils.run('lpstat -p%s' % printer_name)
                            log.info("Printer status: %s" % output.replace("\n", ""))

                            if back_end == 'hpfax' and not 'HP Fax' in desc and desc != '':
                                self.num_errors += 1
                                log.error("Incorrect PPD file for fax queue '%s'. Fax queues must use 'HP-Fax(n)-hpcups.ppd'." % printer_name)

                            elif back_end == 'hp' and 'HP Fax' in desc and desc != '':
                                self.num_errors += 1
                                log.error("Incorrect PPD file for a print queue '%s'. Print queues must not use 'HP-Fax(n)-hpcups.ppd'." % printer_name)

                            elif back_end not in ('hp', 'hpfax'):
                                log.warn("Printer is not HPLIP installed. Printers must use the hp: or hpfax: CUPS backend for HP-Devices.")
                                self.num_warns += 1

                        if device_avail and is_hp:
                            d = None
                            try:
                                try:
                                    d = device.Device(device_uri,None, None, None, True)
                                except Error:
                                    log.error("Device initialization failed.")
                                    continue

                                plugin = d.mq.get('plugin', PLUGIN_NONE)
                                if plugin in (PLUGIN_REQUIRED, PLUGIN_OPTIONAL):
                                    if not plugin_sts:
                                        from installer import pluginhandler
                                        pluginObj = pluginhandler.PluginHandle()
                                        plugin_sts = pluginObj.getStatus()

                                    if plugin_sts == pluginhandler.PLUGIN_INSTALLED:
                                        self.plugin_status = PLUGIN_INSTALLED
                                        if plugin == pluginhandler.PLUGIN_REQUIRED:
                                            log.info("Required plug-in status: Installed")
                                        else:
                                            log.info("Optional plug-in status: Installed")
                                    elif plugin_sts == pluginhandler.PLUGIN_NOT_INSTALLED:
                                        self.plugin_status = PLUGIN_NOT_INSTALLED
                                        if plugin == PLUGIN_REQUIRED:
                                            self.num_errors += 1
                                            log.error("Required plug-in status: Not installed")
                                        else:
                                            self.num_warns +=1
                                            log.warn("Optional plug-in status: Not installed")
                                    elif plugin_sts == pluginhandler.PLUGIN_VERSION_MISMATCH:
                                        self.num_warns += 1
                                        self.plugin_status = pluginhandler.PLUGIN_VERSION_MISMATCH
                                        log.warn("plug-in status: Version mismatch")


                                if bus in ('par', 'usb'):
                                    try:
                                        d.open()
                                    except Error as e:
                                        log.error(e.msg)
                                        deviceid = ''
                                    else:
                                        deviceid = d.getDeviceID()
                                        log.debug(deviceid)

                                    #print deviceid
                                    if not deviceid:
                                        log.error("Communication status: Failed")
                                        self.comm_error_devices[printer_name] = device_uri
                                        self.num_errors += 1
                                    else:
                                        log.info("Communication status: Good")

                                elif bus == 'net':
                                    try:
                                        error_code, deviceid = d.getPML(pml.OID_DEVICE_ID)
                                    except Error:
                                        pass

                                    #print error_code
                                    if not deviceid:
                                        log.error("Communication status: Failed")
                                        self.comm_error_devices[printer_name] = device_uri
                                        self.num_errors += 1
                                    else:
                                        log.info("Communication status: Good")

                            finally:
                                if d is not None:
                                    d.close()
                        log.info()
                else:
                    log.warn("No queues found.")

            tui.header("PERMISSION")
#            sts,avl_grps_out =utils.run('groups')
#            sts, out = utils.check_user_groups(self.user_grps_cmd, avl_grps_out) 
#            if sts:
#                log.info("%-15s %-30s %-15s %-8s %-8s %-8s %s"%("groups", "user-groups","Required", "-","-", "OK",avl_grps_out))
#            else:
#                log.info(log.red("error: %-8s %-30s %-15s %-8s %-8s %-8s %s"%("groups", "user-groups", "Required","-", "-", "MISSING", out)))
#                self.num_errors += 1
#                self.missing_user_grps = out

            if self.hpmudext_avail:
                lsusb = utils.which('lsusb')
                if lsusb:
                    lsusb = os.path.join(lsusb, 'lsusb')
                    status, output = utils.run("%s -d03f0:" % lsusb)

                    if output:
                        lsusb_pat = re.compile("""^Bus\s([0-9a-fA-F]{3,3})\sDevice\s([0-9a-fA-F]{3,3}):\sID\s([0-9a-fA-F]{4,4}):([0-9a-fA-F]{4,4})(.*)""", re.IGNORECASE)
                        log.debug(output)
                        try:
                            import hpmudext
                        except ImportError:
                            log.error("NOT FOUND OR FAILED TO LOAD! Please reinstall HPLIP and check for the proper installation of hpmudext.")
                            self.num_errors += 1

                        for o in output.splitlines():
                            ok = True
                            match = lsusb_pat.search(o)

                            if match is not None:
                                bus, dev, vid, pid, mfg = match.groups()
                                #log.info("\nHP Device 0x%x at %s:%s: " % (int(pid, 16), bus, dev))
                                result_code, deviceuri = hpmudext.make_usb_uri(bus, dev)

                                if result_code == hpmudext.HPMUD_R_OK:
                                    deviceuri = to_string_utf8(deviceuri)
                                #    log.info("    Device URI: %s" %  deviceuri)
                                    d = None
                                    try:
                                        d = device.Device(deviceuri,None, None, None, True)
                                    except Error:
                                        continue
                                    if not d.supported:
                                        continue
                                else:
                                    log.debug("    Device URI: (Makeuri FAILED)")
                                    continue
                                printers = cups.getPrinters()
                                printer_name=None
                                for p in printers:
                                    if p.device_uri == deviceuri:
                                        printer_name=p.name
                                        break

                                devnode = os.path.join("/", "dev", "bus", "usb", bus, dev)

                                if not os.path.exists(devnode):
                                    devnode = os.path.join("/", "proc", "bus", "usb", bus, dev)

                                if os.path.exists(devnode):
                                   # log.debug("    Device node: %s" % devnode)
                                    st_mode, st_ino, st_dev, st_nlink, st_uid, st_gid, \
                                       st_size, st_atime, st_mtime, st_ctime =  os.stat(devnode)

                                    getfacl = utils.which('getfacl',True)
                                    if getfacl:
                                       # log.debug("%s %s" % (getfacl, devnode))
                                        status, output = utils.run("%s %s" % (getfacl, devnode))
                                        getfacl_out_list = output.split('\r\n')

                                        out =''
                                        for g in getfacl_out_list:
                                            if 'getfacl' not in g and '' is not g and 'file' not in g:
                                                pat = re.compile('''.*:(.*)''')
                                                if pat.search(g):
                                                    out = out +' '+ pat.search(g).group(1)
                                        log.info("%-15s %-30s %-15s %-8s %-8s %-8s %s"%("USB", printer_name, "Required", "-", "-", "OK", "Node:'%s' Perm:'%s'"%(devnode,out)))
                                    else:
                                        log.info("%-15s %-30s %-15s %-8s %-8s %-8s %s"%("USB", printer_name, "Required","-","-","OK", "Node:'%s' Mode:'%s'"%(devnode,st_mode&0o777)))

            # selinux_file = '/etc/selinux/config'
            # if os.path.exists(selinux_file):
            #     tui.header("SELINUX")
            #     try:
            #         selinux_fp = open(selinux_file, 'r')
            #     except IOError:
            #         log.error("Failed to open %s file."%selinux_file)
            #     else:
            #         for line in selinux_fp:
            #             line=re.sub(r'\s','',line)
            #             if line == "SELINUX=enforcing":
            #                 self.num_warns += 1
            #                 log.warn("%-12s %-12s %-10s %-3s %-3s %-8s %s" \
            #                               %("SELinux",  "enabled", "Optional", "-", "-", "INCOMPAT", "'SELinux needs to be disabled for Plugin printers and Fax functionality.'"))
            #                 self.disable_selinux = True
            #                 break
            #         if self.disable_selinux == False:
            #             log.info("%-15s %-15s %-10s %-3s %-3s %-8s %s"\
            #                                       %("SELinux",  "disabled", "Optional", "-", "-", "OK", "-"))

            self.smart_install_devices = smart_install.get_smartinstall_enabled_devices()
            if len(self.smart_install_devices):
                tui.header("'CD-ROM'/'Smart Install' Detected Devices")
                self.num_errors += 1
                for d in self.smart_install_devices:
                    log.error("%-30s %-20s %s "%(d, "CD_ROM_Enabled", "Needs to disable Smart Install"))

        else:
            log.error("HPLIP not found.")
            self.num_errors += 1

        if is_quiet_mode:
            log.set_where(org_log_location)

        return self.num_errors, self.num_warns
Example #26
0
    def updateInfoTable(self):
        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        self.DynamicTableWidget.clear()
        self.DynamicTableWidget.setRowCount(0)
        self.DynamicTableWidget.setColumnCount(0)
        flags = Qt.ItemIsSelectable | Qt.ItemIsEnabled

        while self.TabWidget.count() > 3:
            self.TabWidget.removeTab(3)

        self.DynamicTableWidget.clear()
        self.DynamicTableWidget.setRowCount(0)
        self.DynamicTableWidget.setColumnCount(len(self.headers))
        self.DynamicTableWidget.setHorizontalHeaderLabels(self.headers)

        #
        # Static Data
        #

        try:
            d = device.Device(self.device_uri, None)
        except Error:
            QApplication.restoreOverrideCursor()
            FailureUI(
                self,
                self.__tr("<b>Unable to open device %s.</b>" %
                          (self.device_uri)))
            #self.close()
            return

        self.StaticTableWidget.clear()

        self.StaticTableWidget.setColumnCount(len(self.headers))
        self.StaticTableWidget.setHorizontalHeaderLabels(self.headers)

        mq_keys = list(d.mq.keys())
        mq_keys.sort()

        self.StaticTableWidget.setRowCount(len(mq_keys))

        for row, key in enumerate(mq_keys):
            i = QTableWidgetItem(str(key))
            i.setFlags(flags)
            self.StaticTableWidget.setItem(row, 0, i)

            i = QTableWidgetItem(str(d.mq[key]))
            i.setFlags(flags)
            self.StaticTableWidget.setItem(row, 1, i)

        self.StaticTableWidget.resizeColumnToContents(0)
        self.StaticTableWidget.resizeColumnToContents(1)
        self.StaticTableWidget.setSortingEnabled(True)
        self.StaticTableWidget.sortItems(0)

        #
        # Dynamic Data
        #

        try:
            try:
                d.open()
                d.queryDevice()
            except Error as e:
                QApplication.restoreOverrideCursor()
                FailureUI(
                    self,
                    self.__tr("<b>Unable to open device %s.</b>" %
                              (self.device_uri)))
                #self.close()
                return

            dq_keys = list(d.dq.keys())
            dq_keys.sort()

            self.DynamicTableWidget.setRowCount(len(dq_keys))

            for row, key in enumerate(dq_keys):
                i = QTableWidgetItem(str(key))
                i.setFlags(flags)
                self.DynamicTableWidget.setItem(row, 0, i)

                i = QTableWidgetItem(str(d.dq[key]))
                i.setFlags(flags)
                self.DynamicTableWidget.setItem(row, 1, i)

            self.DynamicTableWidget.resizeColumnToContents(0)
            self.DynamicTableWidget.resizeColumnToContents(1)
            self.DynamicTableWidget.setSortingEnabled(True)
            self.DynamicTableWidget.sortItems(0)

        finally:
            d.close()

        #
        # History Table
        #

        self.HistoryTableWidget.clear()
        self.HistoryTableWidget.setRowCount(0)

        if d.device_type == DEVICE_TYPE_FAX:
            self.history_headers[1] = self.__tr("Fax")
        else:
            self.history_headers[1] = self.__tr("Printer")

        self.HistoryTableWidget.setColumnCount(len(self.history_headers))
        self.HistoryTableWidget.setHorizontalHeaderLabels(self.history_headers)

        history = d.queryHistory()
        history.reverse()
        self.HistoryTableWidget.setRowCount(len(history))

        for row, h in enumerate(history):
            dt = QDateTime()
            dt.setTime_t(int(h.timedate))
            dt = value_str(dt)

            ess = device.queryString(h.event_code, 0)

            for col, t in enumerate([
                    dt, h.printer_name,
                    to_unicode(h.event_code), ess, h.username,
                    to_unicode(h.job_id), h.title
            ]):

                i = QTableWidgetItem(str(t))
                i.setFlags(flags)
                self.HistoryTableWidget.setItem(row, col, i)

        self.HistoryTableWidget.resizeColumnToContents(0)
        self.HistoryTableWidget.resizeColumnToContents(1)
        self.HistoryTableWidget.setSortingEnabled(True)
        self.HistoryTableWidget.sortItems(0)

        #
        # Printer Data
        #

        printers = cups.getPrinters()

        for p in printers:
            if p.device_uri == self.device_uri:
                Tab = QWidget()
                Tab.setObjectName(str(p.name))

                GridLayout = QGridLayout(Tab)
                GridLayout.setObjectName(str("GridLayout-%s" % p.name))

                Table = QTableWidget(Tab)
                Table.setAlternatingRowColors(True)
                Table.setSelectionMode(QAbstractItemView.SingleSelection)
                Table.setSelectionBehavior(QAbstractItemView.SelectRows)
                Table.setVerticalScrollMode(QAbstractItemView.ScrollPerItem)
                Table.setHorizontalScrollMode(QAbstractItemView.ScrollPerPixel)
                Table.setGridStyle(Qt.DotLine)
                Table.setObjectName(str("Table-%s" % p.name))
                GridLayout.addWidget(Table, 0, 0, 1, 1)
                self.TabWidget.addTab(Tab, str(p.name))

                Table.setColumnCount(len(self.headers))
                Table.setHorizontalHeaderLabels(self.headers)

                cups.resetOptions()
                cups.openPPD(p.name)
                current_options = dict(cups.getOptions())

                #current_options['cups_error_log_level'] = cups.getErrorLogLevel()

                try:
                    f = open(os.path.expanduser('~/.cups/lpoptions'))
                except IOError as e:
                    log.debug(str(e))
                    current_options['lpoptions_file_data'] = str("(%s)" %
                                                                 str(e))
                else:
                    text = f.read()
                    for d in text.splitlines():
                        if p.name in d:
                            current_options['lpoptions_file_data'] = d
                            break
                    else:
                        current_options['lpoptions_file_data'] = self.__tr(
                            "(no data)")

                keys = list(current_options.keys())
                keys.sort()

                Table.setRowCount(len(keys))

                for row, key in enumerate(keys):
                    i = QTableWidgetItem(str(key))
                    i.setFlags(flags)
                    Table.setItem(row, 0, i)

                    if key == 'printer-state':
                        state = int(current_options[key])
                        if state == cups.IPP_PRINTER_STATE_IDLE:
                            i = QTableWidgetItem(self.__tr("idle (%s)" %
                                                           state))
                        elif state == cups.IPP_PRINTER_STATE_PROCESSING:
                            i = QTableWidgetItem(
                                self.__tr("busy/printing (%s)" % state))
                        elif state == cups.IPP_PRINTER_STATE_STOPPED:
                            i = QTableWidgetItem(
                                self.__tr("stopped (%s)" % state))
                        else:
                            i = QTableWidgetItem(str(state))
                    else:
                        i = QTableWidgetItem(str(current_options[key]))

                    i.setFlags(flags)
                    Table.setItem(row, 1, i)

                Table.resizeColumnToContents(0)
                Table.resizeColumnToContents(1)
                Table.setSortingEnabled(True)
                Table.sortItems(0)

        cups.closePPD()
        self.TabWidget.setCurrentIndex(0)
        QApplication.restoreOverrideCursor()
    def printButton_clicked(self):
        if self.invalid_page_range:
            self.form.FailureUI(self.__tr("<b>Cannot print: Invalid page range: %1</b><p>A valid page range is a list of pages or ranges of pages separated by commas (e.g., 1-2,4,6-7)").arg(self.pageRangeEdit.text()))
            return

        try:
            try:
                self.cur_device.open()
            except Error:
                self.form.FailureUI(self.__tr("<b>Cannot print: Device is busy or not available.</b><p>Please check device and try again."))
                return

            if 1: # Go ahead and allow - print will be queued in CUPS if not rejecting
                printers = cups.getPrinters()
                for p in printers:
                    if p.name == self.cur_printer:
                        break

                if p.state == cups.IPP_PRINTER_STATE_STOPPED:
                    self.form.FailureUI(self.__tr("<b>Cannot print: Printer is stopped.</b><p>Please START the printer to continue this print. Job will begin printing once printer is started."))

                if not p.accepting:
                    self.form.FailureUI(self.__tr("<b>Cannot print: Printer is not accepting jobs.</b><p>Please set the printer to ACCEPTING JOBS to continue printing."))
                    return

                copies = int(self.copiesSpinBox.value())
                all_pages = self.pages_button_group == 0
                page_range = unicode(self.pageRangeEdit.text())
                page_set = int(self.pageSetComboBox.currentItem())

                cups.resetOptions()
                cups.openPPD(self.cur_printer)
                current_options = dict(cups.getOptions())
                cups.closePPD()

                nup = int(current_options.get("number-up", 1))
                log.debug("number-up = %d" % nup)

                for p, t, d in self.file_list:

                    alt_nup = (nup > 1 and t == 'application/postscript' and utils.which('psnup'))

                    if utils.which('lpr'):
                        if alt_nup:
                            cmd = ' '.join(['psnup', '-%d' % nup, ''.join(['"', p, '"']), '| lpr -P', self.cur_printer])
                        else:
                            cmd = ' '.join(['lpr -P', self.cur_printer])

                        if copies > 1:
                            cmd = ' '.join([cmd, '-#%d' % copies])

                    else:
                        if alt_nup:
                            cmd = ' '.join(['psnup', '-%d' % nup, ''.join(['"', p, '"']), '| lp -c -d', self.cur_printer])
                        else:
                            cmd = ' '.join(['lp -c -d', self.cur_printer])

                        if copies > 1:
                            cmd = ' '.join([cmd, '-n%d' % copies])


                    if not all_pages and len(page_range) > 0:
                        cmd = ' '.join([cmd, '-o page-ranges=%s' % page_range])

                    if page_set > 0:
                        if page_set == 1:
                            cmd = ' '.join([cmd, '-o page-set=even'])
                        else:
                            cmd = ' '.join([cmd, '-o page-set=odd'])


                    # Job Storage
                    # self.job_storage_mode = (0=Off, 1=P&H, 2=PJ, 3=QC, 4=SJ)
                    # self.job_storage_pin = u"" (dddd)
                    # self.job_storage_use_pin = True|False
                    # self.job_storage_username = u""
                    # self.job_storage_auto_username = True|False
                    # self.job_storage_jobname = u""
                    # self.job_storage_auto_jobname = True|False
                    # self.job_storage_job_exist = (0=replace, 1=job name+(1-99))

                    if self.job_storage_avail:
                        if self.job_storage_mode: # On

                            if self.job_storage_mode == 1: # Proof and Hold
                                cmd = ' '.join([cmd, '-o HOLD=PROOF'])

                            elif self.job_storage_mode == 2: # Private Job
                                if self.job_storage_use_pin:
                                    cmd = ' '.join([cmd, '-o HOLD=ON'])
                                    cmd = ' '.join([cmd, '-o HOLDTYPE=PRIVATE'])
                                    cmd = ' '.join([cmd, '-o HOLDKEY=%s' % self.job_storage_pin.encode('ascii')])
                                else:
                                    cmd = ' '.join([cmd, '-o HOLD=PROOF'])
                                    cmd = ' '.join([cmd, '-o HOLDTYPE=PRIVATE'])

                            elif self.job_storage_mode == 3: # Quick Copy
                                cmd = ' '.join([cmd, '-o HOLD=ON'])
                                cmd = ' '.join([cmd, '-o HOLDTYPE=PUBLIC'])

                            elif self.job_storage_mode == 4: # Store Job
                                if self.job_storage_use_pin:
                                    cmd = ' '.join([cmd, '-o HOLD=STORE'])
                                    cmd = ' '.join([cmd, '-o HOLDTYPE=PRIVATE'])
                                    cmd = ' '.join([cmd, '-o HOLDKEY=%s' % self.job_storage_pin.encode('ascii')])
                                else:
                                    cmd = ' '.join([cmd, '-o HOLD=STORE'])

                            cmd = ' '.join([cmd, '-o USERNAME=%s' % self.job_storage_username.encode('ascii')\
                                .replace(" ", "_")])

                            cmd = ' '.join([cmd, '-o JOBNAME=%s' % self.job_storage_jobname.encode('ascii')\
                                .replace(" ", "_")])

                            if self.job_storage_job_exist == 1:
                                cmd = ' '.join([cmd, '-o DUPLICATEJOB=APPEND'])
                            else:
                                cmd = ' '.join([cmd, '-o DUPLICATEJOB=REPLACE'])

                        else: # Off
                            cmd = ' '.join([cmd, '-o HOLD=OFF'])


                    if not alt_nup:
                        cmd = ''.join([cmd, ' "', p, '"'])

                    log.debug("Printing: %s" % cmd)

                    code = os.system(cmd)
                    if code != 0:
                        log.error("Print command failed.")
                        self.form.FailureUI(self.__tr("Print command failed with error code %1").arg(code))

                self.form.close()

        finally:
            self.cur_device.close()
Example #28
0
    def processFile(self, path, title=''): # Process an arbitrary file ("Add file...")
        path = os.path.realpath(path)
        if not title:
            title = os.path.basename(path)

        if os.path.exists(path) and os.access(path, os.R_OK):
            mime_type = magic.mime_type(path)
            mime_type_desc = mime_type

            if mime_type == 'application/hplip-fax':
                mime_type_desc = self.MIME_TYPES_DESC[mime_type][0]

                fax_file_fd = file(path, 'r')
                header = fax_file_fd.read(fax.FILE_HEADER_SIZE)

                mg, version, pages, hort_dpi, vert_dpi, page_size, \
                    resolution, encoding, reserved1, reserved2 = self.decode_fax_header(header)

                if mg != 'hplip_g3':
                    log.error("Invalid file header. Bad magic.")
                    self.form.WarningUI(self.__tr("<b>Invalid HPLIP Fax file.</b><p>Bad magic!"))
                    return

                self.addFile(path, title, mime_type, mime_type_desc, pages)

            else:
                log.debug(repr(mime_type))
                try:
                    mime_type_desc = self.MIME_TYPES_DESC[mime_type][0]
                except KeyError:
                    self.form.WarningUI(self.__tr("<b>You are trying to add a file that cannot be directly faxed with this utility.</b><p>To print this file, use the print command in the application that created it."))
                    return
                else:
                    log.debug("Adding file: title='%s' file=%s mime_type=%s mime_desc=%s)" % (title, path, mime_type, mime_type_desc))

                    all_pages = True
                    page_range = ''
                    page_set = 0
                    #nup = 1

                    cups.resetOptions()

                    self.cups_printers = cups.getPrinters()

                    printer_state = cups.IPP_PRINTER_STATE_STOPPED
                    for p in self.cups_printers:
                        if p.name == self.cur_printer:
                            printer_state = p.state

                    log.debug("Printer state = %d" % printer_state)

                    if printer_state == cups.IPP_PRINTER_STATE_IDLE:
                        log.debug("Printing: %s on %s" % (path, self.cur_printer))
                        sent_job_id = cups.printFile(self.cur_printer, path, os.path.basename(path))
                        self.last_job_id = sent_job_id
                        job_types[sent_job_id] = mime_type # save for later
                        log.debug("Job ID=%d" % sent_job_id)

                        QApplication.setOverrideCursor(QApplication.waitCursor)

                        self.waitdlg = WaitForm(0, self.__tr("Processing fax file..."), None, self, modal=1) # self.add_fax_canceled
                        self.waitdlg.show()

                    else:
                        self.form.FailureUI(self.__tr("<b>Printer '%1' is in a stopped or error state.</b><p>Check the printer queue in CUPS and try again.").arg(self.cur_printer))
                        cups.resetOptions()
                        return

                    cups.resetOptions()
                    QApplication.restoreOverrideCursor()

        else:
            self.form.FailureUI(self.__tr("<b>Unable to add file '%1' to file list (file not found or insufficient permissions).</b><p>Check the file name and try again.").arg(path))
Example #29
0
        log.error("hp-systray cannot be run as root. Exiting.")
        sys.exit(1)

    if ui_toolkit == 'qt3':
        if not utils.canEnterGUIMode():
            log.error("%s requires Qt3 GUI and DBus support. Exiting." % __mod__)
            sys.exit(1)
    
    else:
        if not utils.canEnterGUIMode4():
            log.error("%s requires Qt4 GUI and DBus support. Exiting." % __mod__)
            sys.exit(1)

    if not force_startup:
        # Check for any hp: or hpfax: queues. If none, exit
        if not utils.any([p.device_uri for p in cups.getPrinters()], lambda x : x.startswith('hp')):
            log.warn("No hp: or hpfax: devices found in any installed CUPS queue. Exiting.")
            sys.exit(1)

    mod.lockInstance()
    
    r1, w1 = os.pipe()
    log.debug("Creating pipe: hpssd (%d) ==> systemtray (%d)" % (w1, r1))
    
    parent_pid = os.getpid()
    child_pid1 = os.fork()
    
    if child_pid1:
        # parent (UI)
        os.close(w1)
Example #30
0
    def __init__(self, device_uri, printer_name, args,
                 parent=None, name=None,
                 modal=0, fl=0):

        QMainWindow.__init__(self,parent,name,fl)

        self.setIcon(load_pixmap('hp_logo', '128x128'))

        self.init_failed = False
        self.device_uri = device_uri
        self.dev = None
        self.printer_name = printer_name
        bus = ['cups']
        self.filename = ''
        self.username = prop.username
        self.args = args
        self.setCentralWidget(QWidget(self,"qt_central_widget"))
        self.FormLayout = QGridLayout(self.centralWidget(),1,1,11,6,"FormLayout")
        self.resize(QSize(600,480).expandedTo(self.minimumSizeHint()))
        self.clearWState(Qt.WState_Polished)
        self.languageChange()

#        if self.device_uri and self.printer_name:
#            log.error("You may not specify both a printer (-p) and a device (-d).")
#            self.FailureUI(self.__tr("<p><b>You may not specify both a printer (-p) and a device (-d)."))
#            self.device_uri, self.printer_name = None, None
#            self.init_failed = True

        self.cups_printers = cups.getPrinters()
        log.debug(self.cups_printers)

        if self.printer_name:
            found = False
            for p in self.cups_printers:
                if p.name == printer_name:
                    self.device_uri = p.device_uri
                    found = True
                    break

            if not found:
                self.FailureUI(self.__tr("<b>Unknown printer name: %1</b><p>Please check the printer name and try again.").arg(self.printer_name))

            if found and not p.device_uri.startswith('hpfax:/'):
                self.FailureUI(self.__tr("You must specify a printer that has a device URI in the form 'hpfax:/...'"))
                self.init_failed = True

        if not self.device_uri and not self.printer_name:
            t = device.probeDevices(bus=bus, filter={'fax-type':(operator.gt, FAX_TYPE_NONE)})
            #print t
            probed_devices = []

            for d in t:
                probed_devices.append(d.replace('hp:/', 'hpfax:/'))

            #print probed_devices

            probed_devices = utils.uniqueList(probed_devices)
            log.debug(probed_devices)

            max_deviceid_size, x, devices = 0, 0, {}

            for d in probed_devices:
                printers = []
                for p in self.cups_printers:
                    #print p.device_uri, d
                    if p.device_uri == d:
                        #print "OK"
                        printers.append(p.name)

                devices[x] = (d, printers)
                x += 1
                max_deviceid_size = max(len(d), max_deviceid_size)

            x = len(devices)

            #print devices

            if x == 0:
                from .nodevicesform import NoDevicesForm
                self.FailureUI(self.__tr("<p><b>No devices found.</b><p>Please make sure your device is properly installed and try again."))
                self.init_failed = True

            elif x == 1:
                log.info(log.bold("Using device: %s" % devices[0][0]))
                self.device_uri = devices[0][0]

            else:
                from .chooseprinterdlg import ChoosePrinterDlg
                dlg = ChoosePrinterDlg(self.cups_printers, ['hpfax'])

                if dlg.exec_loop() == QDialog.Accepted:
                    self.device_uri = dlg.device_uri
                else:
                    self.init_failed = True

        self.dbus_avail, self.service, session_bus = device.init_dbus()

        self.FaxView = ScrollFaxView(self.service, self.centralWidget(), self)
        self.FormLayout.addWidget(self.FaxView,0,0)

        if not self.init_failed:
            if not self.device_uri or not self.device_uri.startswith("hpfax:"):
                log.error("Invalid device URI: %s" % repr(device_uri))
                self.FailureUI(self.__tr("<b>Invalid device URI %1.</b><p>Please check the parameters to hp-print and try again.").arg(repr(device_uri)));
                self.init_failed = True

            else:
                try:
                    self.cur_device = device.Device(device_uri=self.device_uri,
                                                     printer_name=self.printer_name)
                except Error as e:
                    log.error("Invalid device URI or printer name.")
                    self.FailureUI("<b>Invalid device URI or printer name.</b><p>Please check the parameters to hp-print and try again.")
                    self.init_failed = True

                else:
                    self.device_uri = self.cur_device.device_uri
                    user_conf.set('last_used', 'device_uri', self.device_uri)

                    log.debug(self.device_uri)

                    self.statusBar().message(self.device_uri)


        QTimer.singleShot(0, self.InitialUpdate)