makerst.py 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. import sys
  4. import xml.etree.ElementTree as ET
  5. input_list = []
  6. for arg in sys.argv[1:]:
  7. input_list.append(arg)
  8. if len(input_list) < 1:
  9. print 'usage: makerst.py <classes.xml>'
  10. sys.exit(0)
  11. def validate_tag(elem, tag):
  12. if elem.tag != tag:
  13. print "Tag mismatch, expected '" + tag + "', got " + elem.tag
  14. sys.exit(255)
  15. class_names = []
  16. classes = {}
  17. def ul_string(str,ul):
  18. str+="\n"
  19. for i in range(len(str)-1):
  20. str+=ul
  21. str+="\n"
  22. return str
  23. def make_class_list(class_list, columns):
  24. f = open('class_list.rst', 'wb')
  25. prev = 0
  26. col_max = len(class_list) / columns + 1
  27. print ('col max is ', col_max)
  28. col_count = 0
  29. row_count = 0
  30. last_initial = ''
  31. fit_columns = []
  32. for n in range(0, columns):
  33. fit_columns += [[]]
  34. indexers = []
  35. last_initial = ''
  36. idx = 0
  37. for n in class_list:
  38. col = idx / col_max
  39. if col >= columns:
  40. col = columns - 1
  41. fit_columns[col] += [n]
  42. idx += 1
  43. if n[:1] != last_initial:
  44. indexers += [n]
  45. last_initial = n[:1]
  46. row_max = 0
  47. f.write("\n")
  48. for n in range(0, columns):
  49. if len(fit_columns[n]) > row_max:
  50. row_max = len(fit_columns[n])
  51. f.write("| ")
  52. for n in range(0, columns):
  53. f.write(" | |")
  54. f.write("\n")
  55. f.write("+")
  56. for n in range(0, columns):
  57. f.write("--+-------+")
  58. f.write("\n")
  59. for r in range(0, row_max):
  60. s = '+ '
  61. for c in range(0, columns):
  62. if r >= len(fit_columns[c]):
  63. continue
  64. classname = fit_columns[c][r]
  65. initial = classname[0]
  66. if classname in indexers:
  67. s += '**' + initial + '** | '
  68. else:
  69. s += ' | '
  70. s += '[' + classname + '](class_'+ classname.lower()+') | '
  71. s += '\n'
  72. f.write(s)
  73. for n in range(0, columns):
  74. f.write("--+-------+")
  75. f.write("\n")
  76. def rstize_text(text,cclass):
  77. # Linebreak + tabs in the XML should become two line breaks
  78. pos = 0
  79. while True:
  80. pos = text.find('\n', pos)
  81. if pos == -1:
  82. break
  83. pre_text = text[:pos]
  84. while text[pos+1] == '\t':
  85. pos += 1
  86. post_text = text[pos+1:]
  87. text = pre_text + "\n\n" + post_text
  88. pos += 2
  89. # Escape * character to avoid interpreting it as emphasis
  90. pos = 0
  91. while True:
  92. pos = text.find('*', pos)
  93. if pos == -1:
  94. break
  95. text = text[:pos] + "\*" + text[pos + 1:]
  96. pos += 2
  97. # Escape _ character at the end of a word to avoid interpreting it as an inline hyperlink
  98. pos = 0
  99. while True:
  100. pos = text.find('_', pos)
  101. if pos == -1:
  102. break
  103. if not text[pos + 1].isalnum(): # don't escape within a snake_case word
  104. text = text[:pos] + "\_" + text[pos + 1:]
  105. pos += 2
  106. else:
  107. pos += 1
  108. # Handle [tags]
  109. pos = 0
  110. while True:
  111. pos = text.find('[', pos)
  112. if pos == -1:
  113. break
  114. endq_pos = text.find(']', pos + 1)
  115. if endq_pos == -1:
  116. break
  117. pre_text = text[:pos]
  118. post_text = text[endq_pos + 1:]
  119. tag_text = text[pos + 1:endq_pos]
  120. if tag_text in class_names:
  121. tag_text = make_type(tag_text)
  122. else: # command
  123. cmd = tag_text
  124. space_pos = tag_text.find(' ')
  125. if cmd.find('html') == 0:
  126. cmd = tag_text[:space_pos]
  127. param = tag_text[space_pos + 1:]
  128. tag_text = param
  129. elif cmd.find('method') == 0:
  130. cmd = tag_text[:space_pos]
  131. param = tag_text[space_pos + 1:]
  132. if param.find('.') != -1:
  133. (class_param, method_param) = param.split('.')
  134. tag_text = ':ref:`'+class_param+'.'+method_param+'<' + class_param.lower() + '_' + method_param + '>`'
  135. else:
  136. tag_text = ':ref:`' + param + '<' + cclass +"_"+ param + '>`'
  137. elif cmd.find('image=') == 0:
  138. tag_text = "" #'![](' + cmd[6:] + ')'
  139. elif cmd.find('url=') == 0:
  140. tag_text = ':ref:`' + cmd[4:] + '<'+cmd[4:]+">`"
  141. elif cmd == '/url':
  142. tag_text = ')'
  143. elif cmd == 'center':
  144. tag_text = ''
  145. elif cmd == '/center':
  146. tag_text = ''
  147. elif cmd == 'br':
  148. # Make a new paragraph instead of a linebreak, rst is not so linebreak friendly
  149. tag_text = '\n\n'
  150. # Strip potential leading spaces
  151. while post_text[0] == ' ':
  152. post_text = post_text[1:]
  153. elif cmd == 'i' or cmd == '/i':
  154. tag_text = '*'
  155. elif cmd == 'b' or cmd == '/b':
  156. tag_text = '**'
  157. elif cmd == 'u' or cmd == '/u':
  158. tag_text = ''
  159. elif cmd == 'code' or cmd == '/code':
  160. tag_text = '``'
  161. else:
  162. tag_text = ':ref:`' + tag_text + '<class_'+tag_text.lower()+'>`'
  163. text = pre_text + tag_text + post_text
  164. pos = len(pre_text) + len(tag_text)
  165. # tnode = ET.SubElement(parent,"div")
  166. # tnode.text=text
  167. return text
  168. def make_type(t):
  169. global class_names
  170. if t in class_names:
  171. return ':ref:`'+t+'<class_' + t.lower()+'>`'
  172. return t
  173. def make_method(
  174. f,
  175. name,
  176. m,
  177. declare,
  178. cname,
  179. event=False,
  180. pp=None
  181. ):
  182. if (declare or pp==None):
  183. t = '- '
  184. else:
  185. t = ""
  186. ret_type = 'void'
  187. args = list(m)
  188. mdata = {}
  189. mdata['argidx'] = []
  190. for a in args:
  191. if a.tag == 'return':
  192. idx = -1
  193. elif a.tag == 'argument':
  194. idx = int(a.attrib['index'])
  195. else:
  196. continue
  197. mdata['argidx'].append(idx)
  198. mdata[idx] = a
  199. if not event:
  200. if -1 in mdata['argidx']:
  201. t += make_type(mdata[-1].attrib['type'])
  202. else:
  203. t += 'void'
  204. t += ' '
  205. if declare or pp==None:
  206. # span.attrib["class"]="funcdecl"
  207. # a=ET.SubElement(span,"a")
  208. # a.attrib["name"]=name+"_"+m.attrib["name"]
  209. # a.text=name+"::"+m.attrib["name"]
  210. s = ' **'+m.attrib['name']+'** '
  211. else:
  212. s = ':ref:`'+ m.attrib['name']+'<class_' + cname+"_"+m.attrib['name'] + '>` '
  213. s += ' **(**'
  214. argfound = False
  215. for a in mdata['argidx']:
  216. arg = mdata[a]
  217. if a < 0:
  218. continue
  219. if a > 0:
  220. s += ', '
  221. else:
  222. s += ' '
  223. s += make_type(arg.attrib['type'])
  224. if 'name' in arg.attrib:
  225. s += ' ' + arg.attrib['name']
  226. else:
  227. s += ' arg' + str(a)
  228. if 'default' in arg.attrib:
  229. s += '=' + arg.attrib['default']
  230. argfound = True
  231. if argfound:
  232. s += ' '
  233. s += ' **)**'
  234. if 'qualifiers' in m.attrib:
  235. s += ' ' + m.attrib['qualifiers']
  236. # f.write(s)
  237. if (not declare):
  238. if (pp!=None):
  239. pp.append( (t,s) )
  240. else:
  241. f.write("- "+t+" "+s+"\n")
  242. else:
  243. f.write(t+s+"\n")
  244. def make_heading(title, underline):
  245. return title + '\n' + underline*len(title) + "\n\n"
  246. def make_rst_class(node):
  247. name = node.attrib['name']
  248. f = open("class_"+name.lower() + '.rst', 'wb')
  249. f.write(".. _class_"+name+":\n\n")
  250. f.write(make_heading(name, '='))
  251. if 'inherits' in node.attrib:
  252. inh = node.attrib['inherits'].strip()
  253. # whle inh in classes[cn]
  254. f.write('**Inherits:** ')
  255. first=True
  256. while(inh in classes):
  257. if (not first):
  258. f.write(" **<** ")
  259. else:
  260. first=False
  261. f.write(make_type(inh))
  262. inode = classes[inh]
  263. if ('inherits' in inode.attrib):
  264. inh=inode.attrib['inherits'].strip()
  265. else:
  266. inh=None
  267. f.write("\n\n")
  268. inherited=[]
  269. for cn in classes:
  270. c=classes[cn]
  271. if 'inherits' in c.attrib:
  272. if (c.attrib['inherits'].strip()==name):
  273. inherited.append(c.attrib['name'])
  274. if (len(inherited)):
  275. f.write('**Inherited By:** ')
  276. for i in range(len(inherited)):
  277. if (i>0):
  278. f.write(", ")
  279. f.write(make_type(inherited[i]))
  280. f.write("\n\n")
  281. if 'category' in node.attrib:
  282. f.write('**Category:** ' + node.attrib['category'].strip() + "\n\n")
  283. f.write(make_heading('Brief Description', '-'))
  284. briefd = node.find('brief_description')
  285. if briefd != None:
  286. f.write(rstize_text(briefd.text.strip(),name) + "\n\n")
  287. methods = node.find('methods')
  288. if methods != None and len(list(methods)) > 0:
  289. f.write(make_heading('Member Functions', '-'))
  290. ml=[]
  291. for m in list(methods):
  292. make_method(f, node.attrib['name'], m, False,name,False,ml)
  293. longest_t = 0
  294. longest_s = 0
  295. for s in ml:
  296. sl = len(s[0])
  297. if (sl>longest_s):
  298. longest_s=sl
  299. tl = len(s[1])
  300. if (tl>longest_t):
  301. longest_t=tl
  302. sep="+"
  303. for i in range(longest_s+2):
  304. sep+="-"
  305. sep+="+"
  306. for i in range(longest_t+2):
  307. sep+="-"
  308. sep+="+\n"
  309. f.write(sep)
  310. for s in ml:
  311. rt = s[0]
  312. while( len(rt) < longest_s ):
  313. rt+=" "
  314. st = s[1]
  315. while( len(st) < longest_t ):
  316. st+=" "
  317. f.write("| "+rt+" | "+st+" |\n")
  318. f.write(sep)
  319. f.write('\n')
  320. events = node.find('signals')
  321. if events != None and len(list(events)) > 0:
  322. f.write(make_heading('Signals', '-'))
  323. for m in list(events):
  324. make_method(f, node.attrib['name'], m, True,name, True)
  325. f.write('\n')
  326. members = node.find('members')
  327. if members != None and len(list(members)) > 0:
  328. f.write(make_heading('Member Variables', '-'))
  329. for c in list(members):
  330. s = '- '
  331. s += make_type(c.attrib['type']) + ' '
  332. s += '**' + c.attrib['name'] + '**'
  333. if c.text.strip() != '':
  334. s += ' - ' + c.text.strip()
  335. f.write(s + '\n')
  336. f.write('\n')
  337. constants = node.find('constants')
  338. if constants != None and len(list(constants)) > 0:
  339. f.write(make_heading('Numeric Constants', '-'))
  340. for c in list(constants):
  341. s = '- '
  342. s += '**' + c.attrib['name'] + '**'
  343. if 'value' in c.attrib:
  344. s += ' = **' + c.attrib['value'] + '**'
  345. if c.text.strip() != '':
  346. s += ' --- ' + rstize_text(c.text.strip(),name)
  347. f.write(s + '\n')
  348. f.write('\n')
  349. descr = node.find('description')
  350. if descr != None and descr.text.strip() != '':
  351. f.write(make_heading('Description', '-'))
  352. f.write(rstize_text(descr.text.strip(),name) + "\n\n")
  353. methods = node.find('methods')
  354. if methods != None and len(list(methods)) > 0:
  355. f.write(make_heading('Member Function Description', '-'))
  356. for m in list(methods):
  357. f.write(".. _class_"+name+"_"+m.attrib['name']+":\n\n")
  358. # f.write(ul_string(m.attrib['name'],"^"))
  359. #f.write('\n<a name="'+m.attrib['name']+'">' + m.attrib['name'] + '</a>\n------\n')
  360. make_method(f, node.attrib['name'], m, True,name)
  361. f.write('\n')
  362. d = m.find('description')
  363. if d == None or d.text.strip() == '':
  364. continue
  365. f.write(rstize_text(d.text.strip(),name))
  366. f.write("\n\n")
  367. f.write('\n')
  368. for file in input_list:
  369. tree = ET.parse(file)
  370. doc = tree.getroot()
  371. if 'version' not in doc.attrib:
  372. print "Version missing from 'doc'"
  373. sys.exit(255)
  374. version = doc.attrib['version']
  375. for c in list(doc):
  376. if c.attrib['name'] in class_names:
  377. continue
  378. class_names.append(c.attrib['name'])
  379. classes[c.attrib['name']] = c
  380. class_names.sort()
  381. #Don't make class list for Sphinx, :toctree: handles it
  382. #make_class_list(class_names, 2)
  383. for cn in class_names:
  384. c = classes[cn]
  385. make_rst_class(c)