pyqt5.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. #!/usr/bin/env python
  2. # encoding: utf-8
  3. # Federico Pellegrin, 2016-2018 (fedepell) adapted for Python
  4. """
  5. This tool helps with finding Python Qt5 tools and libraries,
  6. and provides translation from QT5 files to Python code.
  7. The following snippet illustrates the tool usage::
  8. def options(opt):
  9. opt.load('py pyqt5')
  10. def configure(conf):
  11. conf.load('py pyqt5')
  12. def build(bld):
  13. bld(
  14. features = 'py pyqt5',
  15. source = 'main.py textures.qrc aboutDialog.ui',
  16. )
  17. Here, the UI description and resource files will be processed
  18. to generate code.
  19. Usage
  20. =====
  21. Load the "pyqt5" tool.
  22. Add into the sources list also the qrc resources files or ui5
  23. definition files and they will be translated into python code
  24. with the system tools (PyQt5, pyside2, PyQt4 are searched in this
  25. order) and then compiled
  26. """
  27. try:
  28. from xml.sax import make_parser
  29. from xml.sax.handler import ContentHandler
  30. except ImportError:
  31. has_xml = False
  32. ContentHandler = object
  33. else:
  34. has_xml = True
  35. import os
  36. from waflib.Tools import python
  37. from waflib import Task, Options
  38. from waflib.TaskGen import feature, extension
  39. from waflib.Configure import conf
  40. from waflib import Logs
  41. EXT_RCC = ['.qrc']
  42. """
  43. File extension for the resource (.qrc) files
  44. """
  45. EXT_UI = ['.ui']
  46. """
  47. File extension for the user interface (.ui) files
  48. """
  49. class XMLHandler(ContentHandler):
  50. """
  51. Parses ``.qrc`` files
  52. """
  53. def __init__(self):
  54. self.buf = []
  55. self.files = []
  56. def startElement(self, name, attrs):
  57. if name == 'file':
  58. self.buf = []
  59. def endElement(self, name):
  60. if name == 'file':
  61. self.files.append(str(''.join(self.buf)))
  62. def characters(self, cars):
  63. self.buf.append(cars)
  64. @extension(*EXT_RCC)
  65. def create_pyrcc_task(self, node):
  66. "Creates rcc and py task for ``.qrc`` files"
  67. rcnode = node.change_ext('.py')
  68. self.create_task('pyrcc', node, rcnode)
  69. if getattr(self, 'install_from', None):
  70. self.install_from = self.install_from.get_bld()
  71. else:
  72. self.install_from = self.path.get_bld()
  73. self.install_path = getattr(self, 'install_path', '${PYTHONDIR}')
  74. self.process_py(rcnode)
  75. @extension(*EXT_UI)
  76. def create_pyuic_task(self, node):
  77. "Create uic tasks and py for user interface ``.ui`` definition files"
  78. uinode = node.change_ext('.py')
  79. self.create_task('ui5py', node, uinode)
  80. if getattr(self, 'install_from', None):
  81. self.install_from = self.install_from.get_bld()
  82. else:
  83. self.install_from = self.path.get_bld()
  84. self.install_path = getattr(self, 'install_path', '${PYTHONDIR}')
  85. self.process_py(uinode)
  86. @extension('.ts')
  87. def add_pylang(self, node):
  88. """Adds all the .ts file into ``self.lang``"""
  89. self.lang = self.to_list(getattr(self, 'lang', [])) + [node]
  90. @feature('pyqt5')
  91. def apply_pyqt5(self):
  92. """
  93. The additional parameters are:
  94. :param lang: list of translation files (\*.ts) to process
  95. :type lang: list of :py:class:`waflib.Node.Node` or string without the .ts extension
  96. :param langname: if given, transform the \*.ts files into a .qrc files to include in the binary file
  97. :type langname: :py:class:`waflib.Node.Node` or string without the .qrc extension
  98. """
  99. if getattr(self, 'lang', None):
  100. qmtasks = []
  101. for x in self.to_list(self.lang):
  102. if isinstance(x, str):
  103. x = self.path.find_resource(x + '.ts')
  104. qmtasks.append(self.create_task('ts2qm', x, x.change_ext('.qm')))
  105. if getattr(self, 'langname', None):
  106. qmnodes = [k.outputs[0] for k in qmtasks]
  107. rcnode = self.langname
  108. if isinstance(rcnode, str):
  109. rcnode = self.path.find_or_declare(rcnode + '.qrc')
  110. t = self.create_task('qm2rcc', qmnodes, rcnode)
  111. create_pyrcc_task(self, t.outputs[0])
  112. class pyrcc(Task.Task):
  113. """
  114. Processes ``.qrc`` files
  115. """
  116. color = 'BLUE'
  117. run_str = '${QT_PYRCC} ${SRC} -o ${TGT}'
  118. ext_out = ['.py']
  119. def rcname(self):
  120. return os.path.splitext(self.inputs[0].name)[0]
  121. def scan(self):
  122. """Parse the *.qrc* files"""
  123. if not has_xml:
  124. Logs.error('No xml.sax support was found, rcc dependencies will be incomplete!')
  125. return ([], [])
  126. parser = make_parser()
  127. curHandler = XMLHandler()
  128. parser.setContentHandler(curHandler)
  129. fi = open(self.inputs[0].abspath(), 'r')
  130. try:
  131. parser.parse(fi)
  132. finally:
  133. fi.close()
  134. nodes = []
  135. names = []
  136. root = self.inputs[0].parent
  137. for x in curHandler.files:
  138. nd = root.find_resource(x)
  139. if nd:
  140. nodes.append(nd)
  141. else:
  142. names.append(x)
  143. return (nodes, names)
  144. class ui5py(Task.Task):
  145. """
  146. Processes ``.ui`` files for python
  147. """
  148. color = 'BLUE'
  149. run_str = '${QT_PYUIC} ${SRC} -o ${TGT}'
  150. ext_out = ['.py']
  151. class ts2qm(Task.Task):
  152. """
  153. Generates ``.qm`` files from ``.ts`` files
  154. """
  155. color = 'BLUE'
  156. run_str = '${QT_LRELEASE} ${QT_LRELEASE_FLAGS} ${SRC} -qm ${TGT}'
  157. class qm2rcc(Task.Task):
  158. """
  159. Generates ``.qrc`` files from ``.qm`` files
  160. """
  161. color = 'BLUE'
  162. after = 'ts2qm'
  163. def run(self):
  164. """Create a qrc file including the inputs"""
  165. txt = '\n'.join(['<file>%s</file>' % k.path_from(self.outputs[0].parent) for k in self.inputs])
  166. code = '<!DOCTYPE RCC><RCC version="1.0">\n<qresource>\n%s\n</qresource>\n</RCC>' % txt
  167. self.outputs[0].write(code)
  168. def configure(self):
  169. self.find_pyqt5_binaries()
  170. # warn about this during the configuration too
  171. if not has_xml:
  172. Logs.error('No xml.sax support was found, rcc dependencies will be incomplete!')
  173. @conf
  174. def find_pyqt5_binaries(self):
  175. """
  176. Detects PyQt5 or pyside2 programs such as pyuic5/pyside2-uic, pyrcc5/pyside2-rcc
  177. """
  178. env = self.env
  179. if getattr(Options.options, 'want_pyside2', True):
  180. self.find_program(['pyside2-uic'], var='QT_PYUIC')
  181. self.find_program(['pyside2-rcc'], var='QT_PYRCC')
  182. self.find_program(['pyside2-lupdate'], var='QT_PYLUPDATE')
  183. elif getattr(Options.options, 'want_pyqt4', True):
  184. self.find_program(['pyuic4'], var='QT_PYUIC')
  185. self.find_program(['pyrcc4'], var='QT_PYRCC')
  186. self.find_program(['pylupdate4'], var='QT_PYLUPDATE')
  187. else:
  188. self.find_program(['pyuic5','pyside2-uic','pyuic4'], var='QT_PYUIC')
  189. self.find_program(['pyrcc5','pyside2-rcc','pyrcc4'], var='QT_PYRCC')
  190. self.find_program(['pylupdate5', 'pyside2-lupdate','pylupdate4'], var='QT_PYLUPDATE')
  191. if not env.QT_PYUIC:
  192. self.fatal('cannot find the uic compiler for python for qt5')
  193. if not env.QT_PYUIC:
  194. self.fatal('cannot find the rcc compiler for python for qt5')
  195. self.find_program(['lrelease-qt5', 'lrelease'], var='QT_LRELEASE')
  196. def options(opt):
  197. """
  198. Command-line options
  199. """
  200. pyqt5opt=opt.add_option_group("Python QT5 Options")
  201. pyqt5opt.add_option('--pyqt5-pyside2', action='store_true', default=False, dest='want_pyside2', help='use pyside2 bindings as python QT5 bindings (default PyQt5 is searched first, PySide2 after)')
  202. pyqt5opt.add_option('--pyqt5-pyqt4', action='store_true', default=False, dest='want_pyqt4', help='use PyQt4 bindings as python QT5 bindings (default PyQt5 is searched first, PySide2 after, PyQt4 last)')