# -*- coding: utf-8 -*-

#   Test case for metacity compositor bug
#
#    This 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.
#
#    This 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

# - Some events are not debugged. They are marked with '##EVENT' in the code.
#   You may want to enable them..

# - If the problem is related to massive pixbufs, i've left the code to
#   add the emoticons to the table. Get the images from emesene svn with
#   this command (or download them to images/ in this path)
#   svn co https://emesene.svn.sourceforge.net/svnroot/emesene/trunk/emesene/smilies/default images
#
# - The WM properties are set around line 100
#

import os
import gtk
import gobject

_ = lambda x:x

# compressed version from Theme.py from emesene
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',
}

class SmilieTheme:
    def __init__(self):
        self.path = os.path.join(os.path.abspath(os.path.dirname(__file__)), \
            'images', '')
        
    def getImage(self, name):
        location = self.path + name + '.png'
        try:
            return gtk.gdk.pixbuf_new_from_file(location)
        except:
            pass

    def getSmiley( self, shortcode ):
        if shortcode in SMILEY_TO_NAME:
            return self.getImage(SMILEY_TO_NAME[shortcode])

    def getSingleSmileysList(self):
        keys = SMILEY_TO_NAME.keys()
        keys.sort( lambda left, right: cmp( len(left),len(right) ) )
        return keys



#####################################################
#####################################################
#####################################################
#####################################################
#####################################################
#####################################################

# the actual window, yay

class SmilieWindow( gtk.Window ):
    '''this is the window that opens when you press the smilie button on the
    conversation window'''

    def __init__( self, parent=None ):
        
        gtk.Window.__init__( self )

        # IMPORTANT: WINDOW MANAGER PROPERTIES HERE!
        self.set_decorated( False )
        self.set_type_hint( gtk.gdk.WINDOW_TYPE_HINT_DIALOG )

        if parent:
            self.set_transient_for( parent )
        self.set_position( gtk.WIN_POS_MOUSE )
        self.set_resizable( False )
        self.set_title( _('Smilies') )
        self.set_border_width( 2 )

        self.vbox = gtk.VBox()
        table1 = gtk.Table(10)
        self.tooltips = gtk.Tooltips()
        
        self.theme = SmilieTheme()
        
        self.closed = True
        
        x = 0
        y = 0

        for i in self.theme.getSingleSmileysList():
            if x == 10:
                x = 0
                y += 1
            try:
                button = gtk.Button()
                button.set_relief(gtk.RELIEF_NONE)
                self.tooltips.set_tip(button, i)
                smilieImage = gtk.Image()
                pb = self.theme.getSmiley(i)
                smilieImage.set_from_pixbuf(pb)
                button.set_image( smilieImage )
                button.connect('clicked', self.clicked, i)
                button.connect('enter-notify-event',
                    self.on_enter_notify_event)
                table1.attach( button, x, x+1, y, y+1 )
            except Exception, e:
                print e
                x -= 1
            x += 1

        ceLabel = gtk.Label('Custom Emoticons')
        self.vbox.pack_start( table1 )
        self.vbox.pack_start( ceLabel )
        self.fillCETable()
        
        self.add( self.vbox )
        self.vbox.show_all()
        self.connect( 'delete-event' , self.on_delete_event )
        self.connect( 'leave-notify-event' , self.on_leave_notify_event )
        self.connect( 'enter-notify-event' , self.on_enter_notify_event )

        self.tag = None

    def on_leave_notify_event(self, *args):
        print 'leave-notify-event, closing in 500ms'
        if not self.tag and not self.closed:
            self.tag = gobject.timeout_add( 500, self.hide )

    def on_enter_notify_event(self, *args):
        #print 'enter-notify-event' ##EVENT
        if self.tag:
            print 'enter-notify-event, not closing'
            gobject.source_remove( self.tag )
            self.tag = None

    def on_delete_event( self , *args ):
        self.hide()
        self.closed = True
        print 'Hidden. delete-event'
        return True
    
    def clicked( self, button, smilie ):
        self.hide()
        print 'Hidden. Clicked ' + str(smilie)

    def event( self, button, event, smilie ):
        #print 'Event on custom emoticon (%s / %s)' % (event, smilie) ##EVENT
        if event.type == gtk.gdk.BUTTON_PRESS and event.button == 1:
            print 'Event: left click on custom emoticon'
            self.hide()
        if event.type == gtk.gdk.BUTTON_PRESS and event.button == 3:
            print 'Event: right click on custom emoticon'
        
            # -- Custom Emoticon Menu --
            self.emoMenu = gtk.Menu()
            
            self.shortcutItem = gtk.ImageMenuItem( _( "Change shortcut" ) )
            self.shortcutItem.set_image( gtk.image_new_from_stock(
                gtk.STOCK_EDIT, gtk.ICON_SIZE_MENU) )
            
            self.deleteItem = gtk.ImageMenuItem( _( "Delete" ) )
            self.deleteItem.set_image( gtk.image_new_from_stock(
                gtk.STOCK_DELETE, gtk.ICON_SIZE_MENU) )
            
            self.emoMenu.add( self.shortcutItem )
            self.emoMenu.add( self.deleteItem )
            
            self.emoMenu.show_all()
            # -----
            
            self.emoMenu.popup( None, None, None, event.button, event.time )
    
    def clickedAdd( self, button, *args ):
        print 'Clicked add, hiding'
        self.hide()

    def show( self ):
        print 'Showing'
        self.fillCETable()
        gtk.Window.show( self )
        self.tag = None
        self.closed = False

    def hide( self ):
        print 'Hiding'
        gtk.Window.hide( self )
        if self.tag:
            gobject.source_remove( self.tag )
            self.tag = None
        self.closed = True
        
    def fillCETable( self ):
        try:
            self.vbox.remove( self.ceTable )
        except:
            pass
        self.ceTable = gtk.Table()
        x = 0
        y = 0
        
        #for shortcut, filename in self.customEmoticons.list.iteritems():
        if True:
            if x == 10:
                x = 0
                y += 1

            button = gtk.Button()
            button.set_relief(gtk.RELIEF_NONE)
            self.tooltips.set_tip(button, 'dummy')
            button.set_image( gtk.image_new_from_stock( gtk.STOCK_STOP, 
                gtk.ICON_SIZE_BUTTON ) )
            button.connect( 'event', self.event, 'dummy' )
            button.connect( 'enter-notify-event',
                self.on_enter_notify_event )
            self.ceTable.attach( button, x , x+1 , y , y+1 )

            x += 1
            
        button = gtk.Button( None, gtk.STOCK_ADD )
        button.set_image( gtk.image_new_from_stock( gtk.STOCK_ADD,
            gtk.ICON_SIZE_BUTTON ) )
        button.connect( 'enter-notify-event' , self.on_enter_notify_event )
        self.ceTable.attach( button, x , x+1 , y , y+1 )
        
        self.vbox.pack_start( self.ceTable )
        self.vbox.show_all()
        
    def addClicked( self, button ):
        pass

if __name__ == '__main__':
    def show(button):
        print 'def show()'
        smilieWindow.show()
    def main():
        vbox = gtk.VBox()
        vbox.pack_start(gtk.Label("Hi gnome, click this:"))
        button = gtk.Button()
        button.add(gtk.Label('This'))
        button.connect('clicked', show)
        vbox.pack_start(button)
        win.add(vbox)
        win.show_all()
        gtk.main()
    win = gtk.Window()
    win.set_default_size(300, 300)
    smilieWindow = SmilieWindow(win)
    main()
