PageRenderTime 45ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/lib-python/2.7/plat-irix6/flp.py

https://bitbucket.org/kkris/pypy
Python | 454 lines | 381 code | 19 blank | 54 comment | 43 complexity | 81dbbfc7b674b11c95c6d16abdb0f983 MD5 | raw file
  1. #
  2. # flp - Module to load fl forms from fd files
  3. #
  4. # Jack Jansen, December 1991
  5. #
  6. from warnings import warnpy3k
  7. warnpy3k("the flp module has been removed in Python 3.0", stacklevel=2)
  8. del warnpy3k
  9. import os
  10. import sys
  11. import FL
  12. SPLITLINE = '--------------------'
  13. FORMLINE = '=============== FORM ==============='
  14. ENDLINE = '=============================='
  15. class error(Exception):
  16. pass
  17. ##################################################################
  18. # Part 1 - The parsing routines #
  19. ##################################################################
  20. #
  21. # Externally visible function. Load form.
  22. #
  23. def parse_form(filename, formname):
  24. forms = checkcache(filename)
  25. if forms is None:
  26. forms = parse_forms(filename)
  27. if forms.has_key(formname):
  28. return forms[formname]
  29. else:
  30. raise error, 'No such form in fd file'
  31. #
  32. # Externally visible function. Load all forms.
  33. #
  34. def parse_forms(filename):
  35. forms = checkcache(filename)
  36. if forms is not None: return forms
  37. fp = _open_formfile(filename)
  38. nforms = _parse_fd_header(fp)
  39. forms = {}
  40. for i in range(nforms):
  41. form = _parse_fd_form(fp, None)
  42. forms[form[0].Name] = form
  43. writecache(filename, forms)
  44. return forms
  45. #
  46. # Internal: see if a cached version of the file exists
  47. #
  48. MAGIC = '.fdc'
  49. _internal_cache = {} # Used by frozen scripts only
  50. def checkcache(filename):
  51. if _internal_cache.has_key(filename):
  52. altforms = _internal_cache[filename]
  53. return _unpack_cache(altforms)
  54. import marshal
  55. fp, filename = _open_formfile2(filename)
  56. fp.close()
  57. cachename = filename + 'c'
  58. try:
  59. fp = open(cachename, 'r')
  60. except IOError:
  61. #print 'flp: no cache file', cachename
  62. return None
  63. try:
  64. if fp.read(4) != MAGIC:
  65. print 'flp: bad magic word in cache file', cachename
  66. return None
  67. cache_mtime = rdlong(fp)
  68. file_mtime = getmtime(filename)
  69. if cache_mtime != file_mtime:
  70. #print 'flp: outdated cache file', cachename
  71. return None
  72. #print 'flp: valid cache file', cachename
  73. altforms = marshal.load(fp)
  74. return _unpack_cache(altforms)
  75. finally:
  76. fp.close()
  77. def _unpack_cache(altforms):
  78. forms = {}
  79. for name in altforms.keys():
  80. altobj, altlist = altforms[name]
  81. obj = _newobj()
  82. obj.make(altobj)
  83. list = []
  84. for altobj in altlist:
  85. nobj = _newobj()
  86. nobj.make(altobj)
  87. list.append(nobj)
  88. forms[name] = obj, list
  89. return forms
  90. def rdlong(fp):
  91. s = fp.read(4)
  92. if len(s) != 4: return None
  93. a, b, c, d = s[0], s[1], s[2], s[3]
  94. return ord(a)<<24 | ord(b)<<16 | ord(c)<<8 | ord(d)
  95. def wrlong(fp, x):
  96. a, b, c, d = (x>>24)&0xff, (x>>16)&0xff, (x>>8)&0xff, x&0xff
  97. fp.write(chr(a) + chr(b) + chr(c) + chr(d))
  98. def getmtime(filename):
  99. import os
  100. from stat import ST_MTIME
  101. try:
  102. return os.stat(filename)[ST_MTIME]
  103. except os.error:
  104. return None
  105. #
  106. # Internal: write cached version of the form (parsing is too slow!)
  107. #
  108. def writecache(filename, forms):
  109. import marshal
  110. fp, filename = _open_formfile2(filename)
  111. fp.close()
  112. cachename = filename + 'c'
  113. try:
  114. fp = open(cachename, 'w')
  115. except IOError:
  116. print 'flp: can\'t create cache file', cachename
  117. return # Never mind
  118. fp.write('\0\0\0\0') # Seek back and write MAGIC when done
  119. wrlong(fp, getmtime(filename))
  120. altforms = _pack_cache(forms)
  121. marshal.dump(altforms, fp)
  122. fp.seek(0)
  123. fp.write(MAGIC)
  124. fp.close()
  125. #print 'flp: wrote cache file', cachename
  126. #
  127. # External: print some statements that set up the internal cache.
  128. # This is for use with the "freeze" script. You should call
  129. # flp.freeze(filename) for all forms used by the script, and collect
  130. # the output on a file in a module file named "frozenforms.py". Then
  131. # in the main program of the script import frozenforms.
  132. # (Don't forget to take this out when using the unfrozen version of
  133. # the script!)
  134. #
  135. def freeze(filename):
  136. forms = parse_forms(filename)
  137. altforms = _pack_cache(forms)
  138. print 'import flp'
  139. print 'flp._internal_cache[', repr(filename), '] =', altforms
  140. #
  141. # Internal: create the data structure to be placed in the cache
  142. #
  143. def _pack_cache(forms):
  144. altforms = {}
  145. for name in forms.keys():
  146. obj, list = forms[name]
  147. altobj = obj.__dict__
  148. altlist = []
  149. for obj in list: altlist.append(obj.__dict__)
  150. altforms[name] = altobj, altlist
  151. return altforms
  152. #
  153. # Internal: Locate form file (using PYTHONPATH) and open file
  154. #
  155. def _open_formfile(filename):
  156. return _open_formfile2(filename)[0]
  157. def _open_formfile2(filename):
  158. if filename[-3:] != '.fd':
  159. filename = filename + '.fd'
  160. if filename[0] == '/':
  161. try:
  162. fp = open(filename,'r')
  163. except IOError:
  164. fp = None
  165. else:
  166. for pc in sys.path:
  167. pn = os.path.join(pc, filename)
  168. try:
  169. fp = open(pn, 'r')
  170. filename = pn
  171. break
  172. except IOError:
  173. fp = None
  174. if fp is None:
  175. raise error, 'Cannot find forms file ' + filename
  176. return fp, filename
  177. #
  178. # Internal: parse the fd file header, return number of forms
  179. #
  180. def _parse_fd_header(file):
  181. # First read the magic header line
  182. datum = _parse_1_line(file)
  183. if datum != ('Magic', 12321):
  184. raise error, 'Not a forms definition file'
  185. # Now skip until we know number of forms
  186. while 1:
  187. datum = _parse_1_line(file)
  188. if type(datum) == type(()) and datum[0] == 'Numberofforms':
  189. break
  190. return datum[1]
  191. #
  192. # Internal: parse fd form, or skip if name doesn't match.
  193. # the special value None means 'always parse it'.
  194. #
  195. def _parse_fd_form(file, name):
  196. datum = _parse_1_line(file)
  197. if datum != FORMLINE:
  198. raise error, 'Missing === FORM === line'
  199. form = _parse_object(file)
  200. if form.Name == name or name is None:
  201. objs = []
  202. for j in range(form.Numberofobjects):
  203. obj = _parse_object(file)
  204. objs.append(obj)
  205. return (form, objs)
  206. else:
  207. for j in range(form.Numberofobjects):
  208. _skip_object(file)
  209. return None
  210. #
  211. # Internal class: a convenient place to store object info fields
  212. #
  213. class _newobj:
  214. def add(self, name, value):
  215. self.__dict__[name] = value
  216. def make(self, dict):
  217. for name in dict.keys():
  218. self.add(name, dict[name])
  219. #
  220. # Internal parsing routines.
  221. #
  222. def _parse_string(str):
  223. if '\\' in str:
  224. s = '\'' + str + '\''
  225. try:
  226. return eval(s)
  227. except:
  228. pass
  229. return str
  230. def _parse_num(str):
  231. return eval(str)
  232. def _parse_numlist(str):
  233. slist = str.split()
  234. nlist = []
  235. for i in slist:
  236. nlist.append(_parse_num(i))
  237. return nlist
  238. # This dictionary maps item names to parsing routines.
  239. # If no routine is given '_parse_num' is default.
  240. _parse_func = { \
  241. 'Name': _parse_string, \
  242. 'Box': _parse_numlist, \
  243. 'Colors': _parse_numlist, \
  244. 'Label': _parse_string, \
  245. 'Name': _parse_string, \
  246. 'Callback': _parse_string, \
  247. 'Argument': _parse_string }
  248. # This function parses a line, and returns either
  249. # a string or a tuple (name,value)
  250. import re
  251. prog = re.compile('^([^:]*): *(.*)')
  252. def _parse_line(line):
  253. match = prog.match(line)
  254. if not match:
  255. return line
  256. name, value = match.group(1, 2)
  257. if name[0] == 'N':
  258. name = ''.join(name.split())
  259. name = name.lower()
  260. name = name.capitalize()
  261. try:
  262. pf = _parse_func[name]
  263. except KeyError:
  264. pf = _parse_num
  265. value = pf(value)
  266. return (name, value)
  267. def _readline(file):
  268. line = file.readline()
  269. if not line:
  270. raise EOFError
  271. return line[:-1]
  272. def _parse_1_line(file):
  273. line = _readline(file)
  274. while line == '':
  275. line = _readline(file)
  276. return _parse_line(line)
  277. def _skip_object(file):
  278. line = ''
  279. while not line in (SPLITLINE, FORMLINE, ENDLINE):
  280. pos = file.tell()
  281. line = _readline(file)
  282. if line == FORMLINE:
  283. file.seek(pos)
  284. def _parse_object(file):
  285. obj = _newobj()
  286. while 1:
  287. pos = file.tell()
  288. datum = _parse_1_line(file)
  289. if datum in (SPLITLINE, FORMLINE, ENDLINE):
  290. if datum == FORMLINE:
  291. file.seek(pos)
  292. return obj
  293. if type(datum) is not type(()) or len(datum) != 2:
  294. raise error, 'Parse error, illegal line in object: '+datum
  295. obj.add(datum[0], datum[1])
  296. #################################################################
  297. # Part 2 - High-level object/form creation routines #
  298. #################################################################
  299. #
  300. # External - Create a form an link to an instance variable.
  301. #
  302. def create_full_form(inst, (fdata, odatalist)):
  303. form = create_form(fdata)
  304. exec 'inst.'+fdata.Name+' = form\n'
  305. for odata in odatalist:
  306. create_object_instance(inst, form, odata)
  307. #
  308. # External - Merge a form into an existing form in an instance
  309. # variable.
  310. #
  311. def merge_full_form(inst, form, (fdata, odatalist)):
  312. exec 'inst.'+fdata.Name+' = form\n'
  313. if odatalist[0].Class != FL.BOX:
  314. raise error, 'merge_full_form() expects FL.BOX as first obj'
  315. for odata in odatalist[1:]:
  316. create_object_instance(inst, form, odata)
  317. #################################################################
  318. # Part 3 - Low-level object/form creation routines #
  319. #################################################################
  320. #
  321. # External Create_form - Create form from parameters
  322. #
  323. def create_form(fdata):
  324. import fl
  325. return fl.make_form(FL.NO_BOX, fdata.Width, fdata.Height)
  326. #
  327. # External create_object - Create an object. Make sure there are
  328. # no callbacks. Returns the object created.
  329. #
  330. def create_object(form, odata):
  331. obj = _create_object(form, odata)
  332. if odata.Callback:
  333. raise error, 'Creating free object with callback'
  334. return obj
  335. #
  336. # External create_object_instance - Create object in an instance.
  337. #
  338. def create_object_instance(inst, form, odata):
  339. obj = _create_object(form, odata)
  340. if odata.Callback:
  341. cbfunc = eval('inst.'+odata.Callback)
  342. obj.set_call_back(cbfunc, odata.Argument)
  343. if odata.Name:
  344. exec 'inst.' + odata.Name + ' = obj\n'
  345. #
  346. # Internal _create_object: Create the object and fill options
  347. #
  348. def _create_object(form, odata):
  349. crfunc = _select_crfunc(form, odata.Class)
  350. obj = crfunc(odata.Type, odata.Box[0], odata.Box[1], odata.Box[2], \
  351. odata.Box[3], odata.Label)
  352. if not odata.Class in (FL.BEGIN_GROUP, FL.END_GROUP):
  353. obj.boxtype = odata.Boxtype
  354. obj.col1 = odata.Colors[0]
  355. obj.col2 = odata.Colors[1]
  356. obj.align = odata.Alignment
  357. obj.lstyle = odata.Style
  358. obj.lsize = odata.Size
  359. obj.lcol = odata.Lcol
  360. return obj
  361. #
  362. # Internal crfunc: helper function that returns correct create function
  363. #
  364. def _select_crfunc(fm, cl):
  365. if cl == FL.BEGIN_GROUP: return fm.bgn_group
  366. elif cl == FL.END_GROUP: return fm.end_group
  367. elif cl == FL.BITMAP: return fm.add_bitmap
  368. elif cl == FL.BOX: return fm.add_box
  369. elif cl == FL.BROWSER: return fm.add_browser
  370. elif cl == FL.BUTTON: return fm.add_button
  371. elif cl == FL.CHART: return fm.add_chart
  372. elif cl == FL.CHOICE: return fm.add_choice
  373. elif cl == FL.CLOCK: return fm.add_clock
  374. elif cl == FL.COUNTER: return fm.add_counter
  375. elif cl == FL.DIAL: return fm.add_dial
  376. elif cl == FL.FREE: return fm.add_free
  377. elif cl == FL.INPUT: return fm.add_input
  378. elif cl == FL.LIGHTBUTTON: return fm.add_lightbutton
  379. elif cl == FL.MENU: return fm.add_menu
  380. elif cl == FL.POSITIONER: return fm.add_positioner
  381. elif cl == FL.ROUNDBUTTON: return fm.add_roundbutton
  382. elif cl == FL.SLIDER: return fm.add_slider
  383. elif cl == FL.VALSLIDER: return fm.add_valslider
  384. elif cl == FL.TEXT: return fm.add_text
  385. elif cl == FL.TIMER: return fm.add_timer
  386. else:
  387. raise error, 'Unknown object type: %r' % (cl,)
  388. def test():
  389. import time
  390. t0 = time.time()
  391. if len(sys.argv) == 2:
  392. forms = parse_forms(sys.argv[1])
  393. t1 = time.time()
  394. print 'parse time:', 0.001*(t1-t0), 'sec.'
  395. keys = forms.keys()
  396. keys.sort()
  397. for i in keys:
  398. _printform(forms[i])
  399. elif len(sys.argv) == 3:
  400. form = parse_form(sys.argv[1], sys.argv[2])
  401. t1 = time.time()
  402. print 'parse time:', round(t1-t0, 3), 'sec.'
  403. _printform(form)
  404. else:
  405. print 'Usage: test fdfile [form]'
  406. def _printform(form):
  407. f = form[0]
  408. objs = form[1]
  409. print 'Form ', f.Name, ', size: ', f.Width, f.Height, ' Nobj ', f.Numberofobjects
  410. for i in objs:
  411. print ' Obj ', i.Name, ' type ', i.Class, i.Type
  412. print ' Box ', i.Box, ' btype ', i.Boxtype
  413. print ' Label ', i.Label, ' size/style/col/align ', i.Size,i.Style, i.Lcol, i.Alignment
  414. print ' cols ', i.Colors
  415. print ' cback ', i.Callback, i.Argument