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

# notification about new messages in
# gajim using the compiz water ripple effect
# Original written by: Jan Vornberger (jav), xmpp:jav@jabber.de
# Modified by Mateusz Biliński (vArDo),xmpp:mateusz@bilinski.it
# to work with Compiz Fusion [June 2008]

import os
import gobject
import string
import re
import dbus

if getattr(dbus, 'version', (0,0,0)) >= (0,41,0):
    import dbus.glib

GAJIM_SERVICE = 'org.gajim.dbus'
GAJIM_OBJ_PATH = '/org/gajim/dbus/RemoteObject'
GAJIM_INTERFACE = 'org.gajim.dbus.RemoteInterface'

COMPIZ_SERVICE = 'org.freedesktop.compiz'
COMPIZ_OBJ_PATH = '/org/freedesktop/compiz/water/allscreens/point'
COMPIZ_INTERFACE = 'org.freedesktop.compiz'

# function to find root window id;
# we will need to pass that to compiz
def get_root_window_id():
    rootid = 0
    idline = os.popen('xwininfo -root | grep "id:"').readlines()[0]
    idmatch = re.search('id: ([^ ]*)', idline)
    if (idmatch):
        rootid = int(idmatch.group(1), 16)
        return rootid
    else:
        raise 'Can not find window id of root window'

# function to find the position of gajim systray icon;
# we want to ping that position
def get_systray_icon_position():
    # find systray icon
    cmd = 'xwininfo  -root -tree | grep gajim'
    posregex = re.compile('(\d+)x(\d+)\+\d+\+\d+\s*\+(\d+)\+(\d+)') # match window position info

    for line in os.popen(cmd).readlines():
        posmatch = posregex.search(line)
        if (posmatch):
            width = int(posmatch.group(1))
            height = int(posmatch.group(2))
            x = int(posmatch.group(3))
            y = int(posmatch.group(4))
            if (width >= 15 and width <= 30 and height >= 15 and height < 30):
                # I guess this is the systray icon
                return x + (width / 2), y

    raise 'Can not find gajim systray icon'

# callback function to be informed about new messages in gajim
def new_message(details):
    # new message -> ripple notification
    compiz_dbus_iface.activate('root', rootid,
                    'amplitude', 1,
                    'x', systray_x,
                    'y', systray_y)

# get root id and systray position for later use
rootid = get_root_window_id()
systray_x, systray_y = get_systray_icon_position()

# magic starts here
bus = dbus.SessionBus()

# connect to NewMessage signal from gajim
gajim_proxy_obj = bus.get_object(GAJIM_SERVICE, GAJIM_OBJ_PATH)
gajim_dbus_iface = dbus.Interface(gajim_proxy_obj, GAJIM_INTERFACE)
gajim_dbus_iface.connect_to_signal('NewMessage', new_message)

# prepare compiz dbus connection
compiz_proxy_obj = bus.get_object(COMPIZ_SERVICE, COMPIZ_OBJ_PATH)
compiz_dbus_iface = dbus.Interface(compiz_proxy_obj, COMPIZ_INTERFACE)
# compiz_dbus_iface.get_methods()

# get things going
mainloop = gobject.MainLoop()
mainloop.run()
