コード例 #1
0
    def setDefaultPrinterName(self):
        self.installed_print_devices = device.getSupportedCUPSDevices(['hp'])
        log.debug(self.installed_print_devices)

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

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

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

        self.printer_name_ok = True
        self.PrinterNameLineEdit.setText(printer_name)
        log.debug(printer_name)
        self.printer_name = printer_name
コード例 #2
0
    def setDefaultFaxName(self):
        self.installed_fax_devices = device.getSupportedCUPSDevices(['hpfax'])
        log.debug(self.installed_fax_devices)

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

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

        fax_name = default_model + "_fax"
        installed_fax_names = device.getSupportedCUPSPrinterNames(['hpfax'])
        # Check for duplicate names
        if (self.fax_uri in self.installed_fax_devices and fax_name in self.installed_fax_devices[self.fax_uri]) \
           or (fax_name in installed_fax_names):
                i = 2
                while True:
                    t = fax_name + "_%d" % i
                    if (t not in installed_fax_names) and (self.fax_uri not in self.installed_fax_devices or t not in self.installed_fax_devices[self.fax_uri]):
                        fax_name += "_%d" % i
                        break
                    i += 1

        self.fax_name_ok = True
        self.FaxNameLineEdit.setText(fax_name)
        self.fax_name = fax_name
コード例 #3
0
    def setDefaultPrinterName(self):
        self.installed_print_devices = device.getSupportedCUPSDevices(['hp'])
        #self.installed_print_devices = device.getSupportedCUPSDevices('*')
        log.debug(self.installed_print_devices)

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

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

        printer_name = default_model

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

        self.printer_name_ok = True
        self.printerNameLineEdit.setText(printer_name)
        log.debug(printer_name)
        self.printerNameLineEdit.setPaletteBackgroundColor(self.bg)
        self.defaultPrinterNamePushButton.setEnabled(False)
        self.printer_name = printer_name
コード例 #4
0
ファイル: setupform.py プロジェクト: csteacherd22/hplip
    def updatePPDPage(self, ppds=None):
        QApplication.setOverrideCursor(QApplication.waitCursor)
        try:
            back_end, is_hp, bus, model, serial, dev_file, host, zc, port = device.parseDeviceURI(self.device_uri)
        except Error:
            self.FailureUI(
                self.__tr(
                    "<b>Device not found or invalid HPLIP device.</b><p>If you specified a USB ID, IP address, or other parameter, please re-check it and try again."
                )
            )
            self.close()
            sys.exit()

        if ppds is None or not ppds:
            ppds = cups.getSystemPPDs()

        self.ppd = cups.getPPDFile2(self.mq, model, ppds)
        log.debug(self.ppd)
        self.ppdListView.clear()

        if self.ppd is not None:
            PPDListViewItem(self.ppdListView, self.ppd[0], self.ppd[1])

            self.ppd_file = self.ppd[0]
            log.debug(self.ppd_file)

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

        QApplication.restoreOverrideCursor()
コード例 #5
0
    def updatePPDPage(self, ppds=None):
        QApplication.setOverrideCursor(QApplication.waitCursor)
        try:
            back_end, is_hp, bus, model, serial, dev_file, host, zc, port = device.parseDeviceURI(self.device_uri)
        except Error:
            self.FailureUI(self.__tr("<b>Device not found or invalid HPLIP device.</b><p>If you specified a USB ID, IP address, or other parameter, please re-check it and try again."))
            self.close()
            sys.exit()

        if ppds is None or not ppds:
            ppds = cups.getSystemPPDs()

        self.ppd = cups.getPPDFile2(self.mq,  model , ppds)
        log.debug(self.ppd)
        self.ppdListView.clear()

        if self.ppd is not None:
            PPDListViewItem(self.ppdListView, self.ppd[0], self.ppd[1])

            self.ppd_file = self.ppd[0]
            log.debug(self.ppd_file)

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

        QApplication.restoreOverrideCursor()
コード例 #6
0
    def loadDevicesTable(self):
        self.DevicesTableWidget.setSortingEnabled(False)
        self.DevicesTableWidget.setRowCount(len(self.devices))

        headers = [self.__tr('Model'), self.__tr('Device URI')]
        device_uri_col = 1

        self.DevicesTableWidget.setColumnCount(len(headers))
        self.DevicesTableWidget.setHorizontalHeaderLabels(headers)
        flags = Qt.ItemIsSelectable | Qt.ItemIsEnabled

        for row, d in enumerate(self.devices):
            back_end, is_hp, bus, model, serial, dev_file, host, zc, port = device.parseDeviceURI(d)
            model_ui = models.normalizeModelUIName(model)

            i = DeviceTableWidgetItem(str(model_ui), d)
            i.setFlags(flags)
            self.DevicesTableWidget.setItem(row, 0, i)

            i = QTableWidgetItem(str(d))
            i.setFlags(flags)
            self.DevicesTableWidget.setItem(row, device_uri_col, i)

        self.DevicesTableWidget.resizeColumnsToContents()
        self.DevicesTableWidget.setSortingEnabled(True)
        self.DevicesTableWidget.sortItems(0)
        self.DevicesTableWidget.selectRow(0)
コード例 #7
0
    def NextButton_clicked(self):
        p = self.StackedWidget.currentIndex()
        if p == PAGE_INTRO:
            self.showDevicesPage()

        elif p == PAGE_DEVICES:
            row = self.DevicesTableWidget.currentRow()
            if row != -1:
                self.device_uri = self.DevicesTableWidget.item(row, 0).device_uri
                self.mq = device.queryModelByURI(self.device_uri)
                
                self.getWifiObject(self.mq['wifi-config'])               
                back_end, is_hp, bus, model, serial, dev_file, host, zc, port = device.parseDeviceURI(self.device_uri)
                self.model = models.normalizeModelName(model).lower()

            self.showNetworkPage()

        elif p == PAGE_NETWORK:
            self.security = 'None'
            self.mode = 'Infrastructure'
            self.ss = 0
            row = self.NetworksTableWidget.currentRow()
            if row != -1:
                i = self.NetworksTableWidget.item(row, 0)
                if i is not None:
                    self.network = to_unicode(i.text())
                    log.debug("Selected network SSID: %s" % self.network)
                    self.n, ok = value_int(i.data(Qt.UserRole))
                    if ok:
                        self.security = self.networks['encryptiontype-%d' % self.n]
                        log.debug("Security: %s" % self.security)

                        self.mode = self.networks['communicationmode-%d' % self.n]
                        log.debug("Mode: %s" % self.mode)

                        self.ss = self.networks['signalstrength-%d' % self.n]
                        log.debug("Signal strength: %s" % self.ss)

            if self.security.lower() != 'none':
                self.showConfigWifiPage()
            else:
                # Skip config page if no security to setup
                self.associate()
                self.showAssociateProgressDialog()
                self.showExitPage()

        elif p == PAGE_CONFIGURE_WIFI:
            key = to_unicode(self.KeyLineEdit.text())
            self.associate(key)
            self.showAssociateProgressDialog()
            self.showExitPage()

        elif p == PAGE_EXIT:
            if self.dev is not None:
                self.dev.close()

            self.close()

        else:
            log.error("Invalid page!") # shouldn't happen!
コード例 #8
0
ファイル: setupform.py プロジェクト: csteacherd22/hplip
    def setDefaultFaxName(self):
        self.installed_fax_devices = device.getSupportedCUPSDevices(["hpfax"])
        log.debug(self.installed_fax_devices)

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

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

        fax_name = default_model + "_fax"
        installed_fax_names = device.getSupportedCUPSPrinterNames(["hpfax"])

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

        self.fax_name_ok = True
        self.faxNameLineEdit.setText(fax_name)
        self.faxNameLineEdit.setPaletteBackgroundColor(self.bg)
        self.defaultFaxNamePushButton.setEnabled(False)
        self.fax_name = fax_name
コード例 #9
0
    def NextButton_clicked(self):
        p = self.StackedWidget.currentIndex()
        if p == PAGE_INTRO:
            self.showDevicesPage()

        elif p == PAGE_DEVICES:
            row = self.DevicesTableWidget.currentRow()
            if row != -1:
                self.device_uri = self.DevicesTableWidget.item(row, 0).device_uri
                self.mq = device.queryModelByURI(self.device_uri)
                
                self.getWifiObject(self.mq['wifi-config'])               
                back_end, is_hp, bus, model, serial, dev_file, host, zc, port = device.parseDeviceURI(self.device_uri)
                self.model = models.normalizeModelName(model).lower()

            self.showNetworkPage()

        elif p == PAGE_NETWORK:
            self.security = 'None'
            self.mode = 'Infrastructure'
            self.ss = 0
            row = self.NetworksTableWidget.currentRow()
            if row != -1:
                i = self.NetworksTableWidget.item(row, 0)
                if i is not None:
                    self.network = to_unicode(i.text())
                    log.debug("Selected network SSID: %s" % self.network)
                    self.n, ok = value_int(i.data(Qt.UserRole))
                    if ok:
                        self.security = self.networks['encryptiontype-%d' % self.n]
                        log.debug("Security: %s" % self.security)

                        self.mode = self.networks['communicationmode-%d' % self.n]
                        log.debug("Mode: %s" % self.mode)

                        self.ss = self.networks['signalstrength-%d' % self.n]
                        log.debug("Signal strength: %s" % self.ss)

            if self.security.lower() != 'none':
                self.showConfigWifiPage()
            else:
                # Skip config page if no security to setup
                self.associate()
                self.showAssociateProgressDialog()
                self.showExitPage()

        elif p == PAGE_CONFIGURE_WIFI:
            key = to_unicode(self.KeyLineEdit.text())
            self.associate(key)
            self.showAssociateProgressDialog()
            self.showExitPage()

        elif p == PAGE_EXIT:
            if self.dev is not None:
                self.dev.close()

            self.close()

        else:
            log.error("Invalid page!") # shouldn't happen!
コード例 #10
0
    def loadDevicesTable(self):
        self.DevicesTableWidget.setSortingEnabled(False)
        self.DevicesTableWidget.setRowCount(len(self.devices))

        headers = [self.__tr('Model'), self.__tr('Device URI')]
        device_uri_col = 1

        self.DevicesTableWidget.setColumnCount(len(headers))
        self.DevicesTableWidget.setHorizontalHeaderLabels(headers)
        flags = Qt.ItemIsSelectable | Qt.ItemIsEnabled

        for row, d in enumerate(self.devices):
            back_end, is_hp, bus, model, serial, dev_file, host, zc, port = device.parseDeviceURI(d)
            model_ui = models.normalizeModelUIName(model)

            i = DeviceTableWidgetItem(str(model_ui), d)
            i.setFlags(flags)
            self.DevicesTableWidget.setItem(row, 0, i)

            i = QTableWidgetItem(str(d))
            i.setFlags(flags)
            self.DevicesTableWidget.setItem(row, device_uri_col, i)

        self.DevicesTableWidget.resizeColumnsToContents()
        self.DevicesTableWidget.setSortingEnabled(True)
        self.DevicesTableWidget.sortItems(0)
        self.DevicesTableWidget.selectRow(0)
コード例 #11
0
    def setDefaultFaxName(self):
        self.installed_fax_devices = device.getSupportedCUPSDevices(['hpfax'])
        log.debug(self.installed_fax_devices)

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

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

        fax_name = default_model + "_fax"
        installed_fax_names = device.getSupportedCUPSPrinterNames(['hpfax'])

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

        self.fax_name_ok = True
        self.faxNameLineEdit.setText(fax_name)
        self.faxNameLineEdit.setPaletteBackgroundColor(self.bg)
        self.defaultFaxNamePushButton.setEnabled(False)
        self.fax_name = fax_name
コード例 #12
0
    def setupFax(self):
        QApplication.setOverrideCursor(QApplication.waitCursor)
        back_end, is_hp, bus, model, serial, dev_file, host, zc, port = \
                device.parseDeviceURI(self.device_uri)
        norm_model = models.normalizeModelName(model).lower()
        fax_ppd,fax_ppd_name, nick = cups.getFaxPPDFile(self.mq, norm_model)
        # Fax ppd not found
        if not fax_ppd:
            QApplication.restoreOverrideCursor()
            log.error("Fax PPD file not found.")

            if QMessageBox.warning(self, self.__tr("Unable to find HP fax PPD file."),
                self.__tr("The PPD file (%1.ppd) needed to setup the fax queue was not found.").arg(fax_ppd_name),
                self.__tr("Browse to file..."), # button 0
                self.__tr("Quit") # button 1
                ) == 0: # Browse

                while True:
                    ppd_dir = sys_conf.get('dirs', 'ppd')
                    fax_ppd = unicode(QFileDialog.getOpenFileName(ppd_dir,
                        "HP Fax PPD Files (*.ppd *.ppd.gz);;All Files (*)", self,
                        "open file dialog", "Choose the fax PPD file"))

                    if not fax_ppd: # user hit cancel
                        return

                    if os.path.exists(fax_ppd):
                        n = cups.getPPDDescription(fax_ppd)
                        if n == nick:
                            break
                        else:
                            self.FailureUI(self.__tr("<b>Incorrect fax PPD file.</b><p>The fax PPD file must have a nickname of '%1', not '%1'.").arg(nick).arg(n))
                    else:
                        self.FailureUI(self.__tr("<b>File not found.</b><p>hp-setup cannot find the file %1").arg(fax_ppd))

            else: # Quit
                return

        cups.setPasswordPrompt("You do not have permission to add a fax device.")
        if not os.path.exists(fax_ppd):
            status, status_str = cups.addPrinter(self.fax_name.encode('utf8'),
                self.fax_uri, self.fax_location, '', fax_ppd,  self.fax_desc)
        else:
            status, status_str = cups.addPrinter(self.fax_name.encode('utf8'),
                self.fax_uri, self.fax_location, fax_ppd, '', self.fax_desc)

        log.debug("addPrinter() returned (%d, %s)" % (status, status_str))
        self.installed_fax_devices = device.getSupportedCUPSDevices(['hpfax'])

        log.debug(self.installed_fax_devices)

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

            self.FailureUI(self.__tr("<b>Fax queue setup failed.</b><p>Please restart CUPS and try again."))
        else:
            # sending Event to add this device in hp-systray
            utils.sendEvent(EVENT_CUPS_QUEUES_CHANGED,self.fax_uri, self.fax_name)

        QApplication.restoreOverrideCursor()
コード例 #13
0
    def manualDiscovery(self):
        # Validate param...
        device_uri, sane_uri, fax_uri = device.makeURI(self.param, self.jd_port)

        if device_uri:
            log.info("Found device: %s" % device_uri)
            back_end, is_hp, bus, model, serial, dev_file, host, zc, port = \
                device.parseDeviceURI(device_uri)

            name = host
            if bus == 'net':
                try:
                    name = socket.gethostbyaddr(host)[0]
                except (socket.herror, socket.gaierror):
                    pass

            self.devices = {device_uri : (model, model, name)}

            if bus == 'usb':
                self.UsbRadioButton.setChecked(True)
                self.setUsbRadioButton(True)

            elif bus == 'net' and prop.net_build:
                self.NetworkRadioButton.setChecked(True)
                self.setNetworkRadioButton(True)

            elif bus == 'par' and prop.par_build:
                self.ParallelRadioButton.setChecked(True)
                self.setParallelRadioButton(True)

            return True


        return False
コード例 #14
0
    def setDefaultPrinterName(self):
        self.installed_print_devices = device.getSupportedCUPSDevices(['hp'])
        #self.installed_print_devices = device.getSupportedCUPSDevices('*')
        log.debug(self.installed_print_devices)

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

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

        printer_name = default_model

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

        self.printer_name_ok = True
        self.printerNameLineEdit.setText(printer_name)
        log.debug(printer_name)
        self.printerNameLineEdit.setPaletteBackgroundColor(self.bg)
        self.defaultPrinterNamePushButton.setEnabled(False)
        self.printer_name = printer_name
コード例 #15
0
    def setDefaultFaxName(self):
        self.installed_fax_devices = device.getSupportedCUPSDevices(['hpfax'])
        log.debug(self.installed_fax_devices)

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

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

        fax_name = default_model + "_fax"

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

        self.fax_name_ok = True
        self.faxNameLineEdit.setText(fax_name)
        self.faxNameLineEdit.setPaletteBackgroundColor(self.bg)
        self.defaultFaxNamePushButton.setEnabled(False)
        self.fax_name = fax_name
コード例 #16
0
    def showRemovePage(self):
        self.displayPage(PAGE_REMOVE)
        self.StepText.setText(self.__tr("Step 1 of 1"))
        self.setNextButton(BUTTON_REMOVE)
        self.BackButton.setEnabled(False)
        self.NextButton.setEnabled(False)

        self.RemoveDevicesTableWidget.verticalHeader().hide()

        self.installed_printers = device.getSupportedCUPSPrinters(['hp', 'hpfax'])
        log.debug(self.installed_printers)

        if not self.installed_printers:
            FailureUI(self, self.__tr("<b>No printers or faxes found to remove.</b><p>You must setup a least one printer or fax before you can remove it."))
            self.close()
            return

        self.RemoveDevicesTableWidget.setRowCount(len(self.installed_printers))

        headers = [self.__tr("Select"), self.__tr('Printer (Queue) Name'), self.__tr('Type'), self.__tr('Device URI')]

        self.RemoveDevicesTableWidget.setColumnCount(len(headers))
        self.RemoveDevicesTableWidget.setHorizontalHeaderLabels(headers)
        flags = Qt.ItemIsSelectable | Qt.ItemIsEnabled

        row = 0
        for p in self.installed_printers:
            widget = QCheckBox(self.RemoveDevicesTableWidget)
            self.connect(widget, SIGNAL("stateChanged(int)"), self.CheckBox_stateChanged)
            self.RemoveDevicesTableWidget.setCellWidget(row, 0, widget)

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

            if self.device_uri is not None and self.device_uri == p.device_uri:
                widget.setCheckState(Qt.Checked)

            i = QTableWidgetItem(QString(p.name))
            i.setFlags(flags)
            i.setData(Qt.UserRole, QVariant(p.name))
            self.RemoveDevicesTableWidget.setItem(row, 1, i)

            if back_end == 'hpfax':
                typ = self.__tr("Fax")
            else:
                typ = self.__tr("Printer")

            i = QTableWidgetItem(typ)
            i.setFlags(flags)
            self.RemoveDevicesTableWidget.setItem(row, 2, i)

            i = QTableWidgetItem(QString(p.device_uri))
            i.setFlags(flags)
            self.RemoveDevicesTableWidget.setItem(row, 3, i)

            row += 1

        self.RemoveDevicesTableWidget.resizeColumnsToContents()
コード例 #17
0
ファイル: setupform.py プロジェクト: danwallach/VoteBox-v1
    def setupFax(self):
        status = cups.IPP_BAD_REQUEST
        QApplication.setOverrideCursor(QApplication.waitCursor)
        back_end, is_hp, bus, model, serial, dev_file, host, zc, port = \
                device.parseDeviceURI(self.device_uri)
        norm_model = models.normalizeModelName(model).lower()
        fax_ppd,fax_ppd_name, nick = cups.getFaxPPDFile(self.mq, norm_model)
        # Fax ppd not found
        if not fax_ppd:
            QApplication.restoreOverrideCursor()
            log.error("Fax PPD file not found.")

            if QMessageBox.warning(self, self.__tr("Unable to find HP fax PPD file."),
                self.__tr("The PPD file (%1.ppd) needed to setup the fax queue was not found.").arg(fax_ppd_name),
                self.__tr("Browse to file..."), # button 0
                self.__tr("Quit") # button 1
                ) == 0: # Browse

                while True:
                    ppd_dir = sys_conf.get('dirs', 'ppd')
                    fax_ppd = to_unicode(QFileDialog.getOpenFileName(ppd_dir,
                        "HP Fax PPD Files (*.ppd *.ppd.gz);;All Files (*)", self,
                        "open file dialog", "Choose the fax PPD file"))

                    if not fax_ppd: # user hit cancel
                        return

                    if os.path.exists(fax_ppd):
                        n = cups.getPPDDescription(fax_ppd)
                        if n == nick:
                            break
                        else:
                            self.FailureUI(self.__tr("<b>Incorrect fax PPD file.</b><p>The fax PPD file must have a nickname of '%1', not '%1'.").arg(nick).arg(n))
                    else:
                        self.FailureUI(self.__tr("<b>File not found.</b><p>hp-setup cannot find the file %1").arg(fax_ppd))

            else: # Quit
                return

        if not os.path.exists(fax_ppd):
            status, status_str = cups.addPrinter(self.fax_name.encode('utf8'),
                self.fax_uri, self.fax_location, '', fax_ppd,  self.fax_desc)
        else:
            status, status_str = cups.addPrinter(self.fax_name.encode('utf8'),
                self.fax_uri, self.fax_location, fax_ppd, '', self.fax_desc)

        log.debug("addPrinter() returned (%d, %s)" % (status, status_str))
        log.debug(device.getSupportedCUPSDevices(['hpfax']))

        if status != cups.IPP_OK:
            self.FailureUI(self.__tr("<b>Fax queue setup failed.</b><p>Error : %s "%status_str))
        else:
            # sending Event to add this device in hp-systray
            utils.sendEvent(EVENT_CUPS_QUEUES_ADDED,self.fax_uri, self.fax_name)

        QApplication.restoreOverrideCursor()
        return status
コード例 #18
0
    def updatePPDPage(self, ppds=None):
        QApplication.setOverrideCursor(QApplication.waitCursor)
        try:
            back_end, is_hp, bus, model, serial, dev_file, host, zc, port = device.parseDeviceURI(
                self.device_uri)
        except Error:
            self.FailureUI(
                self.__tr(
                    "<b>Device not found or invalid HPLIP device.</b><p>If you specified a USB ID, IP address, or other parameter, please re-check it and try again."
                ))
            self.close()
            sys.exit()

        if ppds is None or not ppds:
            ppds = cups.getSystemPPDs()

        #print ppds

        default_model = utils.xstrip(
            model.replace('series', '').replace('Series', ''), '_')
        stripped_model = cups.stripModel2(
            models.normalizeModelName(model).lower())

        #Check if common ppd name is already given in models.dat(This is needed because in case of devices having more than one derivatives
        #will have diffrent model name strings in device ID, because of which we don't get the common ppd name for search)

        ppd_name = self.mq.get('ppd-name', 0)

        if ppd_name == 0:
            self.ppd = cups.getPPDFile2(stripped_model, ppds)
        else:
            self.ppd = cups.getPPDFile2(ppd_name, ppds)

        log.debug(self.ppd)
        self.ppdListView.clear()

        if self.ppd is not None:
            #for ppd in self.ppd_dict:
            PPDListViewItem(self.ppdListView, self.ppd[0], self.ppd[1])

            #            i = self.ppdListView.firstChild()
            #            self.ppdListView.setCurrentItem(i)
            #            self.ppdListView.setSelected(i, True)
            #            self.ppd_file = self.ppdListView.currentItem().ppd_file
            self.ppd_file = self.ppd[0]
            log.debug(self.ppd_file)

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

        QApplication.restoreOverrideCursor()
コード例 #19
0
    def NextButton_clicked(self):
        p = self.StackedWidget.currentIndex()
        if p == PAGE_DISCOVERY:
            self.manual = self.ManualGroupBox.isChecked()
            self.param = unicode(self.ManualParamLineEdit.text())
            self.jd_port = self.JetDirectSpinBox.value()
            self.search = unicode(self.SearchLineEdit.text())
            self.device_desc = int(self.DeviceTypeComboBox.itemData(self.DeviceTypeComboBox.currentIndex()).toInt()[0])
            self.discovery_method = self.NetworkDiscoveryMethodComboBox.currentIndex()

            if self.WirelessButton.isChecked():
                dlg = WifiSetupDialog(self, device_uri=None, standalone=False)
                dlg.exec_()

                if dlg.success == SUCCESS_CONNECTED:
                    self.manual = True
                    self.param = dlg.hn
                    self.bus = 'net'
            if not self.WirelessButton.isChecked():
                self.showDevicesPage()
           
        elif p == PAGE_DEVICES:
            row = self.DevicesTableWidget.currentRow()
            self.device_uri = self.DevicesTableWidget.item(row, 0).device_uri
            self.mq = device.queryModelByURI(self.device_uri)
            back_end, is_hp, bus, model, serial, dev_file, host, zc, port = device.parseDeviceURI(self.device_uri)
            self.model = models.normalizeModelName(model).lower()
            self.showAddPrinterPage()

        elif p == PAGE_ADD_PRINTER:
            self.print_test_page = self.SendTestPageCheckBox.isChecked()
            self.print_desc = unicode(self.PrinterDescriptionLineEdit.text()).encode('utf8')
            self.print_location = unicode(self.PrinterLocationLineEdit.text()).encode('utf8')
            self.fax_setup = self.SetupFaxGroupBox.isChecked()
            self.fax_desc = unicode(self.FaxDescriptionLineEdit.text()).encode('utf8')
            self.fax_location = unicode(self.FaxLocationLineEdit.text()).encode('utf8')
            self.fax_name_company = unicode(self.NameCompanyLineEdit.text()).encode('utf8')
            self.fax_number = unicode(self.FaxNumberLineEdit.text()).encode('utf8')
            self.addPrinter()

        elif p == PAGE_REMOVE:
            for row in xrange(self.RemoveDevicesTableWidget.rowCount()):
                widget = self.RemoveDevicesTableWidget.cellWidget(row, 0)
                if widget.checkState() == Qt.Checked:
                    item = self.RemoveDevicesTableWidget.item(row, 1)
                    printer = unicode(item.data(Qt.UserRole).toString()).encode('utf-8')
                    log.debug("Removing printer: %s" % printer)
                    if cups.delPrinter(printer) == 0 and os.geteuid!=0 and utils.addgroup()!=[]:
                            FailureUI(self, self.__tr("<b>Unable to delete printer queue. Could not connect to CUPS Server</b><p>Is user added to %s group(s)" %utils.list_to_string(utils.addgroup())))
            self.close()

        else:
            log.error("Invalid page!") # shouldn't happen!
コード例 #20
0
ファイル: hpssd.py プロジェクト: incrazyboyy/RPiTC-X
def check_device(device_uri):
    try:
        devices[device_uri]
    except KeyError:
        log.debug("New device: %s" % device_uri)
        try:
            back_end, is_hp, bus, model, serial, dev_file, host, zc, port = device.parseDeviceURI(device_uri)
        except Error:
            log.debug("Invalid device URI: %s" % device_uri)
            return ERROR_INVALID_DEVICE_URI

        devices[device_uri] = DeviceCache(model)

    return ERROR_SUCCESS
コード例 #21
0
ファイル: hpssd.py プロジェクト: aiminickwong/RPiTC-X
def check_device(device_uri):
    try:
        devices[device_uri]
    except KeyError:
        log.debug("New device: %s" % device_uri)
        try:
            back_end, is_hp, bus, model, serial, dev_file, host, zc, port = \
                device.parseDeviceURI(device_uri)
        except Error:
            log.debug("Invalid device URI: %s" % device_uri)
            return ERROR_INVALID_DEVICE_URI

        devices[device_uri] = DeviceCache(model)

    return ERROR_SUCCESS
コード例 #22
0
ファイル: setupform.py プロジェクト: csteacherd22/hplip
    def setDefaultPrinterName(self):
        self.installed_print_devices = device.getSupportedCUPSDevices(["hp"])
        # self.installed_print_devices = device.getSupportedCUPSDevices('*')
        log.debug(self.installed_print_devices)

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

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

        printer_name = default_model

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

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

        self.printer_name_ok = True
        self.printerNameLineEdit.setText(printer_name)
        log.debug(printer_name)
        self.printerNameLineEdit.setPaletteBackgroundColor(self.bg)
        self.defaultPrinterNamePushButton.setEnabled(False)
        self.printer_name = printer_name
コード例 #23
0
    def setDefaultPrinterName(self):
        self.installed_print_devices = device.getSupportedCUPSDevices(['hp'])
        #self.installed_print_devices = device.getSupportedCUPSDevices('*')
        log.debug(self.installed_print_devices)

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

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

        printer_name = default_model

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

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

        self.printer_name_ok = True
        self.printerNameLineEdit.setText(printer_name)
        log.debug(printer_name)
        self.printerNameLineEdit.setPaletteBackgroundColor(self.bg)
        self.defaultPrinterNamePushButton.setEnabled(False)
        self.printer_name = printer_name
コード例 #24
0
ファイル: setupdialog.py プロジェクト: incrazyboyy/RPiTC-X
    def loadDevicesTable(self):
        self.DevicesTableWidget.setRowCount(len(self.devices))

        if self.bus == 'net':
            if self.discovery_method == 0:
                headers = [self.__tr('Model'), self.__tr('IP Address'), self.__tr('Host Name'), self.__tr('Device URI')]
                device_uri_col = 3
            else:
                headers = [self.__tr('Model'), self.__tr('Host Name'), self.__tr('Device URI')]
                device_uri_col = 2
        else:
            headers = [self.__tr('Model'), self.__tr('Device URI')]
            device_uri_col = 1

        self.DevicesTableWidget.setColumnCount(len(headers))
        self.DevicesTableWidget.setHorizontalHeaderLabels(headers)
        flags = Qt.ItemIsSelectable | Qt.ItemIsEnabled

        for row, d in enumerate(self.devices):
            back_end, is_hp, bus, model, serial, dev_file, host, zc, port = device.parseDeviceURI(d)
            model_ui = models.normalizeModelUIName(model)

            i = DeviceTableWidgetItem(QString(model_ui), d)
            i.setFlags(flags)
            self.DevicesTableWidget.setItem(row, 0, i)

            i = QTableWidgetItem(QString(d))
            i.setFlags(flags)
            self.DevicesTableWidget.setItem(row, device_uri_col, i)

            if self.bus == 'net':
                #if device.ip_pat.search(host) is None:
                     #host = socket.gethostbyname(host)
                i = QTableWidgetItem(QString(host))
                i.setFlags(flags)
                self.DevicesTableWidget.setItem(row, 1, i)

                if self.discovery_method == 0:
                    i = QTableWidgetItem(QString(self.devices[d][2]))
                    i.setFlags(flags)
                    self.DevicesTableWidget.setItem(row, 2, i)

        self.DevicesTableWidget.resizeColumnsToContents()
        self.DevicesTableWidget.selectRow(0)
        self.DevicesTableWidget.setSortingEnabled(True)
        self.DevicesTableWidget.sortItems(0)
コード例 #25
0
    def updatePPDPage(self, ppds=None):
        QApplication.setOverrideCursor(QApplication.waitCursor)
        try:
            back_end, is_hp, bus, model, serial, dev_file, host, zc, port = device.parseDeviceURI(self.device_uri)
        except Error:
            self.FailureUI(self.__tr("<b>Device not found or invalid HPLIP device.</b><p>If you specified a USB ID, IP address, or other parameter, please re-check it and try again."))
            self.close()
            sys.exit()

        if ppds is None or not ppds:
            ppds = cups.getSystemPPDs()

        #print ppds

        default_model = utils.xstrip(model.replace('series', '').replace('Series', ''), '_')
        stripped_model = cups.stripModel2(models.normalizeModelName(model).lower())
        
        
        #Check if common ppd name is already given in models.dat(This is needed because in case of devices having more than one derivatives
        #will have diffrent model name strings in device ID, because of which we don't get the common ppd name for search)
       
        ppd_name = self.mq.get('ppd-name',0)
        
        if ppd_name == 0:
        	self.ppd = cups.getPPDFile2(stripped_model, ppds)
        else:
            self.ppd = cups.getPPDFile2(ppd_name, ppds)
        
        log.debug(self.ppd)
        self.ppdListView.clear()

        if self.ppd is not None:
            #for ppd in self.ppd_dict:
            PPDListViewItem(self.ppdListView, self.ppd[0], self.ppd[1])

#            i = self.ppdListView.firstChild()
#            self.ppdListView.setCurrentItem(i)
#            self.ppdListView.setSelected(i, True)
#            self.ppd_file = self.ppdListView.currentItem().ppd_file
            self.ppd_file = self.ppd[0]
            log.debug(self.ppd_file)

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

        QApplication.restoreOverrideCursor()
コード例 #26
0
ファイル: systemtray.py プロジェクト: aiminickwong/RPiTC-X
    def __init__(self, device_uri, needs_update=True):
        self.needs_update = needs_update
        self.device_uri = device_uri

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

        if bus == 'usb':
            self.id = serial
        elif bus == 'net':
            self.id = host
        elif bus == 'par':
            self.id = dev_file
        else:
            self.id = 'unknown'

        self.model = models.normalizeModelUIName(model)

        if back_end == 'hp':
            self.device_type = DEVICE_TYPE_PRINTER
            self.menu_text = self.__tr("%1 Printer (%2)").arg(self.model).arg(
                self.id)

        elif back_end == 'hpaio':
            self.device_type = DEVICE_TYPE_SCANNER
            self.menu_text = self.__tr("%1 Scanner (%2)").arg(self.model).arg(
                self.id)

        elif back_end == 'hpfax':
            self.device_type = DEVICE_TYPE_FAX
            self.menu_text = self.__tr("%1 Fax (%2)").arg(self.model).arg(
                self.id)

        else:
            self.device_type = DEVICE_TYPE_UNKNOWN
            self.menu_text = self.__tr("%1 (%2)").arg(self.model).arg(self.id)

        self.mq = device.queryModelByURI(self.device_uri)
        self.index = 0
        if self.mq.get('tech-type', TECH_TYPE_NONE) in (TECH_TYPE_MONO_LASER,
                                                        TECH_TYPE_COLOR_LASER):
            self.index = 1
        self.history = None
コード例 #27
0
    def manualFindPushButton_clicked(self):
        dlg = SetupManualFind(self.bus, self)
        if dlg.exec_loop() == QDialog.Accepted:
            QApplication.setOverrideCursor(QApplication.waitCursor)

            cups_uri, sane_uri, fax_uri = device.makeURI(dlg.param)

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

                QApplication.restoreOverrideCursor()
                self.updateProbedDevicesPage({cups_uri: (model, model, name)}, dlg.param)
            else:
                QApplication.restoreOverrideCursor()
                self.updateProbedDevicesPage([], dlg.param)
コード例 #28
0
    def manualFindPushButton_clicked(self):
        dlg = SetupManualFind(self.bus, self)
        if dlg.exec_loop() == QDialog.Accepted:
            QApplication.setOverrideCursor(QApplication.waitCursor)

            cups_uri, sane_uri, fax_uri = device.makeURI(dlg.param)

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

                QApplication.restoreOverrideCursor()
                self.updateProbedDevicesPage({cups_uri: (model, model, name)}, dlg.param)
            else:
                QApplication.restoreOverrideCursor()
                self.updateProbedDevicesPage([], dlg.param)
コード例 #29
0
ファイル: systemtray.py プロジェクト: Alberto-Beralix/Beralix
    def __init__(self, device_uri, needs_update=True):
        self.needs_update = needs_update
        self.device_uri = device_uri

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

        if bus == 'usb':
            self.id = serial
        elif bus == 'net':
            self.id = host
        elif bus == 'par':
            self.id = dev_file
        else:
            self.id = 'unknown'

        self.model = models.normalizeModelUIName(model)

        if back_end == 'hp':
            self.device_type = DEVICE_TYPE_PRINTER
            self.menu_text = self.__tr("%1 Printer (%2)").arg(self.model).arg(self.id)

        elif back_end == 'hpaio':
            self.device_type = DEVICE_TYPE_SCANNER
            self.menu_text = self.__tr("%1 Scanner (%2)").arg(self.model).arg(self.id)

        elif back_end == 'hpfax':
            self.device_type = DEVICE_TYPE_FAX
            self.menu_text = self.__tr("%1 Fax (%2)").arg(self.model).arg(self.id)

        else:
            self.device_type = DEVICE_TYPE_UNKNOWN
            self.menu_text = self.__tr("%1 (%2)").arg(self.model).arg(self.id)

        self.mq = device.queryModelByURI(self.device_uri)
        self.index = 0
        if self.mq.get('tech-type', TECH_TYPE_NONE) in (TECH_TYPE_MONO_LASER, TECH_TYPE_COLOR_LASER):
            self.index = 1
        self.history = None
コード例 #30
0
        import hpmudext
    except:
        log.error("Failed to import hpmudext")
    else:
        hpmudext.handle_smartinstall()

    # ******************************* MAKEURI
    if param:
        device_uri, sane_uri, fax_uri = device.makeURI(param)
    if not device_uri:
        log.error("This is not a valid device")
        sys.exit(0)

    # ******************************* QUERY MODEL AND COLLECT PPDS
    log.debug("\nSetting up device: %s\n" % device_uri)
    back_end, is_hp, bus, model, serial, dev_file, host, zc, port = device.parseDeviceURI(
        device_uri)

    mq = device.queryModelByURI(device_uri)
    if not mq or mq.get('support-type',
                        SUPPORT_TYPE_NONE) == SUPPORT_TYPE_NONE:
        log.error("Unsupported printer model.")
        sys.exit(1)
    while check_cups_process() is False:
        log.debug("CUPS is not running.. waiting for 30 sec")
        time.sleep(30)

    time.sleep(1)
    norm_model = models.normalizeModelName(model).lower()
    remove_non_hp_config = True
    if not mq.get('fax-type',
                  FAX_TYPE_NONE) in (FAX_TYPE_NONE, FAX_TYPE_NOT_SUPPORTED):
コード例 #31
0
    def __init__(self,
                 printers,
                 back_end_filter=['hp'],
                 parent=None,
                 name=None,
                 modal=0,
                 fl=0,
                 show_uris=True):
        QDialog.__init__(self, parent, name, modal, fl)

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

        self.device_uri = ''
        self.printer_name = ''
        self.back_end_filter = back_end_filter

        ChooseDeviceDlg_Layout = QGridLayout(self, 1, 1, 6, 6,
                                             "ChooseDeviceDlg_Layout")

        self.OKButton = QPushButton(self, "OKButton")

        ChooseDeviceDlg_Layout.addWidget(self.OKButton, 2, 2)

        self.CancelButton = QPushButton(self, "CancelButton")

        ChooseDeviceDlg_Layout.addWidget(self.CancelButton, 2, 1)
        spacer1 = QSpacerItem(391, 20, QSizePolicy.Expanding,
                              QSizePolicy.Minimum)
        ChooseDeviceDlg_Layout.addItem(spacer1, 2, 0)
        spacer2 = QSpacerItem(20, 290, QSizePolicy.Minimum,
                              QSizePolicy.Expanding)
        ChooseDeviceDlg_Layout.addItem(spacer2, 1, 0)

        self.DevicesButtonGroup = QButtonGroup(self, "DevicesButtonGroup")
        self.DevicesButtonGroup.setColumnLayout(0, Qt.Vertical)
        self.DevicesButtonGroup.layout().setSpacing(6)
        self.DevicesButtonGroup.layout().setMargin(6)
        DevicesButtonGroupLayout = QGridLayout(
            self.DevicesButtonGroup.layout())
        DevicesButtonGroupLayout.setAlignment(Qt.AlignTop)

        self.radio_buttons = {}

        self.printer_index, x = {}, 0
        for p in printers:
            try:
                back_end, is_hp, bus, model, serial, dev_file, host, zc, port = \
                    device.parseDeviceURI(p.device_uri)

            except Error:
                continue

            if back_end in back_end_filter:
                self.printer_index[x] = (p.name, p.device_uri)
                x += 1

        for y in range(len(self.printer_index)):
            if y == 0:
                self.device_uri = self.printer_index[y][1]
                self.printer_name = self.printer_index[y][0]

            self.radio_buttons[y] = QRadioButton(self.DevicesButtonGroup,
                                                 "radioButton%d" % y)

            if show_uris:
                self.radio_buttons[y].setText("%s  (%s)" %
                                              self.printer_index[y])
            else:
                self.radio_buttons[y].setText(self.printer_index[y])

            DevicesButtonGroupLayout.addWidget(self.radio_buttons[y], y, 0)

        self.radio_buttons[0].setChecked(1)

        ChooseDeviceDlg_Layout.addMultiCellWidget(self.DevicesButtonGroup, 0,
                                                  0, 0, 2)

        self.languageChange()

        self.resize(QSize(592, 112).expandedTo(self.minimumSizeHint()))
        self.clearWState(Qt.WState_Polished)

        self.connect(self.OKButton, SIGNAL("clicked()"), self,
                     SLOT("accept()"))
        self.connect(self.CancelButton, SIGNAL("clicked()"), self,
                     SLOT("reject()"))
        self.connect(self.DevicesButtonGroup, SIGNAL("clicked(int)"),
                     self.DevicesButtonGroup_clicked)
コード例 #32
0
ファイル: chooseprinterdlg.py プロジェクト: Distrotech/hplip
    def __init__(self, printers, back_end_filter=['hp'], parent = None,name = None,modal = 0,fl = 0, show_uris=True):
        QDialog.__init__(self,parent,name,modal,fl)

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

        self.device_uri = ''
        self.printer_name = ''
        self.back_end_filter = back_end_filter

        ChooseDeviceDlg_Layout = QGridLayout(self,1,1,6,6,"ChooseDeviceDlg_Layout")

        self.OKButton = QPushButton(self,"OKButton")

        ChooseDeviceDlg_Layout.addWidget(self.OKButton,2,2)

        self.CancelButton = QPushButton(self,"CancelButton")

        ChooseDeviceDlg_Layout.addWidget(self.CancelButton,2,1)
        spacer1 = QSpacerItem(391,20,QSizePolicy.Expanding,QSizePolicy.Minimum)
        ChooseDeviceDlg_Layout.addItem(spacer1,2,0)
        spacer2 = QSpacerItem(20,290,QSizePolicy.Minimum,QSizePolicy.Expanding)
        ChooseDeviceDlg_Layout.addItem(spacer2,1,0)

        self.DevicesButtonGroup = QButtonGroup(self,"DevicesButtonGroup")
        self.DevicesButtonGroup.setColumnLayout(0,Qt.Vertical)
        self.DevicesButtonGroup.layout().setSpacing(6)
        self.DevicesButtonGroup.layout().setMargin(6)
        DevicesButtonGroupLayout = QGridLayout(self.DevicesButtonGroup.layout())
        DevicesButtonGroupLayout.setAlignment(Qt.AlignTop)

        self.radio_buttons = {}

        self.printer_index, x = {}, 0
        for p in printers:
            try:
                back_end, is_hp, bus, model, serial, dev_file, host, zc, port = \
                    device.parseDeviceURI(p.device_uri)

            except Error:
                continue

            if back_end in back_end_filter:
                self.printer_index[x] = (p.name, p.device_uri)
                x += 1


        for y in range(len(self.printer_index)):
            if y == 0:
                self.device_uri = self.printer_index[y][1]
                self.printer_name = self.printer_index[y][0]

            self.radio_buttons[y] = QRadioButton(self.DevicesButtonGroup,"radioButton%d" % y)

            if show_uris:
                self.radio_buttons[y].setText("%s  (%s)" % self.printer_index[y])
            else:
                self.radio_buttons[y].setText(self.printer_index[y])

            DevicesButtonGroupLayout.addWidget(self.radio_buttons[y], y, 0)

        self.radio_buttons[0].setChecked(1)

        ChooseDeviceDlg_Layout.addMultiCellWidget(self.DevicesButtonGroup,0,0,0,2)

        self.languageChange()

        self.resize(QSize(592,112).expandedTo(self.minimumSizeHint()))
        self.clearWState(Qt.WState_Polished)

        self.connect(self.OKButton,SIGNAL("clicked()"),self,SLOT("accept()"))
        self.connect(self.CancelButton,SIGNAL("clicked()"),self,SLOT("reject()"))
        self.connect(self.DevicesButtonGroup,SIGNAL("clicked(int)"),self.DevicesButtonGroup_clicked)
コード例 #33
0
    def showPage(self, page):
        orig_page = page

        if self.first_page:
            page = self.start_page
            self.first_page = False

        log.debug("%s %s %s" % ("*"*20, "showPage(%s)" % page.name(), "*"*20))

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

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

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


        elif page is self.PPDPage: # ProbedDevicesPage --> PPDPage
            if self.param:
                device_uri, sane_uri, fax_uri = device.makeURI(self.param, self.jd_port)

                if device_uri:
                    self.device_uri = device_uri

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

            self.bus = bus
            self.mq = device.queryModelByURI(self.device_uri)

            norm_model = models.normalizeModelName(model).lower()

            core = core_install.CoreInstall(core_install.MODE_CHECK)
            core.set_plugin_version()
            plugin = self.mq.get('plugin', PLUGIN_NONE)
            plugin_reason = self.mq.get('plugin-reason', PLUGIN_REASON_NONE)
            if plugin > PLUGIN_NONE and core.check_for_plugin() != PLUGIN_INSTALLED:
                ok, sudo_ok = pkit.run_plugin_command(plugin == PLUGIN_REQUIRED, plugin_reason)
                if not sudo_ok:
                    self.FailureUI(self.__tr("<b>Unable to find an appropriate su/sudo utility to run hp-plugin.</b><p>Install kdesu, gnomesu, or gksu.</p>"))
                    return
                if not ok or core.check_for_plugin() != PLUGIN_INSTALLED:
                    if plugin == PLUGIN_REQUIRED:
                        self.FailureUI(self.__tr("<b>The printer you are trying to setup requires a binary driver plug-in and it failed to install.</b><p>Please check your internet connection and try again.</p><p>Visit <u>http://hplipopensource.com</u> for more information.</p>"))
                        return
                    else:
                        self.WarningUI(self.__tr("Either you have chosen to skip the installation of the optional plug-in or that installation has failed.  Your printer may not function at optimal performance."))

            self.updatePPDPage()

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

            if fax_import_ok and prop.fax_build and \
                self.mq.get('fax-type', FAX_TYPE_NONE) not in (FAX_TYPE_NONE, FAX_TYPE_NOT_SUPPORTED):

                self.faxCheckBox.setEnabled(True)
                self.faxCheckBox.setEnabled(True)
                self.faxNameLineEdit.setEnabled(True)
                self.faxNumberLineEdit.setEnabled(True)
                self.faxNameCoLineEdit.setEnabled(True)
                self.faxLocationLineEdit.setEnabled(True)
                self.faxDescriptionLineEdit.setEnabled(True)
                self.faxInfoGroupBox.setEnabled(True)
                self.setup_fax = True
                self.setDefaultFaxName()
                self.readwriteFaxInformation(True)

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

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

            #log.debug("Restarting CUPS...")
            #status, output = utils.run(restart_cups())
            #log.debug("Restart CUPS returned: exit=%d output=%s" % (status, output))

            self.setupPrinter()

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

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

                self.faxGroupBox.setEnabled(True)

            else:
                self.faxGroupBox.setEnabled(False)

            self.setFinishEnabled(self.FinishedPage, True)

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

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

        if page is self.ProbedDevicesPage: # ConnectionPage --> ProbedDevicesPage/EnterIPPage/DeviceNotFoundPage
            if not devices_found:
                self.FailureUI(self.__tr("<b>No devices found.</b><p>Please make sure your printer is properly connected and powered-on."))
コード例 #34
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
コード例 #35
0
ファイル: hpfax.py プロジェクト: csteacherd22/hplip
    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":
                print(
                    'direct %s "HP Fax 3" "%s USB %s HP Fax HPLIP" "MFG:HP;MDL:Fax 3;DES:HP Fax 3;"'
                    % (uri.replace("hp:", "hpfax:"), model.replace("_", " "), serial)
                )

            else:  # par
                print(
コード例 #36
0
ファイル: systemtray.py プロジェクト: Alberto-Beralix/Beralix
    def notifierActivated(self, s):
        m = ''
        while True:
            try:
                r, w, e = select.select([self.read_pipe], [], [self.read_pipe], 1.0)
            except select.error:
                log.debug("Error in select()")
                break

            if e:
                log.error("Pipe error: %s" % e)
                break

            if r:
                m = ''.join([m, os.read(self.read_pipe, self.fmt_size)])
                while len(m) >= self.fmt_size:
                    event = device.Event(*struct.unpack(self.fmt, m[:self.fmt_size]))

                    m = m[self.fmt_size:]

                    if event.event_code == EVENT_USER_CONFIGURATION_CHANGED:
                        log.debug("Re-reading configuration (EVENT_USER_CONFIGURATION_CHANGED)")
                        self.user_settings.load()
                        self.user_settings.debug()

                    elif event.event_code == EVENT_SYSTEMTRAY_EXIT:
                        self.quit()
                        return

                    if self.user_settings.systray_visible in \
                        (SYSTRAY_VISIBLE_SHOW_ALWAYS, SYSTRAY_VISIBLE_HIDE_WHEN_INACTIVE):

                        log.debug("Showing...")
                        self.tray_icon.setVisible(True)

                        if event.event_code == EVENT_DEVICE_UPDATE_ACTIVE:
                            if not self.active_icon:
                                self.tray_icon.setIcon(self.prop_active_icon)
                                self.active_icon = True
                            continue

                        elif event.event_code == EVENT_DEVICE_UPDATE_INACTIVE:
                            if self.active_icon:
                                self.tray_icon.setIcon(self.prop_icon)
                                self.active_icon = False
                            continue

                        elif event.event_code == EVENT_DEVICE_UPDATE_BLIP:
                            if not self.active_icon:
                                self.tray_icon.setIcon(self.prop_active_icon)
                                self.active_icon = True
                                QTimer.singleShot(BLIP_DELAY, self.blipTimeout)
                            continue

                    if self.user_settings.systray_visible in (SYSTRAY_VISIBLE_HIDE_WHEN_INACTIVE, SYSTRAY_VISIBLE_HIDE_ALWAYS):
                        log.debug("Waiting to hide...")
                        QTimer.singleShot(HIDE_INACTIVE_DELAY, self.timeoutHideWhenInactive)

                    if event.event_code <= EVENT_MAX_USER_EVENT:
                        self.addDevice(event.device_uri)
                        self.setMenu()

                        if self.tray_icon.supportsMessages():

                            log.debug("Tray icon message:")
                            event.debug()

                            error_state = STATUS_TO_ERROR_STATE_MAP.get(event.event_code, ERROR_STATE_CLEAR)
                            desc = device.queryString(event.event_code)

                            show_message = False
                            if self.user_settings.systray_messages == SYSTRAY_MESSAGES_SHOW_ALL: # OK, Busy
                                show_message = True

                            elif self.user_settings.systray_messages in (SYSTRAY_MESSAGES_SHOW_ERRORS_AND_WARNINGS, SYSTRAY_MESSAGES_SHOW_ERRORS_ONLY):
                                if error_state == ERROR_STATE_ERROR:
                                    show_message = True

                                elif self.user_settings.systray_messages == SYSTRAY_MESSAGES_SHOW_ERRORS_AND_WARNINGS and \
                                    error_state in (ERROR_STATE_WARNING, ERROR_STATE_LOW_SUPPLIES, ERROR_STATE_LOW_PAPER):

                                    show_message = True

                            if event.printer_name:
                                d = QString(event.printer_name)
                            else:
                                back_end, is_hp, bus, model, serial, dev_file, host, zc, port = \
                                                device.parseDeviceURI(event.device_uri)

                                if bus == 'usb':
                                    idd = serial
                                elif bus == 'net':
                                    idd = host
                                elif bus == 'par':
                                    idd = dev_file
                                else:
                                    idd = 'unknown'

                                self.model = models.normalizeModelUIName(model)

                                if back_end == 'hp':
                                    d = self.__tr("%1 Printer (%2)").arg(model).arg(idd)

                                elif back_end == 'hpaio':
                                    d = self.__tr("%1 Scanner (%2)").arg(model).arg(idd)

                                elif back_end == 'hpfax':
                                    d = self.__tr("%1 Fax (%2)").arg(model).arg(idd)

                                else:
                                    d = self.__tr("%1 (%2)").arg(model).arg(idd)

                            if show_message:
                                if have_pynotify and pynotify.init("hplip"): # Use libnotify/pynotify
                                    icon, urgency = ERROR_STATE_TO_ICON_AND_URGENCY_PYNOTIFY.get(error_state,
                                        (getPynotifyIcon('info'), pynotify.URGENCY_NORMAL))

                                    if event.job_id and event.title:
                                        msg = "%s\n%s: %s\n(%s/%s)" % (unicode(d), desc, event.title, event.username, event.job_id)
                                        log.debug("Notify: uri=%s desc=%s title=%s user=%s job_id=%d code=%d" %
                                                (event.device_uri, desc, event.title, event.username, event.job_id, event.event_code))
                                    else:
                                        msg = "%s\n%s (%s)" % (unicode(d), desc, event.event_code)
                                        log.debug("Notify: uri=%s desc=%s code=%d" % (event.device_uri, desc, event.event_code))

                                    n = pynotify.Notification("HPLIP Device Status", msg, icon)
                                    n.set_urgency(urgency)

                                    if error_state == ERROR_STATE_ERROR:
                                        n.set_timeout(pynotify.EXPIRES_NEVER)
                                    else:
                                        n.set_timeout(TRAY_MESSAGE_DELAY)

                                    n.show()

                                else: # Use "standard" message bubbles
                                    icon = ERROR_STATE_TO_ICON.get(error_state, QSystemTrayIcon.Information)
                                    if event.job_id and event.title:
                                        log.debug("Bubble: uri=%s desc=%s title=%s user=%s job_id=%d code=%d" %
                                                (event.device_uri, desc, event.title, event.username, event.job_id, event.event_code))
                                        self.tray_icon.showMessage(self.__tr("HPLIP Device Status"),
                                            QString("%1\n%2: %3\n(%4/%5)").\
                                            arg(d).\
                                            arg(desc).arg(event.title).\
                                            arg(event.username).arg(event.job_id),
                                            icon, TRAY_MESSAGE_DELAY)

                                    else:
                                        log.debug("Bubble: uri=%s desc=%s code=%d" % (event.device_uri, desc, event.event_code))
                                        self.tray_icon.showMessage(self.__tr("HPLIP Device Status"),
                                            QString("%1\n%2 (%3)").arg(d).\
                                            arg(desc).arg(event.event_code),
                                            icon, TRAY_MESSAGE_DELAY)

            else:
                break
コード例 #37
0
ファイル: hpfax.py プロジェクト: danwallach/VoteBox-v1
        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':
                print('direct %s "HP Fax 3" "%s USB %s HP Fax HPLIP" "MFG:HP;MDL:Fax 3;DES:HP Fax 3;"' % \
                    (uri.replace("hp:", "hpfax:"), model.replace('_', ' '), serial))

            else: # par
                print('direct %s "HP Fax 3" "%s LPT HP Fax HPLIP" "MFG:HP;MDL:Fax 3;DES:HP Fax 3;"' % \
                    (uri.replace("hp:", "hpfax:"), model.replace('_', ' ')))
コード例 #38
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
コード例 #39
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
コード例 #40
0
ファイル: hpfax.py プロジェクト: dhirajpatra/lti_tool
        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':
                print('direct %s "HP Fax 3" "%s USB %s HP Fax HPLIP" "MFG:HP;MDL:Fax 3;DES:HP Fax 3;"' % \
                    (uri.replace("hp:", "hpfax:"), model.replace('_', ' '), serial))

            else:  # par
                print('direct %s "HP Fax 3" "%s LPT HP Fax HPLIP" "MFG:HP;MDL:Fax 3;DES:HP Fax 3;"' % \
                    (uri.replace("hp:", "hpfax:"), model.replace('_', ' ')))
コード例 #41
0
    def notifierActivated(self, s):
        m = ''
        while True:
            try:
                r, w, e = select.select([self.read_pipe], [], [self.read_pipe], 1.0)
            except select.error:
                log.debug("Error in select()")
                break

            if e:
                log.error("Pipe error: %s" % e)
                break

            if r:
                #m = ''.join([m, os.read(self.read_pipe, self.fmt_size)])
                m = os.read(self.read_pipe, self.fmt_size)
                while len(m) >= self.fmt_size:
                    event = device.Event(*[x.rstrip(b'\x00').decode('utf-8') if isinstance(x, bytes) else x for x in struct.unpack(self.fmt, m[:self.fmt_size])])
                    m = m[self.fmt_size:]

                    if event.event_code == EVENT_CUPS_QUEUES_REMOVED or event.event_code == EVENT_CUPS_QUEUES_ADDED:
                        self.resetDevice()
                        for d in device.getSupportedCUPSDevices(back_end_filter=['hp', 'hpfax']):
                            self.addDevice(d)

                        self.setMenu()

                    if event.event_code == EVENT_USER_CONFIGURATION_CHANGED:
                        log.debug("Re-reading configuration (EVENT_USER_CONFIGURATION_CHANGED)")
                        self.user_settings.load()
                        self.user_settings.debug()

                    elif event.event_code == EVENT_SYSTEMTRAY_EXIT:
                        self.quit()
                        return

                    if self.user_settings.systray_visible in \
                        (SYSTRAY_VISIBLE_SHOW_ALWAYS, SYSTRAY_VISIBLE_HIDE_WHEN_INACTIVE):

                        log.debug("Showing...")
                        self.tray_icon.setVisible(True)

                        if event.event_code == EVENT_DEVICE_UPDATE_ACTIVE:
                            if not self.active_icon:
                                self.tray_icon.setIcon(self.prop_active_icon)
                                self.active_icon = True
                            continue

                        elif event.event_code == EVENT_DEVICE_UPDATE_INACTIVE:
                            if self.active_icon:
                                self.tray_icon.setIcon(self.prop_icon)
                                self.active_icon = False
                            continue

                        elif event.event_code == EVENT_DEVICE_UPDATE_BLIP:
                            if not self.active_icon:
                                self.tray_icon.setIcon(self.prop_active_icon)
                                self.active_icon = True
                                QTimer.singleShot(BLIP_DELAY, self.blipTimeout)
                            continue

                    if self.user_settings.systray_visible in (SYSTRAY_VISIBLE_HIDE_WHEN_INACTIVE, SYSTRAY_VISIBLE_HIDE_ALWAYS):
                        log.debug("Waiting to hide...")
                        QTimer.singleShot(HIDE_INACTIVE_DELAY, self.timeoutHideWhenInactive)

                    if event.event_code <= EVENT_MAX_USER_EVENT or \
                        event.event_code == EVENT_CUPS_QUEUES_REMOVED or event.event_code == EVENT_CUPS_QUEUES_ADDED:

                        if event.event_code != EVENT_CUPS_QUEUES_REMOVED:
                            self.addDevice(event.device_uri)
                            self.setMenu()

                        if self.tray_icon.supportsMessages():

                            log.debug("Tray icon message:")
                            event.debug()

                            error_state = STATUS_TO_ERROR_STATE_MAP.get(event.event_code, ERROR_STATE_CLEAR)
                            desc = device.queryString(event.event_code)

                            show_message = False
                            if self.user_settings.systray_messages == SYSTRAY_MESSAGES_SHOW_ALL: # OK, Busy
                                show_message = True

                            elif self.user_settings.systray_messages in (SYSTRAY_MESSAGES_SHOW_ERRORS_AND_WARNINGS, SYSTRAY_MESSAGES_SHOW_ERRORS_ONLY):
                                if error_state == ERROR_STATE_ERROR:
                                    show_message = True

                                elif self.user_settings.systray_messages == SYSTRAY_MESSAGES_SHOW_ERRORS_AND_WARNINGS and \
                                    error_state in (ERROR_STATE_WARNING, ERROR_STATE_LOW_SUPPLIES, ERROR_STATE_LOW_PAPER):

                                    show_message = True

                            if event.printer_name:
                                d = event.printer_name
                            else:
                                back_end, is_hp, bus, model, serial, dev_file, host, zc, port = \
                                                device.parseDeviceURI(event.device_uri)

                                if bus == 'usb':
                                    idd = serial
                                elif bus == 'net':
                                    idd = host
                                elif bus == 'par':
                                    idd = dev_file
                                else:
                                    idd = 'unknown'

                                self.model = models.normalizeModelUIName(model)

                                if back_end == 'hp':
                                    d = self.__tr("%s Printer (%s)"%(model,idd))

                                elif back_end == 'hpaio':
                                    d = self.__tr("%s Scanner (%s)"%(model,idd))

                                elif back_end == 'hpfax':
                                    d = self.__tr("%s Fax (%s)"%(model,idd))

                                else:
                                    d = self.__tr("%s (%s)"%(model,idd))

                            if show_message:
                                if have_pynotify and pynotify.init("hplip"): # Use libnotify/pynotify
                                    icon, urgency = ERROR_STATE_TO_ICON_AND_URGENCY_PYNOTIFY.get(error_state,
                                        (getPynotifyIcon('info'), pynotify.URGENCY_NORMAL))

                                    if event.job_id and event.title:
                                        msg = "%s\n%s: %s\n(%s/%s)" % (to_unicode(d), desc, event.title, event.username, event.job_id)
                                        log.debug("Notify: uri=%s desc=%s title=%s user=%s job_id=%d code=%d" %
                                                (event.device_uri, desc, event.title, event.username, event.job_id, event.event_code))
                                    else:
                                        msg = "%s\n%s (%s)" % (to_unicode(d), desc, event.event_code)
                                        log.debug("Notify: uri=%s desc=%s code=%d" % (event.device_uri, desc, event.event_code))

                                    n = pynotify.Notification("HPLIP Device Status", msg, icon)
                                    # CRID: 11833 Debian Traceback error notification exceeded
                                    n.set_hint('transient', True)
                                    n.set_urgency(urgency)

                                    if error_state == ERROR_STATE_ERROR:
                                        n.set_timeout(pynotify.EXPIRES_NEVER)
                                    else:
                                        n.set_timeout(TRAY_MESSAGE_DELAY)

                                    n.show()

                                else: # Use "standard" message bubbles
                                    icon = ERROR_STATE_TO_ICON.get(error_state, QSystemTrayIcon.Information)
                                    if event.job_id and event.title:
                                        log.debug("Bubble: uri=%s desc=%s title=%s user=%s job_id=%d code=%d" %
                                                (event.device_uri, desc, event.title, event.username, event.job_id, event.event_code))
                                        self.tray_icon.showMessage(self.__tr("HPLIP Device Status"),
                                                                   "%s\n%s: %s\n(%s/%s)"%(d,desc, event.title,event.username,event.job_id),
                                                                   icon, TRAY_MESSAGE_DELAY)

                                    else:
                                        log.debug("Bubble: uri=%s desc=%s code=%d" % (event.device_uri, desc, event.event_code))
                                        self.tray_icon.showMessage(self.__tr("HPLIP Device Status"),
                                                                   "%s\n%s (%s)"%(d,desc,event.event_code),
                                                                   icon, TRAY_MESSAGE_DELAY)

            else:
                break
コード例 #42
0
    def initDiscoveryPage(self):
        self.UsbRadioButton.setChecked(True)
        self.setUsbRadioButton(True)
        self.ManualGroupBox.setChecked(False)

        self.advanced = False
        self.manual = False
        self.skip_discovery = False
        self.discovery_method = 0
        self.NetworkRadioButton.setEnabled(prop.net_build)
        self.WirelessButton.setEnabled(prop.net_build)
        self.ParallelRadioButton.setEnabled(prop.par_build)
        self.devices = {}
        self.bus = 'usb'
        self.timeout = 5
        self.ttl = 4
        self.search = ''
        self.print_test_page = False
        self.device_desc = DEVICE_DESC_ALL

        if self.param:
            log.info("Searching for device...")
            self.manual = True
            self.advanced = True
            self.ManualParamLineEdit.setText(self.param)
            self.JetDirectSpinBox.setValue(self.jd_port)
            self.ManualGroupBox.setChecked(True)
            self.DiscoveryOptionsGroupBox.setEnabled(False)

            if self.manualDiscovery():
                self.skip_discovery = True
            else:
                FailureUI(self, self.__tr("<b>Device not found.</b> <p>Please make sure your printer is properly connected and powered-on."))

                match = device.usb_pat.match(self.param)
                if match is not None:
                    self.UsbRadioButton.setChecked(True)
                    self.setUsbRadioButton(True)

                else:
                    match = device.dev_pat.match(self.param)
                    if match is not None and prop.par_build:
                        self.ParallelRadioButton.setChecked(True)
                        self.setParallelRadioButton(True)

                    else:
                        match = device.ip_pat.match(self.param)
                        if match is not None and prop.net_build:
                            self.NetworkRadioButton.setChecked(True)
                            self.setNetworkRadioButton(True)

                        else:
                            FailureUI(self, self.__tr("<b>Invalid manual discovery parameter.</b>"))

        elif self.device_uri: # If device URI specified on the command line, skip discovery
                              # if the device URI is well-formed (but not necessarily valid)
            try:
                back_end, is_hp, self.bus, model, serial, dev_file, host, zc, port = \
                device.parseDeviceURI(self.device_uri)

            except Error:
                log.error("Invalid device URI specified: %s" % self.device_uri)

            else:
                name = host
                if self.bus == 'net':
                    try:
                        log.debug("Trying to get hostname for device...")
                        name = socket.gethostbyaddr(host)[0]
                    except socket.herror:
                        log.debug("Failed.")
                    else:
                        log.debug("Host name=%s" % name)

                self.devices = {self.device_uri : (model, model, name)}
                self.skip_discovery = True

        # If no network or parallel, usb is only option, skip initial page...
        elif not prop.par_build and not prop.net_build:
            self.skip_discovery = True
            self.bus = 'usb'
            self.UsbRadioButton.setChecked(True)
            self.setUsbRadioButton(True)

        if prop.fax_build and prop.scan_build:
            self.DeviceTypeComboBox.addItem("All devices/printers", QVariant(DEVICE_DESC_ALL))
            self.DeviceTypeComboBox.addItem("Single function printers only", QVariant(DEVICE_DESC_SINGLE_FUNC))
            self.DeviceTypeComboBox.addItem("All-in-one/MFP devices only", QVariant(DEVICE_DESC_MULTI_FUNC))
        else:
            self.DeviceTypeComboBox.setEnabled(False)

        self.connect(self.AdvancedButton, SIGNAL("clicked()"), self.AdvancedButton_clicked)
        self.connect(self.UsbRadioButton, SIGNAL("toggled(bool)"), self.UsbRadioButton_toggled)
        self.connect(self.NetworkRadioButton, SIGNAL("toggled(bool)"), self.NetworkRadioButton_toggled)
        self.connect(self.WirelessButton, SIGNAL("toggled(bool)"), self.WirelessButton_toggled)
        self.connect(self.ParallelRadioButton, SIGNAL("toggled(bool)"), self.ParallelRadioButton_toggled)
        self.connect(self.NetworkTTLSpinBox,  SIGNAL("valueChanged(int)"), self.NetworkTTLSpinBox_valueChanged)
        self.connect(self.NetworkTimeoutSpinBox,  SIGNAL("valueChanged(int)"),
                     self.NetworkTimeoutSpinBox_valueChanged)
        self.connect(self.ManualGroupBox,  SIGNAL("toggled(bool)"),  self.ManualGroupBox_toggled)

        self.showAdvanced()
コード例 #43
0
    def showPage(self, page):
        orig_page = page

        if self.first_page:
            page = self.start_page
            self.first_page = False

        log.debug("%s %s %s" % ("*"*20, "showPage(%s)" % page.name(), "*"*20))

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

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

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


        elif page is self.PPDPage: # ProbedDevicesPage --> PPDPage
            if self.param:
                device_uri, sane_uri, fax_uri = device.makeURI(self.param, self.jd_port)

                if device_uri:
                    self.device_uri = device_uri

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

            self.bus = bus
            self.mq = device.queryModelByURI(self.device_uri)

            norm_model = models.normalizeModelName(model).lower()

            core = core_install.CoreInstall()
            core.set_plugin_version()
            plugin = self.mq.get('plugin', PLUGIN_NONE)
            plugin_reason = self.mq.get('plugin-reason', PLUGIN_REASON_NONE)
            if plugin > PLUGIN_NONE and not core.check_for_plugin():
                ok, sudo_ok = pkit.run_plugin_command(plugin == PLUGIN_REQUIRED, plugin_reason)
                if not sudo_ok:
                    self.FailureUI(self.__tr("<b>Unable to find an appropriate su/sudo utility to run hp-plugin.</b><p>Install kdesu, gnomesu, or gksu.</p>"))
                    return
                if not ok or not core.check_for_plugin():
                    if plugin == PLUGIN_REQUIRED:
                        self.FailureUI(self.__tr("<b>The printer you are trying to setup requires a binary driver plug-in and it failed to install.</b><p>Please check your internet connection and try again.</p><p>Visit <u>http://hplipopensource.com</u> for more information.</p>"))
                        return
                    else:
                        self.WarningUI(self.__tr("Either you have chosen to skip the installation of the optional plug-in or that installation has failed.  Your printer may not function at optimal performance."))

            self.updatePPDPage()

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

            if fax_import_ok and prop.fax_build and \
                self.mq.get('fax-type', FAX_TYPE_NONE) not in (FAX_TYPE_NONE, FAX_TYPE_NOT_SUPPORTED):

                self.faxCheckBox.setEnabled(True)
                self.faxCheckBox.setEnabled(True)
                self.faxNameLineEdit.setEnabled(True)
                self.faxNumberLineEdit.setEnabled(True)
                self.faxNameCoLineEdit.setEnabled(True)
                self.faxLocationLineEdit.setEnabled(True)
                self.faxDescriptionLineEdit.setEnabled(True)
                self.faxInfoGroupBox.setEnabled(True)
                self.setup_fax = True
                self.setDefaultFaxName()
                self.readwriteFaxInformation(True)

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

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

            #log.debug("Restarting CUPS...")
            #status, output = utils.run(restart_cups())
            #log.debug("Restart CUPS returned: exit=%d output=%s" % (status, output))

            self.setupPrinter()

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

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

                self.faxGroupBox.setEnabled(True)

            else:
                self.faxGroupBox.setEnabled(False)

            self.setFinishEnabled(self.FinishedPage, True)

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

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

        if page is self.ProbedDevicesPage: # ConnectionPage --> ProbedDevicesPage/EnterIPPage/DeviceNotFoundPage
            if not devices_found:
                self.FailureUI(self.__tr("<b>No devices found.</b><p>Please make sure your printer is properly connected and powered-on."))
コード例 #44
0
ファイル: systemtray.py プロジェクト: danwallach/VoteBox-v1
    def notifierActivated(self, s):
        m = ''
        while True:
            try:
                r, w, e = select.select([self.read_pipe], [], [self.read_pipe], 1.0)
            except select.error:
                log.debug("Error in select()")
                break

            if e:
                log.error("Pipe error: %s" % e)
                break

            if r:
                #m = ''.join([m, os.read(self.read_pipe, self.fmt_size)])
                m = os.read(self.read_pipe, self.fmt_size)
                while len(m) >= self.fmt_size:
                    event = device.Event(*[x.rstrip(b'\x00').decode('utf-8') if isinstance(x, bytes) else x for x in struct.unpack(self.fmt, m[:self.fmt_size])])
                    m = m[self.fmt_size:]                   

                    if event.event_code == EVENT_ERROR_NO_PROBED_DEVICES_FOUND:
                        newmsg = "HPLIP cannot detect devices in your network. This may be due to existing firewall settings blocking the required ports like (5353/udp). When you are in a trusted network environment, you may open the ports for network services like mdns and slp in the firewall. For detailed steps follow the link.\n\n http://hplipopensource.com/node/375"
                        FailureUI(None, newmsg, "")
                        continue
                    
                    if event.event_code == EVENT_CUPS_QUEUES_REMOVED or event.event_code == EVENT_CUPS_QUEUES_ADDED:
                        self.resetDevice()
                        for d in device.getSupportedCUPSDevices(back_end_filter=['hp', 'hpfax']):
                            self.addDevice(d)
                            
                        self.setMenu()

                    if event.event_code == EVENT_USER_CONFIGURATION_CHANGED:
                        log.debug("Re-reading configuration (EVENT_USER_CONFIGURATION_CHANGED)")
                        self.user_settings.load()
                        self.user_settings.debug()

                    elif event.event_code == EVENT_SYSTEMTRAY_EXIT:
                        self.quit()
                        return

                    if self.user_settings.systray_visible in \
                        (SYSTRAY_VISIBLE_SHOW_ALWAYS, SYSTRAY_VISIBLE_HIDE_WHEN_INACTIVE):
                        
                        log.debug("Showing...")
                        self.tray_icon.setVisible(True)

                        if event.event_code == EVENT_DEVICE_UPDATE_ACTIVE:
                            if not self.active_icon:
                                self.tray_icon.setIcon(self.prop_active_icon)
                                self.active_icon = True
                            continue

                        elif event.event_code == EVENT_DEVICE_UPDATE_INACTIVE:
                            if self.active_icon:
                                self.tray_icon.setIcon(self.prop_icon)
                                self.active_icon = False
                            continue

                        elif event.event_code == EVENT_DEVICE_UPDATE_BLIP:
                            if not self.active_icon:
                                self.tray_icon.setIcon(self.prop_active_icon)
                                self.active_icon = True
                                QTimer.singleShot(BLIP_DELAY, self.blipTimeout)
                            continue

                    if self.user_settings.systray_visible in (SYSTRAY_VISIBLE_HIDE_WHEN_INACTIVE, SYSTRAY_VISIBLE_HIDE_ALWAYS):
                        log.debug("Waiting to hide...")
                        QTimer.singleShot(HIDE_INACTIVE_DELAY, self.timeoutHideWhenInactive)

                    if event.event_code <= EVENT_MAX_USER_EVENT or \
                        event.event_code == EVENT_CUPS_QUEUES_REMOVED or event.event_code == EVENT_CUPS_QUEUES_ADDED:

                        if event.event_code != EVENT_CUPS_QUEUES_REMOVED:
                            self.addDevice(event.device_uri)
                            self.setMenu()

                        if self.tray_icon.supportsMessages():

                            log.debug("Tray icon message:")
                            event.debug()

                            error_state = STATUS_TO_ERROR_STATE_MAP.get(event.event_code, ERROR_STATE_CLEAR)
                            desc = device.queryString(event.event_code)

                            show_message = False
                            if self.user_settings.systray_messages == SYSTRAY_MESSAGES_SHOW_ALL: # OK, Busy
                                show_message = True

                            elif self.user_settings.systray_messages in (SYSTRAY_MESSAGES_SHOW_ERRORS_AND_WARNINGS, SYSTRAY_MESSAGES_SHOW_ERRORS_ONLY):
                                if error_state == ERROR_STATE_ERROR:
                                    show_message = True

                                elif self.user_settings.systray_messages == SYSTRAY_MESSAGES_SHOW_ERRORS_AND_WARNINGS and \
                                    error_state in (ERROR_STATE_WARNING, ERROR_STATE_LOW_SUPPLIES, ERROR_STATE_LOW_PAPER):

                                    show_message = True

                            if event.printer_name:
                                d = QString(event.printer_name)
                            else:
                                back_end, is_hp, bus, model, serial, dev_file, host, zc, port = \
                                                device.parseDeviceURI(event.device_uri)

                                if bus == 'usb':
                                    idd = serial
                                elif bus == 'net':
                                    idd = host
                                elif bus == 'par':
                                    idd = dev_file
                                else:
                                    idd = 'unknown'

                                self.model = models.normalizeModelUIName(model)

                                if back_end == 'hp':
                                    d = self.__tr("%s Printer (%s)"%(model,idd))

                                elif back_end == 'hpaio':
                                    d = self.__tr("%s Scanner (%s)"%(model,idd))

                                elif back_end == 'hpfax':
                                    d = self.__tr("%s Fax (%s)"%(model,idd))

                                else:
                                    d = self.__tr("%s (%s)"%(model,idd))

                            if show_message:
                                if have_pynotify and pynotify.init("hplip"): # Use libnotify/pynotify
                                    icon, urgency = ERROR_STATE_TO_ICON_AND_URGENCY_PYNOTIFY.get(error_state,
                                        (getPynotifyIcon('info'), pynotify.URGENCY_NORMAL))

                                    if event.job_id and event.title:
                                        msg = "%s\n%s: %s\n(%s/%s)" % (to_unicode(d), desc, event.title, event.username, event.job_id)
                                        log.debug("Notify: uri=%s desc=%s title=%s user=%s job_id=%d code=%d" %
                                                (event.device_uri, desc, event.title, event.username, event.job_id, event.event_code))
                                    else:
                                        msg = "%s\n%s (%s)" % (to_unicode(d), desc, event.event_code)
                                        log.debug("Notify: uri=%s desc=%s code=%d" % (event.device_uri, desc, event.event_code))

                                    n = pynotify.Notification("HPLIP Device Status", msg, icon)
                                    # CRID: 11833 Debian Traceback error notification exceeded
                                    n.set_hint('transient', True)
                                    n.set_urgency(urgency)

                                    if error_state == ERROR_STATE_ERROR:
                                        n.set_timeout(pynotify.EXPIRES_NEVER)
                                    else:
                                        n.set_timeout(TRAY_MESSAGE_DELAY)

                                    n.show()

                                else: # Use "standard" message bubbles
                                    icon = ERROR_STATE_TO_ICON.get(error_state, QSystemTrayIcon.Information)
                                    if event.job_id and event.title:
                                        log.debug("Bubble: uri=%s desc=%s title=%s user=%s job_id=%d code=%d" %
                                                (event.device_uri, desc, event.title, event.username, event.job_id, event.event_code))
                                        self.tray_icon.showMessage(self.__tr("HPLIP Device Status"),
                                            QString("%s\n%s: %s\n(%s/%s)"%(d,desc, event.title,event.username,event.job_id)),
                                            icon, TRAY_MESSAGE_DELAY)

                                    else:
                                        log.debug("Bubble: uri=%s desc=%s code=%d" % (event.device_uri, desc, event.event_code))
                                        self.tray_icon.showMessage(self.__tr("HPLIP Device Status"),
                                            QString("%s\n%s (%s)"%(d,desc,event.event_code)),
                                            icon, TRAY_MESSAGE_DELAY)

            else:
                break
コード例 #45
0
ファイル: setupdialog.py プロジェクト: incrazyboyy/RPiTC-X
    def NextButton_clicked(self):
        p = self.StackedWidget.currentIndex()
        if p == PAGE_DISCOVERY:
            self.manual = self.ManualGroupBox.isChecked()
            self.param = unicode(self.ManualParamLineEdit.text())
            self.jd_port = self.JetDirectSpinBox.value()
            self.search = unicode(self.SearchLineEdit.text())
            self.device_desc = int(self.DeviceTypeComboBox.itemData(self.DeviceTypeComboBox.currentIndex()).toInt()[0])
            self.discovery_method = self.NetworkDiscoveryMethodComboBox.currentIndex()

            if self.WirelessButton.isChecked():
                dlg = WifiSetupDialog(self, device_uri=None, standalone=False)
                dlg.exec_()

                if dlg.success == SUCCESS_CONNECTED:
                    self.manual = True
                    self.param = dlg.hn
                    self.bus = 'net'
            if not self.WirelessButton.isChecked():
                self.showDevicesPage()
           
        elif p == PAGE_DEVICES:
            row = self.DevicesTableWidget.currentRow()
            self.device_uri = self.DevicesTableWidget.item(row, 0).device_uri
            self.mq = device.queryModelByURI(self.device_uri)
            back_end, is_hp, bus, model, serial, dev_file, host, zc, port = device.parseDeviceURI(self.device_uri)
            self.model = models.normalizeModelName(model).lower()
            self.showAddPrinterPage()

        elif p == PAGE_ADD_PRINTER:
            self.print_test_page = self.SendTestPageCheckBox.isChecked()
            self.print_desc = unicode(self.PrinterDescriptionLineEdit.text()).encode('utf8')
            self.print_location = unicode(self.PrinterLocationLineEdit.text()).encode('utf8')
            self.fax_setup = self.SetupFaxGroupBox.isChecked()
            self.fax_desc = unicode(self.FaxDescriptionLineEdit.text())
            self.fax_location = unicode(self.FaxLocationLineEdit.text())
            self.fax_name_company = unicode(self.NameCompanyLineEdit.text())
            self.fax_number = unicode(self.FaxNumberLineEdit.text())
            self.addPrinter()

        elif p == PAGE_REMOVE:
            for row in xrange(self.RemoveDevicesTableWidget.rowCount()):
                widget = self.RemoveDevicesTableWidget.cellWidget(row, 0)
                if widget.checkState() == Qt.Checked:
                    item = self.RemoveDevicesTableWidget.item(row, 1)
                    printer = unicode(item.data(Qt.UserRole).toString()).encode('utf-8')
                    uri = device.getDeviceURIByPrinterName(printer)
                    log.debug("Removing printer: %s" % printer)
                    status, status_str = cups.cups_operation(cups.delPrinter, GUI_MODE, 'qt4', self, printer)

                    if  status != cups.IPP_OK:
                        FailureUI(self, self.__tr("<b>Unable to delete '%s' queue. </b><p>Error : %s"%(printer,status_str)))
                        if status == cups.IPP_FORBIDDEN or status == cups.IPP_NOT_AUTHENTICATED or status == cups.IPP_NOT_AUTHORIZED:
                            break
                    else:
                        # sending Event to add this device in hp-systray
                        utils.sendEvent(EVENT_CUPS_QUEUES_REMOVED, uri, printer)

            self.close()

        else:
            log.error("Invalid page!") # shouldn't happen!
コード例 #46
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
コード例 #47
0
ファイル: setup.py プロジェクト: dhirajpatra/lti_tool
            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)

        log.debug("Model=%s" % model)
        mq = device.queryModelByURI(device_uri)

        if not mq or mq.get('support-type', SUPPORT_TYPE_NONE) == SUPPORT_TYPE_NONE:
            log.error("Unsupported printer model.")
            clean_exit(1)

        if mq.get('fax-type', FAX_TYPE_NONE) in (FAX_TYPE_NONE, FAX_TYPE_NOT_SUPPORTED) and setup_fax:
            #log.warning("Cannot setup fax - device does not have fax feature.")
            setup_fax = False

        # ******************************* PLUGIN

        norm_model = models.normalizeModelName(model).lower()
コード例 #48
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