Sync to trunk.

This commit is contained in:
John Schember 2011-05-30 17:33:53 -04:00
commit 0ed8cf0f70
216 changed files with 78435 additions and 43325 deletions

View File

@ -478,7 +478,7 @@
type: major
description : >
"You can now save your frequently used searches and access them with a single click. For details
see http://calibre-ebook.com/user_manual/gui.html#search-sort"
see http://manual.calibre-ebook.com/gui.html#search-sort"
- title: "Add searching by date/published date"
tickets: [5244]

View File

@ -19,6 +19,134 @@
# new recipes:
# - title:
- version: 0.8.3
date: 2011-05-27
new features:
- title: "Allow the coloring of columns in the book list."
description: "You can either create a custom column with a fixed set of values and assign a color to each value, or you can use the calibre template language to color any column in arbitrarily powerful ways. For example, you can have the title appear in red if the book has a particular tag."
type: major
- title: "Support for the Nook Simple Reader"
- title: "Get Books, new stores: Virtualo, lulu.net"
- title: "A store chooser dialog for Get Books (click the little preferences icon at the bottom of the Get Books screen)."
- title: "Add a merge_lists, and, or, not template functions to the calibre template language"
- title: "EPUB Output: Change any white-space:pre declarations in the CSS to pre-wrap to accomodate readers that cannot scroll horizontally."
tickets: [786722]
- title: "Windows installer: Remember and use previous installation folder when upgrading. Note that this will work for future upgrades, after this one."
bug fixes:
- title: "MOBI Output: Fix hidden tags with id attributes also hiding their trailing text"
tickets: [788570]
- title: "Fix switching from one news source to another via a search not saving changes to the scheduling of the first source"
tickets: [774849]
- title: "Dont allow user to use non email usernames when setting up Hotmail or Gmail accounts"
- title: "Amazon metadata download: Use separate identifiers for country specific downloads so that the links to Amazon in the Book details panel work when downloading metadata from country specific amazon websites."
tickets: [786146]
- title: "Nicer error message when user attempts to set title/author via Edit metadata dialog and one of the files is open in another program."
- title: "Fix {id} not working in send to device templates"
- title: "Windows: If creating a bytestring temp dir fails, create a unicode one and hope the rest of calibre can handle it"
- title: "Get Books: Fix some results from Amazon missing."
tickets: [785962]
improved recipes:
- Kathermini
- Faz.net
- The Washington Post
- El Mundo
- Marca
- The Nation
new recipes:
- title: Various German news sources
author: schuster
- title: "George R. R. Martin's Blog"
author: Darko Miletic
- title: "Focus (DE) and National Geographic"
auhtor: Anonymous
- version: 0.8.2
date: 2011-05-20
new features:
- title: "Various new ebook sources added to Get Books: Google Books, O'Reilly, archive.org, some Polish ebooks stores, etc."
- title: "Amazon metadata download: Allow user to configure Amazon plugin to use any of the US, UK, German, French and Italian Amazon websites"
- title: "When deleting large numbers of books, give the user the option to skip the Recycle Bin, since sending lots of files to the recycle bin can be very slow."
tickets: [784987]
- title: "OS X: The unified title+toolbar was disabled as it had various bugs. If you really want it you can turn it on again via Preferences->Tweaks, but be aware that you will see problems like the calibre windowd being too wide, weird animations when a device is detected, etc."
- title: "Add a tweak that controls what words are treated as suffixes when generating an author sort string from an author name."
- title: "Get Books: Store last few searches in history"
bug fixes:
- title: "Fix a crash when a device is connected/disconnected while a modal dialog opened from the toolbar is visible"
tickets: [780484]
- title: "Fix incorrect results from ebooks.com when searching via Get Books"
- title: "Metadata plugboards: Add prioritization scheme to allow for using different settings for different locations"
tickets: [783229]
- title: "Fix manage authors dialog too wide"
tickets: [783065]
- title: "Fix multiple bracket types in author names not handled correctly when generating author sort string"
tickets: [782551]
- title: "MOBI Input: Don't error out when detecting TOC structure if one of the elements has an invalid margin unit"
- title: "More fixes for japanese language calibre on windows"
tickets: [782408]
- title: "Linux binaries: Always use either Cleanlook or Plastique styles for the GUI if no style can be loaded from the host computer"
improved recipes:
- Newsweek
- Economist
- Dvhn
- United Daily
- Dagens Nyheter
- GoComics
- faz.net
- golem.de
new recipes:
- title: National Geographic
author: gagsays
- title: Various German news sources
author: schuster
- title: Dilema Veche
author: Silviu Cotoara
- title: "Glamour, Good to Know, Good Housekeeping and Men's Health"
author: Anonymous
- title: "Financial Sense and iProfessional"
author: Darko Miletic
- version: 0.8.1
date: 2011-05-13
@ -456,7 +584,7 @@
- title: "FB2 Output: Option to set the FB2 genre explicitly."
tickets: [743178]
- title: "Plugin developers: calibre now has a new plugin API, see http://calibre-ebook.com/user_manual/creating_plugins.html. Your existing plugins should continue to work, but it would be good to test them to make sure."
- title: "Plugin developers: calibre now has a new plugin API, see http://manual.calibre-ebook.com/creating_plugins.html. Your existing plugins should continue to work, but it would be good to test them to make sure."
bug fixes:
- title: "Fix text color in the search bar set to black instead of the system font color"
@ -841,7 +969,7 @@
new features:
- title: "Tag Browser: Support the creation of nested User Categories"
description: "See http://calibre-ebook.com/user_manual/gui.html#tag-browser for details"
description: "See http://manual.calibre-ebook.com/gui.html#tag-browser for details"
type: major
- title: "Disable Kent District Library plugin to download series information. The website could not handle the load calibre's 2 million users put on it. You can manually re-enable it if you really want series information, but it is very slow"
@ -3714,7 +3842,7 @@
type: major
description: >
"You can now change the icons used in the User Interface and other static resources. Details on how to
do this are at: http://calibre-ebook.com/user_manual/customize.html#overriding-icons-templates-etcetera"
do this are at: http://manual.calibre-ebook.com/customize.html#overriding-icons-templates-etcetera"
- title: "Split the 'Send to device' button into two buttons, 'Connect/share' and 'Send to device'. The new 'Send to device' button will now only be available when a device is connected."

View File

@ -3,7 +3,7 @@ calibre supports installation from source, only on Linux.
Note that you *do not* need to install from source to hack on
the calibre source code. To get started with calibre development,
use a normal calibre install and follow the instructions at
http://calibre-ebook.com/user_manual/develop.html
http://manual.calibre-ebook.com/develop.html
On Linux, there are two kinds of installation from source possible.
Note that both kinds require lots of dependencies as well as a

4
README
View File

@ -6,8 +6,8 @@ reading. It is cross platform, running on Linux, Windows and OS X.
For screenshots: https://calibre-ebook.com/demo
For installation/usage instructions please see
http://calibre-ebook.com/user_manual
For usage instructions please see
http://manual.calibre-ebook.com
For source code access:
bzr branch lp:calibre

BIN
icons/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 158 KiB

View File

@ -0,0 +1,42 @@
from calibre.web.feeds.recipes import BasicNewsRecipe
class AdvancedUserRecipe(BasicNewsRecipe):
title = u'Aachener Nachrichten'
__author__ = 'schuster'
oldest_article = 1
max_articles_per_feed = 100
use_embedded_content = False
language = 'de'
remove_javascript = True
cover_url = 'http://www.an-online.de/einwaage/images/an_logo.png'
masthead_url = 'http://www.an-online.de/einwaage/images/an_logo.png'
extra_css = '''
.fliesstext_detail:{margin-bottom:10%;}
.headline_1:{margin-bottom:25%;}
b{font-family:Arial,Helvetica,sans-serif; font-weight:200;font-size:large;}
a{font-family:Arial,Helvetica,sans-serif; font-weight:400;font-size:large;}
ll{font-family:Arial,Helvetica,sans-serif; font-weight:100;font-size:large;}
h4{font-family:Arial,Helvetica,sans-serif; font-weight:normal;font-size:small;}
img {min-width:300px; max-width:600px; min-height:300px; max-height:800px}
dd{font-family:Arial,Helvetica,sans-serif;font-size:large;}
body{font-family:Helvetica,Arial,sans-serif;font-size:small;}
'''
keep_only_tags = [
dict(name='span', attrs={'class':['fliesstext_detail', 'headline_1', 'autor_detail']}),
dict(id=['header-logo'])
]
feeds = [(u'Euregio', u'http://www.an-online.de/an/rss/Euregio.xml'),
(u'Aachen', u'http://www.an-online.de/an/rss/Aachen.xml'),
(u'Nordkreis', u'http://www.an-online.de/an/rss/Nordkreis.xml'),
(u'Düren', u'http://www.an-online.de/an/rss/Dueren.xml'),
(u'Eiffel', u'http://www.an-online.de/an/rss/Eifel.xml'),
(u'Eschweiler', u'http://www.an-online.de/an/rss/Eschweiler.xml'),
(u'Geilenkirchen', u'http://www.an-online.de/an/rss/Geilenkirchen.xml'),
(u'Heinsberg', u'http://www.an-online.de/an/rss/Heinsberg.xml'),
(u'Jülich', u'http://www.an-online.de/an/rss/Juelich.xml'),
(u'Stolberg', u'http://www.an-online.de/an/rss/Stolberg.xml'),
(u'Ratgebenr', u'http://www.an-online.de/an/rss/Ratgeber.xml')]

View 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'])
]

View File

@ -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
class DilemaVeche(BasicNewsRecipe):
title = u'Dilema Veche'
__author__ = u'Silviu Cotoar\u0103'
description = u'Sunt vechi, domnule!'
publisher = u'Dilema Veche'
oldest_article = 50
language = 'ro'
max_articles_per_feed = 100
no_stylesheets = True
use_embedded_content = False
category = 'Ziare'
encoding = 'utf-8'
cover_url = 'http://www.dilemaveche.ro/sites/all/themes/dilema/theme/dilema_two/layouter/dilema_two_homepage/logo.png'
conversion_options = {
'comments' : description
,'tags' : category
,'language' : language
,'publisher' : publisher
}
keep_only_tags = [
dict(name='h1', attrs={'class':'art_title'})
, dict(name='h1', attrs={'class':'art_title online'})
, dict(name='div', attrs={'class':'item'})
, dict(name='div', attrs={'class':'art_content'})
]
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__ = 'song2' # inspirat din scriptul pentru Le Monde. Inspired from the Le Monde script
description = '"Sint vechi, domnule!" (I.L. Caragiale)'
publisher = 'Adevarul Holding'
oldest_article = 7
max_articles_per_feed = 200
encoding = 'utf8'
language = 'ro'
masthead_url = 'http://www.dilemaveche.ro/sites/all/themes/dilema/theme/dilema_two/layouter/dilema_two_homepage/logo.png'
publication_type = 'magazine'
feeds = [
('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'),
('Editoriale si opinii - Bordeie si obiceie', 'http://www.dilemaveche.ro/taxonomy/term/44/0/feed'),
('Editoriale si opinii - Talc Show', 'http://www.dilemaveche.ro/taxonomy/term/44/0/feed'),
('Tema saptamanii', 'http://www.dilemaveche.ro/taxonomy/term/19/0/feed'),
('La zi in cultura - Dilema va recomanda', 'http://www.dilemaveche.ro/taxonomy/term/58/0/feed'),
('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'),
('La zi in cultura - Arte performative', 'http://www.dilemaveche.ro/taxonomy/term/1342/0/feed'),
('La zi in cultura - Arte vizuale', 'http://www.dilemaveche.ro/taxonomy/term/1512/0/feed'),
('Societate - Ieri cu vedere spre azi', 'http://www.dilemaveche.ro/taxonomy/term/15/0/feed'),
('Societate - Din polul opus', 'http://www.dilemaveche.ro/taxonomy/term/41/0/feed'),
('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 = [
dict(name='div', attrs={'class':['article_details']})
, dict(name='div', attrs={'class':['controale']})
, dict(name='div', attrs={'class':['art_related_left']})
]
dict(name='div', attrs={'class':'art_related_left'}),
dict(name='div', attrs={'class':'controale'}),
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)

View File

@ -14,7 +14,7 @@ class Economist(BasicNewsRecipe):
description = ('Global news and current affairs from a European'
' perspective. Best downloaded on Friday mornings (GMT).'
' Much slower than the print edition based version.')
extra_css = '.headline {font-size: x-large;} \n h2 { font-size: small; } \n h1 { font-size: medium; }'
oldest_article = 7.0
cover_url = 'http://www.economist.com/images/covers/currentcoverus_large.jpg'
remove_tags = [

View File

@ -1,6 +1,6 @@
__license__ = 'GPL v3'
__copyright__ = '2009, Darko Miletic <darko.miletic at gmail.com>'
__copyright__ = '2009-2011, Darko Miletic <darko.miletic at gmail.com>'
'''
elmundo.es
'''
@ -10,15 +10,24 @@ from calibre.web.feeds.news import BasicNewsRecipe
class ElMundo(BasicNewsRecipe):
title = 'El Mundo'
__author__ = 'Darko Miletic'
description = 'News from Spain'
publisher = 'El Mundo'
description = 'Lider de informacion en espaniol'
publisher = 'Unidad Editorial Informacion General S.L.U.'
category = 'news, politics, Spain'
oldest_article = 2
max_articles_per_feed = 100
no_stylesheets = True
use_embedded_content = False
encoding = 'iso8859_15'
language = 'es'
language = 'es_ES'
masthead_url = 'http://estaticos03.elmundo.es/elmundo/iconos/v4.x/v4.01/bg_h1.png'
publication_type = 'newspaper'
extra_css = """
body{font-family: Arial,Helvetica,sans-serif}
.metadata_noticia{font-size: small}
h1,h2,h3,h4,h5,h6,.subtitulo {color: #3F5974}
.hora{color: red}
.update{color: gray}
"""
conversion_options = {
'comments' : description
@ -30,22 +39,31 @@ class ElMundo(BasicNewsRecipe):
keep_only_tags = [dict(name='div', attrs={'class':'noticia'})]
remove_tags_before = dict(attrs={'class':['titular','antetitulo'] })
remove_tags_after = dict(name='div' , attrs={'id':['desarrollo_noticia','tamano']})
remove_attributes = ['lang','border']
remove_tags = [
dict(name='div', attrs={'class':['herramientas','publicidad_google']})
,dict(name='div', attrs={'id':'modulo_multimedia' })
,dict(name='ul', attrs={'class':'herramientas' })
,dict(name=['object','link'])
,dict(name=['object','link','embed','iframe','base','meta'])
]
feeds = [
(u'Portada' , u'http://rss.elmundo.es/rss/descarga.htm?data2=4' )
,(u'Deportes' , u'http://rss.elmundo.es/rss/descarga.htm?data2=14')
,(u'Economia' , u'http://rss.elmundo.es/rss/descarga.htm?data2=7' )
,(u'Espana' , u'http://rss.elmundo.es/rss/descarga.htm?data2=8' )
,(u'Internacional' , u'http://rss.elmundo.es/rss/descarga.htm?data2=9' )
,(u'Cultura' , u'http://rss.elmundo.es/rss/descarga.htm?data2=6' )
,(u'Ciencia/Ecologia', u'http://rss.elmundo.es/rss/descarga.htm?data2=5' )
,(u'Comunicacion' , u'http://rss.elmundo.es/rss/descarga.htm?data2=26')
,(u'Television' , u'http://rss.elmundo.es/rss/descarga.htm?data2=76')
(u'Portada' , u'http://estaticos.elmundo.es/elmundo/rss/portada.xml' )
,(u'Deportes' , u'http://estaticos.elmundo.es/elmundodeporte/rss/portada.xml')
,(u'Economia' , u'http://estaticos.elmundo.es/elmundo/rss/economia.xml' )
,(u'Espana' , u'http://estaticos.elmundo.es/elmundo/rss/espana.xml' )
,(u'Internacional' , u'http://estaticos.elmundo.es/elmundo/rss/internacional.xml' )
,(u'Cultura' , u'http://estaticos.elmundo.es/elmundo/rss/cultura.xml' )
,(u'Ciencia/Ecologia', u'http://estaticos.elmundo.es/elmundo/rss/ciencia.xml' )
,(u'Comunicacion' , u'http://estaticos.elmundo.es/elmundo/rss/comunicacion.xml' )
,(u'Television' , u'http://estaticos.elmundo.es/elmundo/rss/television.xml' )
]
def preprocess_html(self, soup):
for item in soup.findAll(style=True):
del item['style']
return soup
def get_article_url(self, article):
return article.get('guid', None)

View File

@ -1,38 +1,63 @@
from calibre.web.feeds.recipes import BasicNewsRecipe
class AdvancedUserRecipe1303841067(BasicNewsRecipe):
__license__ = 'GPL v3'
__copyright__ = '2008-2011, Kovid Goyal <kovid at kovidgoyal.net>, Darko Miletic <darko at gmail.com>'
'''
Profile to download FAZ.NET
'''
title = u'Faz.net'
__author__ = 'schuster'
remove_tags = [dict(attrs={'class':['right', 'ArrowLinkRight', 'ModulVerlagsInfo', 'left', 'Head']}),
dict(id=['BreadCrumbs', 'tstag', 'FazFooterPrint']),
dict(name=['script', 'noscript', 'style'])]
oldest_article = 2
from calibre.web.feeds.news import BasicNewsRecipe
class FazNet(BasicNewsRecipe):
title = 'FAZ.NET'
__author__ = 'Kovid Goyal, Darko Miletic'
description = 'Frankfurter Allgemeine Zeitung'
max_articles_per_feed = 100
no_stylesheets = True
use_embedded_content = False
language = 'de'
remove_javascript = True
cover_url = 'http://www.faz.net/f30/Images/Logos/logo.gif'
publisher = 'Frankfurter Allgemeine Zeitung GmbH'
category = 'news, politics, Germany'
use_embedded_content = False
language = 'de'
def print_version(self, url):
return url.replace('.html', '~Afor~Eprint.html')
max_articles_per_feed = 30
no_stylesheets = True
encoding = 'utf-8'
remove_javascript = True
html2lrf_options = [
'--comment', description
, '--category', category
, '--publisher', publisher
]
html2epub_options = 'publisher="' + publisher + '"\ncomments="' + description + '"\ntags="' + category + '"'
feeds = [(u'Politik', u'http://www.faz.net/s/RubA24ECD630CAE40E483841DB7D16F4211/Tpl~Epartner~SRss_.xml'),
(u'Wirtschaft', u'http://www.faz.net/s/RubC9401175958F4DE28E143E68888825F6/Tpl~Epartner~SRss_.xml'),
(u'Feuilleton', u'http://www.faz.net/s/RubCC21B04EE95145B3AC877C874FB1B611/Tpl~Epartner~SRss_.xml'),
(u'Sport', u'http://www.faz.net/s/Rub9F27A221597D4C39A82856B0FE79F051/Tpl~Epartner~SRss_.xml'),
(u'Gesellschaft', u'http://www.faz.net/s/Rub02DBAA63F9EB43CEB421272A670A685C/Tpl~Epartner~SRss_.xml'),
(u'Finanzen', u'http://www.faz.net/s/Rub4B891837ECD14082816D9E088A2D7CB4/Tpl~Epartner~SRss_.xml'),
(u'Wissen', u'http://www.faz.net/s/Rub7F4BEE0E0C39429A8565089709B70C44/Tpl~Epartner~SRss_.xml'),
(u'Reise', u'http://www.faz.net/s/RubE2FB5CA667054BDEA70FB3BC45F8D91C/Tpl~Epartner~SRss_.xml'),
(u'Technik & Motor', u'http://www.faz.net/s/Rub01E4D53776494844A85FDF23F5707AD8/Tpl~Epartner~SRss_.xml'),
(u'Beruf & Chance', u'http://www.faz.net/s/RubB1E10A8367E8446897468EDAA6EA0504/Tpl~Epartner~SRss_.xml'),
(u'Kunstmarkt', u'http://www.faz.net/s/RubBC09F7BF72A2405A96718ECBFB68FBFE/Tpl~Epartner~SRss_.xml'),
(u'Immobilien ', u'http://www.faz.net/s/RubFED172A9E10F46B3A5F01B02098C0C8D/Tpl~Epartner~SRss_.xml'),
(u'Rhein-Main Zeitung', u'http://www.faz.net/s/RubABE881A6669742C2A5EBCB5D50D7EBEE/Tpl~Epartner~SRss_.xml'),
(u'Atomdebatte ', u'http://www.faz.net/s/Rub469C43057F8C437CACC2DE9ED41B7950/Tpl~Epartner~SRss_.xml')
]
keep_only_tags = [dict(name='div', attrs={'class':'Article'})]
remove_tags = [
dict(name=['object','link','embed','base'])
,dict(name='div',
attrs={'class':['LinkBoxModulSmall','ModulVerlagsInfo',
'ArtikelServices', 'ModulLesermeinungenFooter',
'ModulArtikelServices', 'BoxTool Aufklappen_Grau',
'SocialMediaUnten', ]}),
dict(id=['KurzLinkMenu', 'ArtikelServicesMenu']),
]
feeds = [
('FAZ.NET Aktuell', 'http://www.faz.net/s/RubF3CE08B362D244869BE7984590CB6AC1/Tpl~Epartner~SRss_.xml'),
('Politik', 'http://www.faz.net/s/RubA24ECD630CAE40E483841DB7D16F4211/Tpl~Epartner~SRss_.xml'),
('Wirtschaft', 'http://www.faz.net/s/RubC9401175958F4DE28E143E68888825F6/Tpl~Epartner~SRss_.xml'),
('Feuilleton', 'http://www.faz.net/s/RubCC21B04EE95145B3AC877C874FB1B611/Tpl~Epartner~SRss_.xml'),
('Sport', 'http://www.faz.net/s/Rub9F27A221597D4C39A82856B0FE79F051/Tpl~Epartner~SRss_.xml'),
('Gesellschaft', 'http://www.faz.net/s/Rub02DBAA63F9EB43CEB421272A670A685C/Tpl~Epartner~SRss_.xml'),
('Finanzen', 'http://www.faz.net/s/Rub4B891837ECD14082816D9E088A2D7CB4/Tpl~Epartner~SRss_.xml'),
('Wissen', 'http://www.faz.net/s/Rub7F4BEE0E0C39429A8565089709B70C44/Tpl~Epartner~SRss_.xml'),
('Reise', 'http://www.faz.net/s/RubE2FB5CA667054BDEA70FB3BC45F8D91C/Tpl~Epartner~SRss_.xml'),
('Technik & Motor', 'http://www.faz.net/s/Rub01E4D53776494844A85FDF23F5707AD8/Tpl~Epartner~SRss_.xml'),
('Beruf & Chance', 'http://www.faz.net/s/RubB1E10A8367E8446897468EDAA6EA0504/Tpl~Epartner~SRss_.xml')
]
def preprocess_html(self, soup):
mtag = '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>'
soup.head.insert(0,mtag)
del soup.body['onload']
for item in soup.findAll(style=True):
del item['style']
return soup

48
recipes/focus_de.recipe Normal file
View File

@ -0,0 +1,48 @@
from calibre.web.feeds.news import BasicNewsRecipe
class AdvancedUserRecipe1305567197(BasicNewsRecipe):
title = u'Focus (DE)'
__author__ = 'Anonymous'
language = 'de'
oldest_article = 7
max_articles_per_feed = 100
no_stylesheets = True
use_embedded_content = False
remove_javascript = True
def print_version(self, url):
return url + '?drucken=1'
keep_only_tags = [
dict(name='div', attrs={'id':['article']}) ]
remove_tags = [dict(name='div', attrs={'class':'sidebar'}),
dict(name='div', attrs={'class':'commentForm'}),
dict(name='div', attrs={'class':'comment clearfix oid-3534591 open'}),
dict(name='div', attrs={'class':'similarityBlock'}),
dict(name='div', attrs={'class':'footer'}),
dict(name='div', attrs={'class':'getMoreComments'}),
dict(name='div', attrs={'class':'moreComments'}),
dict(name='div', attrs={'class':'ads'}),
dict(name='div', attrs={'class':'articleContent'}),
]
remove_tags_after = [
dict(name='div',attrs={'class':['commentForm','title', 'actions clearfix']})
]
feeds = [ (u'Eilmeldungen', u'http://rss2.focus.de/c/32191/f/533875/index.rss'),
(u'Auto-News', u'http://rss2.focus.de/c/32191/f/443320/index.rss'),
(u'Digital-News', u'http://rss2.focus.de/c/32191/f/443315/index.rss'),
(u'Finanzen-News', u'http://rss2.focus.de/c/32191/f/443317/index.rss'),
(u'Gesundheit-News', u'http://rss2.focus.de/c/32191/f/443314/index.rss'),
(u'Immobilien-News', u'http://rss2.focus.de/c/32191/f/443318/index.rss'),
(u'Kultur-News', u'http://rss2.focus.de/c/32191/f/443321/index.rss'),
(u'Panorama-News', u'http://rss2.focus.de/c/32191/f/533877/index.rss'),
(u'Politik-News', u'http://rss2.focus.de/c/32191/f/443313/index.rss'),
(u'Reisen-News', u'http://rss2.focus.de/c/32191/f/443316/index.rss'),
(u'Sport-News', u'http://rss2.focus.de/c/32191/f/443319/index.rss'),
(u'Wissen-News', u'http://rss2.focus.de/c/32191/f/533876/index.rss'),
]

View File

@ -0,0 +1,35 @@
from calibre.web.feeds.recipes import BasicNewsRecipe
class AdvancedUserRecipe(BasicNewsRecipe):
title = u'Frankfurter Rundschau'
__author__ = 'schuster'
oldest_article = 1
max_articles_per_feed = 100
no_stylesheets = True
use_embedded_content = False
language = 'de'
remove_javascript = True
cover_url = 'http://www.fr-online.de/image/view/-/1474018/data/823538/-/logo.png'
extra_css = '''
h1{font-family:Arial,Helvetica,sans-serif; font-weight:bold;font-size:large;}
h4{font-family:Arial,Helvetica,sans-serif; font-weight:normal;font-size:small;}
img {min-width:300px; max-width:600px; min-height:300px; max-height:800px}
p{font-family:Arial,Helvetica,sans-serif;font-size:small;}
body{font-family:Helvetica,Arial,sans-serif;font-size:small;}
'''
feeds = [(u'Startseite', u'http://www.fr-online.de/home/-/1472778/1472778/-/view/asFeed/-/index.xml'),
(u'Politik', u'http://www.fr-online.de/politik/-/1472596/1472596/-/view/asFeed/-/index.xml'),
(u'Meinungen', u'http://www.fr-online.de/politik/meinung/-/1472602/1472602/-/view/asFeed/-/index.xml'),
(u'Wirtschaft', u'http://www.fr-online.de/wirtschaft/-/1472780/1472780/-/view/asFeed/-/index.xml'),
(u'Sport', u'http://www.fr-online.de/sport/-/1472784/1472784/-/view/asFeed/-/index.xml'),
(u'Kultur', u'http://www.fr-online.de/kultur/-/1472786/1472786/-/view/asFeed/-/index.xml'),
(u'Panorama', u'http://www.fr-online.de/panorama/-/1472782/1472782/-/view/asFeed/-/index.xml'),
(u'Digital', u'http://www.fr-online.de/digital/-/1472406/1472406/-/view/asFeed/-/index.xml'),
(u'Wissenschaft', u'http://www.fr-online.de/wissenschaft/-/1472788/1472788/-/view/asFeed/-/index.xml')
]
def print_version(self, url):
return url.replace('index.html', 'view/printVersion/-/index.html')

36
recipes/grrm.recipe Normal file
View File

@ -0,0 +1,36 @@
__license__ = 'GPL v3'
__copyright__ = '2011, Darko Miletic <darko.miletic at gmail.com>'
'''
grrm.livejournal.com
'''
from calibre.web.feeds.news import BasicNewsRecipe
class NotABlog(BasicNewsRecipe):
title = 'Not A Blog - George R.R. Martin'
__author__ = 'Darko Miletic'
description = 'George R.R. Martin'
oldest_article = 15
max_articles_per_feed = 100
language = 'en'
encoding = 'utf-8'
no_stylesheets = True
use_embedded_content = True
publication_type = 'blog'
conversion_options = {
'comment' : description
, 'tags' : 'sf, fantasy, game of thrones'
, 'publisher': 'George R.R. Martin'
, 'language' : language
}
feeds = [(u'Posts', u'http://grrm.livejournal.com/data/rss')]
def preprocess_html(self, soup):
for item in soup.findAll(style=True):
del item['style']
return self.adeify_images(soup)

Binary file not shown.

Before

Width:  |  Height:  |  Size: 550 B

After

Width:  |  Height:  |  Size: 1.1 KiB

BIN
recipes/icons/marca.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 293 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 925 B

BIN
recipes/icons/wash_post.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

View File

@ -5,14 +5,16 @@ class Kathimerini(BasicNewsRecipe):
__author__ = 'Pan'
description = 'News from Greece'
max_articles_per_feed = 100
oldest_article = 100
oldest_article = 100
publisher = 'Kathimerini'
category = 'news, GR'
language = 'el'
encoding = 'windows-1253'
conversion_options = { 'linearize_tables': True}
no_stylesheets = True
remove_tags_before = dict(name='td',attrs={'class':'news'})
remove_tags_after = dict(name='td',attrs={'class':'news'})
remove_attributes = ['width', 'src','header','footer']
remove_tags_before = dict(name='td',attrs={'class':'news'})
remove_tags_after = dict(name='td',attrs={'class':'news'})
remove_attributes = ['width', 'src','header','footer']
feeds = [(u'\u03a0\u03bf\u03bb\u03b9\u03c4\u03b9\u03ba\u03ae',
'http://wk.kathimerini.gr/xml_files/politics.xml'),
@ -34,4 +36,3 @@ class Kathimerini(BasicNewsRecipe):
def print_version(self, url):
return url.replace('http://news.kathimerini.gr/4dcgi/', 'http://news.kathimerini.gr/4dcgi/4dcgi/')

View File

@ -1,14 +1,11 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__license__ = 'GPL v3'
__copyright__ = '2009, Darko Miletic <darko.miletic at gmail.com>'
__copyright__ = '2009-2011, Darko Miletic <darko.miletic at gmail.com>'
'''
www.marca.com
'''
from calibre.web.feeds.news import BasicNewsRecipe
from calibre.ebooks.BeautifulSoup import Tag
class Marca(BasicNewsRecipe):
title = 'Marca'
@ -22,35 +19,30 @@ class Marca(BasicNewsRecipe):
use_embedded_content = False
delay = 1
encoding = 'iso-8859-15'
language = 'es'
language = 'es_ES'
publication_type = 'newsportal'
masthead_url = 'http://estaticos.marca.com/deporte/img/v3.0/img_marca-com.png'
extra_css = """
body{font-family: Tahoma,Geneva,sans-serif}
h1,h2,h3,h4,h5,h6{font-family: 'LatoBlack',Tahoma,Geneva,sans-serif}
.cab_articulo h4 {font-family: Georgia,"Times New Roman",Times,serif}
.antetitulo{text-transform: uppercase}
"""
direction = 'ltr'
feeds = [(u'Portada', u'http://estaticos.marca.com/rss/portada.xml')]
html2lrf_options = [
'--comment' , description
, '--category' , category
, '--publisher', publisher
]
html2epub_options = 'publisher="' + publisher + '"\ncomments="' + description + '"\ntags="' + category + '"'
feeds = [(u'Portada', u'http://rss.marca.com/rss/descarga.htm?data2=425')]
keep_only_tags = [dict(name='div', attrs={'class':['cab_articulo','col_izq']})]
remove_tags = [
dict(name=['object','link','script'])
,dict(name='div', attrs={'class':['colC','peu']})
,dict(name='div', attrs={'class':['utilidades estirar','bloque_int_corr estirar']})
keep_only_tags = [dict(name='div', attrs={'class':['cab_articulo','cuerpo_articulo']})]
remove_attributes = ['lang']
remove_tags = [
dict(name=['object','link','script','embed','iframe','meta','base'])
,dict(name='div', attrs={'class':'tabs'})
]
remove_tags_after = [dict(name='div', attrs={'class':'bloque_int_corr estirar'})]
def preprocess_html(self, soup):
soup.html['dir' ] = self.direction
mcharset = Tag(soup,'meta',[("http-equiv","Content-Type"),("content","text/html; charset=utf-8")])
soup.head.insert(0,mcharset)
for item in soup.findAll(style=True):
del item['style']
return soup
def get_article_url(self, article):
return article.get('guid', None)

View File

@ -71,7 +71,7 @@ class Mediapart(BasicNewsRecipe):
br = BasicNewsRecipe.get_browser()
if self.username is not None and self.password is not None:
br.open('http://www.mediapart.fr/')
br.select_form(nr=1)
br.select_form(nr=0)
br['name'] = self.username
br['pass'] = self.password
br.submit()

29
recipes/metro_uk.recipe Normal file
View 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/')]

View File

@ -0,0 +1,25 @@
from calibre.web.feeds.news import BasicNewsRecipe
class AdvancedUserRecipe1305567197(BasicNewsRecipe):
title = u'National Geographic (DE)'
__author__ = 'Anonymous'
language = 'de'
oldest_article = 7
max_articles_per_feed = 1000
no_stylesheets = True
use_embedded_content = False
remove_javascript = True
cover_url = 'http://www.nationalgeographic.de/images/national-geographic-logo.jpg'
keep_only_tags = [
dict(name='div', attrs={'class':['contentbox_no_top_border']}) ]
remove_tags = [
dict(name='div', attrs={'class':'related'}),
dict(name='li', attrs={'class':'first'}),
dict(name='div', attrs={'class':'extrasbox_inner'}),
]
feeds = [ (u'National Geographic', u'http://feeds.nationalgeographic.de/ng-neueste-artikel'),
]

View 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

View File

@ -0,0 +1,55 @@
from calibre.web.feeds.recipes import BasicNewsRecipe
class AdvancedUserRecipe(BasicNewsRecipe):
title = u'RP-online'
__author__ = 'schuster'
oldest_article = 2
max_articles_per_feed = 100
no_stylesheets = True
use_embedded_content = False
language = 'de'
remove_javascript = True
masthead_url = 'http://www.die-zeitungen.de/uploads/pics/LOGO_RP_ONLINE_01.jpg'
cover_url = 'http://www.manroland.com/com/pressinfo_images/com/RheinischePost_Logo_300dpi.jpg'
extra_css = '''
h1{font-family:Arial,Helvetica,sans-serif; font-weight:bold;font-size:large;}
h4{font-family:Arial,Helvetica,sans-serif; font-weight:normal;font-size:small;}
img {min-width:300px; max-width:600px; min-height:300px; max-height:800px}
p{font-family:Arial,Helvetica,sans-serif;font-size:small;}
body{font-family:Helvetica,Arial,sans-serif;font-size:small;}
'''
remove_tags_before = dict(id='article_content')
remove_tags_after = dict(id='article_content')
remove_tags = [dict(attrs={'class':['goodies', 'left', 'right', 'clear-all', 'teaser anzeigenwerbung', 'lesermeinung', 'goodiebox', 'goodiebox 1', 'goodiebox 2', 'goodiebox 3', 'boxframe', 'link']}),
dict(id=['click_Fotos_link']),
dict(name=['script', 'noscript', 'style', '_top', 'click_Fotos_link'])]
feeds = [ (u'Top-News', u'http://www.ngz-online.de/app/feed/rss/topnews'),
(u'Politik', u'http://www.ngz-online.de/app/feed/rss/politik'),
(u'Wirtschaft', u'http://www.ngz-online.de/app/feed/rss/wirtschaft'),
(u'Panorama', u'http://www.ngz-online.de/app/feed/rss/panorama'),
(u'Sport', u'http://www.ngz-online.de/app/feed/rss/sport'),
(u'Tour de France', u'http://www.ngz-online.de/app/feed/rss/tourdefrance'),
(u'Fußball', u'http://www.ngz-online.de/app/feed/rss/fussball'),
(u'Fußball BuLi', u'http://www.ngz-online.de/app/feed/rss/bundesliga'),
(u'Formel 1', u'http://www.ngz-online.de/app/feed/rss/formel1'),
(u'US-Sport', u'http://www.ngz-online.de/app/feed/rss/us-sports'),
(u'Boxen', u'http://www.ngz-online.de/app/feed/rss/boxen'),
(u'Eishockey', u'http://www.ngz-online.de/app/feed/rss/eishockey'),
(u'Basketball', u'http://www.ngz-online.de/app/feed/rss/basketball'),
(u'Handball', u'http://www.ngz-online.de/app/feed/rss/handball'),
(u'Motorsport', u'http://www.ngz-online.de/app/feed/rss/motorsport'),
(u'Tennis', u'http://www.ngz-online.de/app/feed/rss/tennis'),
(u'Radsport', u'http://www.ngz-online.de/app/feed/rss/radsport'),
(u'Kultur', u'http://www.ngz-online.de/app/feed/rss/kultur'),
(u'Gesellschaft', u'http://www.ngz-online.de/app/feed/rss/gesellschaft'),
(u'Wissenschaft', u'http://www.ngz-online.de/app/feed/rss/wissen'),
(u'Gesundheit', u'http://www.ngz-online.de/app/feed/rss/gesundheit'),
(u'Digitale Welt', u'http://www.ngz-online.de/app/feed/rss/digitale'),
(u'Auto & Mobil', u'http://www.ngz-online.de/app/feed/rss/auto'),
(u'Reise & Welt', u'http://www.ngz-online.de/app/feed/rss/reise'),
(u'Beruf & Karriere', u'http://www.ngz-online.de/app/feed/rss/beruf'),
(u'Herzrasen', u'http://www.ngz-online.de/app/feed/rss/herzrasen'),
(u'About a Boy', u'http://www.ngz-online.de/app/feed/rss/about_a_boy'),
]

View File

@ -1,5 +1,5 @@
__license__ = 'GPL v3'
__copyright__ = '2008 - 2010, Darko Miletic <darko.miletic at gmail.com>'
__copyright__ = '2008 - 2011, Darko Miletic <darko.miletic at gmail.com>'
'''
thenation.com
'''
@ -16,10 +16,17 @@ class Thenation(BasicNewsRecipe):
max_articles_per_feed = 100
no_stylesheets = True
language = 'en'
use_embedded_content = False
delay = 1
masthead_url = 'http://www.thenation.com/sites/default/themes/thenation/images/logo-main.gif'
exra_css = ' body{font-family: Arial,Helvetica,sans-serif;} .print-created{font-size: small;} .caption{display: block; font-size: x-small;} '
use_embedded_content = False
delay = 1
masthead_url = 'http://www.thenation.com/sites/default/themes/thenation/images/logo-main.gif'
login_url = 'http://www.thenation.com/user?destination=%3Cfront%3E'
publication_type = 'magazine'
needs_subscription = 'optional'
exra_css = """
body{font-family: Arial,Helvetica,sans-serif;}
.print-created{font-size: small;}
.caption{display: block; font-size: x-small;}
"""
conversion_options = {
'comment' : description
@ -28,13 +35,30 @@ class Thenation(BasicNewsRecipe):
, 'language' : language
}
keep_only_tags = [ dict(attrs={'class':['print-title','print-created','print-content','print-links']}) ]
remove_tags = [dict(name='link')]
keep_only_tags = [dict(attrs={'class':['print-title','print-created','print-content','print-links']})]
remove_tags = [dict(name=['link','iframe','base','meta','object','embed'])]
remove_attributes = ['lang']
feeds = [(u"Editor's Picks", u'http://www.thenation.com/rss/editors_picks')]
feeds = [(u"Articles", u'http://www.thenation.com/rss/articles')]
def print_version(self, url):
return url.replace('.thenation.com/','.thenation.com/print/')
def preprocess_html(self, soup):
return self.adeify_images(soup)
def get_browser(self):
br = BasicNewsRecipe.get_browser()
br.open('http://www.thenation.com/')
if self.username is not None and self.password is not None:
br.open(self.login_url)
br.select_form(nr=1)
br['name'] = self.username
br['pass'] = self.password
br.submit()
return br
def get_cover_url(self):
soup = self.index_to_soup('http://www.thenation.com/issue/')
item = soup.find('div',attrs={'id':'cover-wrapper'})
if item:
return item.img['src']
return None

64
recipes/version2.recipe Normal file
View 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')
]

View File

@ -1,64 +1,75 @@
__license__ = 'GPL v3'
__copyright__ = '2011, Darko Miletic <darko.miletic at gmail.com>'
'''
www.washingtonpost.com
'''
from calibre import strftime
from calibre.web.feeds.news import BasicNewsRecipe
class TheWashingtonPost(BasicNewsRecipe):
title = 'The Washington Post'
__author__ = 'Darko Miletic'
description = 'Leading source for news, video and opinion on politics, business, world and national news, science, travel, entertainment and more. Our local coverage includes reporting on education, crime, weather, traffic, real estate, jobs and cars for DC, Maryland and Virginia. Offering award-winning opinion writing, entertainment information and restaurant reviews.'
publisher = 'The Washington Post Company'
category = 'news, politics, USA'
oldest_article = 2
max_articles_per_feed = 200
no_stylesheets = True
encoding = 'utf8'
delay = 1
use_embedded_content = False
language = 'en'
remove_empty_feeds = True
publication_type = 'newspaper'
masthead_url = 'http://www.washingtonpost.com/rw/sites/twpweb/img/logos/twp_logo_300.gif'
cover_url = strftime('http://www.washingtonpost.com/rw/WashingtonPost/Content/Epaper/%Y-%m-%d/Ax1.pdf')
extra_css = """
body{font-family: Georgia,serif }
"""
class WashingtonPost(BasicNewsRecipe):
conversion_options = {
'comment' : description
, 'tags' : category
, 'publisher' : publisher
, 'language' : language
}
title = 'Washington Post'
description = 'US political news'
__author__ = 'Kovid Goyal'
use_embedded_content = False
max_articles_per_feed = 20
language = 'en'
encoding = 'utf-8'
keep_only_tags = [dict(attrs={'id':['content','entryhead','entrytext']})]
remove_tags = [
dict(name=['meta','link','iframe','base'])
,dict(attrs={'id':'multimedia-leaf-page'})
]
remove_attributes= ['lang','property','epochtime','datetitle','pagetype','contenttype','comparetime']
remove_javascript = True
no_stylesheets = True
feeds = [
('Politics', 'http://www.washingtonpost.com/rss/politics'),
('Nation', 'http://www.washingtonpost.com/rss/national'),
('World', 'http://www.washingtonpost.com/rss/world'),
('Business', 'http://www.washingtonpost.com/rss/business'),
('Lifestyle', 'http://www.washingtonpost.com/rss/lifestyle'),
('Sports', 'http://www.washingtonpost.com/rss/sports'),
('Redskins', 'http://www.washingtonpost.com/rss/sports/redskins'),
('Opinions', 'http://www.washingtonpost.com/rss/opinions'),
('Entertainment', 'http://www.washingtonpost.com/rss/entertainment'),
('Local', 'http://www.washingtonpost.com/rss/local'),
('Investigations',
'http://www.washingtonpost.com/rss/investigations'),
]
remove_tags = [
{'class':lambda x: x and 'article-toolbar' in x},
{'class':lambda x: x and 'quick-comments' in x},
{'class':lambda x: x and 'tweet' in x},
{'class':lambda x: x and 'article-related' in x},
{'class':lambda x: x and 'hidden' in x.split()},
{'class':lambda x: x and 'also-read' in x.split()},
{'class':lambda x: x and 'partners-content' in x.split()},
{'class':['module share', 'module ads', 'comment-vars', 'hidden',
'share-icons-wrap', 'comments', 'flipper']},
{'id':['right-rail', 'save-and-share']},
{'width':'1', 'height':'1'},
]
keep_only_tags = dict(id=['content', 'article'])
def get_article_url(self, *args):
ans = BasicNewsRecipe.get_article_url(self, *args)
ans = ans.rpartition('?')[0]
if ans.endswith('_video.html'):
return None
if 'ads.pheedo.com' in ans:
return None
#if not ans.endswith('_blog.html'):
# return None
return ans
(u'World' , u'http://feeds.washingtonpost.com/rss/world' )
,(u'National' , u'http://feeds.washingtonpost.com/rss/national' )
,(u'White House' , u'http://feeds.washingtonpost.com/rss/politics/whitehouse' )
,(u'Business' , u'http://feeds.washingtonpost.com/rss/business' )
,(u'Opinions' , u'http://feeds.washingtonpost.com/rss/opinions' )
,(u'Investigations' , u'http://feeds.washingtonpost.com/rss/investigations' )
,(u'Local' , u'http://feeds.washingtonpost.com/rss/local' )
,(u'Entertainment' , u'http://feeds.washingtonpost.com/rss/entertainment' )
,(u'Sports' , u'http://feeds.washingtonpost.com/rss/sports' )
,(u'Redskins' , u'http://feeds.washingtonpost.com/rss/sports/redskins' )
,(u'Special Reports', u'http://feeds.washingtonpost.com/rss/national/special-reports')
]
def print_version(self, url):
return url.replace('_story.html', '_singlePage.html')
if '_story.html' in url:
return url.replace('_story.html','_print.html')
return url
def get_article_url(self, article):
link = BasicNewsRecipe.get_article_url(self,article)
if not 'washingtonpost.com' in link:
self.log('Skipping adds:', link)
return None
for it in ['_video.html','_gallery.html','_links.html']:
if it in link:
self.log('Skipping non-article:', link)
return None
return link

View File

@ -53,7 +53,8 @@ authors_completer_append_separator = False
# periods are automatically handled.
author_sort_copy_method = 'comma'
author_name_suffixes = ('Jr', 'Sr', 'Inc', 'Ph.D', 'Phd',
'MD', 'M.D', 'I', 'II', 'III', 'IV')
'MD', 'M.D', 'I', 'II', 'III', 'IV',
'Junior', 'Senior')
#: Use author sort in Tag Browser
# Set which author field to display in the tags pane (the list of authors,

View File

@ -1,33 +1,41 @@
{
"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",
"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, 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",
"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",
"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",
"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",
"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",
"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",
"field": "def evaluate(self, formatter, kwargs, mi, locals, name):\n return formatter.get_value(name, [], kwargs)\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",
"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",
"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",
"re": "def evaluate(self, formatter, kwargs, mi, locals, val, pattern, replacement):\n return re.sub(pattern, replacement, val)\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",
"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",
"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",
"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",
"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",
"test": "def evaluate(self, formatter, kwargs, mi, locals, val, value_if_set, value_not_set):\n if val:\n return value_if_set\n else:\n return value_not_set\n",
"eval": "def evaluate(self, formatter, kwargs, mi, locals, template):\n from formatter import eval_formatter\n template = template.replace('[[', '{').replace(']]', '}')\n return eval_formatter.safe_format(template, locals, 'EVAL', None)\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",
"not": "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",
"format_date": "def evaluate(self, formatter, kwargs, mi, locals, val, format_string):\n if not val:\n return ''\n try:\n dt = parse_date(val)\n s = format_date(dt, format_string)\n except:\n s = 'BAD DATE'\n return s\n",
"capitalize": "def evaluate(self, formatter, kwargs, mi, locals, val):\n return capitalize(val)\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",
"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",
"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",
"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",
"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",
"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"

View File

@ -12,7 +12,9 @@ is64bit = platform.architecture()[0] == '64bit'
iswindows = re.search('win(32|64)', sys.platform)
isosx = 'darwin' in sys.platform
isfreebsd = 'freebsd' in sys.platform
islinux = not isosx and not iswindows and not isfreebsd
isnetbsd = 'netbsd' in sys.platform
isbsd = isnetbsd or isfreebsd
islinux = not isosx and not iswindows and not isbsd
SRC = os.path.abspath('src')
sys.path.insert(0, SRC)
sys.resources_location = os.path.join(os.path.dirname(SRC), 'resources')

View File

@ -11,7 +11,7 @@ from distutils import sysconfig
from PyQt4.pyqtconfig import QtGuiModuleMakefile
from setup import Command, islinux, isfreebsd, isosx, SRC, iswindows
from setup import Command, islinux, isfreebsd, isbsd, isosx, SRC, iswindows
from setup.build_environment import fc_inc, fc_lib, chmlib_inc_dirs, \
fc_error, poppler_libs, poppler_lib_dirs, poppler_inc_dirs, podofo_inc, \
podofo_lib, podofo_error, poppler_error, pyqt, OSX_SDK, NMAKE, \
@ -21,7 +21,7 @@ from setup.build_environment import fc_inc, fc_lib, chmlib_inc_dirs, \
jpg_lib_dirs, chmlib_lib_dirs, sqlite_inc_dirs, icu_inc_dirs, \
icu_lib_dirs
MT
isunix = islinux or isosx or isfreebsd
isunix = islinux or isosx or isbsd
make = 'make' if isunix else NMAKE
@ -205,7 +205,7 @@ if islinux:
ldflags.append('-lpython'+sysconfig.get_python_version())
if isfreebsd:
if isbsd:
cflags.append('-pthread')
ldflags.append('-shared')
cflags.append('-I'+sysconfig.get_python_inc())

View File

@ -8,7 +8,7 @@ __docformat__ = 'restructuredtext en'
import sys, os, textwrap, subprocess, shutil, tempfile, atexit, stat, shlex
from setup import Command, islinux, isfreebsd, basenames, modules, functions, \
from setup import Command, islinux, isfreebsd, isbsd, basenames, modules, functions, \
__appname__, __version__
HEADER = '''\
@ -116,7 +116,7 @@ class Develop(Command):
def pre_sub_commands(self, opts):
if not (islinux or isfreebsd):
if not (islinux or isbsd):
self.info('\nSetting up a source based development environment is only '
'supported on linux. On other platforms, see the User Manual'
' for help with setting up a development environment.')
@ -156,7 +156,7 @@ class Develop(Command):
self.warn('Failed to compile mount helper. Auto mounting of',
' devices will not work')
if not isfreebsd and os.geteuid() != 0:
if not isbsd and os.geteuid() != 0:
return self.warn('Must be run as root to compile mount helper. Auto '
'mounting of devices will not work.')
src = os.path.join(self.SRC, 'calibre', 'devices', 'linux_mount_helper.c')
@ -168,7 +168,7 @@ class Develop(Command):
ret = p.wait()
if ret != 0:
return warn()
if not isfreebsd:
if not isbsd:
os.chown(dest, 0, 0)
os.chmod(dest, stat.S_ISUID|stat.S_ISGID|stat.S_IRUSR|stat.S_IWUSR|\
stat.S_IXUSR|stat.S_IXGRP|stat.S_IXOTH)

View File

@ -17,6 +17,7 @@
IncludeMaximum="yes"
OnlyDetect="no"
Language="1033"
MigrateFeatures="yes"
Property="OLDPRODUCTFOUND"/>
<UpgradeVersion Minimum="{version}"
IncludeMinimum="no"
@ -26,6 +27,11 @@
</Upgrade>
<CustomAction Id="PreventDowngrading" Error="Newer version already installed."/>
<Property Id="APPLICATIONFOLDER">
<RegistrySearch Id='calibreInstDir' Type='raw'
Root='HKLM' Key="Software\{app}\Installer" Name="InstallPath" />
</Property>
<Directory Id='TARGETDIR' Name='SourceDir'>
<Merge Id="VCRedist" SourceFile="{crt_msm}" DiskId="1" Language="0"/>
<Directory Id='ProgramFilesFolder' Name='PFiles'>
@ -43,6 +49,9 @@
<Environment Id='UpdatePath' Name='PATH' Action='set' System='yes' Part='last' Value='[APPLICATIONFOLDER]' />
<RegistryValue Root="HKCU" Key="Software\Microsoft\{app}" Name="system_path_updated" Type="integer" Value="1" KeyPath="yes"/>
</Component>
<Component Id="RememberInstallDir" Guid="*">
<RegistryValue Root="HKLM" Key="Software\{app}\Installer" Name="InstallPath" Type="string" Value="[APPLICATIONFOLDER]" KeyPath="yes"/>
</Component>
</DirectoryRef>
<DirectoryRef Id="ApplicationProgramsFolder">
@ -61,7 +70,7 @@
WorkingDirectory="APPLICATIONROOTDIRECTORY" />
<util:InternetShortcut Id="OnlineDocumentationShortcut"
Name="User Manual" Type="url"
Target="http://calibre-ebook.com/user_manual"/>
Target="http://manual.calibre-ebook.com"/>
<util:InternetShortcut Id="GetInvolvedS"
Name="Get Involved" Type="url"
Target="http://calibre-ebook.com/get-involved"/>
@ -87,7 +96,8 @@
ConfigurableDirectory="APPLICATIONFOLDER">
<Feature Id="MainApplication" Title="Program Files" Level="1"
Description="All the files need to run {app}" Absent="disallow">
Description="All the files needed to run {app}" Absent="disallow">
<ComponentRef Id="RememberInstallDir"/>
</Feature>
<Feature Id="VCRedist" Title="Visual C++ 8.0 Runtime" AllowAdvertise="no" Display="hidden" Level="1">
@ -115,7 +125,7 @@
<Property Id="ARPPRODUCTICON" Value="main_icon" />
<Condition
Message="This application is only supported on Windows XP SP2, or higher.">
Message="This application is only supported on Windows XP SP3, or higher.">
<![CDATA[Installed OR (VersionNT >= 501)]]>
</Condition>
<InstallExecuteSequence>

View File

@ -16,7 +16,7 @@ from setup import Command, __version__, installer_name, __appname__
PREFIX = "/var/www/calibre-ebook.com"
DOWNLOADS = PREFIX+"/htdocs/downloads"
BETAS = DOWNLOADS +'/betas'
USER_MANUAL = PREFIX+'/htdocs/user_manual'
USER_MANUAL = '/var/www/localhost/htdocs/'
HTML2LRF = "calibre/ebooks/lrf/html/demo"
TXT2LRF = "src/calibre/ebooks/lrf/txt/demo"
MOBILEREAD = 'ftp://dev.mobileread.com/calibre/'
@ -365,7 +365,7 @@ class UploadUserManual(Command): # {{{
self.build_plugin_example(x)
check_call(' '.join(['scp', '-r', 'src/calibre/manual/.build/html/*',
'divok:%s'%USER_MANUAL]), shell=True)
'bugs:%s'%USER_MANUAL]), shell=True)
# }}}
class UploadDemo(Command): # {{{

View File

@ -12,10 +12,10 @@ from functools import partial
warnings.simplefilter('ignore', DeprecationWarning)
from calibre.constants import (iswindows, isosx, islinux, isfreebsd, isfrozen,
preferred_encoding, __appname__, __version__, __author__,
win32event, win32api, winerror, fcntl,
filesystem_encoding, plugins, config_dir)
from calibre.constants import (iswindows, isosx, islinux, isfrozen,
isbsd, preferred_encoding, __appname__, __version__, __author__,
win32event, win32api, winerror, fcntl,
filesystem_encoding, plugins, config_dir)
from calibre.startup import winutil, winutilerror
if False and islinux and not getattr(sys, 'frozen', False):
@ -31,7 +31,7 @@ if False:
# Prevent pyflakes from complaining
winutil, winutilerror, __appname__, islinux, __version__
fcntl, win32event, isfrozen, __author__
winerror, win32api, isfreebsd
winerror, win32api, isbsd
_mt_inited = False
def _init_mimetypes():

View File

@ -4,7 +4,7 @@ __license__ = 'GPL v3'
__copyright__ = '2008, Kovid Goyal kovid@kovidgoyal.net'
__docformat__ = 'restructuredtext en'
__appname__ = u'calibre'
numeric_version = (0, 8, 1)
numeric_version = (0, 8, 3)
__version__ = u'.'.join(map(unicode, numeric_version))
__author__ = u"Kovid Goyal <kovid@kovidgoyal.net>"
@ -27,7 +27,9 @@ iswindows = 'win32' in _plat or 'win64' in _plat
isosx = 'darwin' in _plat
isnewosx = isosx and getattr(sys, 'new_app_bundle', False)
isfreebsd = 'freebsd' in _plat
islinux = not(iswindows or isosx or isfreebsd)
isnetbsd = 'netbsd' in _plat
isbsd = isfreebsd or isnetbsd
islinux = not(iswindows or isosx or isbsd)
isfrozen = hasattr(sys, 'frozen')
isunix = isosx or islinux

View File

@ -607,10 +607,25 @@ class StoreBase(Plugin): # {{{
supported_platforms = ['windows', 'osx', 'linux']
author = 'John Schember'
type = _('Store')
# Information about the store. Should be in the primary language
# of the store. This should not be translatable when set by
# a subclass.
description = _('An ebook store.')
minimum_calibre_version = (0, 8, 0)
version = (1, 0, 1)
actual_plugin = None
# Does the store only distribute ebooks without DRM.
drm_free_only = False
# This is the 2 letter country code for the corporate
# headquarters of the store.
headquarters = ''
# All formats the store distributes ebooks in.
formats = []
# Is this store on an affiliate program?
affiliate = False
def load_actual_plugin(self, gui):
'''
This method must return the actual interface action plugin object.

View File

@ -594,7 +594,7 @@ from calibre.devices.iliad.driver import ILIAD
from calibre.devices.irexdr.driver import IREXDR1000, IREXDR800
from calibre.devices.jetbook.driver import JETBOOK, MIBUK, JETBOOK_MINI
from calibre.devices.kindle.driver import KINDLE, KINDLE2, KINDLE_DX
from calibre.devices.nook.driver import NOOK, NOOK_COLOR
from calibre.devices.nook.driver import NOOK, NOOK_COLOR, NOOK_TSR
from calibre.devices.prs505.driver import PRS505
from calibre.devices.user_defined.driver import USER_DEFINED
from calibre.devices.android.driver import ANDROID, S60
@ -693,8 +693,7 @@ plugins += [
KINDLE,
KINDLE2,
KINDLE_DX,
NOOK,
NOOK_COLOR,
NOOK, NOOK_COLOR, NOOK_TSR,
PRS505,
ANDROID,
S60,
@ -855,6 +854,17 @@ class ActionStore(InterfaceActionBase):
author = 'John Schember'
actual_plugin = 'calibre.gui2.actions.store:StoreAction'
def customization_help(self, gui=False):
return 'Customize the behavior of the store search.'
def config_widget(self):
from calibre.gui2.store.config.store import config_widget as get_cw
return get_cw()
def save_settings(self, config_widget):
from calibre.gui2.store.config.store import save_settings as save
save(config_widget)
plugins += [ActionAdd, ActionFetchAnnotations, ActionGenerateCatalog,
ActionConvert, ActionDelete, ActionEditMetadata, ActionView,
ActionFetchNews, ActionSaveToDisk, ActionShowBookDetails,
@ -1095,147 +1105,309 @@ plugins += [LookAndFeel, Behavior, Columns, Toolbar, Search, InputOptions,
# Store plugins {{{
class StoreAmazonKindleStore(StoreBase):
name = 'Amazon Kindle'
description = _('Kindle books from Amazon.')
description = u'Kindle books from Amazon.'
actual_plugin = 'calibre.gui2.store.amazon_plugin:AmazonKindleStore'
headquarters = 'US'
formats = ['KINDLE']
affiliate = True
class StoreAmazonDEKindleStore(StoreBase):
name = 'Amazon DE Kindle'
description = _('Kindle books from Amazon.de.')
author = 'Charles Haley'
description = u'Kindle Bücher von Amazon.'
actual_plugin = 'calibre.gui2.store.amazon_de_plugin:AmazonDEKindleStore'
headquarters = 'DE'
formats = ['KINDLE']
affiliate = True
class StoreAmazonUKKindleStore(StoreBase):
name = 'Amazon UK Kindle'
description = _('Kindle books from Amazon.uk.')
author = 'Charles Haley'
description = u'Kindle books from Amazon\'s UK web site. Also, includes French language ebooks.'
actual_plugin = 'calibre.gui2.store.amazon_uk_plugin:AmazonUKKindleStore'
headquarters = 'UK'
formats = ['KINDLE']
affiliate = True
class StoreArchiveOrgStore(StoreBase):
name = 'Archive.org'
description = _('Free Books : Download & Streaming : Ebook and Texts Archive : Internet Archive.')
description = u'An Internet library offering permanent access for researchers, historians, scholars, people with disabilities, and the general public to historical collections that exist in digital format.'
actual_plugin = 'calibre.gui2.store.archive_org_plugin:ArchiveOrgStore'
drm_free_only = True
headquarters = 'US'
formats = ['DAISY', 'DJVU', 'EPUB', 'MOBI', 'PDF', 'TXT']
class StoreBaenWebScriptionStore(StoreBase):
name = 'Baen WebScription'
description = _('Ebooks for readers.')
description = u'Sci-Fi & Fantasy brought to you by Jim Baen.'
actual_plugin = 'calibre.gui2.store.baen_webscription_plugin:BaenWebScriptionStore'
drm_free_only = True
headquarters = 'US'
formats = ['EPUB', 'LIT', 'LRF', 'MOBI', 'RB', 'RTF', 'ZIP']
class StoreBNStore(StoreBase):
name = 'Barnes and Noble'
description = _('Books, Textbooks, eBooks, Toys, Games and More.')
description = u'The world\'s largest book seller. As the ultimate destination for book lovers, Barnes & Noble.com offers an incredible array of content.'
actual_plugin = 'calibre.gui2.store.bn_plugin:BNStore'
headquarters = 'US'
formats = ['NOOK']
affiliate = True
class StoreBeamEBooksDEStore(StoreBase):
name = 'Beam EBooks DE'
description = _('Der eBook Shop.')
author = 'Charles Haley'
description = u'Bei uns finden Sie: Tausende deutschsprachige eBooks; Alle eBooks ohne hartes DRM; PDF, ePub und Mobipocket Format; Sofortige Verfügbarkeit - 24 Stunden am Tag; Günstige Preise; eBooks für viele Lesegeräte, PC,Mac und Smartphones; Viele Gratis eBooks'
actual_plugin = 'calibre.gui2.store.beam_ebooks_de_plugin:BeamEBooksDEStore'
drm_free_only = True
headquarters = 'DE'
formats = ['EPUB', 'MOBI', 'PDF']
affiliate = True
class StoreBeWriteStore(StoreBase):
name = 'BeWrite Books'
description = _('Publishers of fine books.')
description = u'Publishers of fine books. Highly selective and editorially driven. Does not offer: books for children or exclusively YA, erotica, swords-and-sorcery fantasy and space-opera-style science fiction. All other genres are represented.'
actual_plugin = 'calibre.gui2.store.bewrite_plugin:BeWriteStore'
drm_free_only = True
headquarters = 'US'
formats = ['EPUB', 'MOBI', 'PDF']
class StoreDieselEbooksStore(StoreBase):
name = 'Diesel eBooks'
description = _('World Famous eBook Store.')
description = u'Instant access to over 2.4 million titles from hundreds of publishers including Harlequin, HarperCollins, John Wiley & Sons, McGraw-Hill, Simon & Schuster and Random House.'
actual_plugin = 'calibre.gui2.store.diesel_ebooks_plugin:DieselEbooksStore'
headquarters = 'US'
formats = ['EPUB', 'PDF']
affiliate = True
class StoreEbookscomStore(StoreBase):
name = 'eBooks.com'
description = _('The digital bookstore.')
description = u'Sells books in multiple electronic formats in all categories. Technical infrastructure is cutting edge, robust and scalable, with servers in the US and Europe.'
actual_plugin = 'calibre.gui2.store.ebooks_com_plugin:EbookscomStore'
headquarters = 'US'
formats = ['EPUB', 'LIT', 'MOBI', 'PDF']
affiliate = True
class StoreEPubBuyDEStore(StoreBase):
name = 'EPUBBuy DE'
description = _('EPUBReaders eBook Shop.')
author = 'Charles Haley'
description = u'Bei EPUBBuy.com finden Sie ausschliesslich eBooks im weitverbreiteten EPUB-Format und ohne DRM. So haben Sie die freie Wahl, wo Sie Ihr eBook lesen: Tablet, eBook-Reader, Smartphone oder einfach auf Ihrem PC. So macht eBook-Lesen Spaß!'
actual_plugin = 'calibre.gui2.store.epubbuy_de_plugin:EPubBuyDEStore'
drm_free_only = True
headquarters = 'DE'
formats = ['EPUB']
affiliate = True
class StoreEBookShoppeUKStore(StoreBase):
name = 'ebookShoppe UK'
author = u'Charles Haley'
description = u'We made this website in an attempt to offer the widest range of UK eBooks possible across and as many formats as we could manage.'
actual_plugin = 'calibre.gui2.store.ebookshoppe_uk_plugin:EBookShoppeUKStore'
headquarters = 'UK'
formats = ['EPUB', 'PDF']
affiliate = True
class StoreEHarlequinStore(StoreBase):
name = 'eHarlequin'
description = _('Entertain, enrich, inspire.')
description = u'A global leader in series romance and one of the world\'s leading publishers of books for women. Offers women a broad range of reading from romance to bestseller fiction, from young adult novels to erotic literature, from nonfiction to fantasy, from African-American novels to inspirational romance, and more.'
actual_plugin = 'calibre.gui2.store.eharlequin_plugin:EHarlequinStore'
headquarters = 'CA'
formats = ['EPUB', 'PDF']
affiliate = True
class StoreFeedbooksStore(StoreBase):
name = 'Feedbooks'
description = _('Read anywhere.')
description = u'Feedbooks is a cloud publishing and distribution service, connected to a large ecosystem of reading systems and social networks. Provides a variety of genres from independent and classic books.'
actual_plugin = 'calibre.gui2.store.feedbooks_plugin:FeedbooksStore'
headquarters = 'FR'
formats = ['EPUB', 'MOBI', 'PDF']
class StoreFoylesUKStore(StoreBase):
name = 'Foyles UK'
description = _('Foyles of London, online.')
author = 'Charles Haley'
description = u'Foyles of London\'s ebook store. Provides extensive range covering all subjects.'
actual_plugin = 'calibre.gui2.store.foyles_uk_plugin:FoylesUKStore'
headquarters = 'UK'
formats = ['EPUB', 'PDF']
affiliate = True
class StoreGandalfStore(StoreBase):
name = 'Gandalf'
author = 'Tomasz Długosz'
description = _('Zaczarowany świat książek')
author = u'Tomasz Długosz'
description = u'Księgarnia internetowa Gandalf.'
actual_plugin = 'calibre.gui2.store.gandalf_plugin:GandalfStore'
headquarters = 'PL'
formats = ['EPUB', 'PDF']
class StoreGoogleBooksStore(StoreBase):
name = 'Google Books'
description = _('Google Books')
description = u'Google Books'
actual_plugin = 'calibre.gui2.store.google_books_plugin:GoogleBooksStore'
headquarters = 'US'
formats = ['EPUB', 'PDF', 'TXT']
class StoreGutenbergStore(StoreBase):
name = 'Project Gutenberg'
description = _('The first producer of free ebooks.')
description = u'The first producer of free ebooks. Free in the United States because their copyright has expired. They may not be free of copyright in other countries. Readers outside of the United States must check the copyright laws of their countries before downloading or redistributing our ebooks.'
actual_plugin = 'calibre.gui2.store.gutenberg_plugin:GutenbergStore'
drm_free_only = True
headquarters = 'US'
formats = ['EPUB', 'HTML', 'MOBI', 'PDB', 'TXT']
class StoreKoboStore(StoreBase):
name = 'Kobo'
description = _('eReading: anytime. anyplace.')
description = u'With over 2.3 million eBooks to browse we have engaged readers in over 200 countries in Kobo eReading. Our eBook listings include New York Times Bestsellers, award winners, classics and more!'
actual_plugin = 'calibre.gui2.store.kobo_plugin:KoboStore'
headquarters = 'CA'
formats = ['EPUB']
affiliate = True
class StoreLegimiStore(StoreBase):
name = 'Legimi'
author = u'Tomasz Długosz'
description = u'Tanie oraz darmowe ebooki, egazety i blogi w formacie EPUB, wprost na Twój e-czytnik, iPhone, iPad, Android i komputer'
actual_plugin = 'calibre.gui2.store.legimi_plugin:LegimiStore'
headquarters = 'PL'
formats = ['EPUB']
class StoreManyBooksStore(StoreBase):
name = 'ManyBooks'
description = _('The best ebooks at the best price: free!')
description = u'Public domain and creative commons works from many sources.'
actual_plugin = 'calibre.gui2.store.manybooks_plugin:ManyBooksStore'
drm_free_only = True
headquarters = 'US'
formats = ['EPUB', 'FB2', 'JAR', 'LIT', 'LRF', 'MOBI', 'PDB', 'PDF', 'RB', 'RTF', 'TCR', 'TXT', 'ZIP']
class StoreMobileReadStore(StoreBase):
name = 'MobileRead'
description = _('Ebooks handcrafted with the utmost care.')
description = u'Ebooks handcrafted with the utmost care.'
actual_plugin = 'calibre.gui2.store.mobileread.mobileread_plugin:MobileReadStore'
drm_free_only = True
headquarters = 'CH'
formats = ['EPUB', 'IMP', 'LRF', 'LIT', 'MOBI', 'PDF']
class StoreNextoStore(StoreBase):
name = 'Nexto'
author = 'Tomasz Długosz'
description = _('Audiobooki mp3, ebooki, prasa - księgarnia internetowa.')
author = u'Tomasz Długosz'
description = u'Największy w Polsce sklep internetowy z audiobookami mp3, ebookami pdf oraz prasą do pobrania on-line.'
actual_plugin = 'calibre.gui2.store.nexto_plugin:NextoStore'
headquarters = 'PL'
formats = ['EPUB', 'PDF']
affiliate = True
class StoreOpenLibraryStore(StoreBase):
name = 'Open Library'
description = _('One web page for every book.')
description = u'One web page for every book ever published. The goal is to be a true online library. Over 20 million records from a variety of large catalogs as well as single contributions, with more on the way.'
actual_plugin = 'calibre.gui2.store.open_library_plugin:OpenLibraryStore'
drm_free_only = True
headquarters = 'US'
formats = ['DAISY', 'DJVU', 'EPUB', 'MOBI', 'PDF', 'TXT']
class StoreOReillyStore(StoreBase):
name = 'OReilly'
description = _('DRM-Free tech ebooks.')
description = u'Programming and tech ebooks from OReilly.'
actual_plugin = 'calibre.gui2.store.oreilly_plugin:OReillyStore'
drm_free_only = True
headquarters = 'US'
formats = ['APK', 'DAISY', 'EPUB', 'MOBI', 'PDF']
class StorePragmaticBookshelfStore(StoreBase):
name = 'Pragmatic Bookshelf'
description = _('The Pragmatic Bookshelf')
description = u'The Pragmatic Bookshelf\'s collection of programming and tech books avaliable as ebooks.'
actual_plugin = 'calibre.gui2.store.pragmatic_bookshelf_plugin:PragmaticBookshelfStore'
drm_free_only = True
headquarters = 'US'
formats = ['EPUB', 'MOBI', 'PDF']
class StoreSmashwordsStore(StoreBase):
name = 'Smashwords'
description = _('Your ebook. Your way.')
description = u'An ebook publishing and distribution platform for ebook authors, publishers and readers. Covers many genres and formats.'
actual_plugin = 'calibre.gui2.store.smashwords_plugin:SmashwordsStore'
drm_free_only = True
headquarters = 'US'
formats = ['EPUB', 'HTML', 'LRF', 'MOBI', 'PDB', 'RTF', 'TXT']
affiliate = True
class StoreVirtualoStore(StoreBase):
name = 'Virtualo'
author = u'Tomasz Długosz'
description = u'Księgarnia internetowa, która oferuje bezpieczny i szeroki dostęp do książek w formie cyfrowej.'
actual_plugin = 'calibre.gui2.store.virtualo_plugin:VirtualoStore'
headquarters = 'PL'
formats = ['EPUB', 'PDF']
class StoreWaterstonesUKStore(StoreBase):
name = 'Waterstones UK'
description = _('Feel every word.')
author = 'Charles Haley'
description = u'Waterstone\'s mission is to be the leading Bookseller on the High Street and online providing customers the widest choice, great value and expert advice from a team passionate about Bookselling.'
actual_plugin = 'calibre.gui2.store.waterstones_uk_plugin:WaterstonesUKStore'
headquarters = 'UK'
formats = ['EPUB', 'PDF']
class StoreWeightlessBooksStore(StoreBase):
name = 'Weightless Books'
description = '(e)Books That Don\'t Weigh You Down.'
description = u'An independent DRM-free ebooksite devoted to ebooks of all sorts.'
actual_plugin = 'calibre.gui2.store.weightless_books_plugin:WeightlessBooksStore'
drm_free_only = True
headquarters = 'US'
formats = ['EPUB', 'HTML', 'LIT', 'MOBI', 'PDF']
class StoreWHSmithUKStore(StoreBase):
name = 'WH Smith UK'
author = 'Charles Haley'
description = u"Shop for savings on Books, discounted Magazine subscriptions and great prices on Stationery, Toys & Games"
actual_plugin = 'calibre.gui2.store.whsmith_uk_plugin:WHSmithUKStore'
headquarters = 'UK'
formats = ['EPUB', 'PDF']
class StoreWizardsTowerBooksStore(StoreBase):
name = 'Wizards Tower Books'
description = 'Wizard\'s Tower Press.'
description = u'A science fiction and fantasy publisher. Concentrates mainly on making out-of-print works available once more as e-books, and helping other small presses exploit the e-book market. Also publishes a small number of limited-print-run anthologies with a view to encouraging diversity in the science fiction and fantasy field.'
actual_plugin = 'calibre.gui2.store.wizards_tower_books_plugin:WizardsTowerBooksStore'
drm_free_only = True
headquarters = 'UK'
formats = ['EPUB', 'MOBI']
class StoreWoblinkStore(StoreBase):
name = 'Woblink'
author = u'Tomasz Długosz'
description = u'Czytanie zdarza się wszędzie!'
actual_plugin = 'calibre.gui2.store.woblink_plugin:WoblinkStore'
headquarters = 'PL'
formats = ['EPUB']
plugins += [
StoreArchiveOrgStore,
StoreAmazonKindleStore,
@ -1247,6 +1419,7 @@ plugins += [
StoreBeWriteStore,
StoreDieselEbooksStore,
StoreEbookscomStore,
StoreEBookShoppeUKStore,
StoreEPubBuyDEStore,
StoreEHarlequinStore,
StoreFeedbooksStore,
@ -1255,6 +1428,7 @@ plugins += [
StoreGoogleBooksStore,
StoreGutenbergStore,
StoreKoboStore,
StoreLegimiStore,
StoreManyBooksStore,
StoreMobileReadStore,
StoreNextoStore,
@ -1262,9 +1436,12 @@ plugins += [
StoreOReillyStore,
StorePragmaticBookshelfStore,
StoreSmashwordsStore,
StoreVirtualoStore,
StoreWaterstonesUKStore,
StoreWeightlessBooksStore,
StoreWizardsTowerBooksStore
StoreWHSmithUKStore,
StoreWizardsTowerBooksStore,
StoreWoblinkStore
]
# }}}

View File

@ -216,9 +216,26 @@ def store_plugins():
customization = config['plugin_customization']
for plugin in _initialized_plugins:
if isinstance(plugin, Store):
if not is_disabled(plugin):
plugin.site_customization = customization.get(plugin.name, '')
yield plugin
plugin.site_customization = customization.get(plugin.name, '')
yield plugin
def available_store_plugins():
for plugin in store_plugins():
if not is_disabled(plugin):
yield plugin
def stores():
stores = set([])
for plugin in store_plugins():
stores.add(plugin.name)
return stores
def available_stores():
stores = set([])
for plugin in available_store_plugins():
stores.add(plugin.name)
return stores
# }}}
# Metadata read/write {{{

View File

@ -59,7 +59,7 @@ class ANDROID(USBMS):
0x0489 : { 0xc001 : [0x0226], 0xc004 : [0x0226], },
# Acer
0x502 : { 0x3203 : [0x0100]},
0x502 : { 0x3203 : [0x0100, 0x224]},
# Dell
0x413c : { 0xb007 : [0x0100, 0x0224, 0x0226]},

View File

@ -95,9 +95,8 @@ class POCKETBOOK360(EB600):
FORMATS = ['epub', 'fb2', 'prc', 'mobi', 'pdf', 'djvu', 'rtf', 'chm', 'txt']
VENDOR_NAME = 'PHILIPS'
WINDOWS_MAIN_MEM = 'MASS_STORGE'
WINDOWS_CARD_A_MEM = 'MASS_STORGE'
VENDOR_NAME = ['PHILIPS', '__POCKET']
WINDOWS_MAIN_MEM = WINDOWS_CARD_A_MEM = ['MASS_STORGE', 'BOOK_USB_STORAGE']
OSX_MAIN_MEM = 'Philips Mass Storge Media'
OSX_CARD_A_MEM = 'Philips Mass Storge Media'

View File

@ -8,10 +8,10 @@ from ctypes import cdll, POINTER, byref, pointer, Structure as _Structure, \
c_ubyte, c_ushort, c_int, c_char, c_void_p, c_byte, c_uint
from errno import EBUSY, ENOMEM
from calibre import iswindows, isosx, isfreebsd, load_library
from calibre import iswindows, isosx, isbsd, load_library
_libusb_name = 'libusb'
PATH_MAX = 511 if iswindows else 1024 if (isosx or isfreebsd) else 4096
PATH_MAX = 511 if iswindows else 1024 if (isosx or isbsd) else 4096
if iswindows:
class Structure(_Structure):
_pack_ = 1

View File

@ -269,8 +269,8 @@ class NEXTBOOK(USBMS):
EBOOK_DIR_MAIN = ''
VENDOR_NAME = 'NEXT2'
WINDOWS_MAIN_MEM = WINDOWS_CARD_A_MEM = '1.0.14'
VENDOR_NAME = ['NEXT2', 'BK7005']
WINDOWS_MAIN_MEM = WINDOWS_CARD_A_MEM = ['1.0.14', 'PLAYER']
SUPPORTS_SUB_DIRS = True
THUMBNAIL_HEIGHT = 120

View File

@ -107,3 +107,13 @@ class NOOK_COLOR(NOOK):
return filepath
class NOOK_TSR(NOOK):
gui_name = _('Nook Simple')
description = _('Communicate with the Nook TSR eBook reader.')
PRODUCT_ID = [0x003]
BCD = [0x216]
EBOOK_DIR_MAIN = EBOOK_DIR_CARD_A = 'My Files/Books'

View File

@ -926,8 +926,8 @@ class Device(DeviceConfig, DevicePlugin):
if not isinstance(template, unicode):
template = template.decode('utf-8')
app_id = str(getattr(mdata, 'application_id', ''))
# The db id will be in the created filename
extra_components = get_components(template, mdata, fname,
id_ = mdata.get('id', fname)
extra_components = get_components(template, mdata, id_,
timefmt=opts.send_timefmt, length=maxlen-len(app_id)-1)
if not extra_components:
extra_components.append(sanitize(self.filename_callback(fname,

View File

@ -40,7 +40,7 @@ To get help on them specify the input and output file and then use the -h \
option.
For full documentation of the conversion system see
''') + 'http://calibre-ebook.com/user_manual/conversion.html'
''') + 'http://manual.calibre-ebook.com/conversion.html'
HEURISTIC_OPTIONS = ['markup_chapter_headings',
'italicize_common_cases', 'fix_indents',

View File

@ -413,6 +413,13 @@ class EPUBOutput(OutputFormatPlugin):
rule.style.removeProperty('margin-left')
# padding-left breaks rendering in webkit and gecko
rule.style.removeProperty('padding-left')
# Change whitespace:pre to pre-line to accommodate readers that
# cannot scroll horizontally
for rule in stylesheet.data.cssRules.rulesOfType(CSSRule.STYLE_RULE):
style = rule.style
ws = style.getPropertyValue('white-space')
if ws == 'pre':
style.setProperty('white-space', 'pre-wrap')
# }}}

View File

@ -20,7 +20,7 @@ from itertools import izip
from calibre.customize.conversion import InputFormatPlugin
from calibre.ebooks.chardet import xml_to_unicode
from calibre.customize.conversion import OptionRecommendation
from calibre.constants import islinux, isfreebsd, iswindows
from calibre.constants import islinux, isbsd, iswindows
from calibre import unicode_path, as_unicode
from calibre.utils.localization import get_lang
from calibre.utils.filenames import ascii_filename
@ -302,7 +302,7 @@ class HTMLInput(InputFormatPlugin):
if getattr(self, '_is_case_sensitive', None) is not None:
return self._is_case_sensitive
if not path or not os.path.exists(path):
return islinux or isfreebsd
return islinux or isbsd
self._is_case_sensitive = not (os.path.exists(path.lower()) \
and os.path.exists(path.upper()))
return self._is_case_sensitive

View File

@ -41,27 +41,26 @@ field_metadata = FieldMetadata()
class SafeFormat(TemplateFormatter):
def get_value(self, key, args, kwargs):
try:
key = key.lower()
if key != 'title_sort' and key not in TOP_LEVEL_IDENTIFIERS:
key = field_metadata.search_term_to_field_key(key)
b = self.book.get_user_metadata(key, False)
if b and b['datatype'] == 'int' and self.book.get(key, 0) == 0:
v = ''
elif b and b['datatype'] == 'float' and self.book.get(key, 0.0) == 0.0:
v = ''
else:
v = self.book.format_field(key, series_with_index=False)[1]
if v is None:
return ''
if v == '':
return ''
return v
except:
if DEBUG:
traceback.print_exc()
return key
def get_value(self, orig_key, args, kwargs):
if not orig_key:
return ''
key = orig_key.lower()
if key != 'title_sort' and key not in TOP_LEVEL_IDENTIFIERS:
key = field_metadata.search_term_to_field_key(key)
if key is None or (self.book and key not in self.book.all_field_keys()):
raise ValueError(_('Value: unknown field ') + orig_key)
b = self.book.get_user_metadata(key, False)
if b and b['datatype'] == 'int' and self.book.get(key, 0) == 0:
v = ''
elif b and b['datatype'] == 'float' and self.book.get(key, 0.0) == 0.0:
v = ''
else:
v = self.book.format_field(key, series_with_index=False)[1]
if v is None:
return ''
if v == '':
return ''
return v
composite_formatter = SafeFormat()
@ -75,7 +74,7 @@ class Metadata(object):
Metadata from custom columns should be accessed via the get() method,
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.
@ -106,7 +105,7 @@ class Metadata(object):
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
_('Unknown') is null or a language of 'und' is null.
@ -628,6 +627,12 @@ class Metadata(object):
res = _('Yes') if res else _('No')
elif datatype == 'rating':
res = res/2.0
elif datatype in ['int', 'float']:
try:
fmt = cmeta['display'].get('number_format', None)
res = fmt.format(res)
except:
pass
return (name, unicode(res), orig_res, cmeta)
# convert top-level ids into their value

View File

@ -29,7 +29,7 @@ class Worker(Thread): # Get details {{{
Get book details from amazons book page in a separate thread
'''
def __init__(self, url, result_queue, browser, log, relevance, plugin, timeout=20):
def __init__(self, url, result_queue, browser, log, relevance, domain, plugin, timeout=20):
Thread.__init__(self)
self.daemon = True
self.url, self.result_queue = url, result_queue
@ -37,7 +37,7 @@ class Worker(Thread): # Get details {{{
self.relevance, self.plugin = relevance, plugin
self.browser = browser.clone_browser()
self.cover_url = self.amazon_id = self.isbn = None
self.domain = self.plugin.domain
self.domain = domain
months = {
'de': {
@ -199,7 +199,8 @@ class Worker(Thread): # Get details {{{
return
mi = Metadata(title, authors)
mi.set_identifier('amazon', asin)
idtype = 'amazon' if self.domain == 'com' else 'amazon_'+self.domain
mi.set_identifier(idtype, asin)
self.amazon_id = asin
try:
@ -404,12 +405,30 @@ class Amazon(Source):
'country\'s Amazon website.'), choices=AMAZON_DOMAINS),
)
def get_domain_and_asin(self, identifiers):
for key, val in identifiers.iteritems():
key = key.lower()
if key in ('amazon', 'asin'):
return 'com', val
if key.startswith('amazon_'):
domain = key.split('_')[-1]
if domain and domain in self.AMAZON_DOMAINS:
return domain, val
return None, None
def get_book_url(self, identifiers): # {{{
asin = identifiers.get('amazon', None)
if asin is None:
asin = identifiers.get('asin', None)
if asin:
return ('amazon', asin, 'http://amzn.com/%s'%asin)
domain, asin = self.get_domain_and_asin(identifiers)
if domain and asin:
url = None
if domain == 'com':
url = 'http://amzn.com/'+asin
elif domain == 'uk':
url = 'http://www.amazon.co.uk/dp/'+asin
else:
url = 'http://www.amazon.%s/dp/%s'%(domain, asin)
if url:
idtype = 'amazon' if self.domain == 'com' else 'amazon_'+self.domain
return (idtype, asin, url)
# }}}
@property
@ -420,8 +439,14 @@ class Amazon(Source):
return domain
def create_query(self, log, title=None, authors=None, identifiers={}): # {{{
domain = self.domain
def create_query(self, log, title=None, authors=None, identifiers={}, # {{{
domain=None):
if domain is None:
domain = self.domain
idomain, asin = self.get_domain_and_asin(identifiers)
if idomain is not None:
domain = idomain
# See the amazon detailed search page to get all options
q = { 'search-alias' : 'aps',
@ -433,7 +458,6 @@ class Amazon(Source):
else:
q['sort'] = 'relevancerank'
asin = identifiers.get('amazon', None)
isbn = check_isbn(identifiers.get('isbn', None))
if asin is not None:
@ -456,23 +480,22 @@ class Amazon(Source):
if not ('field-keywords' in q or 'field-isbn' in q or
('field-title' in q)):
# Insufficient metadata to make an identify query
return None
return None, None
latin1q = dict([(x.encode('latin1', 'ignore'), y.encode('latin1',
'ignore')) for x, y in
q.iteritems()])
udomain = domain
if domain == 'uk':
domain = 'co.uk'
url = 'http://www.amazon.%s/s/?'%domain + urlencode(latin1q)
return url
udomain = 'co.uk'
url = 'http://www.amazon.%s/s/?'%udomain + urlencode(latin1q)
return url, domain
# }}}
def get_cached_cover_url(self, identifiers): # {{{
url = None
asin = identifiers.get('amazon', None)
if asin is None:
asin = identifiers.get('asin', None)
domain, asin = self.get_domain_and_asin(identifiers)
if asin is None:
isbn = identifiers.get('isbn', None)
if isbn is not None:
@ -489,7 +512,7 @@ class Amazon(Source):
Note this method will retry without identifiers automatically if no
match is found with identifiers.
'''
query = self.create_query(log, title=title, authors=authors,
query, domain = self.create_query(log, title=title, authors=authors,
identifiers=identifiers)
if query is None:
log.error('Insufficient metadata to construct query')
@ -549,7 +572,8 @@ class Amazon(Source):
r'//div[@id="Results"]/descendant::td[starts-with(@id, "search:Td:")]'):
for a in td.xpath(r'descendant::td[@class="dataColumn"]/descendant::a[@href]/span[@class="srTitle"]/..'):
title = tostring(a, method='text', encoding=unicode).lower()
if 'bulk pack' not in title:
if ('bulk pack' not in title and '[audiobook]' not in
title and '[audio cd]' not in title):
matches.append(a.get('href'))
break
@ -570,7 +594,7 @@ class Amazon(Source):
log.error('No matches found with query: %r'%query)
return
workers = [Worker(url, result_queue, br, log, i, self) for i, url in
workers = [Worker(url, result_queue, br, log, i, domain, self) for i, url in
enumerate(matches)]
for w in workers:

View File

@ -313,7 +313,7 @@ class Source(Plugin):
title_patterns = [(re.compile(pat, re.IGNORECASE), repl) for pat, repl in
[
# Remove things like: (2010) (Omnibus) etc.
(r'(?i)[({\[](\d{4}|omnibus|anthology|hardcover|paperback|turtleback|mass\s*market|edition|ed\.)[\])}]', ''),
(r'(?i)[({\[](\d{4}|omnibus|anthology|hardcover|audiobook|audio\scd|paperback|turtleback|mass\s*market|edition|ed\.)[\])}]', ''),
# Remove any strings that contain the substring edition inside
# parentheses
(r'(?i)[({\[].*?(edition|ed.).*?[\]})]', ''),

View File

@ -211,7 +211,10 @@ class Douban(Source):
'q': q,
})
if self.DOUBAN_API_KEY and self.DOUBAN_API_KEY != '':
url = url + "?apikey=" + self.DOUBAN_API_KEY
if t == "isbn" or t == "subject":
url = url + "?apikey=" + self.DOUBAN_API_KEY
else:
url = url + "&apikey=" + self.DOUBAN_API_KEY
return url
# }}}

View File

@ -297,9 +297,11 @@ class MobiMLizer(object):
if id_:
# Keep anchors so people can use display:none
# to generate hidden TOCs
tail = elem.tail
elem.clear()
elem.text = None
elem.set('id', id_)
elem.tail = tail
else:
return
tag = barename(elem.tag)
@ -309,7 +311,8 @@ class MobiMLizer(object):
istates.append(istate)
left = 0
display = style['display']
isblock = not display.startswith('inline')
isblock = (not display.startswith('inline') and style['display'] !=
'none')
isblock = isblock and style['float'] == 'none'
isblock = isblock and tag != 'br'
if isblock:

View File

@ -13,7 +13,7 @@ from functools import partial
from calibre.ebooks import ConversionError, DRMError
from calibre.ptempfile import PersistentTemporaryFile
from calibre.constants import isosx, iswindows, islinux, isfreebsd
from calibre.constants import isosx, iswindows, islinux, isbsd
from calibre import CurrentDir
PDFTOHTML = 'pdftohtml'
@ -23,7 +23,7 @@ if isosx and hasattr(sys, 'frameworks_dir'):
if iswindows and hasattr(sys, 'frozen'):
PDFTOHTML = os.path.join(os.path.dirname(sys.executable), 'pdftohtml.exe')
popen = partial(subprocess.Popen, creationflags=0x08) # CREATE_NO_WINDOW=0x08 so that no ugly console is popped up
if (islinux or isfreebsd) and getattr(sys, 'frozen', False):
if (islinux or isbsd) and getattr(sys, 'frozen', False):
PDFTOHTML = os.path.join(sys.executables_location, 'bin', 'pdftohtml')
def pdftohtml(output_dir, pdf_path, no_images):
@ -43,7 +43,7 @@ def pdftohtml(output_dir, pdf_path, no_images):
# This is neccessary as pdftohtml doesn't always (linux) respect absolute paths
pdf_path = os.path.abspath(pdf_path)
cmd = [PDFTOHTML, '-enc', 'UTF-8', '-noframes', '-p', '-nomerge', '-nodrm', '-q', pdf_path, os.path.basename(index)]
if isfreebsd:
if isbsd:
cmd.remove('-nodrm')
if no_images:
cmd.append('-i')

View File

@ -12,7 +12,7 @@ from PyQt4.Qt import (QVariant, QFileInfo, QObject, SIGNAL, QBuffer, Qt,
ORG_NAME = 'KovidsBrain'
APP_UID = 'libprs500'
from calibre.constants import islinux, iswindows, isfreebsd, isfrozen, isosx
from calibre.constants import islinux, iswindows, isbsd, isfrozen, isosx
from calibre.utils.config import Config, ConfigProxy, dynamic, JSONConfig
from calibre.utils.localization import set_qt_translator
from calibre.ebooks.metadata import MetaInformation
@ -48,8 +48,9 @@ else:
gprefs.defaults['action-layout-menubar-device'] = ()
gprefs.defaults['action-layout-toolbar'] = (
'Add Books', 'Edit Metadata', None, 'Convert Books', 'View', None,
'Choose Library', 'Donate', None, 'Fetch News', 'Store', 'Save To Disk',
'Connect Share', None, 'Remove Books', None, 'Help', 'Preferences',
'Store', 'Donate', 'Fetch News', 'Help', None,
'Remove Books', 'Choose Library', 'Save To Disk',
'Connect Share', 'Preferences',
)
gprefs.defaults['action-layout-toolbar-device'] = (
'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['toolbar_icon_size'] = 'medium'
gprefs.defaults['automerge'] = 'ignore'
gprefs.defaults['toolbar_text'] = 'auto'
gprefs.defaults['toolbar_text'] = 'always'
gprefs.defaults['font'] = None
gprefs.defaults['tags_browser_partition_method'] = 'first letter'
gprefs.defaults['tags_browser_collapse_at'] = 100
@ -628,7 +629,7 @@ class Application(QApplication):
st = self.style()
if st is not None:
st = unicode(st.objectName()).lower()
if (islinux or isfreebsd) and st in ('windows', 'motif', 'cde'):
if (islinux or isbsd) and st in ('windows', 'motif', 'cde'):
from PyQt4.Qt import QStyleFactory
styles = set(map(unicode, QStyleFactory.keys()))
if 'Plastique' in styles and os.environ.get('KDE_FULL_SESSION',
@ -697,7 +698,7 @@ def open_local_file(path):
def is_ok_to_use_qt():
global gui_thread, _store_app
if (islinux or isfreebsd) and ':' not in os.environ.get('DISPLAY', ''):
if (islinux or isbsd) and ':' not in os.environ.get('DISPLAY', ''):
return False
if _store_app is None and QApplication.instance() is None:
_store_app = QApplication([])

View File

@ -317,6 +317,7 @@ class AddAction(InterfaceAction):
_('Uploading books to device.'), 2000)
if getattr(self._adder, 'number_of_books_added', 0) > 0:
self.gui.library_view.model().books_added(self._adder.number_of_books_added)
self.gui.library_view.set_current_row(0)
if hasattr(self.gui, 'db_images'):
self.gui.db_images.reset()
self.gui.tags_view.recount()
@ -338,7 +339,6 @@ class AddAction(InterfaceAction):
self.gui.library_view.model().current_changed(current_idx,
current_idx)
if getattr(self._adder, 'critical', None):
det_msg = []
for name, log in self._adder.critical.items():

View File

@ -16,7 +16,7 @@ from calibre.gui2 import error_dialog, Dispatcher, warning_dialog
from calibre.gui2.dialogs.progress import ProgressDialog
from calibre.utils.config import prefs, tweaks
class Worker(Thread):
class Worker(Thread): # {{{
def __init__(self, ids, db, loc, progress, done, delete_after):
Thread.__init__(self)
@ -75,7 +75,7 @@ class Worker(Thread):
if co is not None:
newdb.set_conversion_options(x, 'PIPE', co)
self.processed.add(x)
# }}}
class CopyToLibraryAction(InterfaceAction):

View File

@ -19,7 +19,7 @@ class HelpAction(InterfaceAction):
self.qaction.triggered.connect(self.show_help)
def show_help(self, *args):
open_url(QUrl('http://calibre-ebook.com/user_manual'))
open_url(QUrl('http://manual.calibre-ebook.com'))

View File

@ -8,7 +8,7 @@ __docformat__ = 'restructuredtext en'
from functools import partial
from PyQt4.Qt import QMenu
from PyQt4.Qt import QMenu, QIcon, QSize
from calibre.gui2 import error_dialog
from calibre.gui2.actions import InterfaceAction
@ -32,8 +32,15 @@ class StoreAction(InterfaceAction):
self.store_menu.addAction(_('Search for this book'), self.search_author_title)
self.store_menu.addSeparator()
self.store_list_menu = self.store_menu.addMenu(_('Stores'))
icon = QIcon()
icon.addFile(I('donate.png'), QSize(16, 16))
for n, p in sorted(self.gui.istores.items(), key=lambda x: x[0].lower()):
self.store_list_menu.addAction(n, partial(self.open_store, p))
if p.base_plugin.affiliate:
self.store_list_menu.addAction(icon, n, partial(self.open_store, p))
else:
self.store_list_menu.addAction(n, partial(self.open_store, p))
self.store_menu.addSeparator()
self.store_menu.addAction(_('Choose stores'), self.choose)
self.qaction.setMenu(self.store_menu)
def do_search(self):
@ -42,7 +49,7 @@ class StoreAction(InterfaceAction):
def search(self, query=''):
self.show_disclaimer()
from calibre.gui2.store.search.search import SearchDialog
sd = SearchDialog(self.gui.istores, self.gui, query)
sd = SearchDialog(self.gui, self.gui, query)
sd.exec_()
def _get_selected_row(self):
@ -107,6 +114,13 @@ class StoreAction(InterfaceAction):
query = 'author:"%s" title:"%s"' % (self._get_author(row), self._get_title(row))
self.search(query)
def choose(self):
from calibre.gui2.store.config.chooser.chooser_dialog import StoreChooserDialog
d = StoreChooserDialog(self.gui)
d.exec_()
self.gui.load_store_plugins()
self.load_menu()
def open_store(self, store_plugin):
self.show_disclaimer()
store_plugin.open(self.gui)

View File

@ -33,7 +33,7 @@
<property name="text">
<string>&lt;p&gt;This wizard will help you choose an appropriate font size key for your needs. Just enter the base font size of the input document and then enter an input font size. The wizard will display what font size it will be mapped to, by the font rescaling algorithm. You can adjust the algorithm by adjusting the output base font size and font key below. When you find values suitable for you, click OK.&lt;/p&gt;
&lt;p&gt;By default, if the output base font size is zero and/or no font size key is specified, calibre will use the values from the current Output Profile. &lt;/p&gt;
&lt;p&gt;See the &lt;a href=&quot;http://calibre-ebook.com/user_manual/conversion.html#font-size-rescaling&quot;&gt;User Manual&lt;/a&gt; for a discussion of how font size rescaling works.&lt;/p&gt;</string>
&lt;p&gt;See the &lt;a href=&quot;http://manual.calibre-ebook.com/conversion.html#font-size-rescaling&quot;&gt;User Manual&lt;/a&gt; for a discussion of how font size rescaling works.&lt;/p&gt;</string>
</property>
<property name="wordWrap">
<bool>true</bool>

View File

@ -17,7 +17,7 @@
<item>
<widget class="QLabel" name="label">
<property name="text">
<string>&lt;b&gt;Heuristic processing&lt;/b&gt; means that calibre will scan your book for common patterns and fix them. As the name implies, this involves guesswork, which means that it could end up worsening the result of a conversion, if calibre guesses wrong. Therefore, it is disabled by default. Often, if a conversion does not turn out as you expect, turning on heuristics can improve matters. Read more about the various heuristic processing options in the &lt;a href=&quot;http://calibre-ebook.com/user_manual/conversion.html#heuristic-processing&quot;&gt;User Manual&lt;/a&gt;.</string>
<string>&lt;b&gt;Heuristic processing&lt;/b&gt; means that calibre will scan your book for common patterns and fix them. As the name implies, this involves guesswork, which means that it could end up worsening the result of a conversion, if calibre guesses wrong. Therefore, it is disabled by default. Often, if a conversion does not turn out as you expect, turning on heuristics can improve matters. Read more about the various heuristic processing options in the &lt;a href=&quot;http://manual.calibre-ebook.com/conversion.html#heuristic-processing&quot;&gt;User Manual&lt;/a&gt;.</string>
</property>
<property name="wordWrap">
<bool>true</bool>

View File

@ -188,7 +188,7 @@
<item row="0" column="0">
<widget class="QLabel" name="label">
<property name="text">
<string>&lt;p&gt;Search and replace uses &lt;i&gt;regular expressions&lt;/i&gt;. See the &lt;a href=&quot;http://calibre-ebook.com/user_manual/regexp.html&quot;&gt;regular expressions tutorial&lt;/a&gt; to get started with regular expressions. Also clicking the wizard buttons below will allow you to test your regular expression against the current input document.</string>
<string>&lt;p&gt;Search and replace uses &lt;i&gt;regular expressions&lt;/i&gt;. See the &lt;a href=&quot;http://manual.calibre-ebook.com/regexp.html&quot;&gt;regular expressions tutorial&lt;/a&gt; to get started with regular expressions. Also clicking the wizard buttons below will allow you to test your regular expression against the current input document.</string>
</property>
<property name="wordWrap">
<bool>true</bool>

View File

@ -127,7 +127,7 @@
<item>
<widget class="QLabel" name="label_5">
<property name="text">
<string>&lt;p&gt;For example, to match all h2 tags that have class=&quot;chapter&quot;, set tag to &lt;i&gt;h2&lt;/i&gt;, attribute to &lt;i&gt;class&lt;/i&gt; and value to &lt;i&gt;chapter&lt;/i&gt;.&lt;/p&gt;&lt;p&gt;Leaving attribute blank will match any attribute and leaving value blank will match any value. Setting tag to * will match any tag.&lt;/p&gt;&lt;p&gt;To learn more advanced usage of XPath see the &lt;a href=&quot;http://calibre-ebook.com/user_manual/xpath.html&quot;&gt;XPath Tutorial&lt;/a&gt;.</string>
<string>&lt;p&gt;For example, to match all h2 tags that have class=&quot;chapter&quot;, set tag to &lt;i&gt;h2&lt;/i&gt;, attribute to &lt;i&gt;class&lt;/i&gt; and value to &lt;i&gt;chapter&lt;/i&gt;.&lt;/p&gt;&lt;p&gt;Leaving attribute blank will match any attribute and leaving value blank will match any value. Setting tag to * will match any tag.&lt;/p&gt;&lt;p&gt;To learn more advanced usage of XPath see the &lt;a href=&quot;http://manual.calibre-ebook.com/xpath.html&quot;&gt;XPath Tutorial&lt;/a&gt;.</string>
</property>
<property name="wordWrap">
<bool>true</bool>

View File

@ -1294,7 +1294,8 @@ class DeviceMixin(object): # {{{
self.book_db_uuid_path_map = None
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
if self.book_db_id_cache is None:

View File

@ -207,8 +207,9 @@ class SchedulerDialog(QDialog, Ui_Dialog):
self.recipe_model.searched.connect(self.search.search_done,
type=Qt.QueuedConnection)
self.recipe_model.searched.connect(self.search_done)
self.search.setFocus(Qt.OtherFocusReason)
self.recipes.setFocus(Qt.OtherFocusReason)
self.commit_on_change = True
self.previous_urn = None
self.recipes.setModel(self.recipe_model)
self.detail_box.setVisible(False)
@ -228,6 +229,9 @@ class SchedulerDialog(QDialog, Ui_Dialog):
self.old_news.setValue(gconf['oldest_news'])
self.go_button.clicked.connect(self.search.do_search)
self.clear_search_button.clicked.connect(self.search.clear_clicked)
def set_pw_echo_mode(self, state):
self.password.setEchoMode(self.password.Normal
if state == Qt.Checked else self.password.Password)
@ -265,14 +269,9 @@ class SchedulerDialog(QDialog, Ui_Dialog):
self.last_downloaded.setVisible(enabled)
def current_changed(self, current, previous):
if self.commit_on_change:
if previous.isValid():
if not self.commit(urn=getattr(previous.internalPointer(),
'urn', None)):
self.commit_on_change = False
self.recipes.setCurrentIndex(previous)
else:
self.commit_on_change = True
if self.previous_urn is not None:
self.commit(urn=self.previous_urn)
self.previous_urn = None
urn = self.current_urn
if urn is not None:
@ -332,6 +331,7 @@ class SchedulerDialog(QDialog, Ui_Dialog):
return True
def initialize_detail_box(self, urn):
self.previous_urn = urn
self.detail_box.setVisible(True)
self.download_button.setVisible(True)
self.detail_box.setCurrentIndex(0)

View File

@ -17,21 +17,30 @@
<iconset resource="../../../../resources/images.qrc">
<normaloff>:/images/scheduler.png</normaloff>:/images/scheduler.png</iconset>
</property>
<layout class="QGridLayout" name="gridLayout" columnstretch="0,1,2">
<layout class="QGridLayout" name="gridLayout">
<item row="0" column="0">
<widget class="QLabel" name="label_8">
<property name="text">
<string>&amp;Search:</string>
</property>
<property name="buddy">
<cstring>search</cstring>
</property>
</widget>
<layout class="QHBoxLayout" name="horizontalLayout_2">
<item>
<widget class="SearchBox2" name="search"/>
</item>
<item>
<widget class="QToolButton" name="go_button">
<property name="text">
<string>Go</string>
</property>
</widget>
</item>
<item>
<widget class="QToolButton" name="clear_search_button">
<property name="icon">
<iconset resource="../../../../resources/images.qrc">
<normaloff>:/images/clear_left.png</normaloff>:/images/clear_left.png</iconset>
</property>
</widget>
</item>
</layout>
</item>
<item row="0" column="1">
<widget class="SearchBox2" name="search"/>
</item>
<item row="0" column="2" rowspan="3">
<item row="0" column="1" rowspan="2">
<widget class="QScrollArea" name="scrollArea">
<property name="frameShape">
<enum>QFrame::NoFrame</enum>
@ -44,7 +53,7 @@
<rect>
<x>0</x>
<y>0</y>
<width>486</width>
<width>524</width>
<height>504</height>
</rect>
</property>
@ -320,7 +329,7 @@
</widget>
</widget>
</item>
<item row="1" column="0" colspan="2">
<item row="1" column="0">
<widget class="QTreeView" name="recipes">
<property name="sizePolicy">
<sizepolicy hsizetype="Minimum" vsizetype="Expanding">
@ -345,7 +354,17 @@
</property>
</widget>
</item>
<item row="3" column="2">
<item row="2" column="0">
<widget class="QLabel" name="count_label">
<property name="text">
<string/>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
<item row="2" column="1">
<layout class="QHBoxLayout" name="horizontalLayout_3">
<item>
<widget class="QLabel" name="label_7">
@ -376,17 +395,7 @@
</item>
</layout>
</item>
<item row="4" column="2">
<widget class="QDialogButtonBox" name="buttonBox">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="standardButtons">
<set>QDialogButtonBox::Save</set>
</property>
</widget>
</item>
<item row="4" column="0" colspan="2">
<item row="3" column="0">
<widget class="QPushButton" name="download_all_button">
<property name="toolTip">
<string>Download all scheduled news sources at once</string>
@ -394,15 +403,19 @@
<property name="text">
<string>Download &amp;all scheduled</string>
</property>
<property name="icon">
<iconset resource="../../../../resources/images.qrc">
<normaloff>:/images/news.png</normaloff>:/images/news.png</iconset>
</property>
</widget>
</item>
<item row="3" column="0" colspan="2">
<widget class="QLabel" name="count_label">
<property name="text">
<string/>
<item row="3" column="1">
<widget class="QDialogButtonBox" name="buttonBox">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
<property name="standardButtons">
<set>QDialogButtonBox::Save</set>
</property>
</widget>
</item>

View File

@ -177,7 +177,7 @@
</size>
</property>
<property name="text">
<string>See the &lt;a href=&quot;http://calibre-ebook.com/user_manual/gui.html#the-search-interface&quot;&gt;User Manual&lt;/a&gt; for more help</string>
<string>See the &lt;a href=&quot;http://manual.calibre-ebook.com/gui.html#the-search-interface&quot;&gt;User Manual&lt;/a&gt; for more help</string>
</property>
<property name="openExternalLinks">
<bool>true</bool>

View File

@ -5,21 +5,213 @@ __license__ = 'GPL v3'
import json
from PyQt4.Qt import Qt, QDialog, QDialogButtonBox
from PyQt4.Qt import (Qt, QDialog, QDialogButtonBox, QSyntaxHighlighter,
QRegExp, QApplication,
QTextCharFormat, QFont, QColor, QCursor)
from calibre.gui2.dialogs.template_dialog_ui import Ui_TemplateDialog
from calibre.utils.formatter_functions import formatter_functions
from calibre.ebooks.metadata.book.base import composite_formatter
class ParenPosition:
def __init__(self, block, pos, paren):
self.block = block
self.pos = pos
self.paren = paren
self.highlight = False
def set_highlight(self, to_what):
self.highlight = to_what
class TemplateHighlighter(QSyntaxHighlighter):
Config = {}
Rules = []
Formats = {}
BN_FACTOR = 1000
KEYWORDS = ["program"]
def __init__(self, parent=None):
super(TemplateHighlighter, self).__init__(parent)
self.initializeFormats()
TemplateHighlighter.Rules.append((QRegExp(
"|".join([r"\b%s\b" % keyword for keyword in self.KEYWORDS])),
"keyword"))
TemplateHighlighter.Rules.append((QRegExp(
"|".join([r"\b%s\b" % builtin for builtin in
formatter_functions.get_builtins()])),
"builtin"))
TemplateHighlighter.Rules.append((QRegExp(
r"\b[+-]?[0-9]+[lL]?\b"
r"|\b[+-]?0[xX][0-9A-Fa-f]+[lL]?\b"
r"|\b[+-]?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\b"),
"number"))
stringRe = QRegExp(r"""(?:[^:]'[^']*'|"[^"]*")""")
stringRe.setMinimal(True)
TemplateHighlighter.Rules.append((stringRe, "string"))
lparenRe = QRegExp(r'\(')
lparenRe.setMinimal(True)
TemplateHighlighter.Rules.append((lparenRe, "lparen"))
rparenRe = QRegExp(r'\)')
rparenRe.setMinimal(True)
TemplateHighlighter.Rules.append((rparenRe, "rparen"))
self.regenerate_paren_positions()
self.highlighted_paren = False
def initializeFormats(self):
Config = self.Config
Config["fontfamily"] = "monospace"
#Config["fontsize"] = 10
for name, color, bold, italic in (
("normal", "#000000", False, False),
("keyword", "#000080", True, False),
("builtin", "#0000A0", False, False),
("comment", "#007F00", False, True),
("string", "#808000", False, False),
("number", "#924900", False, False),
("lparen", "#000000", True, True),
("rparen", "#000000", True, True)):
Config["%sfontcolor" % name] = color
Config["%sfontbold" % name] = bold
Config["%sfontitalic" % name] = italic
baseFormat = QTextCharFormat()
baseFormat.setFontFamily(Config["fontfamily"])
#baseFormat.setFontPointSize(Config["fontsize"])
for name in ("normal", "keyword", "builtin", "comment",
"string", "number", "lparen", "rparen"):
format = QTextCharFormat(baseFormat)
format.setForeground(QColor(Config["%sfontcolor" % name]))
if Config["%sfontbold" % name]:
format.setFontWeight(QFont.Bold)
format.setFontItalic(Config["%sfontitalic" % name])
self.Formats[name] = format
def find_paren(self, bn, pos):
dex = bn * self.BN_FACTOR + pos
return self.paren_pos_map.get(dex, None)
def highlightBlock(self, text):
bn = self.currentBlock().blockNumber()
textLength = text.length()
self.setFormat(0, textLength, self.Formats["normal"])
if text.isEmpty():
pass
elif text[0] == "#":
self.setFormat(0, text.length(), self.Formats["comment"])
return
for regex, format in TemplateHighlighter.Rules:
i = regex.indexIn(text)
while i >= 0:
length = regex.matchedLength()
if format in ['lparen', 'rparen']:
pp = self.find_paren(bn, i)
if pp and pp.highlight:
self.setFormat(i, length, self.Formats[format])
else:
self.setFormat(i, length, self.Formats[format])
i = regex.indexIn(text, i + length)
if self.generate_paren_positions:
t = unicode(text)
i = 0
foundQuote = False
while i < len(t):
c = t[i]
if c == ':':
# Deal with the funky syntax of template program mode.
# This won't work if there are more than one template
# expression in the document.
if not foundQuote and i+1 < len(t) and t[i+1] == "'":
i += 2
elif c in ["'", '"']:
foundQuote = True
i += 1
j = t[i:].find(c)
if j < 0:
i = len(t)
else:
i = i + j
elif c in ['(', ')']:
pp = ParenPosition(bn, i, c)
self.paren_positions.append(pp)
self.paren_pos_map[bn*self.BN_FACTOR+i] = pp
i += 1
def rehighlight(self):
QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
QSyntaxHighlighter.rehighlight(self)
QApplication.restoreOverrideCursor()
def check_cursor_pos(self, chr, block, pos_in_block):
found_pp = -1
for i, pp in enumerate(self.paren_positions):
pp.set_highlight(False)
if pp.block == block and pp.pos == pos_in_block:
found_pp = i
if chr not in ['(', ')']:
if self.highlighted_paren:
self.rehighlight()
self.highlighted_paren = False
return
if found_pp >= 0:
stack = 0
if chr == '(':
list = self.paren_positions[found_pp+1:]
else:
list = reversed(self.paren_positions[0:found_pp])
for pp in list:
if pp.paren == chr:
stack += 1;
elif stack:
stack -= 1
else:
pp.set_highlight(True)
self.paren_positions[found_pp].set_highlight(True)
break
self.highlighted_paren = True
self.rehighlight()
def regenerate_paren_positions(self):
self.generate_paren_positions = True
self.paren_positions = []
self.paren_pos_map = {}
self.rehighlight()
self.generate_paren_positions = False
class TemplateDialog(QDialog, Ui_TemplateDialog):
def __init__(self, parent, text):
def __init__(self, parent, text, mi):
QDialog.__init__(self, parent)
Ui_TemplateDialog.__init__(self)
self.setupUi(self)
self.mi = mi
# Remove help icon on title bar
icon = self.windowIcon()
self.setWindowFlags(self.windowFlags()&(~Qt.WindowContextHelpButtonHint))
self.setWindowIcon(icon)
self.last_text = ''
self.highlighter = TemplateHighlighter(self.textbox.document())
self.textbox.cursorPositionChanged.connect(self.text_cursor_changed)
self.textbox.textChanged.connect(self.textbox_changed)
self.textbox.setTabStopWidth(10)
self.source_code.setTabStopWidth(10)
self.documentation.setReadOnly(True)
@ -45,6 +237,26 @@ class TemplateDialog(QDialog, Ui_TemplateDialog):
self.function.addItems(func_names)
self.function.setCurrentIndex(0)
self.function.currentIndexChanged[str].connect(self.function_changed)
self.textbox_changed()
def textbox_changed(self):
cur_text = unicode(self.textbox.toPlainText())
if self.last_text != cur_text:
self.last_text = cur_text
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):
cursor = self.textbox.textCursor()
block_number = cursor.blockNumber()
pos_in_block = cursor.positionInBlock()
position = cursor.position()
t = unicode(self.textbox.toPlainText())
if position < len(t):
self.highlighter.check_cursor_pos(t[position], block_number,
pos_in_block)
def function_changed(self, toWhat):
name = unicode(toWhat)

View File

@ -23,19 +23,39 @@
<item>
<widget class="QPlainTextEdit" name="textbox"/>
</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>
<layout class="QGridLayout" name="gridLayout">
<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">
<property name="text">
<string>Function &amp;name:</string>
@ -45,10 +65,10 @@
</property>
</widget>
</item>
<item row="0" column="1">
<item row="2" column="1">
<widget class="QComboBox" name="function"/>
</item>
<item row="1" column="0">
<item row="3" column="0">
<widget class="QLabel" name="label_2">
<property name="text">
<string>&amp;Documentation:</string>
@ -61,7 +81,7 @@
</property>
</widget>
</item>
<item row="2" column="0">
<item row="4" column="0">
<widget class="QLabel" name="label_3">
<property name="text">
<string>Python &amp;code:</string>
@ -74,7 +94,7 @@
</property>
</widget>
</item>
<item row="1" column="1">
<item row="3" column="1">
<widget class="QPlainTextEdit" name="documentation">
<property name="maximumSize">
<size>
@ -84,7 +104,7 @@
</property>
</widget>
</item>
<item row="2" column="1">
<item row="4" column="1">
<widget class="QPlainTextEdit" name="source_code"/>
</item>
</layout>

View File

@ -0,0 +1,444 @@
#!/usr/bin/env python
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
__license__ = 'GPL v3'
__copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
from functools import partial
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.complete import MultiCompleteLineEdit
from calibre.gui2 import error_dialog
from calibre.utils.icu import sort_key
class TemplateLineEditor(QLineEdit):
'''
Extend the context menu of a QLineEdit to include more actions.
'''
def __init__(self, parent):
QLineEdit.__init__(self, parent)
self.tags = None
self.mi = None
self.txt = None
def set_mi(self, mi):
self.mi = mi
def set_db(self, db):
self.db = db
def contextMenuEvent(self, event):
menu = self.createStandardContextMenu()
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.triggered.connect(self.open_editor)
menu.exec_(event.globalPos())
def clear_field(self):
self.setText('')
self.txt = None
self.setReadOnly(False)
self.setStyleSheet('TemplateLineEditor { color: black }')
def open_editor(self):
if self.txt:
t = TemplateDialog(self, self.txt, self.mi)
else:
t = TemplateDialog(self, self.text(), self.mi)
t.setWindowTitle(_('Edit template'))
if t.exec_():
self.txt = None
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):
txt = unicode(self.text())
if txt and not self.txt:
error_dialog(self, _('Invalid text'),
_('The text in the box was not generated by this wizard'),
show=True, show_copy_button=False)
return
d = TagWizard(self, self.db, unicode(self.txt), self.mi)
if d.exec_():
self.setText(d.template)
def text(self):
if self.txt:
return self.txt
return QLineEdit.text(self)
class TagWizard(QDialog):
def __init__(self, parent, db, txt, mi):
QDialog.__init__(self, parent)
self.setWindowTitle(_('Coloring Wizard'))
self.setWindowIcon(QIcon(I('wizard.png')))
self.mi = mi
self.columns = []
self.completion_values = defaultdict(dict)
for k in db.all_field_keys():
m = db.metadata_for_field(k)
if m['datatype'] in ('text', 'enumeration', 'series') and \
m['is_category'] and k not in ('identifiers'):
self.columns.append(k)
if m['is_custom']:
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()]
if k in self.completion_values:
if k == 'authors':
self.completion_values[k]['m'] = None
else:
self.completion_values[k]['m'] = m['is_multiple']
self.columns.sort(key=sort_key)
self.columns.insert(0, '')
l = QGridLayout()
self.setLayout(l)
l.setColumnStretch(2, 10)
l.setColumnMinimumWidth(3, 300)
h = QLabel(_('And'))
h.setToolTip('<p>' +
_('Set this box to indicate that the two conditions must both '
'be true to return the "color if value found". 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(_('Not'))
h.setToolTip('<p>' +
_('Set this box to indicate that the value must <b>not</b> match '
'to return the "color if value found". For example, you '
'can check if a tag does not exist by entering that tag '
'and checking this box. You can check if tags are empty by '
'checking this box, entering .* (period asterisk) for the text, '
'then checking the RE box. The .* regular expression matches '
'anything, so if this box is checked, it matches nothing. '
'This box is particularly useful when using the AND box.'))
h.setAlignment(Qt.AlignCenter)
l.addWidget(h, 0, 2, 1, 1)
h = QLabel(_('Values (see the popup help for more information)'))
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: you can '
'enter at most one author.<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 you are checking.<br>'
'Regular expression examples:') + '<ul>' +
_('<li><code><b>.*</b></code> matches anything in the column. No '
'empty values are checked, so you don\'t need to worry about '
'empty strings</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, 3, 1, 1)
c = QLabel(_('is RE'))
c.setToolTip('<p>' +
_('Check this box if the values box contains regular expressions') + '</p>')
l.addWidget(c, 0, 4, 1, 1)
c = QLabel(_('Color if value found'))
c.setToolTip('<p>' +
_('At least one of the two color boxes must have a value. Leave '
'one color box empty if you want the template to use the next '
'line in this wizard. If both boxes are filled in, the rest of '
'the lines in this wizard will be ignored.') + '</p>')
l.addWidget(c, 0, 5, 1, 1)
c = QLabel(_('Color if value not found'))
c.setToolTip('<p>' +
_('This box is usually filled in only on the last test. If it is '
'filled in before the last test, then the color for value found box '
'must be empty or all the rest of the tests will be ignored.') + '</p>')
l.addWidget(c, 0, 6, 1, 1)
self.andboxes = []
self.notboxes = []
self.tagboxes = []
self.colorboxes = []
self.nfcolorboxes = []
self.reboxes = []
self.colboxes = []
self.colors = [unicode(s) for s in list(QColor.colorNames())]
self.colors.insert(0, '')
maxlines = 10
for i in range(1, maxlines+1):
ab = QCheckBox(self)
self.andboxes.append(ab)
if i != maxlines:
# let the last box float in space
l.addWidget(ab, i, 0, 2, 1)
ab.stateChanged.connect(partial(self.and_box_changed, line=i-1))
else:
ab.setVisible(False)
w = QComboBox(self)
w.addItems(self.columns)
l.addWidget(w, i, 1, 1, 1)
self.colboxes.append(w)
nb = QCheckBox(self)
self.notboxes.append(nb)
l.addWidget(nb, i, 2, 1, 1)
tb = MultiCompleteLineEdit(self)
tb.set_separator(', ')
self.tagboxes.append(tb)
l.addWidget(tb, i, 3, 1, 1)
w.currentIndexChanged[str].connect(partial(self.column_changed, valbox=tb))
w = QCheckBox(self)
self.reboxes.append(w)
l.addWidget(w, i, 4, 1, 1)
w = QComboBox(self)
w.addItems(self.colors)
self.colorboxes.append(w)
l.addWidget(w, i, 5, 1, 1)
w = QComboBox(self)
w.addItems(self.colors)
self.nfcolorboxes.append(w)
l.addWidget(w, i, 6, 1, 1)
if txt:
lines = txt.split('\n')[3:]
i = 0
for line in lines:
if line.startswith('#'):
vals = line[1:].split(':|:')
if len(vals) == 2:
t, c = vals
nc = ''
re = False
f = 'tags'
a = False
n = False
else:
t,c,f,nc,re,a,n = vals
try:
self.colboxes[i].setCurrentIndex(self.colboxes[i].findText(f))
self.colorboxes[i].setCurrentIndex(
self.colorboxes[i].findText(c))
self.nfcolorboxes[i].setCurrentIndex(
self.nfcolorboxes[i].findText(nc))
self.tagboxes[i].setText(t)
self.reboxes[i].setChecked(re == '2')
self.andboxes[i].setChecked(a == '2')
self.notboxes[i].setChecked(n == '2')
i += 1
except:
pass
w = QLabel(_('Preview'))
l.addWidget(w, 99, 1, 1, 1)
w = self.test_box = QLineEdit(self)
w.setReadOnly(True)
l.addWidget(w, 99, 3, 1, 1)
w = QPushButton(_('Test'))
l.addWidget(w, 99, 5, 1, 1)
w.clicked.connect(self.preview)
bb = QDialogButtonBox(QDialogButtonBox.Ok|QDialogButtonBox.Cancel, parent=self)
l.addWidget(bb, 100, 3, 1, 2)
bb.accepted.connect(self.accepted)
bb.rejected.connect(self.reject)
self.template = ''
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 column_changed(self, s, valbox=None):
k = unicode(s)
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)
else:
valbox.update_items_cache([])
valbox.set_separator(None)
def generate_program(self):
res = ("program:\n#tag wizard -- do not directly edit\n"
" first_non_empty(\n")
lines = []
was_and = False
had_line = False
line = 0
for tb, cb, fb, nfcb, reb, ab, nb in zip(
self.tagboxes, self.colorboxes, self.colboxes,
self.nfcolorboxes, self.reboxes, self.andboxes, self.notboxes):
f = unicode(fb.currentText())
if not f:
continue
m = self.completion_values[f]['m']
c = unicode(cb.currentText()).strip()
nfc = unicode(nfcb.currentText()).strip()
re = reb.checkState()
a = ab.checkState()
n = nb.checkState()
line += 1
if n == 2:
tval = ''
fval = '1'
else:
tval = '1'
fval = ''
if m:
tags = [t.strip() for t in unicode(tb.text()).split(',') if t.strip()]
if re == 2:
tags = '$|^'.join(tags)
else:
tags = ','.join(tags)
else:
tags = unicode(tb.text()).strip()
if f == 'authors':
tags.replace(',', '|')
if (tags or f) and not (tags 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)
return False
if c not in self.colors:
error_dialog(self, _('Invalid color'),
_('The color {0} is not valid').format(c),
show=True, show_copy_button=False)
return False
if nfc not in self.colors:
error_dialog(self, _('Invalid color'),
_('The color {0} is not valid').format(nfc),
show=True, show_copy_button=False)
return False
if not was_and:
if had_line:
lines[-1] += ','
had_line = True
lines.append(" test(and(")
else:
lines[-1] += ','
if re == 2:
if m:
lines.append(" in_list(field('{1}'), ',', '^{0}$', '{2}', '{3}')".\
format(tags, f, tval, fval))
else:
lines.append(" contains(field('{1}'), '{0}', '{2}', '{3}')".\
format(tags, f, tval, fval))
else:
if m:
lines.append(" str_in_list(field('{1}'), ',', '{0}', '{2}', '{3}')".\
format(tags, f, tval, fval))
else:
lines.append(" strcmp(field('{1}'), '{0}', '{3}', '{2}', '{3}')".\
format(tags, f, tval, fval))
if a == 2:
was_and = True
else:
was_and = False
lines.append(" ), '{0}', '{1}')".format(c, nfc))
res += '\n'.join(lines)
res += ')\n'
self.template = res
res = ''
for tb, cb, fb, nfcb, reb, ab, nb in zip(
self.tagboxes, self.colorboxes, self.colboxes,
self.nfcolorboxes, self.reboxes, self.andboxes, self.notboxes):
t = unicode(tb.text()).strip()
if t.endswith(','):
t = t[:-1]
c = unicode(cb.currentText()).strip()
f = unicode(fb.currentText())
nfc = unicode(nfcb.currentText()).strip()
re = unicode(reb.checkState())
a = unicode(ab.checkState())
n = unicode(nb.checkState())
if f and t and (a == '2' or c):
res += '#' + t + ':|:' + c + ':|:' + f + ':|:' + \
nfc + ':|:' + re + ':|:' + a + ':|:' + n + '\n'
self.template += res
return True
def and_box_changed(self, state, line=None):
if state == 2:
self.colorboxes[line].setCurrentIndex(0)
self.colorboxes[line].setEnabled(False)
self.nfcolorboxes[line].setCurrentIndex(0)
self.nfcolorboxes[line].setEnabled(False)
else:
self.colorboxes[line].setEnabled(True)
self.nfcolorboxes[line].setEnabled(True)
def accepted(self):
if self.generate_program():
self.accept()
else:
self.template = ''

View File

@ -386,7 +386,7 @@ p, li { white-space: pre-wrap; }
<item>
<widget class="QLabel" name="label_8">
<property name="text">
<string>For help with writing advanced news recipes, please visit &lt;a href=&quot;http://__appname__-ebook.com/user_manual/news.html&quot;&gt;User Recipes&lt;/a&gt;</string>
<string>For help with writing advanced news recipes, please visit &lt;a href=&quot;http://manual.__appname__-ebook.com/news.html&quot;&gt;User Recipes&lt;/a&gt;</string>
</property>
<property name="wordWrap">
<bool>true</bool>

View File

@ -19,7 +19,7 @@
<property name="text">
<string>&lt;div style=&quot;font-size:10pt;&quot;&gt;
&lt;p&gt;Set a regular expression pattern to use when trying to guess ebook metadata from filenames. &lt;/p&gt;
&lt;p&gt;A &lt;a href=&quot;http://calibre-ebook.com/user_manual/regexp.html&quot;&gt;tutorial&lt;/a&gt; on using regular expressions is available.&lt;/p&gt;
&lt;p&gt;A &lt;a href=&quot;http://manual.calibre-ebook.com/regexp.html&quot;&gt;tutorial&lt;/a&gt; on using regular expressions is available.&lt;/p&gt;
&lt;p&gt;Use the &lt;b&gt;Test&lt;/b&gt; functionality below to test your regular expression on a few sample filenames (remember to include the file extension). The group names for the various metadata entries are documented in tooltips.&lt;/p&gt;&lt;/div&gt;</string>
</property>
<property name="textFormat">

View File

@ -238,7 +238,6 @@ class Spacer(QWidget): # {{{
self.l.addStretch(10)
# }}}
class MainWindowMixin(object): # {{{
def __init__(self, db):

View File

@ -7,11 +7,12 @@ __docformat__ = 'restructuredtext en'
from math import cos, sin, pi
from PyQt4.Qt import QColor, Qt, QModelIndex, QSize, \
QPainterPath, QLinearGradient, QBrush, \
QPen, QStyle, QPainter, QStyleOptionViewItemV4, \
QIcon, QDoubleSpinBox, QVariant, QSpinBox, \
QStyledItemDelegate, QComboBox, QTextDocument
from PyQt4.Qt import (QColor, Qt, QModelIndex, QSize, QApplication,
QPainterPath, QLinearGradient, QBrush,
QPen, QStyle, QPainter, QStyleOptionViewItemV4,
QIcon, QDoubleSpinBox, QVariant, QSpinBox,
QStyledItemDelegate, QComboBox, QTextDocument,
QAbstractTextDocumentLayout)
from calibre.gui2 import UNDEFINED_QDATE, error_dialog
from calibre.gui2.widgets import EnLineEdit
@ -27,7 +28,6 @@ from calibre.gui2.dialogs.template_dialog import TemplateDialog
class RatingDelegate(QStyledItemDelegate): # {{{
COLOR = QColor("blue")
SIZE = 16
PEN = QPen(COLOR, 1, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin)
def __init__(self, parent):
QStyledItemDelegate.__init__(self, parent)
@ -40,10 +40,7 @@ class RatingDelegate(QStyledItemDelegate): # {{{
50 + 40 * sin(0.8 * i * pi))
self.star_path.closeSubpath()
self.star_path.setFillRule(Qt.WindingFill)
gradient = QLinearGradient(0, 0, 0, 100)
gradient.setColorAt(0.0, self.COLOR)
gradient.setColorAt(1.0, self.COLOR)
self.brush = QBrush(gradient)
self.gradient = QLinearGradient(0, 0, 0, 100)
self.factor = self.SIZE/100.
def sizeHint(self, option, index):
@ -53,7 +50,8 @@ class RatingDelegate(QStyledItemDelegate): # {{{
def paint(self, painter, option, index):
style = self._parent.style()
option = QStyleOptionViewItemV4(option)
self.initStyleOption(option, self.dummy)
self.initStyleOption(option, index)
option.text = u''
num = index.model().data(index, Qt.DisplayRole).toInt()[0]
def draw_star():
painter.save()
@ -70,13 +68,23 @@ class RatingDelegate(QStyledItemDelegate): # {{{
painter, self._parent)
elif option.state & QStyle.State_Selected:
painter.fillRect(option.rect, option.palette.highlight())
else:
painter.fillRect(option.rect, option.backgroundBrush)
try:
painter.setRenderHint(QPainter.Antialiasing)
painter.setClipRect(option.rect)
y = option.rect.center().y()-self.SIZE/2.
x = option.rect.left()
painter.setPen(self.PEN)
painter.setBrush(self.brush)
color = index.data(Qt.ForegroundRole)
if color.isNull() or not color.isValid():
color = self.COLOR
else:
color = QColor(color)
painter.setPen(QPen(color, 1, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin))
self.gradient.setColorAt(0.0, color)
self.gradient.setColorAt(1.0, color)
painter.setBrush(QBrush(self.gradient))
painter.translate(x, y)
i = 0
while i < num:
@ -241,6 +249,23 @@ class CcDateDelegate(QStyledItemDelegate): # {{{
# }}}
class CcTextDelegate(QStyledItemDelegate): # {{{
'''
Delegate for text data.
'''
def createEditor(self, parent, option, index):
m = index.model()
col = m.column_map[index.column()]
editor = MultiCompleteLineEdit(parent)
editor.set_separator(None)
complete_items = sorted(list(m.db.all_custom(label=m.db.field_metadata.key_to_label(col))),
key=sort_key)
editor.update_items_cache(complete_items)
return editor
# }}}
class CcNumberDelegate(QStyledItemDelegate): # {{{
'''
Delegate for text/int/float data.
'''
@ -248,25 +273,23 @@ class CcTextDelegate(QStyledItemDelegate): # {{{
def createEditor(self, parent, option, index):
m = index.model()
col = m.column_map[index.column()]
typ = m.custom_columns[col]['datatype']
if typ == 'int':
if m.custom_columns[col]['datatype'] == 'int':
editor = QSpinBox(parent)
editor.setRange(-100, 100000000)
editor.setSpecialValueText(_('Undefined'))
editor.setSingleStep(1)
elif typ == 'float':
else:
editor = QDoubleSpinBox(parent)
editor.setSpecialValueText(_('Undefined'))
editor.setRange(-100., 100000000)
editor.setDecimals(2)
else:
editor = MultiCompleteLineEdit(parent)
editor.set_separator(None)
complete_items = sorted(list(m.db.all_custom(label=m.db.field_metadata.key_to_label(col))),
key=sort_key)
editor.update_items_cache(complete_items)
return editor
def setEditorData(self, editor, index):
m = index.model()
val = m.db.data[index.row()][m.custom_columns[m.column_map[index.column()]]['rec_index']]
editor.setValue(val)
# }}}
class CcEnumDelegate(QStyledItemDelegate): # {{{
@ -311,18 +334,22 @@ class CcCommentsDelegate(QStyledItemDelegate): # {{{
self.document = QTextDocument()
def paint(self, painter, option, index):
style = self.parent().style()
self.document.setHtml(index.data(Qt.DisplayRole).toString())
painter.save()
self.initStyleOption(option, index)
style = QApplication.style() if option.widget is None \
else option.widget.style()
self.document.setHtml(option.text)
option.text = u''
if hasattr(QStyle, 'CE_ItemViewItem'):
style.drawControl(QStyle.CE_ItemViewItem, option,
painter, self.parent())
elif option.state & QStyle.State_Selected:
painter.fillRect(option.rect, option.palette.highlight())
painter.setClipRect(option.rect)
painter.translate(option.rect.topLeft())
self.document.drawContents(painter)
painter.restore()
style.drawControl(QStyle.CE_ItemViewItem, option, painter)
ctx = QAbstractTextDocumentLayout.PaintContext()
ctx.palette = option.palette #.setColor(QPalette.Text, QColor("red"));
if hasattr(QStyle, 'SE_ItemViewItemText'):
textRect = style.subElementRect(QStyle.SE_ItemViewItemText, option)
painter.save()
painter.translate(textRect.topLeft())
painter.setClipRect(textRect.translated(-textRect.topLeft()))
self.document.documentLayout().draw(painter, ctx)
painter.restore()
def createEditor(self, parent, option, index):
m = index.model()
@ -391,8 +418,9 @@ class CcTemplateDelegate(QStyledItemDelegate): # {{{
def createEditor(self, parent, option, index):
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']
editor = TemplateDialog(parent, text)
editor = TemplateDialog(parent, text, mi)
editor.setWindowTitle(_("Edit template"))
editor.textbox.setTabChangesFocus(False)
editor.textbox.setTabStopWidth(20)

View File

@ -7,6 +7,7 @@ __docformat__ = 'restructuredtext en'
import shutil, functools, re, os, traceback
from contextlib import closing
from collections import defaultdict
from PyQt4.Qt import (QAbstractTableModel, Qt, pyqtSignal, QIcon, QImage,
QModelIndex, QVariant, QDate, QColor)
@ -14,6 +15,7 @@ from PyQt4.Qt import (QAbstractTableModel, Qt, pyqtSignal, QIcon, QImage,
from calibre.gui2 import NONE, UNDEFINED_QDATE
from calibre.utils.pyparsing import ParseException
from calibre.ebooks.metadata import fmt_sidx, authors_to_string, string_to_authors
from calibre.ebooks.metadata.book.base import composite_formatter
from calibre.ptempfile import PersistentTemporaryFile
from calibre.utils.config import tweaks, prefs
from calibre.utils.date import dt_factory, qt_to_dt
@ -86,6 +88,7 @@ class BooksModel(QAbstractTableModel): # {{{
self.column_map = []
self.headers = {}
self.alignment_map = {}
self.color_cache = defaultdict(dict)
self.buffer_size = buffer
self.metadata_backup = None
self.bool_yes_icon = QIcon(I('ok.png'))
@ -96,6 +99,8 @@ class BooksModel(QAbstractTableModel): # {{{
self.ids_to_highlight_set = set()
self.current_highlighted_idx = None
self.highlight_only = False
self.column_color_map = {}
self.colors = [unicode(c) for c in QColor.colorNames()]
self.read_config()
def change_alignment(self, colname, alignment):
@ -151,6 +156,7 @@ class BooksModel(QAbstractTableModel): # {{{
self.headers[col] = self.custom_columns[col]['name']
self.build_data_convertors()
self.set_color_templates(reset=False)
self.reset()
self.database_changed.emit(db)
self.stop_metadata_backup()
@ -168,11 +174,13 @@ class BooksModel(QAbstractTableModel): # {{{
def refresh_ids(self, ids, current_row=-1):
self.color_cache = defaultdict(dict)
rows = self.db.refresh_ids(ids)
if rows:
self.refresh_rows(rows, current_row=current_row)
def refresh_rows(self, rows, current_row=-1):
self.color_cache = defaultdict(dict)
for row in rows:
if row == current_row:
self.new_bookdisplay_data.emit(
@ -202,6 +210,7 @@ class BooksModel(QAbstractTableModel): # {{{
return ret
def count_changed(self, *args):
self.color_cache = defaultdict(dict)
self.count_changed_signal.emit(self.db.count())
def row_indices(self, index):
@ -332,6 +341,10 @@ class BooksModel(QAbstractTableModel): # {{{
self.db.refresh(field=None)
self.resort(reset=reset)
def reset(self):
self.color_cache = defaultdict(dict)
QAbstractTableModel.reset(self)
def resort(self, reset=True):
if not self.db:
return
@ -532,6 +545,15 @@ class BooksModel(QAbstractTableModel): # {{{
img = self.default_image
return img
def set_color_templates(self, reset=True):
self.column_color_map = {}
for i in range(1,self.db.column_color_count+1):
name = self.db.prefs.get('column_color_name_'+str(i))
if name:
self.column_color_map[name] = \
self.db.prefs.get('column_color_template_'+str(i))
if reset:
self.reset()
def build_data_convertors(self):
def authors(r, idx=-1):
@ -610,7 +632,12 @@ class BooksModel(QAbstractTableModel): # {{{
return None
return QVariant(text)
def number_type(r, idx=-1):
def number_type(r, idx=-1, fmt=None):
if fmt is not None:
try:
return QVariant(fmt.format(self.db.data[r][idx]))
except:
pass
return QVariant(self.db.data[r][idx])
self.dc = {
@ -661,7 +688,8 @@ class BooksModel(QAbstractTableModel): # {{{
bool_cols_are_tristate=
self.db.prefs.get('bools_are_tristate'))
elif datatype in ('int', 'float'):
self.dc[col] = functools.partial(number_type, idx=idx)
fmt = self.custom_columns[col]['display'].get('number_format', None)
self.dc[col] = functools.partial(number_type, idx=idx, fmt=fmt)
elif datatype == 'datetime':
self.dc[col] = functools.partial(datetime_type, idx=idx)
elif datatype == 'bool':
@ -693,9 +721,42 @@ class BooksModel(QAbstractTableModel): # {{{
return NONE
if role in (Qt.DisplayRole, Qt.EditRole):
return self.column_to_dc_map[col](index.row())
elif role == Qt.BackgroundColorRole:
elif role == Qt.BackgroundRole:
if self.id(index) in self.ids_to_highlight_set:
return QColor('lightgreen')
return QVariant(QColor('lightgreen'))
elif role == Qt.ForegroundRole:
key = self.column_map[col]
if key in self.column_color_map:
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)
fmt = self.column_color_map[key]
try:
color = composite_formatter.safe_format(fmt, mi, '', mi)
if color in self.colors:
color = QColor(color)
if color.isValid():
color = QVariant(color)
self.color_cache[id_][key] = color
return color
except:
return NONE
elif self.is_custom_column(key) and \
self.custom_columns[key]['datatype'] == 'enumeration':
cc = self.custom_columns[self.column_map[col]]['display']
colors = cc.get('enum_colors', [])
values = cc.get('enum_values', [])
txt = unicode(index.data(Qt.DisplayRole).toString())
if len(colors) > 0 and txt in values:
try:
color = QColor(colors[values.index(txt)])
if color.isValid():
return QVariant(color)
except:
pass
return NONE
elif role == Qt.DecorationRole:
if self.column_to_dc_decorator_map[col] is not None:
return self.column_to_dc_decorator_map[index.column()](index.row())

View File

@ -15,7 +15,7 @@ from PyQt4.Qt import QTableView, Qt, QAbstractItemView, QMenu, pyqtSignal, \
from calibre.gui2.library.delegates import RatingDelegate, PubDateDelegate, \
TextDelegate, DateDelegate, CompleteDelegate, CcTextDelegate, \
CcBoolDelegate, CcCommentsDelegate, CcDateDelegate, CcTemplateDelegate, \
CcEnumDelegate
CcEnumDelegate, CcNumberDelegate
from calibre.gui2.library.models import BooksModel, DeviceBooksModel
from calibre.utils.config import tweaks, prefs
from calibre.gui2 import error_dialog, gprefs
@ -89,6 +89,7 @@ class BooksView(QTableView): # {{{
self.cc_bool_delegate = CcBoolDelegate(self)
self.cc_comments_delegate = CcCommentsDelegate(self)
self.cc_template_delegate = CcTemplateDelegate(self)
self.cc_number_delegate = CcNumberDelegate(self)
self.display_parent = parent
self._model = modelcls(self)
self.setModel(self._model)
@ -501,8 +502,10 @@ class BooksView(QTableView): # {{{
self.tags_delegate)
else:
self.setItemDelegateForColumn(cm.index(colhead), self.cc_text_delegate)
elif cc['datatype'] in ('series', 'int', 'float'):
elif cc['datatype'] == 'series':
self.setItemDelegateForColumn(cm.index(colhead), self.cc_text_delegate)
elif cc['datatype'] in ('int', 'float'):
self.setItemDelegateForColumn(cm.index(colhead), self.cc_number_delegate)
elif cc['datatype'] == 'bool':
self.setItemDelegateForColumn(cm.index(colhead), self.cc_bool_delegate)
elif cc['datatype'] == 'rating':

View File

@ -5,7 +5,7 @@ import sys, logging, os, traceback, time
from PyQt4.QtGui import QKeySequence, QPainter, QDialog, QSpinBox, QSlider, QIcon
from PyQt4.QtCore import Qt, QObject, SIGNAL, QCoreApplication, QThread
from calibre import __appname__, setup_cli_handlers, islinux, isfreebsd
from calibre import __appname__, setup_cli_handlers, islinux, isbsd
from calibre.ebooks.lrf.lrfparser import LRFDocument
from calibre.gui2 import ORG_NAME, APP_UID, error_dialog, \
@ -258,7 +258,7 @@ def file_renderer(stream, opts, parent=None, logger=None):
level = logging.DEBUG if opts.verbose else logging.INFO
logger = logging.getLogger('lrfviewer')
setup_cli_handlers(logger, level)
if islinux or isfreebsd:
if islinux or isbsd:
try: # Set lrfviewer as the default for LRF files for this user
from subprocess import call
call('xdg-mime default calibre-lrfviewer.desktop application/lrf', shell=True)
@ -307,7 +307,7 @@ def main(args=sys.argv, logger=None):
if hasattr(opts, 'help'):
parser.print_help()
return 1
pid = os.fork() if (islinux or isfreebsd) else -1
pid = os.fork() if (islinux or isbsd) else -1
if pid <= 0:
app = Application(args)
app.setWindowIcon(QIcon(I('viewer.png')))

View File

@ -88,11 +88,22 @@ class TitleEdit(EnLineEdit):
def commit(self, db, id_):
title = self.current_val
if self.COMMIT:
getattr(db, 'set_'+ self.TITLE_ATTR)(id_, title, notify=False)
else:
getattr(db, 'set_'+ self.TITLE_ATTR)(id_, title, notify=False,
commit=False)
try:
if self.COMMIT:
getattr(db, 'set_'+ self.TITLE_ATTR)(id_, title, notify=False)
else:
getattr(db, 'set_'+ self.TITLE_ATTR)(id_, title, notify=False,
commit=False)
except (IOError, OSError) as err:
if getattr(err, 'errno', -1) == 13: # Permission denied
import traceback
fname = err.filename if err.filename else 'file'
error_dialog(self, _('Permission denied'),
_('Could not open %s. Is it being used by another'
' program?')%fname, det_msg=traceback.format_exc(),
show=True)
return False
raise
return True
@dynamic_property
@ -225,8 +236,19 @@ class AuthorsEdit(MultiCompleteComboBox):
def commit(self, db, id_):
authors = self.current_val
self.books_to_refresh |= db.set_authors(id_, authors, notify=False,
try:
self.books_to_refresh |= db.set_authors(id_, authors, notify=False,
allow_case_change=True)
except (IOError, OSError) as err:
if getattr(err, 'errno', -1) == 13: # Permission denied
import traceback
fname = err.filename if err.filename else 'file'
error_dialog(self, _('Permission denied'),
_('Could not open %s. Is it being used by another'
' program?')%fname, det_msg=traceback.format_exc(),
show=True)
return False
raise
return True
@dynamic_property

View File

@ -6,7 +6,7 @@ __copyright__ = '2010, Kovid Goyal <kovid at kovidgoyal.net>'
import re
from functools import partial
from PyQt4.Qt import QDialog, Qt, QListWidgetItem, QVariant
from PyQt4.Qt import QDialog, Qt, QListWidgetItem, QVariant, QColor
from calibre.gui2.preferences.create_custom_column_ui import Ui_QCreateCustomColumn
from calibre.gui2 import error_dialog
@ -126,11 +126,18 @@ class CreateCustomColumn(QDialog, Ui_QCreateCustomColumn):
c['display'].get('make_category', False))
elif ct == 'enumeration':
self.enum_box.setText(','.join(c['display'].get('enum_values', [])))
self.enum_colors.setText(','.join(c['display'].get('enum_colors', [])))
elif ct in ['int', 'float']:
if c['display'].get('number_format', None):
self.number_format_box.setText(c['display'].get('number_format', ''))
self.datatype_changed()
if ct in ['text', 'composite', 'enumeration']:
self.use_decorations.setChecked(c['display'].get('use_decorations', False))
elif ct == '*text':
self.is_names.setChecked(c['display'].get('is_names', False))
all_colors = [unicode(s) for s in list(QColor.colorNames())]
self.enum_colors_label.setToolTip('<p>' + ', '.join(all_colors) + '</p>')
self.exec_()
def shortcut_activated(self, url):
@ -167,13 +174,26 @@ class CreateCustomColumn(QDialog, Ui_QCreateCustomColumn):
col_type = None
for x in ('box', 'default_label', 'label'):
getattr(self, 'date_format_'+x).setVisible(col_type == 'datetime')
getattr(self, 'number_format_'+x).setVisible(col_type in ['int', 'float'])
for x in ('box', 'default_label', 'label', 'sort_by', 'sort_by_label',
'make_category'):
getattr(self, 'composite_'+x).setVisible(col_type in ['composite', '*composite'])
for x in ('box', 'default_label', 'label'):
for x in ('box', 'default_label', 'label', 'colors', 'colors_label'):
getattr(self, 'enum_'+x).setVisible(col_type == 'enumeration')
self.use_decorations.setVisible(col_type in ['text', 'composite', 'enumeration'])
self.is_names.setVisible(col_type == '*text')
if col_type == 'int':
self.number_format_box.setToolTip('<p>' +
_('Examples: The format <code>{0:0>4d}</code> '
'gives a 4-digit number with leading zeros. The format '
'<code>{0:d}&nbsp;days</code> prints the number then the word "days"')+ '</p>')
elif col_type == 'float':
self.number_format_box.setToolTip('<p>' +
_('Examples: The format <code>{0:.1f}</code> gives a floating '
'point number with 1 digit after the decimal point. The format '
'<code>Price:&nbsp;$&nbsp;{0:,.2f}</code> prints '
'"Price&nbsp;$&nbsp;" then displays the number with 2 digits '
'after the decimal point and thousands separated by commas.') + '</p>')
def accept(self):
col = unicode(self.column_name_box.text()).strip()
@ -247,9 +267,27 @@ class CreateCustomColumn(QDialog, Ui_QCreateCustomColumn):
if l[i] in l[i+1:]:
return self.simple_error('', _('The value "{0}" is in the '
'list more than once').format(l[i]))
display_dict = {'enum_values': l}
c = unicode(self.enum_colors.text())
if c:
c = [v.strip() for v in unicode(self.enum_colors.text()).split(',')]
else:
c = []
if len(c) != 0 and len(c) != len(l):
return self.simple_error('', _('The colors box must be empty or '
'contain the same number of items as the value box'))
for tc in c:
if tc not in QColor.colorNames():
return self.simple_error('',
_('The color {0} is unknown').format(tc))
display_dict = {'enum_values': l, 'enum_colors': c}
elif col_type == 'text' and is_multiple:
display_dict = {'is_names': self.is_names.isChecked()}
elif col_type in ['int', 'float']:
if unicode(self.number_format_box.text()).strip():
display_dict = {'number_format':unicode(self.number_format_box.text()).strip()}
else:
display_dict = {'number_format': None}
if col_type in ['text', 'composite', 'enumeration'] and not is_multiple:
display_dict['use_decorations'] = self.use_decorations.checkState()

View File

@ -171,6 +171,16 @@ Everything else will show nothing.</string>
</property>
</widget>
</item>
<item>
<widget class="QLineEdit" name="number_format_box">
<property name="sizePolicy">
<sizepolicy hsizetype="Maximum" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="date_format_default_label">
<property name="toolTip">
@ -181,6 +191,21 @@ Everything else will show nothing.</string>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="number_format_default_label">
<property name="toolTip">
<string>&lt;p&gt;The format specifier must begin with &lt;code&gt;{0:&lt;/code&gt;
and end with &lt;code&gt;}&lt;/code&gt; You can have text before and after the format specifier.
</string>
</property>
<property name="text">
<string>&lt;p&gt;Default: Not formatted. For format language details see &lt;a href="http://docs.python.org/library/string.html#format-string-syntax"&gt;the python documentation&lt;/a&gt;</string>
</property>
<property name="openExternalLinks">
<bool>true</bool>
</property>
</widget>
</item>
</layout>
</item>
<item row="4" column="0">
@ -193,6 +218,16 @@ Everything else will show nothing.</string>
</property>
</widget>
</item>
<item row="4" column="0">
<widget class="QLabel" name="number_format_label">
<property name="text">
<string>Format for &amp;numbers</string>
</property>
<property name="buddy">
<cstring>number_format_box</cstring>
</property>
</widget>
</item>
<item row="5" column="0">
<widget class="QLabel" name="composite_label">
<property name="text">
@ -304,8 +339,8 @@ Everything else will show nothing.</string>
</widget>
</item>
<item row="6" column="2">
<layout class="QHBoxLayout" name="horizontalLayout_2">
<item>
<layout class="QGridLayout" name="horizontalLayout_2">
<item row="0" column="0">
<widget class="QLineEdit" name="enum_box">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Fixed">
@ -320,13 +355,34 @@ four values, the first of them being the empty value.</string>
</property>
</widget>
</item>
<item>
<item row="0" column="1">
<widget class="QLabel" name="enum_default_label">
<property name="toolTip">
<string>The empty string is always the first value</string>
</property>
<property name="text">
<string>Default: (nothing)</string>
<string>Values</string>
</property>
</widget>
</item>
<item row="1" column="0">
<widget class="QLineEdit" name="enum_colors">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="toolTip">
<string>A list of color names to use when displaying an item. The
list must be empty or contain a color for each value.</string>
</property>
</widget>
</item>
<item row="1" column="1">
<widget class="QLabel" name="enum_colors_label">
<property name="text">
<string>Colors</string>
</property>
</widget>
</item>

View File

@ -76,7 +76,7 @@ class UserDefinedDevice(QDialog):
for i,d in enumerate(sorted(new_drives,
key=lambda x: after['drive_details'][x][0])):
if i == 0:
res += _('Windows main memory ID string') + ': ' + \
res += _('Windows main memory vendor string') + ': ' + \
after['drive_details'][d][1] + '\n'
res += _('Windows main memory ID string') + ': ' + \
after['drive_details'][d][2] + '\n'

View File

@ -5,12 +5,15 @@ __license__ = 'GPL v3'
__copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
from functools import partial
from PyQt4.Qt import (QApplication, QFont, QFontInfo, QFontDialog,
QAbstractListModel, Qt)
QAbstractListModel, Qt, QColor, QIcon, QToolButton, QComboBox)
from calibre.gui2.preferences import ConfigWidgetBase, test_widget, CommaSeparatedList
from calibre.gui2.preferences.look_feel_ui import Ui_Form
from calibre.gui2 import config, gprefs, qt_app
from calibre.gui2.dialogs.template_line_editor import TemplateLineEditor
from calibre.utils.localization import (available_translations,
get_language, get_lang)
from calibre.utils.config import prefs
@ -129,7 +132,7 @@ class ConfigWidget(ConfigWidgetBase, Ui_Form):
(_('Medium'), 'medium'), (_('Large'), 'large')]
r('toolbar_icon_size', gprefs, choices=choices)
choices = [(_('Automatic'), 'auto'), (_('Always'), 'always'),
choices = [(_('If there is enough room'), 'auto'), (_('Always'), 'always'),
(_('Never'), 'never')]
r('toolbar_text', gprefs, choices=choices)
@ -159,6 +162,118 @@ class ConfigWidget(ConfigWidgetBase, Ui_Form):
self.df_up_button.clicked.connect(self.move_df_up)
self.df_down_button.clicked.connect(self.move_df_down)
self.color_help_text.setText('<p>' +
_('Here you can specify coloring rules for columns shown in the '
'library view. Choose the column you wish to color, then '
'supply a template that specifies the color to use based on '
'the values in the column. There is a '
'<a href="http://manual.calibre-ebook.com/template_lang.html">'
'tutorial</a> on using templates.') +
'</p><p>' +
_('If you want to color a field based on contents of columns, '
'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 '
'template with the same wizard. This is by far the easiest '
'way to specify a template.') +
'</p><p>' +
_('If you manually construct a template, then the template must '
'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 '
'green using the template "green" (without the quotes). '
'To show the title in the color named in the custom column '
'#column, use "{#column}". To show the title in blue if the '
'custom column #column contains the value "foo", in red if the '
'column contains the value "bar", otherwise in black, use '
'<pre>{#column:switch(foo,blue,bar,red,black)}</pre>'
'To show the title in blue if the book has the exact tag '
'"Science Fiction", red if the book has the exact tag '
'"Mystery", or black if the book has neither tag, use'
"<pre>program: \n"
" t = field('tags'); \n"
" first_non_empty(\n"
" in_list(t, ',', '^Science Fiction$', 'blue', ''), \n"
" in_list(t, ',', '^Mystery$', 'red', 'black'))</pre>"
'To show the title in green if it has one format, blue if it '
'two formats, and red if more, use'
"<pre>program:cmp(count(field('formats'),','), 2, 'green', 'blue', 'red')</pre>") +
'</p><p>' +
_('You can access a multi-line template editor from the '
'context menu (right-click).') + '</p><p>' +
_('<b>Note:</b> if you want to color a "custom column with a fixed set '
'of values", it is often easier to specify the '
'colors in the column definition dialog. There you can '
'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.sort(key=sort_key)
choices.insert(0, '')
self.column_color_count = db.column_color_count+1
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):
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_template_'+str(i), db.prefs)
txt = db.prefs.get('column_color_template_'+str(i), None)
wtb.setEnabled(tpl.enable_wizard_button(txt))
ttb.setEnabled(not tpl.enable_wizard_button(txt) or not txt)
all_colors = [unicode(s) for s in list(QColor.colorNames())]
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):
ConfigWidgetBase.initialize(self)
font = gprefs['font']
@ -226,6 +341,12 @@ class ConfigWidget(ConfigWidgetBase, Ui_Form):
self.changed_signal.emit()
def commit(self, *args):
for i in range(1, self.column_color_count):
col = getattr(self, 'opt_column_color_name_'+str(i))
tpl = getattr(self, 'opt_column_color_template_'+str(i))
if not col.currentIndex() or not unicode(tpl.text()).strip():
col.setCurrentIndex(0)
tpl.setText('')
rr = ConfigWidgetBase.commit(self, *args)
if self.current_font != self.initial_font:
gprefs['font'] = (self.current_font[:4] if self.current_font else
@ -238,6 +359,7 @@ class ConfigWidget(ConfigWidgetBase, Ui_Form):
return rr
def refresh_gui(self, gui):
gui.library_view.model().set_color_templates()
self.update_font_display()
gui.tags_view.reread_collapse_parameters()
gui.library_view.refresh_book_details()

View File

@ -7,7 +7,7 @@
<x>0</x>
<y>0</y>
<width>717</width>
<height>390</height>
<height>519</height>
</rect>
</property>
<property name="windowTitle">
@ -407,6 +407,161 @@ then the tags will be displayed each on their own line.</string>
</item>
</layout>
</widget>
<widget class="QWidget" name="tab_5">
<attribute name="icon">
<iconset resource="../../../../resources/images.qrc">
<normaloff>:/images/format-fill-color.png</normaloff>:/images/format-fill-color.png</iconset>
</attribute>
<attribute name="title">
<string>Column Coloring</string>
</attribute>
<layout class="QGridLayout" name="column_color_layout">
<item row="0" column="0">
<widget class="QLabel" name="label">
<property name="text">
<string>Column to color</string>
</property>
</widget>
</item>
<item row="0" column="3">
<layout class="QHBoxLayout">
<item>
<widget class="QLabel" name="label">
<property name="text">
<string>Color selection template</string>
</property>
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Fixed">
<horstretch>10</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="label">
<property name="text">
<string>The template wizard is easiest to use</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="color_help_button">
<property name="text">
<string>Show/hide help text</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="colors_button">
<property name="text">
<string>Show/hide colors</string>
</property>
</widget>
</item>
</layout>
</item>
<item row="20" column="0">
<widget class="QLabel" name="colors_label">
<property name="text">
<string>Color names</string>
</property>
</widget>
</item>
<item row="21" column="0" colspan="8">
<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">
<size>
<width>0</width>
<height>200</height>
</size>
</property>
<property name="widgetResizable">
<bool>true</bool>
</property>
<property name="alignment">
<set>Qt::AlignLeft|Qt::AlignTop</set>
</property>
<widget class="QWidget" name="scrollAreaWidgetContents">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>687</width>
<height>194</height>
</rect>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QLabel" name="color_help_text">
<property name="wordWrap">
<bool>true</bool>
</property>
<property name="openExternalLinks">
<bool>true</bool>
</property>
</widget>
</item>
</layout>
</widget>
</widget>
</item>
<item row="40" column="0">
<spacer>
<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>
<width>0</width>
<height>0</height>
</size>
</property>
</spacer>
</item>
</layout>
</widget>
</widget>
</item>
</layout>
@ -417,6 +572,11 @@ then the tags will be displayed each on their own line.</string>
<extends>QLineEdit</extends>
<header>calibre/gui2/complete.h</header>
</customwidget>
<customwidget>
<class>TemplateLineEditor</class>
<extends>QLineEdit</extends>
<header>calibre/gui2/dialogs/template_line_editor.h</header>
</customwidget>
</customwidgets>
<resources>
<include location="../../../../resources/images.qrc"/>

View File

@ -7,12 +7,12 @@ __docformat__ = 'restructuredtext en'
import copy
from PyQt4.Qt import Qt, QLineEdit, QComboBox, SIGNAL, QListWidgetItem
from PyQt4.Qt import Qt, QComboBox, QListWidgetItem
from calibre.customize.ui import is_disabled
from calibre.gui2 import error_dialog, question_dialog
from calibre.gui2.device import device_name_for_plugboards
from calibre.gui2.dialogs.template_dialog import TemplateDialog
from calibre.gui2.dialogs.template_line_editor import TemplateLineEditor
from calibre.gui2.preferences import ConfigWidgetBase, test_widget
from calibre.gui2.preferences.plugboard_ui import Ui_Form
from calibre.customize.ui import metadata_writers, device_plugins
@ -24,26 +24,6 @@ from calibre.library.server.content import plugboard_content_server_value, \
from calibre.utils.formatter import validation_formatter
class LineEditWithTextBox(QLineEdit):
'''
Extend the context menu of a QLineEdit to include more actions.
'''
def contextMenuEvent(self, event):
menu = self.createStandardContextMenu()
menu.addSeparator()
action_open_editor = menu.addAction(_('Open Editor'))
self.connect(action_open_editor, SIGNAL('triggered()'), self.open_editor)
menu.exec_(event.globalPos())
def open_editor(self):
t = TemplateDialog(self, self.text())
if t.exec_():
self.setText(t.textbox.toPlainText())
class ConfigWidget(ConfigWidgetBase, Ui_Form):
def genesis(self, gui):
@ -107,7 +87,7 @@ class ConfigWidget(ConfigWidgetBase, Ui_Form):
self.source_widgets = []
self.dest_widgets = []
for i in range(0, len(self.dest_fields)-1):
w = LineEditWithTextBox(self)
w = TemplateLineEditor(self)
self.source_widgets.append(w)
self.fields_layout.addWidget(w, 5+i, 0, 1, 1)
w = QComboBox(self)

View File

@ -16,7 +16,7 @@ class AmazonDEKindleStore(AmazonKindleStore):
For comments on the implementation, please see amazon_plugin.py
'''
search_url = 'http://www.amazon.de/s/url=search-alias%3Ddigital-text&field-keywords='
search_url = 'http://www.amazon.de/s/?url=search-alias%3Ddigital-text&field-keywords='
details_url = 'http://amazon.de/dp/'
drm_search_text = u'Gleichzeitige Verwendung von Geräten'
drm_free_text = u'Keine Einschränkung'

View File

@ -8,7 +8,7 @@ __docformat__ = 'restructuredtext en'
import random
import re
import urllib2
import urllib
from contextlib import closing
from lxml import html
@ -22,7 +22,7 @@ from calibre.gui2.store.search_result import SearchResult
class AmazonKindleStore(StorePlugin):
search_url = 'http://www.amazon.com/s/url=search-alias%3Ddigital-text&field-keywords='
search_url = 'http://www.amazon.com/s/?url=search-alias%3Ddigital-text&field-keywords='
details_url = 'http://amazon.com/dp/'
drm_search_text = u'Simultaneous Device Usage'
drm_free_text = u'Unlimited'
@ -122,13 +122,27 @@ class AmazonKindleStore(StorePlugin):
open_url(QUrl(store_link))
def search(self, query, max_results=10, timeout=60):
url = self.search_url + urllib2.quote(query)
url = self.search_url + urllib.quote_plus(query)
br = browser()
counter = max_results
with closing(br.open(url, timeout=timeout)) as f:
doc = html.fromstring(f.read())
for data in doc.xpath('//div[@class="productData"]'):
# Amazon has two results pages.
is_shot = doc.xpath('boolean(//div[@id="shotgunMainResults"])')
# Horizontal grid of books.
if is_shot:
data_xpath = '//div[contains(@class, "result")]'
format_xpath = './/div[@class="productTitle"]/text()'
cover_xpath = './/div[@class="productTitle"]//img/@src'
# Vertical list of books.
else:
data_xpath = '//div[@class="productData"]'
format_xpath = './/span[@class="format"]/text()'
cover_xpath = '../div[@class="productImage"]/a/img/@src'
for data in doc.xpath(data_xpath):
if counter <= 0:
break
@ -136,14 +150,14 @@ class AmazonKindleStore(StorePlugin):
# put in results for non Kindle books (author pages). Se we need
# to explicitly check if the item is a Kindle book and ignore it
# if it isn't.
type = ''.join(data.xpath('//span[@class="format"]/text()'))
if 'kindle' not in type.lower():
format = ''.join(data.xpath(format_xpath))
if 'kindle' not in format.lower():
continue
# We must have an asin otherwise we can't easily reference the
# book later.
asin_href = None
asin_a = data.xpath('div[@class="productTitle"]/a[1]')
asin_a = data.xpath('.//div[@class="productTitle"]/a[1]')
if asin_a:
asin_href = asin_a[0].get('href', '')
m = re.search(r'/dp/(?P<asin>.+?)(/|$)', asin_href)
@ -154,28 +168,21 @@ class AmazonKindleStore(StorePlugin):
else:
continue
cover_url = ''
if asin_href:
cover_img = data.xpath('//div[@class="productImage"]/a[@href="%s"]/img/@src' % asin_href)
if cover_img:
cover_url = cover_img[0]
parts = cover_url.split('/')
bn = parts[-1]
f, _, ext = bn.rpartition('.')
if '_' in f:
bn = f.partition('_')[0]+'_SL160_.'+ext
parts[-1] = bn
cover_url = '/'.join(parts)
cover_url = ''.join(data.xpath(cover_xpath))
title = ''.join(data.xpath('div[@class="productTitle"]/a/text()'))
author = ''.join(data.xpath('div[@class="productTitle"]/span[@class="ptBrand"]/text()'))
author = author.split('by')[-1]
price = ''.join(data.xpath('div[@class="newPrice"]/span/text()'))
title = ''.join(data.xpath('.//div[@class="productTitle"]/a/text()'))
price = ''.join(data.xpath('.//div[@class="newPrice"]/span/text()'))
if is_shot:
author = format.split(' by ')[-1]
else:
author = ''.join(data.xpath('.//div[@class="productTitle"]/span[@class="ptBrand"]/text()'))
author = author.split(' by ')[-1]
counter -= 1
s = SearchResult()
s.cover_url = cover_url
s.cover_url = cover_url.strip()
s.title = title.strip()
s.author = author.strip()
s.price = price.strip()

View File

@ -6,18 +6,24 @@ __license__ = 'GPL 3'
__copyright__ = '2011, John Schember <john@nachtimwald.com>'
__docformat__ = 'restructuredtext en'
import urllib
from contextlib import closing
from lxml import html
from PyQt4.Qt import QUrl
from calibre import browser
from calibre.gui2 import open_url
from calibre.gui2.store.amazon_plugin import AmazonKindleStore
from calibre.gui2.store.search_result import SearchResult
class AmazonUKKindleStore(AmazonKindleStore):
'''
For comments on the implementation, please see amazon_plugin.py
'''
search_url = 'http://www.amazon.co.uk/s/url=search-alias%3Ddigital-text&field-keywords='
search_url = 'http://www.amazon.co.uk/s/?url=search-alias%3Ddigital-text&field-keywords='
details_url = 'http://amazon.co.uk/dp/'
def open(self, parent=None, detail_item=None, external=False):
@ -28,3 +34,81 @@ class AmazonUKKindleStore(AmazonKindleStore):
aff_id['asin'] = detail_item
store_link = 'http://www.amazon.co.uk/gp/redirect.html?ie=UTF8&location=http://www.amazon.co.uk/dp/%(asin)s&tag=%(tag)s&linkCode=ur2&camp=1634&creative=6738' % aff_id
open_url(QUrl(store_link))
def search(self, query, max_results=10, timeout=60):
url = self.search_url + urllib.quote_plus(query)
br = browser()
counter = max_results
with closing(br.open(url, timeout=timeout)) as f:
doc = html.fromstring(f.read())
# Amazon has two results pages.
is_shot = doc.xpath('boolean(//div[@id="shotgunMainResults"])')
# Horizontal grid of books.
if is_shot:
data_xpath = '//div[contains(@class, "result")]'
cover_xpath = './/div[@class="productTitle"]//img/@src'
# Vertical list of books.
else:
data_xpath = '//div[contains(@class, "product")]'
cover_xpath = './div[@class="productImage"]/a/img/@src'
for data in doc.xpath(data_xpath):
if counter <= 0:
break
# We must have an asin otherwise we can't easily reference the
# book later.
asin = ''.join(data.xpath('./@name'))
if not asin:
continue
cover_url = ''.join(data.xpath(cover_xpath))
title = ''.join(data.xpath('.//div[@class="productTitle"]/a/text()'))
price = ''.join(data.xpath('.//div[@class="newPrice"]/span/text()'))
counter -= 1
s = SearchResult()
s.cover_url = cover_url.strip()
s.title = title.strip()
s.price = price.strip()
s.detail_item = asin.strip()
s.formats = 'Kindle'
if is_shot:
# Amazon UK does not include the author on the grid layout
s.author = ''
self.get_details(s, timeout)
else:
author = ''.join(data.xpath('.//div[@class="productTitle"]/span[@class="ptBrand"]/text()'))
s.author = author.split(' by ')[-1].strip()
yield s
def get_details(self, search_result, timeout):
# We might already have been called.
if search_result.drm:
return
url = self.details_url
br = browser()
with closing(br.open(url + search_result.detail_item, timeout=timeout)) as nf:
idata = html.fromstring(nf.read())
if not search_result.author:
search_result.author = ''.join(idata.xpath('//div[@class="buying" and contains(., "Author")]/a/text()'))
if idata.xpath('boolean(//div[@class="content"]//li/b[contains(text(), "' +
self.drm_search_text + '")])'):
if idata.xpath('boolean(//div[@class="content"]//li[contains(., "' +
self.drm_free_text + '") and contains(b, "' +
self.drm_search_text + '")])'):
search_result.drm = SearchResult.DRM_UNLOCKED
else:
search_result.drm = SearchResult.DRM_UNKNOWN
else:
search_result.drm = SearchResult.DRM_LOCKED
return True

View File

@ -0,0 +1,135 @@
# -*- coding: utf-8 -*-
from __future__ import (unicode_literals, division, absolute_import, print_function)
__license__ = 'GPL 3'
__copyright__ = '2011, John Schember <john@nachtimwald.com>'
__docformat__ = 'restructuredtext en'
import re
from PyQt4.Qt import (QDialog, QDialogButtonBox)
from calibre.gui2.store.config.chooser.adv_search_builder_ui import Ui_Dialog
from calibre.library.caches import CONTAINS_MATCH, EQUALS_MATCH
class AdvSearchBuilderDialog(QDialog, Ui_Dialog):
def __init__(self, parent):
QDialog.__init__(self, parent)
self.setupUi(self)
self.buttonBox.accepted.connect(self.advanced_search_button_pushed)
self.tab_2_button_box.accepted.connect(self.accept)
self.tab_2_button_box.rejected.connect(self.reject)
self.clear_button.clicked.connect(self.clear_button_pushed)
self.adv_search_used = False
self.mc = ''
self.tabWidget.setCurrentIndex(0)
self.tabWidget.currentChanged[int].connect(self.tab_changed)
self.tab_changed(0)
def tab_changed(self, idx):
if idx == 1:
self.tab_2_button_box.button(QDialogButtonBox.Ok).setDefault(True)
else:
self.buttonBox.button(QDialogButtonBox.Ok).setDefault(True)
def advanced_search_button_pushed(self):
self.adv_search_used = True
self.accept()
def clear_button_pushed(self):
self.name_box.setText('')
self.description_box.setText('')
self.headquarters_box.setText('')
self.format_box.setText('')
self.enabled_combo.setCurrentIndex(0)
self.drm_combo.setCurrentIndex(0)
self.affiliate_combo.setCurrentIndex(0)
def tokens(self, raw):
phrases = re.findall(r'\s*".*?"\s*', raw)
for f in phrases:
raw = raw.replace(f, ' ')
phrases = [t.strip('" ') for t in phrases]
return ['"' + self.mc + t + '"' for t in phrases + [r.strip() for r in raw.split()]]
def search_string(self):
if self.adv_search_used:
return self.adv_search_string()
else:
return self.box_search_string()
def adv_search_string(self):
mk = self.matchkind.currentIndex()
if mk == CONTAINS_MATCH:
self.mc = ''
elif mk == EQUALS_MATCH:
self.mc = '='
else:
self.mc = '~'
all, any, phrase, none = map(lambda x: unicode(x.text()),
(self.all, self.any, self.phrase, self.none))
all, any, none = map(self.tokens, (all, any, none))
phrase = phrase.strip()
all = ' and '.join(all)
any = ' or '.join(any)
none = ' and not '.join(none)
ans = ''
if phrase:
ans += '"%s"'%phrase
if all:
ans += (' and ' if ans else '') + all
if none:
ans += (' and not ' if ans else 'not ') + none
if any:
ans += (' or ' if ans else '') + any
return ans
def token(self):
txt = unicode(self.text.text()).strip()
if txt:
if self.negate.isChecked():
txt = '!'+txt
tok = self.FIELDS[unicode(self.field.currentText())]+txt
if re.search(r'\s', tok):
tok = '"%s"'%tok
return tok
def box_search_string(self):
mk = self.matchkind.currentIndex()
if mk == CONTAINS_MATCH:
self.mc = ''
elif mk == EQUALS_MATCH:
self.mc = '='
else:
self.mc = '~'
ans = []
self.box_last_values = {}
name = unicode(self.name_box.text()).strip()
if name:
ans.append('name:"' + self.mc + name + '"')
description = unicode(self.description_box.text()).strip()
if description:
ans.append('description:"' + self.mc + description + '"')
headquarters = unicode(self.headquarters_box.text()).strip()
if headquarters:
ans.append('headquarters:"' + self.mc + headquarters + '"')
format = unicode(self.format_box.text()).strip()
if format:
ans.append('format:"' + self.mc + format + '"')
enabled = unicode(self.enabled_combo.currentText()).strip()
if enabled:
ans.append('enabled:' + enabled)
drm = unicode(self.drm_combo.currentText()).strip()
if drm:
ans.append('drm:' + drm)
affiliate = unicode(self.affiliate_combo.currentText()).strip()
if affiliate:
ans.append('affiliate:' + affiliate)
if ans:
return ' and '.join(ans)
return ''

View File

@ -0,0 +1,442 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>Dialog</class>
<widget class="QDialog" name="Dialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>752</width>
<height>472</height>
</rect>
</property>
<property name="windowTitle">
<string>Advanced Search</string>
</property>
<property name="windowIcon">
<iconset>
<normaloff>:/images/search.png</normaloff>:/images/search.png</iconset>
</property>
<layout class="QGridLayout" name="gridLayout_2">
<item row="0" column="0">
<widget class="QLabel" name="label_5">
<property name="text">
<string>&amp;What kind of match to use:</string>
</property>
<property name="buddy">
<cstring>matchkind</cstring>
</property>
</widget>
</item>
<item row="0" column="1">
<widget class="QComboBox" name="matchkind">
<item>
<property name="text">
<string>Contains: the word or phrase matches anywhere in the metadata field</string>
</property>
</item>
<item>
<property name="text">
<string>Equals: the word or phrase must match the entire metadata field</string>
</property>
</item>
<item>
<property name="text">
<string>Regular expression: the expression must match anywhere in the metadata field</string>
</property>
</item>
</widget>
</item>
<item row="2" column="0" colspan="2">
<widget class="QTabWidget" name="tabWidget">
<property name="currentIndex">
<number>0</number>
</property>
<widget class="QWidget" name="tab">
<attribute name="title">
<string>A&amp;dvanced Search</string>
</attribute>
<layout class="QGridLayout" name="gridLayout_3">
<item row="0" column="0">
<widget class="QGroupBox" name="groupBox">
<property name="title">
<string>Find entries that have...</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<widget class="QLabel" name="label">
<property name="text">
<string>&amp;All these words:</string>
</property>
<property name="buddy">
<cstring>all</cstring>
</property>
</widget>
</item>
<item>
<widget class="QLineEdit" name="all"/>
</item>
</layout>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout_2">
<item>
<widget class="QLabel" name="label_2">
<property name="text">
<string>This exact &amp;phrase:</string>
</property>
<property name="buddy">
<cstring>all</cstring>
</property>
</widget>
</item>
<item>
<widget class="QLineEdit" name="phrase"/>
</item>
</layout>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout_3">
<item>
<widget class="QLabel" name="label_3">
<property name="text">
<string>&amp;One or more of these words:</string>
</property>
<property name="buddy">
<cstring>all</cstring>
</property>
</widget>
</item>
<item>
<widget class="QLineEdit" name="any"/>
</item>
</layout>
</item>
</layout>
</widget>
</item>
<item row="1" column="0">
<widget class="QGroupBox" name="groupBox_2">
<property name="title">
<string>But dont show entries that have...</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout_2">
<item>
<layout class="QHBoxLayout" name="horizontalLayout_4">
<item>
<widget class="QLabel" name="label_4">
<property name="text">
<string>Any of these &amp;unwanted words:</string>
</property>
<property name="buddy">
<cstring>all</cstring>
</property>
</widget>
</item>
<item>
<widget class="QLineEdit" name="none"/>
</item>
</layout>
</item>
<item>
<widget class="QLabel" name="label_6">
<property name="maximumSize">
<size>
<width>16777215</width>
<height>30</height>
</size>
</property>
<property name="text">
<string>See the &lt;a href=&quot;http://manual.calibre-ebook.com/gui.html#the-search-interface&quot;&gt;User Manual&lt;/a&gt; for more help</string>
</property>
<property name="openExternalLinks">
<bool>true</bool>
</property>
</widget>
</item>
</layout>
</widget>
</item>
<item row="2" column="0">
<spacer name="verticalSpacer_2">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>40</height>
</size>
</property>
</spacer>
</item>
<item row="3" column="0">
<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>
</layout>
</widget>
<widget class="QWidget" name="tab_2">
<attribute name="title">
<string>Nam&amp;e/Description ...</string>
</attribute>
<layout class="QGridLayout" name="gridLayout">
<item row="1" column="0">
<widget class="QLabel" name="label_7">
<property name="text">
<string>&amp;Name:</string>
</property>
<property name="buddy">
<cstring>name_box</cstring>
</property>
</widget>
</item>
<item row="1" column="1">
<widget class="EnLineEdit" name="name_box">
<property name="toolTip">
<string>Enter the title.</string>
</property>
</widget>
</item>
<item row="2" column="0">
<widget class="QLabel" name="label_8">
<property name="text">
<string>&amp;Description:</string>
</property>
<property name="buddy">
<cstring>description_box</cstring>
</property>
</widget>
</item>
<item row="3" column="0">
<widget class="QLabel" name="price_label">
<property name="text">
<string>&amp;Headquarters:</string>
</property>
<property name="buddy">
<cstring>headquarters_box</cstring>
</property>
</widget>
</item>
<item row="9" column="0" colspan="2">
<layout class="QHBoxLayout" name="horizontalLayout_6">
<item>
<widget class="QPushButton" name="clear_button">
<property name="text">
<string>&amp;Clear</string>
</property>
</widget>
</item>
<item>
<widget class="QDialogButtonBox" name="tab_2_button_box">
<property name="standardButtons">
<set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set>
</property>
</widget>
</item>
</layout>
</item>
<item row="8" column="1">
<spacer name="verticalSpacer">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>40</height>
</size>
</property>
</spacer>
</item>
<item row="0" column="0" colspan="2">
<widget class="QLabel" name="label_11">
<property name="text">
<string>Search only in specific fields:</string>
</property>
</widget>
</item>
<item row="2" column="1">
<widget class="EnLineEdit" name="description_box"/>
</item>
<item row="4" column="1">
<widget class="QLineEdit" name="format_box"/>
</item>
<item row="4" column="0">
<widget class="QLabel" name="label_10">
<property name="text">
<string>&amp;Format:</string>
</property>
<property name="buddy">
<cstring>format_box</cstring>
</property>
</widget>
</item>
<item row="3" column="1">
<widget class="EnLineEdit" name="headquarters_box"/>
</item>
<item row="5" column="0">
<widget class="QLabel" name="label_9">
<property name="text">
<string>Enabled:</string>
</property>
</widget>
</item>
<item row="6" column="0">
<widget class="QLabel" name="label_12">
<property name="text">
<string>DRM:</string>
</property>
</widget>
</item>
<item row="5" column="1">
<widget class="QComboBox" name="enabled_combo">
<item>
<property name="text">
<string/>
</property>
</item>
<item>
<property name="text">
<string>true</string>
</property>
</item>
<item>
<property name="text">
<string>false</string>
</property>
</item>
</widget>
</item>
<item row="6" column="1">
<widget class="QComboBox" name="drm_combo">
<item>
<property name="text">
<string/>
</property>
</item>
<item>
<property name="text">
<string>true</string>
</property>
</item>
<item>
<property name="text">
<string>false</string>
</property>
</item>
</widget>
</item>
<item row="7" column="0">
<widget class="QLabel" name="label_13">
<property name="text">
<string>Affiliate:</string>
</property>
</widget>
</item>
<item row="7" column="1">
<widget class="QComboBox" name="affiliate_combo">
<item>
<property name="text">
<string/>
</property>
</item>
<item>
<property name="text">
<string>true</string>
</property>
</item>
<item>
<property name="text">
<string>false</string>
</property>
</item>
</widget>
</item>
</layout>
</widget>
</widget>
</item>
<item row="1" column="1">
<spacer name="verticalSpacer_3">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>40</height>
</size>
</property>
</spacer>
</item>
</layout>
</widget>
<customwidgets>
<customwidget>
<class>EnLineEdit</class>
<extends>QLineEdit</extends>
<header>widgets.h</header>
</customwidget>
</customwidgets>
<tabstops>
<tabstop>all</tabstop>
<tabstop>phrase</tabstop>
<tabstop>any</tabstop>
<tabstop>none</tabstop>
<tabstop>buttonBox</tabstop>
<tabstop>name_box</tabstop>
<tabstop>description_box</tabstop>
<tabstop>headquarters_box</tabstop>
<tabstop>format_box</tabstop>
<tabstop>clear_button</tabstop>
<tabstop>tab_2_button_box</tabstop>
<tabstop>tabWidget</tabstop>
<tabstop>matchkind</tabstop>
</tabstops>
<resources>
<include location="../../../../resources/images.qrc"/>
</resources>
<connections>
<connection>
<sender>buttonBox</sender>
<signal>accepted()</signal>
<receiver>Dialog</receiver>
<slot>accept()</slot>
<hints>
<hint type="sourcelabel">
<x>248</x>
<y>254</y>
</hint>
<hint type="destinationlabel">
<x>157</x>
<y>274</y>
</hint>
</hints>
</connection>
<connection>
<sender>buttonBox</sender>
<signal>rejected()</signal>
<receiver>Dialog</receiver>
<slot>reject()</slot>
<hints>
<hint type="sourcelabel">
<x>316</x>
<y>260</y>
</hint>
<hint type="destinationlabel">
<x>286</x>
<y>274</y>
</hint>
</hints>
</connection>
</connections>
</ui>

View File

@ -0,0 +1,28 @@
# -*- coding: utf-8 -*-
from __future__ import (unicode_literals, division, absolute_import, print_function)
__license__ = 'GPL 3'
__copyright__ = '2011, John Schember <john@nachtimwald.com>'
__docformat__ = 'restructuredtext en'
from PyQt4.Qt import (QDialog, QDialogButtonBox, QVBoxLayout)
from calibre.gui2.store.config.chooser.chooser_widget import StoreChooserWidget
class StoreChooserDialog(QDialog):
def __init__(self, parent):
QDialog.__init__(self, parent)
self.setWindowTitle(_('Choose stores'))
button_box = QDialogButtonBox(QDialogButtonBox.Close)
button_box.accepted.connect(self.accept)
button_box.rejected.connect(self.reject)
v = QVBoxLayout(self)
self.config_widget = StoreChooserWidget()
v.addWidget(self.config_widget)
v.addWidget(button_box)
self.resize(800, 600)

View File

@ -0,0 +1,37 @@
# -*- coding: utf-8 -*-
from __future__ import (unicode_literals, division, absolute_import, print_function)
__license__ = 'GPL 3'
__copyright__ = '2011, John Schember <john@nachtimwald.com>'
__docformat__ = 'restructuredtext en'
from PyQt4.Qt import (QWidget, QIcon, QDialog)
from calibre.gui2.store.config.chooser.adv_search_builder import AdvSearchBuilderDialog
from calibre.gui2.store.config.chooser.chooser_widget_ui import Ui_Form
class StoreChooserWidget(QWidget, Ui_Form):
def __init__(self):
QWidget.__init__(self)
self.setupUi(self)
self.query.initialize('store_config_chooser_query')
self.adv_search_builder.setIcon(QIcon(I('search.png')))
self.search.clicked.connect(self.do_search)
self.adv_search_builder.clicked.connect(self.build_adv_search)
self.enable_all.clicked.connect(self.results_view.model().enable_all)
self.enable_none.clicked.connect(self.results_view.model().enable_none)
self.enable_invert.clicked.connect(self.results_view.model().enable_invert)
self.results_view.activated.connect(self.results_view.model().toggle_plugin)
def do_search(self):
self.results_view.model().search(unicode(self.query.text()))
def build_adv_search(self):
adv = AdvSearchBuilderDialog(self)
if adv.exec_() == QDialog.Accepted:
self.query.setText(adv.search_string())

View File

@ -0,0 +1,144 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>Form</class>
<widget class="QWidget" name="Form">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>610</width>
<height>553</height>
</rect>
</property>
<property name="windowTitle">
<string>Form</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<widget class="QLabel" name="label">
<property name="text">
<string>Query:</string>
</property>
</widget>
</item>
<item>
<widget class="QToolButton" name="adv_search_builder">
<property name="text">
<string>...</string>
</property>
</widget>
</item>
<item>
<widget class="HistoryLineEdit" name="query">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="search">
<property name="text">
<string>Search</string>
</property>
</widget>
</item>
</layout>
</item>
<item>
<widget class="ResultsView" name="results_view">
<property name="alternatingRowColors">
<bool>true</bool>
</property>
<property name="selectionMode">
<enum>QAbstractItemView::SingleSelection</enum>
</property>
<property name="selectionBehavior">
<enum>QAbstractItemView::SelectRows</enum>
</property>
<property name="rootIsDecorated">
<bool>false</bool>
</property>
<property name="uniformRowHeights">
<bool>true</bool>
</property>
<property name="itemsExpandable">
<bool>false</bool>
</property>
<property name="sortingEnabled">
<bool>true</bool>
</property>
<property name="expandsOnDoubleClick">
<bool>false</bool>
</property>
<attribute name="headerStretchLastSection">
<bool>false</bool>
</attribute>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout_2">
<item>
<widget class="QLabel" name="label_2">
<property name="text">
<string>Enable</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="enable_all">
<property name="text">
<string>All</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="enable_none">
<property name="text">
<string>None</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="enable_invert">
<property name="text">
<string>Invert</string>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
</layout>
</item>
</layout>
</widget>
<customwidgets>
<customwidget>
<class>ResultsView</class>
<extends>QTreeView</extends>
<header>results_view.h</header>
</customwidget>
<customwidget>
<class>HistoryLineEdit</class>
<extends>QLineEdit</extends>
<header>widgets.h</header>
</customwidget>
</customwidgets>
<resources/>
<connections/>
</ui>

View File

@ -0,0 +1,285 @@
# -*- coding: utf-8 -*-
from __future__ import (unicode_literals, division, absolute_import, print_function)
__license__ = 'GPL 3'
__copyright__ = '2011, John Schember <john@nachtimwald.com>'
__docformat__ = 'restructuredtext en'
from PyQt4.Qt import (Qt, QAbstractItemModel, QIcon, QVariant, QModelIndex, QSize)
from calibre.gui2 import NONE
from calibre.customize.ui import is_disabled, disable_plugin, enable_plugin
from calibre.library.caches import _match, CONTAINS_MATCH, EQUALS_MATCH, \
REGEXP_MATCH
from calibre.utils.icu import sort_key
from calibre.utils.search_query_parser import SearchQueryParser
class Matches(QAbstractItemModel):
HEADERS = [_('Enabled'), _('Name'), _('No DRM'), _('Headquarters'), _('Affiliate'), _('Formats')]
HTML_COLS = [1]
def __init__(self, plugins):
QAbstractItemModel.__init__(self)
self.NO_DRM_ICON = QIcon(I('ok.png'))
self.DONATE_ICON = QIcon()
self.DONATE_ICON.addFile(I('donate.png'), QSize(16, 16))
self.all_matches = plugins
self.matches = plugins
self.filter = ''
self.search_filter = SearchFilter(self.all_matches)
self.sort_col = 1
self.sort_order = Qt.AscendingOrder
def get_plugin(self, index):
row = index.row()
if row < len(self.matches):
return self.matches[row]
else:
return None
def search(self, filter):
self.filter = filter.strip()
if not self.filter:
self.matches = self.all_matches
else:
try:
self.matches = list(self.search_filter.parse(self.filter))
except:
self.matches = self.all_matches
self.layoutChanged.emit()
self.sort(self.sort_col, self.sort_order)
def enable_all(self):
for i in xrange(len(self.matches)):
index = self.createIndex(i, 0)
data = QVariant(True)
self.setData(index, data, Qt.CheckStateRole)
def enable_none(self):
for i in xrange(len(self.matches)):
index = self.createIndex(i, 0)
data = QVariant(False)
self.setData(index, data, Qt.CheckStateRole)
def enable_invert(self):
for i in xrange(len(self.matches)):
self.toggle_plugin(self.createIndex(i, 0))
def toggle_plugin(self, index):
new_index = self.createIndex(index.row(), 0)
data = QVariant(is_disabled(self.get_plugin(index)))
self.setData(new_index, data, Qt.CheckStateRole)
def index(self, row, column, parent=QModelIndex()):
return self.createIndex(row, column)
def parent(self, index):
if not index.isValid() or index.internalId() == 0:
return QModelIndex()
return self.createIndex(0, 0)
def rowCount(self, *args):
return len(self.matches)
def columnCount(self, *args):
return len(self.HEADERS)
def headerData(self, section, orientation, role):
if role != Qt.DisplayRole:
return NONE
text = ''
if orientation == Qt.Horizontal:
if section < len(self.HEADERS):
text = self.HEADERS[section]
return QVariant(text)
else:
return QVariant(section+1)
def data(self, index, role):
row, col = index.row(), index.column()
result = self.matches[row]
if role in (Qt.DisplayRole, Qt.EditRole):
if col == 1:
return QVariant('<b>%s</b><br><i>%s</i>' % (result.name, result.description))
elif col == 3:
return QVariant(result.headquarters)
elif col == 5:
return QVariant(', '.join(result.formats).upper())
elif role == Qt.DecorationRole:
if col == 2:
if result.drm_free_only:
return QVariant(self.NO_DRM_ICON)
if col == 4:
if result.affiliate:
return QVariant(self.DONATE_ICON)
elif role == Qt.CheckStateRole:
if col == 0:
if is_disabled(result):
return Qt.Unchecked
return Qt.Checked
elif role == Qt.ToolTipRole:
if col == 0:
if is_disabled(result):
return QVariant('<p>' + _('This store is currently diabled and cannot be used in other parts of calibre.') + '</p>')
else:
return QVariant('<p>' + _('This store is currently enabled and can be used in other parts of calibre.') + '</p>')
elif col == 1:
return QVariant('<p>%s</p>' % result.description)
elif col == 2:
if result.drm_free_only:
return QVariant('<p>' + _('This store only distributes ebooks with DRM.') + '</p>')
else:
return QVariant('<p>' + _('This store distributes ebooks with DRM. It may have some titles without DRM, but you will need to check on a per title basis.') + '</p>')
elif col == 3:
return QVariant('<p>' + _('This store is headquartered in %s. This is a good indication of what market the store caters to. However, this does not necessarily mean that the store is limited to that market only.') % result.headquarters + '</p>')
elif col == 4:
if result.affiliate:
return QVariant('<p>' + _('Buying from this store supports the calibre developer: %s.') % result.author + '</p>')
elif col == 5:
return QVariant('<p>' + _('This store distributes ebooks in the following formats: %s') % ', '.join(result.formats) + '</p>')
return NONE
def setData(self, index, data, role):
if not index.isValid():
return False
row, col = index.row(), index.column()
if col == 0:
if data.toBool():
enable_plugin(self.get_plugin(index))
else:
disable_plugin(self.get_plugin(index))
self.dataChanged.emit(self.index(index.row(), 0), self.index(index.row(), self.columnCount() - 1))
return True
def flags(self, index):
if index.column() == 0:
return QAbstractItemModel.flags(self, index) | Qt.ItemIsUserCheckable
return QAbstractItemModel.flags(self, index)
def data_as_text(self, match, col):
text = ''
if col == 0:
text = 'b' if is_disabled(match) else 'a'
elif col == 1:
text = match.name
elif col == 2:
text = 'a' if getattr(match, 'drm_free_only', True) else 'b'
elif col == 3:
text = getattr(match, 'headquarters', '')
elif col == 4:
text = 'a' if getattr(match, 'affiliate', False) else 'b'
return text
def sort(self, col, order, reset=True):
self.sort_col = col
self.sort_order = order
if not self.matches:
return
descending = order == Qt.DescendingOrder
self.matches.sort(None,
lambda x: sort_key(unicode(self.data_as_text(x, col))),
descending)
if reset:
self.reset()
class SearchFilter(SearchQueryParser):
USABLE_LOCATIONS = [
'all',
'affiliate',
'description',
'drm',
'enabled',
'format',
'formats',
'headquarters',
'name',
]
def __init__(self, all_plugins=[]):
SearchQueryParser.__init__(self, locations=self.USABLE_LOCATIONS)
self.srs = set(all_plugins)
def universal_set(self):
return self.srs
def get_matches(self, location, query):
location = location.lower().strip()
if location == 'formats':
location = 'format'
matchkind = CONTAINS_MATCH
if len(query) > 1:
if query.startswith('\\'):
query = query[1:]
elif query.startswith('='):
matchkind = EQUALS_MATCH
query = query[1:]
elif query.startswith('~'):
matchkind = REGEXP_MATCH
query = query[1:]
if matchkind != REGEXP_MATCH: ### leave case in regexps because it can be significant e.g. \S \W \D
query = query.lower()
if location not in self.USABLE_LOCATIONS:
return set([])
matches = set([])
all_locs = set(self.USABLE_LOCATIONS) - set(['all'])
locations = all_locs if location == 'all' else [location]
q = {
'affiliate': lambda x: x.affiliate,
'description': lambda x: x.description.lower(),
'drm': lambda x: not x.drm_free_only,
'enabled': lambda x: not is_disabled(x),
'format': lambda x: ','.join(x.formats).lower(),
'headquarters': lambda x: x.headquarters.lower(),
'name': lambda x : x.name.lower(),
}
q['formats'] = q['format']
for sr in self.srs:
for locvalue in locations:
accessor = q[locvalue]
if query == 'true':
if locvalue in ('affiliate', 'drm', 'enabled'):
if accessor(sr) == True:
matches.add(sr)
elif accessor(sr) is not None:
matches.add(sr)
continue
if query == 'false':
if locvalue in ('affiliate', 'drm', 'enabled'):
if accessor(sr) == False:
matches.add(sr)
elif accessor(sr) is None:
matches.add(sr)
continue
# this is bool, so can't match below
if locvalue in ('affiliate', 'drm', 'enabled'):
continue
try:
### Can't separate authors because comma is used for name sep and author sep
### Exact match might not get what you want. For that reason, turn author
### exactmatch searches into contains searches.
if locvalue == 'name' and matchkind == EQUALS_MATCH:
m = CONTAINS_MATCH
else:
m = matchkind
if locvalue == 'format':
vals = accessor(sr).split(',')
else:
vals = [accessor(sr)]
if _match(query, vals, m):
matches.add(sr)
break
except ValueError: # Unicode errors
import traceback
traceback.print_exc()
return matches

View File

@ -0,0 +1,53 @@
# -*- coding: utf-8 -*-
from __future__ import (unicode_literals, division, absolute_import, print_function)
__license__ = 'GPL 3'
__copyright__ = '2011, John Schember <john@nachtimwald.com>'
__docformat__ = 'restructuredtext en'
from functools import partial
from PyQt4.Qt import (Qt, QTreeView, QSize, QMenu)
from calibre.customize.ui import store_plugins
from calibre.gui2.metadata.single_download import RichTextDelegate
from calibre.gui2.store.config.chooser.models import Matches
class ResultsView(QTreeView):
def __init__(self, *args):
QTreeView.__init__(self,*args)
self._model = Matches([p for p in store_plugins()])
self.setModel(self._model)
self.setIconSize(QSize(24, 24))
self.rt_delegate = RichTextDelegate(self)
for i in self._model.HTML_COLS:
self.setItemDelegateForColumn(i, self.rt_delegate)
for i in xrange(self._model.columnCount()):
self.resizeColumnToContents(i)
self.model().sort(1, Qt.AscendingOrder)
self.header().setSortIndicator(self.model().sort_col, self.model().sort_order)
def contextMenuEvent(self, event):
index = self.indexAt(event.pos())
if not index.isValid():
return
plugin = self.model().get_plugin(index)
menu = QMenu()
ca = menu.addAction(_('Configure...'), partial(self.configure_plugin, plugin))
if not plugin.is_customizable():
ca.setEnabled(False)
menu.exec_(event.globalPos())
def configure_plugin(self, plugin):
plugin.do_user_config(self)

View File

@ -0,0 +1,45 @@
# -*- coding: utf-8 -*-
from __future__ import (unicode_literals, division, absolute_import, print_function)
__license__ = 'GPL 3'
__copyright__ = '2011, John Schember <john@nachtimwald.com>'
__docformat__ = 'restructuredtext en'
from PyQt4.Qt import QWidget
from calibre.gui2 import JSONConfig
from calibre.gui2.store.config.search.search_widget_ui import Ui_Form
class StoreConfigWidget(QWidget, Ui_Form):
def __init__(self, config=None):
QWidget.__init__(self)
self.setupUi(self)
self.config = JSONConfig('store/search') if not config else config
# These default values should be the same as in
# calibre.gui2.store.search.search:SearchDialog.load_settings
# Seconds
self.opt_timeout.setValue(self.config.get('timeout', 75))
self.opt_hang_time.setValue(self.config.get('hang_time', 75))
self.opt_max_results.setValue(self.config.get('max_results', 10))
self.opt_open_external.setChecked(self.config.get('open_external', True))
# Number of threads to run for each type of operation
self.opt_search_thread_count.setValue(self.config.get('search_thread_count', 4))
self.opt_cache_thread_count.setValue(self.config.get('cache_thread_count', 2))
self.opt_cover_thread_count.setValue(self.config.get('cover_thread_count', 2))
self.opt_details_thread_count.setValue(self.config.get('details_thread_count', 4))
def save_settings(self):
self.config['timeout'] = self.opt_timeout.value()
self.config['hang_time'] = self.opt_hang_time.value()
self.config['max_results'] = self.opt_max_results.value()
self.config['open_external'] = self.opt_open_external.isChecked()
self.config['search_thread_count'] = self.opt_search_thread_count.value()
self.config['cache_thread_count'] = self.opt_cache_thread_count.value()
self.config['cover_thread_count'] = self.opt_cover_thread_count.value()
self.config['details_thread_count'] = self.opt_details_thread_count.value()

View File

@ -0,0 +1,162 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>Form</class>
<widget class="QWidget" name="Form">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>465</width>
<height>396</height>
</rect>
</property>
<property name="windowTitle">
<string>Form</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QGroupBox" name="groupBox">
<property name="title">
<string>Time</string>
</property>
<layout class="QFormLayout" name="formLayout">
<item row="0" column="0">
<widget class="QLabel" name="label">
<property name="text">
<string>Number of seconds to wait for a store to respond</string>
</property>
</widget>
</item>
<item row="0" column="1">
<widget class="QSpinBox" name="opt_timeout">
<property name="minimum">
<number>1</number>
</property>
</widget>
</item>
<item row="1" column="0">
<widget class="QLabel" name="label_2">
<property name="text">
<string>Number of seconds to let a store process results</string>
</property>
</widget>
</item>
<item row="1" column="1">
<widget class="QSpinBox" name="opt_hang_time">
<property name="minimum">
<number>1</number>
</property>
<property name="maximum">
<number>99</number>
</property>
<property name="singleStep">
<number>1</number>
</property>
<property name="value">
<number>1</number>
</property>
</widget>
</item>
</layout>
</widget>
</item>
<item>
<widget class="QGroupBox" name="groupBox_2">
<property name="title">
<string>Display</string>
</property>
<layout class="QFormLayout" name="formLayout_2">
<item row="0" column="0">
<widget class="QLabel" name="label_3">
<property name="text">
<string>Maximum number of results to show per store</string>
</property>
</widget>
</item>
<item row="0" column="1">
<widget class="QSpinBox" name="opt_max_results">
<property name="minimum">
<number>1</number>
</property>
</widget>
</item>
<item row="1" column="0">
<widget class="QCheckBox" name="opt_open_external">
<property name="text">
<string>Open search result in system browser</string>
</property>
</widget>
</item>
</layout>
</widget>
</item>
<item>
<widget class="QGroupBox" name="groupBox_3">
<property name="title">
<string>Threads</string>
</property>
<layout class="QFormLayout" name="formLayout_3">
<item row="0" column="0">
<widget class="QLabel" name="label_4">
<property name="text">
<string>Number of search threads to use</string>
</property>
</widget>
</item>
<item row="0" column="1">
<widget class="QSpinBox" name="opt_search_thread_count">
<property name="minimum">
<number>1</number>
</property>
</widget>
</item>
<item row="1" column="0">
<widget class="QLabel" name="label_5">
<property name="text">
<string>Number of cache update threads to use</string>
</property>
</widget>
</item>
<item row="1" column="1">
<widget class="QSpinBox" name="opt_cache_thread_count">
<property name="minimum">
<number>1</number>
</property>
</widget>
</item>
<item row="2" column="0">
<widget class="QLabel" name="label_6">
<property name="text">
<string>Number of conver download threads to use</string>
</property>
</widget>
</item>
<item row="2" column="1">
<widget class="QSpinBox" name="opt_cover_thread_count">
<property name="minimum">
<number>1</number>
</property>
</widget>
</item>
<item row="3" column="0">
<widget class="QLabel" name="label_7">
<property name="text">
<string>Number of details threads to use</string>
</property>
</widget>
</item>
<item row="3" column="1">
<widget class="QSpinBox" name="opt_details_thread_count">
<property name="minimum">
<number>1</number>
</property>
</widget>
</item>
</layout>
</widget>
</item>
</layout>
</widget>
<resources/>
<connections/>
</ui>

Some files were not shown because too many files have changed in this diff Show More