~ubuntu-branches/ubuntu/hardy/emesene/hardy-backports

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
#   This file is part of emesene.
#
#    Emesene is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    emesene is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with emesene; if not, write to the Free Software
#    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

# Right now we are not using gtk themes facilities
#
# We should consider using them at some point

import re
import os
import gtk.gdk
from shutil import copyfile

from emesenecommon import PATH
import emesenelib.common

ALTERNATIVE_SMILEYS = {\
    '<:o)':['<:O)'],
    '(a)' : [ '(A)' ],\
    ':@' : [ ':-@' ],\
    '(b)' : [ '(B)' ] ,\
    '(z)' : [ '(Z)' ] ,\
    '(u)' : [ '(U)' ] ,\
    '(p)' : [ '(P)' ] ,\
    '(o)' : [ '(O)' ] ,\
    '(c)' : [ '(C)' ] ,\
    ':s' : [ ':S', ':-S' ] ,\
    ':|' : [ ':-|' ] ,\
    '(d)' : [ '(D)' ] ,\
    '(e)' : [ '(E)' ] ,\
    ':$' : [ ':-$' ] ,\
    '(g)' : [ '(G)' ] ,\
    '(x)' : [ '(X)' ] ,\
    '(h)' : [ '(H)' ] ,\
    '(i)' : [ '(I)' ] ,\
    '(m)' : [ '(M)' ] ,\
    ':D' : [ ':d', ':-d', ':-D', ':>' ] ,\
    '(l)' : [ '(L)' ] ,\
    '(k)' : [ '(K)' ] ,\
    '(f)' : [ '(F)' ] ,\
    ':(' : [ ':-(', ':<' ] ,\
    ':)' : [ ':-)' ] ,\
    ':p' : [ ':P', ':-P' ] ,\
    ':-O' : [ ':O', ':o', ':-o' ] ,\
    '(t)' : [ '(T)' ] ,\
    '(n)' : [ '(N)' ] ,\
    '(y)' : [ '(Y)' ] ,\
    '(w)' : [ '(W)' ] ,\
    ';)' : [ ';-)' ] ,\
    '(r)' : [ '(R)' ],\
}

SMILEY_TO_NAME = {\
    '<:o)' : 'party_smiley',\
    '(ap)' : 'Airplane',\
    '(a)' : 'angel',\
    ':@' : 'angry',\
    '(au)' : 'Auto',\
    '8o|' : 'Baring_teeth_smiley',\
    '(b)' : 'beer',\
    '(^)' : 'Birthday_cake',\
    '(bah)' : 'Black_sheep',\
    '(nah)' : 'goat',\
    '(||)' : 'Bowl',\
    '(z)' : 'Boy',\
    '(u)' : 'brheart',\
    '(p)' : 'photo',\
    '(@)' : 'pussy',\
    '(ci)' : 'Cigarette',\
    '(o)' : 'Clock',\
    '(c)' : 'coffee',\
    '(co)' : 'computer',\
    ':s' : 'confused',\
    ':\'(' : 'cry',\
    '(6)' : 'devil',\
    ':|' : 'stare',\
    '(&)' : 'Dog_face',\
    ':-#' : 'Dont_tell_anyone',\
    '(d)' : 'drink',\
    '(e)' : 'mail',\
    ':$' : 'blushing',\
    '8-)' : 'Eye_rolling_smiley',\
    '(~)' : 'video-x-generic',\
    '(yn)' : 'Fingerscrossed',\
    '(g)' : 'Gift_with_a_bow',\
    '(x)' : 'Girl',\
    '(%)' : 'cuffs',\
    '(h5)' : 'Hi_five',\
    '(h)' : 'coolglasses',\
    ':^)' : 'andy',\
    '(ip)' : 'Island_with_a_palm_tree',\
    '({)' : 'hugleft',\
    '(i)' : 'lamp',\
    '(li)' : 'weather-storm',\
    '(m)' : 'Messenger',\
    '(mp)' : 'phone',\
    '(mo)' : 'Money',\
    '8-|' : 'face-glasses',\
    '(8)' : 'audio-x-generic',\
    ':D' : 'grin',\
    '(pi)' : 'Pizza',\
    '(pl)' : 'Plate',\
    '(r)' : 'rainbow',\
    '(st)' : 'weather-showers-scattered',\
    '(l)' : 'emblem-favorite',\
    '(k)' : 'kiss',\
    '(f)' : 'flower',\
    '(})' : 'hugright',\
    ':(' : 'unhappy',\
    '^o)' : 'Sarcastic_smiley',\
    ':-*' : 'Secret_telling_smiley',\
    '+o(' : 'sick',\
    '(S)' : 'weather-clear-night',\
    '|-)' : 'sleeping',\
    ':)' : 'smile',\
    ':p' : 'tongue',\
    '(sn)' : 'Snail',\
    '(so)' : 'Soccer_ball',\
    '(*)' : 'star',\
    '(#)' : 'weather-clear',\
    ':-O' : 'oh',\
    '(t)' : 'Telephone_receiver',\
    '*-)' : 'Thinking_smiley',\
    '(n)' : 'thumbdown',\
    '(y)' : 'thumbup',\
    '(tu)' : 'Turtle',\
    '(um)' : 'Umbrella',\
    ':[' : 'bat',\
    ':-[' : 'bat',\
    '(w)' : 'brflower',\
    ';)' : 'wink',\
    '(xx)' : 'Xbox',\
}

ACCEPTED_FORMATS = [ 'png', 'gif', 'svg', 'xpm' ]

def resizePixbuf( pixbuf, height, width ):
    pWidth, pHeight = pixbuf.get_width(), pixbuf.get_height()
    
    if pWidth == width and pHeight == height:
        return pixbuf
            
    destX = destY = 0
    destWidth, destHeight = width, height
    if pWidth > pHeight:
        scale = float( width ) / pWidth
        destHeight = int( scale * pHeight )
        destY = int( ( height - scale * pHeight ) / 2 )
    elif pHeight > pWidth:
        scale = float( height ) / pHeight
        destWidth = int( scale * pWidth )
        destX = int( ( width - scale * pWidth ) / 2 )
    else:
        return pixbuf.scale_simple( width, height, gtk.gdk.INTERP_BILINEAR )
    
    if scale == 1:
        return pixbuf
    
    scaled = gtk.gdk.Pixbuf( gtk.gdk.COLORSPACE_RGB, True, 8, width, height)
    pixbuf.scale( scaled, 0, 0, width, height, \
                    destX, destY, scale, scale, \
                    gtk.gdk.INTERP_BILINEAR )
    return scaled

def sortedKeysByLen(adict, reverse=True):
    keys = adict.keys()
    keys.sort( lambda left, right: cmp( len(left),len(right) ) , reverse=reverse)
    return keys

class BaseTheme:
    '''Common functions to both theme classes'''

    def setTheme( self, name, small = False ):
        '''Sets the current theme to the name given.
        In case of error, it will directly fallback to the default theme
        Returns True if the specified theme was correctly set, otherwise
        False'''
        
        if name == 'default' and not small:
            self.pixbufs = self.defaults
            self.path = self.defaultPath
            return True
        else:
            self.pixbufs = {}
        
        path = None
        smallFound = False
        SMALL_PATH = self.HOME_PATH + os.sep + '.' + name + 'Small'
        if small and os.path.isdir( SMALL_PATH ):
            path = SMALL_PATH
            smallFound = True
        elif os.path.isdir( self.HOME_PATH + os.sep + name ):
            path = self.HOME_PATH + os.sep + name
        elif os.path.isdir( self.SYSTEM_WIDE_PATH + os.sep + name ):
            path = self.SYSTEM_WIDE_PATH + os.sep + name
        else:
            emesenelib.common.debug( 'Theme '+ name + \
                      ' couldn\'t be found where it was supposed to be' )
            emesenelib.common.debug( 'Falling back to the default theme' )
            self.path = self.defaultPath
            return False
        
        if small and not smallFound:
            if not os.path.isdir( SMALL_PATH ):
                path = self.makeSmall( path, SMALL_PATH )
            else:
                path = path + 'Small'
        self.small = small
        self.path = path + os.sep
        return True
        
    def makeSmall( self, path, spath ):
        return path

    def searchPixbuf( self, path, name, isLocation = False, pixbufCreator = None ):
        '''Finds name in path with ACCEPTED_FORMATS extensions
        Returns location if found and if isLocation
        Else, return pixbufCreator(location)'''
        
        for extension in ACCEPTED_FORMATS:
            location = path + name + '.' + extension
            if isLocation:
                if os.path.exists( location ):
                    return location
            else:
                try:
                    pixbuf = pixbufCreator( location )
                    return pixbuf
                except:
                    pass
        return None
        
    def getImage( self, name, animated=False ):
        '''Returns a pixbuf of the requested image from the current theme
        If the requested image name is not found in the current theme, the
        default theme's corresponding image will be returned.
        If the default theme doesn't have such a image, None is returned'''
        
        # checks if already loaded
        if name in self.pixbufs: return self.pixbufs[ name ]
        
        # determines which pixbuf function is used to create it
        if animated:
            creator = gtk.gdk.PixbufAnimation
        else:
            creator = gtk.gdk.pixbuf_new_from_file
                
        pixbuf = self.searchPixbuf( self.path, name, pixbufCreator = creator )

        if pixbuf:
            # returns icon from theme
            self.pixbufs[ name ] = pixbuf
            return pixbuf

        #else, return icon from default theme
        if name in self.defaults:
            return self.defaults[ name ]

        self.defaults[ name ] = self.searchPixbuf( self.defaultPath, name, pixbufCreator = creator)
        return self.defaults[ name ]
                
    def getImageIcon( self, name, animated=False ):
        '''Returns the location of the requested image from the current theme
        If the requested image name is not found in the current theme, the
        default theme's corresponding image will be returned.
        If the default theme doesn't have such a image, None is returned'''

        location = self.searchPixbuf( self.path, name, isLocation = True )
        if location:
            # returns icon from theme
            return location
        else:
            # will return icon from default theme
            return self.searchPixbuf( self.defaultPath, name, isLocation = True )

class Theme(BaseTheme):
    '''This class contains all the data related to a theme:
    images, icons, animations, path to sounds etc'''
    
    def __init__( self , config, name=None, sname='default' ):
        '''Constructor'''
        
        self.config = config
        self.defaults = {}
        self.pixbufs = {}
        self.HOME_PATH = PATH.THEME_HOME_PATH 
        self.SYSTEM_WIDE_PATH = PATH.THEME_SYSTEM_WIDE_PATH
        self.defaultPath = PATH.DEFAULT_THEME_PATH
        if name:
            self.setTheme( name )
        else:
            self.path = self.defaultPath
        
        self.smilies = SmilieTheme( self, sname )
        self.getSmileysList = self.smilies.getSmileysList
        self.getSmiley = self.smilies.getSmiley
        self.getSmileyPath = self.smilies.getSmileyPath
        self.smileyParser = self.smilies.smileyParser
        self.getSmileysList = self.smilies.getSmileysList
        self.getSingleSmileysList = self.smilies.getSingleSmileysList
    
    def statusToPixbuf( self, status ):
        '''Translates a status code in a pixbuf returning the according
        theme image'''
        
        name = None
        if status == 'NLN' or status == 'online':
            name = 'online'
        elif status == 'AWY' or status == 'away':
            name = 'away'
        elif status == 'BSY' or status == 'busy':
            name = 'busy'
        elif status == 'BRB' or status == 'brb':
            name = 'brb'
        elif status == 'PHN' or status == 'phone':
            name = 'phone'
        elif status == 'LUN' or status == 'lunch':
            name = 'lunch'
        elif status == 'HDN' or status == 'invisible':
            name = 'invisible'
        elif status == 'IDL' or status == 'idle':
            name = 'idle'
        elif status == 'FLN' or status == 'offline':
            name = 'offline'
        # the following status are dummys
        elif status == 'DCD' or status == 'disconnected':
            name = 'trayicon'
        elif status == 'LOG' or status == 'login':
            name = 'trayicon2'

        if name:
            return self.getImage( name )
        else:
            return None
       
    def hasUserDisplayPicture( self, contact ):
        '''return True if the user has a cached Display picture'''
        imagePath = os.path.join(self.config.getCachePath(), \
            contact.displayPicturePath)
        
        if os.path.exists( imagePath ) and os.path.isfile( imagePath ):
            return True
        else:
            return False
            
    def getUserDisplayPicture( self, contact, width=96, height=96 ):
        '''return a pixbuf with the display picture of the user
        or the default image if not found'''
        
        imagePath = os.path.join(self.config.getCachePath(), \
            contact.displayPicturePath)
        
        if os.path.exists( imagePath ) and os.path.isfile( imagePath ):
            try:
                pixbuf = gtk.gdk.pixbuf_new_from_file( imagePath )
            except:
                pixbuf = self.getImage( 'login' )
        else:
            pixbuf = self.getImage( 'login' )
        
        if width == 96 and height == 96:
            return pixbuf
        else:
            return resizePixbuf(pixbuf, width, height)

    def makeSmall( self, path, spath):
        os.mkdir( spath )
        try:
            for root, dirs, files in os.walk( path ):
                del dirs
                if root != path: continue
                for file in files:
                    name = file.split('.')[0]
                    fullname = os.path.join(root, file)
                    destname = os.path.join(spath, file)
                    if name in ('away','brb','busy','icon','idle','lunch', \
                                'invisible','mobile','offline','online', \
                                'phone'):
                        pixbuf = resizePixbuf( gtk.gdk.pixbuf_new_from_file(fullname), 16, 16 )
                        pixbuf.save(destname, 'png')
                    elif file.split('.')[1] in ACCEPTED_FORMATS:
                        copyfile(fullname,destname)
            return spath
        except Exception, e:
            print "Error creating small theme", e
            return path
    
class SmilieTheme(BaseTheme):

    def __init__( self , parent, name ):
        '''Constructor'''
        
        self.theme = parent
        self.defaults = {}
        self.pixbufs = {}
        self.defaultPath = PATH.DEFAULT_SMILIES_PATH
        self.HOME_PATH = PATH.SMILIES_HOME_PATH
        self.SYSTEM_WIDE_PATH = PATH.SMILIES_SYSTEM_WIDE_PATH
        if name:
            self.setTheme( name )
        else:
            self.path = self.defaultPath

        # sets up a dict with the different smiley shortcodes
        # that translates to smileys names
        self.smileyToName = {}
        for (key,value) in SMILEY_TO_NAME.iteritems():
            self.smileyToName[ key ] = value
            
            if key in ALTERNATIVE_SMILEYS:
                for i in ALTERNATIVE_SMILEYS[ key ]:
                    self.smileyToName[ i ] = value
        smileyPattern = ''
        
        for smiley in sortedKeysByLen( self.smileyToName ):
            smileyPattern += re.escape( emesenelib.common.escape(smiley) ) + '|'
        self.reSmiley = re.compile( '('+smileyPattern[:-1]+')' )
    
    def smileyParser( self, text, callback=None ):
        '''return text with smileys parsed in html
        you can set a callback to handle smileys parsing'''
        
        if callback == None:
            return self.reSmiley.sub( lambda data: '<img src="file://%s"/>'%self.getSmileyPath(emesenelib.common.unescape( data.groups()[0]) ) , text )
        else:
            return self.reSmiley.sub( lambda data: callback( self.getSmileyPath(emesenelib.common.unescape( data.groups()[0]) )) , text )
    

    def getSmiley( self, shortcode, animated=True ):
        '''Returns a pixbuf representing the corresponding smiley if we have one,
        otherwise None'''
            
        if shortcode in self.smileyToName:
            pixbuf = self.getImage( self.smileyToName[ shortcode ], animated )
            if not animated and type(pixbuf) == gtk.gdk.PixbufAnimation:
                pixbuf = pixbuf.get_static_image()
            return pixbuf
         
    def getSmileyPath( self, shortcode ):
        '''Returns the path of the smiley if we have one,
        otherwise None'''
        
        if shortcode in self.smileyToName:
            return self.getImageIcon( self.smileyToName[ shortcode ], True )
        
    def getSmileysList( self ):
        '''Returns a list of all the currently accepted smileys shortcodes'''
        
        return sortedKeysByLen( self.smileyToName )
    
    def getSingleSmileysList( self ):
        '''Returns a list of the currently accepted smileys shortcodes,
        without repetitions'''
        
        return sortedKeysByLen( SMILEY_TO_NAME )