#!/usr/bin/python

from Tkinter import *
import string

class Balloon:
    def __init__(self, w, message = 'No help is available for this item'):
	self.w = w
	self.state = 0
	outstr = ''
	cntr = 0
	lines = 0
	for i in string.split(message, None):
	    if cntr > 10:
		outstr = outstr + "\n" + i
		cntr = 0
		lines = lines + 1
	    else:
		outstr = outstr + ' ' + i
		cntr = cntr + len(i)
	self.outstr = outstr
	self.w.bind('<Motion>', self.event_enter)
	self.w.bind('<Leave>', self.event_leave)

    def show(self):
	if self.state == 0:
	    self.msgwin = Tk()
	    self.msgwin.tk.call('wm','overrideredirect','.',1)
	    self.msgwin.tk.call('wm','geometry','.',self.widget_locate_balloon(self.w))
	    self.l = Label(self.msgwin, {'bg':'yellow', 'text':self.outstr, 'justify':'center'}).pack()
	    self.state = 1

    def hide(self):
	if self.state == 1:
	    self.msgwin.tk.call('wm','withdraw','.')
	    del self.l
	    del self.msgwin
	    self.state = 0    # Iconified

    def event_enter(self, e):
	self.show()

    def event_leave(self, e):
	self.hide()

    def event_is_good(self, e):
	wdy = self.w.winfo_height()
	wdx = self.w.winfo_width()
	if (e.x > 7 and e.x < (wdx - 7)) and (e.y > 7 and e.y < (wdy - 7)):
	    return 1
	else:
	    return 0

    def widget_locate_balloon(self, w):
	locs = [w.winfo_rootx(),
		w.winfo_rooty(),
		w.winfo_width(),
		w.winfo_height()]
	retp = [locs[0] + locs[2],
		locs[1] + locs[3]]
	return '+%d+%d' % (int(retp[0])+50,int(retp[1])-25)

    def destroy(self):
	self.hide()
