示例#1
0
    def show_pages(self):
        self.loading.setVisible(False)
        if self.error is not None:
            error_dialog(self, _('Failed to render'),
                _('Could not render this PDF file'), show=True)
            self.reject()
            return
        files = (glob(os.path.join(self.tdir, '*.jpg')) +
                 glob(os.path.join(self.tdir, '*.jpeg')))
        if not files:
            error_dialog(self, _('Failed to render'),
                _('This PDF has no pages'), show=True)
            self.reject()
            return

        try:
            dpr = self.devicePixelRatioF()
        except AttributeError:
            dpr = self.devicePixelRatio()

        for i, f in enumerate(sorted(files)):
            p = QPixmap(f).scaled(self.covers.iconSize()*dpr, aspectRatioMode=Qt.IgnoreAspectRatio, transformMode=Qt.SmoothTransformation)
            p.setDevicePixelRatio(dpr)
            i = QListWidgetItem(_('page %d') % (i + 1))
            i.setData(Qt.DecorationRole, p)
            i.setData(Qt.UserRole, f)
            self.covers.addItem(i)
示例#2
0
 def resources(self, resources):
     self.items.clear()
     self.original_resources = resources
     for url in resources:
         i = QListWidgetItem(url, self.items)
         i.setCheckState(Qt.Checked)
         i.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)
示例#3
0
    def show_pages(self):
        if self.error is not None:
            error_dialog(self, _('Failed to render'),
                _('Could not render this PDF file'), show=True, det_msg=self.error)
            self.reject()
            return
        self.stack.stop()
        files = glob(os.path.join(self.current_tdir, '*.jpg')) + glob(os.path.join(self.current_tdir, '*.jpeg'))
        if not files and not self.covers.count():
            error_dialog(self, _('Failed to render'),
                _('This PDF has no pages'), show=True)
            self.reject()
            return

        try:
            dpr = self.devicePixelRatioF()
        except AttributeError:
            dpr = self.devicePixelRatio()

        for i, f in enumerate(sorted(files)):
            p = QPixmap(f).scaled(self.covers.iconSize()*dpr, aspectRatioMode=Qt.IgnoreAspectRatio, transformMode=Qt.SmoothTransformation)
            p.setDevicePixelRatio(dpr)
            i = QListWidgetItem(_('page %d') % (self.first + i))
            i.setData(Qt.DecorationRole, p)
            i.setData(Qt.UserRole, f)
            self.covers.addItem(i)
        self.first += len(files)
        if len(files) == PAGES_PER_RENDER:
            self.more_pages.setVisible(True)
示例#4
0
 def refill_all_boxes(self):
     if self.refilling:
         return
     self.refilling = True
     self.current_device = None
     self.current_format = None
     self.clear_fields(new_boxes=True)
     self.edit_format.clear()
     self.edit_format.addItem('')
     for format_ in self.current_plugboards:
         self.edit_format.addItem(format_)
     self.edit_format.setCurrentIndex(0)
     self.edit_device.clear()
     self.ok_button.setEnabled(False)
     self.del_button.setEnabled(False)
     self.existing_plugboards.clear()
     for f in self.formats:
         if f not in self.current_plugboards:
             continue
         for d in self.devices:
             if d not in self.current_plugboards[f]:
                 continue
             ops = []
             for op in self.current_plugboards[f][d]:
                 ops.append('([' + op[0] + '] -> ' + op[1] + ')')
             txt = '%s:%s = %s\n'%(f, d, ', '.join(ops))
             item = QListWidgetItem(txt)
             item.setData(Qt.UserRole, (f, d))
             self.existing_plugboards.addItem(item)
     self.refilling = False
示例#5
0
    def search(self):

        text = self.search_space.text()
        print(text)
        self.listWidget.clear()
        self.listWidget.setFocus()
        try:
            url = "https://bookbrainz.org/ws/search/?q=\"" + text + "\"&mode=\"search\""
            hits = request_get(url)['hits']
        except:
            return
        numQueries = len(hits)
        act = 0
        for i in range(numQueries):
            enttype = hits[i]['_source']['_type']
            if not enttype in ['Publication', 'Work', 'Edition']:
                continue
            print(hits[i])
            item = QListWidgetItem("%i. %s BBID : %i" % ((act + 1), hits[i]['_source']['default_alias']['name'], 1))
            Qcol = QColor()
            if i % 2 == 0:
                Qcol.setRed(240)
                Qcol.setGreen(255)
                Qcol.setBlue(255)
            else:
                Qcol.setRed(220)
                Qcol.setGreen(255)
                Qcol.setBlue(240)
            item.setBackground(QBrush(Qcol))
            self.listWidget.addItem(item)
            act += 1

        self.listWidget.setFocus()
        self.searchExecutionButton.setFocus()
示例#6
0
    def add_builtin_recipe(self):
        from calibre.web.feeds.recipes.collection import \
            get_builtin_recipe_collection, get_builtin_recipe_by_id
        from PyQt5.Qt import QDialog, QVBoxLayout, QListWidgetItem, \
                QListWidget, QDialogButtonBox, QSize

        d = QDialog(self)
        d.l = QVBoxLayout()
        d.setLayout(d.l)
        d.list = QListWidget(d)
        d.list.doubleClicked.connect(lambda x: d.accept())
        d.l.addWidget(d.list)
        d.bb = QDialogButtonBox(QDialogButtonBox.Ok|QDialogButtonBox.Cancel,
                Qt.Horizontal, d)
        d.bb.accepted.connect(d.accept)
        d.bb.rejected.connect(d.reject)
        d.l.addWidget(d.bb)
        d.setWindowTitle(_('Choose builtin recipe'))
        items = []
        for r in get_builtin_recipe_collection():
            id_ = r.get('id', '')
            title = r.get('title', '')
            lang = r.get('language', '')
            if id_ and title:
                items.append((title + ' [%s]'%lang, id_))

        items.sort(key=lambda x:sort_key(x[0]))
        for title, id_ in items:
            item = QListWidgetItem(title)
            item.setData(Qt.UserRole, id_)
            d.list.addItem(item)

        d.resize(QSize(450, 400))
        ret = d.exec_()
        d.list.doubleClicked.disconnect()
        if ret != d.Accepted:
            return

        items = list(d.list.selectedItems())
        if not items:
            return
        item = items[-1]
        id_ = unicode(item.data(Qt.UserRole) or '')
        title = unicode(item.data(Qt.DisplayRole) or '').rpartition(' [')[0]
        profile = get_builtin_recipe_by_id(id_, download_recipe=True)
        if profile is None:
            raise Exception('Something weird happened')

        if self._model.has_title(title):
            if question_dialog(self, _('Replace recipe?'),
                _('A custom recipe named %s already exists. Do you want to '
                    'replace it?')%title):
                self._model.replace_by_title(title, profile)
            else:
                return
        else:
            self.model.add(title, profile)

        self.clear()
示例#7
0
 def entry_to_item(entry, parent):
     icon_path = entry.get('Icon') or I('blank.png')
     ans = QListWidgetItem(QIcon(icon_path), entry.get('Name') or _('Unknown'), parent)
     ans.setData(ENTRY_ROLE, entry)
     comment = (entry.get('Comment') or '')
     if comment:
         comment += '\n'
     ans.setToolTip(comment + _('Command line:') + '\n' + (' '.join(entry['Exec'])))
示例#8
0
 def create_item(self, data):
     x = data
     i = QListWidgetItem(
         QIcon(QPixmap(x["path"]).scaled(256, 256, transformMode=Qt.SmoothTransformation)), x["name"], self.images
     )
     i.setData(Qt.UserRole, x["fname"])
     i.setData(Qt.UserRole + 1, x["path"])
     return i
示例#9
0
 def to_item(key, ac, parent):
     ic = ac.icon()
     if not ic or ic.isNull():
         ic = blank
     ans = QListWidgetItem(ic, unicode(ac.text()).replace('&', ''), parent)
     ans.setData(Qt.UserRole, key)
     ans.setToolTip(ac.toolTip())
     return ans
示例#10
0
 def addRoyaume (self,royaume_id):
     self.model.database.setVerbose(True)
     kingdom_sqlite = self.model.database.select("*", "gm_kingdom",False,"IDKingdom=="+str(royaume_id))
     while (kingdom_sqlite.next()):
         text = str(kingdom_sqlite.value("IDKingdom"))+"->"+ str(kingdom_sqlite.value("Name"))
         item = QListWidgetItem(text)
         item.setCheckState(QtCore.Qt.Checked)
         self.list_modified_kingdom.addItem(item)
示例#11
0
 def addHeros (self,heros_id):
     self.model.database.setVerbose(True)
     warrior_sqlite = self.model.database.select("*", "gm_perso",False,"IDPerso=="+str(heros_id))
     while (warrior_sqlite.next()):
         text = str(warrior_sqlite.value("IDPerso"))+"->"+ str(warrior_sqlite.value("Name"))
         item = QListWidgetItem(text)
         item.setCheckState(QtCore.Qt.Checked)
         self.list_modified_heros.addItem(item)
示例#12
0
 def entry_to_item(entry, parent):
     icon = get_icon(entry.get('icon_file'), as_data=False)
     if icon is None:
         icon = entry_to_icon_text(entry)[0]
     else:
         icon = QPixmap.fromImage(icon)
     ans = QListWidgetItem(QIcon(icon), entry.get('name') or _('Unknown'), parent)
     ans.setData(ENTRY_ROLE, entry)
     ans.setToolTip(_('Application path:') + '\n' + entry['path'])
示例#13
0
 def resort(self):
     if self.sort_alphabetically.isChecked():
         sorted_locations = sorted(self.locations, key=lambda (name, loc): numeric_sort_key(name))
     else:
         sorted_locations = self.locations
     self.items.clear()
     for name, loc in sorted_locations:
         i = QListWidgetItem(name, self.items)
         i.setData(Qt.UserRole, loc)
     self.items.setCurrentRow(0)
示例#14
0
 def create_color_scheme(self):
     scheme = self.colors_map[self.current_colors].data(Qt.UserRole)
     d = CreateColorScheme('#' + _('My Color Scheme'), scheme, set(self.colors_map), parent=self)
     if d.exec_() == d.Accepted:
         name, scheme = d.data
         li = QListWidgetItem(name)
         li.setData(Qt.UserRole, scheme), li.setFlags(li.flags() | Qt.ItemIsUserCheckable), li.setCheckState(Qt.Checked)
         self.insert_scheme(name, li)
         self.emit_changed()
         self.original_prefs['color_themes'] = self.current_prefs['color_themes']
示例#15
0
 def update(self):
     scrollToBottom = False;
     while self.messageQueue.empty()!=True:
         message = self.messageQueue.get()
         listItem = QListWidgetItem()
         listItem.setText(message)
         self.messageList.addItem(listItem)
         scrollToBottom = True;
         
     if scrollToBottom:
         self.messageList.scrollToBottom()
示例#16
0
 def updateWarriorList (self):
     row = 0
     self.item = []
     #self.tableWidget.clear()
     self.list_filtered.clear()
     for warrior in self.model.filteredWarriors() :
         item = QListWidgetItem (str(warrior.name))
         item.setData(5,warrior)
         self.list_filtered.addItem(item)
         if warrior.selected == True:
             item.setSelected(True)
    def __init__(self, parent, user):
        if user.username == "root":
            icon = "root"
            name = _("Super User")
        else:
            name = user.username
            icon = "normal"

        label = "%s (%s)" % (name, user.realname)
        QListWidgetItem.__init__(self, QIcon(":/gui/pics/user_%s.png" % icon), label, parent)
        self.user = user
示例#18
0
 def entry_to_item(entry, parent):
     try:
         icon = load_icon_resource(entry.get('icon_resource'))
     except Exception:
         icon = None
         import traceback
         traceback.print_exc()
     if not icon:
         icon = entry_to_icon_text(entry)[0]
     ans = QListWidgetItem(QIcon(icon), entry.get('name') or _('Unknown'), parent)
     ans.setData(ENTRY_ROLE, entry)
     ans.setToolTip(_('Command line:') + '\n' + entry['cmdline'])
示例#19
0
 def re_sort(self):
     self.themes.sort(key=lambda x:sort_key(x.get('title', '')))
     field = self.sort_on
     if field == 'number':
         self.themes.sort(key=lambda x:x.get('number', 0), reverse=True)
     elif field == 'usage':
         self.themes.sort(key=lambda x:self.usage.get(x.get('name'), 0), reverse=True)
     self.theme_list.clear()
     for theme in self.themes:
         i = QListWidgetItem(theme.get('title', '') + ' %s %s' % (theme.get('number'), self.usage.get(theme.get('name'))), self.theme_list)
         i.setData(Qt.UserRole, theme)
         if 'cover-pixmap' in theme:
             i.setData(Qt.DecorationRole, theme['cover-pixmap'])
示例#20
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({'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, (format))
         item.setFlags(Qt.ItemIsEnabled|Qt.ItemIsSelectable)
示例#21
0
    def __init__(self, parent, get_option, get_help, db=None, book_id=None):
        Widget.__init__(self, parent, OPTIONS['input']['txt'])
        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)
示例#22
0
文件: check.py 项目: MarioJC/calibre
    def run_checks(self, container):
        with BusyCursor():
            self.show_busy()
            QApplication.processEvents()
            errors = run_checks(container)
            self.hide_busy()

        for err in sorted(errors, key=lambda e:(100 - e.level, e.name)):
            i = QListWidgetItem('%s\xa0\xa0\xa0\xa0[%s]' % (err.msg, err.name), self.items)
            i.setData(Qt.UserRole, err)
            i.setIcon(icon_for_level(err.level))
        if errors:
            self.items.setCurrentRow(0)
            self.current_item_changed()
            self.items.setFocus(Qt.OtherFocusReason)
        else:
            self.clear_help()
示例#23
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)
示例#24
0
 def change_builtin(self):
     d = QDialog(self)
     lw = QListWidget(d)
     for (trigger, syntaxes), snip in iteritems(builtin_snippets):
         snip = copy.deepcopy(snip)
         snip['trigger'], snip['syntaxes'] = trigger, syntaxes
         i = QListWidgetItem(self.snip_to_text(snip), lw)
         i.setData(Qt.UserRole, snip)
     d.l = l = QVBoxLayout(d)
     l.addWidget(QLabel(_('Choose the built-in snippet to modify:')))
     l.addWidget(lw)
     lw.itemDoubleClicked.connect(d.accept)
     d.bb = bb = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
     l.addWidget(bb)
     bb.accepted.connect(d.accept), bb.rejected.connect(d.reject)
     if d.exec_() == d.Accepted and lw.currentItem() is not None:
         self.stack.setCurrentIndex(1)
         self.edit_snip.apply_snip(lw.currentItem().data(Qt.UserRole), creating_snippet=True)
示例#25
0
    def customize_recipe(self):
        d = QDialog(self)
        d.l = QVBoxLayout()
        d.setLayout(d.l)
        d.list = QListWidget(d)
        d.list.doubleClicked.connect(lambda x: d.accept())
        d.l.addWidget(d.list)
        d.bb = QDialogButtonBox(QDialogButtonBox.Ok|QDialogButtonBox.Cancel,
                Qt.Horizontal, d)
        d.bb.accepted.connect(d.accept)
        d.bb.rejected.connect(d.reject)
        d.l.addWidget(d.bb)
        d.setWindowTitle(_('Choose builtin recipe'))
        items = []
        for r in get_builtin_recipe_collection():
            id_ = r.get('id', '')
            title = r.get('title', '')
            lang = r.get('language', '')
            if id_ and title:
                items.append((title + ' [%s]'%lang, id_))

        items.sort(key=lambda x:sort_key(x[0]))
        for title, id_ in items:
            item = QListWidgetItem(title)
            item.setData(Qt.UserRole, id_)
            d.list.addItem(item)

        d.resize(QSize(450, 400))
        ret = d.exec_()
        d.list.doubleClicked.disconnect()
        if ret != d.Accepted:
            return

        items = list(d.list.selectedItems())
        if not items:
            return
        item = items[-1]
        id_ = unicode(item.data(Qt.UserRole) or '')
        title = unicode(item.data(Qt.DisplayRole) or '').rpartition(' [')[0]
        src = get_builtin_recipe_by_id(id_, download_recipe=True)
        if src is None:
            raise Exception('Something weird happened')

        self.edit_recipe(None, src)
示例#26
0
    def show_pages(self):
        self.loading.setVisible(False)
        if self.error is not None:
            error_dialog(self, _('Failed to render'),
                _('Could not render this PDF file'), show=True)
            self.reject()
            return
        files = (glob(os.path.join(self.tdir, '*.jpg')) +
                 glob(os.path.join(self.tdir, '*.jpeg')))
        if not files:
            error_dialog(self, _('Failed to render'),
                _('This PDF has no pages'), show=True)
            self.reject()
            return

        for f in sorted(files):
            i = QListWidgetItem(QIcon(f), '')
            i.setData(Qt.UserRole, f)
            self.covers.addItem(i)
示例#27
0
 def data(self, role):
     if role == Qt.DisplayRole:
         if self.initial_value != self.current_value:
             return _('%(curr)s (was %(initial)s)')%dict(
                     curr=self.current_value, initial=self.initial_value)
         else:
             return self.current_value
     elif role == Qt.EditRole:
         return self.current_value
     else:
         return QListWidgetItem.data(self, role)
示例#28
0
    def setup_ui(self):
        from calibre.ebooks.oeb.polish.images import get_compressible_images
        self.setWindowIcon(QIcon(I('compress-image.png')))
        self.h = h = QHBoxLayout(self)
        self.images = i = QListWidget(self)
        h.addWidget(i)
        self.l = l = QVBoxLayout()
        h.addLayout(l)
        c = current_container()
        for name in sorted(get_compressible_images(c), key=numeric_sort_key):
            x = QListWidgetItem(name, i)
            x.setData(Qt.UserRole, c.filesize(name))
        i.setSelectionMode(i.ExtendedSelection)
        i.setMinimumHeight(500), i.setMinimumWidth(350)
        i.selectAll(), i.setSpacing(5)
        self.delegate = ImageItemDelegate(self)
        i.setItemDelegate(self.delegate)
        self.la = la = QLabel(_(
            'You can compress the images in this book losslessly, reducing the file size of the book,'
            ' without affecting image quality. Typically image size is reduced by 5 - 15%.'))
        la.setWordWrap(True)
        la.setMinimumWidth(250)
        l.addWidget(la), l.addSpacing(30)

        self.enable_lossy = el = QCheckBox(_('Enable &lossy compression of JPEG images'))
        el.setToolTip(_('This allows you to change the quality factor used for JPEG images.\nBy lowering'
                        ' the quality you can greatly reduce file size, at the expense of the image looking blurred.'))
        l.addWidget(el)
        self.h2 = h = QHBoxLayout()
        l.addLayout(h)
        self.jq = jq = QSpinBox(self)
        jq.setMinimum(0), jq.setMaximum(100), jq.setValue(tprefs.get('jpeg_compression_quality_for_lossless_compression', 80)), jq.setEnabled(False)
        jq.setToolTip(_('The compression quality, 1 is high compression, 100 is low compression.\nImage'
                        ' quality is inversely correlated with compression quality.'))
        jq.valueChanged.connect(self.save_compression_quality)
        el.toggled.connect(jq.setEnabled)
        self.jql = la = QLabel(_('Compression &quality:'))
        la.setBuddy(jq)
        h.addWidget(la), h.addWidget(jq)
        l.addStretch(10)
        l.addWidget(self.bb)
示例#29
0
    def link_stylesheets(self, names):
        s = self.categories["styles"]
        sheets = [unicode(s.child(i).data(0, NAME_ROLE) or "") 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())
示例#30
0
 def refill_all_boxes(self):
     if self.refilling:
         return
     self.refilling = True
     self.current_device = None
     self.current_format = None
     self.clear_fields(new_boxes=True)
     self.edit_format.clear()
     self.edit_format.addItem("")
     for format_ in self.current_plugboards:
         self.edit_format.addItem(format_)
     self.edit_format.setCurrentIndex(0)
     self.edit_device.clear()
     self.ok_button.setEnabled(False)
     self.del_button.setEnabled(False)
     self.existing_plugboards.clear()
     for f in self.formats:
         if f not in self.current_plugboards:
             continue
         for d in sorted(self.devices + self.disabled_devices, key=lambda x: x.lower()):
             if d not in self.current_plugboards[f]:
                 continue
             ops = []
             for op in self.current_plugboards[f][d]:
                 ops.append("([" + op[0] + "] -> " + op[1] + ")")
             txt = "%s:%s = %s\n" % (f, d, ", ".join(ops))
             item = QListWidgetItem(txt)
             item.setData(Qt.UserRole, (f, d))
             if d in self.disabled_devices:
                 item.setFlags(item.flags() & ~Qt.ItemIsEnabled)
             self.existing_plugboards.addItem(item)
     self.refilling = False
示例#31
0
 def fset(self, wl):
     self.dictionary_list.clear()
     for langcode, url in sorted(wl.iteritems(), key=lambda (lc, url):sort_key(calibre_langcode_to_name(lc))):
         i = QListWidgetItem('%s: %s' % (calibre_langcode_to_name(langcode), url), self.dictionary_list)
         i.setData(Qt.UserRole, (langcode, url))
示例#32
0
    def advanceSim(self, line):
        # Strip any new line or white space off the end of the line.
        packet = line.rstrip()
        if (self.packet_counter % 10 == 0):
            #print(packet)
            self.console.addItem(QListWidgetItem(packet))

        # # Print all of the flight information in an easy to read format
        # counter = 1
        # for field in lines.split(',') :
        #   if (counter == 1) :
        #     if (field == '@') :
        #       print('Flight event: none reached')
        #     elif (field == 'A') :
        #       print('Flight event: escape enabled')
        #     elif (field == 'B') :
        #       print('Flight event: escape commanded')
        #     elif (field == 'C') :
        #       print('Flight event: liftoff')
        #     elif (field == 'D') :
        #       print('Flight event: meco')
        #     elif (field == 'E') :
        #       print('Flight event: separation')
        #     elif (field == 'F') :
        #       print('Flight event: coast start')
        #     elif (field == 'G') :
        #       print('Flight event: apogee')
        #     elif (field == 'H') :
        #       print('Flight event: coast end')
        #     elif (field == 'I') :
        #       print('Flight event: drogue chutes')
        #     elif (field == 'J') :
        #       print('Flight event: main chutes')
        #     elif (field == 'K') :
        #       print('Flight event: touchdown')
        #     elif (field == 'L') :
        #       print('Flight event: safing')
        #     elif (field == 'M') :
        #       print('Flight event: mission end')
        #     else :
        #       print('Flight event: unknown')
        #   elif (counter == 2) :
        #     print ('Experiment time: ' + field + ' sec')
        #   elif (counter == 3) :
        #     print ('Altitude: ' + field + ' ft')
        #   elif (counter == 4):
        #     print ('GPS altitude: ' + field + ' ft')
        #   elif (counter == 5):
        #     print ('Velocity:')
        #     print ('   Up: ' + field + ' ft/sec')
        #   elif (counter == 6):
        #     print ('   East: ' + field + ' ft/sec')
        #   elif (counter == 7):
        #     print ('   North: ' + field + ' ft/sec')
        #   elif (counter == 8):
        #     print ('Acceleration:')
        #     print ('   magnitude: ' + field + ' ft/sec^2')
        #   elif (counter == 9):
        #     print ('   x-axis: ' + field + ' ft/sec^2')
        #   elif (counter == 10):
        #     print ('   y-axis: ' + field + ' ft/sec^2')
        #   elif (counter == 11):
        #     print ('   z-axis: ' + field + ' ft/sec^2')
        #   elif (counter == 12):
        #     print ('Attitude:')
        #     print ('   phi: ' + field + ' radians')
        #   elif (counter == 13):
        #     print ('   theta: ' + field + ' radians')
        #   elif (counter == 14):
        #     print ('   psi: ' + field + ' radians')
        #   elif (counter == 15):
        #     print ('Angular velocity:')
        #     print ('   x-axis: ' + field + ' radians/sec')
        #   elif (counter == 16):
        #     print ('   y-axis: ' + field + ' radians/sec')
        #   elif (counter == 17):
        #     print ('   z-axis: ' + field + ' radians/sec')
        #   elif (counter == 18):
        #     if (field == '1') :
        #       print ('Liftoff Imminent warning:       true')
        #     else :
        #       print ('Liftoff Imminent warning:       false')
        #   elif (counter == 19):
        #     if (field == '1') :
        #       print ('Drogue Chute Imminent warning:  true')
        #     else :
        #       print ('Drogue Chute Imminent warning:  false')
        #   elif (counter == 20):
        #     if (field == '1') :
        #       print ('Landing Imminent warning:       true')
        #     else :
        #       print ('Landing Imminent warning:       false')
        #   elif (counter == 21):
        #     if (field == '1') :
        #       print ('Chute Fault warning:            true')
        #     else :
        #       print ('Chute Fault warning:            false')

        #   counter += 1

        # display how far along simulation is
        self.ui.nff_sim_progress_bar.setValue(100 * self.packet_counter /
                                              self.num_lines)

        # Send the packet to each connected device.
        self.publish_socket.send_string(packet)

        # Increment the packet counter.
        self.packet_counter += 1

        # Delay is chosen to result in a send rate of roughly 10Hz, call isn't very precise at ms level.
        time.sleep(0.07)
示例#33
0
 def addItem(self, collection):
     item = QListWidgetItem(self.collectionList)
     item.setSizeHint(QSize(36, CLOSED_SIZE))
     self.collectionList.addItem(item)
     self.collectionList.setItemWidget(
         item, CollectionItem(self, collection, item))
示例#34
0
 def __init__(self, parent, connection, package):
     QListWidgetItem.__init__(self, QIcon(":/gui/pics/%s.png" % package),
                              connection, parent)
     self._connection = [connection, package]
示例#35
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)
示例#36
0
 def add_item(self, player_name):
     item = QListWidgetItem()
     item.setText(player_name)
     item.setIcon(self.get_icon('head.png'))
     self.addItem(item)
示例#37
0
文件: lookup.py 项目: zyhong/calibre
 def add_entry(self, entry, prepend=False):
     i = QListWidgetItem(entry['name'])
     i.setData(Qt.UserRole, entry.copy())
     self.entries.insertItem(0, i) if prepend else self.entries.addItem(i)
示例#38
0
 def snip_to_item(self, snip):
     i = QListWidgetItem(self.snip_to_text(snip), self.snip_list)
     i.setData(Qt.UserRole, copy.deepcopy(snip))
     return i
示例#39
0
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        self.l = l = QGridLayout(self)

        def add_row(*args):
            r = l.rowCount()
            if len(args) == 1:
                l.addWidget(args[0], r, 0, 1, 2)
            else:
                la = QLabel(args[0])
                l.addWidget(la, r, 0,
                            Qt.AlignRight), l.addWidget(args[1], r, 1)
                la.setBuddy(args[1])

        self.heading = la = QLabel('<h2>\xa0')
        add_row(la)
        self.helpl = la = QLabel(
            _('For help with snippets, see the <a href="%s">User Manual</a>') %
            localize_user_manual_link(
                'http://manual.calibre-ebook.com/snippets.html'))
        la.setOpenExternalLinks(True)
        add_row(la)

        self.name = n = QLineEdit(self)
        n.setPlaceholderText(_('The name of this snippet'))
        add_row(_('&Name:'), n)

        self.trig = t = QLineEdit(self)
        t.setPlaceholderText(_('The text used to trigger this snippet'))
        add_row(_('Tri&gger:'), t)

        self.template = t = QPlainTextEdit(self)
        la.setBuddy(t)
        add_row(_('&Template:'), t)

        self.types = t = QListWidget(self)
        t.setFlow(t.LeftToRight)
        t.setWrapping(True), t.setResizeMode(t.Adjust), t.setSpacing(5)
        fm = t.fontMetrics()
        t.setMaximumHeight(2 * (fm.ascent() + fm.descent()) + 25)
        add_row(_('&File types:'), t)
        t.setToolTip(_('Which file types this snippet should be active in'))

        self.frame = f = QFrame(self)
        f.setFrameShape(f.HLine)
        add_row(f)
        self.test = d = SnippetTextEdit('', self)
        d.snippet_manager.snip_func = self.snip_func
        d.setToolTip(_('You can test your snippet here'))
        d.setMaximumHeight(t.maximumHeight() + 15)
        add_row(_('T&est:'), d)

        i = QListWidgetItem(_('All'), t)
        i.setData(Qt.UserRole, '*')
        i.setCheckState(Qt.Checked)
        i.setFlags(i.flags() | Qt.ItemIsUserCheckable)
        for ftype in sorted(all_text_syntaxes):
            i = QListWidgetItem(ftype, t)
            i.setData(Qt.UserRole, ftype)
            i.setCheckState(Qt.Checked)
            i.setFlags(i.flags() | Qt.ItemIsUserCheckable)

        self.creating_snippet = False
示例#40
0
 def add_result(self, result):
     i = QListWidgetItem(' ', self)
     i.setData(Qt.UserRole, result)
     return self.count()
示例#41
0
 def setText(self, txt):
     self.current_value = txt
     QListWidgetItem.setText(txt)
示例#42
0
 def setData(self, role, data):
     if role == Qt.EditRole:
         self.previous_value = self.current_value
         self.current_value = data
     QListWidgetItem.setData(self, role, data)
示例#43
0
 def __init__(self, txt):
     QListWidgetItem.__init__(self, txt)
     self.initial_value = txt
     self.current_value = txt
     self.previous_value = txt
示例#44
0
 def __init__(self, player, parent=None):
     global path
     QListWidgetItem.__init__(self, parent)
     self.setText(player)
     self.setIcon(QIcon(path + "head.png"))
示例#45
0
 def __init__(self, rule, parent):
     QListWidgetItem.__init__(self, '', parent)
     st = self.text_from_rule(rule, parent)
     self.setData(RENDER_ROLE, st)
     self.setData(DATA_ROLE, rule)
示例#46
0
 def create_item(self, data):
     x = data
     i = QListWidgetItem(QIcon(x['path']), x['name'], self.images)
     i.setData(Qt.UserRole, x['fname'])
     i.setData(Qt.UserRole + 1, x['path'])
     return i
示例#47
0
    def __init__(self, gui, initial_panel=None):
        QDialog.__init__(self, gui)
        self.l = l = QGridLayout(self)
        self.setLayout(l)
        self.setWindowTitle(_('Preferences for Edit book'))
        self.setWindowIcon(QIcon(I('config.png')))

        self.stacks = QStackedWidget(self)
        l.addWidget(self.stacks, 0, 1, 1, 1)

        self.categories_list = cl = QListWidget(self)
        cl.currentRowChanged.connect(self.stacks.setCurrentIndex)
        cl.clearPropertyFlags()
        cl.setViewMode(cl.IconMode)
        cl.setFlow(cl.TopToBottom)
        cl.setMovement(cl.Static)
        cl.setWrapping(False)
        cl.setSpacing(15)
        if get_lang()[:2] not in ('zh', 'ja'):
            cl.setWordWrap(True)
        l.addWidget(cl, 0, 0, 1, 1)

        self.bb = bb = QDialogButtonBox(QDialogButtonBox.Ok
                                        | QDialogButtonBox.Cancel)
        bb.accepted.connect(self.accept)
        bb.rejected.connect(self.reject)
        self.rdb = b = bb.addButton(_('Restore all &defaults'), bb.ResetRole)
        b.setToolTip(_('Restore defaults for all preferences'))
        b.clicked.connect(self.restore_all_defaults)
        self.rcdb = b = bb.addButton(_('Restore &current defaults'),
                                     bb.ResetRole)
        b.setToolTip(_('Restore defaults for currently displayed preferences'))
        b.clicked.connect(self.restore_current_defaults)
        self.rconfs = b = bb.addButton(_('Restore c&onfirmations'),
                                       bb.ResetRole)
        b.setToolTip(_('Restore all disabled confirmation prompts'))
        b.clicked.connect(self.restore_confirmations)

        l.addWidget(bb, 1, 0, 1, 2)

        self.resize(800, 600)
        geom = tprefs.get('preferences_geom', None)
        if geom is not None:
            QApplication.instance().safe_restore_geometry(self, geom)

        self.keyboard_panel = ShortcutConfig(self)
        self.keyboard_panel.initialize(gui.keyboard)
        self.editor_panel = EditorSettings(self)
        self.integration_panel = IntegrationSettings(self)
        self.main_window_panel = MainWindowSettings(self)
        self.preview_panel = PreviewSettings(self)
        self.toolbars_panel = ToolbarSettings(self)

        for name, icon, panel in [
            (_('Main window'), 'page.png', 'main_window'),
            (_('Editor settings'), 'modified.png', 'editor'),
            (_('Preview settings'), 'viewer.png', 'preview'),
            (_('Keyboard shortcuts'), 'keyboard-prefs.png', 'keyboard'),
            (_('Toolbars'), 'wizard.png', 'toolbars'),
            (_('Integration with calibre'), 'lt.png', 'integration'),
        ]:
            i = QListWidgetItem(QIcon(I(icon)), name, cl)
            i.setToolTip(name)
            cl.addItem(i)
            self.stacks.addWidget(getattr(self, panel + '_panel'))

        cl.setCurrentRow(0)
        cl.item(0).setSelected(True)
        w, h = cl.sizeHintForColumn(0), 0
        for i in range(cl.count()):
            h = cl.sizeHintForRow(i)
            cl.item(i).setSizeHint(QSize(w, h))

        cl.setMaximumWidth(cl.sizeHintForColumn(0) + 35)
        cl.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        cl.setMinimumWidth(min(cl.maximumWidth(), cl.sizeHint().width()))
示例#48
0
    def __init__(self, settings, all_formats, supports_subdirs,
        supports_non_english_characters,
        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, (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 supports_non_english_characters:
            self.opt_asciiize.setChecked(self.settings.asciiize)
        else:
            self.opt_asciiize.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)
示例#49
0
 def add_account(self):
     i = QListWidgetItem('', self.accounts)
     i.setData(Qt.UserRole, {})
     self.accounts.setCurrentItem(i)
示例#50
0
 def make_list_widget(self, item):
     n = item.name if item.exists else item.name + _(' (not on any book)')
     w = QListWidgetItem(item.icon, n)
     w.setData(Qt.UserRole, item.index)
     w.setToolTip(_('Category lookup name: ') + item.label)
     return w
示例#51
0
    def set_bookmarks(self, bookmarks=()):
        csb = self.current_sort_by
        if csb == 'name':
            sk = lambda x: sort_key(x['title'])
        elif csb == 'timestamp':
            sk = itemgetter('timestamp')
        else:
            from calibre.ebooks.epub.cfi.parse import cfi_sort_key
            defval = cfi_sort_key('/99999999')

            def pos_key(b):
                if b.get('pos_type') == 'epubcfi':
                    return cfi_sort_key(b['pos'], only_path=False)
                return defval

            sk = pos_key

        bookmarks = sorted(bookmarks, key=sk)
        current_bookmark_id = self.current_bookmark_id
        self.bookmarks_list.clear()
        for bm in bookmarks:
            i = QListWidgetItem(bm['title'])
            i.setData(Qt.ToolTipRole, bm['title'])
            i.setData(Qt.UserRole, self.bm_to_item(bm))
            i.setFlags(i.flags() | Qt.ItemIsEditable)
            self.bookmarks_list.addItem(i)
            if bm.get('removed'):
                i.setHidden(True)
        for i in range(self.bookmarks_list.count()):
            item = self.bookmarks_list.item(i)
            if not item.isHidden():
                self.bookmarks_list.setCurrentItem(
                    item, QItemSelectionModel.ClearAndSelect)
                break
        if current_bookmark_id is not None:
            self.current_bookmark_id = current_bookmark_id
示例#52
0
文件: config.py 项目: zwlistu/calibre
 def word_lookups(self, wl):
     self.dictionary_list.clear()
     for langcode, url in sorted(iteritems(wl), key=lambda lc_url:sort_key(calibre_langcode_to_name(lc_url[0]))):
         i = QListWidgetItem('%s: %s' % (calibre_langcode_to_name(langcode), url), self.dictionary_list)
         i.setData(Qt.UserRole, (langcode, url))
示例#53
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() and not re.match(
                        "#(?:[0-9a-f]{3}){1,4}", tc, re.I):
                    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()
        display_dict['description'] = self.description_box.text().strip()

        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, (key))
            item.setData(Qt.DecorationRole, (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)
 def _populate_list(self, list_widget, list_names, set_selected=True):
     list_widget.clear()
     for list_name in list_names:
         item = QListWidgetItem(list_name, list_widget)
         list_widget.addItem(item)
         item.setSelected(set_selected)
示例#55
0
 def book_converted(self, book_id, fmt):
     fmt = fmt.upper()
     if fmt not in self._formats:
         self._formats.append(fmt)
         self.formats.addItem(QListWidgetItem(
             file_icon_provider().icon_from_ext(fmt.lower()), fmt.upper()))
示例#56
0
 def __init__(self, text, user_data=None):
     QListWidgetItem.__init__(self, text)
     self.user_data = user_data
示例#57
0
    def __init__(self, plugin):
        QWidget.__init__(self)

        self.plugin = plugin

        self.layout = QVBoxLayout()
        self.setLayout(self.layout)

        self.engine_location_label = QLabel('ElasticSearch engine location:')
        self.layout.addWidget(self.engine_location_label)

        self.elasticsearch_url_textbox = QLineEdit(self)
        self.elasticsearch_url_textbox.setText(prefs['elasticsearch_url'])
        self.layout.addWidget(self.elasticsearch_url_textbox)
        self.engine_location_label.setBuddy(self.elasticsearch_url_textbox)

        self.layout.addSpacing(10)

        self.pdftotext_path_label = QLabel('Path to pdftotext tool:')
        self.layout.addWidget(self.pdftotext_path_label)

        self.pdftotext_path_textbox = QLineEdit(self)
        self.pdftotext_path_textbox.setText(prefs['pdftotext_path'])
        self.layout.addWidget(self.pdftotext_path_textbox)
        self.pdftotext_path_label.setBuddy(self.pdftotext_path_textbox)

        self.layout.addSpacing(10)

        self.concurrency_label = QLabel(
            'Number of parallel processes for text extraction:')
        self.layout.addWidget(self.concurrency_label)

        self.concurrency_textbox = QLineEdit(self)
        self.concurrency_textbox.setText(str(prefs['concurrency']))
        self.layout.addWidget(self.concurrency_textbox)
        self.concurrency_label.setBuddy(self.concurrency_textbox)

        self.layout.addSpacing(10)

        self.formats_label = QLabel('Index book formats:')
        self.layout.addWidget(self.formats_label)

        file_formats = prefs['file_formats'].split(',')

        self.formats_list = QListWidget(self)
        for fmt in SUPPORTED_FORMATS:
            item = QListWidgetItem(fmt)
            item.setFlags(item.flags() | Qt.ItemIsUserCheckable)
            item.setCheckState(Qt.Checked if fmt in
                               file_formats else Qt.Unchecked)
            self.formats_list.addItem(item)
        self.layout.addWidget(self.formats_list)
        self.formats_label.setBuddy(self.formats_list)

        self.layout.addSpacing(10)

        self.autoindex_checkbox = QCheckBox(
            "Automatically index new books on search", self)
        self.autoindex_checkbox.setCheckState(
            Qt.Checked if prefs['autoindex'] else Qt.Unchecked)
        self.layout.addWidget(self.autoindex_checkbox)

        self.layout.addSpacing(10)

        self.privacy_label = QLabel('Privacy:')
        self.layout.addWidget(self.privacy_label)

        self.clear_search_history_button = QPushButton('Clear search &history',
                                                       self)
        self.clear_search_history_button.clicked.connect(self.on_clear_history)
        self.layout.addWidget(self.clear_search_history_button)

        self.clear_search_index_buttin = QPushButton('Clear search &index',
                                                     self)
        self.clear_search_index_buttin.clicked.connect(self.on_clear_index)
        self.layout.addWidget(self.clear_search_index_buttin)
示例#58
0
 def load(self, highlights):
     self.clear()
     for h in highlights or ():
         i = QListWidgetItem(h['highlighted_text'], self)
         i.setData(Qt.UserRole, h)
示例#59
0
文件: email.py 项目: tokot/calibre
 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)
示例#60
0
    def _refresh(self, book_id, key):
        '''
        Actually fill in the left-hand panel from the information in the
        selected column of the selected book
        '''
        # Only show items for categories
        if not self.is_category(key):
            if self.current_key is None:
                self.indicate_no_items()
                return
            key = self.current_key
        label_text = _('&Item: {0} ({1})')
        if self.is_pane:
            label_text = label_text.replace('&', '')

        self.items.blockSignals(True)
        self.items.clear()
        self.books_table.setRowCount(0)

        mi = self.db.get_metadata(book_id,
                                  index_is_id=True,
                                  get_user_categories=False)
        vals = mi.get(key, None)

        try:
            # Check if we are in the GridView and there are no values for the
            # selected column. In this case switch the column to 'authors'
            # because there isn't an easy way to switch columns in GridView
            # when the QV box is empty.
            if not vals:
                is_grid_view = (
                    self.gui.current_view().alternate_views.current_view !=
                    self.gui.current_view().alternate_views.main_view)
                if is_grid_view:
                    key = 'authors'
                    vals = mi.get(key, None)
        except:
            traceback.print_exc()

        self.current_book_id = book_id
        self.current_key = key
        self.items_label.setText(label_text.format(self.fm[key]['name'], key))

        if vals:
            self.no_valid_items = False
            if self.fm[key]['datatype'] == 'rating':
                if self.fm[key]['display'].get('allow_half_stars', False):
                    vals = unicode_type(vals / 2.0)
                else:
                    vals = unicode_type(vals // 2)
            if not isinstance(vals, list):
                vals = [vals]
            vals.sort(key=sort_key)

            for v in vals:
                a = QListWidgetItem(v)
                a.setToolTip(
                    '<p>' +
                    _('Click to show only books with this item. '
                      'Double click to search for this item in the Tag browser'
                      ) + '</p>')
                self.items.addItem(a)
            self.items.setCurrentRow(0)

            self.fill_in_books_box(vals[0])
        else:
            self.indicate_no_items()
        self.items.blockSignals(False)