#!/usr/bin/env python

#
#CPU Meter
#Copyright (C) 2007 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 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.
#
#You should have received a copy of the GNU General Public License
#along with this program; if not, write to the Free Software
#Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
#

import screenlets
from screenlets.options import FloatOption, BoolOption, StringOption, FontOption, ColorOption, IntOption
import cairo
import pango
import sys
import re
import gobject
from screenlets import DefaultMenuItem
import os
from os import popen
import time
import commands
import screenlets.sensors
#use gettext for translation
import gettext

_ = screenlets.utils.get_translator(__file__)

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

@tdoc

class CPUMeterScreenlet(screenlets.Screenlet):
	"""Shows information about your system"""
	
	# default meta-info for Screenlets
	__name__ = 'CPUMeterScreenlet'
	__version__ = '0.9.1'
	__author__ = 'Helder Fraga aka Whise'
	__desc__ = __doc__

	# internals
	__timeout = None
	
	#editable options
	font_name = "Free Sans 11"
	update_interval = 1
	rgba_color = (1.0, 1.0, 1.0, 0.9)
	text_x = 15
	text_y = 25

	show_load = True

	show_usedmem = True


	p_layouta = None
	p_layout = None
	def __init__(self, **keyword_args):
		screenlets.Screenlet.__init__(self, width=198, height=159, 
			uses_theme=True, **keyword_args)
		self.theme_name = "default"
		self.add_default_menuitems(DefaultMenuItem.XML)
		self.add_default_menuitems()
		
		self.__timeout = gobject.timeout_add(int(1000), self.update)
	def __setattr__(self, name, value):
		screenlets.Screenlet.__setattr__(self, name, value)
		if name in ('show_uptime', 'show_temperature', 
				'show_hostname', 'show_load', 
				'show_usedmem', 'show_freemem',
				'text_x', 'text_y', 'font_name', 
				'rgba_color', 'show_upspeed',
				'show_downspeed', 'show_diskusage',
				'disk_name', 'disk_value', 'temperature_location',
				'use_fahrenheit'):
			if self.window:
				self.redraw_canvas()

				
	def on_menuitem_select(self, id):
		"""handle MenuItem-events in right-click menu"""
		if id[:5] == "exec:":
			# execute shell command
			os.system(id[5:] + " &")
				
	
	# timeout-function
	def update(self):
		self.redraw_canvas()
		return True
		

		
	def get_load(self):
		"""Get average load"""
		data = commands.getoutput("cat /proc/stat")


		self.u2 = float( data.split()[1] )
		self.n2 = float( data.split()[2] )
		self.s2 = float( data.split()[3] )
		self.i2 = float( data.split()[4] )
		#print str(u1) +'      ' + str(n1) +'      ' + str(s1) +'      ' + str(i1)

		#datas = commands.getoutput("cat /proc/stat")

		#print str(u2) +'      ' + str(n2) +'      ' + str(s2) +'      ' + str(i2)
		try:
			usage = (self.u2-self.u1) + (self.n2 - self.n1) + (self.s2 - self.s1)
			total = (self.u2-self.u1) + (self.n2 - self.n1) + (self.s2 - self.s1) + (self.i2 -self.i1)
			lo = (usage/total)* 100
		except:
			lo = 0		
	
		self.load = str(lo)

		self.u1 = self.u2
		self.n1 = self.n2
		self.s1 = self.s2
		self.i1 =	self.i2

		return  str(lo)
		
		
	def get_mem(self):
		"""Get used memory"""
		meminfo = commands.getoutput('cat /proc/meminfo').splitlines()
		
		mem = {}
		for line in meminfo:
			if line.startswith('MemTotal'):
				mem['total'] = line.split()[1]
			elif line.startswith('Cached'):
				mem['cached'] = line.split()[1]
			elif line.startswith('Buffers'):
				mem['buffers'] = line.split()[1]
			elif line.startswith('MemFree'):
				mem['free'] = line.split()[1]

		return mem

		
	def on_draw(self, ctx):
		ctx.scale(self.scale, self.scale)
		ctx.set_operator(cairo.OPERATOR_OVER)
		if self.theme:
			self.theme.render(ctx, 'back')
		#	self.theme.render(ctx, 'dialdot')
		ctx.save()
		#ctx.translate(self.text_x, self.text_y)

		if self.show_load == True:
			load = "" # "<b>Load average:</b> " + self.get_load() + "\n"
			self.get_load()
			lo = int(float(self.load))
			if lo > 99:
				lo = 99
			elif lo < 0:
				lo=0

#self.theme['cpumeter-graph-bg.svg'].render_cairo(ctx)
			w = (float(lo) / 100.0) * 200.0
			#print "width: "+str(w)
			# get step
			#steps_height = 7
			#h = 40
			ctx.save()
			ctx.rectangle(0, 0, 200, 200)
			#ctx.rectangle(20, 15+(70-h), 60, h)
			ctx.clip()
			#ctx.new_path()
			
			ctx.translate(65,82)
			ctx.rotate (-4-(lo*(-5.1))/110)
			#print str((lo*(-5.1))/100)
			print 'CPU - '  + str(lo)
			#ctx.translate(26,28)
			self.theme.render(ctx, 'dial')
			#self.theme['dia.svg'].render_cairo(ctx)
			ctx.restore()
			ctx.save()
			ctx.translate(58,110)
			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(8 * pango.SCALE)
			self.p_layout.set_font_description(p_fdesc)
			a = str(lo)
			if len(a) == 1 : a = '0' + a
			self.p_layout.set_markup('<b>' +a[:2] + '%</b>' )
			ctx.set_source_rgba(1,1,1,1)
			ctx.show_layout(self.p_layout)
			ctx.fill()
			ctx.restore()
			#p_layout.set_width(((self.width - self.text_x) * pango.SCALE))
		

		if self.show_usedmem == True:
			mem = self.get_mem()
			usedmem = int(mem['total'])/1024 - int(mem['cached'])/1024 - int(mem['buffers'])/1024 - int(mem['free'])/1024
			freemem = int(mem['cached'])/1024 + int(mem['buffers'])/1024 + int(mem['free'])/1024
			
			loa = float(usedmem)
			loa = loa + float(freemem)
			loa = float(usedmem) / loa
			loa = loa * 100
			print 'Mem - ' + str(loa)
			#if loa > 99:
			#	loa = 99
			#elif loa < 0:
			#	loa=0
			
#self.theme['cpumeter-graph-bg.svg'].render_cairo(ctx)
			w = (float(loa) / 100.0) * 200.0
			#print "width: "+str(w)
			# get step
			#steps_height = 7
			#h = 40
			
			ctx.save()
			ctx.rectangle(0, 0, 300, 300)
			#ctx.rectangle(20, 15+(70-h), 60, h)
			ctx.clip()
			#ctx.new_path()
			ctx.translate(141,49)
			ctx.rotate (-4-(loa*(-5.1))/110)
			#print str((lo*(-5.1))/100)
			
			#ctx.translate(26,28)
			self.theme.render(ctx, 'dial2')
			#self.theme['ram.svg'].render_cairo(ctx)
			ctx.restore()
			ctx.save()
			ctx.translate(134,67)
			if self.p_layouta == None :
	
				self.p_layouta = ctx.create_layout()
			else:
			
				ctx.update_layout(self.p_layouta)
			p_fdesc = pango.FontDescription()
			p_fdesc.set_family_static("Free Sans")
			p_fdesc.set_size(8 * pango.SCALE)
			self.p_layouta.set_font_description(p_fdesc)
			a = str(loa)
			self.p_layouta.set_markup('<b>' + a[:2] + '%'+ '</b>')
			ctx.set_source_rgba(1,1,1,1)
			ctx.show_layout(self.p_layouta)
			ctx.fill()
			ctx.restore()
			usedmem = "" #"<b>Memory used:</b> " + self.get_usedmem()  + str(loa) + " MB\n"
		else:
			usedmem = ""
		#p_layout.set_markup(om + hostname + uptime \
		#				+ temperature + load \
		#				+ usedmem + freemem + diskusage + cm)
		
		if self.theme:
		#	self.theme.render(ctx, 'back')
			self.theme.render(ctx, 'dialdot')		
	def on_draw_shape(self,ctx):
		ctx.scale(self.scale, self.scale)
		if self.theme:
			
			self.theme.render(ctx, 'back')
			self.theme.render(ctx, 'dialdot')
						
	

if __name__ == "__main__":
	import screenlets.session
	screenlets.session.create_session(CPUMeterScreenlet)

