#!/usr/bin/python

# This is a part of the external applets for Cairo-Dock
# Copyright : (C) 2010 by Fabounet
# E-mail : fabounet@glx-dock.org
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# http://www.gnu.org/licenses/licenses.html#GPL

####################
### dependancies ###
####################
import gettext

try:
	import gtk
except:
	from gi.repository import Gtk as gtk

import sys
import os
import subprocess
from CDApplet import CDApplet, _
try:
	INSTALL_PREFIX = open("/etc/gnomenu/prefix").read()[:-1] 
except:
	INSTALL_PREFIX = '/usr'
sys.path.append(INSTALL_PREFIX + '/lib/gnomenu')

dependancies_ok = True
try:
	import backend
	from Menu_Main import Main_Menu
except:
	dependancies_ok = False

####################
### Applet class ###
####################
class Applet(CDApplet):
	def __init__(self):
		self.appletsize = [0, 0]
		self.container = 0
		self.orient = 0
		self.hwg = None
		CDApplet.__init__(self)
	
	##### private methods #####
	
	def get_geometry(self):
		props = self.icon.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 ShowMenu(self):
		x = self.icon.Get("x")  # center of the icon.
		y = self.icon.Get("y")
		
		if self.orient == 0: #bottom
			self.hwg.Adjust_Window_Dimensions(x - (self.Globals.MenuWidth/2),
				y - self.appletsize[1]/2 - self.Globals.MenuHeight)
		elif self.orient == 1: #top
			self.hwg.Adjust_Window_Dimensions(x -(self.Globals.MenuWidth/2),
				y + self.appletsize[1]/2)
		elif self.orient == 2: #right
			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.hwg.show_window()
		self.hwg.window.present()
	
	def HideMenu(self):
		if self.hwg:
			if self.hwg.window.window:
				if self.hwg.window.window.is_visible():
						self.hwg.hide_window()
						self.show = False

	def ToggleMenu(self):
		if self.hwg is None:
			dialog_attributes = {
				"message" : _("GnoMenu is not installed. Please install it before you run this applet."),
				"time-length" : 6 }
			widget_attributes = {}
			self.icon.PopupDialog (dialog_attributes, widget_attributes)
			return
		if self.hwg.window.window and self.hwg.window.window.is_visible():
			self.HideMenu()
		else:
			self.ShowMenu()
	
	##### applet definition #####
	
	def get_config(self,keyfile):
		self.config['shortkey'] 	= keyfile.get('Configuration', 'shortkey')
	
	def end(self):
		self.hwg.destroy()
	
	def begin(self):
		if (not dependancies_ok):
			return
		self.get_geometry()
		self.hwg = Main_Menu(self.HideMenu)
		import Globals as Globals
		self.Globals = Globals
		
		self.icon.BindShortkey([self.config['shortkey']])
	
	def reload(self):
		self.get_geometry()  # icon's size can change even when the config has not changed (resize by the user)
		self.icon.BindShortkey([self.config['shortkey']])
	
	##### callbacks #####
	
	def on_click(self,iState):
		self.ToggleMenu()
	
	def on_build_menu(self):
		items=[{"label": _("GnoMenu's settings"),
			"icon" : "gtk-preferences",
			"id"   : 0},
			{"label": _("About"),
			"icon" : "gtk-about",
			"id"   : 1},
			{"label": _("Edit Menus"),
			"icon" : "gtk-edit",
			"id"   : 2}]
		self.icon.AddMenuItems(items)
		
	def on_menu_select(self,iNumEntry):
		if iNumEntry == 0:
			os.system("/bin/sh -c '"+ INSTALL_PREFIX +"/lib/gnomenu/GnoMenu-Settings.py' &")  ## should probably be in /usr/bin...
		elif iNumEntry == 1:
			os.system("/bin/sh -c '" + INSTALL_PREFIX +"/lib/gnomenu/GnoMenu-Settings.py --about' &")
		elif iNumEntry == 2:
			subprocess.Popen("alacarte")
	
	def on_shortkey(self,key):
		self.ToggleMenu()
	
############
### main ###
############
if __name__ == '__main__':
	Applet().run()
