# Copyright (C) 1997 James C. Ahlstrom
# Use permitted on the same terms as the WPY Copyright.
import sys, string, os, regex

##BUG: Commas in quoted strings are a problem

usage = """Usage: python pythonrc.py myname.rc"""

if len(sys.argv) < 2:
  print usage
  sys.exit()

reg_dialog = regex.compile("\([^ ]+\) +[^ ]+ +[^ ]+ +[0-9]+[ ,]+[0-9]+[ ,]+\([0-9]+\)[ ,]+\([0-9]+\)")
reg_ltext = regex.compile("""LTEXT +"\([^"]*\)"[ ,]+\(.*\)""")
      # LTEXT           "Lease Start Date",100,6,13,54,8,NOT WS_GROUP

def do_dialog(line, fpin, fpout):
  # CFNJapanDialog DIALOG DISCARDABLE  20, 40, 423, 204
  # CFNJapanDialog DIALOGEX 20, 40, 350, 212
  fields = string.splitfields(line, ",")
  name = string.split(fields[0])[0]
  sizex = string.atoi(fields[2])
  sizey = string.atoi(fields[3])
  caption = "\"\""
  radio_group = None
  while 1:
    line = fpin.readline()
    if not line:
      break
    line = string.strip(line)
    if not line:
      continue
    while line[-1] in ",|+":	# Continue the line
      line = line + string.strip(fpin.readline())
    fields = string.split(line)
    key = fields[0]
    if key == "BEGIN":
      radio_group = None
      fpout.write(
"""class %s(wpy.CRcDialog):	# Created by wpyrc.py
  def __init__(self):
    wpy.CRcDialog.__init__(self, None, %s)
    self.wpySizeX = %s * self.wpyCharSizeX / 4
    self.wpySizeY = %s * self.wpyCharSizeY / 8
    self.wpyCtrlList = []
""" % (name, caption, sizex, sizey))
    elif key == "CAPTION":
      radio_group = None
      # CAPTION "Dialog"
      caption = string.strip(line[7:])
    elif key == "COMBOBOX":
      radio_group = None
      #COMBOBOX        Freq,100,57,41,55,CBS_DROPDOWNLIST | CBS_SORT | 
      #             WS_VSCROLL | WS_TABSTOP
      if string.find(line, "CBS_DROPDOWNLIST") > 0:
        Class = "CComboBox"
      else:
        Class = "CComboBoxEdit"
      fields = GetFields(line[8:], 0)
      try:
        l = `dlgDict[name][fields[0]]`
      except KeyError:
        l = "[]"
      # field[4] is the size of the dropped down box
      fpout.write(
"""    o = wpy.%s(self, \"%s\", %s)
    o.wpyLocX = %s
    o.wpyLocY = %s
    o.wpySizeX = %s
    o.wpySizeY = %s
    self.wpyCtrlList.append(\"%s\", o)
""" % (Class, fields[0], l, fields[1], fields[2], fields[3], 13, fields[0]))
    elif key == "CONTROL":
      if string.find(line, "BS_AUTOCHECKBOX") > 0:
        radio_group = None
        #CONTROL         "Rent Structured to Fiscal Year",IDC_CHECK1,"Button",
        #             BS_AUTOCHECKBOX | WS_TABSTOP,228,122,111,10
        fields = GetFields(line[7:], 1)
        fpout.write(
"""    o = wpy.CCheckButton(self, %s)
    o.wpyLocX = %s
    o.wpyLocY = %s
    o.wpySizeX = %s
    o.wpySizeY = %s
    o.wpyHandler = "OnButton%s"
    self.wpyCtrlList.append(\"%s\", o)
""" % (fields[0], fields[4], fields[5], fields[6], fields[7], fields[1], fields[1]))
      elif string.find(line, "BS_AUTORADIOBUTTON") > 0:
        #CONTROL         "After tax",l_at,"Button",BS_AUTORADIOBUTTON,17,136,43,
        #           10
        fields = GetFields(line[7:], 1)
        if radio_group is None:
          radio_group = 1
          fpout.write(
"""    g = wpy.CRadioButton(self, %s)
    g.wpyLocX = %s
    g.wpyLocY = %s
    g.wpySizeX = %s
    g.wpySizeY = %s
    o.wpyHandler = "OnButton%s"
    self.wpyCtrlList.append(\"%s\", g)
""" % (fields[0], fields[4], fields[5], fields[6], fields[7], fields[1], fields[1]))
        else:
          fpout.write(
"""    o = wpy.CRadioButton(self, %s, g)
    o.wpyLocX = %s
    o.wpyLocY = %s
    o.wpySizeX = %s
    o.wpySizeY = %s
    o.wpyHandler = "OnButton%s"
    self.wpyCtrlList.append(\"%s\", o)
""" % (fields[0], fields[4], fields[5], fields[6], fields[7], fields[1], fields[1]))
    elif key == "EDITTEXT":
      radio_group = None
      # EDITTEXT        IDC_EDIT1,90,15,55,5,ES_AUTOHSCROLL
      fields = GetFields(line[8:], 0)
      if string.find(fields[5], "MULTILINE") >= 0:
        ty = "CMultiEdit"
      else:
        ty = "CEdit"
      fpout.write(
"""    o = wpy.%s(self, \"\")
    o.wpyLocX = %s
    o.wpyLocY = %s
    o.wpySizeX = %s
    o.wpySizeY = %s
    self.wpyCtrlList.append(\"%s\", o)
""" % (ty, fields[1], fields[2], fields[3], fields[4], fields[0]))
      if string.find(fields[5], "WS_VSCROLL") >= 0:
        fpout.write("    o.wpyVScrollSize = 1\n")
      if string.find(fields[5], "WS_HSCROLL") >= 0:
        fpout.write("    o.wpyHScrollSize = 1\n")
    elif key == "END":
      radio_group = None
      return
    elif key == "FONT":
      radio_group = None
      # FONT 8, "Helv"
      pass
    elif key == "GROUPBOX":
      radio_group = None
      # GROUPBOX        "LEASE PARAMETERS",IDC_STATIC,9,6,182,183
      fields = GetFields(line[8:], 1)
      fpout.write(
"""    o = wpy.CGroupBox(self, %s)
    o.wpyLocX = %s
    o.wpyLocY = %s
    o.wpySizeX = %s
    o.wpySizeY = %s
    self.wpyCtrlList.append(\"%s\", o)
""" % (fields[0], fields[2], fields[3], fields[4], fields[5], fields[1]))
    elif key == "LTEXT":
      radio_group = None
      # LTEXT           "Lease Start Date",100,6,13,54,8,NOT WS_GROUP
      fields = GetFields(line[5:], 1)
      if string.atoi(fields[5]) > 15:	# Height of control
        fpout.write(
"""    o = wpy.CMessage(self, %s)
    o.wpyLocX = %s
    o.wpyLocY = %s
    o.wpySizeX = %s
    o.wpySizeY = %s
    self.wpyCtrlList.append(\"%s\", o)
""" % (fields[0], fields[2], fields[3], fields[4], fields[5], fields[1]))
      elif len(fields[0]) < 3:	# Text not specified
        fpout.write(
"""    o = wpy.CLabel(self, %s)
    o.wpyLocX = %s
    o.wpyLocY = %s
    o.wpySizeX = %s
    self.wpyCtrlList.append(\"%s\", o)
""" % (fields[0], fields[2], fields[3], fields[4], fields[1]))
      else:
        fpout.write(
"""    o = wpy.CLabel(self, %s)
    o.wpyLocX = %s
    o.wpyLocY = %s
    self.wpyCtrlList.append(\"%s\", o)
""" % (fields[0], fields[2], fields[3], fields[1]))
    elif key == "PUSHBUTTON":
      radio_group = None
      # PUSHBUTTON      "Cancel",IDC_BUTTON2,327,163,50,14
      fields = GetFields(line[10:], 1)
      fpout.write(
"""    o = wpy.CPushButton(self, %s)
    o.wpyLocX = %s
    o.wpyLocY = %s
    o.wpySizeX = %s
    o.wpySizeY = %s
    o.wpyHandler = "OnButton%s"
    self.wpyCtrlList.append(\"%s\", o)
""" % (fields[0], fields[2], fields[3], fields[4], fields[5], fields[1], fields[1]))
    elif key == "DEFPUSHBUTTON":
      radio_group = None
      # DEFPUSHBUTTON      "Cancel",IDC_BUTTON2,327,163,50,14
      fields = GetFields(line[13:], 1)
      fpout.write(
"""    o = wpy.CPushButton(self, %s)
    o.wpyLocX = %s
    o.wpyLocY = %s
    o.wpySizeX = %s
    o.wpySizeY = %s
    self.wpyDefaultButton = o
    o.wpyHandler = "OnButton%s"
    self.wpyCtrlList.append(\"%s\", o)
""" % (fields[0], fields[2], fields[3], fields[4], fields[5], fields[1], fields[1]))
    elif key == "STYLE":
      radio_group = None
      # STYLE DS_MODALFRAME | WS_VISIBLE | WS_CAPTION | WS_SYSMENU
      pass

def do_dlginit(line, fpin, fpout):
  # CFNJapanDialog DLGINIT
  # BEGIN
  #   Freq, 0x403, 5, 0
  #0x4553, 0x494d, "\000" 
  dlgname = string.split(line)[0]
  begin = 0
  try:
    dict = dlgDict[dlgname]
  except:
    dict = {}
    dlgDict[dlgname] = dict
  while 1:
    line = fpin.readline()
    if not line:
      break
    if line[0:5] == "BEGIN":
      begin = 1
      continue
    elif line[0:3] == "END":
      return
    if not begin:
      continue
    while line[-1] in ",|+":
      line = line + string.strip(fpin.readline())
    fields = GetFields(line, 0)
    if line[0:2] == "0x":
      text = ""
      for f in fields:
        if f[0:2] == "0x":
          t = f[4:6]
          if t != "00":
            text = text + chr(string.atoi(t, 16))
          t = f[2:4]
          if t != "00":
            text = text + chr(string.atoi(t, 16))
      try:
        list = dict[ctrlname]
      except:
        list = []
        dict[ctrlname] = list
      list.append(text)
    elif len(fields) == 4:
      ctrlname = fields[0]
      
def GetFields(line, name_index):
  is_quote = 0		# Are we in a quoted string?
  fields = []
  text = ""
  for i in range(0, len(line)):
    ch = line[i]
    if is_quote == 2:
      is_quote = 1	# Skip a character
    elif ch == "\"":
      if is_quote:
        if line[i+1:i+2] == "\"":	# Two quotes in string
          is_quote = 2
          text = text + "\\\""
        else:
          is_quote = 0
          text = text + ch
      else:
        is_quote = 1
        text = text + ch
    elif ch == "," and not is_quote:
      fields.append(string.strip(text))
      text = ""
    else:
      text = text + ch
  fields.append(string.strip(text))
  if name_index >= 0 and fields[name_index][0] == "_":
    t = fields[name_index]
    while t[0] == "_":	# Strip initial '_' from name
      t = t[1:]
    fields[name_index] = t
  return fields

filename = sys.argv[1]
fpin = open(filename)
oname = os.path.split(filename)[1]
oname = os.path.splitext(oname)[0] + ".py"
fpout = open(oname, "w")
fpout.write("import wpy\n\n")
dlgDict = {}
for npass in (1, 2):
  fpin.seek(0, 0)
  while 1:
    line = fpin.readline()
    if not line:
      break
    if line[0] == " " or line[0] == "#" or line[0:2] == "//":
      continue
    fields = string.split(line)
    if len(fields) < 2:
      continue
    if fields[1] == "DIALOG" and npass == 2:
      do_dialog(line, fpin, fpout)
    elif fields[1] == "DIALOGEX" and npass == 2:
      do_dialog(line, fpin, fpout)
    elif fields[1] == "DLGINIT" and npass == 1:
      do_dlginit(line, fpin, fpout)
fpin.close()
