#!/usr/bin/env python

# This application is released under the GNU General Public License 
# v3 (or, at your option, any later version). You can find the full 
# text of the license under http://www.gnu.org/licenses/gpl.txt. 
# By using, editing and/or distributing this software you agree to 
# the terms and conditions of this license. 
# Thank you for using free software!
#
#(c) Whise 2008,2009 <helderfraga@gmail.com>
# January 2010 : rewritten by Fabounet from the Cairo-Dock project.
#
# GnoMenu Cairo-Dock loader
# Part of the GnoMenu


####################
### dependancies ###
####################
import sys
import os.path
import ConfigParser
import gobject
import glib
import gtk
import dbus
from dbus.mainloop.glib import DBusGMainLoop
import gettext


###################
### global vars ###
###################
applet_name = os.path.basename(os.path.abspath("."))  # the name of the applet must the same as the folder.
try:
	INSTALL_PREFIX = open("/etc/gnomenu/prefix").read()[:-1] 
except:
	INSTALL_PREFIX = '/usr'
sys.path.append(INSTALL_PREFIX + '/lib/gnomenu')
import backend
gettext.textdomain('gnomenu')
gettext.install('gnomenu', INSTALL_PREFIX +  '/share/locale')
gettext.bindtextdomain('gnomenu', INSTALL_PREFIX +  '/share/locale')


##################################
### get our applet on the bus ###
##################################
applet_path = "/org/cairodock/CairoDock/"+applet_name  # path where our object is stored on the bus.
DBusGMainLoop(set_as_default=True)
bus = dbus.SessionBus()
try:
	applet_object = bus.get_object("org.cairodock.CairoDock", applet_path)
except dbus.DBusException:
	print ">>> module '"+applet_name+"' can't be found on the bus, exit."
	sys.exit(2)
myIcon = dbus.Interface(applet_object, "org.cairodock.CairoDock.applet")  # this object represents our applet and also our icon. It can be either in a dock or in a desklet, we don't have to care.


#############################
### initialize our applet ###
#############################
def get_config():
	# well, we don't have any parameters
	pass

def init():
	print ">>> INIT"
	# register to the notifications on our applet.
	myIcon.connect_to_signal("on_click", action_on_click)  # when the user left-clicks on our icon.
	myIcon.connect_to_signal("on_build_menu", action_on_build_menu)  # when the user right-clicks on our applet (which builds the menu)
	myIcon.connect_to_signal("on_menu_select", action_on_menu_select)  # when the user selects an entry of this menu.
	myIcon.connect_to_signal("on_stop_module", action_on_stop)  # when the user deactivate our applet (or the DBus plug-in, or when the Cairo-Dock is stopped).
	myIcon.connect_to_signal("on_reload_module", action_on_reload)  # when the user changes something in our config, or when the desklet is resized (with no change in the config).


##################################
### callbacks on the main icon ###
##################################
def action_on_click(iState):
	appleticon.click()

def action_on_build_menu():
	myIcon.PopulateMenu([_("Preferences"), _("About"), _("Edit Menus")])

def action_on_menu_select(iNumEntry):
	if iNumEntry == 0:
		os.system("/bin/sh -c '"+ INSTALL_PREFIX +"/lib/gnomenu/GnoMenu-Settings.py' &")  ## question : shouldn't it be in /usr/bin ?
	elif iNumEntry == 1:
		os.system("/bin/sh -c '" + INSTALL_PREFIX +"/lib/gnomenu/GnoMenu-Settings.py --about' &")
	elif iNumEntry == 2:
		os.spawnvp(os.P_WAIT,"alacarte",["alacarte"])


###############################
### callbacks on the applet ###
###############################
def action_on_stop():
	print ">>> our module is stopped"
	loop.quit()
	appleticon.end()

def action_on_reload(bConfigHasChanged):
	print ">>> our module is reloaded"
	appleticon.get_geometry()  # icon's size can change even when the config has not changed (resize by the user)


class AppletIcon(object):

	def __init__(self, icon_object):
		
		self.__myIcon = icon_object
		self.appletsize = [0, 0]
		self.get_geometry()
		
		from Menu_Main import Main_Menu
		self.hwg = Main_Menu(self.HideMenu)
		import Globals as Globals
		self.Globals = Globals
		if self.Globals.Settings['Distributor_Logo']:
			import IconFactory as iconfactory
			self.iconfactory = iconfactory
			myIcon.SetIcon(self.iconfactory.GetSystemIcon('distributor-logo'))	
		self.show = False
	
	def get_geometry(self):
		props = myIcon.GetAll();
		self.container = props['container']
		self.orient = props['orientation']
		if self.container == 1:  # Desklet, they are always oriented in a bottom-like way.
			if props['y'] < gtk.gdk.screen_height() / 2:
				self.orient = 1
			else:
				self.orient = 0
		if self.orient == 1:
			backend.save_setting('orientation', 'top')  ## shouldn't GnoMenu guess the orientation itself rather than writing it in the conf ? I feel like we souldn't write something like that in conf, this is not a configuration parameter, but some computation result.
		else:
			backend.save_setting('orientation', 'bottom')  ## what about left and right ??
		self.appletsize[0] = props['width']
		self.appletsize[1] = props['height']
	
	def end(self):
		self.hwg.destroy()
	
	def ShowMenu(self):
		# Display the start menu!!!
		x = myIcon.Get("x")  # center of the icon.
		y = myIcon.Get("y")
		print "x, y, orient:",x,y,self.orient
		
		if self.orient == 0:#bottom
			self.hwg.Adjust_Window_Dimensions(x - (self.Globals.MenuWidth/2),
				y - self.appletsize[1]/2 - self.Globals.MenuHeight) #self.Globals.PG_buttonframedimensions[1])#self.applet.get_window().get_geometry()[3]/2 -10)
		elif self.orient == 1:#top
			self.hwg.Adjust_Window_Dimensions(x -(self.Globals.MenuWidth/2),
				y + self.appletsize[1]/2) #self.Globals.PG_buttonframedimensions[1])#self.applet.get_window().get_geometry()[3]/2 -10) gtk.gdk.screen_height()
		elif self.orient == 2:#right
			print "h : ",self.Globals.MenuHeight,"H : ",gtk.gdk.screen_height()
			print " => y = ",y - self.Globals.MenuHeight/2," / ",gtk.gdk.screen_height() - self.Globals.MenuHeight
			self.hwg.Adjust_Window_Dimensions(x - self.Globals.MenuWidth - (self.appletsize[0])/2,
				min(y - self.Globals.MenuHeight/2 , gtk.gdk.screen_height() - self.Globals.MenuHeight - 10))
		elif self.orient == 3:#left
			self.hwg.Adjust_Window_Dimensions(x + self.appletsize[0]/2,
				min(y - self.Globals.MenuHeight/2 , gtk.gdk.screen_height() - self.Globals.MenuHeight - 10))
		else:
			self.hwg.Adjust_Window_Dimensions(gtk.gdk.screen_width()/2 -(self.Globals.MenuWidth/2),gtk.gdk.screen_height() - self.Globals.MenuHeight - (int(self.appletsize[1])))#self.Globals.PG_buttonframedimensions[1])#self.applet.get_window().get_geometry()[3]/2 -10) gtk.gdk.screen_height()
		self.hwg.show_window()
		self.show = True
	
	def HideMenu(self):
		if self.hwg:
			if self.hwg.window.window:
				if self.hwg.window.window.is_visible()== True:
					self.hwg.hide_window()
					self.show = False
	
	def click(self):
		if self.show:
			self.HideMenu()
		else:
			self.ShowMenu()


############
### main ###
############
if __name__ == '__main__':
	get_config()
	init()
	appleticon = AppletIcon( icon_object=myIcon)
	loop = gobject.MainLoop()
	loop.run()
	print ">>> bye"
	sys.exit(0)
