mirror of
https://github.com/kovidgoyal/calibre.git
synced 2025-07-09 03:04:10 -04:00
Sync to trunk.
This commit is contained in:
commit
6e74a98e8f
@ -4,6 +4,7 @@ src/calibre/plugins
|
|||||||
resources/images.qrc
|
resources/images.qrc
|
||||||
src/calibre/manual/.build/
|
src/calibre/manual/.build/
|
||||||
src/calibre/manual/cli/
|
src/calibre/manual/cli/
|
||||||
|
src/calibre/manual/template_ref.rst
|
||||||
build
|
build
|
||||||
dist
|
dist
|
||||||
docs
|
docs
|
||||||
|
43
recipes/alt_om_herning.recipe
Normal file
43
recipes/alt_om_herning.recipe
Normal file
@ -0,0 +1,43 @@
|
|||||||
|
__license__ = 'GPL v3'
|
||||||
|
__copyright__ = '2011, Rasmus Lauritsen <rasmus at lauritsen.info>'
|
||||||
|
'''
|
||||||
|
aoh.dk
|
||||||
|
'''
|
||||||
|
|
||||||
|
from calibre.web.feeds.news import BasicNewsRecipe
|
||||||
|
|
||||||
|
class aoh_dk(BasicNewsRecipe):
|
||||||
|
title = 'Alt om Herning'
|
||||||
|
__author__ = 'Rasmus Lauritsen'
|
||||||
|
description = 'Nyheder fra Herning om omegn'
|
||||||
|
publisher = 'Mediehuset Herning Folkeblad'
|
||||||
|
category = 'news, local, Denmark'
|
||||||
|
oldest_article = 14
|
||||||
|
max_articles_per_feed = 50
|
||||||
|
no_stylesheets = True
|
||||||
|
delay = 1
|
||||||
|
encoding = 'utf8'
|
||||||
|
use_embedded_content = False
|
||||||
|
language = 'da'
|
||||||
|
extra_css = """ body{font-family: Verdana,Arial,sans-serif }
|
||||||
|
img{margin-bottom: 0.4em}
|
||||||
|
.txtContent,.stamp{font-size: small}
|
||||||
|
"""
|
||||||
|
|
||||||
|
conversion_options = {
|
||||||
|
'comment' : description
|
||||||
|
, 'tags' : category
|
||||||
|
, 'publisher' : publisher
|
||||||
|
, 'language' : language
|
||||||
|
}
|
||||||
|
|
||||||
|
feeds = [(u'All news', u'http://aoh.dk/rss.xml')]
|
||||||
|
|
||||||
|
keep_only_tags = [
|
||||||
|
dict(name='h1')
|
||||||
|
,dict(name='span', attrs={'class':['frontpage_body']})
|
||||||
|
]
|
||||||
|
|
||||||
|
remove_tags = [
|
||||||
|
dict(name=['object','link'])
|
||||||
|
]
|
@ -1,27 +1,30 @@
|
|||||||
__license__ = 'GPL v3'
|
__license__ = 'GPL v3'
|
||||||
__copyright__ = '2010, Darko Miletic <darko.miletic at gmail.com>'
|
__copyright__ = '2010 - 2011, Darko Miletic <darko.miletic at gmail.com>'
|
||||||
'''
|
'''
|
||||||
news.bbc.co.uk
|
news.bbc.co.uk
|
||||||
'''
|
'''
|
||||||
import re
|
|
||||||
from calibre.web.feeds.recipes import BasicNewsRecipe
|
from calibre.web.feeds.recipes import BasicNewsRecipe
|
||||||
|
|
||||||
class BBC(BasicNewsRecipe):
|
class BBC(BasicNewsRecipe):
|
||||||
title = 'BBC News (fast)'
|
title = 'BBC News (fast)'
|
||||||
__author__ = 'Darko Miletic, Starson17'
|
__author__ = 'Darko Miletic, Starson17'
|
||||||
description = 'News from UK. A much faster version that does not download pictures'
|
description = 'Visit BBC News for up-to-the-minute news, breaking news, video, audio and feature stories. BBC News provides trusted World and UK news as well as local and regional perspectives. Also entertainment, business, science, technology and health news.'
|
||||||
oldest_article = 2
|
oldest_article = 2
|
||||||
max_articles_per_feed = 100
|
max_articles_per_feed = 100
|
||||||
no_stylesheets = True
|
no_stylesheets = True
|
||||||
#delay = 1
|
|
||||||
use_embedded_content = False
|
use_embedded_content = False
|
||||||
encoding = 'utf8'
|
encoding = 'utf8'
|
||||||
publisher = 'BBC'
|
publisher = 'BBC'
|
||||||
category = 'news, UK, world'
|
category = 'news, UK, world'
|
||||||
language = 'en_GB'
|
language = 'en_GB'
|
||||||
publication_type = 'newsportal'
|
publication_type = 'newsportal'
|
||||||
extra_css = ' body{ font-family: Verdana,Helvetica,Arial,sans-serif } .introduction{font-weight: bold} .story-feature{display: block; padding: 0; border: 1px solid; width: 40%; font-size: small} .story-feature h2{text-align: center; text-transform: uppercase} '
|
masthead_url = 'http://news.bbcimg.co.uk/img/1_0_1/cream/hi/news/news-blocks.gif'
|
||||||
preprocess_regexps = [(re.compile(r'<!--.*?-->', re.DOTALL), lambda m: '')]
|
extra_css = """
|
||||||
|
body{ font-family: Verdana,Helvetica,Arial,sans-serif }
|
||||||
|
.introduction{font-weight: bold}
|
||||||
|
.story-feature{display: block; padding: 0; border: 1px solid; width: 40%; font-size: small}
|
||||||
|
.story-feature h2{text-align: center; text-transform: uppercase}
|
||||||
|
"""
|
||||||
conversion_options = {
|
conversion_options = {
|
||||||
'comments' : description
|
'comments' : description
|
||||||
,'tags' : category
|
,'tags' : category
|
||||||
@ -31,31 +34,54 @@ class BBC(BasicNewsRecipe):
|
|||||||
}
|
}
|
||||||
|
|
||||||
keep_only_tags = [
|
keep_only_tags = [
|
||||||
dict(name='div', attrs={'class':['layout-block-a layout-block']})
|
dict(name='div', attrs={'class':['layout-block-a layout-block']})
|
||||||
,dict(attrs={'class':['story-body','storybody']})
|
,dict(attrs={'class':['story-body','storybody']})
|
||||||
|
,dict(attrs={'id':['meta-information','story-body']})
|
||||||
]
|
]
|
||||||
|
|
||||||
remove_tags = [
|
remove_tags = [
|
||||||
dict(name='div', attrs={'class':['story-feature related narrow', 'share-help', 'embedded-hyper', \
|
dict(name='div', attrs={'class':['story-feature related narrow', \
|
||||||
'story-feature wide ', 'story-feature narrow']})
|
'share-help', 'embedded-hyper', \
|
||||||
, dict(name=['img'])
|
'story-feature wide ', \
|
||||||
]
|
'story-feature narrow', \
|
||||||
|
'hidden','story-actions', \
|
||||||
|
'embedded-hyper']})
|
||||||
|
,dict(name=['img','meta','link','object','embed','iframe','base'])
|
||||||
|
,dict(attrs={'class':['hidden','videoInStoryC']})
|
||||||
|
,dict(attrs={'id':['bbccom_sponsor_section','toggle-controls', \
|
||||||
|
'toggle-images','toggle-title']})
|
||||||
|
]
|
||||||
|
|
||||||
remove_attributes = ['width','height']
|
remove_attributes = ['width','height','xmlns:og','lang','clear']
|
||||||
|
|
||||||
feeds = [
|
feeds = [
|
||||||
('News Front Page', 'http://newsrss.bbc.co.uk/rss/newsonline_world_edition/front_page/rss.xml'),
|
('Top Stories' , 'http://feeds.bbci.co.uk/news/rss.xml' ),
|
||||||
('Science/Nature', 'http://newsrss.bbc.co.uk/rss/newsonline_world_edition/science/nature/rss.xml'),
|
('Science/Environment', 'http://feeds.bbci.co.uk/news/science_and_environment/rss.xml'),
|
||||||
('Technology', 'http://newsrss.bbc.co.uk/rss/newsonline_world_edition/technology/rss.xml'),
|
('Technology' , 'http://feeds.bbci.co.uk/news/technology/rss.xml' ),
|
||||||
('Entertainment', 'http://newsrss.bbc.co.uk/rss/newsonline_world_edition/entertainment/rss.xml'),
|
('Entertainment/Arts' , 'http://feeds.bbci.co.uk/news/entertainment_and_arts/rss.xml' ),
|
||||||
('Magazine', 'http://newsrss.bbc.co.uk/rss/newsonline_world_edition/uk_news/magazine/rss.xml'),
|
('Magazine' , 'http://feeds.bbci.co.uk/news/magazine/rss.xml' ),
|
||||||
('Business', 'http://newsrss.bbc.co.uk/rss/newsonline_world_edition/business/rss.xml'),
|
('Business' , 'http://feeds.bbci.co.uk/news/business/rss.xml' ),
|
||||||
('Health', 'http://newsrss.bbc.co.uk/rss/newsonline_world_edition/health/rss.xml'),
|
('Politics' , 'http://feeds.bbci.co.uk/news/politics/rss.xml' ),
|
||||||
('Americas', 'http://newsrss.bbc.co.uk/rss/newsonline_world_edition/americas/rss.xml'),
|
('Health' , 'http://feeds.bbci.co.uk/news/health/rss.xml' ),
|
||||||
('Europe', 'http://newsrss.bbc.co.uk/rss/newsonline_world_edition/europe/rss.xml'),
|
('US&Canada' , 'http://feeds.bbci.co.uk/news/world/us_and_canada/rss.xml' ),
|
||||||
('South Asia', 'http://newsrss.bbc.co.uk/rss/newsonline_world_edition/south_asia/rss.xml'),
|
('Latin America' , 'http://feeds.bbci.co.uk/news/world/latin_america/rss.xml' ),
|
||||||
('UK', 'http://newsrss.bbc.co.uk/rss/newsonline_world_edition/uk_news/rss.xml'),
|
('Europe' , 'http://feeds.bbci.co.uk/news/world/europe/rss.xml' ),
|
||||||
('Asia-Pacific', 'http://newsrss.bbc.co.uk/rss/newsonline_world_edition/asia-pacific/rss.xml'),
|
('South Asia' , 'http://feeds.bbci.co.uk/news/world/south_asia/rss.xml' ),
|
||||||
('Africa', 'http://newsrss.bbc.co.uk/rss/newsonline_world_edition/africa/rss.xml'),
|
('England' , 'http://feeds.bbci.co.uk/news/england/rss.xml' ),
|
||||||
|
('Asia-Pacific' , 'http://feeds.bbci.co.uk/news/world/asia_pacific/rss.xml' ),
|
||||||
|
('Africa' , 'http://feeds.bbci.co.uk/news/world/africa/rss.xml' )
|
||||||
]
|
]
|
||||||
|
|
||||||
|
def preprocess_html(self, soup):
|
||||||
|
for item in soup.findAll(style=True):
|
||||||
|
del item['style']
|
||||||
|
for item in soup.findAll('left'):
|
||||||
|
item.name='span'
|
||||||
|
for item in soup.findAll('a'):
|
||||||
|
if item.string is not None:
|
||||||
|
str = item.string
|
||||||
|
item.replaceWith(str)
|
||||||
|
else:
|
||||||
|
str = self.tag_to_string(item)
|
||||||
|
item.replaceWith(str)
|
||||||
|
return soup
|
||||||
|
@ -1,55 +1,71 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
#!/usr/bin/env python
|
|
||||||
|
|
||||||
__license__ = 'GPL v3'
|
|
||||||
__copyright__ = u'2011, Silviu Cotoar\u0103'
|
|
||||||
'''
|
|
||||||
dilemaveche.ro
|
|
||||||
'''
|
|
||||||
|
|
||||||
from calibre.web.feeds.news import BasicNewsRecipe
|
from calibre.web.feeds.news import BasicNewsRecipe
|
||||||
|
|
||||||
class DilemaVeche(BasicNewsRecipe):
|
class DilemaVeche(BasicNewsRecipe):
|
||||||
title = u'Dilema Veche'
|
title = u'Dilema Veche' # apare vinerea, mai pe dupa-masa,depinde de Luiza cred (care se semneaza ca fiind creatorul fiecarui articol in feed-ul RSS)
|
||||||
__author__ = u'Silviu Cotoar\u0103'
|
__author__ = 'song2' # inspirat din scriptul pentru Le Monde. Inspired from the Le Monde script
|
||||||
description = u'Sunt vechi, domnule!'
|
description = '"Sint vechi, domnule!" (I.L. Caragiale)'
|
||||||
publisher = u'Dilema Veche'
|
publisher = 'Adevarul Holding'
|
||||||
oldest_article = 50
|
oldest_article = 7
|
||||||
language = 'ro'
|
max_articles_per_feed = 200
|
||||||
max_articles_per_feed = 100
|
encoding = 'utf8'
|
||||||
no_stylesheets = True
|
language = 'ro'
|
||||||
use_embedded_content = False
|
masthead_url = 'http://www.dilemaveche.ro/sites/all/themes/dilema/theme/dilema_two/layouter/dilema_two_homepage/logo.png'
|
||||||
category = 'Ziare'
|
publication_type = 'magazine'
|
||||||
encoding = 'utf-8'
|
feeds = [
|
||||||
cover_url = 'http://www.dilemaveche.ro/sites/all/themes/dilema/theme/dilema_two/layouter/dilema_two_homepage/logo.png'
|
('Editoriale si opinii - Situatiunea', 'http://www.dilemaveche.ro/taxonomy/term/37/0/feed'),
|
||||||
|
('Editoriale si opinii - Pe ce lume traim', 'http://www.dilemaveche.ro/taxonomy/term/38/0/feed'),
|
||||||
conversion_options = {
|
('Editoriale si opinii - Bordeie si obiceie', 'http://www.dilemaveche.ro/taxonomy/term/44/0/feed'),
|
||||||
'comments' : description
|
('Editoriale si opinii - Talc Show', 'http://www.dilemaveche.ro/taxonomy/term/44/0/feed'),
|
||||||
,'tags' : category
|
('Tema saptamanii', 'http://www.dilemaveche.ro/taxonomy/term/19/0/feed'),
|
||||||
,'language' : language
|
('La zi in cultura - Dilema va recomanda', 'http://www.dilemaveche.ro/taxonomy/term/58/0/feed'),
|
||||||
,'publisher' : publisher
|
('La zi in cultura - Carte', 'http://www.dilemaveche.ro/taxonomy/term/14/0/feed'),
|
||||||
}
|
('La zi in cultura - Film', 'http://www.dilemaveche.ro/taxonomy/term/13/0/feed'),
|
||||||
|
('La zi in cultura - Muzica', 'http://www.dilemaveche.ro/taxonomy/term/1341/0/feed'),
|
||||||
keep_only_tags = [
|
('La zi in cultura - Arte performative', 'http://www.dilemaveche.ro/taxonomy/term/1342/0/feed'),
|
||||||
dict(name='h1', attrs={'class':'art_title'})
|
('La zi in cultura - Arte vizuale', 'http://www.dilemaveche.ro/taxonomy/term/1512/0/feed'),
|
||||||
, dict(name='h1', attrs={'class':'art_title online'})
|
('Societate - Ieri cu vedere spre azi', 'http://www.dilemaveche.ro/taxonomy/term/15/0/feed'),
|
||||||
, dict(name='div', attrs={'class':'item'})
|
('Societate - Din polul opus', 'http://www.dilemaveche.ro/taxonomy/term/41/0/feed'),
|
||||||
, dict(name='div', attrs={'class':'art_content'})
|
('Societate - Mass comedia', 'http://www.dilemaveche.ro/taxonomy/term/43/0/feed'),
|
||||||
]
|
('Societate - La singular si la plural', 'http://www.dilemaveche.ro/taxonomy/term/42/0/feed'),
|
||||||
|
('Oameni si idei - Educatie', 'http://www.dilemaveche.ro/taxonomy/term/46/0/feed'),
|
||||||
|
('Oameni si idei - Polemici si dezbateri', 'http://www.dilemaveche.ro/taxonomy/term/48/0/feed'),
|
||||||
|
('Oameni si idei - Stiinta si tehnologie', 'http://www.dilemaveche.ro/taxonomy/term/46/0/feed'),
|
||||||
|
('Dileme on-line', 'http://www.dilemaveche.ro/taxonomy/term/005/0/feed')
|
||||||
|
]
|
||||||
|
remove_tags_before = dict(name='div',attrs={'class':'spacer_10'})
|
||||||
remove_tags = [
|
remove_tags = [
|
||||||
dict(name='div', attrs={'class':['article_details']})
|
dict(name='div', attrs={'class':'art_related_left'}),
|
||||||
, dict(name='div', attrs={'class':['controale']})
|
dict(name='div', attrs={'class':'controale'}),
|
||||||
, dict(name='div', attrs={'class':['art_related_left']})
|
dict(name='div', attrs={'class':'simple_overlay'}),
|
||||||
]
|
]
|
||||||
|
remove_tags_after = [dict(id='facebookLike')]
|
||||||
|
remove_javascript = True
|
||||||
|
no_stylesheets = True
|
||||||
|
remove_empty_feeds = True
|
||||||
|
extra_css = """
|
||||||
|
body{font-family: Georgia,Times,serif }
|
||||||
|
img{margin-bottom: 0.4em; display:block}
|
||||||
|
"""
|
||||||
|
def get_cover_url(self):
|
||||||
|
cover_url = None
|
||||||
|
soup = self.index_to_soup('http://dilemaveche.ro')
|
||||||
|
link_item = soup.find('div',attrs={'class':'box_dr_pdf_picture'})
|
||||||
|
if link_item and link_item.a:
|
||||||
|
cover_url = link_item.a['href']
|
||||||
|
br = BasicNewsRecipe.get_browser()
|
||||||
|
try:
|
||||||
|
br.open(cover_url)
|
||||||
|
except: #daca nu gaseste pdf-ul
|
||||||
|
self.log("\nPDF indisponibil")
|
||||||
|
link_item = soup.find('div',attrs={'class':'box_dr_pdf_picture'})
|
||||||
|
if link_item and link_item.img:
|
||||||
|
cover_url = link_item.img['src']
|
||||||
|
br = BasicNewsRecipe.get_browser()
|
||||||
|
try:
|
||||||
|
br.open(cover_url)
|
||||||
|
except: #daca nu gaseste nici imaginea mica mica
|
||||||
|
print('Mama lor de nenorociti! nu este nici pdf nici imagine')
|
||||||
|
cover_url ='http://www.dilemaveche.ro/sites/all/themes/dilema/theme/dilema_two/layouter/dilema_two_homepage/logo.png'
|
||||||
|
return cover_url
|
||||||
|
cover_margins = (10, 15, '#ffffff')
|
||||||
|
|
||||||
remove_tags_after = [
|
|
||||||
dict(name='div', attrs={'class':['article_details']})
|
|
||||||
]
|
|
||||||
|
|
||||||
feeds = [
|
|
||||||
(u'Feeds', u'http://www.dilemaveche.ro/rss.xml')
|
|
||||||
]
|
|
||||||
|
|
||||||
def preprocess_html(self, soup):
|
|
||||||
return self.adeify_images(soup)
|
|
||||||
|
@ -71,7 +71,7 @@ class Mediapart(BasicNewsRecipe):
|
|||||||
br = BasicNewsRecipe.get_browser()
|
br = BasicNewsRecipe.get_browser()
|
||||||
if self.username is not None and self.password is not None:
|
if self.username is not None and self.password is not None:
|
||||||
br.open('http://www.mediapart.fr/')
|
br.open('http://www.mediapart.fr/')
|
||||||
br.select_form(nr=1)
|
br.select_form(nr=0)
|
||||||
br['name'] = self.username
|
br['name'] = self.username
|
||||||
br['pass'] = self.password
|
br['pass'] = self.password
|
||||||
br.submit()
|
br.submit()
|
||||||
|
29
recipes/metro_uk.recipe
Normal file
29
recipes/metro_uk.recipe
Normal file
@ -0,0 +1,29 @@
|
|||||||
|
from calibre.web.feeds.news import BasicNewsRecipe
|
||||||
|
class AdvancedUserRecipe1306097511(BasicNewsRecipe):
|
||||||
|
title = u'Metro UK'
|
||||||
|
|
||||||
|
no_stylesheets = True
|
||||||
|
oldest_article = 1
|
||||||
|
max_articles_per_feed = 200
|
||||||
|
|
||||||
|
__author__ = 'Dave Asbury'
|
||||||
|
language = 'en_GB'
|
||||||
|
simultaneous_downloads= 3
|
||||||
|
|
||||||
|
masthead_url = 'http://e-edition.metro.co.uk/images/metro_logo.gif'
|
||||||
|
|
||||||
|
keep_only_tags = [
|
||||||
|
dict(attrs={'class':['img-cnt figure']}),
|
||||||
|
dict(attrs={'class':['art-img']}),
|
||||||
|
dict(name='h1'),
|
||||||
|
dict(name='h2', attrs={'class':'h2'}),
|
||||||
|
dict(name='div', attrs={'class':'art-lft'})
|
||||||
|
]
|
||||||
|
remove_tags = [dict(name='div', attrs={'class':[ 'metroCommentFormWrap',
|
||||||
|
'commentForm', 'metroCommentInnerWrap',
|
||||||
|
'art-rgt','pluck-app pluck-comm','news m12 clrd clr-l p5t', 'flt-r' ]})]
|
||||||
|
|
||||||
|
feeds = [
|
||||||
|
(u'News', u'http://www.metro.co.uk/rss/news/'), (u'Money', u'http://www.metro.co.uk/rss/money/'), (u'Sport', u'http://www.metro.co.uk/rss/sport/'), (u'Film', u'http://www.metro.co.uk/rss/metrolife/film/'), (u'Music', u'http://www.metro.co.uk/rss/metrolife/music/'), (u'TV', u'http://www.metro.co.uk/rss/tv/'), (u'Showbiz', u'http://www.metro.co.uk/rss/showbiz/'), (u'Weird News', u'http://www.metro.co.uk/rss/weird/'), (u'Travel', u'http://www.metro.co.uk/rss/travel/'), (u'Lifestyle', u'http://www.metro.co.uk/rss/lifestyle/'), (u'Books', u'http://www.metro.co.uk/rss/lifestyle/books/'), (u'Food', u'http://www.metro.co.uk/rss/lifestyle/restaurants/')]
|
||||||
|
|
||||||
|
|
64
recipes/observatorul_cultural.recipe
Normal file
64
recipes/observatorul_cultural.recipe
Normal file
@ -0,0 +1,64 @@
|
|||||||
|
import re
|
||||||
|
from calibre.web.feeds.news import BasicNewsRecipe
|
||||||
|
coverpage = None
|
||||||
|
|
||||||
|
class ObservatorulCultural(BasicNewsRecipe):
|
||||||
|
title = u'Observatorul cultural'
|
||||||
|
__author__ = 'song2' #prelucrat dupa un script de http://www.thenowhereman.com
|
||||||
|
encoding = 'utf-8'
|
||||||
|
language = 'ro'
|
||||||
|
publication_type = 'magazine'
|
||||||
|
description = 'Spiritul critic in acţiune\n'
|
||||||
|
no_stylesheets = True
|
||||||
|
remove_javascript = True
|
||||||
|
masthead_url='http://www.observatorcultural.ro/userfiles/article/sigla%20Observator%20cultural_02231058.JPG'
|
||||||
|
keep_only_tags = [
|
||||||
|
dict(name='div', attrs={'class':'detaliuArticol'})]
|
||||||
|
remove_tags = [dict(name='div', attrs={'class':'comentariiArticol'}),
|
||||||
|
dict(name='div', attrs={'class':'postComment'}),
|
||||||
|
dict(name='div', attrs={'class':'utileArticol'}),
|
||||||
|
dict(name='p', attrs={'class':'butonComenteaza'}),
|
||||||
|
dict(name='h5'),
|
||||||
|
dict(name='div', attrs={'style':'margin-top: 0px; padding-top: 0px;'})
|
||||||
|
]
|
||||||
|
def parse_index(self):
|
||||||
|
soup = self.index_to_soup('http://www.observatorcultural.ro/Arhiva*-archive.html')
|
||||||
|
issueTag = soup.find('a', href=re.compile("observatorcultural.ro\/Numarul"))
|
||||||
|
issueURL = issueTag['href']
|
||||||
|
print issueURL;
|
||||||
|
issueSoup = self.index_to_soup(issueURL)
|
||||||
|
feeds = []
|
||||||
|
stories = []
|
||||||
|
for categorie in issueSoup.findAll('dl',attrs={'class':'continutArhive'}):
|
||||||
|
categ=self.tag_to_string(categorie.find('dt'))
|
||||||
|
for story in categorie.findAll('dd'):
|
||||||
|
title=[]
|
||||||
|
for bucatele in story.findAll('a'):
|
||||||
|
title.append(bucatele)
|
||||||
|
if len(title)==1: #daca articolul nu are autor
|
||||||
|
stories.append({
|
||||||
|
'title' : self.tag_to_string(title[0]),
|
||||||
|
'url' : title[0]['href'],
|
||||||
|
'date' : '',
|
||||||
|
'author' : ''})
|
||||||
|
else: # daca articolul are autor len(title)=2
|
||||||
|
stories.append({
|
||||||
|
'title' : self.tag_to_string(title[1]),
|
||||||
|
'url' :title[1]['href'],
|
||||||
|
'date' : '',
|
||||||
|
'author' : self.tag_to_string(title[0])})
|
||||||
|
print(self.tag_to_string(title[0]))
|
||||||
|
if 'Editorial' in categ:
|
||||||
|
global coverpage
|
||||||
|
coverpage=title[1]['href'] # am luat link-ul spre editorial
|
||||||
|
feeds.append((categ,stories))
|
||||||
|
stories = []
|
||||||
|
print feeds
|
||||||
|
return feeds
|
||||||
|
#procedura de luat coperta
|
||||||
|
def get_cover_url(self):
|
||||||
|
soup = self.index_to_soup(coverpage)
|
||||||
|
link_item = soup.find('a',attrs={'rel':'lightbox'}) # caut imaginea textului
|
||||||
|
a=''
|
||||||
|
cover_url = a.join(link_item.img['src'].split('_details_'))
|
||||||
|
return cover_url
|
64
recipes/version2.recipe
Normal file
64
recipes/version2.recipe
Normal file
@ -0,0 +1,64 @@
|
|||||||
|
import re
|
||||||
|
|
||||||
|
__license__ = 'GPL v3'
|
||||||
|
__copyright__ = '2011, Rasmus Lauritsen <rasmus at lauritsen.info>'
|
||||||
|
'''
|
||||||
|
version2.dk
|
||||||
|
'''
|
||||||
|
|
||||||
|
from calibre.web.feeds.news import BasicNewsRecipe
|
||||||
|
|
||||||
|
class version2(BasicNewsRecipe):
|
||||||
|
title = 'Version2.dk'
|
||||||
|
__author__ = 'Rasmus Lauritsen'
|
||||||
|
description = 'IT News'
|
||||||
|
publisher = 'version2.dk'
|
||||||
|
category = 'news, IT, hardware, software, Denmark'
|
||||||
|
oldest_article = 14
|
||||||
|
max_articles_per_feed = 50
|
||||||
|
no_stylesheets = True
|
||||||
|
remove_empty_feeds = True
|
||||||
|
use_embedded_content = False
|
||||||
|
encoding = 'iso-8859-1'
|
||||||
|
language = 'da'
|
||||||
|
|
||||||
|
extra_css = """
|
||||||
|
body {font-family: "Verdana",Times,serif}
|
||||||
|
.articleauthor{color: #9F9F9F;
|
||||||
|
font-family: Arial, sans-serif;
|
||||||
|
font-size: small;
|
||||||
|
text-transform: uppercase}
|
||||||
|
.rubric,.dd,h6#credit{color: #CD0021;
|
||||||
|
font-family: Arial, sans-serif;
|
||||||
|
font-size: small;
|
||||||
|
text-transform: uppercase}
|
||||||
|
.descender:first-letter{display: inline; font-size: xx-large; font-weight: bold}
|
||||||
|
.dd,h6#credit{color: gray}
|
||||||
|
.c{display: block}
|
||||||
|
.caption,h2#articleintro{font-style: italic}
|
||||||
|
.caption{font-size: small}
|
||||||
|
"""
|
||||||
|
|
||||||
|
preprocess_regexps = [ (re.compile(r'</?a[^>]*>'),lambda match: ''),
|
||||||
|
(re.compile(r'<span[^>]*article-link-id.*?<br\s*\/?><br\s*\/?>'), lambda match: '')]
|
||||||
|
|
||||||
|
keep_only_tags = [dict(name='div', attrs={'class':'article'})]
|
||||||
|
|
||||||
|
remove_tags = [
|
||||||
|
dict(name='p',attrs={'class':'meta links'}),
|
||||||
|
dict(name='div',attrs={'class':'float-right'}),
|
||||||
|
dict(name='span',attrs={'class':'article-link-id'})
|
||||||
|
]
|
||||||
|
|
||||||
|
feeds = [
|
||||||
|
(u'Seneste nyheder' , u'http://www.version2.dk/feeds/nyheder')
|
||||||
|
,(u'Forretningssoftware' , u'http://www.version2.dk/feeds/forretningssoftware')
|
||||||
|
,(u'Internet & styresystemer' , u'http://www.version2.dk/feeds/styresystemer')
|
||||||
|
,(u'It-arkitektur' , u'http://www.version2.dk/feeds/it-arkitektur')
|
||||||
|
,(u'It-styring & outsourcing' , u'http://www.version2.dk/feeds/it-styring')
|
||||||
|
,(u'Job & karriere' , u'http://www.version2.dk/feeds/karriere')
|
||||||
|
,(u'Mobil it & tele' , u'http://www.version2.dk/feeds/tele')
|
||||||
|
,(u'Server/storage & netværk' , u'http://www.version2.dk/feeds/server-storage')
|
||||||
|
,(u'Sikkerhed' , u'http://www.version2.dk/feeds/sikkerhed')
|
||||||
|
,(u'Softwareudvikling' , u'http://www.version2.dk/feeds/softwareudvikling')
|
||||||
|
]
|
@ -1,26 +1,27 @@
|
|||||||
{
|
{
|
||||||
"and": "def evaluate(self, formatter, kwargs, mi, locals, *args):\n i = 0\n while i < len(args):\n if not args[i]:\n return ''\n i += 1\n return '1'\n",
|
"and": "def evaluate(self, formatter, kwargs, mi, locals, *args):\n i = 0\n while i < len(args):\n if not args[i]:\n return ''\n i += 1\n return '1'\n",
|
||||||
"contains": "def evaluate(self, formatter, kwargs, mi, locals,\n val, test, value_if_present, value_if_not):\n if re.search(test, val):\n return value_if_present\n else:\n return value_if_not\n",
|
"contains": "def evaluate(self, formatter, kwargs, mi, locals,\n val, test, value_if_present, value_if_not):\n if re.search(test, val, flags=re.I):\n return value_if_present\n else:\n return value_if_not\n",
|
||||||
"divide": "def evaluate(self, formatter, kwargs, mi, locals, x, y):\n x = float(x if x else 0)\n y = float(y if y else 0)\n return unicode(x / y)\n",
|
"divide": "def evaluate(self, formatter, kwargs, mi, locals, x, y):\n x = float(x if x else 0)\n y = float(y if y else 0)\n return unicode(x / y)\n",
|
||||||
"uppercase": "def evaluate(self, formatter, kwargs, mi, locals, val):\n return val.upper()\n",
|
"uppercase": "def evaluate(self, formatter, kwargs, mi, locals, val):\n return val.upper()\n",
|
||||||
"strcat": "def evaluate(self, formatter, kwargs, mi, locals, *args):\n i = 0\n res = ''\n for i in range(0, len(args)):\n res += args[i]\n return res\n",
|
"strcat": "def evaluate(self, formatter, kwargs, mi, locals, *args):\n i = 0\n res = ''\n for i in range(0, len(args)):\n res += args[i]\n return res\n",
|
||||||
"in_list": "def evaluate(self, formatter, kwargs, mi, locals, val, sep, pat, fv, nfv):\n l = [v.strip() for v in val.split(sep) if v.strip()]\n for v in l:\n if re.search(pat, v):\n return fv\n return nfv\n",
|
"in_list": "def evaluate(self, formatter, kwargs, mi, locals, val, sep, pat, fv, nfv):\n l = [v.strip() for v in val.split(sep) if v.strip()]\n if l:\n for v in l:\n if re.search(pat, v, flags=re.I):\n return fv\n return nfv\n",
|
||||||
"multiply": "def evaluate(self, formatter, kwargs, mi, locals, x, y):\n x = float(x if x else 0)\n y = float(y if y else 0)\n return unicode(x * y)\n",
|
"multiply": "def evaluate(self, formatter, kwargs, mi, locals, x, y):\n x = float(x if x else 0)\n y = float(y if y else 0)\n return unicode(x * y)\n",
|
||||||
"ifempty": "def evaluate(self, formatter, kwargs, mi, locals, val, value_if_empty):\n if val:\n return val\n else:\n return value_if_empty\n",
|
"ifempty": "def evaluate(self, formatter, kwargs, mi, locals, val, value_if_empty):\n if val:\n return val\n else:\n return value_if_empty\n",
|
||||||
"booksize": "def evaluate(self, formatter, kwargs, mi, locals):\n if mi.book_size is not None:\n try:\n return str(mi.book_size)\n except:\n pass\n return ''\n",
|
"booksize": "def evaluate(self, formatter, kwargs, mi, locals):\n if mi.book_size is not None:\n try:\n return str(mi.book_size)\n except:\n pass\n return ''\n",
|
||||||
"select": "def evaluate(self, formatter, kwargs, mi, locals, val, key):\n if not val:\n return ''\n vals = [v.strip() for v in val.split(',')]\n for v in vals:\n if v.startswith(key+':'):\n return v[len(key)+1:]\n return ''\n",
|
"select": "def evaluate(self, formatter, kwargs, mi, locals, val, key):\n if not val:\n return ''\n vals = [v.strip() for v in val.split(',')]\n for v in vals:\n if v.startswith(key+':'):\n return v[len(key)+1:]\n return ''\n",
|
||||||
"strcmp": "def evaluate(self, formatter, kwargs, mi, locals, x, y, lt, eq, gt):\n v = strcmp(x, y)\n if v < 0:\n return lt\n if v == 0:\n return eq\n return gt\n",
|
"strcmp": "def evaluate(self, formatter, kwargs, mi, locals, x, y, lt, eq, gt):\n v = strcmp(x, y)\n if v < 0:\n return lt\n if v == 0:\n return eq\n return gt\n",
|
||||||
"first_non_empty": "def evaluate(self, formatter, kwargs, mi, locals, *args):\n i = 0\n while i < len(args):\n if args[i]:\n return args[i]\n i += 1\n return ''\n",
|
"first_non_empty": "def evaluate(self, formatter, kwargs, mi, locals, *args):\n i = 0\n while i < len(args):\n if args[i]:\n return args[i]\n i += 1\n return ''\n",
|
||||||
"re": "def evaluate(self, formatter, kwargs, mi, locals, val, pattern, replacement):\n return re.sub(pattern, replacement, val)\n",
|
"re": "def evaluate(self, formatter, kwargs, mi, locals, val, pattern, replacement):\n return re.sub(pattern, replacement, val, flags=re.I)\n",
|
||||||
"subtract": "def evaluate(self, formatter, kwargs, mi, locals, x, y):\n x = float(x if x else 0)\n y = float(y if y else 0)\n return unicode(x - y)\n",
|
"subtract": "def evaluate(self, formatter, kwargs, mi, locals, x, y):\n x = float(x if x else 0)\n y = float(y if y else 0)\n return unicode(x - y)\n",
|
||||||
"list_item": "def evaluate(self, formatter, kwargs, mi, locals, val, index, sep):\n if not val:\n return ''\n index = int(index)\n val = val.split(sep)\n try:\n return val[index]\n except:\n return ''\n",
|
"list_item": "def evaluate(self, formatter, kwargs, mi, locals, val, index, sep):\n if not val:\n return ''\n index = int(index)\n val = val.split(sep)\n try:\n return val[index]\n except:\n return ''\n",
|
||||||
"shorten": "def evaluate(self, formatter, kwargs, mi, locals,\n val, leading, center_string, trailing):\n l = max(0, int(leading))\n t = max(0, int(trailing))\n if len(val) > l + len(center_string) + t:\n return val[0:l] + center_string + ('' if t == 0 else val[-t:])\n else:\n return val\n",
|
"shorten": "def evaluate(self, formatter, kwargs, mi, locals,\n val, leading, center_string, trailing):\n l = max(0, int(leading))\n t = max(0, int(trailing))\n if len(val) > l + len(center_string) + t:\n return val[0:l] + center_string + ('' if t == 0 else val[-t:])\n else:\n return val\n",
|
||||||
"field": "def evaluate(self, formatter, kwargs, mi, locals, name):\n return formatter.get_value(name, [], kwargs)\n",
|
"field": "def evaluate(self, formatter, kwargs, mi, locals, name):\n return formatter.get_value(name, [], kwargs)\n",
|
||||||
"add": "def evaluate(self, formatter, kwargs, mi, locals, x, y):\n x = float(x if x else 0)\n y = float(y if y else 0)\n return unicode(x + y)\n",
|
"add": "def evaluate(self, formatter, kwargs, mi, locals, x, y):\n x = float(x if x else 0)\n y = float(y if y else 0)\n return unicode(x + y)\n",
|
||||||
"lookup": "def evaluate(self, formatter, kwargs, mi, locals, val, *args):\n if len(args) == 2: # here for backwards compatibility\n if val:\n return formatter.vformat('{'+args[0].strip()+'}', [], kwargs)\n else:\n return formatter.vformat('{'+args[1].strip()+'}', [], kwargs)\n if (len(args) % 2) != 1:\n raise ValueError(_('lookup requires either 2 or an odd number of arguments'))\n i = 0\n while i < len(args):\n if i + 1 >= len(args):\n return formatter.vformat('{' + args[i].strip() + '}', [], kwargs)\n if re.search(args[i], val):\n return formatter.vformat('{'+args[i+1].strip() + '}', [], kwargs)\n i += 2\n",
|
"lookup": "def evaluate(self, formatter, kwargs, mi, locals, val, *args):\n if len(args) == 2: # here for backwards compatibility\n if val:\n return formatter.vformat('{'+args[0].strip()+'}', [], kwargs)\n else:\n return formatter.vformat('{'+args[1].strip()+'}', [], kwargs)\n if (len(args) % 2) != 1:\n raise ValueError(_('lookup requires either 2 or an odd number of arguments'))\n i = 0\n while i < len(args):\n if i + 1 >= len(args):\n return formatter.vformat('{' + args[i].strip() + '}', [], kwargs)\n if re.search(args[i], val, flags=re.I):\n return formatter.vformat('{'+args[i+1].strip() + '}', [], kwargs)\n i += 2\n",
|
||||||
"template": "def evaluate(self, formatter, kwargs, mi, locals, template):\n template = template.replace('[[', '{').replace(']]', '}')\n return formatter.__class__().safe_format(template, kwargs, 'TEMPLATE', mi)\n",
|
"template": "def evaluate(self, formatter, kwargs, mi, locals, template):\n template = template.replace('[[', '{').replace(']]', '}')\n return formatter.__class__().safe_format(template, kwargs, 'TEMPLATE', mi)\n",
|
||||||
"print": "def evaluate(self, formatter, kwargs, mi, locals, *args):\n print args\n return None\n",
|
"print": "def evaluate(self, formatter, kwargs, mi, locals, *args):\n print args\n return None\n",
|
||||||
"merge_lists": "def evaluate(self, formatter, kwargs, mi, locals, list1, list2, separator):\n l1 = [l.strip() for l in list1.split(separator) if l.strip()]\n l2 = [l.strip() for l in list2.split(separator) if l.strip()]\n lcl1 = set([icu_lower(l) for l in l1])\n res = []\n for i in l1:\n res.append(i)\n for i in l2:\n if icu_lower(i) not in lcl1:\n res.append(i)\n return ', '.join(sorted(res, key=sort_key))\n",
|
"merge_lists": "def evaluate(self, formatter, kwargs, mi, locals, list1, list2, separator):\n l1 = [l.strip() for l in list1.split(separator) if l.strip()]\n l2 = [l.strip() for l in list2.split(separator) if l.strip()]\n lcl1 = set([icu_lower(l) for l in l1])\n res = []\n for i in l1:\n res.append(i)\n for i in l2:\n if icu_lower(i) not in lcl1:\n res.append(i)\n return ', '.join(sorted(res, key=sort_key))\n",
|
||||||
|
"str_in_list": "def evaluate(self, formatter, kwargs, mi, locals, val, sep, str, fv, nfv):\n l = [v.strip() for v in val.split(sep) if v.strip()]\n c = [v.strip() for v in str.split(sep) if v.strip()]\n if l:\n for v in l:\n for t in c:\n if strcmp(t, v) == 0:\n return fv\n return nfv\n",
|
||||||
"titlecase": "def evaluate(self, formatter, kwargs, mi, locals, val):\n return titlecase(val)\n",
|
"titlecase": "def evaluate(self, formatter, kwargs, mi, locals, val):\n return titlecase(val)\n",
|
||||||
"subitems": "def evaluate(self, formatter, kwargs, mi, locals, val, start_index, end_index):\n if not val:\n return ''\n si = int(start_index)\n ei = int(end_index)\n items = [v.strip() for v in val.split(',')]\n rv = set()\n for item in items:\n component = item.split('.')\n try:\n if ei == 0:\n rv.add('.'.join(component[si:]))\n else:\n rv.add('.'.join(component[si:ei]))\n except:\n pass\n return ', '.join(sorted(rv, key=sort_key))\n",
|
"subitems": "def evaluate(self, formatter, kwargs, mi, locals, val, start_index, end_index):\n if not val:\n return ''\n si = int(start_index)\n ei = int(end_index)\n items = [v.strip() for v in val.split(',')]\n rv = set()\n for item in items:\n component = item.split('.')\n try:\n if ei == 0:\n rv.add('.'.join(component[si:]))\n else:\n rv.add('.'.join(component[si:ei]))\n except:\n pass\n return ', '.join(sorted(rv, key=sort_key))\n",
|
||||||
"sublist": "def evaluate(self, formatter, kwargs, mi, locals, val, start_index, end_index, sep):\n if not val:\n return ''\n si = int(start_index)\n ei = int(end_index)\n val = val.split(sep)\n try:\n if ei == 0:\n return sep.join(val[si:])\n else:\n return sep.join(val[si:ei])\n except:\n return ''\n",
|
"sublist": "def evaluate(self, formatter, kwargs, mi, locals, val, start_index, end_index, sep):\n if not val:\n return ''\n si = int(start_index)\n ei = int(end_index)\n val = val.split(sep)\n try:\n if ei == 0:\n return sep.join(val[si:])\n else:\n return sep.join(val[si:ei])\n except:\n return ''\n",
|
||||||
@ -32,9 +33,10 @@
|
|||||||
"count": "def evaluate(self, formatter, kwargs, mi, locals, val, sep):\n return unicode(len(val.split(sep)))\n",
|
"count": "def evaluate(self, formatter, kwargs, mi, locals, val, sep):\n return unicode(len(val.split(sep)))\n",
|
||||||
"lowercase": "def evaluate(self, formatter, kwargs, mi, locals, val):\n return val.lower()\n",
|
"lowercase": "def evaluate(self, formatter, kwargs, mi, locals, val):\n return val.lower()\n",
|
||||||
"substr": "def evaluate(self, formatter, kwargs, mi, locals, str_, start_, end_):\n return str_[int(start_): len(str_) if int(end_) == 0 else int(end_)]\n",
|
"substr": "def evaluate(self, formatter, kwargs, mi, locals, str_, start_, end_):\n return str_[int(start_): len(str_) if int(end_) == 0 else int(end_)]\n",
|
||||||
"assign": "def evaluate(self, formatter, kwargs, mi, locals, target, value):\n locals[target] = value\n return value\n",
|
|
||||||
"switch": "def evaluate(self, formatter, kwargs, mi, locals, val, *args):\n if (len(args) % 2) != 1:\n raise ValueError(_('switch requires an odd number of arguments'))\n i = 0\n while i < len(args):\n if i + 1 >= len(args):\n return args[i]\n if re.search(args[i], val):\n return args[i+1]\n i += 2\n",
|
|
||||||
"or": "def evaluate(self, formatter, kwargs, mi, locals, *args):\n i = 0\n while i < len(args):\n if args[i]:\n return '1'\n i += 1\n return ''\n",
|
"or": "def evaluate(self, formatter, kwargs, mi, locals, *args):\n i = 0\n while i < len(args):\n if args[i]:\n return '1'\n i += 1\n return ''\n",
|
||||||
|
"switch": "def evaluate(self, formatter, kwargs, mi, locals, val, *args):\n if (len(args) % 2) != 1:\n raise ValueError(_('switch requires an odd number of arguments'))\n i = 0\n while i < len(args):\n if i + 1 >= len(args):\n return args[i]\n if re.search(args[i], val, flags=re.I):\n return args[i+1]\n i += 2\n",
|
||||||
|
"ondevice": "def evaluate(self, formatter, kwargs, mi, locals):\n if mi.ondevice_col:\n return _('Yes')\n return ''\n",
|
||||||
|
"assign": "def evaluate(self, formatter, kwargs, mi, locals, target, value):\n locals[target] = value\n return value\n",
|
||||||
"raw_field": "def evaluate(self, formatter, kwargs, mi, locals, name):\n return unicode(getattr(mi, name, None))\n",
|
"raw_field": "def evaluate(self, formatter, kwargs, mi, locals, name):\n return unicode(getattr(mi, name, None))\n",
|
||||||
"cmp": "def evaluate(self, formatter, kwargs, mi, locals, x, y, lt, eq, gt):\n x = float(x if x else 0)\n y = float(y if y else 0)\n if x < y:\n return lt\n if x == y:\n return eq\n return gt\n"
|
"cmp": "def evaluate(self, formatter, kwargs, mi, locals, x, y, lt, eq, gt):\n x = float(x if x else 0)\n y = float(y if y else 0)\n if x < y:\n return lt\n if x == y:\n return eq\n return gt\n"
|
||||||
}
|
}
|
@ -17,6 +17,7 @@
|
|||||||
IncludeMaximum="yes"
|
IncludeMaximum="yes"
|
||||||
OnlyDetect="no"
|
OnlyDetect="no"
|
||||||
Language="1033"
|
Language="1033"
|
||||||
|
MigrateFeatures="yes"
|
||||||
Property="OLDPRODUCTFOUND"/>
|
Property="OLDPRODUCTFOUND"/>
|
||||||
<UpgradeVersion Minimum="{version}"
|
<UpgradeVersion Minimum="{version}"
|
||||||
IncludeMinimum="no"
|
IncludeMinimum="no"
|
||||||
|
@ -109,7 +109,8 @@ class ANDROID(USBMS):
|
|||||||
'SGH-T849', '_MB300', 'A70S', 'S_ANDROID', 'A101IT', 'A70H',
|
'SGH-T849', '_MB300', 'A70S', 'S_ANDROID', 'A101IT', 'A70H',
|
||||||
'IDEOS_TABLET', 'MYTOUCH_4G', 'UMS_COMPOSITE', 'SCH-I800_CARD',
|
'IDEOS_TABLET', 'MYTOUCH_4G', 'UMS_COMPOSITE', 'SCH-I800_CARD',
|
||||||
'7', 'A956', 'A955', 'A43', 'ANDROID_PLATFORM', 'TEGRA_2',
|
'7', 'A956', 'A955', 'A43', 'ANDROID_PLATFORM', 'TEGRA_2',
|
||||||
'MB860', 'MULTI-CARD', 'MID7015A', 'INCREDIBLE', 'A7EB', 'STREAK']
|
'MB860', 'MULTI-CARD', 'MID7015A', 'INCREDIBLE', 'A7EB', 'STREAK',
|
||||||
|
'MB525']
|
||||||
WINDOWS_CARD_A_MEM = ['ANDROID_PHONE', 'GT-I9000_CARD', 'SGH-I897',
|
WINDOWS_CARD_A_MEM = ['ANDROID_PHONE', 'GT-I9000_CARD', 'SGH-I897',
|
||||||
'FILE-STOR_GADGET', 'SGH-T959', 'SAMSUNG_ANDROID', 'GT-P1000_CARD',
|
'FILE-STOR_GADGET', 'SGH-T959', 'SAMSUNG_ANDROID', 'GT-P1000_CARD',
|
||||||
'A70S', 'A101IT', '7', 'INCREDIBLE', 'A7EB', 'SGH-T849_CARD']
|
'A70S', 'A101IT', '7', 'INCREDIBLE', 'A7EB', 'SGH-T849_CARD']
|
||||||
|
@ -101,7 +101,7 @@ class Container(object):
|
|||||||
return None
|
return None
|
||||||
return existing[0]
|
return existing[0]
|
||||||
|
|
||||||
def add_name_to_manifest(self, name):
|
def add_name_to_manifest(self, name, mt=None):
|
||||||
item = self.manifest_item_for_name(name)
|
item = self.manifest_item_for_name(name)
|
||||||
if item is not None:
|
if item is not None:
|
||||||
return
|
return
|
||||||
@ -109,11 +109,27 @@ class Container(object):
|
|||||||
item = manifest.makeelement('{%s}item'%OPF_NS, nsmap={'opf':OPF_NS},
|
item = manifest.makeelement('{%s}item'%OPF_NS, nsmap={'opf':OPF_NS},
|
||||||
href=self.name_to_href(name, posixpath.dirname(self.opf_name)),
|
href=self.name_to_href(name, posixpath.dirname(self.opf_name)),
|
||||||
id=self.generate_manifest_id())
|
id=self.generate_manifest_id())
|
||||||
mt = guess_type(posixpath.basename(name))[0]
|
if not mt:
|
||||||
|
mt = guess_type(posixpath.basename(name))[0]
|
||||||
if not mt:
|
if not mt:
|
||||||
mt = 'application/octest-stream'
|
mt = 'application/octest-stream'
|
||||||
item.set('media-type', mt)
|
item.set('media-type', mt)
|
||||||
manifest.append(item)
|
manifest.append(item)
|
||||||
|
self.fix_tail(item)
|
||||||
|
|
||||||
|
def fix_tail(self, item):
|
||||||
|
'''
|
||||||
|
Designed only to work with self closing elements after item has
|
||||||
|
just been inserted/appended
|
||||||
|
'''
|
||||||
|
parent = item.getparent()
|
||||||
|
idx = parent.index(item)
|
||||||
|
if idx == 0:
|
||||||
|
item.tail = parent.text
|
||||||
|
else:
|
||||||
|
item.tail = parent[idx-1].tail
|
||||||
|
if idx == len(parent)-1:
|
||||||
|
parent[idx-1].tail = parent.text
|
||||||
|
|
||||||
def generate_manifest_id(self):
|
def generate_manifest_id(self):
|
||||||
items = self.opf.xpath('//opf:manifest/opf:item[@id]',
|
items = self.opf.xpath('//opf:manifest/opf:item[@id]',
|
||||||
|
@ -41,27 +41,31 @@ field_metadata = FieldMetadata()
|
|||||||
|
|
||||||
class SafeFormat(TemplateFormatter):
|
class SafeFormat(TemplateFormatter):
|
||||||
|
|
||||||
def get_value(self, key, args, kwargs):
|
def get_value(self, orig_key, args, kwargs):
|
||||||
try:
|
if not orig_key:
|
||||||
key = key.lower()
|
return ''
|
||||||
if key != 'title_sort' and key not in TOP_LEVEL_IDENTIFIERS:
|
orig_key = orig_key.lower()
|
||||||
key = field_metadata.search_term_to_field_key(key)
|
key = orig_key
|
||||||
b = self.book.get_user_metadata(key, False)
|
if key != 'title_sort' and key not in TOP_LEVEL_IDENTIFIERS:
|
||||||
if b and b['datatype'] == 'int' and self.book.get(key, 0) == 0:
|
key = field_metadata.search_term_to_field_key(key)
|
||||||
v = ''
|
if key is None or (self.book and
|
||||||
elif b and b['datatype'] == 'float' and self.book.get(key, 0.0) == 0.0:
|
key not in self.book.all_field_keys()):
|
||||||
v = ''
|
if hasattr(self.book, orig_key):
|
||||||
else:
|
key = orig_key
|
||||||
v = self.book.format_field(key, series_with_index=False)[1]
|
else:
|
||||||
if v is None:
|
raise ValueError(_('Value: unknown field ') + orig_key)
|
||||||
return ''
|
b = self.book.get_user_metadata(key, False)
|
||||||
if v == '':
|
if b and b['datatype'] == 'int' and self.book.get(key, 0) == 0:
|
||||||
return ''
|
v = ''
|
||||||
return v
|
elif b and b['datatype'] == 'float' and self.book.get(key, 0.0) == 0.0:
|
||||||
except:
|
v = ''
|
||||||
if DEBUG:
|
else:
|
||||||
traceback.print_exc()
|
v = self.book.format_field(key, series_with_index=False)[1]
|
||||||
return key
|
if v is None:
|
||||||
|
return ''
|
||||||
|
if v == '':
|
||||||
|
return ''
|
||||||
|
return v
|
||||||
|
|
||||||
composite_formatter = SafeFormat()
|
composite_formatter = SafeFormat()
|
||||||
|
|
||||||
@ -75,7 +79,7 @@ class Metadata(object):
|
|||||||
Metadata from custom columns should be accessed via the get() method,
|
Metadata from custom columns should be accessed via the get() method,
|
||||||
passing in the lookup name for the column, for example: "#mytags".
|
passing in the lookup name for the column, for example: "#mytags".
|
||||||
|
|
||||||
Use the :meth:`is_null` method to test if a filed is null.
|
Use the :meth:`is_null` method to test if a field is null.
|
||||||
|
|
||||||
This object also has functions to format fields into strings.
|
This object also has functions to format fields into strings.
|
||||||
|
|
||||||
@ -106,7 +110,7 @@ class Metadata(object):
|
|||||||
|
|
||||||
def is_null(self, field):
|
def is_null(self, field):
|
||||||
'''
|
'''
|
||||||
Return True if the value of filed is null in this object.
|
Return True if the value of field is null in this object.
|
||||||
'null' means it is unknown or evaluates to False. So a title of
|
'null' means it is unknown or evaluates to False. So a title of
|
||||||
_('Unknown') is null or a language of 'und' is null.
|
_('Unknown') is null or a language of 'und' is null.
|
||||||
|
|
||||||
|
@ -46,6 +46,8 @@ cover_url = XPath("descendant::atom:link[@rel='image']/attribute::href")
|
|||||||
|
|
||||||
def get_details(browser, url, timeout): # {{{
|
def get_details(browser, url, timeout): # {{{
|
||||||
try:
|
try:
|
||||||
|
if Douban.DOUBAN_API_KEY and Douban.DOUBAN_API_KEY != '':
|
||||||
|
url = url + "?apikey=" + Douban.DOUBAN_API_KEY
|
||||||
raw = browser.open_novisit(url, timeout=timeout).read()
|
raw = browser.open_novisit(url, timeout=timeout).read()
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
gc = getattr(e, 'getcode', lambda : -1)
|
gc = getattr(e, 'getcode', lambda : -1)
|
||||||
|
@ -408,6 +408,8 @@ def identify(log, abort, # {{{
|
|||||||
for f in plugin.prefs['ignore_fields']:
|
for f in plugin.prefs['ignore_fields']:
|
||||||
if ':' not in f:
|
if ':' not in f:
|
||||||
setattr(result, f, getattr(dummy, f))
|
setattr(result, f, getattr(dummy, f))
|
||||||
|
if f == 'series':
|
||||||
|
result.series_index = dummy.series_index
|
||||||
result.relevance_in_source = i
|
result.relevance_in_source = i
|
||||||
result.has_cached_cover_url = (plugin.cached_cover_url_is_reliable
|
result.has_cached_cover_url = (plugin.cached_cover_url_is_reliable
|
||||||
and plugin.get_cached_cover_url(result.identifiers) is not
|
and plugin.get_cached_cover_url(result.identifiers) is not
|
||||||
|
@ -120,7 +120,19 @@ class Split(object):
|
|||||||
for i, x in enumerate(page_breaks):
|
for i, x in enumerate(page_breaks):
|
||||||
x.set('id', x.get('id', 'calibre_pb_%d'%i))
|
x.set('id', x.get('id', 'calibre_pb_%d'%i))
|
||||||
id = x.get('id')
|
id = x.get('id')
|
||||||
page_breaks_.append((XPath('//*[@id=%r]'%id),
|
try:
|
||||||
|
xp = XPath('//*[@id="%s"]'%id)
|
||||||
|
except:
|
||||||
|
try:
|
||||||
|
xp = XPath("//*[@id='%s']"%id)
|
||||||
|
except:
|
||||||
|
# The id has both a quote and an apostrophe or some other
|
||||||
|
# Just replace it since I doubt its going to work anywhere else
|
||||||
|
# either
|
||||||
|
id = 'calibre_pb_%d'%i
|
||||||
|
x.set('id', id)
|
||||||
|
xp = XPath('//*[@id=%r]'%id)
|
||||||
|
page_breaks_.append((xp,
|
||||||
x.get('pb_before', False)))
|
x.get('pb_before', False)))
|
||||||
page_break_ids.append(id)
|
page_break_ids.append(id)
|
||||||
|
|
||||||
|
@ -48,8 +48,9 @@ else:
|
|||||||
gprefs.defaults['action-layout-menubar-device'] = ()
|
gprefs.defaults['action-layout-menubar-device'] = ()
|
||||||
gprefs.defaults['action-layout-toolbar'] = (
|
gprefs.defaults['action-layout-toolbar'] = (
|
||||||
'Add Books', 'Edit Metadata', None, 'Convert Books', 'View', None,
|
'Add Books', 'Edit Metadata', None, 'Convert Books', 'View', None,
|
||||||
'Choose Library', 'Donate', None, 'Fetch News', 'Store', 'Save To Disk',
|
'Store', 'Donate', 'Fetch News', 'Help', None,
|
||||||
'Connect Share', None, 'Remove Books', None, 'Help', 'Preferences',
|
'Remove Books', 'Choose Library', 'Save To Disk',
|
||||||
|
'Connect Share', 'Preferences',
|
||||||
)
|
)
|
||||||
gprefs.defaults['action-layout-toolbar-device'] = (
|
gprefs.defaults['action-layout-toolbar-device'] = (
|
||||||
'Add Books', 'Edit Metadata', None, 'Convert Books', 'View',
|
'Add Books', 'Edit Metadata', None, 'Convert Books', 'View',
|
||||||
@ -75,7 +76,7 @@ gprefs.defaults['action-layout-context-menu-device'] = (
|
|||||||
gprefs.defaults['show_splash_screen'] = True
|
gprefs.defaults['show_splash_screen'] = True
|
||||||
gprefs.defaults['toolbar_icon_size'] = 'medium'
|
gprefs.defaults['toolbar_icon_size'] = 'medium'
|
||||||
gprefs.defaults['automerge'] = 'ignore'
|
gprefs.defaults['automerge'] = 'ignore'
|
||||||
gprefs.defaults['toolbar_text'] = 'auto'
|
gprefs.defaults['toolbar_text'] = 'always'
|
||||||
gprefs.defaults['font'] = None
|
gprefs.defaults['font'] = None
|
||||||
gprefs.defaults['tags_browser_partition_method'] = 'first letter'
|
gprefs.defaults['tags_browser_partition_method'] = 'first letter'
|
||||||
gprefs.defaults['tags_browser_collapse_at'] = 100
|
gprefs.defaults['tags_browser_collapse_at'] = 100
|
||||||
|
@ -152,7 +152,8 @@ class DeleteAction(InterfaceAction):
|
|||||||
if not ids:
|
if not ids:
|
||||||
return
|
return
|
||||||
fmts = self._get_selected_formats(
|
fmts = self._get_selected_formats(
|
||||||
'<p>'+_('Choose formats <b>not</b> to be deleted'), ids)
|
'<p>'+_('Choose formats <b>not</b> to be deleted.<p>Note that '
|
||||||
|
'this will never remove all formats from a book.'), ids)
|
||||||
if fmts is None:
|
if fmts is None:
|
||||||
return
|
return
|
||||||
for id in ids:
|
for id in ids:
|
||||||
@ -161,9 +162,12 @@ class DeleteAction(InterfaceAction):
|
|||||||
continue
|
continue
|
||||||
bfmts = set([x.lower() for x in bfmts.split(',')])
|
bfmts = set([x.lower() for x in bfmts.split(',')])
|
||||||
rfmts = bfmts - set(fmts)
|
rfmts = bfmts - set(fmts)
|
||||||
for fmt in rfmts:
|
if bfmts - rfmts:
|
||||||
self.gui.library_view.model().db.remove_format(id, fmt,
|
# Do not delete if it will leave the book with no
|
||||||
index_is_id=True, notify=False)
|
# formats
|
||||||
|
for fmt in rfmts:
|
||||||
|
self.gui.library_view.model().db.remove_format(id, fmt,
|
||||||
|
index_is_id=True, notify=False)
|
||||||
self.gui.library_view.model().refresh_ids(ids)
|
self.gui.library_view.model().refresh_ids(ids)
|
||||||
self.gui.library_view.model().current_changed(self.gui.library_view.currentIndex(),
|
self.gui.library_view.model().current_changed(self.gui.library_view.currentIndex(),
|
||||||
self.gui.library_view.currentIndex())
|
self.gui.library_view.currentIndex())
|
||||||
|
@ -482,6 +482,8 @@ class EditMetadataAction(InterfaceAction):
|
|||||||
if mi.identifiers:
|
if mi.identifiers:
|
||||||
idents.update(mi.identifiers)
|
idents.update(mi.identifiers)
|
||||||
mi.identifiers = idents
|
mi.identifiers = idents
|
||||||
|
if mi.is_null('series'):
|
||||||
|
mi.series_index = None
|
||||||
db.set_metadata(i, mi, commit=False, set_title=set_title,
|
db.set_metadata(i, mi, commit=False, set_title=set_title,
|
||||||
set_authors=set_authors, notify=False)
|
set_authors=set_authors, notify=False)
|
||||||
self.applied_ids.append(i)
|
self.applied_ids.append(i)
|
||||||
|
@ -1294,7 +1294,8 @@ class DeviceMixin(object): # {{{
|
|||||||
self.book_db_uuid_path_map = None
|
self.book_db_uuid_path_map = None
|
||||||
return
|
return
|
||||||
|
|
||||||
if not hasattr(self, 'db_book_uuid_cache'):
|
if not self.device_manager.is_device_connected or \
|
||||||
|
not hasattr(self, 'db_book_uuid_cache'):
|
||||||
return loc
|
return loc
|
||||||
|
|
||||||
if self.book_db_id_cache is None:
|
if self.book_db_id_cache is None:
|
||||||
|
@ -44,7 +44,7 @@ class SelectFormats(QDialog):
|
|||||||
self.setLayout(self._l)
|
self.setLayout(self._l)
|
||||||
self.setWindowTitle(_('Choose formats'))
|
self.setWindowTitle(_('Choose formats'))
|
||||||
self._m = QLabel(msg)
|
self._m = QLabel(msg)
|
||||||
self._m.setWordWrap = True
|
self._m.setWordWrap(True)
|
||||||
self._l.addWidget(self._m)
|
self._l.addWidget(self._m)
|
||||||
self.formats = Formats(fmt_list)
|
self.formats = Formats(fmt_list)
|
||||||
self.fview = QListView(self)
|
self.fview = QListView(self)
|
||||||
|
@ -11,6 +11,7 @@ from PyQt4.Qt import (Qt, QDialog, QDialogButtonBox, QSyntaxHighlighter,
|
|||||||
|
|
||||||
from calibre.gui2.dialogs.template_dialog_ui import Ui_TemplateDialog
|
from calibre.gui2.dialogs.template_dialog_ui import Ui_TemplateDialog
|
||||||
from calibre.utils.formatter_functions import formatter_functions
|
from calibre.utils.formatter_functions import formatter_functions
|
||||||
|
from calibre.ebooks.metadata.book.base import composite_formatter
|
||||||
|
|
||||||
class ParenPosition:
|
class ParenPosition:
|
||||||
|
|
||||||
@ -194,10 +195,13 @@ class TemplateHighlighter(QSyntaxHighlighter):
|
|||||||
|
|
||||||
class TemplateDialog(QDialog, Ui_TemplateDialog):
|
class TemplateDialog(QDialog, Ui_TemplateDialog):
|
||||||
|
|
||||||
def __init__(self, parent, text):
|
def __init__(self, parent, text, mi):
|
||||||
QDialog.__init__(self, parent)
|
QDialog.__init__(self, parent)
|
||||||
Ui_TemplateDialog.__init__(self)
|
Ui_TemplateDialog.__init__(self)
|
||||||
self.setupUi(self)
|
self.setupUi(self)
|
||||||
|
|
||||||
|
self.mi = mi
|
||||||
|
|
||||||
# Remove help icon on title bar
|
# Remove help icon on title bar
|
||||||
icon = self.windowIcon()
|
icon = self.windowIcon()
|
||||||
self.setWindowFlags(self.windowFlags()&(~Qt.WindowContextHelpButtonHint))
|
self.setWindowFlags(self.windowFlags()&(~Qt.WindowContextHelpButtonHint))
|
||||||
@ -233,12 +237,16 @@ class TemplateDialog(QDialog, Ui_TemplateDialog):
|
|||||||
self.function.addItems(func_names)
|
self.function.addItems(func_names)
|
||||||
self.function.setCurrentIndex(0)
|
self.function.setCurrentIndex(0)
|
||||||
self.function.currentIndexChanged[str].connect(self.function_changed)
|
self.function.currentIndexChanged[str].connect(self.function_changed)
|
||||||
|
self.textbox_changed()
|
||||||
|
|
||||||
def textbox_changed(self):
|
def textbox_changed(self):
|
||||||
cur_text = unicode(self.textbox.toPlainText())
|
cur_text = unicode(self.textbox.toPlainText())
|
||||||
if self.last_text != cur_text:
|
if self.last_text != cur_text:
|
||||||
self.last_text = cur_text
|
self.last_text = cur_text
|
||||||
self.highlighter.regenerate_paren_positions()
|
self.highlighter.regenerate_paren_positions()
|
||||||
|
self.template_value.setText(
|
||||||
|
composite_formatter.safe_format(cur_text, self.mi,
|
||||||
|
_('EXCEPTION: '), self.mi))
|
||||||
|
|
||||||
def text_cursor_changed(self):
|
def text_cursor_changed(self):
|
||||||
cursor = self.textbox.textCursor()
|
cursor = self.textbox.textCursor()
|
||||||
|
@ -23,19 +23,39 @@
|
|||||||
<item>
|
<item>
|
||||||
<widget class="QPlainTextEdit" name="textbox"/>
|
<widget class="QPlainTextEdit" name="textbox"/>
|
||||||
</item>
|
</item>
|
||||||
<item>
|
|
||||||
<widget class="QDialogButtonBox" name="buttonBox">
|
|
||||||
<property name="orientation">
|
|
||||||
<enum>Qt::Horizontal</enum>
|
|
||||||
</property>
|
|
||||||
<property name="standardButtons">
|
|
||||||
<set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set>
|
|
||||||
</property>
|
|
||||||
</widget>
|
|
||||||
</item>
|
|
||||||
<item>
|
<item>
|
||||||
<layout class="QGridLayout" name="gridLayout">
|
<layout class="QGridLayout" name="gridLayout">
|
||||||
<item row="0" column="0">
|
<item row="0" column="0">
|
||||||
|
<widget class="QLabel">
|
||||||
|
<property name="text">
|
||||||
|
<string>Template value:</string>
|
||||||
|
</property>
|
||||||
|
<property name="buddy">
|
||||||
|
<cstring>template_value</cstring>
|
||||||
|
</property>
|
||||||
|
<property name="toolTip">
|
||||||
|
<string>The value the of the template using the current book in the library view</string>
|
||||||
|
</property>
|
||||||
|
</widget>
|
||||||
|
</item>
|
||||||
|
<item row="0" column="1">
|
||||||
|
<widget class="QLineEdit" name="template_value">
|
||||||
|
<property name="readOnly">
|
||||||
|
<bool>true</bool>
|
||||||
|
</property>
|
||||||
|
</widget>
|
||||||
|
</item>
|
||||||
|
<item row="1" column="1">
|
||||||
|
<widget class="QDialogButtonBox" name="buttonBox">
|
||||||
|
<property name="orientation">
|
||||||
|
<enum>Qt::Horizontal</enum>
|
||||||
|
</property>
|
||||||
|
<property name="standardButtons">
|
||||||
|
<set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set>
|
||||||
|
</property>
|
||||||
|
</widget>
|
||||||
|
</item>
|
||||||
|
<item row="2" column="0">
|
||||||
<widget class="QLabel" name="label">
|
<widget class="QLabel" name="label">
|
||||||
<property name="text">
|
<property name="text">
|
||||||
<string>Function &name:</string>
|
<string>Function &name:</string>
|
||||||
@ -45,10 +65,10 @@
|
|||||||
</property>
|
</property>
|
||||||
</widget>
|
</widget>
|
||||||
</item>
|
</item>
|
||||||
<item row="0" column="1">
|
<item row="2" column="1">
|
||||||
<widget class="QComboBox" name="function"/>
|
<widget class="QComboBox" name="function"/>
|
||||||
</item>
|
</item>
|
||||||
<item row="1" column="0">
|
<item row="3" column="0">
|
||||||
<widget class="QLabel" name="label_2">
|
<widget class="QLabel" name="label_2">
|
||||||
<property name="text">
|
<property name="text">
|
||||||
<string>&Documentation:</string>
|
<string>&Documentation:</string>
|
||||||
@ -61,7 +81,7 @@
|
|||||||
</property>
|
</property>
|
||||||
</widget>
|
</widget>
|
||||||
</item>
|
</item>
|
||||||
<item row="2" column="0">
|
<item row="4" column="0">
|
||||||
<widget class="QLabel" name="label_3">
|
<widget class="QLabel" name="label_3">
|
||||||
<property name="text">
|
<property name="text">
|
||||||
<string>Python &code:</string>
|
<string>Python &code:</string>
|
||||||
@ -74,7 +94,7 @@
|
|||||||
</property>
|
</property>
|
||||||
</widget>
|
</widget>
|
||||||
</item>
|
</item>
|
||||||
<item row="1" column="1">
|
<item row="3" column="1">
|
||||||
<widget class="QPlainTextEdit" name="documentation">
|
<widget class="QPlainTextEdit" name="documentation">
|
||||||
<property name="maximumSize">
|
<property name="maximumSize">
|
||||||
<size>
|
<size>
|
||||||
@ -84,7 +104,7 @@
|
|||||||
</property>
|
</property>
|
||||||
</widget>
|
</widget>
|
||||||
</item>
|
</item>
|
||||||
<item row="2" column="1">
|
<item row="4" column="1">
|
||||||
<widget class="QPlainTextEdit" name="source_code"/>
|
<widget class="QPlainTextEdit" name="source_code"/>
|
||||||
</item>
|
</item>
|
||||||
</layout>
|
</layout>
|
||||||
|
@ -5,12 +5,17 @@ __license__ = 'GPL v3'
|
|||||||
__copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'
|
__copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'
|
||||||
__docformat__ = 'restructuredtext en'
|
__docformat__ = 'restructuredtext en'
|
||||||
|
|
||||||
from PyQt4.Qt import (QLineEdit, QDialog, QGridLayout, QLabel,
|
from functools import partial
|
||||||
QDialogButtonBox, QColor, QComboBox, QIcon)
|
from collections import defaultdict
|
||||||
|
|
||||||
|
from PyQt4.Qt import (Qt, QLineEdit, QDialog, QGridLayout, QLabel, QCheckBox,
|
||||||
|
QIcon, QDialogButtonBox, QColor, QComboBox, QPushButton)
|
||||||
|
|
||||||
|
from calibre.ebooks.metadata.book.base import composite_formatter
|
||||||
from calibre.gui2.dialogs.template_dialog import TemplateDialog
|
from calibre.gui2.dialogs.template_dialog import TemplateDialog
|
||||||
from calibre.gui2.complete import MultiCompleteLineEdit
|
from calibre.gui2.complete import MultiCompleteLineEdit
|
||||||
from calibre.gui2 import error_dialog
|
from calibre.gui2 import error_dialog
|
||||||
|
from calibre.utils.icu import sort_key
|
||||||
|
|
||||||
class TemplateLineEditor(QLineEdit):
|
class TemplateLineEditor(QLineEdit):
|
||||||
|
|
||||||
@ -21,112 +26,514 @@ class TemplateLineEditor(QLineEdit):
|
|||||||
def __init__(self, parent):
|
def __init__(self, parent):
|
||||||
QLineEdit.__init__(self, parent)
|
QLineEdit.__init__(self, parent)
|
||||||
self.tags = None
|
self.tags = None
|
||||||
|
self.mi = None
|
||||||
|
self.txt = None
|
||||||
|
|
||||||
def set_tags(self, tags):
|
def set_mi(self, mi):
|
||||||
self.tags = tags
|
self.mi = mi
|
||||||
|
|
||||||
|
def set_db(self, db):
|
||||||
|
self.db = db
|
||||||
|
|
||||||
def contextMenuEvent(self, event):
|
def contextMenuEvent(self, event):
|
||||||
menu = self.createStandardContextMenu()
|
menu = self.createStandardContextMenu()
|
||||||
menu.addSeparator()
|
menu.addSeparator()
|
||||||
|
|
||||||
|
action_clear_field = menu.addAction(_('Remove any template from the box'))
|
||||||
|
action_clear_field.triggered.connect(self.clear_field)
|
||||||
action_open_editor = menu.addAction(_('Open Template Editor'))
|
action_open_editor = menu.addAction(_('Open Template Editor'))
|
||||||
action_open_editor.triggered.connect(self.open_editor)
|
action_open_editor.triggered.connect(self.open_editor)
|
||||||
if self.tags:
|
|
||||||
action_tag_wizard = menu.addAction(_('Open Tag Wizard'))
|
|
||||||
action_tag_wizard.triggered.connect(self.tag_wizard)
|
|
||||||
menu.exec_(event.globalPos())
|
menu.exec_(event.globalPos())
|
||||||
|
|
||||||
|
def clear_field(self):
|
||||||
|
self.txt = None
|
||||||
|
self.setText('')
|
||||||
|
self.setReadOnly(False)
|
||||||
|
self.setStyleSheet('TemplateLineEditor { color: black }')
|
||||||
|
|
||||||
def open_editor(self):
|
def open_editor(self):
|
||||||
t = TemplateDialog(self, self.text())
|
if self.txt:
|
||||||
|
t = TemplateDialog(self, self.txt, self.mi)
|
||||||
|
else:
|
||||||
|
t = TemplateDialog(self, self.text(), self.mi)
|
||||||
t.setWindowTitle(_('Edit template'))
|
t.setWindowTitle(_('Edit template'))
|
||||||
if t.exec_():
|
if t.exec_():
|
||||||
|
self.txt = None
|
||||||
self.setText(t.textbox.toPlainText())
|
self.setText(t.textbox.toPlainText())
|
||||||
|
|
||||||
|
def enable_wizard_button(self, txt):
|
||||||
|
if not txt or txt.startswith('program:\n#tag wizard'):
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
def setText(self, txt):
|
||||||
|
txt = unicode(txt)
|
||||||
|
if txt and txt.startswith('program:\n#tag wizard'):
|
||||||
|
self.txt = txt
|
||||||
|
self.setReadOnly(True)
|
||||||
|
QLineEdit.setText(self, '')
|
||||||
|
QLineEdit.setText(self, _('Template generated by the wizard'))
|
||||||
|
self.setStyleSheet('TemplateLineEditor { color: gray }')
|
||||||
|
else:
|
||||||
|
QLineEdit.setText(self, txt)
|
||||||
|
|
||||||
def tag_wizard(self):
|
def tag_wizard(self):
|
||||||
txt = unicode(self.text())
|
txt = unicode(self.text())
|
||||||
if txt and not txt.startswith('program:\n#tag wizard'):
|
if txt and not self.txt:
|
||||||
error_dialog(self, _('Invalid text'),
|
error_dialog(self, _('Invalid text'),
|
||||||
_('The text in the box was not generated by this wizard'),
|
_('The text in the box was not generated by this wizard'),
|
||||||
show=True, show_copy_button=False)
|
show=True, show_copy_button=False)
|
||||||
return
|
return
|
||||||
d = TagWizard(self, self.tags, unicode(self.text()))
|
d = TagWizard(self, self.db, unicode(self.txt), self.mi)
|
||||||
if d.exec_():
|
if d.exec_():
|
||||||
self.setText(d.template)
|
self.setText(d.template)
|
||||||
|
|
||||||
|
def text(self):
|
||||||
|
if self.txt:
|
||||||
|
return self.txt
|
||||||
|
return QLineEdit.text(self)
|
||||||
|
|
||||||
class TagWizard(QDialog):
|
class TagWizard(QDialog):
|
||||||
|
|
||||||
def __init__(self, parent, tags, txt):
|
text_template = (" strcmp(field('{f}'), '{v}', '{ltv}', '{eqv}', '{gtv}')", True)
|
||||||
|
text_empty_template = (" test(field('{f}'), '{fv}', '{tv}')", False)
|
||||||
|
text_re_template = (" contains(field('{f}'), '{v}', '{tv}', '{fv}')", False)
|
||||||
|
|
||||||
|
templates = {
|
||||||
|
'text.mult' : (" str_in_list(field('{f}'), '{mult}', '{v}', '{tv}', '{fv}')", False),
|
||||||
|
'text.mult.re' : (" in_list(field('{f}'), '{mult}', '^{v}$', '{tv}', '{fv}')", False),
|
||||||
|
'text.mult.empty' : (" test(field('{f}'), '{fv}', '{tv}')", False),
|
||||||
|
'text' : text_template,
|
||||||
|
'text.re' : text_re_template,
|
||||||
|
'text.empty' : text_empty_template,
|
||||||
|
'rating' : (" cmp(raw_field('{f}'), '{v}', '{ltv}', '{eqv}', '{gtv}')", True),
|
||||||
|
'rating.empty' : text_empty_template,
|
||||||
|
'int' : (" cmp(raw_field('{f}'), '{v}', '{ltv}', '{eqv}', '{gtv}')", True),
|
||||||
|
'int.empty' : text_empty_template,
|
||||||
|
'float' : (" cmp(raw_field('{f}'), '{v}', '{ltv}', '{eqv}', '{gtv}')", True),
|
||||||
|
'float.empty' : text_empty_template,
|
||||||
|
'bool' : (" strcmp(field('{f}'), '{v}', '{ltv}', '{eqv}', '{gtv}')", True),
|
||||||
|
'bool.empty' : text_empty_template,
|
||||||
|
'datetime' : (" strcmp(format_date(raw_field('{f}'), 'yyyyMMdd'), format_date('{v}', 'yyyyMMdd'), '{ltv}', '{eqv}', '{gtv}')", True),
|
||||||
|
'datetime.empty' : text_empty_template,
|
||||||
|
'series' : text_template,
|
||||||
|
'series.re' : text_re_template,
|
||||||
|
'series.empty' : text_empty_template,
|
||||||
|
'composite' : text_template,
|
||||||
|
'composite.re' : text_re_template,
|
||||||
|
'composite.empty' : text_empty_template,
|
||||||
|
'enumeration' : text_template,
|
||||||
|
'enumeration.re' : text_re_template,
|
||||||
|
'enumeration.empty' : text_empty_template,
|
||||||
|
'comments' : text_template,
|
||||||
|
'comments.re' : text_re_template,
|
||||||
|
'comments.empty' : text_empty_template,
|
||||||
|
}
|
||||||
|
|
||||||
|
relationals = ('=', '!=', '<', '>', '<=', '>=')
|
||||||
|
relational_truth_vals = {
|
||||||
|
'=': ('', '1', ''),
|
||||||
|
'!=': ('1', '', '1'),
|
||||||
|
'<': ('1', '', ''),
|
||||||
|
'>': ('', '', '1'),
|
||||||
|
'<=': ('1', '1', ''),
|
||||||
|
'>=': ('', '1', '1'),
|
||||||
|
}
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def uses_this_wizard(txt):
|
||||||
|
if not txt or txt.startswith('program:\n#tag wizard'):
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
def __init__(self, parent, db, txt, mi):
|
||||||
QDialog.__init__(self, parent)
|
QDialog.__init__(self, parent)
|
||||||
self.setWindowTitle(_('Tag Wizard'))
|
self.setWindowTitle(_('Coloring Wizard'))
|
||||||
self.setWindowIcon(QIcon(I('wizard.png')))
|
self.setWindowIcon(QIcon(I('wizard.png')))
|
||||||
|
|
||||||
self.tags = tags
|
self.mi = mi
|
||||||
|
|
||||||
|
self.columns = []
|
||||||
|
self.completion_values = defaultdict(dict)
|
||||||
|
for k in db.all_field_keys():
|
||||||
|
m = db.metadata_for_field(k)
|
||||||
|
if k.endswith('_index') or (
|
||||||
|
m['kind'] == 'field' and m['name'] and
|
||||||
|
k not in ('ondevice', 'path', 'size', 'sort')):
|
||||||
|
self.columns.append(k)
|
||||||
|
self.completion_values[k]['dt'] = m['datatype']
|
||||||
|
if m['is_custom']:
|
||||||
|
if m['datatype'] in ('int', 'float'):
|
||||||
|
self.completion_values[k]['v'] = []
|
||||||
|
elif m['datatype'] == 'bool':
|
||||||
|
self.completion_values[k]['v'] = [_('Yes'), _('No')]
|
||||||
|
else:
|
||||||
|
self.completion_values[k]['v'] = db.all_custom(m['label'])
|
||||||
|
elif k == 'tags':
|
||||||
|
self.completion_values[k]['v'] = db.all_tags()
|
||||||
|
elif k == 'formats':
|
||||||
|
self.completion_values[k]['v'] = db.all_formats()
|
||||||
|
else:
|
||||||
|
if k in ('publisher'):
|
||||||
|
ck = k + 's'
|
||||||
|
else:
|
||||||
|
ck = k
|
||||||
|
f = getattr(db, 'all_' + ck, None)
|
||||||
|
if f:
|
||||||
|
if k == 'authors':
|
||||||
|
self.completion_values[k]['v'] = [v[1].\
|
||||||
|
replace('|', ',') for v in f()]
|
||||||
|
else:
|
||||||
|
self.completion_values[k]['v'] = [v[1] for v in f()]
|
||||||
|
else:
|
||||||
|
self.completion_values[k]['v'] = []
|
||||||
|
|
||||||
|
if k in self.completion_values:
|
||||||
|
if k == 'authors':
|
||||||
|
mult = '&'
|
||||||
|
else:
|
||||||
|
mult = ',' if m['is_multiple'] == '|' else m['is_multiple']
|
||||||
|
self.completion_values[k]['m'] = mult
|
||||||
|
|
||||||
|
self.columns.sort(key=sort_key)
|
||||||
|
self.columns.insert(0, '')
|
||||||
|
|
||||||
l = QGridLayout()
|
l = QGridLayout()
|
||||||
self.setLayout(l)
|
self.setLayout(l)
|
||||||
l.setColumnStretch(0, 1)
|
l.setColumnStretch(2, 10)
|
||||||
l.setColumnMinimumWidth(0, 300)
|
l.setColumnMinimumWidth(5, 300)
|
||||||
l.addWidget(QLabel(_('Tags (more than one per box permitted)')), 0, 0, 1, 1)
|
|
||||||
l.addWidget(QLabel(_('Color')), 0, 1, 1, 1)
|
h = QLabel(_('And'))
|
||||||
self.tagboxes = []
|
h.setToolTip('<p>' +
|
||||||
self.colorboxes = []
|
_('Set this box to indicate that the two conditions must both '
|
||||||
|
'be true to use the color. For example, you '
|
||||||
|
'can check if two tags are present, if the book has a tag '
|
||||||
|
'and a #read custom column is checked, or if a book has '
|
||||||
|
'some tag and has a particular format.'))
|
||||||
|
l.addWidget(h, 0, 0, 1, 1)
|
||||||
|
|
||||||
|
h = QLabel(_('Column'))
|
||||||
|
h.setAlignment(Qt.AlignCenter)
|
||||||
|
l.addWidget(h, 0, 1, 1, 1)
|
||||||
|
|
||||||
|
h = QLabel(_('is'))
|
||||||
|
h.setAlignment(Qt.AlignCenter)
|
||||||
|
l.addWidget(h, 0, 2, 1, 1)
|
||||||
|
|
||||||
|
h = QLabel(_('op'))
|
||||||
|
h.setToolTip('<p>' +
|
||||||
|
_('Use this box to tell what comparison operation to use. Some '
|
||||||
|
'comparisons cannot be used with certain options. For example, '
|
||||||
|
'if regular expressions are used, only equals and not equals '
|
||||||
|
'are valid.') + '</p>')
|
||||||
|
h.setAlignment(Qt.AlignCenter)
|
||||||
|
l.addWidget(h, 0, 3, 1, 1)
|
||||||
|
|
||||||
|
c = QLabel(_('empty'))
|
||||||
|
c.setToolTip('<p>' +
|
||||||
|
_('Check this box to check if the column is empty') + '</p>')
|
||||||
|
l.addWidget(c, 0, 4, 1, 1)
|
||||||
|
|
||||||
|
h = QLabel(_('Values'))
|
||||||
|
h.setAlignment(Qt.AlignCenter)
|
||||||
|
h.setToolTip('<p>' +
|
||||||
|
_('You can enter more than one value per box, separated by commas. '
|
||||||
|
'The comparison ignores letter case. Special note: authors are '
|
||||||
|
'separated by ampersands (&).<br>'
|
||||||
|
'A value can be a regular expression. Check the box to turn '
|
||||||
|
'them on. When using regular expressions, note that the wizard '
|
||||||
|
'puts anchors (^ and $) around the expression, so you '
|
||||||
|
'must ensure your expression matches from the beginning '
|
||||||
|
'to the end of the column/value you are checking.<br>'
|
||||||
|
'Regular expression examples:') + '<ul>' +
|
||||||
|
_('<li><code><b>.*</b></code> matches anything in the column.</li>'
|
||||||
|
'<li><code><b>A.*</b></code> matches anything beginning with A</li>'
|
||||||
|
'<li><code><b>.*mystery.*</b></code> matches anything containing '
|
||||||
|
'the word "mystery"</li>') + '</ul></p>')
|
||||||
|
l.addWidget(h , 0, 5, 1, 1)
|
||||||
|
|
||||||
|
c = QLabel(_('is RE'))
|
||||||
|
c.setToolTip('<p>' +
|
||||||
|
_('Check this box if the values box contains regular expressions') + '</p>')
|
||||||
|
l.addWidget(c, 0, 6, 1, 1)
|
||||||
|
|
||||||
|
c = QLabel(_('color'))
|
||||||
|
c.setAlignment(Qt.AlignCenter)
|
||||||
|
c.setToolTip('<p>' +
|
||||||
|
_('Use this color if the column matches the tests.') + '</p>')
|
||||||
|
l.addWidget(c, 0, 7, 1, 1)
|
||||||
|
|
||||||
|
self.andboxes = []
|
||||||
|
self.opboxes = []
|
||||||
|
self.tagboxes = []
|
||||||
|
self.colorboxes = []
|
||||||
|
self.reboxes = []
|
||||||
|
self.colboxes = []
|
||||||
|
self.emptyboxes = []
|
||||||
|
|
||||||
self.colors = [unicode(s) for s in list(QColor.colorNames())]
|
self.colors = [unicode(s) for s in list(QColor.colorNames())]
|
||||||
self.colors.insert(0, '')
|
self.colors.insert(0, '')
|
||||||
for i in range(0, 10):
|
|
||||||
tb = MultiCompleteLineEdit(self)
|
def create_widget(klass, box, layout, row, col, items,
|
||||||
tb.set_separator(', ')
|
align=Qt.AlignCenter, rowspan=False):
|
||||||
tb.update_items_cache(self.tags)
|
w = klass(self)
|
||||||
self.tagboxes.append(tb)
|
if box is not None:
|
||||||
l.addWidget(tb, i+1, 0, 1, 1)
|
box.append(w)
|
||||||
cb = QComboBox(self)
|
if rowspan:
|
||||||
cb.addItems(self.colors)
|
layout.addWidget(w, row, col, 2, 1, alignment=Qt.Alignment(align))
|
||||||
self.colorboxes.append(cb)
|
else:
|
||||||
l.addWidget(cb, i+1, 1, 1, 1)
|
layout.addWidget(w, row, col, 1, 1, alignment=Qt.Alignment(align))
|
||||||
|
if items:
|
||||||
|
w.addItems(items)
|
||||||
|
return w
|
||||||
|
|
||||||
|
maxlines = 10
|
||||||
|
for i in range(1, maxlines+1):
|
||||||
|
w = create_widget(QCheckBox, self.andboxes, l, i, 0, None, rowspan=True)
|
||||||
|
w.stateChanged.connect(partial(self.and_box_changed, line=i-1))
|
||||||
|
if i == maxlines:
|
||||||
|
# last box is invisible
|
||||||
|
w.setVisible(False)
|
||||||
|
|
||||||
|
w = create_widget(QComboBox, self.colboxes, l, i, 1, self.columns)
|
||||||
|
w.currentIndexChanged[str].connect(partial(self.column_changed, line=i-1))
|
||||||
|
|
||||||
|
w = QLabel(self)
|
||||||
|
w.setText(_('is'))
|
||||||
|
l.addWidget(w, i, 2, 1, 1)
|
||||||
|
|
||||||
|
w = create_widget(QComboBox, self.opboxes, l, i, 3, None)
|
||||||
|
w.setMaximumWidth(40)
|
||||||
|
|
||||||
|
w = create_widget(QCheckBox, self.emptyboxes, l, i, 4, None)
|
||||||
|
w.stateChanged.connect(partial(self.empty_box_changed, line=i-1))
|
||||||
|
|
||||||
|
create_widget(MultiCompleteLineEdit, self.tagboxes, l, i, 5, None, align=0)
|
||||||
|
|
||||||
|
w = create_widget(QCheckBox, self.reboxes, l, i, 6, None)
|
||||||
|
w.stateChanged.connect(partial(self.re_box_changed, line=i-1))
|
||||||
|
|
||||||
|
create_widget(QComboBox, self.colorboxes, l, i, 7, self.colors)
|
||||||
|
|
||||||
|
w = create_widget(QLabel, None, l, maxlines+1, 5, None)
|
||||||
|
w.setText(_('If none of the tests match, set the color to'))
|
||||||
|
self.elsebox = create_widget(QComboBox, None, l, maxlines+1, 7, self.colors)
|
||||||
|
self.elsebox.setToolTip('<p>' +
|
||||||
|
_('If this box contains a color, it will be used if none '
|
||||||
|
'of the above rules match.') + '</p>')
|
||||||
|
|
||||||
if txt:
|
if txt:
|
||||||
lines = txt.split('\n')[3:]
|
lines = txt.split('\n')[3:]
|
||||||
i = 0
|
i = 0
|
||||||
for line in lines:
|
for line in lines:
|
||||||
if line.startswith('#'):
|
if line.startswith('#'):
|
||||||
t,c = line[1:].split(':|:')
|
vals = line[1:].split(':|:')
|
||||||
|
if len(vals) == 1 and line.startswith('#else:'):
|
||||||
|
try:
|
||||||
|
self.elsebox.setCurrentIndex(self.elsebox.findText(line[6:]))
|
||||||
|
except:
|
||||||
|
pass
|
||||||
|
continue
|
||||||
|
if len(vals) == 2:
|
||||||
|
t, c = vals
|
||||||
|
f = 'tags'
|
||||||
|
a = re = e = 0
|
||||||
|
op = '='
|
||||||
|
else:
|
||||||
|
t,c,f,re,a,op,e = vals
|
||||||
try:
|
try:
|
||||||
self.colorboxes[i].setCurrentIndex(self.colorboxes[i].findText(c))
|
self.colboxes[i].setCurrentIndex(self.colboxes[i].findText(f))
|
||||||
|
self.colorboxes[i].setCurrentIndex(
|
||||||
|
self.colorboxes[i].findText(c))
|
||||||
self.tagboxes[i].setText(t)
|
self.tagboxes[i].setText(t)
|
||||||
|
self.reboxes[i].setChecked(re == '2')
|
||||||
|
self.emptyboxes[i].setChecked(e == '2')
|
||||||
|
self.andboxes[i].setChecked(a == '2')
|
||||||
|
self.opboxes[i].setCurrentIndex(self.opboxes[i].findText(op))
|
||||||
|
i += 1
|
||||||
except:
|
except:
|
||||||
|
import traceback
|
||||||
|
traceback.print_exc()
|
||||||
pass
|
pass
|
||||||
i += 1
|
|
||||||
|
w = QLabel(_('Preview'))
|
||||||
|
l.addWidget(w, 99, 1, 1, 1)
|
||||||
|
w = self.test_box = QLineEdit(self)
|
||||||
|
w.setReadOnly(True)
|
||||||
|
l.addWidget(w, 99, 2, 1, 5)
|
||||||
|
w = QPushButton(_('Test'))
|
||||||
|
w.setToolTip('<p>' +
|
||||||
|
_('Press this button to see what color this template will '
|
||||||
|
'produce for the book that was selected when you '
|
||||||
|
'entered the preferences dialog.'))
|
||||||
|
l.addWidget(w, 99, 7, 1, 1)
|
||||||
|
w.clicked.connect(self.preview)
|
||||||
|
|
||||||
bb = QDialogButtonBox(QDialogButtonBox.Ok|QDialogButtonBox.Cancel, parent=self)
|
bb = QDialogButtonBox(QDialogButtonBox.Ok|QDialogButtonBox.Cancel, parent=self)
|
||||||
l.addWidget(bb, 100, 1, 1, 1)
|
l.addWidget(bb, 100, 5, 1, 3)
|
||||||
bb.accepted.connect(self.accepted)
|
bb.accepted.connect(self.accepted)
|
||||||
bb.rejected.connect(self.reject)
|
bb.rejected.connect(self.reject)
|
||||||
self.template = ''
|
self.template = ''
|
||||||
|
|
||||||
def accepted(self):
|
def preview(self):
|
||||||
|
if not self.generate_program():
|
||||||
|
return
|
||||||
|
t = composite_formatter.safe_format(self.template, self.mi,
|
||||||
|
_('EXCEPTION'), self.mi)
|
||||||
|
self.test_box.setText(t)
|
||||||
|
|
||||||
|
def generate_program(self):
|
||||||
res = ("program:\n#tag wizard -- do not directly edit\n"
|
res = ("program:\n#tag wizard -- do not directly edit\n"
|
||||||
" t = field('tags');\n first_non_empty(\n")
|
" first_non_empty(\n")
|
||||||
lines = []
|
lines = []
|
||||||
for tb, cb in zip(self.tagboxes, self.colorboxes):
|
was_and = had_line = False
|
||||||
tags = [t.strip() for t in unicode(tb.text()).split(',') if t.strip()]
|
|
||||||
tags = '$|^'.join(tags)
|
line = 0
|
||||||
c = unicode(cb.currentText()).strip()
|
for tb, cb, fb, reb, ab, ob, eb in zip(
|
||||||
if not tags or not c:
|
self.tagboxes, self.colorboxes, self.colboxes,
|
||||||
|
self.reboxes, self.andboxes, self.opboxes, self.emptyboxes):
|
||||||
|
f = unicode(fb.currentText())
|
||||||
|
if not f:
|
||||||
continue
|
continue
|
||||||
if c not in self.colors:
|
m = self.completion_values[f]['m']
|
||||||
error_dialog(self, _('Invalid color'),
|
dt = self.completion_values[f]['dt']
|
||||||
_('The color {0} is not valid').format(c),
|
c = unicode(cb.currentText()).strip()
|
||||||
|
re = reb.checkState()
|
||||||
|
a = ab.checkState()
|
||||||
|
op = unicode(ob.currentText())
|
||||||
|
e = eb.checkState()
|
||||||
|
line += 1
|
||||||
|
|
||||||
|
if m:
|
||||||
|
tags = [t.strip() for t in unicode(tb.text()).split(m) if t.strip()]
|
||||||
|
if re == 2:
|
||||||
|
tags = '$|^'.join(tags)
|
||||||
|
else:
|
||||||
|
tags = m.join(tags)
|
||||||
|
if m == '&':
|
||||||
|
tags = tags.replace(',', '|')
|
||||||
|
else:
|
||||||
|
tags = unicode(tb.text()).strip()
|
||||||
|
|
||||||
|
if (tags or f) and not ((tags or e) and f and (a == 2 or c)):
|
||||||
|
error_dialog(self, _('Invalid line'),
|
||||||
|
_('Line number {0} is not valid').format(line),
|
||||||
show=True, show_copy_button=False)
|
show=True, show_copy_button=False)
|
||||||
return False
|
return False
|
||||||
lines.append(" in_list(t, ',', '^{0}$', '{1}', '')".format(tags, c))
|
|
||||||
res += ',\n'.join(lines)
|
if not was_and:
|
||||||
|
if had_line:
|
||||||
|
lines[-1] += ','
|
||||||
|
had_line = True
|
||||||
|
lines.append(" test(and(")
|
||||||
|
else:
|
||||||
|
lines[-1] += ','
|
||||||
|
|
||||||
|
key = dt + ('.mult' if m else '') + ('.empty' if e else '') + ('.re' if re else '')
|
||||||
|
tval = '1' if op == '=' else ''
|
||||||
|
fval = '' if op == '=' else '1'
|
||||||
|
template, is_relational = self.templates[key]
|
||||||
|
if is_relational:
|
||||||
|
ltv, eqv, gtv = self.relational_truth_vals[op]
|
||||||
|
else:
|
||||||
|
ltv, eqv, gtv = (None, None, None)
|
||||||
|
lines.append(template.format(v=tags, f=f, tv=tval, fv=fval, mult=m,
|
||||||
|
ltv=ltv, eqv=eqv, gtv=gtv))
|
||||||
|
|
||||||
|
if a == 2:
|
||||||
|
was_and = True
|
||||||
|
else:
|
||||||
|
was_and = False
|
||||||
|
lines.append(" ), '{0}', '')".format(c))
|
||||||
|
|
||||||
|
res += '\n'.join(lines)
|
||||||
|
else_txt = unicode(self.elsebox.currentText())
|
||||||
|
if else_txt:
|
||||||
|
res += ",\n '" + else_txt + "'"
|
||||||
res += ')\n'
|
res += ')\n'
|
||||||
self.template = res
|
self.template = res
|
||||||
res = ''
|
res = ''
|
||||||
for tb, cb in zip(self.tagboxes, self.colorboxes):
|
for tb, cb, fb, reb, ab, ob, eb in zip(
|
||||||
|
self.tagboxes, self.colorboxes, self.colboxes,
|
||||||
|
self.reboxes, self.andboxes, self.opboxes, self.emptyboxes):
|
||||||
t = unicode(tb.text()).strip()
|
t = unicode(tb.text()).strip()
|
||||||
if t.endswith(','):
|
if t.endswith(','):
|
||||||
t = t[:-1]
|
t = t[:-1]
|
||||||
c = unicode(cb.currentText()).strip()
|
c = unicode(cb.currentText()).strip()
|
||||||
if t and c:
|
f = unicode(fb.currentText())
|
||||||
res += '#' + t + ':|:' + c + '\n'
|
re = unicode(reb.checkState())
|
||||||
|
a = unicode(ab.checkState())
|
||||||
|
op = unicode(ob.currentText())
|
||||||
|
e = unicode(eb.checkState())
|
||||||
|
if f and (t or e) and (a == '2' or c):
|
||||||
|
res += '#' + t + ':|:' + c + ':|:' + f + ':|:' + re + ':|:' + \
|
||||||
|
a + ':|:' + op + ':|:' + e + '\n'
|
||||||
|
res += '#else:' + else_txt + '\n'
|
||||||
self.template += res
|
self.template += res
|
||||||
self.accept()
|
return True
|
||||||
|
|
||||||
|
def column_changed(self, s, line=None):
|
||||||
|
k = unicode(s)
|
||||||
|
valbox = self.tagboxes[line]
|
||||||
|
if k in self.completion_values:
|
||||||
|
valbox.update_items_cache(self.completion_values[k]['v'])
|
||||||
|
if self.completion_values[k]['m']:
|
||||||
|
valbox.set_separator(', ')
|
||||||
|
else:
|
||||||
|
valbox.set_separator(None)
|
||||||
|
|
||||||
|
dt = self.completion_values[k]['dt']
|
||||||
|
if dt in ('int', 'float', 'rating', 'bool'):
|
||||||
|
self.reboxes[line].setChecked(0)
|
||||||
|
self.reboxes[line].setEnabled(False)
|
||||||
|
else:
|
||||||
|
self.reboxes[line].setEnabled(True)
|
||||||
|
self.fill_in_opbox(line)
|
||||||
|
else:
|
||||||
|
valbox.update_items_cache([])
|
||||||
|
valbox.set_separator(None)
|
||||||
|
|
||||||
|
def fill_in_opbox(self, line):
|
||||||
|
opbox = self.opboxes[line]
|
||||||
|
opbox.clear()
|
||||||
|
k = unicode(self.colboxes[line].currentText())
|
||||||
|
if not k:
|
||||||
|
return
|
||||||
|
if k in self.completion_values:
|
||||||
|
rebox = self.reboxes[line]
|
||||||
|
ebox = self.emptyboxes[line]
|
||||||
|
idx = opbox.currentIndex()
|
||||||
|
if self.completion_values[k]['m'] or \
|
||||||
|
rebox.checkState() == 2 or ebox.checkState() == 2:
|
||||||
|
opbox.addItems(self.relationals[0:2])
|
||||||
|
idx = idx if idx < 2 else 0
|
||||||
|
else:
|
||||||
|
opbox.addItems(self.relationals)
|
||||||
|
opbox.setCurrentIndex(max(idx, 0))
|
||||||
|
|
||||||
|
def re_box_changed(self, state, line=None):
|
||||||
|
self.fill_in_opbox(line)
|
||||||
|
|
||||||
|
def empty_box_changed(self, state, line=None):
|
||||||
|
if state == 2:
|
||||||
|
self.tagboxes[line].setText('')
|
||||||
|
self.tagboxes[line].setEnabled(False)
|
||||||
|
self.reboxes[line].setChecked(0)
|
||||||
|
self.reboxes[line].setEnabled(False)
|
||||||
|
else:
|
||||||
|
self.reboxes[line].setEnabled(True)
|
||||||
|
self.tagboxes[line].setEnabled(True)
|
||||||
|
self.fill_in_opbox(line)
|
||||||
|
|
||||||
|
def and_box_changed(self, state, line=None):
|
||||||
|
if state == 2:
|
||||||
|
self.colorboxes[line].setCurrentIndex(0)
|
||||||
|
self.colorboxes[line].setEnabled(False)
|
||||||
|
else:
|
||||||
|
self.colorboxes[line].setEnabled(True)
|
||||||
|
|
||||||
|
def accepted(self):
|
||||||
|
if self.generate_program():
|
||||||
|
self.accept()
|
||||||
|
else:
|
||||||
|
self.template = ''
|
||||||
|
@ -238,7 +238,6 @@ class Spacer(QWidget): # {{{
|
|||||||
self.l.addStretch(10)
|
self.l.addStretch(10)
|
||||||
# }}}
|
# }}}
|
||||||
|
|
||||||
|
|
||||||
class MainWindowMixin(object): # {{{
|
class MainWindowMixin(object): # {{{
|
||||||
|
|
||||||
def __init__(self, db):
|
def __init__(self, db):
|
||||||
|
@ -418,8 +418,9 @@ class CcTemplateDelegate(QStyledItemDelegate): # {{{
|
|||||||
|
|
||||||
def createEditor(self, parent, option, index):
|
def createEditor(self, parent, option, index):
|
||||||
m = index.model()
|
m = index.model()
|
||||||
|
mi = m.db.get_metadata(index.row(), index_is_id=False)
|
||||||
text = m.custom_columns[m.column_map[index.column()]]['display']['composite_template']
|
text = m.custom_columns[m.column_map[index.column()]]['display']['composite_template']
|
||||||
editor = TemplateDialog(parent, text)
|
editor = TemplateDialog(parent, text, mi)
|
||||||
editor.setWindowTitle(_("Edit template"))
|
editor.setWindowTitle(_("Edit template"))
|
||||||
editor.textbox.setTabChangesFocus(False)
|
editor.textbox.setTabChangesFocus(False)
|
||||||
editor.textbox.setTabStopWidth(20)
|
editor.textbox.setTabStopWidth(20)
|
||||||
|
@ -7,6 +7,7 @@ __docformat__ = 'restructuredtext en'
|
|||||||
|
|
||||||
import shutil, functools, re, os, traceback
|
import shutil, functools, re, os, traceback
|
||||||
from contextlib import closing
|
from contextlib import closing
|
||||||
|
from collections import defaultdict
|
||||||
|
|
||||||
from PyQt4.Qt import (QAbstractTableModel, Qt, pyqtSignal, QIcon, QImage,
|
from PyQt4.Qt import (QAbstractTableModel, Qt, pyqtSignal, QIcon, QImage,
|
||||||
QModelIndex, QVariant, QDate, QColor)
|
QModelIndex, QVariant, QDate, QColor)
|
||||||
@ -87,6 +88,7 @@ class BooksModel(QAbstractTableModel): # {{{
|
|||||||
self.column_map = []
|
self.column_map = []
|
||||||
self.headers = {}
|
self.headers = {}
|
||||||
self.alignment_map = {}
|
self.alignment_map = {}
|
||||||
|
self.color_cache = defaultdict(dict)
|
||||||
self.buffer_size = buffer
|
self.buffer_size = buffer
|
||||||
self.metadata_backup = None
|
self.metadata_backup = None
|
||||||
self.bool_yes_icon = QIcon(I('ok.png'))
|
self.bool_yes_icon = QIcon(I('ok.png'))
|
||||||
@ -97,7 +99,7 @@ class BooksModel(QAbstractTableModel): # {{{
|
|||||||
self.ids_to_highlight_set = set()
|
self.ids_to_highlight_set = set()
|
||||||
self.current_highlighted_idx = None
|
self.current_highlighted_idx = None
|
||||||
self.highlight_only = False
|
self.highlight_only = False
|
||||||
self.column_color_map = {}
|
self.column_color_list = []
|
||||||
self.colors = [unicode(c) for c in QColor.colorNames()]
|
self.colors = [unicode(c) for c in QColor.colorNames()]
|
||||||
self.read_config()
|
self.read_config()
|
||||||
|
|
||||||
@ -172,11 +174,13 @@ class BooksModel(QAbstractTableModel): # {{{
|
|||||||
|
|
||||||
|
|
||||||
def refresh_ids(self, ids, current_row=-1):
|
def refresh_ids(self, ids, current_row=-1):
|
||||||
|
self.color_cache = defaultdict(dict)
|
||||||
rows = self.db.refresh_ids(ids)
|
rows = self.db.refresh_ids(ids)
|
||||||
if rows:
|
if rows:
|
||||||
self.refresh_rows(rows, current_row=current_row)
|
self.refresh_rows(rows, current_row=current_row)
|
||||||
|
|
||||||
def refresh_rows(self, rows, current_row=-1):
|
def refresh_rows(self, rows, current_row=-1):
|
||||||
|
self.color_cache = defaultdict(dict)
|
||||||
for row in rows:
|
for row in rows:
|
||||||
if row == current_row:
|
if row == current_row:
|
||||||
self.new_bookdisplay_data.emit(
|
self.new_bookdisplay_data.emit(
|
||||||
@ -206,6 +210,7 @@ class BooksModel(QAbstractTableModel): # {{{
|
|||||||
return ret
|
return ret
|
||||||
|
|
||||||
def count_changed(self, *args):
|
def count_changed(self, *args):
|
||||||
|
self.color_cache = defaultdict(dict)
|
||||||
self.count_changed_signal.emit(self.db.count())
|
self.count_changed_signal.emit(self.db.count())
|
||||||
|
|
||||||
def row_indices(self, index):
|
def row_indices(self, index):
|
||||||
@ -336,6 +341,10 @@ class BooksModel(QAbstractTableModel): # {{{
|
|||||||
self.db.refresh(field=None)
|
self.db.refresh(field=None)
|
||||||
self.resort(reset=reset)
|
self.resort(reset=reset)
|
||||||
|
|
||||||
|
def reset(self):
|
||||||
|
self.color_cache = defaultdict(dict)
|
||||||
|
QAbstractTableModel.reset(self)
|
||||||
|
|
||||||
def resort(self, reset=True):
|
def resort(self, reset=True):
|
||||||
if not self.db:
|
if not self.db:
|
||||||
return
|
return
|
||||||
@ -537,12 +546,12 @@ class BooksModel(QAbstractTableModel): # {{{
|
|||||||
return img
|
return img
|
||||||
|
|
||||||
def set_color_templates(self, reset=True):
|
def set_color_templates(self, reset=True):
|
||||||
self.column_color_map = {}
|
self.column_color_list = []
|
||||||
for i in range(1,self.db.column_color_count+1):
|
for i in range(1,self.db.column_color_count+1):
|
||||||
name = self.db.prefs.get('column_color_name_'+str(i))
|
name = self.db.prefs.get('column_color_name_'+str(i))
|
||||||
if name:
|
if name:
|
||||||
self.column_color_map[name] = \
|
self.column_color_list.append((name,
|
||||||
self.db.prefs.get('column_color_template_'+str(i))
|
self.db.prefs.get('column_color_template_'+str(i))))
|
||||||
if reset:
|
if reset:
|
||||||
self.reset()
|
self.reset()
|
||||||
|
|
||||||
@ -717,18 +726,25 @@ class BooksModel(QAbstractTableModel): # {{{
|
|||||||
return QVariant(QColor('lightgreen'))
|
return QVariant(QColor('lightgreen'))
|
||||||
elif role == Qt.ForegroundRole:
|
elif role == Qt.ForegroundRole:
|
||||||
key = self.column_map[col]
|
key = self.column_map[col]
|
||||||
if key in self.column_color_map:
|
for k,fmt in self.column_color_list:
|
||||||
|
if k != key:
|
||||||
|
continue
|
||||||
|
id_ = self.id(index)
|
||||||
|
if id_ in self.color_cache:
|
||||||
|
if key in self.color_cache[id_]:
|
||||||
|
return self.color_cache[id_][key]
|
||||||
mi = self.db.get_metadata(self.id(index), index_is_id=True)
|
mi = self.db.get_metadata(self.id(index), index_is_id=True)
|
||||||
fmt = self.column_color_map[key]
|
|
||||||
try:
|
try:
|
||||||
color = composite_formatter.safe_format(fmt, mi, '', mi)
|
color = composite_formatter.safe_format(fmt, mi, '', mi)
|
||||||
if color in self.colors:
|
if color in self.colors:
|
||||||
color = QColor(color)
|
color = QColor(color)
|
||||||
if color.isValid():
|
if color.isValid():
|
||||||
return QVariant(color)
|
color = QVariant(color)
|
||||||
|
self.color_cache[id_][key] = color
|
||||||
|
return color
|
||||||
except:
|
except:
|
||||||
return NONE
|
return NONE
|
||||||
elif self.is_custom_column(key) and \
|
if self.is_custom_column(key) and \
|
||||||
self.custom_columns[key]['datatype'] == 'enumeration':
|
self.custom_columns[key]['datatype'] == 'enumeration':
|
||||||
cc = self.custom_columns[self.column_map[col]]['display']
|
cc = self.custom_columns[self.column_map[col]]['display']
|
||||||
colors = cc.get('enum_colors', [])
|
colors = cc.get('enum_colors', [])
|
||||||
|
340
src/calibre/gui2/preferences/coloring.py
Normal file
340
src/calibre/gui2/preferences/coloring.py
Normal file
@ -0,0 +1,340 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
|
||||||
|
from __future__ import (unicode_literals, division, absolute_import,
|
||||||
|
print_function)
|
||||||
|
|
||||||
|
__license__ = 'GPL v3'
|
||||||
|
__copyright__ = '2011, Kovid Goyal <kovid@kovidgoyal.net>'
|
||||||
|
__docformat__ = 'restructuredtext en'
|
||||||
|
|
||||||
|
from PyQt4.Qt import (QWidget, QDialog, QLabel, QGridLayout, QComboBox,
|
||||||
|
QLineEdit, QIntValidator, QDoubleValidator, QFrame, QColor, Qt, QIcon,
|
||||||
|
QScrollArea, QPushButton, QVBoxLayout, QDialogButtonBox)
|
||||||
|
|
||||||
|
from calibre.utils.icu import sort_key
|
||||||
|
from calibre.gui2 import error_dialog
|
||||||
|
from calibre.library.coloring import (Rule, conditionable_columns,
|
||||||
|
displayable_columns)
|
||||||
|
|
||||||
|
class ConditionEditor(QWidget): # {{{
|
||||||
|
|
||||||
|
def __init__(self, fm, parent=None):
|
||||||
|
QWidget.__init__(self, parent)
|
||||||
|
self.fm = fm
|
||||||
|
|
||||||
|
self.action_map = {
|
||||||
|
'bool' : (
|
||||||
|
(_('is true'), 'is true',),
|
||||||
|
(_('is false'), 'is false'),
|
||||||
|
(_('is undefined'), 'is undefined')
|
||||||
|
),
|
||||||
|
'int' : (
|
||||||
|
(_('is equal to'), 'eq'),
|
||||||
|
(_('is less than'), 'lt'),
|
||||||
|
(_('is greater than'), 'gt')
|
||||||
|
),
|
||||||
|
'multiple' : (
|
||||||
|
(_('has'), 'has'),
|
||||||
|
(_('does not have'), 'does not have'),
|
||||||
|
(_('has pattern'), 'has pattern'),
|
||||||
|
(_('does not have pattern'), 'does not have pattern'),
|
||||||
|
(_('is set'), 'is set'),
|
||||||
|
(_('is not set'), 'is not set'),
|
||||||
|
),
|
||||||
|
'single' : (
|
||||||
|
(_('is'), 'is'),
|
||||||
|
(_('is not'), 'is not'),
|
||||||
|
(_('matches pattern'), 'matches pattern'),
|
||||||
|
(_('does not match pattern'), 'does not match pattern'),
|
||||||
|
(_('is set'), 'is set'),
|
||||||
|
(_('is not set'), 'is not set'),
|
||||||
|
),
|
||||||
|
}
|
||||||
|
|
||||||
|
for x in ('float', 'rating', 'datetime'):
|
||||||
|
self.action_map[x] = self.action_map['int']
|
||||||
|
|
||||||
|
self.l = l = QGridLayout(self)
|
||||||
|
self.setLayout(l)
|
||||||
|
|
||||||
|
self.l1 = l1 = QLabel(_('If the '))
|
||||||
|
l.addWidget(l1, 0, 0)
|
||||||
|
|
||||||
|
self.column_box = QComboBox(self)
|
||||||
|
l.addWidget(self.column_box, 0, 1)
|
||||||
|
|
||||||
|
self.l2 = l2 = QLabel(_(' column '))
|
||||||
|
l.addWidget(l2, 0, 2)
|
||||||
|
|
||||||
|
self.action_box = QComboBox(self)
|
||||||
|
l.addWidget(self.action_box, 0, 3)
|
||||||
|
|
||||||
|
self.l3 = l3 = QLabel(_(' the value '))
|
||||||
|
l.addWidget(l3, 0, 4)
|
||||||
|
|
||||||
|
self.value_box = QLineEdit(self)
|
||||||
|
l.addWidget(self.value_box, 0, 5)
|
||||||
|
|
||||||
|
self.column_box.addItem('', '')
|
||||||
|
for key in sorted(
|
||||||
|
conditionable_columns(fm),
|
||||||
|
key=lambda x:sort_key(fm[x]['name'])):
|
||||||
|
self.column_box.addItem(key, key)
|
||||||
|
self.column_box.setCurrentIndex(0)
|
||||||
|
|
||||||
|
self.column_box.currentIndexChanged.connect(self.init_action_box)
|
||||||
|
self.action_box.currentIndexChanged.connect(self.init_value_box)
|
||||||
|
|
||||||
|
for b in (self.column_box, self.action_box):
|
||||||
|
b.setSizeAdjustPolicy(b.AdjustToMinimumContentsLengthWithIcon)
|
||||||
|
b.setMinimumContentsLength(15)
|
||||||
|
|
||||||
|
@dynamic_property
|
||||||
|
def current_col(self):
|
||||||
|
def fget(self):
|
||||||
|
idx = self.column_box.currentIndex()
|
||||||
|
return unicode(self.column_box.itemData(idx).toString())
|
||||||
|
def fset(self, val):
|
||||||
|
for idx in range(self.column_box.count()):
|
||||||
|
c = unicode(self.column_box.itemData(idx).toString())
|
||||||
|
if c == val:
|
||||||
|
self.column_box.setCurrentIndex(idx)
|
||||||
|
return
|
||||||
|
raise ValueError('Column %r not found'%val)
|
||||||
|
return property(fget=fget, fset=fset)
|
||||||
|
|
||||||
|
@dynamic_property
|
||||||
|
def current_action(self):
|
||||||
|
def fget(self):
|
||||||
|
idx = self.action_box.currentIndex()
|
||||||
|
return unicode(self.action_box.itemData(idx).toString())
|
||||||
|
def fset(self, val):
|
||||||
|
for idx in range(self.action_box.count()):
|
||||||
|
c = unicode(self.action_box.itemData(idx).toString())
|
||||||
|
if c == val:
|
||||||
|
self.action_box.setCurrentIndex(idx)
|
||||||
|
return
|
||||||
|
raise ValueError('Action %r not valid for current column'%val)
|
||||||
|
return property(fget=fget, fset=fset)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def current_val(self):
|
||||||
|
return unicode(self.value_box.text()).strip()
|
||||||
|
|
||||||
|
@dynamic_property
|
||||||
|
def condition(self):
|
||||||
|
|
||||||
|
def fget(self):
|
||||||
|
c, a, v = (self.current_col, self.current_action,
|
||||||
|
self.current_val)
|
||||||
|
if not c or not a:
|
||||||
|
return None
|
||||||
|
return (c, a, v)
|
||||||
|
|
||||||
|
def fset(self, condition):
|
||||||
|
c, a, v = condition
|
||||||
|
if not v:
|
||||||
|
v = ''
|
||||||
|
v = v.strip()
|
||||||
|
self.current_col = c
|
||||||
|
self.current_action = a
|
||||||
|
self.value_box.setText(v)
|
||||||
|
|
||||||
|
return property(fget=fget, fset=fset)
|
||||||
|
|
||||||
|
def init_action_box(self):
|
||||||
|
self.action_box.blockSignals(True)
|
||||||
|
self.action_box.clear()
|
||||||
|
self.action_box.addItem('', '')
|
||||||
|
col = self.current_col
|
||||||
|
m = self.fm[col]
|
||||||
|
dt = m['datatype']
|
||||||
|
if dt in self.action_map:
|
||||||
|
actions = self.action_map[dt]
|
||||||
|
else:
|
||||||
|
k = 'multiple' if m['is_multiple'] else 'single'
|
||||||
|
actions = self.action_map[k]
|
||||||
|
|
||||||
|
for text, key in actions:
|
||||||
|
self.action_box.addItem(text, key)
|
||||||
|
self.action_box.setCurrentIndex(0)
|
||||||
|
self.action_box.blockSignals(False)
|
||||||
|
self.init_value_box()
|
||||||
|
|
||||||
|
def init_value_box(self):
|
||||||
|
self.value_box.setEnabled(True)
|
||||||
|
self.value_box.setText('')
|
||||||
|
self.value_box.setInputMask('')
|
||||||
|
self.value_box.setValidator(None)
|
||||||
|
col = self.current_col
|
||||||
|
m = self.fm[col]
|
||||||
|
dt = m['datatype']
|
||||||
|
action = self.current_action
|
||||||
|
if not col or not action:
|
||||||
|
return
|
||||||
|
tt = ''
|
||||||
|
if dt in ('int', 'float', 'rating'):
|
||||||
|
tt = _('Enter a number')
|
||||||
|
v = QIntValidator if dt == 'int' else QDoubleValidator
|
||||||
|
self.value_box.setValidator(v(self.value_box))
|
||||||
|
elif dt == 'datetime':
|
||||||
|
self.value_box.setInputMask('9999-99-99')
|
||||||
|
tt = _('Enter a date in the format YYYY-MM-DD')
|
||||||
|
else:
|
||||||
|
tt = _('Enter a string')
|
||||||
|
if 'pattern' in action:
|
||||||
|
tt = _('Enter a regular expression')
|
||||||
|
self.value_box.setToolTip(tt)
|
||||||
|
if action in ('is set', 'is not set', 'is true', 'is false',
|
||||||
|
'is undefined'):
|
||||||
|
self.value_box.setEnabled(False)
|
||||||
|
# }}}
|
||||||
|
|
||||||
|
class RuleEditor(QDialog): # {{{
|
||||||
|
|
||||||
|
def __init__(self, fm, parent=None):
|
||||||
|
QDialog.__init__(self, parent)
|
||||||
|
self.fm = fm
|
||||||
|
|
||||||
|
self.setWindowIcon(QIcon(I('format-fill-color.png')))
|
||||||
|
self.setWindowTitle(_('Create/edit a column coloring rule'))
|
||||||
|
|
||||||
|
self.l = l = QGridLayout(self)
|
||||||
|
self.setLayout(l)
|
||||||
|
|
||||||
|
self.l1 = l1 = QLabel(_('Create a coloring rule by'
|
||||||
|
' filling in the boxes below'))
|
||||||
|
l.addWidget(l1, 0, 0, 1, 4)
|
||||||
|
|
||||||
|
self.f1 = QFrame(self)
|
||||||
|
self.f1.setFrameShape(QFrame.HLine)
|
||||||
|
l.addWidget(self.f1, 1, 0, 1, 4)
|
||||||
|
|
||||||
|
self.l2 = l2 = QLabel(_('Set the color of the column:'))
|
||||||
|
l.addWidget(l2, 2, 0)
|
||||||
|
|
||||||
|
self.column_box = QComboBox(self)
|
||||||
|
l.addWidget(self.column_box, 2, 1)
|
||||||
|
|
||||||
|
self.l3 = l3 = QLabel(_('to'))
|
||||||
|
l3.setAlignment(Qt.AlignHCenter)
|
||||||
|
l.addWidget(l3, 2, 2)
|
||||||
|
|
||||||
|
self.color_box = QComboBox(self)
|
||||||
|
l.addWidget(self.color_box, 2, 3)
|
||||||
|
|
||||||
|
self.l4 = l4 = QLabel(
|
||||||
|
_('Only if the following conditions are all satisfied:'))
|
||||||
|
l4.setAlignment(Qt.AlignHCenter)
|
||||||
|
l.addWidget(l4, 3, 0, 1, 4)
|
||||||
|
|
||||||
|
self.scroll_area = sa = QScrollArea(self)
|
||||||
|
sa.setMinimumHeight(300)
|
||||||
|
sa.setMinimumWidth(950)
|
||||||
|
sa.setWidgetResizable(True)
|
||||||
|
l.addWidget(sa, 4, 0, 1, 4)
|
||||||
|
|
||||||
|
self.add_button = b = QPushButton(QIcon(I('plus.png')),
|
||||||
|
_('Add another condition'))
|
||||||
|
l.addWidget(b, 5, 0, 1, 4)
|
||||||
|
b.clicked.connect(self.add_blank_condition)
|
||||||
|
|
||||||
|
self.l5 = l5 = QLabel(_('You can disable a condition by'
|
||||||
|
' blanking all of its boxes'))
|
||||||
|
l.addWidget(l5, 6, 0, 1, 4)
|
||||||
|
|
||||||
|
self.bb = bb = QDialogButtonBox(
|
||||||
|
QDialogButtonBox.Ok|QDialogButtonBox.Cancel)
|
||||||
|
bb.accepted.connect(self.accept)
|
||||||
|
bb.rejected.connect(self.reject)
|
||||||
|
l.addWidget(bb, 7, 0, 1, 4)
|
||||||
|
|
||||||
|
self.conditions_widget = QWidget(self)
|
||||||
|
sa.setWidget(self.conditions_widget)
|
||||||
|
self.conditions_widget.setLayout(QVBoxLayout())
|
||||||
|
self.conditions_widget.layout().setAlignment(Qt.AlignTop)
|
||||||
|
self.conditions = []
|
||||||
|
|
||||||
|
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 x:sort_key(fm[x]['name'])):
|
||||||
|
name = fm[key]['name']
|
||||||
|
if name:
|
||||||
|
self.column_box.addItem(key, key)
|
||||||
|
self.column_box.setCurrentIndex(0)
|
||||||
|
|
||||||
|
self.color_box.addItems(QColor.colorNames())
|
||||||
|
self.color_box.setCurrentIndex(0)
|
||||||
|
|
||||||
|
self.resize(self.sizeHint())
|
||||||
|
|
||||||
|
def add_blank_condition(self):
|
||||||
|
c = ConditionEditor(self.fm, parent=self.conditions_widget)
|
||||||
|
self.conditions.append(c)
|
||||||
|
self.conditions_widget.layout().addWidget(c)
|
||||||
|
|
||||||
|
def accept(self):
|
||||||
|
if self.validate():
|
||||||
|
QDialog.accept(self)
|
||||||
|
|
||||||
|
def validate(self):
|
||||||
|
r = Rule(self.fm)
|
||||||
|
for c in self.conditions:
|
||||||
|
condition = c.condition
|
||||||
|
if condition is not None:
|
||||||
|
try:
|
||||||
|
r.add_condition(*condition)
|
||||||
|
except Exception as e:
|
||||||
|
import traceback
|
||||||
|
error_dialog(self, _('Invalid condition'),
|
||||||
|
_('One of the conditions for this rule is'
|
||||||
|
' invalid: <b>%s</b>')%e,
|
||||||
|
det_msg=traceback.format_exc(), show=True)
|
||||||
|
return False
|
||||||
|
if len(r.conditions) < 1:
|
||||||
|
error_dialog(self, _('No conditions'),
|
||||||
|
_('You must specify at least one non-empty condition'
|
||||||
|
' for this rule'), show=True)
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
|
||||||
|
@property
|
||||||
|
def rule(self):
|
||||||
|
r = Rule(self.fm)
|
||||||
|
r.color = unicode(self.color_box.currentText())
|
||||||
|
idx = self.column_box.currentIndex()
|
||||||
|
col = unicode(self.column_box.itemData(idx).toString())
|
||||||
|
for c in self.conditions:
|
||||||
|
condition = c.condition
|
||||||
|
if condition is not None:
|
||||||
|
r.add_condition(*condition)
|
||||||
|
|
||||||
|
return col, r
|
||||||
|
# }}}
|
||||||
|
|
||||||
|
class EditRules(QWidget):
|
||||||
|
|
||||||
|
def __init__(self, db, parent=None):
|
||||||
|
QWidget.__init__(self, parent)
|
||||||
|
self.db = db
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
from PyQt4.Qt import QApplication
|
||||||
|
app = QApplication([])
|
||||||
|
|
||||||
|
from calibre.library import db
|
||||||
|
|
||||||
|
d = RuleEditor(db().field_metadata)
|
||||||
|
d.add_blank_condition()
|
||||||
|
d.exec_()
|
||||||
|
|
||||||
|
col, r = d.rule
|
||||||
|
|
||||||
|
print ('Column to be colored:', col)
|
||||||
|
print ('Template:')
|
||||||
|
print (r.template)
|
||||||
|
|
@ -5,12 +5,15 @@ __license__ = 'GPL v3'
|
|||||||
__copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'
|
__copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'
|
||||||
__docformat__ = 'restructuredtext en'
|
__docformat__ = 'restructuredtext en'
|
||||||
|
|
||||||
|
from functools import partial
|
||||||
|
|
||||||
from PyQt4.Qt import (QApplication, QFont, QFontInfo, QFontDialog,
|
from PyQt4.Qt import (QApplication, QFont, QFontInfo, QFontDialog,
|
||||||
QAbstractListModel, Qt, QColor)
|
QAbstractListModel, Qt, QColor, QIcon, QToolButton, QComboBox)
|
||||||
|
|
||||||
from calibre.gui2.preferences import ConfigWidgetBase, test_widget, CommaSeparatedList
|
from calibre.gui2.preferences import ConfigWidgetBase, test_widget, CommaSeparatedList
|
||||||
from calibre.gui2.preferences.look_feel_ui import Ui_Form
|
from calibre.gui2.preferences.look_feel_ui import Ui_Form
|
||||||
from calibre.gui2 import config, gprefs, qt_app
|
from calibre.gui2 import config, gprefs, qt_app
|
||||||
|
from calibre.gui2.dialogs.template_line_editor import TemplateLineEditor
|
||||||
from calibre.utils.localization import (available_translations,
|
from calibre.utils.localization import (available_translations,
|
||||||
get_language, get_lang)
|
get_language, get_lang)
|
||||||
from calibre.utils.config import prefs
|
from calibre.utils.config import prefs
|
||||||
@ -129,7 +132,7 @@ class ConfigWidget(ConfigWidgetBase, Ui_Form):
|
|||||||
(_('Medium'), 'medium'), (_('Large'), 'large')]
|
(_('Medium'), 'medium'), (_('Large'), 'large')]
|
||||||
r('toolbar_icon_size', gprefs, choices=choices)
|
r('toolbar_icon_size', gprefs, choices=choices)
|
||||||
|
|
||||||
choices = [(_('Automatic'), 'auto'), (_('Always'), 'always'),
|
choices = [(_('If there is enough room'), 'auto'), (_('Always'), 'always'),
|
||||||
(_('Never'), 'never')]
|
(_('Never'), 'never')]
|
||||||
r('toolbar_text', gprefs, choices=choices)
|
r('toolbar_text', gprefs, choices=choices)
|
||||||
|
|
||||||
@ -167,14 +170,15 @@ class ConfigWidget(ConfigWidgetBase, Ui_Form):
|
|||||||
'<a href="http://manual.calibre-ebook.com/template_lang.html">'
|
'<a href="http://manual.calibre-ebook.com/template_lang.html">'
|
||||||
'tutorial</a> on using templates.') +
|
'tutorial</a> on using templates.') +
|
||||||
'</p><p>' +
|
'</p><p>' +
|
||||||
_('If you want to color a field based on tags, then click the '
|
_('If you want to color a field based on contents of columns, '
|
||||||
'button next to an empty line to open the tags wizard. '
|
'then click the button next to an empty line to open the wizard. '
|
||||||
'It will build a template for you. You can later edit that '
|
'It will build a template for you. You can later edit that '
|
||||||
'template with the same wizard. If you edit it by hand, the '
|
'template with the same wizard. This is by far the easiest '
|
||||||
'wizard might not work or might restore old values.') +
|
'way to specify a template.') +
|
||||||
'</p><p>' +
|
'</p><p>' +
|
||||||
_('The template must evaluate to one of the color names shown '
|
_('If you manually construct a template, then the template must '
|
||||||
'below. You can use any legal template expression. '
|
'evaluate to a valid color name shown in the color names box.'
|
||||||
|
'You can use any legal template expression. '
|
||||||
'For example, you can set the title to always display in '
|
'For example, you can set the title to always display in '
|
||||||
'green using the template "green" (without the quotes). '
|
'green using the template "green" (without the quotes). '
|
||||||
'To show the title in the color named in the custom column '
|
'To show the title in the color named in the custom column '
|
||||||
@ -200,21 +204,76 @@ class ConfigWidget(ConfigWidgetBase, Ui_Form):
|
|||||||
'of values", it is often easier to specify the '
|
'of values", it is often easier to specify the '
|
||||||
'colors in the column definition dialog. There you can '
|
'colors in the column definition dialog. There you can '
|
||||||
'provide a color for each value without using a template.')+ '</p>')
|
'provide a color for each value without using a template.')+ '</p>')
|
||||||
|
self.color_help_scrollArea.setVisible(False)
|
||||||
|
self.color_help_button.clicked.connect(self.change_help_text)
|
||||||
|
self.colors_scrollArea.setVisible(False)
|
||||||
|
self.colors_label.setVisible(False)
|
||||||
|
self.colors_button.clicked.connect(self.change_colors_text)
|
||||||
|
|
||||||
choices = db.field_metadata.displayable_field_keys()
|
choices = db.field_metadata.displayable_field_keys()
|
||||||
choices.sort(key=sort_key)
|
choices.sort(key=sort_key)
|
||||||
choices.insert(0, '')
|
choices.insert(0, '')
|
||||||
self.column_color_count = db.column_color_count+1
|
self.column_color_count = db.column_color_count+1
|
||||||
tags = db.all_tags()
|
|
||||||
|
mi=None
|
||||||
|
try:
|
||||||
|
idx = gui.library_view.currentIndex().row()
|
||||||
|
mi = db.get_metadata(idx, index_is_id=False)
|
||||||
|
except:
|
||||||
|
pass
|
||||||
|
|
||||||
|
l = self.column_color_layout
|
||||||
for i in range(1, self.column_color_count):
|
for i in range(1, self.column_color_count):
|
||||||
|
ccn = QComboBox(parent=self)
|
||||||
|
setattr(self, 'opt_column_color_name_'+str(i), ccn)
|
||||||
|
l.addWidget(ccn, i, 0, 1, 1)
|
||||||
|
|
||||||
|
wtb = QToolButton(parent=self)
|
||||||
|
setattr(self, 'opt_column_color_wizard_'+str(i), wtb)
|
||||||
|
wtb.setIcon(QIcon(I('wizard.png')))
|
||||||
|
l.addWidget(wtb, i, 1, 1, 1)
|
||||||
|
|
||||||
|
ttb = QToolButton(parent=self)
|
||||||
|
setattr(self, 'opt_column_color_tpledit_'+str(i), ttb)
|
||||||
|
ttb.setIcon(QIcon(I('edit_input.png')))
|
||||||
|
l.addWidget(ttb, i, 2, 1, 1)
|
||||||
|
|
||||||
|
tpl = TemplateLineEditor(parent=self)
|
||||||
|
setattr(self, 'opt_column_color_template_'+str(i), tpl)
|
||||||
|
tpl.textChanged.connect(partial(self.tpl_edit_text_changed, ctrl=i))
|
||||||
|
tpl.set_db(db)
|
||||||
|
tpl.set_mi(mi)
|
||||||
|
l.addWidget(tpl, i, 3, 1, 1)
|
||||||
|
|
||||||
|
wtb.clicked.connect(tpl.tag_wizard)
|
||||||
|
ttb.clicked.connect(tpl.open_editor)
|
||||||
|
|
||||||
r('column_color_name_'+str(i), db.prefs, choices=choices)
|
r('column_color_name_'+str(i), db.prefs, choices=choices)
|
||||||
r('column_color_template_'+str(i), db.prefs)
|
r('column_color_template_'+str(i), db.prefs)
|
||||||
tpl = getattr(self, 'opt_column_color_template_'+str(i))
|
txt = db.prefs.get('column_color_template_'+str(i), None)
|
||||||
tpl.set_tags(tags)
|
|
||||||
toolbutton = getattr(self, 'opt_column_color_wizard_'+str(i))
|
wtb.setEnabled(tpl.enable_wizard_button(txt))
|
||||||
toolbutton.clicked.connect(tpl.tag_wizard)
|
ttb.setEnabled(not tpl.enable_wizard_button(txt) or not txt)
|
||||||
|
|
||||||
all_colors = [unicode(s) for s in list(QColor.colorNames())]
|
all_colors = [unicode(s) for s in list(QColor.colorNames())]
|
||||||
self.colors_box.setText(', '.join(all_colors))
|
self.colors_box.setText(', '.join(all_colors))
|
||||||
|
|
||||||
|
def change_help_text(self):
|
||||||
|
self.color_help_scrollArea.setVisible(not self.color_help_scrollArea.isVisible())
|
||||||
|
|
||||||
|
def change_colors_text(self):
|
||||||
|
self.colors_scrollArea.setVisible(not self.colors_scrollArea.isVisible())
|
||||||
|
self.colors_label.setVisible(not self.colors_label.isVisible())
|
||||||
|
|
||||||
|
def tpl_edit_text_changed(self, ign, ctrl=None):
|
||||||
|
tpl = getattr(self, 'opt_column_color_template_'+str(ctrl))
|
||||||
|
txt = unicode(tpl.text())
|
||||||
|
wtb = getattr(self, 'opt_column_color_wizard_'+str(ctrl))
|
||||||
|
ttb = getattr(self, 'opt_column_color_tpledit_'+str(ctrl))
|
||||||
|
wtb.setEnabled(tpl.enable_wizard_button(txt))
|
||||||
|
ttb.setEnabled(not tpl.enable_wizard_button(txt) or not txt)
|
||||||
|
tpl.setFocus()
|
||||||
|
|
||||||
def initialize(self):
|
def initialize(self):
|
||||||
ConfigWidgetBase.initialize(self)
|
ConfigWidgetBase.initialize(self)
|
||||||
font = gprefs['font']
|
font = gprefs['font']
|
||||||
|
@ -416,114 +416,95 @@ then the tags will be displayed each on their own line.</string>
|
|||||||
<string>Column Coloring</string>
|
<string>Column Coloring</string>
|
||||||
</attribute>
|
</attribute>
|
||||||
<layout class="QGridLayout" name="column_color_layout">
|
<layout class="QGridLayout" name="column_color_layout">
|
||||||
<item row="1" column="0">
|
<item row="0" column="0">
|
||||||
<widget class="QLabel" name="label">
|
<widget class="QLabel" name="label">
|
||||||
<property name="text">
|
<property name="text">
|
||||||
<string>Column to color</string>
|
<string>Column to color</string>
|
||||||
</property>
|
</property>
|
||||||
</widget>
|
</widget>
|
||||||
</item>
|
</item>
|
||||||
<item row="1" column="1">
|
<item row="0" column="3">
|
||||||
<widget class="QLabel" name="label">
|
<layout class="QHBoxLayout">
|
||||||
<property name="text">
|
<item>
|
||||||
<string>Color selection template</string>
|
<widget class="QLabel" name="label">
|
||||||
</property>
|
<property name="text">
|
||||||
</widget>
|
<string>Color selection template</string>
|
||||||
</item>
|
</property>
|
||||||
<item row="2" column="0">
|
<property name="sizePolicy">
|
||||||
<widget class="QComboBox" name="opt_column_color_name_1"/>
|
<sizepolicy hsizetype="Expanding" vsizetype="Fixed">
|
||||||
</item>
|
<horstretch>10</horstretch>
|
||||||
<item row="2" column="1">
|
<verstretch>0</verstretch>
|
||||||
<widget class="TemplateLineEditor" name="opt_column_color_template_1"/>
|
</sizepolicy>
|
||||||
</item>
|
</property>
|
||||||
<item row="2" column="2">
|
</widget>
|
||||||
<widget class="QToolButton" name="opt_column_color_wizard_1">
|
</item>
|
||||||
<property name="icon">
|
<item>
|
||||||
<iconset resource="../../../../resources/images.qrc">
|
<widget class="QLabel" name="label">
|
||||||
<normaloff>:/images/wizard.png</normaloff>:/images/wizard.png</iconset>
|
<property name="text">
|
||||||
</property>
|
<string>The template wizard is easiest to use</string>
|
||||||
<property name="toolTip">
|
</property>
|
||||||
<string>Open the tags wizard.</string>
|
</widget>
|
||||||
</property>
|
</item>
|
||||||
</widget>
|
<item>
|
||||||
</item>
|
<widget class="QPushButton" name="color_help_button">
|
||||||
<item row="3" column="0">
|
<property name="text">
|
||||||
<widget class="QComboBox" name="opt_column_color_name_2"/>
|
<string>Show/hide help text</string>
|
||||||
</item>
|
</property>
|
||||||
<item row="3" column="1">
|
</widget>
|
||||||
<widget class="TemplateLineEditor" name="opt_column_color_template_2"/>
|
</item>
|
||||||
</item>
|
<item>
|
||||||
<item row="3" column="2">
|
<widget class="QPushButton" name="colors_button">
|
||||||
<widget class="QToolButton" name="opt_column_color_wizard_2">
|
<property name="text">
|
||||||
<property name="icon">
|
<string>Show/hide colors</string>
|
||||||
<iconset resource="../../../../resources/images.qrc">
|
</property>
|
||||||
<normaloff>:/images/wizard.png</normaloff>:/images/wizard.png</iconset>
|
</widget>
|
||||||
</property>
|
</item>
|
||||||
<property name="toolTip">
|
</layout>
|
||||||
<string>Open the tags wizard.</string>
|
|
||||||
</property>
|
|
||||||
</widget>
|
|
||||||
</item>
|
|
||||||
<item row="4" column="0">
|
|
||||||
<widget class="QComboBox" name="opt_column_color_name_3"/>
|
|
||||||
</item>
|
|
||||||
<item row="4" column="1">
|
|
||||||
<widget class="TemplateLineEditor" name="opt_column_color_template_3"/>
|
|
||||||
</item>
|
|
||||||
<item row="4" column="2">
|
|
||||||
<widget class="QToolButton" name="opt_column_color_wizard_3">
|
|
||||||
<property name="icon">
|
|
||||||
<iconset resource="../../../../resources/images.qrc">
|
|
||||||
<normaloff>:/images/wizard.png</normaloff>:/images/wizard.png</iconset>
|
|
||||||
</property>
|
|
||||||
<property name="toolTip">
|
|
||||||
<string>Open the tags wizard.</string>
|
|
||||||
</property>
|
|
||||||
</widget>
|
|
||||||
</item>
|
|
||||||
<item row="5" column="0">
|
|
||||||
<widget class="QComboBox" name="opt_column_color_name_4"/>
|
|
||||||
</item>
|
|
||||||
<item row="5" column="1">
|
|
||||||
<widget class="TemplateLineEditor" name="opt_column_color_template_4"/>
|
|
||||||
</item>
|
|
||||||
<item row="5" column="2">
|
|
||||||
<widget class="QToolButton" name="opt_column_color_wizard_4">
|
|
||||||
<property name="icon">
|
|
||||||
<iconset resource="../../../../resources/images.qrc">
|
|
||||||
<normaloff>:/images/wizard.png</normaloff>:/images/wizard.png</iconset>
|
|
||||||
</property>
|
|
||||||
<property name="toolTip">
|
|
||||||
<string>Open the tags wizard.</string>
|
|
||||||
</property>
|
|
||||||
</widget>
|
|
||||||
</item>
|
|
||||||
<item row="6" column="0">
|
|
||||||
<widget class="QComboBox" name="opt_column_color_name_5"/>
|
|
||||||
</item>
|
|
||||||
<item row="6" column="1">
|
|
||||||
<widget class="TemplateLineEditor" name="opt_column_color_template_5"/>
|
|
||||||
</item>
|
|
||||||
<item row="6" column="2">
|
|
||||||
<widget class="QToolButton" name="opt_column_color_wizard_5">
|
|
||||||
<property name="icon">
|
|
||||||
<iconset resource="../../../../resources/images.qrc">
|
|
||||||
<normaloff>:/images/wizard.png</normaloff>:/images/wizard.png</iconset>
|
|
||||||
</property>
|
|
||||||
<property name="toolTip">
|
|
||||||
<string>Open the tags wizard.</string>
|
|
||||||
</property>
|
|
||||||
</widget>
|
|
||||||
</item>
|
</item>
|
||||||
<item row="20" column="0">
|
<item row="20" column="0">
|
||||||
<widget class="QLabel" name="label">
|
<widget class="QLabel" name="colors_label">
|
||||||
<property name="text">
|
<property name="text">
|
||||||
<string>Color names</string>
|
<string>Color names</string>
|
||||||
</property>
|
</property>
|
||||||
</widget>
|
</widget>
|
||||||
</item>
|
</item>
|
||||||
<item row="0" column="0" colspan="3">
|
<item row="21" column="0" colspan="8">
|
||||||
<widget class="QScrollArea" name="scrollArea">
|
<widget class="QScrollArea" name="colors_scrollArea">
|
||||||
|
<property name="maximumSize">
|
||||||
|
<size>
|
||||||
|
<width>16777215</width>
|
||||||
|
<height>300</height>
|
||||||
|
</size>
|
||||||
|
</property>
|
||||||
|
<property name="widgetResizable">
|
||||||
|
<bool>true</bool>
|
||||||
|
</property>
|
||||||
|
<widget class="QWidget" name="scrollAreaWidgetContents_2">
|
||||||
|
<property name="geometry">
|
||||||
|
<rect>
|
||||||
|
<x>0</x>
|
||||||
|
<y>0</y>
|
||||||
|
<width>687</width>
|
||||||
|
<height>61</height>
|
||||||
|
</rect>
|
||||||
|
</property>
|
||||||
|
<layout class="QVBoxLayout" name="verticalLayout_2">
|
||||||
|
<item>
|
||||||
|
<widget class="QLabel" name="colors_box">
|
||||||
|
<property name="wordWrap">
|
||||||
|
<bool>true</bool>
|
||||||
|
</property>
|
||||||
|
<property name="alignment">
|
||||||
|
<set>Qt::AlignLeft|Qt::AlignTop</set>
|
||||||
|
</property>
|
||||||
|
</widget>
|
||||||
|
</item>
|
||||||
|
</layout>
|
||||||
|
</widget>
|
||||||
|
</widget>
|
||||||
|
</item>
|
||||||
|
<item row="30" column="0" colspan="8">
|
||||||
|
<widget class="QScrollArea" name="color_help_scrollArea">
|
||||||
<property name="minimumSize">
|
<property name="minimumSize">
|
||||||
<size>
|
<size>
|
||||||
<width>0</width>
|
<width>0</width>
|
||||||
@ -534,7 +515,7 @@ then the tags will be displayed each on their own line.</string>
|
|||||||
<bool>true</bool>
|
<bool>true</bool>
|
||||||
</property>
|
</property>
|
||||||
<property name="alignment">
|
<property name="alignment">
|
||||||
<set>Qt::AlignCenter</set>
|
<set>Qt::AlignLeft|Qt::AlignTop</set>
|
||||||
</property>
|
</property>
|
||||||
<widget class="QWidget" name="scrollAreaWidgetContents">
|
<widget class="QWidget" name="scrollAreaWidgetContents">
|
||||||
<property name="geometry">
|
<property name="geometry">
|
||||||
@ -560,37 +541,24 @@ then the tags will be displayed each on their own line.</string>
|
|||||||
</widget>
|
</widget>
|
||||||
</widget>
|
</widget>
|
||||||
</item>
|
</item>
|
||||||
<item row="21" column="0" colspan="3">
|
<item row="40" column="0">
|
||||||
<widget class="QScrollArea" name="scrollArea_2">
|
<spacer>
|
||||||
<property name="maximumSize">
|
<property name="sizePolicy">
|
||||||
|
<sizepolicy vsizetype="Expanding" hsizetype="Fixed">
|
||||||
|
<horstretch>0</horstretch>
|
||||||
|
<verstretch>10</verstretch>
|
||||||
|
</sizepolicy>
|
||||||
|
</property>
|
||||||
|
<property name="orientation">
|
||||||
|
<enum>Qt::Vertical</enum>
|
||||||
|
</property>
|
||||||
|
<property name="sizeHint" stdset="0">
|
||||||
<size>
|
<size>
|
||||||
<width>16777215</width>
|
<width>0</width>
|
||||||
<height>120</height>
|
<height>0</height>
|
||||||
</size>
|
</size>
|
||||||
</property>
|
</property>
|
||||||
<property name="widgetResizable">
|
</spacer>
|
||||||
<bool>true</bool>
|
|
||||||
</property>
|
|
||||||
<widget class="QWidget" name="scrollAreaWidgetContents_2">
|
|
||||||
<property name="geometry">
|
|
||||||
<rect>
|
|
||||||
<x>0</x>
|
|
||||||
<y>0</y>
|
|
||||||
<width>687</width>
|
|
||||||
<height>61</height>
|
|
||||||
</rect>
|
|
||||||
</property>
|
|
||||||
<layout class="QVBoxLayout" name="verticalLayout_2">
|
|
||||||
<item>
|
|
||||||
<widget class="QLabel" name="colors_box">
|
|
||||||
<property name="wordWrap">
|
|
||||||
<bool>true</bool>
|
|
||||||
</property>
|
|
||||||
</widget>
|
|
||||||
</item>
|
|
||||||
</layout>
|
|
||||||
</widget>
|
|
||||||
</widget>
|
|
||||||
</item>
|
</item>
|
||||||
</layout>
|
</layout>
|
||||||
</widget>
|
</widget>
|
||||||
|
@ -7,7 +7,9 @@ __docformat__ = 'restructuredtext en'
|
|||||||
|
|
||||||
import json, traceback
|
import json, traceback
|
||||||
|
|
||||||
from calibre.gui2 import error_dialog
|
from PyQt4.Qt import QDialogButtonBox
|
||||||
|
|
||||||
|
from calibre.gui2 import error_dialog, warning_dialog
|
||||||
from calibre.gui2.preferences import ConfigWidgetBase, test_widget
|
from calibre.gui2.preferences import ConfigWidgetBase, test_widget
|
||||||
from calibre.gui2.preferences.template_functions_ui import Ui_Form
|
from calibre.gui2.preferences.template_functions_ui import Ui_Form
|
||||||
from calibre.gui2.widgets import PythonHighlighter
|
from calibre.gui2.widgets import PythonHighlighter
|
||||||
@ -152,10 +154,15 @@ class ConfigWidget(ConfigWidgetBase, Ui_Form):
|
|||||||
_('Name already used'), show=True)
|
_('Name already used'), show=True)
|
||||||
return
|
return
|
||||||
if self.argument_count.value() == 0:
|
if self.argument_count.value() == 0:
|
||||||
error_dialog(self.gui, _('Template functions'),
|
box = warning_dialog(self.gui, _('Template functions'),
|
||||||
_('Argument count must be -1 or greater than zero'),
|
_('Argument count should be -1 or greater than zero.'
|
||||||
show=True)
|
'Setting it to zero means that this function cannot '
|
||||||
return
|
'be used in single function mode.'), det_msg = '',
|
||||||
|
show=False)
|
||||||
|
box.bb.setStandardButtons(box.bb.standardButtons() | QDialogButtonBox.Cancel)
|
||||||
|
box.det_msg_toggle.setVisible(False)
|
||||||
|
if not box.exec_():
|
||||||
|
return
|
||||||
try:
|
try:
|
||||||
prog = unicode(self.program.toPlainText())
|
prog = unicode(self.program.toPlainText())
|
||||||
cls = compile_user_function(name, unicode(self.documentation.toPlainText()),
|
cls = compile_user_function(name, unicode(self.documentation.toPlainText()),
|
||||||
|
@ -49,10 +49,12 @@ class UpdateNotification(QDialog):
|
|||||||
self.logo.setMaximumWidth(110)
|
self.logo.setMaximumWidth(110)
|
||||||
self.logo.setPixmap(QPixmap(I('lt.png')).scaled(100, 100,
|
self.logo.setPixmap(QPixmap(I('lt.png')).scaled(100, 100,
|
||||||
Qt.IgnoreAspectRatio, Qt.SmoothTransformation))
|
Qt.IgnoreAspectRatio, Qt.SmoothTransformation))
|
||||||
self.label = QLabel('<p>'+
|
self.label = QLabel(('<p>'+
|
||||||
_('%s has been updated to version <b>%s</b>. '
|
_('%s has been updated to version <b>%s</b>. '
|
||||||
'See the <a href="http://calibre-ebook.com/whats-new'
|
'See the <a href="http://calibre-ebook.com/whats-new'
|
||||||
'">new features</a>.')%(__appname__, version))
|
'">new features</a>.') + '<p>'+_('Update <b>only</b> if one of the '
|
||||||
|
'new features or bug fixes is important to you. '
|
||||||
|
'If the current version works well for you, do not update.'))%(__appname__, version))
|
||||||
self.label.setOpenExternalLinks(True)
|
self.label.setOpenExternalLinks(True)
|
||||||
self.label.setWordWrap(True)
|
self.label.setWordWrap(True)
|
||||||
self.setWindowTitle(_('Update available!'))
|
self.setWindowTitle(_('Update available!'))
|
||||||
|
@ -200,6 +200,11 @@ class CacheRow(list): # {{{
|
|||||||
def __getslice__(self, i, j):
|
def __getslice__(self, i, j):
|
||||||
return self.__getitem__(slice(i, j))
|
return self.__getitem__(slice(i, j))
|
||||||
|
|
||||||
|
def refresh_composites(self):
|
||||||
|
for c in self._composites:
|
||||||
|
self[c] = None
|
||||||
|
self._must_do = True
|
||||||
|
|
||||||
# }}}
|
# }}}
|
||||||
|
|
||||||
class ResultCache(SearchQueryParser): # {{{
|
class ResultCache(SearchQueryParser): # {{{
|
||||||
@ -918,6 +923,7 @@ class ResultCache(SearchQueryParser): # {{{
|
|||||||
for item in self._data:
|
for item in self._data:
|
||||||
if item is not None:
|
if item is not None:
|
||||||
item[ondevice_col] = db.book_on_device_string(item[0])
|
item[ondevice_col] = db.book_on_device_string(item[0])
|
||||||
|
item.refresh_composites()
|
||||||
|
|
||||||
def refresh(self, db, field=None, ascending=True):
|
def refresh(self, db, field=None, ascending=True):
|
||||||
temp = db.conn.get('SELECT * FROM meta2')
|
temp = db.conn.get('SELECT * FROM meta2')
|
||||||
|
178
src/calibre/library/coloring.py
Normal file
178
src/calibre/library/coloring.py
Normal file
@ -0,0 +1,178 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
|
||||||
|
from __future__ import (unicode_literals, division, absolute_import,
|
||||||
|
print_function)
|
||||||
|
from future_builtins import map
|
||||||
|
|
||||||
|
__license__ = 'GPL v3'
|
||||||
|
__copyright__ = '2011, Kovid Goyal <kovid@kovidgoyal.net>'
|
||||||
|
__docformat__ = 'restructuredtext en'
|
||||||
|
|
||||||
|
import binascii, re, json
|
||||||
|
from textwrap import dedent
|
||||||
|
|
||||||
|
class Rule(object): # {{{
|
||||||
|
|
||||||
|
SIGNATURE = '# BasicColorRule():'
|
||||||
|
|
||||||
|
def __init__(self, fm, color=None):
|
||||||
|
self.color = color
|
||||||
|
self.fm = fm
|
||||||
|
self.conditions = []
|
||||||
|
|
||||||
|
def add_condition(self, col, action, val):
|
||||||
|
if col not in self.fm:
|
||||||
|
raise ValueError('%r is not a valid column name'%col)
|
||||||
|
v = self.validate_condition(col, action, val)
|
||||||
|
if v:
|
||||||
|
raise ValueError(v)
|
||||||
|
self.conditions.append((col, action, val))
|
||||||
|
|
||||||
|
def validate_condition(self, col, action, val):
|
||||||
|
m = self.fm[col]
|
||||||
|
dt = m['datatype']
|
||||||
|
if (dt in ('int', 'float', 'rating') and action in ('lt', 'eq', 'gt')):
|
||||||
|
try:
|
||||||
|
int(val) if dt == 'int' else float(val)
|
||||||
|
except:
|
||||||
|
return '%r is not a valid numerical value'%val
|
||||||
|
|
||||||
|
if (dt in ('comments', 'series', 'text', 'enumeration') and 'pattern'
|
||||||
|
in action):
|
||||||
|
try:
|
||||||
|
re.compile(val)
|
||||||
|
except:
|
||||||
|
return '%r is not a valid regular expression'%val
|
||||||
|
|
||||||
|
@property
|
||||||
|
def signature(self):
|
||||||
|
args = (self.color, self.conditions)
|
||||||
|
sig = json.dumps(args, ensure_ascii=False)
|
||||||
|
return self.SIGNATURE + binascii.hexlify(sig.encode('utf-8'))
|
||||||
|
|
||||||
|
@property
|
||||||
|
def template(self):
|
||||||
|
if not self.color or not self.conditions:
|
||||||
|
return None
|
||||||
|
conditions = map(self.apply_condition, self.conditions)
|
||||||
|
conditions = (',\n' + ' '*9).join(conditions)
|
||||||
|
return dedent('''\
|
||||||
|
program:
|
||||||
|
{sig}
|
||||||
|
test(and(
|
||||||
|
{conditions}
|
||||||
|
), {color}, '');
|
||||||
|
''').format(sig=self.signature, conditions=conditions,
|
||||||
|
color=self.color)
|
||||||
|
|
||||||
|
def apply_condition(self, condition):
|
||||||
|
col, action, val = condition
|
||||||
|
m = self.fm[col]
|
||||||
|
dt = m['datatype']
|
||||||
|
|
||||||
|
if dt == 'bool':
|
||||||
|
return self.bool_condition(col, action, val)
|
||||||
|
|
||||||
|
if dt in ('int', 'float', 'rating'):
|
||||||
|
return self.number_condition(col, action, val)
|
||||||
|
|
||||||
|
if dt == 'datetime':
|
||||||
|
return self.date_condition(col, action, val)
|
||||||
|
|
||||||
|
if dt in ('comments', 'series', 'text', 'enumeration'):
|
||||||
|
ism = m.get('is_multiple', False)
|
||||||
|
if ism:
|
||||||
|
return self.multiple_condition(col, action, val, ism)
|
||||||
|
return self.text_condition(col, action, val)
|
||||||
|
|
||||||
|
def bool_condition(self, col, action, val):
|
||||||
|
test = {'is true': 'True',
|
||||||
|
'is false': 'False',
|
||||||
|
'is undefined': 'None'}[action]
|
||||||
|
return "strcmp('%s', raw_field('%s'), '', '1', '')"%(test, col)
|
||||||
|
|
||||||
|
def number_condition(self, col, action, val):
|
||||||
|
lt, eq, gt = {
|
||||||
|
'eq': ('', '1', ''),
|
||||||
|
'lt': ('1', '', ''),
|
||||||
|
'gt': ('', '', '1')
|
||||||
|
}[action]
|
||||||
|
lt, eq, gt = '', '1', ''
|
||||||
|
return "cmp(field('%s'), %s, '%s', '%s', '%s')" % (col, val, lt, eq, gt)
|
||||||
|
|
||||||
|
def date_condition(self, col, action, val):
|
||||||
|
lt, eq, gt = {
|
||||||
|
'eq': ('', '1', ''),
|
||||||
|
'lt': ('1', '', ''),
|
||||||
|
'gt': ('', '', '1')
|
||||||
|
}[action]
|
||||||
|
return "cmp(format_date(raw_field('%s'), 'yyyy-MM-dd'), %s, '%s', '%s', '%s')" % (col,
|
||||||
|
val, lt, eq, gt)
|
||||||
|
|
||||||
|
def multiple_condition(self, col, action, val, sep):
|
||||||
|
if action == 'is set':
|
||||||
|
return "test('%s', '1', '')"%col
|
||||||
|
if action == 'is not set':
|
||||||
|
return "test('%s', '', '1')"%col
|
||||||
|
if action == 'has':
|
||||||
|
return "str_in_list(field('%s'), '%s', \"%s\", '1', '')"%(col, sep, val)
|
||||||
|
if action == 'does not have':
|
||||||
|
return "str_in_list(field('%s'), '%s', \"%s\", '', '1')"%(col, sep, val)
|
||||||
|
if action == 'has pattern':
|
||||||
|
return "in_list(field('%s'), '%s', \"%s\", '1', '')"%(col, sep, val)
|
||||||
|
if action == 'does not have pattern':
|
||||||
|
return "in_list(field('%s'), '%s', \"%s\", '', '1')"%(col, sep, val)
|
||||||
|
|
||||||
|
def text_condition(self, col, action, val):
|
||||||
|
if action == 'is set':
|
||||||
|
return "test('%s', '1', '')"%col
|
||||||
|
if action == 'is not set':
|
||||||
|
return "test('%s', '', '1')"%col
|
||||||
|
if action == 'is':
|
||||||
|
return "strcmp(field('%s'), \"%s\", '', '1', '')"%(col, val)
|
||||||
|
if action == 'is not':
|
||||||
|
return "strcmp(field('%s'), \"%s\", '1', '', '1')"%(col, val)
|
||||||
|
if action == 'matches pattern':
|
||||||
|
return "contains(field('%s'), \"%s\", '1', '')"%(col, val)
|
||||||
|
if action == 'does not match pattern':
|
||||||
|
return "contains(field('%s'), \"%s\", '', '1')"%(col, val)
|
||||||
|
|
||||||
|
# }}}
|
||||||
|
|
||||||
|
def rule_from_template(fm, template):
|
||||||
|
ok_lines = []
|
||||||
|
for line in template.splitlines():
|
||||||
|
if line.startswith(Rule.SIGNATURE):
|
||||||
|
raw = line[len(Rule.SIGNATURE):].strip()
|
||||||
|
try:
|
||||||
|
color, conditions = json.loads(binascii.unhexlify(raw).decode('utf-8'))
|
||||||
|
except:
|
||||||
|
continue
|
||||||
|
r = Rule(fm)
|
||||||
|
r.color = color
|
||||||
|
for c in conditions:
|
||||||
|
try:
|
||||||
|
r.add_condition(*c)
|
||||||
|
except:
|
||||||
|
continue
|
||||||
|
if r.color and r.conditions:
|
||||||
|
return r
|
||||||
|
else:
|
||||||
|
ok_lines.append(line)
|
||||||
|
return '\n'.join(ok_lines)
|
||||||
|
|
||||||
|
def conditionable_columns(fm):
|
||||||
|
for key in fm:
|
||||||
|
m = fm[key]
|
||||||
|
dt = m['datatype']
|
||||||
|
if m.get('name', False) and dt in ('bool', 'int', 'float', 'rating', 'series',
|
||||||
|
'comments', 'text', 'enumeration', 'datetime'):
|
||||||
|
yield key
|
||||||
|
|
||||||
|
|
||||||
|
def displayable_columns(fm):
|
||||||
|
for key in fm.displayable_field_keys():
|
||||||
|
if key not in ('sort', 'author_sort', 'comments', 'formats',
|
||||||
|
'identifiers', 'path'):
|
||||||
|
yield key
|
||||||
|
|
@ -860,6 +860,7 @@ class LibraryDatabase2(LibraryDatabase, SchemaUpgrade, CustomColumns):
|
|||||||
mi.uuid = row[fm['uuid']]
|
mi.uuid = row[fm['uuid']]
|
||||||
mi.title_sort = row[fm['sort']]
|
mi.title_sort = row[fm['sort']]
|
||||||
mi.book_size = row[fm['size']]
|
mi.book_size = row[fm['size']]
|
||||||
|
mi.ondevice_col= row[fm['ondevice']]
|
||||||
mi.last_modified = row[fm['last_modified']]
|
mi.last_modified = row[fm['last_modified']]
|
||||||
formats = row[fm['formats']]
|
formats = row[fm['formats']]
|
||||||
if not formats:
|
if not formats:
|
||||||
|
@ -134,6 +134,8 @@ class SafeFormat(TemplateFormatter):
|
|||||||
'''
|
'''
|
||||||
|
|
||||||
def get_value(self, key, args, kwargs):
|
def get_value(self, key, args, kwargs):
|
||||||
|
if key == '':
|
||||||
|
return ''
|
||||||
try:
|
try:
|
||||||
key = key.lower()
|
key = key.lower()
|
||||||
try:
|
try:
|
||||||
|
@ -240,11 +240,21 @@ def cli_docs(app):
|
|||||||
raw += '\n'+'\n'.join(lines)
|
raw += '\n'+'\n'.join(lines)
|
||||||
update_cli_doc(os.path.join('cli', cmd+'.rst'), raw, info)
|
update_cli_doc(os.path.join('cli', cmd+'.rst'), raw, info)
|
||||||
|
|
||||||
|
def generate_docs(app):
|
||||||
|
cli_docs(app)
|
||||||
|
template_docs(app)
|
||||||
|
|
||||||
|
def template_docs(app):
|
||||||
|
from template_ref_generate import generate_template_language_help
|
||||||
|
info = app.builder.info
|
||||||
|
raw = generate_template_language_help()
|
||||||
|
update_cli_doc('template_ref.rst', raw, info)
|
||||||
|
|
||||||
def setup(app):
|
def setup(app):
|
||||||
app.add_config_value('epub_cover', None, False)
|
app.add_config_value('epub_cover', None, False)
|
||||||
app.add_builder(EPUBHelpBuilder)
|
app.add_builder(EPUBHelpBuilder)
|
||||||
app.connect('doctree-read', substitute)
|
app.connect('doctree-read', substitute)
|
||||||
app.connect('builder-inited', cli_docs)
|
app.connect('builder-inited', generate_docs)
|
||||||
app.connect('build-finished', finished)
|
app.connect('build-finished', finished)
|
||||||
|
|
||||||
def finished(app, exception):
|
def finished(app, exception):
|
||||||
|
@ -65,7 +65,7 @@ this, make your changes, then run::
|
|||||||
bzr send -o my-changes
|
bzr send -o my-changes
|
||||||
|
|
||||||
This will create a :file:`my-changes` file in the current directory,
|
This will create a :file:`my-changes` file in the current directory,
|
||||||
simply attach that to a ticket on the |app| `bug tracker <http://bugs.calibre-ebook.com/newticket>`_.
|
simply attach that to a ticket on the |app| `bug tracker <http://calibre-ebook.com/bugs>`_.
|
||||||
|
|
||||||
If you plan to do a lot of development on |app|, then the best method is to create a
|
If you plan to do a lot of development on |app|, then the best method is to create a
|
||||||
`Launchpad <http://launchpad.net>`_ account. Once you have the account, you can use it to register
|
`Launchpad <http://launchpad.net>`_ account. Once you have the account, you can use it to register
|
||||||
|
@ -560,7 +560,7 @@ I want some feature added to |app|. What can I do?
|
|||||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||||
You have two choices:
|
You have two choices:
|
||||||
1. Create a patch by hacking on |app| and send it to me for review and inclusion. See `Development <http://calibre-ebook.com/get-involved>`_.
|
1. Create a patch by hacking on |app| and send it to me for review and inclusion. See `Development <http://calibre-ebook.com/get-involved>`_.
|
||||||
2. `Open a ticket <http://bugs.calibre-ebook.com/newticket>`_ (you have to register and login first). Remember that |app| development is done by volunteers, so if you get no response to your feature request, it means no one feels like implementing it.
|
2. `Open a ticket <http://calibre-ebook.com/bugs>`_ (you have to register and login first). Remember that |app| development is done by volunteers, so if you get no response to your feature request, it means no one feels like implementing it.
|
||||||
|
|
||||||
How is |app| licensed?
|
How is |app| licensed?
|
||||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||||
|
@ -352,7 +352,7 @@ The syntax for searching for dates is::
|
|||||||
If the date is ambiguous, the current locale is used for date comparison. For example, in an mm/dd/yyyy
|
If the date is ambiguous, the current locale is used for date comparison. For example, in an mm/dd/yyyy
|
||||||
locale, 2/1/2009 is interpreted as 1 Feb 2009. In a dd/mm/yyyy locale, it is interpreted as 2 Jan 2009. Some
|
locale, 2/1/2009 is interpreted as 1 Feb 2009. In a dd/mm/yyyy locale, it is interpreted as 2 Jan 2009. Some
|
||||||
special date strings are available. The string ``today`` translates to today's date, whatever it is. The
|
special date strings are available. The string ``today`` translates to today's date, whatever it is. The
|
||||||
strings `yesterday`` and ``thismonth`` also work. In addition, the string ``daysago`` can be used to compare
|
strings ``yesterday`` and ``thismonth`` also work. In addition, the string ``daysago`` can be used to compare
|
||||||
to a date some number of days ago, for example: date:>10daysago, date:<=45daysago.
|
to a date some number of days ago, for example: date:>10daysago, date:<=45daysago.
|
||||||
|
|
||||||
You can search for books that have a format of a certain size like this::
|
You can search for books that have a format of a certain size like this::
|
||||||
|
@ -114,13 +114,15 @@ The syntax for using functions is ``{field:function(arguments)}``, or ``{field:f
|
|||||||
|
|
||||||
If you have programming experience, please note that the syntax in this mode (single function) is not what you might expect. Strings are not quoted. Spaces are significant. All arguments must be constants; there is no sub-evaluation. Use :ref:`template program mode <template_mode>` and :ref:`general program mode <general_mode>` to avoid these differences.
|
If you have programming experience, please note that the syntax in this mode (single function) is not what you might expect. Strings are not quoted. Spaces are significant. All arguments must be constants; there is no sub-evaluation. Use :ref:`template program mode <template_mode>` and :ref:`general program mode <general_mode>` to avoid these differences.
|
||||||
|
|
||||||
|
Many functions use regular expressions. In all cases, regular expression matching is case-insensitive.
|
||||||
|
|
||||||
The functions available are:
|
The functions available are:
|
||||||
|
|
||||||
* ``lowercase()`` -- return value of the field in lower case.
|
* ``lowercase()`` -- return value of the field in lower case.
|
||||||
* ``uppercase()`` -- return the value of the field in upper case.
|
* ``uppercase()`` -- return the value of the field in upper case.
|
||||||
* ``titlecase()`` -- return the value of the field in title case.
|
* ``titlecase()`` -- return the value of the field in title case.
|
||||||
* ``capitalize()`` -- return the value with the first letter upper case and the rest lower case.
|
* ``capitalize()`` -- return the value with the first letter upper case and the rest lower case.
|
||||||
* ``contains(pattern, text if match, text if not match`` -- checks if field contains matches for the regular expression `pattern`. Returns `text if match` if matches are found, otherwise it returns `text if no match`.
|
* ``contains(pattern, text if match, text if not match)`` -- checks if field contains matches for the regular expression `pattern`. Returns `text if match` if matches are found, otherwise it returns `text if no match`.
|
||||||
* ``count(separator)`` -- interprets the value as a list of items separated by `separator`, returning the number of items in the list. Most lists use a comma as the separator, but authors uses an ampersand. Examples: `{tags:count(,)}`, `{authors:count(&)}`
|
* ``count(separator)`` -- interprets the value as a list of items separated by `separator`, returning the number of items in the list. Most lists use a comma as the separator, but authors uses an ampersand. Examples: `{tags:count(,)}`, `{authors:count(&)}`
|
||||||
* ``ifempty(text)`` -- if the field is not empty, return the value of the field. Otherwise return `text`.
|
* ``ifempty(text)`` -- if the field is not empty, return the value of the field. Otherwise return `text`.
|
||||||
* ``in_list(separator, pattern, found_val, not_found_val)`` -- interpret the field as a list of items separated by `separator`, comparing the `pattern` against each value in the list. If the pattern matches a value, return `found_val`, otherwise return `not_found_val`.
|
* ``in_list(separator, pattern, found_val, not_found_val)`` -- interpret the field as a list of items separated by `separator`, comparing the `pattern` against each value in the list. If the pattern matches a value, return `found_val`, otherwise return `not_found_val`.
|
||||||
@ -130,6 +132,7 @@ The functions available are:
|
|||||||
* ``switch(pattern, value, pattern, value, ..., else_value)`` -- for each ``pattern, value`` pair, checks if the field matches the regular expression ``pattern`` and if so, returns that ``value``. If no ``pattern`` matches, then ``else_value`` is returned. You can have as many ``pattern, value`` pairs as you want.
|
* ``switch(pattern, value, pattern, value, ..., else_value)`` -- for each ``pattern, value`` pair, checks if the field matches the regular expression ``pattern`` and if so, returns that ``value``. If no ``pattern`` matches, then ``else_value`` is returned. You can have as many ``pattern, value`` pairs as you want.
|
||||||
* ``lookup(pattern, field, pattern, field, ..., else_field)`` -- like switch, except the arguments are field (metadata) names, not text. The value of the appropriate field will be fetched and used. Note that because composite columns are fields, you can use this function in one composite field to use the value of some other composite field. This is extremely useful when constructing variable save paths (more later).
|
* ``lookup(pattern, field, pattern, field, ..., else_field)`` -- like switch, except the arguments are field (metadata) names, not text. The value of the appropriate field will be fetched and used. Note that because composite columns are fields, you can use this function in one composite field to use the value of some other composite field. This is extremely useful when constructing variable save paths (more later).
|
||||||
* ``select(key)`` -- interpret the field as a comma-separated list of items, with the items being of the form "id:value". Find the pair with the id equal to key, and return the corresponding value. This function is particularly useful for extracting a value such as an isbn from the set of identifiers for a book.
|
* ``select(key)`` -- interpret the field as a comma-separated list of items, with the items being of the form "id:value". Find the pair with the id equal to key, and return the corresponding value. This function is particularly useful for extracting a value such as an isbn from the set of identifiers for a book.
|
||||||
|
* ``str_in_list(val, separator, string, found_val, not_found_val)`` -- treat val as a list of items separated by separator, comparing the string against each value in the list. If the string matches a value, return found_val, otherwise return not_found_val. If the string contains separators, then it is also treated as a list and each value is checked.
|
||||||
* ``subitems(val, start_index, end_index)`` -- This function is used to break apart lists of tag-like hierarchical items such as genres. It interprets the value as a comma-separated list of tag-like items, where each item is a period-separated list. Returns a new list made by first finding all the period-separated tag-like items, then for each such item extracting the components from `start_index` to `end_index`, then combining the results back together. The first component in a period-separated list has an index of zero. If an index is negative, then it counts from the end of the list. As a special case, an end_index of zero is assumed to be the length of the list. Examples::
|
* ``subitems(val, start_index, end_index)`` -- This function is used to break apart lists of tag-like hierarchical items such as genres. It interprets the value as a comma-separated list of tag-like items, where each item is a period-separated list. Returns a new list made by first finding all the period-separated tag-like items, then for each such item extracting the components from `start_index` to `end_index`, then combining the results back together. The first component in a period-separated list has an index of zero. If an index is negative, then it counts from the end of the list. As a special case, an end_index of zero is assumed to be the length of the list. Examples::
|
||||||
|
|
||||||
Assuming a #genre column containing "A.B.C":
|
Assuming a #genre column containing "A.B.C":
|
||||||
@ -255,6 +258,7 @@ The following functions are available in addition to those described in single-f
|
|||||||
* ``not(value)`` -- returns the string "1" if the value is empty, otherwise returns the empty string. This function works well with test or first_non_empty. You can have as many values as you want.
|
* ``not(value)`` -- returns the string "1" if the value is empty, otherwise returns the empty string. This function works well with test or first_non_empty. You can have as many values as you want.
|
||||||
* ``merge_lists(list1, list2, separator)`` -- return a list made by merging the items in list1 and list2, removing duplicate items using a case-insensitive compare. If items differ in case, the one in list1 is used. The items in list1 and list2 are separated by separator, as are the items in the returned list.
|
* ``merge_lists(list1, list2, separator)`` -- return a list made by merging the items in list1 and list2, removing duplicate items using a case-insensitive compare. If items differ in case, the one in list1 is used. The items in list1 and list2 are separated by separator, as are the items in the returned list.
|
||||||
* ``multiply(x, y)`` -- returns x * y. Throws an exception if either x or y are not numbers.
|
* ``multiply(x, y)`` -- returns x * y. Throws an exception if either x or y are not numbers.
|
||||||
|
* ``ondevice()`` -- return the string "Yes" if ondevice is set, otherwise return the empty string
|
||||||
* ``or(value, value, ...)`` -- returns the string "1" if any value is not empty, otherwise returns the empty string. This function works well with test or first_non_empty. You can have as many values as you want.
|
* ``or(value, value, ...)`` -- returns the string "1" if any value is not empty, otherwise returns the empty string. This function works well with test or first_non_empty. You can have as many values as you want.
|
||||||
* ``print(a, b, ...)`` -- prints the arguments to standard output. Unless you start calibre from the command line (``calibre-debug -g``), the output will go to a black hole.
|
* ``print(a, b, ...)`` -- prints the arguments to standard output. Unless you start calibre from the command line (``calibre-debug -g``), the output will go to a black hole.
|
||||||
* ``raw_field(name)`` -- returns the metadata field named by name without applying any formatting.
|
* ``raw_field(name)`` -- returns the metadata field named by name without applying any formatting.
|
||||||
@ -264,20 +268,14 @@ The following functions are available in addition to those described in single-f
|
|||||||
* ``subtract(x, y)`` -- returns x - y. Throws an exception if either x or y are not numbers.
|
* ``subtract(x, y)`` -- returns x - y. Throws an exception if either x or y are not numbers.
|
||||||
* ``template(x)`` -- evaluates x as a template. The evaluation is done in its own context, meaning that variables are not shared between the caller and the template evaluation. Because the `{` and `}` characters are special, you must use `[[` for the `{` character and `]]` for the '}' character; they are converted automatically. For example, ``template('[[title_sort]]') will evaluate the template ``{title_sort}`` and return its value.
|
* ``template(x)`` -- evaluates x as a template. The evaluation is done in its own context, meaning that variables are not shared between the caller and the template evaluation. Because the `{` and `}` characters are special, you must use `[[` for the `{` character and `]]` for the '}' character; they are converted automatically. For example, ``template('[[title_sort]]') will evaluate the template ``{title_sort}`` and return its value.
|
||||||
|
|
||||||
Function classification summary:
|
Function classification
|
||||||
|
---------------------------
|
||||||
|
|
||||||
|
.. toctree::
|
||||||
|
:maxdepth: 3
|
||||||
|
|
||||||
|
template_ref
|
||||||
|
|
||||||
* Get values from metadata: ``field``. ``raw_field``. In some situations, ``lookup`` can be used in place of ``field``.
|
|
||||||
* Arithmetic: ``add``, ``subtract``, ``multiply``, ``divide``
|
|
||||||
* Boolean: ``and``, ``or``, ``not``. The function ``if_empty`` is similar to ``and`` called with one argument.
|
|
||||||
* If-then-else: ``contains``, ``test``
|
|
||||||
* Iterating over values: ``first_non_empty``, ``lookup``, ``switch``
|
|
||||||
* List lookup: ``in_list``, ``list_item``, ``select``,
|
|
||||||
* List manipulation: ``count``, ``merge_lists``, ``sublist``, ``subitems``
|
|
||||||
* Recursion: ``eval``, ``template``
|
|
||||||
* Relational: ``cmp`` , ``strcmp`` for strings
|
|
||||||
* String case changes: ``lowercase``, ``uppercase``, ``titlecase``, ``capitalize``
|
|
||||||
* String manipulation: ``re``, ``shorten``, ``substr``
|
|
||||||
* Other: ``assign``, ``booksize``, ``print``, ``format_date``,
|
|
||||||
|
|
||||||
.. _general_mode:
|
.. _general_mode:
|
||||||
|
|
||||||
@ -422,19 +420,8 @@ You might find the following tips useful.
|
|||||||
* In a plugboard, you can set a field to empty (or whatever is equivalent to empty) by using the special template ``{null}``. This template will always evaluate to an empty string.
|
* In a plugboard, you can set a field to empty (or whatever is equivalent to empty) by using the special template ``{null}``. This template will always evaluate to an empty string.
|
||||||
* The technique described above to show numbers even if they have a zero value works with the standard field series_index.
|
* The technique described above to show numbers even if they have a zero value works with the standard field series_index.
|
||||||
|
|
||||||
API of the Metadata objects
|
.. toctree::
|
||||||
----------------------------
|
:hidden:
|
||||||
|
|
||||||
.. module:: calibre.ebooks.metadata.book.base
|
template_ref
|
||||||
|
|
||||||
.. autoclass:: Metadata
|
|
||||||
:members:
|
|
||||||
:member-order: bysource
|
|
||||||
|
|
||||||
.. data:: STANDARD_METADATA_FIELDS
|
|
||||||
|
|
||||||
The set of standard metadata fields.
|
|
||||||
|
|
||||||
.. literalinclude:: ../ebooks/metadata/book/__init__.py
|
|
||||||
:lines: 7-
|
|
||||||
|
|
||||||
|
92
src/calibre/manual/template_ref_generate.py
Normal file
92
src/calibre/manual/template_ref_generate.py
Normal file
@ -0,0 +1,92 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
|
||||||
|
|
||||||
|
__license__ = 'GPL v3'
|
||||||
|
__copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>'
|
||||||
|
|
||||||
|
from collections import defaultdict
|
||||||
|
|
||||||
|
PREAMBLE = '''\
|
||||||
|
.. include:: global.rst
|
||||||
|
|
||||||
|
.. _templaterefcalibre:
|
||||||
|
|
||||||
|
Reference for all builtin template language functions
|
||||||
|
========================================================
|
||||||
|
|
||||||
|
Here, we document all the builtin functions available in the |app| template language. Every function is implemented as a class in python and you can click the source links to see the source code, in case the documentation is insufficient. The functions are arranged in logical groups by type.
|
||||||
|
|
||||||
|
.. contents::
|
||||||
|
:depth: 2
|
||||||
|
:local:
|
||||||
|
|
||||||
|
.. module:: calibre.utils.formatter_functions
|
||||||
|
|
||||||
|
'''
|
||||||
|
|
||||||
|
CATEGORY_TEMPLATE = '''\
|
||||||
|
{category}
|
||||||
|
{dashes}
|
||||||
|
|
||||||
|
'''
|
||||||
|
|
||||||
|
FUNCTION_TEMPLATE = '''\
|
||||||
|
{fs}
|
||||||
|
{hats}
|
||||||
|
|
||||||
|
.. autoclass:: {cn}
|
||||||
|
|
||||||
|
'''
|
||||||
|
|
||||||
|
POSTAMBLE = '''\
|
||||||
|
|
||||||
|
API of the Metadata objects
|
||||||
|
----------------------------
|
||||||
|
|
||||||
|
The python implementation of the template functions is passed in a Metadata object. Knowing it's API is useful if you want to define your own template functions.
|
||||||
|
|
||||||
|
.. module:: calibre.ebooks.metadata.book.base
|
||||||
|
|
||||||
|
.. autoclass:: Metadata
|
||||||
|
:members:
|
||||||
|
:member-order: bysource
|
||||||
|
|
||||||
|
.. data:: STANDARD_METADATA_FIELDS
|
||||||
|
|
||||||
|
The set of standard metadata fields.
|
||||||
|
|
||||||
|
.. literalinclude:: ../ebooks/metadata/book/__init__.py
|
||||||
|
:lines: 7-
|
||||||
|
'''
|
||||||
|
|
||||||
|
|
||||||
|
def generate_template_language_help():
|
||||||
|
from calibre.utils.formatter_functions import all_builtin_functions
|
||||||
|
|
||||||
|
funcs = defaultdict(dict)
|
||||||
|
|
||||||
|
for func in all_builtin_functions:
|
||||||
|
class_name = func.__class__.__name__
|
||||||
|
func_sig = getattr(func, 'doc')
|
||||||
|
x = func_sig.find(' -- ')
|
||||||
|
if x < 0:
|
||||||
|
print 'No sig for ', class_name
|
||||||
|
continue
|
||||||
|
func_sig = func_sig[:x]
|
||||||
|
func_cat = getattr(func, 'category')
|
||||||
|
funcs[func_cat][func_sig] = class_name
|
||||||
|
|
||||||
|
output = PREAMBLE
|
||||||
|
cats = sorted(funcs.keys())
|
||||||
|
for cat in cats:
|
||||||
|
output += CATEGORY_TEMPLATE.format(category=cat, dashes='-'*len(cat))
|
||||||
|
entries = [k for k in sorted(funcs[cat].keys())]
|
||||||
|
for entry in entries:
|
||||||
|
output += FUNCTION_TEMPLATE.format(fs = entry, cn=funcs[cat][entry],
|
||||||
|
hats='^'*len(entry))
|
||||||
|
|
||||||
|
output += POSTAMBLE
|
||||||
|
return output
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
generate_template_language_help()
|
File diff suppressed because it is too large
Load Diff
@ -98,7 +98,10 @@ class _Parser(object):
|
|||||||
cls = funcs['assign']
|
cls = funcs['assign']
|
||||||
return cls.eval_(self.parent, self.parent.kwargs,
|
return cls.eval_(self.parent, self.parent.kwargs,
|
||||||
self.parent.book, self.parent.locals, id, self.expr())
|
self.parent.book, self.parent.locals, id, self.expr())
|
||||||
return self.parent.locals.get(id, _('unknown id ') + id)
|
val = self.parent.locals.get(id, None)
|
||||||
|
if val is None:
|
||||||
|
self.error(_('Unknown identifier ') + id)
|
||||||
|
return val
|
||||||
# We have a function.
|
# We have a function.
|
||||||
# Check if it is a known one. We do this here so error reporting is
|
# Check if it is a known one. We do this here so error reporting is
|
||||||
# better, as it can identify the tokens near the problem.
|
# better, as it can identify the tokens near the problem.
|
||||||
@ -317,8 +320,8 @@ class TemplateFormatter(string.Formatter):
|
|||||||
try:
|
try:
|
||||||
ans = self.vformat(fmt, [], kwargs).strip()
|
ans = self.vformat(fmt, [], kwargs).strip()
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
if DEBUG:
|
# if DEBUG:
|
||||||
traceback.print_exc()
|
# traceback.print_exc()
|
||||||
ans = error_value + ' ' + e.message
|
ans = error_value + ' ' + e.message
|
||||||
return ans
|
return ans
|
||||||
|
|
||||||
@ -339,6 +342,8 @@ class EvalFormatter(TemplateFormatter):
|
|||||||
A template formatter that uses a simple dict instead of an mi instance
|
A template formatter that uses a simple dict instead of an mi instance
|
||||||
'''
|
'''
|
||||||
def get_value(self, key, args, kwargs):
|
def get_value(self, key, args, kwargs):
|
||||||
|
if key == '':
|
||||||
|
return ''
|
||||||
key = key.lower()
|
key = key.lower()
|
||||||
return kwargs.get(key, _('No such variable ') + key)
|
return kwargs.get(key, _('No such variable ') + key)
|
||||||
|
|
||||||
|
@ -8,7 +8,7 @@ __license__ = 'GPL v3'
|
|||||||
__copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'
|
__copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'
|
||||||
__docformat__ = 'restructuredtext en'
|
__docformat__ = 'restructuredtext en'
|
||||||
|
|
||||||
import inspect, re, traceback, sys
|
import inspect, re, traceback
|
||||||
|
|
||||||
from calibre.utils.titlecase import titlecase
|
from calibre.utils.titlecase import titlecase
|
||||||
from calibre.utils.icu import capitalize, strcmp, sort_key
|
from calibre.utils.icu import capitalize, strcmp, sort_key
|
||||||
@ -57,26 +57,20 @@ class FormatterFunction(object):
|
|||||||
|
|
||||||
doc = _('No documentation provided')
|
doc = _('No documentation provided')
|
||||||
name = 'no name provided'
|
name = 'no name provided'
|
||||||
|
category = 'Unknown'
|
||||||
arg_count = 0
|
arg_count = 0
|
||||||
|
|
||||||
def evaluate(self, formatter, kwargs, mi, locals, *args):
|
def evaluate(self, formatter, kwargs, mi, locals, *args):
|
||||||
raise NotImplementedError()
|
raise NotImplementedError()
|
||||||
|
|
||||||
def eval_(self, formatter, kwargs, mi, locals, *args):
|
def eval_(self, formatter, kwargs, mi, locals, *args):
|
||||||
try:
|
ret = self.evaluate(formatter, kwargs, mi, locals, *args)
|
||||||
ret = self.evaluate(formatter, kwargs, mi, locals, *args)
|
if isinstance(ret, (str, unicode)):
|
||||||
if isinstance(ret, (str, unicode)):
|
return ret
|
||||||
return ret
|
if isinstance(ret, (int, float, bool)):
|
||||||
if isinstance(ret, (int, float, bool)):
|
return unicode(ret)
|
||||||
return unicode(ret)
|
if isinstance(ret, list):
|
||||||
if isinstance(ret, list):
|
return ','.join(list)
|
||||||
return ','.join(list)
|
|
||||||
except:
|
|
||||||
traceback.print_exc()
|
|
||||||
exc_type, exc_value, exc_traceback = sys.exc_info()
|
|
||||||
info = ': '.join(traceback.format_exception(exc_type, exc_value,
|
|
||||||
exc_traceback)[-2:]).replace('\n', '')
|
|
||||||
return _('Exception ') + info
|
|
||||||
|
|
||||||
all_builtin_functions = []
|
all_builtin_functions = []
|
||||||
class BuiltinFormatterFunction(FormatterFunction):
|
class BuiltinFormatterFunction(FormatterFunction):
|
||||||
@ -94,7 +88,8 @@ class BuiltinFormatterFunction(FormatterFunction):
|
|||||||
class BuiltinStrcmp(BuiltinFormatterFunction):
|
class BuiltinStrcmp(BuiltinFormatterFunction):
|
||||||
name = 'strcmp'
|
name = 'strcmp'
|
||||||
arg_count = 5
|
arg_count = 5
|
||||||
doc = _('strcmp(x, y, lt, eq, gt) -- does a case-insensitive comparison of x '
|
category = 'Relational'
|
||||||
|
__doc__ = doc = _('strcmp(x, y, lt, eq, gt) -- does a case-insensitive comparison of x '
|
||||||
'and y as strings. Returns lt if x < y. Returns eq if x == y. '
|
'and y as strings. Returns lt if x < y. Returns eq if x == y. '
|
||||||
'Otherwise returns gt.')
|
'Otherwise returns gt.')
|
||||||
|
|
||||||
@ -108,13 +103,14 @@ class BuiltinStrcmp(BuiltinFormatterFunction):
|
|||||||
|
|
||||||
class BuiltinCmp(BuiltinFormatterFunction):
|
class BuiltinCmp(BuiltinFormatterFunction):
|
||||||
name = 'cmp'
|
name = 'cmp'
|
||||||
|
category = 'Relational'
|
||||||
arg_count = 5
|
arg_count = 5
|
||||||
doc = _('cmp(x, y, lt, eq, gt) -- compares x and y after converting both to '
|
__doc__ = doc = _('cmp(x, y, lt, eq, gt) -- compares x and y after converting both to '
|
||||||
'numbers. Returns lt if x < y. Returns eq if x == y. Otherwise returns gt.')
|
'numbers. Returns lt if x < y. Returns eq if x == y. Otherwise returns gt.')
|
||||||
|
|
||||||
def evaluate(self, formatter, kwargs, mi, locals, x, y, lt, eq, gt):
|
def evaluate(self, formatter, kwargs, mi, locals, x, y, lt, eq, gt):
|
||||||
x = float(x if x else 0)
|
x = float(x if x and x != 'None' else 0)
|
||||||
y = float(y if y else 0)
|
y = float(y if y and y != 'None' else 0)
|
||||||
if x < y:
|
if x < y:
|
||||||
return lt
|
return lt
|
||||||
if x == y:
|
if x == y:
|
||||||
@ -124,7 +120,8 @@ class BuiltinCmp(BuiltinFormatterFunction):
|
|||||||
class BuiltinStrcat(BuiltinFormatterFunction):
|
class BuiltinStrcat(BuiltinFormatterFunction):
|
||||||
name = 'strcat'
|
name = 'strcat'
|
||||||
arg_count = -1
|
arg_count = -1
|
||||||
doc = _('strcat(a, b, ...) -- can take any number of arguments. Returns a '
|
category = 'String Manipulation'
|
||||||
|
__doc__ = doc = _('strcat(a, b, ...) -- can take any number of arguments. Returns a '
|
||||||
'string formed by concatenating all the arguments')
|
'string formed by concatenating all the arguments')
|
||||||
|
|
||||||
def evaluate(self, formatter, kwargs, mi, locals, *args):
|
def evaluate(self, formatter, kwargs, mi, locals, *args):
|
||||||
@ -137,7 +134,8 @@ class BuiltinStrcat(BuiltinFormatterFunction):
|
|||||||
class BuiltinAdd(BuiltinFormatterFunction):
|
class BuiltinAdd(BuiltinFormatterFunction):
|
||||||
name = 'add'
|
name = 'add'
|
||||||
arg_count = 2
|
arg_count = 2
|
||||||
doc = _('add(x, y) -- returns x + y. Throws an exception if either x or y are not numbers.')
|
category = 'Arithmetic'
|
||||||
|
__doc__ = doc = _('add(x, y) -- returns x + y. Throws an exception if either x or y are not numbers.')
|
||||||
|
|
||||||
def evaluate(self, formatter, kwargs, mi, locals, x, y):
|
def evaluate(self, formatter, kwargs, mi, locals, x, y):
|
||||||
x = float(x if x else 0)
|
x = float(x if x else 0)
|
||||||
@ -147,7 +145,8 @@ class BuiltinAdd(BuiltinFormatterFunction):
|
|||||||
class BuiltinSubtract(BuiltinFormatterFunction):
|
class BuiltinSubtract(BuiltinFormatterFunction):
|
||||||
name = 'subtract'
|
name = 'subtract'
|
||||||
arg_count = 2
|
arg_count = 2
|
||||||
doc = _('subtract(x, y) -- returns x - y. Throws an exception if either x or y are not numbers.')
|
category = 'Arithmetic'
|
||||||
|
__doc__ = doc = _('subtract(x, y) -- returns x - y. Throws an exception if either x or y are not numbers.')
|
||||||
|
|
||||||
def evaluate(self, formatter, kwargs, mi, locals, x, y):
|
def evaluate(self, formatter, kwargs, mi, locals, x, y):
|
||||||
x = float(x if x else 0)
|
x = float(x if x else 0)
|
||||||
@ -157,7 +156,8 @@ class BuiltinSubtract(BuiltinFormatterFunction):
|
|||||||
class BuiltinMultiply(BuiltinFormatterFunction):
|
class BuiltinMultiply(BuiltinFormatterFunction):
|
||||||
name = 'multiply'
|
name = 'multiply'
|
||||||
arg_count = 2
|
arg_count = 2
|
||||||
doc = _('multiply(x, y) -- returns x * y. Throws an exception if either x or y are not numbers.')
|
category = 'Arithmetic'
|
||||||
|
__doc__ = doc = _('multiply(x, y) -- returns x * y. Throws an exception if either x or y are not numbers.')
|
||||||
|
|
||||||
def evaluate(self, formatter, kwargs, mi, locals, x, y):
|
def evaluate(self, formatter, kwargs, mi, locals, x, y):
|
||||||
x = float(x if x else 0)
|
x = float(x if x else 0)
|
||||||
@ -167,7 +167,8 @@ class BuiltinMultiply(BuiltinFormatterFunction):
|
|||||||
class BuiltinDivide(BuiltinFormatterFunction):
|
class BuiltinDivide(BuiltinFormatterFunction):
|
||||||
name = 'divide'
|
name = 'divide'
|
||||||
arg_count = 2
|
arg_count = 2
|
||||||
doc = _('divide(x, y) -- returns x / y. Throws an exception if either x or y are not numbers.')
|
category = 'Arithmetic'
|
||||||
|
__doc__ = doc = _('divide(x, y) -- returns x / y. Throws an exception if either x or y are not numbers.')
|
||||||
|
|
||||||
def evaluate(self, formatter, kwargs, mi, locals, x, y):
|
def evaluate(self, formatter, kwargs, mi, locals, x, y):
|
||||||
x = float(x if x else 0)
|
x = float(x if x else 0)
|
||||||
@ -177,7 +178,9 @@ class BuiltinDivide(BuiltinFormatterFunction):
|
|||||||
class BuiltinTemplate(BuiltinFormatterFunction):
|
class BuiltinTemplate(BuiltinFormatterFunction):
|
||||||
name = 'template'
|
name = 'template'
|
||||||
arg_count = 1
|
arg_count = 1
|
||||||
doc = _('template(x) -- evaluates x as a template. The evaluation is done '
|
category = 'Recursion'
|
||||||
|
|
||||||
|
__doc__ = doc = _('template(x) -- evaluates x as a template. The evaluation is done '
|
||||||
'in its own context, meaning that variables are not shared between '
|
'in its own context, meaning that variables are not shared between '
|
||||||
'the caller and the template evaluation. Because the { and } '
|
'the caller and the template evaluation. Because the { and } '
|
||||||
'characters are special, you must use [[ for the { character and '
|
'characters are special, you must use [[ for the { character and '
|
||||||
@ -192,7 +195,8 @@ class BuiltinTemplate(BuiltinFormatterFunction):
|
|||||||
class BuiltinEval(BuiltinFormatterFunction):
|
class BuiltinEval(BuiltinFormatterFunction):
|
||||||
name = 'eval'
|
name = 'eval'
|
||||||
arg_count = 1
|
arg_count = 1
|
||||||
doc = _('eval(template) -- evaluates the template, passing the local '
|
category = 'Recursion'
|
||||||
|
__doc__ = doc = _('eval(template) -- evaluates the template, passing the local '
|
||||||
'variables (those \'assign\'ed to) instead of the book metadata. '
|
'variables (those \'assign\'ed to) instead of the book metadata. '
|
||||||
' This permits using the template processor to construct complex '
|
' This permits using the template processor to construct complex '
|
||||||
'results from local variables.')
|
'results from local variables.')
|
||||||
@ -205,7 +209,8 @@ class BuiltinEval(BuiltinFormatterFunction):
|
|||||||
class BuiltinAssign(BuiltinFormatterFunction):
|
class BuiltinAssign(BuiltinFormatterFunction):
|
||||||
name = 'assign'
|
name = 'assign'
|
||||||
arg_count = 2
|
arg_count = 2
|
||||||
doc = _('assign(id, val) -- assigns val to id, then returns val. '
|
category = 'Other'
|
||||||
|
__doc__ = doc = _('assign(id, val) -- assigns val to id, then returns val. '
|
||||||
'id must be an identifier, not an expression')
|
'id must be an identifier, not an expression')
|
||||||
|
|
||||||
def evaluate(self, formatter, kwargs, mi, locals, target, value):
|
def evaluate(self, formatter, kwargs, mi, locals, target, value):
|
||||||
@ -215,7 +220,8 @@ class BuiltinAssign(BuiltinFormatterFunction):
|
|||||||
class BuiltinPrint(BuiltinFormatterFunction):
|
class BuiltinPrint(BuiltinFormatterFunction):
|
||||||
name = 'print'
|
name = 'print'
|
||||||
arg_count = -1
|
arg_count = -1
|
||||||
doc = _('print(a, b, ...) -- prints the arguments to standard output. '
|
category = 'Other'
|
||||||
|
__doc__ = doc = _('print(a, b, ...) -- prints the arguments to standard output. '
|
||||||
'Unless you start calibre from the command line (calibre-debug -g), '
|
'Unless you start calibre from the command line (calibre-debug -g), '
|
||||||
'the output will go to a black hole.')
|
'the output will go to a black hole.')
|
||||||
|
|
||||||
@ -226,15 +232,17 @@ class BuiltinPrint(BuiltinFormatterFunction):
|
|||||||
class BuiltinField(BuiltinFormatterFunction):
|
class BuiltinField(BuiltinFormatterFunction):
|
||||||
name = 'field'
|
name = 'field'
|
||||||
arg_count = 1
|
arg_count = 1
|
||||||
doc = _('field(name) -- returns the metadata field named by name')
|
category = 'Get values from metadata'
|
||||||
|
__doc__ = doc = _('field(name) -- returns the metadata field named by name')
|
||||||
|
|
||||||
def evaluate(self, formatter, kwargs, mi, locals, name):
|
def evaluate(self, formatter, kwargs, mi, locals, name):
|
||||||
return formatter.get_value(name, [], kwargs)
|
return formatter.get_value(name, [], kwargs)
|
||||||
|
|
||||||
class BuiltinRaw_field(BuiltinFormatterFunction):
|
class BuiltinRawField(BuiltinFormatterFunction):
|
||||||
name = 'raw_field'
|
name = 'raw_field'
|
||||||
arg_count = 1
|
arg_count = 1
|
||||||
doc = _('raw_field(name) -- returns the metadata field named by name '
|
category = 'Get values from metadata'
|
||||||
|
__doc__ = doc = _('raw_field(name) -- returns the metadata field named by name '
|
||||||
'without applying any formatting.')
|
'without applying any formatting.')
|
||||||
|
|
||||||
def evaluate(self, formatter, kwargs, mi, locals, name):
|
def evaluate(self, formatter, kwargs, mi, locals, name):
|
||||||
@ -243,7 +251,8 @@ class BuiltinRaw_field(BuiltinFormatterFunction):
|
|||||||
class BuiltinSubstr(BuiltinFormatterFunction):
|
class BuiltinSubstr(BuiltinFormatterFunction):
|
||||||
name = 'substr'
|
name = 'substr'
|
||||||
arg_count = 3
|
arg_count = 3
|
||||||
doc = _('substr(str, start, end) -- returns the start\'th through the end\'th '
|
category = 'String Manipulation'
|
||||||
|
__doc__ = doc = _('substr(str, start, end) -- returns the start\'th through the end\'th '
|
||||||
'characters of str. The first character in str is the zero\'th '
|
'characters of str. The first character in str is the zero\'th '
|
||||||
'character. If end is negative, then it indicates that many '
|
'character. If end is negative, then it indicates that many '
|
||||||
'characters counting from the right. If end is zero, then it '
|
'characters counting from the right. If end is zero, then it '
|
||||||
@ -256,7 +265,8 @@ class BuiltinSubstr(BuiltinFormatterFunction):
|
|||||||
class BuiltinLookup(BuiltinFormatterFunction):
|
class BuiltinLookup(BuiltinFormatterFunction):
|
||||||
name = 'lookup'
|
name = 'lookup'
|
||||||
arg_count = -1
|
arg_count = -1
|
||||||
doc = _('lookup(val, pattern, field, pattern, field, ..., else_field) -- '
|
category = 'Iterating over values'
|
||||||
|
__doc__ = doc = _('lookup(val, pattern, field, pattern, field, ..., else_field) -- '
|
||||||
'like switch, except the arguments are field (metadata) names, not '
|
'like switch, except the arguments are field (metadata) names, not '
|
||||||
'text. The value of the appropriate field will be fetched and used. '
|
'text. The value of the appropriate field will be fetched and used. '
|
||||||
'Note that because composite columns are fields, you can use this '
|
'Note that because composite columns are fields, you can use this '
|
||||||
@ -276,14 +286,15 @@ class BuiltinLookup(BuiltinFormatterFunction):
|
|||||||
while i < len(args):
|
while i < len(args):
|
||||||
if i + 1 >= len(args):
|
if i + 1 >= len(args):
|
||||||
return formatter.vformat('{' + args[i].strip() + '}', [], kwargs)
|
return formatter.vformat('{' + args[i].strip() + '}', [], kwargs)
|
||||||
if re.search(args[i], val):
|
if re.search(args[i], val, flags=re.I):
|
||||||
return formatter.vformat('{'+args[i+1].strip() + '}', [], kwargs)
|
return formatter.vformat('{'+args[i+1].strip() + '}', [], kwargs)
|
||||||
i += 2
|
i += 2
|
||||||
|
|
||||||
class BuiltinTest(BuiltinFormatterFunction):
|
class BuiltinTest(BuiltinFormatterFunction):
|
||||||
name = 'test'
|
name = 'test'
|
||||||
arg_count = 3
|
arg_count = 3
|
||||||
doc = _('test(val, text if not empty, text if empty) -- return `text if not '
|
category = 'If-then-else'
|
||||||
|
__doc__ = doc = _('test(val, text if not empty, text if empty) -- return `text if not '
|
||||||
'empty` if the field is not empty, otherwise return `text if empty`')
|
'empty` if the field is not empty, otherwise return `text if empty`')
|
||||||
|
|
||||||
def evaluate(self, formatter, kwargs, mi, locals, val, value_if_set, value_not_set):
|
def evaluate(self, formatter, kwargs, mi, locals, val, value_if_set, value_not_set):
|
||||||
@ -295,14 +306,15 @@ class BuiltinTest(BuiltinFormatterFunction):
|
|||||||
class BuiltinContains(BuiltinFormatterFunction):
|
class BuiltinContains(BuiltinFormatterFunction):
|
||||||
name = 'contains'
|
name = 'contains'
|
||||||
arg_count = 4
|
arg_count = 4
|
||||||
doc = _('contains(val, pattern, text if match, text if not match) -- checks '
|
category = 'If-then-else'
|
||||||
|
__doc__ = doc = _('contains(val, pattern, text if match, text if not match) -- checks '
|
||||||
'if field contains matches for the regular expression `pattern`. '
|
'if field contains matches for the regular expression `pattern`. '
|
||||||
'Returns `text if match` if matches are found, otherwise it returns '
|
'Returns `text if match` if matches are found, otherwise it returns '
|
||||||
'`text if no match`')
|
'`text if no match`')
|
||||||
|
|
||||||
def evaluate(self, formatter, kwargs, mi, locals,
|
def evaluate(self, formatter, kwargs, mi, locals,
|
||||||
val, test, value_if_present, value_if_not):
|
val, test, value_if_present, value_if_not):
|
||||||
if re.search(test, val):
|
if re.search(test, val, flags=re.I):
|
||||||
return value_if_present
|
return value_if_present
|
||||||
else:
|
else:
|
||||||
return value_if_not
|
return value_if_not
|
||||||
@ -310,7 +322,8 @@ class BuiltinContains(BuiltinFormatterFunction):
|
|||||||
class BuiltinSwitch(BuiltinFormatterFunction):
|
class BuiltinSwitch(BuiltinFormatterFunction):
|
||||||
name = 'switch'
|
name = 'switch'
|
||||||
arg_count = -1
|
arg_count = -1
|
||||||
doc = _('switch(val, pattern, value, pattern, value, ..., else_value) -- '
|
category = 'Iterating over values'
|
||||||
|
__doc__ = doc = _('switch(val, pattern, value, pattern, value, ..., else_value) -- '
|
||||||
'for each `pattern, value` pair, checks if the field matches '
|
'for each `pattern, value` pair, checks if the field matches '
|
||||||
'the regular expression `pattern` and if so, returns that '
|
'the regular expression `pattern` and if so, returns that '
|
||||||
'`value`. If no pattern matches, then else_value is returned. '
|
'`value`. If no pattern matches, then else_value is returned. '
|
||||||
@ -323,14 +336,15 @@ class BuiltinSwitch(BuiltinFormatterFunction):
|
|||||||
while i < len(args):
|
while i < len(args):
|
||||||
if i + 1 >= len(args):
|
if i + 1 >= len(args):
|
||||||
return args[i]
|
return args[i]
|
||||||
if re.search(args[i], val):
|
if re.search(args[i], val, flags=re.I):
|
||||||
return args[i+1]
|
return args[i+1]
|
||||||
i += 2
|
i += 2
|
||||||
|
|
||||||
class BuiltinInList(BuiltinFormatterFunction):
|
class BuiltinInList(BuiltinFormatterFunction):
|
||||||
name = 'in_list'
|
name = 'in_list'
|
||||||
arg_count = 5
|
arg_count = 5
|
||||||
doc = _('in_list(val, separator, pattern, found_val, not_found_val) -- '
|
category = 'List Lookup'
|
||||||
|
__doc__ = doc = _('in_list(val, separator, pattern, found_val, not_found_val) -- '
|
||||||
'treat val as a list of items separated by separator, '
|
'treat val as a list of items separated by separator, '
|
||||||
'comparing the pattern against each value in the list. If the '
|
'comparing the pattern against each value in the list. If the '
|
||||||
'pattern matches a value, return found_val, otherwise return '
|
'pattern matches a value, return found_val, otherwise return '
|
||||||
@ -338,26 +352,51 @@ class BuiltinInList(BuiltinFormatterFunction):
|
|||||||
|
|
||||||
def evaluate(self, formatter, kwargs, mi, locals, val, sep, pat, fv, nfv):
|
def evaluate(self, formatter, kwargs, mi, locals, val, sep, pat, fv, nfv):
|
||||||
l = [v.strip() for v in val.split(sep) if v.strip()]
|
l = [v.strip() for v in val.split(sep) if v.strip()]
|
||||||
for v in l:
|
if l:
|
||||||
if re.search(pat, v):
|
for v in l:
|
||||||
return fv
|
if re.search(pat, v, flags=re.I):
|
||||||
|
return fv
|
||||||
|
return nfv
|
||||||
|
|
||||||
|
class BuiltinStrInList(BuiltinFormatterFunction):
|
||||||
|
name = 'str_in_list'
|
||||||
|
arg_count = 5
|
||||||
|
category = 'List Lookup'
|
||||||
|
category = 'Iterating over values'
|
||||||
|
__doc__ = doc = _('str_in_list(val, separator, string, found_val, not_found_val) -- '
|
||||||
|
'treat val as a list of items separated by separator, '
|
||||||
|
'comparing the string against each value in the list. If the '
|
||||||
|
'string matches a value, return found_val, otherwise return '
|
||||||
|
'not_found_val. If the string contains separators, then it is '
|
||||||
|
'also treated as a list and each value is checked.')
|
||||||
|
|
||||||
|
def evaluate(self, formatter, kwargs, mi, locals, val, sep, str, fv, nfv):
|
||||||
|
l = [v.strip() for v in val.split(sep) if v.strip()]
|
||||||
|
c = [v.strip() for v in str.split(sep) if v.strip()]
|
||||||
|
if l:
|
||||||
|
for v in l:
|
||||||
|
for t in c:
|
||||||
|
if strcmp(t, v) == 0:
|
||||||
|
return fv
|
||||||
return nfv
|
return nfv
|
||||||
|
|
||||||
class BuiltinRe(BuiltinFormatterFunction):
|
class BuiltinRe(BuiltinFormatterFunction):
|
||||||
name = 're'
|
name = 're'
|
||||||
arg_count = 3
|
arg_count = 3
|
||||||
doc = _('re(val, pattern, replacement) -- return the field after applying '
|
category = 'String Manipulation'
|
||||||
|
__doc__ = doc = _('re(val, pattern, replacement) -- return the field after applying '
|
||||||
'the regular expression. All instances of `pattern` are replaced '
|
'the regular expression. All instances of `pattern` are replaced '
|
||||||
'with `replacement`. As in all of calibre, these are '
|
'with `replacement`. As in all of calibre, these are '
|
||||||
'python-compatible regular expressions')
|
'python-compatible regular expressions')
|
||||||
|
|
||||||
def evaluate(self, formatter, kwargs, mi, locals, val, pattern, replacement):
|
def evaluate(self, formatter, kwargs, mi, locals, val, pattern, replacement):
|
||||||
return re.sub(pattern, replacement, val)
|
return re.sub(pattern, replacement, val, flags=re.I)
|
||||||
|
|
||||||
class BuiltinIfempty(BuiltinFormatterFunction):
|
class BuiltinIfempty(BuiltinFormatterFunction):
|
||||||
name = 'ifempty'
|
name = 'ifempty'
|
||||||
arg_count = 2
|
arg_count = 2
|
||||||
doc = _('ifempty(val, text if empty) -- return val if val is not empty, '
|
category = 'If-then-else'
|
||||||
|
__doc__ = doc = _('ifempty(val, text if empty) -- return val if val is not empty, '
|
||||||
'otherwise return `text if empty`')
|
'otherwise return `text if empty`')
|
||||||
|
|
||||||
def evaluate(self, formatter, kwargs, mi, locals, val, value_if_empty):
|
def evaluate(self, formatter, kwargs, mi, locals, val, value_if_empty):
|
||||||
@ -369,7 +408,8 @@ class BuiltinIfempty(BuiltinFormatterFunction):
|
|||||||
class BuiltinShorten(BuiltinFormatterFunction):
|
class BuiltinShorten(BuiltinFormatterFunction):
|
||||||
name = 'shorten'
|
name = 'shorten'
|
||||||
arg_count = 4
|
arg_count = 4
|
||||||
doc = _('shorten(val, left chars, middle text, right chars) -- Return a '
|
category = 'String Manipulation'
|
||||||
|
__doc__ = doc = _('shorten(val, left chars, middle text, right chars) -- Return a '
|
||||||
'shortened version of the field, consisting of `left chars` '
|
'shortened version of the field, consisting of `left chars` '
|
||||||
'characters from the beginning of the field, followed by '
|
'characters from the beginning of the field, followed by '
|
||||||
'`middle text`, followed by `right chars` characters from '
|
'`middle text`, followed by `right chars` characters from '
|
||||||
@ -394,7 +434,8 @@ class BuiltinShorten(BuiltinFormatterFunction):
|
|||||||
class BuiltinCount(BuiltinFormatterFunction):
|
class BuiltinCount(BuiltinFormatterFunction):
|
||||||
name = 'count'
|
name = 'count'
|
||||||
arg_count = 2
|
arg_count = 2
|
||||||
doc = _('count(val, separator) -- interprets the value as a list of items '
|
category = 'List Manipulation'
|
||||||
|
__doc__ = doc = _('count(val, separator) -- interprets the value as a list of items '
|
||||||
'separated by `separator`, returning the number of items in the '
|
'separated by `separator`, returning the number of items in the '
|
||||||
'list. Most lists use a comma as the separator, but authors '
|
'list. Most lists use a comma as the separator, but authors '
|
||||||
'uses an ampersand. Examples: {tags:count(,)}, {authors:count(&)}')
|
'uses an ampersand. Examples: {tags:count(,)}, {authors:count(&)}')
|
||||||
@ -405,7 +446,8 @@ class BuiltinCount(BuiltinFormatterFunction):
|
|||||||
class BuiltinListitem(BuiltinFormatterFunction):
|
class BuiltinListitem(BuiltinFormatterFunction):
|
||||||
name = 'list_item'
|
name = 'list_item'
|
||||||
arg_count = 3
|
arg_count = 3
|
||||||
doc = _('list_item(val, index, separator) -- interpret the value as a list of '
|
category = 'List Lookup'
|
||||||
|
__doc__ = doc = _('list_item(val, index, separator) -- interpret the value as a list of '
|
||||||
'items separated by `separator`, returning the `index`th item. '
|
'items separated by `separator`, returning the `index`th item. '
|
||||||
'The first item is number zero. The last item can be returned '
|
'The first item is number zero. The last item can be returned '
|
||||||
'using `list_item(-1,separator)`. If the item is not in the list, '
|
'using `list_item(-1,separator)`. If the item is not in the list, '
|
||||||
@ -425,7 +467,8 @@ class BuiltinListitem(BuiltinFormatterFunction):
|
|||||||
class BuiltinSelect(BuiltinFormatterFunction):
|
class BuiltinSelect(BuiltinFormatterFunction):
|
||||||
name = 'select'
|
name = 'select'
|
||||||
arg_count = 2
|
arg_count = 2
|
||||||
doc = _('select(val, key) -- interpret the value as a comma-separated list '
|
category = 'List Lookup'
|
||||||
|
__doc__ = doc = _('select(val, key) -- interpret the value as a comma-separated list '
|
||||||
'of items, with the items being "id:value". Find the pair with the'
|
'of items, with the items being "id:value". Find the pair with the'
|
||||||
'id equal to key, and return the corresponding value.'
|
'id equal to key, and return the corresponding value.'
|
||||||
)
|
)
|
||||||
@ -442,9 +485,10 @@ class BuiltinSelect(BuiltinFormatterFunction):
|
|||||||
class BuiltinSublist(BuiltinFormatterFunction):
|
class BuiltinSublist(BuiltinFormatterFunction):
|
||||||
name = 'sublist'
|
name = 'sublist'
|
||||||
arg_count = 4
|
arg_count = 4
|
||||||
doc = _('sublist(val, start_index, end_index, separator) -- interpret the '
|
category = 'List Manipulation'
|
||||||
|
__doc__ = doc = _('sublist(val, start_index, end_index, separator) -- interpret the '
|
||||||
'value as a list of items separated by `separator`, returning a '
|
'value as a list of items separated by `separator`, returning a '
|
||||||
'new list made from the `start_index`th to the `end_index`th item. '
|
'new list made from the `start_index` to the `end_index` item. '
|
||||||
'The first item is number zero. If an index is negative, then it '
|
'The first item is number zero. If an index is negative, then it '
|
||||||
'counts from the end of the list. As a special case, an end_index '
|
'counts from the end of the list. As a special case, an end_index '
|
||||||
'of zero is assumed to be the length of the list. Examples using '
|
'of zero is assumed to be the length of the list. Examples using '
|
||||||
@ -452,7 +496,8 @@ class BuiltinSublist(BuiltinFormatterFunction):
|
|||||||
'comma-separated) contains "A, B, C": '
|
'comma-separated) contains "A, B, C": '
|
||||||
'{tags:sublist(0,1,\,)} returns "A". '
|
'{tags:sublist(0,1,\,)} returns "A". '
|
||||||
'{tags:sublist(-1,0,\,)} returns "C". '
|
'{tags:sublist(-1,0,\,)} returns "C". '
|
||||||
'{tags:sublist(0,-1,\,)} returns "A, B".')
|
'{tags:sublist(0,-1,\,)} returns "A, B".'
|
||||||
|
)
|
||||||
|
|
||||||
def evaluate(self, formatter, kwargs, mi, locals, val, start_index, end_index, sep):
|
def evaluate(self, formatter, kwargs, mi, locals, val, start_index, end_index, sep):
|
||||||
if not val:
|
if not val:
|
||||||
@ -471,12 +516,13 @@ class BuiltinSublist(BuiltinFormatterFunction):
|
|||||||
class BuiltinSubitems(BuiltinFormatterFunction):
|
class BuiltinSubitems(BuiltinFormatterFunction):
|
||||||
name = 'subitems'
|
name = 'subitems'
|
||||||
arg_count = 3
|
arg_count = 3
|
||||||
doc = _('subitems(val, start_index, end_index) -- This function is used to '
|
category = 'List Manipulation'
|
||||||
|
__doc__ = doc = _('subitems(val, start_index, end_index) -- This function is used to '
|
||||||
'break apart lists of items such as genres. It interprets the value '
|
'break apart lists of items such as genres. It interprets the value '
|
||||||
'as a comma-separated list of items, where each item is a period-'
|
'as a comma-separated list of items, where each item is a period-'
|
||||||
'separated list. Returns a new list made by first finding all the '
|
'separated list. Returns a new list made by first finding all the '
|
||||||
'period-separated items, then for each such item extracting the '
|
'period-separated items, then for each such item extracting the '
|
||||||
'start_index`th to the `end_index`th components, then combining '
|
'start_index` to the `end_index` components, then combining '
|
||||||
'the results back together. The first component in a period-'
|
'the results back together. The first component in a period-'
|
||||||
'separated list has an index of zero. If an index is negative, '
|
'separated list has an index of zero. If an index is negative, '
|
||||||
'then it counts from the end of the list. As a special case, an '
|
'then it counts from the end of the list. As a special case, an '
|
||||||
@ -505,11 +551,12 @@ class BuiltinSubitems(BuiltinFormatterFunction):
|
|||||||
pass
|
pass
|
||||||
return ', '.join(sorted(rv, key=sort_key))
|
return ', '.join(sorted(rv, key=sort_key))
|
||||||
|
|
||||||
class BuiltinFormat_date(BuiltinFormatterFunction):
|
class BuiltinFormatDate(BuiltinFormatterFunction):
|
||||||
name = 'format_date'
|
name = 'format_date'
|
||||||
arg_count = 2
|
arg_count = 2
|
||||||
doc = _('format_date(val, format_string) -- format the value, which must '
|
category = 'Get values from metadata'
|
||||||
'be a date field, using the format_string, returning a string. '
|
__doc__ = doc = _('format_date(val, format_string) -- format the value, '
|
||||||
|
'which must be a date, using the format_string, returning a string. '
|
||||||
'The formatting codes are: '
|
'The formatting codes are: '
|
||||||
'd : the day as number without a leading zero (1 to 31) '
|
'd : the day as number without a leading zero (1 to 31) '
|
||||||
'dd : the day as number with a leading zero (01 to 31) '
|
'dd : the day as number with a leading zero (01 to 31) '
|
||||||
@ -524,7 +571,7 @@ class BuiltinFormat_date(BuiltinFormatterFunction):
|
|||||||
'iso : the date with time and timezone. Must be the only format present')
|
'iso : the date with time and timezone. Must be the only format present')
|
||||||
|
|
||||||
def evaluate(self, formatter, kwargs, mi, locals, val, format_string):
|
def evaluate(self, formatter, kwargs, mi, locals, val, format_string):
|
||||||
if not val:
|
if not val or val == 'None':
|
||||||
return ''
|
return ''
|
||||||
try:
|
try:
|
||||||
dt = parse_date(val)
|
dt = parse_date(val)
|
||||||
@ -536,7 +583,8 @@ class BuiltinFormat_date(BuiltinFormatterFunction):
|
|||||||
class BuiltinUppercase(BuiltinFormatterFunction):
|
class BuiltinUppercase(BuiltinFormatterFunction):
|
||||||
name = 'uppercase'
|
name = 'uppercase'
|
||||||
arg_count = 1
|
arg_count = 1
|
||||||
doc = _('uppercase(val) -- return value of the field in upper case')
|
category = 'String case changes'
|
||||||
|
__doc__ = doc = _('uppercase(val) -- return value of the field in upper case')
|
||||||
|
|
||||||
def evaluate(self, formatter, kwargs, mi, locals, val):
|
def evaluate(self, formatter, kwargs, mi, locals, val):
|
||||||
return val.upper()
|
return val.upper()
|
||||||
@ -544,7 +592,8 @@ class BuiltinUppercase(BuiltinFormatterFunction):
|
|||||||
class BuiltinLowercase(BuiltinFormatterFunction):
|
class BuiltinLowercase(BuiltinFormatterFunction):
|
||||||
name = 'lowercase'
|
name = 'lowercase'
|
||||||
arg_count = 1
|
arg_count = 1
|
||||||
doc = _('lowercase(val) -- return value of the field in lower case')
|
category = 'String case changes'
|
||||||
|
__doc__ = doc = _('lowercase(val) -- return value of the field in lower case')
|
||||||
|
|
||||||
def evaluate(self, formatter, kwargs, mi, locals, val):
|
def evaluate(self, formatter, kwargs, mi, locals, val):
|
||||||
return val.lower()
|
return val.lower()
|
||||||
@ -552,7 +601,8 @@ class BuiltinLowercase(BuiltinFormatterFunction):
|
|||||||
class BuiltinTitlecase(BuiltinFormatterFunction):
|
class BuiltinTitlecase(BuiltinFormatterFunction):
|
||||||
name = 'titlecase'
|
name = 'titlecase'
|
||||||
arg_count = 1
|
arg_count = 1
|
||||||
doc = _('titlecase(val) -- return value of the field in title case')
|
category = 'String case changes'
|
||||||
|
__doc__ = doc = _('titlecase(val) -- return value of the field in title case')
|
||||||
|
|
||||||
def evaluate(self, formatter, kwargs, mi, locals, val):
|
def evaluate(self, formatter, kwargs, mi, locals, val):
|
||||||
return titlecase(val)
|
return titlecase(val)
|
||||||
@ -560,7 +610,8 @@ class BuiltinTitlecase(BuiltinFormatterFunction):
|
|||||||
class BuiltinCapitalize(BuiltinFormatterFunction):
|
class BuiltinCapitalize(BuiltinFormatterFunction):
|
||||||
name = 'capitalize'
|
name = 'capitalize'
|
||||||
arg_count = 1
|
arg_count = 1
|
||||||
doc = _('capitalize(val) -- return value of the field capitalized')
|
category = 'String case changes'
|
||||||
|
__doc__ = doc = _('capitalize(val) -- return value of the field capitalized')
|
||||||
|
|
||||||
def evaluate(self, formatter, kwargs, mi, locals, val):
|
def evaluate(self, formatter, kwargs, mi, locals, val):
|
||||||
return capitalize(val)
|
return capitalize(val)
|
||||||
@ -568,7 +619,8 @@ class BuiltinCapitalize(BuiltinFormatterFunction):
|
|||||||
class BuiltinBooksize(BuiltinFormatterFunction):
|
class BuiltinBooksize(BuiltinFormatterFunction):
|
||||||
name = 'booksize'
|
name = 'booksize'
|
||||||
arg_count = 0
|
arg_count = 0
|
||||||
doc = _('booksize() -- return value of the field capitalized')
|
category = 'Get values from metadata'
|
||||||
|
__doc__ = doc = _('booksize() -- return value of the size field')
|
||||||
|
|
||||||
def evaluate(self, formatter, kwargs, mi, locals):
|
def evaluate(self, formatter, kwargs, mi, locals):
|
||||||
if mi.book_size is not None:
|
if mi.book_size is not None:
|
||||||
@ -578,10 +630,23 @@ class BuiltinBooksize(BuiltinFormatterFunction):
|
|||||||
pass
|
pass
|
||||||
return ''
|
return ''
|
||||||
|
|
||||||
|
class BuiltinOndevice(BuiltinFormatterFunction):
|
||||||
|
name = 'ondevice'
|
||||||
|
arg_count = 0
|
||||||
|
category = 'Get values from metadata'
|
||||||
|
__doc__ = doc = _('ondevice() -- return Yes if ondevice is set, otherwise return '
|
||||||
|
'the empty string')
|
||||||
|
|
||||||
|
def evaluate(self, formatter, kwargs, mi, locals):
|
||||||
|
if mi.ondevice_col:
|
||||||
|
return _('Yes')
|
||||||
|
return ''
|
||||||
|
|
||||||
class BuiltinFirstNonEmpty(BuiltinFormatterFunction):
|
class BuiltinFirstNonEmpty(BuiltinFormatterFunction):
|
||||||
name = 'first_non_empty'
|
name = 'first_non_empty'
|
||||||
arg_count = -1
|
arg_count = -1
|
||||||
doc = _('first_non_empty(value, value, ...) -- '
|
category = 'Iterating over values'
|
||||||
|
__doc__ = doc = _('first_non_empty(value, value, ...) -- '
|
||||||
'returns the first value that is not empty. If all values are '
|
'returns the first value that is not empty. If all values are '
|
||||||
'empty, then the empty value is returned.'
|
'empty, then the empty value is returned.'
|
||||||
'You can have as many values as you want.')
|
'You can have as many values as you want.')
|
||||||
@ -597,7 +662,8 @@ class BuiltinFirstNonEmpty(BuiltinFormatterFunction):
|
|||||||
class BuiltinAnd(BuiltinFormatterFunction):
|
class BuiltinAnd(BuiltinFormatterFunction):
|
||||||
name = 'and'
|
name = 'and'
|
||||||
arg_count = -1
|
arg_count = -1
|
||||||
doc = _('and(value, value, ...) -- '
|
category = 'Boolean'
|
||||||
|
__doc__ = doc = _('and(value, value, ...) -- '
|
||||||
'returns the string "1" if all values are not empty, otherwise '
|
'returns the string "1" if all values are not empty, otherwise '
|
||||||
'returns the empty string. This function works well with test or '
|
'returns the empty string. This function works well with test or '
|
||||||
'first_non_empty. You can have as many values as you want.')
|
'first_non_empty. You can have as many values as you want.')
|
||||||
@ -613,7 +679,8 @@ class BuiltinAnd(BuiltinFormatterFunction):
|
|||||||
class BuiltinOr(BuiltinFormatterFunction):
|
class BuiltinOr(BuiltinFormatterFunction):
|
||||||
name = 'or'
|
name = 'or'
|
||||||
arg_count = -1
|
arg_count = -1
|
||||||
doc = _('or(value, value, ...) -- '
|
category = 'Boolean'
|
||||||
|
__doc__ = doc = _('or(value, value, ...) -- '
|
||||||
'returns the string "1" if any value is not empty, otherwise '
|
'returns the string "1" if any value is not empty, otherwise '
|
||||||
'returns the empty string. This function works well with test or '
|
'returns the empty string. This function works well with test or '
|
||||||
'first_non_empty. You can have as many values as you want.')
|
'first_non_empty. You can have as many values as you want.')
|
||||||
@ -629,7 +696,8 @@ class BuiltinOr(BuiltinFormatterFunction):
|
|||||||
class BuiltinNot(BuiltinFormatterFunction):
|
class BuiltinNot(BuiltinFormatterFunction):
|
||||||
name = 'not'
|
name = 'not'
|
||||||
arg_count = 1
|
arg_count = 1
|
||||||
doc = _('not(value) -- '
|
category = 'Boolean'
|
||||||
|
__doc__ = doc = _('not(value) -- '
|
||||||
'returns the string "1" if the value is empty, otherwise '
|
'returns the string "1" if the value is empty, otherwise '
|
||||||
'returns the empty string. This function works well with test or '
|
'returns the empty string. This function works well with test or '
|
||||||
'first_non_empty. You can have as many values as you want.')
|
'first_non_empty. You can have as many values as you want.')
|
||||||
@ -645,7 +713,8 @@ class BuiltinNot(BuiltinFormatterFunction):
|
|||||||
class BuiltinMergeLists(BuiltinFormatterFunction):
|
class BuiltinMergeLists(BuiltinFormatterFunction):
|
||||||
name = 'merge_lists'
|
name = 'merge_lists'
|
||||||
arg_count = 3
|
arg_count = 3
|
||||||
doc = _('merge_lists(list1, list2, separator) -- '
|
category = 'List Manipulation'
|
||||||
|
__doc__ = doc = _('merge_lists(list1, list2, separator) -- '
|
||||||
'return a list made by merging the items in list1 and list2, '
|
'return a list made by merging the items in list1 and list2, '
|
||||||
'removing duplicate items using a case-insensitive compare. If '
|
'removing duplicate items using a case-insensitive compare. If '
|
||||||
'items differ in case, the one in list1 is used. '
|
'items differ in case, the one in list1 is used. '
|
||||||
@ -678,7 +747,7 @@ builtin_divide = BuiltinDivide()
|
|||||||
builtin_eval = BuiltinEval()
|
builtin_eval = BuiltinEval()
|
||||||
builtin_first_non_empty = BuiltinFirstNonEmpty()
|
builtin_first_non_empty = BuiltinFirstNonEmpty()
|
||||||
builtin_field = BuiltinField()
|
builtin_field = BuiltinField()
|
||||||
builtin_format_date = BuiltinFormat_date()
|
builtin_format_date = BuiltinFormatDate()
|
||||||
builtin_ifempty = BuiltinIfempty()
|
builtin_ifempty = BuiltinIfempty()
|
||||||
builtin_in_list = BuiltinInList()
|
builtin_in_list = BuiltinInList()
|
||||||
builtin_list_item = BuiltinListitem()
|
builtin_list_item = BuiltinListitem()
|
||||||
@ -687,14 +756,16 @@ builtin_lowercase = BuiltinLowercase()
|
|||||||
builtin_merge_lists = BuiltinMergeLists()
|
builtin_merge_lists = BuiltinMergeLists()
|
||||||
builtin_multiply = BuiltinMultiply()
|
builtin_multiply = BuiltinMultiply()
|
||||||
builtin_not = BuiltinNot()
|
builtin_not = BuiltinNot()
|
||||||
|
builtin_ondevice = BuiltinOndevice()
|
||||||
builtin_or = BuiltinOr()
|
builtin_or = BuiltinOr()
|
||||||
builtin_print = BuiltinPrint()
|
builtin_print = BuiltinPrint()
|
||||||
builtin_raw_field = BuiltinRaw_field()
|
builtin_raw_field = BuiltinRawField()
|
||||||
builtin_re = BuiltinRe()
|
builtin_re = BuiltinRe()
|
||||||
builtin_select = BuiltinSelect()
|
builtin_select = BuiltinSelect()
|
||||||
builtin_shorten = BuiltinShorten()
|
builtin_shorten = BuiltinShorten()
|
||||||
builtin_strcat = BuiltinStrcat()
|
builtin_strcat = BuiltinStrcat()
|
||||||
builtin_strcmp = BuiltinStrcmp()
|
builtin_strcmp = BuiltinStrcmp()
|
||||||
|
builtin_str_in_list = BuiltinStrInList()
|
||||||
builtin_subitems = BuiltinSubitems()
|
builtin_subitems = BuiltinSubitems()
|
||||||
builtin_sublist = BuiltinSublist()
|
builtin_sublist = BuiltinSublist()
|
||||||
builtin_substr = BuiltinSubstr()
|
builtin_substr = BuiltinSubstr()
|
||||||
|
@ -1123,6 +1123,13 @@ class ZipFile:
|
|||||||
targetpath = os.sep.join(components)
|
targetpath = os.sep.join(components)
|
||||||
with open(targetpath, 'wb') as target:
|
with open(targetpath, 'wb') as target:
|
||||||
shutil.copyfileobj(source, target)
|
shutil.copyfileobj(source, target)
|
||||||
|
# Kovid: Try to preserve the timestamps in the ZIP file
|
||||||
|
try:
|
||||||
|
mtime = time.localtime()
|
||||||
|
mtime = time.mktime(member.date_time + (0, 0) + (mtime.tm_isdst,))
|
||||||
|
os.utime(targetpath, (mtime, mtime))
|
||||||
|
except:
|
||||||
|
pass
|
||||||
self.extract_mapping[member.filename] = targetpath
|
self.extract_mapping[member.filename] = targetpath
|
||||||
return targetpath
|
return targetpath
|
||||||
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user