Newer
Older
Import / projects / LGN-IP3870 / t / new / sdmmc.py
from basemodel import Stage, NotifyStage, ListStage
import baseui
import config
import os, utils
import runtime
import uiconfig
import phonesetting
import phonedb
import dircache
import shutil
import status
import time
from setting import setting

bt_depth = 0

def sort_list(choice, mode, directory, fsize = None, cdir = None):
	files = []
	direct = []

	index = 0
	for z in choice:
		if z.endswith('/') or z.endswith('../'):
			direct.append(z)
		elif mode != 'filetosdmmc2':

			if mode == 'filefromsdmmc' or mode == 'filefrombluetooth':
				if mode == 'filefrombluetooth':
					filesize = (int(fsize[index])+1023) / 1024
				else:
					filesize = utils.get_size_kb(cdir + z)
				if directory.find('photo') != -1:
					if z.endswith('.jpg') or z.endswith('.gif') or z.endswith('.png') or z.endswith('.jpeg') or z.endswith('.bmp')\
						or z.endswith('.JPG') or z.endswith('.GIF') or z.endswith('.PNG') or z.endswith('.JPEG') or z.endswith('.BMP'):
						z = z + ' ['+str(filesize)+'kb]'
						files.append(z)

				elif directory.find('audio') != -1:
					if z.endswith('.mid') or z.endswith('.imy') or z.endswith('.amr') or z.endswith('.wav') or z.endswith('.mp3') \
						or z.endswith('.MID') or z.endswith('.IMY') or z.endswith('.AMR') or z.endswith('.WAV') or z.endswith('.MP3'):
						z = z + ' ['+str(filesize)+'kb]'
						files.append(z)

				elif directory.find('video') != -1:
					if z.endswith('.3gp') or z.endswith('.mp4') \
						or z.endswith('.3GP') or z.endswith('.MP4'):
						z = z + ' ['+str(filesize)+'kb]'
						files.append(z)
			else:
				if fsize:
					filesize = (int(fsize[index])+1023) / 1024
				else:
					filesize = utils.get_size_kb(directory+z)

				z = z + ' ['+str(filesize)+'kb]'
				files.append(z)
			index += 1

	choice = direct + files

	return choice

def inserted_sdmmc():
	'''
	try:
		os.system('mount > /tmp/sdmmc_mount')

		fp = open('/tmp/sdmmc_mount')
		str_m = fp.read()
	except:
		str_m = ''

	if str_m.find('/dev/mmcda1 on /usr/mmchd') >= 0:
		return True
	return False
	'''

	return os.path.exists(config.sdmmc_dir)


def inserted_usb():
	if mount_usb():
		print 'ka....#### insert success'
		os.system('cd /mnt')
		os.system('sync')
	else:
		print 'ka....#### insert fail'
		

def umount_usb():
	os.system('cd /')
	os.system('umount /mnt')
	os.system('sync&')	
	
def mount_usb():
	os.system('echo 1 > /proc/sys/lvp3870/usb_uart_switch')
	os.system('sync')
	os.system('mount -t vfat /dev/sda1 /mnt -o iocharset=cp949 2> /tmp/usb_mount')

	try:
		fp = open('/tmp/usb_mount')
		str_m = fp.read()
	except:
		str_m = ''
	os.system('rm -rf /tmp/usb_mount')

#	if str_m.find('/dev/mmcda1 on /usr/mmchd') >= 0:
	if len(str_m) == 0:
		return True
	else:
		return False
#	return os.path.exists(config.usb_dir)


class CopyNotifyStage(NotifyStage):
	def __init__(self, message,cb=None, icon = uiconfig.baloon_copy_icon):
		NotifyStage.__init__(self, message, icon, cb)

class CheckListStage(Stage):
	def __init__(self, mode, direc, tmp1 = None, tmp2= None, chk_choice = None): #tmp1, tmp2는 filetosdmmc2, frombt 사용
		self.dir_list = []
		self.mode = mode
		self.direc = direc
		self.tmp1 = tmp1
		self.tmp2 = tmp2
		self.chk_choice = chk_choice
		self.choice = self.get_flist()
		if mode == 'filefromsdmmc':
			self.title = _('COPY FROM SD/MMC')
		elif mode == 'filetosdmmc' or mode == 'filetosdmmc2':
			self.title = _('COPY TO SD/MMC')
		elif mode == 'filetobluetooth' or mode == 'filetobluetooth2': #filetobluetooth
			self.title = _('COPY TO BLUETOOTH')
		elif mode == 'filefrombluetooth':
			self.title = _('COPY FROM BLUETOOTH')
		elif mode == 'filefromusb':
			self.title = _('COPY FROM USB')
		elif mode == 'filetousb' or mode == 'filetousb2':
			self.title = _('COPY TO USB')

		self.dlist_index = 0
		if mode == 'filetosdmmc2' or self.choice[0] == '/' or self.choice[0] == './':
			self.ui = baseui.CheckListUI( '', _('COPY'), self.title)
		else:
			self.ui = baseui.CheckListUI(_('SELECT'), _('COPY'), self.title)

		self.ui.set_list(self.choice)

	def destroy(self):
		os.system('sync&')
#		os.system('umount /usr/mmchd')
		self.ui.destroy()

	def get_flist(self):
		choice = None
		if self.mode == 'filefromsdmmc' or self.mode == 'filetosdmmc2':
			start_dir = config.sdmmc_dir
		elif self.mode == 'filetosdmmc':
			start_dir = self.direc
		elif self.mode == 'filefromusb' or self.mode == 'filetousb2':
			start_dir = config.usb_dir
		elif self.mode == 'filetousb':
			start_dir = self.direc
#		elif self.mode == 'filetobluetooth': #filetobluetooth
#			start_dir = self.direc
			

		if self.mode == 'filefrombluetooth':
			choice, self.tmp2 = bt_ftpParsing(self.direc)
		elif self.mode == 'filetobluetooth2':
			choice = bt_ftpParsing(self.direc, 1)

		else:
			self.dir_list.append(start_dir)

			choice = os.listdir(self.dir_list[len(self.dir_list) - 1])


		if self.mode == 'filetosdmmc2' or self.mode == 'filetousb2': #only directory show

			dircache.annotate(self.dir_list[0], choice)
			choice.insert(0,'/')

			tmp = []
			for z in choice:
				if z.endswith('/'):
					tmp.append(z)

			return tmp

		else:  #dirctry, file.. show

			if self.mode == 'filefrombluetooth' or self.mode == 'filetobluetooth2':
				if bt_depth > 0:
					choice.insert(0 ,'../')

			else: #if bfirst == True: # and self.mode != 'filefrombluetooth':
				dircache.annotate(self.dir_list[0], choice) #if directory... / add
				choice.insert(0,'/')	 # root display

			if len(self.dir_list) == 0:
				if self.mode == 'filefrombluetooth':
					choice = sort_list(choice, self.mode, self.tmp1, self.tmp2)
				else:
					choice = sort_list(choice, self.mode, self.direc, self.tmp2) #, self.dir_list[len(self.dir_list) - 1])
			else:
				choice = sort_list(choice, self.mode, self.direc, self.tmp2, self.dir_list[len(self.dir_list) - 1])

			return choice

	def handle_key(self, key):
		global bt_depth
		if key == config.Menu1: # and self.mode != 'filetosdmmc2':

			cur_choice = self.choice[self.ui.get_focus()]
			if cur_choice == '/' or cur_choice == './':
				return

			elif cur_choice.endswith('../'):
				if self.mode == 'filefrombluetooth' or self.mode == 'filetobluetooth2':
					bt_depth -= 1
					runtime.btapp.bt_flist = []
					runtime.btapp.fEnd = '2'
					runtime.btapp.send_message('20|V') #x|'+cur_choice)

					if self.mode == 'filetobluetooth2':
						runtime.manager.change_stage(phonesetting.BluetoothWaitStage(self.tmp1, 4, self.tmp2, self.chk_choice))
					else:
						runtime.manager.change_stage(phonesetting.BluetoothWaitStage(self.tmp1))
					return

				self.dlist_index -= 1
				self.dir_list.pop()
				cur_directory = self.dir_list[self.dlist_index]

				try:
					self.choice = os.listdir(cur_directory)
				except:
					runtime.manager.change_stage(CopyNotifyStage(_('Insert SD/MMC Card'), icon = uiconfig.baloon_sd_mmc_icon))
					return

				dircache.annotate(cur_directory, self.choice)
				if self.dlist_index == 0:
					self.choice.insert(0, '/')
				else:
					self.choice.insert(0, '../')

				if self.mode == 'filefromsdmmc' or self.mode == 'filefromusb':
					os.system('sync&')
				self.choice = sort_list(self.choice, self.mode, self.direc, cdir = self.dir_list[self.dlist_index])

				if self.mode == 'filetosdmmc2' or self.mode == 'filetousb2':	#only show directory
					tmp_list = []
					for z in self.choice:
						if z.endswith('/')  or z.endswith('..'):
							tmp_list.append(z)
					self.choice = tmp_list

				self.ui.destroy()
				if  self.choice[0] == '/':
					self.ui = baseui.CheckListUI( '', _('COPY'),  self.title, None)
				else:
					self.ui = baseui.CheckListUI(_('SELECT'), _('COPY'),  self.title, None)
				self.ui.set_list(self.choice)
				self.ui.show()
				return

			elif cur_choice.endswith('/'):# and cur_choice != '/':
				if self.mode == 'filefrombluetooth' or self.mode == 'filetobluetooth2':
					bt_depth += 1

					runtime.btapp.bt_flist = []
					runtime.btapp.fEnd = '2'
					runtime.btapp.send_message('20|x|'+cur_choice[:-1])

					if self.mode == 'filetobluetooth2':
						runtime.manager.change_stage(phonesetting.BluetoothWaitStage(self.tmp1, 4, self.tmp2, self.chk_choice))
					else:
						runtime.manager.change_stage(phonesetting.BluetoothWaitStage(self.tmp1))
					return

				else:
					cur_directory = self.dir_list[self.dlist_index] + cur_choice
					self.dlist_index += 1
					self.dir_list.append(cur_directory)

					try:
						self.choice = os.listdir(cur_directory)
					except:
						runtime.manager.change_stage(CopyNotifyStage(_('Insert SD/MMC Card'), icon = uiconfig.baloon_sd_mmc_icon))
						return

					if self.mode == 'filefromsdmmc' or self.mode == 'filefromusb':
						os.system('sync&')

					dircache.annotate(cur_directory, self.choice)
					self.choice.insert(0, '../')

				self.choice = sort_list(self.choice,  self.mode, self.direc, cdir = self.dir_list[self.dlist_index])

				if self.mode == 'filetosdmmc2' or self.mode == 'filetousb2':	#only show directory
					tmp_list = []
					for z in self.choice:
						if z.endswith('/') or z.endswith('../'):
							tmp_list.append(z)

					self.choice = tmp_list

				self.ui.destroy()
				self.ui = baseui.CheckListUI(_('SELECT'), _('COPY'),  self.title, None)
				self.ui.set_list(self.choice)
				self.ui.show()
				return

			self.ui.toggle()
			return True

		elif key == config.Menu2:
			def fileSelectchk():
				count_checked = 0
				for z in self.ui.list.checked:
					if z == True:
						count_checked += 1
				return count_checked

			if self.mode == 'filetosdmmc2' or self.mode == 'filetousb2':
				des_dir = self.dir_list[len(self.dir_list)-1]
				self.ui.list.checked = self.direc
				self.choice = self.tmp1
				self.dir_list = self.tmp2

			elif self.mode == 'filetosdmmc':

#				os.system('mount -t vfat /dev/mmcda1 /usr/mmchd/')

				if fileSelectchk() == 0:
					runtime.manager.stack_stage(CopyNotifyStage(_('No file selected.')))
					return

				if inserted_sdmmc() == False:
					runtime.manager.stack_stage(CopyNotifyStage(_('Insert SD/MMC Card'), icon = uiconfig.baloon_sd_mmc_icon))
				else:
					runtime.manager.stack_stage(FileSelectStage('filetosdmmc2', self.ui.list.checked, self.choice, self.dir_list))
				return

			elif self.mode == 'filefromsdmmc':

				if fileSelectchk() == 0:
					runtime.manager.stack_stage(CopyNotifyStage(_('No file selected.')))
					return

				des_dir = self.direc

			elif self.mode == 'filetousb':

				if fileSelectchk() == 0:
					runtime.manager.stack_stage(CopyNotifyStage(_('No file selected.')))
					return

#				if inserted_usb() == False:
#					runtime.manager.stack_stage(CopyNotifyStage(_('Insert USB'), icon = uiconfig.baloon_sd_mmc_icon))
#				else:
				runtime.manager.stack_stage(FileSelectStage('filetousb2', self.ui.list.checked, self.choice, self.dir_list))
				return

			elif self.mode == 'filefromusb':

				if fileSelectchk() == 0:
					runtime.manager.stack_stage(CopyNotifyStage(_('No file selected.')))
					return

				des_dir = self.direc





			'''
			elif self.mode == 'filetobluetooth':
				if fileSelectchk() == 0:
					runtime.manager.stack_stage(CopyNotifyStage(_('No file selected.')))
					return

				runtime.btapp.set_default()
				runtime.btapp.send_message('20|i')

				runtime.manager.stack_stage(phonesetting.BluetoothSearchStage(4, self.direc, self.ui.list.checked, self.choice))
				return

			elif self.mode == 'filetobluetooth2':
				runtime.btapp.set_default()

				src_file = []

				index = 0
				for z in self.tmp2:
					if z == True:
						src_file.append(self.chk_choice[index])

					index += 1

				runtime.manager.change_stage(BluetoothCopyingStage(self.tmp1, src_file))  #_('Copying...')))

				return

			elif self.mode == 'filefrombluetooth':
				if fileSelectchk() == 0:
					runtime.manager.stack_stage(CopyNotifyStage(_('No file selected.')))
					return

				runtime.btapp.set_default()
				index = 0
				fsize = 0
				src_file = []

				for z in self.ui.list.checked:
					if z == True:
						src_file.append(self.choice[index])

						fsize += int(self.tmp2[index-1])

					index += 1

				if len(os.listdir(self.tmp1)) + len(src_file) > config.limit_filecount:
					runtime.manager.stack_stage(CopyNotifyStage(_('Not enough memory.') +'\n'+ str(config.limit_filecount - len(os.listdir(self.tmp1))) + ' '+_('left only.')))
					return

				if utils.check_free_storage(self.mode, fsize/1024) == False:
					runtime.manager.stack_stage(CopyNotifyStage(_('Impossible to copy.') + '\n' + _('Memory exhausted.')))
					return

				runtime.manager.change_stage(BluetoothCopyingStage(self.tmp1, src_file, 1))
				return
			'''

			#free space check
			files_size = 0
			index = 0
			file_count = 0
			sel_choice = []
			try:
				for z in self.ui.list.checked:
					if z == True:
						src_file = self.dir_list[len(self.dir_list)-1] + self.choice[index][:self.choice[index].find(' [')]

						files_size += os.path.getsize(src_file)
						file_count += 1
						sel_choice.append(self.choice[index])
					index += 1
				files_size = files_size/1024
			except:
				runtime.manager.stack_stage(CopyNotifyStage(_('Insert SD/MMC Card.'), icon = uiconfig.baloon_sd_mmc_icon))
				return

			#free space check
#Roxia Begin smyook 06.02.13
			if utils.check_free_storage(self.mode, files_size) == False:
#Roxia End smyook
				runtime.manager.back_stage('copystage')
				runtime.manager.stack_stage(CopyNotifyStage(_('Impossible to copy.') + '\n' + _('Memory exhausted.')))
				return

			#한 폴더의 파일수 제한
			if len(os.listdir(des_dir)) + file_count > config.limit_filecount and self.mode == 'filefromsdmmc':
				runtime.manager.stack_stage(CopyNotifyStage(_('Not enough memory.') + '\n' + str(config.limit_filecount - len(os.listdir(des_dir))) + ' '+_('left only.')))
				return

			if self.mode != 'filefromsdmmc':
				try:
					os.system('sd_lock_check > /tmp/sdlockch')
					f = file('/tmp/sdlockch')
					sd_check = f.read()
					if sd_check[:6] == 'locked':
						runtime.manager.back_stage()
						runtime.manager.change_stage(CopyNotifyStage(_('SD/MMC is locked.'), icon = uiconfig.baloon_sd_mmc_icon))
						return
				except:
					pass

			runtime.manager.stack_stage(SdmmcCopyingStage(sel_choice, self.dir_list, des_dir, self.title, file_count))

			return True

		elif key == config.Red:
			if self.mode == 'filetobluetooth' or self.mode == 'filetobluetooth2' or self.mode == 'filefrombluetooth':
				bt_depth = 0
				runtime.btapp.set_default()
				runtime.btapp.send_message('20|v')
				runtime.btapp.send_message('20|D')
			runtime.manager.back_stage()
			return True

		elif key == config.Green or key == config.Video or key == config.OffHook:
			if self.mode == 'filetobluetooth' or self.mode == 'filetobluetooth2' or self.mode == 'filefrombluetooth':
				bt_depth = 0
				runtime.btapp.set_default()
				runtime.btapp.send_message('20|v')
				runtime.btapp.send_message('20|D')
			runtime.manager.back_stage('idle')
			runtime.evas.render_now()
			return

		return self.ui.handle_key(key)

class BluetoothCopyingStage(Stage):
	def __init__(self, direc, src_file, mode = 0):
		self.src_file = src_file
		self.direc = direc
		self.idx = 0

		self.cpfn = None
		self.bsend_msg = False


		message = _('Copying...')
		if mode == 0:
			title = _('COPY TO BLUETOOTH')
		else:
			title = _('COPY FROM BLUETOOTH')
		self.ui = phonesetting.BtYesNoUI(title, message, uiconfig.baloon_bluetooth_icon)

		if mode == 0:
			self.pfilet = utils.Timer(500,self.put_file)
		else:
			self.gfilet = utils.Timer(500,self.get_file)
		status.supervision_not_allowed = 1

	def destroy(self):
		status.supervision_not_allowed = 0
		if self.idx != len(self.src_file):
			runtime.btapp.send_message('20|R')
		runtime.btapp.send_message('20|v')
		runtime.btapp.set_default()
		self.gfilet = None
		self.pfilet = None
		if self.cpfn:
			self.cpfn.hide()
			self.cpfn.free()
		self.ui.destroy()

	def put_file(self):
		filename = self.src_file[self.idx][:self.src_file[self.idx].find(' [')]
		if self.bsend_msg == False:
			cpfile = (self.direc + filename, '/usr/local/bin/' + filename)
			shutil.copyfile(*cpfile)
		if os.path.exists(*('/usr/local/bin/'+ filename,)):
			if self.bsend_msg == False:
				runtime.btapp.send_message('20|z|' + filename)
				self.cpfn = runtime.evas.text(font=(uiconfig.def_font,14), color=uiconfig.baloon_text_color)

#Roxia Begin smyook 06.05.09
				#if len(filename) > 19:
				#	show_fn = filename[:18]+ '...'
				#else:
				#	show_fn = filename

				#self.cpfn.text = show_fn
				self.cpfn.text = utils.cut_text(filename, 290, uiconfig.baloon_font, with_punc=True)[0]
#Roxia End smyook
				self.cpfn.pos = ( 300 - self.cpfn.geometry[2] ) / 2, 130
				self.cpfn.show()
				self.bsend_msg = True

			#while 1:   #카피 완료 후
			svalue = runtime.btapp.fEnd
			if svalue[0] == '1' or svalue[0] == '0':
				self.cpfn.hide()
				self.cpfn.free()
				try:
					os.remove(*('/usr/local/bin/' + filename,))
				except:
					pass

				self.idx += 1
				self.bsend_msg = False
				if runtime.btapp.fEnd.find('operation aborted') != -1:
					runtime.manager.back_stage('copystage')
					runtime.manager.change_stage(CopyNotifyStage(_('Operation Aborted')))
					bt_depth = 0
					return

		if self.idx == len(self.src_file):
			runtime.manager.back_stage('copystage')
			runtime.manager.stack_stage(CopyNotifyStage(_('Copy completed')))
			bt_depth = 0
		else:
			runtime.btapp.fEnd = '2'
			self.pfilet = utils.Timer(500, self.put_file)

	def get_file(self):
		filename =  self.src_file[self.idx][:self.src_file[self.idx].find(' [')]
		if self.bsend_msg == False:
			self.cpfn = runtime.evas.text(font=(uiconfig.def_font,14), color=uiconfig.baloon_text_color)

#Roxia Begin smyook 06.05.09
			#if len(filename) > 19:
			#	show_fn = filename[:18]+ '...'
			#else:
			#	show_fn = filename

			#self.cpfn.text = show_fn
			self.cpfn.text = utils.cut_text(filename, 290, uiconfig.baloon_font, with_punc=True)[0]
#Roxia End smyook
			
			self.cpfn.pos = ( 300 - self.cpfn.geometry[2] ) / 2, 130
			self.cpfn.show()
			runtime.btapp.send_message('20|Z|' + filename)
			runtime.btapp.fEnd = '2'
			self.bsend_msg = True

		svalue = runtime.btapp.fEnd
		if svalue[0] == '1':
			time.sleep(0.5)
			if os.path.exists(self.direc + filename):
				def yb():
					if filename.lower().endswith('.3gp') or filename.lower().endswith('.mp4'):

						if self.direc.find('recorded') != -1:
							if os.path.exists(config.video_recorded_thumnail_dir + filename[:-4] + '.png'):
								os.remove(*(config.video_recorded_thumnail_dir + filename[:-4] + '.png',))
						else:
							if os.path.exists(config.video_received_thumnail_dir + filename[:-4] + '.png'):
								os.remove(*(config.video_received_thumnail_dir + filename[:-4] + '.png',))

					rname = ('/usr/local/bin/' + filename, self.direc + filename)
					os.rename(*rname)
					runtime.manager.back_stage()
					self.cpfn.hide()
					self.cpfn.free()
					self.idx += 1
					self.bsend_msg = False

					if self.idx == len(self.src_file):
						runtime.manager.back_stage('copystage')
						runtime.manager.stack_stage(CopyNotifyStage(_('Copy completed')))
						bt_depth = 0
					else:
						runtime.btapp.fEnd = '2'
						self.gfilet = utils.Timer(500, self.get_file)

				def nb():
					try:
						os.remove(*('/usr/local/bin/' + filename,))
					except:
						pass

					runtime.manager.back_stage()
					self.cpfn.hide()
					self.cpfn.free()
					self.idx += 1
					self.bsend_msg = False

					if self.idx == len(self.src_file):
						runtime.manager.back_stage('copystage')
						runtime.manager.stack_stage(CopyNotifyStage(_('Copy completed')))
						bt_depth = 0
					else:
						runtime.btapp.fEnd = '2'
						self.gfilet = utils.Timer(500, self.get_file)


				runtime.manager.stack_stage(AlreadyExistStage(filename, yb, nb, uiconfig.baloon_bluetooth_icon))
				return

			else:
				self.cpfn.hide()
				self.cpfn.free()
				rname = ('/usr/local/bin/' + filename, self.direc + filename)
				os.rename(*rname)

				self.idx += 1
				self.bsend_msg = False
		elif svalue[0] == '0':
			self.cpfn.hide()
			self.cpfn.free()
			self.idx += 1
			self.bsend_msg = False

			if runtime.btapp.fEnd.find('operation aborted') != -1:
				runtime.manager.back_stage('copystage')
				runtime.manager.change_stage(CopyNotifyStage(_('Operation Aborted')))
				bt_depth = 0
				return
		if self.idx == len(self.src_file):
			runtime.manager.back_stage('copystage')
			runtime.manager.stack_stage(CopyNotifyStage(_('Copy completed')))
			bt_depth = 0
		else:
			self.gfilet = utils.Timer(500, self.get_file)


	def handle_key(self, key):

		if key == config.Menu2 or key == config.Red:
			runtime.manager.back_stage('copystage')
			runtime.manager.stack_stage(CopyNotifyStage(_('Copy canceled')))

		elif key == config.Green or key == config.Video or key == config.OffHook:
			runtime.manager.back_stage('idle')
			runtime.evas.render_now()
			return
		else: return False
		return True

class AlreadyExistStage(Stage):
	agenda_forbidden = True
	def __init__(self, item, replace_cb, ignore_cb, icon = uiconfig.baloon_phonebook_icon):
		# remain copy list
		message = item + '\n' + _('already existing')
		self.ui = baseui.BaloonMessageUI(_('REPLACE'), _('IGNORE'), '', icon, message)
		self.replace_cb = replace_cb
		self.ignore_cb = ignore_cb

	def handle_key(self, key):
		if key == config.Menu1:
			self.replace_cb()
		elif key in (config.Menu2, config.Red):
			self.ignore_cb()
		elif key == config.Green or key == config.Video or key == config.OffHook:
			runtime.manager.back_stage('idle')
			return
		return True

class SdmmcYesNoUI(baseui.BaloonMessageUI):
	def __init__(self, title, message,icon):
		baseui.BaloonMessageUI.__init__(self, '', _('CANCEL'), title,icon, message)

class SdmmcCopyingStage(Stage):
	def __init__(self, filename, direc, des_dir, title, file_count):
		self.title = title
		message = _('Copying...')

		self.filename = filename
		self.direc = direc
		self.des_dir = des_dir

		self.ui = SdmmcYesNoUI(self.title, message, uiconfig.baloon_copy_icon)
		self.flag = 0
		self.index = 0
		self.count_selected = file_count
		self.count_cp = 0
		self.cpfn = None

		self.bexist = False

	def hide(self):
		self.cptimer = None
		if self.cpfn:
			self.cpfn.hide()
		Stage.hide(self)

	def show(self):
		self.get_list()
		Stage.show(self)

	def get_list(self):

		def cb():
			runtime.manager.back_stage('copystage')

		def copying():
			showtext = self.filename[self.index][:self.filename[self.index].find(' [')]
			if self.cpfn:
				self.cpfn.hide()
				self.cpfn.free()

			self.cpfn = runtime.evas.text(font=(uiconfig.def_font,14), color=uiconfig.baloon_text_color)

#Roxia Begin smyook 06.05.09
			#if len(showtext) > 19:
			#	show_fn = showtext[:18]+ '...'
			#else:
			#	show_fn = showtext
			self.cpfn.text = utils.cut_text(showtext, 290, uiconfig.baloon_font, with_punc=True)[0]
			#self.cpfn.text = show_fn
#Roxia End smyook
			self.cpfn.pos = ( 300 - self.cpfn.geometry[2] ) / 2, 130
			self.cpfn.show()
			runtime.evas.render_now()

			src_file = self.direc[len(self.direc)-1] + showtext

			if os.path.exists(self.des_dir+showtext) == 1 and self.bexist == False:

				def replace():
					sfile = (src_file, self.des_dir + showtext)
					self.index -= 1
					try:
						if showtext.lower().endswith('.3gp') or showtext.lower().endswith('.mp4'):

							if self.des_dir.find('recorded') != -1:
								if os.path.exists(config.video_recorded_thumnail_dir + showtext[:-4] + '.png'):
									os.remove(*(config.video_recorded_thumnail_dir + showtext[:-4] + '.png',))
							else:
								if os.path.exists(config.video_received_thumnail_dir + showtext[:-4] + '.png'):
									os.remove(*(config.video_received_thumnail_dir + showtext[:-4] + '.png',))
						self.bexist = True
					except:
						os.system('sync')
						self.cpfn.hide()
						self.cpfn.free()

					runtime.manager.back_stage()
					self.get_list()

				def ignore():
					if self.index == len(self.filename):
						if self.count_selected == 1:
							runtime.manager.change_stage(CopyNotifyStage(str(self.count_selected)+ ' '+_('file selected.') + '\n' + str(self.count_cp) +' '+_('entry copied.'), cb))
						else:
							runtime.manager.change_stage(CopyNotifyStage(str(self.count_selected)+ ' '+_('files selected.') + '\n' + str(self.count_cp) + ' '+_('entries copied.'), cb))
						return
					else:
						runtime.manager.back_stage()
						self.get_list()

				runtime.manager.stack_stage(AlreadyExistStage(showtext, replace, ignore, uiconfig.baloon_sd_mmc_icon))
				self.index += 1
				self.cpfn.hide()
				return
			else:
				self.bexist = False
				sfile = (src_file, self.des_dir+ showtext)
				try:
					shutil.copyfile(*sfile)
				except:
					self.no_cb()
					return
				self.count_cp += 1

			self.index += 1

			os.system('sync')

			if self.flag == 1:  #canceled
				return

			if inserted_sdmmc() == False: #no card??
				runtime.manager.change_stage(CopyNotifyStage(_('Insert SD/MMC Card.'), cb, icon = uiconfig.baloon_sd_mmc_icon))
				return

			if self.index == len(self.filename):
				if self.count_selected == 1:
					runtime.manager.change_stage(CopyNotifyStage(str(self.count_selected)+ ' ' + _('file selected.') + '\n' + str(self.count_cp) +' '+_('entry copied.'), cb))
				else:
					runtime.manager.change_stage(CopyNotifyStage(str(self.count_selected)+ ' ' + _('files selected.') + '\n' + str(self.count_cp) +' '+_('entries copied.'), cb))
				return
			else:
				self.get_list()
		self.cptimer = utils.Timer(50, copying)

	def destroy(self):
		os.system('sync&')
		self.cptimer = None
		if self.cpfn:
			self.cpfn.hide()
			self.cpfn.free()
		self.ui.destroy()

	def no_cb(self):
		os.system('sync&')
		self.flag = 1
		self.cpfn.hide()
		self.cpfn.free()

		def cb():
			try:
				os.remove(*(self.des_dir + self.filename[self.index-1][:self.filename[self.index-1].find(' [')],))
			except:
				pass
			runtime.manager.back_stage('copystage')
		self.count_cp -= 1
		if self.count_cp < 0:
			self.count_cp =0
		runtime.manager.change_stage(CopyNotifyStage(_('Copy canceled.') + '\n' + str(self.count_cp) +' '+_('entries copied.'), cb))

	def handle_key(self, key):
		if key in (config.Menu2,config.Red):
			self.no_cb()
			return True
		elif key == config.Green or key == config.Video or key == config.OffHook:
			self.cptimer = None
			if self.cpfn:
				self.cpfn.hide()
				self.cpfn.free()
			try:
				os.remove(*(self.des_dir + self.filename[self.index-1][:self.filename[self.index-1].find(' [')],))
			except:
				pass
			runtime.manager.back_stage('idle')
			runtime.evas.render_now()
			return

class InsertWaitingSDMMCStage(Stage):
	def __init__(self, mode= None, direc = None):
		status.supervision_not_allowed = 1
		self.mode = mode
		self.direc = direc
		self.bluetooths = []
		message = _('Insert SD/MMC Card')
		icon = uiconfig.baloon_sd_mmc_icon
		self.ui = phonesetting.BtYesNoUI(_('COPY'), message, icon)
		self.get_bcardt = utils.Timer(500, self.get_bcard)

	def destroy(self):
		status.supervision_not_allowed = 0
		self.get_bcardt = None
		self.ui.destroy()

	def get_bcard(self):
#		os.system('mount -t vfat /dev/mmcda1 /usr/mmchd/')

		if inserted_sdmmc() == True:
			runtime.manager.change_stage(FileSelectStage(self.mode, self.direc))
			return False

		return True

	def no_cb(self):
		self.get_bcardt = None
		runtime.manager.back_stage()

	def handle_key(self, key):
		if key == config.Red:
			self.get_bcardt = None
		elif key == config.Menu2:
			self.no_cb()
		return False

def bt_ftpParsing(value, mode = 0):
	choice = []
	choice_size = []
	only_direc = []

	for z in value:
		fname, fsize, bdirec = z.split('<>')
		fname = fname.strip()
		fsize = fsize.strip()
		bdirec = bdirec.strip()

		if bdirec == 'y':
			fname = fname + '/'

			if mode != 0:
				only_direc.append(fname)

		choice.append(fname)
		choice_size.append(fsize)

	if mode != 0:
		global bt_depth
		if len(only_direc) == 0 and bt_depth == 0:
			only_direc.append('./')
		return only_direc
	else:
		return [choice, choice_size]

class FileSelectStage(CheckListStage):  #파일 선택.. 탐색기 기능
	# filetobluetooth : tmp2 = chklist, chk_choice
	def __init__(self, mode, direc, tmp1 = None, tmp2 = None, chk_choice = None):   #mode: to or from , direc : src_direc
		self.mode = mode
		status.supervision_not_allowed = 1
		CheckListStage.__init__(self, mode, direc, tmp1, tmp2, chk_choice)

	def show(self):
		CheckListStage.show(self)

	def destroy(self):
		if self.mode != 'filefrombluetooth' and self.mode != 'filetobluetooth2':
			status.supervision_not_allowed = 0
		CheckListStage.destroy(self)

def make_vcard(checked = None, mode = 0):
	fp = open('phonenumber.txt')
	phdb_list = [] #all phonebook data list..
	phdb_name = [] # phonebook's names...
	for fline in fp:
		ph_db = fline.split('\t')
		phdb_name.append(ph_db[0])
		phdb_list.append(ph_db)

	if mode == 1:
		return phdb_name
	elif checked == None:
		checked = []
		for z in range(len(phdb_list)):
			checked.append(True)

	index = 0
	selected_fname = []
	for z in checked:   #선택된 데이터 vcard로 저장 후 카피
		if z == True:
			vcard = 'BEGIN:VCARD\n'
			vcard += 'VERSION:2.1\n'
			vcard += 'N:'+ str(phdb_list[index][0]) + '\n'
			vcard += 'TEL;HOME:' + str(phdb_list[index][1]) + '\n'
			vcard += 'TEL;CEL:' + str(phdb_list[index][2]) + '\n'
			vcard += 'EMAIL;INTERNET:' +str(phdb_list[index][3]) + '\n'
			vcard += 'TEL;FAX:' + str(phdb_list[index][4]) + '\n'
			vcard += 'END:VCARD'

			fname = 'VC' + str(index)+'.vcf'
			fp = open(fname, 'w')
			fp.write(vcard)
			fp.close()

			selected_fname.append(fname)

		index += 1
	return selected_fname

def vcard_parse(fname):
	fvcf = open(fname)

	name = ''
	home = ''
	cel = ''
	email = ''
	fax = ''

	for z in fvcf.readlines():
		if z.find('N:') >= 0:
			name = z[z.find('N:')+2:].strip()
		elif z.find('TEL;HOME:') >= 0:
			home = z[z.find('TEL;HOME:')+9:].strip()
		elif z.find('TEL;PREF;HOME:') >= 0:
			home = z[z.find('TEL;PREF;HOME:')+14:].strip()
		elif z.find('TEL;CEL:') >= 0:
			cel = z[z.find('TEL;CEL:')+8:].strip()
		elif z.find('TEL;PREF;CEL:') >= 0:
			cel = z[z.find('TEL;PREF;CEL:')+13:].strip()
		elif z.find('EMAIL;INTERNET:') >= 0:
			email = z[z.find('EMAIL;INTERNET:')+15:].strip()
		elif z.find('TEL;FAX:') >= 0:
			fax = z[z.find('TEL;FAX:')+8:].strip()

	item = phonedb.PhoneItem()
	item.name = name
	item.number = home
	item.mobile = cel
	item.email = email
	item.fax = fax

	return item

class CheckListStage2(Stage):
	def __init__(self, btvalue):
		self.choice = make_vcard(mode = 1)
		self.btvalue = btvalue
		self.ui = baseui.CheckListUI(_('SELECT'), _('COPY'), _('SELECT ENTRIES'))
		self.ui.set_list(self.choice)

	def handle_key(self, key):
		if key == config.Menu1:
			self.ui.toggle()
			return True
		elif key == config.Menu2:
			selected_check = 0
			for z in self.ui.list.checked:
				if z == True:
					selected_check += 1

			if selected_check == 0:
				runtime.manager.stack_stage(CopyNotifyStage(_('Select entry')))
				return

			runtime.btapp.set_default()
			runtime.manager.stack_stage(phonesetting.BluetoothCopyStage(self.btvalue, self.ui.list.checked))
			return True

		return self.ui.handle_key(key)

	def destroy(self):
		self.ui.destroy()

class CopyToPbBTStage(CheckListStage2):  #phonenumber.txt 에 저장된 내용 파싱후 이름 리스트 보여줌
	title = _('SELECT ENTRIES')

	def __init__(self, mode = None):
		CheckListStage2.__init__(self, mode)

class AcceptRequestStage(Stage):
	name = 'btaccept'
	def __init__(self, item, mode = 0): #, yes_cb, no_cb):
		status.bluetooth_activated = True
		self.mode = mode
		icon = uiconfig.baloon_bluetooth_icon
		self.fname = item[4:item.find('is')].strip()

		if self.fname.endswith('vcf'):
			item = vcard_parse(self.fname)
			message = item.name + _('`s vcf') + '\n' + _('received.') + ' ' + _('Save in phonebook?')
			self.ui = baseui.BaloonMessageUI(_('YES'), _('NO'), '', icon, message)
		elif mode == 0:
			message = item + '\n' + _('Accept?')
			self.ui = baseui.BaloonMessageUI(_('YES'), _('NO'), '', icon, message)
		else:
			message = self.fname + '\n' + _('is received')
			self.ui = baseui.BaloonMessageUI(_('OK'), '', '', icon, message)
		status.save_callback = self.save_callback

	def save_callback(self):
		runtime.btapp.send_message('20|Y|0')
		runtime.manager.back_stage()
		runtime.btapp.set_default()
		self.show_time = None
		return None, None
	def hide(self):
		self.show_time = None
		Stage.hide(self)

	def show(self):
		if setting.screen_saver_enabled:
			setting.reset_screen_saver_timer()
			status.screensaver_activated = False
		self.show_time = utils.Timer(10000, self.time_out)
		Stage.show(self)

	def destroy(self):
		status.save_callback = None
		self.show_time = None
		self.ui.destroy()

	def time_out(self):
		if self.mode == 1: #vcf -> phonenumber.txt
			self.save_pb()
		else:
			runtime.btapp.send_message('20|Y|0')
			runtime.manager.back_stage()
		runtime.btapp.set_default()
		self.show_time = None

	def save_pb(self):
		if self.fname.endswith('vcf'):
			free_slot = config.phone_db_size - phonedb.phonedb.count()

			if free_slot <= 0:
				message = _('Memory full') + '\n' + self.fname + ' '+_('not copied')

				runtime.manager.change_stage(CopyNotifyStage(message))
				return False

			item = vcard_parse(self.fname)

			if phonedb.phonedb.has_name(item.name):
				def yes():
					phonedb.phonedb.remove(phonedb.phonedb.find_by_name_near(item.name))
					phonedb.phonedb.insert_item(item)
					try:
						os.remove(*('/usr/local/lgvp/' + self.fname,))
					except:
						pass

					runtime.manager.back_stage()
				def no():
					try:
						os.remove(*('/usr/local/lgvp/' + self.fname,))
					except:
						pass
					runtime.manager.back_stage()

				runtime.manager.change_stage(AlreadyExistStage(item.name, yes, no))
			else:
				phonedb.phonedb.insert_item(item)
				try:
					os.remove(*('/usr/local/lgvp/' + self.fname,))
				except:
					pass
				runtime.manager.back_stage()
		else:
			runtime.manager.back_stage()

	def handle_key(self, key):
		status.bluetooth_activated = False
		if key == config.Menu1:
			self.show_time = None
			if self.mode == 1: #vcf -> phonenumber.txt
				self.save_pb()
			else:
				runtime.btapp.send_message('20|Y|1')
				runtime.manager.back_stage()
		elif key in (config.Menu2, config.Red):
			runtime.btapp.set_default()
			self.show_time = None
			if self.mode != 1:
				runtime.btapp.send_message('20|Y|0')
				runtime.manager.back_stage()
			else:
				if self.fname.endswith('vcf'):
					try:
						os.remove(*('/usr/local/lgvp/' + self.fname,))
					except:
						pass
					runtime.manager.back_stage()
			return True
		elif key == config.Green or key == config.Video or key == config.OffHook:
			self.show_time = None
			runtime.btapp.set_default()
			runtime.btapp.send_message('20|Y|0')
			runtime.manager.back_stage('idle')
			runtime.evas.render_now()
			return


class PlayingCheckListStage(ListStage):
	name = 'PlayingCheckList'
	icon = uiconfig.image_sound_icon
	def __init__(self, mode, direc):

		self.direc = direc
		self.mode = mode
			
		if mode == 'Playingfromsdmmc':
			self.title = _('PLAYING FROM SD/MMC')
		else:
			self.title = _('PLAYING FROM USB')
			self.usb_mount()

		self.choice = self.get_flist()
		
		ListStage.__init__(self, choice=self.choice, title=self.title, icon=self.icon)

		self.audio_index = 0
		self.player_pid = None
		
	def usb_mount(self):
		os.system('echo 1 > /proc/sys/lvp3870/usb_uart_switch')
		os.system('sync')
		os.system('mount -t vfat /dev/sda1 /mnt -o iocharset=cp949')
		os.system('sync')
		os.system('cd /mnt')
		os.system('sync')

	def usb_umount(self):
		os.system('cd /')
		os.system('umount /mnt')
		os.system('sync')	

	def get_flist(self):
		choice = []
		all_list = os.listdir(self.direc)
		for i in range(len(all_list)):
			if all_list[i].lower().endswith('.mp3'): #or all_list[i].lower().endswith('.wav'):
				choice.append(all_list[i])
		return choice

	def get_current_file(self):
		return self.direc + self.choice[self.audio_index]

	def play_audio(self):
		if status.phone_status != status.Disconnected:
			return
		if len(self.choice) == 0:
			return
		audio_file = self.get_current_file()
		if audio_file.lower().startswith(config.sdmmc_dir):
			audio_file = audio_file.replace(config.sdmmc_dir, '/mfs/sd/')
		self.player_pid = utils.player.play(audio_file)

	def stop_audio(self):
		if status.phone_status != status.Disconnected:
			return
		if not self.player_pid:
			return 
		utils.player.stop(self.player_pid)

	def show(self):
		os.system('fb0top 0')
		self.play_audio()
		ListStage.show(self)

	def hide(self):
		self.stop_audio()
		if self.mode == 'Playingfromusb':
			self.usb_umount()
		ListStage.hide(self)

	def destroy(self):
		os.system('fb0top 1')
		self.stop_audio()
		if self.mode == 'Playingfromusb':
			self.usb_umount()
		ListStage.destroy(self)

	def handle_key(self, key):
		ret = ListStage.handle_key(self, key)
		if key in ('Up', 'Down'):
			new_audio_index = self.ui.get_focus()
			runtime.evas.render_now()
			if self.audio_index != new_audio_index:
				self.audio_index = new_audio_index
				self.stop_audio()
				self.play_audio()
		return ret


		

# KA: [20080221] SDMMC
#class CopyToFromStage(ListStage):
class PlayingFromStage(ListStage):
	name = 'PlayingFrom'
	icon = uiconfig.image_sound_icon
	def __init__(self):			
		self.title = _('Playing From')
		self.choice = _('Playing from SD/MMC'), _('Playing from USB')

		ListStage.__init__(self, self.choice, self.title)

	def activate(self, index):
		if index == 0:
			dir_path = config.sdmmc_dir
			if not self.check_module(dir_path):
				runtime.manager.change_stage(CopyNotifyStage(_('SD/MMC is not inserted.'), icon = uiconfig.baloon_sd_mmc_icon))
			else:
				runtime.manager.stack_stage(PlayingCheckListStage('Playingfromsdmmc', dir_path))
		elif index == 1:
			self.dir_path = config.usb_dir
			runtime.manager.stack_stage(PlayingCheckListStage('Playingfromusb', self.dir_path))

	def check_module(self, path):
		return os.path.exists(path)


class TemperatureUI(baseui.SmallWindowUI):
	def __init__(self):
		title = _('Temperature & humid')
		baseui.SmallWindowUI.__init__(self,_('UPDATE'), _('BACK'), title)
		try:
			os.system('th_test_onetime.bin > /tmp/temperature.txt')
			fp = open('/tmp/temperature.txt')
			temperature = fp.readline().strip()
			fp.close()
		except:
			pass

		self.data = runtime.evas.text(text=temperature, pos = (50, 110), font=(uiconfig.def_font,14), color = uiconfig.list_text_color)
		self.add(self.data)

	def show(self):
		try:
			os.system('th_test_onetime.bin > /tmp/temperature.txt')
			fp = open('/tmp/temperature.txt')
			temperature = fp.readline().strip()
			fp.close()
		except:
			pass
		
		self.data.text_set(temperature)
		baseui.SmallWindowUI.show(self)
	

class StereoBalanceStage(ListStage):
	name = 'StereoBalance'
	icon = uiconfig.image_sound_icon
	def __init__(self):
		self.title = _('StereoBalance check')
		self.choice = _('Left side'), _('Right side')

		ListStage.__init__(self, choice=self.choice, title=self.title, icon=self.icon, left=_('PLAY'), right=_('BACK'))
		self.pid = None

	def activate(self, index):
		self.play_audio(index)
		self.update_softkey()

	def update_softkey(self):
		self.show()
	
	def show(self):
		ListStage.show(self)
		if self.pid:
			self.ui.set_right(_('STOP'))
		else:
			self.ui.set_right(_('BACK'))

	def destroy(self):
		ListStage.destroy(self)
		if self.pid:
			self.stop_audio()
		
	def play_audio(self, index):
		if index == 0:
			path = '4' # left stereo
		else:
			path = '5' # right stereo

		runtime.SP_context.SP_stereoPlayback()
			
		self.pid = os.fork()
		if self.pid == 0:
			try:
				file = '/usr/local/lgvp/100_500_1K_1.5K_2K_3K_4K_5K_6K_7K.wav'
				file = ('--loop', file, path)
				command = ('playulaw','playulaw') + file
				
				os.execlp(*command)
			except:
				os._exit(1)

		if config.utils_debug:
			print 'player: pid=', self.pid, 'child handler', self.old_sigchild
		return self.pid

	def stop_audio(self):
		if not self.pid:
			return 
		try:
			import signal
			os.kill(self.pid, signal.SIGKILL)
			if config.utils_debug:
				print 'now call waitpid', self.pid
			os.waitpid(self.pid, 0)
		except:
			if config.utils_debug:
				print 'fail to kill!!!'

		self.pid = None
				
		runtime.SP_context.SP_stereoStopPlayback()			

	def handle_key(self, key):
		if key == config.Menu2:
			if self.pid:
				self.stop_audio()
				self.update_softkey()
				return True

		ret = ListStage.handle_key(self, key)
		if key in ('Up', 'Down'):
			if not self.pid:
				self.stop_audio()
		return ret