"""
wxDesigner_Conv2-5.py   23-April-2004  David Hughes  (dfh@forestfield.co.uk)

Convert Python source files that have been auto-generated by wxDesigner v2.9 or
earlier. Code that has been created to use wxPython 2.4.x is converted to be
compatible with wxPython 2.5.1 in accordance with the wxPython 2.5 Migration
Guide (http://wxpython.org/migrationguide.php)

Program accepts a single file name or a directory name as its only argument.
If arg not supplied, the name hard-coded into 'source' is used.
Only .py files containing the text "# Python source generated by wxDesigner"
are converted. Note that the files are converted in-situ and this conversion
must be re-run every time that new Python source code is generated by wxDesigner.
It is re-runnable over source code that has already been converted.
"""

import os, sys, time, string
import wx
source = 'C:/Myproject/wxdesign'    # Replace with file or directory to be converted
                                    # if information not supplied on command line

punct = string.punctuation.replace('_','')                  # exclude single underscore - allowed in names 
punctable = string.maketrans(punct, ' '*len(punct))         # map punctuation characters to spaces
identitext = "# Python source generated by wxDesigner"
numfiles = 0

def convwidht(line):
    """ Change content of line
          from 'AddSpacer( <wid>, <ht>, ...'
          to 'AddSpacer( wxSize(<wid>, <ht>), ...'
    """
    ix0 = line.find('AddSpacer(') + 10
    ix1 = line[ix0:].find(',') + ix0 + 1
    ix2 = line[ix1:].find(',') + ix1
    return line[:ix0] + ' wxSize(' + line[ix0:ix2] + ' ),' + line[ix2+1:]

conversions = {'from wxPython.wx import *': ['import wx', None],
               'AddWindow': ['Add', None],
               'AddSizer': ['Add', None],
               'AddSpacer': ['Add', convwidht],
               'PrependWindow': ['Prepend', None],
               'PrependSizer': ['Prepend', None],
               'PrependSpacer': ['Prepend', convwidht],
               'InsertWindow': ['Insert', None],
               'InsertSizer': ['Insert', None],
               'InsertSpacer': ['Insert', convwidht],
               'true': ['True', None],
               'false': ['False', None]
               }        # conversions dictionary is keyed by text to be replaced.
                        # Value is a list containing the replacing text and,
                        # optionally, an associated function to be called.

#----------------------------------------------------------------------------

def wxconvert(pathname):
    """ Scan each line of text in pathname. Replace each occurrence of any key
        in conversions dictionary with the content stored under that key and
        change all wxName to wx.Name
    """
    global numfiles                            
    fi = open(pathname, 'r')
    linelist = fi.readlines()
    fi.close()
    isdesignerfile = False
    for line in linelist:
        if line.find(identitext) >= 0:
            isdesignerfile = True
            break
            
    if isdesignerfile:
        fo = open(pathname, 'w')
        for line in linelist:
            for key in conversions:                                     # non-wx changes
                if line.find(key) >= 0:
                    newtext, func = conversions[key]
                    if func:
                        line = func(line) 
                    line = line.replace(key, newtext)
            tokenlist = line.translate(punctable).split()               # split on white space and punctuation
            for token in tokenlist:
                if token.startswith('wx') and hasattr(wx, token[2:]):   # change wx names
                    line = line.replace(token, 'wx.' + token[2:])
            fo.write(line)
        fo.close()
        numfiles += 1
    
def pausexit():
    " Message to stdout and stop."
    print
    print 'Press ENTER to continue',
    sys.stdin.readline()          # wait for CR/LF
    sys.exit(0)

#----------------------------------------------------------------------------

# Usage: python wxDesigner_Conv2-5.py [file|directory]

if __name__ == '__main__':
    t0 = time.time()
    if len(sys.argv) > 1:
        source = sys.argv[1]
    if os.path.exists(source):
        print 'Converting %s' % source
        if os.path.isdir(source):
            sourcelist = [ os.path.join(source, item) for item in os.listdir(source)]
        else:
            sourcelist = [source]
        for name in sourcelist:
            if os.path.isfile(name) and name[-3:].lower() == '.py':
                wxconvert(name)
        print '%d files converted in %.2f seconds' % (numfiles, time.time() - t0) 
    else:
        print '%s not found' % source
    pausexit()
    
