PageRenderTime 50ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/uClinux-dist/user/python/Lib/plat-irix5/flp.py

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