minor bug fix, changed timeout, avoid broken files
[comic-widget] / src / usr / lib / hildon-desktop / comicwidget.py
index 5838299..01fa400 100644 (file)
@@ -12,6 +12,9 @@ import cairo
 import datetime
 import shutil
 import sys
+import socket
+
+socket.setdefaulttimeout(10)
 
 supports_alpha = False
 
@@ -22,7 +25,7 @@ supports_alpha = False
 
 # constants. dbfile is the location of the csv
 # comiccache is the location of the images
-APP_VERSION = "0.3.2"
+APP_VERSION = "0.3.4-2"
 
 basedbdir = "/opt/comic-widget/db/"
 imagedir = "/opt/comic-widget/images/"
@@ -33,9 +36,13 @@ comics = {"xkcd":{"name":"xkcd","link":"http://xkcd.org/","start":666,"dbfile":d
                "sinfest":{"name":"Sinfest","link":"http://sinfest.com/","start":3400,"dbfile":dbdir + "comicdb.sinfest.csv"},
                "phd":{"name":"PHD Comics","link":"http://www.phdcomics.com/","start":1240,"dbfile":dbdir + "comicdb.phd.csv"},
                "dilbert":{"name":"Dilbert","link":"http://dilbert.com/","start":"2009-01-01","dbfile":dbdir + "comicdb.dilbert.csv"},
-               "cyanide":{"name":"Cyanide&Happiness","link":"http://explosm.com/","start":"1920","dbfile":dbdir + "comicdb.cyanide.csv"},
+               "cyanide":{"name":"Cyanide and Happiness","link":"http://explosm.com/","start":"1920","dbfile":dbdir + "comicdb.cyanide.csv"},
+               "wulff":{"name":"Wulffmorgenthaler","link":"http://wulffmorgenthaler.com/","start":"edd3411b-96ca-4d93-bd5f-0cf1deb67c8a","dbfile":dbdir + "comicdb.wulff.csv"},
+
                }
-defaults = {}
+defaults = {'width':480,'height':230}
+#defaults = {'width':480,'height':240}
+sizefile = "/home/user/.comic-widget/size.cfg"
 previous = False
 next = False
 
@@ -133,7 +140,12 @@ class ComicDb():
                                        print "created dir"
                                except:
                                        print "comic db creation failed on mkdir"
-                       urllib.urlretrieve(dbrow['url'], filename)
+                       try:
+
+                               urllib.urlretrieve(dbrow['url'], filename)
+                       except:
+                               if os.path.isfile(filename):
+                                       os.remove(filename)
                        print "success\n"
                        return filename
 
@@ -190,8 +202,11 @@ class ComicDb():
 # fetch earlier
        def fetch_earlier(self, comic, earliest):
                print "fetch before, " + comic + " earliest"
-               if comic == "cyanide":
+               if comic == "cyanide" or comic == "wulff":
                        comicid = self.get_prev_id(comic,earliest)
+                       if not comicid:
+                               print "already at first comic"
+                               return
                        print "got " + comicid + " as the one before current..."
                elif len(earliest) == 10:
                        # date id.
@@ -220,8 +235,11 @@ class ComicDb():
 
 
        def fetch_newer(self, comic, newest):
-               if comic == "cyanide":
+               if comic == "cyanide" or comic == "wulff":
                        comicid = self.get_next_id(comic,newest)
+                       if not comicid:
+                               print "already at last comic"
+                               return
                elif len(newest) == 10:
                        # date id.
                        dt = string.split(newest, "-")
@@ -333,6 +351,38 @@ class ComicDb():
                                else:
                                        print "got next: " + splt[0]
                                        return splt[0]  
+               if comic == 'wulff':
+                       link = "http://wulffmorgenthaler.com/default.aspx?id=" + number
+                       print "link: " + link
+                       try:
+                               f = urllib2.urlopen(link)
+                               hcode = f.code
+                       except:
+                               hcode = 404
+                       print "got hcode = " + str(hcode) + "\n"
+                       if (hcode != 200):
+                               return False
+                       else:
+                               s = f.read()
+                               f.close()
+                               # title:
+                               splt = string.split(s, '<a href="/default.aspx?id=', 1)
+                               if not splt[1][36:69] == '" id="ctl00_content_Strip1_aPrev"':
+                                       print "no previous found"
+                                       if not splt[1][36:69] == '" id="ctl00_content_Strip1_aNext"':
+                                               print "no next found!"
+                                               return False
+                               else:
+                                       splt = string.split(splt[1], '<a href="/default.aspx?id=', 1)
+                               if len(splt) < 2:
+                                       print "no next found! At newest comic!"
+                                       return False
+                               if not splt[1][36:69] == '" id="ctl00_content_Strip1_aNext"':
+                                       print "no next found!"
+                                       return False
+                               else:
+                                       return splt[1][:36]
+
 
        def get_prev_id(self, comic, number):
                if comic == 'cyanide':
@@ -362,6 +412,30 @@ class ComicDb():
                                else:
                                        print "got previous: " + splt[0]
                                        return splt[0]                          
+               if comic == 'wulff':
+                       link = "http://wulffmorgenthaler.com/default.aspx?id=" + number
+                       print "link: " + link
+                       try:
+                               f = urllib2.urlopen(link)
+                               hcode = f.code
+                       except:
+                               hcode = 404
+                       print "got hcode = " + str(hcode) + "\n"
+                       if (hcode != 200):
+                               return False
+                       else:
+                               s = f.read()
+                               f.close()
+                               # title:
+                               splt = string.split(s, '<a href="/default.aspx?id=', 1)
+                               if not splt[1][36:69] == '" id="ctl00_content_Strip1_aPrev"':
+                                       print splt[1][36:69]
+                                       print splt[1][:36]
+                                       print "no previous found"
+                                       exit()
+                                       return False
+                               else:
+                                       return splt[1][:36]
 
 
 
@@ -385,6 +459,8 @@ class ComicDb():
                        link = "http://www.phdcomics.com/comics/archive.php?comicid=" + str(number)
                elif comic == 'cyanide':
                        link = "http://www.explosm.net/comics/" + str(number) + "/"
+               elif comic == 'wulff':
+                       link = "http://wulffmorgenthaler.com/default.aspx?id=" + str(number)
                else:
                        return False
 
@@ -496,12 +572,43 @@ class ComicDb():
                                filename = splt2[1]
                                irow = [comic,number,link,url,filename,title,next,prev]
                                return irow
-       
+                       elif comic == 'wulff':
+                               # wulf is type .gif
+                               s = f.read()
+                               f.close()
+# <img src="pics/dates/month/2.gif" alt="" />
+# <img src="pics/dates/day/4.gif" alt="" />
+# <img src="pics/dates/komma.gif" alt="" />
+# <img src="pics/dates/year/2010.gif" alt="" />
+                               splt = string.split(s, '<img src="pics/dates/month/', 1)
+                               if not splt[1][1:2] == ".":
+                                       title = splt[1][:2]
+                               else:
+                                       title = "0" + splt[1][:1]
+                               splt = string.split(splt[1], '<img src="pics/dates/day/', 1)
+                               if not splt[1][1:2] == ".":
+                                       title = title + "-" + splt[1][:2]
+                               else:
+                                       title = title + "-0" + splt[1][:1]
+                               splt = string.split(splt[1], '<img src="pics/dates/year/', 1)
+                               title = splt[1][:4] + "-" + title
+                               # title done...
+                               splt = string.split(splt[1], 'id="ctl00_content_Strip1_imgStrip" class="strip" src="striphandler.ashx?stripid=', 1)
+                               number = splt[1][:36]
+                               url = "http://wulffmorgenthaler.com/striphandler.ashx?stripid=" + number
+                               filename = number + ".gif"
+                               irow = [comic,number,link,url,filename,title]
+                               return irow
+                               
+
                        splt2 = string.rsplit(url, "/", 1)
                        filename = splt2[1]
-                       if filename == self.db[0]['filename']:
-                               print "already exists! Break break break!"
-                               return False
+                       try:
+                               if filename == self.db[0]['filename']:
+                                       print "already exists! Break break break!"
+                                       return False
+                       except:
+                               pass
                        irow = [comic,number,link,url,filename,title]
                        return irow
 
@@ -515,6 +622,9 @@ class ComicHomePlugin(hildondesktop.HomePluginItem):
                global supports_alpha
                self.set_settings(True)
                self.active_comics = self.get_active_comics()
+               self.sizes = self.get_size_settings()
+               self.new_width = self.sizes['width']
+               self.new_height = self.sizes['height']
                self.connect("show-settings", self.show_options)
                self.osso_c = osso.Context("comic-widget", "0.3.0", False)
                self.osso_rpc = osso.Rpc(self.osso_c)
@@ -534,7 +644,7 @@ class ComicHomePlugin(hildondesktop.HomePluginItem):
                self.set_colormap(colormap)
                self.set_app_paintable(True)
                #setup internal area
-               self.set_size_request(480, 230)
+               self.set_size_request(self.sizes['width'], self.sizes['height'])
                self.imgvpos = 0;
                self.vbox = gtk.VBox()
                self.hbox = gtk.HBox()
@@ -544,7 +654,7 @@ class ComicHomePlugin(hildondesktop.HomePluginItem):
                titl = str(self.db.db[self.db.currentcomic]['title'])
                if len(titl) > 22:
                        titl = titl[:19] + "..."
-               self.label.set_markup('<span size="12000" face="monospace"> <b>' + self.comicname + '</b> ' + str(self.db.db[self.db.currentcomic]['id']) + '\n ' + titl + '</span>')
+               self.label.set_markup(self.get_markup())
 
 
                self.e_goweb = gtk.EventBox()
@@ -639,6 +749,8 @@ class ComicHomePlugin(hildondesktop.HomePluginItem):
                self.vbox.show_all()
                self.add(self.vbox)
 
+
+
        # **************** Cairo draw functions ***************
 
        def realize(self, widget):
@@ -725,7 +837,7 @@ class ComicHomePlugin(hildondesktop.HomePluginItem):
                                titl = str(self.db.db[self.db.currentcomic]['title'])
                                if len(titl) > 22:
                                        titl = titl[:19] + "..."
-                               self.label.set_markup('<span size="12000" face="monospace"> <b>' + self.comicname + '</b> ' + str(self.db.db[self.db.currentcomic]['id']) + '\n ' + titl + '</span>')
+                               self.label.set_markup(self.get_markup())
                                self.e_goweb.add(self.label)
                                self.e_goweb.show_all()
 
@@ -740,7 +852,7 @@ class ComicHomePlugin(hildondesktop.HomePluginItem):
                                titl = str(self.db.db[self.db.currentcomic]['title'])
                                if len(titl) > 22:
                                        titl = titl[:19] + "..."
-                               self.label.set_markup('<span size="12000" face="monospace"> <b>' + self.comicname + '</b> ' + str(self.db.db[self.db.currentcomic]['id']) + '\n ' + titl + '</span>')
+                               self.label.set_markup(self.get_markup())
                                self.e_goweb.add(self.label)
                                self.e_goweb.show_all()
 
@@ -764,7 +876,7 @@ class ComicHomePlugin(hildondesktop.HomePluginItem):
                                titl = str(self.db.db[self.db.currentcomic]['title'])
                                if len(titl) > 22:
                                        titl = titl[:19] + "..."
-                               self.label.set_markup('<span size="12000" face="monospace"> <b>' + self.comicname + '</b> ' + str(self.db.db[self.db.currentcomic]['id']) + '\n ' + titl + '</span>')
+                               self.label.set_markup(self.get_markup())
                                self.e_goweb.add(self.label)
                                self.e_goweb.show_all()
                                self.e_open.add(self.comic_image)
@@ -799,23 +911,26 @@ class ComicHomePlugin(hildondesktop.HomePluginItem):
 
        def get_resized_pixmap(self, filename, vpos):
                print "vpos: " + str(vpos)
-
-               maxheight = 182
+               
+               width = int(self.sizes['width'])
+               height = int(self.sizes['height'])
+               picwidth = width - 2
+               maxheight = height - 48
 
                pixbuf = gtk.gdk.pixbuf_new_from_file(filename)
-               parent_buf = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, pixbuf.get_has_alpha(), 8, 480, maxheight)
+               parent_buf = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, pixbuf.get_has_alpha(), 8, width, maxheight)
                parent_buf.fill(0xffffffff)
                retimg = gtk.Image()
                # get correct width/height
                new_height = 1
-               new_width = 478
-               new_height = int((478.0 / pixbuf.get_width()) * pixbuf.get_height())
+               new_width = picwidth
+               new_height = int((float(picwidth) / pixbuf.get_width()) * pixbuf.get_height())
                scaled_buf = pixbuf.scale_simple(new_width,new_height,gtk.gdk.INTERP_BILINEAR)
                print "scaled height: " + str(scaled_buf.get_height())
                if scaled_buf.get_height() > maxheight:
                        if scaled_buf.get_height() - (vpos + maxheight) < 0:
                                vpos = scaled_buf.get_height() - maxheight
-                       scaled_buf.copy_area(0,vpos,478,maxheight,parent_buf,1,0)
+                       scaled_buf.copy_area(0,vpos,picwidth,maxheight,parent_buf,1,0)
                        # parent_buf.composite(scaled_buf, 0, 0, 478, maxheight, 0, 0, 478, maxheight, gtk.gdk.INTERP_BILINEAR, 0)
                        self.imgvpos = vpos
                else:
@@ -823,10 +938,10 @@ class ComicHomePlugin(hildondesktop.HomePluginItem):
                        if tmpy > 0:
                                tmpy = tmpy / 2
 
-                       scaled_buf.copy_area(0,0,478,scaled_buf.get_height(),parent_buf,1,tmpy)
+                       scaled_buf.copy_area(0,0,picwidth,scaled_buf.get_height(),parent_buf,1,tmpy)
                        self.imgvpos = 0
 #              test = parent_buf.render_pixmap_and_mask(0)
-               parent_buf.add_alpha(True,chr(255),chr(255),chr(255))
+#              parent_buf.add_alpha(True,chr(255),chr(255),chr(255))
                retimg.set_from_pixbuf(parent_buf)
                print retimg.get_pixel_size()
                print "vpos after fixing image: " + str(self.imgvpos)
@@ -890,7 +1005,12 @@ class ComicHomePlugin(hildondesktop.HomePluginItem):
                        return ret
 
                
-               
+       def get_markup(self):
+               if len(self.comicname + " " + str(self.db.db[self.db.currentcomic]['id'])) < 20:
+                       return '<span size="12000" face="monospace"> <b>' + self.comicname + '</b> ' + str(self.db.db[self.db.currentcomic]['id']) + '\n ' + str(self.db.db[self.db.currentcomic]['title']) + '</span>'
+               else:
+                       return '<span size="12000" face="monospace"> <b>' + self.comicname + '</b>' + '\n ' + str(self.db.db[self.db.currentcomic]['title']) + '</span>'
+
                
                #check if settings file exists
 
@@ -912,10 +1032,16 @@ class ComicHomePlugin(hildondesktop.HomePluginItem):
                comics_button.set_alignment(0,0,0,0)
                comics_button.connect("clicked", self.show_comics)
 
+               # size_button = hildon.Button(gtk.HILDON_SIZE_AUTO_WIDTH | gtk.HILDON_SIZE_FINGER_HEIGHT, hildon.BUTTON_ARRANGEMENT_VERTICAL)
+               # size_button.set_text("Change size", "Change the size of the widget")
+               # size_button.set_alignment(0,0,0,0)
+               # size_button.connect("clicked", self.show_size)
+
                print "adding buttons to dialog, starting with comics"
                dialog.vbox.pack_start(comics_button, True, True, 0)
                print "adding about button"
                dialog.vbox.pack_start(about_button, True, True, 0)
+               # dialog.vbox.pack_start(size_button, True, True, 0)
                print "show!"
                dialog.show_all()
                dialog.run()
@@ -937,40 +1063,64 @@ class ComicHomePlugin(hildondesktop.HomePluginItem):
                dialog.run()
                dialog.destroy()
 
-       def show_comics(self, widget):
+       def show_comics(self, widget, data = None):
                print "in comics dialog! yay!"
-               dialog = gtk.Dialog("Configure Search Engines", None, gtk.DIALOG_DESTROY_WITH_PARENT | gtk.DIALOG_NO_SEPARATOR)
+               dialog = gtk.Dialog("Choose comics", None, gtk.DIALOG_DESTROY_WITH_PARENT | gtk.DIALOG_NO_SEPARATOR)
                comiclist = comics.keys()
                comiclist.sort()
                buttonlist = {}
                self.connlist = {}
+               self.liststore = gtk.ListStore(str,str,bool)
                for comicid in comiclist:
-                       buttonlist[comicid] = hildon.Button(gtk.HILDON_SIZE_AUTO_WIDTH | gtk.HILDON_SIZE_FINGER_HEIGHT, hildon.BUTTON_ARRANGEMENT_VERTICAL)
-                       print buttonlist[comicid].get_name()
-                       
-                       print buttonlist[comicid].set_alignment(0, 0.5, 0, 0.5) 
                        active = False
                        for acomic in self.active_comics:
                                if acomic == comicid:
                                        active = True
                                        break
                        if active:
-                               buttonlist[comicid].set_text(comics[comicid]['name'] + " *", comicid + ": click to remove")
-                               self.connlist[comicid] = buttonlist[comicid].connect("clicked", self.remove_comic)
+                               self.liststore.append(["* " + comics[comicid]['name'],comicid, active])
                        else:
-                               buttonlist[comicid].set_text(comics[comicid]['name'], comicid + ": click to add")
-                               self.connlist[comicid] = buttonlist[comicid].connect("clicked", self.add_comic)
-                       dialog.vbox.pack_start(buttonlist[comicid], True, True, 0)
+                               self.liststore.append(["  " + comics[comicid]['name'],comicid, active])
+               self.treeview = hildon.GtkTreeView(gtk.HILDON_UI_MODE_EDIT)
+               self.treeview.set_model(self.liststore)
+               self.treeview.set_reorderable(True)
+               tvcolumn = gtk.TreeViewColumn('Column 0')
+               self.treeview.append_column(tvcolumn)
+               cell = gtk.CellRendererText()
+               tvcolumn.pack_start(cell, True)
+               tvcolumn.add_attribute(cell, 'text', 0)
+
+               ts = hildon.PannableArea()
+       
+               ts.set_size_request(-1, 280)
+               ts.add(self.treeview)
+               selection = self.treeview.get_selection()
 
-               
+               dialog.vbox.pack_start(ts,True,True,0)
                dialog.show_all()
+               selection.connect("changed", self.pick_comic, comiclist)
                dialog.run()
                dialog.destroy()
+
+       def pick_comic(self, widget, data):
+               selected = widget.get_selected()
+               if selected == None:
+                       return False
+               
+               print selected[0].get_value(selected[1],0) + ", " + selected[0].get_value(selected[1],1) + ", " + str(selected[0].get_value(selected[1],2))
+               if selected[0].get_value(selected[1],2):
+                       self.remove_comic(selected[0].get_value(selected[1],1))
+                       splt = selected[0].get_value(selected[1],0)[1:]
+                       selected[0].set_value(selected[1],0," " + splt)
+                       selected[0].set_value(selected[1],2,False)
+               else:
+                       self.add_comic(selected[0].get_value(selected[1],1))
+                       splt = selected[0].get_value(selected[1],0)[1:]
+                       selected[0].set_value(selected[1],0,"*" + splt)
+                       selected[0].set_value(selected[1],2,True)
+
                                
-       def add_comic(self, widget):
-               print "add " + widget.get_title()
-               splt = string.split(widget.get_value(), ':', 1)
-               comicid = splt[0]
+       def add_comic(self, comicid):
                if os.path.isfile(activecomics) == True:
                        print "added " + comicid + " to " + str(self.active_comics)
                        try:
@@ -981,16 +1131,8 @@ class ComicHomePlugin(hildondesktop.HomePluginItem):
                        dbw = csv.writer(dbf)
                        dbw.writerow(self.active_comics)
                        dbf.close()
-               widget.set_text(comics[comicid]['name'] + " *", comicid + ": click to remove")
-               widget.disconnect(self.connlist[comicid])
-               self.connlist[comicid] = widget.connect("clicked", self.remove_comic)
-
-       def remove_comic(self, widget):
-               print "remove " + widget.get_title()
-               if len(self.active_comics) == 1:
-                       return
-               splt = string.split(widget.get_value(), ':', 1)
-               comicid = splt[0]
+
+       def remove_comic(self, comicid):
                if os.path.isfile(activecomics) == True:
                        print "removing " + comicid + " from " + str(self.active_comics)
                        try:
@@ -1001,9 +1143,42 @@ class ComicHomePlugin(hildondesktop.HomePluginItem):
                        dbw = csv.writer(dbf)
                        dbw.writerow(self.active_comics)
                        dbf.close()
-               widget.set_text(comics[comicid]['name'], comicid + ": click to add")
-               widget.disconnect(self.connlist[comicid])
-               self.connlist[comicid] = widget.connect("clicked", self.add_comic)
+
+
+       def get_size_settings(self):
+               # defaults = {'width':480,'height':230}
+               # options: w 798 700 600 500 480 400
+               # options: h 420 360 310 270 240 200
+               print "checking to see if config file is available"
+               if os.path.isfile(sizefile) == True:
+                       print "found " + sizefile
+                       dbf = open(sizefile, 'r')
+                       dbr = csv.reader(dbf)
+                       try:
+                               cfg = dbr.next()
+                       except:
+                               dbf.close()
+                               print "empty config file"
+                               return defaults
+                       dbf.close()
+                       
+                       sizes = {'width':int(cfg[0]),'height':int(cfg[1])}
+                       if sizes['width'] > 798:
+                               sizes['width'] = 798
+                       if sizes['width'] < 400:
+                               sizes['width'] = 400
+                       if sizes['height'] > 420:
+                               sizes['height'] = 420
+                       if sizes['height'] < 200:
+                               sizes['height'] = 200
+                       
+                       return sizes
+                       
+                       
+               # if not, copy it.
+               else:
+                       print "no config file"
+                       return defaults
                
 hd_plugin_type = ComicHomePlugin