mirror of
https://github.com/kovidgoyal/calibre.git
synced 2025-06-23 15:30:45 -04:00
merge with John's branch
This commit is contained in:
commit
fc1bba1a07
@ -1148,7 +1148,7 @@ plugins += [LookAndFeel, Behavior, Columns, Toolbar, Search, InputOptions,
|
||||
class StoreAmazonKindleStore(StoreBase):
|
||||
name = 'Amazon Kindle'
|
||||
description = u'Kindle books from Amazon.'
|
||||
actual_plugin = 'calibre.gui2.store.amazon_plugin:AmazonKindleStore'
|
||||
actual_plugin = 'calibre.gui2.store.stores.amazon_plugin:AmazonKindleStore'
|
||||
|
||||
headquarters = 'US'
|
||||
formats = ['KINDLE']
|
||||
@ -1158,7 +1158,7 @@ class StoreAmazonDEKindleStore(StoreBase):
|
||||
name = 'Amazon DE Kindle'
|
||||
author = 'Charles Haley'
|
||||
description = u'Kindle Bücher von Amazon.'
|
||||
actual_plugin = 'calibre.gui2.store.amazon_de_plugin:AmazonDEKindleStore'
|
||||
actual_plugin = 'calibre.gui2.store.stores.amazon_de_plugin:AmazonDEKindleStore'
|
||||
|
||||
headquarters = 'DE'
|
||||
formats = ['KINDLE']
|
||||
@ -1168,7 +1168,7 @@ class StoreAmazonUKKindleStore(StoreBase):
|
||||
name = 'Amazon UK Kindle'
|
||||
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'
|
||||
actual_plugin = 'calibre.gui2.store.stores.amazon_uk_plugin:AmazonUKKindleStore'
|
||||
|
||||
headquarters = 'UK'
|
||||
formats = ['KINDLE']
|
||||
@ -1177,7 +1177,7 @@ class StoreAmazonUKKindleStore(StoreBase):
|
||||
class StoreArchiveOrgStore(StoreBase):
|
||||
name = 'Archive.org'
|
||||
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'
|
||||
actual_plugin = 'calibre.gui2.store.stores.archive_org_plugin:ArchiveOrgStore'
|
||||
|
||||
drm_free_only = True
|
||||
headquarters = 'US'
|
||||
@ -1186,7 +1186,7 @@ class StoreArchiveOrgStore(StoreBase):
|
||||
class StoreBaenWebScriptionStore(StoreBase):
|
||||
name = 'Baen WebScription'
|
||||
description = u'Sci-Fi & Fantasy brought to you by Jim Baen.'
|
||||
actual_plugin = 'calibre.gui2.store.baen_webscription_plugin:BaenWebScriptionStore'
|
||||
actual_plugin = 'calibre.gui2.store.stores.baen_webscription_plugin:BaenWebScriptionStore'
|
||||
|
||||
drm_free_only = True
|
||||
headquarters = 'US'
|
||||
@ -1195,7 +1195,7 @@ class StoreBaenWebScriptionStore(StoreBase):
|
||||
class StoreBNStore(StoreBase):
|
||||
name = 'Barnes and Noble'
|
||||
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'
|
||||
actual_plugin = 'calibre.gui2.store.stores.bn_plugin:BNStore'
|
||||
|
||||
headquarters = 'US'
|
||||
formats = ['NOOK']
|
||||
@ -1205,7 +1205,7 @@ class StoreBeamEBooksDEStore(StoreBase):
|
||||
name = 'Beam EBooks DE'
|
||||
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'
|
||||
actual_plugin = 'calibre.gui2.store.stores.beam_ebooks_de_plugin:BeamEBooksDEStore'
|
||||
|
||||
drm_free_only = True
|
||||
headquarters = 'DE'
|
||||
@ -1215,7 +1215,7 @@ class StoreBeamEBooksDEStore(StoreBase):
|
||||
class StoreBeWriteStore(StoreBase):
|
||||
name = 'BeWrite 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'
|
||||
actual_plugin = 'calibre.gui2.store.stores.bewrite_plugin:BeWriteStore'
|
||||
|
||||
drm_free_only = True
|
||||
headquarters = 'US'
|
||||
@ -1224,7 +1224,7 @@ class StoreBeWriteStore(StoreBase):
|
||||
class StoreDieselEbooksStore(StoreBase):
|
||||
name = 'Diesel eBooks'
|
||||
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'
|
||||
actual_plugin = 'calibre.gui2.store.stores.diesel_ebooks_plugin:DieselEbooksStore'
|
||||
|
||||
headquarters = 'US'
|
||||
formats = ['EPUB', 'PDF']
|
||||
@ -1233,7 +1233,7 @@ class StoreDieselEbooksStore(StoreBase):
|
||||
class StoreEbookscomStore(StoreBase):
|
||||
name = 'eBooks.com'
|
||||
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'
|
||||
actual_plugin = 'calibre.gui2.store.stores.ebooks_com_plugin:EbookscomStore'
|
||||
|
||||
headquarters = 'US'
|
||||
formats = ['EPUB', 'LIT', 'MOBI', 'PDF']
|
||||
@ -1243,7 +1243,7 @@ class StoreEPubBuyDEStore(StoreBase):
|
||||
name = 'EPUBBuy DE'
|
||||
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'
|
||||
actual_plugin = 'calibre.gui2.store.stores.epubbuy_de_plugin:EPubBuyDEStore'
|
||||
|
||||
drm_free_only = True
|
||||
headquarters = 'DE'
|
||||
@ -1254,7 +1254,7 @@ 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'
|
||||
actual_plugin = 'calibre.gui2.store.stores.ebookshoppe_uk_plugin:EBookShoppeUKStore'
|
||||
|
||||
headquarters = 'UK'
|
||||
formats = ['EPUB', 'PDF']
|
||||
@ -1263,7 +1263,7 @@ class StoreEBookShoppeUKStore(StoreBase):
|
||||
class StoreEHarlequinStore(StoreBase):
|
||||
name = 'eHarlequin'
|
||||
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'
|
||||
actual_plugin = 'calibre.gui2.store.stores.eharlequin_plugin:EHarlequinStore'
|
||||
|
||||
headquarters = 'CA'
|
||||
formats = ['EPUB', 'PDF']
|
||||
@ -1272,7 +1272,7 @@ class StoreEHarlequinStore(StoreBase):
|
||||
class StoreEpubBudStore(StoreBase):
|
||||
name = 'ePub Bud'
|
||||
description = 'Well, it\'s pretty much just "YouTube for Children\'s eBooks. A not-for-profit organization devoted to brining self published childrens books to the world.'
|
||||
actual_plugin = 'calibre.gui2.store.epubbud_plugin:EpubBudStore'
|
||||
actual_plugin = 'calibre.gui2.store.stores.epubbud_plugin:EpubBudStore'
|
||||
|
||||
drm_free_only = True
|
||||
headquarters = 'US'
|
||||
@ -1281,7 +1281,7 @@ class StoreEpubBudStore(StoreBase):
|
||||
class StoreFeedbooksStore(StoreBase):
|
||||
name = 'Feedbooks'
|
||||
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'
|
||||
actual_plugin = 'calibre.gui2.store.stores.feedbooks_plugin:FeedbooksStore'
|
||||
|
||||
headquarters = 'FR'
|
||||
formats = ['EPUB', 'MOBI', 'PDF']
|
||||
@ -1290,7 +1290,7 @@ class StoreFoylesUKStore(StoreBase):
|
||||
name = 'Foyles UK'
|
||||
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'
|
||||
actual_plugin = 'calibre.gui2.store.stores.foyles_uk_plugin:FoylesUKStore'
|
||||
|
||||
headquarters = 'UK'
|
||||
formats = ['EPUB', 'PDF']
|
||||
@ -1300,7 +1300,7 @@ class StoreGandalfStore(StoreBase):
|
||||
name = 'Gandalf'
|
||||
author = u'Tomasz Długosz'
|
||||
description = u'Księgarnia internetowa Gandalf.'
|
||||
actual_plugin = 'calibre.gui2.store.gandalf_plugin:GandalfStore'
|
||||
actual_plugin = 'calibre.gui2.store.stores.gandalf_plugin:GandalfStore'
|
||||
|
||||
headquarters = 'PL'
|
||||
formats = ['EPUB', 'PDF']
|
||||
@ -1308,7 +1308,7 @@ class StoreGandalfStore(StoreBase):
|
||||
class StoreGoogleBooksStore(StoreBase):
|
||||
name = 'Google Books'
|
||||
description = u'Google Books'
|
||||
actual_plugin = 'calibre.gui2.store.google_books_plugin:GoogleBooksStore'
|
||||
actual_plugin = 'calibre.gui2.store.stores.google_books_plugin:GoogleBooksStore'
|
||||
|
||||
headquarters = 'US'
|
||||
formats = ['EPUB', 'PDF', 'TXT']
|
||||
@ -1316,7 +1316,7 @@ class StoreGoogleBooksStore(StoreBase):
|
||||
class StoreGutenbergStore(StoreBase):
|
||||
name = 'Project Gutenberg'
|
||||
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'
|
||||
actual_plugin = 'calibre.gui2.store.stores.gutenberg_plugin:GutenbergStore'
|
||||
|
||||
drm_free_only = True
|
||||
headquarters = 'US'
|
||||
@ -1325,7 +1325,7 @@ class StoreGutenbergStore(StoreBase):
|
||||
class StoreKoboStore(StoreBase):
|
||||
name = 'Kobo'
|
||||
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'
|
||||
actual_plugin = 'calibre.gui2.store.stores.kobo_plugin:KoboStore'
|
||||
|
||||
headquarters = 'CA'
|
||||
formats = ['EPUB']
|
||||
@ -1335,7 +1335,7 @@ 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'
|
||||
actual_plugin = 'calibre.gui2.store.stores.legimi_plugin:LegimiStore'
|
||||
|
||||
headquarters = 'PL'
|
||||
formats = ['EPUB']
|
||||
@ -1344,7 +1344,7 @@ class StoreLibreDEStore(StoreBase):
|
||||
name = 'Libri DE'
|
||||
author = 'Charles Haley'
|
||||
description = u'Sicher Bücher, Hörbücher und Downloads online bestellen.'
|
||||
actual_plugin = 'calibre.gui2.store.libri_de_plugin:LibreDEStore'
|
||||
actual_plugin = 'calibre.gui2.store.stores.libri_de_plugin:LibreDEStore'
|
||||
|
||||
headquarters = 'DE'
|
||||
formats = ['EPUB', 'PDF']
|
||||
@ -1353,7 +1353,7 @@ class StoreLibreDEStore(StoreBase):
|
||||
class StoreManyBooksStore(StoreBase):
|
||||
name = 'ManyBooks'
|
||||
description = u'Public domain and creative commons works from many sources.'
|
||||
actual_plugin = 'calibre.gui2.store.manybooks_plugin:ManyBooksStore'
|
||||
actual_plugin = 'calibre.gui2.store.stores.manybooks_plugin:ManyBooksStore'
|
||||
|
||||
drm_free_only = True
|
||||
headquarters = 'US'
|
||||
@ -1362,7 +1362,7 @@ class StoreManyBooksStore(StoreBase):
|
||||
class StoreMobileReadStore(StoreBase):
|
||||
name = 'MobileRead'
|
||||
description = u'Ebooks handcrafted with the utmost care.'
|
||||
actual_plugin = 'calibre.gui2.store.mobileread.mobileread_plugin:MobileReadStore'
|
||||
actual_plugin = 'calibre.gui2.store.stores.mobileread.mobileread_plugin:MobileReadStore'
|
||||
|
||||
drm_free_only = True
|
||||
headquarters = 'CH'
|
||||
@ -1372,7 +1372,7 @@ class StoreNextoStore(StoreBase):
|
||||
name = 'Nexto'
|
||||
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'
|
||||
actual_plugin = 'calibre.gui2.store.stores.nexto_plugin:NextoStore'
|
||||
|
||||
headquarters = 'PL'
|
||||
formats = ['EPUB', 'PDF']
|
||||
@ -1381,7 +1381,7 @@ class StoreNextoStore(StoreBase):
|
||||
class StoreOpenBooksStore(StoreBase):
|
||||
name = 'Open Books'
|
||||
description = u'Comprehensive listing of DRM free ebooks from a variety of sources provided by users of calibre.'
|
||||
actual_plugin = 'calibre.gui2.store.open_books_plugin:OpenBooksStore'
|
||||
actual_plugin = 'calibre.gui2.store.stores.open_books_plugin:OpenBooksStore'
|
||||
|
||||
drm_free_only = True
|
||||
headquarters = 'US'
|
||||
@ -1389,7 +1389,7 @@ class StoreOpenBooksStore(StoreBase):
|
||||
class StoreOpenLibraryStore(StoreBase):
|
||||
name = 'Open Library'
|
||||
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'
|
||||
actual_plugin = 'calibre.gui2.store.stores.open_library_plugin:OpenLibraryStore'
|
||||
|
||||
drm_free_only = True
|
||||
headquarters = 'US'
|
||||
@ -1398,7 +1398,7 @@ class StoreOpenLibraryStore(StoreBase):
|
||||
class StoreOReillyStore(StoreBase):
|
||||
name = 'OReilly'
|
||||
description = u'Programming and tech ebooks from OReilly.'
|
||||
actual_plugin = 'calibre.gui2.store.oreilly_plugin:OReillyStore'
|
||||
actual_plugin = 'calibre.gui2.store.stores.oreilly_plugin:OReillyStore'
|
||||
|
||||
drm_free_only = True
|
||||
headquarters = 'US'
|
||||
@ -1407,7 +1407,7 @@ class StoreOReillyStore(StoreBase):
|
||||
class StorePragmaticBookshelfStore(StoreBase):
|
||||
name = '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'
|
||||
actual_plugin = 'calibre.gui2.store.stores.pragmatic_bookshelf_plugin:PragmaticBookshelfStore'
|
||||
|
||||
drm_free_only = True
|
||||
headquarters = 'US'
|
||||
@ -1416,7 +1416,7 @@ class StorePragmaticBookshelfStore(StoreBase):
|
||||
class StoreSmashwordsStore(StoreBase):
|
||||
name = 'Smashwords'
|
||||
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'
|
||||
actual_plugin = 'calibre.gui2.store.stores.smashwords_plugin:SmashwordsStore'
|
||||
|
||||
drm_free_only = True
|
||||
headquarters = 'US'
|
||||
@ -1427,7 +1427,7 @@ 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'
|
||||
actual_plugin = 'calibre.gui2.store.stores.virtualo_plugin:VirtualoStore'
|
||||
|
||||
headquarters = 'PL'
|
||||
formats = ['EPUB', 'PDF']
|
||||
@ -1436,7 +1436,7 @@ class StoreWaterstonesUKStore(StoreBase):
|
||||
name = 'Waterstones UK'
|
||||
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'
|
||||
actual_plugin = 'calibre.gui2.store.stores.waterstones_uk_plugin:WaterstonesUKStore'
|
||||
|
||||
headquarters = 'UK'
|
||||
formats = ['EPUB', 'PDF']
|
||||
@ -1444,7 +1444,7 @@ class StoreWaterstonesUKStore(StoreBase):
|
||||
class StoreWeightlessBooksStore(StoreBase):
|
||||
name = 'Weightless Books'
|
||||
description = u'An independent DRM-free ebooksite devoted to ebooks of all sorts.'
|
||||
actual_plugin = 'calibre.gui2.store.weightless_books_plugin:WeightlessBooksStore'
|
||||
actual_plugin = 'calibre.gui2.store.stores.weightless_books_plugin:WeightlessBooksStore'
|
||||
|
||||
drm_free_only = True
|
||||
headquarters = 'US'
|
||||
@ -1454,7 +1454,7 @@ 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'
|
||||
actual_plugin = 'calibre.gui2.store.stores.whsmith_uk_plugin:WHSmithUKStore'
|
||||
|
||||
headquarters = 'UK'
|
||||
formats = ['EPUB', 'PDF']
|
||||
@ -1462,7 +1462,7 @@ class StoreWHSmithUKStore(StoreBase):
|
||||
class StoreWizardsTowerBooksStore(StoreBase):
|
||||
name = 'Wizards Tower Books'
|
||||
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'
|
||||
actual_plugin = 'calibre.gui2.store.stores.wizards_tower_books_plugin:WizardsTowerBooksStore'
|
||||
|
||||
drm_free_only = True
|
||||
headquarters = 'UK'
|
||||
@ -1472,7 +1472,7 @@ 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'
|
||||
actual_plugin = 'calibre.gui2.store.stores.woblink_plugin:WoblinkStore'
|
||||
|
||||
headquarters = 'PL'
|
||||
formats = ['EPUB']
|
||||
@ -1481,7 +1481,7 @@ class StoreZixoStore(StoreBase):
|
||||
name = 'Zixo'
|
||||
author = u'Tomasz Długosz'
|
||||
description = u'Księgarnia z ebookami oraz książkami audio. Aby otwierać książki w formacie Zixo należy zainstalować program dostępny na stronie księgarni. Umożliwia on m.in. dodawanie zakładek i dostosowywanie rozmiaru czcionki.'
|
||||
actual_plugin = 'calibre.gui2.store.zixo_plugin:ZixoStore'
|
||||
actual_plugin = 'calibre.gui2.store.stores.zixo_plugin:ZixoStore'
|
||||
|
||||
headquarters = 'PL'
|
||||
formats = ['PDF, ZIXO']
|
||||
|
@ -351,7 +351,9 @@ class ComicInput(InputFormatPlugin):
|
||||
comics = []
|
||||
with CurrentDir(tdir):
|
||||
if not os.path.exists('comics.txt'):
|
||||
raise ValueError('%s is not a valid comic collection'
|
||||
raise ValueError((
|
||||
'%s is not a valid comic collection'
|
||||
' no comics.txt was found in the file')
|
||||
%stream.name)
|
||||
raw = open('comics.txt', 'rb').read()
|
||||
if raw.startswith(codecs.BOM_UTF16_BE):
|
||||
|
@ -17,6 +17,8 @@ def decompress_doc(data):
|
||||
return cPalmdoc.decompress(data)
|
||||
|
||||
def compress_doc(data):
|
||||
if not data:
|
||||
return u''
|
||||
return cPalmdoc.compress(data)
|
||||
|
||||
def test():
|
||||
|
@ -5,7 +5,7 @@ __license__ = 'GPL v3'
|
||||
__copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'
|
||||
__docformat__ = 'restructuredtext en'
|
||||
|
||||
import os, shutil
|
||||
import os
|
||||
from functools import partial
|
||||
|
||||
from PyQt4.Qt import QMenu, Qt, QInputDialog, QToolButton
|
||||
@ -14,7 +14,7 @@ from calibre import isbytestring
|
||||
from calibre.constants import filesystem_encoding, iswindows
|
||||
from calibre.utils.config import prefs
|
||||
from calibre.gui2 import (gprefs, warning_dialog, Dispatcher, error_dialog,
|
||||
question_dialog, info_dialog)
|
||||
question_dialog, info_dialog, open_local_file)
|
||||
from calibre.library.database2 import LibraryDatabase2
|
||||
from calibre.gui2.actions import InterfaceAction
|
||||
|
||||
@ -107,7 +107,7 @@ class ChooseLibraryAction(InterfaceAction):
|
||||
self.quick_menu_action = self.choose_menu.addMenu(self.quick_menu)
|
||||
self.rename_menu = QMenu(_('Rename library'))
|
||||
self.rename_menu_action = self.choose_menu.addMenu(self.rename_menu)
|
||||
self.delete_menu = QMenu(_('Delete library'))
|
||||
self.delete_menu = QMenu(_('Remove library'))
|
||||
self.delete_menu_action = self.choose_menu.addMenu(self.delete_menu)
|
||||
|
||||
ac = self.create_action(spec=(_('Pick a random book'), 'catalog.png',
|
||||
@ -252,22 +252,15 @@ class ChooseLibraryAction(InterfaceAction):
|
||||
|
||||
def delete_requested(self, name, location):
|
||||
loc = location.replace('/', os.sep)
|
||||
if not question_dialog(self.gui, _('Are you sure?'),
|
||||
_('<h1 style="color:red">WARNING</h1>')+
|
||||
_('<b style="color: red">All files</b> (not just ebooks) '
|
||||
'from <br><br><b>%s</b><br><br> will be '
|
||||
'<b>permanently deleted</b>. Are you sure?') % loc,
|
||||
show_copy_button=False, default_yes=False):
|
||||
return
|
||||
exists = self.gui.library_view.model().db.exists_at(loc)
|
||||
if exists:
|
||||
try:
|
||||
shutil.rmtree(loc, ignore_errors=True)
|
||||
except:
|
||||
pass
|
||||
self.stats.remove(location)
|
||||
self.build_menus()
|
||||
self.gui.iactions['Copy To Library'].build_menus()
|
||||
info_dialog(self.gui, _('Library removed'),
|
||||
_('The library %s has been removed from calibre. '
|
||||
'The files remain on your computer, if you want '
|
||||
'to delete them, you will have to do so manually.') % loc,
|
||||
show=True)
|
||||
open_local_file(loc)
|
||||
|
||||
def backup_status(self, location):
|
||||
dirty_text = 'no'
|
||||
|
@ -16,7 +16,7 @@ from calibre.constants import isosx, __appname__, preferred_encoding, \
|
||||
from calibre.gui2 import config, is_widescreen, gprefs
|
||||
from calibre.gui2.library.views import BooksView, DeviceBooksView
|
||||
from calibre.gui2.widgets import Splitter
|
||||
from calibre.gui2.tag_view import TagBrowserWidget
|
||||
from calibre.gui2.tag_browser.ui import TagBrowserWidget
|
||||
from calibre.gui2.book_details import BookDetails
|
||||
from calibre.gui2.notify import get_notifier
|
||||
|
||||
|
@ -1,89 +0,0 @@
|
||||
# -*- 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 urllib
|
||||
from contextlib import closing
|
||||
|
||||
from lxml import html
|
||||
|
||||
from PyQt4.Qt import QUrl
|
||||
|
||||
from calibre import browser, url_slash_cleaner
|
||||
from calibre.gui2 import open_url
|
||||
from calibre.gui2.store import StorePlugin
|
||||
from calibre.gui2.store.basic_config import BasicStoreConfig
|
||||
from calibre.gui2.store.search_result import SearchResult
|
||||
from calibre.gui2.store.web_store_dialog import WebStoreDialog
|
||||
|
||||
class ArchiveOrgStore(BasicStoreConfig, StorePlugin):
|
||||
|
||||
def open(self, parent=None, detail_item=None, external=False):
|
||||
url = 'http://www.archive.org/details/texts'
|
||||
|
||||
if detail_item:
|
||||
detail_item = url_slash_cleaner('http://www.archive.org' + detail_item)
|
||||
|
||||
if external or self.config.get('open_external', False):
|
||||
open_url(QUrl(url_slash_cleaner(detail_item if detail_item else url)))
|
||||
else:
|
||||
d = WebStoreDialog(self.gui, url, parent, detail_item)
|
||||
d.setWindowTitle(self.name)
|
||||
d.set_tags(self.config.get('tags', ''))
|
||||
d.exec_()
|
||||
|
||||
def search(self, query, max_results=10, timeout=60):
|
||||
query = query + ' AND mediatype:texts'
|
||||
url = 'http://www.archive.org/search.php?query=' + urllib.quote(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('//td[@class="hitCell"]'):
|
||||
if counter <= 0:
|
||||
break
|
||||
|
||||
id = ''.join(data.xpath('.//a[@class="titleLink"]/@href'))
|
||||
if not id:
|
||||
continue
|
||||
|
||||
title = ''.join(data.xpath('.//a[@class="titleLink"]//text()'))
|
||||
authors = data.xpath('.//text()')
|
||||
if not authors:
|
||||
continue
|
||||
author = None
|
||||
for a in authors:
|
||||
if '-' in a:
|
||||
author = a.replace('-', ' ').strip()
|
||||
if author:
|
||||
break
|
||||
if not author:
|
||||
continue
|
||||
|
||||
counter -= 1
|
||||
|
||||
s = SearchResult()
|
||||
s.title = title.strip()
|
||||
s.author = author.strip()
|
||||
s.price = '$0.00'
|
||||
s.detail_item = id.strip()
|
||||
s.drm = SearchResult.DRM_UNLOCKED
|
||||
|
||||
yield s
|
||||
|
||||
def get_details(self, search_result, timeout):
|
||||
url = url_slash_cleaner('http://www.archive.org' + search_result.detail_item)
|
||||
|
||||
br = browser()
|
||||
with closing(br.open(url, timeout=timeout)) as nf:
|
||||
idata = html.fromstring(nf.read())
|
||||
formats = ', '.join(idata.xpath('//p[@id="dl" and @class="content"]//a/text()'))
|
||||
search_result.formats = formats.upper()
|
||||
|
||||
return True
|
@ -1,78 +0,0 @@
|
||||
# -*- 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 urllib
|
||||
from contextlib import closing
|
||||
|
||||
from lxml import html
|
||||
|
||||
from PyQt4.Qt import QUrl
|
||||
|
||||
from calibre import browser, url_slash_cleaner
|
||||
from calibre.gui2 import open_url
|
||||
from calibre.gui2.store import StorePlugin
|
||||
from calibre.gui2.store.basic_config import BasicStoreConfig
|
||||
from calibre.gui2.store.search_result import SearchResult
|
||||
from calibre.gui2.store.web_store_dialog import WebStoreDialog
|
||||
|
||||
class EpubBudStore(BasicStoreConfig, StorePlugin):
|
||||
|
||||
def open(self, parent=None, detail_item=None, external=False):
|
||||
url = 'http://epubbud.com/'
|
||||
|
||||
if external or self.config.get('open_external', False):
|
||||
open_url(QUrl(url_slash_cleaner(detail_item if detail_item else url)))
|
||||
else:
|
||||
d = WebStoreDialog(self.gui, url, parent, detail_item)
|
||||
d.setWindowTitle(self.name)
|
||||
d.set_tags(self.config.get('tags', ''))
|
||||
d.exec_()
|
||||
|
||||
def search(self, query, max_results=10, timeout=60):
|
||||
'''
|
||||
OPDS based search.
|
||||
|
||||
We really should get the catelog from http://pragprog.com/catalog.opds
|
||||
and look for the application/opensearchdescription+xml entry.
|
||||
Then get the opensearch description to get the search url and
|
||||
format. However, we are going to be lazy and hard code it.
|
||||
'''
|
||||
url = 'http://www.epubbud.com/search.php?format=atom&q=' + urllib.quote_plus(query)
|
||||
|
||||
br = browser()
|
||||
|
||||
counter = max_results
|
||||
with closing(br.open(url, timeout=timeout)) as f:
|
||||
# Use html instead of etree as html allows us
|
||||
# to ignore the namespace easily.
|
||||
doc = html.fromstring(f.read())
|
||||
for data in doc.xpath('//entry'):
|
||||
if counter <= 0:
|
||||
break
|
||||
|
||||
id = ''.join(data.xpath('.//id/text()'))
|
||||
if not id:
|
||||
continue
|
||||
|
||||
cover_url = ''.join(data.xpath('.//link[@rel="http://opds-spec.org/thumbnail"]/@href'))
|
||||
|
||||
title = u''.join(data.xpath('.//title/text()'))
|
||||
author = u''.join(data.xpath('.//author/name/text()'))
|
||||
|
||||
counter -= 1
|
||||
|
||||
s = SearchResult()
|
||||
s.cover_url = cover_url
|
||||
s.title = title.strip()
|
||||
s.author = author.strip()
|
||||
s.price = '$0.00'
|
||||
s.detail_item = id.strip()
|
||||
s.drm = SearchResult.DRM_UNLOCKED
|
||||
s.formats = 'EPUB'
|
||||
|
||||
yield s
|
@ -1,106 +0,0 @@
|
||||
# -*- 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 urllib2
|
||||
from contextlib import closing
|
||||
|
||||
from lxml import html
|
||||
|
||||
from PyQt4.Qt import QUrl
|
||||
|
||||
from calibre import browser, url_slash_cleaner
|
||||
from calibre.gui2 import open_url
|
||||
from calibre.gui2.store import StorePlugin
|
||||
from calibre.gui2.store.basic_config import BasicStoreConfig
|
||||
from calibre.gui2.store.search_result import SearchResult
|
||||
from calibre.gui2.store.web_store_dialog import WebStoreDialog
|
||||
|
||||
class FeedbooksStore(BasicStoreConfig, StorePlugin):
|
||||
|
||||
def open(self, parent=None, detail_item=None, external=False):
|
||||
url = 'http://m.feedbooks.com/'
|
||||
ext_url = 'http://feedbooks.com/'
|
||||
|
||||
if external or self.config.get('open_external', False):
|
||||
if detail_item:
|
||||
ext_url = ext_url + detail_item
|
||||
open_url(QUrl(url_slash_cleaner(ext_url)))
|
||||
else:
|
||||
detail_url = None
|
||||
if detail_item:
|
||||
detail_url = url + detail_item
|
||||
d = WebStoreDialog(self.gui, url, parent, detail_url)
|
||||
d.setWindowTitle(self.name)
|
||||
d.set_tags(self.config.get('tags', ''))
|
||||
d.exec_()
|
||||
|
||||
def search(self, query, max_results=10, timeout=60):
|
||||
url = 'http://m.feedbooks.com/search?query=' + urllib2.quote(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('//ul[@class="m-list"]//li'):
|
||||
if counter <= 0:
|
||||
break
|
||||
data = html.fromstring(html.tostring(data))
|
||||
|
||||
id = ''
|
||||
id_a = data.xpath('//a[@class="buy"]')
|
||||
if id_a:
|
||||
id = id_a[0].get('href', None)
|
||||
id = id.split('/')[-2]
|
||||
id = '/item/' + id
|
||||
else:
|
||||
id_a = data.xpath('//a[@class="download"]')
|
||||
if id_a:
|
||||
id = id_a[0].get('href', None)
|
||||
id = id.split('/')[-1]
|
||||
id = id.split('.')[0]
|
||||
id = '/book/' + id
|
||||
if not id:
|
||||
continue
|
||||
|
||||
title = ''.join(data.xpath('//h5//a/text()'))
|
||||
author = ''.join(data.xpath('//h6//a/text()'))
|
||||
price = ''.join(data.xpath('//a[@class="buy"]/text()'))
|
||||
formats = 'EPUB'
|
||||
if not price:
|
||||
price = '$0.00'
|
||||
formats = 'EPUB, MOBI, PDF'
|
||||
cover_url = ''
|
||||
cover_url_img = data.xpath('//img')
|
||||
if cover_url_img:
|
||||
cover_url = cover_url_img[0].get('src')
|
||||
cover_url.split('?')[0]
|
||||
|
||||
counter -= 1
|
||||
|
||||
s = SearchResult()
|
||||
s.cover_url = cover_url
|
||||
s.title = title.strip()
|
||||
s.author = author.strip()
|
||||
s.price = price.replace(' ', '').strip()
|
||||
s.detail_item = id.strip()
|
||||
s.formats = formats
|
||||
|
||||
yield s
|
||||
|
||||
def get_details(self, search_result, timeout):
|
||||
url = 'http://m.feedbooks.com/'
|
||||
|
||||
br = browser()
|
||||
with closing(br.open(url_slash_cleaner(url + search_result.detail_item), timeout=timeout)) as nf:
|
||||
idata = html.fromstring(nf.read())
|
||||
if idata.xpath('boolean(//div[contains(@class, "m-description-long")]//p[contains(., "DRM") or contains(b, "Protection")])'):
|
||||
search_result.drm = SearchResult.DRM_LOCKED
|
||||
else:
|
||||
search_result.drm = SearchResult.DRM_UNLOCKED
|
||||
return True
|
101
src/calibre/gui2/store/opensearch_store.py
Normal file
101
src/calibre/gui2/store/opensearch_store.py
Normal file
@ -0,0 +1,101 @@
|
||||
# -*- 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 mimetypes
|
||||
import urllib
|
||||
from contextlib import closing
|
||||
|
||||
from lxml import etree
|
||||
|
||||
from PyQt4.Qt import QUrl
|
||||
|
||||
from calibre import browser
|
||||
from calibre.gui2 import open_url
|
||||
from calibre.gui2.store import StorePlugin
|
||||
from calibre.gui2.store.search_result import SearchResult
|
||||
from calibre.gui2.store.web_store_dialog import WebStoreDialog
|
||||
from calibre.utils.opensearch.description import Description
|
||||
from calibre.utils.opensearch.query import Query
|
||||
|
||||
class OpenSearchStore(StorePlugin):
|
||||
|
||||
open_search_url = ''
|
||||
web_url = ''
|
||||
|
||||
def open(self, parent=None, detail_item=None, external=False):
|
||||
if not hasattr(self, 'web_url'):
|
||||
return
|
||||
|
||||
if external or self.config.get('open_external', False):
|
||||
open_url(QUrl(detail_item if detail_item else self.web_url))
|
||||
else:
|
||||
d = WebStoreDialog(self.gui, self.web_url, parent, detail_item)
|
||||
d.setWindowTitle(self.name)
|
||||
d.set_tags(self.config.get('tags', ''))
|
||||
d.exec_()
|
||||
|
||||
def search(self, query, max_results=10, timeout=60):
|
||||
if not hasattr(self, 'open_search_url'):
|
||||
return
|
||||
|
||||
description = Description(self.open_search_url)
|
||||
url_template = description.get_best_template()
|
||||
if not url_template:
|
||||
return
|
||||
oquery = Query(url_template)
|
||||
|
||||
# set up initial values
|
||||
oquery.searchTerms = urllib.quote_plus(query)
|
||||
oquery.count = max_results
|
||||
url = oquery.url()
|
||||
|
||||
counter = max_results
|
||||
br = browser()
|
||||
with closing(br.open(url, timeout=timeout)) as f:
|
||||
doc = etree.fromstring(f.read())
|
||||
for data in doc.xpath('//*[local-name() = "entry"]'):
|
||||
if counter <= 0:
|
||||
break
|
||||
|
||||
counter -= 1
|
||||
|
||||
s = SearchResult()
|
||||
|
||||
s.detail_item = ''.join(data.xpath('./*[local-name() = "id"]/text()')).strip()
|
||||
|
||||
for link in data.xpath('./*[local-name() = "link"]'):
|
||||
rel = link.get('rel')
|
||||
href = link.get('href')
|
||||
type = link.get('type')
|
||||
|
||||
if rel and href and type:
|
||||
if rel in ('http://opds-spec.org/thumbnail', 'http://opds-spec.org/image/thumbnail'):
|
||||
s.cover_url = href
|
||||
elif rel == u'http://opds-spec.org/acquisition/buy':
|
||||
s.detail_item = href
|
||||
elif rel == u'http://opds-spec.org/acquisition':
|
||||
if type:
|
||||
ext = mimetypes.guess_extension(type)
|
||||
if ext:
|
||||
ext = ext[1:].upper().strip()
|
||||
s.downloads[ext] = href
|
||||
s.formats = ', '.join(s.downloads.keys()).strip()
|
||||
|
||||
s.title = ' '.join(data.xpath('./*[local-name() = "title"]//text()')).strip()
|
||||
s.author = ', '.join(data.xpath('./*[local-name() = "author"]//*[local-name() = "name"]//text()')).strip()
|
||||
|
||||
price_e = data.xpath('.//*[local-name() = "price"][1]')
|
||||
if price_e:
|
||||
price_e = price_e[0]
|
||||
currency_code = price_e.get('currencycode', '')
|
||||
price = ''.join(price_e.xpath('.//text()')).strip()
|
||||
s.price = currency_code + ' ' + price
|
||||
s.price = s.price.strip()
|
||||
|
||||
|
||||
yield s
|
@ -1,84 +0,0 @@
|
||||
# -*- 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 urllib
|
||||
from contextlib import closing
|
||||
|
||||
from lxml import html
|
||||
|
||||
from PyQt4.Qt import QUrl
|
||||
|
||||
from calibre import browser, url_slash_cleaner
|
||||
from calibre.gui2 import open_url
|
||||
from calibre.gui2.store import StorePlugin
|
||||
from calibre.gui2.store.basic_config import BasicStoreConfig
|
||||
from calibre.gui2.store.search_result import SearchResult
|
||||
from calibre.gui2.store.web_store_dialog import WebStoreDialog
|
||||
|
||||
class PragmaticBookshelfStore(BasicStoreConfig, StorePlugin):
|
||||
|
||||
def open(self, parent=None, detail_item=None, external=False):
|
||||
url = 'http://pragprog.com/'
|
||||
|
||||
if external or self.config.get('open_external', False):
|
||||
open_url(QUrl(url_slash_cleaner(detail_item if detail_item else url)))
|
||||
else:
|
||||
d = WebStoreDialog(self.gui, url, parent, detail_item)
|
||||
d.setWindowTitle(self.name)
|
||||
d.set_tags(self.config.get('tags', ''))
|
||||
d.exec_()
|
||||
|
||||
def search(self, query, max_results=10, timeout=60):
|
||||
'''
|
||||
OPDS based search.
|
||||
|
||||
We really should get the catelog from http://pragprog.com/catalog.opds
|
||||
and look for the application/opensearchdescription+xml entry.
|
||||
Then get the opensearch description to get the search url and
|
||||
format. However, we are going to be lazy and hard code it.
|
||||
'''
|
||||
url = 'http://pragprog.com/catalog/search?q=' + urllib.quote_plus(query)
|
||||
|
||||
br = browser()
|
||||
|
||||
counter = max_results
|
||||
with closing(br.open(url, timeout=timeout)) as f:
|
||||
# Use html instead of etree as html allows us
|
||||
# to ignore the namespace easily.
|
||||
doc = html.fromstring(f.read())
|
||||
for data in doc.xpath('//entry'):
|
||||
if counter <= 0:
|
||||
break
|
||||
|
||||
id = ''.join(data.xpath('.//link[@rel="http://opds-spec.org/acquisition/buy"]/@href'))
|
||||
if not id:
|
||||
continue
|
||||
|
||||
price = ''.join(data.xpath('.//price/@currencycode')).strip()
|
||||
price += ' '
|
||||
price += ''.join(data.xpath('.//price/text()')).strip()
|
||||
if not price.strip():
|
||||
continue
|
||||
|
||||
cover_url = ''.join(data.xpath('.//link[@rel="http://opds-spec.org/cover"]/@href'))
|
||||
|
||||
title = ''.join(data.xpath('.//title/text()'))
|
||||
author = ''.join(data.xpath('.//author//text()'))
|
||||
|
||||
counter -= 1
|
||||
|
||||
s = SearchResult()
|
||||
s.cover_url = cover_url
|
||||
s.title = title.strip()
|
||||
s.author = author.strip()
|
||||
s.price = price.strip()
|
||||
s.detail_item = id.strip()
|
||||
s.drm = SearchResult.DRM_UNLOCKED
|
||||
s.formats = 'EPUB, PDF, MOBI'
|
||||
|
||||
yield s
|
@ -45,6 +45,7 @@ class AdvSearchBuilderDialog(QDialog, Ui_Dialog):
|
||||
self.author_box.setText('')
|
||||
self.price_box.setText('')
|
||||
self.format_box.setText('')
|
||||
self.download_combo.setCurrentIndex(0)
|
||||
self.affiliate_combo.setCurrentIndex(0)
|
||||
|
||||
def tokens(self, raw):
|
||||
@ -119,6 +120,9 @@ class AdvSearchBuilderDialog(QDialog, Ui_Dialog):
|
||||
format = unicode(self.format_box.text()).strip()
|
||||
if format:
|
||||
ans.append('format:"' + self.mc + format + '"')
|
||||
download = unicode(self.download_combo.currentText()).strip()
|
||||
if download:
|
||||
ans.append('download:' + download)
|
||||
affiliate = unicode(self.affiliate_combo.currentText()).strip()
|
||||
if affiliate:
|
||||
ans.append('affiliate:' + affiliate)
|
||||
|
@ -226,7 +226,7 @@
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item row="7" column="0" colspan="2">
|
||||
<item row="8" column="0" colspan="2">
|
||||
<layout class="QHBoxLayout" name="horizontalLayout_6">
|
||||
<item>
|
||||
<widget class="QPushButton" name="clear_button">
|
||||
@ -244,7 +244,7 @@
|
||||
</item>
|
||||
</layout>
|
||||
</item>
|
||||
<item row="6" column="1">
|
||||
<item row="7" column="1">
|
||||
<spacer name="verticalSpacer">
|
||||
<property name="orientation">
|
||||
<enum>Qt::Vertical</enum>
|
||||
@ -283,14 +283,14 @@
|
||||
<item row="3" column="1">
|
||||
<widget class="EnLineEdit" name="price_box"/>
|
||||
</item>
|
||||
<item row="5" column="0">
|
||||
<item row="6" column="0">
|
||||
<widget class="QLabel" name="label_9">
|
||||
<property name="text">
|
||||
<string>Affiliate:</string>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item row="5" column="1">
|
||||
<item row="6" column="1">
|
||||
<widget class="QComboBox" name="affiliate_combo">
|
||||
<item>
|
||||
<property name="text">
|
||||
@ -309,6 +309,32 @@
|
||||
</item>
|
||||
</widget>
|
||||
</item>
|
||||
<item row="5" column="0">
|
||||
<widget class="QLabel" name="label_12">
|
||||
<property name="text">
|
||||
<string>Download:</string>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item row="5" column="1">
|
||||
<widget class="QComboBox" name="download_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>
|
||||
|
@ -33,7 +33,7 @@ class Matches(QAbstractItemModel):
|
||||
|
||||
total_changed = pyqtSignal(int)
|
||||
|
||||
HEADERS = [_('Cover'), _('Title'), _('Price'), _('DRM'), _('Store'), '']
|
||||
HEADERS = [_('Cover'), _('Title'), _('Price'), _('DRM'), _('Store'), _('Download'), _('Affiliate')]
|
||||
HTML_COLS = (1, 4)
|
||||
|
||||
def __init__(self, cover_thread_count=2, detail_thread_count=4):
|
||||
@ -47,6 +47,8 @@ class Matches(QAbstractItemModel):
|
||||
Qt.SmoothTransformation)
|
||||
self.DONATE_ICON = QPixmap(I('donate.png')).scaledToHeight(16,
|
||||
Qt.SmoothTransformation)
|
||||
self.DOWNLOAD_ICON = QPixmap(I('arrow-down.png')).scaledToHeight(16,
|
||||
Qt.SmoothTransformation)
|
||||
|
||||
# All matches. Used to determine the order to display
|
||||
# self.matches because the SearchFilter returns
|
||||
@ -181,9 +183,11 @@ class Matches(QAbstractItemModel):
|
||||
elif result.drm == SearchResult.DRM_UNKNOWN:
|
||||
return QVariant(self.DRM_UNKNOWN_ICON)
|
||||
if col == 5:
|
||||
if result.downloads:
|
||||
return QVariant(self.DOWNLOAD_ICON)
|
||||
if col == 6:
|
||||
if result.affiliate:
|
||||
return QVariant(self.DONATE_ICON)
|
||||
return NONE
|
||||
elif role == Qt.ToolTipRole:
|
||||
if col == 1:
|
||||
return QVariant('<p>%s</p>' % result.title)
|
||||
@ -199,6 +203,9 @@ class Matches(QAbstractItemModel):
|
||||
elif col == 4:
|
||||
return QVariant('<p>%s</p>' % result.formats)
|
||||
elif col == 5:
|
||||
if result.downloads:
|
||||
return QVariant('<p>' + _('The following formats can be downloaded directly: %s.') % ', '.join(result.downloads.keys()) + '</p>')
|
||||
elif col == 6:
|
||||
if result.affiliate:
|
||||
return QVariant('<p>' + _('Buying from this store supports the calibre developer: %s.') % result.plugin_author + '</p>')
|
||||
elif role == Qt.SizeHintRole:
|
||||
@ -221,6 +228,11 @@ class Matches(QAbstractItemModel):
|
||||
elif col == 4:
|
||||
text = result.store_name
|
||||
elif col == 5:
|
||||
if result.downloads:
|
||||
text = 'a'
|
||||
else:
|
||||
text = 'b'
|
||||
elif col == 6:
|
||||
if result.affiliate:
|
||||
text = 'a'
|
||||
else:
|
||||
@ -257,6 +269,8 @@ class SearchFilter(SearchQueryParser):
|
||||
'author',
|
||||
'authors',
|
||||
'cover',
|
||||
'download',
|
||||
'downloads',
|
||||
'drm',
|
||||
'format',
|
||||
'formats',
|
||||
@ -282,6 +296,8 @@ class SearchFilter(SearchQueryParser):
|
||||
location = location.lower().strip()
|
||||
if location == 'authors':
|
||||
location = 'author'
|
||||
elif location == 'downloads':
|
||||
location = 'download'
|
||||
elif location == 'formats':
|
||||
location = 'format'
|
||||
|
||||
@ -308,12 +324,13 @@ class SearchFilter(SearchQueryParser):
|
||||
'author': lambda x: x.author.lower(),
|
||||
'cover': attrgetter('cover_url'),
|
||||
'drm': attrgetter('drm'),
|
||||
'download': attrgetter('downloads'),
|
||||
'format': attrgetter('formats'),
|
||||
'price': lambda x: comparable_price(x.price),
|
||||
'store': lambda x: x.store_name.lower(),
|
||||
'title': lambda x: x.title.lower(),
|
||||
}
|
||||
for x in ('author', 'format'):
|
||||
for x in ('author', 'download', 'format'):
|
||||
q[x+'s'] = q[x]
|
||||
for sr in self.srs:
|
||||
for locvalue in locations:
|
||||
@ -347,7 +364,7 @@ class SearchFilter(SearchQueryParser):
|
||||
matches.add(sr)
|
||||
continue
|
||||
# this is bool or treated as bool, so can't match below.
|
||||
if locvalue in ('affiliate', 'drm'):
|
||||
if locvalue in ('affiliate', 'drm', 'download', 'downloads'):
|
||||
continue
|
||||
try:
|
||||
### Can't separate authors because comma is used for name sep and author sep
|
||||
|
@ -6,13 +6,18 @@ __license__ = 'GPL 3'
|
||||
__copyright__ = '2011, John Schember <john@nachtimwald.com>'
|
||||
__docformat__ = 'restructuredtext en'
|
||||
|
||||
from PyQt4.Qt import (QTreeView)
|
||||
from functools import partial
|
||||
|
||||
from PyQt4.Qt import (pyqtSignal, QMenu, QTreeView)
|
||||
|
||||
from calibre.gui2.metadata.single_download import RichTextDelegate
|
||||
from calibre.gui2.store.search.models import Matches
|
||||
|
||||
class ResultsView(QTreeView):
|
||||
|
||||
download_requested = pyqtSignal(object)
|
||||
open_requested = pyqtSignal(object)
|
||||
|
||||
def __init__(self, *args):
|
||||
QTreeView.__init__(self,*args)
|
||||
|
||||
@ -24,3 +29,18 @@ class ResultsView(QTreeView):
|
||||
for i in self._model.HTML_COLS:
|
||||
self.setItemDelegateForColumn(i, self.rt_delegate)
|
||||
|
||||
def contextMenuEvent(self, event):
|
||||
index = self.indexAt(event.pos())
|
||||
|
||||
if not index.isValid():
|
||||
return
|
||||
|
||||
result = self.model().get_result(index)
|
||||
|
||||
menu = QMenu()
|
||||
da = menu.addAction(_('Download...'), partial(self.download_requested.emit, result))
|
||||
if not result.downloads:
|
||||
da.setEnabled(False)
|
||||
menu.addSeparator()
|
||||
menu.addAction(_('Goto in store...'), partial(self.open_requested.emit, result))
|
||||
menu.exec_(event.globalPos())
|
||||
|
@ -14,6 +14,7 @@ from PyQt4.Qt import (Qt, QDialog, QDialogButtonBox, QTimer, QCheckBox, QLabel,
|
||||
QComboBox)
|
||||
|
||||
from calibre.gui2 import JSONConfig, info_dialog
|
||||
from calibre.gui2.dialogs.choose_format import ChooseFormatDialog
|
||||
from calibre.gui2.progress_indicator import ProgressIndicator
|
||||
from calibre.gui2.store.config.chooser.chooser_widget import StoreChooserWidget
|
||||
from calibre.gui2.store.config.search.search_widget import StoreConfigWidget
|
||||
@ -72,7 +73,9 @@ class SearchDialog(QDialog, Ui_Dialog):
|
||||
self.search.clicked.connect(self.do_search)
|
||||
self.checker.timeout.connect(self.get_results)
|
||||
self.progress_checker.timeout.connect(self.check_progress)
|
||||
self.results_view.activated.connect(self.open_store)
|
||||
self.results_view.activated.connect(self.result_item_activated)
|
||||
self.results_view.download_requested.connect(self.download_book)
|
||||
self.results_view.open_requested.connect(self.open_store)
|
||||
self.results_view.model().total_changed.connect(self.update_book_total)
|
||||
self.select_all_stores.clicked.connect(self.stores_select_all)
|
||||
self.select_invert_stores.clicked.connect(self.stores_select_invert)
|
||||
@ -129,11 +132,15 @@ class SearchDialog(QDialog, Ui_Dialog):
|
||||
# Title / Author
|
||||
self.results_view.setColumnWidth(1,int(total*.40))
|
||||
# Price
|
||||
self.results_view.setColumnWidth(2,int(total*.20))
|
||||
self.results_view.setColumnWidth(2,int(total*.12))
|
||||
# DRM
|
||||
self.results_view.setColumnWidth(3, int(total*.15))
|
||||
# Store / Formats
|
||||
self.results_view.setColumnWidth(4, int(total*.25))
|
||||
# Download
|
||||
self.results_view.setColumnWidth(5, 20)
|
||||
# Affiliate
|
||||
self.results_view.setColumnWidth(6, 20)
|
||||
|
||||
def do_search(self):
|
||||
# Stop all running threads.
|
||||
@ -183,7 +190,7 @@ class SearchDialog(QDialog, Ui_Dialog):
|
||||
query = re.sub(r'%s:"(?P<a>[^\s"]+)"' % loc, '\g<a>', query)
|
||||
query = query.replace('%s:' % loc, '')
|
||||
# Remove the prefix and search text.
|
||||
for loc in ('cover', 'drm', 'format', 'formats', 'price', 'store'):
|
||||
for loc in ('cover', 'download', 'downloads', 'drm', 'format', 'formats', 'price', 'store'):
|
||||
query = re.sub(r'%s:"[^"]"' % loc, '', query)
|
||||
query = re.sub(r'%s:[^\s]*' % loc, '', query)
|
||||
# Remove logic.
|
||||
@ -330,8 +337,21 @@ class SearchDialog(QDialog, Ui_Dialog):
|
||||
def update_book_total(self, total):
|
||||
self.total.setText('%s' % total)
|
||||
|
||||
def open_store(self, index):
|
||||
def result_item_activated(self, index):
|
||||
result = self.results_view.model().get_result(index)
|
||||
|
||||
if result.downloads:
|
||||
self.download_book(result)
|
||||
else:
|
||||
self.open_store(result)
|
||||
|
||||
def download_book(self, result):
|
||||
d = ChooseFormatDialog(self, _('Choose format to download to your library.'), result.downloads.keys())
|
||||
if d.exec_() == d.Accepted:
|
||||
ext = d.format()
|
||||
self.gui.download_ebook(result.downloads[ext])
|
||||
|
||||
def open_store(self, result):
|
||||
self.gui.istores[result.store_name].open(self, result.detail_item, self.open_external.isChecked())
|
||||
|
||||
def check_progress(self):
|
||||
|
@ -22,6 +22,9 @@ class SearchResult(object):
|
||||
self.detail_item = ''
|
||||
self.drm = None
|
||||
self.formats = ''
|
||||
# key = format in upper case.
|
||||
# value = url to download the file.
|
||||
self.downloads = {}
|
||||
self.affiliate = False
|
||||
self.plugin_author = ''
|
||||
|
||||
|
3
src/calibre/gui2/store/stores/__init__.py
Normal file
3
src/calibre/gui2/store/stores/__init__.py
Normal file
@ -0,0 +1,3 @@
|
||||
'''
|
||||
All store plugins are placed here.
|
||||
'''
|
43
src/calibre/gui2/store/stores/archive_org_plugin.py
Normal file
43
src/calibre/gui2/store/stores/archive_org_plugin.py
Normal file
@ -0,0 +1,43 @@
|
||||
# -*- 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 contextlib import closing
|
||||
|
||||
from lxml import html
|
||||
|
||||
from calibre import browser
|
||||
from calibre.gui2.store.basic_config import BasicStoreConfig
|
||||
from calibre.gui2.store.opensearch_store import OpenSearchStore
|
||||
from calibre.gui2.store.search_result import SearchResult
|
||||
|
||||
class ArchiveOrgStore(BasicStoreConfig, OpenSearchStore):
|
||||
|
||||
open_search_url = 'http://bookserver.archive.org/catalog/opensearch.xml'
|
||||
web_url = 'http://www.archive.org/details/texts'
|
||||
|
||||
# http://bookserver.archive.org/catalog/
|
||||
|
||||
def search(self, query, max_results=10, timeout=60):
|
||||
for s in OpenSearchStore.search(self, query, max_results, timeout):
|
||||
s.detail_item = 'http://www.archive.org/details/' + s.detail_item.split(':')[-1]
|
||||
s.price = '$0.00'
|
||||
s.drm = SearchResult.DRM_UNLOCKED
|
||||
yield s
|
||||
|
||||
def get_details(self, search_result, timeout):
|
||||
'''
|
||||
The opensearch feed only returns a subset of formats that are available.
|
||||
We want to get a list of all formats that the user can get.
|
||||
'''
|
||||
br = browser()
|
||||
with closing(br.open(search_result.detail_item, timeout=timeout)) as nf:
|
||||
idata = html.fromstring(nf.read())
|
||||
formats = ', '.join(idata.xpath('//p[@id="dl" and @class="content"]//a/text()'))
|
||||
search_result.formats = formats.upper()
|
||||
|
||||
return True
|
27
src/calibre/gui2/store/stores/epubbud_plugin.py
Normal file
27
src/calibre/gui2/store/stores/epubbud_plugin.py
Normal file
@ -0,0 +1,27 @@
|
||||
# -*- 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 calibre.gui2.store.basic_config import BasicStoreConfig
|
||||
from calibre.gui2.store.opensearch_store import OpenSearchStore
|
||||
from calibre.gui2.store.search_result import SearchResult
|
||||
|
||||
class EpubBudStore(BasicStoreConfig, OpenSearchStore):
|
||||
|
||||
open_search_url = 'http://www.epubbud.com/feeds/opensearch.xml'
|
||||
web_url = 'http://www.epubbud.com/'
|
||||
|
||||
# http://www.epubbud.com/feeds/catalog.atom
|
||||
|
||||
def search(self, query, max_results=10, timeout=60):
|
||||
for s in OpenSearchStore.search(self, query, max_results, timeout):
|
||||
s.price = '$0.00'
|
||||
s.drm = SearchResult.DRM_UNLOCKED
|
||||
s.formats = 'EPUB'
|
||||
# Download links are broken for this store.
|
||||
s.downloads = {}
|
||||
yield s
|
28
src/calibre/gui2/store/stores/feedbooks_plugin.py
Normal file
28
src/calibre/gui2/store/stores/feedbooks_plugin.py
Normal 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 calibre.gui2.store.basic_config import BasicStoreConfig
|
||||
from calibre.gui2.store.opensearch_store import OpenSearchStore
|
||||
from calibre.gui2.store.search_result import SearchResult
|
||||
|
||||
class FeedbooksStore(BasicStoreConfig, OpenSearchStore):
|
||||
|
||||
open_search_url = 'http://assets0.feedbooks.net/opensearch.xml?t=1253087147'
|
||||
web_url = 'http://feedbooks.com/'
|
||||
|
||||
# http://www.feedbooks.com/catalog
|
||||
|
||||
def search(self, query, max_results=10, timeout=60):
|
||||
for s in OpenSearchStore.search(self, query, max_results, timeout):
|
||||
if s.downloads:
|
||||
s.drm = SearchResult.DRM_UNLOCKED
|
||||
s.price = '$0.00'
|
||||
else:
|
||||
s.drm = SearchResult.DRM_LOCKED
|
||||
s.formats = 'EPUB'
|
||||
yield s
|
119
src/calibre/gui2/store/stores/mobileread/adv_search_builder.py
Normal file
119
src/calibre/gui2/store/stores/mobileread/adv_search_builder.py
Normal file
@ -0,0 +1,119 @@
|
||||
# -*- 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.stores.mobileread.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.title_box.setText('')
|
||||
self.author_box.setText('')
|
||||
self.format_box.setText('')
|
||||
|
||||
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 = {}
|
||||
title = unicode(self.title_box.text()).strip()
|
||||
if title:
|
||||
ans.append('title:"' + self.mc + title + '"')
|
||||
author = unicode(self.author_box.text()).strip()
|
||||
if author:
|
||||
ans.append('author:"' + self.mc + author + '"')
|
||||
format = unicode(self.format_box.text()).strip()
|
||||
if format:
|
||||
ans.append('format:"' + self.mc + format + '"')
|
||||
if ans:
|
||||
return ' and '.join(ans)
|
||||
return ''
|
350
src/calibre/gui2/store/stores/mobileread/adv_search_builder.ui
Normal file
350
src/calibre/gui2/store/stores/mobileread/adv_search_builder.ui
Normal file
@ -0,0 +1,350 @@
|
||||
<?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>&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&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>&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 &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>&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 &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 <a href="http://calibre-ebook.com/user_manual/gui.html#the-search-interface">User Manual</a> 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>Titl&e/Author/Price ...</string>
|
||||
</attribute>
|
||||
<layout class="QGridLayout" name="gridLayout">
|
||||
<item row="1" column="0">
|
||||
<widget class="QLabel" name="label_7">
|
||||
<property name="text">
|
||||
<string>&Title:</string>
|
||||
</property>
|
||||
<property name="buddy">
|
||||
<cstring>title_box</cstring>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item row="1" column="1">
|
||||
<widget class="EnLineEdit" name="title_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>&Author:</string>
|
||||
</property>
|
||||
<property name="buddy">
|
||||
<cstring>author_box</cstring>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item row="5" column="0" colspan="2">
|
||||
<layout class="QHBoxLayout" name="horizontalLayout_6">
|
||||
<item>
|
||||
<widget class="QPushButton" name="clear_button">
|
||||
<property name="text">
|
||||
<string>&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="4" 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="author_box"/>
|
||||
</item>
|
||||
<item row="3" column="1">
|
||||
<widget class="QLineEdit" name="format_box"/>
|
||||
</item>
|
||||
<item row="3" column="0">
|
||||
<widget class="QLabel" name="label_10">
|
||||
<property name="text">
|
||||
<string>&Format:</string>
|
||||
</property>
|
||||
<property name="buddy">
|
||||
<cstring>format_box</cstring>
|
||||
</property>
|
||||
</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>title_box</tabstop>
|
||||
<tabstop>author_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>
|
@ -0,0 +1,62 @@
|
||||
# -*- 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
|
||||
|
||||
from calibre.gui2.store.stores.mobileread.cache_progress_dialog_ui import Ui_Dialog
|
||||
|
||||
class CacheProgressDialog(QDialog, Ui_Dialog):
|
||||
|
||||
def __init__(self, parent=None, total=None):
|
||||
QDialog.__init__(self, parent)
|
||||
self.setupUi(self)
|
||||
|
||||
self.completed = 0
|
||||
self.canceled = False
|
||||
|
||||
self.progress.setValue(0)
|
||||
self.progress.setMinimum(0)
|
||||
self.progress.setMaximum(total if total else 0)
|
||||
|
||||
def exec_(self):
|
||||
self.completed = 0
|
||||
self.canceled = False
|
||||
QDialog.exec_(self)
|
||||
|
||||
def open(self):
|
||||
self.completed = 0
|
||||
self.canceled = False
|
||||
QDialog.open(self)
|
||||
|
||||
def reject(self):
|
||||
self.canceled = True
|
||||
QDialog.reject(self)
|
||||
|
||||
def update_progress(self):
|
||||
'''
|
||||
completed is an int from 0 to total representing the number
|
||||
records that have bee completed.
|
||||
'''
|
||||
self.set_progress(self.completed + 1)
|
||||
|
||||
def set_message(self, msg):
|
||||
self.message.setText(msg)
|
||||
|
||||
def set_details(self, msg):
|
||||
self.details.setText(msg)
|
||||
|
||||
def set_progress(self, completed):
|
||||
'''
|
||||
completed is an int from 0 to total representing the number
|
||||
records that have bee completed.
|
||||
'''
|
||||
self.completed = completed
|
||||
self.progress.setValue(self.completed)
|
||||
|
||||
def set_total(self, total):
|
||||
self.progress.setMaximum(total)
|
@ -0,0 +1,104 @@
|
||||
<?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>402</width>
|
||||
<height>138</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="windowTitle">
|
||||
<string>Dialog</string>
|
||||
</property>
|
||||
<layout class="QVBoxLayout" name="verticalLayout">
|
||||
<item>
|
||||
<widget class="QLabel" name="message">
|
||||
<property name="text">
|
||||
<string>Updating book cache</string>
|
||||
</property>
|
||||
<property name="alignment">
|
||||
<set>Qt::AlignCenter</set>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QProgressBar" name="progress">
|
||||
<property name="value">
|
||||
<number>24</number>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QLabel" name="details">
|
||||
<property name="text">
|
||||
<string/>
|
||||
</property>
|
||||
<property name="alignment">
|
||||
<set>Qt::AlignCenter</set>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<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>
|
||||
<widget class="QDialogButtonBox" name="buttonBox">
|
||||
<property name="orientation">
|
||||
<enum>Qt::Horizontal</enum>
|
||||
</property>
|
||||
<property name="standardButtons">
|
||||
<set>QDialogButtonBox::Cancel</set>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
</layout>
|
||||
</widget>
|
||||
<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>
|
@ -0,0 +1,94 @@
|
||||
# -*- 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 time
|
||||
from contextlib import closing
|
||||
from threading import Thread
|
||||
|
||||
from lxml import html
|
||||
|
||||
from PyQt4.Qt import (pyqtSignal, QObject)
|
||||
|
||||
from calibre import browser
|
||||
from calibre.gui2.store.search_result import SearchResult
|
||||
|
||||
class CacheUpdateThread(Thread, QObject):
|
||||
|
||||
total_changed = pyqtSignal(int)
|
||||
update_progress = pyqtSignal(int)
|
||||
update_details = pyqtSignal(unicode)
|
||||
|
||||
def __init__(self, config, seralize_books_function, timeout):
|
||||
Thread.__init__(self)
|
||||
QObject.__init__(self)
|
||||
|
||||
self.daemon = True
|
||||
self.config = config
|
||||
self.seralize_books = seralize_books_function
|
||||
self.timeout = timeout
|
||||
self._run = True
|
||||
|
||||
def abort(self):
|
||||
self._run = False
|
||||
|
||||
def run(self):
|
||||
url = 'http://www.mobileread.com/forums/ebooks.php?do=getlist&type=html'
|
||||
|
||||
self.update_details.emit(_('Checking last download date.'))
|
||||
last_download = self.config.get('last_download', None)
|
||||
# Don't update the book list if our cache is less than one week old.
|
||||
if last_download and (time.time() - last_download) < 604800:
|
||||
return
|
||||
|
||||
self.update_details.emit(_('Downloading book list from MobileRead.'))
|
||||
# Download the book list HTML file from MobileRead.
|
||||
br = browser()
|
||||
raw_data = None
|
||||
try:
|
||||
with closing(br.open(url, timeout=self.timeout)) as f:
|
||||
raw_data = f.read()
|
||||
except:
|
||||
return
|
||||
|
||||
if not raw_data or not self._run:
|
||||
return
|
||||
|
||||
self.update_details.emit(_('Processing books.'))
|
||||
# Turn books listed in the HTML file into SearchResults's.
|
||||
books = []
|
||||
try:
|
||||
data = html.fromstring(raw_data)
|
||||
raw_books = data.xpath('//ul/li')
|
||||
self.total_changed.emit(len(raw_books))
|
||||
|
||||
for i, book_data in enumerate(raw_books):
|
||||
self.update_details.emit(_('%s of %s books processed.') % (i, len(raw_books)))
|
||||
book = SearchResult()
|
||||
book.detail_item = ''.join(book_data.xpath('.//a/@href'))
|
||||
book.formats = ''.join(book_data.xpath('.//i/text()'))
|
||||
book.formats = book.formats.strip()
|
||||
|
||||
text = ''.join(book_data.xpath('.//a/text()'))
|
||||
if ':' in text:
|
||||
book.author, q, text = text.partition(':')
|
||||
book.author = book.author.strip()
|
||||
book.title = text.strip()
|
||||
books.append(book)
|
||||
|
||||
if not self._run:
|
||||
books = []
|
||||
break
|
||||
else:
|
||||
self.update_progress.emit(i)
|
||||
except:
|
||||
pass
|
||||
|
||||
# Save the book list and it's create time.
|
||||
if books:
|
||||
self.config['book_list'] = self.seralize_books(books)
|
||||
self.config['last_download'] = time.time()
|
105
src/calibre/gui2/store/stores/mobileread/mobileread_plugin.py
Normal file
105
src/calibre/gui2/store/stores/mobileread/mobileread_plugin.py
Normal file
@ -0,0 +1,105 @@
|
||||
# -*- 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 threading import Lock
|
||||
|
||||
from PyQt4.Qt import (QUrl, QCoreApplication)
|
||||
|
||||
from calibre.gui2 import open_url
|
||||
from calibre.gui2.store import StorePlugin
|
||||
from calibre.gui2.store.basic_config import BasicStoreConfig
|
||||
from calibre.gui2.store.search_result import SearchResult
|
||||
from calibre.gui2.store.web_store_dialog import WebStoreDialog
|
||||
from calibre.gui2.store.stores.mobileread.models import SearchFilter
|
||||
from calibre.gui2.store.stores.mobileread.cache_progress_dialog import CacheProgressDialog
|
||||
from calibre.gui2.store.stores.mobileread.cache_update_thread import CacheUpdateThread
|
||||
from calibre.gui2.store.stores.mobileread.store_dialog import MobileReadStoreDialog
|
||||
|
||||
class MobileReadStore(BasicStoreConfig, StorePlugin):
|
||||
|
||||
def genesis(self):
|
||||
self.lock = Lock()
|
||||
|
||||
def open(self, parent=None, detail_item=None, external=False):
|
||||
url = 'http://www.mobileread.com/'
|
||||
|
||||
if external or self.config.get('open_external', False):
|
||||
open_url(QUrl(detail_item if detail_item else url))
|
||||
else:
|
||||
if detail_item:
|
||||
d = WebStoreDialog(self.gui, url, parent, detail_item)
|
||||
d.setWindowTitle(self.name)
|
||||
d.set_tags(self.config.get('tags', ''))
|
||||
d.exec_()
|
||||
else:
|
||||
self.update_cache(parent, 30)
|
||||
d = MobileReadStoreDialog(self, parent)
|
||||
d.setWindowTitle(self.name)
|
||||
d.exec_()
|
||||
|
||||
def search(self, query, max_results=10, timeout=60):
|
||||
books = self.get_book_list()
|
||||
|
||||
sf = SearchFilter(books)
|
||||
matches = sf.parse(query)
|
||||
|
||||
for book in matches:
|
||||
book.price = '$0.00'
|
||||
book.drm = SearchResult.DRM_UNLOCKED
|
||||
yield book
|
||||
|
||||
def update_cache(self, parent=None, timeout=10, force=False, suppress_progress=False):
|
||||
if self.lock.acquire(False):
|
||||
try:
|
||||
update_thread = CacheUpdateThread(self.config, self.seralize_books, timeout)
|
||||
if not suppress_progress:
|
||||
progress = CacheProgressDialog(parent)
|
||||
progress.set_message(_('Updating MobileRead book cache...'))
|
||||
|
||||
update_thread.total_changed.connect(progress.set_total)
|
||||
update_thread.update_progress.connect(progress.set_progress)
|
||||
update_thread.update_details.connect(progress.set_details)
|
||||
progress.rejected.connect(update_thread.abort)
|
||||
|
||||
progress.open()
|
||||
update_thread.start()
|
||||
while update_thread.is_alive() and not progress.canceled:
|
||||
QCoreApplication.processEvents()
|
||||
|
||||
if progress.isVisible():
|
||||
progress.accept()
|
||||
return not progress.canceled
|
||||
else:
|
||||
update_thread.start()
|
||||
finally:
|
||||
self.lock.release()
|
||||
|
||||
def get_book_list(self):
|
||||
return self.deseralize_books(self.config.get('book_list', []))
|
||||
|
||||
def seralize_books(self, books):
|
||||
sbooks = []
|
||||
for b in books:
|
||||
data = {}
|
||||
data['author'] = b.author
|
||||
data['title'] = b.title
|
||||
data['detail_item'] = b.detail_item
|
||||
data['formats'] = b.formats
|
||||
sbooks.append(data)
|
||||
return sbooks
|
||||
|
||||
def deseralize_books(self, sbooks):
|
||||
books = []
|
||||
for s in sbooks:
|
||||
b = SearchResult()
|
||||
b.author = s.get('author', '')
|
||||
b.title = s.get('title', '')
|
||||
b.detail_item = s.get('detail_item', '')
|
||||
b.formats = s.get('formats', '')
|
||||
books.append(b)
|
||||
return books
|
191
src/calibre/gui2/store/stores/mobileread/models.py
Normal file
191
src/calibre/gui2/store/stores/mobileread/models.py
Normal file
@ -0,0 +1,191 @@
|
||||
# -*- 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 operator import attrgetter
|
||||
|
||||
from PyQt4.Qt import (Qt, QAbstractItemModel, QModelIndex, QVariant, pyqtSignal)
|
||||
|
||||
from calibre.gui2 import NONE
|
||||
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 BooksModel(QAbstractItemModel):
|
||||
|
||||
total_changed = pyqtSignal(int)
|
||||
|
||||
HEADERS = [_('Title'), _('Author(s)'), _('Format')]
|
||||
|
||||
def __init__(self, all_books):
|
||||
QAbstractItemModel.__init__(self)
|
||||
self.books = all_books
|
||||
self.all_books = all_books
|
||||
self.filter = ''
|
||||
self.search_filter = SearchFilter(all_books)
|
||||
self.sort_col = 0
|
||||
self.sort_order = Qt.AscendingOrder
|
||||
|
||||
def get_book(self, index):
|
||||
row = index.row()
|
||||
if row < len(self.books):
|
||||
return self.books[row]
|
||||
else:
|
||||
return None
|
||||
|
||||
def search(self, filter):
|
||||
self.filter = filter.strip()
|
||||
if not self.filter:
|
||||
self.books = self.all_books
|
||||
else:
|
||||
try:
|
||||
self.books = list(self.search_filter.parse(self.filter))
|
||||
except:
|
||||
self.books = self.all_books
|
||||
self.layoutChanged.emit()
|
||||
self.sort(self.sort_col, self.sort_order)
|
||||
self.total_changed.emit(self.rowCount())
|
||||
|
||||
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.books)
|
||||
|
||||
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.books[row]
|
||||
if role == Qt.DisplayRole:
|
||||
if col == 0:
|
||||
return QVariant(result.title)
|
||||
elif col == 1:
|
||||
return QVariant(result.author)
|
||||
elif col == 2:
|
||||
return QVariant(result.formats)
|
||||
return NONE
|
||||
|
||||
def data_as_text(self, result, col):
|
||||
text = ''
|
||||
if col == 0:
|
||||
text = result.title
|
||||
elif col == 1:
|
||||
text = result.author
|
||||
elif col == 2:
|
||||
text = result.formats
|
||||
return text
|
||||
|
||||
def sort(self, col, order, reset=True):
|
||||
self.sort_col = col
|
||||
self.sort_order = order
|
||||
if not self.books:
|
||||
return
|
||||
descending = order == Qt.DescendingOrder
|
||||
self.books.sort(None,
|
||||
lambda x: sort_key(unicode(self.data_as_text(x, col))),
|
||||
descending)
|
||||
if reset:
|
||||
self.reset()
|
||||
|
||||
|
||||
class SearchFilter(SearchQueryParser):
|
||||
|
||||
USABLE_LOCATIONS = [
|
||||
'all',
|
||||
'author',
|
||||
'authors',
|
||||
'format',
|
||||
'formats',
|
||||
'title',
|
||||
]
|
||||
|
||||
def __init__(self, all_books=[]):
|
||||
SearchQueryParser.__init__(self, locations=self.USABLE_LOCATIONS)
|
||||
self.srs = set(all_books)
|
||||
|
||||
def universal_set(self):
|
||||
return self.srs
|
||||
|
||||
def get_matches(self, location, query):
|
||||
location = location.lower().strip()
|
||||
if location == 'authors':
|
||||
location = 'author'
|
||||
elif 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 = {
|
||||
'author': lambda x: x.author.lower(),
|
||||
'format': attrgetter('formats'),
|
||||
'title': lambda x: x.title.lower(),
|
||||
}
|
||||
for x in ('author', 'format'):
|
||||
q[x+'s'] = q[x]
|
||||
for sr in self.srs:
|
||||
for locvalue in locations:
|
||||
accessor = q[locvalue]
|
||||
if query == 'true':
|
||||
if accessor(sr) is not None:
|
||||
matches.add(sr)
|
||||
continue
|
||||
if query == 'false':
|
||||
if accessor(sr) is None:
|
||||
matches.add(sr)
|
||||
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 == 'author' and matchkind == EQUALS_MATCH:
|
||||
m = CONTAINS_MATCH
|
||||
else:
|
||||
m = matchkind
|
||||
|
||||
vals = [accessor(sr)]
|
||||
if _match(query, vals, m):
|
||||
matches.add(sr)
|
||||
break
|
||||
except ValueError: # Unicode errors
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
return matches
|
84
src/calibre/gui2/store/stores/mobileread/store_dialog.py
Normal file
84
src/calibre/gui2/store/stores/mobileread/store_dialog.py
Normal file
@ -0,0 +1,84 @@
|
||||
# -*- 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, QDialog, QIcon, QComboBox)
|
||||
|
||||
from calibre.gui2.store.stores.mobileread.adv_search_builder import AdvSearchBuilderDialog
|
||||
from calibre.gui2.store.stores.mobileread.models import BooksModel
|
||||
from calibre.gui2.store.stores.mobileread.store_dialog_ui import Ui_Dialog
|
||||
|
||||
class MobileReadStoreDialog(QDialog, Ui_Dialog):
|
||||
|
||||
def __init__(self, plugin, *args):
|
||||
QDialog.__init__(self, *args)
|
||||
self.setupUi(self)
|
||||
|
||||
self.plugin = plugin
|
||||
self.search_query.initialize('store_mobileread_search')
|
||||
self.search_query.setSizeAdjustPolicy(QComboBox.AdjustToMinimumContentsLengthWithIcon)
|
||||
self.search_query.setMinimumContentsLength(25)
|
||||
|
||||
self.adv_search_button.setIcon(QIcon(I('search.png')))
|
||||
|
||||
self._model = BooksModel(self.plugin.get_book_list())
|
||||
self.results_view.setModel(self._model)
|
||||
self.total.setText('%s' % self.results_view.model().rowCount())
|
||||
|
||||
self.search_button.clicked.connect(self.do_search)
|
||||
self.adv_search_button.clicked.connect(self.build_adv_search)
|
||||
self.results_view.activated.connect(self.open_store)
|
||||
self.results_view.model().total_changed.connect(self.update_book_total)
|
||||
self.finished.connect(self.dialog_closed)
|
||||
|
||||
self.restore_state()
|
||||
|
||||
def do_search(self):
|
||||
self.results_view.model().search(unicode(self.search_query.text()))
|
||||
|
||||
def open_store(self, index):
|
||||
result = self.results_view.model().get_book(index)
|
||||
if result:
|
||||
self.plugin.open(self, result.detail_item)
|
||||
|
||||
def update_book_total(self, total):
|
||||
self.total.setText('%s' % total)
|
||||
|
||||
def build_adv_search(self):
|
||||
adv = AdvSearchBuilderDialog(self)
|
||||
if adv.exec_() == QDialog.Accepted:
|
||||
self.search_query.setText(adv.search_string())
|
||||
|
||||
def restore_state(self):
|
||||
geometry = self.plugin.config.get('dialog_geometry', None)
|
||||
if geometry:
|
||||
self.restoreGeometry(geometry)
|
||||
|
||||
results_cwidth = self.plugin.config.get('dialog_results_view_column_width')
|
||||
if results_cwidth:
|
||||
for i, x in enumerate(results_cwidth):
|
||||
if i >= self.results_view.model().columnCount():
|
||||
break
|
||||
self.results_view.setColumnWidth(i, x)
|
||||
else:
|
||||
for i in xrange(self.results_view.model().columnCount()):
|
||||
self.results_view.resizeColumnToContents(i)
|
||||
|
||||
self.results_view.model().sort_col = self.plugin.config.get('dialog_sort_col', 0)
|
||||
self.results_view.model().sort_order = self.plugin.config.get('dialog_sort_order', Qt.AscendingOrder)
|
||||
self.results_view.model().sort(self.results_view.model().sort_col, self.results_view.model().sort_order)
|
||||
self.results_view.header().setSortIndicator(self.results_view.model().sort_col, self.results_view.model().sort_order)
|
||||
|
||||
def save_state(self):
|
||||
self.plugin.config['dialog_geometry'] = bytearray(self.saveGeometry())
|
||||
self.plugin.config['dialog_results_view_column_width'] = [self.results_view.columnWidth(i) for i in range(self.results_view.model().columnCount())]
|
||||
self.plugin.config['dialog_sort_col'] = self.results_view.model().sort_col
|
||||
self.plugin.config['dialog_sort_order'] = self.results_view.model().sort_order
|
||||
|
||||
def dialog_closed(self, result):
|
||||
self.save_state()
|
143
src/calibre/gui2/store/stores/mobileread/store_dialog.ui
Normal file
143
src/calibre/gui2/store/stores/mobileread/store_dialog.ui
Normal file
@ -0,0 +1,143 @@
|
||||
<?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>691</width>
|
||||
<height>614</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="windowTitle">
|
||||
<string>Dialog</string>
|
||||
</property>
|
||||
<layout class="QVBoxLayout" name="verticalLayout">
|
||||
<item>
|
||||
<layout class="QHBoxLayout" name="horizontalLayout_2">
|
||||
<item>
|
||||
<widget class="QLabel" name="label">
|
||||
<property name="text">
|
||||
<string>&Query:</string>
|
||||
</property>
|
||||
<property name="buddy">
|
||||
<cstring>search_query</cstring>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QToolButton" name="adv_search_button">
|
||||
<property name="text">
|
||||
<string>...</string>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="HistoryLineEdit" name="search_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_button">
|
||||
<property name="text">
|
||||
<string>Search</string>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
</layout>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QTreeView" name="results_view">
|
||||
<property name="alternatingRowColors">
|
||||
<bool>true</bool>
|
||||
</property>
|
||||
<property name="rootIsDecorated">
|
||||
<bool>false</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="headerCascadingSectionResizes">
|
||||
<bool>false</bool>
|
||||
</attribute>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<layout class="QHBoxLayout" name="horizontalLayout">
|
||||
<item>
|
||||
<widget class="QLabel" name="label_2">
|
||||
<property name="text">
|
||||
<string>Books:</string>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QLabel" name="total">
|
||||
<property name="text">
|
||||
<string>0</string>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<spacer name="horizontalSpacer">
|
||||
<property name="orientation">
|
||||
<enum>Qt::Horizontal</enum>
|
||||
</property>
|
||||
<property name="sizeHint" stdset="0">
|
||||
<size>
|
||||
<width>308</width>
|
||||
<height>20</height>
|
||||
</size>
|
||||
</property>
|
||||
</spacer>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QPushButton" name="close_button">
|
||||
<property name="text">
|
||||
<string>Close</string>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
</layout>
|
||||
</item>
|
||||
</layout>
|
||||
</widget>
|
||||
<customwidgets>
|
||||
<customwidget>
|
||||
<class>HistoryLineEdit</class>
|
||||
<extends>QLineEdit</extends>
|
||||
<header>widgets.h</header>
|
||||
</customwidget>
|
||||
</customwidgets>
|
||||
<resources/>
|
||||
<connections>
|
||||
<connection>
|
||||
<sender>close_button</sender>
|
||||
<signal>clicked()</signal>
|
||||
<receiver>Dialog</receiver>
|
||||
<slot>accept()</slot>
|
||||
<hints>
|
||||
<hint type="sourcelabel">
|
||||
<x>440</x>
|
||||
<y>432</y>
|
||||
</hint>
|
||||
<hint type="destinationlabel">
|
||||
<x>245</x>
|
||||
<y>230</y>
|
||||
</hint>
|
||||
</hints>
|
||||
</connection>
|
||||
</connections>
|
||||
</ui>
|
24
src/calibre/gui2/store/stores/pragmatic_bookshelf_plugin.py
Normal file
24
src/calibre/gui2/store/stores/pragmatic_bookshelf_plugin.py
Normal file
@ -0,0 +1,24 @@
|
||||
# -*- 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 calibre.gui2.store.basic_config import BasicStoreConfig
|
||||
from calibre.gui2.store.opensearch_store import OpenSearchStore
|
||||
from calibre.gui2.store.search_result import SearchResult
|
||||
|
||||
class PragmaticBookshelfStore(BasicStoreConfig, OpenSearchStore):
|
||||
|
||||
open_search_url = 'http://pragprog.com/catalog/search-description'
|
||||
web_url = 'http://pragprog.com/'
|
||||
|
||||
# http://pragprog.com/catalog.opds
|
||||
|
||||
def search(self, query, max_results=10, timeout=60):
|
||||
for s in OpenSearchStore.search(self, query, max_results, timeout):
|
||||
s.drm = SearchResult.DRM_UNLOCKED
|
||||
s.formats = 'EPUB, PDF, MOBI'
|
||||
yield s
|
11
src/calibre/gui2/tag_browser/__init__.py
Normal file
11
src/calibre/gui2/tag_browser/__init__.py
Normal file
@ -0,0 +1,11 @@
|
||||
#!/usr/bin/env python
|
||||
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
|
||||
from __future__ import (unicode_literals, division, absolute_import,
|
||||
print_function)
|
||||
|
||||
__license__ = 'GPL v3'
|
||||
__copyright__ = '2011, Kovid Goyal <kovid@kovidgoyal.net>'
|
||||
__docformat__ = 'restructuredtext en'
|
||||
|
||||
|
||||
|
File diff suppressed because it is too large
Load Diff
458
src/calibre/gui2/tag_browser/ui.py
Normal file
458
src/calibre/gui2/tag_browser/ui.py
Normal file
@ -0,0 +1,458 @@
|
||||
#!/usr/bin/env python
|
||||
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
|
||||
from __future__ import (unicode_literals, division, absolute_import,
|
||||
print_function)
|
||||
|
||||
__license__ = 'GPL v3'
|
||||
__copyright__ = '2011, Kovid Goyal <kovid@kovidgoyal.net>'
|
||||
__docformat__ = 'restructuredtext en'
|
||||
|
||||
from functools import partial
|
||||
|
||||
from PyQt4.Qt import (Qt, QIcon, QWidget, QHBoxLayout, QVBoxLayout, QShortcut,
|
||||
QKeySequence, QToolButton, QString, QLabel, QFrame, QTimer, QComboBox,
|
||||
QMenu, QPushButton)
|
||||
|
||||
from calibre.gui2 import error_dialog, question_dialog
|
||||
from calibre.gui2.widgets import HistoryLineEdit
|
||||
from calibre.library.field_metadata import category_icon_map
|
||||
from calibre.utils.icu import sort_key
|
||||
from calibre.gui2.tag_browser.view import TagsView
|
||||
from calibre.ebooks.metadata import title_sort
|
||||
from calibre.gui2.dialogs.tag_categories import TagCategories
|
||||
from calibre.gui2.dialogs.tag_list_editor import TagListEditor
|
||||
from calibre.gui2.dialogs.edit_authors_dialog import EditAuthorsDialog
|
||||
|
||||
class TagBrowserMixin(object): # {{{
|
||||
|
||||
def __init__(self, db):
|
||||
self.library_view.model().count_changed_signal.connect(self.tags_view.recount)
|
||||
self.tags_view.set_database(db, self.tag_match, self.sort_by)
|
||||
self.tags_view.tags_marked.connect(self.search.set_search_string)
|
||||
self.tags_view.tag_list_edit.connect(self.do_tags_list_edit)
|
||||
self.tags_view.edit_user_category.connect(self.do_edit_user_categories)
|
||||
self.tags_view.delete_user_category.connect(self.do_delete_user_category)
|
||||
self.tags_view.del_item_from_user_cat.connect(self.do_del_item_from_user_cat)
|
||||
self.tags_view.add_subcategory.connect(self.do_add_subcategory)
|
||||
self.tags_view.add_item_to_user_cat.connect(self.do_add_item_to_user_cat)
|
||||
self.tags_view.saved_search_edit.connect(self.do_saved_search_edit)
|
||||
self.tags_view.rebuild_saved_searches.connect(self.do_rebuild_saved_searches)
|
||||
self.tags_view.author_sort_edit.connect(self.do_author_sort_edit)
|
||||
self.tags_view.tag_item_renamed.connect(self.do_tag_item_renamed)
|
||||
self.tags_view.search_item_renamed.connect(self.saved_searches_changed)
|
||||
self.tags_view.drag_drop_finished.connect(self.drag_drop_finished)
|
||||
self.tags_view.restriction_error.connect(self.do_restriction_error,
|
||||
type=Qt.QueuedConnection)
|
||||
|
||||
for text, func, args, cat_name in (
|
||||
(_('Manage Authors'),
|
||||
self.do_author_sort_edit, (self, None), 'authors'),
|
||||
(_('Manage Series'),
|
||||
self.do_tags_list_edit, (None, 'series'), 'series'),
|
||||
(_('Manage Publishers'),
|
||||
self.do_tags_list_edit, (None, 'publisher'), 'publisher'),
|
||||
(_('Manage Tags'),
|
||||
self.do_tags_list_edit, (None, 'tags'), 'tags'),
|
||||
(_('Manage User Categories'),
|
||||
self.do_edit_user_categories, (None,), 'user:'),
|
||||
(_('Manage Saved Searches'),
|
||||
self.do_saved_search_edit, (None,), 'search')
|
||||
):
|
||||
self.manage_items_button.menu().addAction(
|
||||
QIcon(I(category_icon_map[cat_name])),
|
||||
text, partial(func, *args))
|
||||
|
||||
def do_restriction_error(self):
|
||||
error_dialog(self.tags_view, _('Invalid search restriction'),
|
||||
_('The current search restriction is invalid'), show=True)
|
||||
|
||||
def do_add_subcategory(self, on_category_key, new_category_name=None):
|
||||
'''
|
||||
Add a subcategory to the category 'on_category'. If new_category_name is
|
||||
None, then a default name is shown and the user is offered the
|
||||
opportunity to edit the name.
|
||||
'''
|
||||
db = self.library_view.model().db
|
||||
user_cats = db.prefs.get('user_categories', {})
|
||||
|
||||
# Ensure that the temporary name we will use is not already there
|
||||
i = 0
|
||||
if new_category_name is not None:
|
||||
new_name = new_category_name.replace('.', '')
|
||||
else:
|
||||
new_name = _('New Category').replace('.', '')
|
||||
n = new_name
|
||||
while True:
|
||||
new_cat = on_category_key[1:] + '.' + n
|
||||
if new_cat not in user_cats:
|
||||
break
|
||||
i += 1
|
||||
n = new_name + unicode(i)
|
||||
# Add the new category
|
||||
user_cats[new_cat] = []
|
||||
db.prefs.set('user_categories', user_cats)
|
||||
self.tags_view.set_new_model()
|
||||
m = self.tags_view.model()
|
||||
idx = m.index_for_path(m.find_category_node('@' + new_cat))
|
||||
m.show_item_at_index(idx)
|
||||
# Open the editor on the new item to rename it
|
||||
if new_category_name is None:
|
||||
self.tags_view.edit(idx)
|
||||
|
||||
def do_edit_user_categories(self, on_category=None):
|
||||
'''
|
||||
Open the user categories editor.
|
||||
'''
|
||||
db = self.library_view.model().db
|
||||
d = TagCategories(self, db, on_category)
|
||||
if d.exec_() == d.Accepted:
|
||||
db.prefs.set('user_categories', d.categories)
|
||||
db.field_metadata.remove_user_categories()
|
||||
for k in d.categories:
|
||||
db.field_metadata.add_user_category('@' + k, k)
|
||||
db.data.change_search_locations(db.field_metadata.get_search_terms())
|
||||
self.tags_view.set_new_model()
|
||||
|
||||
def do_delete_user_category(self, category_name):
|
||||
'''
|
||||
Delete the user category named category_name. Any leading '@' is removed
|
||||
'''
|
||||
if category_name.startswith('@'):
|
||||
category_name = category_name[1:]
|
||||
db = self.library_view.model().db
|
||||
user_cats = db.prefs.get('user_categories', {})
|
||||
cat_keys = sorted(user_cats.keys(), key=sort_key)
|
||||
has_children = False
|
||||
found = False
|
||||
for k in cat_keys:
|
||||
if k == category_name:
|
||||
found = True
|
||||
has_children = len(user_cats[k])
|
||||
elif k.startswith(category_name + '.'):
|
||||
has_children = True
|
||||
if not found:
|
||||
return error_dialog(self.tags_view, _('Delete user category'),
|
||||
_('%s is not a user category')%category_name, show=True)
|
||||
if has_children:
|
||||
if not question_dialog(self.tags_view, _('Delete user category'),
|
||||
_('%s contains items. Do you really '
|
||||
'want to delete it?')%category_name):
|
||||
return
|
||||
for k in cat_keys:
|
||||
if k == category_name:
|
||||
del user_cats[k]
|
||||
elif k.startswith(category_name + '.'):
|
||||
del user_cats[k]
|
||||
db.prefs.set('user_categories', user_cats)
|
||||
self.tags_view.set_new_model()
|
||||
|
||||
def do_del_item_from_user_cat(self, user_cat, item_name, item_category):
|
||||
'''
|
||||
Delete the item (item_name, item_category) from the user category with
|
||||
key user_cat. Any leading '@' characters are removed
|
||||
'''
|
||||
if user_cat.startswith('@'):
|
||||
user_cat = user_cat[1:]
|
||||
db = self.library_view.model().db
|
||||
user_cats = db.prefs.get('user_categories', {})
|
||||
if user_cat not in user_cats:
|
||||
error_dialog(self.tags_view, _('Remove category'),
|
||||
_('User category %s does not exist')%user_cat,
|
||||
show=True)
|
||||
return
|
||||
self.tags_view.model().delete_item_from_user_category(user_cat,
|
||||
item_name, item_category)
|
||||
self.tags_view.recount()
|
||||
|
||||
def do_add_item_to_user_cat(self, dest_category, src_name, src_category):
|
||||
'''
|
||||
Add the item src_name in src_category to the user category
|
||||
dest_category. Any leading '@' is removed
|
||||
'''
|
||||
db = self.library_view.model().db
|
||||
user_cats = db.prefs.get('user_categories', {})
|
||||
|
||||
if dest_category and dest_category.startswith('@'):
|
||||
dest_category = dest_category[1:]
|
||||
|
||||
if dest_category not in user_cats:
|
||||
return error_dialog(self.tags_view, _('Add to user category'),
|
||||
_('A user category %s does not exist')%dest_category, show=True)
|
||||
|
||||
# Now add the item to the destination user category
|
||||
add_it = True
|
||||
if src_category == 'news':
|
||||
src_category = 'tags'
|
||||
for tup in user_cats[dest_category]:
|
||||
if src_name == tup[0] and src_category == tup[1]:
|
||||
add_it = False
|
||||
if add_it:
|
||||
user_cats[dest_category].append([src_name, src_category, 0])
|
||||
db.prefs.set('user_categories', user_cats)
|
||||
self.tags_view.recount()
|
||||
|
||||
def do_tags_list_edit(self, tag, category):
|
||||
'''
|
||||
Open the 'manage_X' dialog where X == category. If tag is not None, the
|
||||
dialog will position the editor on that item.
|
||||
'''
|
||||
db=self.library_view.model().db
|
||||
if category == 'tags':
|
||||
result = db.get_tags_with_ids()
|
||||
key = sort_key
|
||||
elif category == 'series':
|
||||
result = db.get_series_with_ids()
|
||||
key = lambda x:sort_key(title_sort(x))
|
||||
elif category == 'publisher':
|
||||
result = db.get_publishers_with_ids()
|
||||
key = sort_key
|
||||
else: # should be a custom field
|
||||
cc_label = None
|
||||
if category in db.field_metadata:
|
||||
cc_label = db.field_metadata[category]['label']
|
||||
result = db.get_custom_items_with_ids(label=cc_label)
|
||||
else:
|
||||
result = []
|
||||
key = sort_key
|
||||
|
||||
d = TagListEditor(self, tag_to_match=tag, data=result, key=key)
|
||||
d.exec_()
|
||||
if d.result() == d.Accepted:
|
||||
to_rename = d.to_rename # dict of new text to old id
|
||||
to_delete = d.to_delete # list of ids
|
||||
orig_name = d.original_names # dict of id: name
|
||||
|
||||
rename_func = None
|
||||
if category == 'tags':
|
||||
rename_func = db.rename_tag
|
||||
delete_func = db.delete_tag_using_id
|
||||
elif category == 'series':
|
||||
rename_func = db.rename_series
|
||||
delete_func = db.delete_series_using_id
|
||||
elif category == 'publisher':
|
||||
rename_func = db.rename_publisher
|
||||
delete_func = db.delete_publisher_using_id
|
||||
else:
|
||||
rename_func = partial(db.rename_custom_item, label=cc_label)
|
||||
delete_func = partial(db.delete_custom_item_using_id, label=cc_label)
|
||||
m = self.tags_view.model()
|
||||
if rename_func:
|
||||
for item in to_delete:
|
||||
delete_func(item)
|
||||
m.delete_item_from_all_user_categories(orig_name[item], category)
|
||||
for old_id in to_rename:
|
||||
rename_func(old_id, new_name=unicode(to_rename[old_id]))
|
||||
m.rename_item_in_all_user_categories(orig_name[old_id],
|
||||
category, unicode(to_rename[old_id]))
|
||||
|
||||
# Clean up the library view
|
||||
self.do_tag_item_renamed()
|
||||
self.tags_view.recount()
|
||||
|
||||
def do_tag_item_renamed(self):
|
||||
# Clean up library view and search
|
||||
# get information to redo the selection
|
||||
rows = [r.row() for r in \
|
||||
self.library_view.selectionModel().selectedRows()]
|
||||
m = self.library_view.model()
|
||||
ids = [m.id(r) for r in rows]
|
||||
|
||||
m.refresh(reset=False)
|
||||
m.research()
|
||||
self.library_view.select_rows(ids)
|
||||
# refreshing the tags view happens at the emit()/call() site
|
||||
|
||||
def do_author_sort_edit(self, parent, id, select_sort=True):
|
||||
'''
|
||||
Open the manage authors dialog
|
||||
'''
|
||||
db = self.library_view.model().db
|
||||
editor = EditAuthorsDialog(parent, db, id, select_sort)
|
||||
d = editor.exec_()
|
||||
if d:
|
||||
for (id, old_author, new_author, new_sort) in editor.result:
|
||||
if old_author != new_author:
|
||||
# The id might change if the new author already exists
|
||||
id = db.rename_author(id, new_author)
|
||||
db.set_sort_field_for_author(id, unicode(new_sort),
|
||||
commit=False, notify=False)
|
||||
db.commit()
|
||||
self.library_view.model().refresh()
|
||||
self.tags_view.recount()
|
||||
|
||||
def drag_drop_finished(self, ids):
|
||||
self.library_view.model().refresh_ids(ids)
|
||||
|
||||
# }}}
|
||||
|
||||
class TagBrowserWidget(QWidget): # {{{
|
||||
|
||||
def __init__(self, parent):
|
||||
QWidget.__init__(self, parent)
|
||||
self.parent = parent
|
||||
self._layout = QVBoxLayout()
|
||||
self.setLayout(self._layout)
|
||||
self._layout.setContentsMargins(0,0,0,0)
|
||||
|
||||
# Set up the find box & button
|
||||
search_layout = QHBoxLayout()
|
||||
self._layout.addLayout(search_layout)
|
||||
self.item_search = HistoryLineEdit(parent)
|
||||
try:
|
||||
self.item_search.lineEdit().setPlaceholderText(
|
||||
_('Find item in tag browser'))
|
||||
except:
|
||||
pass # Using Qt < 4.7
|
||||
self.item_search.setToolTip(_(
|
||||
'Search for items. This is a "contains" search; items containing the\n'
|
||||
'text anywhere in the name will be found. You can limit the search\n'
|
||||
'to particular categories using syntax similar to search. For example,\n'
|
||||
'tags:foo will find foo in any tag, but not in authors etc. Entering\n'
|
||||
'*foo will filter all categories at once, showing only those items\n'
|
||||
'containing the text "foo"'))
|
||||
search_layout.addWidget(self.item_search)
|
||||
# Not sure if the shortcut should be translatable ...
|
||||
sc = QShortcut(QKeySequence(_('ALT+f')), parent)
|
||||
sc.activated.connect(self.set_focus_to_find_box)
|
||||
|
||||
self.search_button = QToolButton()
|
||||
self.search_button.setText(_('F&ind'))
|
||||
self.search_button.setToolTip(_('Find the first/next matching item'))
|
||||
search_layout.addWidget(self.search_button)
|
||||
|
||||
self.expand_button = QToolButton()
|
||||
self.expand_button.setText('-')
|
||||
self.expand_button.setToolTip(_('Collapse all categories'))
|
||||
search_layout.addWidget(self.expand_button)
|
||||
search_layout.setStretch(0, 10)
|
||||
search_layout.setStretch(1, 1)
|
||||
search_layout.setStretch(2, 1)
|
||||
|
||||
self.current_find_position = None
|
||||
self.search_button.clicked.connect(self.find)
|
||||
self.item_search.initialize('tag_browser_search')
|
||||
self.item_search.lineEdit().returnPressed.connect(self.do_find)
|
||||
self.item_search.lineEdit().textEdited.connect(self.find_text_changed)
|
||||
self.item_search.activated[QString].connect(self.do_find)
|
||||
self.item_search.completer().setCaseSensitivity(Qt.CaseSensitive)
|
||||
|
||||
parent.tags_view = TagsView(parent)
|
||||
self.tags_view = parent.tags_view
|
||||
self.expand_button.clicked.connect(self.tags_view.collapseAll)
|
||||
self._layout.addWidget(parent.tags_view)
|
||||
|
||||
# Now the floating 'not found' box
|
||||
l = QLabel(self.tags_view)
|
||||
self.not_found_label = l
|
||||
l.setFrameStyle(QFrame.StyledPanel)
|
||||
l.setAutoFillBackground(True)
|
||||
l.setText('<p><b>'+_('No More Matches.</b><p> Click Find again to go to first match'))
|
||||
l.setAlignment(Qt.AlignVCenter)
|
||||
l.setWordWrap(True)
|
||||
l.resize(l.sizeHint())
|
||||
l.move(10,20)
|
||||
l.setVisible(False)
|
||||
self.not_found_label_timer = QTimer()
|
||||
self.not_found_label_timer.setSingleShot(True)
|
||||
self.not_found_label_timer.timeout.connect(self.not_found_label_timer_event,
|
||||
type=Qt.QueuedConnection)
|
||||
|
||||
parent.sort_by = QComboBox(parent)
|
||||
# Must be in the same order as db2.CATEGORY_SORTS
|
||||
for x in (_('Sort by name'), _('Sort by popularity'),
|
||||
_('Sort by average rating')):
|
||||
parent.sort_by.addItem(x)
|
||||
parent.sort_by.setToolTip(
|
||||
_('Set the sort order for entries in the Tag Browser'))
|
||||
parent.sort_by.setStatusTip(parent.sort_by.toolTip())
|
||||
parent.sort_by.setCurrentIndex(0)
|
||||
self._layout.addWidget(parent.sort_by)
|
||||
|
||||
# Must be in the same order as db2.MATCH_TYPE
|
||||
parent.tag_match = QComboBox(parent)
|
||||
for x in (_('Match any'), _('Match all')):
|
||||
parent.tag_match.addItem(x)
|
||||
parent.tag_match.setCurrentIndex(0)
|
||||
self._layout.addWidget(parent.tag_match)
|
||||
parent.tag_match.setToolTip(
|
||||
_('When selecting multiple entries in the Tag Browser '
|
||||
'match any or all of them'))
|
||||
parent.tag_match.setStatusTip(parent.tag_match.toolTip())
|
||||
|
||||
|
||||
l = parent.manage_items_button = QPushButton(self)
|
||||
l.setStyleSheet('QPushButton {text-align: left; }')
|
||||
l.setText(_('Manage authors, tags, etc'))
|
||||
l.setToolTip(_('All of these category_managers are available by right-clicking '
|
||||
'on items in the tag browser above'))
|
||||
l.m = QMenu()
|
||||
l.setMenu(l.m)
|
||||
self._layout.addWidget(l)
|
||||
|
||||
# self.leak_test_timer = QTimer(self)
|
||||
# self.leak_test_timer.timeout.connect(self.test_for_leak)
|
||||
# self.leak_test_timer.start(5000)
|
||||
|
||||
def set_pane_is_visible(self, to_what):
|
||||
self.tags_view.set_pane_is_visible(to_what)
|
||||
|
||||
def find_text_changed(self, str):
|
||||
self.current_find_position = None
|
||||
|
||||
def set_focus_to_find_box(self):
|
||||
self.item_search.setFocus()
|
||||
self.item_search.lineEdit().selectAll()
|
||||
|
||||
def do_find(self, str=None):
|
||||
self.current_find_position = None
|
||||
self.find()
|
||||
|
||||
def find(self):
|
||||
model = self.tags_view.model()
|
||||
model.clear_boxed()
|
||||
txt = unicode(self.item_search.currentText()).strip()
|
||||
|
||||
if txt.startswith('*'):
|
||||
self.tags_view.set_new_model(filter_categories_by=txt[1:])
|
||||
self.current_find_position = None
|
||||
return
|
||||
if model.get_filter_categories_by():
|
||||
self.tags_view.set_new_model(filter_categories_by=None)
|
||||
self.current_find_position = None
|
||||
model = self.tags_view.model()
|
||||
|
||||
if not txt:
|
||||
return
|
||||
|
||||
self.item_search.lineEdit().blockSignals(True)
|
||||
self.search_button.setFocus(True)
|
||||
self.item_search.lineEdit().blockSignals(False)
|
||||
|
||||
key = None
|
||||
colon = txt.rfind(':') if len(txt) > 2 else 0
|
||||
if colon > 0:
|
||||
key = self.parent.library_view.model().db.\
|
||||
field_metadata.search_term_to_field_key(txt[:colon])
|
||||
txt = txt[colon+1:]
|
||||
|
||||
self.current_find_position = \
|
||||
model.find_item_node(key, txt, self.current_find_position)
|
||||
if self.current_find_position:
|
||||
model.show_item_at_path(self.current_find_position, box=True)
|
||||
elif self.item_search.text():
|
||||
self.not_found_label.setVisible(True)
|
||||
if self.tags_view.verticalScrollBar().isVisible():
|
||||
sbw = self.tags_view.verticalScrollBar().width()
|
||||
else:
|
||||
sbw = 0
|
||||
width = self.width() - 8 - sbw
|
||||
height = self.not_found_label.heightForWidth(width) + 20
|
||||
self.not_found_label.resize(width, height)
|
||||
self.not_found_label.move(4, 10)
|
||||
self.not_found_label_timer.start(2000)
|
||||
|
||||
def not_found_label_timer_event(self):
|
||||
self.not_found_label.setVisible(False)
|
||||
|
||||
# }}}
|
||||
|
578
src/calibre/gui2/tag_browser/view.py
Normal file
578
src/calibre/gui2/tag_browser/view.py
Normal file
@ -0,0 +1,578 @@
|
||||
#!/usr/bin/env python
|
||||
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
|
||||
from __future__ import (unicode_literals, division, absolute_import,
|
||||
print_function)
|
||||
|
||||
__license__ = 'GPL v3'
|
||||
__copyright__ = '2011, Kovid Goyal <kovid@kovidgoyal.net>'
|
||||
__docformat__ = 'restructuredtext en'
|
||||
|
||||
import cPickle, traceback
|
||||
from functools import partial
|
||||
|
||||
from PyQt4.Qt import (QItemDelegate, Qt, QTreeView, pyqtSignal, QSize, QIcon,
|
||||
QApplication, QMenu, QPoint)
|
||||
|
||||
from calibre.gui2.tag_browser.model import (TagTreeItem, TAG_SEARCH_STATES,
|
||||
TagsModel)
|
||||
from calibre.gui2 import config, gprefs
|
||||
from calibre.utils.search_query_parser import saved_searches
|
||||
from calibre.utils.icu import sort_key
|
||||
|
||||
class TagDelegate(QItemDelegate): # {{{
|
||||
|
||||
def paint(self, painter, option, index):
|
||||
item = index.data(Qt.UserRole).toPyObject()
|
||||
if item.type != TagTreeItem.TAG:
|
||||
QItemDelegate.paint(self, painter, option, index)
|
||||
return
|
||||
r = option.rect
|
||||
model = self.parent().model()
|
||||
icon = model.data(index, Qt.DecorationRole).toPyObject()
|
||||
painter.save()
|
||||
if item.tag.state != 0 or not config['show_avg_rating'] or \
|
||||
item.tag.avg_rating is None:
|
||||
icon.paint(painter, r, Qt.AlignLeft)
|
||||
else:
|
||||
painter.setOpacity(0.3)
|
||||
icon.paint(painter, r, Qt.AlignLeft)
|
||||
painter.setOpacity(1)
|
||||
rating = item.tag.avg_rating
|
||||
painter.setClipRect(r.left(), r.bottom()-int(r.height()*(rating/5.0)),
|
||||
r.width(), r.height())
|
||||
icon.paint(painter, r, Qt.AlignLeft)
|
||||
painter.setClipRect(r)
|
||||
|
||||
# Paint the text
|
||||
if item.boxed:
|
||||
painter.drawRoundedRect(r.adjusted(1,1,-1,-1), 5, 5)
|
||||
r.setLeft(r.left()+r.height()+3)
|
||||
painter.drawText(r, Qt.AlignLeft|Qt.AlignVCenter,
|
||||
model.data(index, Qt.DisplayRole).toString())
|
||||
painter.restore()
|
||||
|
||||
# }}}
|
||||
|
||||
class TagsView(QTreeView): # {{{
|
||||
|
||||
refresh_required = pyqtSignal()
|
||||
tags_marked = pyqtSignal(object)
|
||||
edit_user_category = pyqtSignal(object)
|
||||
delete_user_category = pyqtSignal(object)
|
||||
del_item_from_user_cat = pyqtSignal(object, object, object)
|
||||
add_item_to_user_cat = pyqtSignal(object, object, object)
|
||||
add_subcategory = pyqtSignal(object)
|
||||
tag_list_edit = pyqtSignal(object, object)
|
||||
saved_search_edit = pyqtSignal(object)
|
||||
rebuild_saved_searches = pyqtSignal()
|
||||
author_sort_edit = pyqtSignal(object, object)
|
||||
tag_item_renamed = pyqtSignal()
|
||||
search_item_renamed = pyqtSignal()
|
||||
drag_drop_finished = pyqtSignal(object)
|
||||
restriction_error = pyqtSignal()
|
||||
|
||||
def __init__(self, parent=None):
|
||||
QTreeView.__init__(self, parent=None)
|
||||
self.tag_match = None
|
||||
self.disable_recounting = False
|
||||
self.setUniformRowHeights(True)
|
||||
self.setCursor(Qt.PointingHandCursor)
|
||||
self.setIconSize(QSize(30, 30))
|
||||
self.setTabKeyNavigation(True)
|
||||
self.setAlternatingRowColors(True)
|
||||
self.setAnimated(True)
|
||||
self.setHeaderHidden(True)
|
||||
self.setItemDelegate(TagDelegate(self))
|
||||
self.made_connections = False
|
||||
self.setAcceptDrops(True)
|
||||
self.setDragEnabled(True)
|
||||
self.setDragDropMode(self.DragDrop)
|
||||
self.setDropIndicatorShown(True)
|
||||
self.setAutoExpandDelay(500)
|
||||
self.pane_is_visible = False
|
||||
if gprefs['tags_browser_collapse_at'] == 0:
|
||||
self.collapse_model = 'disable'
|
||||
else:
|
||||
self.collapse_model = gprefs['tags_browser_partition_method']
|
||||
self.search_icon = QIcon(I('search.png'))
|
||||
self.user_category_icon = QIcon(I('tb_folder.png'))
|
||||
self.delete_icon = QIcon(I('list_remove.png'))
|
||||
self.rename_icon = QIcon(I('edit-undo.png'))
|
||||
|
||||
def set_pane_is_visible(self, to_what):
|
||||
pv = self.pane_is_visible
|
||||
self.pane_is_visible = to_what
|
||||
if to_what and not pv:
|
||||
self.recount()
|
||||
|
||||
def reread_collapse_parameters(self):
|
||||
if gprefs['tags_browser_collapse_at'] == 0:
|
||||
self.collapse_model = 'disable'
|
||||
else:
|
||||
self.collapse_model = gprefs['tags_browser_partition_method']
|
||||
self.set_new_model(self._model.get_filter_categories_by())
|
||||
|
||||
def set_database(self, db, tag_match, sort_by):
|
||||
hidden_cats = db.prefs.get('tag_browser_hidden_categories', None)
|
||||
self.hidden_categories = []
|
||||
# migrate from config to db prefs
|
||||
if hidden_cats is None:
|
||||
hidden_cats = config['tag_browser_hidden_categories']
|
||||
# strip out any non-existence field keys
|
||||
for cat in hidden_cats:
|
||||
if cat in db.field_metadata:
|
||||
self.hidden_categories.append(cat)
|
||||
db.prefs.set('tag_browser_hidden_categories', list(self.hidden_categories))
|
||||
self.hidden_categories = set(self.hidden_categories)
|
||||
|
||||
old = getattr(self, '_model', None)
|
||||
if old is not None:
|
||||
old.break_cycles()
|
||||
self._model = TagsModel(db, parent=self,
|
||||
hidden_categories=self.hidden_categories,
|
||||
search_restriction=None,
|
||||
drag_drop_finished=self.drag_drop_finished,
|
||||
collapse_model=self.collapse_model,
|
||||
state_map={})
|
||||
self.pane_is_visible = True # because TagsModel.init did a recount
|
||||
self.sort_by = sort_by
|
||||
self.tag_match = tag_match
|
||||
self.db = db
|
||||
self.search_restriction = None
|
||||
self.setModel(self._model)
|
||||
self.setContextMenuPolicy(Qt.CustomContextMenu)
|
||||
pop = config['sort_tags_by']
|
||||
self.sort_by.setCurrentIndex(self.db.CATEGORY_SORTS.index(pop))
|
||||
try:
|
||||
match_pop = self.db.MATCH_TYPE.index(config['match_tags_type'])
|
||||
except ValueError:
|
||||
match_pop = 0
|
||||
self.tag_match.setCurrentIndex(match_pop)
|
||||
if not self.made_connections:
|
||||
self.clicked.connect(self.toggle)
|
||||
self.customContextMenuRequested.connect(self.show_context_menu)
|
||||
self.refresh_required.connect(self.recount, type=Qt.QueuedConnection)
|
||||
self.sort_by.currentIndexChanged.connect(self.sort_changed)
|
||||
self.tag_match.currentIndexChanged.connect(self.match_changed)
|
||||
self.made_connections = True
|
||||
self.refresh_signal_processed = True
|
||||
db.add_listener(self.database_changed)
|
||||
self.expanded.connect(self.item_expanded)
|
||||
|
||||
def database_changed(self, event, ids):
|
||||
if self.refresh_signal_processed:
|
||||
self.refresh_signal_processed = False
|
||||
self.refresh_required.emit()
|
||||
|
||||
@property
|
||||
def match_all(self):
|
||||
return self.tag_match and self.tag_match.currentIndex() > 0
|
||||
|
||||
def sort_changed(self, pop):
|
||||
config.set('sort_tags_by', self.db.CATEGORY_SORTS[pop])
|
||||
self.recount()
|
||||
|
||||
def match_changed(self, pop):
|
||||
try:
|
||||
config.set('match_tags_type', self.db.MATCH_TYPE[pop])
|
||||
except:
|
||||
pass
|
||||
|
||||
def set_search_restriction(self, s):
|
||||
if s:
|
||||
self.search_restriction = s
|
||||
else:
|
||||
self.search_restriction = None
|
||||
self.set_new_model()
|
||||
|
||||
def mouseReleaseEvent(self, event):
|
||||
# Swallow everything except leftButton so context menus work correctly
|
||||
if event.button() == Qt.LeftButton:
|
||||
QTreeView.mouseReleaseEvent(self, event)
|
||||
|
||||
def mouseDoubleClickEvent(self, event):
|
||||
# swallow these to avoid toggling and editing at the same time
|
||||
pass
|
||||
|
||||
@property
|
||||
def search_string(self):
|
||||
tokens = self._model.tokens()
|
||||
joiner = ' and ' if self.match_all else ' or '
|
||||
return joiner.join(tokens)
|
||||
|
||||
def toggle(self, index):
|
||||
self._toggle(index, None)
|
||||
|
||||
def _toggle(self, index, set_to):
|
||||
'''
|
||||
set_to: if None, advance the state. Otherwise must be one of the values
|
||||
in TAG_SEARCH_STATES
|
||||
'''
|
||||
modifiers = int(QApplication.keyboardModifiers())
|
||||
exclusive = modifiers not in (Qt.CTRL, Qt.SHIFT)
|
||||
if self._model.toggle(index, exclusive, set_to=set_to):
|
||||
self.tags_marked.emit(self.search_string)
|
||||
|
||||
def conditional_clear(self, search_string):
|
||||
if search_string != self.search_string:
|
||||
self.clear()
|
||||
|
||||
def context_menu_handler(self, action=None, category=None,
|
||||
key=None, index=None, search_state=None):
|
||||
if not action:
|
||||
return
|
||||
try:
|
||||
if action == 'edit_item':
|
||||
self.edit(index)
|
||||
return
|
||||
if action == 'open_editor':
|
||||
self.tag_list_edit.emit(category, key)
|
||||
return
|
||||
if action == 'manage_categories':
|
||||
self.edit_user_category.emit(category)
|
||||
return
|
||||
if action == 'search':
|
||||
self._toggle(index, set_to=search_state)
|
||||
return
|
||||
if action == 'add_to_category':
|
||||
tag = index.tag
|
||||
if len(index.children) > 0:
|
||||
for c in index.children:
|
||||
self.add_item_to_user_cat.emit(category, c.tag.original_name,
|
||||
c.tag.category)
|
||||
self.add_item_to_user_cat.emit(category, tag.original_name,
|
||||
tag.category)
|
||||
return
|
||||
if action == 'add_subcategory':
|
||||
self.add_subcategory.emit(key)
|
||||
return
|
||||
if action == 'search_category':
|
||||
self._toggle(index, set_to=search_state)
|
||||
return
|
||||
if action == 'delete_user_category':
|
||||
self.delete_user_category.emit(key)
|
||||
return
|
||||
if action == 'delete_search':
|
||||
saved_searches().delete(key)
|
||||
self.rebuild_saved_searches.emit()
|
||||
return
|
||||
if action == 'delete_item_from_user_category':
|
||||
tag = index.tag
|
||||
if len(index.children) > 0:
|
||||
for c in index.children:
|
||||
self.del_item_from_user_cat.emit(key, c.tag.original_name,
|
||||
c.tag.category)
|
||||
self.del_item_from_user_cat.emit(key, tag.original_name, tag.category)
|
||||
return
|
||||
if action == 'manage_searches':
|
||||
self.saved_search_edit.emit(category)
|
||||
return
|
||||
if action == 'edit_author_sort':
|
||||
self.author_sort_edit.emit(self, index)
|
||||
return
|
||||
|
||||
if action == 'hide':
|
||||
self.hidden_categories.add(category)
|
||||
elif action == 'show':
|
||||
self.hidden_categories.discard(category)
|
||||
elif action == 'categorization':
|
||||
changed = self.collapse_model != category
|
||||
self.collapse_model = category
|
||||
if changed:
|
||||
self.set_new_model(self._model.get_filter_categories_by())
|
||||
gprefs['tags_browser_partition_method'] = category
|
||||
elif action == 'defaults':
|
||||
self.hidden_categories.clear()
|
||||
self.db.prefs.set('tag_browser_hidden_categories', list(self.hidden_categories))
|
||||
self.set_new_model()
|
||||
except:
|
||||
return
|
||||
|
||||
def show_context_menu(self, point):
|
||||
def display_name( tag):
|
||||
if tag.category == 'search':
|
||||
n = tag.name
|
||||
if len(n) > 45:
|
||||
n = n[:45] + '...'
|
||||
return "'" + n + "'"
|
||||
return tag.name
|
||||
|
||||
index = self.indexAt(point)
|
||||
self.context_menu = QMenu(self)
|
||||
|
||||
if index.isValid():
|
||||
item = index.data(Qt.UserRole).toPyObject()
|
||||
tag = None
|
||||
|
||||
if item.type == TagTreeItem.TAG:
|
||||
tag_item = item
|
||||
tag = item.tag
|
||||
while item.type != TagTreeItem.CATEGORY:
|
||||
item = item.parent
|
||||
|
||||
if item.type == TagTreeItem.CATEGORY:
|
||||
if not item.category_key.startswith('@'):
|
||||
while item.parent != self._model.root_item:
|
||||
item = item.parent
|
||||
category = unicode(item.name.toString())
|
||||
key = item.category_key
|
||||
# Verify that we are working with a field that we know something about
|
||||
if key not in self.db.field_metadata:
|
||||
return True
|
||||
|
||||
# Did the user click on a leaf node?
|
||||
if tag:
|
||||
# If the user right-clicked on an editable item, then offer
|
||||
# the possibility of renaming that item.
|
||||
if tag.is_editable:
|
||||
# Add the 'rename' items
|
||||
self.context_menu.addAction(self.rename_icon,
|
||||
_('Rename %s')%display_name(tag),
|
||||
partial(self.context_menu_handler, action='edit_item',
|
||||
index=index))
|
||||
if key == 'authors':
|
||||
self.context_menu.addAction(_('Edit sort for %s')%display_name(tag),
|
||||
partial(self.context_menu_handler,
|
||||
action='edit_author_sort', index=tag.id))
|
||||
|
||||
# is_editable is also overloaded to mean 'can be added
|
||||
# to a user category'
|
||||
m = self.context_menu.addMenu(self.user_category_icon,
|
||||
_('Add %s to user category')%display_name(tag))
|
||||
nt = self.model().category_node_tree
|
||||
def add_node_tree(tree_dict, m, path):
|
||||
p = path[:]
|
||||
for k in sorted(tree_dict.keys(), key=sort_key):
|
||||
p.append(k)
|
||||
n = k[1:] if k.startswith('@') else k
|
||||
m.addAction(self.user_category_icon, n,
|
||||
partial(self.context_menu_handler,
|
||||
'add_to_category',
|
||||
category='.'.join(p), index=tag_item))
|
||||
if len(tree_dict[k]):
|
||||
tm = m.addMenu(self.user_category_icon,
|
||||
_('Children of %s')%n)
|
||||
add_node_tree(tree_dict[k], tm, p)
|
||||
p.pop()
|
||||
add_node_tree(nt, m, [])
|
||||
elif key == 'search':
|
||||
self.context_menu.addAction(self.rename_icon,
|
||||
_('Rename %s')%display_name(tag),
|
||||
partial(self.context_menu_handler, action='edit_item',
|
||||
index=index))
|
||||
self.context_menu.addAction(self.delete_icon,
|
||||
_('Delete search %s')%display_name(tag),
|
||||
partial(self.context_menu_handler,
|
||||
action='delete_search', key=tag.name))
|
||||
if key.startswith('@') and not item.is_gst:
|
||||
self.context_menu.addAction(self.user_category_icon,
|
||||
_('Remove %s from category %s')%
|
||||
(display_name(tag), item.py_name),
|
||||
partial(self.context_menu_handler,
|
||||
action='delete_item_from_user_category',
|
||||
key = key, index = tag_item))
|
||||
# Add the search for value items. All leaf nodes are searchable
|
||||
self.context_menu.addAction(self.search_icon,
|
||||
_('Search for %s')%display_name(tag),
|
||||
partial(self.context_menu_handler, action='search',
|
||||
search_state=TAG_SEARCH_STATES['mark_plus'],
|
||||
index=index))
|
||||
self.context_menu.addAction(self.search_icon,
|
||||
_('Search for everything but %s')%display_name(tag),
|
||||
partial(self.context_menu_handler, action='search',
|
||||
search_state=TAG_SEARCH_STATES['mark_minus'],
|
||||
index=index))
|
||||
self.context_menu.addSeparator()
|
||||
elif key.startswith('@') and not item.is_gst:
|
||||
if item.can_be_edited:
|
||||
self.context_menu.addAction(self.rename_icon,
|
||||
_('Rename %s')%item.py_name,
|
||||
partial(self.context_menu_handler, action='edit_item',
|
||||
index=index))
|
||||
self.context_menu.addAction(self.user_category_icon,
|
||||
_('Add sub-category to %s')%item.py_name,
|
||||
partial(self.context_menu_handler,
|
||||
action='add_subcategory', key=key))
|
||||
self.context_menu.addAction(self.delete_icon,
|
||||
_('Delete user category %s')%item.py_name,
|
||||
partial(self.context_menu_handler,
|
||||
action='delete_user_category', key=key))
|
||||
self.context_menu.addSeparator()
|
||||
# Hide/Show/Restore categories
|
||||
self.context_menu.addAction(_('Hide category %s') % category,
|
||||
partial(self.context_menu_handler, action='hide',
|
||||
category=key))
|
||||
if self.hidden_categories:
|
||||
m = self.context_menu.addMenu(_('Show category'))
|
||||
for col in sorted(self.hidden_categories,
|
||||
key=lambda x: sort_key(self.db.field_metadata[x]['name'])):
|
||||
m.addAction(self.db.field_metadata[col]['name'],
|
||||
partial(self.context_menu_handler, action='show', category=col))
|
||||
|
||||
# search by category. Some categories are not searchable, such
|
||||
# as search and news
|
||||
if item.tag.is_searchable:
|
||||
self.context_menu.addAction(self.search_icon,
|
||||
_('Search for books in category %s')%category,
|
||||
partial(self.context_menu_handler,
|
||||
action='search_category',
|
||||
index=self._model.createIndex(item.row(), 0, item),
|
||||
search_state=TAG_SEARCH_STATES['mark_plus']))
|
||||
self.context_menu.addAction(self.search_icon,
|
||||
_('Search for books not in category %s')%category,
|
||||
partial(self.context_menu_handler,
|
||||
action='search_category',
|
||||
index=self._model.createIndex(item.row(), 0, item),
|
||||
search_state=TAG_SEARCH_STATES['mark_minus']))
|
||||
# Offer specific editors for tags/series/publishers/saved searches
|
||||
self.context_menu.addSeparator()
|
||||
if key in ['tags', 'publisher', 'series'] or \
|
||||
self.db.field_metadata[key]['is_custom']:
|
||||
self.context_menu.addAction(_('Manage %s')%category,
|
||||
partial(self.context_menu_handler, action='open_editor',
|
||||
category=tag.original_name if tag else None,
|
||||
key=key))
|
||||
elif key == 'authors':
|
||||
self.context_menu.addAction(_('Manage %s')%category,
|
||||
partial(self.context_menu_handler, action='edit_author_sort'))
|
||||
elif key == 'search':
|
||||
self.context_menu.addAction(_('Manage Saved Searches'),
|
||||
partial(self.context_menu_handler, action='manage_searches',
|
||||
category=tag.name if tag else None))
|
||||
|
||||
# Always show the user categories editor
|
||||
self.context_menu.addSeparator()
|
||||
if key.startswith('@') and \
|
||||
key[1:] in self.db.prefs.get('user_categories', {}).keys():
|
||||
self.context_menu.addAction(_('Manage User Categories'),
|
||||
partial(self.context_menu_handler, action='manage_categories',
|
||||
category=key[1:]))
|
||||
else:
|
||||
self.context_menu.addAction(_('Manage User Categories'),
|
||||
partial(self.context_menu_handler, action='manage_categories',
|
||||
category=None))
|
||||
|
||||
if self.hidden_categories:
|
||||
if not self.context_menu.isEmpty():
|
||||
self.context_menu.addSeparator()
|
||||
self.context_menu.addAction(_('Show all categories'),
|
||||
partial(self.context_menu_handler, action='defaults'))
|
||||
|
||||
m = self.context_menu.addMenu(_('Change sub-categorization scheme'))
|
||||
da = m.addAction('Disable',
|
||||
partial(self.context_menu_handler, action='categorization', category='disable'))
|
||||
fla = m.addAction('By first letter',
|
||||
partial(self.context_menu_handler, action='categorization', category='first letter'))
|
||||
pa = m.addAction('Partition',
|
||||
partial(self.context_menu_handler, action='categorization', category='partition'))
|
||||
if self.collapse_model == 'disable':
|
||||
da.setCheckable(True)
|
||||
da.setChecked(True)
|
||||
elif self.collapse_model == 'first letter':
|
||||
fla.setCheckable(True)
|
||||
fla.setChecked(True)
|
||||
else:
|
||||
pa.setCheckable(True)
|
||||
pa.setChecked(True)
|
||||
|
||||
if not self.context_menu.isEmpty():
|
||||
self.context_menu.popup(self.mapToGlobal(point))
|
||||
return True
|
||||
|
||||
def dragMoveEvent(self, event):
|
||||
QTreeView.dragMoveEvent(self, event)
|
||||
self.setDropIndicatorShown(False)
|
||||
index = self.indexAt(event.pos())
|
||||
if not index.isValid():
|
||||
return
|
||||
src_is_tb = event.mimeData().hasFormat('application/calibre+from_tag_browser')
|
||||
item = index.data(Qt.UserRole).toPyObject()
|
||||
flags = self._model.flags(index)
|
||||
if item.type == TagTreeItem.TAG and flags & Qt.ItemIsDropEnabled:
|
||||
self.setDropIndicatorShown(not src_is_tb)
|
||||
return
|
||||
if item.type == TagTreeItem.CATEGORY and not item.is_gst:
|
||||
fm_dest = self.db.metadata_for_field(item.category_key)
|
||||
if fm_dest['kind'] == 'user':
|
||||
if src_is_tb:
|
||||
if event.dropAction() == Qt.MoveAction:
|
||||
data = str(event.mimeData().data('application/calibre+from_tag_browser'))
|
||||
src = cPickle.loads(data)
|
||||
for s in src:
|
||||
if s[0] == TagTreeItem.TAG and \
|
||||
(not s[1].startswith('@') or s[2]):
|
||||
return
|
||||
self.setDropIndicatorShown(True)
|
||||
return
|
||||
md = event.mimeData()
|
||||
if hasattr(md, 'column_name'):
|
||||
fm_src = self.db.metadata_for_field(md.column_name)
|
||||
if md.column_name in ['authors', 'publisher', 'series'] or \
|
||||
(fm_src['is_custom'] and (
|
||||
(fm_src['datatype'] in ['series', 'text', 'enumeration'] and
|
||||
not fm_src['is_multiple']) or
|
||||
(fm_src['datatype'] == 'composite' and
|
||||
fm_src['display'].get('make_category', False)))):
|
||||
self.setDropIndicatorShown(True)
|
||||
|
||||
def clear(self):
|
||||
if self.model():
|
||||
self.model().clear_state()
|
||||
|
||||
def is_visible(self, idx):
|
||||
item = idx.data(Qt.UserRole).toPyObject()
|
||||
if getattr(item, 'type', None) == TagTreeItem.TAG:
|
||||
idx = idx.parent()
|
||||
return self.isExpanded(idx)
|
||||
|
||||
def recount(self, *args):
|
||||
'''
|
||||
Rebuild the category tree, expand any categories that were expanded,
|
||||
reset the search states, and reselect the current node.
|
||||
'''
|
||||
if self.disable_recounting or not self.pane_is_visible:
|
||||
return
|
||||
self.refresh_signal_processed = True
|
||||
ci = self.currentIndex()
|
||||
if not ci.isValid():
|
||||
ci = self.indexAt(QPoint(10, 10))
|
||||
path = self.model().path_for_index(ci) if self.is_visible(ci) else None
|
||||
expanded_categories, state_map = self.model().get_state()
|
||||
self.set_new_model(state_map=state_map)
|
||||
for category in expanded_categories:
|
||||
self.expand(self.model().index_for_category(category))
|
||||
self._model.show_item_at_path(path)
|
||||
|
||||
def item_expanded(self, idx):
|
||||
'''
|
||||
Called by the expanded signal
|
||||
'''
|
||||
self.setCurrentIndex(idx)
|
||||
|
||||
def set_new_model(self, filter_categories_by=None, state_map={}):
|
||||
'''
|
||||
There are cases where we need to rebuild the category tree without
|
||||
attempting to reposition the current node.
|
||||
'''
|
||||
try:
|
||||
old = getattr(self, '_model', None)
|
||||
if old is not None:
|
||||
old.break_cycles()
|
||||
self._model = TagsModel(self.db, parent=self,
|
||||
hidden_categories=self.hidden_categories,
|
||||
search_restriction=self.search_restriction,
|
||||
drag_drop_finished=self.drag_drop_finished,
|
||||
filter_categories_by=filter_categories_by,
|
||||
collapse_model=self.collapse_model,
|
||||
state_map=state_map)
|
||||
self.setModel(self._model)
|
||||
except:
|
||||
# The DB must be gone. Set the model to None and hope that someone
|
||||
# will call set_database later. I don't know if this in fact works.
|
||||
# But perhaps a Bad Thing Happened, so print the exception
|
||||
traceback.print_exc()
|
||||
self._model = None
|
||||
self.setModel(None)
|
||||
# }}}
|
||||
|
||||
|
@ -39,7 +39,7 @@ from calibre.gui2.jobs import JobManager, JobsDialog, JobsButton
|
||||
from calibre.gui2.init import LibraryViewMixin, LayoutMixin
|
||||
from calibre.gui2.search_box import SearchBoxMixin, SavedSearchBoxMixin
|
||||
from calibre.gui2.search_restriction_mixin import SearchRestrictionMixin
|
||||
from calibre.gui2.tag_view import TagBrowserMixin
|
||||
from calibre.gui2.tag_browser.ui import TagBrowserMixin
|
||||
|
||||
|
||||
class Listener(Thread): # {{{
|
||||
|
@ -72,9 +72,7 @@ class UpdateNotification(QDialog):
|
||||
self.label = QLabel(('<p>'+
|
||||
_('%s has been updated to version <b>%s</b>. '
|
||||
'See the <a href="http://calibre-ebook.com/whats-new'
|
||||
'">new features</a>.') + '<p>'+_('Update <b>only</b> if one of the '
|
||||
'new features or bug fixes is important to you. '
|
||||
'If the current version works well for you, do not update.'))%(
|
||||
'">new features</a>.'))%(
|
||||
__appname__, calibre_version))
|
||||
self.label.setOpenExternalLinks(True)
|
||||
self.label.setWordWrap(True)
|
||||
|
@ -2012,7 +2012,7 @@ class LibraryDatabase2(LibraryDatabase, SchemaUpgrade, CustomColumns):
|
||||
val = mi.get(key, None)
|
||||
if force_changes or val is not None:
|
||||
doit(self.set_custom, id, val=val, extra=mi.get_extra(key),
|
||||
label=user_mi[key]['label'], commit=False)
|
||||
label=user_mi[key]['label'], commit=False, notify=False)
|
||||
if commit:
|
||||
self.conn.commit()
|
||||
if notify:
|
||||
|
@ -785,7 +785,7 @@ class BuiltinDaysBetween(BuiltinFormatterFunction):
|
||||
except:
|
||||
return ''
|
||||
i = d1 - d2
|
||||
return str(i.days)
|
||||
return str('%d.%d'%(i.days, i.seconds/8640))
|
||||
|
||||
|
||||
builtin_add = BuiltinAdd()
|
||||
|
0
src/calibre/utils/opensearch/__init__.py
Normal file
0
src/calibre/utils/opensearch/__init__.py
Normal file
114
src/calibre/utils/opensearch/description.py
Normal file
114
src/calibre/utils/opensearch/description.py
Normal file
@ -0,0 +1,114 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
from __future__ import (unicode_literals, division, absolute_import, print_function)
|
||||
|
||||
__license__ = 'GPL 3'
|
||||
__copyright__ = '''
|
||||
2011, John Schember <john@nachtimwald.com>,
|
||||
2006, Ed Summers <ehs@pobox.com>
|
||||
'''
|
||||
__docformat__ = 'restructuredtext en'
|
||||
|
||||
from contextlib import closing
|
||||
|
||||
from lxml import etree
|
||||
|
||||
from calibre import browser
|
||||
from calibre.utils.opensearch.url import URL
|
||||
|
||||
class Description(object):
|
||||
'''
|
||||
A class for representing OpenSearch Description files.
|
||||
'''
|
||||
|
||||
def __init__(self, url=""):
|
||||
'''
|
||||
The constructor which may pass an optional url to load from.
|
||||
|
||||
d = Description("http://www.example.com/description")
|
||||
'''
|
||||
if url:
|
||||
self.load(url)
|
||||
|
||||
|
||||
def load(self, url):
|
||||
'''
|
||||
For loading up a description object from a url. Normally
|
||||
you'll probably just want to pass a URL into the constructor.
|
||||
'''
|
||||
br = browser()
|
||||
with closing(br.open(url, timeout=15)) as f:
|
||||
doc = etree.fromstring(f.read())
|
||||
|
||||
# version 1.1 has repeating Url elements
|
||||
self.urls = []
|
||||
for element in doc.xpath('//*[local-name() = "Url"]'):
|
||||
template = element.get('template')
|
||||
type = element.get('type')
|
||||
if template and type:
|
||||
url = URL()
|
||||
url.template = template
|
||||
url.type = type
|
||||
self.urls.append(url)
|
||||
|
||||
# this is version 1.0 specific
|
||||
self.url = ''.join(doc.xpath('//*[local-name() = "Url"][1]//text()'))
|
||||
self.format = ''.join(doc.xpath('//*[local-name() = "Format"][1]//text()'))
|
||||
|
||||
self.shortname = ''.join(doc.xpath('//*[local-name() = "ShortName"][1]//text()'))
|
||||
self.longname = ''.join(doc.xpath('//*[local-name() = "LongName"][1]//text()'))
|
||||
self.description = ''.join(doc.xpath('//*[local-name() = "Description"][1]//text()'))
|
||||
self.image = ''.join(doc.xpath('//*[local-name() = "Image"][1]//text()'))
|
||||
self.sameplesearch = ''.join(doc.xpath('//*[local-name() = "SampleSearch"][1]//text()'))
|
||||
self.developer = ''.join(doc.xpath('//*[local-name() = "Developer"][1]//text()'))
|
||||
self.contact = ''.join(doc.xpath('/*[local-name() = "Contact"][1]//text()'))
|
||||
self.attribution = ''.join(doc.xpath('//*[local-name() = "Attribution"][1]//text()'))
|
||||
self.syndicationright = ''.join(doc.xpath('//*[local-name() = "SyndicationRight"][1]//text()'))
|
||||
|
||||
tag_text = ' '.join(doc.xpath('//*[local-name() = "Tags"]//text()'))
|
||||
if tag_text != None:
|
||||
self.tags = tag_text.split(' ')
|
||||
|
||||
self.adultcontent = doc.xpath('boolean(//*[local-name() = "AdultContent" and contains(., "true")])')
|
||||
|
||||
def get_url_by_type(self, type):
|
||||
'''
|
||||
Walks available urls and returns them by type. Only
|
||||
appropriate in opensearch v1.1 where there can be multiple
|
||||
query targets. Returns none if no such type is found.
|
||||
|
||||
url = description.get_url_by_type('application/rss+xml')
|
||||
'''
|
||||
for url in self.urls:
|
||||
if url.type == type:
|
||||
return url
|
||||
return None
|
||||
|
||||
def get_best_template(self):
|
||||
'''
|
||||
OK, best is a value judgement, but so be it. You'll get
|
||||
back either the atom, rss or first template available. This
|
||||
method handles the main difference between opensearch v1.0 and v1.1
|
||||
'''
|
||||
# version 1.0
|
||||
if self.url:
|
||||
return self.url
|
||||
|
||||
# atom
|
||||
if self.get_url_by_type('application/atom+xml'):
|
||||
return self.get_url_by_type('application/atom+xml').template
|
||||
|
||||
# rss
|
||||
if self.get_url_by_type('application/rss+xml'):
|
||||
return self.get_url_by_type('application/rss+xml').template
|
||||
|
||||
# other possible rss type
|
||||
if self.get_url_by_type('text/xml'):
|
||||
return self.get_url_by_Type('text/xml').template
|
||||
|
||||
# otherwise just the first one
|
||||
if len(self.urls) > 0:
|
||||
return self.urls[0].template
|
||||
|
||||
# out of luck
|
||||
return None
|
74
src/calibre/utils/opensearch/query.py
Normal file
74
src/calibre/utils/opensearch/query.py
Normal file
@ -0,0 +1,74 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
from __future__ import (unicode_literals, division, absolute_import, print_function)
|
||||
|
||||
__license__ = 'GPL 3'
|
||||
__copyright__ = '2006, Ed Summers <ehs@pobox.com>'
|
||||
__docformat__ = 'restructuredtext en'
|
||||
|
||||
from urlparse import urlparse, urlunparse, parse_qs
|
||||
from urllib import urlencode
|
||||
|
||||
class Query(object):
|
||||
'''
|
||||
Represents an opensearch query Really this class is just a
|
||||
helper for substituting values into the macros in a format.
|
||||
|
||||
format = 'http://beta.indeed.com/opensearch?q={searchTerms}&start={startIndex}&limit={count}'
|
||||
q = Query(format)
|
||||
q.searchTerms('zx81')
|
||||
q.startIndex = 1
|
||||
q.count = 25
|
||||
print q.url()
|
||||
'''
|
||||
|
||||
standard_macros = ['searchTerms', 'count', 'startIndex', 'startPage',
|
||||
'language', 'outputEncoding', 'inputEncoding']
|
||||
|
||||
def __init__(self, format):
|
||||
'''
|
||||
Create a query object by passing it the url format obtained
|
||||
from the opensearch Description.
|
||||
'''
|
||||
self.format = format
|
||||
|
||||
# unpack the url to a tuple
|
||||
self.url_parts = urlparse(format)
|
||||
|
||||
# unpack the query string to a dictionary
|
||||
self.query_string = parse_qs(self.url_parts[4])
|
||||
|
||||
# look for standard macros and create a mapping of the
|
||||
# opensearch names to the service specific ones
|
||||
# so q={searchTerms} will result in a mapping between searchTerms and q
|
||||
self.macro_map = {}
|
||||
for key,values in self.query_string.items():
|
||||
# TODO eventually optional/required params should be
|
||||
# distinguished somehow (the ones with/without trailing ?
|
||||
macro = values[0].replace('{', '').replace('}', '').replace('?', '')
|
||||
if macro in Query.standard_macros:
|
||||
self.macro_map[macro] = key
|
||||
|
||||
def url(self):
|
||||
# copy the original query string
|
||||
query_string = dict(self.query_string)
|
||||
|
||||
# iterate through macros and set the position in the querystring
|
||||
for macro, name in self.macro_map.items():
|
||||
if hasattr(self, macro):
|
||||
# set the name/value pair
|
||||
query_string[name] = [getattr(self, macro)]
|
||||
else:
|
||||
# remove the name/value pair
|
||||
del(query_string[name])
|
||||
|
||||
# copy the url parts and substitute in our new query string
|
||||
url_parts = list(self.url_parts)
|
||||
url_parts[4] = urlencode(query_string, 1)
|
||||
|
||||
# recompose and return url
|
||||
return urlunparse(tuple(url_parts))
|
||||
|
||||
def has_macro(self, macro):
|
||||
return self.macro_map.has_key(macro)
|
||||
|
18
src/calibre/utils/opensearch/url.py
Normal file
18
src/calibre/utils/opensearch/url.py
Normal file
@ -0,0 +1,18 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
from __future__ import (unicode_literals, division, absolute_import, print_function)
|
||||
|
||||
__license__ = 'GPL 3'
|
||||
__copyright__ = '2006, Ed Summers <ehs@pobox.com>'
|
||||
__docformat__ = 'restructuredtext en'
|
||||
|
||||
class URL(object):
|
||||
'''
|
||||
Class for representing a URL in an opensearch v1.1 query
|
||||
'''
|
||||
|
||||
def __init__(self, type='', template='', method='GET'):
|
||||
self.type = type
|
||||
self.template = template
|
||||
self.method = 'GET'
|
||||
self.params = []
|
@ -85,7 +85,7 @@ def serialize_builtin_recipes():
|
||||
return serialize_collection(recipe_mapping)
|
||||
|
||||
def get_builtin_recipe_collection():
|
||||
return etree.parse(P('builtin_recipes.xml')).getroot()
|
||||
return etree.parse(P('builtin_recipes.xml', allow_user_override=False)).getroot()
|
||||
|
||||
def get_custom_recipe_collection(*args):
|
||||
from calibre.web.feeds.recipes import compile_recipe, \
|
||||
@ -179,7 +179,7 @@ def download_builtin_recipe(urn):
|
||||
return br.open_novisit('http://status.calibre-ebook.com/recipe/'+urn).read()
|
||||
|
||||
def get_builtin_recipe(urn):
|
||||
with zipfile.ZipFile(P('builtin_recipes.zip'), 'r') as zf:
|
||||
with zipfile.ZipFile(P('builtin_recipes.zip', allow_user_override=False), 'r') as zf:
|
||||
return zf.read(urn+'.recipe')
|
||||
|
||||
def get_builtin_recipe_by_title(title, log=None, download_recipe=False):
|
||||
|
@ -140,7 +140,8 @@ class RecipeModel(QAbstractItemModel, SearchQueryParser):
|
||||
self.builtin_recipe_collection = get_builtin_recipe_collection()
|
||||
self.scheduler_config = SchedulerConfig()
|
||||
try:
|
||||
with zipfile.ZipFile(P('builtin_recipes.zip'), 'r') as zf:
|
||||
with zipfile.ZipFile(P('builtin_recipes.zip',
|
||||
allow_user_override=False), 'r') as zf:
|
||||
self.favicons = dict([(x.filename, x) for x in zf.infolist() if
|
||||
x.filename.endswith('.png')])
|
||||
except:
|
||||
@ -181,7 +182,7 @@ class RecipeModel(QAbstractItemModel, SearchQueryParser):
|
||||
|
||||
def do_refresh(self, restrict_to_urns=set([])):
|
||||
self.custom_recipe_collection = get_custom_recipe_collection()
|
||||
zf = P('builtin_recipes.zip')
|
||||
zf = P('builtin_recipes.zip', allow_user_override=False)
|
||||
|
||||
def factory(cls, parent, *args):
|
||||
args = list(args)
|
||||
|
Loading…
x
Reference in New Issue
Block a user