#!/usr/bin/python
# -*- coding: utf-8 -*-

import gtk
import gtk.gdk as gdk
import gobject

try:
    from egg.trayicon import TrayIcon
except ImportError:
    TrayIcon = lambda a: None

class StatusIcon(gobject.GObject):
    __gtype_name__ = "test"
    def __init__(self):
        self.__size = 24
        self.__tray_icon = None
        self.__pixbuf = None
        self.__image = None
        self.__image_data = None
        self.__storage_type = None

        super(StatusIcon, self).__init__()
        self.__tray_icon = TrayIcon(self.__gtype_name__)
        self.__image = gtk.Image()
        self.__image.set_flags(gtk.CAN_FOCUS)
        self.__tray_icon.add(self.__image)
        self.__image.show()

    def __update_image(self):
        if self.__storage_type == gtk.IMAGE_PIXBUF:
            pixbuf = self.__image_data;
            width = pixbuf.get_width()
            height = pixbuf.get_height()
            if width > self.__size:
                width = self.__size
            if height > self.__size:
                height = self.__size
            self.__pixbuf = pixbuf.scale_simple(width, height, gdk.INTERP_BILINEAR)
        if self.__storage_type == gtk.IMAGE_ICON_NAME:
            icon_name = self.__image_data
            theme = gtk.icon_theme_get_default()
            self.__pixbuf = theme.load_icon(icon_name, self.__size, 0)
        if self.__pixbuf:
            self.__image.set_from_pixbuf(self.__pixbuf)

    def __set_image(self, storage_type, data):
        self.__storage_type = storage_type
        self.__image_data = data
        self.__update_image()

    def set_from_icon_name(self, icon_name):
        if self.__tray_icon == None:
            super(StatusIcon, self).set_from_icon_name(icon_name)
            return
        if not icon_name:
            return
        self.__set_image(gtk.IMAGE_ICON_NAME, icon_name)

    def set_from_pixbuf(self, pixbuf):
        if self.__tray_icon == None:
            super(StatusIcon, self).set_from_pixbuf(pixbuf)
            return
        self.__set_image(gtk.IMAGE_PIXBUF, pixbuf)

    def set_from_file(self, filename):
        if self.__tray_icon == None:
            super(StatusIcon, self).set_from_file(filename)
            return
        if not filename:
            return
        pixbuf = gdk.pixbuf_new_from_file (filename)
        self.set_from_pixbuf(pixbuf)

    def set_visible(self, visible):
        if self.__tray_icon == None:
            super(StatusIcon, self).set_visible(visible)
            return
        if visible:
            self.__tray_icon.show()
        else:
            self.__tray_icon.hide()
            self.__tray_icon.unrealize()


def main():
    status_icon = StatusIcon()
    status_icon.set_from_icon_name("gnome-applets")
    status_icon.set_visible(True)
    gtk.main()

main()
