#!/usr/bin/env python

# ExecuteScreenlet by Helder Fraga 

#    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 3 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.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.

import screenlets
from screenlets.options import FileOption, StringOption
import cairo
import pango
import gtk
from os import system
import gtk
import gobject
#use gettext for translation
import gettext

_ = screenlets.utils.get_translator(__file__)

def tdoc(obj):
	obj.__doc__ = _(obj.__doc__)
	return obj

@tdoc
class ExecuteScreenlet(screenlets.Screenlet):
	"""A screenlet that executes any command that you type"""
	
	# default meta-info for Screenlets
	__name__ = 'ExecuteScreenlet'
	__version__ = '0.3.1'
	__author__ = 'Helder Fraga aka whise'
	__desc__ = __doc__
	clipboard = gtk.clipboard_get()
	
	__has_focus = False
	__query = ''
	# editable options
	
	clipboard = None
	p_layout = None
	# constructor
	def __init__(self, **keyword_args):
		#call super
		screenlets.Screenlet.__init__(self, width=200, height=40, 
				**keyword_args)
		# set theme
		self.theme_name = "default"
		self.add_menuitem(_("Paste Command"), _("Paste"))
		# add default menu items
		#self.add_default_menuitems(DefaultMenuItem.XML)
		self.add_default_menuitems()
		
		# add options
		
		
	def __setattr__(self, name, value):
		# call Screenlet.__setattr__ in baseclass (ESSENTIAL!!!!)
		screenlets.Screenlet.__setattr__(self, name, value)

	
	def on_key_down(self, keycode, keyvalue, event):
		"""Called when a keypress-event occured in Screenlet's window."""
		key = gtk.gdk.keyval_name(event.keyval)
		if key == "Return" or key == "Tab":
		
			
			print  self.__query
			system(self.__query + ' &')
			self.__query = ''
			self.redraw_canvas()

			
			
		elif key == "BackSpace":
			self.__query = self.__query[:-1]
			self.redraw_canvas()
		elif key == "space":
			self.__query += " "
			self.redraw_canvas()
	
		else:
			self.__query += keyvalue
			self.redraw_canvas()

	def on_mouse_down(self, event):
		
		# filter events
		if event.button != 1 or event.type != gtk.gdk.BUTTON_PRESS:
			return False
		# recalculate cursor position
		x = event.x / self.scale
		y = event.y / self.scale
		# compute space between fields
		n = 1
		m = 10
		# find if a click occured over some field...
		if x >= 50 and x <= 190:
			if y >= m and y <= 100:
				d = y - m
				if d % (20 + m) <= 20:
					self.redraw_canvas()
					return True
		return False

	def on_focus(self, event):
		self.__has_focus = True
		#if self.__converter:
		#	self.__converter.replace = True
		self.redraw_canvas()

	def on_unfocus(self, event):
		self.__has_focus = False
		self.redraw_canvas()
	def menuitem_callback(self, widget, id):
		screenlets.Screenlet.menuitem_callback(self, widget, id)
		print id
		if id=="Paste Command":
			self.clipboard = gtk.clipboard_get()

		
			self.__query = self.clipboard.wait_for_text()
		
			self.redraw_canvas()	
	def on_draw(self, ctx):
		# if a converter or theme is not yet loaded, there's no way to continue
		# set scale relative to scale-attribute
		ctx.scale(self.scale, self.scale)
		# render background
		self.theme['background.svg'].render_cairo(ctx)
		self.theme['glass.svg'].render_cairo(ctx)
		# compute space between fields
		n = 1
		m = 10
		# draw fields
		ctx.save()
		ctx.scale(0.9, 0.9)
		self.theme.render(ctx, 'exe')
		ctx.restore()
		ctx.save()
		ctx.translate(50, m)
		for i in range(n):
			if self.__has_focus:
				self.theme['fieldh.svg'].render_cairo(ctx)
				# cursor: disabled - it looks weird
				ctx.rectangle(185, 3, 2, 16)
				ctx.fill()
			else:
				self.theme['field.svg'].render_cairo(ctx)
			ctx.translate(0, m + 20)
		ctx.restore()
		# render field names
		# ctx.save()
		if self.p_layout == None : 
                      self.p_layout = ctx.create_layout() 
                else: 
                      ctx.update_layout(self.p_layout)
		p_fdesc = pango.FontDescription()
		p_fdesc.set_family_static("Free Sans")
		p_fdesc.set_size(11 * pango.SCALE)
		self.p_layout.set_font_description(p_fdesc)
		self.p_layout.set_width(40 * pango.SCALE)
		# ctx.translate(10, m + 3)
		# ctx.set_source_rgba(0, 0, 0, 1)
		# for i in range(n):
		# 	self.p_layout.set_markup('<b>' 
		#			+ 'etst' 
		#			+ '</b>')
		#	ctx.show_layout(self.p_layout)
		#	ctx.translate(0, m + 20)
		#ctx.restore()
		# render field values
		ctx.save()
		ctx.translate(55, m + 3)
		self.p_layout.set_alignment(pango.ALIGN_RIGHT)
		self.p_layout.set_width(130 * pango.SCALE)
		self.p_layout.set_ellipsize(pango.ELLIPSIZE_START)
		
	
		self.p_layout.set_markup(self.__query)
		ctx.show_layout(self.p_layout)
		ctx.translate(0, m + 20)
		ctx.restore()
		# ...and finally something to cover this all
		
	
	def on_draw_shape(self, ctx):
		if self.theme:
			ctx.scale(self.scale, self.scale)
			# the background will serve well
			self.theme['background.svg'].render_cairo(ctx)
			self.theme.render(ctx, 'exe')
			if self.__has_focus:
				self.theme['fieldh.svg'].render_cairo(ctx)
				# cursor: disabled - it looks weird
				
			else:
				self.theme['field.svg'].render_cairo(ctx)


# If the program is run directly or passed as an argument to the python
# interpreter then create a Screenlet instance and show it
if __name__ == "__main__":
	import screenlets.session
	screenlets.session.create_session(ExecuteScreenlet)
