jump functions
[comic-widget] / src / usr / lib / hildon-desktop / comicwidget.py
1 import gobject
2 import hildon
3 import hildondesktop
4 import gtk
5 import csv
6 import urllib2
7 import string
8 import os
9 import osso
10 import cairo
11 import datetime
12 import shutil
13 import sys
14 import socket
15
16 socket.setdefaulttimeout(30)
17
18 supports_alpha = False
19
20 # LOGGING!
21 # sys.stdout = open('/home/user/.comic-widget/output_log.txt', 'a')
22 # sys.stderr = open('/home/user/.comic-widget/error_log.txt', 'a')
23 # print "Start logging!"
24
25 # constants. dbfile is the location of the csv
26 # comiccache is the location of the images
27 APP_VERSION = "0.4.1-1"
28
29 basedbdir = "/opt/comic-widget/db/"
30 imagedir = "/opt/comic-widget/images/"
31 dbdir = "/home/user/.comic-widget/"
32 activecomics = dbdir + "activecomics.cfg"
33 comiccache = "/home/user/MyDocs/.comics/"
34 defaultcomics = ['xkcd','wulff','sinfest']
35 comics = {
36                 "9_chickweed_lanecomicscom":{"name":"9 Chickweed Lane","link":"http://comics.com/9_chickweed_lane/","start":"2010-02-01","dbfile":dbdir + "comicdb.9chickweedlane.csv"},
37                 "agnescomicscom":{"name":"Agnes","link":"http://comics.com/agnes/","start":"2010-02-01","dbfile":dbdir + "comicdb.agnes.csv"},
38                 "andy_cappcomicscom":{"name":"Andy Capp","link":"http://comics.com/andy_capp/","start":"2010-02-01","dbfile":dbdir + "comicdb.andycapp.csv"},
39                 "alley_oopcomicscom":{"name":"Alley Oop","link":"http://comics.com/alley_oop/","start":"2010-02-01","dbfile":dbdir + "comicdb.alleyoop.csv"},
40                 "arlonjaniscomicscom":{"name":"Arlo and Janis","link":'http://comics.com/arlo&janis/',"start":"2010-02-01","dbfile":dbdir + "comicdb.arlonjanis.csv"},
41                 "bccomicscom":{"name":"B.C.","link":"http://comics.com/bc/","start":"2010-02-01","dbfile":dbdir + "comicdb.bc.csv"},
42                 "ballard_streetcomicscom":{"name":"Ballard Street","link":"http://comics.com/ballard_street/","start":"2010-02-01","dbfile":dbdir + "comicdb.ballardstreet.csv"},
43                 "babyblues":{"name":"Baby Blues","link":"http://www.babyblues.com/","start":"01/19/2010","dbfile":dbdir + "comicdb.babyblues.csv"},
44                 "bencomicscom":{"name":"Ben","link":'http://comics.com/ben/',"start":"2010-02-01","dbfile":dbdir + "comicdb.ben.csv"},
45                 "bettycomicscom":{"name":"Betty","link":"http://comics.com/betty/","start":"2010-02-01","dbfile":dbdir + "comicdb.betty.csv"},
46                 "big_natecomicscom":{"name":"Big Nate","link":"http://comics.com/big_nate/","start":"2010-02-01","dbfile":dbdir + "comicdb.bignate.csv"},
47                 "brevitycomicscom":{"name":"Brevity","link":"http://comics.com/brevity/","start":"2010-02-01","dbfile":dbdir + "comicdb.brevity.csv"},
48                 "candorvillecomicscom":{"name":"Candorville","link":"http://comics.com/candorville/","start":"2010-02-01","dbfile":dbdir + "comicdb.candorville.csv"},
49                 "cheap_thrillscomicscom":{"name":"Cheap Thrills","link":"http://comics.com/cheap_thrills/","start":"2010-02-01","dbfile":dbdir + "comicdb.cheapthrills.csv"},
50                 "committedcomicscom":{"name":"Committed","link":"http://comics.com/committed/","start":"2010-02-01","dbfile":dbdir + "comicdb.committed.csv"},
51                 "cownboycomicscom":{"name":"Cow and Boy","link":'http://comics.com/cow&boy/',"start":"2010-02-01","dbfile":dbdir + "comicdb.cownboy.csv"},
52                 "cyanide":{"name":"Cyanide and Happiness","link":"http://explosm.com/","start":"1920","dbfile":dbdir + "comicdb.cyanide.csv"},
53                 "daddyshomecomicscom":{"name":"Daddy's Home","link":"http://comics.com/daddys_home/","start":"2010-02-01","dbfile":dbdir + "comicdb.daddyshome.csv"},
54                 "dilbert":{"name":"Dilbert","link":"http://dilbert.com/","start":"2010-01-01","dbfile":dbdir + "comicdb.dilbert.csv"},
55                 "dog_eat_dougcomicscom":{"name":"Dog eat Doug","link":"http://comics.com/dog_eat_doug/","start":"2010-02-01","dbfile":dbdir + "comicdb.dogeatdoug.csv"},
56                 "drabblecomicscom":{"name":"Drabble","link":"http://comics.com/drabble/","start":"2010-02-01","dbfile":dbdir + "comicdb.drabble.csv"},
57                 "f_minuscomicscom":{"name":"F Minus","link":"http://comics.com/f_minus/","start":"2010-02-01","dbfile":dbdir + "comicdb.f_minus.csv"},
58                 "family_treecomicscom":{"name":"Family Tree","link":"http://comics.com/family_tree/","start":"2010-02-01","dbfile":dbdir + "comicdb.familytree.csv"},
59                 "farcuscomicscom":{"name":"Farcus","link":'http://comics.com/farcus/',"start":"2010-02-01","dbfile":dbdir + "comicdb.farcus.csv"},
60                 "fat_catscomicscom":{"name":"Fat Cats","link":'http://comics.com/fat_cats_classics/',"start":"2010-02-01","dbfile":dbdir + "comicdb.fatcats.csv"},
61                 "ferdnandcomicscom":{"name":"Ferd'nand","link":'http://comics.com/ferdnand/',"start":"2010-02-01","dbfile":dbdir + "comicdb.ferdnand.csv"},
62                 "flight_deckcomicscom":{"name":"Flight_Deck","link":'http://comics.com/flight_deck/',"start":"2010-02-01","dbfile":dbdir + "comicdb.flightdeck.csv"},
63                 "flonfriendscomicscom":{"name":"Flo and Friends","link":'http://comics.com/flo&friends/',"start":"2010-02-01","dbfile":dbdir + "comicdb.flonfriends.csv"},
64                 "fort_knoxcomicscom":{"name":"Fort Knox","link":'http://comics.com/fort_knox/',"start":"2010-02-01","dbfile":dbdir + "comicdb.fortknox.csv"},
65                 "franknernestcomicscom":{"name":"Frank and Ernest","link":'http://comics.com/frank&ernest/',"start":"2010-02-01","dbfile":dbdir + "comicdb.franknernest.csv"},
66                 "frazzcomicscom":{"name":"Frazz","link":"http://comics.com/frazz/","start":"2010-02-01","dbfile":dbdir + "comicdb.frazz.csv"},
67                 "free_rangecomicscom":{"name":"Free Range","link":'http://comics.com/free_range/',"start":"2010-02-01","dbfile":dbdir + "comicdb.freerange.csv"},
68                 "geechcomicscom":{"name":"Geech","link":'http://comics.com/geech_classics/',"start":"2010-02-01","dbfile":dbdir + "comicdb.geech.csv"},
69                 "getfuzzycomicscom":{"name":"Get Fuzzy","link":"http://comics.com/get_fuzzy/","start":"2010-02-01","dbfile":dbdir + "comicdb.getfuzzy.csv"},
70                 "girlsnsportscomicscom":{"name":"Girls and Sports","link":'http://comics.com/girls&sports/',"start":"2010-02-01","dbfile":dbdir + "comicdb.gitlsnsports.csv"},
71                 "graffiticomicscom":{"name":"Graffiti","link":'http://comics.com/graffiti/',"start":"2010-02-01","dbfile":dbdir + "comicdb.graffiti.csv"},
72                 "grand_avenuecomicscom":{"name":"Grand Avenue","link":'http://comics.com/grand_avenue/',"start":"2010-02-01","dbfile":dbdir + "comicdb.grandavenue.csv"},
73                 "heathcliffcomicscom":{"name":"Heathcliff","link":'http://comics.com/heathcliff/',"start":"2010-02-01","dbfile":dbdir + "comicdb.heathcliff.csv"},
74                 "herb_and_jamaalcomicscom":{"name":"Herb and Jamaal","link":'http://comics.com/herb_and_jamaal/',"start":"2010-02-01","dbfile":dbdir + "comicdb.herbandjamaal.csv"},
75                 "hermancomicscom":{"name":"Herman","link":'http://comics.com/herman/',"start":"2010-02-01","dbfile":dbdir + "comicdb.herman.csv"},
76                 "home_and_awaycomicscom":{"name":"Home and Away","link":'http://comics.com/home_and_away/',"start":"2010-02-01","dbfile":dbdir + "comicdb.homeandaway.csv"},
77                 "its_all_about_youcomicscom":{"name":"It's All About You","link":'http://comics.com/its_all_about_you/',"start":"2010-02-01","dbfile":dbdir + "comicdb.itsallaboutyou.csv"},
78                 "janes_worldcomicscom":{"name":"Jane's World","link":'http://comics.com/janes_world/',"start":"2010-02-01","dbfile":dbdir + "comicdb.janesworld.csv"},
79                 "jump_startcomicscom":{"name":"Jump Start","link":'http://comics.com/jump_start/',"start":"2010-02-01","dbfile":dbdir + "comicdb.jumpstart.csv"},
80                 "kit_n_carlylecomicscom":{"name":"Kit 'n' Carlyle","link":'http://comics.com/kit_n_carlyle/',"start":"2010-02-01","dbfile":dbdir + "comicdb.kitncarlyle.csv"},
81                 "lil_abnercomicscom":{"name":"Li'l Abner","link":'http://comics.com/lil_abner_classics/',"start":"2010-02-01","dbfile":dbdir + "comicdb.lilabner.csv"},
82                 "liberty_meadowscomicscom":{"name":"Liberty Meadows","link":'http://comics.com/liberty_meadows/',"start":"2010-02-01","dbfile":dbdir + "comicdb.libertymeadows.csv"},
83                 "little_dog_lostcomicscom":{"name":"Little Dog Lost","link":'http://comics.com/little_dog_lost/',"start":"2010-02-01","dbfile":dbdir + "comicdb.littledoglost.csv"},
84                 "lolacomicscom":{"name":"Lola","link":'http://comics.com/lola/',"start":"2010-02-01","dbfile":dbdir + "comicdb.lola.csv"},
85                 "luanncomicscom":{"name":"Luann","link":'http://comics.com/luann/',"start":"2010-02-01","dbfile":dbdir + "comicdb.luann.csv"},
86                 "marmadukecomicscom":{"name":"Marmaduke","link":'http://comics.com/marmaduke/',"start":"2010-02-01","dbfile":dbdir + "comicdb.marmaduke.csv"},
87                 "megcomicscom":{"name":"Meg","link":'http://comics.com/meg_classics/',"start":"2010-02-01","dbfile":dbdir + "comicdb.meg.csv"},
88                 "minimum_securitycomicscom":{"name":"Minimum Security","link":'http://comics.com/minimum_security/',"start":"2010-02-01","dbfile":dbdir + "comicdb.minimumsecurity.csv"},
89                 "moderately_confusedcomicscom":{"name":"Moderately Confused","link":'http://comics.com/moderately_confused/',"start":"2010-02-01","dbfile":dbdir + "comicdb.moderatelyconfused.csv"},
90                 "mommacomicscom":{"name":"Momma","link":'http://comics.com/momma/',"start":"2010-02-01","dbfile":dbdir + "comicdb.momma.csv"},
91                 "motleycomicscom":{"name":"Motley","link":'http://comics.com/motley_classics/',"start":"2010-02-01","dbfile":dbdir + "comicdb.motley.csv"},
92                 "nancycomicscom":{"name":"Nancy","link":'http://comics.com/nancy/',"start":"2010-02-01","dbfile":dbdir + "comicdb.nancy.csv"},
93                 "natural_selectioncomicscom":{"name":"Natural Selection","link":'http://comics.com/natural_selection/',"start":"2010-02-01","dbfile":dbdir + "comicdb.naturalselection.csv"},
94                 "nest_headscomicscom":{"name":"Nest Heads","link":'http://comics.com/nest_heads/',"start":"2010-02-01","dbfile":dbdir + "comicdb.nestheads.csv"},
95                 "off_the_markcomicscom":{"name":"Off the mark","link":"http://comics.com/off_the_mark/","start":"2010-02-01","dbfile":dbdir + "comicdb.offthemark.csv"},
96                 "on_a_claire_daycomicscom":{"name":"On A Claire Day","link":'http://comics.com/on_a_claire_day/',"start":"2010-02-01","dbfile":dbdir + "comicdb.onaclaireday.csv"},
97                 "one_big_happycomicscom":{"name":"One Big Happy","link":'http://comics.com/one_big_happy_classics/',"start":"2010-02-01","dbfile":dbdir + "comicdb.onebighappy.csv"},
98                 "over_the_hedgecomicscom":{"name":"Over the Hedge","link":'http://comics.com/over_the_hedge/',"start":"2010-02-01","dbfile":dbdir + "comicdb.overthehedge.csv"},
99                 "pc_and_pixelcomicscom":{"name":"PC and Pixel","link":'http://comics.com/pc_and_pixel/',"start":"2010-02-01","dbfile":dbdir + "comicdb.pcandpixel.csv"},
100                 "peanutscomicscom":{"name":"Peanuts","link":"http://comics.com/peanuts/","start":"2010-02-01","dbfile":dbdir + "comicdb.peanuts.csv"},
101                 "pearls_before_swinecomicscom":{"name":"Pearls Before Swine","link":'http://comics.com/pearls_before_swine/',"start":"2010-02-01","dbfile":dbdir + "comicdb.pearlsbeforeswine.csv"},
102                 "phd":{"name":"PHD Comics","link":"http://www.phdcomics.com/","start":1240,"dbfile":dbdir + "comicdb.phd.csv"},
103                 "picklescomicscom":{"name":"Pickles","link":'http://comics.com/pickles/',"start":"2010-02-01","dbfile":dbdir + "comicdb.pickles.csv"},
104                 "prickly_citycomicscom":{"name":"Prickly City","link":'http://comics.com/prickly_city/',"start":"2010-02-01","dbfile":dbdir + "comicdb.pricklycity.csv"},
105                 "raising_duncancomicscom":{"name":"Raising Duncan","link":'http://comics.com/raising_duncan_classics/',"start":"2010-02-01","dbfile":dbdir + "comicdb.raisingduncan.csv"},
106                 "reality_checkcomicscom":{"name":"Reality Check","link":'http://comics.com/reality_check/',"start":"2010-02-01","dbfile":dbdir + "comicdb.realitycheck.csv"},
107                 "rednrovercomicscom":{"name":"Red and Rover","link":'http://comics.com/red&rover/',"start":"2010-02-01","dbfile":dbdir + "comicdb.rednrover.csv"},
108                 "rip_haywirecomicscom":{"name":"Rip Haywire","link":'http://comics.com/rip_haywire/',"start":"2010-02-01","dbfile":dbdir + "comicdb.riphaywire.csv"},
109                 "ripleys_believe_it_or_notcomicscom":{"name":"Ripley's Believe it or not","link":'http://comics.com/ripleys_believe_it_or_not/',"start":"2010-02-01","dbfile":dbdir + "comicdb.ripleysbelieveitornot.csv"},
110                 "rose_is_rosecomicscom":{"name":"Rose Is Rose","link":'http://comics.com/rose_is_rose/',"start":"2010-02-01","dbfile":dbdir + "comicdb.roseisrose.csv"},
111                 "rubescomicscom":{"name":"Rubes","link":'http://comics.com/rubes/',"start":"2010-02-01","dbfile":dbdir + "comicdb.rubes.csv"},
112                 "rudy_parkcomicscom":{"name":"Rudy Park","link":'http://comics.com/rudy_park/',"start":"2010-02-01","dbfile":dbdir + "comicdb.rudypark.csv"},
113                 "scary_garycomicscom":{"name":"Scary Gary","link":'http://comics.com/scary_gary/',"start":"2010-02-01","dbfile":dbdir + "comicdb.scarygary.csv"},
114                 "shirley_and_soncomicscom":{"name":"Shirley and Son","link":'http://comics.com/shirley_and_son_classics/',"start":"2010-02-01","dbfile":dbdir + "comicdb.shirleyandson.csv"},
115                 "sinfest":{"name":"Sinfest","link":"http://sinfest.com/","start":3400,"dbfile":dbdir + "comicdb.sinfest.csv"},
116                 "soup_to_nutzcomicscom":{"name":"Soup to Nutz","link":'http://comics.com/soup_to_nutz/',"start":"2010-02-01","dbfile":dbdir + "comicdb.souptonutz.csv"},
117                 "speed_bumpcomicscom":{"name":"Speed Bump","link":'http://comics.com/speed_bump/',"start":"2010-02-01","dbfile":dbdir + "comicdb.speedbump.csv"},
118                 "spot_the_frogcomicscom":{"name":"Spot the Frog","link":'http://comics.com/spot_the_frog/',"start":"2010-02-01","dbfile":dbdir + "comicdb.spotthefrog.csv"},
119                 "state_of_the_unioncomicscom":{"name":"State of the Union","link":'http://comics.com/state_of_the_union/',"start":"2010-02-01","dbfile":dbdir + "comicdb.stateoftheunion.csv"},
120                 "strange_brewcomicscom":{"name":"Strange Brew","link":'http://comics.com/strange_brew/',"start":"2010-02-01","dbfile":dbdir + "comicdb.strangebrew.csv"},
121                 "tarzancomicscom":{"name":"Tarzan","link":'http://comics.com/tarzan_classics/',"start":"2010-02-01","dbfile":dbdir + "comicdb.tarzan.csv"},
122                 "thats_lifecomicscom":{"name":"That's Life","link":'http://comics.com/thats_life/',"start":"2010-02-01","dbfile":dbdir + "comicdb.thatslife.csv"},
123                 "the_barncomicscom":{"name":"The Barn","link":'http://comics.com/the_barn/',"start":"2010-02-01","dbfile":dbdir + "comicdb.the_barn.csv"},
124                 "the_born_losercomicscom":{"name":"The Born Loser","link":'http://comics.com/the_born_loser/',"start":"2010-02-01","dbfile":dbdir + "comicdb.thebornloser.csv"},
125                 "the_bucketscomicscom":{"name":"The Buckets","link":'http://comics.com/the_buckets/',"start":"2010-02-01","dbfile":dbdir + "comicdb.thebuckets.csv"},
126                 "the_dinette_setcomicscom":{"name":"The Dinette Set","link":'http://comics.com/the_dinette_set/',"start":"2010-02-01","dbfile":dbdir + "comicdb.thedinetteset.csv"},
127                 "the_grizzwellscomicscom":{"name":"The Grizzwells","link":'http://comics.com/the_grizzwells/',"start":"2010-02-01","dbfile":dbdir + "comicdb.thegrizzwells.csv"},
128                 "the_humble_stumblecomicscom":{"name":"The Humble Stumble","link":'http://comics.com/the_humble_stumble/',"start":"2010-02-01","dbfile":dbdir + "comicdb.thehumblestumble.csv"},
129                 "the_knight_lifecomicscom":{"name":"The Knight Life","link":'http://comics.com/the_knight_life/',"start":"2010-02-01","dbfile":dbdir + "comicdb.theknightlife.csv"},
130                 "the_meaning_of_lilacomicscom":{"name":"The Meaning of Lila","link":'http://comics.com/the_meaning_of_lila/',"start":"2010-02-01","dbfile":dbdir + "comicdb.themeaningoflila.csv"},
131                 "the_other_coastcomicscom":{"name":"The Other Coast","link":'http://comics.com/the_other_coast/',"start":"2010-02-01","dbfile":dbdir + "comicdb.theothercoast.csv"},
132                 "the_sunshine_clubcomicscom":{"name":"the Sunshine Club","link":'http://comics.com/the_sunshine_club/',"start":"2010-02-01","dbfile":dbdir + "comicdb.thesunshineclub.csv"},
133                 "unstrange_phenomenacomicscom":{"name":"Unstrange Phenomena","link":'http://comics.com/unstrange_phenomena/',"start":"2010-02-01","dbfile":dbdir + "comicdb.unstrangephenomena.csv"},
134                 "watch_your_headcomicscom":{"name":"Watch Your Head","link":'http://comics.com/watch_your_head/',"start":"2010-02-01","dbfile":dbdir + "comicdb.watchyourhead.csv"},
135                 "wizard_of_idcomicscom":{"name":"Wizard of Id","link":'http://comics.com/wizard_of_id/',"start":"2010-02-01","dbfile":dbdir + "comicdb.wizardofid.csv"},
136                 "working_dazecomicscom":{"name":"Working Daze","link":'http://comics.com/working_daze/',"start":"2010-02-01","dbfile":dbdir + "comicdb.workingdaze.csv"},
137                 "working_it_outcomicscom":{"name":"Working It Out","link":'http://comics.com/working_it_out/',"start":"2010-02-01","dbfile":dbdir + "comicdb.workingitout.csv"},
138                 "wulff":{"name":"Wulffmorgenthaler","link":"http://wulffmorgenthaler.com/","start":"edd3411b-96ca-4d93-bd5f-0cf1deb67c8a","dbfile":dbdir + "comicdb.wulff.csv"},
139                 "xkcd":{"name":"xkcd","link":"http://xkcd.org/","start":666,"dbfile":dbdir + "comicdb.xkcd.csv"},
140                 "zack_hillcomicscom":{"name":"Zack Hill","link":'http://comics.com/zack_hill/',"start":"2010-02-01","dbfile":dbdir + "comicdb.zackhill.csv"},
141
142
143
144                 }
145 defaults = {'width':480,'height':230}
146 #defaults = {'width':480,'height':240}
147 sizefile = "/home/user/.comic-widget/size.cfg"
148 previous = False
149 next = False
150
151
152 # handling of the comics
153 class ComicDb():
154         def __init__(self, comic):
155                 self.comic = comic
156                 self.start = comics[self.comic]["start"]
157                 self.dbfile = comics[self.comic]["dbfile"]
158
159                 #if db file exist, read it
160                 # if os.path.isfile(self.dbfile) == True:
161                 #       dbf = open(self.dbfile, 'r')
162                 # if not, create it.
163                 dbf = self.get_dbfile()
164                 dbr = csv.DictReader(dbf)
165                 self.db = []
166                 for row in dbr:
167                         self.db.insert(0,row)
168                 dbf.close()
169                 if len(self.db) == 0:
170                         self.refresh()
171                 self.currentcomic = 0
172
173
174
175         def get_dbfile(self):
176                 #if db file exist, read it
177                 print "fetching " + self.dbfile
178                 if os.path.isfile(self.dbfile) == True:
179                         print "found " + self.dbfile
180                         dbf = open(self.dbfile, 'r')
181                         return dbf
182                 # if not, copy it.
183                 else:
184                         print "file " + self.dbfile + " not found"
185                         if not os.path.exists(dbdir):
186                                 print "path not found: " + dbdir
187                                 try:
188                                         os.makedirs(dbdir)
189                                 except:
190                                         print "comic db creation failed on mkdir"
191                                         exit()
192                         try:
193                                 shutil.copyfile(basedbdir + "comicdb." + self.comic + ".csv", dbdir + "comicdb." + self.comic + ".csv")
194                         except:
195                                 print "comic db creation failed on copy"
196                                 print "creating new..."
197                                 dbf = open(self.dbfile, 'w')
198                                 dbf.write('comic,id,link,url,filename,title\n')
199                                 dbf.close()
200                                 
201                         if os.path.isfile(self.dbfile) == True:
202                                 dbf = open(self.dbfile, 'r')
203                                 return dbf
204                         else:
205                                 print "comic db creation failed after copy"
206
207
208         def get_stored(self):
209                 try:
210                         idf = open(self.dbfile + ".last", 'r')
211                         retval = idf.read()
212                         print "got stored index :" + str(retval)
213                         idf.close()
214                         return int(retval)
215                 except:
216                         return 0
217
218         def store_last(self, sid = 0):
219                 try:
220                         idf = open(self.dbfile + ".last", 'w')
221                         if sid > 0:
222                                 idf.write(str(sid))
223                         else:
224                                 idf.write(str(self.currentcomic))
225                         idf.close()
226                         return True
227                 except:                 
228                         return False
229
230
231         def get_comic(self):
232                 print str(self.currentcomic)
233                 if self.currentcomic < 0:
234                         self.currentcomic = 0
235                         if len(self.db) > 0:
236                                 fetchid = self.db[self.currentcomic]['id']
237                         else:
238                                 fetchid = comics[self.comic]['start']
239                         self.fetch_newer(self.comic, fetchid)
240                         self.refresh()
241                 if  len(self.db) < (self.currentcomic + 1):
242                         print "Empty db"
243                         self.currentcomic = len(self.db) - 1
244                         if len(self.db) > 0:
245                                 fetchid = self.db[self.currentcomic]['id']
246                         else:
247                                 fetchid = comics[self.comic]['start']
248                         self.fetch_earlier(self.comic, fetchid)
249                         self.refresh()
250                         self.currentcomic = len(self.db) - 1
251                         
252                 dbrow = self.db[self.currentcomic]
253                 filename = comiccache + self.comic + "/" + dbrow['filename']
254                 print filename + "\n"
255                 
256                 if os.path.isfile(filename):
257                         print "found, returning " + filename + "\n"
258                         return filename
259                 else:
260                         #fetch file
261                         print filename + " not found\nretrieving " + dbrow['url'] + "\n"
262                         if not os.path.exists(comiccache + self.comic + "/"):
263                                 print "create dir " + comiccache + self.comic + "/"
264                                 try:
265                                         os.makedirs(comiccache + self.comic + "/")
266                                         print "created dir"
267                                 except:
268                                         print "comic db creation failed on mkdir"
269                         try:
270                                 f = open(filename, "wb")
271                                 print "writing to " + filename
272                                 req = urllib2.Request(dbrow['url'])
273                                 req.add_header('Referer', dbrow['link'])
274                                 tmpimg = urllib2.urlopen(req)
275                                 f.write(tmpimg.read())
276                                 tmpimg = None
277                                 f.close()
278
279 #                               urllib.urlretrieve(dbrow['url'], filename)
280                         except:
281                                 if os.path.isfile(filename):
282                                         os.remove(filename)
283                         print "success\n"
284                         return filename
285
286         def get_current_row(self):
287                 return self.db[self.currentcomic]               
288
289         def get_link(self):
290                 print str(self.currentcomic)
291                 if self.currentcomic < 0:
292                         self.refresh()
293                         self.currentcomic = 0
294                 if  len(self.db) < (self.currentcomic + 1):
295                         self.currentcomic -= 1
296                 return self.db[self.currentcomic]['link']
297
298
299
300         def insert_row(self, irow):
301                 dbf = open(self.dbfile, 'a')
302                 dbw = csv.writer(dbf)
303                 dbw.writerow(irow)
304                 dbf.close()
305                 stored = self.get_stored()
306                 if stored > 0:
307                         self.store_last(stored + 1)
308
309         def insert_row_first(self, irow):
310                 dbf = open(self.dbfile, 'w')
311                 dbf.write('comic,id,link,url,filename,title\n')
312                 dbw = csv.writer(dbf)
313                 dbw.writerow(irow)
314                 dbf.close()
315                 dbf = open(self.dbfile, 'a')
316                 dbw = csv.DictWriter(dbf, ['comic','id','link','url','filename','title'])
317                 tmpdb = self.db
318                 tmpdb.reverse()
319                 for row in tmpdb:
320                         dbw.writerow(row)
321                 dbf.close()
322
323         def refresh(self):
324         #       if len(self.db) < 1:
325         #               self.currentcomic = -1
326         #               self.fetch_latest_std(self.comic, self.start)
327         #       elif self.currentcomic == 0 or self.currentcomic < 0:
328         #               self.fetch_latest_std(self.comic, self.db[0]['id'])
329         #       elif self.currentcomic == (len(self.db) - 1):
330         #               self.fetch_earlier(self.comic, self.db[self.currentcomic]['id'])
331                 dbf = open(self.dbfile, 'r')
332                 dbr = csv.DictReader(dbf)
333                 self.db = []
334                 for row in dbr:
335                         self.db.insert(0,row)
336                 dbf.close()
337                 if len(self.db) == 0:
338                         self.fetch_earlier(self.comic, self.start)
339                         dbf = open(self.dbfile, 'r')
340                         dbr = csv.DictReader(dbf)
341                         self.db = []
342                         for row in dbr:
343                                 self.db.insert(0,row)
344                         dbf.close()
345
346
347 # fetch earlier
348         def fetch_earlier(self, comic, earliest):
349                 print "fetch before, " + comic + " earliest"
350                 print comic[-9:]
351                 if comic == "cyanide" or comic == "wulff" or comic == "babyblues" or comic[-9:] == "comicscom":
352                         print "getting get_prev_id..."
353                         comicid = self.get_prev_id(comic,earliest)
354                         if not comicid:
355                                 print "already at first comic"
356                                 return
357                         print "got " + comicid + " as the one before current..."
358                 elif len(str(earliest)) == 10:
359                         # date id.
360                         dt = string.split(earliest, "-")
361                         d = datetime.date(int(dt[0]),int(dt[1]),int(dt[2]))
362                         earlier = d - datetime.timedelta( 1 )
363                         comicid = earlier.isoformat()
364                 else:
365                         comicid = int(earliest) - 1
366
367                 irow = self.get_irow(comic, comicid)
368                 if irow and irow[0] == "skip":
369                                 print "problem with this one, fetching " + str(irow[2]) + " instead."
370                                 irow = self.get_irow(comic, irow[2])
371
372                 if irow and len(irow) > 3:
373                         print "got irow: "
374                         print irow
375                         print "\ninserting...\n"
376                         self.insert_row_first([irow[0],irow[1],irow[2],irow[3],irow[4],irow[5]])
377                 else:
378                         print "No comic found at " + comicid
379
380
381
382
383
384         def fetch_newer(self, comic, newest):
385                 if comic == "cyanide" or comic == "wulff" or comic == "babyblues" or comic[-9:] == "comicscom":
386                         comicid = self.get_next_id(comic,newest)
387                         if not comicid:
388                                 print "already at last comic"
389                                 return
390                 elif len(newest) == 10:
391                         # date id.
392                         dt = string.split(newest, "-")
393                         d = datetime.date(int(dt[0]),int(dt[1]),int(dt[2]))
394                         newest = d + datetime.timedelta( 1 )
395                         comicid = newest.isoformat()
396                 else:
397                         comicid = int(newest) + 1
398
399                 irow = self.get_irow(comic, comicid)
400                 if irow and irow[0] == "skip":
401                                 print "problem with this one, fetching " + str(irow[1]) + " instead."
402                                 irow = self.get_irow(comic, irow[1])
403
404                 if irow and len(irow) > 3:
405                         print "got irow: "
406                         print irow
407                         print "\ninserting...\n"
408                         self.insert_row([irow[0],irow[1],irow[2],irow[3],irow[4],irow[5]])
409                 else:
410                         print "No comic found at " + str(comicid)
411
412
413
414
415         def fetch_latest_std(self, comic, latest):
416                 print "fetching new after " + str(comic) + " " + str(latest)
417                 next = False
418                 dateid = False
419                 if comic == 'cyanide':
420                         next = self.get_next_id(comic, latest)
421                         if not next:
422                                 return
423                         else:
424                                 comicid = next
425                 else: 
426                         if len(str(latest)) == 10:
427                                 # date id.
428                                 dateid = True
429                                 dt = string.split(latest, "-")
430                                 d = datetime.date(int(dt[0]),int(dt[1]),int(dt[2]))
431                                 newer = d + datetime.timedelta( 1 )
432                                 comicid = newer.isoformat()
433                         else:
434                                 comicid = int(latest) + 1
435
436                 if len(self.db) > 0:
437                         lasturl = self.db[0]['url']
438                 else:
439                         lasturl = "http"
440                 while True:
441                         irow = self.get_irow(comic, comicid)
442                         if irow:
443                                 print "got irow: " + str(irow)
444                                 if str(irow[0]) == 'skip':
445                                         print "skipping this one..."
446                                         next = int(irow[1])
447                                 else:
448                                         if irow[3] == lasturl:
449                                                 print "Looping the same, break break break!"
450                                                 break
451                                         lasturl = irow[3]
452                                         print "inserting..."
453                                         self.insert_row([irow[0],irow[1],irow[2],irow[3],irow[4],irow[5]])
454                                         if len(irow) > 6:
455                                                 next = irow[6]
456                                                 if not next:
457                                                         break
458                                 if dateid:
459                                         dt = string.split(comicid, "-")
460                                         d = datetime.date(int(dt[0]),int(dt[1]),int(dt[2]))
461                                         newer = d + datetime.timedelta( 1 )
462                                         comicid = newer.isoformat()
463                                 elif next:
464                                         comicid = next
465                                 else:
466                                         comicid += 1
467                         else:
468                                 break
469
470
471
472
473         def get_next_id(self, comic, number):
474                 if comic == 'babyblues':
475                         link = "http://www.babyblues.com/archive/index.php?formname=getstrip&GoToDay=" + str(number)
476                         print "link: " + link
477                         try:
478                                 f = urllib2.urlopen(link)
479                                 hcode = f.code
480                         except:
481                                 hcode = 404
482                         print "got hcode = " + str(hcode) + "\n"
483                         if (hcode != 200):
484                                 return False
485                         else:
486                                 print "checking next Babyblues date.."
487                                 s = f.read()
488                                 f.close()
489                                 # title:
490                                 splt = string.split(s, 'nextStripLink', 1)
491                                 if len(splt) < 2:
492                                         print "no 'prev' found"
493                                         return False
494                                 else:
495                                         next = splt[1][48:58]
496                                         print "got next: " + next
497
498                                         return next
499
500                 if comic == 'cyanide':
501                         link = "http://www.explosm.net/comics/" + str(number) + "/"
502                         print "link: " + link
503                         try:
504                                 f = urllib2.urlopen(link)
505                                 hcode = f.code
506                         except:
507                                 hcode = 404
508                         print "got hcode = " + str(hcode) + "\n"
509                         if (hcode != 200):
510                                 return False
511                         else:
512                                 # print "Cyanide & Happiness is unreliable, so we need to track next and prev"
513                                 s = f.read()
514                                 f.close()
515                                 # title:
516                                 splt = string.split(s, 'Previous</a> | <a href="/comics/', 1)
517                                 if len(splt) < 2:
518                                         print "no 'next' found"
519                                         return False
520                                 splt = string.split(splt[1], '/">Next >', 1)
521                                 if len(splt) < 2:
522                                         print "no 'next' found"
523                                         return False
524                                 else:
525                                         print "got next: " + splt[0]
526                                         return splt[0]  
527                 if comic == 'wulff':
528                         link = "http://wulffmorgenthaler.com/default.aspx?id=" + number
529                         print "link: " + link
530                         try:
531                                 f = urllib2.urlopen(link)
532                                 hcode = f.code
533                         except:
534                                 hcode = 404
535                         print "got hcode = " + str(hcode) + "\n"
536                         if (hcode != 200):
537                                 return False
538                         else:
539                                 s = f.read()
540                                 f.close()
541                                 # title:
542                                 splt = string.split(s, '<a href="/default.aspx?id=', 1)
543                                 if not splt[1][36:69] == '" id="ctl00_content_Strip1_aPrev"':
544                                         print "no previous found"
545                                         if not splt[1][36:69] == '" id="ctl00_content_Strip1_aNext"':
546                                                 print "no next found!"
547                                                 return False
548                                 else:
549                                         splt = string.split(splt[1], '<a href="/default.aspx?id=', 1)
550                                 if len(splt) < 2:
551                                         print "no next found! At newest comic!"
552                                         return False
553                                 if not splt[1][36:69] == '" id="ctl00_content_Strip1_aNext"':
554                                         print "no next found!"
555                                         return False
556                                 else:
557                                         return splt[1][:36]
558                 elif comic[-9:] == "comicscom":
559                         link = comics[comic]['link'] + str(number) + "/"
560                         print "link: " + link
561                         try:
562                                 f = urllib2.urlopen(link)
563                                 hcode = f.code
564                         except:
565                                 hcode = 404
566                         print "got hcode = " + str(hcode) + "\n"
567                         if (hcode != 200):
568                                 return False
569                         else:
570                                 s = f.read()
571                                 f.close()
572                                 return self.parse_comics_com(comic, s, 'next')
573
574
575
576
577
578
579         def get_prev_id(self, comic, number):
580                 if comic == 'babyblues':
581                         link = 'http://www.babyblues.com/archive/index.php?formname=getstrip&GoToDay=' + str(number)
582                         print "link: " + link
583                         try:
584                                 f = urllib2.urlopen(link)
585                                 hcode = f.code
586                         except:
587                                 hcode = 404
588                         print "got hcode = " + str(hcode) + "\n"
589                         if (hcode != 200):
590                                 return False
591                         else:
592                                 print "checking prev Babyblues date.."
593                                 s = f.read()
594                                 f.close()
595                                 # title:
596                                 splt = string.split(s, 'prevStripLink', 1)
597                                 if len(splt) < 2:
598                                         print "no 'prev' found"
599                                         exit()
600                                         return False
601                                 else:
602                                         prev = splt[1][48:58]
603                                         print "got previous: " + prev
604                                         return prev
605
606                 if comic == 'cyanide':
607                         link = "http://www.explosm.net/comics/" + str(number) + "/"
608                         print "link: " + link
609                         try:
610                                 f = urllib2.urlopen(link)
611                                 hcode = f.code
612                         except:
613                                 hcode = 404
614                         print "got hcode = " + str(hcode) + "\n"
615                         if (hcode != 200):
616                                 return False
617                         else:
618                                 print "Cyanide & Happiness is unreliable, so we need to track next and prev"
619                                 s = f.read()
620                                 f.close()
621                                 # title:
622                                 splt = string.split(s, 'First</a> | <a href="/comics/', 1)
623                                 if len(splt) < 2:
624                                         print "no 'prev' found"
625                                         return False
626                                 splt = string.split(splt[1], '/">< Previous', 1)
627                                 if len(splt) < 2 or len(splt[0]) > 5:
628                                         print "no 'next' found"
629                                         return False
630                                 else:
631                                         print "got previous: " + splt[0]
632                                         return splt[0]  
633                 elif comic == 'wulff':
634                         link = "http://wulffmorgenthaler.com/default.aspx?id=" + number
635                         print "link: " + link
636                         try:
637                                 f = urllib2.urlopen(link)
638                                 hcode = f.code
639                         except:
640                                 hcode = 404
641                         print "got hcode = " + str(hcode) + "\n"
642                         if (hcode != 200):
643                                 return False
644                         else:
645                                 s = f.read()
646                                 f.close()
647                                 # title:
648                                 splt = string.split(s, '<a href="/default.aspx?id=', 1)
649                                 if not splt[1][36:69] == '" id="ctl00_content_Strip1_aPrev"':
650                                         print splt[1][36:69]
651                                         print splt[1][:36]
652                                         print "no previous found"
653                                         return False
654                                 else:
655                                         return splt[1][:36]
656                 elif comic[-9:] == "comicscom":
657                         print "fetch prev, still in function..."
658                         link = comics[comic]['link'] + str(number) + "/"
659                         print "link: " + link
660                         try:
661                                 f = urllib2.urlopen(link)
662                                 hcode = f.code
663                         except:
664                                 hcode = 404
665                         print "got hcode = " + str(hcode) + "\n"
666                         if (hcode != 200):
667                                 return False
668                         else:
669                                 s = f.read()
670                                 f.close()
671                                 return self.parse_comics_com(comic, s, 'prev')
672
673
674
675
676         def get_irow(self, comic, number):
677                 dateid = False
678                 if len(str(number)) == 10:
679                         dateid = True
680                 else:
681                         if number < 0:
682                                 return False
683                         print "number is now: " + str(number) + "\n"
684                 if comic == 'xkcd':
685                         link = "http://xkcd.org/" + str(number) + "/"
686                 elif comic == 'sinfest':
687                         link = "http://www.sinfest.net/archive_page.php?comicID=" + str(number)
688                 elif comic == 'dilbert':
689                         link = "http://dilbert.com/" + str(number) + "/"
690                 elif comic == 'phd':
691                         link = "http://www.phdcomics.com/comics/archive.php?comicid=" + str(number)
692                 elif comic == 'cyanide':
693                         link = "http://www.explosm.net/comics/" + str(number) + "/"
694                 elif comic == 'wulff':
695                         link = "http://wulffmorgenthaler.com/default.aspx?id=" + str(number)
696                 elif comic == 'babyblues':
697                         link = "http://www.babyblues.com/archive/index.php?formname=getstrip&GoToDay=" + str(number)
698                 elif comic[-9:] == 'comicscom': 
699                         link = comics[comic]['link'] + str(number) + "/"
700                 else:
701                         return False
702
703                 print "link: " + link
704                 try:
705                         f = urllib2.urlopen(link)
706                         hcode = f.code
707                 except:
708                         hcode = 404
709                 print "got hcode = " + str(hcode) + "\n"
710                 if (hcode != 200):
711                         return False
712                 else:
713                         # Build db entry.
714                         # they look like: comic,id,link,url,filename,title
715                         # We already have comic, number/id and link
716
717                         if comic == 'xkcd':
718                                 s = f.read()
719                                 f.close()
720                                 # This should be done with regex but...
721                                 splt = string.split(s, 'png" title="', 1)
722                                 splt = string.split(splt[1], '" alt="', 1)
723                                 title = splt[0]
724                                 splt = string.split(splt[1], "<h3>Image URL (for hotlinking/embedding): ", 1)
725                                 splt = string.split(splt[1], "</h3>", 1)
726                                 url = splt[0]
727
728
729                         elif comic == 'sinfest':
730                                 s = f.read()
731                                 f.close()
732                                 splt = string.split(s, 'height="107"', 1)
733                                 splt = string.split(splt[1], '<img src="', 1)
734                                 splt = string.split(splt[1], '" alt="', 1)
735                                 url = splt[0]
736                                 if len(url) < 49:
737                                         print "Fake 404! Break break break!"
738                                         return False
739                                 splt = string.split(splt[1], '" border="0" />', 1)
740                                 title = splt[0]
741
742                         elif comic == 'dilbert':
743                                 s = f.read()
744                                 f.close()
745                                 splt = string.split(s, 'input type="hidden" name="PrintPath" value="', 1)
746                                 splt = string.split(splt[1], '" />', 1)
747                                 url = "http://dilbert.com" + splt[0]
748                                 if len(url) < 50:
749                                         print "Fake 404! Break break break!"
750                                         return False
751                                 title = ""
752
753                         elif comic == 'phd':
754                                 s = f.read()
755                                 f.close()
756                                 # title:
757                                 splt = string.split(s, '<title>PHD Comics: ', 1)
758                                 splt = string.split(splt[1], '</title>', 1)
759                                 title = splt[0];
760                                 splt = string.split(splt[1], '<td bgcolor=#FFFFFF align=center><img src=', 1)
761                                 splt = string.split(splt[1], ' align=top>', 1)
762                                 url = splt[0]
763                                 if len(url) < 49:
764                                         print "Fake 404! Break break break!"
765                                         return False
766
767                         elif comic == 'cyanide':
768                                 s = f.read()
769                                 f.close()
770                                 # title:
771                                 splt = string.split(s, ' First</a> | <a href="/comics/', 1)
772                                 if len(splt) < 2:
773                                         print "first comic?"
774                                         prev = False
775                                 else:
776                                         splt = string.split(splt[1], '/">< ', 1)
777                                         prev = splt[0];
778                                         print "got prev: " + prev
779                                 splt = string.split(s, 'Previous</a> | <a href="/comics/', 1)
780                                 if len(splt) < 2:
781                                         print "last comic?"
782                                         next = False
783                                 else:
784                                         splt = string.split(splt[1], '/">Next ></a>', 1)
785                                         if len(splt[0]) > 10:
786                                                 next = False
787                                         else:
788                                                 next = splt[0]
789                                                 print "got next: " + next
790
791                                 splt = string.split(s, '</tr><tr><td colspan=2>', 1)
792                                 if len(splt) < 2:
793                                         print "no comic?"
794                                         return False
795                                 splt = string.split(splt[1], ' <b>by <a href="', 1)
796                                 title = splt[0];
797                                 if len(title) > 10:
798                                         print "title wrong..."
799                                         return False
800                                 splt = string.split(splt[1], 'a daily webcomic" src="http://www.explosm', 1)
801                                 if len(splt) < 2:
802                                         print "a video? Try skipping"
803                                         return ['skip',next,prev]
804                                         
805                                 splt = string.split(splt[1], '">', 1)
806                                 url = "http://www.explosm" + splt[0]
807                                 splt2 = string.rsplit(url, "/", 1)
808                                 filename = splt2[1]
809                                 irow = [comic,number,link,url,filename,title,next,prev]
810                                 return irow
811
812
813                         elif comic == 'babyblues':
814                                 # babyblues is type .gif
815                                 s = f.read()
816                                 f.close()
817                                 splt = string.split(s, 'http://est.rbma.com/content/Baby_Blues?date=', 1)
818                                 flnm = splt[1][:8]
819                                 # check filename...
820                                 datesplt = string.split(number, "/")
821                                 flncheck = datesplt[2] + datesplt[0] + datesplt[1]
822                                 if not flnm == flncheck:
823                                         print "incorrect filename, end of line. Break break break!"
824                                         return False
825                                 url = 'http://est.rbma.com/content/Baby_Blues?date=' + flnm
826                                 title = number + " (2 weeks delay)"
827                                 filename = flnm + ".gif"
828                                 irow = [comic,number,link,url,filename,title]
829                                 return irow
830
831
832                         elif comic == 'wulff':
833                                 # wulf is type .gif
834                                 s = f.read()
835                                 f.close()
836                                 splt = string.split(s, '<img src="pics/dates/month/', 1)
837                                 if not splt[1][1:2] == ".":
838                                         title = splt[1][:2]
839                                 else:
840                                         title = "0" + splt[1][:1]
841                                 splt = string.split(splt[1], '<img src="pics/dates/day/', 1)
842                                 if not splt[1][1:2] == ".":
843                                         title = title + "-" + splt[1][:2]
844                                 else:
845                                         title = title + "-0" + splt[1][:1]
846                                 splt = string.split(splt[1], '<img src="pics/dates/year/', 1)
847                                 title = splt[1][:4] + "-" + title
848                                 # title done...
849                                 splt = string.split(splt[1], 'id="ctl00_content_Strip1_imgStrip" class="strip" src="striphandler.ashx?stripid=', 1)
850                                 number = splt[1][:36]
851                                 url = "http://wulffmorgenthaler.com/striphandler.ashx?stripid=" + number
852                                 filename = number + ".gif"
853                                 irow = [comic,number,link,url,filename,title]
854                                 return irow
855                         elif comic[-9:] == 'comicscom':
856                                 url = self.parse_comics_com(comic, f.read(), 'url') 
857                                 f.close()
858                                 title = number
859
860                         splt2 = string.rsplit(url, "/", 1)
861                         filename = splt2[1]
862                         try:
863                                 if filename == self.db[0]['filename']:
864                                         print "already exists! Break break break!"
865                                         return False
866                         except:
867                                 pass
868                         irow = [comic,number,link,url,filename,title]
869                         return irow
870
871
872         def parse_comics_com(self, comicname, source, get_what):
873                 #       rel="{StripID:309486, ComicID:36, Type:'Comic', DateStrip:'2010-02-06', URL_Comic: 'girls&sports', Link_Previous: '/girls&sports/2010-02-05/', Link_Next: '/girls&sports/2010-02-07/'}"
874                 if get_what == "url":
875                         splt = string.split(source, 'StripID:', 1)
876                         splt = string.split(splt[1], ', ComicID:', 1)
877                         url = "http://c0389161.cdn.cloudfiles.rackspacecloud.com/dyn/str_strip/" + splt[0] + ".full.gif"
878                         return url
879                 elif get_what == "next":
880                         splt = string.split(source, "Link_Next: '", 1)
881                         splt = string.split(splt[1], "'", 1)
882                         splt = string.split(splt[0], "/")
883                         if len(splt) < 3:
884                                 return False
885                         else:
886                                 
887                                 return splt[2]
888
889                 elif get_what == "prev":
890                         print "getting comics com prev: " + comicname
891                         splt = string.split(source, "Link_Previous: '", 1)
892                         splt = string.split(splt[1], "'", 1)
893                         splt = string.split(splt[0], "/")
894                         if len(splt) == 0:
895                                 return False
896                         else:
897                                 if len(splt[2]) == 10:
898                                         return splt[2]
899                                 else:
900                                         return False
901                 
902
903
904 # ------------UI
905
906 class ComicHomePlugin(hildondesktop.HomePluginItem):
907         # __gtype_name__ = 'ComicHomePlugin'
908         def __init__(self):
909                 hildondesktop.HomePluginItem.__init__(self)
910                 global supports_alpha
911                 self.set_settings(True)
912                 self.active_comics = self.get_active_comics()
913                 self.sizes = self.get_size_settings()
914                 self.new_width = self.sizes['width']
915                 self.new_height = self.sizes['height']
916                 self.connect("show-settings", self.show_options)
917                 self.osso_c = osso.Context("comic-widget", "0.3.0", False)
918                 self.osso_rpc = osso.Rpc(self.osso_c)
919                 self.keypointer = 0
920                 if len(self.active_comics) < 1:
921                         self.active_comics = ['xkcd']
922                 
923                 self.db = ComicDb(self.active_comics[self.keypointer])
924                 self.comicname = comics[self.active_comics[self.keypointer]]['name']
925                 self.set_name = "comicwidget"
926                 screen = self.get_screen()
927                 colormap = screen.get_rgba_colormap()
928                 if colormap == None:
929                         colormap = screen.get_rgb_colormap()
930                         supports_alpha = False
931                 else:
932                         supports_alpha = True
933                 self.set_colormap(colormap)
934                 self.set_app_paintable(True)
935                 #setup internal area
936                 self.set_size_request(self.sizes['width'], self.sizes['height'])
937                 self.imgvpos = 0;
938                 self.vbox = gtk.VBox()
939                 self.hbox = gtk.HBox()
940                 self.label = gtk.Label()
941                 self.label.set_alignment(xalign = 0, yalign = 0.5)
942                 self.label.set_use_markup(True)
943                 self.label.set_markup(self.get_markup())
944
945
946                 self.e_goweb = gtk.EventBox()
947                 self.e_goweb.set_name('goweb')
948                 self.e_goweb.set_size_request(self.sizes['width'] - 250, 48)
949                 # e_open is the eventbox for the image. Does nothing, but it's convenient to have it.
950                 # it will change to be a cairo thing when I have the time.
951                 self.e_open = gtk.EventBox()
952                 self.e_open.set_name('open')
953                 self.e_switch = gtk.EventBox()
954                 self.e_switch.set_name('switch')
955                 self.e_switch.set_size_request(48, 48)
956                 self.e_next = gtk.EventBox()
957                 self.e_next.set_name('next')
958                 self.e_next.set_size_request(48, 48)
959                 self.e_prev = gtk.EventBox()
960                 self.e_prev.set_name('prev')
961                 self.e_prev.set_size_request(48, 48)
962                 self.e_up = gtk.EventBox()
963                 self.e_up.set_name('up')
964                 self.e_up.set_size_request(48, 48)
965                 self.e_down = gtk.EventBox()
966                 self.e_down.set_name('down')
967                 self.e_down.set_size_request(48, 48)
968                 self.comic_image = self.get_resized_pixmap(self.db.get_comic(), self.imgvpos)
969                 self.comic_image.show()
970                 
971
972                 # Preload images into a dictionary, so that we can access them by the names of the eventboxes:
973
974                 self.images = {'up0':cairo.ImageSurface.create_from_png(imagedir + "up0-48x48.png"),
975                                         'up1':cairo.ImageSurface.create_from_png(imagedir + "up1-48x48.png"),
976                                         'down0':cairo.ImageSurface.create_from_png(imagedir + "down0-48x48.png"),
977                                         'down1':cairo.ImageSurface.create_from_png(imagedir + "down1-48x48.png"),
978                                         'next0':cairo.ImageSurface.create_from_png(imagedir + "next0-48x48.png"),
979                                         'next1':cairo.ImageSurface.create_from_png(imagedir + "next1-48x48.png"),
980                                         'prev0':cairo.ImageSurface.create_from_png(imagedir + "prev0-48x48.png"),
981                                         'prev1':cairo.ImageSurface.create_from_png(imagedir + "prev1-48x48.png"),
982                                         'switch0':cairo.ImageSurface.create_from_png(imagedir + "switch0-48x48.png"),
983                                         'switch1':cairo.ImageSurface.create_from_png(imagedir + "switch1-48x48.png"),
984                                         }
985
986
987
988                 self.e_goweb.add(self.label)
989                 self.e_goweb.set_events(gtk.gdk.BUTTON_RELEASE_MASK)
990                 self.e_goweb.connect("button-release-event", self.view_comic)
991
992                 self.e_open.add(self.comic_image)
993
994                 # self.e_switch.add(self.switch)
995                 self.e_switch.set_events(gtk.gdk.BUTTON_PRESS_MASK|gtk.gdk.BUTTON_RELEASE_MASK|gtk.gdk.LEAVE_NOTIFY)
996                 self.e_switch.connect("button-press-event", self.button_press)
997                 self.e_switch.connect("button-release-event", self.button_release)
998                 self.e_switch.connect("leave-notify-event", self.button_release)
999
1000
1001                 # self.e_next.add(self.next)
1002                 self.e_next.set_events(gtk.gdk.BUTTON_PRESS_MASK|gtk.gdk.BUTTON_RELEASE_MASK|gtk.gdk.LEAVE_NOTIFY)
1003                 self.e_next.connect("button-press-event", self.button_press)
1004                 self.e_next.connect("button-release-event", self.button_release)
1005                 self.e_next.connect("leave-notify-event", self.button_release)
1006
1007                 #self.e_prev.add(self.prev)
1008                 self.e_prev.set_events(gtk.gdk.BUTTON_PRESS_MASK|gtk.gdk.BUTTON_RELEASE_MASK|gtk.gdk.LEAVE_NOTIFY)
1009                 self.e_prev.connect("button-press-event", self.button_press)
1010                 self.e_prev.connect("button-release-event", self.button_release)
1011                 self.e_prev.connect("leave-notify-event", self.button_release)
1012
1013                 #self.e_up.add(self.up)
1014                 self.e_up.set_events(gtk.gdk.BUTTON_PRESS_MASK|gtk.gdk.BUTTON_RELEASE_MASK|gtk.gdk.LEAVE_NOTIFY)
1015                 self.e_up.connect("button-press-event", self.button_press)
1016                 self.e_up.connect("button-release-event", self.button_release)
1017                 self.e_up.connect("leave-notify-event", self.button_release)
1018                 
1019
1020                 #self.e_down.add(self.down)
1021                 self.e_down.set_events(gtk.gdk.BUTTON_PRESS_MASK|gtk.gdk.BUTTON_RELEASE_MASK|gtk.gdk.LEAVE_NOTIFY)
1022                 self.e_down.connect("button-press-event", self.button_press)
1023                 self.e_down.connect("button-release-event", self.button_release)
1024                 self.e_down.connect("leave-notify-event", self.button_release)
1025
1026                 self.vbox.pack_start(self.e_open,False,False,0)
1027                 self.vbox.pack_end(self.hbox,False,False,0)
1028
1029                 self.hbox.pack_start(self.e_switch,False,False,0)
1030                 self.hbox.pack_start(self.e_goweb,False,False,5)
1031                 self.hbox.pack_end(self.e_next,False,False,0)
1032                 self.hbox.pack_end(self.e_prev,False,False,0)
1033                 self.hbox.pack_end(self.e_down,False,False,0)
1034                 self.hbox.pack_end(self.e_up,False,False,0)
1035                 self.vbox.show_all()
1036                 self.add(self.vbox)
1037
1038
1039
1040         # **************** Cairo draw functions ***************
1041
1042         def realize(self, widget):
1043                 global supports_alpha
1044
1045                 # To check if the display supports alpha channels, get the colormap
1046                 screen = self.get_screen()
1047                 colormap = screen.get_rgba_colormap()
1048                 if colormap == None:
1049                         print 'Your screen does not support alpha channels!'
1050                         colormap = screen.get_rgb_colormap()
1051                         supports_alpha = False
1052                 else:
1053                 #      print 'Your screen supports alpha channels!'
1054                         supports_alpha = True
1055
1056                 # Now we have a colormap appropriate for the screen, use it
1057                 self.set_colormap(colormap)
1058
1059                 return False
1060
1061         def do_expose_event(widget, event):
1062                 cr = widget.window.cairo_create()
1063                 widget.draw(widget.e_up, 0)
1064                 widget.draw(widget.e_down, 0)
1065                 widget.draw(widget.e_prev,0)
1066                 widget.draw(widget.e_next, 0)
1067                 widget.draw(widget.e_switch, 0)
1068 #               widget.writeit(widget.e_goweb, "asdf")
1069                 cr.set_operator(cairo.OPERATOR_OVER)
1070                 region = gtk.gdk.region_rectangle(event.area)
1071                 cr.region(region)
1072                 bg_color=gtk.gdk.color_parse('#000000')
1073                 if supports_alpha:
1074                         cr.set_source_rgba (0.0, 0.0, 0.0, 0.5)
1075                 else:
1076                         cr.set_source_rgb (0.0, 0.0, 0.0)
1077                         
1078                 cr.fill_preserve()
1079                 return False
1080
1081         # Function that draws a button preloaded in the images dictionary.
1082         def draw(self, target, postfix):
1083                 cr_e = target.window.cairo_create()
1084                 cr_e.set_source_rgba(0.0, 0.0, 0.0, 0.5) # Transparent
1085                 cr_e.set_operator(cairo.OPERATOR_SOURCE)
1086                 cr_e.paint()
1087                 cr_e.set_operator(cairo.OPERATOR_OVER)
1088                 cr_e.set_source_surface(self.images[target.get_name() + str(postfix)], 0, 0)
1089                 cr_e.paint()
1090
1091         # ********** Event handlers *************
1092
1093
1094         # Most events happen on release, so I moved all of them into the same event handler.
1095         def button_release(self, widget, event):
1096                 if event.type == gtk.gdk.BUTTON_RELEASE:
1097                         func = widget.get_name()
1098                         print "pressed: " + func
1099                         if func == 'up':
1100                                 self.e_open.remove(self.comic_image)
1101                                 self.imgvpos = self.imgvpos - ((self.sizes['height'] - 48) / 2.1)
1102                                 if self.imgvpos < 0:
1103                                         self.imgvpos = 0
1104                                 self.comic_image = self.get_resized_pixmap(self.db.get_comic(), self.imgvpos)
1105                                 self.e_open.add(self.comic_image)
1106                                 self.e_open.show_all()
1107
1108                         elif func == 'down':
1109                                 self.e_open.remove(self.comic_image)
1110                                 self.imgvpos = self.imgvpos + ((self.sizes['height'] - 48) / 2.1)
1111                                 self.comic_image = self.get_resized_pixmap(self.db.get_comic(), self.imgvpos)
1112                                 self.e_open.add(self.comic_image)
1113                                 self.e_open.show_all()
1114                         
1115                         elif func == 'next':
1116                                 self.db.currentcomic -= 1
1117                                 self.imgvpos = 0
1118                                 self.e_open.remove(self.comic_image)
1119                                 self.comic_image = self.get_resized_pixmap(self.db.get_comic(), self.imgvpos)
1120                                 self.e_open.add(self.comic_image)
1121                                 self.e_open.show_all()
1122                                 self.e_goweb.remove(self.label)
1123                                 titl = str(self.db.db[self.db.currentcomic]['title'])
1124                                 if len(titl) > 22:
1125                                         titl = titl[:19] + "..."
1126                                 self.label.set_markup(self.get_markup())
1127                                 self.e_goweb.add(self.label)
1128                                 self.e_goweb.show_all()
1129
1130                         elif func == 'prev':
1131                                 self.db.currentcomic += 1
1132                                 self.imgvpos = 0
1133                                 self.e_open.remove(self.comic_image)
1134                                 self.comic_image = self.get_resized_pixmap(self.db.get_comic(), self.imgvpos)
1135                                 self.e_open.add(self.comic_image)
1136                                 self.e_open.show_all()
1137                                 self.e_goweb.remove(self.label)
1138                                 titl = str(self.db.db[self.db.currentcomic]['title'])
1139                                 if len(titl) > 22:
1140                                         titl = titl[:19] + "..."
1141                                 self.label.set_markup(self.get_markup())
1142                                 self.e_goweb.add(self.label)
1143                                 self.e_goweb.show_all()
1144
1145                         elif func == 'switch':
1146                                 # Check if store needed..
1147                                 if not self.db.currentcomic == 0 and not self.db.currentcomic == (len(self.db.db) - 1):
1148                                         print "Storing location " + str(self.db.currentcomic)
1149                                         if self.db.store_last():
1150                                                 print "stored successfully"
1151                                         else:
1152                                                 print "store failed"
1153                                  
1154                                 self.active_comics = self.get_active_comics()
1155                                 # print "closing log"
1156                                 #sys.stdout.close()
1157                                 #sys.stdout = sys.__stdout__
1158                                 #sys.stderr.close()
1159                                 #sys.stderr = sys.__stderr__
1160                                 print "active comics: " + str(self.active_comics)
1161                                 self.keypointer = (self.keypointer + 1) % len(self.active_comics)
1162                                 self.imgvpos = 0
1163                                 self.db = []
1164                                 print "switching to " + self.active_comics[self.keypointer]
1165                                 self.comicname = comics[self.active_comics[self.keypointer]]['name']
1166                                 self.db = ComicDb(self.active_comics[self.keypointer])
1167                                 self.e_open.remove(self.comic_image)
1168                                 self.comic_image = self.get_resized_pixmap(self.db.get_comic(), self.imgvpos)
1169                                 self.e_goweb.remove(self.label)
1170                                 titl = str(self.db.db[self.db.currentcomic]['title'])
1171                                 if len(titl) > 22:
1172                                         titl = titl[:19] + "..."
1173                                 self.label.set_markup(self.get_markup())
1174                                 self.e_goweb.add(self.label)
1175                                 self.e_goweb.show_all()
1176                                 self.e_open.add(self.comic_image)
1177                                 self.e_open.show_all()  
1178
1179                         else:
1180                                 return False                    
1181                 self.draw(widget, "0")
1182
1183         # this one only switches to pressed button image
1184         def button_press(self, widget, event):
1185                 if not event.type == gtk.gdk.BUTTON_PRESS:
1186                         return False
1187                 self.draw(widget, "1")
1188
1189         # this one cancels a button press when pointer is moved out from it after press.
1190         def button_out(self, widget, event):
1191                 if not event.type == gtk.gdk.BUTTON_PRESS:
1192                         return False
1193                 self.draw(widget, "0")
1194
1195         # no fancy cairo stuff here. simply launches url in browser.
1196         def view_comic(self, widget, event):
1197                 if not event.type == gtk.gdk.BUTTON_RELEASE:
1198                         return False
1199                 link = self.db.get_link()
1200                 self.osso_rpc.rpc_run_with_defaults("osso_browser", "open_new_window", (link,))
1201
1202
1203
1204         # this function modifies the image to fit the widget and then returns it.
1205
1206         def get_resized_pixmap(self, filename, vpos):
1207                 print "vpos: " + str(vpos)
1208                 
1209                 width = int(self.sizes['width'])
1210                 height = int(self.sizes['height'])
1211                 picwidth = width - 2
1212                 maxheight = height - 48
1213
1214                 pixbuf = gtk.gdk.pixbuf_new_from_file(filename)
1215                 parent_buf = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, pixbuf.get_has_alpha(), 8, width, maxheight)
1216                 parent_buf.fill(0xffffffff)
1217                 retimg = gtk.Image()
1218                 # get correct width/height
1219                 new_height = 1
1220                 new_width = picwidth
1221                 new_height = int((float(picwidth) / pixbuf.get_width()) * pixbuf.get_height())
1222                 scaled_buf = pixbuf.scale_simple(new_width,new_height,gtk.gdk.INTERP_BILINEAR)
1223                 print "scaled height: " + str(scaled_buf.get_height())
1224                 if scaled_buf.get_height() > maxheight:
1225                         if scaled_buf.get_height() - (vpos + maxheight) < 0:
1226                                 vpos = scaled_buf.get_height() - maxheight
1227                         scaled_buf.copy_area(0,vpos,picwidth,maxheight,parent_buf,1,0)
1228                         # parent_buf.composite(scaled_buf, 0, 0, 478, maxheight, 0, 0, 478, maxheight, gtk.gdk.INTERP_BILINEAR, 0)
1229                         self.imgvpos = vpos
1230                 else:
1231                         tmpy = maxheight - scaled_buf.get_height()
1232                         if tmpy > 0:
1233                                 tmpy = tmpy / 2
1234
1235                         scaled_buf.copy_area(0,0,picwidth,scaled_buf.get_height(),parent_buf,1,tmpy)
1236                         self.imgvpos = 0
1237 #               test = parent_buf.render_pixmap_and_mask(0)
1238 #               parent_buf.add_alpha(True,chr(255),chr(255),chr(255))
1239                 retimg.set_from_pixbuf(parent_buf)
1240                 print retimg.get_pixel_size()
1241                 print "vpos after fixing image: " + str(self.imgvpos)
1242                 return retimg
1243
1244         def screen_changed(self, widget, old_screen=None):
1245                 global supports_alpha
1246
1247                 # To check if the display supports alpha channels, get the colormap
1248                 screen = self.get_screen()
1249                 colormap = screen.get_rgba_colormap()
1250                 if colormap == None:
1251                         print 'Your screen does not support alpha channels!'
1252                         colormap = screen.get_rgb_colormap()
1253                         supports_alpha = False
1254                 else:
1255                 #      print 'Your screen supports alpha channels!'
1256                         supports_alpha = True
1257
1258                 # Now we have a colormap appropriate for the screen, use it
1259                 self.set_colormap(colormap)
1260
1261                 return False
1262
1263
1264         def get_active_comics(self):
1265                 print "get list"
1266
1267                 if os.path.isfile(activecomics) == True:
1268                         print "found " + activecomics
1269                         dbf = open(activecomics, 'r')
1270                         dbr = csv.reader(dbf)
1271                         try:
1272                                 active = dbr.next()
1273                         except:
1274                                 active = []
1275                         dbf.close()
1276                         return active
1277                 # if not, copy it.
1278                 else:
1279                         print "file " + activecomics + " not found"
1280                         if not os.path.exists(dbdir):
1281                                 print "path not found: " + dbdir
1282                                 try:
1283                                         os.makedirs(dbdir)
1284                                 except:
1285                                         print "settings dir creation failed. Exiting."
1286                                         exit()
1287                         try:
1288 #                               dbf = file(activecomics, 'w')
1289 #                               dbf.close()
1290                                 dbf = open(activecomics, 'w')
1291                         except:
1292                                 print "error storing settings"
1293                                 exit()
1294                         dbw = csv.writer(dbf)
1295                         dbw.writerow(defaultcomics)
1296                         dbf.close()
1297                         ret = defaultcomics
1298                         return ret
1299
1300                 
1301         def get_markup(self):
1302                 if len(self.comicname + " " + str(self.db.db[self.db.currentcomic]['id'])) < 20:
1303                         return '<span size="12000" face="arial"> <b>' + self.comicname + '</b> ' + str(self.db.db[self.db.currentcomic]['id']) + '\n ' + str(self.db.db[self.db.currentcomic]['title']) + '</span>'
1304                 else:
1305                         return '<span size="12000" face="arial"> <b>' + self.comicname + '</b>' + '\n ' + str(self.db.db[self.db.currentcomic]['title']) + '</span>'
1306
1307                 
1308                 #check if settings file exists
1309
1310                 #if not, write defaults
1311
1312         def goto_comic(self, index):
1313                 self.db.currentcomic = index
1314                 self.e_open.remove(self.comic_image)
1315                 self.comic_image = self.get_resized_pixmap(self.db.get_comic(), self.imgvpos)
1316                 self.e_open.add(self.comic_image)
1317                 self.e_open.show_all()
1318                 self.e_goweb.remove(self.label)
1319                 titl = str(self.db.db[self.db.currentcomic]['title'])
1320                 if len(titl) > 22:
1321                         titl = titl[:19] + "..."
1322                 self.label.set_markup(self.get_markup())
1323                 self.e_goweb.add(self.label)
1324                 self.e_goweb.show_all()
1325         
1326 # ************************* OPTION DIALOGS ********************************
1327
1328         def show_options(self, widget):
1329                 print "loading options dialog"
1330                 dialog = gtk.Dialog("Comic Widget", None, gtk.DIALOG_DESTROY_WITH_PARENT)
1331
1332                 about_button = hildon.Button(gtk.HILDON_SIZE_AUTO_WIDTH | gtk.HILDON_SIZE_FINGER_HEIGHT, hildon.BUTTON_ARRANGEMENT_VERTICAL)
1333                 about_button.set_text("About", "See Author, Copyright and License information")
1334                 about_button.set_alignment(0,0,0,0)
1335                 about_button.connect("clicked", self.show_about)
1336
1337                 comics_button = hildon.Button(gtk.HILDON_SIZE_AUTO_WIDTH | gtk.HILDON_SIZE_FINGER_HEIGHT, hildon.BUTTON_ARRANGEMENT_VERTICAL)
1338                 comics_button.set_text("Comics", "Choose which comics to view")
1339                 comics_button.set_alignment(0,0,0,0)
1340                 comics_button.connect("clicked", self.show_comics)
1341
1342                 navfirst_button = hildon.Button(gtk.HILDON_SIZE_AUTO_WIDTH | gtk.HILDON_SIZE_FINGER_HEIGHT, hildon.BUTTON_ARRANGEMENT_VERTICAL)
1343                 navfirst_button.set_text("Go to earliest", "Jump to the earliest cached comic")
1344                 navfirst_button.set_alignment(0,0,0,0)
1345                 navfirst_button.connect("clicked", self.show_nav, "oldest")
1346
1347                 navlast_button = hildon.Button(gtk.HILDON_SIZE_AUTO_WIDTH | gtk.HILDON_SIZE_FINGER_HEIGHT, hildon.BUTTON_ARRANGEMENT_VERTICAL)
1348                 navlast_button.set_text("Go to latest", "Jump to the latest cached comic")
1349                 navlast_button.set_alignment(0,0,0,0)
1350                 navlast_button.connect("clicked", self.show_nav, "newest")
1351
1352                 navstored_button = hildon.Button(gtk.HILDON_SIZE_AUTO_WIDTH | gtk.HILDON_SIZE_FINGER_HEIGHT, hildon.BUTTON_ARRANGEMENT_VERTICAL)
1353                 navstored_button.set_text("Go to last visited", "Jump to where you were before you switched comics")
1354                 navstored_button.set_alignment(0,0,0,0)
1355                 navstored_button.connect("clicked", self.show_nav, "stored")
1356
1357                 # size_button = hildon.Button(gtk.HILDON_SIZE_AUTO_WIDTH | gtk.HILDON_SIZE_FINGER_HEIGHT, hildon.BUTTON_ARRANGEMENT_VERTICAL)
1358                 # size_button.set_text("Change size", "Change the size of the widget")
1359                 # size_button.set_alignment(0,0,0,0)
1360                 # size_button.connect("clicked", self.show_size)
1361
1362
1363
1364                 print "adding buttons to dialog, starting with comics"
1365                 dialog.vbox.pack_start(navstored_button, True, True, 0)
1366                 dialog.vbox.pack_start(navfirst_button, True, True, 0)
1367                 dialog.vbox.pack_start(navlast_button, True, True, 0)
1368                 dialog.vbox.pack_start(comics_button, True, True, 0)
1369                 print "adding about button"
1370                 dialog.vbox.pack_start(about_button, True, True, 0)
1371                 # dialog.vbox.pack_start(size_button, True, True, 0)
1372                 print "show!"
1373                 dialog.show_all()
1374                 dialog.run()
1375                 dialog.destroy()
1376
1377         def show_nav(self, widget, goto):
1378                 if goto == "stored":
1379                         print "look for stored file"
1380                         self.goto_comic(self.db.get_stored())
1381                 elif goto == "newest":
1382                         self.goto_comic(0)
1383                 elif goto == "oldest":
1384                         self.goto_comic(len(self.db.db) - 1)
1385         def show_about(self, widget):
1386                 print "in about dialog"
1387                 dialog = gtk.AboutDialog()
1388                 dialog.set_title("About")
1389                 dialog.set_name("Comic widget")
1390                 dialog.set_version(APP_VERSION)
1391                 dialog.set_copyright("Copyright 2010 Marcus Wikstrom")
1392                 dialog.set_authors(["Marcus Wikstrom <mece@ovi.com>\nLogo by Martin Wikstrom\n\nSpecial thanks to all the great python developers on t.m.o who share their code, and the helpful wizards on #maemo."])
1393                 dialog.set_logo(gtk.gdk.pixbuf_new_from_file("/opt/comic-widget/images/icon2-64x64.png"))
1394                 dialog.set_comments("Silly rabbit, tricks are for kids.")
1395                 dialog.set_license("""This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License. <http://www.gnu.org/licenses/>.""")
1396                 dialog.set_wrap_license(True)
1397                 dialog.show_all()
1398                 dialog.run()
1399                 dialog.destroy()
1400
1401         def show_comics(self, widget, data = None):
1402                 print "in comics dialog! yay!"
1403                 dialog = gtk.Dialog("Choose comics", None, gtk.DIALOG_DESTROY_WITH_PARENT | gtk.DIALOG_NO_SEPARATOR)
1404                 comiclist = comics.keys()
1405                 comiclist.sort()
1406                 buttonlist = {}
1407                 self.connlist = {}
1408                 self.liststore = gtk.ListStore(str,str,bool)
1409                 for comicid in comiclist:
1410                         active = False
1411                         for acomic in self.active_comics:
1412                                 if acomic == comicid:
1413                                         active = True
1414                                         break
1415                         if active:
1416                                 self.liststore.append(["* " + comics[comicid]['name'],comicid, active])
1417                         else:
1418                                 self.liststore.append(["  " + comics[comicid]['name'],comicid, active])
1419                 self.treeview = hildon.GtkTreeView(gtk.HILDON_UI_MODE_EDIT)
1420                 self.treeview.set_model(self.liststore)
1421                 self.treeview.set_reorderable(True)
1422                 tvcolumn = gtk.TreeViewColumn('Column 0')
1423                 self.treeview.append_column(tvcolumn)
1424                 cell = gtk.CellRendererText()
1425                 tvcolumn.pack_start(cell, True)
1426                 tvcolumn.add_attribute(cell, 'text', 0)
1427
1428                 ts = hildon.PannableArea()
1429         
1430                 ts.set_size_request(-1, 280)
1431                 ts.add(self.treeview)
1432                 selection = self.treeview.get_selection()
1433
1434                 dialog.vbox.pack_start(ts,True,True,0)
1435                 dialog.show_all()
1436                 selection.connect("changed", self.pick_comic, comiclist)
1437                 dialog.run()
1438                 dialog.destroy()
1439
1440         def pick_comic(self, widget, data):
1441                 selected = widget.get_selected()
1442                 if selected == None:
1443                         return False
1444                 
1445                 print selected[0].get_value(selected[1],0) + ", " + selected[0].get_value(selected[1],1) + ", " + str(selected[0].get_value(selected[1],2))
1446                 if selected[0].get_value(selected[1],2):
1447                         self.remove_comic(selected[0].get_value(selected[1],1))
1448                         splt = selected[0].get_value(selected[1],0)[1:]
1449                         selected[0].set_value(selected[1],0," " + splt)
1450                         selected[0].set_value(selected[1],2,False)
1451                 else:
1452                         self.add_comic(selected[0].get_value(selected[1],1))
1453                         splt = selected[0].get_value(selected[1],0)[1:]
1454                         selected[0].set_value(selected[1],0,"*" + splt)
1455                         selected[0].set_value(selected[1],2,True)
1456
1457                                 
1458         def add_comic(self, comicid):
1459                 if os.path.isfile(activecomics) == True:
1460                         print "added " + comicid + " to " + str(self.active_comics)
1461                         try:
1462                                 found = self.active_comics.index(comicid)
1463                         except:
1464                                 self.active_comics.append(comicid)
1465                         dbf = open(activecomics, 'w')
1466                         dbw = csv.writer(dbf)
1467                         dbw.writerow(self.active_comics)
1468                         dbf.close()
1469
1470         def remove_comic(self, comicid):
1471                 if os.path.isfile(activecomics) == True:
1472                         print "removing " + comicid + " from " + str(self.active_comics)
1473                         try:
1474                                 del self.active_comics[self.active_comics.index(comicid)]
1475                         except:
1476                                 pass
1477                         dbf = open(activecomics, 'w')
1478                         dbw = csv.writer(dbf)
1479                         dbw.writerow(self.active_comics)
1480                         dbf.close()
1481
1482
1483         def get_size_settings(self):
1484                 # defaults = {'width':480,'height':230}
1485                 # options: w 798 700 600 500 480 400
1486                 # options: h 420 360 310 270 240 200
1487                 print "checking to see if config file is available"
1488                 if os.path.isfile(sizefile) == True:
1489                         print "found " + sizefile
1490                         dbf = open(sizefile, 'r')
1491                         dbr = csv.reader(dbf)
1492                         try:
1493                                 cfg = dbr.next()
1494                         except:
1495                                 dbf.close()
1496                                 print "empty config file"
1497                                 return defaults
1498                         dbf.close()
1499                         
1500                         sizes = {'width':int(cfg[0]),'height':int(cfg[1])}
1501                         if sizes['width'] > 798:
1502                                 sizes['width'] = 798
1503                         if sizes['width'] < 400:
1504                                 sizes['width'] = 400
1505                         if sizes['height'] > 420:
1506                                 sizes['height'] = 420
1507                         if sizes['height'] < 200:
1508                                 sizes['height'] = 200
1509                         
1510                         return sizes
1511                         
1512                         
1513                 # if not, copy it.
1514                 else:
1515                         print "no config file"
1516                         return defaults
1517                 
1518 hd_plugin_type = ComicHomePlugin
1519
1520
1521 if __name__ == "__main__":
1522         import gobject
1523         gobject.type_register(hd_plugin_type)
1524         obj = gobject.new(hd_plugin_type, plugin_id="plugin_id")
1525         obj.show_all()
1526         gtk.main()