Merge from trunk

This commit is contained in:
Charles Haley 2010-08-16 11:19:40 +01:00
commit 0987d89f7e
162 changed files with 46120 additions and 46602 deletions

View File

@ -4,6 +4,64 @@
# for important features/bug fixes.
# Also, each release can have new and improved recipes.
- version: 0.7.14
date: 2010-08-13
new features:
- title: "Device drivers for the: Teclast K-5, Samsung SNE-60 and Samsung i7500"
- title: "When showing cover browser in a separate window, remember the last used window size"
- title: "Add keyboard shortcuts to show/hide the Tag Browser, Book details and Cover Browser panels. Hover your mouse over the buttons that toggle them to see the shortcuts."
- title: "Calibre library: When the case of title or author is changed, automatically rename the folders to reflect the new case, even on case insensitive filesystems"
- title: "Metadata download: If downloaded title or author is all upper case, automatically fix the case"
- title: "Add method to add books by ISBN. Click the arrow next to Add Books to add from a list of ISBNs."
tickets: [6327]
- title: "Allow editing of tweaks via Preferences->Advanced"
- title: "Add button to the manage authors dialog to automatically reset all author sort values"
bug fixes:
- title: "Fix regression in 0.7.13 that broke changing libraries"
- title: "MOBI Output: When processing an input document that specifies non-existant files in the OPF guide, don't crash."
tickets: [6490]
- title: "E-book viewer: When opening consecutive documents in the same viewer, show the correct title in the titlebar"
- title: "Set screen size to 540x718 in Kobo output profile"
- title: "Dont allow calibredb to create custom columns with invalid labels."
tickets: [6487]
- title: "Fix preference to 'search as you type' not working"
- title: "iTunes driver: Fixed bug in PDF file name searching after adding to iTunes database (Windows only)"
- title: "Displaying HTML comments: Do not start a new paragraph at the period in words like Ph.D"
tickets: [6462]
- title: "Respect restriction in effect when refreshing book list"
- title: "Fix drives being reversed for softrooted nook"
new recipes:
- title: "Yahoo News, Skeptical Enquirer and Skeptic"
author: Startson17
- title: "Bolivian newspapers"
author: Darko Miletic
improved recipes:
- Esquire
- Big Oven
- NSPM
- version: 0.7.13
date: 2010-08-06

Binary file not shown.

After

Width:  |  Height:  |  Size: 479 B

View File

@ -9,9 +9,9 @@ from calibre import strftime
from calibre.web.feeds.news import BasicNewsRecipe
class ElPaisImpresa(BasicNewsRecipe):
title = 'El País - edicion impresa'
title = u'El Pa\xeds - edicion impresa'
__author__ = 'Darko Miletic'
description = 'el periodico global en Español'
description = u'el periodico global en Espa\xf1ol'
publisher = 'EDICIONES EL PAIS, S.L.'
category = 'news, politics,Spain,actualidad,noticias,informacion,videos,fotografias,audios,graficos,nacional,internacional,deportes,economia,tecnologia,cultura,gente,television,sociedad,opinion,blogs,foros,chats,encuestas,entrevistas,participacion'
no_stylesheets = True
@ -32,10 +32,10 @@ class ElPaisImpresa(BasicNewsRecipe):
feeds = [
(u'Internacional' , index + u'internacional/' )
,(u'España' , index + u'espana/' )
,(u'Espa\xf1a' , index + u'espana/' )
,(u'Economia' , index + u'economia/' )
,(u'Opinion' , index + u'opinion/' )
,(u'Viñetas' , index + u'vineta/' )
,(u'Vi\xf1etas' , index + u'vineta/' )
,(u'Sociedad' , index + u'sociedad/' )
,(u'Cultura' , index + u'cultura/' )
,(u'Tendencias' , index + u'tendencias/' )

View File

@ -5,7 +5,6 @@ __copyright__ = '2009-2010, Darko Miletic <darko.miletic at gmail.com>'
www.esquire.com
'''
from calibre import strftime
from calibre.web.feeds.news import BasicNewsRecipe
class Esquire(BasicNewsRecipe):
@ -20,8 +19,8 @@ class Esquire(BasicNewsRecipe):
encoding = 'cp1250'
use_embedded_content = False
language = 'en'
publication_type = 'magazine'
masthead_url = 'http://www.esquire.com/cm/shared/site_images/print_this/esquire_logo.gif'
publication_type = 'magazine'
masthead_url = 'http://www.esquire.com/cm/shared/site_images/print_this/esquire_logo.gif'
conversion_options = {
'comment' : description
@ -33,7 +32,7 @@ class Esquire(BasicNewsRecipe):
keep_only_tags = [dict(name='div', attrs={'id':['article_header','article_content']})]
remove_tags = [dict(name=['object','link','embed','iframe','base'])]
remove_attributes = ['width','height']
feeds = [
(u'Style' , u'http://www.esquire.com/style/rss/' )
,(u'Women' , u'http://www.esquire.com/women/rss/' )

View File

@ -0,0 +1,38 @@
__license__ = 'GPL v3'
__copyright__ = '2010, Darko Miletic <darko.miletic at gmail.com>'
'''
futurismic.com
'''
from calibre.web.feeds.news import BasicNewsRecipe
class Futurismic(BasicNewsRecipe):
title = 'Futurismic'
__author__ = 'Darko Miletic'
description = 'Near-future science fiction and fact since 2001'
oldest_article = 15
max_articles_per_feed = 100
language = 'en'
encoding = 'utf-8'
no_stylesheets = True
use_embedded_content = False
publication_type = 'blog'
extra_css = ' body{font-family: Arial,Verdana,sans-serif} '
conversion_options = {
'comment' : description
, 'tags' : 'blog, sf'
, 'publisher': 'Futurismic'
, 'language' : language
}
remove_attributes = ['width','height']
keep_only_tags = [dict(attrs={'class':['post','commentlist']})]
remove_tags = [dict(attrs={'class':['sociable','feedback','tagwords']})]
feeds = [(u'Posts', u'http://feeds2.feedburner.com/futurismic_feed')]
def preprocess_html(self, soup):
return self.adeify_images(soup)

View File

@ -0,0 +1,348 @@
#!/usr/bin/env python
__license__ = 'GPL v3'
__copyright__ = 'Copyright 2010 Starson17'
'''
www.gocomics.com
'''
from calibre.web.feeds.news import BasicNewsRecipe
import mechanize
class GoComics(BasicNewsRecipe):
title = 'GoComics'
__author__ = 'Starson17'
__version__ = '1.02'
__date__ = '14 August 2010'
description = u'200+ Comics - Customize for more days/comics: Defaults to 7 days, 25 comics - 20 general, 5 editorial.'
category = 'news, comics'
language = 'en'
use_embedded_content= False
no_stylesheets = True
remove_javascript = True
cover_url = 'http://paulbuckley14059.files.wordpress.com/2008/06/calvin-and-hobbes.jpg'
####### USER PREFERENCES - COMICS, IMAGE SIZE AND NUMBER OF COMICS TO RETRIEVE ########
# num_comics_to_get - I've tried up to 99 on Calvin&Hobbes
num_comics_to_get = 7
# comic_size 300 is small, 600 is medium, 900 is large, 1500 is extra-large
comic_size = 900
# CHOOSE COMIC STRIPS BELOW - REMOVE COMMENT '# ' FROM IN FRONT OF DESIRED STRIPS
# Please do not overload their servers by selecting all comics and 1000 strips from each!
conversion_options = {'linearize_tables' : True
, 'comment' : description
, 'tags' : category
, 'language' : language
}
keep_only_tags = [dict(name='div', attrs={'class':['feature','banner']}),
]
remove_tags = [dict(name='a', attrs={'class':['beginning','prev','cal','next','newest']}),
dict(name='div', attrs={'class':['tag-wrapper']}),
dict(name='ul', attrs={'class':['share-nav','feature-nav']}),
]
def get_browser(self):
br = BasicNewsRecipe.get_browser(self)
cookies = mechanize.CookieJar()
br = mechanize.build_opener(mechanize.HTTPCookieProcessor(cookies))
br.addheaders = [('Referer','http://www.gocomics.com/')]
return br
def parse_index(self):
feeds = []
for title, url in [
######## COMICS - GENERAL ########
(u"2 Cows and a Chicken", u"http://www.gocomics.com/2cowsandachicken"),
# (u"9 to 5", u"http://www.gocomics.com/9to5"),
# (u"The Academia Waltz", u"http://www.gocomics.com/academiawaltz"),
# (u"Adam@Home", u"http://www.gocomics.com/adamathome"),
# (u"Agnes", u"http://www.gocomics.com/agnes"),
# (u"Andy Capp", u"http://www.gocomics.com/andycapp"),
# (u"Animal Crackers", u"http://www.gocomics.com/animalcrackers"),
# (u"Annie", u"http://www.gocomics.com/annie"),
(u"The Argyle Sweater", u"http://www.gocomics.com/theargylesweater"),
# (u"Ask Shagg", u"http://www.gocomics.com/askshagg"),
(u"B.C.", u"http://www.gocomics.com/bc"),
# (u"Back in the Day", u"http://www.gocomics.com/backintheday"),
# (u"Bad Reporter", u"http://www.gocomics.com/badreporter"),
# (u"Baldo", u"http://www.gocomics.com/baldo"),
# (u"Ballard Street", u"http://www.gocomics.com/ballardstreet"),
# (u"Barkeater Lake", u"http://www.gocomics.com/barkeaterlake"),
# (u"The Barn", u"http://www.gocomics.com/thebarn"),
# (u"Basic Instructions", u"http://www.gocomics.com/basicinstructions"),
# (u"Bewley", u"http://www.gocomics.com/bewley"),
# (u"Big Top", u"http://www.gocomics.com/bigtop"),
# (u"Biographic", u"http://www.gocomics.com/biographic"),
(u"Birdbrains", u"http://www.gocomics.com/birdbrains"),
# (u"Bleeker: The Rechargeable Dog", u"http://www.gocomics.com/bleeker"),
# (u"Bliss", u"http://www.gocomics.com/bliss"),
(u"Bloom County", u"http://www.gocomics.com/bloomcounty"),
# (u"Bo Nanas", u"http://www.gocomics.com/bonanas"),
# (u"Bob the Squirrel", u"http://www.gocomics.com/bobthesquirrel"),
# (u"The Boiling Point", u"http://www.gocomics.com/theboilingpoint"),
# (u"Boomerangs", u"http://www.gocomics.com/boomerangs"),
# (u"The Boondocks", u"http://www.gocomics.com/boondocks"),
# (u"Bottomliners", u"http://www.gocomics.com/bottomliners"),
# (u"Bound and Gagged", u"http://www.gocomics.com/boundandgagged"),
# (u"Brainwaves", u"http://www.gocomics.com/brainwaves"),
# (u"Brenda Starr", u"http://www.gocomics.com/brendastarr"),
# (u"Brewster Rockit", u"http://www.gocomics.com/brewsterrockit"),
# (u"Broom Hilda", u"http://www.gocomics.com/broomhilda"),
(u"Calvin and Hobbes", u"http://www.gocomics.com/calvinandhobbes"),
# (u"Candorville", u"http://www.gocomics.com/candorville"),
# (u"Cathy", u"http://www.gocomics.com/cathy"),
# (u"C'est la Vie", u"http://www.gocomics.com/cestlavie"),
# (u"Chuckle Bros", u"http://www.gocomics.com/chucklebros"),
# (u"Citizen Dog", u"http://www.gocomics.com/citizendog"),
# (u"The City", u"http://www.gocomics.com/thecity"),
# (u"Cleats", u"http://www.gocomics.com/cleats"),
# (u"Close to Home", u"http://www.gocomics.com/closetohome"),
# (u"Compu-toon", u"http://www.gocomics.com/compu-toon"),
# (u"Cornered", u"http://www.gocomics.com/cornered"),
(u"Cul de Sac", u"http://www.gocomics.com/culdesac"),
# (u"Daddy's Home", u"http://www.gocomics.com/daddyshome"),
# (u"Deep Cover", u"http://www.gocomics.com/deepcover"),
# (u"Dick Tracy", u"http://www.gocomics.com/dicktracy"),
# (u"The Dinette Set", u"http://www.gocomics.com/dinetteset"),
# (u"Dog Eat Doug", u"http://www.gocomics.com/dogeatdoug"),
# (u"Domestic Abuse", u"http://www.gocomics.com/domesticabuse"),
# (u"Doodles", u"http://www.gocomics.com/doodles"),
(u"Doonesbury", u"http://www.gocomics.com/doonesbury"),
# (u"The Doozies", u"http://www.gocomics.com/thedoozies"),
# (u"The Duplex", u"http://www.gocomics.com/duplex"),
# (u"Eek!", u"http://www.gocomics.com/eek"),
# (u"The Elderberries", u"http://www.gocomics.com/theelderberries"),
# (u"Flight Deck", u"http://www.gocomics.com/flightdeck"),
# (u"Flo and Friends", u"http://www.gocomics.com/floandfriends"),
# (u"The Flying McCoys", u"http://www.gocomics.com/theflyingmccoys"),
(u"For Better or For Worse", u"http://www.gocomics.com/forbetterorforworse"),
# (u"For Heaven's Sake", u"http://www.gocomics.com/forheavenssake"),
# (u"Fort Knox", u"http://www.gocomics.com/fortknox"),
# (u"FoxTrot", u"http://www.gocomics.com/foxtrot"),
(u"FoxTrot Classics", u"http://www.gocomics.com/foxtrotclassics"),
# (u"Frank & Ernest", u"http://www.gocomics.com/frankandernest"),
# (u"Fred Basset", u"http://www.gocomics.com/fredbasset"),
# (u"Free Range", u"http://www.gocomics.com/freerange"),
# (u"Frog Applause", u"http://www.gocomics.com/frogapplause"),
# (u"The Fusco Brothers", u"http://www.gocomics.com/thefuscobrothers"),
(u"Garfield", u"http://www.gocomics.com/garfield"),
# (u"Garfield Minus Garfield", u"http://www.gocomics.com/garfieldminusgarfield"),
# (u"Gasoline Alley", u"http://www.gocomics.com/gasolinealley"),
# (u"Gil Thorp", u"http://www.gocomics.com/gilthorp"),
# (u"Ginger Meggs", u"http://www.gocomics.com/gingermeggs"),
# (u"Girls & Sports", u"http://www.gocomics.com/girlsandsports"),
# (u"Haiku Ewe", u"http://www.gocomics.com/haikuewe"),
# (u"Heart of the City", u"http://www.gocomics.com/heartofthecity"),
# (u"Heathcliff", u"http://www.gocomics.com/heathcliff"),
# (u"Herb and Jamaal", u"http://www.gocomics.com/herbandjamaal"),
# (u"Home and Away", u"http://www.gocomics.com/homeandaway"),
# (u"Housebroken", u"http://www.gocomics.com/housebroken"),
# (u"Hubert and Abby", u"http://www.gocomics.com/hubertandabby"),
# (u"Imagine This", u"http://www.gocomics.com/imaginethis"),
# (u"In the Bleachers", u"http://www.gocomics.com/inthebleachers"),
# (u"In the Sticks", u"http://www.gocomics.com/inthesticks"),
# (u"Ink Pen", u"http://www.gocomics.com/inkpen"),
# (u"It's All About You", u"http://www.gocomics.com/itsallaboutyou"),
# (u"Joe Vanilla", u"http://www.gocomics.com/joevanilla"),
# (u"La Cucaracha", u"http://www.gocomics.com/lacucaracha"),
# (u"Last Kiss", u"http://www.gocomics.com/lastkiss"),
# (u"Legend of Bill", u"http://www.gocomics.com/legendofbill"),
# (u"Liberty Meadows", u"http://www.gocomics.com/libertymeadows"),
(u"Lio", u"http://www.gocomics.com/lio"),
# (u"Little Dog Lost", u"http://www.gocomics.com/littledoglost"),
# (u"Little Otto", u"http://www.gocomics.com/littleotto"),
# (u"Loose Parts", u"http://www.gocomics.com/looseparts"),
# (u"Love Is...", u"http://www.gocomics.com/loveis"),
# (u"Maintaining", u"http://www.gocomics.com/maintaining"),
# (u"The Meaning of Lila", u"http://www.gocomics.com/meaningoflila"),
# (u"Middle-Aged White Guy", u"http://www.gocomics.com/middleagedwhiteguy"),
# (u"The Middletons", u"http://www.gocomics.com/themiddletons"),
# (u"Momma", u"http://www.gocomics.com/momma"),
# (u"Mutt & Jeff", u"http://www.gocomics.com/muttandjeff"),
# (u"Mythtickle", u"http://www.gocomics.com/mythtickle"),
# (u"Nest Heads", u"http://www.gocomics.com/nestheads"),
# (u"NEUROTICA", u"http://www.gocomics.com/neurotica"),
(u"New Adventures of Queen Victoria", u"http://www.gocomics.com/thenewadventuresofqueenvictoria"),
(u"Non Sequitur", u"http://www.gocomics.com/nonsequitur"),
# (u"The Norm", u"http://www.gocomics.com/thenorm"),
# (u"On A Claire Day", u"http://www.gocomics.com/onaclaireday"),
# (u"One Big Happy", u"http://www.gocomics.com/onebighappy"),
# (u"The Other Coast", u"http://www.gocomics.com/theothercoast"),
# (u"Out of the Gene Pool Re-Runs", u"http://www.gocomics.com/outofthegenepool"),
# (u"Overboard", u"http://www.gocomics.com/overboard"),
# (u"Pibgorn", u"http://www.gocomics.com/pibgorn"),
# (u"Pibgorn Sketches", u"http://www.gocomics.com/pibgornsketches"),
(u"Pickles", u"http://www.gocomics.com/pickles"),
# (u"Pinkerton", u"http://www.gocomics.com/pinkerton"),
# (u"Pluggers", u"http://www.gocomics.com/pluggers"),
(u"Pooch Cafe", u"http://www.gocomics.com/poochcafe"),
# (u"PreTeena", u"http://www.gocomics.com/preteena"),
# (u"The Quigmans", u"http://www.gocomics.com/thequigmans"),
# (u"Rabbits Against Magic", u"http://www.gocomics.com/rabbitsagainstmagic"),
(u"Real Life Adventures", u"http://www.gocomics.com/reallifeadventures"),
# (u"Red and Rover", u"http://www.gocomics.com/redandrover"),
# (u"Red Meat", u"http://www.gocomics.com/redmeat"),
# (u"Reynolds Unwrapped", u"http://www.gocomics.com/reynoldsunwrapped"),
# (u"Ronaldinho Gaucho", u"http://www.gocomics.com/ronaldinhogaucho"),
# (u"Rubes", u"http://www.gocomics.com/rubes"),
# (u"Scary Gary", u"http://www.gocomics.com/scarygary"),
(u"Shoe", u"http://www.gocomics.com/shoe"),
# (u"Shoecabbage", u"http://www.gocomics.com/shoecabbage"),
# (u"Skin Horse", u"http://www.gocomics.com/skinhorse"),
# (u"Slowpoke", u"http://www.gocomics.com/slowpoke"),
# (u"Speed Bump", u"http://www.gocomics.com/speedbump"),
# (u"State of the Union", u"http://www.gocomics.com/stateoftheunion"),
(u"Stone Soup", u"http://www.gocomics.com/stonesoup"),
# (u"Strange Brew", u"http://www.gocomics.com/strangebrew"),
# (u"Sylvia", u"http://www.gocomics.com/sylvia"),
# (u"Tank McNamara", u"http://www.gocomics.com/tankmcnamara"),
# (u"Tiny Sepuku", u"http://www.gocomics.com/tinysepuku"),
# (u"TOBY", u"http://www.gocomics.com/toby"),
# (u"Tom the Dancing Bug", u"http://www.gocomics.com/tomthedancingbug"),
# (u"Too Much Coffee Man", u"http://www.gocomics.com/toomuchcoffeeman"),
# (u"W.T. Duck", u"http://www.gocomics.com/wtduck"),
# (u"Watch Your Head", u"http://www.gocomics.com/watchyourhead"),
# (u"Wee Pals", u"http://www.gocomics.com/weepals"),
# (u"Winnie the Pooh", u"http://www.gocomics.com/winniethepooh"),
(u"Wizard of Id", u"http://www.gocomics.com/wizardofid"),
# (u"Working It Out", u"http://www.gocomics.com/workingitout"),
# (u"Yenny", u"http://www.gocomics.com/yenny"),
# (u"Zack Hill", u"http://www.gocomics.com/zackhill"),
(u"Ziggy", u"http://www.gocomics.com/ziggy"),
######## COMICS - EDITORIAL ########
("Lalo Alcaraz","http://www.gocomics.com/laloalcaraz"),
("Nick Anderson","http://www.gocomics.com/nickanderson"),
("Chuck Asay","http://www.gocomics.com/chuckasay"),
("Tony Auth","http://www.gocomics.com/tonyauth"),
("Donna Barstow","http://www.gocomics.com/donnabarstow"),
# ("Bruce Beattie","http://www.gocomics.com/brucebeattie"),
# ("Clay Bennett","http://www.gocomics.com/claybennett"),
# ("Lisa Benson","http://www.gocomics.com/lisabenson"),
# ("Steve Benson","http://www.gocomics.com/stevebenson"),
# ("Chip Bok","http://www.gocomics.com/chipbok"),
# ("Steve Breen","http://www.gocomics.com/stevebreen"),
# ("Chris Britt","http://www.gocomics.com/chrisbritt"),
# ("Stuart Carlson","http://www.gocomics.com/stuartcarlson"),
# ("Ken Catalino","http://www.gocomics.com/kencatalino"),
# ("Paul Conrad","http://www.gocomics.com/paulconrad"),
# ("Jeff Danziger","http://www.gocomics.com/jeffdanziger"),
# ("Matt Davies","http://www.gocomics.com/mattdavies"),
# ("John Deering","http://www.gocomics.com/johndeering"),
# ("Bob Gorrell","http://www.gocomics.com/bobgorrell"),
# ("Walt Handelsman","http://www.gocomics.com/walthandelsman"),
# ("Clay Jones","http://www.gocomics.com/clayjones"),
# ("Kevin Kallaugher","http://www.gocomics.com/kevinkallaugher"),
# ("Steve Kelley","http://www.gocomics.com/stevekelley"),
# ("Dick Locher","http://www.gocomics.com/dicklocher"),
# ("Chan Lowe","http://www.gocomics.com/chanlowe"),
# ("Mike Luckovich","http://www.gocomics.com/mikeluckovich"),
# ("Gary Markstein","http://www.gocomics.com/garymarkstein"),
# ("Glenn McCoy","http://www.gocomics.com/glennmccoy"),
# ("Jim Morin","http://www.gocomics.com/jimmorin"),
# ("Jack Ohman","http://www.gocomics.com/jackohman"),
# ("Pat Oliphant","http://www.gocomics.com/patoliphant"),
# ("Joel Pett","http://www.gocomics.com/joelpett"),
# ("Ted Rall","http://www.gocomics.com/tedrall"),
# ("Michael Ramirez","http://www.gocomics.com/michaelramirez"),
# ("Marshall Ramsey","http://www.gocomics.com/marshallramsey"),
# ("Steve Sack","http://www.gocomics.com/stevesack"),
# ("Ben Sargent","http://www.gocomics.com/bensargent"),
# ("Drew Sheneman","http://www.gocomics.com/drewsheneman"),
# ("John Sherffius","http://www.gocomics.com/johnsherffius"),
# ("Small World","http://www.gocomics.com/smallworld"),
# ("Scott Stantis","http://www.gocomics.com/scottstantis"),
# ("Wayne Stayskal","http://www.gocomics.com/waynestayskal"),
# ("Dana Summers","http://www.gocomics.com/danasummers"),
# ("Paul Szep","http://www.gocomics.com/paulszep"),
# ("Mike Thompson","http://www.gocomics.com/mikethompson"),
# ("Tom Toles","http://www.gocomics.com/tomtoles"),
# ("Gary Varvel","http://www.gocomics.com/garyvarvel"),
# ("ViewsAfrica","http://www.gocomics.com/viewsafrica"),
# ("ViewsAmerica","http://www.gocomics.com/viewsamerica"),
# ("ViewsAsia","http://www.gocomics.com/viewsasia"),
# ("ViewsBusiness","http://www.gocomics.com/viewsbusiness"),
# ("ViewsEurope","http://www.gocomics.com/viewseurope"),
# ("ViewsLatinAmerica","http://www.gocomics.com/viewslatinamerica"),
# ("ViewsMidEast","http://www.gocomics.com/viewsmideast"),
# ("Views of the World","http://www.gocomics.com/viewsoftheworld"),
# ("Kerry Waghorn","http://www.gocomics.com/facesinthenews"),
# ("Dan Wasserman","http://www.gocomics.com/danwasserman"),
# ("Signe Wilkinson","http://www.gocomics.com/signewilkinson"),
# ("Wit of the World","http://www.gocomics.com/witoftheworld"),
# ("Don Wright","http://www.gocomics.com/donwright"),
]:
articles = self.make_links(url)
if articles:
feeds.append((title, articles))
return feeds
def make_links(self, url):
title = 'Temp'
current_articles = []
pages = range(1, self.num_comics_to_get+1)
for page in pages:
page_soup = self.index_to_soup(url)
if page_soup:
try:
strip_title = page_soup.h1.a.string
except:
strip_title = 'Error - no page_soup.h1.a.string'
try:
date_title = page_soup.find('ul', attrs={'class': 'feature-nav'}).li.string
except:
date_title = 'Error - no page_soup.h1.li.string'
title = strip_title + ' - ' + date_title
for i in range(2):
try:
strip_url_date = page_soup.h1.a['href']
break #success - this is normal exit
except:
continue #try to get strip_url_date again
continue # give up on this strip date
for i in range(2):
try:
prev_strip_url_date = page_soup.find('a', attrs={'class': 'prev'})['href']
break #success - this is normal exit
except:
continue #try to get prev_strip_url_date again
continue # give up on this prev strip date
if strip_url_date:
page_url = 'http://www.gocomics.com' + strip_url_date
else:
continue
if prev_strip_url_date:
prev_page_url = 'http://www.gocomics.com' + prev_strip_url_date
else:
continue
current_articles.append({'title': title, 'url': page_url, 'description':'', 'date':''})
url = prev_page_url
current_articles.reverse()
return current_articles
def preprocess_html(self, soup):
if soup.title:
title_string = soup.title.string.strip()
_cd = title_string.split(',',1)[1]
comic_date = ' '.join(_cd.split(' ', 4)[0:-1])
if soup.h1.span:
artist = soup.h1.span.string
soup.h1.span.string.replaceWith(comic_date + artist)
feature_item = soup.find('p',attrs={'class':'feature_item'})
if feature_item.a:
a_tag = feature_item.a
a_href = a_tag["href"]
img_tag = a_tag.img
img_tag["src"] = a_href
img_tag["width"] = self.comic_size
img_tag["height"] = None
return self.adeify_images(soup)
extra_css = '''
h1{font-family:Arial,Helvetica,sans-serif; font-weight:bold;font-size:large;}
h2{font-family:Arial,Helvetica,sans-serif; font-weight:normal;font-size:small;}
img {max-width:100%; min-width:100%;}
p{font-family:Arial,Helvetica,sans-serif;font-size:small;}
body{font-family:Helvetica,Arial,sans-serif;font-size:small;}
'''

View File

@ -1,13 +1,10 @@
#!/usr/bin/env python
__license__ = 'GPL v3'
__copyright__ = '2008-2009, Darko Miletic <darko.miletic at gmail.com>'
__copyright__ = '2008-2010, Darko Miletic <darko.miletic at gmail.com>'
'''
economictimes.indiatimes.com
'''
from calibre.web.feeds.news import BasicNewsRecipe
from calibre.ebooks.BeautifulSoup import Tag
class TheEconomicTimes(BasicNewsRecipe):
title = 'The Economic Times India'
@ -21,18 +18,21 @@ class TheEconomicTimes(BasicNewsRecipe):
use_embedded_content = False
simultaneous_downloads = 1
encoding = 'utf-8'
lang = 'en-IN'
language = 'en_IN'
html2lrf_options = [
'--comment', description
, '--category', category
, '--publisher', publisher
, '--ignore-tables'
]
html2epub_options = 'publisher="' + publisher + '"\ncomments="' + description + '"\ntags="' + category + '"\nlinearize_tables=True'
language = 'en_IN'
publication_type = 'newspaper'
masthead_url = 'http://economictimes.indiatimes.com/photo/2676871.cms'
extra_css = """ body{font-family: Arial,Helvetica,sans-serif}
.heading1{font-size: xx-large; font-weight: bold} """
conversion_options = {
'comment' : description
, 'tags' : category
, 'publisher' : publisher
, 'language' : language
}
keep_only_tags = [dict(attrs={'class':['heading1','headingnext','Normal']})]
remove_tags = [dict(name=['object','link','embed','iframe','base','table','meta'])]
feeds = [(u'All articles', u'http://economictimes.indiatimes.com/rssfeedsdefault.cms')]
@ -47,11 +47,6 @@ class TheEconomicTimes(BasicNewsRecipe):
return rurl
def preprocess_html(self, soup):
soup.html['xml:lang'] = self.lang
soup.html['lang'] = self.lang
mlang = Tag(soup,'meta',[("http-equiv","Content-Language"),("content",self.lang)])
mcharset = Tag(soup,'meta',[("http-equiv","Content-Type"),("content","text/html; charset=utf-8")])
soup.head.insert(0,mlang)
soup.head.insert(1,mcharset)
for item in soup.findAll(style=True):
del item['style']
return self.adeify_images(soup)

View File

@ -1,244 +0,0 @@
Changes from 4.0 to 4.0.1
1) Added support for Python 2.6. On Windows a manifest file is now required
because of the switch to using the new Microsoft C runtime.
2) Ensure that hooks are run for builtin modules.
Changes from 4.0b1 to 4.0
1) Added support for copying files to the target directory.
2) Added support for a hook that runs when a module is missing.
3) Added support for binary path includes as well as excludes; use sequences
rather than dictionaries as a more convenient API; exclude the standard
locations for 32-bit and 64-bit libaries in multi-architecture systems.
4) Added support for searching zip files (egg files) for modules.
5) Added support for handling system exit exceptions similarly to what Python
does itself as requested by Sylvain.
6) Added code to wait for threads to shut down like the normal Python
interpreter does. Thanks to Mariano Disanzo for discovering this
discrepancy.
7) Hooks added or modified based on feedback from many people.
8) Don't include the version name in the display name of the MSI.
9) Use the OS dependent path normalization routines rather than simply use the
lowercase value as on Unix case is important; thanks to Artie Eoff for
pointing this out.
10) Include a version attribute in the cx_Freeze package and display it in the
output for the --version option to the script.
11) Include build instructions as requested by Norbert Sebok.
12) Add support for copying files when modules are included which require data
files to operate properly; add support for copying the necessary files for
the Tkinter and matplotlib modules.
13) Handle deferred imports recursively as needed; ensure that from lists do
not automatically indicate that they are part of the module or the deferred
import processing doesn't actually work!
14) Handle the situation where a module imports everything from a package and
the __all__ variable has been defined but the package has not actually
imported everything in the __all__ variable during initialization.
15) Modified license text to more closely match the Python Software Foundation
license as was intended.
16) Added sample script for freezing an application using matplotlib.
17) Renamed freeze to cxfreeze to avoid conflict with another package that uses
that executable as requested by Siegfried Gevatter.
Changes from 3.0.3 to 4.0b1
1) Added support for placing modules in library.zip or in a separate zip file
for each executable that is produced.
2) Added support for copying binary dependent files (DLLs and shared
libraries)
3) Added support for including all submodules in a package
4) Added support for including icons in Windows executables
5) Added support for constants module which can be used for determining
certain build constants at runtime
6) Added support for relative imports available in Python 2.5 and up
7) Added support for building Windows installers (Python 2.5 and up) and
RPM packages
8) Added support for distutils configuration scripts
9) Added support for hooks which can force inclusion or exclusion of modules
when certain modules are included
10) Added documentation and samples
11) Added setup.py for building the cx_Freeze package instead of a script
used to build only the frozen bases
12) FreezePython renamed to a script called freeze in the Python distribution
13) On Linux and other platforms that support it set LD_RUN_PATH to include
the directory in which the executable is located
Changes from 3.0.2 to 3.0.3
1) In Common.c, used MAXPATHLEN defined in the Python OS independent include
file rather than the PATH_MAX define which is OS dependent and is not
available on IRIX as noted by Andrew Jones.
2) In the initscript ConsoleSetLibPath.py, added lines from initscript
Console.py that should have been there since the only difference between
that script and this one is the automatic re-execution of the executable.
3) Added an explicit "import encodings" to the initscripts in order to handle
Unicode encodings a little better. Thanks to Ralf Schmitt for pointing out
the problem and its solution.
4) Generated a meaningful name for the extension loader script so that it is
clear which particular extension module is being loaded when an exception
is being raised.
5) In MakeFrozenBases.py, use distutils to figure out a few more
platform-dependent linker flags as suggested by Ralf Schmitt.
Changes from 3.0.1 to 3.0.2
1) Add support for compressing the byte code in the zip files that are
produced.
2) Add better support for the win32com package as requested by Barry Scott.
3) Prevent deletion of target file if it happens to be identical to the
source file.
4) Include additional flags for local modifications to a Python build as
suggested by Benjamin Rutt.
5) Expanded instructions for building cx_Freeze from source based on a
suggestion from Gregg Lind.
6) Fix typo in help string.
Changes from 3.0 to 3.0.1
1) Added option --default-path which is used to specify the path used when
finding modules. This is particularly useful when performing cross
compilations (such as for building a frozen executable for Windows CE).
2) Added option --shared-lib-name which can be used to specify the name of
the shared library (DLL) implementing the Python runtime that is required
for the frozen executable to work. This option is also particularly useful
when cross compiling since the normal method for determining this
information cannot be used.
3) Added option --zip-include which allows for additional files to be added
to the zip file that contains the modules that implement the Python
script. Thanks to Barray Warsaw for providing the initial patch.
4) Added support for handling read-only files properly. Thanks to Peter
Grayson for pointing out the problem and providing a solution.
5) Added support for a frozen executable to be a symbolic link. Thanks to
Robert Kiendl for providing the initial patch.
6) Enhanced the support for running a frozen executable that uses an existing
Python installation to locate modules it requires. This is primarily of
use for embedding Python where the interface is C but the ability to run
from source is still desired.
7) Modified the documentation to indicate that building from source on
Windows currently requires the mingw compiler (http://www.mingw.org).
8) Workaround the problem in Python 2.3 (fixed in Python 2.4) which causes a
broken module to be left in sys.modules if an ImportError takes place
during the execution of the code in that module. Thanks to Roger Binns
for pointing this out.
Changes from 3.0 beta3 to 3.0
1) Ensure that ldd is only run on extension modules.
2) Allow for using a compiler other than gcc for building the frozen base
executables by setting the environment variable CC.
3) Ensure that the import lock is not held while executing the main script;
otherwise, attempts to import a module within a thread will hang that
thread as noted by Roger Binns.
4) Added support for replacing the paths in all frozen modules with something
else (so that for example the path of the machine on which the freezing
was done is not displayed in tracebacks)
Changes from 3.0 beta2 to 3.0 beta3
1) Explicitly include the warnings module so that at runtime warnings are
suppressed as when running Python normally.
2) Improve the extension loader so that an ImportError is raised when the
dynamic module is not located; otherwise an error about missing attributes
is raised instead.
3) Extension loaders are only created when copying dependencies since the
normal module should be loadable in the situation where a Python
installation is available.
4) Added support for Python 2.4.
5) Fixed the dependency checking for wxPython to be a little more
intelligent.
Changes from 3.0 beta1 to 3.0 beta2
1) Fix issues with locating the initscripts and bases relative to the
directory in which the executable was started.
2) Added new base executable ConsoleKeepPath which is used when an existing
Python installation is required (such as for FreezePython itself).
3) Forced the existence of a Python installation to be ignored when using the
standard Console base executable.
4) Remove the existing file when copying dependent files; otherwise, an error
is raised when attempting to overwrite read-only files.
5) Added option -O (or -OO) to FreezePython to set the optimization used when
generating bytecode.
Changes from 2.2 to 3.0 beta1
1) cx_Freeze now requires Python 2.3 or higher since it takes advantage of
the ability of Python 2.3 and higher to import modules from zip files.
This makes the freezing process considerably simpler and also allows for
the execution of multiple frozen packages (such as found in COM servers or
shared libraries) without requiring modification to the Python modules.
2) All external dependencies have been removed. cx_Freeze now only requires
a standard Python distribution to do its work.
3) Added the ability to define the initialization scripts that cx_Freeze uses
on startup of the frozen program. Previously, these scripts were written
in C and could not easily be changed; now they are written in Python and
can be found in the initscripts directory (and chosen with the
new --init-script option to FreezePython).
4) The base executable ConsoleSetLibPath has been removed and replaced with
the initscript ConsoleSetLibPath.
5) Removed base executables for Win32 services and Win32 COM servers. This
functionality will be restored in the future but it is not currently in a
state that is ready for release. If this functionality is required, please
use py2exe or contact me for my work in progress.
6) The attribute sys.frozen is now set so that more recent pywin32 modules
work as expected when frozen.
7) Added option --include-path to FreezePython to allow overriding of
sys.path without modifying the environment variable PYTHONPATH.
8) Added option --target-dir/--install-dir to specify the directory in which
the frozen executable and its dependencies will be placed.
9) Removed the option --shared-lib since it was used for building shared
libraries and can be managed with the initscript SharedLib.py.
10) MakeFrozenBases.py now checks the platform specific include directory as
requested by Michael Partridge.
Changes from 2.1 to 2.2
1) Add option (--ext-list-file) to FreezePython to write the list of
extensions copied to the installation directory to a file. This option is
useful in cases where multiple builds are performed into the same
installation directory.
2) Pass the arguments on the command line through to Win32 GUI applications.
Thanks to Michael Porter for pointing this out.
3) Link directly against the python DLL when building the frozen bases on
Windows, thus eliminating the need for building an import library.
4) Force sys.path to include the directory in which the script to be frozen
is found.
5) Make sure that the installation directory exists before attempting to
copy the target binary into it.
6) The Win32GUI base has been modified to display fatal errors in message
boxes, rather than printing errors to stderr, since on Windows the
standard file IO handles are all closed.
Changes from 2.0 to 2.1
1) Remove dependency on Python 2.2. Thanks to Paul Moore for not only
pointing it out but providing patches.
2) Set up the list of frozen modules in advance, rather than doing it after
Python is initialized so that implicit imports done by Python can be
satisfied. The bug in Python 2.3 that demonstrated this issue has been
fixed in the first release candidate. Thanks to Thomas Heller for pointing
out the obvious in this instance!
3) Added additional base executable (ConsoleSetLibPath) to support setting
the LD_LIBRARY_PATH variable on Unix platforms and restarting the
executable to put the new setting into effect. This is primarily of use
in distributing wxPython applications on Unix where the shared library
has an embedded RPATH value which can cause problems.
4) Small improvements of documentation based on feedback from several people.
5) Print information about the files written or copied during the freezing
process.
6) Do not copy extensions when freezing if the path is being overridden since
it is expected that a full Python installation is available to the target
users of the frozen binary.
7) Provide meaningful error message when the wxPython library cannot be
found during the freezing process.
Changes from 1.1 to 2.0
1) Added support for in process (DLL) COM servers using PythonCOM.
2) Ensured that the frozen flag is set prior to determining the full path for
the program in order to avoid warnings about Python not being found on
some platforms.
3) Added include file and resource file to the source tree to avoid the
dependency on the Wine message compiler for Win32 builds.
4) Dropped the option --copy-extensions; this now happens automatically since
the resulting binary is useless without them.
5) Added a sample for building a Win32 service.
6) Make use of improved modules from Python 2.3 (which function under 2.2)
Changes from 1.0 to 1.1
1) Fixed import error with C extensions in packages; thanks to Thomas Heller
for pointing out the solution to this problem.
2) Added options to FreezePython to allow for the inclusion of modules which
will not be found by the module finder (--include-modules) and the
exclusion of modules which will be found by the module finder but should
not be included (--exclude-modules).
3) Fixed typo in README.txt.

View File

@ -1,53 +0,0 @@
Copyright © 2007-2008, Colt Engineering, Edmonton, Alberta, Canada.
Copyright © 2001-2006, Computronix (Canada) Ltd., Edmonton, Alberta, Canada.
All rights reserved.
NOTE: this license is derived from the Python Software Foundation License
which can be found at http://www.python.org/psf/license
License for cx_Freeze 4.0.1
---------------------------
1. This LICENSE AGREEMENT is between the copyright holders and the Individual
or Organization ("Licensee") accessing and otherwise using cx_Freeze
software in source or binary form and its associated documentation.
2. Subject to the terms and conditions of this License Agreement, the
copyright holders hereby grant Licensee a nonexclusive, royalty-free,
world-wide license to reproduce, analyze, test, perform and/or display
publicly, prepare derivative works, distribute, and otherwise use cx_Freeze
alone or in any derivative version, provided, however, that this License
Agreement and this notice of copyright are retained in cx_Freeze alone or in
any derivative version prepared by Licensee.
3. In the event Licensee prepares a derivative work that is based on or
incorporates cx_Freeze or any part thereof, and wants to make the derivative
work available to others as provided herein, then Licensee hereby agrees to
include in any such work a brief summary of the changes made to cx_Freeze.
4. The copyright holders are making cx_Freeze available to Licensee on an
"AS IS" basis. THE COPYRIGHT HOLDERS MAKE NO REPRESENTATIONS OR WARRANTIES,
EXPRESS OR IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, THE COPYRIGHT
HOLDERS MAKE NO AND DISCLAIM ANY REPRESENTATION OR WARRANTY OF
MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF
CX_FREEZE WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.
5. THE COPYRIGHT HOLDERS SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF
CX_FREEZE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING CX_FREEZE, OR ANY
DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
6. This License Agreement will automatically terminate upon a material breach
of its terms and conditions.
7. Nothing in this License Agreement shall be deemed to create any relationship
of agency, partnership, or joint venture between the copyright holders and
Licensee. This License Agreement does not grant permission to use
copyright holder's trademarks or trade name in a trademark sense to endorse
or promote products or services of Licensee, or any third party.
8. By copying, installing or otherwise using cx_Freeze, Licensee agrees to be
bound by the terms and conditions of this License Agreement.
Computronix® is a registered trademark of Computronix (Canada) Ltd.

View File

@ -1,6 +0,0 @@
include MANIFEST.in
include *.txt
recursive-include doc *.html
recursive-include initscripts *.py
recursive-include samples *.py
recursive-include source *.c *.rc

View File

@ -1,22 +0,0 @@
Metadata-Version: 1.0
Name: cx_Freeze
Version: 4.0.1
Summary: create standalone executables from Python scripts
Home-page: http://cx-freeze.sourceforge.net
Author: Anthony Tuininga
Author-email: anthony.tuininga@gmail.com
License: Python Software Foundation License
Description: create standalone executables from Python scripts
Keywords: freeze
Platform: UNKNOWN
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: Python Software Foundation License
Classifier: Natural Language :: English
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: C
Classifier: Programming Language :: Python
Classifier: Topic :: Software Development :: Build Tools
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: System :: Software Distribution
Classifier: Topic :: Utilities

View File

@ -1,12 +0,0 @@
Please see cx_Freeze.html for documentation on how to use cx_Freeze.
To build:
python setup.py build
python setup.py install
On Windows I have used the MinGW compiler (http://www.mingw.org)
python setup.py build --compiler=mingw32
python setup.py build --compiler=mingw32 install

View File

@ -1,14 +0,0 @@
version = "4.0.1"
import sys
from dist import *
if sys.platform == "win32" and sys.version_info[:2] >= (2, 5):
from windist import *
from finder import *
from freezer import *
from main import *
del dist
del finder
del freezer

View File

@ -1,279 +0,0 @@
import distutils.command.bdist_rpm
import distutils.command.build
import distutils.command.install
import distutils.core
import distutils.dir_util
import distutils.dist
import distutils.util
import distutils.version
import os
import sys
import cx_Freeze
__all__ = [ "bdist_rpm", "build", "build_exe", "install", "install_exe",
"setup" ]
class Distribution(distutils.dist.Distribution):
def __init__(self, attrs):
self.executables = []
distutils.dist.Distribution.__init__(self, attrs)
class bdist_rpm(distutils.command.bdist_rpm.bdist_rpm):
def finalize_options(self):
distutils.command.bdist_rpm.bdist_rpm.finalize_options(self)
self.use_rpm_opt_flags = 1
def _make_spec_file(self):
contents = distutils.command.bdist_rpm.bdist_rpm._make_spec_file(self)
return [c for c in contents if c != 'BuildArch: noarch']
class build(distutils.command.build.build):
user_options = distutils.command.build.build.user_options + [
('build-exe=', None, 'build directory for executables')
]
def get_sub_commands(self):
subCommands = distutils.command.build.build.get_sub_commands(self)
if self.distribution.executables:
subCommands.append("build_exe")
return subCommands
def initialize_options(self):
distutils.command.build.build.initialize_options(self)
self.build_exe = None
def finalize_options(self):
distutils.command.build.build.finalize_options(self)
if self.build_exe is None:
dirName = "exe.%s-%s" % \
(distutils.util.get_platform(), sys.version[0:3])
self.build_exe = os.path.join(self.build_base, dirName)
class build_exe(distutils.core.Command):
description = "build executables from Python scripts"
user_options = [
('build-exe=', 'b',
'directory for built executables'),
('optimize=', 'O',
'optimization level: -O1 for "python -O", '
'-O2 for "python -OO" and -O0 to disable [default: -O0]'),
('excludes=', 'e',
'comma-separated list of modules to exclude'),
('includes=', 'i',
'comma-separated list of modules to include'),
('packages=', 'p',
'comma-separated list of packages to include'),
('replace-paths=', None,
'comma-separated list of paths to replace in included modules'),
('path=', None,
'comma-separated list of paths to search'),
('init-script=', 'i',
'name of script to use during initialization'),
('base=', None,
'name of base executable to use'),
('compressed', 'c',
'create a compressed zipfile'),
('copy-dependent-files', None,
'copy all dependent files'),
('create-shared-zip', None,
'create a shared zip file containing shared modules'),
('append-script-to-exe', None,
'append the script module to the exe'),
('include-in-shared-zip', None,
'include the script module in the shared zip file'),
('icon', None,
'include the icon along with the frozen executable(s)'),
('constants=', None,
'comma-separated list of constants to include'),
('include-files=', 'f',
'list of tuples of additional files to include in distribution'),
('bin-includes', None,
'list of names of files to include when determining dependencies'),
('bin-excludes', None,
'list of names of files to exclude when determining dependencies')
]
boolean_options = ["compressed", "copy_dependent_files",
"create_shared_zip", "append_script_to_exe",
"include_in_shared_zip"]
def _normalize(self, attrName):
value = getattr(self, attrName)
if value is None:
normalizedValue = []
elif isinstance(value, basestring):
normalizedValue = value.split()
else:
normalizedValue = list(value)
setattr(self, attrName, normalizedValue)
def initialize_options(self):
self.optimize = 0
self.build_exe = None
self.excludes = []
self.includes = []
self.packages = []
self.replace_paths = []
self.compressed = None
self.copy_dependent_files = None
self.init_script = None
self.base = None
self.path = None
self.create_shared_zip = None
self.append_script_to_exe = None
self.include_in_shared_zip = None
self.icon = None
self.constants = []
self.include_files = []
self.bin_excludes = []
self.bin_includes = []
def finalize_options(self):
self.set_undefined_options('build', ('build_exe', 'build_exe'))
self.optimize = int(self.optimize)
self._normalize("excludes")
self._normalize("includes")
self._normalize("packages")
self._normalize("constants")
def run(self):
metadata = self.distribution.metadata
constantsModule = cx_Freeze.ConstantsModule(metadata.version)
for constant in self.constants:
parts = constant.split("=")
if len(parts) == 1:
name = constant
value = None
else:
name, stringValue = parts
value = eval(stringValue)
constantsModule.values[name] = value
freezer = cx_Freeze.Freezer(self.distribution.executables,
[constantsModule], self.includes, self.excludes, self.packages,
self.replace_paths, self.compressed, self.optimize,
self.copy_dependent_files, self.init_script, self.base,
self.path, self.create_shared_zip, self.append_script_to_exe,
self.include_in_shared_zip, self.build_exe, icon = self.icon,
includeFiles = self.include_files,
binIncludes = self.bin_includes,
binExcludes = self.bin_excludes)
freezer.Freeze()
class install(distutils.command.install.install):
user_options = distutils.command.install.install.user_options + [
('install-exe=', None,
'installation directory for executables')
]
def expand_dirs(self):
distutils.command.install.install.expand_dirs(self)
self._expand_attrs(['install_exe'])
def get_sub_commands(self):
subCommands = distutils.command.install.install.get_sub_commands(self)
if self.distribution.executables:
subCommands.append("install_exe")
return [s for s in subCommands if s != "install_egg_info"]
def initialize_options(self):
distutils.command.install.install.initialize_options(self)
self.install_exe = None
def finalize_options(self):
if self.prefix is None and sys.platform == "win32":
import _winreg
key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,
r"Software\Microsoft\Windows\CurrentVersion")
prefix = str(_winreg.QueryValueEx(key, "ProgramFilesDir")[0])
metadata = self.distribution.metadata
dirName = "%s-%s" % (metadata.name, metadata.version)
self.prefix = "%s/%s" % (prefix, dirName)
distutils.command.install.install.finalize_options(self)
self.convert_paths('exe')
if self.root is not None:
self.change_roots('exe')
def select_scheme(self, name):
distutils.command.install.install.select_scheme(self, name)
if self.install_exe is None:
if sys.platform == "win32":
self.install_exe = '$base'
else:
metadata = self.distribution.metadata
dirName = "%s-%s" % (metadata.name, metadata.version)
self.install_exe = '$base/lib/%s' % dirName
class install_exe(distutils.core.Command):
description = "install executables built from Python scripts"
user_options = [
('install-dir=', 'd', 'directory to install executables to'),
('build-dir=', 'b', 'build directory (where to install from)'),
('force', 'f', 'force installation (overwrite existing files)'),
('skip-build', None, 'skip the build steps')
]
def initialize_options(self):
self.install_dir = None
self.force = 0
self.build_dir = None
self.skip_build = None
def finalize_options(self):
self.set_undefined_options('build', ('build_exe', 'build_dir'))
self.set_undefined_options('install',
('install_exe', 'install_dir'),
('force', 'force'),
('skip_build', 'skip_build'))
def run(self):
if not self.skip_build:
self.run_command('build_exe')
self.outfiles = self.copy_tree(self.build_dir, self.install_dir)
if sys.platform != "win32":
baseDir = os.path.dirname(os.path.dirname(self.install_dir))
binDir = os.path.join(baseDir, "bin")
if not os.path.exists(binDir):
os.makedirs(binDir)
sourceDir = os.path.join("..", self.install_dir[len(baseDir) + 1:])
for executable in self.distribution.executables:
name = os.path.basename(executable.targetName)
source = os.path.join(sourceDir, name)
target = os.path.join(binDir, name)
if os.path.exists(target):
os.unlink(target)
os.symlink(source, target)
self.outfiles.append(target)
def get_inputs(self):
return self.distribution.executables or []
def get_outputs(self):
return self.outfiles or []
def _AddCommandClass(commandClasses, name, cls):
if name not in commandClasses:
commandClasses[name] = cls
def setup(**attrs):
attrs["distclass"] = Distribution
commandClasses = attrs.setdefault("cmdclass", {})
if sys.platform == "win32":
if sys.version_info[:2] >= (2, 5):
_AddCommandClass(commandClasses, "bdist_msi", cx_Freeze.bdist_msi)
else:
_AddCommandClass(commandClasses, "bdist_rpm", cx_Freeze.bdist_rpm)
_AddCommandClass(commandClasses, "build", build)
_AddCommandClass(commandClasses, "build_exe", build_exe)
_AddCommandClass(commandClasses, "install", install)
_AddCommandClass(commandClasses, "install_exe", install_exe)
distutils.core.setup(**attrs)

View File

@ -1,455 +0,0 @@
"""
Base class for finding modules.
"""
import dis
import imp
import marshal
import new
import opcode
import os
import sys
import zipfile
import cx_Freeze.hooks
BUILD_LIST = opcode.opmap["BUILD_LIST"]
INPLACE_ADD = opcode.opmap["INPLACE_ADD"]
LOAD_CONST = opcode.opmap["LOAD_CONST"]
IMPORT_NAME = opcode.opmap["IMPORT_NAME"]
IMPORT_FROM = opcode.opmap["IMPORT_FROM"]
STORE_NAME = opcode.opmap["STORE_NAME"]
STORE_GLOBAL = opcode.opmap["STORE_GLOBAL"]
STORE_OPS = (STORE_NAME, STORE_GLOBAL)
__all__ = [ "Module", "ModuleFinder" ]
class ModuleFinder(object):
def __init__(self, includeFiles, excludes, path, replacePaths):
self.includeFiles = includeFiles
self.excludes = dict.fromkeys(excludes)
self.replacePaths = replacePaths
self.path = path or sys.path
self.modules = []
self.aliases = {}
self._modules = dict.fromkeys(excludes)
self._builtinModules = dict.fromkeys(sys.builtin_module_names)
self._badModules = {}
self._zipFileEntries = {}
self._zipFiles = {}
cx_Freeze.hooks.initialize(self)
def _AddModule(self, name):
"""Add a module to the list of modules but if one is already found,
then return it instead; this is done so that packages can be
handled properly."""
module = self._modules.get(name)
if module is None:
module = self._modules[name] = Module(name)
self.modules.append(module)
if name in self._badModules:
del self._badModules[name]
return module
def _DetermineParent(self, caller):
"""Determine the parent to use when searching packages."""
if caller is not None:
if caller.path is not None:
return caller
return self._GetParentByName(caller.name)
def _EnsureFromList(self, caller, packageModule, fromList,
deferredImports):
"""Ensure that the from list is satisfied. This is only necessary for
package modules. If the caller is the package itself, actually
attempt to import right then since it must be a submodule; otherwise
defer until after all global names are defined in order to avoid
spurious complaints about missing modules."""
if caller is not packageModule:
deferredImports.append((packageModule, fromList))
else:
if fromList == ("*",):
fromList = packageModule.allNames
for name in fromList:
if name in packageModule.globalNames:
continue
subModuleName = "%s.%s" % (packageModule.name, name)
self._ImportModule(subModuleName, deferredImports, caller)
def _FindModule(self, name, path):
try:
return imp.find_module(name, path)
except ImportError:
if not path:
path = []
for location in path:
if name in self._zipFileEntries:
break
if location in self._zipFiles:
continue
if os.path.isdir(location) or not zipfile.is_zipfile(location):
self._zipFiles[location] = None
continue
zip = zipfile.ZipFile(location)
for archiveName in zip.namelist():
baseName, ext = os.path.splitext(archiveName)
if ext not in ('.pyc', '.pyo'):
continue
moduleName = ".".join(baseName.split("/"))
if moduleName in self._zipFileEntries:
continue
self._zipFileEntries[moduleName] = (zip, archiveName)
self._zipFiles[location] = None
info = self._zipFileEntries.get(name)
if info is not None:
zip, archiveName = info
fp = zip.read(archiveName)
info = (".pyc", "rb", imp.PY_COMPILED)
return fp, os.path.join(zip.filename, archiveName), info
raise
def _GetParentByName(self, name):
"""Return the parent module given the name of a module."""
pos = name.rfind(".")
if pos > 0:
parentName = name[:pos]
return self._modules[parentName]
def _ImportAllSubModules(self, module, deferredImports, recursive = True):
"""Import all sub modules to the given package."""
suffixes = dict.fromkeys([s[0] for s in imp.get_suffixes()])
for dir in module.path:
try:
fileNames = os.listdir(dir)
except os.error:
continue
for fileName in fileNames:
name, ext = os.path.splitext(fileName)
if ext not in suffixes:
continue
if name == "__init__":
continue
subModuleName = "%s.%s" % (module.name, name)
subModule, returnError = \
self._InternalImportModule(subModuleName,
deferredImports)
if returnError and subModule is None:
raise ImportError, "No module named %s" % subModuleName
module.globalNames[name] = None
if subModule.path and recursive:
self._ImportAllSubModules(subModule, deferredImports,
recursive)
def _ImportDeferredImports(self, deferredImports):
"""Import any sub modules that were deferred, if applicable."""
while deferredImports:
newDeferredImports = []
for packageModule, subModuleNames in deferredImports:
self._EnsureFromList(packageModule, packageModule,
subModuleNames, newDeferredImports)
deferredImports = newDeferredImports
def _ImportModule(self, name, deferredImports, caller = None,
relativeImportIndex = 0):
"""Attempt to find the named module and return it or None if no module
by that name could be found."""
# absolute import (available in Python 2.5 and up)
# the name given is the only name that will be searched
if relativeImportIndex == 0:
module, returnError = self._InternalImportModule(name,
deferredImports)
# old style relative import (only possibility in Python 2.4 and prior)
# the name given is tried in all parents until a match is found and if
# no match is found, the global namespace is searched
elif relativeImportIndex < 0:
parent = self._DetermineParent(caller)
while parent is not None:
fullName = "%s.%s" % (parent.name, name)
module, returnError = self._InternalImportModule(fullName,
deferredImports)
if module is not None:
parent.globalNames[name] = None
return module
parent = self._GetParentByName(parent.name)
module, returnError = self._InternalImportModule(name,
deferredImports)
# new style relative import (available in Python 2.5 and up)
# the index indicates how many levels to traverse and only that level
# is searched for the named module
elif relativeImportIndex > 0:
parent = caller
if parent.path is not None:
relativeImportIndex -= 1
while parent is not None and relativeImportIndex > 0:
parent = self._GetParentByName(parent.name)
relativeImportIndex -= 1
if parent is None:
module = None
returnError = True
elif not name:
module = parent
else:
name = "%s.%s" % (parent.name, name)
module, returnError = self._InternalImportModule(name,
deferredImports)
# if module not found, track that fact
if module is None:
if caller is None:
raise ImportError, "No module named %s" % name
self._RunHook("missing", name, caller)
if returnError and name not in caller.ignoreNames:
callers = self._badModules.setdefault(name, {})
callers[caller.name] = None
return module
def _InternalImportModule(self, name, deferredImports):
"""Internal method used for importing a module which assumes that the
name given is an absolute name. None is returned if the module
cannot be found."""
try:
return self._modules[name], False
except KeyError:
pass
if name in self._builtinModules:
module = self._AddModule(name)
self._RunHook("load", module.name, module)
return module, False
pos = name.rfind(".")
if pos < 0:
path = self.path
searchName = name
parentModule = None
else:
parentName = name[:pos]
parentModule, returnError = \
self._InternalImportModule(parentName, deferredImports)
if parentModule is None:
return None, returnError
path = parentModule.path
searchName = name[pos + 1:]
if name in self.aliases:
actualName = self.aliases[name]
module, returnError = \
self._InternalImportModule(actualName, deferredImports)
self._modules[name] = module
return module, returnError
try:
fp, path, info = self._FindModule(searchName, path)
except ImportError:
self._modules[name] = None
return None, True
module = self._LoadModule(name, fp, path, info, deferredImports,
parentModule)
return module, False
def _LoadModule(self, name, fp, path, info, deferredImports,
parent = None):
"""Load the module, given the information acquired by the finder."""
suffix, mode, type = info
if type == imp.PKG_DIRECTORY:
return self._LoadPackage(name, path, parent, deferredImports)
module = self._AddModule(name)
module.file = path
module.parent = parent
if type == imp.PY_SOURCE:
module.code = compile(fp.read() + "\n", path, "exec")
elif type == imp.PY_COMPILED:
if isinstance(fp, str):
magic = fp[:4]
else:
magic = fp.read(4)
if magic != imp.get_magic():
raise ImportError, "Bad magic number in %s" % path
if isinstance(fp, str):
module.code = marshal.loads(fp[8:])
module.inZipFile = True
else:
fp.read(4)
module.code = marshal.load(fp)
self._RunHook("load", module.name, module)
if module.code is not None:
if self.replacePaths:
topLevelModule = module
while topLevelModule.parent is not None:
topLevelModule = topLevelModule.parent
module.code = self._ReplacePathsInCode(topLevelModule,
module.code)
self._ScanCode(module.code, module, deferredImports)
return module
def _LoadPackage(self, name, path, parent, deferredImports):
"""Load the package, given its name and path."""
module = self._AddModule(name)
module.path = [path]
fp, path, info = imp.find_module("__init__", module.path)
self._LoadModule(name, fp, path, info, deferredImports, parent)
return module
def _ReplacePathsInCode(self, topLevelModule, co):
"""Replace paths in the code as directed, returning a new code object
with the modified paths in place."""
origFileName = newFileName = os.path.normpath(co.co_filename)
for searchValue, replaceValue in self.replacePaths:
if searchValue == "*":
searchValue = os.path.dirname(topLevelModule.file)
if topLevelModule.path:
searchValue = os.path.dirname(searchValue)
if searchValue:
searchValue = searchValue + os.pathsep
elif not origFileName.startswith(searchValue):
continue
newFileName = replaceValue + origFileName[len(searchValue):]
break
constants = list(co.co_consts)
for i, value in enumerate(constants):
if isinstance(value, type(co)):
constants[i] = self._ReplacePathsInCode(topLevelModule, value)
return new.code(co.co_argcount, co.co_nlocals, co.co_stacksize,
co.co_flags, co.co_code, tuple(constants), co.co_names,
co.co_varnames, newFileName, co.co_name, co.co_firstlineno,
co.co_lnotab, co.co_freevars, co.co_cellvars)
def _RunHook(self, hookName, moduleName, *args):
"""Run hook for the given module if one is present."""
name = "%s_%s" % (hookName, moduleName.replace(".", "_"))
method = getattr(cx_Freeze.hooks, name, None)
if method is not None:
method(self, *args)
def _ScanCode(self, co, module, deferredImports):
"""Scan code, looking for imported modules and keeping track of the
constants that have been created in order to better tell which
modules are truly missing."""
opIndex = 0
arguments = []
code = co.co_code
numOps = len(code)
while opIndex < numOps:
op = ord(code[opIndex])
opIndex += 1
if op >= dis.HAVE_ARGUMENT:
opArg = ord(code[opIndex]) + ord(code[opIndex + 1]) * 256
opIndex += 2
if op == LOAD_CONST:
arguments.append(co.co_consts[opArg])
elif op == IMPORT_NAME:
name = co.co_names[opArg]
if len(arguments) == 2:
relativeImportIndex, fromList = arguments
else:
relativeImportIndex = -1
fromList, = arguments
if name not in module.excludeNames:
subModule = self._ImportModule(name, deferredImports,
module, relativeImportIndex)
if subModule is not None:
module.globalNames.update(subModule.globalNames)
if fromList and subModule.path is not None:
self._EnsureFromList(module, subModule, fromList,
deferredImports)
elif op == IMPORT_FROM:
opIndex += 3
elif op not in (BUILD_LIST, INPLACE_ADD):
if op in STORE_OPS:
name = co.co_names[opArg]
if name == "__all__":
module.allNames.extend(arguments)
module.globalNames[name] = None
arguments = []
for constant in co.co_consts:
if isinstance(constant, type(co)):
self._ScanCode(constant, module, deferredImports)
def AddAlias(self, name, aliasFor):
"""Add an alias for a particular module; when an attempt is made to
import a module using the alias name, import the actual name
instead."""
self.aliases[name] = aliasFor
def ExcludeModule(self, name):
"""Exclude the named module from the resulting frozen executable."""
self.excludes[name] = None
self._modules[name] = None
def IncludeFile(self, path, moduleName = None):
"""Include the named file as a module in the frozen executable."""
name, ext = os.path.splitext(os.path.basename(path))
if moduleName is None:
moduleName = name
info = (ext, "r", imp.PY_SOURCE)
deferredImports = []
module = self._LoadModule(moduleName, file(path, "U"), path, info,
deferredImports)
self._ImportDeferredImports(deferredImports)
return module
def IncludeFiles(self, sourcePath, targetPath):
"""Include the files in the given directory in the target build."""
self.includeFiles.append((sourcePath, targetPath))
def IncludeModule(self, name):
"""Include the named module in the frozen executable."""
deferredImports = []
module = self._ImportModule(name, deferredImports)
self._ImportDeferredImports(deferredImports)
return module
def IncludePackage(self, name):
"""Include the named package and any submodules in the frozen
executable."""
deferredImports = []
module = self._ImportModule(name, deferredImports)
if module.path:
self._ImportAllSubModules(module, deferredImports)
self._ImportDeferredImports(deferredImports)
return module
def ReportMissingModules(self):
if self._badModules:
print "Missing modules:"
names = self._badModules.keys()
names.sort()
for name in names:
callers = self._badModules[name].keys()
callers.sort()
print "?", name, "imported from", ", ".join(callers)
print
class Module(object):
def __init__(self, name):
self.name = name
self.file = None
self.path = None
self.code = None
self.parent = None
self.globalNames = {}
self.excludeNames = {}
self.ignoreNames = {}
self.allNames = []
self.inZipFile = False
def __repr__(self):
parts = ["name=%s" % repr(self.name)]
if self.file is not None:
parts.append("file=%s" % repr(self.file))
if self.path is not None:
parts.append("path=%s" % repr(self.path))
return "<Module %s>" % ", ".join(parts)
def AddGlobalName(self, name):
self.globalNames[name] = None
def ExcludeName(self, name):
self.excludeNames[name] = None
def IgnoreName(self, name):
self.ignoreNames[name] = None

View File

@ -1,550 +0,0 @@
"""
Base class for freezing scripts into executables.
"""
import datetime
import distutils.sysconfig
import imp
import marshal
import os
import shutil
import socket
import stat
import struct
import sys
import time
import zipfile
import cx_Freeze
import cx_Freeze.util
__all__ = [ "ConfigError", "ConstantsModule", "Executable", "Freezer" ]
if sys.platform == "win32":
pythonDll = "python%s%s.dll" % sys.version_info[:2]
GLOBAL_BIN_PATH_EXCLUDES = [cx_Freeze.util.GetSystemDir()]
GLOBAL_BIN_INCLUDES = [
pythonDll,
"gdiplus.dll",
"mfc71.dll",
"msvcp71.dll",
"msvcr71.dll"
]
GLOBAL_BIN_EXCLUDES = [
"comctl32.dll",
"oci.dll",
"cx_Logging.pyd"
]
else:
extension = distutils.sysconfig.get_config_var("SO")
pythonSharedLib = "libpython%s.%s%s" % \
(sys.version_info[:2] + (extension,))
GLOBAL_BIN_INCLUDES = [pythonSharedLib]
GLOBAL_BIN_EXCLUDES = [
"libclntsh.so",
"libwtc9.so"
]
GLOBAL_BIN_PATH_EXCLUDES = ["/lib", "/lib32", "/lib64", "/usr/lib",
"/usr/lib32", "/usr/lib64"]
# NOTE: the try: except: block in this code is not necessary under Python 2.4
# and higher and can be removed once support for Python 2.3 is no longer needed
EXTENSION_LOADER_SOURCE = \
"""
import imp, os, sys
found = False
for p in sys.path:
if not os.path.isdir(p):
continue
f = os.path.join(p, "%s")
if not os.path.exists(f):
continue
try:
m = imp.load_dynamic(__name__, f)
except ImportError:
del sys.modules[__name__]
raise
sys.modules[__name__] = m
found = True
break
if not found:
del sys.modules[__name__]
raise ImportError, "No module named %%s" %% __name__
"""
class Freezer(object):
def __init__(self, executables, constantsModules = [], includes = [],
excludes = [], packages = [], replacePaths = [], compress = None,
optimizeFlag = 0, copyDependentFiles = None, initScript = None,
base = None, path = None, createLibraryZip = None,
appendScriptToExe = None, appendScriptToLibrary = None,
targetDir = None, binIncludes = [], binExcludes = [],
binPathIncludes = [], binPathExcludes = [], icon = None,
includeFiles = []):
self.executables = executables
self.constantsModules = constantsModules
self.includes = includes
self.excludes = excludes
self.packages = packages
self.replacePaths = replacePaths
self.compress = compress
self.optimizeFlag = optimizeFlag
self.copyDependentFiles = copyDependentFiles
self.initScript = initScript
self.base = base
self.path = path
self.createLibraryZip = createLibraryZip
self.appendScriptToExe = appendScriptToExe
self.appendScriptToLibrary = appendScriptToLibrary
self.targetDir = targetDir
self.binIncludes = [os.path.normcase(n) \
for n in GLOBAL_BIN_INCLUDES + binIncludes]
self.binExcludes = [os.path.normcase(n) \
for n in GLOBAL_BIN_EXCLUDES + binExcludes]
self.binPathIncludes = [os.path.normcase(n) for n in binPathIncludes]
self.binPathExcludes = [os.path.normcase(n) \
for n in GLOBAL_BIN_PATH_EXCLUDES + binPathExcludes]
self.icon = icon
self.includeFiles = includeFiles
self._VerifyConfiguration()
def _CopyFile(self, source, target, copyDependentFiles,
includeMode = False):
normalizedSource = os.path.normcase(os.path.normpath(source))
normalizedTarget = os.path.normcase(os.path.normpath(target))
if normalizedTarget in self.filesCopied:
return
if normalizedSource == normalizedTarget:
return
self._RemoveFile(target)
targetDir = os.path.dirname(target)
self._CreateDirectory(targetDir)
print "copying", source, "->", target
shutil.copyfile(source, target)
if includeMode:
shutil.copymode(source, target)
self.filesCopied[normalizedTarget] = None
if copyDependentFiles:
for source in self._GetDependentFiles(source):
target = os.path.join(targetDir, os.path.basename(source))
self._CopyFile(source, target, copyDependentFiles)
def _CreateDirectory(self, path):
if not os.path.isdir(path):
print "creating directory", path
os.makedirs(path)
def _FreezeExecutable(self, exe):
if self.createLibraryZip:
finder = self.finder
else:
finder = self._GetModuleFinder(exe)
if exe.script is None:
scriptModule = None
else:
scriptModule = finder.IncludeFile(exe.script, exe.moduleName)
self._CopyFile(exe.base, exe.targetName, exe.copyDependentFiles,
includeMode = True)
if exe.icon is not None:
if sys.platform == "win32":
cx_Freeze.util.AddIcon(exe.targetName, exe.icon)
else:
targetName = os.path.join(os.path.dirname(exe.targetName),
os.path.basename(exe.icon))
self._CopyFile(exe.icon, targetName,
copyDependentFiles = False)
if not os.access(exe.targetName, os.W_OK):
mode = os.stat(exe.targetName).st_mode
os.chmod(exe.targetName, mode | stat.S_IWUSR)
if not exe.appendScriptToLibrary:
if exe.appendScriptToExe:
fileName = exe.targetName
else:
baseFileName, ext = os.path.splitext(exe.targetName)
fileName = baseFileName + ".zip"
self._RemoveFile(fileName)
if not self.createLibraryZip and exe.copyDependentFiles:
scriptModule = None
self._WriteModules(fileName, exe.initScript, finder, exe.compress,
exe.copyDependentFiles, scriptModule)
def _GetBaseFileName(self, argsSource = None):
if argsSource is None:
argsSource = self
name = argsSource.base
if name is None:
if argsSource.copyDependentFiles:
name = "Console"
else:
name = "ConsoleKeepPath"
argsSource.base = self._GetFileName("bases", name)
if argsSource.base is None:
raise ConfigError("no base named %s", name)
def _GetDependentFiles(self, path):
dependentFiles = self.dependentFiles.get(path)
if dependentFiles is None:
if sys.platform == "win32":
origPath = os.environ["PATH"]
os.environ["PATH"] = origPath + os.pathsep + \
os.pathsep.join(sys.path)
dependentFiles = cx_Freeze.util.GetDependentFiles(path)
os.environ["PATH"] = origPath
else:
dependentFiles = []
for line in os.popen('ldd "%s"' % path):
parts = line.strip().split(" => ")
if len(parts) != 2:
continue
dependentFile = parts[1]
if dependentFile == "not found":
print "WARNING: cannot find", parts[0]
continue
pos = dependentFile.find(" (")
if pos >= 0:
dependentFile = dependentFile[:pos].strip()
if dependentFile:
dependentFiles.append(dependentFile)
dependentFiles = self.dependentFiles[path] = \
[f for f in dependentFiles if self._ShouldCopyFile(f)]
return dependentFiles
def _GetFileName(self, dir, name):
if os.path.isabs(name):
return name
name = os.path.normcase(name)
fullDir = os.path.join(os.path.dirname(cx_Freeze.__file__), dir)
if os.path.isdir(fullDir):
for fileName in os.listdir(fullDir):
if name == os.path.splitext(os.path.normcase(fileName))[0]:
return os.path.join(fullDir, fileName)
def _GetInitScriptFileName(self, argsSource = None):
if argsSource is None:
argsSource = self
name = argsSource.initScript
if name is None:
if argsSource.copyDependentFiles:
name = "Console"
else:
name = "ConsoleKeepPath"
argsSource.initScript = self._GetFileName("initscripts", name)
if argsSource.initScript is None:
raise ConfigError("no initscript named %s", name)
def _GetModuleFinder(self, argsSource = None):
if argsSource is None:
argsSource = self
finder = cx_Freeze.ModuleFinder(self.includeFiles, argsSource.excludes,
argsSource.path, argsSource.replacePaths)
if argsSource.copyDependentFiles:
finder.IncludeModule("imp")
finder.IncludeModule("os")
finder.IncludeModule("sys")
if argsSource.compress:
finder.IncludeModule("zlib")
for name in argsSource.includes:
finder.IncludeModule(name)
for name in argsSource.packages:
finder.IncludePackage(name)
return finder
def _PrintReport(self, fileName, modules):
print "writing zip file", fileName
print
print " %-25s %s" % ("Name", "File")
print " %-25s %s" % ("----", "----")
for module in modules:
if module.path:
print "P",
else:
print "m",
print "%-25s" % module.name, module.file or ""
print
def _RemoveFile(self, path):
if os.path.exists(path):
os.chmod(path, 0777)
os.remove(path)
def _ShouldCopyFile(self, path):
dir, name = os.path.split(os.path.normcase(path))
parts = name.split(".")
tweaked = False
while True:
if not parts[-1].isdigit():
break
parts.pop(-1)
tweaked = True
if tweaked:
name = ".".join(parts)
if name in self.binIncludes:
return True
if name in self.binExcludes:
return False
for path in self.binPathIncludes:
if dir.startswith(path):
return True
for path in self.binPathExcludes:
if dir.startswith(path):
return False
return True
def _VerifyCanAppendToLibrary(self):
if not self.createLibraryZip:
raise ConfigError("script cannot be appended to library zip if "
"one is not being created")
def _VerifyConfiguration(self):
if self.compress is None:
self.compress = True
if self.copyDependentFiles is None:
self.copyDependentFiles = True
if self.createLibraryZip is None:
self.createLibraryZip = True
if self.appendScriptToExe is None:
self.appendScriptToExe = False
if self.appendScriptToLibrary is None:
self.appendScriptToLibrary = \
self.createLibraryZip and not self.appendScriptToExe
if self.targetDir is None:
self.targetDir = os.path.abspath("dist")
self._GetInitScriptFileName()
self._GetBaseFileName()
if self.path is None:
self.path = sys.path
if self.appendScriptToLibrary:
self._VerifyCanAppendToLibrary()
for sourceFileName, targetFileName in self.includeFiles:
if not os.path.exists(sourceFileName):
raise ConfigError("cannot find file/directory named %s",
sourceFileName)
if os.path.isabs(targetFileName):
raise ConfigError("target file/directory cannot be absolute")
for executable in self.executables:
executable._VerifyConfiguration(self)
def _WriteModules(self, fileName, initScript, finder, compress,
copyDependentFiles, scriptModule = None):
initModule = finder.IncludeFile(initScript, "cx_Freeze__init__")
if scriptModule is None:
for module in self.constantsModules:
module.Create(finder)
modules = [m for m in finder.modules \
if m.name not in self.excludeModules]
else:
modules = [initModule, scriptModule]
self.excludeModules[initModule.name] = None
self.excludeModules[scriptModule.name] = None
itemsToSort = [(m.name, m) for m in modules]
itemsToSort.sort()
modules = [m for n, m in itemsToSort]
self._PrintReport(fileName, modules)
if scriptModule is None:
finder.ReportMissingModules()
targetDir = os.path.dirname(fileName)
self._CreateDirectory(targetDir)
filesToCopy = []
if os.path.exists(fileName):
mode = "a"
else:
mode = "w"
outFile = zipfile.PyZipFile(fileName, mode, zipfile.ZIP_DEFLATED)
for module in modules:
if module.code is None and module.file is not None:
fileName = os.path.basename(module.file)
baseFileName, ext = os.path.splitext(fileName)
if baseFileName != module.name and module.name != "zlib":
if "." in module.name:
fileName = module.name + ext
generatedFileName = "ExtensionLoader_%s.py" % \
module.name.replace(".", "_")
module.code = compile(EXTENSION_LOADER_SOURCE % fileName,
generatedFileName, "exec")
target = os.path.join(targetDir, fileName)
filesToCopy.append((module, target))
if module.code is None:
continue
fileName = "/".join(module.name.split("."))
if module.path:
fileName += "/__init__"
if module.file is not None and os.path.exists(module.file):
mtime = os.stat(module.file).st_mtime
else:
mtime = time.time()
zipTime = time.localtime(mtime)[:6]
data = imp.get_magic() + struct.pack("<i", mtime) + \
marshal.dumps(module.code)
zinfo = zipfile.ZipInfo(fileName + ".pyc", zipTime)
if compress:
zinfo.compress_type = zipfile.ZIP_DEFLATED
outFile.writestr(zinfo, data)
origPath = os.environ["PATH"]
for module, target in filesToCopy:
try:
if module.parent is not None:
path = os.pathsep.join([origPath] + module.parent.path)
os.environ["PATH"] = path
self._CopyFile(module.file, target, copyDependentFiles)
finally:
os.environ["PATH"] = origPath
def Freeze(self):
self.finder = None
self.excludeModules = {}
self.dependentFiles = {}
self.filesCopied = {}
cx_Freeze.util.SetOptimizeFlag(self.optimizeFlag)
if self.createLibraryZip:
self.finder = self._GetModuleFinder()
for executable in self.executables:
self._FreezeExecutable(executable)
if self.createLibraryZip:
fileName = os.path.join(self.targetDir, "library.zip")
self._RemoveFile(fileName)
self._WriteModules(fileName, self.initScript, self.finder,
self.compress, self.copyDependentFiles)
for sourceFileName, targetFileName in self.includeFiles:
fullName = os.path.join(self.targetDir, targetFileName)
if os.path.isdir(sourceFileName):
for path, dirNames, fileNames in os.walk(sourceFileName):
shortPath = path[len(sourceFileName) + 1:]
if ".svn" in dirNames:
dirNames.remove(".svn")
if "CVS" in dirNames:
dirNames.remove("CVS")
for fileName in fileNames:
fullSourceName = os.path.join(path, fileName)
fullTargetName = os.path.join(self.targetDir,
targetFileName, shortPath, fileName)
self._CopyFile(fullSourceName, fullTargetName,
copyDependentFiles = False)
else:
self._CopyFile(sourceFileName, fullName,
copyDependentFiles = False)
class ConfigError(Exception):
def __init__(self, format, *args):
self.what = format % args
def __str__(self):
return self.what
class Executable(object):
def __init__(self, script, initScript = None, base = None, path = None,
targetDir = None, targetName = None, includes = None,
excludes = None, packages = None, replacePaths = None,
compress = None, copyDependentFiles = None,
appendScriptToExe = None, appendScriptToLibrary = None,
icon = None):
self.script = script
self.initScript = initScript
self.base = base
self.path = path
self.targetDir = targetDir
self.targetName = targetName
self.includes = includes
self.excludes = excludes
self.packages = packages
self.replacePaths = replacePaths
self.compress = compress
self.copyDependentFiles = copyDependentFiles
self.appendScriptToExe = appendScriptToExe
self.appendScriptToLibrary = appendScriptToLibrary
self.icon = icon
def __repr__(self):
return "<Executable script=%s>" % self.script
def _VerifyConfiguration(self, freezer):
if self.path is None:
self.path = freezer.path
if self.targetDir is None:
self.targetDir = freezer.targetDir
if self.includes is None:
self.includes = freezer.includes
if self.excludes is None:
self.excludes = freezer.excludes
if self.packages is None:
self.packages = freezer.packages
if self.replacePaths is None:
self.replacePaths = freezer.replacePaths
if self.compress is None:
self.compress = freezer.compress
if self.copyDependentFiles is None:
self.copyDependentFiles = freezer.copyDependentFiles
if self.appendScriptToExe is None:
self.appendScriptToExe = freezer.appendScriptToExe
if self.appendScriptToLibrary is None:
self.appendScriptToLibrary = freezer.appendScriptToLibrary
if self.initScript is None:
self.initScript = freezer.initScript
else:
freezer._GetInitScriptFileName(self)
if self.base is None:
self.base = freezer.base
else:
freezer._GetBaseFileName(self)
if self.appendScriptToLibrary:
freezer._VerifyCanAppendToLibrary()
if self.icon is None:
self.icon = freezer.icon
if self.script is not None:
name, ext = os.path.splitext(os.path.basename(self.script))
if self.appendScriptToLibrary:
self.moduleName = "%s__main__" % os.path.normcase(name)
else:
self.moduleName = "__main__"
if self.targetName is None:
baseName, ext = os.path.splitext(self.base)
self.targetName = name + ext
self.targetName = os.path.join(self.targetDir, self.targetName)
class ConstantsModule(object):
def __init__(self, releaseString = None, copyright = None,
moduleName = "BUILD_CONSTANTS", timeFormat = "%B %d, %Y %H:%M:%S"):
self.moduleName = moduleName
self.timeFormat = timeFormat
self.values = {}
self.values["BUILD_RELEASE_STRING"] = releaseString
self.values["BUILD_COPYRIGHT"] = copyright
def Create(self, finder):
"""Create the module which consists of declaration statements for each
of the values."""
today = datetime.datetime.today()
sourceTimestamp = 0
for module in finder.modules:
if module.file is None:
continue
if module.inZipFile:
continue
if not os.path.exists(module.file):
raise ConfigError("no file named %s", module.file)
timestamp = os.stat(module.file).st_mtime
sourceTimestamp = max(sourceTimestamp, timestamp)
sourceTimestamp = datetime.datetime.fromtimestamp(sourceTimestamp)
self.values["BUILD_TIMESTAMP"] = today.strftime(self.timeFormat)
self.values["BUILD_HOST"] = socket.gethostname().split(".")[0]
self.values["SOURCE_TIMESTAMP"] = \
sourceTimestamp.strftime(self.timeFormat)
module = finder._AddModule(self.moduleName)
sourceParts = []
names = self.values.keys()
names.sort()
for name in names:
value = self.values[name]
sourceParts.append("%s = %r" % (name, value))
source = "\n".join(sourceParts)
module.code = compile(source, "%s.py" % self.moduleName, "exec")

View File

@ -1,281 +0,0 @@
import os
import sys
def initialize(finder):
"""upon initialization of the finder, this routine is called to set up some
automatic exclusions for various platforms."""
finder.ExcludeModule("FCNTL")
finder.ExcludeModule("os.path")
if os.name == "nt":
finder.ExcludeModule("fcntl")
finder.ExcludeModule("grp")
finder.ExcludeModule("pwd")
finder.ExcludeModule("termios")
else:
finder.ExcludeModule("_winreg")
finder.ExcludeModule("msilib")
finder.ExcludeModule("msvcrt")
finder.ExcludeModule("nt")
if os.name not in ("os2", "ce"):
finder.ExcludeModule("ntpath")
finder.ExcludeModule("nturl2path")
finder.ExcludeModule("pythoncom")
finder.ExcludeModule("pywintypes")
finder.ExcludeModule("winerror")
finder.ExcludeModule("winsound")
finder.ExcludeModule("win32api")
finder.ExcludeModule("win32con")
finder.ExcludeModule("win32event")
finder.ExcludeModule("win32file")
finder.ExcludeModule("win32pdh")
finder.ExcludeModule("win32pipe")
finder.ExcludeModule("win32process")
finder.ExcludeModule("win32security")
finder.ExcludeModule("win32service")
finder.ExcludeModule("wx.activex")
if os.name != "posix":
finder.ExcludeModule("posix")
if os.name != "mac":
finder.ExcludeModule("Carbon")
finder.ExcludeModule("gestalt")
finder.ExcludeModule("ic")
finder.ExcludeModule("mac")
finder.ExcludeModule("MacOS")
finder.ExcludeModule("macpath")
finder.ExcludeModule("macurl2path")
if os.name != "nt":
finder.ExcludeModule("EasyDialogs")
if os.name != "os2":
finder.ExcludeModule("os2")
finder.ExcludeModule("os2emxpath")
finder.ExcludeModule("_emx_link")
if os.name != "ce":
finder.ExcludeModule("ce")
if os.name != "riscos":
finder.ExcludeModule("riscos")
finder.ExcludeModule("riscosenviron")
finder.ExcludeModule("riscospath")
finder.ExcludeModule("rourl2path")
if sys.platform[:4] != "java":
finder.ExcludeModule("java.lang")
finder.ExcludeModule("org.python.core")
def load_cElementTree(finder, module):
"""the cElementTree module implicitly loads the elementtree.ElementTree
module; make sure this happens."""
finder.IncludeModule("elementtree.ElementTree")
def load_ceODBC(finder, module):
"""the ceODBC module implicitly imports both datetime and decimal; make
sure this happens."""
finder.IncludeModule("datetime")
finder.IncludeModule("decimal")
def load_cx_Oracle(finder, module):
"""the cx_Oracle module implicitly imports datetime; make sure this
happens."""
finder.IncludeModule("datetime")
def load_docutils_frontend(finder, module):
"""The optik module is the old name for the optparse module; ignore the
module if it cannot be found."""
module.IgnoreName("optik")
def load_dummy_threading(finder, module):
"""the dummy_threading module plays games with the name of the threading
module for its own purposes; ignore that here"""
finder.ExcludeModule("_dummy_threading")
def load_email(finder, module):
"""the email package has a bunch of aliases as the submodule names were
all changed to lowercase in Python 2.5; mimic that here."""
if sys.version_info[:2] >= (2, 5):
for name in ("Charset", "Encoders", "Errors", "FeedParser",
"Generator", "Header", "Iterators", "Message", "Parser",
"Utils", "base64MIME", "quopriMIME"):
finder.AddAlias("email.%s" % name, "email.%s" % name.lower())
def load_ftplib(finder, module):
"""the ftplib module attempts to import the SOCKS module; ignore this
module if it cannot be found"""
module.IgnoreName("SOCKS")
def load_matplotlib(finder, module):
"""the matplotlib module requires data to be found in mpl-data in the
same directory as the frozen executable so oblige it"""
dir = os.path.join(module.path[0], "mpl-data")
finder.IncludeFiles(dir, "mpl-data")
def load_matplotlib_numerix(finder, module):
"""the numpy.numerix module loads a number of modules dynamically"""
for name in ("ma", "fft", "linear_algebra", "random_array", "mlab"):
finder.IncludeModule("%s.%s" % (module.name, name))
def load_numpy_linalg(finder, module):
"""the numpy.linalg module implicitly loads the lapack_lite module; make
sure this happens"""
finder.IncludeModule("numpy.linalg.lapack_lite")
def load_pty(finder, module):
"""The sgi module is not needed for this module to function."""
module.IgnoreName("sgi")
def load_pythoncom(finder, module):
"""the pythoncom module is actually contained in a DLL but since those
cannot be loaded directly in Python 2.5 and higher a special module is
used to perform that task; simply use that technique directly to
determine the name of the DLL and ensure it is included as a normal
extension; also load the pywintypes module which is implicitly
loaded."""
import pythoncom
module.file = pythoncom.__file__
module.code = None
finder.IncludeModule("pywintypes")
def load_pywintypes(finder, module):
"""the pywintypes module is actually contained in a DLL but since those
cannot be loaded directly in Python 2.5 and higher a special module is
used to perform that task; simply use that technique directly to
determine the name of the DLL and ensure it is included as a normal
extension."""
import pywintypes
module.file = pywintypes.__file__
module.code = None
def load_PyQt4_Qt(finder, module):
"""the PyQt4.Qt module is an extension module which imports a number of
other modules and injects their namespace into its own. It seems a
foolish way of doing things but perhaps there is some hidden advantage
to this technique over pure Python; ignore the absence of some of
the modules since not every installation includes all of them."""
finder.IncludeModule("PyQt4.QtCore")
finder.IncludeModule("PyQt4.QtGui")
finder.IncludeModule("sip")
for name in ("PyQt4.QtSvg", "PyQt4.Qsci", "PyQt4.QtAssistant",
"PyQt4.QtNetwork", "PyQt4.QtOpenGL", "PyQt4.QtScript", "PyQt4._qt",
"PyQt4.QtSql", "PyQt4.QtSvg", "PyQt4.QtTest", "PyQt4.QtXml"):
try:
finder.IncludeModule(name)
except ImportError:
pass
def load_Tkinter(finder, module):
"""the Tkinter module has data files that are required to be loaded so
ensure that they are copied into the directory that is expected at
runtime."""
import Tkinter
import _tkinter
tk = _tkinter.create()
tclDir = os.path.dirname(tk.call("info", "library"))
tclSourceDir = os.path.join(tclDir, "tcl%s" % _tkinter.TCL_VERSION)
tkSourceDir = os.path.join(tclDir, "tk%s" % _tkinter.TK_VERSION)
finder.IncludeFiles(tclSourceDir, "tcl")
finder.IncludeFiles(tkSourceDir, "tk")
def load_tempfile(finder, module):
"""the tempfile module attempts to load the fcntl and thread modules but
continues if these modules cannot be found; ignore these modules if they
cannot be found."""
module.IgnoreName("fcntl")
module.IgnoreName("thread")
def load_time(finder, module):
"""the time module implicitly loads _strptime; make sure this happens."""
finder.IncludeModule("_strptime")
def load_win32api(finder, module):
"""the win32api module implicitly loads the pywintypes module; make sure
this happens."""
finder.IncludeModule("pywintypes")
def load_win32com(finder, module):
"""the win32com package manipulates its search path at runtime to include
the sibling directory called win32comext; simulate that by changing the
search path in a similar fashion here."""
baseDir = os.path.dirname(os.path.dirname(module.file))
module.path.append(os.path.join(baseDir, "win32comext"))
def load_win32file(finder, module):
"""the win32api module implicitly loads the pywintypes module; make sure
this happens."""
finder.IncludeModule("pywintypes")
def load_xml(finder, module):
"""the builtin xml package attempts to load the _xmlplus module to see if
that module should take its role instead; ignore the failure to find
this module, though."""
module.IgnoreName("_xmlplus")
def load_xml_etree_cElementTree(finder, module):
"""the xml.etree.cElementTree module implicitly loads the
xml.etree.ElementTree module; make sure this happens."""
finder.IncludeModule("xml.etree.ElementTree")
def load_IPython(finder, module):
ipy = os.path.join(os.path.dirname(module.file), 'Extensions')
extensions = set([])
for m in os.listdir(ipy):
extensions.add(os.path.splitext(m)[0])
extensions.remove('__init__')
for m in extensions:
finder.IncludeModule('IPython.Extensions.'+m)
def load_lxml(finder, module):
finder.IncludeModule('lxml._elementpath')
def load_cherrypy(finder, module):
finder.IncludeModule('cherrypy.lib.encoding')
def missing_cElementTree(finder, caller):
"""the cElementTree has been incorporated into the standard library in
Python 2.5 so ignore its absence if it cannot found."""
if sys.version_info[:2] >= (2, 5):
caller.IgnoreName("cElementTree")
def missing_EasyDialogs(finder, caller):
"""the EasyDialogs module is not normally present on Windows but it also
may be so instead of excluding it completely, ignore it if it can't be
found"""
if sys.platform == "win32":
caller.IgnoreName("EasyDialogs")
def missing_readline(finder, caller):
"""the readline module is not normally present on Windows but it also may
be so instead of excluding it completely, ignore it if it can't be
found"""
if sys.platform == "win32":
caller.IgnoreName("readline")
def missing_xml_etree(finder, caller):
"""the xml.etree package is new for Python 2.5 but it is common practice
to use a try..except.. block in order to support versions earlier than
Python 2.5 transparently; ignore the absence of the package in this
situation."""
if sys.version_info[:2] < (2, 5):
caller.IgnoreName("xml.etree")

View File

@ -1,171 +0,0 @@
import optparse
import os
import shutil
import stat
import sys
import cx_Freeze
__all__ = ["main"]
USAGE = \
"""
%prog [options] [SCRIPT]
Freeze a Python script and all of its referenced modules to a base
executable which can then be distributed without requiring a Python
installation."""
VERSION = \
"""
%%prog %s
Copyright (c) 2007-2008 Colt Engineering. All rights reserved.
Copyright (c) 2001-2006 Computronix Corporation. All rights reserved.""" % \
cx_Freeze.version
def ParseCommandLine():
parser = optparse.OptionParser(version = VERSION.strip(),
usage = USAGE.strip())
parser.add_option("-O",
action = "count",
default = 0,
dest = "optimized",
help = "optimize generated bytecode as per PYTHONOPTIMIZE; "
"use -OO in order to remove doc strings")
parser.add_option("-c", "--compress",
action = "store_true",
dest = "compress",
help = "compress byte code in zip files")
parser.add_option("--base-name",
dest = "baseName",
metavar = "NAME",
help = "file on which to base the target file; if the name of the "
"file is not an absolute file name, the subdirectory bases "
"(rooted in the directory in which the freezer is found) "
"will be searched for a file matching the name")
parser.add_option("--init-script",
dest = "initScript",
metavar = "NAME",
help = "script which will be executed upon startup; if the name "
"of the file is not an absolute file name, the "
"subdirectory initscripts (rooted in the directory in "
"which the cx_Freeze package is found) will be searched "
"for a file matching the name")
parser.add_option("--target-dir", "--install-dir",
dest = "targetDir",
metavar = "DIR",
help = "the directory in which to place the target file and "
"any dependent files")
parser.add_option("--target-name",
dest = "targetName",
metavar = "NAME",
help = "the name of the file to create instead of the base name "
"of the script and the extension of the base binary")
parser.add_option("--no-copy-deps",
dest = "copyDeps",
default = True,
action = "store_false",
help = "do not copy the dependent files (extensions, shared "
"libraries, etc.) to the target directory; this also "
"modifies the default init script to ConsoleKeepPath.py "
"and means that the target executable requires a Python "
"installation to execute properly")
parser.add_option("--default-path",
action = "append",
dest = "defaultPath",
metavar = "DIRS",
help = "list of paths separated by the standard path separator "
"for the platform which will be used to initialize "
"sys.path prior to running the module finder")
parser.add_option("--include-path",
action = "append",
dest = "includePath",
metavar = "DIRS",
help = "list of paths separated by the standard path separator "
"for the platform which will be used to modify sys.path "
"prior to running the module finder")
parser.add_option("--replace-paths",
dest = "replacePaths",
metavar = "DIRECTIVES",
help = "replace all the paths in modules found in the given paths "
"with the given replacement string; multiple values are "
"separated by the standard path separator and each value "
"is of the form path=replacement_string; path can be * "
"which means all paths not already specified")
parser.add_option("--include-modules",
dest = "includeModules",
metavar = "NAMES",
help = "comma separated list of modules to include")
parser.add_option("--exclude-modules",
dest = "excludeModules",
metavar = "NAMES",
help = "comma separated list of modules to exclude")
parser.add_option("--ext-list-file",
dest = "extListFile",
metavar = "NAME",
help = "name of file in which to place the list of dependent files "
"which were copied into the target directory")
parser.add_option("-z", "--zip-include",
dest = "zipIncludes",
action = "append",
default = [],
metavar = "SPEC",
help = "name of file to add to the zip file or a specification of "
"the form name=arcname which will specify the archive name "
"to use; multiple --zip-include arguments can be used")
options, args = parser.parse_args()
if len(args) == 0:
options.script = None
elif len(args) == 1:
options.script, = args
else:
parser.error("only one script can be specified")
if not args and options.includeModules is None and options.copyDeps:
parser.error("script or a list of modules must be specified")
if not args and options.targetName is None:
parser.error("script or a target name must be specified")
if options.excludeModules:
options.excludeModules = options.excludeModules.split(",")
else:
options.excludeModules = []
if options.includeModules:
options.includeModules = options.includeModules.split(",")
else:
options.includeModules = []
replacePaths = []
if options.replacePaths:
for directive in options.replacePaths.split(os.pathsep):
fromPath, replacement = directive.split("=")
replacePaths.append((fromPath, replacement))
options.replacePaths = replacePaths
if options.defaultPath is not None:
sys.path = [p for mp in options.defaultPath \
for p in mp.split(os.pathsep)]
if options.includePath is not None:
paths = [p for mp in options.includePath for p in mp.split(os.pathsep)]
sys.path = paths + sys.path
if options.script is not None:
sys.path.insert(0, os.path.dirname(options.script))
return options
def main():
options = ParseCommandLine()
executables = [cx_Freeze.Executable(options.script,
targetName = options.targetName)]
freezer = cx_Freeze.Freezer(executables,
includes = options.includeModules,
excludes = options.excludeModules,
replacePaths = options.replacePaths,
compress = options.compress,
optimizeFlag = options.optimized,
copyDependentFiles = options.copyDeps,
initScript = options.initScript,
base = options.baseName,
path = None,
createLibraryZip = False,
appendScriptToExe = True,
targetDir = options.targetDir)
freezer.Freeze()

View File

@ -1,337 +0,0 @@
import distutils.command.bdist_msi
import msilib
import os
__all__ = [ "bdist_msi" ]
# force the remove existing products action to happen first since Windows
# installer appears to be braindead and doesn't handle files shared between
# different "products" very well
sequence = msilib.sequence.InstallExecuteSequence
for index, info in enumerate(sequence):
if info[0] == u'RemoveExistingProducts':
sequence[index] = (info[0], info[1], 1450)
class bdist_msi(distutils.command.bdist_msi.bdist_msi):
user_options = distutils.command.bdist_msi.bdist_msi.user_options + [
('add-to-path=', None, 'add target dir to PATH environment variable'),
('upgrade-code=', None, 'upgrade code to use')
]
x = y = 50
width = 370
height = 300
title = "[ProductName] Setup"
modeless = 1
modal = 3
def add_config(self, fullname):
initialTargetDir = self.get_initial_target_dir(fullname)
if self.add_to_path is None:
self.add_to_path = False
for executable in self.distribution.executables:
if os.path.basename(executable.base).startswith("Console"):
self.add_to_path = True
break
if self.add_to_path:
msilib.add_data(self.db, 'Environment',
[("E_PATH", "Path", r"[~];[TARGETDIR]", "TARGETDIR")])
msilib.add_data(self.db, 'CustomAction',
[("InitialTargetDir", 256 + 51, "TARGETDIR", initialTargetDir)
])
msilib.add_data(self.db, 'InstallExecuteSequence',
[("InitialTargetDir", 'TARGETDIR=""', 401)])
msilib.add_data(self.db, 'InstallUISequence',
[("PrepareDlg", None, 140),
("InitialTargetDir", 'TARGETDIR=""', 401),
("SelectDirectoryDlg", "not Installed", 1230),
("MaintenanceTypeDlg",
"Installed and not Resume and not Preselected", 1250),
("ProgressDlg", None, 1280)
])
def add_cancel_dialog(self):
dialog = msilib.Dialog(self.db, "CancelDlg", 50, 10, 260, 85, 3,
self.title, "No", "No", "No")
dialog.text("Text", 48, 15, 194, 30, 3,
"Are you sure you want to cancel [ProductName] installation?")
button = dialog.pushbutton("Yes", 72, 57, 56, 17, 3, "Yes", "No")
button.event("EndDialog", "Exit")
button = dialog.pushbutton("No", 132, 57, 56, 17, 3, "No", "Yes")
button.event("EndDialog", "Return")
def add_error_dialog(self):
dialog = msilib.Dialog(self.db, "ErrorDlg", 50, 10, 330, 101, 65543,
self.title, "ErrorText", None, None)
dialog.text("ErrorText", 50, 9, 280, 48, 3, "")
for text, x in [("No", 120), ("Yes", 240), ("Abort", 0),
("Cancel", 42), ("Ignore", 81), ("Ok", 159), ("Retry", 198)]:
button = dialog.pushbutton(text[0], x, 72, 81, 21, 3, text, None)
button.event("EndDialog", "Error%s" % text)
def add_exit_dialog(self):
dialog = distutils.command.bdist_msi.PyDialog(self.db, "ExitDialog",
self.x, self.y, self.width, self.height, self.modal,
self.title, "Finish", "Finish", "Finish")
dialog.title("Completing the [ProductName] installer")
dialog.back("< Back", "Finish", active = False)
dialog.cancel("Cancel", "Back", active = False)
dialog.text("Description", 15, 235, 320, 20, 0x30003,
"Click the Finish button to exit the installer.")
button = dialog.next("Finish", "Cancel", name = "Finish")
button.event("EndDialog", "Return")
def add_fatal_error_dialog(self):
dialog = distutils.command.bdist_msi.PyDialog(self.db, "FatalError",
self.x, self.y, self.width, self.height, self.modal,
self.title, "Finish", "Finish", "Finish")
dialog.title("[ProductName] installer ended prematurely")
dialog.back("< Back", "Finish", active = False)
dialog.cancel("Cancel", "Back", active = False)
dialog.text("Description1", 15, 70, 320, 80, 0x30003,
"[ProductName] setup ended prematurely because of an error. "
"Your system has not been modified. To install this program "
"at a later time, please run the installation again.")
dialog.text("Description2", 15, 155, 320, 20, 0x30003,
"Click the Finish button to exit the installer.")
button = dialog.next("Finish", "Cancel", name = "Finish")
button.event("EndDialog", "Exit")
def add_files_in_use_dialog(self):
dialog = distutils.command.bdist_msi.PyDialog(self.db, "FilesInUse",
self.x, self.y, self.width, self.height, 19, self.title,
"Retry", "Retry", "Retry", bitmap = False)
dialog.text("Title", 15, 6, 200, 15, 0x30003,
r"{\DlgFontBold8}Files in Use")
dialog.text("Description", 20, 23, 280, 20, 0x30003,
"Some files that need to be updated are currently in use.")
dialog.text("Text", 20, 55, 330, 50, 3,
"The following applications are using files that need to be "
"updated by this setup. Close these applications and then "
"click Retry to continue the installation or Cancel to exit "
"it.")
dialog.control("List", "ListBox", 20, 107, 330, 130, 7,
"FileInUseProcess", None, None, None)
button = dialog.back("Exit", "Ignore", name = "Exit")
button.event("EndDialog", "Exit")
button = dialog.next("Ignore", "Retry", name = "Ignore")
button.event("EndDialog", "Ignore")
button = dialog.cancel("Retry", "Exit", name = "Retry")
button.event("EndDialog", "Retry")
def add_maintenance_type_dialog(self):
dialog = distutils.command.bdist_msi.PyDialog(self.db,
"MaintenanceTypeDlg", self.x, self.y, self.width, self.height,
self.modal, self.title, "Next", "Next", "Cancel")
dialog.title("Welcome to the [ProductName] Setup Wizard")
dialog.text("BodyText", 15, 63, 330, 42, 3,
"Select whether you want to repair or remove [ProductName].")
group = dialog.radiogroup("RepairRadioGroup", 15, 108, 330, 60, 3,
"MaintenanceForm_Action", "", "Next")
group.add("Repair", 0, 18, 300, 17, "&Repair [ProductName]")
group.add("Remove", 0, 36, 300, 17, "Re&move [ProductName]")
dialog.back("< Back", None, active = False)
button = dialog.next("Finish", "Cancel")
button.event("[REINSTALL]", "ALL",
'MaintenanceForm_Action="Repair"', 5)
button.event("[Progress1]", "Repairing",
'MaintenanceForm_Action="Repair"', 6)
button.event("[Progress2]", "repairs",
'MaintenanceForm_Action="Repair"', 7)
button.event("Reinstall", "ALL",
'MaintenanceForm_Action="Repair"', 8)
button.event("[REMOVE]", "ALL",
'MaintenanceForm_Action="Remove"', 11)
button.event("[Progress1]", "Removing",
'MaintenanceForm_Action="Remove"', 12)
button.event("[Progress2]", "removes",
'MaintenanceForm_Action="Remove"', 13)
button.event("Remove", "ALL",
'MaintenanceForm_Action="Remove"', 14)
button.event("EndDialog", "Return",
'MaintenanceForm_Action<>"Change"', 20)
button = dialog.cancel("Cancel", "RepairRadioGroup")
button.event("SpawnDialog", "CancelDlg")
def add_prepare_dialog(self):
dialog = distutils.command.bdist_msi.PyDialog(self.db, "PrepareDlg",
self.x, self.y, self.width, self.height, self.modeless,
self.title, "Cancel", "Cancel", "Cancel")
dialog.text("Description", 15, 70, 320, 40, 0x30003,
"Please wait while the installer prepares to guide you through"
"the installation.")
dialog.title("Welcome to the [ProductName] installer")
text = dialog.text("ActionText", 15, 110, 320, 20, 0x30003,
"Pondering...")
text.mapping("ActionText", "Text")
text = dialog.text("ActionData", 15, 135, 320, 30, 0x30003, None)
text.mapping("ActionData", "Text")
dialog.back("Back", None, active = False)
dialog.next("Next", None, active = False)
button = dialog.cancel("Cancel", None)
button.event("SpawnDialog", "CancelDlg")
def add_progress_dialog(self):
dialog = distutils.command.bdist_msi.PyDialog(self.db, "ProgressDlg",
self.x, self.y, self.width, self.height, self.modeless,
self.title, "Cancel", "Cancel", "Cancel", bitmap = False)
dialog.text("Title", 20, 15, 200, 15, 0x30003,
r"{\DlgFontBold8}[Progress1] [ProductName]")
dialog.text("Text", 35, 65, 300, 30, 3,
"Please wait while the installer [Progress2] [ProductName].")
dialog.text("StatusLabel", 35, 100 ,35, 20, 3, "Status:")
text = dialog.text("ActionText", 70, 100, self.width - 70, 20, 3,
"Pondering...")
text.mapping("ActionText", "Text")
control = dialog.control("ProgressBar", "ProgressBar", 35, 120, 300,
10, 65537, None, "Progress done", None, None)
control.mapping("SetProgress", "Progress")
dialog.back("< Back", "Next", active = False)
dialog.next("Next >", "Cancel", active = False)
button = dialog.cancel("Cancel", "Back")
button.event("SpawnDialog", "CancelDlg")
def add_properties(self):
metadata = self.distribution.metadata
props = [
('DistVersion', metadata.get_version()),
('DefaultUIFont', 'DlgFont8'),
('ErrorDialog', 'ErrorDlg'),
('Progress1', 'Install'),
('Progress2', 'installs'),
('MaintenanceForm_Action', 'Repair')
]
email = metadata.author_email or metadata.maintainer_email
if email:
props.append(("ARPCONTACT", email))
if metadata.url:
props.append(("ARPURLINFOABOUT", metadata.url))
if self.upgrade_code is not None:
props.append(("UpgradeCode", self.upgrade_code))
msilib.add_data(self.db, 'Property', props)
def add_select_directory_dialog(self):
dialog = distutils.command.bdist_msi.PyDialog(self.db,
"SelectDirectoryDlg", self.x, self.y, self.width, self.height,
self.modal, self.title, "Next", "Next", "Cancel")
dialog.title("Select destination directory")
dialog.back("< Back", None, active = False)
button = dialog.next("Next >", "Cancel")
button.event("SetTargetPath", "TARGETDIR", ordering = 1)
button.event("SpawnWaitDialog", "WaitForCostingDlg", ordering = 2)
button.event("EndDialog", "Return", ordering = 3)
button = dialog.cancel("Cancel", "DirectoryCombo")
button.event("SpawnDialog", "CancelDlg")
dialog.control("DirectoryCombo", "DirectoryCombo", 15, 70, 272, 80,
393219, "TARGETDIR", None, "DirectoryList", None)
dialog.control("DirectoryList", "DirectoryList", 15, 90, 308, 136, 3,
"TARGETDIR", None, "PathEdit", None)
dialog.control("PathEdit", "PathEdit", 15, 230, 306, 16, 3,
"TARGETDIR", None, "Next", None)
button = dialog.pushbutton("Up", 306, 70, 18, 18, 3, "Up", None)
button.event("DirectoryListUp", "0")
button = dialog.pushbutton("NewDir", 324, 70, 30, 18, 3, "New", None)
button.event("DirectoryListNew", "0")
def add_text_styles(self):
msilib.add_data(self.db, 'TextStyle',
[("DlgFont8", "Tahoma", 9, None, 0),
("DlgFontBold8", "Tahoma", 8, None, 1),
("VerdanaBold10", "Verdana", 10, None, 1),
("VerdanaRed9", "Verdana", 9, 255, 0)
])
def add_ui(self):
self.add_text_styles()
self.add_error_dialog()
self.add_fatal_error_dialog()
self.add_cancel_dialog()
self.add_exit_dialog()
self.add_user_exit_dialog()
self.add_files_in_use_dialog()
self.add_wait_for_costing_dialog()
self.add_prepare_dialog()
self.add_select_directory_dialog()
self.add_progress_dialog()
self.add_maintenance_type_dialog()
def add_upgrade_config(self, sversion):
if self.upgrade_code is not None:
msilib.add_data(self.db, 'Upgrade',
[(self.upgrade_code, None, sversion, None, 513, None,
"REMOVEOLDVERSION"),
(self.upgrade_code, sversion, None, None, 257, None,
"REMOVENEWVERSION")
])
def add_user_exit_dialog(self):
dialog = distutils.command.bdist_msi.PyDialog(self.db, "UserExit",
self.x, self.y, self.width, self.height, self.modal,
self.title, "Finish", "Finish", "Finish")
dialog.title("[ProductName] installer was interrupted")
dialog.back("< Back", "Finish", active = False)
dialog.cancel("Cancel", "Back", active = False)
dialog.text("Description1", 15, 70, 320, 80, 0x30003,
"[ProductName] setup was interrupted. Your system has not "
"been modified. To install this program at a later time, "
"please run the installation again.")
dialog.text("Description2", 15, 155, 320, 20, 0x30003,
"Click the Finish button to exit the installer.")
button = dialog.next("Finish", "Cancel", name = "Finish")
button.event("EndDialog", "Exit")
def add_wait_for_costing_dialog(self):
dialog = msilib.Dialog(self.db, "WaitForCostingDlg", 50, 10, 260, 85,
self.modal, self.title, "Return", "Return", "Return")
dialog.text("Text", 48, 15, 194, 30, 3,
"Please wait while the installer finishes determining your "
"disk space requirements.")
button = dialog.pushbutton("Return", 102, 57, 56, 17, 3, "Return",
None)
button.event("EndDialog", "Exit")
def get_initial_target_dir(self, fullname):
return r"[ProgramFilesFolder]\%s" % fullname
def get_installer_filename(self, fullname):
return os.path.join(self.dist_dir, "%s.msi" % fullname)
def initialize_options(self):
distutils.command.bdist_msi.bdist_msi.initialize_options(self)
self.upgrade_code = None
self.add_to_path = None
def run(self):
if not self.skip_build:
self.run_command('build')
install = self.reinitialize_command('install', reinit_subcommands = 1)
install.prefix = self.bdist_dir
install.skip_build = self.skip_build
install.warn_dir = 0
distutils.log.info("installing to %s", self.bdist_dir)
install.ensure_finalized()
install.run()
self.mkpath(self.dist_dir)
fullname = self.distribution.get_fullname()
filename = os.path.abspath(self.get_installer_filename(fullname))
if os.path.exists(filename):
os.unlink(filename)
metadata = self.distribution.metadata
author = metadata.author or metadata.maintainer or "UNKNOWN"
version = metadata.get_version()
sversion = "%d.%d.%d" % \
distutils.version.StrictVersion(version).version
self.db = msilib.init_database(filename, msilib.schema,
self.distribution.metadata.name, msilib.gen_uuid(), sversion,
author)
msilib.add_tables(self.db, msilib.sequence)
self.add_properties()
self.add_config(fullname)
self.add_upgrade_config(sversion)
self.add_ui()
self.add_files()
self.db.Commit()
if not self.keep_temp:
distutils.dir_util.remove_tree(self.bdist_dir,
dry_run = self.dry_run)

View File

@ -1,6 +0,0 @@
#!/usr/bin/python
from cx_Freeze import main
main()

View File

@ -1,35 +0,0 @@
#------------------------------------------------------------------------------
# Console.py
# Initialization script for cx_Freeze which manipulates the path so that the
# directory in which the executable is found is searched for extensions but
# no other directory is searched. It also sets the attribute sys.frozen so that
# the Win32 extensions behave as expected.
#------------------------------------------------------------------------------
import encodings
import os
import sys
import warnings
import zipimport
sys.frozen = True
sys.path = sys.path[:4]
os.environ["TCL_LIBRARY"] = os.path.join(DIR_NAME, "tcl")
os.environ["TK_LIBRARY"] = os.path.join(DIR_NAME, "tk")
m = __import__("__main__")
importer = zipimport.zipimporter(INITSCRIPT_ZIP_FILE_NAME)
if INITSCRIPT_ZIP_FILE_NAME != SHARED_ZIP_FILE_NAME:
moduleName = m.__name__
else:
name, ext = os.path.splitext(os.path.basename(os.path.normcase(FILE_NAME)))
moduleName = "%s__main__" % name
code = importer.get_code(moduleName)
exec code in m.__dict__
if sys.version_info[:2] >= (2, 5):
module = sys.modules.get("threading")
if module is not None:
module._shutdown()

View File

@ -1,19 +0,0 @@
#------------------------------------------------------------------------------
# ConsoleKeepPath.py
# Initialization script for cx_Freeze which leaves the path alone and does
# not set the sys.frozen attribute.
#------------------------------------------------------------------------------
import sys
import zipimport
m = __import__("__main__")
importer = zipimport.zipimporter(INITSCRIPT_ZIP_FILE_NAME)
code = importer.get_code(m.__name__)
exec code in m.__dict__
if sys.version_info[:2] >= (2, 5):
module = sys.modules.get("threading")
if module is not None:
module._shutdown()

View File

@ -1,38 +0,0 @@
#------------------------------------------------------------------------------
# ConsoleSetLibPath.py
# Initialization script for cx_Freeze which manipulates the path so that the
# directory in which the executable is found is searched for extensions but
# no other directory is searched. The environment variable LD_LIBRARY_PATH is
# manipulated first, however, to ensure that shared libraries found in the
# target directory are found. This requires a restart of the executable because
# the environment variable LD_LIBRARY_PATH is only checked at startup.
#------------------------------------------------------------------------------
import encodings
import os
import sys
import warnings
import zipimport
paths = os.environ.get("LD_LIBRARY_PATH", "").split(os.pathsep)
if DIR_NAME not in paths:
paths.insert(0, DIR_NAME)
os.environ["LD_LIBRARY_PATH"] = os.pathsep.join(paths)
os.execv(sys.executable, sys.argv)
sys.frozen = True
sys.path = sys.path[:4]
os.environ["TCL_LIBRARY"] = os.path.join(DIR_NAME, "tcl")
os.environ["TK_LIBRARY"] = os.path.join(DIR_NAME, "tk")
m = __import__("__main__")
importer = zipimport.zipimporter(INITSCRIPT_ZIP_FILE_NAME)
code = importer.get_code(m.__name__)
exec code in m.__dict__
if sys.version_info[:2] >= (2, 5):
module = sys.modules.get("threading")
if module is not None:
module._shutdown()

View File

@ -1,20 +0,0 @@
#------------------------------------------------------------------------------
# SharedLib.py
# Initialization script for cx_Freeze which behaves similarly to the one for
# console based applications but must handle the case where Python has already
# been initialized and another DLL of this kind has been loaded. As such it
# does not block the path unless sys.frozen is not already set.
#------------------------------------------------------------------------------
import encodings
import os
import sys
import warnings
if not hasattr(sys, "frozen"):
sys.frozen = True
sys.path = sys.path[:4]
os.environ["TCL_LIBRARY"] = os.path.join(DIR_NAME, "tcl")
os.environ["TK_LIBRARY"] = os.path.join(DIR_NAME, "tk")

View File

@ -1,23 +0,0 @@
#------------------------------------------------------------------------------
# SharedLibSource.py
# Initialization script for cx_Freeze which imports the site module (as per
# normal processing of a Python script) and then searches for a file with the
# same name as the shared library but with the extension .pth. The entries in
# this file are used to modify the path to use for subsequent imports.
#------------------------------------------------------------------------------
import os
import sys
import warnings
# the site module must be imported for normal behavior to take place; it is
# done dynamically so that cx_Freeze will not add all modules referenced by
# the site module to the frozen executable
__import__("site")
# now locate the pth file to modify the path appropriately
baseName, ext = os.path.splitext(FILE_NAME)
pathFileName = baseName + ".pth"
sys.path = [s.strip() for s in file(pathFileName).read().splitlines()] + \
sys.path

View File

@ -1,7 +0,0 @@
import sys
print "Hello from cx_Freeze Advanced #1"
print
module = __import__("testfreeze_1")

View File

@ -1,7 +0,0 @@
import sys
print "Hello from cx_Freeze Advanced #2"
print
module = __import__("testfreeze_2")

View File

@ -1 +0,0 @@
print "Test freeze module #1"

View File

@ -1 +0,0 @@
print "Test freeze module #2"

View File

@ -1,31 +0,0 @@
# An advanced setup script to create multiple executables and demonstrate a few
# of the features available to setup scripts
#
# hello.py is a very simple "Hello, world" type script which also displays the
# environment in which the script runs
#
# Run the build process by running the command 'python setup.py build'
#
# If everything works well you should find a subdirectory in the build
# subdirectory that contains the files needed to run the script without Python
import sys
from cx_Freeze import setup, Executable
executables = [
Executable("advanced_1.py"),
Executable("advanced_2.py")
]
buildOptions = dict(
compressed = True,
includes = ["testfreeze_1", "testfreeze_2"],
path = sys.path + ["modules"])
setup(
name = "advanced_cx_Freeze_sample",
version = "0.1",
description = "Advanced sample cx_Freeze script",
options = dict(build_exe = buildOptions),
executables = executables)

View File

@ -1,27 +0,0 @@
# A simple setup script to create an executable using matplotlib.
#
# test_matplotlib.py is a very simple matplotlib application that demonstrates
# its use.
#
# Run the build process by running the command 'python setup.py build'
#
# If everything works well you should find a subdirectory in the build
# subdirectory that contains the files needed to run the application
import cx_Freeze
import sys
base = None
if sys.platform == "win32":
base = "Win32GUI"
executables = [
cx_Freeze.Executable("test_matplotlib.py", base = base)
]
cx_Freeze.setup(
name = "test_matplotlib",
version = "0.1",
description = "Sample matplotlib script",
executables = executables)

View File

@ -1,48 +0,0 @@
from numpy import arange, sin, pi
import matplotlib
matplotlib.use('WXAgg')
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas
from matplotlib.backends.backend_wx import NavigationToolbar2Wx
from matplotlib.figure import Figure
from wx import *
class CanvasFrame(Frame):
def __init__(self):
Frame.__init__(self,None,-1, 'CanvasFrame',size=(550,350))
self.SetBackgroundColour(NamedColor("WHITE"))
self.figure = Figure()
self.axes = self.figure.add_subplot(111)
t = arange(0.0,3.0,0.01)
s = sin(2*pi*t)
self.axes.plot(t,s)
self.canvas = FigureCanvas(self, -1, self.figure)
self.sizer = BoxSizer(VERTICAL)
self.sizer.Add(self.canvas, 1, LEFT | TOP | GROW)
self.SetSizerAndFit(self.sizer)
self.add_toolbar()
def add_toolbar(self):
self.toolbar = NavigationToolbar2Wx(self.canvas)
self.toolbar.Realize()
if Platform == '__WXMAC__':
self.SetToolBar(self.toolbar)
else:
tw, th = self.toolbar.GetSizeTuple()
fw, fh = self.canvas.GetSizeTuple()
self.toolbar.SetSize(Size(fw, th))
self.sizer.Add(self.toolbar, 0, LEFT | EXPAND)
self.toolbar.update()
def OnPaint(self, event):
self.canvas.draw()
class App(App):
def OnInit(self):
'Create the main window and insert the custom frame'
frame = CanvasFrame()
frame.Show(True)
return True
app = App(0)
app.MainLoop()

View File

@ -1,3 +0,0 @@
print "importing pkg1"
from . import sub1
from . import pkg2

View File

@ -1,3 +0,0 @@
print "importing pkg1.pkg2"
from . import sub3
from .. import sub4

View File

@ -1,3 +0,0 @@
print "importing pkg1.pkg2.sub3"
from . import sub5
from .. import sub6

View File

@ -1 +0,0 @@
print "importing pkg1.pkg2.sub5"

View File

@ -1,2 +0,0 @@
print "importing pkg1.sub1"
from . import sub2

View File

@ -1 +0,0 @@
print "importing pkg1.sub2"

View File

@ -1 +0,0 @@
print 'importing pkg1.sub4'

View File

@ -1 +0,0 @@
print "importing pkg1.sub6"

View File

@ -1 +0,0 @@
import pkg1

View File

@ -1,16 +0,0 @@
# relimport.py is a very simple script that tests importing using relative
# imports (available in Python 2.5 and up)
#
# Run the build process by running the command 'python setup.py build'
#
# If everything works well you should find a subdirectory in the build
# subdirectory that contains the files needed to run the script without Python
from cx_Freeze import setup, Executable
setup(
name = "relimport",
version = "0.1",
description = "Sample cx_Freeze script for relative imports",
executables = [Executable("relimport.py")])

View File

@ -1,19 +0,0 @@
import sys
print "Hello from cx_Freeze"
print
print "sys.executable", sys.executable
print "sys.prefix", sys.prefix
print
print "ARGUMENTS:"
for a in sys.argv:
print a
print
print "PATH:"
for p in sys.path:
print p
print

View File

@ -1,18 +0,0 @@
# A very simple setup script to create a single executable
#
# hello.py is a very simple "Hello, world" type script which also displays the
# environment in which the script runs
#
# Run the build process by running the command 'python setup.py build'
#
# If everything works well you should find a subdirectory in the build
# subdirectory that contains the files needed to run the script without Python
from cx_Freeze import setup, Executable
setup(
name = "hello",
version = "0.1",
description = "Sample cx_Freeze script",
executables = [Executable("hello.py")])

View File

@ -1,25 +0,0 @@
# A simple setup script to create an executable running wxPython. This also
# demonstrates the method for creating a Windows executable that does not have
# an associated console.
#
# wxapp.py is a very simple "Hello, world" type wxPython application
#
# Run the build process by running the command 'python setup.py build'
#
# If everything works well you should find a subdirectory in the build
# subdirectory that contains the files needed to run the application
import sys
from cx_Freeze import setup, Executable
base = None
if sys.platform == "win32":
base = "Win32GUI"
setup(
name = "hello",
version = "0.1",
description = "Sample cx_Freeze wxPython script",
executables = [Executable("wxapp.py", base = base)])

View File

@ -1,42 +0,0 @@
import wx
class Frame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, parent = None, title = "Hello from cx_Freeze")
panel = wx.Panel(self)
closeMeButton = wx.Button(panel, -1, "Close Me")
wx.EVT_BUTTON(self, closeMeButton.GetId(), self.OnCloseMe)
wx.EVT_CLOSE(self, self.OnCloseWindow)
pushMeButton = wx.Button(panel, -1, "Push Me")
wx.EVT_BUTTON(self, pushMeButton.GetId(), self.OnPushMe)
sizer = wx.BoxSizer(wx.HORIZONTAL)
sizer.Add(closeMeButton, flag = wx.ALL, border = 20)
sizer.Add(pushMeButton, flag = wx.ALL, border = 20)
panel.SetSizer(sizer)
topSizer = wx.BoxSizer(wx.VERTICAL)
topSizer.Add(panel, flag = wx.ALL | wx.EXPAND)
topSizer.Fit(self)
def OnCloseMe(self, event):
self.Close(True)
def OnPushMe(self, event):
1 / 0
def OnCloseWindow(self, event):
self.Destroy()
class App(wx.App):
def OnInit(self):
frame = Frame()
frame.Show(True)
self.SetTopWindow(frame)
return True
app = App(1)
app.MainLoop()

View File

@ -1,197 +0,0 @@
"""
Distutils script for cx_Freeze.
"""
import distutils.command.bdist_rpm
import distutils.command.build_ext
import distutils.command.build_scripts
import distutils.command.install
import distutils.command.install_data
import distutils.sysconfig
import os
import sys
from distutils.core import setup
from distutils.extension import Extension
class bdist_rpm(distutils.command.bdist_rpm.bdist_rpm):
# rpm automatically byte compiles all Python files in a package but we
# don't want that to happen for initscripts and samples so we tell it to
# ignore those files
def _make_spec_file(self):
specFile = distutils.command.bdist_rpm.bdist_rpm._make_spec_file(self)
specFile.insert(0, "%define _unpackaged_files_terminate_build 0%{nil}")
return specFile
def run(self):
distutils.command.bdist_rpm.bdist_rpm.run(self)
specFile = os.path.join(self.rpm_base, "SPECS",
"%s.spec" % self.distribution.get_name())
queryFormat = "%{name}-%{version}-%{release}.%{arch}.rpm"
command = "rpm -q --qf '%s' --specfile %s" % (queryFormat, specFile)
origFileName = os.popen(command).read()
parts = origFileName.split("-")
parts.insert(2, "py%s%s" % sys.version_info[:2])
newFileName = "-".join(parts)
self.move_file(os.path.join("dist", origFileName),
os.path.join("dist", newFileName))
class build_ext(distutils.command.build_ext.build_ext):
def build_extension(self, ext):
if ext.name.find("bases") < 0:
distutils.command.build_ext.build_ext.build_extension(self, ext)
return
os.environ["LD_RUN_PATH"] = "${ORIGIN}:${ORIGIN}/../lib"
objects = self.compiler.compile(ext.sources,
output_dir = self.build_temp,
include_dirs = ext.include_dirs,
debug = self.debug,
depends = ext.depends)
fileName = os.path.splitext(self.get_ext_filename(ext.name))[0]
fullName = os.path.join(self.build_lib, fileName)
libraryDirs = ext.library_dirs or []
libraries = self.get_libraries(ext)
extraArgs = ext.extra_link_args or []
if sys.platform != "win32":
vars = distutils.sysconfig.get_config_vars()
libraryDirs.append(vars["LIBPL"])
libraries.append("python%s.%s" % sys.version_info[:2])
if vars["LINKFORSHARED"]:
extraArgs.extend(vars["LINKFORSHARED"].split())
if vars["LIBS"]:
extraArgs.extend(vars["LIBS"].split())
if vars["LIBM"]:
extraArgs.append(vars["LIBM"])
if vars["BASEMODLIBS"]:
extraArgs.extend(vars["BASEMODLIBS"].split())
if vars["LOCALMODLIBS"]:
extraArgs.extend(vars["LOCALMODLIBS"].split())
extraArgs.append("-s")
self.compiler.link_executable(objects, fullName,
libraries = libraries,
library_dirs = libraryDirs,
runtime_library_dirs = ext.runtime_library_dirs,
extra_postargs = extraArgs,
debug = self.debug)
def get_ext_filename(self, name):
fileName = distutils.command.build_ext.build_ext.get_ext_filename(self,
name)
if name.find("bases") < 0:
return fileName
ext = self.compiler.exe_extension or ""
return os.path.splitext(fileName)[0] + ext
class build_scripts(distutils.command.build_scripts.build_scripts):
def copy_scripts(self):
distutils.command.build_scripts.build_scripts.copy_scripts(self)
if sys.platform == "win32":
for script in self.scripts:
batFileName = os.path.join(self.build_dir, script + ".bat")
fullScriptName = r"%s\Scripts\%s" % \
(os.path.dirname(sys.executable), script)
command = "%s %s %%1 %%2 %%3 %%4 %%5 %%6 %%7 %%8 %%9" % \
(sys.executable, fullScriptName)
file(batFileName, "w").write("@echo off\n\n%s" % command)
class install(distutils.command.install.install):
def get_sub_commands(self):
subCommands = distutils.command.install.install.get_sub_commands(self)
subCommands.append("install_packagedata")
return subCommands
class install_packagedata(distutils.command.install_data.install_data):
def run(self):
installCommand = self.get_finalized_command("install")
installDir = getattr(installCommand, "install_lib")
sourceDirs = ["samples", "initscripts"]
while sourceDirs:
sourceDir = sourceDirs.pop(0)
targetDir = os.path.join(installDir, "cx_Freeze", sourceDir)
self.mkpath(targetDir)
for name in os.listdir(sourceDir):
if name == "build" or name.startswith("."):
continue
fullSourceName = os.path.join(sourceDir, name)
if os.path.isdir(fullSourceName):
sourceDirs.append(fullSourceName)
else:
fullTargetName = os.path.join(targetDir, name)
self.copy_file(fullSourceName, fullTargetName)
self.outfiles.append(fullTargetName)
commandClasses = dict(
build_ext = build_ext,
build_scripts = build_scripts,
bdist_rpm = bdist_rpm,
install = install,
install_packagedata = install_packagedata)
if sys.platform == "win32":
libraries = ["imagehlp"]
else:
libraries = []
utilModule = Extension("cx_Freeze.util", ["source/util.c"],
libraries = libraries)
depends = ["source/bases/Common.c"]
if sys.platform == "win32":
if sys.version_info[:2] >= (2, 6):
extraSources = ["source/bases/manifest.rc"]
else:
extraSources = ["source/bases/dummy.rc"]
else:
extraSources = []
console = Extension("cx_Freeze.bases.Console",
["source/bases/Console.c"] + extraSources, depends = depends)
consoleKeepPath = Extension("cx_Freeze.bases.ConsoleKeepPath",
["source/bases/ConsoleKeepPath.c"] + extraSources, depends = depends)
extensions = [utilModule, console, consoleKeepPath]
if sys.platform == "win32":
gui = Extension("cx_Freeze.bases.Win32GUI",
["source/bases/Win32GUI.c"] + extraSources,
depends = depends, extra_link_args = ["-mwindows"])
extensions.append(gui)
docFiles = "LICENSE.txt README.txt HISTORY.txt doc/cx_Freeze.html"
classifiers = [
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"License :: OSI Approved :: Python Software Foundation License",
"Natural Language :: English",
"Operating System :: OS Independent",
"Programming Language :: C",
"Programming Language :: Python",
"Topic :: Software Development :: Build Tools",
"Topic :: Software Development :: Libraries :: Python Modules",
"Topic :: System :: Software Distribution",
"Topic :: Utilities"
]
setup(name = "cx_Freeze",
description = "create standalone executables from Python scripts",
long_description = "create standalone executables from Python scripts",
version = "4.0.1",
cmdclass = commandClasses,
options = dict(bdist_rpm = dict(doc_files = docFiles),
install = dict(optimize = 1)),
ext_modules = extensions,
packages = ['cx_Freeze'],
maintainer="Anthony Tuininga",
maintainer_email="anthony.tuininga@gmail.com",
url = "http://cx-freeze.sourceforge.net",
scripts = ["cxfreeze"],
classifiers = classifiers,
keywords = "freeze",
license = "Python Software Foundation License")

View File

@ -1,262 +0,0 @@
//-----------------------------------------------------------------------------
// Common.c
// Routines which are common to running frozen executables.
//-----------------------------------------------------------------------------
#include <compile.h>
#include <eval.h>
#include <osdefs.h>
// global variables (used for simplicity)
static PyObject *g_FileName = NULL;
static PyObject *g_DirName = NULL;
static PyObject *g_ExclusiveZipFileName = NULL;
static PyObject *g_SharedZipFileName = NULL;
static PyObject *g_InitScriptZipFileName = NULL;
//-----------------------------------------------------------------------------
// GetDirName()
// Return the directory name of the given path.
//-----------------------------------------------------------------------------
static int GetDirName(
const char *path, // path to calculate dir name for
PyObject **dirName) // directory name (OUT)
{
int i;
for (i = strlen(path); i > 0 && path[i] != SEP; --i);
*dirName = PyString_FromStringAndSize(path, i);
if (!*dirName)
return FatalError("cannot create string for directory name");
return 0;
}
//-----------------------------------------------------------------------------
// SetExecutableName()
// Set the script to execute and calculate the directory in which the
// executable is found as well as the exclusive (only for this executable) and
// shared zip file names.
//-----------------------------------------------------------------------------
static int SetExecutableName(
const char *fileName) // script to execute
{
char temp[MAXPATHLEN + 12], *ptr;
#ifndef WIN32
char linkData[MAXPATHLEN + 1];
struct stat statData;
size_t linkSize, i;
PyObject *dirName;
#endif
// store file name
g_FileName = PyString_FromString(fileName);
if (!g_FileName)
return FatalError("cannot create string for file name");
#ifndef WIN32
for (i = 0; i < 25; i++) {
if (lstat(fileName, &statData) < 0) {
PyErr_SetFromErrnoWithFilename(PyExc_OSError, (char*) fileName);
return FatalError("unable to stat file");
}
if (!S_ISLNK(statData.st_mode))
break;
linkSize = readlink(fileName, linkData, sizeof(linkData));
if (linkSize < 0) {
PyErr_SetFromErrnoWithFilename(PyExc_OSError, (char*) fileName);
return FatalError("unable to stat file");
}
if (linkData[0] == '/') {
Py_DECREF(g_FileName);
g_FileName = PyString_FromStringAndSize(linkData, linkSize);
} else {
if (GetDirName(PyString_AS_STRING(g_FileName), &dirName) < 0)
return -1;
if (PyString_GET_SIZE(dirName) + linkSize + 1 > MAXPATHLEN) {
Py_DECREF(dirName);
return FatalError("cannot dereference link, path too large");
}
strcpy(temp, PyString_AS_STRING(dirName));
strcat(temp, "/");
strcat(temp, linkData);
Py_DECREF(g_FileName);
g_FileName = PyString_FromString(temp);
}
if (!g_FileName)
return FatalError("cannot create string for linked file name");
fileName = PyString_AS_STRING(g_FileName);
}
#endif
// calculate and store directory name
if (GetDirName(fileName, &g_DirName) < 0)
return -1;
// calculate and store exclusive zip file name
strcpy(temp, fileName);
ptr = temp + strlen(temp) - 1;
while (ptr > temp && *ptr != SEP && *ptr != '.')
ptr--;
if (*ptr == '.')
*ptr = '\0';
strcat(temp, ".zip");
g_ExclusiveZipFileName = PyString_FromString(temp);
if (!g_ExclusiveZipFileName)
return FatalError("cannot create string for exclusive zip file name");
// calculate and store shared zip file name
strcpy(temp, PyString_AS_STRING(g_DirName));
ptr = temp + strlen(temp);
*ptr++ = SEP;
strcpy(ptr, "library.zip");
g_SharedZipFileName = PyString_FromString(temp);
if (!g_SharedZipFileName)
return FatalError("cannot create string for shared zip file name");
return 0;
}
//-----------------------------------------------------------------------------
// SetPathToSearch()
// Set the path to search. This includes the file (for those situations where
// a zip file is attached to the executable itself), the directory where the
// executable is found (to search for extensions), the exclusive zip file
// name and the shared zip file name.
//-----------------------------------------------------------------------------
static int SetPathToSearch(void)
{
PyObject *pathList;
pathList = PySys_GetObject("path");
if (!pathList)
return FatalError("cannot acquire sys.path");
if (PyList_Insert(pathList, 0, g_FileName) < 0)
return FatalError("cannot insert file name into sys.path");
if (PyList_Insert(pathList, 1, g_DirName) < 0)
return FatalError("cannot insert directory name into sys.path");
if (PyList_Insert(pathList, 2, g_ExclusiveZipFileName) < 0)
return FatalError("cannot insert exclusive zip name into sys.path");
if (PyList_Insert(pathList, 3, g_SharedZipFileName) < 0)
return FatalError("cannot insert shared zip name into sys.path");
return 0;
}
//-----------------------------------------------------------------------------
// GetImporterHelper()
// Helper which is used to locate the importer for the initscript.
//-----------------------------------------------------------------------------
static PyObject *GetImporterHelper(
PyObject *module, // zipimport module
PyObject *fileName) // name of file to search
{
PyObject *importer;
importer = PyObject_CallMethod(module, "zipimporter", "O", fileName);
if (importer)
g_InitScriptZipFileName = fileName;
else
PyErr_Clear();
return importer;
}
//-----------------------------------------------------------------------------
// GetImporter()
// Return the importer which will be used for importing the initialization
// script. The executable itself is searched first, followed by the exclusive
// zip file and finally by the shared zip file.
//-----------------------------------------------------------------------------
static int GetImporter(
PyObject **importer) // importer (OUT)
{
PyObject *module;
module = PyImport_ImportModule("zipimport");
if (!module)
return FatalError("cannot import zipimport module");
*importer = GetImporterHelper(module, g_FileName);
if (!*importer) {
*importer = GetImporterHelper(module, g_ExclusiveZipFileName);
if (!*importer)
*importer = GetImporterHelper(module, g_SharedZipFileName);
}
Py_DECREF(module);
if (!*importer)
return FatalError("cannot get zipimporter instance");
return 0;
}
//-----------------------------------------------------------------------------
// PopulateInitScriptDict()
// Return the dictionary used by the initialization script.
//-----------------------------------------------------------------------------
static int PopulateInitScriptDict(
PyObject *dict) // dictionary to populate
{
if (!dict)
return FatalError("unable to create temporary dictionary");
if (PyDict_SetItemString(dict, "__builtins__", PyEval_GetBuiltins()) < 0)
return FatalError("unable to set __builtins__");
if (PyDict_SetItemString(dict, "FILE_NAME", g_FileName) < 0)
return FatalError("unable to set FILE_NAME");
if (PyDict_SetItemString(dict, "DIR_NAME", g_DirName) < 0)
return FatalError("unable to set DIR_NAME");
if (PyDict_SetItemString(dict, "EXCLUSIVE_ZIP_FILE_NAME",
g_ExclusiveZipFileName) < 0)
return FatalError("unable to set EXCLUSIVE_ZIP_FILE_NAME");
if (PyDict_SetItemString(dict, "SHARED_ZIP_FILE_NAME",
g_SharedZipFileName) < 0)
return FatalError("unable to set SHARED_ZIP_FILE_NAME");
if (PyDict_SetItemString(dict, "INITSCRIPT_ZIP_FILE_NAME",
g_InitScriptZipFileName) < 0)
return FatalError("unable to set INITSCRIPT_ZIP_FILE_NAME");
return 0;
}
//-----------------------------------------------------------------------------
// ExecuteScript()
// Execute the script found within the file.
//-----------------------------------------------------------------------------
static int ExecuteScript(
const char *fileName) // name of file containing Python code
{
PyObject *importer, *dict, *code, *temp;
if (SetExecutableName(fileName) < 0)
return -1;
if (SetPathToSearch() < 0)
return -1;
importer = NULL;
if (GetImporter(&importer) < 0)
return -1;
// create and populate dictionary for initscript module
dict = PyDict_New();
if (PopulateInitScriptDict(dict) < 0) {
Py_XDECREF(dict);
Py_DECREF(importer);
return -1;
}
// locate and execute script
code = PyObject_CallMethod(importer, "get_code", "s", "cx_Freeze__init__");
Py_DECREF(importer);
if (!code)
return FatalError("unable to locate initialization module");
temp = PyEval_EvalCode( (PyCodeObject*) code, dict, dict);
Py_DECREF(code);
Py_DECREF(dict);
if (!temp)
return FatalScriptError();
Py_DECREF(temp);
return 0;
}

View File

@ -1,72 +0,0 @@
//-----------------------------------------------------------------------------
// Console.c
// Main routine for frozen programs which run in a console.
//-----------------------------------------------------------------------------
#include <Python.h>
#ifdef __WIN32__
#include <windows.h>
#endif
//-----------------------------------------------------------------------------
// FatalError()
// Prints a fatal error.
//-----------------------------------------------------------------------------
static int FatalError(
const char *message) // message to print
{
PyErr_Print();
Py_FatalError(message);
return -1;
}
//-----------------------------------------------------------------------------
// FatalScriptError()
// Prints a fatal error in the initialization script.
//-----------------------------------------------------------------------------
static int FatalScriptError(void)
{
PyErr_Print();
return -1;
}
#include "Common.c"
//-----------------------------------------------------------------------------
// main()
// Main routine for frozen programs.
//-----------------------------------------------------------------------------
int main(int argc, char **argv)
{
const char *fileName;
char *encoding;
// initialize Python
Py_NoSiteFlag = 1;
Py_FrozenFlag = 1;
Py_IgnoreEnvironmentFlag = 1;
encoding = getenv("PYTHONIOENCODING");
if (encoding != NULL) {
Py_FileSystemDefaultEncoding = strndup(encoding, 100);
}
Py_SetPythonHome("");
Py_SetProgramName(argv[0]);
fileName = Py_GetProgramFullPath();
Py_Initialize();
PySys_SetArgv(argc, argv);
// do the work
if (ExecuteScript(fileName) < 0)
return 1;
Py_Finalize();
return 0;
}

View File

@ -1,60 +0,0 @@
//-----------------------------------------------------------------------------
// ConsoleKeepPath.c
// Main routine for frozen programs which need a Python installation to do
// their work.
//-----------------------------------------------------------------------------
#include <Python.h>
#ifdef __WIN32__
#include <windows.h>
#endif
//-----------------------------------------------------------------------------
// FatalError()
// Prints a fatal error.
//-----------------------------------------------------------------------------
static int FatalError(
const char *message) // message to print
{
PyErr_Print();
Py_FatalError(message);
return -1;
}
//-----------------------------------------------------------------------------
// FatalScriptError()
// Prints a fatal error in the initialization script.
//-----------------------------------------------------------------------------
static int FatalScriptError(void)
{
PyErr_Print();
return -1;
}
#include "Common.c"
//-----------------------------------------------------------------------------
// main()
// Main routine for frozen programs.
//-----------------------------------------------------------------------------
int main(int argc, char **argv)
{
const char *fileName;
// initialize Python
Py_SetProgramName(argv[0]);
fileName = Py_GetProgramFullPath();
Py_Initialize();
PySys_SetArgv(argc, argv);
// do the work
if (ExecuteScript(fileName) < 0)
return 1;
Py_Finalize();
return 0;
}

View File

@ -1,242 +0,0 @@
//-----------------------------------------------------------------------------
// Win32GUI.c
// Main routine for frozen programs written for the Win32 GUI subsystem.
//-----------------------------------------------------------------------------
#include <Python.h>
#include <windows.h>
//-----------------------------------------------------------------------------
// FatalError()
// Handle a fatal error.
//-----------------------------------------------------------------------------
static int FatalError(
char *a_Message) // message to display
{
MessageBox(NULL, a_Message, "cx_Freeze Fatal Error", MB_ICONERROR);
Py_Finalize();
return -1;
}
//-----------------------------------------------------------------------------
// StringifyObject()
// Stringify a Python object.
//-----------------------------------------------------------------------------
static char *StringifyObject(
PyObject *object, // object to stringify
PyObject **stringRep) // string representation
{
if (object) {
*stringRep = PyObject_Str(object);
if (*stringRep)
return PyString_AS_STRING(*stringRep);
return "Unable to stringify";
}
// object is NULL
*stringRep = NULL;
return "None";
}
//-----------------------------------------------------------------------------
// FatalPythonErrorNoTraceback()
// Handle a fatal Python error without traceback.
//-----------------------------------------------------------------------------
static int FatalPythonErrorNoTraceback(
PyObject *origType, // exception type
PyObject *origValue, // exception value
char *message) // message to display
{
PyObject *typeStrRep, *valueStrRep, *origTypeStrRep, *origValueStrRep;
char *totalMessage, *typeStr, *valueStr, *origTypeStr, *origValueStr;
PyObject *type, *value, *traceback;
int totalMessageLength;
char *messageFormat;
// fetch error and string representations of the error
PyErr_Fetch(&type, &value, &traceback);
origTypeStr = StringifyObject(origType, &origTypeStrRep);
origValueStr = StringifyObject(origValue, &origValueStrRep);
typeStr = StringifyObject(type, &typeStrRep);
valueStr = StringifyObject(value, &valueStrRep);
// fill out the message to be displayed
messageFormat = "Type: %s\nValue: %s\nOther Type: %s\nOtherValue: %s\n%s";
totalMessageLength = strlen(origTypeStr) + strlen(origValueStr) +
strlen(typeStr) + strlen(valueStr) + strlen(message) +
strlen(messageFormat) + 1;
totalMessage = malloc(totalMessageLength);
if (!totalMessage)
return FatalError("Out of memory!");
sprintf(totalMessage, messageFormat, typeStr, valueStr, origTypeStr,
origValueStr, message);
// display the message
MessageBox(NULL, totalMessage,
"cx_Freeze: Python error in main script (traceback unavailable)",
MB_ICONERROR);
free(totalMessage);
return -1;
}
//-----------------------------------------------------------------------------
// ArgumentValue()
// Return a suitable argument value by replacing NULL with Py_None.
//-----------------------------------------------------------------------------
static PyObject *ArgumentValue(
PyObject *object) // argument to massage
{
if (object) {
Py_INCREF(object);
return object;
}
Py_INCREF(Py_None);
return Py_None;
}
//-----------------------------------------------------------------------------
// HandleSystemExitException()
// Handles a system exit exception differently. If an integer value is passed
// through then that becomes the exit value; otherwise the string value of the
// value passed through is displayed in a message box.
//-----------------------------------------------------------------------------
static void HandleSystemExitException()
{
PyObject *type, *value, *traceback, *valueStr;
int exitCode = 0;
char *message;
PyErr_Fetch(&type, &value, &traceback);
if (PyInstance_Check(value)) {
PyObject *code = PyObject_GetAttrString(value, "code");
if (code) {
Py_DECREF(value);
value = code;
if (value == Py_None)
Py_Exit(0);
}
}
if (PyInt_Check(value))
exitCode = PyInt_AsLong(value);
else {
message = StringifyObject(value, &valueStr);
MessageBox(NULL, message, "cx_Freeze: Application Terminated",
MB_ICONERROR);
Py_XDECREF(valueStr);
exitCode = 1;
}
Py_Exit(exitCode);
}
//-----------------------------------------------------------------------------
// FatalScriptError()
// Handle a fatal Python error with traceback.
//-----------------------------------------------------------------------------
static int FatalScriptError()
{
PyObject *type, *value, *traceback, *argsTuple, *module, *method, *result;
int tracebackLength, i;
char *tracebackStr;
// if a system exception, handle it specially
if (PyErr_ExceptionMatches(PyExc_SystemExit))
HandleSystemExitException();
// get the exception details
PyErr_Fetch(&type, &value, &traceback);
// import the traceback module
module = PyImport_ImportModule("traceback");
if (!module)
return FatalPythonErrorNoTraceback(type, value,
"Cannot import traceback module.");
// get the format_exception method
method = PyObject_GetAttrString(module, "format_exception");
Py_DECREF(module);
if (!method)
return FatalPythonErrorNoTraceback(type, value,
"Cannot get format_exception method.");
// create a tuple for the arguments
argsTuple = PyTuple_New(3);
if (!argsTuple) {
Py_DECREF(method);
return FatalPythonErrorNoTraceback(type, value,
"Cannot create arguments tuple for traceback.");
}
PyTuple_SET_ITEM(argsTuple, 0, ArgumentValue(type));
PyTuple_SET_ITEM(argsTuple, 1, ArgumentValue(value));
PyTuple_SET_ITEM(argsTuple, 2, ArgumentValue(traceback));
// call the format_exception method
result = PyObject_CallObject(method, argsTuple);
Py_DECREF(method);
Py_DECREF(argsTuple);
if (!result)
return FatalPythonErrorNoTraceback(type, value,
"Failed calling format_exception method.");
// determine length of string representation of formatted traceback
tracebackLength = 1;
for (i = 0; i < PyList_GET_SIZE(result); i++)
tracebackLength += PyString_GET_SIZE(PyList_GET_ITEM(result, i));
// create a string representation of the formatted traceback
tracebackStr = malloc(tracebackLength);
if (!tracebackStr) {
Py_DECREF(result);
return FatalError("Out of memory!");
}
tracebackStr[0] = '\0';
for (i = 0; i < PyList_GET_SIZE(result); i++)
strcat(tracebackStr, PyString_AS_STRING(PyList_GET_ITEM(result, i)));
Py_DECREF(result);
// bring up the error
MessageBox(NULL, tracebackStr, "cx_Freeze: Python error in main script",
MB_ICONERROR);
Py_Finalize();
return 1;
}
#include "Common.c"
//-----------------------------------------------------------------------------
// WinMain()
// Main routine for the executable in Windows.
//-----------------------------------------------------------------------------
int WINAPI WinMain(
HINSTANCE instance, // handle to application
HINSTANCE prevInstance, // previous handle to application
LPSTR commandLine, // command line
int showFlag) // show flag
{
const char *fileName;
// initialize Python
Py_NoSiteFlag = 1;
Py_FrozenFlag = 1;
Py_IgnoreEnvironmentFlag = 1;
Py_SetPythonHome("");
Py_SetProgramName(__argv[0]);
fileName = Py_GetProgramFullPath();
Py_Initialize();
PySys_SetArgv(__argc, __argv);
// do the work
if (ExecuteScript(fileName) < 0)
return 1;
// terminate Python
Py_Finalize();
return 0;
}

View File

@ -1,5 +0,0 @@
STRINGTABLE
{
1, "Just to ensure that buggy EndUpdateResource doesn't fall over."
}

View File

@ -1,3 +0,0 @@
#include "dummy.rc"
1 24 source/bases/manifest.txt

View File

@ -1,418 +0,0 @@
//-----------------------------------------------------------------------------
// util.c
// Shared library for use by cx_Freeze.
//-----------------------------------------------------------------------------
#include <Python.h>
#ifdef WIN32
#include <windows.h>
#include <imagehlp.h>
#pragma pack(2)
typedef struct {
BYTE bWidth; // Width, in pixels, of the image
BYTE bHeight; // Height, in pixels, of the image
BYTE bColorCount; // Number of colors in image
BYTE bReserved; // Reserved ( must be 0)
WORD wPlanes; // Color Planes
WORD wBitCount; // Bits per pixel
DWORD dwBytesInRes; // How many bytes in this resource?
DWORD dwImageOffset; // Where in the file is this image?
} ICONDIRENTRY;
typedef struct {
WORD idReserved; // Reserved (must be 0)
WORD idType; // Resource Type (1 for icons)
WORD idCount; // How many images?
ICONDIRENTRY idEntries[0]; // An entry for each image
} ICONDIR;
typedef struct {
BYTE bWidth; // Width, in pixels, of the image
BYTE bHeight; // Height, in pixels, of the image
BYTE bColorCount; // Number of colors in image
BYTE bReserved; // Reserved ( must be 0)
WORD wPlanes; // Color Planes
WORD wBitCount; // Bits per pixel
DWORD dwBytesInRes; // How many bytes in this resource?
WORD nID; // resource ID
} GRPICONDIRENTRY;
typedef struct {
WORD idReserved; // Reserved (must be 0)
WORD idType; // Resource Type (1 for icons)
WORD idCount; // How many images?
GRPICONDIRENTRY idEntries[0]; // An entry for each image
} GRPICONDIR;
#endif
//-----------------------------------------------------------------------------
// Globals
//-----------------------------------------------------------------------------
#ifdef WIN32
static PyObject *g_BindErrorException = NULL;
static PyObject *g_ImageNames = NULL;
#endif
#ifdef WIN32
//-----------------------------------------------------------------------------
// BindStatusRoutine()
// Called by BindImageEx() at various points. This is used to determine the
// dependency tree which is later examined by cx_Freeze.
//-----------------------------------------------------------------------------
static BOOL __stdcall BindStatusRoutine(
IMAGEHLP_STATUS_REASON reason, // reason called
PSTR imageName, // name of image being examined
PSTR dllName, // name of DLL
ULONG virtualAddress, // computed virtual address
ULONG parameter) // parameter (value depends on reason)
{
char fileName[MAX_PATH + 1];
switch (reason) {
case BindImportModule:
if (!SearchPath(NULL, dllName, NULL, sizeof(fileName), fileName,
NULL))
return FALSE;
Py_INCREF(Py_None);
if (PyDict_SetItemString(g_ImageNames, fileName, Py_None) < 0)
return FALSE;
break;
default:
break;
}
return TRUE;
}
//-----------------------------------------------------------------------------
// GetFileData()
// Return the data for the given file.
//-----------------------------------------------------------------------------
static int GetFileData(
const char *fileName, // name of file to read
char **data) // pointer to data (OUT)
{
DWORD numberOfBytesRead, dataSize;
HANDLE file;
file = CreateFile(fileName, GENERIC_READ, FILE_SHARE_READ, NULL,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (file == INVALID_HANDLE_VALUE)
return -1;
dataSize = GetFileSize(file, NULL);
if (dataSize == INVALID_FILE_SIZE) {
CloseHandle(file);
return -1;
}
*data = PyMem_Malloc(dataSize);
if (!*data) {
CloseHandle(file);
return -1;
}
if (!ReadFile(file, *data, dataSize, &numberOfBytesRead, NULL)) {
CloseHandle(file);
return -1;
}
CloseHandle(file);
return 0;
}
//-----------------------------------------------------------------------------
// CreateGroupIconResource()
// Return the group icon resource given the icon file data.
//-----------------------------------------------------------------------------
static GRPICONDIR *CreateGroupIconResource(
ICONDIR *iconDir, // icon information
DWORD *resourceSize) // size of resource (OUT)
{
GRPICONDIR *groupIconDir;
int i;
*resourceSize = sizeof(GRPICONDIR) +
sizeof(GRPICONDIRENTRY) * iconDir->idCount;
groupIconDir = PyMem_Malloc(*resourceSize);
if (!groupIconDir)
return NULL;
groupIconDir->idReserved = iconDir->idReserved;
groupIconDir->idType = iconDir->idType;
groupIconDir->idCount = iconDir->idCount;
for (i = 0; i < iconDir->idCount; i++) {
groupIconDir->idEntries[i].bWidth = iconDir->idEntries[i].bWidth;
groupIconDir->idEntries[i].bHeight = iconDir->idEntries[i].bHeight;
groupIconDir->idEntries[i].bColorCount =
iconDir->idEntries[i].bColorCount;
groupIconDir->idEntries[i].bReserved = iconDir->idEntries[i].bReserved;
groupIconDir->idEntries[i].wPlanes = iconDir->idEntries[i].wPlanes;
groupIconDir->idEntries[i].wBitCount = iconDir->idEntries[i].wBitCount;
groupIconDir->idEntries[i].dwBytesInRes =
iconDir->idEntries[i].dwBytesInRes;
groupIconDir->idEntries[i].nID = i + 1;
}
return groupIconDir;
}
//-----------------------------------------------------------------------------
// ExtAddIcon()
// Add the icon as a resource to the specified file.
//-----------------------------------------------------------------------------
static PyObject *ExtAddIcon(
PyObject *self, // passthrough argument
PyObject *args) // arguments
{
char *executableName, *iconName, *data, *iconData;
GRPICONDIR *groupIconDir;
DWORD resourceSize;
ICONDIR *iconDir;
BOOL succeeded;
HANDLE handle;
int i;
if (!PyArg_ParseTuple(args, "ss", &executableName, &iconName))
return NULL;
// begin updating the executable
handle = BeginUpdateResource(executableName, FALSE);
if (!handle) {
PyErr_SetExcFromWindowsErrWithFilename(PyExc_WindowsError,
GetLastError(), executableName);
return NULL;
}
// first attempt to get the data from the icon file
data = NULL;
succeeded = TRUE;
groupIconDir = NULL;
if (GetFileData(iconName, &data) < 0)
succeeded = FALSE;
iconDir = (ICONDIR*) data;
// next, attempt to add a group icon resource
if (succeeded) {
groupIconDir = CreateGroupIconResource(iconDir, &resourceSize);
if (groupIconDir)
succeeded = UpdateResource(handle, RT_GROUP_ICON,
MAKEINTRESOURCE(1),
MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL),
groupIconDir, resourceSize);
else succeeded = FALSE;
}
// next, add each icon as a resource
if (succeeded) {
for (i = 0; i < iconDir->idCount; i++) {
iconData = &data[iconDir->idEntries[i].dwImageOffset];
resourceSize = iconDir->idEntries[i].dwBytesInRes;
succeeded = UpdateResource(handle, RT_ICON, MAKEINTRESOURCE(i + 1),
MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL), iconData,
resourceSize);
if (!succeeded)
break;
}
}
// finish writing the resource (or discarding the changes upon an error)
if (!EndUpdateResource(handle, !succeeded)) {
if (succeeded) {
succeeded = FALSE;
PyErr_SetExcFromWindowsErrWithFilename(PyExc_WindowsError,
GetLastError(), executableName);
}
}
// clean up
if (groupIconDir)
PyMem_Free(groupIconDir);
if (data)
PyMem_Free(data);
if (!succeeded)
return NULL;
Py_INCREF(Py_None);
return Py_None;
}
//-----------------------------------------------------------------------------
// ExtBeginUpdateResource()
// Wrapper for BeginUpdateResource().
//-----------------------------------------------------------------------------
static PyObject *ExtBeginUpdateResource(
PyObject *self, // passthrough argument
PyObject *args) // arguments
{
BOOL deleteExistingResources;
char *fileName;
HANDLE handle;
deleteExistingResources = TRUE;
if (!PyArg_ParseTuple(args, "s|i", &fileName, &deleteExistingResources))
return NULL;
handle = BeginUpdateResource(fileName, deleteExistingResources);
if (!handle) {
PyErr_SetExcFromWindowsErrWithFilename(PyExc_WindowsError,
GetLastError(), fileName);
return NULL;
}
return PyInt_FromLong((long) handle);
}
//-----------------------------------------------------------------------------
// ExtUpdateResource()
// Wrapper for UpdateResource().
//-----------------------------------------------------------------------------
static PyObject *ExtUpdateResource(
PyObject *self, // passthrough argument
PyObject *args) // arguments
{
int resourceType, resourceId, resourceDataSize;
char *resourceData;
HANDLE handle;
if (!PyArg_ParseTuple(args, "iiis#", &handle, &resourceType, &resourceId,
&resourceData, &resourceDataSize))
return NULL;
if (!UpdateResource(handle, MAKEINTRESOURCE(resourceType),
MAKEINTRESOURCE(resourceId),
MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL), resourceData,
resourceDataSize)) {
PyErr_SetExcFromWindowsErr(PyExc_WindowsError, GetLastError());
return NULL;
}
Py_INCREF(Py_None);
return Py_None;
}
//-----------------------------------------------------------------------------
// ExtEndUpdateResource()
// Wrapper for EndUpdateResource().
//-----------------------------------------------------------------------------
static PyObject *ExtEndUpdateResource(
PyObject *self, // passthrough argument
PyObject *args) // arguments
{
BOOL discardChanges;
HANDLE handle;
discardChanges = FALSE;
if (!PyArg_ParseTuple(args, "i|i", &handle, &discardChanges))
return NULL;
if (!EndUpdateResource(handle, discardChanges)) {
PyErr_SetExcFromWindowsErr(PyExc_WindowsError, GetLastError());
return NULL;
}
Py_INCREF(Py_None);
return Py_None;
}
//-----------------------------------------------------------------------------
// ExtGetDependentFiles()
// Return a list of files that this file depends on.
//-----------------------------------------------------------------------------
static PyObject *ExtGetDependentFiles(
PyObject *self, // passthrough argument
PyObject *args) // arguments
{
PyObject *results;
char *imageName;
if (!PyArg_ParseTuple(args, "s", &imageName))
return NULL;
g_ImageNames = PyDict_New();
if (!g_ImageNames)
return NULL;
if (!BindImageEx(BIND_NO_BOUND_IMPORTS | BIND_NO_UPDATE | BIND_ALL_IMAGES,
imageName, NULL, NULL, BindStatusRoutine)) {
Py_DECREF(g_ImageNames);
PyErr_SetExcFromWindowsErrWithFilename(g_BindErrorException,
GetLastError(), imageName);
return NULL;
}
results = PyDict_Keys(g_ImageNames);
Py_DECREF(g_ImageNames);
return results;
}
//-----------------------------------------------------------------------------
// ExtGetSystemDir()
// Return the Windows directory (C:\Windows for example).
//-----------------------------------------------------------------------------
static PyObject *ExtGetSystemDir(
PyObject *self, // passthrough argument
PyObject *args) // arguments (ignored)
{
char dir[MAX_PATH + 1];
if (GetSystemDirectory(dir, sizeof(dir)))
return PyString_FromString(dir);
PyErr_SetExcFromWindowsErr(PyExc_RuntimeError, GetLastError());
return NULL;
}
#endif
//-----------------------------------------------------------------------------
// ExtSetOptimizeFlag()
// Set the optimize flag as needed.
//-----------------------------------------------------------------------------
static PyObject *ExtSetOptimizeFlag(
PyObject *self, // passthrough argument
PyObject *args) // arguments
{
if (!PyArg_ParseTuple(args, "i", &Py_OptimizeFlag))
return NULL;
Py_INCREF(Py_None);
return Py_None;
}
//-----------------------------------------------------------------------------
// Methods
//-----------------------------------------------------------------------------
static PyMethodDef g_ModuleMethods[] = {
{ "SetOptimizeFlag", ExtSetOptimizeFlag, METH_VARARGS },
#ifdef WIN32
{ "BeginUpdateResource", ExtBeginUpdateResource, METH_VARARGS },
{ "UpdateResource", ExtUpdateResource, METH_VARARGS },
{ "EndUpdateResource", ExtEndUpdateResource, METH_VARARGS },
{ "AddIcon", ExtAddIcon, METH_VARARGS },
{ "GetDependentFiles", ExtGetDependentFiles, METH_VARARGS },
{ "GetSystemDir", ExtGetSystemDir, METH_NOARGS },
#endif
{ NULL }
};
//-----------------------------------------------------------------------------
// initutil()
// Initialization routine for the shared libary.
//-----------------------------------------------------------------------------
void initutil(void)
{
PyObject *module;
module = Py_InitModule("cx_Freeze.util", g_ModuleMethods);
if (!module)
return;
#ifdef WIN32
g_BindErrorException = PyErr_NewException("cx_Freeze.util.BindError",
NULL, NULL);
if (!g_BindErrorException)
return;
if (PyModule_AddObject(module, "BindError", g_BindErrorException) < 0)
return;
#endif
}

View File

@ -237,28 +237,10 @@ cp build/podofo/build/src/Release/podofo.exp lib/
cp build/podofo/build/podofo_config.h include/podofo/
cp -r build/podofo/src/* include/podofo/
The following patch (against 0.8.1) was required to get it to compile:
You have to use >0.8.1 (>= revision 1269)
The following patch (against -r1269) was required to get it to compile:
Index: src/PdfImage.cpp
===================================================================
--- src/PdfImage.cpp (revision 1261)
+++ src/PdfImage.cpp (working copy)
@@ -627,7 +627,7 @@
long lLen = static_cast<long>(pInfo->rowbytes * height);
char* pBuffer = static_cast<char*>(malloc(sizeof(char) * lLen));
- png_bytep pRows[height];
+ png_bytepp pRows = static_cast<png_bytepp>(malloc(sizeof(png_bytep)*height));
for(int y=0; y<height; y++)
{
pRows[y] = reinterpret_cast<png_bytep>(pBuffer + (y * pInfo->rowbytes));
@@ -672,6 +672,7 @@
this->SetImageData( width, height, pInfo->bit_depth, &stream );
free(pBuffer);
+ free(pRows);
}
#endif // PODOFO_HAVE_PNG_LIB
Index: src/PdfFiltersPrivate.cpp
===================================================================

View File

@ -3,7 +3,7 @@ __license__ = 'GPL v3'
__copyright__ = '2008, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
import sys, os, re, logging, time, mimetypes, \
import uuid, sys, os, re, logging, time, mimetypes, \
__builtin__, warnings, multiprocessing
from urllib import getproxies
__builtin__.__dict__['dynamic_property'] = lambda(func): func(None)
@ -23,6 +23,8 @@ from calibre.startup import winutil, winutilerror
import mechanize
uuid.uuid4() # Imported before PyQt4 to workaround PyQt4 util-linux conflict on gentoo
if False:
winutil, winutilerror, __appname__, islinux, __version__
fcntl, win32event, isfrozen, __author__, terminal_controller

View File

@ -2,7 +2,7 @@ __license__ = 'GPL v3'
__copyright__ = '2008, Kovid Goyal kovid@kovidgoyal.net'
__docformat__ = 'restructuredtext en'
__appname__ = 'calibre'
__version__ = '0.7.13'
__version__ = '0.7.14'
__author__ = "Kovid Goyal <kovid@kovidgoyal.net>"
import re

View File

@ -351,3 +351,12 @@ class CatalogPlugin(Plugin):
# Default implementation does nothing
raise NotImplementedError('CatalogPlugin.generate_catalog() default '
'method, should be overridden in subclass')
class InterfaceActionBase(Plugin):
supported_platforms = ['windows', 'osx', 'linux']
author = 'Kovid Goyal'
type = _('User Interface Action')
can_be_disabled = False
actual_plugin = None

View File

@ -574,3 +574,92 @@ plugins += [x for x in list(locals().values()) if isinstance(x, type) and \
plugins += [x for x in list(locals().values()) if isinstance(x, type) and \
x.__name__.endswith('MetadataWriter')]
plugins += input_profiles + output_profiles
from calibre.customize import InterfaceActionBase
class ActionAdd(InterfaceActionBase):
name = 'Add Books'
actual_plugin = 'calibre.gui2.actions.add:AddAction'
class ActionFetchAnnotations(InterfaceActionBase):
name = 'Fetch Annotations'
actual_plugin = 'calibre.gui2.actions.annotate:FetchAnnotationsAction'
class ActionGenerateCatalog(InterfaceActionBase):
name = 'Generate Catalog'
actual_plugin = 'calibre.gui2.actions.catalog:GenerateCatalogAction'
class ActionConvert(InterfaceActionBase):
name = 'Convert Books'
actual_plugin = 'calibre.gui2.actions.convert:ConvertAction'
class ActionDelete(InterfaceActionBase):
name = 'Remove Books'
actual_plugin = 'calibre.gui2.actions.delete:DeleteAction'
class ActionEditMetadata(InterfaceActionBase):
name = 'Edit Metadata'
actual_plugin = 'calibre.gui2.actions.edit_metadata:EditMetadataAction'
class ActionView(InterfaceActionBase):
name = 'View'
actual_plugin = 'calibre.gui2.actions.view:ViewAction'
class ActionFetchNews(InterfaceActionBase):
name = 'Fetch News'
actual_plugin = 'calibre.gui2.actions.fetch_news:FetchNewsAction'
class ActionSaveToDisk(InterfaceActionBase):
name = 'Save To Disk'
actual_plugin = 'calibre.gui2.actions.save_to_disk:SaveToDiskAction'
class ActionShowBookDetails(InterfaceActionBase):
name = 'Show Book Details'
actual_plugin = 'calibre.gui2.actions.show_book_details:ShowBookDetailsAction'
class ActionRestart(InterfaceActionBase):
name = 'Restart'
actual_plugin = 'calibre.gui2.actions.restart:RestartAction'
class ActionOpenFolder(InterfaceActionBase):
name = 'Open Folder'
actual_plugin = 'calibre.gui2.actions.open:OpenFolderAction'
class ActionSendToDevice(InterfaceActionBase):
name = 'Send To Device'
actual_plugin = 'calibre.gui2.actions.device:SendToDeviceAction'
class ActionConnectShare(InterfaceActionBase):
name = 'Connect Share'
actual_plugin = 'calibre.gui2.actions.device:ConnectShareAction'
class ActionHelp(InterfaceActionBase):
name = 'Help'
actual_plugin = 'calibre.gui2.actions.help:HelpAction'
class ActionPreferences(InterfaceActionBase):
name = 'Preferences'
actual_plugin = 'calibre.gui2.actions.preferences:PreferencesAction'
class ActionSimilarBooks(InterfaceActionBase):
name = 'Similar Books'
actual_plugin = 'calibre.gui2.actions.similar_books:SimilarBooksAction'
class ActionChooseLibrary(InterfaceActionBase):
name = 'Choose Library'
actual_plugin = 'calibre.gui2.actions.choose_library:ChooseLibraryAction'
class ActionAddToLibrary(InterfaceActionBase):
name = 'Add To Library'
actual_plugin = 'calibre.gui2.actions.add_to_library:AddToLibraryAction'
class ActionEditCollections(InterfaceActionBase):
name = 'Edit Collections'
actual_plugin = 'calibre.gui2.actions.edit_collections:EditCollectionsAction'
plugins += [ActionAdd, ActionFetchAnnotations, ActionGenerateCatalog,
ActionConvert, ActionDelete, ActionEditMetadata, ActionView,
ActionFetchNews, ActionSaveToDisk, ActionShowBookDetails,
ActionRestart, ActionOpenFolder, ActionConnectShare,
ActionSendToDevice, ActionHelp, ActionPreferences, ActionSimilarBooks,
ActionAddToLibrary, ActionEditCollections, ActionChooseLibrary]

View File

@ -112,6 +112,10 @@ class InputFormatPlugin(Plugin):
#: convenience method, :meth:`get_image_collection`.
is_image_collection = False
#: Number of CPU cores used by this plugin
#: A value of -1 means that it uses all available cores
core_usage = 1
#: If set to True, the input plugin will perform special processing
#: to make its output suitable for viewing
for_viewer = False

View File

@ -426,7 +426,7 @@ class KoboReaderOutput(OutputProfile):
description = _('This profile is intended for the Kobo Reader.')
screen_size = (590, 775)
screen_size = (540, 718)
comic_screen_size = (540, 718)
dpi = 168.451
fbase = 12

View File

@ -6,7 +6,8 @@ import os, shutil, traceback, functools, sys, re
from contextlib import closing
from calibre.customize import Plugin, CatalogPlugin, FileTypePlugin, \
MetadataReaderPlugin, MetadataWriterPlugin
MetadataReaderPlugin, MetadataWriterPlugin, \
InterfaceActionBase as InterfaceAction
from calibre.customize.conversion import InputFormatPlugin, OutputFormatPlugin
from calibre.customize.profiles import InputProfile, OutputProfile
from calibre.customize.builtins import plugins as builtin_plugins
@ -19,7 +20,6 @@ from calibre.utils.config import make_config_dir, Config, ConfigProxy, \
plugin_dir, OptionParser, prefs
from calibre.ebooks.epub.fix import ePubFixer
platform = 'linux'
if iswindows:
platform = 'windows'
@ -246,6 +246,17 @@ def cover_sources():
# }}}
# Interface Actions # {{{
def interface_actions():
customization = config['plugin_customization']
for plugin in _initialized_plugins:
if isinstance(plugin, InterfaceAction):
if not is_disabled(plugin):
plugin.site_customization = customization.get(plugin.name, '')
yield plugin
# }}}
# Metadata read/write {{{
_metadata_readers = {}
_metadata_writers = {}

View File

@ -33,7 +33,9 @@ class ANDROID(USBMS):
# Samsung
0x04e8 : { 0x681d : [0x0222, 0x0400],
0x681c : [0x0222, 0x0224, 0x0400]},
0x681c : [0x0222, 0x0224, 0x0400],
0x6640 : [0x0100],
},
# Acer
0x502 : { 0x3203 : [0x0100]},
@ -44,7 +46,7 @@ class ANDROID(USBMS):
# Eken?
0x040d : { 0x0851 : [0x0001]},
}
EBOOK_DIR_MAIN = ['wordplayer/calibretransfer', 'eBooks/import', 'Books']
EBOOK_DIR_MAIN = ['eBooks/import', 'wordplayer/calibretransfer', 'Books']
EXTRA_CUSTOMIZATION_MESSAGE = _('Comma separated list of directories to '
'send e-books to on the device. The first one that exists will '
'be used')
@ -54,9 +56,9 @@ class ANDROID(USBMS):
'GT-I5700', 'SAMSUNG', 'DELL', 'LINUX']
WINDOWS_MAIN_MEM = ['ANDROID_PHONE', 'A855', 'A853', 'INC.NEXUS_ONE',
'__UMS_COMPOSITE', '_MB200', 'MASS_STORAGE', '_-_CARD',
'GT-I9000', 'FILE-STOR_GADGET', 'SGH-T959']
'GT-I9000', 'FILE-STOR_GADGET', 'SGH-T959', 'SAMSUNG_ANDROID']
WINDOWS_CARD_A_MEM = ['ANDROID_PHONE', 'GT-I9000_CARD',
'FILE-STOR_GADGET', 'SGH-T959']
'FILE-STOR_GADGET', 'SGH-T959', 'SAMSUNG_ANDROID']
OSX_MAIN_MEM = 'HTC Android Phone Media'

View File

@ -56,6 +56,8 @@ class WinPNPScanner(object):
def drive_order(self, pnp_id):
order = 0
match = re.search(r'REV_.*?&(\d+)#', pnp_id)
if match is None:
match = re.search(r'REV_.*?&(\d+)', pnp_id)
if match is not None:
order = int(match.group(1))
return order

View File

@ -20,20 +20,19 @@ class SNE(USBMS):
# Ordered list of supported formats
# Be sure these have an entry in calibre.devices.mime
FORMATS = ['epub', 'txt']
FORMATS = ['epub', 'pdf', 'txt']
VENDOR_ID = [0x04e8]
PRODUCT_ID = [0x2051]
PRODUCT_ID = [0x2051, 0x2053]
BCD = [0x0323]
VENDOR_NAME = ''
#WINDOWS_MAIN_MEM = 'MASS_STORAGE'
#WINDOWS_CARD_A_MEM = 'MASS_STORAGE'
VENDOR_NAME = 'SAMSUNG'
WINDOWS_MAIN_MEM = WINDOWS_CARD_A_MEM = 'SNE-60'
MAIN_MEMORY_VOLUME_LABEL = 'SNE Main Memory'
STORAGE_CARD_VOLUME_LABEL = 'SNE Storage Card'
EBOOK_DIR_MAIN = 'Book'
EBOOK_DIR_MAIN = 'Books'
SUPPORTS_SUB_DIRS = True

View File

@ -6,9 +6,9 @@ from calibre.devices.usbms.driver import USBMS
class TECLAST_K3(USBMS):
name = 'Teclast K3 Device Interface'
gui_name = 'K3'
description = _('Communicate with the Teclast K3 reader.')
name = 'Teclast K3/K5 Device Interface'
gui_name = 'K3/K5'
description = _('Communicate with the Teclast K3/K5 reader.')
author = 'Kovid Goyal'
supported_platforms = ['windows', 'osx', 'linux']
@ -17,11 +17,10 @@ class TECLAST_K3(USBMS):
VENDOR_ID = [0x071b]
PRODUCT_ID = [0x3203]
BCD = [0x0000]
BCD = [0x0000, 0x0100]
VENDOR_NAME = 'TECLAST'
WINDOWS_MAIN_MEM = 'DIGITAL_PLAYER'
WINDOWS_CARD_A_MEM = 'DIGITAL_PLAYER'
WINDOWS_MAIN_MEM = WINDOWS_CARD_A_MEM = ['DIGITAL_PLAYER', 'TL-K5']
MAIN_MEMORY_VOLUME_LABEL = 'K3 Main Memory'
STORAGE_CARD_VOLUME_LABEL = 'K3 Storage Card'

View File

@ -163,8 +163,12 @@ class PageProcessor(list):
wand.quantize(self.opts.colors)
dest = '%d_%d.%s'%(self.num, i, self.opts.output_format)
dest = os.path.join(self.dest, dest)
wand.save(dest+'8')
os.rename(dest+'8', dest)
if dest.lower().endswith('.png'):
dest += '8'
wand.save(dest)
if dest.endswith('8'):
dest = dest[:-1]
os.rename(dest+'8', dest)
self.append(dest)
def render_pages(tasks, dest, opts, notification=lambda x, y: x):
@ -247,6 +251,7 @@ class ComicInput(InputFormatPlugin):
description = 'Optimize comic files (.cbz, .cbr, .cbc) for viewing on portable devices'
file_types = set(['cbz', 'cbr', 'cbc'])
is_image_collection = True
core_usage = -1
options = set([
OptionRecommendation(name='colors', recommended_value=256,

View File

@ -185,7 +185,7 @@ class Serializer(object):
buffer.write('<guide>')
for ref in self.oeb.guide.values():
path = urldefrag(ref.href)[0]
if hrefs[path].media_type not in OEB_DOCS:
if path not in hrefs or hrefs[path].media_type not in OEB_DOCS:
continue
buffer.write('<reference type="')

View File

@ -244,14 +244,20 @@ def info_dialog(parent, title, msg, det_msg='', show=False):
class Dispatcher(QObject):
'''Convenience class to ensure that a function call always happens in the
thread the receiver was created in.'''
'''
Convenience class to use Qt signals with arbitrary python callables.
By default, ensures that a function call always happens in the
thread this Dispatcher was created in.
'''
dispatch_signal = pyqtSignal(object, object)
def __init__(self, func):
QObject.__init__(self)
def __init__(self, func, queued=True, parent=None):
QObject.__init__(self, parent)
self.func = func
self.dispatch_signal.connect(self.dispatch, type=Qt.QueuedConnection)
typ = Qt.QueuedConnection
if not queued:
typ = Qt.AutoConnection if queued is None else Qt.DirectConnection
self.dispatch_signal.connect(self.dispatch, type=typ)
def __call__(self, *args, **kwargs):
self.dispatch_signal.emit(args, kwargs)

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,266 @@
#!/usr/bin/env python
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
__license__ = 'GPL v3'
__copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
import os
from functools import partial
from PyQt4.Qt import QInputDialog, QPixmap, QMenu
from calibre.gui2 import error_dialog, choose_files, \
choose_dir, warning_dialog, info_dialog
from calibre.gui2.widgets import IMAGE_EXTENSIONS
from calibre.ebooks import BOOK_EXTENSIONS
from calibre.utils.filenames import ascii_filename
from calibre.constants import preferred_encoding, filesystem_encoding
from calibre.gui2.actions import InterfaceAction
class AddAction(InterfaceAction):
name = 'Add Books'
action_spec = (_('Add books'), 'add_book.svg', None, _('A'))
def genesis(self):
self._add_filesystem_book = self.Dispatcher(self.__add_filesystem_book)
self.add_menu = QMenu()
self.add_menu.addAction(_('Add books from a single directory'),
self.add_books)
self.add_menu.addAction(_('Add books from directories, including '
'sub-directories (One book per directory, assumes every ebook '
'file is the same book in a different format)'),
self.add_recursive_single)
self.add_menu.addAction(_('Add books from directories, including '
'sub directories (Multiple books per directory, assumes every '
'ebook file is a different book)'), self.add_recursive_multiple)
self.add_menu.addSeparator()
self.add_menu.addAction(_('Add Empty book. (Book entry with no '
'formats)'), self.add_empty)
self.add_menu.addAction(_('Add from ISBN'), self.add_from_isbn)
self.qaction.setMenu(self.add_menu)
self.qaction.triggered.connect(self.add_books)
def location_selected(self, loc):
enabled = loc == 'library'
for action in list(self.add_menu.actions())[1:]:
action.setEnabled(enabled)
def add_recursive(self, single):
root = choose_dir(self.gui, 'recursive book import root dir dialog',
'Select root folder')
if not root:
return
from calibre.gui2.add import Adder
self._adder = Adder(self.gui,
self.gui.library_view.model().db,
self.Dispatcher(self._files_added), spare_server=self.gui.spare_server)
self._adder.add_recursive(root, single)
def add_recursive_single(self, *args):
'''
Add books from the local filesystem to either the library or the device
recursively assuming one book per folder.
'''
self.add_recursive(True)
def add_recursive_multiple(self, *args):
'''
Add books from the local filesystem to either the library or the device
recursively assuming multiple books per folder.
'''
self.add_recursive(False)
def add_empty(self, *args):
'''
Add an empty book item to the library. This does not import any formats
from a book file.
'''
num, ok = QInputDialog.getInt(self.gui, _('How many empty books?'),
_('How many empty books should be added?'), 1, 1, 100)
if ok:
from calibre.ebooks.metadata import MetaInformation
for x in xrange(num):
self.gui.library_view.model().db.import_book(MetaInformation(None), [])
self.gui.library_view.model().books_added(num)
def add_isbns(self, isbns):
from calibre.ebooks.metadata import MetaInformation
ids = set([])
for x in isbns:
mi = MetaInformation(None)
mi.isbn = x
ids.add(self.gui.library_view.model().db.import_book(mi, []))
self.gui.library_view.model().books_added(len(isbns))
self.gui.iactions['Edit Metadata'].do_download_metadata(ids)
def files_dropped(self, paths):
to_device = self.gui.stack.currentIndex() != 0
self._add_books(paths, to_device)
def files_dropped_on_book(self, event, paths):
accept = False
if self.gui.current_view() is not self.gui.library_view:
return
db = self.gui.library_view.model().db
current_idx = self.gui.library_view.currentIndex()
if not current_idx.isValid(): return
cid = db.id(current_idx.row())
for path in paths:
ext = os.path.splitext(path)[1].lower()
if ext:
ext = ext[1:]
if ext in IMAGE_EXTENSIONS:
pmap = QPixmap()
pmap.load(path)
if not pmap.isNull():
accept = True
db.set_cover(cid, pmap)
elif ext in BOOK_EXTENSIONS:
db.add_format_with_hooks(cid, ext, path, index_is_id=True)
accept = True
if accept:
event.accept()
self.gui.library_view.model().current_changed(current_idx, current_idx)
def __add_filesystem_book(self, paths, allow_device=True):
if isinstance(paths, basestring):
paths = [paths]
books = [path for path in map(os.path.abspath, paths) if os.access(path,
os.R_OK)]
if books:
to_device = allow_device and self.gui.stack.currentIndex() != 0
self._add_books(books, to_device)
if to_device:
self.gui.status_bar.show_message(\
_('Uploading books to device.'), 2000)
def add_filesystem_book(self, paths, allow_device=True):
self._add_filesystem_book(paths, allow_device=allow_device)
def add_from_isbn(self, *args):
from calibre.gui2.dialogs.add_from_isbn import AddFromISBN
d = AddFromISBN(self.gui)
if d.exec_() == d.Accepted:
self.add_isbns(d.isbns)
def add_books(self, *args):
'''
Add books from the local filesystem to either the library or the device.
'''
filters = [
(_('Books'), BOOK_EXTENSIONS),
(_('EPUB Books'), ['epub']),
(_('LRF Books'), ['lrf']),
(_('HTML Books'), ['htm', 'html', 'xhtm', 'xhtml']),
(_('LIT Books'), ['lit']),
(_('MOBI Books'), ['mobi', 'prc', 'azw']),
(_('Topaz books'), ['tpz','azw1']),
(_('Text books'), ['txt', 'rtf']),
(_('PDF Books'), ['pdf']),
(_('Comics'), ['cbz', 'cbr', 'cbc']),
(_('Archives'), ['zip', 'rar']),
]
to_device = self.gui.stack.currentIndex() != 0
if to_device:
filters = [(_('Supported books'), self.gui.device_manager.device.FORMATS)]
books = choose_files(self.gui, 'add books dialog dir', 'Select books',
filters=filters)
if not books:
return
self._add_books(books, to_device)
def _add_books(self, paths, to_device, on_card=None):
if on_card is None:
on_card = 'carda' if self.gui.stack.currentIndex() == 2 else \
'cardb' if self.gui.stack.currentIndex() == 3 else None
if not paths:
return
from calibre.gui2.add import Adder
self.__adder_func = partial(self._files_added, on_card=on_card)
self._adder = Adder(self.gui,
None if to_device else self.gui.library_view.model().db,
self.Dispatcher(self.__adder_func), spare_server=self.gui.spare_server)
self._adder.add(paths)
def _files_added(self, paths=[], names=[], infos=[], on_card=None):
if paths:
self.gui.upload_books(paths,
list(map(ascii_filename, names)),
infos, on_card=on_card)
self.gui.status_bar.show_message(
_('Uploading books to device.'), 2000)
if getattr(self._adder, 'number_of_books_added', 0) > 0:
self.gui.library_view.model().books_added(self._adder.number_of_books_added)
if hasattr(self.gui, 'db_images'):
self.gui.db_images.reset()
if getattr(self._adder, 'merged_books', False):
books = u'\n'.join([x if isinstance(x, unicode) else
x.decode(preferred_encoding, 'replace') for x in
self._adder.merged_books])
info_dialog(self.gui, _('Merged some books'),
_('Some duplicates were found and merged into the '
'following existing books:'), det_msg=books, show=True)
if getattr(self._adder, 'critical', None):
det_msg = []
for name, log in self._adder.critical.items():
if isinstance(name, str):
name = name.decode(filesystem_encoding, 'replace')
det_msg.append(name+'\n'+log)
warning_dialog(self.gui, _('Failed to read metadata'),
_('Failed to read metadata from the following')+':',
det_msg='\n\n'.join(det_msg), show=True)
if hasattr(self._adder, 'cleanup'):
self._adder.cleanup()
self._adder = None
def _add_from_device_adder(self, paths=[], names=[], infos=[],
on_card=None, model=None):
self._files_added(paths, names, infos, on_card=on_card)
# set the in-library flags, and as a consequence send the library's
# metadata for this book to the device. This sets the uuid to the
# correct value.
self.gui.set_books_in_library(booklists=[model.db], reset=True)
model.reset()
def add_books_from_device(self, view):
rows = view.selectionModel().selectedRows()
if not rows or len(rows) == 0:
d = error_dialog(self.gui, _('Add to library'), _('No book selected'))
d.exec_()
return
paths = [p for p in view._model.paths(rows) if p is not None]
ve = self.gui.device_manager.device.VIRTUAL_BOOK_EXTENSIONS
def ext(x):
ans = os.path.splitext(x)[1]
ans = ans[1:] if len(ans) > 1 else ans
return ans.lower()
remove = set([p for p in paths if ext(p) in ve])
if remove:
paths = [p for p in paths if p not in remove]
info_dialog(self.gui, _('Not Implemented'),
_('The following books are virtual and cannot be added'
' to the calibre library:'), '\n'.join(remove),
show=True)
if not paths:
return
if not paths or len(paths) == 0:
d = error_dialog(self.gui, _('Add to library'), _('No book files found'))
d.exec_()
return
from calibre.gui2.add import Adder
self.__adder_func = partial(self._add_from_device_adder, on_card=None,
model=view._model)
self._adder = Adder(self.gui, self.gui.library_view.model().db,
self.Dispatcher(self.__adder_func), spare_server=self.gui.spare_server)
self._adder.add(paths)

View File

@ -0,0 +1,22 @@
#!/usr/bin/env python
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
__license__ = 'GPL v3'
__copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
from calibre.gui2.actions import InterfaceAction
class AddToLibraryAction(InterfaceAction):
name = 'Add To Library'
action_spec = (_('Add books to library'), 'add_book.svg', None, None)
def location_selected(self, loc):
enabled = loc != 'library'
self.qaction.setEnabled(enabled)
self.qaction.triggered.connect(self.add_books_to_library)
def add_books_to_library(self, *args):
self.gui.iactions['Add Books'].add_books_from_device(
self.gui.current_view())

View File

@ -0,0 +1,244 @@
#!/usr/bin/env python
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
__license__ = 'GPL v3'
__copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
import os, datetime
from PyQt4.Qt import pyqtSignal, QModelIndex, QThread, Qt
from calibre.gui2 import error_dialog, gprefs
from calibre.ebooks.BeautifulSoup import BeautifulSoup, Tag, NavigableString
from calibre import strftime
from calibre.gui2.actions import InterfaceAction
class FetchAnnotationsAction(InterfaceAction):
name = 'Fetch Annotations'
action_spec = (_('Fetch annotations (experimental)'), None, None, None)
def genesis(self):
pass
def fetch_annotations(self, *args):
# Generate a path_map from selected ids
def get_ids_from_selected_rows():
rows = self.gui.library_view.selectionModel().selectedRows()
if not rows or len(rows) < 2:
rows = xrange(self.gui.library_view.model().rowCount(QModelIndex()))
ids = map(self.gui.library_view.model().id, rows)
return ids
def get_formats(id):
formats = db.formats(id, index_is_id=True)
fmts = []
if formats:
for format in formats.split(','):
fmts.append(format.lower())
return fmts
def generate_annotation_paths(ids, db, device):
# Generate path templates
# Individual storage mount points scanned/resolved in driver.get_annotations()
path_map = {}
for id in ids:
mi = db.get_metadata(id, index_is_id=True)
a_path = device.create_upload_path(os.path.abspath('/<storage>'), mi, 'x.bookmark', create_dirs=False)
path_map[id] = dict(path=a_path, fmts=get_formats(id))
return path_map
device = self.gui.device_manager.device
if self.gui.current_view() is not self.gui.library_view:
return error_dialog(self.gui, _('Use library only'),
_('User annotations generated from main library only'),
show=True)
db = self.gui.library_view.model().db
# Get the list of ids
ids = get_ids_from_selected_rows()
if not ids:
return error_dialog(self.gui, _('No books selected'),
_('No books selected to fetch annotations from'),
show=True)
# Map ids to paths
path_map = generate_annotation_paths(ids, db, device)
# Dispatch to devices.kindle.driver.get_annotations()
self.gui.device_manager.annotations(self.Dispatcher(self.annotations_fetched),
path_map)
def annotations_fetched(self, job):
from calibre.devices.usbms.device import Device
from calibre.ebooks.metadata import MetaInformation
from calibre.gui2.dialogs.progress import ProgressDialog
from calibre.library.cli import do_add_format
class Updater(QThread): # {{{
update_progress = pyqtSignal(int)
update_done = pyqtSignal()
FINISHED_READING_PCT_THRESHOLD = 96
def __init__(self, parent, db, annotation_map, done_callback):
QThread.__init__(self, parent)
self.db = db
self.pd = ProgressDialog(_('Merging user annotations into database'), '',
0, len(job.result), parent=parent)
self.am = annotation_map
self.done_callback = done_callback
self.pd.canceled_signal.connect(self.canceled)
self.pd.setModal(True)
self.pd.show()
self.update_progress.connect(self.pd.set_value,
type=Qt.QueuedConnection)
self.update_done.connect(self.pd.hide, type=Qt.QueuedConnection)
def generate_annotation_html(self, bookmark):
# Returns <div class="user_annotations"> ... </div>
last_read_location = bookmark.last_read_location
timestamp = datetime.datetime.utcfromtimestamp(bookmark.timestamp)
percent_read = bookmark.percent_read
ka_soup = BeautifulSoup()
dtc = 0
divTag = Tag(ka_soup,'div')
divTag['class'] = 'user_annotations'
# Add the last-read location
spanTag = Tag(ka_soup, 'span')
spanTag['style'] = 'font-weight:bold'
if bookmark.book_format == 'pdf':
spanTag.insert(0,NavigableString(
_("%s<br />Last Page Read: %d (%d%%)") % \
(strftime(u'%x', timestamp.timetuple()),
last_read_location,
percent_read)))
else:
spanTag.insert(0,NavigableString(
_("%s<br />Last Page Read: Location %d (%d%%)") % \
(strftime(u'%x', timestamp.timetuple()),
last_read_location,
percent_read)))
divTag.insert(dtc, spanTag)
dtc += 1
divTag.insert(dtc, Tag(ka_soup,'br'))
dtc += 1
if bookmark.user_notes:
user_notes = bookmark.user_notes
annotations = []
# Add the annotations sorted by location
# Italicize highlighted text
for location in sorted(user_notes):
if user_notes[location]['text']:
annotations.append(
_('<b>Location %d &bull; %s</b><br />%s<br />') % \
(user_notes[location]['displayed_location'],
user_notes[location]['type'],
user_notes[location]['text'] if \
user_notes[location]['type'] == 'Note' else \
'<i>%s</i>' % user_notes[location]['text']))
else:
if bookmark.book_format == 'pdf':
annotations.append(
_('<b>Page %d &bull; %s</b><br />') % \
(user_notes[location]['displayed_location'],
user_notes[location]['type']))
else:
annotations.append(
_('<b>Location %d &bull; %s</b><br />') % \
(user_notes[location]['displayed_location'],
user_notes[location]['type']))
for annotation in annotations:
divTag.insert(dtc, annotation)
dtc += 1
ka_soup.insert(0,divTag)
return ka_soup
def mark_book_as_read(self,id):
read_tag = gprefs.get('catalog_epub_mobi_read_tag')
if read_tag:
self.db.set_tags(id, [read_tag], append=True)
def canceled(self):
self.pd.hide()
def run(self):
ignore_tags = set(['Catalog','Clippings'])
for (i, id) in enumerate(self.am):
bm = Device.UserAnnotation(self.am[id][0],self.am[id][1])
if bm.type == 'kindle_bookmark':
mi = self.db.get_metadata(id, index_is_id=True)
user_notes_soup = self.generate_annotation_html(bm.value)
if mi.comments:
a_offset = mi.comments.find('<div class="user_annotations">')
ad_offset = mi.comments.find('<hr class="annotations_divider" />')
if a_offset >= 0:
mi.comments = mi.comments[:a_offset]
if ad_offset >= 0:
mi.comments = mi.comments[:ad_offset]
if set(mi.tags).intersection(ignore_tags):
continue
if mi.comments:
hrTag = Tag(user_notes_soup,'hr')
hrTag['class'] = 'annotations_divider'
user_notes_soup.insert(0,hrTag)
mi.comments += user_notes_soup.prettify()
else:
mi.comments = unicode(user_notes_soup.prettify())
# Update library comments
self.db.set_comment(id, mi.comments)
# Update 'read' tag except for Catalogs/Clippings
if bm.value.percent_read >= self.FINISHED_READING_PCT_THRESHOLD:
if not set(mi.tags).intersection(ignore_tags):
self.mark_book_as_read(id)
# Add bookmark file to id
self.db.add_format_with_hooks(id, bm.value.bookmark_extension,
bm.value.path, index_is_id=True)
self.update_progress.emit(i)
elif bm.type == 'kindle_clippings':
# Find 'My Clippings' author=Kindle in database, or add
last_update = 'Last modified %s' % strftime(u'%x %X',bm.value['timestamp'].timetuple())
mc_id = list(db.data.parse('title:"My Clippings"'))
if mc_id:
do_add_format(self.db, mc_id[0], 'TXT', bm.value['path'])
mi = self.db.get_metadata(mc_id[0], index_is_id=True)
mi.comments = last_update
self.db.set_metadata(mc_id[0], mi)
else:
mi = MetaInformation('My Clippings', authors = ['Kindle'])
mi.tags = ['Clippings']
mi.comments = last_update
self.db.add_books([bm.value['path']], ['txt'], [mi])
self.update_done.emit()
self.done_callback(self.am.keys())
# }}}
if not job.result: return
if self.gui.current_view() is not self.gui.library_view:
return error_dialog(self.gui, _('Use library only'),
_('User annotations generated from main library only'),
show=True)
db = self.gui.library_view.model().db
self.__annotation_updater = Updater(self.gui, db, job.result,
self.Dispatcher(self.gui.library_view.model().refresh_ids))
self.__annotation_updater.start()

View File

@ -0,0 +1,73 @@
#!/usr/bin/env python
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
__license__ = 'GPL v3'
__copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
import os, shutil
from PyQt4.Qt import QModelIndex
from calibre.gui2 import error_dialog, choose_dir
from calibre.gui2.tools import generate_catalog
from calibre.utils.config import dynamic
from calibre.gui2.actions import InterfaceAction
class GenerateCatalogAction(InterfaceAction):
name = 'Generate Catalog'
action_spec = (_('Create catalog of books in your calibre library'), None, None, None)
def generate_catalog(self):
rows = self.gui.library_view.selectionModel().selectedRows()
if not rows or len(rows) < 2:
rows = xrange(self.gui.library_view.model().rowCount(QModelIndex()))
ids = map(self.gui.library_view.model().id, rows)
dbspec = None
if not ids:
return error_dialog(self.gui, _('No books selected'),
_('No books selected to generate catalog for'),
show=True)
# Calling gui2.tools:generate_catalog()
ret = generate_catalog(self.gui, dbspec, ids, self.gui.device_manager.device)
if ret is None:
return
func, args, desc, out, sync, title = ret
fmt = os.path.splitext(out)[1][1:].upper()
job = self.gui.job_manager.run_job(
self.Dispatcher(self.catalog_generated), func, args=args,
description=desc)
job.catalog_file_path = out
job.fmt = fmt
job.catalog_sync, job.catalog_title = sync, title
self.gui.status_bar.show_message(_('Generating %s catalog...')%fmt)
def catalog_generated(self, job):
if job.result:
# Search terms nulled catalog results
return error_dialog(self.gui, _('No books found'),
_("No books to catalog\nCheck exclude tags"),
show=True)
if job.failed:
return self.gui.job_exception(job)
id = self.gui.library_view.model().add_catalog(job.catalog_file_path, job.catalog_title)
self.gui.library_view.model().reset()
if job.catalog_sync:
sync = dynamic.get('catalogs_to_be_synced', set([]))
sync.add(id)
dynamic.set('catalogs_to_be_synced', sync)
self.gui.status_bar.show_message(_('Catalog generated.'), 3000)
self.gui.sync_catalogs()
if job.fmt not in ['EPUB','MOBI']:
export_dir = choose_dir(self.gui, _('Export Catalog Directory'),
_('Select destination for %s.%s') % (job.catalog_title, job.fmt.lower()))
if export_dir:
destination = os.path.join(export_dir, '%s.%s' % (job.catalog_title, job.fmt.lower()))
shutil.copyfile(job.catalog_file_path, destination)

View File

@ -0,0 +1,172 @@
#!/usr/bin/env python
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
__license__ = 'GPL v3'
__copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
import os
from functools import partial
from PyQt4.Qt import QMenu
from calibre import isbytestring
from calibre.constants import filesystem_encoding
from calibre.utils.config import prefs
from calibre.gui2 import gprefs, warning_dialog
from calibre.gui2.actions import InterfaceAction
class LibraryUsageStats(object):
def __init__(self):
self.stats = {}
self.read_stats()
def read_stats(self):
stats = gprefs.get('library_usage_stats', {})
self.stats = stats
def write_stats(self):
locs = list(self.stats.keys())
locs.sort(cmp=lambda x, y: cmp(self.stats[x], self.stats[y]),
reverse=True)
for key in locs[15:]:
self.stats.pop(key)
gprefs.set('library_usage_stats', self.stats)
def remove(self, location):
self.stats.pop(location, None)
self.write_stats()
def canonicalize_path(self, lpath):
if isbytestring(lpath):
lpath = lpath.decode(filesystem_encoding)
lpath = lpath.replace(os.sep, '/')
return lpath
def library_used(self, db):
lpath = self.canonicalize_path(db.library_path)
if lpath not in self.stats:
self.stats[lpath] = 0
self.stats[lpath] += 1
self.write_stats()
def locations(self, db):
lpath = self.canonicalize_path(db.library_path)
locs = list(self.stats.keys())
if lpath in locs:
locs.remove(lpath)
locs.sort(cmp=lambda x, y: cmp(self.stats[x], self.stats[y]),
reverse=True)
for loc in locs:
yield self.pretty(loc), loc
def pretty(self, loc):
if loc.endswith('/'):
loc = loc[:-1]
return loc.split('/')[-1]
class ChooseLibraryAction(InterfaceAction):
name = 'Choose Library'
action_spec = (_('%d books'), 'lt.png',
_('Choose calibre library to work with'), None)
def genesis(self):
self.count_changed(0)
self.qaction.triggered.connect(self.choose_library)
self.stats = LibraryUsageStats()
self.create_action(spec=(_('Switch to library...'), 'lt.png', None,
None), attr='action_choose')
self.action_choose.triggered.connect(self.choose_library)
self.choose_menu = QMenu(self.gui)
self.choose_menu.addAction(self.action_choose)
self.qaction.setMenu(self.choose_menu)
self.quick_menu = QMenu(_('Quick switch'))
self.quick_menu_action = self.choose_menu.addMenu(self.quick_menu)
self.qs_separator = self.choose_menu.addSeparator()
self.switch_actions = []
for i in range(5):
ac = self.create_action(spec=('', None, None, None),
attr='switch_action%d'%i)
self.switch_actions.append(ac)
ac.setVisible(False)
ac.triggered.connect(partial(self.qs_requested, i))
self.choose_menu.addAction(ac)
def library_name(self):
db = self.gui.library_view.model().db
path = db.library_path
if isbytestring(path):
path = path.decode(filesystem_encoding)
path = path.replace(os.sep, '/')
return self.stats.pretty(path)
def library_changed(self, db):
self.stats.library_used(db)
self.build_menus()
def initialization_complete(self):
self.library_changed(self.gui.library_view.model().db)
def build_menus(self):
db = self.gui.library_view.model().db
locations = list(self.stats.locations(db))
for ac in self.switch_actions:
ac.setVisible(False)
self.quick_menu.clear()
self.qs_locations = [i[1] for i in locations]
for name, loc in locations:
self.quick_menu.addAction(name, partial(self.switch_requested,
loc))
for i, x in enumerate(locations[:len(self.switch_actions)]):
name, loc = x
ac = self.switch_actions[i]
ac.setText(name)
ac.setVisible(True)
self.quick_menu_action.setVisible(bool(locations))
def location_selected(self, loc):
enabled = loc == 'library'
self.qaction.setEnabled(enabled)
def switch_requested(self, location):
loc = location.replace('/', os.sep)
exists = self.gui.library_view.model().db.exists_at(loc)
if not exists:
warning_dialog(self.gui, _('No library found'),
_('No existing calibre library was found at %s.'
' It will be removed from the list of known'
' libraries.')%loc, show=True)
self.stats.remove(location)
self.build_menus()
return
prefs['library_path'] = loc
self.gui.library_moved(loc)
def qs_requested(self, idx, *args):
self.switch_requested(self.qs_locations[idx])
def count_changed(self, new_count):
text = self.action_spec[0]%new_count
a = self.qaction
a.setText(text)
tooltip = self.action_spec[2] + '\n\n' + text
a.setToolTip(tooltip)
a.setStatusTip(tooltip)
a.setWhatsThis(tooltip)
def choose_library(self, *args):
from calibre.gui2.dialogs.choose_library import ChooseLibrary
db = self.gui.library_view.model().db
c = ChooseLibrary(db, self.gui.library_moved, self.gui)
c.exec_()

View File

@ -0,0 +1,183 @@
#!/usr/bin/env python
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
__license__ = 'GPL v3'
__copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
import os
from functools import partial
from PyQt4.Qt import QModelIndex, QMenu
from calibre.gui2 import error_dialog, Dispatcher
from calibre.gui2.tools import convert_single_ebook, convert_bulk_ebook
from calibre.utils.config import prefs
from calibre.gui2.actions import InterfaceAction
from calibre.customize.ui import plugin_for_input_format
class ConvertAction(InterfaceAction):
name = 'Convert Books'
action_spec = (_('Convert books'), 'convert.svg', None, _('C'))
def genesis(self):
cm = QMenu()
cm.addAction(_('Convert individually'), partial(self.convert_ebook,
False, bulk=False))
cm.addAction(_('Bulk convert'),
partial(self.convert_ebook, False, bulk=True))
cm.addSeparator()
ac = cm.addAction(
_('Create catalog of books in your calibre library'))
ac.triggered.connect(self.gui.iactions['Generate Catalog'].generate_catalog)
self.qaction.setMenu(cm)
self.qaction.triggered.connect(self.convert_ebook)
self.convert_menu = cm
self.conversion_jobs = {}
def location_selected(self, loc):
enabled = loc == 'library'
self.qaction.setEnabled(enabled)
def auto_convert(self, book_ids, on_card, format):
previous = self.gui.library_view.currentIndex()
rows = [x.row() for x in \
self.gui.library_view.selectionModel().selectedRows()]
jobs, changed, bad = convert_single_ebook(self.gui, self.gui.library_view.model().db, book_ids, True, format)
if jobs == []: return
self.queue_convert_jobs(jobs, changed, bad, rows, previous,
self.book_auto_converted, extra_job_args=[on_card])
def auto_convert_mail(self, to, fmts, delete_from_library, book_ids, format):
previous = self.gui.library_view.currentIndex()
rows = [x.row() for x in \
self.gui.library_view.selectionModel().selectedRows()]
jobs, changed, bad = convert_single_ebook(self.gui, self.gui.library_view.model().db, book_ids, True, format)
if jobs == []: return
self.queue_convert_jobs(jobs, changed, bad, rows, previous,
self.book_auto_converted_mail,
extra_job_args=[delete_from_library, to, fmts])
def auto_convert_news(self, book_ids, format):
previous = self.gui.library_view.currentIndex()
rows = [x.row() for x in \
self.gui.library_view.selectionModel().selectedRows()]
jobs, changed, bad = convert_single_ebook(self.gui, self.gui.library_view.model().db, book_ids, True, format)
if jobs == []: return
self.queue_convert_jobs(jobs, changed, bad, rows, previous,
self.book_auto_converted_news)
def auto_convert_catalogs(self, book_ids, format):
previous = self.gui.library_view.currentIndex()
rows = [x.row() for x in \
self.gui.library_view.selectionModel().selectedRows()]
jobs, changed, bad = convert_single_ebook(self.gui, self.gui.library_view.model().db, book_ids, True, format)
if jobs == []: return
self.queue_convert_jobs(jobs, changed, bad, rows, previous,
self.book_auto_converted_catalogs)
def get_books_for_conversion(self):
rows = [r.row() for r in \
self.gui.library_view.selectionModel().selectedRows()]
if not rows or len(rows) == 0:
d = error_dialog(self.gui, _('Cannot convert'),
_('No books selected'))
d.exec_()
return None
return [self.gui.library_view.model().db.id(r) for r in rows]
def convert_ebook(self, checked, bulk=None):
book_ids = self.get_books_for_conversion()
if book_ids is None: return
previous = self.gui.library_view.currentIndex()
rows = [x.row() for x in \
self.gui.library_view.selectionModel().selectedRows()]
num = 0
if bulk or (bulk is None and len(book_ids) > 1):
self.__bulk_queue = convert_bulk_ebook(self.gui, self.queue_convert_jobs,
self.gui.library_view.model().db, book_ids,
out_format=prefs['output_format'], args=(rows, previous,
self.book_converted))
if self.__bulk_queue is None:
return
num = len(self.__bulk_queue.book_ids)
else:
jobs, changed, bad = convert_single_ebook(self.gui,
self.gui.library_view.model().db, book_ids, out_format=prefs['output_format'])
self.queue_convert_jobs(jobs, changed, bad, rows, previous,
self.book_converted)
num = len(jobs)
if num > 0:
self.gui.status_bar.show_message(_('Starting conversion of %d book(s)') %
num, 2000)
def queue_convert_jobs(self, jobs, changed, bad, rows, previous,
converted_func, extra_job_args=[]):
for func, args, desc, fmt, id, temp_files in jobs:
input_file = args[0]
input_fmt = os.path.splitext(input_file)[1]
core_usage = 1
if input_fmt:
input_fmt = input_fmt[1:]
plugin = plugin_for_input_format(input_fmt)
if plugin is not None:
core_usage = plugin.core_usage
if id not in bad:
job = self.gui.job_manager.run_job(Dispatcher(converted_func),
func, args=args, description=desc,
core_usage=core_usage)
args = [temp_files, fmt, id]+extra_job_args
self.conversion_jobs[job] = tuple(args)
if changed:
self.gui.library_view.model().refresh_rows(rows)
current = self.gui.library_view.currentIndex()
self.gui.library_view.model().current_changed(current, previous)
def book_auto_converted(self, job):
temp_files, fmt, book_id, on_card = self.conversion_jobs[job]
self.book_converted(job)
self.gui.sync_to_device(on_card, False, specific_format=fmt, send_ids=[book_id], do_auto_convert=False)
def book_auto_converted_mail(self, job):
temp_files, fmt, book_id, delete_from_library, to, fmts = self.conversion_jobs[job]
self.book_converted(job)
self.gui.send_by_mail(to, fmts, delete_from_library, specific_format=fmt, send_ids=[book_id], do_auto_convert=False)
def book_auto_converted_news(self, job):
temp_files, fmt, book_id = self.conversion_jobs[job]
self.book_converted(job)
self.gui.sync_news(send_ids=[book_id], do_auto_convert=False)
def book_auto_converted_catalogs(self, job):
temp_files, fmt, book_id = self.conversion_jobs[job]
self.book_converted(job)
self.gui.sync_catalogs(send_ids=[book_id], do_auto_convert=False)
def book_converted(self, job):
temp_files, fmt, book_id = self.conversion_jobs.pop(job)[:3]
try:
if job.failed:
self.gui.job_exception(job)
return
data = open(temp_files[-1].name, 'rb')
self.gui.library_view.model().db.add_format(book_id, \
fmt, data, index_is_id=True)
data.close()
self.gui.status_bar.show_message(job.description + \
(' completed'), 2000)
finally:
for f in temp_files:
try:
if os.path.exists(f.name):
os.remove(f.name)
except:
pass
self.gui.tags_view.recount()
if self.gui.current_view() is self.gui.library_view:
current = self.gui.library_view.currentIndex()
self.gui.library_view.model().current_changed(current, QModelIndex())

View File

@ -0,0 +1,195 @@
#!/usr/bin/env python
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
__license__ = 'GPL v3'
__copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
from PyQt4.Qt import QMenu
from calibre.gui2 import error_dialog
from calibre.gui2.dialogs.delete_matching_from_device import DeleteMatchingFromDeviceDialog
from calibre.gui2.dialogs.confirm_delete import confirm
from calibre.gui2.actions import InterfaceAction
class DeleteAction(InterfaceAction):
name = 'Remove Books'
action_spec = (_('Remove books'), 'trash.svg', None, _('Del'))
def genesis(self):
self.qaction.triggered.connect(self.delete_books)
self.delete_menu = QMenu()
self.delete_menu.addAction(_('Remove selected books'), self.delete_books)
self.delete_menu.addAction(
_('Remove files of a specific format from selected books..'),
self.delete_selected_formats)
self.delete_menu.addAction(
_('Remove all formats from selected books, except...'),
self.delete_all_but_selected_formats)
self.delete_menu.addAction(
_('Remove covers from selected books'), self.delete_covers)
self.delete_menu.addSeparator()
self.delete_menu.addAction(
_('Remove matching books from device'),
self.remove_matching_books_from_device)
self.qaction.setMenu(self.delete_menu)
self.delete_memory = {}
def location_selected(self, loc):
enabled = loc == 'library'
for action in list(self.delete_menu.actions())[1:]:
action.setEnabled(enabled)
def _get_selected_formats(self, msg):
from calibre.gui2.dialogs.select_formats import SelectFormats
fmts = self.gui.library_view.model().db.all_formats()
d = SelectFormats([x.lower() for x in fmts], msg, parent=self.gui)
if d.exec_() != d.Accepted:
return None
return d.selected_formats
def _get_selected_ids(self, err_title=_('Cannot delete')):
rows = self.gui.library_view.selectionModel().selectedRows()
if not rows or len(rows) == 0:
d = error_dialog(self.gui, err_title, _('No book selected'))
d.exec_()
return set([])
return set(map(self.gui.library_view.model().id, rows))
def delete_selected_formats(self, *args):
ids = self._get_selected_ids()
if not ids:
return
fmts = self._get_selected_formats(
_('Choose formats to be deleted'))
if not fmts:
return
for id in ids:
for fmt in fmts:
self.gui.library_view.model().db.remove_format(id, fmt,
index_is_id=True, notify=False)
self.gui.library_view.model().refresh_ids(ids)
self.gui.library_view.model().current_changed(self.gui.library_view.currentIndex(),
self.gui.library_view.currentIndex())
if ids:
self.gui.tags_view.recount()
def delete_all_but_selected_formats(self, *args):
ids = self._get_selected_ids()
if not ids:
return
fmts = self._get_selected_formats(
'<p>'+_('Choose formats <b>not</b> to be deleted'))
if fmts is None:
return
for id in ids:
bfmts = self.gui.library_view.model().db.formats(id, index_is_id=True)
if bfmts is None:
continue
bfmts = set([x.lower() for x in bfmts.split(',')])
rfmts = bfmts - set(fmts)
for fmt in rfmts:
self.gui.library_view.model().db.remove_format(id, fmt,
index_is_id=True, notify=False)
self.gui.library_view.model().refresh_ids(ids)
self.gui.library_view.model().current_changed(self.gui.library_view.currentIndex(),
self.gui.library_view.currentIndex())
if ids:
self.gui.tags_view.recount()
def remove_matching_books_from_device(self, *args):
if not self.gui.device_manager.is_device_connected:
d = error_dialog(self.gui, _('Cannot delete books'),
_('No device is connected'))
d.exec_()
return
ids = self._get_selected_ids()
if not ids:
#_get_selected_ids shows a dialog box if nothing is selected, so we
#do not need to show one here
return
to_delete = {}
some_to_delete = False
for model,name in ((self.gui.memory_view.model(), _('Main memory')),
(self.gui.card_a_view.model(), _('Storage Card A')),
(self.gui.card_b_view.model(), _('Storage Card B'))):
to_delete[name] = (model, model.paths_for_db_ids(ids))
if len(to_delete[name][1]) > 0:
some_to_delete = True
if not some_to_delete:
d = error_dialog(self.gui, _('No books to delete'),
_('None of the selected books are on the device'))
d.exec_()
return
d = DeleteMatchingFromDeviceDialog(self.gui, to_delete)
if d.exec_():
paths = {}
ids = {}
for (model, id, path) in d.result:
if model not in paths:
paths[model] = []
ids[model] = []
paths[model].append(path)
ids[model].append(id)
for model in paths:
job = self.gui.remove_paths(paths[model])
self.delete_memory[job] = (paths[model], model)
model.mark_for_deletion(job, ids[model], rows_are_ids=True)
self.gui.status_bar.show_message(_('Deleting books from device.'), 1000)
def delete_covers(self, *args):
ids = self._get_selected_ids()
if not ids:
return
for id in ids:
self.gui.library_view.model().db.remove_cover(id)
self.gui.library_view.model().refresh_ids(ids)
self.gui.library_view.model().current_changed(self.gui.library_view.currentIndex(),
self.gui.library_view.currentIndex())
def delete_books(self, *args):
'''
Delete selected books from device or library.
'''
view = self.gui.current_view()
rows = view.selectionModel().selectedRows()
if not rows or len(rows) == 0:
return
if self.gui.stack.currentIndex() == 0:
if not confirm('<p>'+_('The selected books will be '
'<b>permanently deleted</b> and the files '
'removed from your computer. Are you sure?')
+'</p>', 'library_delete_books', self.gui):
return
ci = view.currentIndex()
row = None
if ci.isValid():
row = ci.row()
ids_deleted = view.model().delete_books(rows)
for v in (self.gui.memory_view, self.gui.card_a_view, self.gui.card_b_view):
if v is None:
continue
v.model().clear_ondevice(ids_deleted)
if row is not None:
ci = view.model().index(row, 0)
if ci.isValid():
view.set_current_row(row)
else:
if not confirm('<p>'+_('The selected books will be '
'<b>permanently deleted</b> '
'from your device. Are you sure?')
+'</p>', 'device_delete_books', self.gui):
return
if self.gui.stack.currentIndex() == 1:
view = self.gui.memory_view
elif self.gui.stack.currentIndex() == 2:
view = self.gui.card_a_view
else:
view = self.gui.card_b_view
paths = view.model().paths(rows)
job = self.gui.remove_paths(paths)
self.delete_memory[job] = (paths, view.model())
view.model().mark_for_deletion(job, rows)
self.gui.status_bar.show_message(_('Deleting books from device.'), 1000)

View File

@ -0,0 +1,146 @@
#!/usr/bin/env python
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
__license__ = 'GPL v3'
__copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
from functools import partial
from PyQt4.Qt import QToolButton, QMenu, pyqtSignal, QIcon
from calibre.gui2.actions import InterfaceAction
from calibre.utils.smtp import config as email_config
from calibre.constants import iswindows, isosx
class ShareConnMenu(QMenu): # {{{
connect_to_folder = pyqtSignal()
connect_to_itunes = pyqtSignal()
config_email = pyqtSignal()
toggle_server = pyqtSignal()
def __init__(self, parent=None):
QMenu.__init__(self, parent)
mitem = self.addAction(QIcon(I('devices/folder.svg')), _('Connect to folder'))
mitem.setEnabled(True)
mitem.triggered.connect(lambda x : self.connect_to_folder.emit())
self.connect_to_folder_action = mitem
mitem = self.addAction(QIcon(I('devices/itunes.png')),
_('Connect to iTunes'))
mitem.setEnabled(True)
mitem.triggered.connect(lambda x : self.connect_to_itunes.emit())
self.connect_to_itunes_action = mitem
if not (iswindows or isosx):
mitem.setVisible(False)
self.addSeparator()
self.toggle_server_action = \
self.addAction(QIcon(I('network-server.svg')),
_('Start Content Server'))
self.toggle_server_action.triggered.connect(lambda x:
self.toggle_server.emit())
self.addSeparator()
self.email_actions = []
def server_state_changed(self, running):
text = _('Start Content Server')
if running:
text = _('Stop Content Server')
self.toggle_server_action.setText(text)
def build_email_entries(self, sync_menu):
from calibre.gui2.device import DeviceAction
for ac in self.email_actions:
self.removeAction(ac)
self.email_actions = []
self.memory = []
opts = email_config().parse()
if opts.accounts:
self.email_to_menu = QMenu(_('Email to')+'...', self)
keys = sorted(opts.accounts.keys())
for account in keys:
formats, auto, default = opts.accounts[account]
dest = 'mail:'+account+';'+formats
action1 = DeviceAction(dest, False, False, I('mail.svg'),
_('Email to')+' '+account)
action2 = DeviceAction(dest, True, False, I('mail.svg'),
_('Email to')+' '+account+ _(' and delete from library'))
map(self.email_to_menu.addAction, (action1, action2))
map(self.memory.append, (action1, action2))
if default:
map(self.addAction, (action1, action2))
map(self.email_actions.append, (action1, action2))
self.email_to_menu.addSeparator()
action1.a_s.connect(sync_menu.action_triggered)
action2.a_s.connect(sync_menu.action_triggered)
ac = self.addMenu(self.email_to_menu)
self.email_actions.append(ac)
else:
ac = self.addAction(_('Setup email based sharing of books'))
self.email_actions.append(ac)
ac.triggered.connect(self.setup_email)
def setup_email(self, *args):
self.config_email.emit()
def set_state(self, device_connected):
self.connect_to_folder_action.setEnabled(not device_connected)
self.connect_to_itunes_action.setEnabled(not device_connected)
# }}}
class SendToDeviceAction(InterfaceAction):
name = 'Send To Device'
action_spec = (_('Send to device'), 'sync.svg', None, _('D'))
def genesis(self):
self.qaction.triggered.connect(self.do_sync)
self.gui.create_device_menu()
def location_selected(self, loc):
enabled = loc == 'library'
self.qaction.setEnabled(enabled)
def do_sync(self, *args):
self.gui._sync_action_triggered()
class ConnectShareAction(InterfaceAction):
name = 'Connect Share'
action_spec = (_('Connect/share'), 'connect_share.svg', None, None)
popup_type = QToolButton.InstantPopup
def genesis(self):
self.share_conn_menu = ShareConnMenu(self.gui)
self.share_conn_menu.toggle_server.connect(self.toggle_content_server)
self.share_conn_menu.config_email.connect(partial(
self.gui.iactions['Preferences'].do_config,
initial_category='email'))
self.qaction.setMenu(self.share_conn_menu)
self.share_conn_menu.connect_to_folder.connect(self.gui.connect_to_folder)
self.share_conn_menu.connect_to_itunes.connect(self.gui.connect_to_itunes)
def location_selected(self, loc):
enabled = loc == 'library'
self.qaction.setEnabled(enabled)
def set_state(self, device_connected):
self.share_conn_menu.set_state(device_connected)
def build_email_entries(self):
m = self.gui.iactions['Send To Device'].qaction.menu()
self.share_conn_menu.build_email_entries(m)
def content_server_state_changed(self, running):
self.share_conn_menu.server_state_changed(running)
def toggle_content_server(self):
if self.gui.content_server is None:
self.gui.start_content_server()
else:
self.gui.content_server.exit()
self.gui.content_server = None

View File

@ -0,0 +1,29 @@
#!/usr/bin/env python
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
__license__ = 'GPL v3'
__copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
from calibre.gui2.actions import InterfaceAction
class EditCollectionsAction(InterfaceAction):
name = 'Edit Collections'
action_spec = (_('Manage collections'), None, None, None)
def location_selected(self, loc):
enabled = loc != 'library'
self.qaction.setEnabled(enabled)
self.qaction.triggered.connect(self.edit_collections)
def edit_collections(self, *args):
oncard = None
cv = self.gui.current_view()
if cv is self.gui.card_a_view:
oncard = 'carda'
if cv is self.gui.card_b_view:
oncard = 'cardb'
self.gui.iactions['Edit Metadata'].edit_device_collections(cv,
oncard=oncard)

View File

@ -0,0 +1,359 @@
#!/usr/bin/env python
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
__license__ = 'GPL v3'
__copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
import os
from functools import partial
from PyQt4.Qt import Qt, QTimer, QMenu
from calibre.gui2 import error_dialog, config, warning_dialog
from calibre.gui2.dialogs.metadata_single import MetadataSingleDialog
from calibre.gui2.dialogs.metadata_bulk import MetadataBulkDialog
from calibre.gui2.dialogs.confirm_delete import confirm
from calibre.gui2.dialogs.tag_list_editor import TagListEditor
from calibre.gui2.actions import InterfaceAction
class EditMetadataAction(InterfaceAction):
name = 'Edit Metadata'
action_spec = (_('Edit metadata'), 'edit_input.svg', None, _('E'))
def genesis(self):
self.create_action(spec=(_('Merge book records'), 'merge_books.svg',
None, _('M')), attr='action_merge')
md = QMenu()
md.addAction(_('Edit metadata individually'),
partial(self.edit_metadata, False, bulk=False))
md.addSeparator()
md.addAction(_('Edit metadata in bulk'),
partial(self.edit_metadata, False, bulk=True))
md.addSeparator()
md.addAction(_('Download metadata and covers'),
partial(self.download_metadata, False, covers=True),
Qt.ControlModifier+Qt.Key_D)
md.addAction(_('Download only metadata'),
partial(self.download_metadata, False, covers=False))
md.addAction(_('Download only covers'),
partial(self.download_metadata, False, covers=True,
set_metadata=False, set_social_metadata=False))
md.addAction(_('Download only social metadata'),
partial(self.download_metadata, False, covers=False,
set_metadata=False, set_social_metadata=True))
self.metadata_menu = md
mb = QMenu()
mb.addAction(_('Merge into first selected book - delete others'),
self.merge_books)
mb.addSeparator()
mb.addAction(_('Merge into first selected book - keep others'),
partial(self.merge_books, safe_merge=True))
self.merge_menu = mb
self.action_merge.setMenu(mb)
md.addSeparator()
md.addAction(self.action_merge)
self.qaction.triggered.connect(self.edit_metadata)
self.qaction.setMenu(md)
self.action_merge.triggered.connect(self.merge_books)
def location_selected(self, loc):
enabled = loc == 'library'
self.qaction.setEnabled(enabled)
self.action_merge.setEnabled(enabled)
def download_metadata(self, checked, covers=True, set_metadata=True,
set_social_metadata=None):
rows = self.gui.library_view.selectionModel().selectedRows()
if not rows or len(rows) == 0:
d = error_dialog(self.gui, _('Cannot download metadata'),
_('No books selected'))
d.exec_()
return
db = self.gui.library_view.model().db
ids = [db.id(row.row()) for row in rows]
self.do_download_metadata(ids, covers=covers,
set_metadata=set_metadata,
set_social_metadata=set_social_metadata)
def do_download_metadata(self, ids, covers=True, set_metadata=True,
set_social_metadata=None):
db = self.gui.library_view.model().db
if set_social_metadata is None:
get_social_metadata = config['get_social_metadata']
else:
get_social_metadata = set_social_metadata
from calibre.gui2.metadata import DownloadMetadata
self._download_book_metadata = DownloadMetadata(db, ids,
get_covers=covers, set_metadata=set_metadata,
get_social_metadata=get_social_metadata)
self._download_book_metadata.start()
if set_social_metadata is not None and set_social_metadata:
x = _('social metadata')
else:
x = _('covers') if covers and not set_metadata else _('metadata')
self.gui.progress_indicator.start(
_('Downloading %s for %d book(s)')%(x, len(ids)))
self._book_metadata_download_check = QTimer(self.gui)
self._book_metadata_download_check.timeout.connect(self.book_metadata_download_check,
type=Qt.QueuedConnection)
self._book_metadata_download_check.start(100)
def book_metadata_download_check(self):
if self._download_book_metadata.is_alive():
return
self._book_metadata_download_check.stop()
self.gui.progress_indicator.stop()
cr = self.gui.library_view.currentIndex().row()
x = self._download_book_metadata
self._download_book_metadata = None
if x.exception is None:
self.gui.library_view.model().refresh_ids(
x.updated, cr)
if self.gui.cover_flow:
self.gui.cover_flow.dataChanged()
if x.failures:
details = ['%s: %s'%(title, reason) for title,
reason in x.failures.values()]
details = '%s\n'%('\n'.join(details))
warning_dialog(self.gui, _('Failed to download some metadata'),
_('Failed to download metadata for the following:'),
det_msg=details).exec_()
else:
err = _('Failed to download metadata:')
error_dialog(self.gui, _('Error'), err, det_msg=x.tb).exec_()
def edit_metadata(self, checked, bulk=None):
'''
Edit metadata of selected books in library.
'''
rows = self.gui.library_view.selectionModel().selectedRows()
previous = self.gui.library_view.currentIndex()
if not rows or len(rows) == 0:
d = error_dialog(self.gui, _('Cannot edit metadata'),
_('No books selected'))
d.exec_()
return
if bulk or (bulk is None and len(rows) > 1):
return self.edit_bulk_metadata(checked)
def accepted(id):
self.gui.library_view.model().refresh_ids([id])
for row in rows:
self.gui.iactions['View'].metadata_view_id = self.gui.library_view.model().db.id(row.row())
d = MetadataSingleDialog(self.gui, row.row(),
self.gui.library_view.model().db,
accepted_callback=accepted,
cancel_all=rows.index(row) < len(rows)-1)
d.view_format.connect(self.gui.iactions['View'].metadata_view_format)
d.exec_()
if d.cancel_all:
break
if rows:
current = self.gui.library_view.currentIndex()
m = self.gui.library_view.model()
if self.gui.cover_flow:
self.gui.cover_flow.dataChanged()
m.current_changed(current, previous)
self.gui.tags_view.recount()
def edit_bulk_metadata(self, checked):
'''
Edit metadata of selected books in library in bulk.
'''
rows = [r.row() for r in \
self.gui.library_view.selectionModel().selectedRows()]
if not rows or len(rows) == 0:
d = error_dialog(self.gui, _('Cannot edit metadata'),
_('No books selected'))
d.exec_()
return
if MetadataBulkDialog(self.gui, rows,
self.gui.library_view.model().db).changed:
self.gui.library_view.model().resort(reset=False)
self.gui.library_view.model().research()
self.gui.tags_view.recount()
if self.gui.cover_flow:
self.gui.cover_flow.dataChanged()
# Merge books {{{
def merge_books(self, safe_merge=False):
'''
Merge selected books in library.
'''
if self.gui.stack.currentIndex() != 0:
return
rows = self.gui.library_view.selectionModel().selectedRows()
if not rows or len(rows) == 0:
return error_dialog(self.gui, _('Cannot merge books'),
_('No books selected'), show=True)
if len(rows) < 2:
return error_dialog(self.gui, _('Cannot merge books'),
_('At least two books must be selected for merging'),
show=True)
dest_id, src_books, src_ids = self.books_to_merge(rows)
if safe_merge:
if not confirm('<p>'+_(
'All book formats and metadata from the selected books '
'will be added to the <b>first selected book.</b><br><br> '
'The second and subsequently selected books will not '
'be deleted or changed.<br><br>'
'Please confirm you want to proceed.')
+'</p>', 'merge_books_safe', self.gui):
return
self.add_formats(dest_id, src_books)
self.merge_metadata(dest_id, src_ids)
else:
if not confirm('<p>'+_(
'All book formats and metadata from the selected books will be merged '
'into the <b>first selected book</b>.<br><br>'
'After merger the second and '
'subsequently selected books will be <b>deleted</b>. <br><br>'
'All book formats of the first selected book will be kept '
'and any duplicate formats in the second and subsequently selected books '
'will be permanently <b>deleted</b> from your computer.<br><br> '
'Are you <b>sure</b> you want to proceed?')
+'</p>', 'merge_books', self.gui):
return
if len(rows)>5:
if not confirm('<p>'+_('You are about to merge more than 5 books. '
'Are you <b>sure</b> you want to proceed?')
+'</p>', 'merge_too_many_books', self.gui):
return
self.add_formats(dest_id, src_books)
self.merge_metadata(dest_id, src_ids)
self.delete_books_after_merge(src_ids)
# leave the selection highlight on first selected book
dest_row = rows[0].row()
for row in rows:
if row.row() < rows[0].row():
dest_row -= 1
ci = self.gui.library_view.model().index(dest_row, 0)
if ci.isValid():
self.gui.library_view.setCurrentIndex(ci)
def add_formats(self, dest_id, src_books, replace=False):
for src_book in src_books:
if src_book:
fmt = os.path.splitext(src_book)[-1].replace('.', '').upper()
with open(src_book, 'rb') as f:
self.gui.library_view.model().db.add_format(dest_id, fmt, f, index_is_id=True,
notify=False, replace=replace)
def books_to_merge(self, rows):
src_books = []
src_ids = []
m = self.gui.library_view.model()
for i, row in enumerate(rows):
id_ = m.id(row)
if i == 0:
dest_id = id_
else:
src_ids.append(id_)
dbfmts = m.db.formats(id_, index_is_id=True)
if dbfmts:
for fmt in dbfmts.split(','):
src_books.append(m.db.format_abspath(id_, fmt,
index_is_id=True))
return [dest_id, src_books, src_ids]
def delete_books_after_merge(self, ids_to_delete):
self.gui.library_view.model().delete_books_by_id(ids_to_delete)
def merge_metadata(self, dest_id, src_ids):
db = self.gui.library_view.model().db
dest_mi = db.get_metadata(dest_id, index_is_id=True, get_cover=True)
orig_dest_comments = dest_mi.comments
for src_id in src_ids:
src_mi = db.get_metadata(src_id, index_is_id=True, get_cover=True)
if src_mi.comments and orig_dest_comments != src_mi.comments:
if not dest_mi.comments:
dest_mi.comments = src_mi.comments
else:
dest_mi.comments = unicode(dest_mi.comments) + u'\n\n' + unicode(src_mi.comments)
if src_mi.title and (not dest_mi.title or
dest_mi.title == _('Unknown')):
dest_mi.title = src_mi.title
if src_mi.title and (not dest_mi.authors or dest_mi.authors[0] ==
_('Unknown')):
dest_mi.authors = src_mi.authors
dest_mi.author_sort = src_mi.author_sort
if src_mi.tags:
if not dest_mi.tags:
dest_mi.tags = src_mi.tags
else:
dest_mi.tags.extend(src_mi.tags)
if src_mi.cover and not dest_mi.cover:
dest_mi.cover = src_mi.cover
if not dest_mi.publisher:
dest_mi.publisher = src_mi.publisher
if not dest_mi.rating:
dest_mi.rating = src_mi.rating
if not dest_mi.series:
dest_mi.series = src_mi.series
dest_mi.series_index = src_mi.series_index
db.set_metadata(dest_id, dest_mi, ignore_errors=False)
for key in db.field_metadata: #loop thru all defined fields
if db.field_metadata[key]['is_custom']:
colnum = db.field_metadata[key]['colnum']
# Get orig_dest_comments before it gets changed
if db.field_metadata[key]['datatype'] == 'comments':
orig_dest_value = db.get_custom(dest_id, num=colnum, index_is_id=True)
for src_id in src_ids:
dest_value = db.get_custom(dest_id, num=colnum, index_is_id=True)
src_value = db.get_custom(src_id, num=colnum, index_is_id=True)
if db.field_metadata[key]['datatype'] == 'comments':
if src_value and src_value != orig_dest_value:
if not dest_value:
db.set_custom(dest_id, src_value, num=colnum)
else:
dest_value = unicode(dest_value) + u'\n\n' + unicode(src_value)
db.set_custom(dest_id, dest_value, num=colnum)
if db.field_metadata[key]['datatype'] in \
('bool', 'int', 'float', 'rating', 'datetime') \
and not dest_value:
db.set_custom(dest_id, src_value, num=colnum)
if db.field_metadata[key]['datatype'] == 'series' \
and not dest_value:
if src_value:
src_index = db.get_custom_extra(src_id, num=colnum, index_is_id=True)
db.set_custom(dest_id, src_value, num=colnum, extra=src_index)
if db.field_metadata[key]['datatype'] == 'text' \
and not db.field_metadata[key]['is_multiple'] \
and not dest_value:
db.set_custom(dest_id, src_value, num=colnum)
if db.field_metadata[key]['datatype'] == 'text' \
and db.field_metadata[key]['is_multiple']:
if src_value:
if not dest_value:
dest_value = src_value
else:
dest_value.extend(src_value)
db.set_custom(dest_id, dest_value, num=colnum)
# }}}
def edit_device_collections(self, view, oncard=None):
model = view.model()
result = model.get_collections_with_ids()
compare = (lambda x,y:cmp(x.lower(), y.lower()))
d = TagListEditor(self.gui, tag_to_match=None, data=result, compare=compare)
d.exec_()
if d.result() == d.Accepted:
to_rename = d.to_rename # dict of new text to old ids
to_delete = d.to_delete # list of ids
for text in to_rename:
for old_id in to_rename[text]:
model.rename_collection(old_id, new_name=unicode(text))
for item in to_delete:
model.delete_collection_using_id(item)
self.gui.upload_collections(model.db, view=view, oncard=oncard)
view.reset()

View File

@ -0,0 +1,71 @@
#!/usr/bin/env python
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
__license__ = 'GPL v3'
__copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
from PyQt4.Qt import Qt
from calibre.gui2 import Dispatcher
from calibre.gui2.tools import fetch_scheduled_recipe
from calibre.utils.config import dynamic
from calibre.gui2.actions import InterfaceAction
class FetchNewsAction(InterfaceAction):
name = 'Fetch News'
action_spec = (_('Fetch news'), 'news.svg', None, _('F'))
def location_selected(self, loc):
enabled = loc == 'library'
self.qaction.setEnabled(enabled)
def genesis(self):
self.conversion_jobs = {}
def init_scheduler(self, db):
from calibre.gui2.dialogs.scheduler import Scheduler
self.scheduler = Scheduler(self.gui, db)
self.scheduler.start_recipe_fetch.connect(self.download_scheduled_recipe, type=Qt.QueuedConnection)
self.qaction.setMenu(self.scheduler.news_menu)
self.qaction.triggered.connect(
self.scheduler.show_dialog)
def library_changed(self, db):
self.scheduler.database_changed(db)
def initialization_complete(self):
self.connect_scheduler()
def connect_scheduler(self):
self.scheduler.delete_old_news.connect(
self.gui.library_view.model().delete_books_by_id,
type=Qt.QueuedConnection)
def download_scheduled_recipe(self, arg):
func, args, desc, fmt, temp_files = \
fetch_scheduled_recipe(arg)
job = self.gui.job_manager.run_job(
Dispatcher(self.scheduled_recipe_fetched), func, args=args,
description=desc)
self.conversion_jobs[job] = (temp_files, fmt, arg)
self.gui.status_bar.show_message(_('Fetching news from ')+arg['title'], 2000)
def scheduled_recipe_fetched(self, job):
temp_files, fmt, arg = self.conversion_jobs.pop(job)
pt = temp_files[0]
if job.failed:
self.scheduler.recipe_download_failed(arg)
return self.gui.job_exception(job)
id = self.gui.library_view.model().add_news(pt.name, arg)
self.gui.library_view.model().reset()
sync = dynamic.get('news_to_be_synced', set([]))
sync.add(id)
dynamic.set('news_to_be_synced', sync)
self.scheduler.recipe_downloaded(arg)
self.gui.status_bar.show_message(arg['title'] + _(' fetched.'), 3000)
self.gui.email_news(id)
self.gui.sync_news()

View File

@ -0,0 +1,25 @@
#!/usr/bin/env python
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
__license__ = 'GPL v3'
__copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
from PyQt4.Qt import QUrl
from calibre.gui2 import open_url
from calibre.gui2.actions import InterfaceAction
class HelpAction(InterfaceAction):
name = 'Help'
action_spec = (_('Help'), 'help.svg', _('Browse the calibre User Manual'), _('F1'),)
def genesis(self):
self.qaction.triggered.connect(self.show_help)
def show_help(self, *args):
open_url(QUrl('http://calibre-ebook.com/user_manual'))

View File

@ -0,0 +1,24 @@
#!/usr/bin/env python
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
__license__ = 'GPL v3'
__copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
from calibre.gui2.actions import InterfaceAction
class OpenFolderAction(InterfaceAction):
name = 'Open Folder'
action_spec = (_('Open containing folder'), 'document_open.svg', None,
_('O'))
def genesis(self):
self.qaction.triggered.connect(self.gui.iactions['View'].view_folder)
def location_selected(self, loc):
enabled = loc == 'library'
self.qaction.setEnabled(enabled)

View File

@ -0,0 +1,61 @@
#!/usr/bin/env python
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
__license__ = 'GPL v3'
__copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
from PyQt4.Qt import QIcon, QMenu
from calibre.gui2.actions import InterfaceAction
from calibre.gui2.dialogs.config import ConfigDialog
from calibre.gui2 import error_dialog, config
class PreferencesAction(InterfaceAction):
name = 'Preferences'
action_spec = (_('Preferences'), 'config.svg', None, _('Ctrl+P'))
def genesis(self):
pm = QMenu()
pm.addAction(QIcon(I('config.svg')), _('Preferences'), self.do_config)
pm.addAction(QIcon(I('wizard.svg')), _('Run welcome wizard'),
self.gui.run_wizard)
self.qaction.setMenu(pm)
self.preferences_menu = pm
for x in (self.gui.preferences_action, self.qaction):
x.triggered.connect(self.do_config)
def do_config(self, checked=False, initial_category='general'):
if self.gui.job_manager.has_jobs():
d = error_dialog(self.gui, _('Cannot configure'),
_('Cannot configure while there are running jobs.'))
d.exec_()
return
if self.gui.must_restart_before_config:
d = error_dialog(self.gui, _('Cannot configure'),
_('Cannot configure before calibre is restarted.'))
d.exec_()
return
d = ConfigDialog(self.gui, self.gui.library_view,
server=self.gui.content_server, initial_category=initial_category)
d.exec_()
self.gui.content_server = d.server
if self.gui.content_server is not None:
self.gui.content_server.state_callback = \
self.Dispatcher(self.gui.iactions['Connect Share'].content_server_state_changed)
self.gui.content_server.state_callback(self.gui.content_server.is_running)
if d.result() == d.Accepted:
self.gui.search.search_as_you_type(config['search_as_you_type'])
self.gui.tags_view.set_new_model() # in case columns changed
self.gui.iactions['Save To Disk'].reread_prefs()
self.gui.tags_view.recount()
self.gui.create_device_menu()
self.gui.set_device_menu_items_state(bool(self.gui.device_connected))
self.gui.tool_bar.apply_settings()

View File

@ -0,0 +1,22 @@
#!/usr/bin/env python
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
__license__ = 'GPL v3'
__copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
from calibre.gui2.actions import InterfaceAction
class RestartAction(InterfaceAction):
name = 'Restart'
action_spec = (_('&Restart'), None, None, _('Ctrl+R'))
def genesis(self):
self.qaction.triggered.connect(self.restart)
def restart(self, *args):
self.gui.quit(restart=True)

View File

@ -0,0 +1,153 @@
#!/usr/bin/env python
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
__license__ = 'GPL v3'
__copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
import os
from functools import partial
from PyQt4.Qt import QMenu, pyqtSignal
from calibre.utils.config import prefs
from calibre.gui2 import error_dialog, Dispatcher, \
choose_dir, warning_dialog, open_local_file
from calibre.gui2.actions import InterfaceAction
from calibre.ebooks import BOOK_EXTENSIONS
class SaveMenu(QMenu): # {{{
save_fmt = pyqtSignal(object)
def __init__(self, parent):
QMenu.__init__(self, _('Save single format to disk...'), parent)
for ext in sorted(BOOK_EXTENSIONS):
action = self.addAction(ext.upper())
setattr(self, 'do_'+ext, partial(self.do, ext))
action.triggered.connect(
getattr(self, 'do_'+ext))
def do(self, ext, *args):
self.save_fmt.emit(ext)
# }}}
class SaveToDiskAction(InterfaceAction):
name = "Save To Disk"
action_spec = (_('Save to disk'), 'save.svg', None, _('S'))
def genesis(self):
self.qaction.triggered.connect(self.save_to_disk)
self.save_menu = QMenu()
self.save_menu.addAction(_('Save to disk'), partial(self.save_to_disk,
False))
self.save_menu.addAction(_('Save to disk in a single directory'),
partial(self.save_to_single_dir, False))
self.save_menu.addAction(_('Save only %s format to disk')%
prefs['output_format'].upper(),
partial(self.save_single_format_to_disk, False))
self.save_menu.addAction(
_('Save only %s format to disk in a single directory')%
prefs['output_format'].upper(),
partial(self.save_single_fmt_to_single_dir, False))
self.save_sub_menu = SaveMenu(self.gui)
self.save_sub_menu_action = self.save_menu.addMenu(self.save_sub_menu)
self.save_sub_menu.save_fmt.connect(self.save_specific_format_disk)
self.qaction.setMenu(self.save_menu)
def location_selected(self, loc):
enabled = loc == 'library'
for action in list(self.save_menu.actions())[1:]:
action.setEnabled(enabled)
def reread_prefs(self):
self.save_menu.actions()[2].setText(
_('Save only %s format to disk')%
prefs['output_format'].upper())
self.save_menu.actions()[3].setText(
_('Save only %s format to disk in a single directory')%
prefs['output_format'].upper())
def save_single_format_to_disk(self, checked):
self.save_to_disk(checked, False, prefs['output_format'])
def save_specific_format_disk(self, fmt):
self.save_to_disk(False, False, fmt)
def save_to_single_dir(self, checked):
self.save_to_disk(checked, True)
def save_single_fmt_to_single_dir(self, *args):
self.save_to_disk(False, single_dir=True,
single_format=prefs['output_format'])
def save_to_disk(self, checked, single_dir=False, single_format=None):
rows = self.gui.current_view().selectionModel().selectedRows()
if not rows or len(rows) == 0:
return error_dialog(self.gui, _('Cannot save to disk'),
_('No books selected'), show=True)
path = choose_dir(self.gui, 'save to disk dialog',
_('Choose destination directory'))
if not path:
return
dpath = os.path.abspath(path).replace('/', os.sep)+os.sep
lpath = self.gui.library_view.model().db.library_path.replace('/',
os.sep)+os.sep
if dpath.startswith(lpath):
return error_dialog(self.gui, _('Not allowed'),
_('You are trying to save files into the calibre '
'library. This can cause corruption of your '
'library. Save to disk is meant to export '
'files from your calibre library elsewhere.'), show=True)
if self.gui.current_view() is self.gui.library_view:
from calibre.gui2.add import Saver
from calibre.library.save_to_disk import config
opts = config().parse()
if single_format is not None:
opts.formats = single_format
# Special case for Kindle annotation files
if single_format.lower() in ['mbp','pdr','tan']:
opts.to_lowercase = False
opts.save_cover = False
opts.write_opf = False
opts.template = opts.send_template
if single_dir:
opts.template = opts.template.split('/')[-1].strip()
if not opts.template:
opts.template = '{title} - {authors}'
self._saver = Saver(self.gui, self.gui.library_view.model().db,
Dispatcher(self._books_saved), rows, path, opts,
spare_server=self.gui.spare_server)
else:
paths = self.gui.current_view().model().paths(rows)
self.gui.device_manager.save_books(
Dispatcher(self.books_saved), paths, path)
def _books_saved(self, path, failures, error):
self._saver = None
if error:
return error_dialog(self.gui, _('Error while saving'),
_('There was an error while saving.'),
error, show=True)
if failures:
failures = [u'%s\n\t%s'%
(title, '\n\t'.join(err.splitlines())) for title, err in
failures]
warning_dialog(self.gui, _('Could not save some books'),
_('Could not save some books') + ', ' +
_('Click the show details button to see which ones.'),
u'\n\n'.join(failures), show=True)
open_local_file(path)
def books_saved(self, job):
if job.failed:
return self.gui.device_job_exception(job)

View File

@ -0,0 +1,31 @@
#!/usr/bin/env python
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
__license__ = 'GPL v3'
__copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
from calibre.gui2.actions import InterfaceAction
from calibre.gui2.dialogs.book_info import BookInfo
from calibre.gui2 import error_dialog
class ShowBookDetailsAction(InterfaceAction):
name = 'Show Book Details'
action_spec = (_('Show book details'), 'dialog_information.svg', None,
_('I'))
def genesis(self):
self.qaction.triggered.connect(self.show_book_info)
def show_book_info(self, *args):
if self.gui.current_view() is not self.gui.library_view:
error_dialog(self.gui, _('No detailed info available'),
_('No detailed information is available for books '
'on the device.')).exec_()
return
index = self.gui.library_view.currentIndex()
if index.isValid():
BookInfo(self.gui, self.gui.library_view, index).show()

View File

@ -0,0 +1,60 @@
#!/usr/bin/env python
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
__license__ = 'GPL v3'
__copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
from functools import partial
from PyQt4.Qt import QMenu
from calibre.gui2.actions import InterfaceAction
class SimilarBooksAction(InterfaceAction):
name = 'Similar Books'
action_spec = (_('Similar books...'), None, None, None)
def genesis(self):
m = QMenu(self.gui)
for text, icon, target, shortcut in [
(_('Books by same author'), 'user_profile.svg', 'authors', _('Alt+A')),
(_('Books in this series'), 'books_in_series.svg', 'series', _('Alt+S')),
(_('Books by this publisher'), 'publisher.png', 'publisher', _('Alt+P')),
(_('Books with the same tags'), 'tags.svg', 'tag', _('Alt+T')),]:
ac = self.create_action(spec=(text, icon, None, shortcut),
attr=target)
m.addAction(ac)
m.triggered.connect(partial(self.show_similar_books, target))
self.qaction.setMenu(m)
self.similar_menu = m
def show_similar_books(self, type, *args):
search, join = [], ' '
idx = self.gui.library_view.currentIndex()
if not idx.isValid():
return
row = idx.row()
if type == 'series':
series = idx.model().db.series(row)
if series:
search = ['series:"'+series+'"']
elif type == 'publisher':
publisher = idx.model().db.publisher(row)
if publisher:
search = ['publisher:"'+publisher+'"']
elif type == 'tag':
tags = idx.model().db.tags(row)
if tags:
search = ['tag:"='+t+'"' for t in tags.split(',')]
elif type in ('author', 'authors'):
authors = idx.model().db.authors(row)
if authors:
search = ['author:"='+a.strip().replace('|', ',')+'"' \
for a in authors.split(',')]
join = ' or '
if search:
self.gui.search.set_search_string(join.join(search))

View File

@ -0,0 +1,181 @@
#!/usr/bin/env python
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
__license__ = 'GPL v3'
__copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
import os, time
from functools import partial
from PyQt4.Qt import Qt, QMenu
from calibre.constants import isosx
from calibre.gui2 import error_dialog, Dispatcher, question_dialog, config, \
open_local_file
from calibre.gui2.dialogs.choose_format import ChooseFormatDialog
from calibre.utils.config import prefs
from calibre.ptempfile import PersistentTemporaryFile
from calibre.gui2.actions import InterfaceAction
class ViewAction(InterfaceAction):
name = 'View'
action_spec = (_('View'), 'view.svg', None, _('V'))
def genesis(self):
self.persistent_files = []
self.metadata_view_id = None
self.qaction.triggered.connect(self.view_book)
self.view_menu = QMenu()
self.view_menu.addAction(_('View'), partial(self.view_book, False))
ac = self.view_menu.addAction(_('View specific format'))
ac.setShortcut((Qt.ControlModifier if isosx else Qt.AltModifier)+Qt.Key_V)
self.qaction.setMenu(self.view_menu)
ac.triggered.connect(self.view_specific_format, type=Qt.QueuedConnection)
def location_selected(self, loc):
enabled = loc == 'library'
for action in list(self.view_menu.actions())[1:]:
action.setEnabled(enabled)
def view_format(self, row, format):
fmt_path = self.gui.library_view.model().db.format_abspath(row, format)
if fmt_path:
self._view_file(fmt_path)
def view_format_by_id(self, id_, format):
fmt_path = self.gui.library_view.model().db.format_abspath(id_, format,
index_is_id=True)
if fmt_path:
self._view_file(fmt_path)
def metadata_view_format(self, fmt):
fmt_path = self.gui.library_view.model().db.\
format_abspath(self.metadata_view_id,
fmt, index_is_id=True)
if fmt_path:
self._view_file(fmt_path)
def book_downloaded_for_viewing(self, job):
if job.failed:
self.gui.device_job_exception(job)
return
self._view_file(job.result)
def _launch_viewer(self, name=None, viewer='ebook-viewer', internal=True):
self.gui.setCursor(Qt.BusyCursor)
try:
if internal:
args = [viewer]
if isosx and 'ebook' in viewer:
args.append('--raise-window')
if name is not None:
args.append(name)
self.gui.job_manager.launch_gui_app(viewer,
kwargs=dict(args=args))
else:
open_local_file(name)
time.sleep(2) # User feedback
finally:
self.gui.unsetCursor()
def _view_file(self, name):
ext = os.path.splitext(name)[1].upper().replace('.', '')
viewer = 'lrfviewer' if ext == 'LRF' else 'ebook-viewer'
internal = ext in config['internally_viewed_formats']
self._launch_viewer(name, viewer, internal)
def view_specific_format(self, triggered):
rows = self.gui.library_view.selectionModel().selectedRows()
if not rows or len(rows) == 0:
d = error_dialog(self.gui, _('Cannot view'), _('No book selected'))
d.exec_()
return
row = rows[0].row()
formats = self.gui.library_view.model().db.formats(row).upper().split(',')
d = ChooseFormatDialog(self.gui, _('Choose the format to view'), formats)
if d.exec_() == d.Accepted:
format = d.format()
self.view_format(row, format)
def _view_check(self, num, max_=3):
if num <= max_:
return True
return question_dialog(self.gui, _('Multiple Books Selected'),
_('You are attempting to open %d books. Opening too many '
'books at once can be slow and have a negative effect on the '
'responsiveness of your computer. Once started the process '
'cannot be stopped until complete. Do you wish to continue?'
) % num)
def view_folder(self, *args):
rows = self.gui.current_view().selectionModel().selectedRows()
if not rows or len(rows) == 0:
d = error_dialog(self.gui, _('Cannot open folder'),
_('No book selected'))
d.exec_()
return
if not self._view_check(len(rows)):
return
for row in rows:
path = self.gui.library_view.model().db.abspath(row.row())
open_local_file(path)
def view_folder_for_id(self, id_):
path = self.gui.library_view.model().db.abspath(id_, index_is_id=True)
open_local_file(path)
def view_book(self, triggered):
rows = self.gui.current_view().selectionModel().selectedRows()
self._view_books(rows)
def view_specific_book(self, index):
self._view_books([index])
def _view_books(self, rows):
if not rows or len(rows) == 0:
self._launch_viewer()
return
if not self._view_check(len(rows)):
return
if self.gui.current_view() is self.gui.library_view:
for row in rows:
if hasattr(row, 'row'):
row = row.row()
formats = self.gui.library_view.model().db.formats(row)
title = self.gui.library_view.model().db.title(row)
if not formats:
error_dialog(self.gui, _('Cannot view'),
_('%s has no available formats.')%(title,), show=True)
continue
formats = formats.upper().split(',')
in_prefs = False
for format in prefs['input_format_order']:
if format in formats:
in_prefs = True
self.view_format(row, format)
break
if not in_prefs:
self.view_format(row, formats[0])
else:
paths = self.gui.current_view().model().paths(rows)
for path in paths:
pt = PersistentTemporaryFile('_viewer_'+\
os.path.splitext(path)[1])
self.persistent_files.append(pt)
pt.close()
self.gui.device_manager.view_book(\
Dispatcher(self.book_downloaded_for_viewing),
path, pt.name)

View File

@ -443,7 +443,7 @@ class Saver(QObject):
from calibre.ebooks.metadata.worker import SaveWorker
self.worker = SaveWorker(self.rq, db, self.ids, path, self.opts,
spare_server=self.spare_server)
self.connect(self.pd, SIGNAL('canceled()'), self.canceled)
self.pd.canceled_signal.connect(self.canceled)
self.timer = QTimer(self)
self.connect(self.timer, SIGNAL('timeout()'), self.update)
self.timer.start(200)

View File

@ -16,18 +16,39 @@ from calibre.ebooks.conversion.config import load_defaults, \
save_defaults as save_defaults_, \
load_specifics, GuiRecommendations
from calibre import prepare_string_for_xml
from calibre.customize.ui import plugin_for_input_format
def config_widget_for_input_plugin(plugin):
name = plugin.name.lower().replace(' ', '_')
try:
return __import__('calibre.gui2.convert.'+name,
fromlist=[1]).PluginWidget
except ImportError:
pass
def bulk_defaults_for_input_format(fmt):
plugin = plugin_for_input_format(fmt)
if plugin is not None:
w = config_widget_for_input_plugin(plugin)
if w is not None:
return load_defaults(w.COMMIT_NAME)
return {}
class Widget(QWidget):
TITLE = _('Unknown')
ICON = I('config.svg')
HELP = ''
COMMIT_NAME = None
def __init__(self, parent, name, options):
def __init__(self, parent, options):
QWidget.__init__(self, parent)
self.setupUi(self)
self._options = options
self._name = name
self._name = self.commit_name = self.COMMIT_NAME
assert self._name is not None
self._icon = QIcon(self.ICON)
for name in self._options:
if not hasattr(self, 'opt_'+name):
@ -58,7 +79,7 @@ class Widget(QWidget):
def commit_options(self, save_defaults=False):
recs = self.create_recommendations()
if save_defaults:
save_defaults_(self._name, recs)
save_defaults_(self.commit_name, recs)
return recs
def create_recommendations(self):

View File

@ -14,9 +14,10 @@ class PluginWidget(Widget, Ui_Form):
TITLE = _('Comic Input')
HELP = _('Options specific to')+' comic '+_('input')
COMMIT_NAME = 'comic_input'
def __init__(self, parent, get_option, get_help, db=None, book_id=None):
Widget.__init__(self, parent, 'comic_input',
Widget.__init__(self, parent,
['colors', 'dont_normalize', 'keep_aspect_ratio', 'right2left',
'despeckle', 'no_sort', 'no_process', 'landscape',
'dont_sharpen', 'disable_trim', 'wide', 'output_format',

View File

@ -19,9 +19,10 @@ class DebugWidget(Widget, Ui_Form):
TITLE = _('Debug')
ICON = I('debug.svg')
HELP = _('Debug the conversion process.')
COMMIT_NAME = 'debug'
def __init__(self, parent, get_option, get_help, db=None, book_id=None):
Widget.__init__(self, parent, 'debug',
Widget.__init__(self, parent,
['debug_pipeline']
)
self.db, self.book_id = db, book_id

View File

@ -14,9 +14,10 @@ class PluginWidget(Widget, Ui_Form):
TITLE = _('EPUB Output')
HELP = _('Options specific to')+' EPUB '+_('output')
COMMIT_NAME = 'epub_output'
def __init__(self, parent, get_option, get_help, db=None, book_id=None):
Widget.__init__(self, parent, 'epub_output',
Widget.__init__(self, parent,
['dont_split_on_page_breaks', 'flow_size',
'no_default_epub_cover', 'no_svg_cover',
'preserve_cover_aspect_ratio',]

View File

@ -11,9 +11,10 @@ class PluginWidget(Widget, Ui_Form):
TITLE = _('FB2 Input')
HELP = _('Options specific to')+' FB2 '+_('input')
COMMIT_NAME = 'fb2_input'
def __init__(self, parent, get_option, get_help, db=None, book_id=None):
Widget.__init__(self, parent, 'fb2_input',
Widget.__init__(self, parent,
['no_inline_fb2_toc'])
self.db, self.book_id = db, book_id
self.initialize_options(get_option, get_help, db, book_id)

View File

@ -13,8 +13,9 @@ class PluginWidget(Widget, Ui_Form):
TITLE = _('FB2 Output')
HELP = _('Options specific to')+' FB2 '+_('output')
COMMIT_NAME = 'fb2_output'
def __init__(self, parent, get_option, get_help, db=None, book_id=None):
Widget.__init__(self, parent, 'fb2_output', ['inline_toc'])
Widget.__init__(self, parent, ['inline_toc'])
self.db, self.book_id = db, book_id
self.initialize_options(get_option, get_help, db, book_id)

View File

@ -16,9 +16,10 @@ class LookAndFeelWidget(Widget, Ui_Form):
TITLE = _('Look & Feel')
ICON = I('lookfeel.svg')
HELP = _('Control the look and feel of the output')
COMMIT_NAME = 'look_and_feel'
def __init__(self, parent, get_option, get_help, db=None, book_id=None):
Widget.__init__(self, parent, 'look_and_feel',
Widget.__init__(self, parent,
['change_justification', 'extra_css', 'base_font_size',
'font_size_mapping', 'line_height',
'linearize_tables',

View File

@ -18,9 +18,10 @@ class PluginWidget(Widget, Ui_Form):
TITLE = _('LRF Output')
HELP = _('Options specific to')+' LRF '+_('output')
COMMIT_NAME = 'lrf_output'
def __init__(self, parent, get_option, get_help, db=None, book_id=None):
Widget.__init__(self, parent, 'lrf_output',
Widget.__init__(self, parent,
['wordspace', 'header', 'header_format',
'minimum_indent', 'serif_family',
'render_tables_as_images', 'sans_family', 'mono_family',

View File

@ -42,9 +42,10 @@ class MetadataWidget(Widget, Ui_Form):
ICON = I('dialog_information.svg')
HELP = _('Set the metadata. The output file will contain as much of this '
'metadata as possible.')
COMMIT_NAME = 'metadata'
def __init__(self, parent, get_option, get_help, db=None, book_id=None):
Widget.__init__(self, parent, 'metadata', ['prefer_metadata_cover'])
Widget.__init__(self, parent, ['prefer_metadata_cover'])
self.db, self.book_id = db, book_id
self.cover_changed = False
self.cover_data = None

View File

@ -19,10 +19,10 @@ class PluginWidget(Widget, Ui_Form):
TITLE = _('MOBI Output')
HELP = _('Options specific to')+' MOBI '+_('output')
COMMIT_NAME = 'mobi_output'
def __init__(self, parent, get_option, get_help, db=None, book_id=None):
Widget.__init__(self, parent, 'mobi_output',
Widget.__init__(self, parent,
['prefer_author_sort', 'rescale_images', 'toc_title',
'dont_compress', 'no_inline_toc', 'masthead_font','personal_doc']
)

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