コード例 #1
0
ファイル: wifisetupdialog.py プロジェクト: jpopelka/hplip
    def showDevicesPage(self):
        self.BackButton.setEnabled(True)
        self.setNextButton(BUTTON_NEXT)

        beginWaitCursor()
        try:
            if not self.devices:
                log.info("Searching on USB bus...")
                filter_dict = {'wifi-config': (operator.gt, WIFI_CONFIG_NONE)}

                try:
                    from base import smart_install
                except ImportError:
                    log.error("Failed to Import smart_install.py from base")
                else:
                    endWaitCursor()
                    smart_install.disable(GUI_MODE, 'qt4')
                    beginWaitCursor()

                self.devices = device.probeDevices([self.bus], 0, 0,
                                                   filter_dict, self.search)

        finally:
            endWaitCursor()

        self.clearDevicesTable()

        if self.devices:
            self.NextButton.setEnabled(True)
            self.DevicesFoundIcon.setPixmap(load_pixmap('info', '16x16'))

            if len(self.devices) == 1:
                self.DevicesFoundLabel.setText(
                    self.__tr(
                        "<b>1 wireless capable device found.</b> Click <i>Next</i> to continue."
                    ))
            else:
                self.DevicesFoundLabel.setText(
                    self.__tr(
                        "<b>%s wireless capable devices found.</b> Select the device to install and click <i>Next</i> to continue."
                        % len(self.devices)))

            self.loadDevicesTable()

        else:
            self.NextButton.setEnabled(False)
            self.DevicesFoundIcon.setPixmap(load_pixmap('error', '16x16'))
            log.error("No devices found on bus: %s" % self.bus)
            self.DevicesFoundLabel.setText(
                self.__tr(
                    "<b>No wireless capable devices found.</b><br>Plug in your printer with a USB cable and click <i>Refresh</i> to search again."
                ))

        self.displayPage(PAGE_DEVICES)
コード例 #2
0
    def showDevicesPage(self):
        self.BackButton.setEnabled(True)
        self.setNextButton(BUTTON_NEXT)

        beginWaitCursor()
        try:
            if not self.devices:
                log.info("Searching on USB bus...")
                filter_dict = {'wifi-config' : (operator.gt, WIFI_CONFIG_NONE)}

                try:
                    from base import smart_install
                except ImportError:
                    log.error("Failed to Import smart_install.py from base")
                else:
                    endWaitCursor()
                    smart_install.disable(GUI_MODE, 'qt4')
                    beginWaitCursor()

                self.devices = device.probeDevices([self.bus], 0, 0, filter_dict, self.search)

        finally:
            endWaitCursor()

        self.clearDevicesTable()

        if self.devices:
            self.NextButton.setEnabled(True)
            self.DevicesFoundIcon.setPixmap(load_pixmap('info', '16x16'))

            if len(self.devices) == 1:
                self.DevicesFoundLabel.setText(self.__tr("<b>1 wireless capable device found.</b> Click <i>Next</i> to continue."))
            else:
                self.DevicesFoundLabel.setText(self.__tr("<b>%s wireless capable devices found.</b> Select the device to install and click <i>Next</i> to continue." % len(self.devices)))

            self.loadDevicesTable()

        else:
            self.NextButton.setEnabled(False)
            self.DevicesFoundIcon.setPixmap(load_pixmap('error', '16x16'))
            log.error("No devices found on bus: %s" % self.bus)
            self.DevicesFoundLabel.setText(self.__tr("<b>No wireless capable devices found.</b><br>Plug in your printer with a USB cable and click <i>Refresh</i> to search again."))

        self.displayPage(PAGE_DEVICES)
コード例 #3
0
                #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 devices.items():
                            f.add((d, dd[0]))

                        f.output()

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

                tui.header("INSTALLED CUPS PRINTER QUEUES")
コード例 #4
0
ファイル: makecopiesform.py プロジェクト: Distrotech/hplip
    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)
コード例 #5
0
ファイル: hpfax.py プロジェクト: danwallach/VoteBox-v1
    elif o in ('-h', '--help'):
        usage()

    elif o == '--help-rest':
        usage('rest')

    elif o == '--help-man':
        usage('man')


if len( args ) == 0:
    cups11 = utils.to_bool(sys_conf.get('configure', 'cups11', '0'))

    try:
        probed_devices = device.probeDevices(['usb', 'par'], filter={'fax-type': (operator.gt, 0)})
    except Error:
        sys.exit(CUPS_BACKEND_FAILED)

    good_devices = 0
    for uri in probed_devices:
        try:
            back_end, is_hp, bus, model, serial, dev_file, host, zc, port = \
                device.parseDeviceURI(uri)
        except Error:
            continue

        mq = device.queryModelByModel(model)

        if mq.get('fax-type', FAX_TYPE_NONE) in (FAX_TYPE_MARVELL,):
            # HP Fax 3
コード例 #6
0
ファイル: printerform.py プロジェクト: danwallach/VoteBox-v1
    def __init__(self, printer_name=None, args=None,
                 parent=None,name=None,modal=0,fl=0):

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

        self.printer_name = printer_name
        self.file_list = []
        self.args = args
        self.init_failed = False

        self.statusBar()

        self.setIcon(load_pixmap('hp_logo', '128x128'))
        signal.signal(signal.SIGINT, signal.SIG_DFL)

        if not name:
            self.setName("PrinterForm")

        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()

        self.cups_printers = device.getSupportedCUPSPrinters()
        log.debug(self.cups_printers)

        if  not self.printer_name: # no -p provided
            t = device.probeDevices(['cups'])
            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.device_uri = devices[0][0]

            else:
                from .chooseprinterdlg import ChoosePrinterDlg
                dlg = ChoosePrinterDlg(self.cups_printers)
                if dlg.exec_loop() == QDialog.Accepted:
                    self.printer_name = dlg.printer_name
                    self.device_uri = dlg.device_uri
                else:
                    self.init_failed = True

        else: # -p provided
            for p in self.cups_printers:
                if p.name == self.printer_name:
                    self.device_uri = p.device_uri
                    break
            else:
                self.FailureUI("<b>Invalid printer name.</b><p>Please check the parameters to hp-print and try again.")
                self.init_failed = True


        if not self.init_failed:
            self.PrintView = ScrollPrintView(None, self.centralWidget(), self, "PrintView")
            self.FormLayout.addWidget(self.PrintView,0,0)

            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)
コード例 #7
0
    def updateProbedDevicesPage(self, devices=None, param=''):
        QApplication.setOverrideCursor(QApplication.waitCursor)

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

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

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

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

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

        self.probedDevicesListView.clear()

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

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

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

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

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

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

        if devices is None:
            FILTER_MAP = {'print' : None,
                          'none' : None,
                          'scan': 'scan-type',
                          'copy': 'copy-type',
                          'pcard': 'pcard-type',
                          'fax': 'fax-type',
                          }

            filter_dict = {}

            if prop.fax_build and prop.scan_build:
                for f in self.filter:
                    if f in FILTER_MAP:
                        filter_dict[FILTER_MAP[f]] = (operator.gt, 0)
                    else:
                        filter_dict[f] = (operator.gt, 0)
            else:
                filter_dict['scan-type'] = (operator.ge, SCAN_TYPE_NONE)

            devices = device.probeDevices([self.bus], self.timeout, self.ttl, filter_dict, self.search, net_search='slp')

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

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

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

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

        log.debug(devices)

        if devices:
            row = 0
            for d in devices:
                back_end, is_hp, bus, model, serial, dev_file, host, zc, port = device.parseDeviceURI(d)

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

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

                elif self.bus == 'net':
                    i = DeviceListViewItem(self.probedDevicesListView, d, mq, model_ui, host, devices[d][2], d)

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

                row += 1

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

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

        QApplication.restoreOverrideCursor()
        return True
コード例 #8
0
ファイル: hpfax.py プロジェクト: dhirajpatra/lti_tool
        log.set_level('debug')

    elif o in ('-h', '--help'):
        usage()

    elif o == '--help-rest':
        usage('rest')

    elif o == '--help-man':
        usage('man')

if len(args) == 0:
    cups11 = utils.to_bool(sys_conf.get('configure', 'cups11', '0'))

    try:
        probed_devices = device.probeDevices(
            ['usb', 'par'], filter={'fax-type': (operator.gt, 0)})
    except Error:
        sys.exit(CUPS_BACKEND_FAILED)

    good_devices = 0
    for uri in probed_devices:
        try:
            back_end, is_hp, bus, model, serial, dev_file, host, zc, port = \
                device.parseDeviceURI(uri)
        except Error:
            continue

        mq = device.queryModelByModel(model)

        if mq.get('fax-type', FAX_TYPE_NONE) in (FAX_TYPE_MARVELL, ):
            # HP Fax 3
コード例 #9
0
ファイル: check.py プロジェクト: incrazyboyy/RPiTC-X
                    #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 devices.items():
                            f.add((d, dd[0]))

                        f.output()

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


                tui.header("INSTALLED CUPS PRINTER QUEUES")
コード例 #10
0
ファイル: check.py プロジェクト: rfabbri/hplip
                # 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 devices.items():
                            f.add((d, dd[0]))

                        f.output()

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

                tui.header("INSTALLED CUPS PRINTER QUEUES")
コード例 #11
0
ファイル: faxsendjobform.py プロジェクト: super11/hplip
    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)
コード例 #12
0
ファイル: setup.py プロジェクト: Distrotech/hplip
        # ******************************* CONNECTION TYPE CHOOSER
        if not device_uri and bus is None:
            bus = tui.connection_table()

            if bus is None:
                sys.exit(0)

            log.info("\nUsing connection type: %s" % bus[0])

            log.info("")

        # ******************************* DEVICE CHOOSER

        if not device_uri:
            log.debug("\nDEVICE CHOOSER setup_fax=%s, setup_print=%s" % (setup_fax, setup_print))
            device_uri = mod.getDeviceUri(device_uri, selected_device_name, devices = device.probeDevices(bus))


        # ******************************* QUERY MODEL AND COLLECT PPDS
        log.info(log.bold("\nSetting up device: %s\n" % device_uri))

        log.info("")
        print_uri = device_uri.replace("hpfax:", "hp:")
        fax_uri = device_uri.replace("hp:", "hpfax:")

        back_end, is_hp, bus, model, \
            serial, dev_file, host, zc, port = \
            device.parseDeviceURI(device_uri)

        log.debug("Model=%s" % model)
        mq = device.queryModelByURI(device_uri)
コード例 #13
0
ファイル: probe.py プロジェクト: thnguyn2/ECE_527_MP
                      'scan': 'scan-type',
                      'copy': 'copy-type',
                      'pcard': 'pcard-type',
                      'fax': 'fax-type',
                      }

        filter_dict = {}
        for f in filter:
            if f in FILTER_MAP:
                filter_dict[FILTER_MAP[f]] = (operator.gt, 0)
            else:
                filter_dict[f] = (operator.gt, 0)

        log.debug(filter_dict)

        devices = device.probeDevices([b], timeout, ttl, filter_dict, search, method)
        cleanup_spinner()

        max_c1, max_c2, max_c3, max_c4 = 0, 0, 0, 0

        if devices:
            for d in devices:
                max_c1 = max(len(d), max_c1)
                max_c3 = max(len(devices[d][0]), max_c3)
                max_c4 = max(len(devices[d][2]), max_c4)

            if b == 'net':
                formatter = utils.TextFormatter(
                            (
                                {'width': max_c1, 'margin' : 2},
                                {'width': max_c3, 'margin' : 2},
コード例 #14
0
 def discovery_uris(self, bus=None):
     if not bus:
         bus = ["usb"]
     return list(device.probeDevices(bus).keys())
コード例 #15
0
ファイル: makecopiesform.py プロジェクト: super11/hplip
    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)
コード例 #16
0
ファイル: probe.py プロジェクト: super11/hplip
                      'scan': 'scan-type',
                      'copy': 'copy-type',
                      'pcard': 'pcard-type',
                      'fax': 'fax-type',
                      }

        filter_dict = {}
        for f in filter:
            if f in FILTER_MAP:
                filter_dict[FILTER_MAP[f]] = (operator.gt, 0)
            else:
                filter_dict[f] = (operator.gt, 0)

        log.debug(filter_dict)

        devices = device.probeDevices([b], timeout, ttl, filter_dict, search, method)
        cleanup_spinner()

        max_c1, max_c2, max_c3, max_c4 = 0, 0, 0, 0

        if devices:
            for d in devices:
                max_c1 = max(len(d), max_c1)
                max_c3 = max(len(devices[d][0]), max_c3)
                max_c4 = max(len(devices[d][2]), max_c4)

            if b == 'net':
                formatter = utils.TextFormatter(
                            (
                                {'width': max_c1, 'margin' : 2},
                                {'width': max_c3, 'margin' : 2},
コード例 #17
0
ファイル: setupform.py プロジェクト: csteacherd22/hplip
    def updateProbedDevicesPage(self, devices=None, param=""):
        QApplication.setOverrideCursor(QApplication.waitCursor)

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

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

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

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

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

        self.probedDevicesListView.clear()

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

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

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

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

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

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

        if devices is None:
            FILTER_MAP = {
                "print": None,
                "none": None,
                "scan": "scan-type",
                "copy": "copy-type",
                "pcard": "pcard-type",
                "fax": "fax-type",
            }

            filter_dict = {}

            if prop.fax_build and prop.scan_build:
                for f in self.filter:
                    if f in FILTER_MAP:
                        filter_dict[FILTER_MAP[f]] = (operator.gt, 0)
                    else:
                        filter_dict[f] = (operator.gt, 0)
            else:
                filter_dict["scan-type"] = (operator.ge, SCAN_TYPE_NONE)

            if self.bus == "usb":
                try:
                    from base import smart_install
                except ImportError:
                    log.error("Failed to Import smart_install.py")
                else:  # check if any SmartInstall devices and disables (if not, ignores)
                    smart_install.disable(GUI_MODE, "qt3")

            devices = device.probeDevices(
                [self.bus], self.timeout, self.ttl, filter_dict, self.search, net_search="slp"
            )

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

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

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

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

        log.debug(devices)

        if devices:
            row = 0
            for d in devices:
                back_end, is_hp, bus, model, serial, dev_file, host, zc, port = device.parseDeviceURI(d)

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

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

                elif self.bus == "net":
                    i = DeviceListViewItem(self.probedDevicesListView, d, mq, model_ui, host, devices[d][2], d)

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

                row += 1

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

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

        QApplication.restoreOverrideCursor()
        return True
コード例 #18
0
    def updateProbedDevicesPage(self, devices=None, param=''):
        QApplication.setOverrideCursor(QApplication.waitCursor)

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

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

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

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

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

        self.probedDevicesListView.clear()

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

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

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

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

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

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

        if devices is None:
            FILTER_MAP = {'print' : None,
                          'none' : None,
                          'scan': 'scan-type',
                          'copy': 'copy-type',
                          'pcard': 'pcard-type',
                          'fax': 'fax-type',
                          }

            filter_dict = {}

            if prop.fax_build and prop.scan_build:
                for f in self.filter:
                    if f in FILTER_MAP:
                        filter_dict[FILTER_MAP[f]] = (operator.gt, 0)
                    else:
                        filter_dict[f] = (operator.gt, 0)
            else:
                filter_dict['scan-type'] = (operator.ge, SCAN_TYPE_NONE)

            devices = device.probeDevices([self.bus], self.timeout, self.ttl, filter_dict, self.search, net_search='slp')

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

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

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

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

        log.debug(devices)

        if devices:
            row = 0
            for d in devices:
                back_end, is_hp, bus, model, serial, dev_file, host, zc, port = device.parseDeviceURI(d)

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

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

                elif self.bus == 'net':
                    i = DeviceListViewItem(self.probedDevicesListView, d, mq, model_ui, host, devices[d][2], d)

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

                row += 1

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

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

        QApplication.restoreOverrideCursor()
        return True
コード例 #19
0
ファイル: check.py プロジェクト: csteacherd22/hplip
    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
コード例 #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 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)
コード例 #21
0
ファイル: check.py プロジェクト: jianglei12138/hplip
    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
コード例 #22
0
ファイル: unloadform.py プロジェクト: dhirajpatra/lti_tool
    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)
コード例 #23
0
    def __init__(self,
                 printer_name=None,
                 args=None,
                 parent=None,
                 name=None,
                 modal=0,
                 fl=0):

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

        self.printer_name = printer_name
        self.file_list = []
        self.args = args
        self.init_failed = False

        self.statusBar()

        self.setIcon(load_pixmap('hp_logo', '128x128'))
        signal.signal(signal.SIGINT, signal.SIG_DFL)

        if not name:
            self.setName("PrinterForm")

        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()

        self.cups_printers = device.getSupportedCUPSPrinters()
        log.debug(self.cups_printers)

        if not self.printer_name:  # no -p provided
            t = device.probeDevices(['cups'])
            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.device_uri = devices[0][0]

            else:
                from .chooseprinterdlg import ChoosePrinterDlg
                dlg = ChoosePrinterDlg(self.cups_printers)
                if dlg.exec_loop() == QDialog.Accepted:
                    self.printer_name = dlg.printer_name
                    self.device_uri = dlg.device_uri
                else:
                    self.init_failed = True

        else:  # -p provided
            for p in self.cups_printers:
                if p.name == self.printer_name:
                    self.device_uri = p.device_uri
                    break
            else:
                self.FailureUI(
                    "<b>Invalid printer name.</b><p>Please check the parameters to hp-print and try again."
                )
                self.init_failed = True

        if not self.init_failed:
            self.PrintView = ScrollPrintView(None, self.centralWidget(), self,
                                             "PrintView")
            self.FormLayout.addWidget(self.PrintView, 0, 0)

            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)
コード例 #24
0
ファイル: hpfax.py プロジェクト: csteacherd22/hplip
    elif o in ("-h", "--help"):
        usage()

    elif o == "--help-rest":
        usage("rest")

    elif o == "--help-man":
        usage("man")


if len(args) == 0:
    cups11 = utils.to_bool(sys_conf.get("configure", "cups11", "0"))

    try:
        probed_devices = device.probeDevices(["usb", "par"], filter={"fax-type": (operator.gt, 0)})
    except Error:
        sys.exit(CUPS_BACKEND_FAILED)

    good_devices = 0
    for uri in probed_devices:
        try:
            back_end, is_hp, bus, model, serial, dev_file, host, zc, port = device.parseDeviceURI(uri)
        except Error:
            continue

        mq = device.queryModelByModel(model)

        if mq.get("fax-type", FAX_TYPE_NONE) in (FAX_TYPE_MARVELL,):
            # HP Fax 3
            if bus == "usb":
コード例 #25
0
    def showDevicesPage(self):
        self.BackButton.setEnabled(True)
        self.setNextButton(BUTTON_NEXT)
        search = ""

        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        try:
            if not self.devices:
                if self.manual and self.param: # manual, but not passed-in on command line
                    self.manualDiscovery()

                else: # probe
                    net_search_type = ''

                    if self.bus == 'net':
                        if self.discovery_method == 0:
                            net_search_type = "slp"
                        else:
                            net_search_type = "mdns"

                        log.info("Searching... (bus=%s, timeout=%d, ttl=%d, search=%s desc=%d, method=%s)" %
                                 (self.bus,  self.timeout, self.ttl, self.search or "(None)",
                                  self.device_desc, net_search_type))
                    else:
                        log.info("Searching... (bus=%s, search=%s, desc=%d)" %
                                 (self.bus,  self.search or "(None)", self.device_desc))

                    if self.device_desc == DEVICE_DESC_SINGLE_FUNC:
                        filter_dict = {'scan-type' : (operator.le, SCAN_TYPE_NONE)}

                    elif self.device_desc == DEVICE_DESC_MULTI_FUNC:
                        filter_dict = {'scan-type': (operator.gt, SCAN_TYPE_NONE)}

                    else: # DEVICE_DESC_ALL
                        filter_dict = {}

                    self.devices = device.probeDevices([self.bus], self.timeout, self.ttl,
                                                       filter_dict, self.search, net_search=net_search_type)
        finally:
            QApplication.restoreOverrideCursor()

        self.clearDevicesTable()

        if self.devices:
            self.NextButton.setEnabled(True)
            self.DevicesFoundIcon.setPixmap(load_pixmap('info', '16x16'))

            if len(self.devices) == 1:
                self.DevicesFoundLabel.setText(self.__tr("<b>1 device found.</b> Click <i>Next</i> to continue."))
            else:
                self.DevicesFoundLabel.setText(self.__tr("<b>%1 devices found.</b> Select the device to install and click <i>Next</i> to continue.").arg(len(self.devices)))

            self.loadDevicesTable()

        else:
            self.NextButton.setEnabled(False)
            self.DevicesFoundIcon.setPixmap(load_pixmap('error', '16x16'))
            log.error("No devices found on bus: %s" % self.bus)
            self.DevicesFoundLabel.setText(self.__tr("<b>No devices found.</b><br>Click <i>Back</i> to change discovery options, or <i>Refresh</i> to search again."))

        self.displayPage(PAGE_DEVICES)
コード例 #26
0
            if bus is None:
                sys.exit(0)

            log.info("\nUsing connection type: %s" % bus[0])

            log.info("")

        # ******************************* DEVICE CHOOSER

        if not device_uri:
            log.debug("\nDEVICE CHOOSER setup_fax=%s, setup_print=%s" %
                      (setup_fax, setup_print))
            device_uri = mod.getDeviceUri(device_uri,
                                          selected_device_name,
                                          devices=device.probeDevices(bus))

        # ******************************* QUERY MODEL AND COLLECT PPDS
        log.info(log.bold("\nSetting up device: %s\n" % device_uri))

        log.info("")
        print_uri = device_uri.replace("hpfax:", "hp:")
        fax_uri = device_uri.replace("hp:", "hpfax:")

        back_end, is_hp, bus, model, \
            serial, dev_file, host, zc, port = \
            device.parseDeviceURI(device_uri)

        log.debug("Model=%s" % model)
        mq = device.queryModelByURI(device_uri)
コード例 #27
0
ファイル: setup.py プロジェクト: dhirajpatra/lti_tool
        # ******************************* CONNECTION TYPE CHOOSER
        if not device_uri and bus is None:
            bus = tui.connection_table()

            if bus is None:
                clean_exit(0)

            log.info("\nUsing connection type: %s" % bus[0])

            log.info("")

        # ******************************* DEVICE CHOOSER

        if not device_uri:
            log.debug("\nDEVICE CHOOSER setup_fax=%s, setup_print=%s" % (setup_fax, setup_print))
            device_uri = mod.getDeviceUri(devices = device.probeDevices(bus))

        if not device_uri:
            clean_exit(0)

        # ******************************* QUERY MODEL AND COLLECT PPDS
        log.info(log.bold("\nSetting up device: %s\n" % device_uri))

        log.info("")
        print_uri = device_uri.replace("hpfax:", "hp:")
        fax_uri = device_uri.replace("hp:", "hpfax:")

        back_end, is_hp, bus, model, \
            serial, dev_file, host, zc, port = \
            device.parseDeviceURI(device_uri)
コード例 #28
0
ファイル: unloadform.py プロジェクト: Distrotech/hplip
    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)