# File Browser and Editor Version 0.2
# This software is under GPL
# All Nokia components have Copyright (c)  by Nokia 2004
# Some parts of the code are from Nokia's filebrowser.py and 
# from discussions on Nokia developer forum
# by Stefan Mueller-Stach 
# - this version has been modded by Zen - z-en@seznam.cz

import os
import appuifw
import e32
import dir_iter
import sys
import codecs
from key_codes import *    
             
class myeditor:
    def __init__(self):
        self.script_lock = e32.Ao_lock()
        self.dir_stack = []
        self.current_dir = dir_iter.Directory_iter(e32.drive_list())
        self.last_find=""

    def cd(self,iter,dir,up=True):
     list=iter.list_repr()
     list=self.first(list)
     if up==True:
      list=self.upperlist(list)
      dir=dir.upper().strip()
 #    if list.find(dir)!=-1:  
     iter.add(list.index(dir))
     return iter

    def begin(self):
     appuifw.app.body.set_pos(0)

    def find(self,text=""):
     t=appuifw.app.body.get()[appuifw.app.body.get_pos()+3:].upper()
     if text=="": 
      f=appuifw.query(u"Find text:",'text',self.last_find).upper()
     else:
      f=self.last_find.upper()

     self.last_find=f.lower()
     p=t.find(f)+appuifw.app.body.get_pos()
     if p==-1+appuifw.app.body.get_pos():
      if appuifw.query(u"Not found. Go to begin?",'query'):
       self.appuifw.app.body.set_pos(0)
       self.find(f)
     else:
      appuifw.app.body.set_pos(p+3)

    def upperlist(self,list):
      newlist=[]
      for i in range(0, len(list)):
       if list[i] != None:
        newlist.append(list[i].upper())
      return newlist 


    def first(self,tup):
     a=[]
     for i in range(0,len(tup)):
      a.append(tup[i][0])
     return a

    def go(self):
     self.current_dir = dir_iter.Directory_iter(e32.drive_list())
     self.current_dir=self.cd(self.current_dir,u"E:")
     self.current_dir=self.cd(self.current_dir,u"[SYSTEM]")
     self.current_dir=self.cd(self.current_dir,u"[APPS]")
     self.current_dir=self.cd(self.current_dir,u"[PYTHON]")
     self.current_dir=self.cd(self.current_dir,u"[my]",False)
     self.dir_stack=[0,0,0,0,0,0,0]
     os.mkdir("E:/System/Apps/Python/my/z/")

     self.current_dir=self.cd(self.current_dir,u"[z]")
     os.rmdir("E:/System/Apps/Python/my/z/")
     self.observe(0)
 
    def showmenu(self):
     m=[u"def declaration",u"class declaration",u"for cycle",u"for i in range cycle",u"main function",u"import",u"import all"]
     i=appuifw.popup_menu(m)
     if i!=None:
      pos=appuifw.app.body.get_pos()
      text1=appuifw.app.body.get(0,appuifw.app.body.get_pos())
      if i==0:
       text2="def ():\n   \n   "
       pos+=4
      elif i==1:
       text2="class :\n def __init__(self):\n  \n  "
       pos+=6
      elif i==2:
       text2="for in :\n \n "
       pos+=4
      elif i==3:
       text2="for i in range(, ):\n \n"
       pos+=15
      elif i==4:
       text2="if __name__ == \"__main__\":\n main()"
       pos+=len(text2)
      elif i==5:
       text2="import "
       pos+=6
      elif i==6:
       text2="from  import *"
       pos+=5
      text3=appuifw.app.body.get(appuifw.app.body.get_pos())
      appuifw.app.body.set(text1+text2+text3)
      appuifw.app.body.set_pos(pos)

    def runpy(self):
     ch=appuifw.Content_handler()
     ch.open_standalone(self.path)  

    def cycle(self):
     if appuifw.app.body.current()==0:
      appuifw.app.body.set_list(self.entries,len(self.entries)+1)

    def run(self):
        entries = self.current_dir.list_repr()
        if not self.current_dir.at_root:
            entries.insert(0, (u"..", u""))
        self.entries=entries
        self.lb = appuifw.Listbox(entries, self.observe)
        self.lb.bind(EKeyLeftArrow, lambda: self.observe(0))
        self.lb.bind(EKeyRightArrow, self.observe)
        self.lb.bind(EKeyYes, self.go)
        self.lb.bind(EKeyUpArrow, self.cycle)
        old_title = appuifw.app.title
        self.refresh()
        self.script_lock.wait()
        appuifw.app.title = old_title
        appuifw.app.body = None
        self.lb = None

    def refresh(self):
        appuifw.app.title = u"file browser and editor"
        appuifw.app.menu = []
        appuifw.app.exit_key_handler = self.exit_key_handler
        appuifw.app.body = self.lb

    def do_exit(self):
        self.exit_key_handler()

    def exit_key_handler(self):
        appuifw.app.exit_key_handler = None
        self.script_lock.signal()
 

    def observe(self, ind = None):
        if not ind == None:
            index = ind
        else:
            index = self.lb.current()
        focused_item = 0
        if self.current_dir.at_root:
            self.dir_stack.append(index)
            self.current_dir.add(index)
        elif index == 0:                    
            focused_item = self.dir_stack.pop()
            self.current_dir.pop()
        elif os.path.isdir(self.current_dir.entry(index-1)):
            self.dir_stack.append(index)
            self.current_dir.add(index-1)
        else:
            self.item = self.current_dir.entry(index-1)
            path=unicode(os.path.splitext(self.item)[0]+os.path.splitext(self.item)[1])
            self.path=path
            i = appuifw.popup_menu([u"Edit (UTF-8)", u"Delete", u"Move to c:", u"Exit"])
            if i ==0:
                appuifw.app.body = appuifw.Text()
                appuifw.app.body.bind(EKeyYes,self.showmenu) 
                (encoding,decoding,reader,writer) = codecs.lookup('UTF-8')
                input = reader(open(path,'rb'))
                appuifw.app.body.set(input.read())
                appuifw.app.menu = [(u'Save', self.save), (u'Find',self.find),(u'Go to begin',self.begin),(u'Run py',self.runpy),(u'Quit', self.quit)]
            elif i == 1:
                if appuifw.query(u"Really delete entry?",'query'):
                    os.remove(self.item)
                    focused_item = index - 1
                else:
                    pass
            elif i == 2:
                if appuifw.query(u"Really move to c:?",'query'):
                    file=appuifw.query(u"New file name (optional)?:", 'text')
                    if file:
                       os.rename(path,u"c:\\nokia\\others\\"+unicode(file))
                    else:
                        pass
                else:
                    pass
            else:
                if appuifw.query(u"Really exit?",'query'):
                    self.do_exit()
                else:
                    pass
        entries = self.current_dir.list_repr()
        if not self.current_dir.at_root:
            entries.insert(0, (u"..", u""))
        self.lb.set_list(entries, focused_item)
        self.entries,self.cur=entries,self.lb.current()==0        

    def save(self):
        path=unicode(os.path.splitext(self.item)[0]+os.path.splitext(self.item)[1])
        text=appuifw.app.body.get().encode('utf8').replace("\xE2\x80\xA9","\x0D\x0A")
        open(path,'wb').write(text)

    def quit(self):
        self.refresh()
        pass


if __name__ == '__main__':
    myeditor().run()

