sphinx_doc_gen.py 71 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152
  1. # ##### BEGIN GPL LICENSE BLOCK #####
  2. #
  3. # This program is free software; you can redistribute it and/or
  4. # modify it under the terms of the GNU General Public License
  5. # as published by the Free Software Foundation; either version 2
  6. # of the License, or (at your option) any later version.
  7. #
  8. # This program is distributed in the hope that it will be useful,
  9. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. # GNU General Public License for more details.
  12. #
  13. # You should have received a copy of the GNU General Public License
  14. # along with this program; if not, write to the Free Software Foundation,
  15. # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  16. #
  17. # ##### END GPL LICENSE BLOCK #####
  18. # <pep8 compliant>
  19. SCRIPT_HELP_MSG = """
  20. API dump in RST files
  21. ---------------------
  22. Run this script from Blender's root path once you have compiled Blender
  23. blender --background --factory-startup -noaudio --python doc/python_api/sphinx_doc_gen.py
  24. This will generate python files in doc/python_api/sphinx-in/
  25. providing ./blender is or links to the blender executable
  26. To choose sphinx-in directory:
  27. blender --background --factory-startup --python doc/python_api/sphinx_doc_gen.py -- --output ../python_api
  28. For quick builds:
  29. blender --background --factory-startup --python doc/python_api/sphinx_doc_gen.py -- --partial bmesh.*
  30. Sphinx: HTML generation
  31. -----------------------
  32. After you have built doc/python_api/sphinx-in (see above),
  33. generate html docs by running:
  34. cd doc/python_api
  35. sphinx-build sphinx-in sphinx-out
  36. Sphinx: PDF generation
  37. ----------------------
  38. After you have built doc/python_api/sphinx-in (see above),
  39. generate the pdf doc by running:
  40. sphinx-build -b latex doc/python_api/sphinx-in doc/python_api/sphinx-out
  41. cd doc/python_api/sphinx-out
  42. make
  43. """
  44. try:
  45. import bpy # Blender module
  46. except ImportError:
  47. print("\nERROR: this script must run from inside Blender")
  48. print(SCRIPT_HELP_MSG)
  49. import sys
  50. sys.exit()
  51. import rna_info # Blender module
  52. def rna_info_BuildRNAInfo_cache():
  53. if rna_info_BuildRNAInfo_cache.ret is None:
  54. rna_info_BuildRNAInfo_cache.ret = rna_info.BuildRNAInfo()
  55. return rna_info_BuildRNAInfo_cache.ret
  56. rna_info_BuildRNAInfo_cache.ret = None
  57. # --- end rna_info cache
  58. # import rpdb2; rpdb2.start_embedded_debugger('test')
  59. import os
  60. import sys
  61. import inspect
  62. import shutil
  63. import logging
  64. from platform import platform
  65. PLATFORM = platform().split('-')[0].lower() # 'linux', 'darwin', 'windows'
  66. SCRIPT_DIR = os.path.abspath(os.path.dirname(__file__))
  67. def handle_args():
  68. '''
  69. Parse the args passed to Blender after "--", ignored by Blender
  70. '''
  71. import argparse
  72. # When --help is given, print the usage text
  73. parser = argparse.ArgumentParser(
  74. formatter_class=argparse.RawTextHelpFormatter,
  75. usage=SCRIPT_HELP_MSG
  76. )
  77. # optional arguments
  78. parser.add_argument("-p", "--partial",
  79. dest="partial",
  80. type=str,
  81. default="",
  82. help="Use a wildcard to only build specific module(s)\n"
  83. "Example: --partial bmesh*\n",
  84. required=False)
  85. parser.add_argument("-f", "--fullrebuild",
  86. dest="full_rebuild",
  87. default=False,
  88. action='store_true',
  89. help="Rewrite all rst files in sphinx-in/ "
  90. "(default=False)",
  91. required=False)
  92. parser.add_argument("-b", "--bpy",
  93. dest="bpy",
  94. default=False,
  95. action='store_true',
  96. help="Write the rst file of the bpy module "
  97. "(default=False)",
  98. required=False)
  99. parser.add_argument("-o", "--output",
  100. dest="output_dir",
  101. type=str,
  102. default=SCRIPT_DIR,
  103. help="Path of the API docs (default=<script dir>)",
  104. required=False)
  105. parser.add_argument("-B", "--sphinx-build",
  106. dest="sphinx_build",
  107. default=False,
  108. action='store_true',
  109. help="Build the html docs by running:\n"
  110. "sphinx-build SPHINX_IN SPHINX_OUT\n"
  111. "(default=False; does not depend on -P)",
  112. required=False)
  113. parser.add_argument("-P", "--sphinx-build-pdf",
  114. dest="sphinx_build_pdf",
  115. default=False,
  116. action='store_true',
  117. help="Build the pdf by running:\n"
  118. "sphinx-build -b latex SPHINX_IN SPHINX_OUT_PDF\n"
  119. "(default=False; does not depend on -B)",
  120. required=False)
  121. parser.add_argument("-R", "--pack-reference",
  122. dest="pack_reference",
  123. default=False,
  124. action='store_true',
  125. help="Pack all necessary files in the deployed dir.\n"
  126. "(default=False; use with -B and -P)",
  127. required=False)
  128. parser.add_argument("-l", "--log",
  129. dest="log",
  130. default=False,
  131. action='store_true',
  132. help="Log the output of the api dump and sphinx|latex "
  133. "warnings and errors (default=False).\n"
  134. "If given, save logs in:\n"
  135. "* OUTPUT_DIR/.bpy.log\n"
  136. "* OUTPUT_DIR/.sphinx-build.log\n"
  137. "* OUTPUT_DIR/.sphinx-build_pdf.log\n"
  138. "* OUTPUT_DIR/.latex_make.log",
  139. required=False)
  140. # parse only the args passed after '--'
  141. argv = []
  142. if "--" in sys.argv:
  143. argv = sys.argv[sys.argv.index("--") + 1:] # get all args after "--"
  144. return parser.parse_args(argv)
  145. ARGS = handle_args()
  146. # ----------------------------------BPY-----------------------------------------
  147. BPY_LOGGER = logging.getLogger('bpy')
  148. BPY_LOGGER.setLevel(logging.DEBUG)
  149. """
  150. # for quick rebuilds
  151. rm -rf /b/doc/python_api/sphinx-* && \
  152. ./blender -b -noaudio --factory-startup -P doc/python_api/sphinx_doc_gen.py && \
  153. sphinx-build doc/python_api/sphinx-in doc/python_api/sphinx-out
  154. or
  155. ./blender -b -noaudio --factory-startup -P doc/python_api/sphinx_doc_gen.py -- -f -B
  156. """
  157. # Switch for quick testing so doc-builds don't take so long
  158. if not ARGS.partial:
  159. # full build
  160. FILTER_BPY_OPS = None
  161. FILTER_BPY_TYPES = None
  162. EXCLUDE_INFO_DOCS = False
  163. EXCLUDE_MODULES = []
  164. else:
  165. # can manually edit this too:
  166. # FILTER_BPY_OPS = ("import.scene", ) # allow
  167. # FILTER_BPY_TYPES = ("bpy_struct", "Operator", "ID") # allow
  168. EXCLUDE_INFO_DOCS = True
  169. EXCLUDE_MODULES = [
  170. "aud",
  171. "bgl",
  172. "blf",
  173. "bmesh",
  174. "bmesh.ops",
  175. "bmesh.types",
  176. "bmesh.utils",
  177. "bmesh.geometry",
  178. "bpy.app",
  179. "bpy.app.handlers",
  180. "bpy.app.timers",
  181. "bpy.app.translations",
  182. "bpy.context",
  183. "bpy.data",
  184. "bpy.ops", # supports filtering
  185. "bpy.path",
  186. "bpy.props",
  187. "bpy.types", # supports filtering
  188. "bpy.utils",
  189. "bpy.utils.previews",
  190. "bpy_extras",
  191. "gpu",
  192. "gpu.types",
  193. "gpu.matrix",
  194. "gpu.select",
  195. "gpu_extras",
  196. "idprop.types",
  197. "mathutils",
  198. "mathutils.bvhtree",
  199. "mathutils.geometry",
  200. "mathutils.interpolate",
  201. "mathutils.kdtree",
  202. "mathutils.noise",
  203. "freestyle",
  204. "freestyle.chainingiterators",
  205. "freestyle.functions",
  206. "freestyle.predicates",
  207. "freestyle.shaders",
  208. "freestyle.types",
  209. "freestyle.utils",
  210. ]
  211. # ------
  212. # Filter
  213. #
  214. # TODO, support bpy.ops and bpy.types filtering
  215. import fnmatch
  216. m = None
  217. EXCLUDE_MODULES = [m for m in EXCLUDE_MODULES if not fnmatch.fnmatchcase(m, ARGS.partial)]
  218. # special support for bpy.types.XXX
  219. FILTER_BPY_OPS = tuple([m[8:] for m in ARGS.partial.split(":") if m.startswith("bpy.ops.")])
  220. if FILTER_BPY_OPS:
  221. EXCLUDE_MODULES.remove("bpy.ops")
  222. FILTER_BPY_TYPES = tuple([m[10:] for m in ARGS.partial.split(":") if m.startswith("bpy.types.")])
  223. if FILTER_BPY_TYPES:
  224. EXCLUDE_MODULES.remove("bpy.types")
  225. print(FILTER_BPY_TYPES)
  226. EXCLUDE_INFO_DOCS = (not fnmatch.fnmatchcase("info", ARGS.partial))
  227. del m
  228. del fnmatch
  229. BPY_LOGGER.debug(
  230. "Partial Doc Build, Skipping: %s\n" %
  231. "\n ".join(sorted(EXCLUDE_MODULES)))
  232. #
  233. # done filtering
  234. # --------------
  235. try:
  236. __import__("aud")
  237. except ImportError:
  238. BPY_LOGGER.debug("Warning: Built without 'aud' module, docs incomplete...")
  239. EXCLUDE_MODULES.append("aud")
  240. try:
  241. __import__("freestyle")
  242. except ImportError:
  243. BPY_LOGGER.debug("Warning: Built without 'freestyle' module, docs incomplete...")
  244. EXCLUDE_MODULES.extend([
  245. "freestyle",
  246. "freestyle.chainingiterators",
  247. "freestyle.functions",
  248. "freestyle.predicates",
  249. "freestyle.shaders",
  250. "freestyle.types",
  251. "freestyle.utils",
  252. ])
  253. # Source files we use, and need to copy to the OUTPUT_DIR
  254. # to have working out-of-source builds.
  255. # Note that ".." is replaced by "__" in the RST files,
  256. # to avoid having to match Blender's source tree.
  257. EXTRA_SOURCE_FILES = (
  258. "../../../release/scripts/templates_py/bmesh_simple.py",
  259. "../../../release/scripts/templates_py/gizmo_operator.py",
  260. "../../../release/scripts/templates_py/gizmo_operator_target.py",
  261. "../../../release/scripts/templates_py/gizmo_simple.py",
  262. "../../../release/scripts/templates_py/operator_simple.py",
  263. "../../../release/scripts/templates_py/ui_panel_simple.py",
  264. "../../../release/scripts/templates_py/ui_previews_custom_icon.py",
  265. "../examples/bmesh.ops.1.py",
  266. "../examples/bpy.app.translations.py",
  267. )
  268. # examples
  269. EXAMPLES_DIR = os.path.abspath(os.path.join(SCRIPT_DIR, "examples"))
  270. EXAMPLE_SET = set()
  271. for f in os.listdir(EXAMPLES_DIR):
  272. if f.endswith(".py"):
  273. EXAMPLE_SET.add(os.path.splitext(f)[0])
  274. EXAMPLE_SET_USED = set()
  275. # rst files dir
  276. RST_DIR = os.path.abspath(os.path.join(SCRIPT_DIR, "rst"))
  277. # extra info, not api reference docs
  278. # stored in ./rst/info_*
  279. INFO_DOCS = (
  280. ("info_quickstart.rst",
  281. "Quickstart: new to Blender or scripting and want to get your feet wet?"),
  282. ("info_overview.rst",
  283. "API Overview: a more complete explanation of Python integration"),
  284. ("info_api_reference.rst",
  285. "API Reference Usage: examples of how to use the API reference docs"),
  286. ("info_best_practice.rst",
  287. "Best Practice: Conventions to follow for writing good scripts"),
  288. ("info_tips_and_tricks.rst",
  289. "Tips and Tricks: Hints to help you while writing scripts for Blender"),
  290. ("info_gotcha.rst",
  291. "Gotcha's: some of the problems you may come up against when writing scripts"),
  292. ("change_log.rst", "List of changes since last Blender release"),
  293. )
  294. # only support for properties atm.
  295. RNA_BLACKLIST = {
  296. # XXX messes up PDF!, really a bug but for now just workaround.
  297. "PreferencesSystem": {"language", }
  298. }
  299. MODULE_GROUPING = {
  300. "bmesh.types": (
  301. ("Base Mesh Type", '-'),
  302. "BMesh",
  303. ("Mesh Elements", '-'),
  304. "BMVert",
  305. "BMEdge",
  306. "BMFace",
  307. "BMLoop",
  308. ("Sequence Accessors", '-'),
  309. "BMElemSeq",
  310. "BMVertSeq",
  311. "BMEdgeSeq",
  312. "BMFaceSeq",
  313. "BMLoopSeq",
  314. "BMIter",
  315. ("Selection History", '-'),
  316. "BMEditSelSeq",
  317. "BMEditSelIter",
  318. ("Custom-Data Layer Access", '-'),
  319. "BMLayerAccessVert",
  320. "BMLayerAccessEdge",
  321. "BMLayerAccessFace",
  322. "BMLayerAccessLoop",
  323. "BMLayerCollection",
  324. "BMLayerItem",
  325. ("Custom-Data Layer Types", '-'),
  326. "BMLoopUV",
  327. "BMDeformVert"
  328. )
  329. }
  330. # --------------------configure compile time options----------------------------
  331. # -------------------------------BLENDER----------------------------------------
  332. blender_version_strings = [str(v) for v in bpy.app.version]
  333. is_release = bpy.app.version_cycle in {"rc", "release"}
  334. # converting bytes to strings, due to T30154
  335. BLENDER_REVISION = str(bpy.app.build_hash, 'utf_8')
  336. if is_release:
  337. # '2.62a'
  338. BLENDER_VERSION_DOTS = ".".join(blender_version_strings[:2]) + bpy.app.version_char
  339. else:
  340. # '2.62.1'
  341. BLENDER_VERSION_DOTS = ".".join(blender_version_strings)
  342. if BLENDER_REVISION != "Unknown":
  343. # '2.62a SHA1' (release) or '2.62.1 SHA1' (non-release)
  344. BLENDER_VERSION_HASH = BLENDER_REVISION
  345. else:
  346. # Fallback: Should not be used
  347. BLENDER_VERSION_HASH = "Hash Unknown"
  348. if is_release:
  349. # '2_62a_release'
  350. BLENDER_VERSION_PATH = "%s%s_release" % ("_".join(blender_version_strings[:2]), bpy.app.version_char)
  351. else:
  352. # '2_62_1'
  353. BLENDER_VERSION_PATH = "_".join(blender_version_strings)
  354. # --------------------------DOWNLOADABLE FILES----------------------------------
  355. REFERENCE_NAME = "blender_python_reference_%s" % BLENDER_VERSION_PATH
  356. REFERENCE_PATH = os.path.join(ARGS.output_dir, REFERENCE_NAME)
  357. BLENDER_PDF_FILENAME = "%s.pdf" % REFERENCE_NAME
  358. BLENDER_ZIP_FILENAME = "%s.zip" % REFERENCE_NAME
  359. # -------------------------------SPHINX-----------------------------------------
  360. SPHINX_IN = os.path.join(ARGS.output_dir, "sphinx-in")
  361. SPHINX_IN_TMP = SPHINX_IN + "-tmp"
  362. SPHINX_OUT = os.path.join(ARGS.output_dir, "sphinx-out")
  363. # html build
  364. if ARGS.sphinx_build:
  365. SPHINX_BUILD = ["sphinx-build", SPHINX_IN, SPHINX_OUT]
  366. if ARGS.log:
  367. SPHINX_BUILD_LOG = os.path.join(ARGS.output_dir, ".sphinx-build.log")
  368. SPHINX_BUILD = ["sphinx-build",
  369. "-w", SPHINX_BUILD_LOG,
  370. SPHINX_IN, SPHINX_OUT]
  371. # pdf build
  372. if ARGS.sphinx_build_pdf:
  373. SPHINX_OUT_PDF = os.path.join(ARGS.output_dir, "sphinx-out_pdf")
  374. SPHINX_BUILD_PDF = ["sphinx-build",
  375. "-b", "latex",
  376. SPHINX_IN, SPHINX_OUT_PDF]
  377. SPHINX_MAKE_PDF = ["make", "-C", SPHINX_OUT_PDF]
  378. SPHINX_MAKE_PDF_STDOUT = None
  379. if ARGS.log:
  380. SPHINX_BUILD_PDF_LOG = os.path.join(ARGS.output_dir, ".sphinx-build_pdf.log")
  381. SPHINX_BUILD_PDF = ["sphinx-build", "-b", "latex",
  382. "-w", SPHINX_BUILD_PDF_LOG,
  383. SPHINX_IN, SPHINX_OUT_PDF]
  384. sphinx_make_pdf_log = os.path.join(ARGS.output_dir, ".latex_make.log")
  385. SPHINX_MAKE_PDF_STDOUT = open(sphinx_make_pdf_log, "w", encoding="utf-8")
  386. # --------------------------------API DUMP--------------------------------------
  387. # lame, python won't give some access
  388. ClassMethodDescriptorType = type(dict.__dict__['fromkeys'])
  389. MethodDescriptorType = type(dict.get)
  390. GetSetDescriptorType = type(int.real)
  391. StaticMethodType = type(staticmethod(lambda: None))
  392. from types import (
  393. MemberDescriptorType,
  394. MethodType,
  395. FunctionType,
  396. )
  397. _BPY_STRUCT_FAKE = "bpy_struct"
  398. _BPY_PROP_COLLECTION_FAKE = "bpy_prop_collection"
  399. if _BPY_PROP_COLLECTION_FAKE:
  400. _BPY_PROP_COLLECTION_ID = ":class:`%s`" % _BPY_PROP_COLLECTION_FAKE
  401. else:
  402. _BPY_PROP_COLLECTION_ID = "collection"
  403. def escape_rst(text):
  404. """ Escape plain text which may contain characters used by RST.
  405. """
  406. return text.translate(escape_rst.trans)
  407. escape_rst.trans = str.maketrans({
  408. "`": "\\`",
  409. "|": "\\|",
  410. "*": "\\*",
  411. "\\": "\\\\",
  412. })
  413. def is_struct_seq(value):
  414. return isinstance(value, tuple) and type(tuple) != tuple and hasattr(value, "n_fields")
  415. def undocumented_message(module_name, type_name, identifier):
  416. return "Undocumented `contribute <https://developer.blender.org/T51061>`"
  417. def range_str(val):
  418. '''
  419. Converts values to strings for the range directive.
  420. (unused function it seems)
  421. '''
  422. if val < -10000000:
  423. return '-inf'
  424. elif val > 10000000:
  425. return 'inf'
  426. elif type(val) == float:
  427. return '%g' % val
  428. else:
  429. return str(val)
  430. def example_extract_docstring(filepath):
  431. file = open(filepath, "r", encoding="utf-8")
  432. line = file.readline()
  433. line_no = 0
  434. text = []
  435. if line.startswith('"""'): # assume nothing here
  436. line_no += 1
  437. else:
  438. file.close()
  439. return "", 0
  440. for line in file.readlines():
  441. line_no += 1
  442. if line.startswith('"""'):
  443. break
  444. else:
  445. text.append(line.rstrip())
  446. line_no += 1
  447. file.close()
  448. return "\n".join(text), line_no
  449. def title_string(text, heading_char, double=False):
  450. filler = len(text) * heading_char
  451. if double:
  452. return "%s\n%s\n%s\n\n" % (filler, text, filler)
  453. else:
  454. return "%s\n%s\n\n" % (text, filler)
  455. def write_example_ref(ident, fw, example_id, ext="py"):
  456. if example_id in EXAMPLE_SET:
  457. # extract the comment
  458. filepath = os.path.join("..", "examples", "%s.%s" % (example_id, ext))
  459. filepath_full = os.path.join(os.path.dirname(fw.__self__.name), filepath)
  460. text, line_no = example_extract_docstring(filepath_full)
  461. for line in text.split("\n"):
  462. fw("%s\n" % (ident + line).rstrip())
  463. fw("\n")
  464. fw("%s.. literalinclude:: %s\n" % (ident, filepath))
  465. if line_no > 0:
  466. fw("%s :lines: %d-\n" % (ident, line_no))
  467. fw("\n")
  468. EXAMPLE_SET_USED.add(example_id)
  469. else:
  470. if bpy.app.debug:
  471. BPY_LOGGER.debug("\tskipping example: " + example_id)
  472. # Support for numbered files bpy.types.Operator -> bpy.types.Operator.1.py
  473. i = 1
  474. while True:
  475. example_id_num = "%s.%d" % (example_id, i)
  476. if example_id_num in EXAMPLE_SET:
  477. write_example_ref(ident, fw, example_id_num, ext)
  478. i += 1
  479. else:
  480. break
  481. def write_indented_lines(ident, fn, text, strip=True):
  482. '''
  483. Apply same indentation to all lines in a multilines text.
  484. '''
  485. if text is None:
  486. return
  487. lines = text.split("\n")
  488. # strip empty lines from the start/end
  489. while lines and not lines[0].strip():
  490. del lines[0]
  491. while lines and not lines[-1].strip():
  492. del lines[-1]
  493. if strip:
  494. # set indentation to <indent>
  495. ident_strip = 1000
  496. for l in lines:
  497. if l.strip():
  498. ident_strip = min(ident_strip, len(l) - len(l.lstrip()))
  499. for l in lines:
  500. fn(ident + l[ident_strip:] + "\n")
  501. else:
  502. # add <indent> number of blanks to the current indentation
  503. for l in lines:
  504. fn(ident + l + "\n")
  505. def pymethod2sphinx(ident, fw, identifier, py_func):
  506. '''
  507. class method to sphinx
  508. '''
  509. arg_str = inspect.formatargspec(*inspect.getargspec(py_func))
  510. if arg_str.startswith("(self, "):
  511. arg_str = "(" + arg_str[7:]
  512. func_type = "method"
  513. elif arg_str.startswith("(cls, "):
  514. arg_str = "(" + arg_str[6:]
  515. func_type = "classmethod"
  516. else:
  517. func_type = "staticmethod"
  518. fw(ident + ".. %s:: %s%s\n\n" % (func_type, identifier, arg_str))
  519. if py_func.__doc__:
  520. write_indented_lines(ident + " ", fw, py_func.__doc__)
  521. fw("\n")
  522. def pyfunc2sphinx(ident, fw, module_name, type_name, identifier, py_func, is_class=True):
  523. '''
  524. function or class method to sphinx
  525. '''
  526. if type(py_func) == MethodType:
  527. return
  528. arg_str = str(inspect.signature(py_func))
  529. if not is_class:
  530. func_type = "function"
  531. # the rest are class methods
  532. elif arg_str.startswith("(self, ") or arg_str == "(self)":
  533. arg_str = "()" if (arg_str == "(self)") else ("(" + arg_str[7:])
  534. func_type = "method"
  535. elif arg_str.startswith("(cls, "):
  536. arg_str = "()" if (arg_str == "(cls)") else ("(" + arg_str[6:])
  537. func_type = "classmethod"
  538. else:
  539. func_type = "staticmethod"
  540. doc = py_func.__doc__
  541. if (not doc) or (not doc.startswith(".. %s:: " % func_type)):
  542. fw(ident + ".. %s:: %s%s\n\n" % (func_type, identifier, arg_str))
  543. ident_temp = ident + " "
  544. else:
  545. ident_temp = ident
  546. if doc:
  547. write_indented_lines(ident_temp, fw, doc)
  548. fw("\n")
  549. del doc, ident_temp
  550. if is_class:
  551. write_example_ref(ident + " ", fw, module_name + "." + type_name + "." + identifier)
  552. else:
  553. write_example_ref(ident + " ", fw, module_name + "." + identifier)
  554. def py_descr2sphinx(ident, fw, descr, module_name, type_name, identifier):
  555. if identifier.startswith("_"):
  556. return
  557. doc = descr.__doc__
  558. if not doc:
  559. doc = undocumented_message(module_name, type_name, identifier)
  560. if type(descr) == GetSetDescriptorType:
  561. fw(ident + ".. attribute:: %s\n\n" % identifier)
  562. write_indented_lines(ident + " ", fw, doc, False)
  563. fw("\n")
  564. elif type(descr) == MemberDescriptorType: # same as above but use 'data'
  565. fw(ident + ".. data:: %s\n\n" % identifier)
  566. write_indented_lines(ident + " ", fw, doc, False)
  567. fw("\n")
  568. elif type(descr) in {MethodDescriptorType, ClassMethodDescriptorType}:
  569. write_indented_lines(ident, fw, doc, False)
  570. fw("\n")
  571. else:
  572. raise TypeError("type was not GetSetDescriptorType, MethodDescriptorType or ClassMethodDescriptorType")
  573. write_example_ref(ident + " ", fw, module_name + "." + type_name + "." + identifier)
  574. fw("\n")
  575. def py_c_func2sphinx(ident, fw, module_name, type_name, identifier, py_func, is_class=True):
  576. '''
  577. c defined function to sphinx.
  578. '''
  579. # dump the docstring, assume its formatted correctly
  580. if py_func.__doc__:
  581. write_indented_lines(ident, fw, py_func.__doc__, False)
  582. fw("\n")
  583. else:
  584. fw(ident + ".. function:: %s()\n\n" % identifier)
  585. fw(ident + " " + undocumented_message(module_name, type_name, identifier))
  586. if is_class:
  587. write_example_ref(ident + " ", fw, module_name + "." + type_name + "." + identifier)
  588. else:
  589. write_example_ref(ident + " ", fw, module_name + "." + identifier)
  590. fw("\n")
  591. def pyprop2sphinx(ident, fw, identifier, py_prop):
  592. '''
  593. Python property to sphinx
  594. '''
  595. # readonly properties use "data" directive, variables use "attribute" directive
  596. if py_prop.fset is None:
  597. fw(ident + ".. data:: %s\n\n" % identifier)
  598. else:
  599. fw(ident + ".. attribute:: %s\n\n" % identifier)
  600. write_indented_lines(ident + " ", fw, py_prop.__doc__)
  601. if py_prop.fset is None:
  602. fw(ident + " (readonly)\n\n")
  603. else:
  604. fw("\n")
  605. def pymodule2sphinx(basepath, module_name, module, title):
  606. import types
  607. attribute_set = set()
  608. filepath = os.path.join(basepath, module_name + ".rst")
  609. module_all = getattr(module, "__all__", None)
  610. module_dir = sorted(dir(module))
  611. if module_all:
  612. module_dir = module_all
  613. # TODO - currently only used for classes
  614. # grouping support
  615. module_grouping = MODULE_GROUPING.get(module_name)
  616. def module_grouping_index(name):
  617. if module_grouping is not None:
  618. try:
  619. return module_grouping.index(name)
  620. except ValueError:
  621. pass
  622. return -1
  623. def module_grouping_heading(name):
  624. if module_grouping is not None:
  625. i = module_grouping_index(name) - 1
  626. if i >= 0 and type(module_grouping[i]) == tuple:
  627. return module_grouping[i]
  628. return None, None
  629. def module_grouping_sort_key(name):
  630. return module_grouping_index(name)
  631. # done grouping support
  632. file = open(filepath, "w", encoding="utf-8")
  633. fw = file.write
  634. fw(title_string("%s (%s)" % (title, module_name), "="))
  635. fw(".. module:: %s\n\n" % module_name)
  636. if module.__doc__:
  637. # Note, may contain sphinx syntax, don't mangle!
  638. fw(module.__doc__.strip())
  639. fw("\n\n")
  640. write_example_ref("", fw, module_name)
  641. # write submodules
  642. # we could also scan files but this ensures __all__ is used correctly
  643. if module_all is not None:
  644. submod_name = None
  645. submod = None
  646. submod_ls = []
  647. for submod_name in module_all:
  648. ns = {}
  649. exec_str = "from %s import %s as submod" % (module.__name__, submod_name)
  650. exec(exec_str, ns, ns)
  651. submod = ns["submod"]
  652. if type(submod) == types.ModuleType:
  653. submod_ls.append((submod_name, submod))
  654. del submod_name
  655. del submod
  656. if submod_ls:
  657. fw(".. toctree::\n")
  658. fw(" :maxdepth: 1\n\n")
  659. for submod_name, submod in submod_ls:
  660. submod_name_full = "%s.%s" % (module_name, submod_name)
  661. fw(" %s.rst\n\n" % submod_name_full)
  662. pymodule2sphinx(basepath, submod_name_full, submod, "%s submodule" % module_name)
  663. del submod_ls
  664. # done writing submodules!
  665. # write members of the module
  666. # only tested with PyStructs which are not exactly modules
  667. for key, descr in sorted(type(module).__dict__.items()):
  668. if key.startswith("__"):
  669. continue
  670. # naughty, we also add getset's into PyStructs, this is not typical py but also not incorrect.
  671. # type_name is only used for examples and messages
  672. # "<class 'bpy.app.handlers'>" --> bpy.app.handlers
  673. type_name = str(type(module)).strip("<>").split(" ", 1)[-1][1:-1]
  674. if type(descr) == types.GetSetDescriptorType:
  675. py_descr2sphinx("", fw, descr, module_name, type_name, key)
  676. attribute_set.add(key)
  677. descr_sorted = []
  678. for key, descr in sorted(type(module).__dict__.items()):
  679. if key.startswith("__"):
  680. continue
  681. if type(descr) == MemberDescriptorType:
  682. if descr.__doc__:
  683. value = getattr(module, key, None)
  684. value_type = type(value)
  685. descr_sorted.append((key, descr, value, type(value)))
  686. # sort by the valye type
  687. descr_sorted.sort(key=lambda descr_data: str(descr_data[3]))
  688. for key, descr, value, value_type in descr_sorted:
  689. # must be documented as a submodule
  690. if is_struct_seq(value):
  691. continue
  692. type_name = value_type.__name__
  693. py_descr2sphinx("", fw, descr, module_name, type_name, key)
  694. attribute_set.add(key)
  695. del key, descr, descr_sorted
  696. classes = []
  697. submodules = []
  698. # use this list so we can sort by type
  699. module_dir_value_type = []
  700. for attribute in module_dir:
  701. if attribute.startswith("_"):
  702. continue
  703. if attribute in attribute_set:
  704. continue
  705. if attribute.startswith("n_"): # annoying exception, needed for bpy.app
  706. continue
  707. # workaround for bpy.app documenting .index() and .count()
  708. if isinstance(module, tuple) and hasattr(tuple, attribute):
  709. continue
  710. value = getattr(module, attribute)
  711. module_dir_value_type.append((attribute, value, type(value)))
  712. # sort by str of each type
  713. # this way lists, functions etc are grouped.
  714. module_dir_value_type.sort(key=lambda triple: str(triple[2]))
  715. for attribute, value, value_type in module_dir_value_type:
  716. if value_type == FunctionType:
  717. pyfunc2sphinx("", fw, module_name, None, attribute, value, is_class=False)
  718. # both the same at the moment but to be future proof
  719. elif value_type in {types.BuiltinMethodType, types.BuiltinFunctionType}:
  720. # note: can't get args from these, so dump the string as is
  721. # this means any module used like this must have fully formatted docstrings.
  722. py_c_func2sphinx("", fw, module_name, None, attribute, value, is_class=False)
  723. elif value_type == type:
  724. classes.append((attribute, value))
  725. elif issubclass(value_type, types.ModuleType):
  726. submodules.append((attribute, value))
  727. elif issubclass(value_type, (bool, int, float, str, tuple)):
  728. # constant, not much fun we can do here except to list it.
  729. # TODO, figure out some way to document these!
  730. fw(".. data:: %s\n\n" % attribute)
  731. write_indented_lines(" ", fw, "constant value %s" % repr(value), False)
  732. fw("\n")
  733. else:
  734. BPY_LOGGER.debug("\tnot documenting %s.%s of %r type" % (module_name, attribute, value_type.__name__))
  735. continue
  736. attribute_set.add(attribute)
  737. # TODO, more types...
  738. del module_dir_value_type
  739. # TODO, bpy_extras does this already, mathutils not.
  740. '''
  741. if submodules:
  742. fw("\n"
  743. "**********\n"
  744. "Submodules\n"
  745. "**********\n"
  746. "\n"
  747. )
  748. for attribute, submod in submodules:
  749. fw("* :mod:`%s.%s`\n" % (module_name, attribute))
  750. fw("\n")
  751. '''
  752. if module_grouping is not None:
  753. classes.sort(key=lambda pair: module_grouping_sort_key(pair[0]))
  754. # write collected classes now
  755. for (type_name, value) in classes:
  756. if module_grouping is not None:
  757. heading, heading_char = module_grouping_heading(type_name)
  758. if heading:
  759. fw(title_string(heading, heading_char))
  760. # May need to be its own function
  761. if value.__doc__:
  762. if value.__doc__.startswith(".. class::"):
  763. fw(value.__doc__)
  764. else:
  765. fw(".. class:: %s\n\n" % type_name)
  766. write_indented_lines(" ", fw, value.__doc__, True)
  767. else:
  768. fw(".. class:: %s\n\n" % type_name)
  769. fw("\n")
  770. write_example_ref(" ", fw, module_name + "." + type_name)
  771. descr_items = [(key, descr) for key, descr in sorted(value.__dict__.items()) if not key.startswith("_")]
  772. for key, descr in descr_items:
  773. if type(descr) == ClassMethodDescriptorType:
  774. py_descr2sphinx(" ", fw, descr, module_name, type_name, key)
  775. # needed for pure Python classes
  776. for key, descr in descr_items:
  777. if type(descr) == FunctionType:
  778. pyfunc2sphinx(" ", fw, module_name, type_name, key, descr, is_class=True)
  779. for key, descr in descr_items:
  780. if type(descr) == MethodDescriptorType:
  781. py_descr2sphinx(" ", fw, descr, module_name, type_name, key)
  782. for key, descr in descr_items:
  783. if type(descr) == GetSetDescriptorType:
  784. py_descr2sphinx(" ", fw, descr, module_name, type_name, key)
  785. for key, descr in descr_items:
  786. if type(descr) == StaticMethodType:
  787. descr = getattr(value, key)
  788. write_indented_lines(" ", fw, descr.__doc__ or "Undocumented", False)
  789. fw("\n")
  790. fw("\n\n")
  791. file.close()
  792. # Changes in Blender will force errors here
  793. context_type_map = {
  794. # context_member: (RNA type, is_collection)
  795. "active_base": ("ObjectBase", False),
  796. "active_bone": ("EditBone", False),
  797. "active_gpencil_frame": ("GreasePencilLayer", True),
  798. "active_gpencil_layer": ("GPencilLayer", True),
  799. "active_node": ("Node", False),
  800. "active_object": ("Object", False),
  801. "active_operator": ("Operator", False),
  802. "active_pose_bone": ("PoseBone", False),
  803. "active_editable_fcurve": ("FCurve", False),
  804. "armature": ("Armature", False),
  805. "bone": ("Bone", False),
  806. "brush": ("Brush", False),
  807. "camera": ("Camera", False),
  808. "cloth": ("ClothModifier", False),
  809. "collection": ("LayerCollection", False),
  810. "collision": ("CollisionModifier", False),
  811. "curve": ("Curve", False),
  812. "dynamic_paint": ("DynamicPaintModifier", False),
  813. "edit_bone": ("EditBone", False),
  814. "edit_image": ("Image", False),
  815. "edit_mask": ("Mask", False),
  816. "edit_movieclip": ("MovieClip", False),
  817. "edit_object": ("Object", False),
  818. "edit_text": ("Text", False),
  819. "editable_bones": ("EditBone", True),
  820. "editable_gpencil_layers": ("GPencilLayer", True),
  821. "editable_gpencil_strokes": ("GPencilStroke", True),
  822. "editable_objects": ("Object", True),
  823. "editable_fcurves": ("FCurve", True),
  824. "fluid": ("FluidSimulationModifier", False),
  825. "gpencil": ("GreasePencil", False),
  826. "gpencil_data": ("GreasePencil", False),
  827. "gpencil_data_owner": ("ID", False),
  828. "image_paint_object": ("Object", False),
  829. "lattice": ("Lattice", False),
  830. "light": ("Light", False),
  831. "lightprobe": ("LightProbe", False),
  832. "line_style": ("FreestyleLineStyle", False),
  833. "material": ("Material", False),
  834. "material_slot": ("MaterialSlot", False),
  835. "mesh": ("Mesh", False),
  836. "meta_ball": ("MetaBall", False),
  837. "object": ("Object", False),
  838. "objects_in_mode": ("Object", True),
  839. "objects_in_mode_unique_data": ("Object", True),
  840. "particle_edit_object": ("Object", False),
  841. "particle_settings": ("ParticleSettings", False),
  842. "particle_system": ("ParticleSystem", False),
  843. "particle_system_editable": ("ParticleSystem", False),
  844. "pose_bone": ("PoseBone", False),
  845. "pose_object": ("Object", False),
  846. "scene": ("Scene", False),
  847. "sculpt_object": ("Object", False),
  848. "selectable_objects": ("Object", True),
  849. "selected_bones": ("EditBone", True),
  850. "selected_editable_bones": ("EditBone", True),
  851. "selected_editable_fcurves": ("FCurve", True),
  852. "selected_editable_objects": ("Object", True),
  853. "selected_editable_sequences": ("Sequence", True),
  854. "selected_nodes": ("Node", True),
  855. "selected_objects": ("Object", True),
  856. "selected_pose_bones": ("PoseBone", True),
  857. "selected_pose_bones_from_active_object": ("PoseBone", True),
  858. "selected_sequences": ("Sequence", True),
  859. "selected_visible_fcurves": ("FCurve", True),
  860. "sequences": ("Sequence", True),
  861. "smoke": ("SmokeModifier", False),
  862. "soft_body": ("SoftBodyModifier", False),
  863. "speaker": ("Speaker", False),
  864. "texture": ("Texture", False),
  865. "texture_slot": ("MaterialTextureSlot", False),
  866. "texture_user": ("ID", False),
  867. "texture_user_property": ("Property", False),
  868. "vertex_paint_object": ("Object", False),
  869. "view_layer": ("ViewLayer", False),
  870. "visible_bones": ("EditBone", True),
  871. "visible_gpencil_layers": ("GPencilLayer", True),
  872. "visible_objects": ("Object", True),
  873. "visible_pose_bones": ("PoseBone", True),
  874. "visible_fcurves": ("FCurve", True),
  875. "weight_paint_object": ("Object", False),
  876. "world": ("World", False),
  877. }
  878. def pycontext2sphinx(basepath):
  879. # Only use once. very irregular
  880. filepath = os.path.join(basepath, "bpy.context.rst")
  881. file = open(filepath, "w", encoding="utf-8")
  882. fw = file.write
  883. fw(title_string("Context Access (bpy.context)", "="))
  884. fw(".. module:: bpy.context\n")
  885. fw("\n")
  886. fw("The context members available depend on the area of Blender which is currently being accessed.\n")
  887. fw("\n")
  888. fw("Note that all context values are readonly,\n")
  889. fw("but may be modified through the data api or by running operators\n\n")
  890. def write_contex_cls():
  891. fw(title_string("Global Context", "-"))
  892. fw("These properties are available in any contexts.\n\n")
  893. # very silly. could make these global and only access once.
  894. # structs, funcs, ops, props = rna_info.BuildRNAInfo()
  895. structs, funcs, ops, props = rna_info_BuildRNAInfo_cache()
  896. struct = structs[("", "Context")]
  897. struct_blacklist = RNA_BLACKLIST.get(struct.identifier, ())
  898. del structs, funcs, ops, props
  899. sorted_struct_properties = struct.properties[:]
  900. sorted_struct_properties.sort(key=lambda prop: prop.identifier)
  901. # First write RNA
  902. for prop in sorted_struct_properties:
  903. # support blacklisting props
  904. if prop.identifier in struct_blacklist:
  905. continue
  906. type_descr = prop.get_type_description(
  907. class_fmt=":class:`bpy.types.%s`", collection_id=_BPY_PROP_COLLECTION_ID)
  908. fw(".. data:: %s\n\n" % prop.identifier)
  909. if prop.description:
  910. fw(" %s\n\n" % prop.description)
  911. # special exception, can't use generic code here for enums
  912. if prop.type == "enum":
  913. enum_text = pyrna_enum2sphinx(prop)
  914. if enum_text:
  915. write_indented_lines(" ", fw, enum_text)
  916. fw("\n")
  917. del enum_text
  918. # end enum exception
  919. fw(" :type: %s\n\n" % type_descr)
  920. write_contex_cls()
  921. del write_contex_cls
  922. # end
  923. # nasty, get strings directly from Blender because there is no other way to get it
  924. import ctypes
  925. context_strings = (
  926. "screen_context_dir",
  927. "view3d_context_dir",
  928. "buttons_context_dir",
  929. "image_context_dir",
  930. "node_context_dir",
  931. "text_context_dir",
  932. "clip_context_dir",
  933. "sequencer_context_dir",
  934. )
  935. unique = set()
  936. blend_cdll = ctypes.CDLL("")
  937. for ctx_str in context_strings:
  938. subsection = "%s Context" % ctx_str.split("_")[0].title()
  939. fw("\n%s\n%s\n\n" % (subsection, (len(subsection) * '-')))
  940. attr = ctypes.addressof(getattr(blend_cdll, ctx_str))
  941. c_char_p_p = ctypes.POINTER(ctypes.c_char_p)
  942. char_array = c_char_p_p.from_address(attr)
  943. i = 0
  944. while char_array[i] is not None:
  945. member = ctypes.string_at(char_array[i]).decode(encoding="ascii")
  946. fw(".. data:: %s\n\n" % member)
  947. member_type, is_seq = context_type_map[member]
  948. fw(" :type: %s :class:`bpy.types.%s`\n\n" % ("sequence of " if is_seq else "", member_type))
  949. unique.add(member)
  950. i += 1
  951. # generate typemap...
  952. # for member in sorted(unique):
  953. # print(' "%s": ("", False),' % member)
  954. if len(context_type_map) > len(unique):
  955. raise Exception(
  956. "Some types are not used: %s" %
  957. str([member for member in context_type_map if member not in unique]))
  958. else:
  959. pass # will have raised an error above
  960. file.close()
  961. def pyrna_enum2sphinx(prop, use_empty_descriptions=False):
  962. """ write a bullet point list of enum + descriptions
  963. """
  964. if use_empty_descriptions:
  965. ok = True
  966. else:
  967. ok = False
  968. for identifier, name, description in prop.enum_items:
  969. if description:
  970. ok = True
  971. break
  972. if ok:
  973. return "".join(["* ``%s`` %s.\n" %
  974. (identifier,
  975. ", ".join(escape_rst(val) for val in (name, description) if val),
  976. )
  977. for identifier, name, description in prop.enum_items
  978. ])
  979. else:
  980. return ""
  981. def pyrna2sphinx(basepath):
  982. """ bpy.types and bpy.ops
  983. """
  984. # structs, funcs, ops, props = rna_info.BuildRNAInfo()
  985. structs, funcs, ops, props = rna_info_BuildRNAInfo_cache()
  986. if FILTER_BPY_TYPES is not None:
  987. structs = {k: v for k, v in structs.items() if k[1] in FILTER_BPY_TYPES}
  988. if FILTER_BPY_OPS is not None:
  989. ops = {k: v for k, v in ops.items() if v.module_name in FILTER_BPY_OPS}
  990. def write_param(ident, fw, prop, is_return=False):
  991. if is_return:
  992. id_name = "return"
  993. id_type = "rtype"
  994. kwargs = {"as_ret": True}
  995. identifier = ""
  996. else:
  997. id_name = "arg"
  998. id_type = "type"
  999. kwargs = {"as_arg": True}
  1000. identifier = " %s" % prop.identifier
  1001. kwargs["class_fmt"] = ":class:`%s`"
  1002. kwargs["collection_id"] = _BPY_PROP_COLLECTION_ID
  1003. type_descr = prop.get_type_description(**kwargs)
  1004. enum_text = pyrna_enum2sphinx(prop)
  1005. if prop.name or prop.description or enum_text:
  1006. fw(ident + ":%s%s:\n\n" % (id_name, identifier))
  1007. if prop.name or prop.description:
  1008. fw(ident + " " + ", ".join(val for val in (prop.name, prop.description) if val) + "\n\n")
  1009. # special exception, can't use generic code here for enums
  1010. if enum_text:
  1011. write_indented_lines(ident + " ", fw, enum_text)
  1012. fw("\n")
  1013. del enum_text
  1014. # end enum exception
  1015. fw(ident + ":%s%s: %s\n" % (id_type, identifier, type_descr))
  1016. def write_struct(struct):
  1017. # if not struct.identifier.startswith("Sc") and not struct.identifier.startswith("I"):
  1018. # return
  1019. # if not struct.identifier == "Object":
  1020. # return
  1021. filepath = os.path.join(basepath, "bpy.types.%s.rst" % struct.identifier)
  1022. file = open(filepath, "w", encoding="utf-8")
  1023. fw = file.write
  1024. base_id = getattr(struct.base, "identifier", "")
  1025. struct_id = struct.identifier
  1026. if _BPY_STRUCT_FAKE:
  1027. if not base_id:
  1028. base_id = _BPY_STRUCT_FAKE
  1029. if base_id:
  1030. title = "%s(%s)" % (struct_id, base_id)
  1031. else:
  1032. title = struct_id
  1033. fw(title_string(title, "="))
  1034. fw(".. module:: bpy.types\n\n")
  1035. # docs first?, ok
  1036. write_example_ref("", fw, "bpy.types.%s" % struct_id)
  1037. base_ids = [base.identifier for base in struct.get_bases()]
  1038. if _BPY_STRUCT_FAKE:
  1039. base_ids.append(_BPY_STRUCT_FAKE)
  1040. base_ids.reverse()
  1041. if base_ids:
  1042. if len(base_ids) > 1:
  1043. fw("base classes --- ")
  1044. else:
  1045. fw("base class --- ")
  1046. fw(", ".join((":class:`%s`" % base_id) for base_id in base_ids))
  1047. fw("\n\n")
  1048. subclass_ids = [
  1049. s.identifier for s in structs.values()
  1050. if s.base is struct
  1051. if not rna_info.rna_id_ignore(s.identifier)
  1052. ]
  1053. subclass_ids.sort()
  1054. if subclass_ids:
  1055. fw("subclasses --- \n" + ", ".join((":class:`%s`" % s) for s in subclass_ids) + "\n\n")
  1056. base_id = getattr(struct.base, "identifier", "")
  1057. if _BPY_STRUCT_FAKE:
  1058. if not base_id:
  1059. base_id = _BPY_STRUCT_FAKE
  1060. if base_id:
  1061. fw(".. class:: %s(%s)\n\n" % (struct_id, base_id))
  1062. else:
  1063. fw(".. class:: %s\n\n" % struct_id)
  1064. fw(" %s\n\n" % struct.description)
  1065. # properties sorted in alphabetical order
  1066. sorted_struct_properties = struct.properties[:]
  1067. sorted_struct_properties.sort(key=lambda prop: prop.identifier)
  1068. # support blacklisting props
  1069. struct_blacklist = RNA_BLACKLIST.get(struct_id, ())
  1070. for prop in sorted_struct_properties:
  1071. # support blacklisting props
  1072. if prop.identifier in struct_blacklist:
  1073. continue
  1074. type_descr = prop.get_type_description(class_fmt=":class:`%s`", collection_id=_BPY_PROP_COLLECTION_ID)
  1075. # readonly properties use "data" directive, variables properties use "attribute" directive
  1076. if 'readonly' in type_descr:
  1077. fw(" .. data:: %s\n\n" % prop.identifier)
  1078. else:
  1079. fw(" .. attribute:: %s\n\n" % prop.identifier)
  1080. if prop.description:
  1081. fw(" %s\n\n" % prop.description)
  1082. # special exception, can't use generic code here for enums
  1083. if prop.type == "enum":
  1084. enum_text = pyrna_enum2sphinx(prop)
  1085. if enum_text:
  1086. write_indented_lines(" ", fw, enum_text)
  1087. fw("\n")
  1088. del enum_text
  1089. # end enum exception
  1090. fw(" :type: %s\n\n" % type_descr)
  1091. # Python attributes
  1092. py_properties = struct.get_py_properties()
  1093. py_prop = None
  1094. for identifier, py_prop in py_properties:
  1095. pyprop2sphinx(" ", fw, identifier, py_prop)
  1096. del py_properties, py_prop
  1097. for func in struct.functions:
  1098. args_str = ", ".join(prop.get_arg_default(force=False) for prop in func.args)
  1099. fw(" .. %s:: %s(%s)\n\n" %
  1100. ("classmethod" if func.is_classmethod else "method", func.identifier, args_str))
  1101. fw(" %s\n\n" % func.description)
  1102. for prop in func.args:
  1103. write_param(" ", fw, prop)
  1104. if len(func.return_values) == 1:
  1105. write_param(" ", fw, func.return_values[0], is_return=True)
  1106. elif func.return_values: # multiple return values
  1107. fw(" :return (%s):\n" % ", ".join(prop.identifier for prop in func.return_values))
  1108. for prop in func.return_values:
  1109. # TODO, pyrna_enum2sphinx for multiple return values... actually don't
  1110. # think we even use this but still!!!
  1111. type_descr = prop.get_type_description(
  1112. as_ret=True, class_fmt=":class:`%s`", collection_id=_BPY_PROP_COLLECTION_ID)
  1113. descr = prop.description
  1114. if not descr:
  1115. descr = prop.name
  1116. # In rare cases descr may be empty
  1117. fw(" `%s`, %s\n\n" %
  1118. (prop.identifier,
  1119. ", ".join((val for val in (descr, type_descr) if val))))
  1120. write_example_ref(" ", fw, "bpy.types." + struct_id + "." + func.identifier)
  1121. fw("\n")
  1122. # Python methods
  1123. py_funcs = struct.get_py_functions()
  1124. py_func = None
  1125. for identifier, py_func in py_funcs:
  1126. pyfunc2sphinx(" ", fw, "bpy.types", struct_id, identifier, py_func, is_class=True)
  1127. del py_funcs, py_func
  1128. py_funcs = struct.get_py_c_functions()
  1129. py_func = None
  1130. for identifier, py_func in py_funcs:
  1131. py_c_func2sphinx(" ", fw, "bpy.types", struct_id, identifier, py_func, is_class=True)
  1132. lines = []
  1133. if struct.base or _BPY_STRUCT_FAKE:
  1134. bases = list(reversed(struct.get_bases()))
  1135. # props
  1136. del lines[:]
  1137. if _BPY_STRUCT_FAKE:
  1138. descr_items = [
  1139. (key, descr) for key, descr in sorted(bpy.types.Struct.__bases__[0].__dict__.items())
  1140. if not key.startswith("__")
  1141. ]
  1142. if _BPY_STRUCT_FAKE:
  1143. for key, descr in descr_items:
  1144. if type(descr) == GetSetDescriptorType:
  1145. lines.append(" * :class:`%s.%s`\n" % (_BPY_STRUCT_FAKE, key))
  1146. for base in bases:
  1147. for prop in base.properties:
  1148. lines.append(" * :class:`%s.%s`\n" % (base.identifier, prop.identifier))
  1149. for identifier, py_prop in base.get_py_properties():
  1150. lines.append(" * :class:`%s.%s`\n" % (base.identifier, identifier))
  1151. for identifier, py_prop in base.get_py_properties():
  1152. lines.append(" * :class:`%s.%s`\n" % (base.identifier, identifier))
  1153. if lines:
  1154. fw(".. rubric:: Inherited Properties\n\n")
  1155. fw(".. hlist::\n")
  1156. fw(" :columns: 2\n\n")
  1157. for line in lines:
  1158. fw(line)
  1159. fw("\n")
  1160. # funcs
  1161. del lines[:]
  1162. if _BPY_STRUCT_FAKE:
  1163. for key, descr in descr_items:
  1164. if type(descr) == MethodDescriptorType:
  1165. lines.append(" * :class:`%s.%s`\n" % (_BPY_STRUCT_FAKE, key))
  1166. for base in bases:
  1167. for func in base.functions:
  1168. lines.append(" * :class:`%s.%s`\n" % (base.identifier, func.identifier))
  1169. for identifier, py_func in base.get_py_functions():
  1170. lines.append(" * :class:`%s.%s`\n" % (base.identifier, identifier))
  1171. if lines:
  1172. fw(".. rubric:: Inherited Functions\n\n")
  1173. fw(".. hlist::\n")
  1174. fw(" :columns: 2\n\n")
  1175. for line in lines:
  1176. fw(line)
  1177. fw("\n")
  1178. del lines[:]
  1179. if struct.references:
  1180. # use this otherwise it gets in the index for a normal heading.
  1181. fw(".. rubric:: References\n\n")
  1182. fw(".. hlist::\n")
  1183. fw(" :columns: 2\n\n")
  1184. # context does its own thing
  1185. # "active_base": ("ObjectBase", False),
  1186. for ref_attr, (ref_type, ref_is_seq) in sorted(context_type_map.items()):
  1187. if ref_type == struct_id:
  1188. fw(" * :mod:`bpy.context.%s`\n" % ref_attr)
  1189. del ref_attr, ref_type, ref_is_seq
  1190. for ref in struct.references:
  1191. ref_split = ref.split(".")
  1192. if len(ref_split) > 2:
  1193. ref = ref_split[-2] + "." + ref_split[-1]
  1194. fw(" * :class:`%s`\n" % ref)
  1195. fw("\n")
  1196. # docs last?, disable for now
  1197. # write_example_ref("", fw, "bpy.types.%s" % struct_id)
  1198. file.close()
  1199. if "bpy.types" not in EXCLUDE_MODULES:
  1200. for struct in structs.values():
  1201. # TODO, rna_info should filter these out!
  1202. if "_OT_" in struct.identifier:
  1203. continue
  1204. write_struct(struct)
  1205. def fake_bpy_type(class_value, class_name, descr_str, use_subclasses=True):
  1206. filepath = os.path.join(basepath, "bpy.types.%s.rst" % class_name)
  1207. file = open(filepath, "w", encoding="utf-8")
  1208. fw = file.write
  1209. fw(title_string(class_name, "="))
  1210. fw(".. module:: bpy.types\n")
  1211. fw("\n")
  1212. if use_subclasses:
  1213. subclass_ids = [
  1214. s.identifier for s in structs.values()
  1215. if s.base is None
  1216. if not rna_info.rna_id_ignore(s.identifier)
  1217. ]
  1218. if subclass_ids:
  1219. fw("subclasses --- \n" + ", ".join((":class:`%s`" % s) for s in sorted(subclass_ids)) + "\n\n")
  1220. fw(".. class:: %s\n\n" % class_name)
  1221. fw(" %s\n\n" % descr_str)
  1222. fw(" .. note::\n\n")
  1223. fw(" Note that bpy.types.%s is not actually available from within Blender,\n"
  1224. " it only exists for the purpose of documentation.\n\n" % class_name)
  1225. descr_items = [
  1226. (key, descr) for key, descr in sorted(class_value.__dict__.items())
  1227. if not key.startswith("__")
  1228. ]
  1229. for key, descr in descr_items:
  1230. # GetSetDescriptorType, GetSetDescriptorType's are not documented yet
  1231. if type(descr) == MethodDescriptorType:
  1232. py_descr2sphinx(" ", fw, descr, "bpy.types", class_name, key)
  1233. for key, descr in descr_items:
  1234. if type(descr) == GetSetDescriptorType:
  1235. py_descr2sphinx(" ", fw, descr, "bpy.types", class_name, key)
  1236. file.close()
  1237. # write fake classes
  1238. if _BPY_STRUCT_FAKE:
  1239. class_value = bpy.types.Struct.__bases__[0]
  1240. fake_bpy_type(
  1241. class_value, _BPY_STRUCT_FAKE,
  1242. "built-in base class for all classes in bpy.types.", use_subclasses=True)
  1243. if _BPY_PROP_COLLECTION_FAKE:
  1244. class_value = bpy.data.objects.__class__
  1245. fake_bpy_type(
  1246. class_value, _BPY_PROP_COLLECTION_FAKE,
  1247. "built-in class used for all collections.", use_subclasses=False)
  1248. # operators
  1249. def write_ops():
  1250. API_BASEURL = "https://developer.blender.org/diffusion/B/browse/master/release/scripts"
  1251. API_BASEURL_ADDON = "https://developer.blender.org/diffusion/BA"
  1252. API_BASEURL_ADDON_CONTRIB = "https://developer.blender.org/diffusion/BAC"
  1253. op_modules = {}
  1254. for op in ops.values():
  1255. op_modules.setdefault(op.module_name, []).append(op)
  1256. del op
  1257. for op_module_name, ops_mod in op_modules.items():
  1258. filepath = os.path.join(basepath, "bpy.ops.%s.rst" % op_module_name)
  1259. file = open(filepath, "w", encoding="utf-8")
  1260. fw = file.write
  1261. title = "%s Operators" % op_module_name.replace("_", " ").title()
  1262. fw(title_string(title, "="))
  1263. fw(".. module:: bpy.ops.%s\n\n" % op_module_name)
  1264. ops_mod.sort(key=lambda op: op.func_name)
  1265. for op in ops_mod:
  1266. args_str = ", ".join(prop.get_arg_default(force=True) for prop in op.args)
  1267. fw(".. function:: %s(%s)\n\n" % (op.func_name, args_str))
  1268. # if the description isn't valid, we output the standard warning
  1269. # with a link to the wiki so that people can help
  1270. if not op.description or op.description == "(undocumented operator)":
  1271. operator_description = undocumented_message('bpy.ops', op.module_name, op.func_name)
  1272. else:
  1273. operator_description = op.description
  1274. fw(" %s\n\n" % operator_description)
  1275. for prop in op.args:
  1276. write_param(" ", fw, prop)
  1277. if op.args:
  1278. fw("\n")
  1279. location = op.get_location()
  1280. if location != (None, None):
  1281. if location[0].startswith("addons_contrib" + os.sep):
  1282. url_base = API_BASEURL_ADDON_CONTRIB
  1283. elif location[0].startswith("addons" + os.sep):
  1284. url_base = API_BASEURL_ADDON
  1285. else:
  1286. url_base = API_BASEURL
  1287. fw(" :file: `%s\\:%d <%s/%s$%d>`_\n\n" %
  1288. (location[0], location[1], url_base, location[0], location[1]))
  1289. file.close()
  1290. if "bpy.ops" not in EXCLUDE_MODULES:
  1291. write_ops()
  1292. def write_sphinx_conf_py(basepath):
  1293. '''
  1294. Write sphinx's conf.py
  1295. '''
  1296. filepath = os.path.join(basepath, "conf.py")
  1297. file = open(filepath, "w", encoding="utf-8")
  1298. fw = file.write
  1299. fw("import sys, os\n\n")
  1300. fw("extensions = ['sphinx.ext.intersphinx']\n\n")
  1301. fw("intersphinx_mapping = {'blender_manual': ('https://docs.blender.org/manual/en/dev/', None)}\n\n")
  1302. fw("project = 'Blender %s Python API'\n" % BLENDER_VERSION_DOTS)
  1303. fw("master_doc = 'index'\n")
  1304. fw("copyright = u'Blender Foundation'\n")
  1305. fw("version = '%s'\n" % BLENDER_VERSION_HASH)
  1306. fw("release = '%s'\n" % BLENDER_VERSION_HASH)
  1307. # Quiet file not in table-of-contents warnings.
  1308. fw("exclude_patterns = [\n")
  1309. fw(" 'include__bmesh.rst',\n")
  1310. fw("]\n\n")
  1311. fw("html_title = 'Blender Python API'\n")
  1312. fw("html_theme = 'sphinx_rtd_theme'\n")
  1313. fw("html_theme_options = {\n")
  1314. fw(" 'canonical_url': 'https://docs.blender.org/api/current/',\n")
  1315. # fw(" 'analytics_id': '',\n")
  1316. # fw(" 'collapse_navigation': True,\n")
  1317. fw(" 'sticky_navigation': False,\n")
  1318. fw(" 'navigation_depth': 1,\n")
  1319. # fw(" 'includehidden': True,\n")
  1320. # fw(" 'titles_only': False\n")
  1321. fw(" }\n\n")
  1322. # not helpful since the source is generated, adds to upload size.
  1323. fw("html_copy_source = False\n")
  1324. fw("html_show_sphinx = False\n")
  1325. fw("html_use_opensearch = 'https://docs.blender.org/api/current'\n")
  1326. fw("html_split_index = True\n")
  1327. fw("html_static_path = ['static']\n")
  1328. fw("html_extra_path = ['static/favicon.ico', 'static/blender_logo.svg']\n")
  1329. fw("html_favicon = 'static/favicon.ico'\n")
  1330. fw("html_logo = 'static/blender_logo.svg'\n")
  1331. fw("html_last_updated_fmt = '%m/%d/%Y'\n\n")
  1332. # needed for latex, pdf gen
  1333. fw("latex_elements = {\n")
  1334. fw(" 'papersize': 'a4paper',\n")
  1335. fw("}\n\n")
  1336. fw("latex_documents = [ ('contents', 'contents.tex', 'Blender Index', 'Blender Foundation', 'manual'), ]\n")
  1337. # Workaround for useless links leading to compile errors
  1338. # See https://github.com/sphinx-doc/sphinx/issues/3866
  1339. fw(r"""
  1340. from sphinx.domains.python import PythonDomain
  1341. class PatchedPythonDomain(PythonDomain):
  1342. def resolve_xref(self, env, fromdocname, builder, typ, target, node, contnode):
  1343. if 'refspecific' in node:
  1344. del node['refspecific']
  1345. return super(PatchedPythonDomain, self).resolve_xref(
  1346. env, fromdocname, builder, typ, target, node, contnode)
  1347. """)
  1348. # end workaround
  1349. fw("def setup(app):\n")
  1350. fw(" app.add_stylesheet('css/theme_overrides.css')\n")
  1351. fw(" app.override_domain(PatchedPythonDomain)\n\n")
  1352. file.close()
  1353. def execfile(filepath):
  1354. global_namespace = {"__file__": filepath, "__name__": "__main__"}
  1355. file_handle = open(filepath)
  1356. exec(compile(file_handle.read(), filepath, 'exec'), global_namespace)
  1357. file_handle.close()
  1358. def write_rst_contents(basepath):
  1359. '''
  1360. Write the rst file of the main page, needed for sphinx (index.html)
  1361. '''
  1362. filepath = os.path.join(basepath, "index.rst")
  1363. file = open(filepath, "w", encoding="utf-8")
  1364. fw = file.write
  1365. fw(title_string("Blender %s Python API Documentation" % BLENDER_VERSION_DOTS, "%", double=True))
  1366. fw("\n")
  1367. fw("Welcome to the Python API documentation for `Blender <https://www.blender.org>`__, ")
  1368. fw("the free and open source 3D creation suite.\n")
  1369. fw("\n")
  1370. # fw("`A PDF version of this document is also available <%s>`_\n" % BLENDER_PDF_FILENAME)
  1371. fw("This site can be used offline: `Download the full documentation (zipped HTML files) <%s>`__\n" %
  1372. BLENDER_ZIP_FILENAME)
  1373. fw("\n")
  1374. if not EXCLUDE_INFO_DOCS:
  1375. fw(".. toctree::\n")
  1376. fw(" :maxdepth: 1\n")
  1377. fw(" :caption: Documentation\n\n")
  1378. for info, info_desc in INFO_DOCS:
  1379. fw(" %s <%s>\n" % (info_desc, info))
  1380. fw("\n")
  1381. fw(".. toctree::\n")
  1382. fw(" :maxdepth: 1\n")
  1383. fw(" :caption: Application Modules\n\n")
  1384. app_modules = (
  1385. "bpy.context", # note: not actually a module
  1386. "bpy.data", # note: not actually a module
  1387. "bpy.ops",
  1388. "bpy.types",
  1389. # py modules
  1390. "bpy.utils",
  1391. "bpy.utils.previews",
  1392. "bpy.path",
  1393. "bpy.app",
  1394. # C modules
  1395. "bpy.props",
  1396. )
  1397. for mod in app_modules:
  1398. if mod not in EXCLUDE_MODULES:
  1399. fw(" %s\n" % mod)
  1400. fw("\n")
  1401. fw(".. toctree::\n")
  1402. fw(" :maxdepth: 1\n")
  1403. fw(" :caption: Standalone Modules\n\n")
  1404. standalone_modules = (
  1405. # submodules are added in parent page
  1406. "mathutils", "freestyle", "bgl", "blf", "gpu", "gpu_extras",
  1407. "aud", "bpy_extras", "idprop.types", "bmesh",
  1408. )
  1409. for mod in standalone_modules:
  1410. if mod not in EXCLUDE_MODULES:
  1411. fw(" %s\n" % mod)
  1412. fw("\n")
  1413. # special case, this 'bmesh.ops.rst' is extracted from C source
  1414. if "bmesh.ops" not in EXCLUDE_MODULES:
  1415. execfile(os.path.join(SCRIPT_DIR, "rst_from_bmesh_opdefines.py"))
  1416. file.close()
  1417. def write_rst_bpy(basepath):
  1418. '''
  1419. Write rst file of bpy module (disabled by default)
  1420. '''
  1421. if ARGS.bpy:
  1422. filepath = os.path.join(basepath, "bpy.rst")
  1423. file = open(filepath, "w", encoding="utf-8")
  1424. fw = file.write
  1425. fw("\n")
  1426. title = ":mod:`bpy` --- Blender Python Module"
  1427. fw(title_string(title, "="))
  1428. fw(".. module:: bpy.types\n\n")
  1429. file.close()
  1430. def write_rst_types_index(basepath):
  1431. '''
  1432. Write the rst file of bpy.types module (index)
  1433. '''
  1434. if "bpy.types" not in EXCLUDE_MODULES:
  1435. filepath = os.path.join(basepath, "bpy.types.rst")
  1436. file = open(filepath, "w", encoding="utf-8")
  1437. fw = file.write
  1438. fw(title_string("Types (bpy.types)", "="))
  1439. fw(".. toctree::\n")
  1440. fw(" :glob:\n\n")
  1441. fw(" bpy.types.*\n\n")
  1442. file.close()
  1443. def write_rst_ops_index(basepath):
  1444. '''
  1445. Write the rst file of bpy.ops module (index)
  1446. '''
  1447. if "bpy.ops" not in EXCLUDE_MODULES:
  1448. filepath = os.path.join(basepath, "bpy.ops.rst")
  1449. file = open(filepath, "w", encoding="utf-8")
  1450. fw = file.write
  1451. fw(title_string("Operators (bpy.ops)", "="))
  1452. write_example_ref("", fw, "bpy.ops")
  1453. fw(".. toctree::\n")
  1454. fw(" :glob:\n\n")
  1455. fw(" bpy.ops.*\n\n")
  1456. file.close()
  1457. def write_rst_data(basepath):
  1458. '''
  1459. Write the rst file of bpy.data module
  1460. '''
  1461. if "bpy.data" not in EXCLUDE_MODULES:
  1462. # not actually a module, only write this file so we
  1463. # can reference in the TOC
  1464. filepath = os.path.join(basepath, "bpy.data.rst")
  1465. file = open(filepath, "w", encoding="utf-8")
  1466. fw = file.write
  1467. fw(title_string("Data Access (bpy.data)", "="))
  1468. fw(".. module:: bpy\n")
  1469. fw("\n")
  1470. fw("This module is used for all Blender/Python access.\n")
  1471. fw("\n")
  1472. fw(".. data:: data\n")
  1473. fw("\n")
  1474. fw(" Access to Blender's internal data\n")
  1475. fw("\n")
  1476. fw(" :type: :class:`bpy.types.BlendData`\n")
  1477. fw("\n")
  1478. fw(".. literalinclude:: ../examples/bpy.data.py\n")
  1479. file.close()
  1480. EXAMPLE_SET_USED.add("bpy.data")
  1481. def write_rst_importable_modules(basepath):
  1482. '''
  1483. Write the rst files of importable modules
  1484. '''
  1485. importable_modules = {
  1486. # Python_modules
  1487. "bpy.path": "Path Utilities",
  1488. "bpy.utils": "Utilities",
  1489. "bpy_extras": "Extra Utilities",
  1490. "gpu_extras": "GPU Utilities",
  1491. # C_modules
  1492. "aud": "Audio System",
  1493. "blf": "Font Drawing",
  1494. "gpu": "GPU Shader Module",
  1495. "gpu.types": "GPU Types",
  1496. "gpu.matrix": "GPU Matrix",
  1497. "gpu.select": "GPU Select",
  1498. "gpu.shader": "GPU Shader",
  1499. "bmesh": "BMesh Module",
  1500. "bmesh.types": "BMesh Types",
  1501. "bmesh.utils": "BMesh Utilities",
  1502. "bmesh.geometry": "BMesh Geometry Utilities",
  1503. "bpy.app": "Application Data",
  1504. "bpy.app.handlers": "Application Handlers",
  1505. "bpy.app.translations": "Application Translations",
  1506. "bpy.app.icons": "Application Icons",
  1507. "bpy.app.timers": "Application Timers",
  1508. "bpy.props": "Property Definitions",
  1509. "idprop.types": "ID Property Access",
  1510. "mathutils": "Math Types & Utilities",
  1511. "mathutils.geometry": "Geometry Utilities",
  1512. "mathutils.bvhtree": "BVHTree Utilities",
  1513. "mathutils.kdtree": "KDTree Utilities",
  1514. "mathutils.interpolate": "Interpolation Utilities",
  1515. "mathutils.noise": "Noise Utilities",
  1516. "freestyle": "Freestyle Module",
  1517. "freestyle.types": "Freestyle Types",
  1518. "freestyle.predicates": "Freestyle Predicates",
  1519. "freestyle.functions": "Freestyle Functions",
  1520. "freestyle.chainingiterators": "Freestyle Chaining Iterators",
  1521. "freestyle.shaders": "Freestyle Shaders",
  1522. "freestyle.utils": "Freestyle Utilities",
  1523. }
  1524. for mod_name, mod_descr in importable_modules.items():
  1525. if mod_name not in EXCLUDE_MODULES:
  1526. module = __import__(mod_name,
  1527. fromlist=[mod_name.rsplit(".", 1)[-1]])
  1528. pymodule2sphinx(basepath, mod_name, module, mod_descr)
  1529. def copy_handwritten_rsts(basepath):
  1530. # info docs
  1531. if not EXCLUDE_INFO_DOCS:
  1532. for info, info_desc in INFO_DOCS:
  1533. shutil.copy2(os.path.join(RST_DIR, info), basepath)
  1534. # TODO put this docs in Blender's code and use import as per modules above
  1535. handwritten_modules = [
  1536. "bgl", # "Blender OpenGl wrapper"
  1537. "bmesh.ops", # generated by rst_from_bmesh_opdefines.py
  1538. # includes...
  1539. "include__bmesh",
  1540. ]
  1541. for mod_name in handwritten_modules:
  1542. if mod_name not in EXCLUDE_MODULES:
  1543. # copy2 keeps time/date stamps
  1544. shutil.copy2(os.path.join(RST_DIR, "%s.rst" % mod_name), basepath)
  1545. # changelog
  1546. shutil.copy2(os.path.join(RST_DIR, "change_log.rst"), basepath)
  1547. # copy images, could be smarter but just glob for now.
  1548. for f in os.listdir(RST_DIR):
  1549. if f.endswith(".png"):
  1550. shutil.copy2(os.path.join(RST_DIR, f), basepath)
  1551. def copy_handwritten_extra(basepath):
  1552. for f_src in EXTRA_SOURCE_FILES:
  1553. if os.sep != "/":
  1554. f_src = os.sep.join(f_src.split("/"))
  1555. f_dst = f_src.replace("..", "__")
  1556. f_src = os.path.join(RST_DIR, f_src)
  1557. f_dst = os.path.join(basepath, f_dst)
  1558. os.makedirs(os.path.dirname(f_dst), exist_ok=True)
  1559. shutil.copy2(f_src, f_dst)
  1560. def copy_theme_assets(basepath):
  1561. shutil.copytree(os.path.join(SCRIPT_DIR, "static"),
  1562. os.path.join(basepath, "static"),
  1563. copy_function=shutil.copy)
  1564. def rna2sphinx(basepath):
  1565. try:
  1566. os.mkdir(basepath)
  1567. except:
  1568. pass
  1569. # sphinx setup
  1570. write_sphinx_conf_py(basepath)
  1571. # main page
  1572. write_rst_contents(basepath)
  1573. # context
  1574. if "bpy.context" not in EXCLUDE_MODULES:
  1575. # one of a kind, context doc (uses ctypes to extract info!)
  1576. # doesn't work on mac and windows
  1577. if PLATFORM not in {"darwin", "windows"}:
  1578. pycontext2sphinx(basepath)
  1579. # internal modules
  1580. write_rst_bpy(basepath) # bpy, disabled by default
  1581. write_rst_types_index(basepath) # bpy.types
  1582. write_rst_ops_index(basepath) # bpy.ops
  1583. pyrna2sphinx(basepath) # bpy.types.* and bpy.ops.*
  1584. write_rst_data(basepath) # bpy.data
  1585. write_rst_importable_modules(basepath)
  1586. # copy the other rsts
  1587. copy_handwritten_rsts(basepath)
  1588. # copy source files referenced
  1589. copy_handwritten_extra(basepath)
  1590. # copy extra files needed for theme
  1591. copy_theme_assets(basepath)
  1592. def align_sphinx_in_to_sphinx_in_tmp(dir_src, dir_dst):
  1593. '''
  1594. Move changed files from SPHINX_IN_TMP to SPHINX_IN
  1595. '''
  1596. import filecmp
  1597. # possible the dir doesn't exist when running recursively
  1598. os.makedirs(dir_dst, exist_ok=True)
  1599. sphinx_dst_files = set(os.listdir(dir_dst))
  1600. sphinx_src_files = set(os.listdir(dir_src))
  1601. # remove deprecated files that have been removed
  1602. for f in sorted(sphinx_dst_files):
  1603. if f not in sphinx_src_files:
  1604. BPY_LOGGER.debug("\tdeprecated: %s" % f)
  1605. f_dst = os.path.join(dir_dst, f)
  1606. if os.path.isdir(f_dst):
  1607. shutil.rmtree(f_dst, True)
  1608. else:
  1609. os.remove(f_dst)
  1610. # freshen with new files.
  1611. for f in sorted(sphinx_src_files):
  1612. f_src = os.path.join(dir_src, f)
  1613. f_dst = os.path.join(dir_dst, f)
  1614. if os.path.isdir(f_src):
  1615. align_sphinx_in_to_sphinx_in_tmp(f_src, f_dst)
  1616. else:
  1617. do_copy = True
  1618. if f in sphinx_dst_files:
  1619. if filecmp.cmp(f_src, f_dst):
  1620. do_copy = False
  1621. if do_copy:
  1622. BPY_LOGGER.debug("\tupdating: %s" % f)
  1623. shutil.copy(f_src, f_dst)
  1624. def refactor_sphinx_log(sphinx_logfile):
  1625. refactored_log = []
  1626. with open(sphinx_logfile, "r", encoding="utf-8") as original_logfile:
  1627. lines = set(original_logfile.readlines())
  1628. for line in lines:
  1629. if 'warning' in line.lower() or 'error' in line.lower():
  1630. line = line.strip().split(None, 2)
  1631. if len(line) == 3:
  1632. location, kind, msg = line
  1633. location = os.path.relpath(location, start=SPHINX_IN)
  1634. refactored_log.append((kind, location, msg))
  1635. with open(sphinx_logfile, "w", encoding="utf-8") as refactored_logfile:
  1636. for log in sorted(refactored_log):
  1637. refactored_logfile.write("%-12s %s\n %s\n" % log)
  1638. def monkey_patch():
  1639. filepath = os.path.join(SCRIPT_DIR, "sphinx_doc_gen_monkeypatch.py")
  1640. global_namespace = {"__file__": filepath, "__name__": "__main__"}
  1641. file = open(filepath, 'rb')
  1642. exec(compile(file.read(), filepath, 'exec'), global_namespace)
  1643. file.close()
  1644. def main():
  1645. # first monkey patch to load in fake members
  1646. monkey_patch()
  1647. # eventually, create the dirs
  1648. for dir_path in [ARGS.output_dir, SPHINX_IN]:
  1649. if not os.path.exists(dir_path):
  1650. os.mkdir(dir_path)
  1651. # eventually, log in files
  1652. if ARGS.log:
  1653. bpy_logfile = os.path.join(ARGS.output_dir, ".bpy.log")
  1654. bpy_logfilehandler = logging.FileHandler(bpy_logfile, mode="w")
  1655. bpy_logfilehandler.setLevel(logging.DEBUG)
  1656. BPY_LOGGER.addHandler(bpy_logfilehandler)
  1657. # using a FileHandler seems to disable the stdout, so we add a StreamHandler
  1658. bpy_log_stdout_handler = logging.StreamHandler(stream=sys.stdout)
  1659. bpy_log_stdout_handler.setLevel(logging.DEBUG)
  1660. BPY_LOGGER.addHandler(bpy_log_stdout_handler)
  1661. # in case of out-of-source build, copy the needed dirs
  1662. if ARGS.output_dir != SCRIPT_DIR:
  1663. # examples dir
  1664. examples_dir_copy = os.path.join(ARGS.output_dir, "examples")
  1665. if os.path.exists(examples_dir_copy):
  1666. shutil.rmtree(examples_dir_copy, True)
  1667. shutil.copytree(EXAMPLES_DIR,
  1668. examples_dir_copy,
  1669. ignore=shutil.ignore_patterns(*(".svn",)),
  1670. copy_function=shutil.copy)
  1671. # dump the api in rst files
  1672. if os.path.exists(SPHINX_IN_TMP):
  1673. shutil.rmtree(SPHINX_IN_TMP, True)
  1674. rna2sphinx(SPHINX_IN_TMP)
  1675. if ARGS.full_rebuild:
  1676. # only for full updates
  1677. shutil.rmtree(SPHINX_IN, True)
  1678. shutil.copytree(SPHINX_IN_TMP,
  1679. SPHINX_IN,
  1680. copy_function=shutil.copy)
  1681. if ARGS.sphinx_build and os.path.exists(SPHINX_OUT):
  1682. shutil.rmtree(SPHINX_OUT, True)
  1683. if ARGS.sphinx_build_pdf and os.path.exists(SPHINX_OUT_PDF):
  1684. shutil.rmtree(SPHINX_OUT_PDF, True)
  1685. else:
  1686. # move changed files in SPHINX_IN
  1687. align_sphinx_in_to_sphinx_in_tmp(SPHINX_IN_TMP, SPHINX_IN)
  1688. # report which example files weren't used
  1689. EXAMPLE_SET_UNUSED = EXAMPLE_SET - EXAMPLE_SET_USED
  1690. if EXAMPLE_SET_UNUSED:
  1691. BPY_LOGGER.debug("\nUnused examples found in '%s'..." % EXAMPLES_DIR)
  1692. for f in sorted(EXAMPLE_SET_UNUSED):
  1693. BPY_LOGGER.debug(" %s.py" % f)
  1694. BPY_LOGGER.debug(" %d total\n" % len(EXAMPLE_SET_UNUSED))
  1695. # eventually, build the html docs
  1696. if ARGS.sphinx_build:
  1697. import subprocess
  1698. subprocess.call(SPHINX_BUILD)
  1699. # sphinx-build log cleanup+sort
  1700. if ARGS.log:
  1701. if os.stat(SPHINX_BUILD_LOG).st_size:
  1702. refactor_sphinx_log(SPHINX_BUILD_LOG)
  1703. # eventually, build the pdf docs
  1704. if ARGS.sphinx_build_pdf:
  1705. import subprocess
  1706. subprocess.call(SPHINX_BUILD_PDF)
  1707. subprocess.call(SPHINX_MAKE_PDF, stdout=SPHINX_MAKE_PDF_STDOUT)
  1708. # sphinx-build log cleanup+sort
  1709. if ARGS.log:
  1710. if os.stat(SPHINX_BUILD_PDF_LOG).st_size:
  1711. refactor_sphinx_log(SPHINX_BUILD_PDF_LOG)
  1712. # eventually, prepare the dir to be deployed online (REFERENCE_PATH)
  1713. if ARGS.pack_reference:
  1714. if ARGS.sphinx_build:
  1715. # delete REFERENCE_PATH
  1716. if os.path.exists(REFERENCE_PATH):
  1717. shutil.rmtree(REFERENCE_PATH, True)
  1718. # copy SPHINX_OUT to the REFERENCE_PATH
  1719. ignores = ('.doctrees', 'objects.inv', '.buildinfo')
  1720. shutil.copytree(SPHINX_OUT,
  1721. REFERENCE_PATH,
  1722. ignore=shutil.ignore_patterns(*ignores))
  1723. # zip REFERENCE_PATH
  1724. basename = os.path.join(ARGS.output_dir, REFERENCE_NAME)
  1725. tmp_path = shutil.make_archive(basename, 'zip',
  1726. root_dir=ARGS.output_dir,
  1727. base_dir=REFERENCE_NAME)
  1728. final_path = os.path.join(REFERENCE_PATH, BLENDER_ZIP_FILENAME)
  1729. os.rename(tmp_path, final_path)
  1730. if ARGS.sphinx_build_pdf:
  1731. # copy the pdf to REFERENCE_PATH
  1732. shutil.copy(os.path.join(SPHINX_OUT_PDF, "contents.pdf"),
  1733. os.path.join(REFERENCE_PATH, BLENDER_PDF_FILENAME))
  1734. sys.exit()
  1735. if __name__ == '__main__':
  1736. main()