Example #1
0
    def __init__(self, all_formats, format_map):
        QWidget.__init__(self)
        self.l = l = QGridLayout()
        self.setLayout(l)

        self.f = f = QListWidget(self)
        l.addWidget(f, 0, 0, 3, 1)
        unchecked_formats = sorted(all_formats - set(format_map))
        for fmt in format_map + unchecked_formats:
            item = QListWidgetItem(fmt, f)
            item.setData(Qt.UserRole, fmt)
            item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsUserCheckable
                          | Qt.ItemIsSelectable)
            item.setCheckState(Qt.Checked if fmt in
                               format_map else Qt.Unchecked)

        self.button_up = b = QToolButton(self)
        b.setIcon(QIcon(I('arrow-up.png')))
        l.addWidget(b, 0, 1)
        b.clicked.connect(self.up)

        self.button_down = b = QToolButton(self)
        b.setIcon(QIcon(I('arrow-down.png')))
        l.addWidget(b, 2, 1)
        b.clicked.connect(self.down)
Example #2
0
    def insertItems(self, row, items, setAsDefault = True):
        """
        Insert the <items> specified items in this list widget. 
        The list widget shows item name string , as a QListwidgetItem. 

        This QListWidgetItem object defines a 'key' of a dictionary 
        (self._itemDictionary) and the 'value' of this key is the object 
        specified by the 'item' itself.         
        Example: self._itemDictionary['C6'] = instance of class Atom. 

        @param row: The row number for the item. 
        @type row: int

        @param items: A list of objects. These objects are treated as values in 
                      the self._itemDictionary
        @type items: list 

        @param setAsDefault: Not used here. See PM_ListWidget.insertItems where 
                             it is used.

        @see: self.renameItemValue() for a comment about 
              self._suppress_itemChanged_signal

        """       

        #delete unused argument. Should this be provided as an argument in this
        #class method ?  
        del setAsDefault

        #self.__init__ for a comment about this flag
        self._suppress_itemChanged_signal = True

        #Clear the previous contents of the self._itemDictionary 
        self._itemDictionary.clear()

        #Clear the contents of this list widget, using QListWidget.clear()
        #See U{<http://doc.trolltech.com/4.2/qlistwidget.html>} for details
        self.clear()

        for item in items:
            if hasattr(item.__class__, 'name'):
                itemName = item.name
            else:
                itemName = str(item)
            listWidgetItem = QListWidgetItem(itemName, self)

            #When we support editing list widget items , uncomment out the 
            #following line . See also self.editItems -- Ninad 2008-01-16
            listWidgetItem.setFlags( listWidgetItem.flags()| Qt.ItemIsEditable)

            if hasattr(item.__class__, 'iconPath'):
                try:
                    listWidgetItem.setIcon(geticon(item.iconPath))
                except:
                    print_compact_traceback()

            self._itemDictionary[listWidgetItem] = item  

        #Reset the flag that temporarily suppresses itemChange signal.   
        self._suppress_itemChanged_signal = False
Example #3
0
    def link_stylesheets(self, names):
        s = self.categories['styles']
        sheets = [unicode(s.child(i).data(0, NAME_ROLE).toString()) for i in xrange(s.childCount())]
        if not sheets:
            return error_dialog(self, _('No stylesheets'), _(
                'This book currently has no stylesheets. You must first create a stylesheet'
                ' before linking it.'), show=True)
        d = QDialog(self)
        d.l = l = QVBoxLayout(d)
        d.setLayout(l)
        d.setWindowTitle(_('Choose stylesheets'))
        d.la = la = QLabel(_('Choose the stylesheets to link. Drag and drop to re-arrange'))

        la.setWordWrap(True)
        l.addWidget(la)
        d.s = s = QListWidget(d)
        l.addWidget(s)
        s.setDragEnabled(True)
        s.setDropIndicatorShown(True)
        s.setDragDropMode(self.InternalMove)
        s.setAutoScroll(True)
        s.setDefaultDropAction(Qt.MoveAction)
        for name in sheets:
            i = QListWidgetItem(name, s)
            flags = Qt.ItemIsEnabled | Qt.ItemIsUserCheckable | Qt.ItemIsDragEnabled | Qt.ItemIsSelectable
            i.setFlags(flags)
            i.setCheckState(Qt.Checked)
        d.bb = bb = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        bb.accepted.connect(d.accept), bb.rejected.connect(d.reject)
        l.addWidget(bb)
        if d.exec_() == d.Accepted:
            sheets = [unicode(s.item(i).text()) for i in xrange(s.count()) if s.item(i).checkState() == Qt.Checked]
            if sheets:
                self.link_stylesheets_requested.emit(names, sheets)
Example #4
0
 def __init__(self, parent, duplicates, loc):
     QDialog.__init__(self, parent)
     l = QVBoxLayout()
     self.setLayout(l)
     self.la = la = QLabel(_('Books with the same title and author as the following already exist in the library %s.'
                             ' Select which books you want copied anyway.') %
                           os.path.basename(loc))
     la.setWordWrap(True)
     l.addWidget(la)
     self.setWindowTitle(_('Duplicate books'))
     self.books = QListWidget(self)
     self.items = []
     for book_id, (title, authors) in duplicates.iteritems():
         i = QListWidgetItem(_('{0} by {1}').format(title, ' & '.join(authors[:3])), self.books)
         i.setData(Qt.UserRole, book_id)
         i.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)
         i.setCheckState(Qt.Checked)
         self.items.append(i)
     l.addWidget(self.books)
     self.bb = bb = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
     bb.accepted.connect(self.accept)
     bb.rejected.connect(self.reject)
     self.a = b = bb.addButton(_('Select &all'), bb.ActionRole)
     b.clicked.connect(self.select_all), b.setIcon(QIcon(I('plus.png')))
     self.n = b = bb.addButton(_('Select &none'), bb.ActionRole)
     b.clicked.connect(self.select_none), b.setIcon(QIcon(I('minus.png')))
     self.ctc = b = bb.addButton(_('&Copy to clipboard'), bb.ActionRole)
     b.clicked.connect(self.copy_to_clipboard), b.setIcon(QIcon(I('edit-copy.png')))
     l.addWidget(bb)
     self.resize(600, 400)
    def insertItems(self, row, items, setAsDefault = True):
        """
        Insert the <items> specified items in this list widget.
        The list widget shows item name string , as a QListwidgetItem.

        This QListWidgetItem object defines a 'key' of a dictionary
        (self._itemDictionary) and the 'value' of this key is the object
        specified by the 'item' itself.
        Example: self._itemDictionary['C6'] = instance of class Atom.

        @param row: The row number for the item.
        @type row: int

        @param items: A list of objects. These objects are treated as values in
                      the self._itemDictionary
        @type items: list

        @param setAsDefault: Not used here. See PM_ListWidget.insertItems where
                             it is used.

        @see: self.renameItemValue() for a comment about
              self._suppress_itemChanged_signal

        """

        #delete unused argument. Should this be provided as an argument in this
        #class method ?
        del setAsDefault

        #self.__init__ for a comment about this flag
        self._suppress_itemChanged_signal = True

        #Clear the previous contents of the self._itemDictionary
        self._itemDictionary.clear()

        #Clear the contents of this list widget, using QListWidget.clear()
        #See U{<http://doc.trolltech.com/4.2/qlistwidget.html>} for details
        self.clear()

        for item in items:
            if hasattr(item.__class__, 'name'):
                itemName = item.name
            else:
                itemName = str(item)
            listWidgetItem = QListWidgetItem(itemName, self)

            #When we support editing list widget items , uncomment out the
            #following line . See also self.editItems -- Ninad 2008-01-16
            listWidgetItem.setFlags( listWidgetItem.flags()| Qt.ItemIsEditable)

            if hasattr(item.__class__, 'iconPath'):
                try:
                    listWidgetItem.setIcon(geticon(item.iconPath))
                except:
                    print_compact_traceback()

            self._itemDictionary[listWidgetItem] = item

        #Reset the flag that temporarily suppresses itemChange signal.
        self._suppress_itemChanged_signal = False
Example #6
0
 def setter(w, val):
     order_map = {x: i for i, x in enumerate(val)}
     items = list(w.defaults)
     limit = len(items)
     items.sort(key=lambda x: order_map.get(x, limit))
     w.clear()
     for x in items:
         i = QListWidgetItem(w)
         i.setText(x)
         i.setFlags(i.flags() | Qt.ItemIsDragEnabled)
Example #7
0
 def initialize(self):
     self.devices.blockSignals(True)
     self.devices.clear()
     for dev in self.gui.device_manager.devices:
         for d, name in dev.get_user_blacklisted_devices().iteritems():
             item = QListWidgetItem('%s [%s]'%(name, d), self.devices)
             item.setData(Qt.UserRole, (dev, d))
             item.setFlags(Qt.ItemIsEnabled|Qt.ItemIsUserCheckable|Qt.ItemIsSelectable)
             item.setCheckState(Qt.Checked)
     self.devices.blockSignals(False)
Example #8
0
 def setter(w, val):
     order_map = {x:i for i, x in enumerate(val)}
     items = list(w.defaults)
     limit = len(items)
     items.sort(key=lambda x:order_map.get(x, limit))
     w.clear()
     for x in items:
         i = QListWidgetItem(w)
         i.setText(x)
         i.setFlags(i.flags() | Qt.ItemIsDragEnabled)
Example #9
0
 def set_bookmarks(self, bookmarks=None):
     if bookmarks is None:
         bookmarks = self.original_bookmarks
     self.bookmarks_list.clear()
     for bm in bookmarks:
         i = QListWidgetItem(bm['title'])
         i.setData(Qt.UserRole, self.bm_to_item(bm))
         i.setFlags(i.flags() | Qt.ItemIsEditable)
         self.bookmarks_list.addItem(i)
     if len(bookmarks) > 0:
         self.bookmarks_list.setCurrentItem(self.bookmarks_list.item(0), QItemSelectionModel.ClearAndSelect)
Example #10
0
 def set_bookmarks(self, bookmarks=None):
     if bookmarks is None:
         bookmarks = self.original_bookmarks
     self.bookmarks_list.clear()
     for bm in bookmarks:
         i = QListWidgetItem(bm['title'])
         i.setData(Qt.UserRole, self.bm_to_item(bm))
         i.setFlags(i.flags() | Qt.ItemIsEditable)
         self.bookmarks_list.addItem(i)
     if len(bookmarks) > 0:
         self.bookmarks_list.setCurrentItem(
             self.bookmarks_list.item(0),
             QItemSelectionModel.ClearAndSelect)
Example #11
0
 def init_input_order(self, defaults=False):
     if defaults:
         input_map = prefs.defaults['input_format_order']
     else:
         input_map = prefs['input_format_order']
     all_formats = set()
     self.opt_input_order.clear()
     for fmt in all_input_formats().union(set(['ZIP', 'RAR'])):
         all_formats.add(fmt.upper())
     for format in input_map + list(all_formats.difference(input_map)):
         item = QListWidgetItem(format, self.opt_input_order)
         item.setData(Qt.UserRole, QVariant(format))
         item.setFlags(Qt.ItemIsEnabled|Qt.ItemIsSelectable)
Example #12
0
    def link_stylesheets(self, names):
        s = self.categories['styles']
        sheets = [
            unicode(s.child(i).data(0, NAME_ROLE).toString())
            for i in xrange(s.childCount())
        ]
        if not sheets:
            return error_dialog(
                self,
                _('No stylesheets'),
                _('This book currently has no stylesheets. You must first create a stylesheet'
                  ' before linking it.'),
                show=True)
        d = QDialog(self)
        d.l = l = QVBoxLayout(d)
        d.setLayout(l)
        d.setWindowTitle(_('Choose stylesheets'))
        d.la = la = QLabel(
            _('Choose the stylesheets to link. Drag and drop to re-arrange'))

        la.setWordWrap(True)
        l.addWidget(la)
        d.s = s = QListWidget(d)
        l.addWidget(s)
        s.setDragEnabled(True)
        s.setDropIndicatorShown(True)
        s.setDragDropMode(self.InternalMove)
        s.setAutoScroll(True)
        s.setDefaultDropAction(Qt.MoveAction)
        for name in sheets:
            i = QListWidgetItem(name, s)
            flags = Qt.ItemIsEnabled | Qt.ItemIsUserCheckable | Qt.ItemIsDragEnabled | Qt.ItemIsSelectable
            i.setFlags(flags)
            i.setCheckState(Qt.Checked)
        d.r = r = QCheckBox(_('Remove existing links to stylesheets'))
        r.setChecked(tprefs['remove_existing_links_when_linking_sheets'])
        l.addWidget(r)
        d.bb = bb = QDialogButtonBox(QDialogButtonBox.Ok
                                     | QDialogButtonBox.Cancel)
        bb.accepted.connect(d.accept), bb.rejected.connect(d.reject)
        l.addWidget(bb)
        if d.exec_() == d.Accepted:
            tprefs['remove_existing_links_when_linking_sheets'] = r.isChecked()
            sheets = [
                unicode(s.item(il).text()) for il in xrange(s.count())
                if s.item(il).checkState() == Qt.Checked
            ]
            if sheets:
                self.link_stylesheets_requested.emit(names, sheets,
                                                     r.isChecked())
    def initialize(self, name):
        '''
        Retrieve plugin-specific settings from general prefs store
        Need to store order of all possible formats, enabled formats
        '''
        self.name = name

        # Supported, enabled formats
        all_formats = self.prefs.get('kindle_supported_formats', KINDLE_SUPPORTED_FORMATS)
        enabled_formats = self.prefs.get('kindle_enabled_formats', KINDLE_ENABLED_FORMATS)

        for format in all_formats:
            item = QListWidgetItem(format, self.columns)
            item.setData(Qt.UserRole, QVariant(format))
            item.setFlags(Qt.ItemIsEnabled|Qt.ItemIsUserCheckable|Qt.ItemIsSelectable)
            item.setCheckState(Qt.Checked if format in enabled_formats else Qt.Unchecked)

        self.column_up.clicked.connect(self.up_column)
        self.column_down.clicked.connect(self.down_column)
Example #14
0
    def __init__(self, parent, get_option, get_help, db=None, book_id=None):
        Widget.__init__(self, parent, [
            'paragraph_type', 'formatting_type', 'markdown_extensions',
            'preserve_spaces', 'txt_in_remove_indents'
        ])
        self.db, self.book_id = db, book_id
        for x in get_option('paragraph_type').option.choices:
            self.opt_paragraph_type.addItem(x)
        for x in get_option('formatting_type').option.choices:
            self.opt_formatting_type.addItem(x)
        self.md_map = {}
        for name, text in MD_EXTENSIONS.iteritems():
            i = QListWidgetItem('%s - %s' % (name, text),
                                self.opt_markdown_extensions)
            i.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)
            i.setData(Qt.UserRole, name)
            self.md_map[name] = i

        self.initialize_options(get_option, get_help, db, book_id)
Example #15
0
    def __init__(self, parent, get_option, get_help, db=None, book_id=None):
        Widget.__init__(
            self,
            parent,
            ["paragraph_type", "formatting_type", "markdown_extensions", "preserve_spaces", "txt_in_remove_indents"],
        )
        self.db, self.book_id = db, book_id
        for x in get_option("paragraph_type").option.choices:
            self.opt_paragraph_type.addItem(x)
        for x in get_option("formatting_type").option.choices:
            self.opt_formatting_type.addItem(x)
        self.md_map = {}
        for name, text in MD_EXTENSIONS.iteritems():
            i = QListWidgetItem("%s - %s" % (name, text), self.opt_markdown_extensions)
            i.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)
            i.setData(Qt.UserRole, name)
            self.md_map[name] = i

        self.initialize_options(get_option, get_help, db, book_id)
Example #16
0
    def __init__(self, dev, ignored_folders=None, parent=None):
        QDialog.__init__(self, parent)
        self.l = l = QVBoxLayout()
        self.setLayout(l)
        self.la = la = QLabel(
            "<p>"
            + _("<b>Scanned folders:</b>")
            + " "
            + _("You can select which top level folders calibre will " "scan when searching this device for books.")
        )
        la.setWordWrap(True)
        l.addWidget(la)
        self.tabs = QTabWidget(self)
        l.addWidget(self.tabs)
        self.widgets = []

        for storage in dev.filesystem_cache.entries:
            w = QListWidget(self)
            w.storage = storage
            self.tabs.addTab(w, storage.name)
            self.widgets.append(w)
            for child in sorted(storage.folders, key=attrgetter("name")):
                i = QListWidgetItem(child.name)
                i.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)
                i.setCheckState(
                    Qt.Unchecked
                    if dev.is_folder_ignored(storage, child.name, ignored_folders=ignored_folders)
                    else Qt.Checked
                )
                w.addItem(i)

        self.bb = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        self.bb.accepted.connect(self.accept)
        self.bb.rejected.connect(self.reject)
        self.sab = self.bb.addButton(_("Select &All"), self.bb.ActionRole)
        self.sab.clicked.connect(self.select_all)
        self.snb = self.bb.addButton(_("Select &None"), self.bb.ActionRole)
        self.snb.clicked.connect(self.select_none)
        l.addWidget(self.bb)
        self.setWindowTitle(_("Choose folders to scan"))
        self.setWindowIcon(QIcon(I("devices/tablet.png")))

        self.resize(500, 500)
Example #17
0
    def addTestrun(self, tr):
        self.testruns.append(tr)
        self.probListWidget.clear()
        self.trListWidget.clear()

        for testrun in self.testruns:
            item = QListWidgetItem((self.getTestrunName(testrun)))
            self.trListWidget.addItem(item)
            item.setFlags(item.flags() | QtCore.Qt.ItemIsEditable)

        problems = []
        if len(self.testruns) > 0:
            problems = self.testruns[0].getProblemNames()
        if len(self.testruns) > 1:
            for testrun in self.testruns[1:]:
                problems = [p for p in problems if p in set(testrun.getProblemNames())]

        for prob in sorted(problems):
            self.probListWidget.addItem(str(prob))

        self.trListWidget.selectAll()
Example #18
0
 def init_columns(self, defaults=False):
     # Set up columns
     self.opt_columns.blockSignals(True)
     model = self.gui.library_view.model()
     colmap = list(model.column_map)
     state = self.columns_state(defaults)
     hidden_cols = state['hidden_columns']
     positions = state['column_positions']
     colmap.sort(cmp=lambda x,y: cmp(positions[x], positions[y]))
     self.opt_columns.clear()
     for col in colmap:
         item = QListWidgetItem(model.headers[col], self.opt_columns)
         item.setData(Qt.UserRole, QVariant(col))
         flags = Qt.ItemIsEnabled|Qt.ItemIsSelectable
         if col != 'ondevice':
             flags |= Qt.ItemIsUserCheckable
         item.setFlags(flags)
         if col != 'ondevice':
             item.setCheckState(Qt.Unchecked if col in hidden_cols else
                     Qt.Checked)
     self.opt_columns.blockSignals(False)
Example #19
0
    def __init__(self, devs, blacklist):
        QWidget.__init__(self)
        self.l = l = QVBoxLayout()
        self.setLayout(l)
        self.la = la = QLabel('<p>'+_(
            '''Select the devices to be <b>ignored</b>. calibre <b>will not</b>
            connect to devices with a checkmark next to their names.'''))
        la.setWordWrap(True)
        l.addWidget(la)
        self.f = f = QListWidget(self)
        l.addWidget(f)

        devs = [(snum, (x[0], parse_date(x[1]))) for snum, x in
                devs.iteritems()]
        for dev, x in sorted(devs, key=lambda x:x[1][1], reverse=True):
            name = x[0]
            name = '%s [%s]'%(name, dev)
            item = QListWidgetItem(name, f)
            item.setData(Qt.UserRole, dev)
            item.setFlags(Qt.ItemIsEnabled|Qt.ItemIsUserCheckable|Qt.ItemIsSelectable)
            item.setCheckState(Qt.Checked if dev in blacklist else Qt.Unchecked)
Example #20
0
    def __init__(self, dev, ignored_folders=None, parent=None):
        QDialog.__init__(self, parent)
        self.l = l = QVBoxLayout()
        self.setLayout(l)
        self.la = la = QLabel(
            '<p>' + _('<b>Scanned folders:</b>') + ' ' +
            _('You can select which top level folders calibre will '
              'scan when searching this device for books.'))
        la.setWordWrap(True)
        l.addWidget(la)
        self.tabs = QTabWidget(self)
        l.addWidget(self.tabs)
        self.widgets = []

        for storage in dev.filesystem_cache.entries:
            w = QListWidget(self)
            w.storage = storage
            self.tabs.addTab(w, storage.name)
            self.widgets.append(w)
            for child in sorted(storage.folders, key=attrgetter('name')):
                i = QListWidgetItem(child.name)
                i.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)
                i.setCheckState(Qt.Unchecked if dev.is_folder_ignored(
                    storage, child.name, ignored_folders=ignored_folders
                ) else Qt.Checked)
                w.addItem(i)

        self.bb = QDialogButtonBox(QDialogButtonBox.Ok
                                   | QDialogButtonBox.Cancel)
        self.bb.accepted.connect(self.accept)
        self.bb.rejected.connect(self.reject)
        self.sab = self.bb.addButton(_('Select &All'), self.bb.ActionRole)
        self.sab.clicked.connect(self.select_all)
        self.snb = self.bb.addButton(_('Select &None'), self.bb.ActionRole)
        self.snb.clicked.connect(self.select_none)
        l.addWidget(self.bb)
        self.setWindowTitle(_('Choose folders to scan'))
        self.setWindowIcon(QIcon(I('devices/tablet.png')))

        self.resize(500, 500)
Example #21
0
 def init_columns(self, defaults=False):
     # Set up columns
     self.opt_columns.blockSignals(True)
     model = self.gui.library_view.model()
     colmap = list(model.column_map)
     state = self.columns_state(defaults)
     hidden_cols = state['hidden_columns']
     positions = state['column_positions']
     colmap.sort(cmp=lambda x,y: cmp(positions[x], positions[y]))
     self.opt_columns.clear()
     for col in colmap:
         item = QListWidgetItem(model.headers[col], self.opt_columns)
         item.setData(Qt.UserRole, QVariant(col))
         if col.startswith('#'):
             item.setData(Qt.DecorationRole, QVariant(QIcon(I('column.png'))))
         flags = Qt.ItemIsEnabled|Qt.ItemIsSelectable
         if col != 'ondevice':
             flags |= Qt.ItemIsUserCheckable
         item.setFlags(flags)
         if col != 'ondevice':
             item.setCheckState(Qt.Unchecked if col in hidden_cols else
                     Qt.Checked)
     self.opt_columns.blockSignals(False)
Example #22
0
    def __init__(self, all_formats, format_map):
        QWidget.__init__(self)
        self.l = l = QGridLayout()
        self.setLayout(l)

        self.f = f = QListWidget(self)
        l.addWidget(f, 0, 0, 3, 1)
        unchecked_formats = sorted(all_formats - set(format_map))
        for fmt in format_map + unchecked_formats:
            item = QListWidgetItem(fmt, f)
            item.setData(Qt.UserRole, fmt)
            item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsUserCheckable | Qt.ItemIsSelectable)
            item.setCheckState(Qt.Checked if fmt in format_map else Qt.Unchecked)

        self.button_up = b = QToolButton(self)
        b.setIcon(QIcon(I("arrow-up.png")))
        l.addWidget(b, 0, 1)
        b.clicked.connect(self.up)

        self.button_down = b = QToolButton(self)
        b.setIcon(QIcon(I("arrow-down.png")))
        l.addWidget(b, 2, 1)
        b.clicked.connect(self.down)
Example #23
0
    def __init__(self, devs, blacklist):
        QWidget.__init__(self)
        self.l = l = QVBoxLayout()
        self.setLayout(l)
        self.la = la = QLabel('<p>' + _(
            '''Select the devices to be <b>ignored</b>. calibre <b>will not</b>
            connect to devices with a checkmark next to their names.'''))
        la.setWordWrap(True)
        l.addWidget(la)
        self.f = f = QListWidget(self)
        l.addWidget(f)

        devs = [(snum, (x[0], parse_date(x[1])))
                for snum, x in devs.iteritems()]
        for dev, x in sorted(devs, key=lambda x: x[1][1], reverse=True):
            name = x[0]
            name = '%s [%s]' % (name, dev)
            item = QListWidgetItem(name, f)
            item.setData(Qt.UserRole, dev)
            item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsUserCheckable
                          | Qt.ItemIsSelectable)
            item.setCheckState(Qt.Checked if dev in
                               blacklist else Qt.Unchecked)
Example #24
0
    def initialize(self):
        self.devices.blockSignals(True)
        self.devices.clear()
        for dev in self.gui.device_manager.devices:
            for d, name in dev.get_user_blacklisted_devices().iteritems():
                item = QListWidgetItem('%s [%s]' % (name, d), self.devices)
                item.setData(Qt.UserRole, (dev, d))
                item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsUserCheckable
                              | Qt.ItemIsSelectable)
                item.setCheckState(Qt.Checked)
        self.devices.blockSignals(False)

        self.device_plugins.blockSignals(True)
        for dev in self.gui.device_manager.disabled_device_plugins:
            n = dev.get_gui_name()
            item = QListWidgetItem(n, self.device_plugins)
            item.setData(Qt.UserRole, dev)
            item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsUserCheckable
                          | Qt.ItemIsSelectable)
            item.setCheckState(Qt.Checked)
            item.setIcon(QIcon(I('plugins.png')))
        self.device_plugins.sortItems()
        self.device_plugins.blockSignals(False)
Example #25
0
    def accept(self):
        col = unicode(self.column_name_box.text()).strip()
        if not col:
            return self.simple_error('', _('No lookup name was provided'))
        if col.startswith('#'):
            col = col[1:]
        if re.match('^\w*$', col) is None or not col[0].isalpha() or col.lower() != col:
            return self.simple_error('', _('The lookup name must contain only '
                    'lower case letters, digits and underscores, and start with a letter'))
        if col.endswith('_index'):
            return self.simple_error('', _('Lookup names cannot end with _index, '
                    'because these names are reserved for the index of a series column.'))
        col_heading = unicode(self.column_heading_box.text()).strip()
        col_type = self.column_types[self.column_type_box.currentIndex()]['datatype']
        if col_type[0] == '*':
            col_type = col_type[1:]
            is_multiple = True
        else:
            is_multiple = False
        if not col_heading:
            return self.simple_error('', _('No column heading was provided'))

        db = self.parent.gui.library_view.model().db
        key = db.field_metadata.custom_field_prefix+col
        bad_col = False
        if key in self.parent.custcols:
            if not self.editing_col or \
                    self.parent.custcols[key]['colnum'] != self.orig_column_number:
                bad_col = True
        if bad_col:
            return self.simple_error('', _('The lookup name %s is already used')%col)

        bad_head = False
        for t in self.parent.custcols:
            if self.parent.custcols[t]['name'] == col_heading:
                if not self.editing_col or \
                        self.parent.custcols[t]['colnum'] != self.orig_column_number:
                    bad_head = True
        for t in self.standard_colheads:
            if self.standard_colheads[t] == col_heading:
                bad_head = True
        if bad_head:
            return self.simple_error('', _('The heading %s is already used')%col_heading)

        display_dict = {}

        if col_type == 'datetime':
            if unicode(self.date_format_box.text()).strip():
                display_dict = {'date_format':unicode(self.date_format_box.text()).strip()}
            else:
                display_dict = {'date_format': None}
        elif col_type == 'composite':
            if not unicode(self.composite_box.text()).strip():
                return self.simple_error('', _('You must enter a template for'
                    ' composite columns'))
            display_dict = {'composite_template':unicode(self.composite_box.text()).strip(),
                            'composite_sort': ['text', 'number', 'date', 'bool']
                                        [self.composite_sort_by.currentIndex()],
                            'make_category': self.composite_make_category.isChecked(),
                            'contains_html': self.composite_contains_html.isChecked(),
                        }
        elif col_type == 'enumeration':
            if not unicode(self.enum_box.text()).strip():
                return self.simple_error('', _('You must enter at least one'
                    ' value for enumeration columns'))
            l = [v.strip() for v in unicode(self.enum_box.text()).split(',') if v.strip()]
            l_lower = [v.lower() for v in l]
            for i,v in enumerate(l_lower):
                if v in l_lower[i+1:]:
                    return self.simple_error('', _('The value "{0}" is in the '
                    'list more than once, perhaps with different case').format(l[i]))
            c = unicode(self.enum_colors.text())
            if c:
                c = [v.strip() for v in unicode(self.enum_colors.text()).split(',')]
            else:
                c = []
            if len(c) != 0 and len(c) != len(l):
                return self.simple_error('', _('The colors box must be empty or '
                'contain the same number of items as the value box'))
            for tc in c:
                if tc not in QColor.colorNames():
                    return self.simple_error('',
                            _('The color {0} is unknown').format(tc))

            display_dict = {'enum_values': l, 'enum_colors': c}
        elif col_type == 'text' and is_multiple:
            display_dict = {'is_names': self.is_names.isChecked()}
        elif col_type in ['int', 'float']:
            if unicode(self.number_format_box.text()).strip():
                display_dict = {'number_format':unicode(self.number_format_box.text()).strip()}
            else:
                display_dict = {'number_format': None}

        if col_type in ['text', 'composite', 'enumeration'] and not is_multiple:
            display_dict['use_decorations'] = self.use_decorations.checkState()

        if not self.editing_col:
            self.parent.custcols[key] = {
                    'label':col,
                    'name':col_heading,
                    'datatype':col_type,
                    'display':display_dict,
                    'normalized':None,
                    'colnum':None,
                    'is_multiple':is_multiple,
                }
            item = QListWidgetItem(col_heading, self.parent.opt_columns)
            item.setData(Qt.UserRole, QVariant(key))
            item.setFlags(Qt.ItemIsEnabled|Qt.ItemIsUserCheckable|Qt.ItemIsSelectable)
            item.setCheckState(Qt.Checked)
        else:
            idx = self.parent.opt_columns.currentRow()
            item = self.parent.opt_columns.item(idx)
            item.setText(col_heading)
            self.parent.custcols[self.orig_column_name]['label'] = col
            self.parent.custcols[self.orig_column_name]['name'] = col_heading
            self.parent.custcols[self.orig_column_name]['display'].update(display_dict)
            self.parent.custcols[self.orig_column_name]['*edited'] = True
            self.parent.custcols[self.orig_column_name]['*must_restart'] = True
        QDialog.accept(self)
Example #26
0
 def create_item(self, alias, key, checked=False):
     i = QListWidgetItem(alias, self.recipients)
     i.setFlags(Qt.ItemIsEnabled | Qt.ItemIsUserCheckable)
     i.setCheckState(Qt.Checked if checked else Qt.Unchecked)
     i.setData(Qt.UserRole, key)
     self.items.append(i)
Example #27
0
    def __init__(self, settings, all_formats, supports_subdirs,
        must_read_metadata, supports_use_author_sort,
        extra_customization_message, device, extra_customization_choices=None):

        QWidget.__init__(self)
        Ui_ConfigWidget.__init__(self)
        self.setupUi(self)

        self.settings = settings

        all_formats = set(all_formats)
        self.calibre_known_formats = device.FORMATS
        try:
            self.device_name = device.get_gui_name()
        except TypeError:
            self.device_name = getattr(device, 'gui_name', None) or _('Device')
        if device.USER_CAN_ADD_NEW_FORMATS:
            all_formats = set(all_formats) | set(BOOK_EXTENSIONS)

        format_map = settings.format_map
        disabled_formats = list(set(all_formats).difference(format_map))
        for format in format_map + list(sorted(disabled_formats)):
            item = QListWidgetItem(format, self.columns)
            item.setData(Qt.UserRole, QVariant(format))
            item.setFlags(Qt.ItemIsEnabled|Qt.ItemIsUserCheckable|Qt.ItemIsSelectable)
            item.setCheckState(Qt.Checked if format in format_map else Qt.Unchecked)

        self.column_up.clicked.connect(self.up_column)
        self.column_down.clicked.connect(self.down_column)

        if device.HIDE_FORMATS_CONFIG_BOX:
            self.groupBox.hide()

        if supports_subdirs:
            self.opt_use_subdirs.setChecked(self.settings.use_subdirs)
        else:
            self.opt_use_subdirs.hide()
        if not must_read_metadata:
            self.opt_read_metadata.setChecked(self.settings.read_metadata)
        else:
            self.opt_read_metadata.hide()
        if supports_use_author_sort:
            self.opt_use_author_sort.setChecked(self.settings.use_author_sort)
        else:
            self.opt_use_author_sort.hide()
        if extra_customization_message:
            extra_customization_choices = extra_customization_choices or {}
            def parse_msg(m):
                msg, _, tt = m.partition(':::') if m else ('', '', '')
                return msg.strip(), textwrap.fill(tt.strip(), 100)

            if isinstance(extra_customization_message, list):
                self.opt_extra_customization = []
                if len(extra_customization_message) > 6:
                    row_func = lambda x, y: ((x/2) * 2) + y
                    col_func = lambda x: x%2
                else:
                    row_func = lambda x, y: x*2 + y
                    col_func = lambda x: 0

                for i, m in enumerate(extra_customization_message):
                    label_text, tt = parse_msg(m)
                    if not label_text:
                        self.opt_extra_customization.append(None)
                        continue
                    if isinstance(settings.extra_customization[i], bool):
                        self.opt_extra_customization.append(QCheckBox(label_text))
                        self.opt_extra_customization[-1].setToolTip(tt)
                        self.opt_extra_customization[i].setChecked(bool(settings.extra_customization[i]))
                    elif i in extra_customization_choices:
                        cb = QComboBox(self)
                        self.opt_extra_customization.append(cb)
                        l = QLabel(label_text)
                        l.setToolTip(tt), cb.setToolTip(tt), l.setBuddy(cb), cb.setToolTip(tt)
                        for li in sorted(extra_customization_choices[i]):
                            self.opt_extra_customization[i].addItem(li)
                        cb.setCurrentIndex(max(0, cb.findText(settings.extra_customization[i])))
                    else:
                        self.opt_extra_customization.append(QLineEdit(self))
                        l = QLabel(label_text)
                        l.setToolTip(tt)
                        self.opt_extra_customization[i].setToolTip(tt)
                        l.setBuddy(self.opt_extra_customization[i])
                        l.setWordWrap(True)
                        self.opt_extra_customization[i].setText(settings.extra_customization[i])
                        self.opt_extra_customization[i].setCursorPosition(0)
                        self.extra_layout.addWidget(l, row_func(i, 0), col_func(i))
                    self.extra_layout.addWidget(self.opt_extra_customization[i],
                                                row_func(i, 1), col_func(i))
            else:
                self.opt_extra_customization = QLineEdit()
                label_text, tt = parse_msg(extra_customization_message)
                l = QLabel(label_text)
                l.setToolTip(tt)
                l.setBuddy(self.opt_extra_customization)
                l.setWordWrap(True)
                if settings.extra_customization:
                    self.opt_extra_customization.setText(settings.extra_customization)
                    self.opt_extra_customization.setCursorPosition(0)
                self.opt_extra_customization.setCursorPosition(0)
                self.extra_layout.addWidget(l, 0, 0)
                self.extra_layout.addWidget(self.opt_extra_customization, 1, 0)
        self.opt_save_template.setText(settings.save_template)
Example #28
0
    def accept(self):
        col = unicode(self.column_name_box.text()).strip()
        if not col:
            return self.simple_error('', _('No lookup name was provided'))
        if col.startswith('#'):
            col = col[1:]
        if re.match('^\w*$',
                    col) is None or not col[0].isalpha() or col.lower() != col:
            return self.simple_error(
                '',
                _('The lookup name must contain only '
                  'lower case letters, digits and underscores, and start with a letter'
                  ))
        if col.endswith('_index'):
            return self.simple_error(
                '',
                _('Lookup names cannot end with _index, '
                  'because these names are reserved for the index of a series column.'
                  ))
        col_heading = unicode(self.column_heading_box.text()).strip()
        col_type = self.column_types[
            self.column_type_box.currentIndex()]['datatype']
        if col_type[0] == '*':
            col_type = col_type[1:]
            is_multiple = True
        else:
            is_multiple = False
        if not col_heading:
            return self.simple_error('', _('No column heading was provided'))

        db = self.parent.gui.library_view.model().db
        key = db.field_metadata.custom_field_prefix + col
        bad_col = False
        if key in self.parent.custcols:
            if not self.editing_col or \
                    self.parent.custcols[key]['colnum'] != self.orig_column_number:
                bad_col = True
        if bad_col:
            return self.simple_error(
                '',
                _('The lookup name %s is already used') % col)

        bad_head = False
        for t in self.parent.custcols:
            if self.parent.custcols[t]['name'] == col_heading:
                if not self.editing_col or \
                        self.parent.custcols[t]['colnum'] != self.orig_column_number:
                    bad_head = True
        for t in self.standard_colheads:
            if self.standard_colheads[t] == col_heading:
                bad_head = True
        if bad_head:
            return self.simple_error(
                '',
                _('The heading %s is already used') % col_heading)

        display_dict = {}

        if col_type == 'datetime':
            if unicode(self.date_format_box.text()).strip():
                display_dict = {
                    'date_format':
                    unicode(self.date_format_box.text()).strip()
                }
            else:
                display_dict = {'date_format': None}
        elif col_type == 'composite':
            if not unicode(self.composite_box.text()).strip():
                return self.simple_error(
                    '', _('You must enter a template for'
                          ' composite columns'))
            display_dict = {
                'composite_template':
                unicode(self.composite_box.text()).strip(),
                'composite_sort':
                ['text', 'number', 'date',
                 'bool'][self.composite_sort_by.currentIndex()],
                'make_category':
                self.composite_make_category.isChecked(),
                'contains_html':
                self.composite_contains_html.isChecked(),
            }
        elif col_type == 'enumeration':
            if not unicode(self.enum_box.text()).strip():
                return self.simple_error(
                    '',
                    _('You must enter at least one'
                      ' value for enumeration columns'))
            l = [
                v.strip() for v in unicode(self.enum_box.text()).split(',')
                if v.strip()
            ]
            l_lower = [v.lower() for v in l]
            for i, v in enumerate(l_lower):
                if v in l_lower[i + 1:]:
                    return self.simple_error(
                        '',
                        _('The value "{0}" is in the '
                          'list more than once, perhaps with different case').
                        format(l[i]))
            c = unicode(self.enum_colors.text())
            if c:
                c = [
                    v.strip()
                    for v in unicode(self.enum_colors.text()).split(',')
                ]
            else:
                c = []
            if len(c) != 0 and len(c) != len(l):
                return self.simple_error(
                    '',
                    _('The colors box must be empty or '
                      'contain the same number of items as the value box'))
            for tc in c:
                if tc not in QColor.colorNames():
                    return self.simple_error(
                        '',
                        _('The color {0} is unknown').format(tc))

            display_dict = {'enum_values': l, 'enum_colors': c}
        elif col_type == 'text' and is_multiple:
            display_dict = {'is_names': self.is_names.isChecked()}
        elif col_type in ['int', 'float']:
            if unicode(self.number_format_box.text()).strip():
                display_dict = {
                    'number_format':
                    unicode(self.number_format_box.text()).strip()
                }
            else:
                display_dict = {'number_format': None}

        if col_type in ['text', 'composite', 'enumeration'
                        ] and not is_multiple:
            display_dict['use_decorations'] = self.use_decorations.checkState()

        if not self.editing_col:
            self.parent.custcols[key] = {
                'label': col,
                'name': col_heading,
                'datatype': col_type,
                'display': display_dict,
                'normalized': None,
                'colnum': None,
                'is_multiple': is_multiple,
            }
            item = QListWidgetItem(col_heading, self.parent.opt_columns)
            item.setData(Qt.UserRole, QVariant(key))
            item.setData(Qt.DecorationRole, QVariant(QIcon(I('column.png'))))
            item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsUserCheckable
                          | Qt.ItemIsSelectable)
            item.setCheckState(Qt.Checked)
        else:
            idx = self.parent.opt_columns.currentRow()
            item = self.parent.opt_columns.item(idx)
            item.setText(col_heading)
            self.parent.custcols[self.orig_column_name]['label'] = col
            self.parent.custcols[self.orig_column_name]['name'] = col_heading
            self.parent.custcols[self.orig_column_name]['display'].update(
                display_dict)
            self.parent.custcols[self.orig_column_name]['*edited'] = True
            self.parent.custcols[self.orig_column_name]['*must_restart'] = True
        QDialog.accept(self)
Example #29
0
 def create_item(self, alias, key, checked=False):
     i = QListWidgetItem(alias, self.recipients)
     i.setFlags(Qt.ItemIsEnabled | Qt.ItemIsUserCheckable)
     i.setCheckState(Qt.Checked if checked else Qt.Unchecked)
     i.setData(Qt.UserRole, key)
     self.items.append(i)
Example #30
0
    def accept(self):
        col = unicode(self.column_name_box.text()).strip()
        if not col:
            return self.simple_error("", _("No lookup name was provided"))
        if col.startswith("#"):
            col = col[1:]
        if re.match("^\w*$", col) is None or not col[0].isalpha() or col.lower() != col:
            return self.simple_error(
                "",
                _(
                    "The lookup name must contain only "
                    "lower case letters, digits and underscores, and start with a letter"
                ),
            )
        if col.endswith("_index"):
            return self.simple_error(
                "",
                _(
                    "Lookup names cannot end with _index, "
                    "because these names are reserved for the index of a series column."
                ),
            )
        col_heading = unicode(self.column_heading_box.text()).strip()
        col_type = self.column_types[self.column_type_box.currentIndex()]["datatype"]
        if col_type[0] == "*":
            col_type = col_type[1:]
            is_multiple = True
        else:
            is_multiple = False
        if not col_heading:
            return self.simple_error("", _("No column heading was provided"))

        db = self.parent.gui.library_view.model().db
        key = db.field_metadata.custom_field_prefix + col
        bad_col = False
        if key in self.parent.custcols:
            if not self.editing_col or self.parent.custcols[key]["colnum"] != self.orig_column_number:
                bad_col = True
        if bad_col:
            return self.simple_error("", _("The lookup name %s is already used") % col)

        bad_head = False
        for t in self.parent.custcols:
            if self.parent.custcols[t]["name"] == col_heading:
                if not self.editing_col or self.parent.custcols[t]["colnum"] != self.orig_column_number:
                    bad_head = True
        for t in self.standard_colheads:
            if self.standard_colheads[t] == col_heading:
                bad_head = True
        if bad_head:
            return self.simple_error("", _("The heading %s is already used") % col_heading)

        display_dict = {}

        if col_type == "datetime":
            if unicode(self.date_format_box.text()).strip():
                display_dict = {"date_format": unicode(self.date_format_box.text()).strip()}
            else:
                display_dict = {"date_format": None}
        elif col_type == "composite":
            if not unicode(self.composite_box.text()).strip():
                return self.simple_error("", _("You must enter a template for" " composite columns"))
            display_dict = {
                "composite_template": unicode(self.composite_box.text()).strip(),
                "composite_sort": ["text", "number", "date", "bool"][self.composite_sort_by.currentIndex()],
                "make_category": self.composite_make_category.isChecked(),
                "contains_html": self.composite_contains_html.isChecked(),
            }
        elif col_type == "enumeration":
            if not unicode(self.enum_box.text()).strip():
                return self.simple_error("", _("You must enter at least one" " value for enumeration columns"))
            l = [v.strip() for v in unicode(self.enum_box.text()).split(",") if v.strip()]
            l_lower = [v.lower() for v in l]
            for i, v in enumerate(l_lower):
                if v in l_lower[i + 1 :]:
                    return self.simple_error(
                        "",
                        _('The value "{0}" is in the ' "list more than once, perhaps with different case").format(l[i]),
                    )
            c = unicode(self.enum_colors.text())
            if c:
                c = [v.strip() for v in unicode(self.enum_colors.text()).split(",")]
            else:
                c = []
            if len(c) != 0 and len(c) != len(l):
                return self.simple_error(
                    "", _("The colors box must be empty or " "contain the same number of items as the value box")
                )
            for tc in c:
                if tc not in QColor.colorNames():
                    return self.simple_error("", _("The color {0} is unknown").format(tc))

            display_dict = {"enum_values": l, "enum_colors": c}
        elif col_type == "text" and is_multiple:
            display_dict = {"is_names": self.is_names.isChecked()}
        elif col_type in ["int", "float"]:
            if unicode(self.number_format_box.text()).strip():
                display_dict = {"number_format": unicode(self.number_format_box.text()).strip()}
            else:
                display_dict = {"number_format": None}

        if col_type in ["text", "composite", "enumeration"] and not is_multiple:
            display_dict["use_decorations"] = self.use_decorations.checkState()

        if not self.editing_col:
            self.parent.custcols[key] = {
                "label": col,
                "name": col_heading,
                "datatype": col_type,
                "display": display_dict,
                "normalized": None,
                "colnum": None,
                "is_multiple": is_multiple,
            }
            item = QListWidgetItem(col_heading, self.parent.opt_columns)
            item.setData(Qt.UserRole, QVariant(key))
            item.setData(Qt.DecorationRole, QVariant(QIcon(I("column.png"))))
            item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsUserCheckable | Qt.ItemIsSelectable)
            item.setCheckState(Qt.Checked)
        else:
            idx = self.parent.opt_columns.currentRow()
            item = self.parent.opt_columns.item(idx)
            item.setText(col_heading)
            self.parent.custcols[self.orig_column_name]["label"] = col
            self.parent.custcols[self.orig_column_name]["name"] = col_heading
            self.parent.custcols[self.orig_column_name]["display"].update(display_dict)
            self.parent.custcols[self.orig_column_name]["*edited"] = True
            self.parent.custcols[self.orig_column_name]["*must_restart"] = True
        QDialog.accept(self)