from appuifw import Canvas, app, note, Content_handler
content = Content_handler()
app.screen = 'full'
from gles import *
from glcanvas import *
from imp import get_magic
from marshal import dump
from zipfile import ZipFile, ZIP_DEFLATED, is_zipfile as iszipfile
import gzip
from decompile2 import main as pydecompile
from binascii import b2a_qp, b2a_uu
from cElementTree import XML
from graphics import *
from _graphics import ImageOpen
from e32 import Ao_lock, ao_sleep, ao_yield, drive_list, start_exe, file_copy
from os import path, abort, remove, removedirs, listdir, chdir, sep, makedirs, fstat, stat
from key import *
import __builtin__
import sysinfo
from struct import unpack, pack
x, y = Canvas().size
lock = Ao_lock()
k = press.is_down
old = app.body
chdir('d:\\')


class gz:
  def Decompress(s, filename, fileout):
    ob = GzipFile(filename)
    cn = ob.read()
    ob.close()
    ta = file(fileout + filename, 'w')
    ta.write(cn)
    ta.close()

def wr_long(f, x):
    f.write(chr((x & 255)))
    f.write(chr(((x >> 8) & 255)))
    f.write(chr(((x >> 16) & 255)))
    f.write(chr(((x >> 24) & 255)))

def pycompile(file, cfile = None, dfile = None):
    f = open(file)
    try :  timestamp = long(fstat(f.fileno())[8])
    except AttributeError : timestamp = long(stat(file)[8])
    codestring = f.read()
    codestring = codestring.replace('\r\n', '\n')
    codestring = codestring.replace('\r', '\n')
    f.close()
    if codestring and codestring[-1] != '\n' :  codestring = codestring + '\n'
    codeobject = __builtin__.compile(codestring, dfile or file, 'exec')
    if  not (cfile) :  cfile = file + __debug__ and 'c' or 'o'
    fc = open(cfile, 'wb')
    fc.write('\x00\x00\x00\x00')
    wr_long(fc, timestamp)
    dump(codeobject, fc)
    fc.flush()
    fc.seek(0, 0)
    fc.write(get_magic())
    fc.close()

def WHtext( text, fonts):
    return Canvas().measure_text(text , fonts)[0][2], - Canvas().measure_text(text, fonts)[0][1]

def hpng(x):
  try:
    x = open(x, 'r').read(8)
    return x == '\x89\x50\x4e\x47\x0d\x0a\x1a\x0a'
  except: pass

def docx2text(path):
  TAG = '{http://schemas.openxmlformats.org/wordprocessingml/2006/main}'
  PARAGRAF = TAG + 'p'
  TEXT = TAG + 't'
  dox = ZipFile(path)
  content = dox.read('word/document.xml')
  dox.close()
  tree = XML(content)
  lines = []
  for line in tree.getiterator(PARAGRAF):
    texts = [node.text for node in line.getiterator(TEXT) if node.text]
    if texts:  lines.append(''.join(texts))
  filetxt = open('d:\\fileman.txt', 'w')
  filetxt.write('\n\n'.join([i for i in lines]).encode('utf-8'))
  filetxt.close()
  return 'd:\\fileman.txt'

def aiftool(filename):
  mbmhdr = '\x37\x00\x00\x10\x42\x00\x00\x10\x00\x00\x00\x00\x39\x64\x39\x47'
  mbmcur = '\x28\x00\x00\x00'
  t = open(filename).read()
  sp = t.find(mbmcur) - 8
  l, = unpack('h', t[sp : sp+2])
  if sp >16 : end = len(t)
  else : end = l
  mbm = t[int(sp+2) : end]
  try: remove('d:\\fileman.mbm')
  except: pass
  f = open('d:\\fileman.mbm', 'w')
  f.write(mbmhdr+ pack('h',l)+ mbm)
  f.close()
  return 'd:\\fileman.mbm'

def openimage(filename):
  img = Image(ImageOpen(filename, lambda e: lock.signal()))
  lock.wait()
  return img

def pima(x):
  e = path.splitext(x)[1].lower()
  return e == '.jpg' or e == '.jpeg' or e == '.png' or e == '.gif' or e == '.ico' or e == '.bmp'

def ppy(x):
  e = path.splitext(x)[1].lower()
  return e == '.py'

def ppyc(x):
  e = path.splitext(x)[1].lower()
  return e == '.pyc'

def pzip(x):
  e = path.splitext(x)[1].lower()
  return e == '.zip'

def pima1(x):
  e = path.splitext(x)[1].lower()
  return e == '.jpg' or e == '.jpeg' or e == '.png' or e == '.gif'

def pmbm(x): 
  e = path.splitext(x)[1].lower()
  return e == '.mbm'

def pobj(x): 
  e = path.splitext(x)[1].lower()
  return e == '.obj'

def pdoc(x): 
  e = path.splitext(x)[1].lower()
  return e == '.doc' or e == '.docx'

def pdocx(x): 
  e = path.splitext(x)[1].lower()
  return e == '.docx'

def pexe(x): 
  e = path.splitext(x)[1].lower()
  return e == '.exe'

def pvid(x): 
  e = path.splitext(x)[1].lower()
  return e == '.3gp' or e == '.mp4'

def paud(x): 
  e = path.splitext(x)[1].lower()
  return e == '.mp3' or e == '.wav' or e == '.mid' or e == '.aac'

def pcom(x): 
  e = path.splitext(x)[1].lower()
  return e == '.zip' or e == '.tar' or e == '.rar' or e == '.7z' or e == '.tgz' or e == '.gz'

def ptxt(x): 
  e = path.splitext(x)[1].lower()
  return e == '.txt' or e == '.py' or e == '.html' or e == '.xml' or e == '.ini' or e == '.js' or e == '.docx' 

def copy(out, file):
  try: return file_copy(out, file)
  except: return None

class Author:
  def __init__(s):
    s.canv = None
    app.body = s.canv = Canvas(s.draw, press.handle_event)
    s.text = [u'Fileman Version 0.1', u'By Taufiq Hidayat']
    while True:
      if k(165) or k(EScancode0): break
      s.draw(None)
      ao_yield()
  def draw(s, gl):
    if s.canv:
      s.canv.clear(0)
      for i in xrange(len(s.text)):
        w, h = WHtext(s.text[i], (u'legend', 12, 1))
        s.canv.text((x/2- w/2, y/2- h/2+ (i*12)), s.text[i], (100, 100, 100), font =( u'legend', 12, 1))

class Obj2OpenGL:
  h, v, z = 0, 0, 0
  a, b, c = 0, 0, 0
  def __init__(s, p):
    s.nor = array(GL_SHORT, 3, s.loader(p))
    s.run = True
    app.screen='large'
    s.render = 0
    atr = { EGL_STENCIL_SIZE : 0}
    s.canv = GLCanvas(s.openGL, press.handle_event, s.resize, atr)
    app.body = s.canv
    s.render = 1
    glEnable(GL_RESCALE_NORMAL)
    glEnable(GL_DITHER)
    glEnable(GL_LIGHTING)
    glEnable(GL_LIGHT0)
    glEnable(GL_DEPTH_TEST)
    glEnable(GL_COLOR_MATERIAL)
    glEnableClientState(GL_VERTEX_ARRAY)
    glEnableClientState(GL_NORMAL_ARRAY)
    glHint(GL_PERSPECTIVE_CORRECTION_HINT,GL_NICEST)
    glLightfv(GL_LIGHT0,GL_DIFFUSE,(.9, 0.2, 0.08, 1.0))
    glLightfv(GL_LIGHT0,GL_AMBIENT,(.5, 0.3, 0.01, 1.0))
    glLightfv(GL_LIGHT0,GL_SPECULAR,(.9, 0.9, 0.9, 1.0))
    while s.run:
      if k(EScancode1): s.c -= 2
      elif k(EScancode2): s.c += 2
      elif k(EScancode0) or k(165): break
      elif k(EScancode4): s.h += 2
      elif k(EScancode5): s.h -= 2
      elif k(EScancode6): s.v -= 2
      elif k(EScancode7): s.v += 2
      elif k(EScancode8): s.z += 2
      elif k(EScancode9): s.z -= 2
      elif k(EScancodeLeftArrow): s.b += 2
      elif k(EScancodeRightArrow): s.b -= 2
      elif k(EScancodeUpArrow): s.a += 2
      elif k(EScancodeDownArrow): s.a -= 2
      s.canv.drawNow()
      ao_yield()
  def openGL(s, GL):
    if not s.render: return
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
    glPushMatrix()
    glTranslatef(s.h, s.v, s.z)
    glRotatef(s.a,1,0,0)
    glRotatef(s.b,0,1,0)
    glRotatef(s.c,0,0,1)
    glVertexPointers(s.nor)
    glNormalPointer(GL_SHORT, 0, s.nor)
    glDrawArrays(GL_TRIANGLES,0, len(s.nor)/3)
    glPopMatrix()
  def resize(s):
    asp = float(s.canv.size[1]) / float(s.canv.size[0])
    glMatrixMode(GL_PROJECTION)
    glLoadIdentity()
    glFrustumf(-1, 1, -1*asp, 1*asp, 2, 50000)
    glMatrixMode(GL_MODELVIEW)
    glLoadIdentity()
    glTranslatef(0, 0, -500)
  def loader(s, dir):
    a=file(dir,'r')
    c=a.readlines()  
    v=[]
    vn=[]
    f=[]
    n=[]
    face=[]
    vv=[]
    for i in xrange(len(c)):
      c[i] = c[i].replace('\r','')
      c[i] = c[i].replace('\n','')
      c[i] = c[i].replace('#','')
      if c[i].count('v '):
        c[i] = c[i].replace('v','')
        c[i] = c[i].split()
        [vv.append(float(c[i][x]))  for x in xrange(len(c[i])) ]
        ao_yield
      elif c[i].count('f '):
        d=[]
        if c[i].count('//'):  c[i]=c[i].replace('//','-1 ')
        else:  c[i]=c[i].replace('/','-1 ')
        c[i]=c[i].replace('f','')
        c[i]=c[i].split()
        [ d.append(eval(c[i][x])) for x in xrange(len(c[i])) ]
        f.append(d)
        ao_yield()
    [v.extend([vv[i*3:3*(i+1)]])  for i in xrange(len(vv)/3)]
    for x in xrange(len(f)):
      a=len(f[x])/3
      face.append([int(f[x][a*0]),int(f[x][a*1]),int(f[x][a*2])]) 
    nor=[]
    for i in face:
      try:  [nor.append(v[x]) for x in i]
      except:  [nor.append(v[x-1]) for x in i]
      ao_yield
    return nor


class editfile:
  def delfile(s, files):
    if path.isfile(files): remove(files)
    else:
      l = []
      l.append(files)
      for i in listdir(files):
        if path.isdir(files + sep + i): s.delfile(files + sep + i)
        else: remove(files + sep + i)
        ao_yield()
      if l != []:
        dir = l
        for i in xrange(len(l)):
          try: removedirs(l[-(i+1)])
          except: pass
          ao_yield()
  def addfile(s, files, out):
    chdir(out)
    if path.isfile(files): copy(out, files)
    elif path.isdir(files):
      d = files.split(sep)
      d = d[len(d)-1]
      try: makedirs(out+ sep+ d)
      except: pass
      for i in listdir(files):
        if path.isdir(files+ sep+ i):
          s.addfile(files + sep+ i, out + sep+ d)
        else:
          copy(out + sep+ d, files +sep + i)
        ao_yield()

class Zip:
    def Compress(s, path_in, file_out):
        file_out = str(file_out[0])
        file_zip = ZipFile(file_out, 'w', ZIP_DEFLATED)
        for path_in in path_in:
            path_in = str(path_in)
            s._addFile(file_zip, path_in, path_in)
        file_zip.close()
    def Decompress(s, path_out, file_in):
            path_out = str(path_out[0])
            file_in = str(file_in[0])
            if  not (path_out.endswith(sep)): path_out = path_out + sep
            s.createDir(path_out)
            file_zip = ZipFile(file_in, 'r', ZIP_DEFLATED)
            listfile = file_zip.namelist()
            s.createDir(path_out)
            chdir(path_out)
            for id in listfile:
                s.createDir(s._leggiDirectory(id))
                s.createFile(id, file_zip.read(id))
                try: removedirs(s._leggiDirectory(id))
                except :  pass
                ao_yield()
            file_zip.close()
    def _leggiDirectory(s, dir_path):
        file_path = ''
        for i in range((len(dir_path) - 1), -1, -1):
            if dir_path[i] == sep : 
                file_path = dir_path[(i + 1) : ]
                break
        return dir_path[ : ( - len(file_path) - 1)]
    def createDir(s, path_):
      try:   makedirs(path_)
      except: pass
    def createFile(s, filename, stream):
      try:
        f = open(filename, 'w')
        f.write(stream)
        f.close()
      except: pass
    def _addFile(s, zip, path_ , dir_path):
        try :
            if path.isfile(dir_path) : 
                for i in range((len(dir_path) - 1), -1, -1):
                    if dir_path[i] == sep :
                        file_path = dir_path[(i + 1) : ]
                        break
                zip.write(dir_path, file_path)
            elif path.isdir(path_ ) : 
                if  not path_.endswith(sep): 
                    path_ = path_ + sep
                if  not dir_path.endswith(sep):
                    dir_path = dir_path + sep
                for i in listdir(path_):
                    if path.isdir(path_ + i) : 
                        ao_yield()
                        s._addFile(zip, path_ + i, dir_path)
                    else : 
                        p = path_ + i
                        p = p.split(sep)
                        f = ''
                        d = dir_path.split(sep)
                        fd = p.index(d[len(d)-2])
                        fd = p[fd:]
                        for i in fd:
                          f += i + sep
                        f = f[:len(f)-1]
                        zip.write(path_ + i, f)
                pass
        except : pass

class openImage(object):
  def __init__(s, filename):
    s.ima = openimage(filename)
    s.w, s.h = s.ima.size
    s.canv = None
    app.body = s.canv = Canvas(s.draw, press.handle_event)
    s.x, s.y = s.canv.size
    if s.w < s.x and s.h < s.y:
      ww = float(s.w)/ float(s.h)
      hh = float(s.h)/ float(s.w)
      xw = float(s.x)/ float(s.w)
      yh = float(s.y)/ float(s.h)
      if xw < yh:
        s.w = s.x 
        s.h = s.x* hh
      else:
        s.w = s.y* ww
        s.h = s.y
      s.ima = openimage(filename).resize((s.w, s.h))
      s.scaling = True
    else:
      s.scaling = False
    s.tw, s.th = 0, 0
    s.zoomx, s.zoomy = 0, 0
    s.seep = False
    while True:
      if s.seep : s.seep = False
      if k(EScancode0) or k(165): del s.ima; break
      elif k(EScancodeDownArrow):
        if (s.y/2- s.h/2+ s.h)+ s.th > s.y:  s.th -= 1
        s.seep = True
      elif k(EScancodeUpArrow):
        if (s.y/2- s.h/2+ s.th) < 0:  s.th += 1
        s.seep = True
      elif k(EScancodeLeftArrow): 
        if (s.x/2- s.w/2+ s.tw) < 0: s.tw += 1
        s.seep = True
      elif k(EScancodeRightArrow): 
        if (s.x/2- s.w/2+ s.w)+ s.tw > s.x: s.tw -= 1
        s.seep = True
      elif k(EScancodeSelect) or k(3): os.abort()
      elif k(EScancode1):
        s.seep = True
        s.zoomx, s.zoomy = 0, 0
        scalex, scaley = openimage(filename).size
        if scalex > scaley:
          s.zoomx += (float(scalex)/ float(scaley))* scalex/ 8
          s.zoomy += (float(scaley)/ float(scaley))* scalex/ 8
        else:
          s.zoomx += (float(scalex)/ float(scalex))* scaley/ 8
          s.zoomy += (float(scaley)/ float(scalex))* scaley/ 8
        s.ima = openimage(filename).resize((s.zoomx+ s.w, s.zoomy+ s.h))
        s.w, s.h = s.ima.size
      elif k(EScancode3):
        s.seep = True
        s.zoomx, s.zoomy = 0, 0
        scalex, scaley = openimage(filename).size
        if scalex > scaley:
          if s.zoomx - (float(scalex)/ float(scaley))* scalex/ 8+ s.w > 10 or s.zoomy- (float(scaley)/ float(scaley))* scalex/ 8 + s.h > 10:
            s.zoomx -= (float(scalex)/ float(scaley))* scalex/ 8
            s.zoomy -= (float(scaley)/ float(scaley))* scalex/ 8
        else:
          if s.zoomx- (float(scalex)/ float(scalex))* scaley/ 8+ s.w > 10 or s.zoomy - (float(scaley)/ float(scalex))* scaley/ 8 + s.h > 10:
            s.zoomx -= (float(scalex)/ float(scalex))* scaley/ 8
            s.zoomy -= (float(scaley)/ float(scalex))* scaley/ 8
        s.ima = openimage(filename).resize((s.zoomx+ s.w, s.zoomy+ s.h))
        s.w, s.h = s.ima.size
      elif k(EScancode7):
        s.seep = True
        s.w, s.h = openimage(filename).size
        if not s.scaling:
          ww = float(s.w)/ float(s.h)
          hh = float(s.h)/ float(s.w)
          xw = float(s.x)/ float(s.w)
          yh = float(s.y)/ float(s.h)
          if xw < yh:
            s.w = s.x 
            s.h = s.x* hh
          else:
            s.w = s.y* ww
            s.h = s.y
          s.ima = openimage(filename).resize((s.w, s.h))
          s.scaling = True
          s.tw = 0
          s.th = 0
        else:
          s.ima = openimage(filename)
          s.w, s.h = s.ima.size
          s.tw = 0
          s.th = 0
          s.scaling = False
      elif k(EScancode4):
        s.ima = s.ima.transpose(ROTATE_270)
        s.w, s.h = s.ima.size
        s.tw, s.th = 0, 0
      elif k(EScancode6):
        s.ima = s.ima.transpose(ROTATE_90)
        s.w, s.h = s.ima.size
        s.tw, s.th = 0, 0
      s.draw(())
      if s.seep:  ao_yield()
      else: ao_sleep(0.1)
  def draw(s, gl):
    if s.canv:
      s.canv.clear(0)
      s.canv.blit(s.ima, target =  ((s.x/2- s.w/2+ s.tw, s.y/2- s.h/2+ s.th)) )

class openText(object):
  def __init__(s, filename, fonts = u'title', fontsize = 12):
    s.fontsize = fontsize
    if pdocx(filename):
      s.of = file(docx2text(filename), 'r')
      s.of = s.of.readlines()
    else:
      s.of = file(filename, 'r')
      s.of = s.of.readlines()
    reading = False
    s.textfile = None
    s.canv = None
    s.br = (U'legend', 12, 1)
    s.cano = u'Bad Reading File'
    app.body = s.canv = Canvas(s.draw,press.handle_event)
    s.canox, s.canoy = s.canv.measure_text(s.cano, s.br)[0][2], -s.canv.measure_text(s.cano, s.br)[0][1]
    s.x, s.y = s.canv.size
    s.ty, s.tx = 0, 0
    s.sleep = False
    s.high = s.y/ s.fontsize-1
    s.min = 0
    s.max = s.high
    while True:
      if len(s.of) > s.high: s.textfile = s.of[s.min: s.max]
      else: s.text = s.of
      if not s.sleep: s.sleep = True
      if k(EScancode0) or k(165): break; del s.text; del s.of;
      elif k(EScancodeUpArrow):
        s.sleep = False
        if s.min > 0:
          s.min -= 1
          s.max -= 1
      elif k(EScancodeDownArrow):
        s.sleep = False
        if s.max < len(s.of):
          s.min += 1
          s.max += 1
      elif k(EScancodeLeftArrow):
        s.sleep = False
        s.tx -= 12
      elif k(EScancodeRightArrow):
        s.sleep = False
        s.tx += 12
      elif k(EScancodeSelect) or k(3): 
        s.tx = 0
        s.sleep = False
      s.draw(())
      if s.sleep: ao_sleep(0.1)
      else: ao_yield()
  def draw(s, gl):
    if s.canv:
      s.canv.clear(0)
      try:
        try:
          line = 0
          for i in s.textfile:
            line += 1
            try:
              i = i.replace('\r', '')
              i = i.replace('\n', '')
              s.canv.text((s.tx, 12* line), unicode(i), (100,100,100), font= (u'legend', 12, 1) )
            except:
              i = b2a_qp(i)
              i = i.replace('\n', '')
              s.canv.text((s.tx, 12* line), unicode(i), (100,100,100), font= (u'legend', 12, 1) )
        except:
          line = 0
          for i in s.of:
            line += 1
            try:
              i = i.replace('\r', '')
              i = i.replace('\n', '')
              s.canv.text((s.tx, 12* line), unicode(i), (100,100,100), font= (u'legend', 12, 1) )
            except:
              i = b2a_qp(i)
              i = i.replace('\n', '')
              s.canv.text((s.tx, 12* line), unicode(i), (100,100,100), font= (u'legend', 12, 1) )
      except:
        s.canv.text((s.x/2- s.canox/2, s.y/2- s.canoy/2), unicode( s.cano ), (100,100,100), font= (u'legend', 12, 1) )

class mbmfile:
  def image(s, filename, index):
    file = open( filename )
    file.read(16)
    file.seek(unpack('i', file.read(4))[0])
    count = unpack('i',file.read(4))[0]
    file.seek(index* 4, 1)
    position = unpack('i', file.read(4))[0]
    file.seek( position )
    dlina = unpack('i', file.read(4))[0]
    file.seek(4,1)
    unpack('ii',file.read(8))
    file.seek(8,1)
    unpack('i',file.read(4))[0]
    file.seek(position)
    tempfile = open('d:\\fileman.png', 'w')
    tempfile.write('\x37\x00\x00\x10\x42\x00\x00\x10\x00\x00\x00\x00\x39\x64\x39\x47'+ pack('i', dlina+ 20)+ file.read(dlina)+'\x01\x00\x00\x00\x14\x00\x00\x00')
    file.close(), tempfile.close()
    img = openimage(u'd:\\fileman.png')
    return img, count



class openMbm(object):
  def __init__(s, filename):
    s.file = open(filename, 'r')
    if s.file.read(8) == '\x37\x00\x00\x10\x38\x3a\x00\x10':
      s.file.close()
      filename = aiftool(filename)
    s.step = 0
    s.mbm =  mbmfile().image
    s.count = s.mbm(str(filename), s.step)[1]- 1
    s.canv = None
    app.body = s.canv = Canvas(s.draw, press.handle_event)
    s.x, s.y = s.canv.size
    s.update = True
    s.br = (u'legend',12,FONT_BOLD)
    s.speed = False
    s.tm = 0
    s.selectzip = ''
    while True:
      if s.speed: s.speed = False
      if k(EScancode0) or k(165): break
      elif s.update:
        s.speed = True
        s.ima = mbmfile().image(str(filename), s.step)[0]
        s.w, s.h = s.ima.size
        s.update = False
        s.text = str(s.step)
        s.text1 = str( s.count)
        s.text2 = ':'
        s.wt, s.ht = s.canv.measure_text(s.text, s.br)[0][2], -s.canv.measure_text(s.text, s.br)[0][1]
        s.wt1, s.ht1 = s.canv.measure_text(s.text1, s.br)[0][2], -s.canv.measure_text(s.text1, s.br)[0][1]
        s.wt2, s.ht2 = s.canv.measure_text(s.text2, s.br)[0][2], -s.canv.measure_text(s.text2, s.br)[0][1]
      elif k(EScancodeRightArrow):
        s.speed = True
        s.update = True
        s.step += 1
        if s.step > s.count: s.step = 0
      elif k(EScancodeLeftArrow):
        s.speed = True
        s.update = True
        s.step -= 1
        if s.step < 0: s.step = s.count
      
      s.draw(None)
      if s.speed: ao_yield()
      else: ao_sleep(.1)
  def draw(s, gl):
    if s.canv:
      s.canv.clear(0)
      s.canv.text((s.x/2-  (s.wt1* 2)-12, 12),unicode(s.text), (150,150,150), s.br)
      s.canv.text((s.x/2+ (s.wt1)+12, 12),unicode(s.text1), (150,150,150), s.br)
      s.canv.text((s.x/2- s.wt2/2, 12),unicode(s.text2), (150,150,150), s.br)
      s.canv.blit(s.ima, target= ((s.x/2- s.w/2, s.y/2- s.h/2)))
    
    
class fileman:
  def __init__(s, fontsize = 12, fontstyle = 1, fonts = u'title'):
    s.fontsize = fontsize
    s.fontstyle = fontstyle
    s.fonts = fonts
    s.font = (fonts, fontsize, fontstyle)
    s.canv= None
    app.body = s.canv = Canvas(s.draw, press.handle_event)
    s.x, s.y = s.canv.size
    s.d = []
    s.drive = []
    for i in drive_list(): s.drive.append([i])
    s.rb = (unicode(s.fonts), s.fontsize, s.fontstyle)
    s.t = 0
    s.od = []
    s.ts = []
    s.move = 0
    s.high = (s.y/ s.fontsize)- 2
    s.min = 0
    s.max = s.high
    s.marked = []
    s.menuoption = [u'Open', u'Open By System', u'Zip', u'Mark', u'Back']
    s.wmenu = WHtext(u' ', s.rb)[0]
    for i in s.menuoption: 
      if s.wmenu < WHtext(i, s.rb)[0]: s.wmenu = WHtext(i, s.rb)[0]
    s.optioneditfile = [u'Move', u'Copy']
    s.Optzippack = u'Pack'
    s.Optzipunpack = u'unPack'
    s.menu = 0
    s.nonti = ''
    s.colortext = (100, 100, 100)
    s.selectmenu = 0
    s.tm = 0
    s.selectzip = ''
    s.selectmarkzip = ''
    s.tomark = True
    s.compile = False
    s.decompile = False
    s.selectfile = ''
    s.selectdir = ''
    s.copyfile = True
    s.todo = True
    while True:
      if s.menu == 0:
        if k(5) and not k(EScancodeLeftArrow) and s.tomark:
          try:
            di = ''
            for i in s.d[s.t]: di += i+ sep
            di = di[: len(di)-1]
            if di not in s.marked and di not in drive_list():  s.marked.append(di)
          except: pass
        if k(EScancode1): break
        elif k(EScancode2): abort()
        elif k(23) or k(164):
          try:
            di = ''
            for i in s.d[s.t]: di += i+ sep
            di = di[: len(di)-1]
            if iszipfile(di) and s.selectzip == '' and s.marked == [] and s.copyfile:
              s.menuoption = [u'Open', u'Open By System', u'unPack', u'Copy', u'Del', u'Mark', u'About', u'Back']
              
            elif path.isdir(di) and s.selectzip != '' and s.copyfile: 
              s.menuoption = [u'Open', u'Open By System', u'unPack Here', u'Mark', u'About', u'Back']
              
            elif s.marked and s.tomark and s.copyfile: 
              s.menuoption = [u'Open', u'Open By System', u'Packing2Zip', u'Copy Mark', u'Copy', u'Del', u'Mark',u'About', u'Back']
              
            elif s.marked and not s.tomark and s.copyfile:
              s.menuoption = [u'Open', u'Open By System', u'Pack Here', u'Mark',u'About', u'Back']
              
            elif not s.marked and ppy(di) and not s.compile and s.copyfile:
              s.menuoption = [u'Open', u'Open By System', u'Compile2Pyc', u'Copy', u'Del', u'Mark',u'About', u'Back']
              
            elif not s.marked and s.compile and path.isdir(di) and s.copyfile:
              s.menuoption = [u'Open', u'Open By System', u'Compile here', u'Mark',u'About', u'Back']
              
            elif not s.marked and ppyc(di) and not s.decompile and s.copyfile:
              s.menuoption = [u'Open', u'Open By System', u'Decompile2Py', u'Copy', u'Del', u'Mark',u'About', u'Back']

            elif not s.marked and s.decompile and path.isdir(di) and s.copyfile: 
              s.menuoption = [u'Open', u'Open By System', u'Decompile Here', u'Mark',u'About', u'Back']
              
            elif not s.copyfile:
              s.menuoption = [u'Open', u'Open By System', u'Copy Here', u'Mark',u'About', u'Back']
              
            else: s.menuoption = [u'Open', u'Open By System', u'Copy', u'Del', u'Mark',u'About', u'Back']
            s.menu = 1
          except: pass
        elif (k(EScancodeSelect) or k(3)) and not k(5):
          try:
            di = ''
            for i in s.d[s.t]: di += i+ sep
            di = di[: len(di)-1]
            if pima(di) or hpng(di): 
              try: openImage(unicode(di))
              except: pass
            elif pobj(di):
              try: Obj2OpenGL(di)
              except: pass
            elif pmbm(di):
              try:  openMbm(unicode(di))
              except: pass
            elif pvid(di): 
              try:
                ao_sleep(.1);
                content.open(di); 
                ao_sleep(.1)
              except: pass
            else: 
              if path.isfile(di):  openText(unicode(di))
            app.body = s.canv = Canvas(s.draw, press.handle_event)
            app.screen = 'full'
          except: raise
        elif k(EScancodeUpArrow):  
          s.t -= 1
        elif k(EScancodeDownArrow):  
          s.t += 1
        elif k(EScancodeRightArrow):
          try:
            di = ''
            for i in s.d[s.t]: di += i+ sep
            if s.d[s.t] not in s.od and path.isdir(di):
              s.ld = listdir(di)
              for i in s.ld:
                s.ts = []
                s.ts.extend(s.d[s.t])
                s.ts.append(i)
                s.drive.insert(s.drive.index(s.d[s.t])+1, s.ts)
              if s.ld != []: s.od.append(s.d[s.t])
            else: s.t += 1
          except: pass
        elif k(53): s.marked = []
        elif k(EScancodeLeftArrow) and not k(5):
          if s.d[s.t] in s.od:
            s.do = []
            for i in s.od:
              count = 0
              for n in xrange(len(s.d[s.t])):
                try:
                  if s.d[s.t][n] is i[n]:  count +=1
                except: pass
              if count == len(s.d[s.t]): s.do.append(i)
            for n in s.do:
              di = ''
              for i in n:  di += i+ sep
              s.ld = listdir(di)
              for i in s.ld:
                s.ts = []
                s.ts.extend(n)
                s.ts.append(i)
                s.drive.pop(s.drive.index(s.ts))
              s.od.pop(s.od.index(n))
          else:
            try:
              try:
                s.t = s.d.index(s.d[s.t][: len(s.d[s.t])-1 ])
              except:
                s.min = s.drive.index(s.d[s.t][: len(s.d[s.t])-1 ])
                s.max = s.min + s.high
                s.d = s.drive[s.min: s.max]
                s.t = s.d.index(s.d[s.t][: len(s.d[s.t])-1 ])              
                ao_sleep(0.1)
            except: pass
        if len(s.drive) < s.high: 
          s.d = s.drive
          if s.t > len(s.d)-1: s.t = 0
          elif s.t < 0: s.t = len(s.d) -1
          ao_sleep(.05)
        else: 
          s.d = s.drive[s.min: s.max]
          ao_yield()
          if s.t > len(s.d)-1:
            s.min += 1
            s.max += 1
            s.t = len(s.d)-1
            if s.max > len(s.drive):
              s.max = s.high
              s.min = 0
              s.t = s.min
          elif s.t < 0:
            try:
              s.min -= 1
              s.max -= 1
              s.t = 0
              if s.min < 0:
                s.min = len(s.drive)- 1- s.high
                s.max = len(s.drive)- 1
                s.t = s.max
            except: pass 
      elif s.menu == 1:
        if k(EScancodeUpArrow):
          s.tm -= 1
          if s.tm < 0: s.tm = len(s.menuoption)- 1
        elif k(EScancodeDownArrow):
          s.tm += 1
          if s.tm > len(s.menuoption)- 1: s.tm = 0
        elif k(EScancode1): break
        elif k(EScancodeLeftArrow): s.menu = 0; s.tm = 0; ao_sleep(.01)
        elif k(EScancodeSelect) or k(3):
          di = ''
          for i in s.d[s.t]: di += i+ sep
          di = di[: len(di)-1]
          if s.tm == 0: pass
          elif s.menuoption[s.tm] == u'Open By System': 
            try:
              ao_sleep(.5)
              content.open(di)
              ao_sleep(.5)
            except: pass
          elif s.menuoption[s.tm] == u'Decompile2Py':
            s.tomark = False
            s.nonti = 'Decompile to'
            s.decompile = True
            s.selectfile = di
            s.menu = 0
          elif s.menuoption[s.tm] == u'Decompile Here':
            s.tomark = True
            s.decompile = False
            s.nonti = ''
            s.selectdir = di
            di = s.selectfile.split(sep )
            di = di[ len(di)- 1]
            di = di[ : len(di)- 1]
            s.selectdir = s.selectdir + sep + di
            if s.d[ s.t] in s.od:
              s.do = []
              for i in s.od:
                count = 0
                for n in xrange(len(s.d[s.t])):
                  try:
                    if s.d[s.t][n] is i[n]:  count +=1
                  except: pass
                if count == len(s.d[s.t]): s.do.append(i)
              for n in s.do:
                di = ''
                for i in n:  di += i+ sep
                s.ld = listdir(di)
                for i in s.ld:
                  s.ts = []
                  s.ts.extend(n)
                  s.ts.append(i)
                  s.drive.pop(s.drive.index(s.ts))
                s.od.pop(s.od.index(n))
            pydecompile(s.selectfile, s.selectdir)
            s.selectfile = ''
            s.selectdir = ''
            s.menu = 0
          elif s.menuoption[s.tm] == u'Compile2Pyc':
            s.tomark = False
            s.nonti = 'Compile to'
            s.compile = True
            s.selectfile = di
            s.menu = 0
          elif s.menuoption[s.tm] == u'Compile here':
            s.tomark = True
            s.compile = False
            s.nonti = ''
            s.selectdir = di
            di = s.selectfile.split(sep)
            di = di[len(di)- 1]
            s.selectdir = s.selectdir + sep + di+ 'c'
            if s.d[s.t] in s.od:
              s.do = []
              for i in s.od:
                count = 0
                for n in xrange(len(s.d[s.t])):
                  try:
                    if s.d[s.t][n] is i[n]:  count +=1
                  except: pass
                if count == len(s.d[s.t]): s.do.append(i)
              for n in s.do:
                di = ''
                for i in n:  di += i+ sep
                s.ld = listdir(di)
                for i in s.ld:
                  s.ts = []
                  s.ts.extend(n)
                  s.ts.append(i)
                  s.drive.pop(s.drive.index(s.ts))
                s.od.pop(s.od.index(n))
            pycompile(s.selectfile, s.selectdir)
            s.selectfile = ''
            s.selectdir = ''
            s.menu = 0
          elif s.menuoption[s.tm] == u'unPack' and s.selectzip == '' and s.marked == [] :
            s.tomark = False
            s.nonti = 'unPack Zip to';
            s.selectzip = di;
            s.menu = 0
          elif s.menuoption[s.tm] == u'unPack Here' and s.selectzip != '' and s.marked == []:
            s.menu = 0
            s.nonti = ''
            s.selectmarkzip = di
            if s.d[s.t] in s.od:
              s.do = []
              for i in s.od:
                count = 0
                for n in xrange(len(s.d[s.t])):
                  try:
                    if s.d[s.t][n] is i[n]:  count +=1
                  except: pass
                if count == len(s.d[s.t]): s.do.append(i)
              for n in s.do:
                di = ''
                for i in n:  di += i+ sep
                s.ld = listdir(di)
                for i in s.ld:
                  s.ts = []
                  s.ts.extend(n)
                  s.ts.append(i)
                  s.drive.pop(s.drive.index(s.ts))
                s.od.pop(s.od.index(n))
            Zip().Decompress([s.selectmarkzip], [s.selectzip])
            s.selectzip = ''
            s.selectmarkzip = ''
            s.nonti = ''
            s.tomark = True
          elif s.menuoption[s.tm] == u'Packing2Zip' and s.marked: 
            s.nonti = 'Pack to'
            s.menu = 0;
            s.tomark = False
          elif s.menuoption[s.tm] == u'Pack Here' and s.marked:
            s.tomark = True
            s.menu = 0
            s.nonti = ''
            if s.d[s.t] in s.od:
              s.do = []
              for i in s.od:
                count = 0
                for n in xrange(len(s.d[s.t])):
                  try:
                    if s.d[s.t][n] is i[n]:  count +=1
                  except: pass
                if count == len(s.d[s.t]): s.do.append(i)
              for n in s.do:
                di = ''
                for i in n:  di += i+ sep
                s.ld = listdir(di)
                for i in s.ld:
                  s.ts = []
                  s.ts.extend(n)
                  s.ts.append(i)
                  s.drive.pop(s.drive.index(s.ts))
                s.od.pop(s.od.index(n))
            Zip().Compress(s.marked, [di+ sep+ 'fileman.zip'])
            s.marked = []
          elif s.menuoption[s.tm] == u'Copy':
            s.selectfile = di
            s.tomark = False
            s.copyfile = False
            s.menu = 0
            s.nonti = 'Select Directory to Copying File'
          elif s.menuoption[s.tm] == u'Copy Mark':
            s.selectfile = s.marked
            s.tomark = False
            s.copyfile = False
            s.menu = 0
            s.nonti = 'Select Directory to Copying File'
          elif s.menuoption[s.tm] == u'Copy Here':
            s.selectdir = di
            s.tomark = True
            s.copyfile = True
            if s.d[s.t] in s.od:
              s.do = []
              for i in s.od:
                count = 0
                for n in xrange(len(s.d[s.t])):
                  try:
                    if s.d[s.t][n] is i[n]:  count +=1
                  except: pass
                if count == len(s.d[s.t]): s.do.append(i)
              for n in s.do:
                di = ''
                for i in n:  di += i+ sep
                s.ld = listdir(di)
                for i in s.ld:
                  s.ts = []
                  s.ts.extend(n)
                  s.ts.append(i)
                  s.drive.pop(s.drive.index(s.ts))
                s.od.pop(s.od.index(n))
            
            if not s.marked and s.selectfile != s.selectdir:
              editfile().addfile(str(s.selectfile), str(s.selectdir))
            else:
              if s.selectdir in s.marked:
                s.marked.pop(s.marked.index(s.selectdir))
              for i in s.marked:
                editfile().addfile(str(i), str(s.selectdir))
            s.marked = []
            s.selectfile = ''
            s.selectdir = ''
            s.menu = 0
            s.nonti = ''
          elif s.menuoption[s.tm] == u'Mark': 
            if di not in drive_list():
              s.marked.append(di); 
            s.menu = 0; 
            s.tm = 0
          elif s.menuoption[s.tm] == u'Del':
            if s.d[ s.t] in s.od:
              s.do = []
              for i in s.od:
                count = 0
                for n in xrange(len(s.d[s.t])):
                  try:
                    if s.d[s.t][n] is i[n]:  count +=1
                  except: pass
                if count == len(s.d[s.t]): s.do.append(i)
              for n in s.do:
                di = ''
                for i in n:  di += i+ sep
                s.ld = listdir(di)
                for i in s.ld:
                  s.ts = []
                  s.ts.extend(n)
                  s.ts.append(i)
                  s.drive.pop(s.drive.index(s.ts))
                s.od.pop(s.od.index(n))
            if s.marked == []:  
              editfile().delfile(str(di))
            else:
              for i in s.marked:
                editfile().delfile(str(i))
            s.drive = []
            for i in drive_list():
              s.drive.append([i])
            s.od = []
            s.marked = []
            s.menu = 0
            di = ''
          elif s.menuoption[s.tm] == u'Back': 
            s.menu = 0; 
            s.tm = 0
          elif s.menuoption[s.tm] == u'About':
            s.menu = 0; 
            s.tm = 0
            Author()
            app.body = s.canv = Canvas(s.draw, press.handle_event)
          ao_sleep(0.1);
        ao_sleep(.05)
      s.draw(None)
      ao_yield()
  def draw(s, gl):
    if s.canv:
      s.canv.clear(0)
      if s.nonti: s.canv.text((0, s.fontsize), unicode(s.nonti), (50,0,0), font= s.font)
      for i in xrange(len(s.d)):
        try:
          di = ''
          for n in s.d[i]:  di += n+ sep
          icon = di[: len(di)- 1]
          if icon in s.marked: s.colortext = (50, 0, 150)
          else: s.colortext = (100, 100, 100)
          wide = s.fontsize - 1
          if path.isfile(di):  
            s.canv.point(((s.fontsize/2)* (len(s.d[i])), s.fontsize* (i+1)- 5+ s.move+ s.fontsize), (100,100,100), width = wide)
          else: s.canv.point(((s.fontsize/2)* (len(s.d[i])), s.fontsize* (i+1)- 5+ s.move+ s.fontsize), (100,50,0), width = wide)
        except: pass
        if i != s.t:
          try: 
            s.canv.text(((s.fontsize/2)* (len(s.d[i]))+10, s.fontsize* (i+1)+ s.move+ s.fontsize), unicode( s.d[i][len(s.d[i])-1]), s.colortext, font= s.font)
          except: s.canv.text(((s.fontsize/2)* (len(s.d[i]))+10, s.fontsize* (i+1)+ s.move+ s.fontsize), unicode('Unknow File'), (100,100,100), font= s.font)
        else:
          try:
            s.canv.text(((s.fontsize/2)* (len(s.d[i]))+10, s.fontsize* (i+1)+ s.move+ s.fontsize), unicode(s.d[i][len(s.d[i])-1]), (50,0,0), font= s.font)
          except:
            s.canv.text(((s.fontsize/2)* (len(s.d[i]))+10, s.fontsize* (i+1)+ s.move+ s.fontsize), unicode('Unknow File'), (50,0,0), font= s.font)
      if s.menu == 1:
        s.canv.rectangle((s.fontsize- (s.fontsize/2), s.fontsize, s.wmenu+ s.fontsize+ (s.fontsize/2), s.fontsize* len(s.menuoption)+ s.fontsize+ (s.fontsize/2)), fill= (2,2,2))
        for i in xrange(len(s.menuoption)):
          if i != s.tm:
            s.canv.text((s.fontsize, s.fontsize* (i+1)+ s.fontsize), s.menuoption[i], (100,100,100), font= s.font)
          else:
            s.canv.text((s.fontsize, s.fontsize* (i+1)+ s.fontsize), s.menuoption[i], (50,0,0), font= s.font)
          

fileman()
app.body = old
app.screen = 'normal'
