예제 #1
0
    def test_folder_operations(self):
        ''' Test the creation of folders, duplicate folders and sub folders '''
        self.check_setup()

        # Create a folder
        name = 'zzz-test-folder'
        folder = self.dev.create_folder(self.storage, name)
        self.cleanup.append(folder)
        self.assertTrue(folder.is_folder)
        self.assertEqual(folder.parent_id, self.storage.object_id)
        self.assertEqual(folder.storage_id, self.storage.object_id)
        self.assertEqual(lower(name), lower(folder.name))

        # Create a sub-folder
        name = 'sub-folder'
        subfolder = self.dev.create_folder(folder, name)
        self.assertTrue(subfolder.is_folder)
        self.assertEqual(subfolder.parent_id, folder.object_id)
        self.assertEqual(subfolder.storage_id, self.storage.object_id)
        self.assertEqual(lower(name), lower(subfolder.name))
        self.cleanup.append(subfolder)

        # Check that creating an existing folder returns that folder (case
        # insensitively)
        self.assertIs(subfolder, self.dev.create_folder(folder,
            'SUB-FOLDER'),
            msg='Creating an existing folder did not return the existing folder')

        # Check that creating folders as children of files is not allowed
        root_file = [f for f in self.dev.filesystem_cache.entries[0].files if
                not f.is_folder]
        if root_file:
            with self.assertRaises(ValueError):
                self.dev.create_folder(root_file[0], 'sub-folder')
예제 #2
0
파일: test.py 프로젝트: yeyanchao/calibre
    def test_folder_operations(self):
        ''' Test the creation of folders, duplicate folders and sub folders '''
        self.check_setup()

        # Create a folder
        name = 'zzz-test-folder'
        folder = self.dev.create_folder(self.storage, name)
        self.cleanup.append(folder)
        self.assertTrue(folder.is_folder)
        self.assertEqual(folder.parent_id, self.storage.object_id)
        self.assertEqual(folder.storage_id, self.storage.object_id)
        self.assertEqual(lower(name), lower(folder.name))

        # Create a sub-folder
        name = 'sub-folder'
        subfolder = self.dev.create_folder(folder, name)
        self.assertTrue(subfolder.is_folder)
        self.assertEqual(subfolder.parent_id, folder.object_id)
        self.assertEqual(subfolder.storage_id, self.storage.object_id)
        self.assertEqual(lower(name), lower(subfolder.name))
        self.cleanup.append(subfolder)

        # Check that creating an existing folder returns that folder (case
        # insensitively)
        self.assertIs(subfolder, self.dev.create_folder(folder,
            'SUB-FOLDER'),
            msg='Creating an existing folder did not return the existing folder')

        # Check that creating folders as children of files is not allowed
        root_file = [f for f in self.dev.filesystem_cache.entries[0].files if
                not f.is_folder]
        if root_file:
            with self.assertRaises(ValueError):
                self.dev.create_folder(root_file[0], 'sub-folder')
예제 #3
0
 def ismatch(title):
     title = lower(title)
     match = not title_tokens
     for t in title_tokens:
         if lower(t) in title:
             match = True
             break
     return match
예제 #4
0
 def ismatch(title):
     title = lower(title)
     match = not title_tokens
     for t in title_tokens:
         if lower(t) in title:
             match = True
             break
     return match
예제 #5
0
 def ismatch(authors):
     authors = lower(' '.join(authors))
     amatch = not self.match_authors
     for a in self.match_authors:
         if lower(a) in authors:
             amatch = True
             break
     if not self.match_authors: amatch = True
     return amatch
예제 #6
0
파일: jobs.py 프로젝트: 089git/calibre
 def get_matches(self, location, query, candidates=None):
     if candidates is None:
         candidates = self.universal_set()
     ans = set()
     if not query:
         return ans
     query = lower(query)
     for j in candidates:
         job = self.jobs[j]
         if job.description and query in lower(job.description):
             ans.add(j)
     return ans
예제 #7
0
파일: jobs.py 프로젝트: ziyuyouming/calibre
 def get_matches(self, location, query, candidates=None):
     if candidates is None:
         candidates = self.universal_set()
     ans = set()
     if not query:
         return ans
     query = lower(query)
     for j in candidates:
         job = self.jobs[j]
         if job.description and query in lower(job.description):
             ans.add(j)
     return ans
예제 #8
0
파일: coloring.py 프로젝트: rakyi/calibre
 def get_filenames_from_box(self):
     if self.doing_multiple:
         model = self.filename_box.model()
         fnames = []
         for i in range(1, model.rowCount()):
             item = model.item(i, 0)
             if item.checkState() == Qt.Checked:
                 fnames.append(lower(unicode(item.text())))
         fname = ' : '.join(fnames)
     else:
         fname = lower(unicode(self.filename_box.currentText()))
     return fname
예제 #9
0
파일: coloring.py 프로젝트: tletnes/calibre
 def get_filenames_from_box(self):
     if self.doing_multiple:
         model = self.filename_box.model()
         fnames = []
         for i in range(1, model.rowCount()):
             item = model.item(i, 0)
             if item.checkState() == Qt.Checked:
                 fnames.append(lower(unicode_type(item.text())))
         fname = ' : '.join(fnames)
     else:
         fname = lower(unicode_type(self.filename_box.currentText()))
     return fname
예제 #10
0
파일: tweaks.py 프로젝트: rakyi/calibre
 def get_matches(self, location, query, candidates=None):
     if candidates is None:
         candidates = self.universal_set()
     ans = set()
     if not query:
         return ans
     query = lower(query)
     for r in candidates:
         dat = self.data(self.index(r), Qt.UserRole)
         var_names = u' '.join(dat.default_values)
         if query in lower(dat.name) or query in lower(var_names):
             ans.add(r)
     return ans
예제 #11
0
 def get_matches(self, location, query, candidates=None):
     if candidates is None:
         candidates = self.universal_set()
     ans = set()
     if not query:
         return ans
     query = lower(query)
     for r in candidates:
         dat = self.data(self.index(r), Qt.UserRole)
         var_names = u' '.join(dat.default_values)
         if query in lower(dat.name) or query in lower(var_names):
             ans.add(r)
     return ans
 def ismatch(title, authors):
     authors = lower(' '.join(authors))
     title = lower(title)
     match = not title_tokens
     for t in title_tokens:
         if lower(t) in title:
             match = True
             break
     amatch = not author_tokens
     for a in author_tokens:
         if lower(a) in authors:
             amatch = True
             break
     if not author_tokens: amatch = True
     return match and amatch
예제 #13
0
 def ismatch(title, authors):
     authors = lower(' '.join(authors))
     title = lower(title)
     match = not title_tokens
     for t in title_tokens:
         if lower(t) in title:
             match = True
             break
     amatch = not author_tokens
     for a in author_tokens:
         if lower(a) in authors:
             amatch = True
             break
     if not author_tokens: amatch = True
     return match and amatch
예제 #14
0
파일: base.py 프로젝트: yeyanchao/calibre
def cap_author_token(token):
    lt = lower(token)
    if lt in ("von", "de", "el", "van", "le"):
        return lt
    # no digits no spez. characters
    if re.match(r"([^\d\W]\.){2,}$", lt, re.UNICODE) is not None:
        # Normalize tokens of the form J.K. to J. K.
        parts = token.split(".")
        return ". ".join(map(capitalize, parts)).strip()
    scots_name = None
    for x in ("mc", "mac"):
        if (
            token.lower().startswith(x)
            and len(token) > len(x)
            and (token[len(x)] == upper(token[len(x)]) or lt == token)
        ):
            scots_name = len(x)
            break
    ans = capitalize(token)
    if scots_name is not None:
        ans = ans[:scots_name] + upper(ans[scots_name]) + ans[scots_name + 1 :]
    for x in ("-", "'"):
        idx = ans.find(x)
        if idx > -1 and len(ans) > idx + 2:
            ans = ans[: idx + 1] + upper(ans[idx + 1]) + ans[idx + 2 :]
    return ans
예제 #15
0
def ret_clean_text(log, dbg_lvl, text, swap=False, who=''):
    # for noosfere search to work smoothly, authors and title needs to be cleaned
    # we need to remove non significant characters and remove useless space character
    #
    debug = dbg_lvl & 4
    if debug:
        log.info("\nIn ret_clean_txt(self, log, text, swap =", swap, ")")
        log.info("text         : ", text)

    # Calibre per default presents the author as "Firstname Lastname", cleaned to be become "firstname lastname"
    # Noosfere present the author as "LASTNAME Firstname", let's get "Firstname LASTNAME" cleaned to "firstname lastname"
    #
    for k in [',', '.', '-', "'", '"', '(',
              ')']:  # yes I found a name with '(' and ')' in it...
        if k in text:
            text = text.replace(k, " ")
    text = " ".join(text.split())

    if swap:
        if debug:
            log.info("swap name and surname")
        nom = prenom = ""
        for i in range(len(text.split())):
            if (len(text.split()[i]) == 1) or (not text.split()[i].isupper()):
                prenom += " " + text.split()[i]
            else:
                nom += " " + text.split()[i]
        text = prenom + " " + nom
        if debug: log.info("text         : ", text)

    if debug:
        log.info("cleaned text : ", text)
        log.info("return text from ret_clean_txt")

    return lower(get_udc().decode(text))
예제 #16
0
def cap_author_token(token):
    lt = lower(token)
    if lt in ('von', 'de', 'el', 'van', 'le'):
        return lt
    # no digits no spez. characters
    if re.match(r'([^\d\W]\.){2,}$', lt, re.UNICODE) is not None:
        # Normalize tokens of the form J.K. to J. K.
        parts = token.split('.')
        return '. '.join(map(capitalize, parts)).strip()
    scots_name = None
    for x in ('mc', 'mac'):
        if (token.lower().startswith(x) and len(token) > len(x) and
                (
                    token[len(x)] == upper(token[len(x)]) or
                    lt == token
                )):
            scots_name = len(x)
            break
    ans = capitalize(token)
    if scots_name is not None:
        ans = ans[:scots_name] + upper(ans[scots_name]) + ans[scots_name+1:]
    for x in ('-', "'"):
        idx = ans.find(x)
        if idx > -1 and len(ans) > idx+2:
            ans = ans[:idx+1] + upper(ans[idx+1]) + ans[idx+2:]
    return ans
예제 #17
0
파일: base.py 프로젝트: Polyfun/calibre
def cap_author_token(token):
    lt = lower(token)
    if lt in ('von', 'de', 'el', 'van', 'le'):
        return lt
    # no digits no spez. characters
    if re.match(r'([^\d\W]\.){2,}$', lt, re.UNICODE) is not None:
        # Normalize tokens of the form J.K. to J. K.
        parts = token.split('.')
        return '. '.join(map(capitalize, parts)).strip()
    scots_name = None
    for x in ('mc', 'mac'):
        if (token.lower().startswith(x) and len(token) > len(x) and
                (
                    token[len(x)] == upper(token[len(x)]) or
                    lt == token
                )):
            scots_name = len(x)
            break
    ans = capitalize(token)
    if scots_name is not None:
        ans = ans[:scots_name] + upper(ans[scots_name]) + ans[scots_name+1:]
    for x in ('-', "'"):
        idx = ans.find(x)
        if idx > -1 and len(ans) > idx+2:
            ans = ans[:idx+1] + upper(ans[idx+1]) + ans[idx+2:]
    return ans
예제 #18
0
 def lang_codes(self):
     vals = self.vals
     ans = []
     for name in vals:
         if name:
             code = self._rmap.get(lower(name), None)
             if code is not None:
                 ans.append(code)
     return ans
예제 #19
0
파일: coloring.py 프로젝트: rakyi/calibre
 def populate_icon_filenames(self):
     d = self.icon_folder
     self.icon_file_names = []
     if os.path.exists(d):
         for icon_file in os.listdir(d):
             icon_file = lower(icon_file)
             if os.path.exists(os.path.join(d, icon_file)) and icon_file.endswith('.png'):
                 self.icon_file_names.append(icon_file)
     self.icon_file_names.sort(key=sort_key)
예제 #20
0
파일: languages.py 프로젝트: tokot/calibre
 def fget(self):
     vals = self.vals
     ans = []
     for name in vals:
         if name:
             code = self._rmap.get(lower(name), None)
             if code is not None:
                 ans.append(code)
     return ans
예제 #21
0
파일: languages.py 프로젝트: tokot/calibre
 def validate(self):
     vals = self.vals
     bad = []
     for name in vals:
         if name:
             code = self._rmap.get(lower(name), None)
             if code is None:
                 bad.append(name)
     return bad
예제 #22
0
 def accept(self):
     if self.rule_kind != 'color':
         fname = lower(unicode(self.filename_box.currentText()))
         if not fname:
             error_dialog(self, _('No icon selected'),
                     _('You must choose an icon for this rule'), show=True)
             return
     if self.validate():
         QDialog.accept(self)
예제 #23
0
파일: coloring.py 프로젝트: tletnes/calibre
 def populate_icon_filenames(self):
     d = self.icon_folder
     self.icon_file_names = []
     if os.path.exists(d):
         for icon_file in os.listdir(d):
             icon_file = lower(icon_file)
             if os.path.exists(os.path.join(d, icon_file)) and icon_file.endswith('.png'):
                 self.icon_file_names.append(icon_file)
     self.icon_file_names.sort(key=sort_key)
예제 #24
0
 def validate(self):
     vals = self.vals
     bad = []
     for name in vals:
         if name:
             code = self._rmap.get(lower(name), None)
             if code is None:
                 bad.append(name)
     return bad
예제 #25
0
 def get_matches(self, location, query, candidates=None):
     if candidates is None:
         candidates = self.universal_set()
     ans = set()
     if not query:
         return ans
     query = lower(query)
     for c, p in candidates:
         if p < 0:
             if query in lower(self.data[c].data):
                 ans.add((c, p))
         else:
             try:
                 sc = self.data[c].children[p].data
             except:
                 continue
             if query in lower(sc['name']):
                 ans.add((c, p))
     return ans
예제 #26
0
 def get_matches(self, location, query, candidates=None):
     if candidates is None:
         candidates = self.universal_set()
     ans = set([])
     if not query:
         return ans
     query = lower(query)
     for c, p in candidates:
         if p < 0:
             if query in lower(self.data[c].data):
                 ans.add((c, p))
         else:
             try:
                 sc = self.data[c].children[p].data
             except:
                 continue
             if query in lower(sc['name']):
                 ans.add((c, p))
     return ans
예제 #27
0
파일: plugins.py 프로젝트: hashken/calibre
 def get_matches(self, location, query, candidates=None):
     if candidates is None:
         candidates = self.universal_set()
     ans = set([])
     if not query:
         return ans
     query = lower(query)
     for c, p in candidates:
         if p < 0:
             if query in lower(self.categories[c]):
                 ans.add((c, p))
             continue
         else:
             try:
                 plugin = self._data[self.categories[c]][p]
             except:
                 continue
         if query in lower(plugin.name) or query in lower(plugin.author) or query in lower(plugin.description):
             ans.add((c, p))
     return ans
예제 #28
0
파일: languages.py 프로젝트: 089git/calibre
    def __init__(self, parent=None, db=None):
        EditWithComplete.__init__(self, parent)

        self.setSizeAdjustPolicy(self.AdjustToMinimumContentsLengthWithIcon)
        self.setMinimumContentsLength(20)
        self._lang_map = lang_map()
        self.names_with_commas = [x for x in self._lang_map.itervalues() if ',' in x]
        self.comma_map = {k:k.replace(',', '|') for k in self.names_with_commas}
        self.comma_rmap = {v:k for k, v in self.comma_map.iteritems()}
        self._rmap = {lower(v):k for k,v in self._lang_map.iteritems()}
        self.init_langs(db)
예제 #29
0
 def accept(self):
     if self.rule_kind != 'color':
         fname = lower(unicode(self.filename_box.currentText()))
         if not fname:
             error_dialog(self,
                          _('No icon selected'),
                          _('You must choose an icon for this rule'),
                          show=True)
             return
     if self.validate():
         QDialog.accept(self)
예제 #30
0
 def get_matches(self, location, query, candidates=None):
     if candidates is None:
         candidates = self.universal_set()
     ans = set([])
     if not query:
         return ans
     query = lower(query)
     for c, p in candidates:
         if p < 0:
             if query in lower(self.categories[c]):
                 ans.add((c, p))
             continue
         else:
             try:
                 plugin = self._data[self.categories[c]][p]
             except:
                 continue
         if query in lower(plugin.name) or query in lower(plugin.author) or \
                 query in lower(plugin.description):
             ans.add((c, p))
     return ans
예제 #31
0
    def test_change_case(self):
        ' Test the various ways of changing the case '
        from calibre.utils.titlecase import titlecase
        # Test corner cases
        self.ae('A', icu.upper(b'a'))

        for x in ('a', 'Alice\'s code', 'macdonald\'s machIne', '02 the wars'):
            self.ae(icu.upper(x), x.upper())
            self.ae(icu.lower(x), x.lower())
            # ICU's title case algorithm is different from ours, when there are
            # capitals inside words
            self.ae(icu.title_case(x), titlecase(x).replace('machIne', 'Machine'))
            self.ae(icu.capitalize(x), x[0].upper() + x[1:].lower())
예제 #32
0
    def __init__(self, parent=None, db=None, prefs=None):
        self.prefs = prefs or gui_prefs()
        self.refresh_recently_used()
        EditWithComplete.__init__(self, parent, sort_func=self.sort_language_items_key)

        self.setSizeAdjustPolicy(self.AdjustToMinimumContentsLengthWithIcon)
        self.setMinimumContentsLength(20)
        self._lang_map = lang_map_for_ui()
        self.names_with_commas = [x for x in itervalues(self._lang_map) if ',' in x]
        self.comma_map = {k:k.replace(',', '|') for k in self.names_with_commas}
        self.comma_rmap = {v:k for k, v in iteritems(self.comma_map)}
        self._rmap = {lower(v):k for k,v in iteritems(self._lang_map)}
        self.init_langs(db)
        self.item_selected.connect(self.update_recently_used)
예제 #33
0
    def __init__(self, parent=None, db=None, prefs=None):
        self.prefs = prefs or gui_prefs()
        self.refresh_recently_used()
        EditWithComplete.__init__(self, parent, sort_func=self.sort_language_items_key)

        self.setSizeAdjustPolicy(self.AdjustToMinimumContentsLengthWithIcon)
        self.setMinimumContentsLength(20)
        self._lang_map = lang_map_for_ui()
        self.names_with_commas = [x for x in self._lang_map.itervalues() if ',' in x]
        self.comma_map = {k:k.replace(',', '|') for k in self.names_with_commas}
        self.comma_rmap = {v:k for k, v in self.comma_map.iteritems()}
        self._rmap = {lower(v):k for k,v in self._lang_map.iteritems()}
        self.init_langs(db)
        self.item_selected.connect(self.update_recently_used)
예제 #34
0
    def test_change_case(self):
        ' Test the various ways of changing the case '
        from calibre.utils.titlecase import titlecase
        # Test corner cases
        self.ae('A', icu.upper(b'a'))
        for x in ('', None, False, 1):
            self.ae(x, icu.capitalize(x))

        for x in ('a', 'Alice\'s code', 'macdonald\'s machIne', '02 the wars'):
            self.ae(icu.upper(x), x.upper())
            self.ae(icu.lower(x), x.lower())
            # ICU's title case algorithm is different from ours, when there are
            # capitals inside words
            self.ae(icu.title_case(x), titlecase(x).replace('machIne', 'Machine'))
            self.ae(icu.capitalize(x), x[0].upper() + x[1:].lower())
예제 #35
0
    def test_change_case(self):
        " Test the various ways of changing the case "
        from calibre.utils.titlecase import titlecase

        # Test corner cases
        self.ae("A", icu.upper(b"a"))
        for x in ("", None, False, 1):
            self.ae(x, icu.capitalize(x))

        for x in ("a", "Alice's code", "macdonald's machIne", "02 the wars"):
            self.ae(icu.upper(x), x.upper())
            self.ae(icu.lower(x), x.lower())
            # ICU's title case algorithm is different from ours, when there are
            # capitals inside words
            self.ae(icu.title_case(x), titlecase(x).replace("machIne", "Machine"))
            self.ae(icu.capitalize(x), x[0].upper() + x[1:].lower())
예제 #36
0
파일: languages.py 프로젝트: tokot/calibre
    def __init__(self, parent=None, db=None):
        EditWithComplete.__init__(self, parent)

        self.setSizeAdjustPolicy(self.AdjustToMinimumContentsLengthWithIcon)
        self.setMinimumContentsLength(20)
        self._lang_map = lang_map()
        self.names_with_commas = [
            x for x in self._lang_map.itervalues() if ',' in x
        ]
        self.comma_map = {
            k: k.replace(',', '|')
            for k in self.names_with_commas
        }
        self.comma_rmap = {v: k for k, v in self.comma_map.iteritems()}
        self._rmap = {lower(v): k for k, v in self._lang_map.iteritems()}
        self.init_langs(db)
예제 #37
0
파일: coloring.py 프로젝트: tokot/calibre
 def filename_button_clicked(self):
     try:
         path = choose_files(self,
                             'choose_category_icon',
                             _('Select Icon'),
                             filters=[('Images',
                                       ['png', 'gif', 'jpg', 'jpeg'])],
                             all_files=False,
                             select_only_single_file=True)
         if path:
             icon_path = path[0]
             icon_name = lower(
                 sanitize_file_name_unicode(
                     os.path.splitext(os.path.basename(icon_path))[0] +
                     '.png'))
             if icon_name not in self.icon_file_names:
                 self.icon_file_names.append(icon_name)
                 self.update_filename_box()
                 self.update_remove_button()
                 try:
                     p = QIcon(icon_path).pixmap(QSize(128, 128))
                     d = self.icon_folder
                     if not os.path.exists(os.path.join(d, icon_name)):
                         if not os.path.exists(d):
                             os.makedirs(d)
                         with open(os.path.join(d, icon_name), 'wb') as f:
                             f.write(pixmap_to_data(p, format='PNG'))
                 except:
                     import traceback
                     traceback.print_exc()
             if self.doing_multiple:
                 if icon_name not in self.rule_icon_files:
                     self.rule_icon_files.append(icon_name)
                 self.update_icon_filenames_in_box()
             else:
                 self.filename_box.setCurrentIndex(
                     self.filename_box.findText(icon_name))
             self.filename_box.adjustSize()
     except:
         import traceback
         traceback.print_exc()
     return
예제 #38
0
파일: coloring.py 프로젝트: Ralnoc/calibre
 def filename_button_clicked(self):
     try:
         path = choose_files(self, 'choose_category_icon',
                     _('Select Icon'), filters=[
                     ('Images', ['png', 'gif', 'jpg', 'jpeg'])],
                 all_files=False, select_only_single_file=True)
         if path:
             icon_path = path[0]
             icon_name = lower(sanitize_file_name_unicode(
                          os.path.splitext(
                                os.path.basename(icon_path))[0]+'.png'))
             if icon_name not in self.icon_file_names:
                 self.icon_file_names.append(icon_name)
                 self.update_filename_box()
                 self.update_remove_button()
                 try:
                     p = QIcon(icon_path).pixmap(QSize(128, 128))
                     d = self.icon_folder
                     if not os.path.exists(os.path.join(d, icon_name)):
                         if not os.path.exists(d):
                             os.makedirs(d)
                         with open(os.path.join(d, icon_name), 'wb') as f:
                             f.write(pixmap_to_data(p, format='PNG'))
                 except:
                     import traceback
                     traceback.print_exc()
             if self.doing_multiple:
                 if icon_name not in self.rule_icon_files:
                     self.rule_icon_files.append(icon_name)
                 self.update_icon_filenames_in_box()
             else:
                 self.filename_box.setCurrentIndex(self.filename_box.findText(icon_name))
             self.filename_box.adjustSize()
     except:
         import traceback
         traceback.print_exc()
     return
예제 #39
0
    def __init__(self, fm, pref_name, parent=None):
        QDialog.__init__(self, parent)
        self.fm = fm

        if pref_name == 'column_color_rules':
            self.rule_kind = 'color'
            rule_text = _('coloring')
        else:
            self.rule_kind = 'icon'
            rule_text = _('icon')

        self.setWindowIcon(QIcon(I('format-fill-color.png')))
        self.setWindowTitle(
            _('Create/edit a column {0} rule').format(rule_text))

        self.l = l = QGridLayout(self)
        self.setLayout(l)

        self.l1 = l1 = QLabel(
            _('Create a column {0} rule by'
              ' filling in the boxes below'.format(rule_text)))
        l.addWidget(l1, 0, 0, 1, 8)

        self.f1 = QFrame(self)
        self.f1.setFrameShape(QFrame.HLine)
        l.addWidget(self.f1, 1, 0, 1, 8)

        self.l2 = l2 = QLabel(_('Set the'))
        l.addWidget(l2, 2, 0)

        if self.rule_kind == 'color':
            l.addWidget(QLabel(_('color')))
        else:
            self.kind_box = QComboBox(self)
            for tt, t in icon_rule_kinds:
                self.kind_box.addItem(tt, t)
            l.addWidget(self.kind_box, 2, 1)

        self.l3 = l3 = QLabel(_('of the column:'))
        l.addWidget(l3, 2, 2)

        self.column_box = QComboBox(self)
        l.addWidget(self.column_box, 2, 3)

        self.l4 = l4 = QLabel(_('to'))
        l.addWidget(l4, 2, 4)

        if self.rule_kind == 'color':
            self.color_box = QComboBox(self)
            self.color_label = QLabel('Sample text Sample text')
            self.color_label.setTextFormat(Qt.RichText)
            l.addWidget(self.color_box, 2, 5)
            l.addWidget(self.color_label, 2, 6)
            l.addItem(QSpacerItem(10, 10, QSizePolicy.Expanding), 2, 7)
        else:
            self.filename_box = QComboBox()
            self.filename_box.setInsertPolicy(
                self.filename_box.InsertAlphabetically)
            d = os.path.join(config_dir, 'cc_icons')
            self.icon_file_names = []
            if os.path.exists(d):
                for icon_file in os.listdir(d):
                    icon_file = lower(icon_file)
                    if os.path.exists(os.path.join(d, icon_file)):
                        if icon_file.endswith('.png'):
                            self.icon_file_names.append(icon_file)
            self.icon_file_names.sort(key=sort_key)
            self.update_filename_box()

            l.addWidget(self.filename_box, 2, 5)
            self.filename_button = QPushButton(QIcon(I('document_open.png')),
                                               _('&Add icon'))
            l.addWidget(self.filename_button, 2, 6)
            l.addWidget(QLabel(_('Icons should be square or landscape')), 2, 7)
            l.setColumnStretch(7, 10)

        self.l5 = l5 = QLabel(
            _('Only if the following conditions are all satisfied:'))
        l.addWidget(l5, 3, 0, 1, 7)

        self.scroll_area = sa = QScrollArea(self)
        sa.setMinimumHeight(300)
        sa.setMinimumWidth(950)
        sa.setWidgetResizable(True)
        l.addWidget(sa, 4, 0, 1, 8)

        self.add_button = b = QPushButton(QIcon(I('plus.png')),
                                          _('Add another condition'))
        l.addWidget(b, 5, 0, 1, 8)
        b.clicked.connect(self.add_blank_condition)

        self.l6 = l6 = QLabel(
            _('You can disable a condition by'
              ' blanking all of its boxes'))
        l.addWidget(l6, 6, 0, 1, 8)

        self.bb = bb = QDialogButtonBox(QDialogButtonBox.Ok
                                        | QDialogButtonBox.Cancel)
        bb.accepted.connect(self.accept)
        bb.rejected.connect(self.reject)
        l.addWidget(bb, 7, 0, 1, 8)

        self.conditions_widget = QWidget(self)
        sa.setWidget(self.conditions_widget)
        self.conditions_widget.setLayout(QVBoxLayout())
        self.conditions_widget.layout().setAlignment(Qt.AlignTop)
        self.conditions = []

        if self.rule_kind == 'color':
            for b in (self.column_box, self.color_box):
                b.setSizeAdjustPolicy(b.AdjustToMinimumContentsLengthWithIcon)
                b.setMinimumContentsLength(15)

        for key in sorted(displayable_columns(fm),
                          key=lambda (k): sort_key(fm[k]['name'])
                          if k != color_row_key else 0):
            if key == color_row_key and self.rule_kind != 'color':
                continue
            name = all_columns_string if key == color_row_key else fm[key][
                'name']
            if name:
                self.column_box.addItem(name, key)
        self.column_box.setCurrentIndex(0)

        if self.rule_kind == 'color':
            self.color_box.addItems(QColor.colorNames())
            self.color_box.setCurrentIndex(0)
            self.update_color_label()
            self.color_box.currentIndexChanged.connect(self.update_color_label)
        else:
            self.filename_button.clicked.connect(self.filename_button_clicked)

        self.resize(self.sizeHint())
예제 #40
0
파일: coloring.py 프로젝트: tletnes/calibre
 def sanitize_icon_file_name(self, icon_path):
     n = lower(sanitize_file_name_unicode(
                          os.path.splitext(
                                os.path.basename(icon_path))[0]+'.png'))
     return n.replace("'", '_')
예제 #41
0
파일: widgets.py 프로젝트: JimmXinu/calibre
 def lower_case(self):
     from calibre.utils.icu import lower
     self.setText(lower(unicode_type(self.text())))
예제 #42
0
파일: coloring.py 프로젝트: tletnes/calibre
 def current_val(self):
     ans = unicode_type(self.value_box.text()).strip()
     if self.current_col == 'languages':
         rmap = {lower(v):k for k, v in lang_map().iteritems()}
         ans = rmap.get(lower(ans), ans)
     return ans
예제 #43
0
#!/usr/bin/env python
예제 #44
0
 def file_named(self, name):
     name = lower(name)
     for e in self.files:
         if e.name and lower(e.name) == name:
             return e
     return None
예제 #45
0
파일: coloring.py 프로젝트: rakyi/calibre
 def sanitize_icon_file_name(self, icon_path):
     n = lower(sanitize_file_name_unicode(
                          os.path.splitext(
                                os.path.basename(icon_path))[0]+'.png'))
     return n.replace("'", '_')
예제 #46
0
 def file_named(self, name):
     name = lower(name)
     for e in self.files:
         if e.name and lower(e.name) == name:
             return e
     return None
예제 #47
0
    def __init__(self, fm, pref_name, parent=None):
        QDialog.__init__(self, parent)
        self.fm = fm

        if pref_name == 'column_color_rules':
            self.rule_kind = 'color'
            rule_text = _('coloring')
        else:
            self.rule_kind = 'icon'
            rule_text = _('icon')

        self.setWindowIcon(QIcon(I('format-fill-color.png')))
        self.setWindowTitle(_('Create/edit a column {0} rule').format(rule_text))

        self.l = l = QGridLayout(self)
        self.setLayout(l)

        self.l1 = l1 = QLabel(_('Create a column {0} rule by'
            ' filling in the boxes below'.format(rule_text)))
        l.addWidget(l1, 0, 0, 1, 8)

        self.f1 = QFrame(self)
        self.f1.setFrameShape(QFrame.HLine)
        l.addWidget(self.f1, 1, 0, 1, 8)

        self.l2 = l2 = QLabel(_('Set the'))
        l.addWidget(l2, 2, 0)

        if self.rule_kind == 'color':
            l.addWidget(QLabel(_('color')))
        else:
            self.kind_box = QComboBox(self)
            for tt, t in icon_rule_kinds:
                self.kind_box.addItem(tt, t)
            l.addWidget(self.kind_box, 2, 1)

        self.l3 = l3 = QLabel(_('of the column:'))
        l.addWidget(l3, 2, 2)

        self.column_box = QComboBox(self)
        l.addWidget(self.column_box, 2, 3)

        self.l4 = l4 = QLabel(_('to'))
        l.addWidget(l4, 2, 4)

        if self.rule_kind == 'color':
            self.color_box = QComboBox(self)
            self.color_label = QLabel('Sample text Sample text')
            self.color_label.setTextFormat(Qt.RichText)
            l.addWidget(self.color_box, 2, 5)
            l.addWidget(self.color_label, 2, 6)
            l.addItem(QSpacerItem(10, 10, QSizePolicy.Expanding), 2, 7)
        else:
            self.filename_box = QComboBox()
            self.filename_box.setInsertPolicy(self.filename_box.InsertAlphabetically)
            d = os.path.join(config_dir, 'cc_icons')
            self.icon_file_names = []
            if os.path.exists(d):
                for icon_file in os.listdir(d):
                    icon_file = lower(icon_file)
                    if os.path.exists(os.path.join(d, icon_file)):
                        if icon_file.endswith('.png'):
                            self.icon_file_names.append(icon_file)
            self.icon_file_names.sort(key=sort_key)
            self.update_filename_box()

            l.addWidget(self.filename_box, 2, 5)
            self.filename_button = QPushButton(QIcon(I('document_open.png')),
                                               _('&Add icon'))
            l.addWidget(self.filename_button, 2, 6)
            l.addWidget(QLabel(_('Icons should be square or landscape')), 2, 7)
            l.setColumnStretch(7, 10)

        self.l5 = l5 = QLabel(
            _('Only if the following conditions are all satisfied:'))
        l.addWidget(l5, 3, 0, 1, 7)

        self.scroll_area = sa = QScrollArea(self)
        sa.setMinimumHeight(300)
        sa.setMinimumWidth(950)
        sa.setWidgetResizable(True)
        l.addWidget(sa, 4, 0, 1, 8)

        self.add_button = b = QPushButton(QIcon(I('plus.png')),
                _('Add another condition'))
        l.addWidget(b, 5, 0, 1, 8)
        b.clicked.connect(self.add_blank_condition)

        self.l6 = l6 = QLabel(_('You can disable a condition by'
            ' blanking all of its boxes'))
        l.addWidget(l6, 6, 0, 1, 8)

        self.bb = bb = QDialogButtonBox(
                QDialogButtonBox.Ok|QDialogButtonBox.Cancel)
        bb.accepted.connect(self.accept)
        bb.rejected.connect(self.reject)
        l.addWidget(bb, 7, 0, 1, 8)

        self.conditions_widget = QWidget(self)
        sa.setWidget(self.conditions_widget)
        self.conditions_widget.setLayout(QVBoxLayout())
        self.conditions_widget.layout().setAlignment(Qt.AlignTop)
        self.conditions = []

        if self.rule_kind == 'color':
            for b in (self.column_box, self.color_box):
                b.setSizeAdjustPolicy(b.AdjustToMinimumContentsLengthWithIcon)
                b.setMinimumContentsLength(15)

        for key in sorted(displayable_columns(fm),
                          key=lambda(k): sort_key(fm[k]['name']) if k != color_row_key else 0):
            if key == color_row_key and self.rule_kind != 'color':
                continue
            name = all_columns_string if key == color_row_key else fm[key]['name']
            if name:
                self.column_box.addItem(name, key)
        self.column_box.setCurrentIndex(0)

        if self.rule_kind == 'color':
            self.color_box.addItems(QColor.colorNames())
            self.color_box.setCurrentIndex(0)
            self.update_color_label()
            self.color_box.currentIndexChanged.connect(self.update_color_label)
        else:
            self.filename_button.clicked.connect(self.filename_button_clicked)

        self.resize(self.sizeHint())
예제 #48
0
 def folder_named(self, name):
     name = lower(name)
     for e in self.folders:
         if e.name and lower(e.name) == name:
             return e
     return None
예제 #49
0
파일: widgets.py 프로젝트: zdndanny/calibre
 def lower_case(self):
     from calibre.utils.icu import lower
     self.setText(lower(unicode_type(self.text())))
예제 #50
0
파일: widgets.py 프로젝트: smdx023/calibre
 def lower_case(self):
     from calibre.utils.icu import lower
     self.setText(lower(str(self.text())))
예제 #51
0
    def merge_metadata_results(self, merge_on_identifiers=False):
        '''
        Merge results with identical title and authors or an identical
        identifier
        '''
        # First title/author
        groups = {}
        for result in self.results:
            title = lower(result.title if result.title else '')
            key = (title, tuple([lower(x) for x in result.authors]))
            if key not in groups:
                groups[key] = []
            groups[key].append(result)

        if len(groups) != len(self.results):
            self.results = []
            for rgroup in groups.itervalues():
                rel = [r.average_source_relevance for r in rgroup]
                if len(rgroup) > 1:
                    result = self.merge(rgroup, None, do_asr=False)
                    result.average_source_relevance = sum(rel)/len(rel)
                else:
                    result = rgroup[0]
                self.results.append(result)

        if merge_on_identifiers:
            # Now identifiers
            groups, empty = {}, []
            for result in self.results:
                key = set()
                for typ, val in result.identifiers.iteritems():
                    if typ and val:
                        key.add((typ, val))
                if key:
                    key = frozenset(key)
                    match = None
                    for candidate in list(groups):
                        if candidate.intersection(key):
                            # We have at least one identifier in common
                            match = candidate.union(key)
                            results = groups.pop(candidate)
                            results.append(result)
                            groups[match] = results
                            break
                    if match is None:
                        groups[key] = [result]
                else:
                    empty.append(result)

            if len(groups) != len(self.results):
                self.results = []
                for rgroup in groups.itervalues():
                    rel = [r.average_source_relevance for r in rgroup]
                    if len(rgroup) > 1:
                        result = self.merge(rgroup, None, do_asr=False)
                        result.average_source_relevance = sum(rel)/len(rel)
                    elif rgroup:
                        result = rgroup[0]
                    self.results.append(result)

            if empty:
                self.results.extend(empty)

        self.results.sort(key=attrgetter('average_source_relevance'))
예제 #52
0
 def folder_named(self, name):
     name = lower(name)
     for e in self.folders:
         if e.name and lower(e.name) == name:
             return e
     return None
예제 #53
0
파일: coloring.py 프로젝트: rakyi/calibre
 def current_val(self):
     ans = unicode(self.value_box.text()).strip()
     if self.current_col == 'languages':
         rmap = {lower(v):k for k, v in lang_map().iteritems()}
         ans = rmap.get(lower(ans), ans)
     return ans