def debug(ioreg_to_tmp=False, buf=None, plugins=None, disabled_plugins=None):
    '''
    If plugins is None, then this method calls startup and shutdown on the
    device plugins. So if you are using it in a context where startup could
    already have been called (for example in the main GUI), pass in the list of
    device plugins as the plugins parameter.
    '''
    import textwrap
    from calibre.customize.ui import device_plugins, disabled_device_plugins
    from calibre.debug import print_basic_debug_info
    from calibre.devices.scanner import DeviceScanner
    from calibre.constants import iswindows, ismacos
    from calibre import prints
    from polyglot.io import PolyglotStringIO
    oldo, olde = sys.stdout, sys.stderr

    if buf is None:
        buf = PolyglotStringIO()
    sys.stdout = sys.stderr = buf
    out = partial(prints, file=buf)

    devplugins = device_plugins() if plugins is None else plugins
    devplugins = list(sorted(devplugins, key=lambda x: x.__class__.__name__))
    if plugins is None:
        for d in devplugins:
            try:
                d.startup()
            except:
                out('Startup failed for device plugin: %s' % d)

    if disabled_plugins is None:
        disabled_plugins = list(disabled_device_plugins())

    try:
        print_basic_debug_info(out=buf)
        s = DeviceScanner()
        s.scan()
        devices = (s.devices)
        if not iswindows:
            devices = [list(x) for x in devices]
            for d in devices:
                for i in range(3):
                    d[i] = hex(d[i])
        out('USB devices on system:')
        out(pprint.pformat(devices))

        ioreg = None
        if ismacos:
            from calibre.devices.usbms.device import Device
            mount = '\n'.join(
                repr(x) for x in Device.osx_run_mount().splitlines())
            drives = pprint.pformat(Device.osx_get_usb_drives())
            ioreg = 'Output from mount:\n' + mount + '\n\n'
            ioreg += 'Output from osx_get_usb_drives:\n' + drives + '\n\n'
            ioreg += Device.run_ioreg().decode('utf-8')
        connected_devices = []
        if disabled_plugins:
            out(
                '\nDisabled plugins:',
                textwrap.fill(' '.join(
                    [x.__class__.__name__ for x in disabled_plugins])))
            out(' ')
        else:
            out('\nNo disabled plugins')
        found_dev = False
        for dev in devplugins:
            if not dev.MANAGES_DEVICE_PRESENCE:
                continue
            out('Looking for devices of type:', dev.__class__.__name__)
            if dev.debug_managed_device_detection(s.devices, buf):
                found_dev = True
                break
            out(' ')

        if not found_dev:
            out('Looking for devices...')
            for dev in devplugins:
                if dev.MANAGES_DEVICE_PRESENCE:
                    continue
                connected, det = s.is_device_connected(dev, debug=True)
                if connected:
                    out('\t\tDetected possible device', dev.__class__.__name__)
                    connected_devices.append((dev, det))

            out(' ')
            errors = {}
            success = False
            out('Devices possibly connected:', end=' ')
            for dev, det in connected_devices:
                out(dev.name, end=', ')
            if not connected_devices:
                out('None', end='')
            out(' ')
            for dev, det in connected_devices:
                out('Trying to open', dev.name, '...', end=' ')
                dev.do_device_debug = True
                try:
                    dev.reset(detected_device=det)
                    dev.open(det, None)
                    out('OK')
                except:
                    import traceback
                    errors[dev] = traceback.format_exc()
                    out('failed')
                    continue
                dev.do_device_debug = False
                success = True
                if hasattr(dev, '_main_prefix'):
                    out('Main memory:', repr(dev._main_prefix))
                out('Total space:', dev.total_space())
                break
            if not success and errors:
                out('Opening of the following devices failed')
                for dev, msg in errors.items():
                    out(dev)
                    out(msg)
                    out(' ')

            if ioreg is not None:
                ioreg = 'IOREG Output\n' + ioreg
                out(' ')
                if ioreg_to_tmp:
                    lopen('/tmp/ioreg.txt', 'w').write(ioreg)
                    out('Dont forget to send the contents of /tmp/ioreg.txt')
                    out('You can open it with the command: open /tmp/ioreg.txt'
                        )
                else:
                    out(ioreg)

        if hasattr(buf, 'getvalue'):
            return buf.getvalue()
    finally:
        sys.stdout = oldo
        sys.stderr = olde
        if plugins is None:
            for d in devplugins:
                try:
                    d.shutdown()
                except:
                    pass
Example #2
0
def debug(ioreg_to_tmp=False, buf=None, plugins=None,
        disabled_plugins=None):
    '''
    If plugins is None, then this method calls startup and shutdown on the
    device plugins. So if you are using it in a context where startup could
    already have been called (for example in the main GUI), pass in the list of
    device plugins as the plugins parameter.
    '''
    import textwrap
    from calibre.customize.ui import device_plugins, disabled_device_plugins
    from calibre.debug import print_basic_debug_info
    from calibre.devices.scanner import DeviceScanner
    from calibre.constants import iswindows, isosx
    from calibre import prints
    from polyglot.io import PolyglotBytesIO
    oldo, olde = sys.stdout, sys.stderr

    if buf is None:
        buf = PolyglotBytesIO()
    sys.stdout = sys.stderr = buf
    out = partial(prints, file=buf)

    devplugins = device_plugins() if plugins is None else plugins
    devplugins = list(sorted(devplugins, key=lambda x: x.__class__.__name__))
    if plugins is None:
        for d in devplugins:
            try:
                d.startup()
            except:
                out('Startup failed for device plugin: %s'%d)

    if disabled_plugins is None:
        disabled_plugins = list(disabled_device_plugins())

    try:
        print_basic_debug_info(out=buf)
        s = DeviceScanner()
        s.scan()
        devices = (s.devices)
        if not iswindows:
            devices = [list(x) for x in devices]
            for d in devices:
                for i in range(3):
                    d[i] = hex(d[i])
        out('USB devices on system:')
        out(pprint.pformat(devices))

        ioreg = None
        if isosx:
            from calibre.devices.usbms.device import Device
            mount = '\n'.join(repr(x) for x in Device.osx_run_mount().splitlines())
            drives = pprint.pformat(Device.osx_get_usb_drives())
            ioreg = 'Output from mount:\n'+mount+'\n\n'
            ioreg += 'Output from osx_get_usb_drives:\n'+drives+'\n\n'
            ioreg += Device.run_ioreg()
        connected_devices = []
        if disabled_plugins:
            out('\nDisabled plugins:', textwrap.fill(' '.join([x.__class__.__name__ for x in
                disabled_plugins])))
            out(' ')
        else:
            out('\nNo disabled plugins')
        found_dev = False
        for dev in devplugins:
            if not dev.MANAGES_DEVICE_PRESENCE:
                continue
            out('Looking for devices of type:', dev.__class__.__name__)
            if dev.debug_managed_device_detection(s.devices, buf):
                found_dev = True
                break
            out(' ')

        if not found_dev:
            out('Looking for devices...')
            for dev in devplugins:
                if dev.MANAGES_DEVICE_PRESENCE:
                    continue
                connected, det = s.is_device_connected(dev, debug=True)
                if connected:
                    out('\t\tDetected possible device', dev.__class__.__name__)
                    connected_devices.append((dev, det))

            out(' ')
            errors = {}
            success = False
            out('Devices possibly connected:', end=' ')
            for dev, det in connected_devices:
                out(dev.name, end=', ')
            if not connected_devices:
                out('None', end='')
            out(' ')
            for dev, det in connected_devices:
                out('Trying to open', dev.name, '...', end=' ')
                dev.do_device_debug = True
                try:
                    dev.reset(detected_device=det)
                    dev.open(det, None)
                    out('OK')
                except:
                    import traceback
                    errors[dev] = traceback.format_exc()
                    out('failed')
                    continue
                dev.do_device_debug = False
                success = True
                if hasattr(dev, '_main_prefix'):
                    out('Main memory:', repr(dev._main_prefix))
                out('Total space:', dev.total_space())
                break
            if not success and errors:
                out('Opening of the following devices failed')
                for dev,msg in errors.items():
                    out(dev)
                    out(msg)
                    out(' ')

            if ioreg is not None:
                ioreg = 'IOREG Output\n'+ioreg
                out(' ')
                if ioreg_to_tmp:
                    lopen('/tmp/ioreg.txt', 'wb').write(ioreg)
                    out('Dont forget to send the contents of /tmp/ioreg.txt')
                    out('You can open it with the command: open /tmp/ioreg.txt')
                else:
                    out(ioreg)

        if hasattr(buf, 'getvalue'):
            return buf.getvalue().decode('utf-8', 'replace')
    finally:
        sys.stdout = oldo
        sys.stderr = olde
        if plugins is None:
            for d in devplugins:
                try:
                    d.shutdown()
                except:
                    pass
Example #3
0
    def initialize(self):
        ConfigWidgetBase.initialize(self)

        self.current_plugboards = copy.deepcopy(
            self.db.prefs.get('plugboards', {}))
        self.current_device = None
        self.current_format = None

        if self.gui.device_manager.connected_device is not None:
            self.device_label.setText(
                _('Device currently connected: ') +
                self.gui.device_manager.connected_device.__class__.__name__)
        else:
            self.device_label.setText(_('Device currently connected: None'))

        self.devices = ['', 'APPLE', 'FOLDER_DEVICE']
        self.disabled_devices = []
        self.device_to_formats_map = {}
        for device in device_plugins():
            n = device_name_for_plugboards(device)
            self.device_to_formats_map[n] = set(device.settings().format_map)
            if getattr(device, 'CAN_DO_DEVICE_DB_PLUGBOARD', False):
                self.device_to_formats_map[n].add('device_db')
            if n not in self.devices:
                self.devices.append(n)

        for device in disabled_device_plugins():
            n = device_name_for_plugboards(device)
            if n not in self.disabled_devices:
                self.disabled_devices.append(n)

        self.devices.sort(key=lambda x: x.lower())
        self.devices.insert(1, plugboard_save_to_disk_value)
        self.devices.insert(1, plugboard_content_server_value)
        self.device_to_formats_map[plugboard_content_server_value] = \
                        plugboard_content_server_formats
        self.devices.insert(1, plugboard_email_value)
        self.device_to_formats_map[plugboard_email_value] = \
                        plugboard_email_formats
        self.devices.insert(1, plugboard_any_device_value)
        self.new_device.addItems(self.devices)

        self.formats = ['']
        self.format_to_writers_map = defaultdict(list)
        for w in metadata_writers():
            for f in w.file_types:
                if f not in self.formats:
                    self.formats.append(f)
                self.format_to_writers_map[f].append(w)
        self.formats.append('device_db')
        self.formats.sort()
        self.formats.insert(1, plugboard_any_format_value)
        self.new_format.addItems(self.formats)

        self.dest_fields = [
            '', 'authors', 'author_sort', 'language', 'publisher', 'series',
            'tags', 'title', 'title_sort', 'comments'
        ]

        self.source_widgets = []
        self.dest_widgets = []
        for i in range(0, len(self.dest_fields) - 1):
            w = TemplateLineEditor(self)
            self.source_widgets.append(w)
            self.fields_layout.addWidget(w, 5 + i, 0, 1, 1)
            w = QComboBox(self)
            self.dest_widgets.append(w)
            self.fields_layout.addWidget(w, 5 + i, 1, 1, 1)

        self.edit_device.currentIndexChanged[native_string_type].connect(
            self.edit_device_changed)
        self.edit_format.currentIndexChanged[native_string_type].connect(
            self.edit_format_changed)
        self.new_device.currentIndexChanged[native_string_type].connect(
            self.new_device_changed)
        self.new_format.currentIndexChanged[native_string_type].connect(
            self.new_format_changed)
        self.existing_plugboards.itemClicked.connect(self.existing_pb_clicked)
        self.ok_button.clicked.connect(self.ok_clicked)
        self.del_button.clicked.connect(self.del_clicked)

        self.refilling = False
        self.refill_all_boxes()
Example #4
0
    def initialize(self):
        def field_cmp(x, y):
            if x.startswith('#'):
                if y.startswith('#'):
                    return cmp(x.lower(), y.lower())
                else:
                    return 1
            elif y.startswith('#'):
                return -1
            else:
                return cmp(x.lower(), y.lower())

        ConfigWidgetBase.initialize(self)

        self.current_plugboards = copy.deepcopy(self.db.prefs.get('plugboards',{}))
        self.current_device = None
        self.current_format = None

        if self.gui.device_manager.connected_device is not None:
            self.device_label.setText(_('Device currently connected: ') +
                    self.gui.device_manager.connected_device.__class__.__name__)
        else:
            self.device_label.setText(_('Device currently connected: None'))

        self.devices = ['', 'APPLE', 'FOLDER_DEVICE']
        self.disabled_devices = []
        self.device_to_formats_map = {}
        for device in device_plugins():
            n = device_name_for_plugboards(device)
            self.device_to_formats_map[n] = set(device.settings().format_map)
            if getattr(device, 'CAN_DO_DEVICE_DB_PLUGBOARD', False):
                self.device_to_formats_map[n].add('device_db')
            if n not in self.devices:
                self.devices.append(n)

        for device in disabled_device_plugins():
            n = device_name_for_plugboards(device)
            if n not in self.disabled_devices:
                self.disabled_devices.append(n)

        self.devices.sort(cmp=lambda x, y: cmp(x.lower(), y.lower()))
        self.devices.insert(1, plugboard_save_to_disk_value)
        self.devices.insert(1, plugboard_content_server_value)
        self.device_to_formats_map[plugboard_content_server_value] = \
                        plugboard_content_server_formats
        self.devices.insert(1, plugboard_email_value)
        self.device_to_formats_map[plugboard_email_value] = \
                        plugboard_email_formats
        self.devices.insert(1, plugboard_any_device_value)
        self.new_device.addItems(self.devices)

        self.formats = ['']
        self.format_to_writers_map = defaultdict(list)
        for w in metadata_writers():
            for f in w.file_types:
                if f not in self.formats:
                    self.formats.append(f)
                self.format_to_writers_map[f].append(w)
        self.formats.append('device_db')
        self.formats.sort()
        self.formats.insert(1, plugboard_any_format_value)
        self.new_format.addItems(self.formats)

        self.dest_fields = ['',
                            'authors', 'author_sort', 'language', 'publisher',
                            'tags', 'title', 'title_sort']

        self.source_widgets = []
        self.dest_widgets = []
        for i in range(0, len(self.dest_fields)-1):
            w = TemplateLineEditor(self)
            self.source_widgets.append(w)
            self.fields_layout.addWidget(w, 5+i, 0, 1, 1)
            w = QComboBox(self)
            self.dest_widgets.append(w)
            self.fields_layout.addWidget(w, 5+i, 1, 1, 1)

        self.edit_device.currentIndexChanged[str].connect(self.edit_device_changed)
        self.edit_format.currentIndexChanged[str].connect(self.edit_format_changed)
        self.new_device.currentIndexChanged[str].connect(self.new_device_changed)
        self.new_format.currentIndexChanged[str].connect(self.new_format_changed)
        self.existing_plugboards.itemClicked.connect(self.existing_pb_clicked)
        self.ok_button.clicked.connect(self.ok_clicked)
        self.del_button.clicked.connect(self.del_clicked)

        self.refilling = False
        self.refill_all_boxes()