#!/usr/bin/env python

import cgi
import dbus
import dbus.glib
import curses
import gtk, gobject
import os
import sys
import select
from time import sleep
import thread
import threading, time


import signal

__module_name__ = "bmp-remote-curses"
__module_description__ = "BMPx Curses Remote Control by daelstorm (pre-alpha state, bear with me :P)"

prefix = '/usr/local'


version = "0.1.1"

class capturekeys( threading.Thread):
	def __init__(self, BMPMonitor):
		threading.Thread.__init__(self)

		self.BMPMonitor = BMPMonitor
		
		self.stdscr = curses.initscr()
		self.BMPMonitor.h, self.BMPMonitor.w = self.stdscr.getmaxyx()
		
	def run(self):
		while 1:
			keys = []

			try:
				c = self.BMPMonitor.stdscr.getkey(self.BMPMonitor.h-3, self.BMPMonitor.edit.x+1)
				keys.append(c)
			except:
				pass

			if not keys:
				d = 1000
			else:
				d = 0

			sleep(0.01)
			while keys:
				
				c, keys = keys[0], keys[1:]
				
				try:
					
					if self.BMPMonitor.edit.process(c):
						line = self.BMPMonitor.edit.line
						#yes = self.BMPMonitor.commands(line)
						yes =1
						if yes == 0:
							break
						elif yes == 2:
							return
						else:
							self.BMPMonitor.edit.clear()
							self.BMPMonitor.edit.reset()
							
							
				except Exception, e:
					print e

		
class BMPMonitor(capturekeys):
    def __init__(self):
	    
	self.statusText = ''
	self.status=''
	self.title=''
	self.uri = ''
	self.metadata = []
	self.length = 0
	self.stdscr = None
	self.currentTrack = 0
	self.selectedTracks =[]
	self.highliteTrack =0

	# Init DBus shizzle
	self.bus = dbus.SessionBus()
	
	
	try:
		self.bmpx_obj = self.bus.get_object('org.beepmediaplayer.BMPx', '/org/beepmediaplayer/BMPx/BmpSystemControl')
		self.bmpx = dbus.Interface(self.bmpx_obj, 'org.beepmediaplayer.BMPx')
		self.bmpx.connect_to_signal('SetPlaystatus', self.bmpx_set_playstatus)
	except:
		print "ERROR: BMP-Curses Cannot Access BMPx via D-Bus"
		os._exit(1)

	self.capturekeys = capturekeys(self)
	self.stdscr = curses.initscr()
	curses.curs_set(0)
	curses.start_color()
	curses.noecho()
	self.stdscr.keypad(1)
	
	curses.mousemask(curses.BUTTON1_CLICKED)
	curses.mouseinterval(110)
	self.colors = {}
	if curses.has_colors() == True:
		try:
			curses.use_default_colors()
			curses.can_change_color()
			curses.init_pair(1, curses.COLOR_RED, -1)
			curses.init_pair(2, curses.COLOR_YELLOW, -1)
			curses.init_pair(3, curses.COLOR_CYAN, -1)
			curses.init_pair(4, curses.COLOR_BLUE, -1)
			curses.init_pair(5, curses.COLOR_GREEN, -1)
			curses.init_pair(6, curses.COLOR_BLACK, -1)
			curses.init_pair(7, curses.COLOR_WHITE, -1)
			curses.init_pair(8, curses.COLOR_MAGENTA, -1)
			curses.init_pair(9, 0, curses.COLOR_CYAN)
			curses.init_pair(10, curses.COLOR_GREEN, curses.COLOR_BLACK )
			curses.init_pair(11, curses.COLOR_YELLOW, curses.COLOR_BLUE)
			curses.init_pair(12, curses.COLOR_BLACK, curses.COLOR_WHITE)
			self.colors["red"] = curses.color_pair(1)
			self.colors["yellow"] = curses.color_pair(2)
			self.colors["cyan"] =  curses.color_pair(3)
			self.colors["blue"] = curses.color_pair(4)
			self.colors["green"] =  curses.color_pair(5)
			self.colors["black"] = curses.color_pair(6)
			self.colors["white"] = curses.color_pair(7)
			self.colors["magenta"] = curses.color_pair(8)
			self.colors["cyanbg"] = curses.color_pair(9)
			self.colors["greenbg"] = curses.color_pair(10)
			self.colors["hotkey"] = curses.color_pair(11)
			self.colors["blackfgcyanbg"] = curses.color_pair(12)
			
		except AttributeError:
			curses.init_pair(1, curses.COLOR_RED, 0)
			curses.init_pair(2, curses.COLOR_YELLOW, 0)
			curses.init_pair(3, curses.COLOR_CYAN, 0)
			curses.init_pair(4, curses.COLOR_BLUE, 0)
			curses.init_pair(5, curses.COLOR_GREEN, 0)
			curses.init_pair(6, curses.COLOR_BLACK, curses.COLOR_WHITE)
			curses.init_pair(7, curses.COLOR_WHITE, 0)
			curses.init_pair(8, curses.COLOR_MAGENTA, 0)
			curses.init_pair(9, 0, curses.COLOR_CYAN)
			curses.init_pair(10, curses.COLOR_GREEN, curses.COLOR_BLACK )
			curses.init_pair(11, curses.COLOR_YELLOW, curses.COLOR_BLUE)
			curses.init_pair(12, curses.COLOR_BLACK, curses.COLOR_WHITE)
			self.colors["red"] = curses.color_pair(1)
			self.colors["yellow"] = curses.color_pair(2)
			self.colors["cyan"] =  curses.color_pair(3)
			self.colors["blue"] = curses.color_pair(4)
			self.colors["green"] =  curses.color_pair(5)
			self.colors["black"] = curses.color_pair(6)
			self.colors["white"] = curses.color_pair(7)
			self.colors["magenta"] = curses.color_pair(8)
			self.colors["cyanbg"] = curses.color_pair(9)
			self.colors["blackfgcyanbg"] = curses.color_pair(12)
			self.colors["greenbg"] = curses.color_pair(10)
			self.colors["hotkey"] = curses.color_pair(11)
	else:
		self.colors["blackfgcyanbg"] = self.colors["hotkey"] = self.colors["greenbg"] =self.colors["cyanbg"] = self.colors["magenta"] = self.colors["white"] = self.colors["black"] = self.colors["green"] =  self.colors["blue"] = self.colors["cyan"] = self.colors["yellow"] = self.colors["red"] =  curses.color_pair(0)

	
	self.bmpx.connect_to_signal('SetStreamPos',  self.bmpx_set_stream_pos)
	self.bmpx.connect_to_signal('SetVolume',     self.bmpx_set_volume)
	self.bmpx.connect_to_signal('TrackChange',     self.bmpx_track_change)
	self.bmpx.connect_to_signal('TracklistItemsAdded',     self.bmpx_playlist_item_added)
	self.bmpx.connect_to_signal('TracklistItemsRemoved',       self.bmpx_playlist_item_removed)
	self.bmpx.connect_to_signal('TracklistListSorted',     self.bmpx_playlist_item_sorted)
	self.bmpx.connect_to_signal('ListAdded',     self.bmpx_playlist_added)

	self.bmpx.connect_to_signal('ListDeleted',     self.bmpx_playlist_item_sorted)
	self.bmpx.connect_to_signal('ListRenamed',     self.bmpx_playlist_item_sorted)
	#self.bmpx.connect_to_signal('AddUriList',     self.bmpx_playlist_new)
	self.bmpx.connect_to_signal('SetRepeat',     self.setrepeat)
	self.bmpx.connect_to_signal('SetShuffle',     self.setshuffle)
	self.bmpx.SendStatus()
	self.shuffle = self.bmpx.ShuffleGet()
	self.repeat = self.bmpx.RepeatGet()

	self.currentVolume = int( self.bmpx.VolumeGet() )
	
	
	self.set_title()
	
    def dummy(self, something):
	    self.mainwin.addstr(str( something))
	    self.mainwin.refresh()
	    pass

    def setshuffle(self, bool):
	    if bool != self.shuffle:
		self.shuffle = bool
		self.shuffwin.clear()
		if self.shuffle == True:
			self.shuffwin.addstr("Shuffle", self.colors["cyan"] )
		else:
			self.shuffwin.addstr("Shuffle", self.colors["red"] )
		self.shuffwin.refresh()
		
    def setrepeat(self, bool):
	   if bool != self.repeat:
		self.repeat = bool
		self.repwin.clear()
		if self.repeat == True:
			self.repwin.addstr("Repeat", self.colors["cyan"] )
		else:
			self.repwin.addstr("Repeat", self.colors["red"] )
		self.repwin.refresh()

    def set_title(self):
	    if os.path.expandvars("$SHELL") in  ("/bin/bash", "/bin/sh"):
		os.system("echo -ne \"\033]0;BMP-Curses %s: %s [%s]\007\" " %(version, self.title, self.statusText))	
		
    def bmpx_playlist_new(self, playlist_num):
	print playlist_num
	self.build_playlists(playlist_num)
	
    def bmpx_playlist_item_added(self, playlist_num, tracks, track_nums):
	#print "Playlist:", playlist_num, "Tracks:",tracks, "Number:",track_nums
	#sleep(1)
	self.build_playlists(playlist_num)
	
    def bmpx_playlist_added(self, playlist_num):
	#print self.bmpx.GetPlaylists()#self.playlists = self.bmpx.GetPlaylists()
	self.build_playlists(playlist_num)
	pass
	
    def bmpx_playlist_item_sorted(self, playlist_num):
	self.build_playlists(playlist_num)
	
    def bmpx_playlist_item_removed(self, playlist_num, tracks, track_nums):
	#print "Playlist:", playlist_num, "Tracks:",tracks, "Number:",track_nums
	#sleep(1)
	self.build_playlists(playlist_num)
	
    def bmpx_track_change(self):
	#print str(w)
	#print "EWerWE"
	if self.title != self.bmpx.GetCurrentTitle():
		self.title = self.bmpx.GetCurrentTitle()
		self.onlinetitle =  curses.newwin(1, self.w-12, 0, 0)
		self.onlinetitle.bkgdset(" ", curses.A_REVERSE | curses.A_BOLD)
		self.onlinetitle.idlok(1)
		self.onlinetitle.clear()
		try:
			#self.onlinestatus.clear()
			
			self.onlinetitle.addstr(str(self.title[:self.w-13]))
		except Exception, e:
			print "ERROR: title",e
		#sleep(5)
		#	pass
		self.onlinetitle.refresh()
	self.trackwin.clear()
	self.trackwin.addstr("Track: "+str(self.bmpx.GetCurrentTrack()+1))
	self.trackwin.refresh()
	#self.build_playlists()
	self.set_title()
	self.display_playlist( self.bmpx.GetCurrentTracklist())
		
    def bmpx_button_press(self, widget, event):
	    pass

    def bmpx_volume_changed(self, widget):
	
	volume = int(widget.get_value())

	if self.currentVolume != volume:
		self.currentVolume = volume
		self.bmpx.VolumeSet (volume)

    def bmpx_play_current(self, widget):
	self.bmpx.PlayCurrent()

    def bmpx_play_next(self, widget):
	self.bmpx.PlayNext()

    def bmpx_play_prev(self, widget):
	self.bmpx.PlayPrev()

    def bmpx_play_pause(self, widget):
	self.bmpx.PlayPause()

    def bmpx_play_stop(self, widget):
	self.bmpx.PlayStop()

    def update_info(self):
	#self.l_title.set_sensitive (1)

	self.uri = self.bmpx.GetCurrentUri()
	self.currentTrack = self.bmpx.GetCurrentTrack()+1
	self.metadata = self.bmpx.GetMetadataForUri(self.uri)
	'''
	if self.uri[-3:] in ("ogg", "mp3"):
		self.metadata = self.bmpx.GetMetadataForUri(self.uri)
		self.length = int(self.metadata['time'])

		artist = cgi.escape(self.metadata['artist'])
		title = cgi.escape(self.metadata['title'])
		album = cgi.escape(self.metadata['album'])
		artist_s = artist.strip()
		title_s = title.strip()
		album_s = album.strip()
	else:
		self.length = 0
	'''
	#self.title= '(%d)  %s \'%s\' (%s)' % (self.currentTrack+1, artist_s, title_s, album_s)
	
	return 1

    def bmpx_set_volume(self, volume):

	self.currentVolume = int(volume)

	self.volwin.clear()
	self.volwin.addstr("Vol: "+str(self.currentVolume))
	self.volwin.refresh()

    def bmpx_set_stream_pos(self, stream_pos):
	minutes = int(stream_pos) / int(60)
	seconds = stream_pos % 60;
	self.current_pos = stream_pos
	minutes_length = int(self.length) / int(60)
	seconds_length = int(self.length) % int(60)

	self.statusnew ='%2.2d:%2.2d / %2.2d:%2.2d' % (minutes, seconds, minutes_length, seconds_length)
	if self.status != self.statusnew:
		self.status = self.statusnew
		try:
			self.onlinetime.clear()
			self.onlinetime.addstr(self.status)
			self.onlinetime.refresh()
		except Exception, e:
			print ""
			#print "Eeeeeeeeee", e

    def bmpx_set_playstatus(self, playstatus):

	if playstatus == 2:	    #Stopped
	    self.statusText = 'STOPPED'
	    self.update_info()
	elif playstatus == 4:	    #Playing
	    self.statusText = 'PLAYING'
	    self.update_info()
	elif playstatus == 8:	    #Paused
	    self.statusText = 'PAUSED'
	self.onlinestatus =  curses.newwin(1, 10, 0, self.w-10)
	self.onlinestatus.idlok(1)
	self.onlinestatus.clear()
	
	try:
		self.onlinestatus.addstr(self.statusText)
		self.onlinestatus.refresh()
	except Exception, e:
		print ""
		#print "Eeeeeeeeee", e

	if self.title != "":
		self.set_title()

	return 1
	
    def run(self):
		self.capturekeys.start()
			
    def build(self, stdscr, line = ""):
		self.stdscr = stdscr
		self.stdscr.clear()
		self.stdscr.refresh()
		self.h, self.w = self.stdscr.getmaxyx()
		#if  self.h >=15 and self.w >=77:
		try:
			
			continue_build = 1
			uri = self.bmpx.GetCurrentUri()
			#if uri[-3:] in ("ogg", "mp3"):
			#	metadata = self.bmpx.GetMetadataForUri(uri)

			if self.title != self.bmpx.GetCurrentTitle():
				self.title = self.bmpx.GetCurrentTitle()
				self.set_title()
				continue_build = 1
				
			self.highliteTrack=self.bmpx.GetCurrentTrack()

			self.mainowin =  curses.newwin(self.h-1, self.w-15, 1, 0)
			self.mainowin.idlok(1)
			self.mainowin.clear()
			self.mainowin.border()
			self.mainowin.refresh()
			
			self.mainwin =  self.mainowin.subwin(self.h-3, self.w-17, 2, 1)
			self.mainwin.scrollok(1)
			self.mainwin.idlok(1)
			
			
			self.build_playlists(-1)
			
			
			self.instructions =  curses.newwin(13, 15, 6, self.w-15)
			self.instructions.idlok(1)
			self.instructions.clear()
			self.instructions.addstr("\nFor help, \nPress ? ")
			self.instructions.refresh()
			
			
			self.trackwin =  curses.newwin(1, 14, 3, self.w-15)
			self.trackwin.idlok(1)
			self.trackwin.clear()
			self.trackwin.addstr("Track: "+str(self.bmpx.GetCurrentTrack()+1))
			self.trackwin.refresh()
			
			
			self.onlinetime =  curses.newwin(1, 14, 1, self.w-15)
			self.onlinetime.idlok(1)
			self.onlinetime.clear()
			
			try:
				self.onlinetime.addstr(self.status)
				self.onlinetime.refresh()
			except Exception, e:
				print ""
				#print "Eeeeeeeeee", e
					
			if continue_build == 1:
				self.onlinetitle =  curses.newwin(1, self.w-11, 0, 0)
				self.onlinetitle.bkgdset(" ", curses.A_REVERSE | curses.A_BOLD)
				self.onlinetitle.idlok(1)
				try:
					self.onlinetitle.addstr(str(self.title[:self.w-12]))
				except Exception, e:
					print "title",e
					
				self.onlinetitle.refresh()
				
			self.volwin =  curses.newwin(1, 14, 2, self.w-15)
			self.volwin.idlok(1)
			self.volwin.clear()
			self.volwin.addstr("Vol: "+str(self.currentVolume))
			self.volwin.refresh()
			
			self.repwin =  curses.newwin(1, 14, 4, self.w-15)
			self.repwin.idlok(1)
			self.repwin.clear()
			if self.repeat == True:
				self.repwin.addstr("Repeat", self.colors["cyan"] )
			else:
				self.repwin.addstr("Repeat", self.colors["red"] )
			
			self.repwin.refresh()
			
			

			

			self.shuffwin =  curses.newwin(1, 14, 5, self.w-15)
			self.shuffwin.idlok(1)
			self.shuffwin.clear()
			if self.shuffle == True:
				self.shuffwin.addstr("Shuffle", self.colors["cyan"] )
			else:
				self.shuffwin.addstr("Shuffle", self.colors["red"] )
			self.shuffwin.refresh()

			self.editwin = curses.newwin(1, self.w-3, self.h-4, 1)
			
			
		except Exception, e:
			print e
			
		try:
			self.edit = editor(self.editwin, self.escaped, line)
			self.stdscr.nodelay(1)	
		except Exception,e :
			print e
		sleep(0.01)
		
    def build_playlists(self, value):
	try:
		
		self.playlists = self.bmpx.GetPlaylists()
		
		self.playlist_dict = {}
		
		x = 0 # playlist number
		for playlist in self.playlists:
			if int(value) != -1: # Specific Playlist chooser
				if x != int(value):
					x += 1
					continue
			t =0
			self.playlist_dict[x] = []
			
			thelist = self.bmpx.GetPlaylist(x)

			if  thelist == []:
				continue
			
			for track in thelist:
				ta = str(t+1) # add 1 for zero correction
				while len(ta) <3:
					ta = " "+ta
				tra = "[%s] " % ta # track number
				
				if track[-3:] in ("ogg", "mp3"):
					metadata = self.bmpx.GetMetadataForUri(track)
					length = int(metadata['time'])
					artist = cgi.escape(metadata['artist']).strip()
					artist = artist.replace("&amp;", "&")
					title = cgi.escape(metadata['title']).strip()
					title = title.replace("&amp;", "&")
				else:
					length = 0
					artist = ""
					title = track
				'''
				else:
					length = 0
					artist = ""
					title = track[:-4]
					
				'''
				trackname = "[%s] %s" % ( artist,  title)
				
				minutes = int(length)/60
				seconds = str( int(length) - (60 * minutes))
				minutes= str(minutes)
				if len(minutes) < 2:
					minutes = '0' + minutes
				if len(seconds) < 2:
					seconds = '0' + seconds
				
				if len(trackname) > self.w-30:
										
					string = str(tra)+str(trackname[:self.w-30-len(trackname)]+" "+str(minutes)+":"+seconds )
					
				else:
					b = str(tra)+str(trackname)
					while len(b) < self.w-23:
						b+=" "
					string = b+str(minutes)+":"+seconds
					
				self.playlist_dict[x].append([t, string])
			
				t +=1
			x += 1
			
		self.display_playlist(self.bmpx.GetCurrentTracklist())

		
	except Exception, e:
		print  "ERROR playlist: " + str(e)
	
	
    def display_playlist(self, playlist):
	# Draw Current Playlist Title in bold, others normally
	self.playlists = self.bmpx.GetPlaylists()
	self.current_playlist = self.bmpx.GetPlaylists()[self.bmpx.GetCurrentTracklist()]
	
	self.mainowin.border()
	pos = 2
	try:
		
		for playlists in self.playlists:
			
			if pos > self.w-20:
				break
			if playlists ==  self.current_playlist:
				self.mainowin.addstr( 0, pos, "< ")
				pos += 2
				self.mainowin.addstr( 0, pos, playlists , curses.A_BOLD | self.colors["cyan"])
				pos +=len(playlists)
				self.mainowin.addstr( 0, pos, " >")
				pos += 3
			else:
				self.mainowin.addstr( 0, pos, "< "+ playlists + " >")
				pos = pos + len(playlists)+4 +1
	except Exception,e:
		print e
	self.mainowin.refresh()
	
	# Draw playlist
	self.mainwin.clear()
	playlength = len(self.playlist_dict[playlist])

	try:
		height = self.h-3
		from_a = self.highliteTrack-height/2
		
		if from_a < 0:
			to = self.highliteTrack+(height-height/2)-from_a
			from_a = 0
		else:
			to = self.highliteTrack+(height-height/2)
		#debug scrolling
		#self.mainowin.addstr(str(from_a)+"::"+str(to) )
		#self.mainowin.refresh()
		#sleep(1)
		self.current = self.bmpx.GetCurrentTrack()
		self.mainwin.scrollok(0)
		for t, string in self.playlist_dict[playlist][from_a:to]:
				
			if t == self.current:
				
				try:
					if t == self.highliteTrack:
						self.mainwin.addstr( string,curses.A_BOLD | self.colors["cyan"] | curses.A_REVERSE )
					else:
						self.mainwin.addstr( string,curses.A_BOLD | self.colors["cyan"] )
					self.mainwin.addstr( "\n")
				except:
					pass
				#self.mainwin.refresh()
				#sleep(1)
			elif t in self.selectedTracks:
				try:
					self.mainwin.addstr( string, curses.A_REVERSE | self.colors["yellow"])
					self.mainwin.addstr( "\n")
				except Exception, e:
					
					pass
			elif t == self.highliteTrack:
				try:
					self.mainwin.addstr( string, curses.A_REVERSE )
					#self.mainwin.addstr( string, curses.A_REVERSE |, curses.color_pair(4) )
					self.mainwin.addstr( "\n")
				except Exception, e:
					
					pass
			else:
				
				
				try:
					self.mainwin.addstr( string )
					self.mainwin.addstr( "\n")
				except:
					pass
	except Exception, e:
		print e
	self.mainwin.refresh()
	
    def escaped(self, key, line):
		#print key
		if key == "KEY_RESIZE":
			self.stdscr.keypad(1)
			self.build(self.stdscr, line)
		elif key in( "KEY_LEFT", "CC", chr(2)):#  "KEY_RIGHT", chr(6) ):
# 			if self.current_pos != 0:
# 				percent = self.length*(float(self.current_pos)/1000)
# 			else:
# 				percent=0
			#self.mainwin.addstr( "\npercent: " +str(self.length) + "* "+str(float(self.current_pos)/100)+ "="+str(percent) )
			#self.mainwin.refresh()
			
			#self.bmpx.Seek(int(percent))
			#self.bmpx.SetStreamPos()
			pass
		elif key in ("KEY_UP"):#,  "KEY_DOWN", "KEY_PPAGE", "KEY_NPAGE"):
			if self.currentVolume < 100:
				self.bmpx.VolumeSet (self.currentVolume+1)

		elif key in ("KEY_DOWN"):
			if self.currentVolume > 0:
				self.bmpx.VolumeSet (self.currentVolume-1)
				
		elif key == "KEY_PPAGE":
			self.highliteTrack -= self.h-3
			if self.highliteTrack <0:
				self.highliteTrack=0
			self.display_playlist(self.bmpx.GetCurrentTracklist())
		elif key == "KEY_NPAGE":
			if self.highliteTrack < len(self.playlist_dict[self.bmpx.GetCurrentTracklist()]) -1:	
				self.highliteTrack += self.h-3
				if self.highliteTrack > len(self.playlist_dict[self.bmpx.GetCurrentTracklist()]) -1:
					self.highliteTrack =  len(self.playlist_dict[self.bmpx.GetCurrentTracklist()]) -1
				self.display_playlist(self.bmpx.GetCurrentTracklist())
		elif key == "scroll_up":
			if self.highliteTrack > 0: # len(self.playlist_dict[self.current_playlist]
				self.highliteTrack -= 1
				self.display_playlist(self.bmpx.GetCurrentTracklist())
		elif key == "scroll_down":
			if self.highliteTrack < len(self.playlist_dict[self.bmpx.GetCurrentTracklist()]) -1:
				self.highliteTrack += 1
				self.display_playlist(self.bmpx.GetCurrentTracklist())
		elif key == "a":
			'''
			try:
				#array = dbus.Array([], signature="s")
				array = []
				directory = "/home/daelstorm/music/Games/"
				dirs = os.listdir(directory)
				#print dirs
				#path = "/home/daelstorm/music/Games/v-e1m1.mp3"
				for path in dirs:
					if path[-3:] in ("ogg", "mp3"):
						array.append("file://"+directory+path)
				
			except Exception,e:
				print e
			self.bmpx.AddUriList(array, 0, 0)
			'''
			pass
		elif key == "r":
			if self.repeat == False:
				self.bmpx.RepeatSet(True)
			else:
				self.bmpx.RepeatSet(False)

		elif key == "s":
			if self.shuffle == False:
				self.bmpx.ShuffleSet(True)
			else:
				self.bmpx.ShuffleSet(False)
		elif key == "o":
			self.build(self.stdscr, line)
			#cself.build_playlists(-1)
		elif key == "?":
			self.instructions.clear()
			self.instructions.addstr(\
"Control BMPx"\
"\n-----------"\
"\n|z|x|c|v|b|"\
"\nReload: Alt-O"\
"\nVol: Alt-Up"\
"\n     Alt-Down"+\
"\nSwitch list: L\n"+\
"\nScroll List:"\
"\nUp/Down"\
"\nPgUp/PgDown"\
"\n-----------")
			self.instructions.refresh()
			pass
		elif key in ( "l", "L"):
			#print "Hmm"#, # len (self.playlists)
			
			self.playlists = self.bmpx.GetPlaylists()
			#print self.playlists
			#sleep(13)
			self.selectedTracks = []
			if len (self.playlists) > 1:
				self.current = self.bmpx.GetCurrentTracklist()
				#print self.current
				l = 0
				for lists in self.playlists:
					#print lists
					if self.current+1 == l:
						self.bmpx.CurrentTracklistSet(l)
						#print l
						break

					if  self.current+2 > len (self.playlists):

						self.bmpx.CurrentTracklistSet(0)
					l += 1
				
				self.current = self.bmpx.GetCurrentTracklist()
				#print self.current
				if self.highliteTrack > len(self.playlist_dict[self.bmpx.GetCurrentTracklist()]) -1:
					self.highliteTrack = len(self.playlist_dict[self.bmpx.GetCurrentTracklist()]) -1
				self.display_playlist( self.bmpx.GetCurrentTracklist())
		elif key == "KEY_IC":
			
			if self.highliteTrack  in self.selectedTracks:
				self.selectedTracks.remove(self.highliteTrack )
			else:
				self.selectedTracks.append(self.highliteTrack )
		elif key == "d":
			if self.selectedTracks != []:
				self.bmpx.TracklistRemoveItems(self.bmpx.GetCurrentTracklist(), self.selectedTracks, len(self.selectedTracks))
			else:
				self.bmpx.TracklistRemoveItems(self.bmpx.GetCurrentTracklist(), [self.highliteTrack], 1)
			self.selectedTracks = []
			#print self.selectedTracks
		elif key == "KEY_F(1)":
			#self.chat_mode()
			self.build(self.stdscr, line)
		elif key in ( "z", "Z"):
			if self.bmpx.GetCurrentTrack() != 0:
				self.bmpx.PlayPrev()
		elif key in ( "x", "X"):
			if self.bmpx.GetCurrentTrack() != -1:
				self.bmpx.PlayCurrent()
			else:
				self.bmpx.PlayNext()
		elif key in ( "c", "C"):
			self.bmpx.PlayPause()
		elif key in ( "v", "V"):
			self.bmpx.PlayStop()
		elif key in ( "b", "B"):
			#print self.bmpx.GetCurrentTrack() 
			#self.mainwin.addstr( "\nkeys: " + str(self.bmpx.GetCurrentTrack()) )
			#self.mainwin.refresh()
			self.bmpx.PlayNext()
		elif key == chr(10) or key == "KEY_ENTER":
			self.bmpx.PlayTrack(self.highliteTrack)
	
class editor:
	def __init__(self, win, escaped, line = ""):
		self.win = win
		self.escaped = escaped
		self.h, self.w = win.getmaxyx()
		self.scroll = 0
		
		self.line = line
		self.x = len(self.line)
		#self.fixpos()
		self.escape = False
		self.y = None

		

	def process(self, c):
		#pos = self.x + self.scroll
		
		# debugging: display keypress
		#print c
		
		if c in ('z', 'Z','x','X','c', 'v','V','b'):
			#BMPMonitor.bmpx.PlayPrev()
			self.escaped(c, self.line)
		elif c == chr(10) or c == "KEY_ENTER":
			self.escape = False
			self.escaped(c, self.line)
		elif c == "KEY_LEFT" or c == chr(2) or c == "KEY_RIGHT" or c == chr(6):
			if self.escape:
				self.escaped(c, self.line)
		elif c in ("KEY_F(1)", "?", "a"):
			self.escaped(c, self.line)
		#, "KEY_F(1)"
		elif c == "KEY_PPAGE":
			self.escaped(c, self.line)
		elif c == "KEY_NPAGE":
			self.escaped(c, self.line)
		elif c in ("KEY_UP", "KEY_DOWN"):
			if self.escape:
				self.escaped(c, self.line)
			else:
				if c == "KEY_UP":
					c = "scroll_up"
					self.escaped(c, self.line)
				elif c == "KEY_DOWN":
					c = "scroll_down"
					self.escaped(c, self.line)
		elif c in ("r", "s", "o", "d"):
			if self.escape:
				self.escaped(c, self.line)
		elif c == "KEY_IC": # Insert
			self.escaped(c, self.line)
		elif c in (	"L", "l"):
			self.escaped(c, self.line)
		elif c == chr(27):
			self.escape = True
			return False
		else: 
			return False
		#self.fixpos()
		
		self.escape = False
		return False


	def reset(self):
		self.x = self.scroll = 0
		self.line = ""

		#self.win.erase()
		self.win.refresh()
			
class MainApp:
	def __init__(self):



		self.app = BMPMonitor()
		
	def MainLoop(self):

		signal.signal(signal.SIGINT, signal.SIG_DFL)

		
		#self.app.MutrayWindow.show()
		self.app.build(self.app.stdscr, line)
		
		Mapp.app.capturekeys.start()
		gtk.gdk.threads_enter()
		gtk.main()
		gtk.gdk.threads_leave()
		
gobject.threads_init()
#c = BMPMonitor()
Mapp = MainApp()

line = ""

try:
	Mapp.MainLoop()
	sleep(0.01)

except Exception, e:
	pass
# 	try:
# 		curses.nocbreak()
# 		Mapp.stdscr.keypad(0)
# 		curses.echo()
# 		curses.endwin()
# 	except:
# 		pass
# 
# 	print "main:", e
# curses.nocbreak()
# Mapp.stdscr.keypad(0)
# curses.echo()
#curses.endwin()
