Exemplo n.º 1
0
    def updatePrintButton(self):
        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        self.PrintTestpageButton.setEnabled(False)
        ok = False
        try:
            try:
                d = device.Device(self.device_uri, self.printer_name)
            except Error as e:
                log.error("Device error (%s)." % e.msg)
            else:
                try:
                    d.open()
                except Error:
                    log.error("Unable to print to printer. Please check device and try again.")
                else:
                    ok = d.isIdleAndNoError()

            self.PrintTestpageButton.setEnabled(ok)

            if not ok:
                QApplication.restoreOverrideCursor()
                FailureUI(self, self.__tr("<b>Unable to communicate with printer %s.</b><p>Please check the printer and try again." % self.printer_name))

            d.close()

        finally:
            QApplication.restoreOverrideCursor()
Exemplo n.º 2
0
    def CalibrateButton_clicked(self):
        d = None

        try:
            try:
                d = device.Device(self.device_uri)
            except Error:
                CheckDeviceUI(self)
                return

            linefeed_type = d.linefeed_cal_type

            try:
                d.open()
            except Error:
                CheckDeviceUI(self)
            else:
                if d.isIdleAndNoError():
                    if linefeed_type == LINEFEED_CAL_TYPE_OJ_K550: # 1
                        maint.linefeedCalType1(d, lambda : True)

                    elif linefeed_type == LINEFEED_CAL_TYPE_OJ_PRO_L7XXX: # 2
                        maint.linefeedCalType2(d, lambda : True)

                else:
                    CheckDeviceUI(self)

        finally:
            if d is not None:
                d.close()

        self.close()
Exemplo n.º 3
0
    def DeviceUriComboBox_currentChanged(self, device_uri):
        beginWaitCursor()
        try:
            self.device_uri = device_uri

            if self.dev is not None:
                self.dev.close()

            self.dev = device.Device(self.device_uri)

            # Update
            self.mq = device.queryModelByURI(self.device_uri)
            self.power_settings = self.mq.get('power-settings',
                                              POWER_SETTINGS_NONE)

            self.TabWidget.setTabEnabled(
                TAB_POWER_SETTINGS, self.power_settings != POWER_SETTINGS_NONE)

            if self.power_settings == POWER_SETTINGS_EPML:
                self.updatePowerSettingsEPML()

            elif self.power_settings == POWER_SETTINGS_PML:
                self.updatePowerSettingsPML()

        finally:
            endWaitCursor()
Exemplo n.º 4
0
    def PrintTestpageButton_clicked(self):
        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        ok = False
        try:
            try:
                d = device.Device(self.device_uri, self.printer_name)
            except Error as e:
                log.error("Device error (%s)." % e.msg)
            else:
                try:
                    d.open()
                except Error:
                    log.error("Unable to print to printer. Please check device and try again.")
                else:
                    ok = d.isIdleAndNoError()

        finally:
            QApplication.restoreOverrideCursor()

        if ok:
            QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
            try:
                d.printTestPage(self.printer_name)
            finally:
                QApplication.restoreOverrideCursor()

            self.close()

        else:
            FailureUI(self, self.__tr("<b>A error occured sending the test page to printer %s.</b><p>Please check the printer and try again."% self.printer_name))

        d.close()
Exemplo n.º 5
0
    def downloadFirmware(self):
        d = None

        try:
            try:
                d = device.Device(self.device_uri)
            except Error:
                CheckDeviceUI(self)
                return

            try:
                d.open()
            except Error:
                CheckDeviceUI(self)
            else:
                if d.isIdleAndNoError():
                    ok = d.downloadFirmware()

                else:
                    CheckDeviceUI(self)

        finally:
            if d is not None:
                d.close()

        self.close()
Exemplo n.º 6
0
    def RunButton_clicked(self):
        d = None

        try:
            try:
                d = device.Device(self.device_uri)
            except Error:
                CheckDeviceUI(self)
                return

            pqdiag_type = d.pq_diag_type

            try:
                d.open()
            except Error:
                CheckDeviceUI(self)
            else:
                if d.isIdleAndNoError():
                    if pqdiag_type == 1:
                        maint.printQualityDiagType1(d, lambda: True)

                    elif pqdiag_type == 2:
                        maint.printQualityDiagType2(d, lambda: True)

                else:
                    CheckDeviceUI(self)

        finally:
            if d is not None:
                d.close()

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

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

                        try:
                            d.printTestPage(self.printer_name)
                        except Error, e:
                            if e.opt == ERROR_NO_CUPS_QUEUE_FOUND_FOR_DEVICE:
                                self.FailureUI(self.__tr("<b>No CUPS queue found for device.</b><p>Please install the printer in CUPS and try again."))
                            else:
                                self.FailureUI(self.__tr("<b>Printer Error</b><p>An error occured: %s (code=%d)." % (e.msg, e.opt)))
                    else:
                        self.FailureUI(self.__tr("<b>Printer Error.</b><p>Printer is busy, offline, or in an error state. Please check the device and try again."))
Exemplo n.º 8
0
    def PrinterNameComboBox_currentChanged(self, device_uri, printer_name):
        try:
            self.devices[device_uri]
        except KeyError:
            self.devices[device_uri] = device.Device(device_uri)

        self.OptionsToolBox.updateUi(self.devices[device_uri], printer_name)
Exemplo n.º 9
0
    def actionPushButton_clicked(self):
        if self.path:  # path
            if not self.path.startswith('http://'):
                self.path = 'file://' + self.path

        else:
            log.info("Checking for network connection...")
            ok = utils.check_network_connection()

            if not ok:
                log.error("Network connection not detected.")
                self.FailureUI(self.__tr("Network connection not detected."))
                self.close()
                return

        log.info("Downloading plug-in from: %s" % self.path)

        status, self.path, error_str = self.pluginObj.download(
            self.path, self.plugin_download_callback)

        if status != ERROR_SUCCESS:

            self.pluginObj.deleteInstallationFiles(self.path)
            self.FailureUI(error_str)
            self.close()
            return

        if not self.pluginObj.run_plugin(self.path, GUI_MODE):
            self.pluginObj.deleteInstallationFiles(self.path)
            self.FailureUI(self.__tr("Plug-in install failed."))
            self.close()
            return

        cups_devices = device.getSupportedCUPSDevices(['hp'])  #, 'hpfax'])

        for dev in cups_devices:
            mq = device.queryModelByURI(dev)

            if mq.get('fw-download', False):

                # Download firmware if needed
                log.info(
                    log.bold("\nDownloading firmware to device %s..." % dev))
                try:
                    d = device.Device(dev)
                except Error:
                    log.error("Error opening device.")
                    continue

                if d.downloadFirmware():
                    log.info("Firmware download successful.\n")

                d.close()

        self.pluginObj.deleteInstallationFiles(self.path)
        self.SuccessUI("Plug-in install successful")
        self.close()
Exemplo n.º 10
0
    def showNetworkPage(self):
        if self.dev is None:
            try:
                self.dev = device.Device(self.device_uri)
            except Error as e:
                FailureUI(
                    self,
                    self.__tr(
                        "<b>Error opening device:</b><p>%s</p><p>(%s)</p>") %
                    (self.device_uri, QString(e[0])))

                if self.dev is not None:
                    self.dev.close()

                self.close()
                return

        self.networks.clear()
        self.num_networks = 0

        try:
            adaptor_list = self.wifiObj.getWifiAdaptorID(self.dev)
        except Error as e:
            self.showIOError(e)
            return

        if len(adaptor_list) == 0:
            FailureUI(
                self,
                self.__tr(
                    "<b>Unable to locate wireless hardware on device.</b>"))
            if self.dev is not None:
                self.dev.close()

            self.close()

        log.debug("Turning on wireless radio...")
        try:
            self.adaptor_id, self.adapterName, state, presence = self.wifiObj.setAdaptorPower(
                self.dev, adaptor_list)
        except Error as e:
            self.showIOError(e)
            return
        if self.adaptor_id == -1:
            FailureUI(self,
                      self.__tr("<b>Unable to turn on wireless adaptor.</b>"))
            if self.dev is not None:
                self.dev.close()

        log.debug("Adaptor ID: %s" % self.adaptor_id)
        log.debug("Adaptor name: %s" % self.adapterName)
        log.debug("Adaptor state: %s" % state)
        log.debug("Adaptor presence: %s" % presence)

        self.performScan()
        self.setNextButton(BUTTON_NEXT)
        self.displayPage(PAGE_NETWORK)
Exemplo n.º 11
0
 def PrintTestpageButton_clicked(self):
     QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
     ok = False
     try:
         try:
             d = device.Device(self.device_uri, self.printer_name)
         except Error, e:
             log.error("Device error (%s)." % e.msg)
         else:
Exemplo n.º 12
0
 def flashFirmware(self):
     if self.mq.get('fw-download', False):
         try:
             d = device.Device(self.device_uri)
         except Error as e:
             self.FailureUI(self.__tr("<b>Error opening device. Firmware download is Failed.</b><p>%s (%s)." % (e.msg, e.opt)))
         else:
             if d.downloadFirmware():
                 log.info("Firmware download successful.\n")
             else:
                 self.FailureUI(self.__tr("<b>Firmware download is Failed.</b>"))
             d.close()
Exemplo n.º 13
0
    def endStartPage(self):
        self.mq = device.queryModelByURI(self.device_uri)
        self.clean_type = self.mq.get('clean-type', CLEAN_TYPE_NONE)
        self.seq_index = -1

        log.debug("clean-type=%d" % self.clean_type)
        self.step_max = self.max_steps[self.clean_type]

        try:
            self.dev = device.Device(self.device_uri)
        except Error:
            CheckDeviceUI(self)
            return
Exemplo n.º 14
0
    def endStartPage(self):
        self.mq = device.queryModelByURI(self.device_uri)
        self.align_type = self.mq.get('align-type', ALIGN_TYPE_NONE)
        self.seq_index = -1

        #self.align_type = ALIGN_TYPE_TEST# XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

        log.debug("align-type=%d" % self.align_type)
        self.step_max = self.max_steps[self.align_type]

        try:
            self.dev = device.Device(self.device_uri)
        except Error:
            CheckDeviceUI(self)
            return
Exemplo n.º 15
0
    def endStartPage(self):
        self.mq = device.queryModelByURI(self.device_uri)
        self.color_cal_type = self.mq.get('color-cal-type', COLOR_CAL_TYPE_NONE)
        self.seq_index = -1

        #self.color_cal_type = COLOR_CAL_TYPE_TEST # XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

        log.debug("color-cal-type=%d" % self.color_cal_type)
        self.step_max = self.max_steps[self.color_cal_type]

        try:
            self.dev = device.Device(self.device_uri)
        except Error:
            CheckDeviceUI(self)
            return
Exemplo n.º 16
0
    def __init__(self, dev_obj=None, device_uri=None, printer_name=None):

        if dev_obj is None:
            self.device = device.Device(device_uri, printer_name)
            self.device.open()
            self.close_device = True
        else:
            self.device = dev_obj
            self.close_device = False

        self.dir_stack = utils.Stack()
        self.current_dir = []
        self.device_uri = self.device.device_uri
        self.pcard_mounted = False
        self.saved_pwd = []
        self.sector_buffer = {}
        self.sector_buffer_counts = {}
        self.cache_flag = True
        self.write_protect = False

        self.callback = None

        self.channel_opened = False
Exemplo n.º 17
0
            status, status_str = cups.cups_operation(cups.addPrinter, INTERACTIVE_MODE, '', None, *add_prnt_args)

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

            if status != cups.IPP_OK:
                log.error("Printer queue setup failed. Error : %s "%status_str)
                clean_exit(1)
            else:
                # sending Event to add this device in hp-systray
                utils.sendEvent(EVENT_CUPS_QUEUES_ADDED,print_uri, printer_name)

        # Updating firmware download for supported devices.
        if ignore_plugin_check is False and mq.get('fw-download', False):
            try:
                d = device.Device(print_uri)
            except Error:
                log.error("Error opening device. Firmware download is Failed.")
            else:
                if d.downloadFirmware():
                    log.info("Firmware download successful.\n")
                else:
                    log.error("Firmware download is Failed.")
                d.close()

        # ******************************* FAX QUEUE SETUP
        if setup_fax and not prop.fax_build:
            log.error("Cannot setup fax - HPLIP not built with fax enabled.")
            setup_fax = False

        if setup_fax:
Exemplo n.º 18
0
def run(
        read_pipe2=None,  # pipe from hpssd
        write_pipe3=None):  # pipe to hpssd

    global r2, w3
    #    tmp_dir = '/tmp'
    os.umask(0o111)

    try:
        log.set_module("hp-systray(hpdio)")
        log.debug("PID=%d" % os.getpid())

        r2, w3 = read_pipe2, write_pipe3

        fmt = "80s80sI32sI80sf"  # TODO: Move to Event class
        fmt_size = struct.calcsize(fmt)

        response = {}
        dev = None
        m = ''
        while True:
            try:
                r, w, e = select.select([r2], [], [r2], 1.0)
            except KeyboardInterrupt:
                break
            except select.error as e:
                if e[0] == errno.EINTR:
                    continue
                else:
                    break

            if not r: continue
            if e: break
            m = os.read(r2, fmt_size)
            if not m:
                break

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

                action = event.event_code
                if PY3:
                    device_uri = event.device_uri
                else:
                    device_uri = str(event.device_uri)

                log.debug("Handling event...")
                event.debug()

                send_message(device_uri, EVENT_DEVICE_UPDATE_ACTIVE)

                if action in (EVENT_DEVICE_UPDATE_REQUESTED,
                              EVENT_POLLING_REQUEST):
                    #try:
                    if 1:
                        #log.debug("%s starting for %s" % (ACTION_NAMES[action], device_uri))

                        try:
                            dev = devices[device_uri]
                        except KeyError:
                            dev = devices[device_uri] = device.Device(
                                device_uri, disable_dbus=True)

                        try:
                            #print "Device.open()"
                            dev.open()
                        except Error as e:
                            log.error(e.msg)
                            response = {
                                'error-state': ERROR_STATE_ERROR,
                                'device-state': DEVICE_STATE_NOT_FOUND,
                                'status-code': EVENT_ERROR_DEVICE_IO_ERROR
                            }

                        if dev.device_state == DEVICE_STATE_NOT_FOUND:
                            dev.error_state = ERROR_STATE_ERROR
                        else:
                            if action == EVENT_DEVICE_UPDATE_REQUESTED:
                                try:
                                    #print "Device.queryDevice()"
                                    dev.queryDevice()

                                except Error as e:
                                    log.error("Query device error (%s)." %
                                              e.msg)
                                    dev.error_state = ERROR_STATE_ERROR
                                    dev.status_code = EVENT_ERROR_DEVICE_IO_ERROR

                                response = dev.dq
                                #print response

                                log.debug("Device state = %d" %
                                          dev.device_state)
                                log.debug("Status code = %d" % dev.status_code)
                                log.debug("Error state = %d" % dev.error_state)

                            else:  # EVENT_POLLING_REQUEST
                                try:
                                    dev.pollDevice()

                                except Error as e:
                                    log.error("Poll device error (%s)." %
                                              e.msg)
                                    dev.error_state = ERROR_STATE_ERROR

                                else:
                                    response = {'test': 1}

                    #finally:
                    if 1:
                        if dev is not None:
                            dev.close()

                    #thread_activity_lock.release()

                elif action == EVENT_USER_CONFIGURATION_CHANGED:
                    pass

                elif action == EVENT_SYSTEMTRAY_EXIT:
                    log.debug("Exiting")
                    sys.exit(1)

                send_message(device_uri, EVENT_DEVICE_UPDATE_INACTIVE)

                if action == EVENT_DEVICE_UPDATE_REQUESTED:
                    #print response
                    data = dumps(response, HIGHEST_PROTOCOL)

                    log.debug("Sending data through pipe to hpssd...")
                    total_written = 0
                    while True:
                        total_written += os.write(w3, data[:PIPE_BUF])
                        data = data[PIPE_BUF:]
                        if not data:
                            break

                    log.debug("Wrote %d bytes" % total_written)

                    send_message(device_uri, EVENT_DEVICE_UPDATE_REPLY,
                                 total_written)

                elif action == EVENT_POLLING_REQUEST:
                    # TODO: Translate into event: scan requested, copy requested, etc.. send as event
                    #try:
                    #    os.write
                    pass

    except KeyboardInterrupt:
        log.debug("Ctrl-C: Exiting...")
Exemplo n.º 19
0
    def __init__(self,
                 device_uri,
                 printer_name,
                 args,
                 parent=None,
                 name=None,
                 modal=0,
                 fl=0):

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

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

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

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

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

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

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

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

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

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

            #print probed_devices

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

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

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

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

            x = len(devices)

            #print devices

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

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

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

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

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

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

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

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

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

                    log.debug(self.device_uri)

                    self.statusBar().message(self.device_uri)
Exemplo n.º 20
0
    def __init__(self,
                 printer_name=None,
                 args=None,
                 parent=None,
                 name=None,
                 modal=0,
                 fl=0):

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

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

        self.statusBar()

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

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

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

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

        if not self.printer_name:  # no -p provided
            t = device.probeDevices(['cups'])
            probed_devices = []

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

            log.debug(probed_devices)

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

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

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

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

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

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

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

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

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

                log.debug(self.device_uri)

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

        QTimer.singleShot(0, self.InitialUpdate)
Exemplo n.º 21
0
    def updateInfoTable(self):
        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        self.DynamicTableWidget.clear()
        self.DynamicTableWidget.setRowCount(0)
        self.DynamicTableWidget.setColumnCount(0)
        flags = Qt.ItemIsSelectable | Qt.ItemIsEnabled

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

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

        #
        # Static Data
        #

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

        self.StaticTableWidget.clear()

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

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

        self.StaticTableWidget.setRowCount(len(mq_keys))

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

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

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

        #
        # Dynamic Data
        #

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

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

            self.DynamicTableWidget.setRowCount(len(dq_keys))

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

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

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

        finally:
            d.close()

        #
        # History Table
        #

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

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

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

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

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

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

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

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

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

        #
        # Printer Data
        #

        printers = cups.getPrinters()

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

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

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

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

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

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

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

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

                Table.setRowCount(len(keys))

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

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

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

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

        cups.closePPD()
        self.TabWidget.setCurrentIndex(0)
        QApplication.restoreOverrideCursor()
Exemplo n.º 22
0
    def _init_device(self):
        if not self.device_uri:
            raise DeviceNotFoundError("device_uri miss")

        print(self.device_uri)
        self.dev = device.Device(self.device_uri)
Exemplo n.º 23
0
        title = False

        for dev in cups_devices:
            mq = device.queryModelByURI(dev)

            if mq.get('fw-download', 0):

                if not title:
                    tui.header("DOWNLOADING FIRMWARE")
                    title = True

                # Download firmware if needed
                log.info(
                    log.bold("\nDownloading firmware to device %s..." % dev))
                try:
                    d = device.Device(dev)
                except Error:
                    log.error("Error opening device. Exiting.")
                    clean_exit(1)

                if d.downloadFirmware():
                    log.info("Firmware download successful.\n")

                d.close()

    except KeyboardInterrupt:
        log.error("User exit")

log.info("")
log.info("Done.")
clean_exit(0)
Exemplo n.º 24
0
    def validate(self,
                 time_flag=DEPENDENCY_RUN_AND_COMPILE_TIME,
                 is_quiet_mode=False):
        ############ Variables #######################
        self.cups_ddk_not_req = False
        self.hpmudext_avail = False
        self.ui_toolkit = sys_conf.get('configure', 'ui-toolkit')
        org_log_location = log.get_where()

        if is_quiet_mode:
            log.set_where(log.LOG_TO_FILE)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                        f.output()

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

                tui.header("INSTALLED CUPS PRINTER QUEUES")

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        if is_quiet_mode:
            log.set_where(org_log_location)

        return self.num_errors, self.num_warns
Exemplo n.º 25
0
                                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
Exemplo n.º 26
0
def run(read_pipe2=None,  # pipe from hpssd
        write_pipe3=None): # pipe to hpssd

    global r2, w3
#    tmp_dir = '/tmp'
    os.umask(0111)

    try:
        log.set_module("hp-systray(hpdio)")
        log.debug("PID=%d" % os.getpid())

        r2, w3 = read_pipe2, write_pipe3

        fmt = "80s80sI32sI80sf" # TODO: Move to Event class
        fmt_size = struct.calcsize(fmt)

        response = {}
        dev = None
        m = ''
        while True:
            try:
                r, w, e = select.select([r2], [], [r2], 1.0)
            except KeyboardInterrupt:
                break
            except select.error, e:
                if e[0] == errno.EINTR:
                    continue
                else:
                    break

            if not r: continue
            if e: break

            m = ''.join([m, os.read(r2, fmt_size)])

            if not m:
                break

            while len(m) >= fmt_size:
                response.clear()
                event = device.Event(*struct.unpack(fmt, m[:fmt_size]))
                m = m[fmt_size:]

                action = event.event_code
                device_uri = event.device_uri

                log.debug("Handling event...")
                event.debug()

                send_message(device_uri, EVENT_DEVICE_UPDATE_ACTIVE)

                if action in (EVENT_DEVICE_UPDATE_REQUESTED, EVENT_POLLING_REQUEST):
                    #try:
                    if 1:
                        #log.debug("%s starting for %s" % (ACTION_NAMES[action], device_uri))

                        try:
                            dev = devices[device_uri]
                        except KeyError:
                            dev = devices[device_uri] = device.Device(device_uri, disable_dbus=True)

                        try:
                            #print "Device.open()"
                            dev.open()
                        except Error, e:
                            log.error(e.msg)
                            response = {'error-state': ERROR_STATE_ERROR,
                                        'device-state': DEVICE_STATE_NOT_FOUND,
                                        'status-code' : EVENT_ERROR_DEVICE_IO_ERROR}

                        if dev.device_state == DEVICE_STATE_NOT_FOUND:
                            dev.error_state = ERROR_STATE_ERROR
                        else:
                            if action == EVENT_DEVICE_UPDATE_REQUESTED:
                                try:
                                    #print "Device.queryDevice()"
                                    dev.queryDevice()

                                except Error, e:
                                    log.error("Query device error (%s)." % e.msg)
                                    dev.error_state = ERROR_STATE_ERROR
                                    dev.status_code = EVENT_ERROR_DEVICE_IO_ERROR

                                response = dev.dq
                                #print response

                                log.debug("Device state = %d" % dev.device_state)
                                log.debug("Status code = %d" % dev.status_code)
                                log.debug("Error state = %d" % dev.error_state)

                            else: # EVENT_POLLING_REQUEST
                                try:
                                    dev.pollDevice()

                                except Error, e:
                                    log.error("Poll device error (%s)." % e.msg)
                                    dev.error_state = ERROR_STATE_ERROR

                                else:
                                    response = {'test' : 1}
Exemplo n.º 27
0
            if size < 1 or size > DEFAULT_BAR_GRAPH_SIZE:
                log.warn("Invalid size specified. Using the default of %d" %
                         DEFAULT_BAR_GRAPH_SIZE)
                size = DEFAULT_BAR_GRAPH_SIZE

        elif o in ('-c', '--color'):
            color = True

        elif o in ('-a', '--char'):
            try:
                bar_char = a[0]
            except KeyError:
                bar_char = '/'

    try:
        d = device.Device(device_uri, printer_name)
    except Error:
        log.error("Error opening device. Exiting.")
        sys.exit(1)

    try:
        try:
            d.open()
            d.queryDevice()
        except Error, e:
            log.error("Error opening device (%s). Exiting." % e.msg)
            sys.exit(1)

        if d.mq['status-type'] != STATUS_TYPE_NONE:
            log.info("")
Exemplo n.º 28
0
                        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 to function in HPLIP."
                        )
                        num_errors += 1

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

                        plugin = d.mq.get('plugin', PLUGIN_NONE)
                        if plugin in (PLUGIN_REQUIRED, PLUGIN_OPTIONAL):

                            if core.check_for_plugin():
                                if plugin == PLUGIN_REQUIRED:
                                    log.info(
                                        "Required plug-in status: Installed")
                                else:
                                    log.info(
                                        "Optional plug-in status: Installed")
                            else:
Exemplo n.º 29
0
    def NextButton_clicked(self):
        if self.SkipRadioButton.isChecked():
            log.debug("Skipping plug-in installation.")
            self.close()
            return

        beginWaitCursor()
        try:

            if self.plugin_path: # User specified Path
                if not self.plugin_path.startswith('http://'):
                    self.plugin_path = 'file://' + self.plugin_path

            else:
                log.info("Checking for network connection...")
                ok = utils.check_network_connection()

                if not ok:
                    log.error("Network connection not detected.")
                    endWaitCursor()
                    FailureUI(self, self.__tr("Network connection not detected."))
                    self.close()
                    return

            log.info("Downloading plug-in from: %s" % self.plugin_path)

            status, download_plugin_file, error_str = self.pluginObj.download(self.plugin_path,self.plugin_download_callback)

            if status in (ERROR_UNABLE_TO_RECV_KEYS, ERROR_DIGITAL_SIGN_NOT_FOUND):
                endWaitCursor()

                if QMessageBox.question(self, " ",
                        self.__tr("<b>%s</b><p>Without this, it is not possible to authenticate and validate the plug-in prior to installation.</p>Do you still want to install the plug-in?" %error_str),
                                        QMessageBox.Yes | QMessageBox.No, QMessageBox.No) != QMessageBox.Yes:

                    self.pluginObj.deleteInstallationFiles(download_plugin_file)
                    self.close()
                    return

            elif status != ERROR_SUCCESS:
                self.pluginObj.deleteInstallationFiles(download_plugin_file)
                endWaitCursor()
                FailureUI(self, error_str)
                self.close()
                return

            if not self.pluginObj.run_plugin(download_plugin_file, GUI_MODE):
                self.pluginObj.deleteInstallationFiles(download_plugin_file)
                endWaitCursor()
                FailureUI(self, self.__tr("Plug-in install failed."))
                self.close()
                return

            cups_devices = device.getSupportedCUPSDevices(['hp'])
            for dev in cups_devices:
                mq = device.queryModelByURI(dev)

                if mq.get('fw-download', False):
                    # Download firmware if needed
                    log.info(log.bold("\nDownloading firmware to device %s..." % dev))
                    try:
                        d = None
                        try:
                            d = device.Device(dev)
                        except Error:
                            log.error("Error opening device.")
                            endWaitCursor()
                            FailureUI(self, self.__tr("<b>Firmware download to device failed.</b><p>%s</p>"%dev))
                            continue

                        if d.downloadFirmware():
                            log.info("Firmware download successful.\n")
                        else:
                            endWaitCursor()
                            FailureUI(self, self.__tr("<b>Firmware download to device failed.</b><p>%s</p>"%dev))

                    finally:
                        if d is not None:
                            d.close()
        finally:
            endWaitCursor()

        self.pluginObj.deleteInstallationFiles(download_plugin_file)
        SuccessUI(self, self.__tr("<b>Plug-in installation successful</b>"))
        self.result = True
        self.close()
Exemplo n.º 30
0
    def __init__(self,
                 bus=['usb', 'par'],
                 device_uri=None,
                 printer_name=None,
                 parent=None,
                 name=None,
                 fl=0):

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

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

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

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

        self.languageChange()

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

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

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

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

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

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

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

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

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

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

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

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

                log.debug(self.device_uri)

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

        QTimer.singleShot(0, self.initialUpdate)