"""Simple test app that hangs when bonobo.main is run in its own
thread.  To reproduce the hang:

1) Run this application in an xterm
2) Run a gnome-terminal
3) Click on the file menu of the gnome-terminal

The desktop will hang every time.
"""


import threading

import bonobo
import ORBit

ORBit.load_typelib("Accessibility")
ORBit.CORBA.ORB_init()

import Accessibility
import Accessibility__POA

import gobject
import gtk

listeners = []

registry = bonobo.get_object("OAFIID:Accessibility_Registry:1.0",
                             "Accessibility/Registry")

class EventListener(Accessibility__POA.EventListener):
    def __init__(self, registry, callback, eventType):
        self.registry  = registry
        self.callback  = callback
        self.eventType = eventType
        self.register()

    def ref(self): pass

    def unref(self): pass

    def queryInterface(self, repo_id):
	thiz = None
        if repo_id == "IDL:Accessibility/EventListener:1.0":
            thiz = self._this()
	return thiz

    def register(self):
        self._default_POA().the_POAManager.activate()
        self.registry.registerGlobalEventListener(self._this(),
                                                  self.eventType)
        self.__registered = True
        return self.__registered

    def deregister(self):
        if not self.__registered:
            return
        self.registry.deregisterGlobalEventListener(self._this(),
                                                    self.eventType)
        self.__registered = False

    def notifyEvent(self, event):
        try:
            self.callback(event)
        except:
            print "OOPS!"
        return True
    
    def __del__(self):
        self.deregister()

def registerEventListener(callback, eventType):
    global listeners
    listener = EventListener(registry, callback, eventType)
    listeners.append(listener)

def notifyEvent(event):
    print "notifyEvent"

def shutdownAndExit(signum=None, frame=None):
    print "shutdownAndExit"
    for listener in (listeners):
        listener.deregister()
    bonobo.main_quit()
    
class _BonoboMainThread(threading.Thread):
    def run(self):
        print "BONOBO MAIN THREAD RUN CALLED"
        #gobject.threads_init()
        #gtk.gdk.threads_init()
        #gtk.gdk.threads_enter()
        bonobo.main()
        #gtk.gdk.threads_leave()
        print "BONOBO MAIN THREAD FINISHING"
    
def test():
    registerEventListener(notifyEvent, "focus:")

    if True:
        _BonoboMainThread().start()
        print "BONOBO MAIN THREAD START CALLED"
    else:
        print "CALLING BONOBO MAIN"
        #gobject.threads_init()
        #gtk.gdk.threads_init()
        #gtk.gdk.threads_enter()
        bonobo.main()
        #gtk.gdk.threads_leave()
        print "BONOBO MAIN COMPLETED"
        
if __name__ == "__main__":
    import signal
    signal.signal(signal.SIGINT, shutdownAndExit)
    signal.signal(signal.SIGQUIT, shutdownAndExit)
    test()
